diff --git a/.prettierrc b/.prettierrc index 3376d58f2..d45484de7 100644 --- a/.prettierrc +++ b/.prettierrc @@ -1,29 +1,29 @@ { - "printWidth": 100, - "semi": true, - "singleQuote": true, - "tabWidth": 2, - "trailingComma": "es5", - "useTabs": true, - "plugins": ["prettier-plugin-astro"], - "overrides": [ - { - "files": "*.astro", - "options": { - "parser": "astro" - } - }, - { - "files": ["*.json", "*.md", "*.toml", "*.yml"], - "options": { - "useTabs": false - } - }, - { - "files": ["*.md", "*.mdx"], - "options": { - "printWidth": 80 - } - } - ] + "printWidth": 100, + "semi": true, + "singleQuote": true, + "tabWidth": 2, + "trailingComma": "es5", + "useTabs": false, + "plugins": ["prettier-plugin-astro"], + "overrides": [ + { + "files": "*.astro", + "options": { + "parser": "astro" + } + }, + { + "files": ["*.json", "*.md", "*.toml", "*.yml"], + "options": { + "useTabs": false + } + }, + { + "files": ["*.md", "*.mdx"], + "options": { + "printWidth": 80 + } + } + ] } diff --git a/astro.config.mjs b/astro.config.mjs index 159a9a981..748219f4e 100644 --- a/astro.config.mjs +++ b/astro.config.mjs @@ -8,395 +8,395 @@ import starlightBlog from 'starlight-blog'; import serviceWorker from 'astrojs-service-worker'; const authors = { - nothingismagick: { - name: 'Daniel Thompson-Yvetot', - title: 'Tauri Co-Founder', - picture: '/authors/nothingismagick.jpeg', - }, - lucasfernog: { - name: 'Lucas Nogueira', - title: 'Tauri Co-Founder', - picture: '/authors/lucasfernog.jpeg', - }, - beanow: { - name: 'Robin van Boven', - title: 'Tauri Board Director', - picture: '/authors/Beanow.png', - }, - jbolda: { - name: 'Jacob Bolda', - title: 'Tauri Board Director', - picture: '/authors/jbolda.jpeg', - }, - lorenzolewis: { - name: 'Lorenzo Lewis', - title: 'Tauri Community Lead', - picture: '/authors/lorenzolewis.png', - }, - tweidinger: { - name: 'Tillmann Weidinger', - title: 'Tauri Security', - picture: '/authors/tweidinger.png', - }, - amrbashir: { - name: 'Amr Bashir', - title: 'Tauri Development', - picture: '/authors/amrbashir.png', - }, - wusyong: { - name: 'Wu Yu Wei', - title: 'Tauri Development Lead', - picture: '/authors/wusyong.png', - }, - chip: { - name: 'Chip Reed', - title: 'Tauri Security', - picture: '/authors/chip.png', - }, + nothingismagick: { + name: 'Daniel Thompson-Yvetot', + title: 'Tauri Co-Founder', + picture: '/authors/nothingismagick.jpeg', + }, + lucasfernog: { + name: 'Lucas Nogueira', + title: 'Tauri Co-Founder', + picture: '/authors/lucasfernog.jpeg', + }, + beanow: { + name: 'Robin van Boven', + title: 'Tauri Board Director', + picture: '/authors/Beanow.png', + }, + jbolda: { + name: 'Jacob Bolda', + title: 'Tauri Board Director', + picture: '/authors/jbolda.jpeg', + }, + lorenzolewis: { + name: 'Lorenzo Lewis', + title: 'Tauri Community Lead', + picture: '/authors/lorenzolewis.png', + }, + tweidinger: { + name: 'Tillmann Weidinger', + title: 'Tauri Security', + picture: '/authors/tweidinger.png', + }, + amrbashir: { + name: 'Amr Bashir', + title: 'Tauri Development', + picture: '/authors/amrbashir.png', + }, + wusyong: { + name: 'Wu Yu Wei', + title: 'Tauri Development Lead', + picture: '/authors/wusyong.png', + }, + chip: { + name: 'Chip Reed', + title: 'Tauri Security', + picture: '/authors/chip.png', + }, }; const site = 'https://v2.tauri.app'; // https://astro.build/config export default defineConfig({ - site, - integrations: [ - starlight({ - plugins: [ - starlightBlog({ authors }), - starlightLinksValidator({ errorOnRelativeLinks: false }), - ], - title: 'Tauri', - description: 'The cross-platform app building toolkit', - logo: { - dark: './src/assets/logo.svg', - light: './src/assets/logo_light.svg', - replacesTitle: true, - }, - social: { - github: 'https://github.com/tauri-apps/tauri', - discord: 'https://discord.com/invite/tauri', - twitter: 'https://twitter.com/TauriApps', - mastodon: 'https://fosstodon.org/@TauriApps', - rss: `${site}/rss`, - }, - components: { - Sidebar: './src/components/overrides/Sidebar.astro', - Header: './src/components/overrides/Header.astro', - Footer: 'src/components/overrides/Footer.astro', - ThemeSelect: 'src/components/overrides/ThemeSelect.astro', - PageFrame: 'src/components/overrides/PageFrame.astro', - }, - head: [ - { - tag: 'meta', - attrs: { property: 'og:image', content: site + '/og.png?v=1' }, - }, - { - tag: 'meta', - attrs: { property: 'twitter:image', content: site + '/og.png?v=1' }, - }, - { - tag: 'script', - attrs: { - src: '/navigate.js', - }, - }, - { - tag: 'link', - attrs: { - rel: 'manifest', - href: '/manifest.json', - }, - }, - { - tag: 'meta', - attrs: { name: 'theme-color', content: '#181818' }, - }, - ], - editLink: { - baseUrl: 'https://github.com/tauri-apps/tauri-docs/edit/v2', - }, - customCss: ['./src/styles/custom.scss'], - sidebar: [ - { - label: 'Guides', - collapsed: true, - items: [ - { - label: 'Quick Start', - collapsed: true, - items: [ - { - label: 'What is Tauri?', - link: '/start/', - }, - { - label: 'Prerequisites', - link: '/start/prerequisites/', - }, - { - label: 'Create a Project', - link: '/start/create-project/', - badge: { - text: 'WIP', - variant: 'caution', - }, - }, - { - label: 'Frontend Configuration', - collapsed: true, - autogenerate: { directory: 'start/frontend' }, - }, - { - label: 'Upgrade & Migrate', - collapsed: true, - autogenerate: { directory: 'start/migrate' }, - }, - ], - }, - { - label: 'Core Concepts', - collapsed: true, - autogenerate: { directory: 'concept' }, - }, - { - label: 'Security', - collapsed: true, - autogenerate: { directory: 'security' }, - }, - { - label: 'Develop', - collapsed: true, - autogenerate: { directory: 'develop' }, - }, - { - label: 'Distribute', - collapsed: true, - autogenerate: { directory: 'distribute' }, - }, - { - label: 'Learn', - collapsed: true, - autogenerate: { directory: 'learn' }, - }, - { - label: 'Plugins', - collapsed: true, - autogenerate: { directory: 'plugin' }, - }, - { - label: 'About', - collapsed: true, - autogenerate: { directory: 'about' }, - }, - ], - }, - { - label: 'References', - collapsed: true, - items: [ - { - label: 'Access Control List', - link: '/reference/acl/', - }, - { - label: 'Command Line Interface (CLI)', - link: '/reference/cli/', - }, - { - label: 'Configuration', - link: '/reference/config/', - }, - { - label: 'Environment Variables', - link: '/reference/environment-variables/', - }, - { - label: 'Webview Versions', - link: '/reference/webview-versions/', - }, - { - label: 'Releases', - collapsed: true, - autogenerate: { directory: 'release' }, - }, - { - label: 'JavaScript', - collapsed: true, - autogenerate: { directory: 'reference/javascript' }, - }, - { - label: 'Rust (docs.rs)', - link: 'https://docs.rs/tauri/2.0.0-beta.19/tauri/index.html', - }, - ], - }, - { - label: 'Blog', - collapsed: true, - items: [ - { - label: 'All posts', - link: '/blog/', - }, - { - label: 'Recent posts', - collapsed: false, - autogenerate: { directory: 'blog' }, // TODO: Manually construct `items` to sort by dates - }, - ], - }, - ], - locales, - lastUpdated: true, - }), - serviceWorker({ - workbox: { - cleanupOutdatedCaches: true, - clientsClaim: true, - inlineWorkboxRuntime: true, - skipWaiting: true, - globIgnores: ['**_redirects**', '**_headers**'], - globPatterns: ['**/*.js', '**/*.css'], - runtimeCaching: [ - { - urlPattern: new RegExp('.*'), - handler: 'CacheFirst', - options: { - cacheName: 'tauri-runtime', - expiration: { - maxAgeSeconds: 30 * 60, // 30 minutes - }, - }, - }, - ], - }, - }), - ], - markdown: { - shikiConfig: { - langs: ['powershell', 'ts', 'rust', 'bash', 'json', 'toml', 'html', 'js'], - }, - rehypePlugins: [ - rehypeHeadingIds, - [ - rehypeAutolinkHeadings, - { - behavior: 'wrap', - properties: { ariaHidden: true, tabIndex: -1, class: 'heading-link' }, - }, - ], - ], - }, - redirects: { - // Old blog url schema redirects - '/blog/2022/06/19/tauri-1-0': '/blog/tauri-1-0', - '/blog/tauri_1_0': '/blog/tauri-1-0', - '/blog/2022/07/12/tauri-programme-turns-1-and-board-elections': - '/blog/tauri-programme-turns-1-and-board-elections', - '/blog/2022/09/15/tauri-1-1': '/blog/tauri-1-1', - '/blog/2022/09/19/tauri-egui-0-1': '/blog/tauri-egui-0-1', - '/blog/2022/11/18/tauri-1-2': '/blog/tauri-1-2', - '/blog/2022/12/09/tauri-mobile-alpha': '/blog/tauri-mobile-alpha', - '/blog/2023/02/03/tauri-2-0-0-alpha-3': '/blog/tauri-2-0-0-alpha-3', - '/blog/2023/02/09/tauri-community-growth-and-feedback': - '/blog/tauri-community-growth-and-feedback', - '/blog/2023/03/01/create-tauri-app-version-3-released': - '/blog/create-tauri-app-version-3-released', - '/blog/2023/03/20/tauri-2-0-0-alpha-4': '/blog/tauri-2-0-0-alpha-4', - '/blog/2023/05/03/tauri-1-3': '/blog/tauri-1-3', - '/blog/2023/06/14/tauri-1-4': '/blog/tauri-1-4', - '/blog/2023/06/15/tauri-board-elections-and-governance-updates': - '/blog/tauri-board-elections-and-governance-updates', - 'about/intro': 'about/philosophy', - // v1 /guides/debugging -> /guides/debug - ...i18nRedirect('/v1/guides/debugging/application', '/guides/debug/application'), - ...i18nRedirect('/v1/guides/debugging/vs-code', '/guides/debug/vs-code'), - ...i18nRedirect('/v1/guides/debugging/clion', '/guides/debug/clion'), - // v1 /guides/development -> /guides/develop - ...i18nRedirect( - '/v1/guides/development/development-cycle', - '/guides/develop/development-cycle' - ), - ...i18nRedirect( - '/v1/guides/development/updating-dependencies', - '/guides/develop/updating-dependencies' - ), - // v1 /guides/testing -> /guides/test - ...i18nRedirect('/v1/guides/testing/mocking', '/guides/test/mocking'), - ...i18nRedirect('/v1/guides/testing/webdriver/ci', '/guides/test/webdriver/ci'), - ...i18nRedirect('/v1/guides/testing/webdriver/introduction', '/guides/test/webdriver/'), - ...i18nRedirect( - '/v1/guides/testing/webdriver/example/setup', - '/guides/test/webdriver/example/' - ), - ...i18nRedirect( - '/v1/guides/testing/webdriver/example/selenium', - '/guides/test/webdriver/example/selenium' - ), - ...i18nRedirect( - '/v1/guides/testing/webdriver/example/webdriverio', - '/test/webdriver/example/webdriverio' - ), + site, + integrations: [ + starlight({ + plugins: [ + starlightBlog({ authors }), + starlightLinksValidator({ errorOnRelativeLinks: false }), + ], + title: 'Tauri', + description: 'The cross-platform app building toolkit', + logo: { + dark: './src/assets/logo.svg', + light: './src/assets/logo_light.svg', + replacesTitle: true, + }, + social: { + github: 'https://github.com/tauri-apps/tauri', + discord: 'https://discord.com/invite/tauri', + twitter: 'https://twitter.com/TauriApps', + mastodon: 'https://fosstodon.org/@TauriApps', + rss: `${site}/rss`, + }, + components: { + Sidebar: './src/components/overrides/Sidebar.astro', + Header: './src/components/overrides/Header.astro', + Footer: 'src/components/overrides/Footer.astro', + ThemeSelect: 'src/components/overrides/ThemeSelect.astro', + PageFrame: 'src/components/overrides/PageFrame.astro', + }, + head: [ + { + tag: 'meta', + attrs: { property: 'og:image', content: site + '/og.png?v=1' }, + }, + { + tag: 'meta', + attrs: { property: 'twitter:image', content: site + '/og.png?v=1' }, + }, + { + tag: 'script', + attrs: { + src: '/navigate.js', + }, + }, + { + tag: 'link', + attrs: { + rel: 'manifest', + href: '/manifest.json', + }, + }, + { + tag: 'meta', + attrs: { name: 'theme-color', content: '#181818' }, + }, + ], + editLink: { + baseUrl: 'https://github.com/tauri-apps/tauri-docs/edit/v2', + }, + customCss: ['./src/styles/custom.scss'], + sidebar: [ + { + label: 'Guides', + collapsed: true, + items: [ + { + label: 'Quick Start', + collapsed: true, + items: [ + { + label: 'What is Tauri?', + link: '/start/', + }, + { + label: 'Prerequisites', + link: '/start/prerequisites/', + }, + { + label: 'Create a Project', + link: '/start/create-project/', + badge: { + text: 'WIP', + variant: 'caution', + }, + }, + { + label: 'Frontend Configuration', + collapsed: true, + autogenerate: { directory: 'start/frontend' }, + }, + { + label: 'Upgrade & Migrate', + collapsed: true, + autogenerate: { directory: 'start/migrate' }, + }, + ], + }, + { + label: 'Core Concepts', + collapsed: true, + autogenerate: { directory: 'concept' }, + }, + { + label: 'Security', + collapsed: true, + autogenerate: { directory: 'security' }, + }, + { + label: 'Develop', + collapsed: true, + autogenerate: { directory: 'develop' }, + }, + { + label: 'Distribute', + collapsed: true, + autogenerate: { directory: 'distribute' }, + }, + { + label: 'Learn', + collapsed: true, + autogenerate: { directory: 'learn' }, + }, + { + label: 'Plugins', + collapsed: true, + autogenerate: { directory: 'plugin' }, + }, + { + label: 'About', + collapsed: true, + autogenerate: { directory: 'about' }, + }, + ], + }, + { + label: 'References', + collapsed: true, + items: [ + { + label: 'Access Control List', + link: '/reference/acl/', + }, + { + label: 'Command Line Interface (CLI)', + link: '/reference/cli/', + }, + { + label: 'Configuration', + link: '/reference/config/', + }, + { + label: 'Environment Variables', + link: '/reference/environment-variables/', + }, + { + label: 'Webview Versions', + link: '/reference/webview-versions/', + }, + { + label: 'Releases', + collapsed: true, + autogenerate: { directory: 'release' }, + }, + { + label: 'JavaScript', + collapsed: true, + autogenerate: { directory: 'reference/javascript' }, + }, + { + label: 'Rust (docs.rs)', + link: 'https://docs.rs/tauri/2.0.0-beta.19/tauri/index.html', + }, + ], + }, + { + label: 'Blog', + collapsed: true, + items: [ + { + label: 'All posts', + link: '/blog/', + }, + { + label: 'Recent posts', + collapsed: false, + autogenerate: { directory: 'blog' }, // TODO: Manually construct `items` to sort by dates + }, + ], + }, + ], + locales, + lastUpdated: true, + }), + serviceWorker({ + workbox: { + cleanupOutdatedCaches: true, + clientsClaim: true, + inlineWorkboxRuntime: true, + skipWaiting: true, + globIgnores: ['**_redirects**', '**_headers**'], + globPatterns: ['**/*.js', '**/*.css'], + runtimeCaching: [ + { + urlPattern: new RegExp('.*'), + handler: 'CacheFirst', + options: { + cacheName: 'tauri-runtime', + expiration: { + maxAgeSeconds: 30 * 60, // 30 minutes + }, + }, + }, + ], + }, + }), + ], + markdown: { + shikiConfig: { + langs: ['powershell', 'ts', 'rust', 'bash', 'json', 'toml', 'html', 'js'], + }, + rehypePlugins: [ + rehypeHeadingIds, + [ + rehypeAutolinkHeadings, + { + behavior: 'wrap', + properties: { ariaHidden: true, tabIndex: -1, class: 'heading-link' }, + }, + ], + ], + }, + redirects: { + // Old blog url schema redirects + '/blog/2022/06/19/tauri-1-0': '/blog/tauri-1-0', + '/blog/tauri_1_0': '/blog/tauri-1-0', + '/blog/2022/07/12/tauri-programme-turns-1-and-board-elections': + '/blog/tauri-programme-turns-1-and-board-elections', + '/blog/2022/09/15/tauri-1-1': '/blog/tauri-1-1', + '/blog/2022/09/19/tauri-egui-0-1': '/blog/tauri-egui-0-1', + '/blog/2022/11/18/tauri-1-2': '/blog/tauri-1-2', + '/blog/2022/12/09/tauri-mobile-alpha': '/blog/tauri-mobile-alpha', + '/blog/2023/02/03/tauri-2-0-0-alpha-3': '/blog/tauri-2-0-0-alpha-3', + '/blog/2023/02/09/tauri-community-growth-and-feedback': + '/blog/tauri-community-growth-and-feedback', + '/blog/2023/03/01/create-tauri-app-version-3-released': + '/blog/create-tauri-app-version-3-released', + '/blog/2023/03/20/tauri-2-0-0-alpha-4': '/blog/tauri-2-0-0-alpha-4', + '/blog/2023/05/03/tauri-1-3': '/blog/tauri-1-3', + '/blog/2023/06/14/tauri-1-4': '/blog/tauri-1-4', + '/blog/2023/06/15/tauri-board-elections-and-governance-updates': + '/blog/tauri-board-elections-and-governance-updates', + 'about/intro': 'about/philosophy', + // v1 /guides/debugging -> /guides/debug + ...i18nRedirect('/v1/guides/debugging/application', '/guides/debug/application'), + ...i18nRedirect('/v1/guides/debugging/vs-code', '/guides/debug/vs-code'), + ...i18nRedirect('/v1/guides/debugging/clion', '/guides/debug/clion'), + // v1 /guides/development -> /guides/develop + ...i18nRedirect( + '/v1/guides/development/development-cycle', + '/guides/develop/development-cycle' + ), + ...i18nRedirect( + '/v1/guides/development/updating-dependencies', + '/guides/develop/updating-dependencies' + ), + // v1 /guides/testing -> /guides/test + ...i18nRedirect('/v1/guides/testing/mocking', '/guides/test/mocking'), + ...i18nRedirect('/v1/guides/testing/webdriver/ci', '/guides/test/webdriver/ci'), + ...i18nRedirect('/v1/guides/testing/webdriver/introduction', '/guides/test/webdriver/'), + ...i18nRedirect( + '/v1/guides/testing/webdriver/example/setup', + '/guides/test/webdriver/example/' + ), + ...i18nRedirect( + '/v1/guides/testing/webdriver/example/selenium', + '/guides/test/webdriver/example/selenium' + ), + ...i18nRedirect( + '/v1/guides/testing/webdriver/example/webdriverio', + '/test/webdriver/example/webdriverio' + ), - // v1 /references - ...i18nRedirect('/v1/references', '/concepts'), - ...i18nRedirect('/v1/reference/architecture', '/concepts/architecture'), - ...i18nRedirect('/v1/reference/architecture/process-model', '/concepts/process-model'), - ...i18nRedirect('/v1/reference/architecture/security', '/concepts/tauri-security'), - ...i18nRedirect( - '/v1/reference/architecture/inter-process-communication', - '/concepts/inter-process-communication' - ), - ...i18nRedirect( - '/v1/reference/architecture/inter-process-communication/brownfield', - '/concepts/inter-process-communication/brownfield' - ), - ...i18nRedirect( - '/v1/reference/architecture/inter-process-communication/isolation', - '/concepts/inter-process-communication/isolation' - ), - ...i18nRedirect('/v1/reference/security', '/concepts/development-security'), - ...i18nRedirect('/v1/reference/configuration-files', '/reference/configuration-files'), - ...i18nRedirect('/v1/reference/webview-versions', '/reference/webview-versions'), + // v1 /references + ...i18nRedirect('/v1/references', '/concepts'), + ...i18nRedirect('/v1/reference/architecture', '/concepts/architecture'), + ...i18nRedirect('/v1/reference/architecture/process-model', '/concepts/process-model'), + ...i18nRedirect('/v1/reference/architecture/security', '/concepts/tauri-security'), + ...i18nRedirect( + '/v1/reference/architecture/inter-process-communication', + '/concepts/inter-process-communication' + ), + ...i18nRedirect( + '/v1/reference/architecture/inter-process-communication/brownfield', + '/concepts/inter-process-communication/brownfield' + ), + ...i18nRedirect( + '/v1/reference/architecture/inter-process-communication/isolation', + '/concepts/inter-process-communication/isolation' + ), + ...i18nRedirect('/v1/reference/security', '/concepts/development-security'), + ...i18nRedirect('/v1/reference/configuration-files', '/reference/configuration-files'), + ...i18nRedirect('/v1/reference/webview-versions', '/reference/webview-versions'), - // Decommissioned locales -> refer to /public/_redirects file - // '/ko/[...slug]': '/[...slug]', - // '/it/[...slug]': '/[...slug]', - }, - server: { - headers: readHeaders(), - }, - // + // Decommissioned locales -> refer to /public/_redirects file + // '/ko/[...slug]': '/[...slug]', + // '/it/[...slug]': '/[...slug]', + }, + server: { + headers: readHeaders(), + }, + // }); // Generates a redirect for each locale. function i18nRedirect(from, to) { - const routes = {}; - Object.keys(locales).map((locale) => - locale === 'root' - ? (routes[from] = to) - : (routes[`/${locale}/${from.replaceAll(/^\/*/g, '')}`] = `/${locale}/${to.replaceAll( - /^\/*/g, - '' - )}`) - ); - return routes; + const routes = {}; + Object.keys(locales).map((locale) => + locale === 'root' + ? (routes[from] = to) + : (routes[`/${locale}/${from.replaceAll(/^\/*/g, '')}`] = `/${locale}/${to.replaceAll( + /^\/*/g, + '' + )}`) + ); + return routes; } // Read the HTTP header file in `public/_headers` function readHeaders() { - const header_file = fs - .readFileSync('public/_headers', { encoding: 'utf8' }) - .split('\n') - .filter(Boolean); - const headers = {}; - for (const line of header_file) { - const [key, val] = line.trim().split(/\s*:\s*(.+)/); - if (key != undefined && val != undefined) { - headers[key] = val.toString(); - } - } - return headers; + const header_file = fs + .readFileSync('public/_headers', { encoding: 'utf8' }) + .split('\n') + .filter(Boolean); + const headers = {}; + for (const line of header_file) { + const [key, val] = line.trim().split(/\s*:\s*(.+)/); + if (key != undefined && val != undefined) { + headers[key] = val.toString(); + } + } + return headers; } diff --git a/packages/config-generator/build.ts b/packages/config-generator/build.ts index c8d845e0b..617f22e01 100644 --- a/packages/config-generator/build.ts +++ b/packages/config-generator/build.ts @@ -3,69 +3,69 @@ import { existsSync, writeFileSync } from 'node:fs'; import { slug } from 'github-slugger'; buildConfig( - '../tauri/core/tauri-config-schema/schema.json', - '../../src/content/docs/reference/config.md' + '../tauri/core/tauri-config-schema/schema.json', + '../../src/content/docs/reference/config.md' ); async function buildConfig(schemaFile: string, outputFile: string) { - if (!existsSync(schemaFile)) { - throw Error('Could not find the Tauri config schema. Is the Tauri submodule initialized?'); - } + if (!existsSync(schemaFile)) { + throw Error('Could not find the Tauri config schema. Is the Tauri submodule initialized?'); + } - let schema: JSONSchema7 = (await import(schemaFile)).default; + let schema: JSONSchema7 = (await import(schemaFile)).default; - const output = [ - '---\n# NOTE: This file is auto-generated in packages/config-generator/build.ts\n# For corrections please edit https://github.com/tauri-apps/tauri/blob/dev/core/tauri-utils/src/config.rs directly\n\ntitle: Configuration\nsidebar:\n order: 1\n---', - ]; + const output = [ + '---\n# NOTE: This file is auto-generated in packages/config-generator/build.ts\n# For corrections please edit https://github.com/tauri-apps/tauri/blob/dev/core/tauri-utils/src/config.rs directly\n\ntitle: Configuration\nsidebar:\n order: 1\n---', + ]; - output.push( - ...buildSchemaDefinition(schema, { - headingLevel: 2, - renderTitle: false, - }) - ); + output.push( + ...buildSchemaDefinition(schema, { + headingLevel: 2, + renderTitle: false, + }) + ); - writeFileSync(outputFile, output.join('\n\n')); + writeFileSync(outputFile, output.join('\n\n')); } interface Options { - headingLevel: number; - renderTitle: boolean; - leadWithType: boolean; + headingLevel: number; + renderTitle: boolean; + leadWithType: boolean; } function buildSchemaDefinition( - schema: JSONSchema7Definition, - passedOptions: Partial = {} + schema: JSONSchema7Definition, + passedOptions: Partial = {} ): string[] { - // Note: $id, $schema, and $comment are explicitly not rendered + // Note: $id, $schema, and $comment are explicitly not rendered - // Assign default values for any missing options - const opts = Object.assign( - { - headingLevel: 1, - renderTitle: true, - leadWithType: false, - }, - passedOptions - ); + // Assign default values for any missing options + const opts = Object.assign( + { + headingLevel: 1, + renderTitle: true, + leadWithType: false, + }, + passedOptions + ); - if (typeof schema === 'boolean') { - return [`\`${schema}\``]; - } + if (typeof schema === 'boolean') { + return [`\`${schema}\``]; + } - const out: string[] = []; + const out: string[] = []; - out.push(...buildType(schema, opts)); - out.push(...buildExtendedItems(schema, opts)); - out.push(...buildConditionalSubschemas(schema, opts)); - out.push(...buildBooleanSubschemas(schema, opts)); - out.push(...buildMetadata(schema, opts)); - out.push(...buildProperties(schema, opts)); - out.push(...buildExtendedMetadata(schema, opts)); - out.push(...buildDefinitions(schema, opts)); + out.push(...buildType(schema, opts)); + out.push(...buildExtendedItems(schema, opts)); + out.push(...buildConditionalSubschemas(schema, opts)); + out.push(...buildBooleanSubschemas(schema, opts)); + out.push(...buildMetadata(schema, opts)); + out.push(...buildProperties(schema, opts)); + out.push(...buildExtendedMetadata(schema, opts)); + out.push(...buildDefinitions(schema, opts)); - return out; + return out; } /** @@ -74,37 +74,37 @@ function buildSchemaDefinition( * Also see: buildExtendedMetadata() */ function buildMetadata(schema: JSONSchema7Definition, opts: Options): string[] { - if (typeof schema !== 'object') { - return []; - } + if (typeof schema !== 'object') { + return []; + } - const out: string[] = []; + const out: string[] = []; - opts.renderTitle && - schema.title && - out.push(`${'#'.repeat(Math.min(opts.headingLevel, 6))} ${schema.title}`); + opts.renderTitle && + schema.title && + out.push(`${'#'.repeat(Math.min(opts.headingLevel, 6))} ${schema.title}`); - if (schema.readOnly || schema.writeOnly) { - const line = []; - schema.readOnly && line.push('Read only'); - schema.writeOnly && line.push('Write only'); - out.push(line.join(' & ')); - } + if (schema.readOnly || schema.writeOnly) { + const line = []; + schema.readOnly && line.push('Read only'); + schema.writeOnly && line.push('Write only'); + out.push(line.join(' & ')); + } - schema.description && - out.push( - schema.description - // Set headings to appropriate level - .replaceAll(/#{1,6}(?=.+[\n\\n])/g, '#'.repeat(Math.min(opts.headingLevel + 1, 6))) - // Fix improperly formatted heading links - .replaceAll(/#{1,6}(?=[^\s#])/g, '#') - .replaceAll('<', '<') - .replaceAll('>', '>') - // Fix for link at https://github.com/tauri-apps/tauri/blob/713f84db2b5bf17e4217053a229f9c11cbb22c74/core/tauri-config-schema/schema.json#L1863-L1864 - .replace('#SecurityConfig.devCsp', '#securityconfig') - ); + schema.description && + out.push( + schema.description + // Set headings to appropriate level + .replaceAll(/#{1,6}(?=.+[\n\\n])/g, '#'.repeat(Math.min(opts.headingLevel + 1, 6))) + // Fix improperly formatted heading links + .replaceAll(/#{1,6}(?=[^\s#])/g, '#') + .replaceAll('<', '<') + .replaceAll('>', '>') + // Fix for link at https://github.com/tauri-apps/tauri/blob/713f84db2b5bf17e4217053a229f9c11cbb22c74/core/tauri-config-schema/schema.json#L1863-L1864 + .replace('#SecurityConfig.devCsp', '#securityconfig') + ); - return out; + return out; } /** @@ -117,318 +117,318 @@ function buildMetadata(schema: JSONSchema7Definition, opts: Options): string[] { * Non-JSON data validation: contentMediaType, contentEncoding */ function buildType(schema: JSONSchema7Definition, opts: Options): string[] { - if (typeof schema !== 'object') { - return []; - } + if (typeof schema !== 'object') { + return []; + } - let line: string = ''; + let line: string = ''; - if (schema.type) { - if (Array.isArray(schema.type)) { - line += schema.type.map((value) => buildTypeName(value, schema, opts)).join(' | '); - } else { - line += buildTypeName(schema.type, schema, opts); - } - } + if (schema.type) { + if (Array.isArray(schema.type)) { + line += schema.type.map((value) => buildTypeName(value, schema, opts)).join(' | '); + } else { + line += buildTypeName(schema.type, schema, opts); + } + } - if (schema.$ref) { - const reference = schema.$ref.split('/').pop(); + if (schema.$ref) { + const reference = schema.$ref.split('/').pop(); - if (!reference) { - throw Error(`Invalid reference: ${schema.$ref}`); - } + if (!reference) { + throw Error(`Invalid reference: ${schema.$ref}`); + } - line += `[\`${reference}\`](#${slug(reference)})`; - } + line += `[\`${reference}\`](#${slug(reference)})`; + } - if (schema.const) { - switch (typeof schema.const) { - case 'string': - line += `\`"${schema.const}"\``; - break; - default: - line += `\`${schema.const}\``; - } - } + if (schema.const) { + switch (typeof schema.const) { + case 'string': + line += `\`"${schema.const}"\``; + break; + default: + line += `\`${schema.const}\``; + } + } - if (schema.enum) { - const enumValues: string[] = []; - schema.enum.forEach((value) => { - switch (typeof value) { - case 'string': - enumValues.push(`\`"${value}"\``); - break; - default: - enumValues.push(`\`${value}\``); - } - }); - line += enumValues.join(' | '); - } + if (schema.enum) { + const enumValues: string[] = []; + schema.enum.forEach((value) => { + switch (typeof value) { + case 'string': + enumValues.push(`\`"${value}"\``); + break; + default: + enumValues.push(`\`${value}\``); + } + }); + line += enumValues.join(' | '); + } - const validation = []; + const validation = []; - // Number validation - schema.multipleOf && validation.push(`multiple of \`${schema.multipleOf}\``); - schema.maximum && validation.push(`maximum of \`${schema.maximum}\``); - schema.exclusiveMaximum && validation.push(`exclusive maximum of \`${schema.exclusiveMaximum}\``); - schema.minimum && validation.push(`minimum of \`${schema.minimum}\``); - schema.exclusiveMinimum && validation.push(`exclusive minimum of \`${schema.exclusiveMinimum}\``); + // Number validation + schema.multipleOf && validation.push(`multiple of \`${schema.multipleOf}\``); + schema.maximum && validation.push(`maximum of \`${schema.maximum}\``); + schema.exclusiveMaximum && validation.push(`exclusive maximum of \`${schema.exclusiveMaximum}\``); + schema.minimum && validation.push(`minimum of \`${schema.minimum}\``); + schema.exclusiveMinimum && validation.push(`exclusive minimum of \`${schema.exclusiveMinimum}\``); - // String validation - schema.maxLength && validation.push(`maximum length of \`${schema.maxLength}\``); - schema.minLength && validation.push(`minimum length of \`${schema.minLength}\``); - schema.pattern && validation.push(`pattern of \`${schema.pattern}\``); + // String validation + schema.maxLength && validation.push(`maximum length of \`${schema.maxLength}\``); + schema.minLength && validation.push(`minimum length of \`${schema.minLength}\``); + schema.pattern && validation.push(`pattern of \`${schema.pattern}\``); - // Array validation - schema.maxItems && validation.push(`maximum of \`${schema.maxItems}\` items`); - schema.minItems && validation.push(`minimum of \`${schema.minItems}\` items`); - schema.uniqueItems && validation.push(`each item must be unique`); + // Array validation + schema.maxItems && validation.push(`maximum of \`${schema.maxItems}\` items`); + schema.minItems && validation.push(`minimum of \`${schema.minItems}\` items`); + schema.uniqueItems && validation.push(`each item must be unique`); - // Object validation - schema.maxProperties && validation.push(`maximum of \`${schema.maxProperties}\` properties`); - schema.minProperties && validation.push(`minimum of \`${schema.minProperties}\` properties`); + // Object validation + schema.maxProperties && validation.push(`maximum of \`${schema.maxProperties}\` properties`); + schema.minProperties && validation.push(`minimum of \`${schema.minProperties}\` properties`); - // Semantic validation - schema.format && validation.push(`formatted as \`${schema.format}\``); + // Semantic validation + schema.format && validation.push(`formatted as \`${schema.format}\``); - // Non-JSON data validation - schema.contentMediaType && - validation.push(`content media type of \`${schema.contentMediaType}\``); - schema.contentEncoding && validation.push(`content encoding of \`${schema.contentEncoding}\``); + // Non-JSON data validation + schema.contentMediaType && + validation.push(`content media type of \`${schema.contentMediaType}\``); + schema.contentEncoding && validation.push(`content encoding of \`${schema.contentEncoding}\``); - if (validation.length > 0) { - line += ' ' + validation.join(', '); - } + if (validation.length > 0) { + line += ' ' + validation.join(', '); + } - return [line]; + return [line]; - function buildTypeName( - typeName: JSONSchema7TypeName, - parentSchema: JSONSchema7Definition, - opts: Options - ): string { - // Rendering logic for enums and consts are handled separately - if (typeof parentSchema === 'object' && (parentSchema.enum || parentSchema.const)) { - return ''; - } + function buildTypeName( + typeName: JSONSchema7TypeName, + parentSchema: JSONSchema7Definition, + opts: Options + ): string { + // Rendering logic for enums and consts are handled separately + if (typeof parentSchema === 'object' && (parentSchema.enum || parentSchema.const)) { + return ''; + } - let line = ''; - switch (typeName) { - case 'object': - break; - case 'array': - if (typeof parentSchema !== 'object' || !parentSchema.items) { - throw Error('Invalid array'); - } - if (Array.isArray(parentSchema.items)) { - line += parentSchema.items - .map((value) => { - const definition = buildSchemaDefinition(value, opts); - if (definition.length > 1) { - // Format additional information to be in parenthesis - const [first, ...rest] = definition; - return [first, ' (', rest.join(', '), ')']; - } else { - return definition.join(); - } - }) - .join(' | '); - } else { - line += buildSchemaDefinition(parentSchema.items, opts); - } - line += '[]'; - break; - default: - line += '`' + typeName + '`'; - } - return line; - } + let line = ''; + switch (typeName) { + case 'object': + break; + case 'array': + if (typeof parentSchema !== 'object' || !parentSchema.items) { + throw Error('Invalid array'); + } + if (Array.isArray(parentSchema.items)) { + line += parentSchema.items + .map((value) => { + const definition = buildSchemaDefinition(value, opts); + if (definition.length > 1) { + // Format additional information to be in parenthesis + const [first, ...rest] = definition; + return [first, ' (', rest.join(', '), ')']; + } else { + return definition.join(); + } + }) + .join(' | '); + } else { + line += buildSchemaDefinition(parentSchema.items, opts); + } + line += '[]'; + break; + default: + line += '`' + typeName + '`'; + } + return line; + } } /** * Builds: additionalItems, contains */ function buildExtendedItems(schema: JSONSchema7Definition, opts: Options): string[] { - if (typeof schema !== 'object') { - return []; - } + if (typeof schema !== 'object') { + return []; + } - if (schema.additionalItems) { - throw Error('Not implemented'); - } - if (schema.contains) { - throw Error('Not implemented'); - } + if (schema.additionalItems) { + throw Error('Not implemented'); + } + if (schema.contains) { + throw Error('Not implemented'); + } - const out: string[] = []; + const out: string[] = []; - schema.additionalItems && out.push(`additionalItems: ${JSON.stringify(schema.additionalItems)}`); - schema.contains && out.push(`contains: ${JSON.stringify(schema.contains)}`); + schema.additionalItems && out.push(`additionalItems: ${JSON.stringify(schema.additionalItems)}`); + schema.contains && out.push(`contains: ${JSON.stringify(schema.contains)}`); - return out; + return out; } /** * Builds: required, properties, patternProperties, additionalProperties, dependencies, propertyNames */ function buildProperties(schema: JSONSchema7Definition, opts: Options): string[] { - if (typeof schema !== 'object') { - return []; - } + if (typeof schema !== 'object') { + return []; + } - const out: string[] = []; + const out: string[] = []; - if (schema.properties) { - out.push(`**Object Properties**:`); + if (schema.properties) { + out.push(`**Object Properties**:`); - const properties = Object.entries(schema.properties) - .filter(([key]) => key !== '$schema') - .sort(([a], [b]) => a.localeCompare(b)); + const properties = Object.entries(schema.properties) + .filter(([key]) => key !== '$schema') + .sort(([a], [b]) => a.localeCompare(b)); - out.push( - properties - .map( - ([key]) => - `- ${key} ${schema.required && schema.required.includes(key) ? '(required)' : ''}` - ) - .join('\n') - ); + out.push( + properties + .map( + ([key]) => + `- ${key} ${schema.required && schema.required.includes(key) ? '(required)' : ''}` + ) + .join('\n') + ); - properties.forEach(([key, value]) => { - out.push(`${'#'.repeat(Math.min(6, opts.headingLevel + 1))} ${key}`); - out.push(...buildSchemaDefinition(value, { ...opts, headingLevel: opts.headingLevel + 1 })); - }); - } + properties.forEach(([key, value]) => { + out.push(`${'#'.repeat(Math.min(6, opts.headingLevel + 1))} ${key}`); + out.push(...buildSchemaDefinition(value, { ...opts, headingLevel: opts.headingLevel + 1 })); + }); + } - schema.additionalProperties && - out.push( - `**Allows additional properties**: ${buildSchemaDefinition( - schema.additionalProperties, - opts - )}` - ); + schema.additionalProperties && + out.push( + `**Allows additional properties**: ${buildSchemaDefinition( + schema.additionalProperties, + opts + )}` + ); - if (schema.patternProperties || schema.dependencies || schema.propertyNames) { - throw Error('Not implemented'); - } + if (schema.patternProperties || schema.dependencies || schema.propertyNames) { + throw Error('Not implemented'); + } - schema.patternProperties && - out.push(`patternProperties: ${JSON.stringify(schema.patternProperties)}`); - schema.dependencies && out.push(`dependencies: ${JSON.stringify(schema.dependencies)}`); - schema.propertyNames && out.push(`propertyNames: ${JSON.stringify(schema.propertyNames)}`); + schema.patternProperties && + out.push(`patternProperties: ${JSON.stringify(schema.patternProperties)}`); + schema.dependencies && out.push(`dependencies: ${JSON.stringify(schema.dependencies)}`); + schema.propertyNames && out.push(`propertyNames: ${JSON.stringify(schema.propertyNames)}`); - return out; + return out; } /** * Builds: if, then, else */ function buildConditionalSubschemas(schema: JSONSchema7Definition, opts: Options): string[] { - if (typeof schema !== 'object') { - return []; - } + if (typeof schema !== 'object') { + return []; + } - const out: string[] = []; + const out: string[] = []; - if (schema.if || schema.then || schema.else) { - throw Error('Not implemented'); - } + if (schema.if || schema.then || schema.else) { + throw Error('Not implemented'); + } - schema.if && out.push(`if: ${JSON.stringify(schema.if)}`); - schema.then && out.push(`then: ${JSON.stringify(schema.then)}`); - schema.else && out.push(`else: ${JSON.stringify(schema.else)}`); + schema.if && out.push(`if: ${JSON.stringify(schema.if)}`); + schema.then && out.push(`then: ${JSON.stringify(schema.then)}`); + schema.else && out.push(`else: ${JSON.stringify(schema.else)}`); - return out; + return out; } /** * Builds: allOf, anyOf, oneOf, not */ function buildBooleanSubschemas(schema: JSONSchema7Definition, opts: Options): string[] { - if (typeof schema !== 'object') { - return []; - } + if (typeof schema !== 'object') { + return []; + } - const out: string[] = []; + const out: string[] = []; - if (schema.allOf) { - out.push(...buildXOf('All', schema.allOf, opts)); - } + if (schema.allOf) { + out.push(...buildXOf('All', schema.allOf, opts)); + } - if (schema.anyOf) { - out.push(...buildXOf('Any', schema.anyOf, opts)); - } + if (schema.anyOf) { + out.push(...buildXOf('Any', schema.anyOf, opts)); + } - if (schema.oneOf) { - out.push(...buildXOf('One', schema.oneOf, opts)); - } + if (schema.oneOf) { + out.push(...buildXOf('One', schema.oneOf, opts)); + } - if (schema.not) { - throw Error('Not implemented'); - } + if (schema.not) { + throw Error('Not implemented'); + } - schema.not && out.push(`not: ${JSON.stringify(schema.not)}`); + schema.not && out.push(`not: ${JSON.stringify(schema.not)}`); - return out; + return out; - function buildXOf( - label: 'One' | 'Any' | 'All', - schemas: JSONSchema7Definition[], - opts: Options - ): string[] { - const definitions = schemas.map((value) => - buildSchemaDefinition(value, { ...opts, leadWithType: true }) - ); + function buildXOf( + label: 'One' | 'Any' | 'All', + schemas: JSONSchema7Definition[], + opts: Options + ): string[] { + const definitions = schemas.map((value) => + buildSchemaDefinition(value, { ...opts, leadWithType: true }) + ); - if (definitions.every((definition) => definition.length == 1)) { - // Short definition, can be rendered on a single line - return [definitions.join(' | ')]; - } + if (definitions.every((definition) => definition.length == 1)) { + // Short definition, can be rendered on a single line + return [definitions.join(' | ')]; + } - const out: string[] = []; + const out: string[] = []; - if (definitions.length > 1) { - // Render as a list - out.push(`**${label} of the following**:`); - const list: string[] = []; + if (definitions.length > 1) { + // Render as a list + out.push(`**${label} of the following**:`); + const list: string[] = []; - const additionalDefinitions: string[][] = []; + const additionalDefinitions: string[][] = []; - definitions.forEach((definition) => { - if (definition[0].startsWith('`object`')) { - // Is an object, need to render subdefinitions - const [first] = definition; - list.push(`- ${first}: Subdefinition ${additionalDefinitions.length + 1}`); - additionalDefinitions.push(definition); - } else { - // Render inline in list - list.push(`- ${definition.map((value) => value.replaceAll('\n', ' ')).join(' ')}`); - } - }); + definitions.forEach((definition) => { + if (definition[0].startsWith('`object`')) { + // Is an object, need to render subdefinitions + const [first] = definition; + list.push(`- ${first}: Subdefinition ${additionalDefinitions.length + 1}`); + additionalDefinitions.push(definition); + } else { + // Render inline in list + list.push(`- ${definition.map((value) => value.replaceAll('\n', ' ')).join(' ')}`); + } + }); - out.push(list.join('\n')); + out.push(list.join('\n')); - if (additionalDefinitions.length > 0) { - out.push(`${'#'.repeat(Math.min(6, opts.headingLevel))} Subdefinitions`); - additionalDefinitions.forEach((definition, index) => { - // Render heading - out.push(`${'#'.repeat(Math.min(6, opts.headingLevel + 1))} Subdefinition ${index + 1}`); + if (additionalDefinitions.length > 0) { + out.push(`${'#'.repeat(Math.min(6, opts.headingLevel))} Subdefinitions`); + additionalDefinitions.forEach((definition, index) => { + // Render heading + out.push(`${'#'.repeat(Math.min(6, opts.headingLevel + 1))} Subdefinition ${index + 1}`); - // Render definition, giving additional heading indention as needed - definition.forEach((line) => { - out.push( - line.replaceAll(/#{1,6}\s(?=.+)/g, '#'.repeat(Math.min(opts.headingLevel + 2, 6))) - ); - }); - }); - } - } else { - // Render as a block - // Mapping might need some fixing... - out.push(...definitions.map((definition) => definition.join())); - } - return out; - } + // Render definition, giving additional heading indention as needed + definition.forEach((line) => { + out.push( + line.replaceAll(/#{1,6}\s(?=.+)/g, '#'.repeat(Math.min(opts.headingLevel + 2, 6))) + ); + }); + }); + } + } else { + // Render as a block + // Mapping might need some fixing... + out.push(...definitions.map((definition) => definition.join())); + } + return out; + } } /** @@ -438,34 +438,34 @@ function buildBooleanSubschemas(schema: JSONSchema7Definition, opts: Options): s * https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-validation-01#section-9 */ function buildExtendedMetadata(schema: JSONSchema7Definition, opts: Options): string[] { - if (typeof schema !== 'object') { - return []; - } + if (typeof schema !== 'object') { + return []; + } - const out: string[] = []; + const out: string[] = []; - if (schema.default) { - if (typeof schema.default === 'string') { - out.push(`**Default**: \`"${schema.default}"\``); - } else if (typeof schema.default !== 'object') { - // Render on single line - out.push(`**Default**: \`${schema.default}\``); - } else if (Object.keys(schema.default).length == 0) { - // Empty object, render on a single line - out.push(`**Default**: \`${JSON.stringify(schema.default)}\``); - } else { - // Object with properties, render in code block - out.push( - `\n\`\`\`json title='Default'\n${JSON.stringify(schema.default, null, '\t')}\n\`\`\`\n` - ); - } - } + if (schema.default) { + if (typeof schema.default === 'string') { + out.push(`**Default**: \`"${schema.default}"\``); + } else if (typeof schema.default !== 'object') { + // Render on single line + out.push(`**Default**: \`${schema.default}\``); + } else if (Object.keys(schema.default).length == 0) { + // Empty object, render on a single line + out.push(`**Default**: \`${JSON.stringify(schema.default)}\``); + } else { + // Object with properties, render in code block + out.push( + `\n\`\`\`json title='Default'\n${JSON.stringify(schema.default, null, '\t')}\n\`\`\`\n` + ); + } + } - if (schema.examples) { - throw Error('Examples not implemented'); - } + if (schema.examples) { + throw Error('Examples not implemented'); + } - return out; + return out; } /** @@ -475,28 +475,28 @@ function buildExtendedMetadata(schema: JSONSchema7Definition, opts: Options): st * https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-validation-01#section-9 */ function buildDefinitions(schema: JSONSchema7Definition, opts: Options): string[] { - if (typeof schema !== 'object') { - return []; - } + if (typeof schema !== 'object') { + return []; + } - const out: string[] = []; + const out: string[] = []; - // Combine definitions together - // `definitions` was renamed to `$defs` in Draft 7 but still allowed in either place - const definitions = { ...schema.$defs, ...schema.definitions }; - if (Object.keys(definitions).length > 0) { - out.push(`${'#'.repeat(Math.min(opts.headingLevel, 6))} Definitions`); - Object.entries(definitions) - .sort(([a], [b]) => a.localeCompare(b)) - .forEach(([key, value]) => { - out.push(`${'#'.repeat(Math.min(opts.headingLevel, 6) + 1)} ${key}`); - out.push( - ...buildSchemaDefinition(value, { - ...opts, - headingLevel: Math.min(opts.headingLevel, 6) + 2, - }) - ); - }); - } - return out; + // Combine definitions together + // `definitions` was renamed to `$defs` in Draft 7 but still allowed in either place + const definitions = { ...schema.$defs, ...schema.definitions }; + if (Object.keys(definitions).length > 0) { + out.push(`${'#'.repeat(Math.min(opts.headingLevel, 6))} Definitions`); + Object.entries(definitions) + .sort(([a], [b]) => a.localeCompare(b)) + .forEach(([key, value]) => { + out.push(`${'#'.repeat(Math.min(opts.headingLevel, 6) + 1)} ${key}`); + out.push( + ...buildSchemaDefinition(value, { + ...opts, + headingLevel: Math.min(opts.headingLevel, 6) + 2, + }) + ); + }); + } + return out; } diff --git a/packages/i18n-tracker/build.ts b/packages/i18n-tracker/build.ts index 42258d8b1..89e2875b3 100644 --- a/packages/i18n-tracker/build.ts +++ b/packages/i18n-tracker/build.ts @@ -2,18 +2,18 @@ import { TranslationStatusBuilder } from './lib/translation-status/builder'; import locales from '../../locales.json'; const translationStatusBuilder = new TranslationStatusBuilder({ - pageSourceDir: '../../src/content/docs', - htmlOutputFilePath: '../../dist/contribute/translate-status.html', - sourceLanguage: 'en', - targetLanguages: Object.values(locales) - .reduce((acc, { lang }) => (lang !== 'en' ? [lang, ...acc] : acc), []) - .sort(), - languageLabels: Object.values(locales) - .filter((loc) => loc.lang !== 'en') - .reduce((acc, curr) => ({ [curr.lang]: curr.label, ...acc }), {}), - githubRepo: process.env.GITHUB_REPOSITORY || 'tauri-apps/tauri-docs', - gitHubRef: 'v2', - githubToken: process.env.GITHUB_TOKEN, + pageSourceDir: '../../src/content/docs', + htmlOutputFilePath: '../../dist/contribute/translate-status.html', + sourceLanguage: 'en', + targetLanguages: Object.values(locales) + .reduce((acc, { lang }) => (lang !== 'en' ? [lang, ...acc] : acc), []) + .sort(), + languageLabels: Object.values(locales) + .filter((loc) => loc.lang !== 'en') + .reduce((acc, curr) => ({ [curr.lang]: curr.label, ...acc }), {}), + githubRepo: process.env.GITHUB_REPOSITORY || 'tauri-apps/tauri-docs', + gitHubRef: 'v2', + githubToken: process.env.GITHUB_TOKEN, }); await translationStatusBuilder.run(); diff --git a/packages/i18n-tracker/lib/github-get.mjs b/packages/i18n-tracker/lib/github-get.mjs index 875411dbe..90a4c07da 100644 --- a/packages/i18n-tracker/lib/github-get.mjs +++ b/packages/i18n-tracker/lib/github-get.mjs @@ -7,27 +7,27 @@ import pRetry, { AbortError } from 'p-retry'; * @returns {Promise} */ export async function githubGet({ url, githubToken = undefined }) { - return await pRetry( - async () => { - const headers = { - Accept: 'application/vnd.github.v3+json', - }; - if (githubToken) { - headers.Authorization = `token ${githubToken}`; - } - const response = await fetch(url, { headers }); - const json = await response.json(); + return await pRetry( + async () => { + const headers = { + Accept: 'application/vnd.github.v3+json', + }; + if (githubToken) { + headers.Authorization = `token ${githubToken}`; + } + const response = await fetch(url, { headers }); + const json = await response.json(); - if (!response.ok) { - throw new AbortError( - `GitHub API call failed: GET "${url}" returned status ${ - response.status - }: ${JSON.stringify(json)}` - ); - } + if (!response.ok) { + throw new AbortError( + `GitHub API call failed: GET "${url}" returned status ${ + response.status + }: ${JSON.stringify(json)}` + ); + } - return json; - }, - { retries: 5 } - ); + return json; + }, + { retries: 5 } + ); } diff --git a/packages/i18n-tracker/lib/output.mjs b/packages/i18n-tracker/lib/output.mjs index 31ff52fb2..19ed0bc07 100644 --- a/packages/i18n-tracker/lib/output.mjs +++ b/packages/i18n-tracker/lib/output.mjs @@ -8,7 +8,7 @@ export const isCi = process.env.CI; * @param {...any} params */ export function debug(message, ...params) { - console.log(message, ...params); + console.log(message, ...params); } /** @@ -16,7 +16,7 @@ export function debug(message, ...params) { * @param {...any} params */ export function warning(message, ...params) { - console.warn(kleur.yellow().bold(`*** WARNING: ${message}`), ...params); + console.warn(kleur.yellow().bold(`*** WARNING: ${message}`), ...params); } /** @@ -24,7 +24,7 @@ export function warning(message, ...params) { * @param {...any} params */ export function error(message, ...params) { - console.error(kleur.red().bold(`*** ERROR: ${message}`), ...params); + console.error(kleur.red().bold(`*** ERROR: ${message}`), ...params); } /** @@ -32,7 +32,7 @@ export function error(message, ...params) { * while leaving new paragraphs intact. */ export function dedentMd(...markdown) { - return dedent(...markdown).replace(/(\S)\n(?!\n)/g, '$1 '); + return dedent(...markdown).replace(/(\S)\n(?!\n)/g, '$1 '); } /** @@ -52,27 +52,27 @@ export function dedentMd(...markdown) { * @param {string} template */ export function formatCount(count, template) { - /** @param {string} text */ - const wrapWithCount = (text) => { - // If no count was given, we're outputting a single issue in annotations, - // so omit count and capitalize the first letter of the issue type description - if (count === undefined) return text[0].toUpperCase() + text.slice(1); + /** @param {string} text */ + const wrapWithCount = (text) => { + // If no count was given, we're outputting a single issue in annotations, + // so omit count and capitalize the first letter of the issue type description + if (count === undefined) return text[0].toUpperCase() + text.slice(1); - // Otherwise, prefix the issue type description with count - return `${count} ${text}`; - }; + // Otherwise, prefix the issue type description with count + return `${count} ${text}`; + }; - const usePlural = count !== undefined && count !== 1; - const templateParts = template.split('|'); - const usedTemplate = templateParts.length === 2 ? templateParts[usePlural ? 1 : 0] : template; - return wrapWithCount(usedTemplate.replace(/\(s\)/g, usePlural ? 's' : '')); + const usePlural = count !== undefined && count !== 1; + const templateParts = template.split('|'); + const usedTemplate = templateParts.length === 2 ? templateParts[usePlural ? 1 : 0] : template; + return wrapWithCount(usedTemplate.replace(/\(s\)/g, usePlural ? 's' : '')); } export default { - debug, - warning, - error, - dedentMd, - formatCount, - isCi, + debug, + warning, + error, + dedentMd, + formatCount, + isCi, }; diff --git a/packages/i18n-tracker/lib/translation-status/builder.ts b/packages/i18n-tracker/lib/translation-status/builder.ts index ff7e88002..fd67af7b8 100644 --- a/packages/i18n-tracker/lib/translation-status/builder.ts +++ b/packages/i18n-tracker/lib/translation-status/builder.ts @@ -13,11 +13,11 @@ import type { PageData, PageIndex, PageTranslationStatus } from './types'; export const COMMIT_IGNORE = /(en-only|typo|broken link|i18nReady|i18nIgnore)/i; interface PullRequest { - html_url: string; - title: string; - labels: { - name: string; - }[]; + html_url: string; + title: string; + labels: { + name: string; + }[]; } /** @@ -27,458 +27,458 @@ interface PullRequest { * This code is designed to be run on every push to the `main` branch. */ export class TranslationStatusBuilder { - constructor(config: { - pageSourceDir: string; - /** - * Full path & file name of the HTML file that the translation status should be written to. - * If the parent path does not exist yet, it will be created. - * */ - htmlOutputFilePath: string; - sourceLanguage: string; - targetLanguages: string[]; - languageLabels: { [key: string]: string }; - githubRepo: string; - gitHubRef: string; - githubToken?: string | undefined; - }) { - this.pageSourceDir = config.pageSourceDir; - this.htmlOutputFilePath = path.resolve(config.htmlOutputFilePath); - this.sourceLanguage = config.sourceLanguage; - this.targetLanguages = config.targetLanguages; - this.languageLabels = config.languageLabels; - this.githubRepo = config.githubRepo; - this.githubRef = config.gitHubRef; - this.githubToken = config.githubToken ?? ''; - this.git = simpleGit({ - maxConcurrentProcesses: Math.max(2, Math.min(32, os.cpus().length)), - }); - } + constructor(config: { + pageSourceDir: string; + /** + * Full path & file name of the HTML file that the translation status should be written to. + * If the parent path does not exist yet, it will be created. + * */ + htmlOutputFilePath: string; + sourceLanguage: string; + targetLanguages: string[]; + languageLabels: { [key: string]: string }; + githubRepo: string; + gitHubRef: string; + githubToken?: string | undefined; + }) { + this.pageSourceDir = config.pageSourceDir; + this.htmlOutputFilePath = path.resolve(config.htmlOutputFilePath); + this.sourceLanguage = config.sourceLanguage; + this.targetLanguages = config.targetLanguages; + this.languageLabels = config.languageLabels; + this.githubRepo = config.githubRepo; + this.githubRef = config.gitHubRef; + this.githubToken = config.githubToken ?? ''; + this.git = simpleGit({ + maxConcurrentProcesses: Math.max(2, Math.min(32, os.cpus().length)), + }); + } - readonly pageSourceDir; - readonly htmlOutputFilePath; - readonly sourceLanguage; - readonly targetLanguages; - readonly languageLabels; - readonly githubRepo; - readonly githubRef; - readonly githubToken; - readonly git; + readonly pageSourceDir; + readonly htmlOutputFilePath; + readonly sourceLanguage; + readonly targetLanguages; + readonly languageLabels; + readonly githubRepo; + readonly githubRef; + readonly githubToken; + readonly git; - async run() { - // Before we start, validate that this is not a shallow clone of the repo - const isShallowRepo = await this.git.revparse(['--is-shallow-repository']); - if (isShallowRepo !== 'false') { - output.error(dedent`This script cannot operate on a shallow clone of the git repository. + async run() { + // Before we start, validate that this is not a shallow clone of the repo + const isShallowRepo = await this.git.revparse(['--is-shallow-repository']); + if (isShallowRepo !== 'false') { + output.error(dedent`This script cannot operate on a shallow clone of the git repository. Please add the checkout setting "fetch-depth: 0" to your GitHub workflow: - name: Checkout uses: actions/checkout@v3 with: fetch-depth: 0 `); - process.exit(1); - } + process.exit(1); + } - output.debug(`*** Building translation status`); + output.debug(`*** Building translation status`); - // Ensure that the output directory exists before continuing - output.debug(`- Output file path: ${this.htmlOutputFilePath}`); - const outputDir = path.dirname(this.htmlOutputFilePath); - if (!fs.existsSync(outputDir)) { - fs.mkdirSync(outputDir, { recursive: true }); - } + // Ensure that the output directory exists before continuing + output.debug(`- Output file path: ${this.htmlOutputFilePath}`); + const outputDir = path.dirname(this.htmlOutputFilePath); + if (!fs.existsSync(outputDir)) { + fs.mkdirSync(outputDir, { recursive: true }); + } - // Create an index of all Markdown/MDX pages grouped by language, - // with information about the last minor & major commit per page - output.debug(`- Generating page index...`); - const pages = await this.createPageIndex(); + // Create an index of all Markdown/MDX pages grouped by language, + // with information about the last minor & major commit per page + output.debug(`- Generating page index...`); + const pages = await this.createPageIndex(); - // Determine translation status by source page - const statusByPage = this.getTranslationStatusByPage(pages); + // Determine translation status by source page + const statusByPage = this.getTranslationStatusByPage(pages); - // Fetch all pull requests - const pullRequests = await this.getPullRequests(); + // Fetch all pull requests + const pullRequests = await this.getPullRequests(); - // Render a human-friendly summary - output.debug(`- Building HTML file...`); - const html = this.renderHtmlStatusPage(statusByPage, pullRequests); + // Render a human-friendly summary + output.debug(`- Building HTML file...`); + const html = this.renderHtmlStatusPage(statusByPage, pullRequests); - // Write HTML output to file - fs.writeFileSync(this.htmlOutputFilePath, html); + // Write HTML output to file + fs.writeFileSync(this.htmlOutputFilePath, html); - output.debug(''); - output.debug('*** Success!'); - output.debug(''); - } + output.debug(''); + output.debug('*** Success!'); + output.debug(''); + } - /** Get all pull requests with the `i18n` tag */ - async getPullRequests() { - const pullRequests: PullRequest[] = await githubGet({ - url: `https://api.github.com/repos/${this.githubRepo}/pulls?state=open&per_page=100`, - githubToken: this.githubToken, - }); + /** Get all pull requests with the `i18n` tag */ + async getPullRequests() { + const pullRequests: PullRequest[] = await githubGet({ + url: `https://api.github.com/repos/${this.githubRepo}/pulls?state=open&per_page=100`, + githubToken: this.githubToken, + }); - return pullRequests.filter((pr) => pr.labels.find((label) => label.name === 'i18n')); - } + return pullRequests.filter((pr) => pr.labels.find((label) => label.name === 'i18n')); + } - async createPageIndex(): Promise { - // Initialize a new page index with a stable key order - const pages: PageIndex = { - [this.sourceLanguage]: {}, - }; - this.targetLanguages.forEach((lang) => (pages[lang.toLowerCase()] = {})); + async createPageIndex(): Promise { + // Initialize a new page index with a stable key order + const pages: PageIndex = { + [this.sourceLanguage]: {}, + }; + this.targetLanguages.forEach((lang) => (pages[lang.toLowerCase()] = {})); - // Enumerate all markdown pages with supported languages in pageSourceDir, - // retrieve their page data and update them - const pagePaths = await glob(`**/*.{md,mdx}`, { - cwd: this.pageSourceDir, - }); - const updatedPages = await Promise.all( - pagePaths.sort().map(async (pagePath) => { - const pathParts = pagePath.split('/'); - const isLanguageSubpathIncluded = this.targetLanguages - .map((el) => el.toLowerCase()) - .includes(pathParts[0]!); + // Enumerate all markdown pages with supported languages in pageSourceDir, + // retrieve their page data and update them + const pagePaths = await glob(`**/*.{md,mdx}`, { + cwd: this.pageSourceDir, + }); + const updatedPages = await Promise.all( + pagePaths.sort().map(async (pagePath) => { + const pathParts = pagePath.split('/'); + const isLanguageSubpathIncluded = this.targetLanguages + .map((el) => el.toLowerCase()) + .includes(pathParts[0]!); - // If the first path of a file does not belong to a language, it will be by default a page of the original language set. - const lang = isLanguageSubpathIncluded ? pathParts[0] : this.sourceLanguage; - const subpath = pathParts.splice(1).join('/'); + // If the first path of a file does not belong to a language, it will be by default a page of the original language set. + const lang = isLanguageSubpathIncluded ? pathParts[0] : this.sourceLanguage; + const subpath = pathParts.splice(1).join('/'); - // Create or update page data for the page - return { - lang, - subpath: isLanguageSubpathIncluded ? subpath : pagePath, - pageData: await this.getSinglePageData(pagePath), - }; - }) - ); + // Create or update page data for the page + return { + lang, + subpath: isLanguageSubpathIncluded ? subpath : pagePath, + pageData: await this.getSinglePageData(pagePath), + }; + }) + ); - // Write the updated pages to the index - updatedPages.forEach((page) => { - if (!page) return; - const { lang, subpath, pageData } = page; - if (!pageData) return; - pages[lang!]![subpath] = pageData; - }); + // Write the updated pages to the index + updatedPages.forEach((page) => { + if (!page) return; + const { lang, subpath, pageData } = page; + if (!pageData) return; + pages[lang!]![subpath] = pageData; + }); - return pages; - } + return pages; + } - /** - * Processes the markdown page located in the pageSourceDir subpath `pagePath` - * and creates a new page data object based on its frontmatter and git history. - */ - async getSinglePageData(pagePath: string): Promise { - const fullFilePath = `${this.pageSourceDir}/${pagePath}`; + /** + * Processes the markdown page located in the pageSourceDir subpath `pagePath` + * and creates a new page data object based on its frontmatter and git history. + */ + async getSinglePageData(pagePath: string): Promise { + const fullFilePath = `${this.pageSourceDir}/${pagePath}`; - // Retrieve git history for the current page - const gitHistory = await this.getGitHistory(fullFilePath); + // Retrieve git history for the current page + const gitHistory = await this.getGitHistory(fullFilePath); - if (!gitHistory) return; + if (!gitHistory) return; - // Retrieve i18nReady flag from frontmatter - const frontMatterBlock = tryGetFrontMatterBlock(fullFilePath); - const i18nReady = /^\s*i18nReady:\s*true\s*$/m.test(frontMatterBlock); + // Retrieve i18nReady flag from frontmatter + const frontMatterBlock = tryGetFrontMatterBlock(fullFilePath); + const i18nReady = /^\s*i18nReady:\s*true\s*$/m.test(frontMatterBlock); - return { - ...(i18nReady ? { i18nReady: true } : {}), - lastChange: gitHistory.lastCommitDate, - lastCommitMsg: gitHistory.lastCommitMessage, - lastMajorChange: gitHistory.lastMajorCommitDate, - lastMajorCommitMsg: gitHistory.lastMajorCommitMessage, - }; - } + return { + ...(i18nReady ? { i18nReady: true } : {}), + lastChange: gitHistory.lastCommitDate, + lastCommitMsg: gitHistory.lastCommitMessage, + lastMajorChange: gitHistory.lastMajorCommitDate, + lastMajorCommitMsg: gitHistory.lastMajorCommitMessage, + }; + } - async getGitHistory(filePath: string) { - const gitLog = await this.git.log({ - file: filePath, - strictDate: true, - }); + async getGitHistory(filePath: string) { + const gitLog = await this.git.log({ + file: filePath, + strictDate: true, + }); - const lastCommit = gitLog.latest; - if (!lastCommit) { - return; - // Disabled since we have generated reference files - // throw new Error(dedent`Failed to retrieve last commit information for file - // "${filePath}". Your working copy should not contain uncommitted new pages - // when running this script.`); - } + const lastCommit = gitLog.latest; + if (!lastCommit) { + return; + // Disabled since we have generated reference files + // throw new Error(dedent`Failed to retrieve last commit information for file + // "${filePath}". Your working copy should not contain uncommitted new pages + // when running this script.`); + } - // Attempt to find the last "major" commit, ignoring any commits that - // usually do not require translations to be updated - const lastMajorCommit = - gitLog.all.find((logEntry) => { - return !logEntry.message.match(COMMIT_IGNORE); - }) || lastCommit; + // Attempt to find the last "major" commit, ignoring any commits that + // usually do not require translations to be updated + const lastMajorCommit = + gitLog.all.find((logEntry) => { + return !logEntry.message.match(COMMIT_IGNORE); + }) || lastCommit; - return { - lastCommitMessage: lastCommit.message, - lastCommitDate: toUtcString(lastCommit.date), - lastMajorCommitMessage: lastMajorCommit.message, - lastMajorCommitDate: toUtcString(lastMajorCommit.date), - }; - } + return { + lastCommitMessage: lastCommit.message, + lastCommitDate: toUtcString(lastCommit.date), + lastMajorCommitMessage: lastMajorCommit.message, + lastMajorCommitDate: toUtcString(lastMajorCommit.date), + }; + } - getTranslationStatusByPage(pages: PageIndex): PageTranslationStatus[] { - const sourcePages = pages[this.sourceLanguage]; - const arrContent: PageTranslationStatus[] = []; + getTranslationStatusByPage(pages: PageIndex): PageTranslationStatus[] { + const sourcePages = pages[this.sourceLanguage]; + const arrContent: PageTranslationStatus[] = []; - Object.keys(sourcePages!).forEach((subpath) => { - const sourcePage = sourcePages![subpath]!; - if (!sourcePage.i18nReady) return; + Object.keys(sourcePages!).forEach((subpath) => { + const sourcePage = sourcePages![subpath]!; + if (!sourcePage.i18nReady) return; - const content: PageTranslationStatus = { - subpath, - sourcePage, - githubUrl: this.getPageUrl({ lang: this.sourceLanguage, subpath }), - translations: {}, - }; + const content: PageTranslationStatus = { + subpath, + sourcePage, + githubUrl: this.getPageUrl({ lang: this.sourceLanguage, subpath }), + translations: {}, + }; - this.targetLanguages.forEach((lang) => { - const i18nPage = pages[lang.toLowerCase()]![subpath]!; - content.translations[lang] = { - page: i18nPage, - isMissing: !i18nPage, - isOutdated: i18nPage && sourcePage.lastMajorChange > i18nPage.lastMajorChange, - githubUrl: this.getPageUrl({ lang, subpath }), - sourceHistoryUrl: this.getPageUrl({ - lang: 'en', - subpath, - type: 'commits', - query: i18nPage ? `?since=${i18nPage.lastMajorChange}` : '', - }), - }; - }); + this.targetLanguages.forEach((lang) => { + const i18nPage = pages[lang.toLowerCase()]![subpath]!; + content.translations[lang] = { + page: i18nPage, + isMissing: !i18nPage, + isOutdated: i18nPage && sourcePage.lastMajorChange > i18nPage.lastMajorChange, + githubUrl: this.getPageUrl({ lang, subpath }), + sourceHistoryUrl: this.getPageUrl({ + lang: 'en', + subpath, + type: 'commits', + query: i18nPage ? `?since=${i18nPage.lastMajorChange}` : '', + }), + }; + }); - arrContent.push(content); - }); + arrContent.push(content); + }); - return arrContent; - } + return arrContent; + } - getPageUrl({ - type = 'blob', - lang, - subpath, - query = '', - }: { - type?: string; - refName?: string; - lang: string; - subpath: string; - query?: string; - }) { - const noDotSrcDir = this.pageSourceDir.replaceAll(/\.+\//g, ''); - const isSrcLang = lang === this.sourceLanguage; - return `https://github.com/${this.githubRepo}/${type}/${this.githubRef}/${noDotSrcDir}${ - isSrcLang ? '' : `/${lang}` - }/${subpath}${query}`; - } + getPageUrl({ + type = 'blob', + lang, + subpath, + query = '', + }: { + type?: string; + refName?: string; + lang: string; + subpath: string; + query?: string; + }) { + const noDotSrcDir = this.pageSourceDir.replaceAll(/\.+\//g, ''); + const isSrcLang = lang === this.sourceLanguage; + return `https://github.com/${this.githubRepo}/${type}/${this.githubRef}/${noDotSrcDir}${ + isSrcLang ? '' : `/${lang}` + }/${subpath}${query}`; + } - /** - * Renders the primary HTML output of this script by loading a template from disk, - * rendering the individual views to HTML, and inserting them into the template. - */ - renderHtmlStatusPage(statusByPage: PageTranslationStatus[], prs: PullRequest[]) { - // Load HTML template - const templateFilePath = path.join( - path.dirname(fileURLToPath(import.meta.url)), - 'template.html' - ); - const html = fs.readFileSync(templateFilePath, { encoding: 'utf8' }); + /** + * Renders the primary HTML output of this script by loading a template from disk, + * rendering the individual views to HTML, and inserting them into the template. + */ + renderHtmlStatusPage(statusByPage: PageTranslationStatus[], prs: PullRequest[]) { + // Load HTML template + const templateFilePath = path.join( + path.dirname(fileURLToPath(import.meta.url)), + 'template.html' + ); + const html = fs.readFileSync(templateFilePath, { encoding: 'utf8' }); - // Replace placeholders in the template with the rendered views - // and return the resulting HTML page - return html - .replace( - '', - this.renderTranslationStatusByLanguage(statusByPage) - ) - .replace('', this.renderTranslationNeedsReview(prs)) - .replace( - '', - this.renderTranslationStatusByPage(statusByPage) - ); - } + // Replace placeholders in the template with the rendered views + // and return the resulting HTML page + return html + .replace( + '', + this.renderTranslationStatusByLanguage(statusByPage) + ) + .replace('', this.renderTranslationNeedsReview(prs)) + .replace( + '', + this.renderTranslationStatusByPage(statusByPage) + ); + } - renderTranslationStatusByLanguage(statusByPage: PageTranslationStatus[]) { - const lines: string[] = []; + renderTranslationStatusByLanguage(statusByPage: PageTranslationStatus[]) { + const lines: string[] = []; - this.targetLanguages.forEach((lang) => { - const missing = statusByPage.filter((content) => content.translations[lang]!.isMissing); - const outdated = statusByPage.filter((content) => content.translations[lang]!.isOutdated); - lines.push('
'); - lines.push( - `` + - `${this.languageLabels[lang]} (${lang})` + - `
` + - `` + - `${statusByPage.length - outdated.length - missing.length} done, ` + - `${outdated.length} need${outdated.length === 1 ? 's' : ''} updating, ` + - `${missing.length} missing` + - `` + - '
' + - this.renderProgressBar(statusByPage.length, outdated.length, missing.length) + - `
` - ); - lines.push(``); - if (outdated.length > 0) { - lines.push(`
🔄  Needs updating
`); - lines.push(`
    `); - lines.push( - ...outdated.map( - (content) => - `
  • ` + - `${this.renderLink(content.githubUrl, content.subpath)} ` + - `(${this.renderLink( - content.translations[lang]!.githubUrl, - 'outdated translation' - )}, ${this.renderLink( - content.translations[lang]!.sourceHistoryUrl, - 'source change history' - )})` + - `
  • ` - ) - ); - lines.push(`
`); - } - if (missing.length > 0) { - lines.push(`
❌  Missing
`); - lines.push(`
    `); - lines.push( - ...missing.map( - (content) => - `
  • ` + - `${this.renderLink( - content.githubUrl, - content.subpath - )}   ${this.renderCreatePageButton(lang, content.subpath)}` + - `
  • ` - ) - ); - lines.push(`
`); - } - lines.push(`
`); - lines.push(``); - }); + this.targetLanguages.forEach((lang) => { + const missing = statusByPage.filter((content) => content.translations[lang]!.isMissing); + const outdated = statusByPage.filter((content) => content.translations[lang]!.isOutdated); + lines.push('
'); + lines.push( + `` + + `${this.languageLabels[lang]} (${lang})` + + `
` + + `` + + `${statusByPage.length - outdated.length - missing.length} done, ` + + `${outdated.length} need${outdated.length === 1 ? 's' : ''} updating, ` + + `${missing.length} missing` + + `` + + '
' + + this.renderProgressBar(statusByPage.length, outdated.length, missing.length) + + `
` + ); + lines.push(``); + if (outdated.length > 0) { + lines.push(`
🔄  Needs updating
`); + lines.push(`
    `); + lines.push( + ...outdated.map( + (content) => + `
  • ` + + `${this.renderLink(content.githubUrl, content.subpath)} ` + + `(${this.renderLink( + content.translations[lang]!.githubUrl, + 'outdated translation' + )}, ${this.renderLink( + content.translations[lang]!.sourceHistoryUrl, + 'source change history' + )})` + + `
  • ` + ) + ); + lines.push(`
`); + } + if (missing.length > 0) { + lines.push(`
❌  Missing
`); + lines.push(`
    `); + lines.push( + ...missing.map( + (content) => + `
  • ` + + `${this.renderLink( + content.githubUrl, + content.subpath + )}   ${this.renderCreatePageButton(lang, content.subpath)}` + + `
  • ` + ) + ); + lines.push(`
`); + } + lines.push(`
`); + lines.push(``); + }); - return lines.join('\n'); - } + return lines.join('\n'); + } - renderTranslationNeedsReview(prs: PullRequest[]) { - const lines: string[] = []; + renderTranslationNeedsReview(prs: PullRequest[]) { + const lines: string[] = []; - if (prs.length > 0) { - lines.push(`
    `); - lines.push( - ...prs.map((pr) => { - const title = pr.title.replaceAll('`', ''); - return `
  • ` + this.renderLink(pr.html_url, title) + `
  • `; - }) - ); - lines.push(`
`); - } - lines.push(``); + if (prs.length > 0) { + lines.push(`
    `); + lines.push( + ...prs.map((pr) => { + const title = pr.title.replaceAll('`', ''); + return `
  • ` + this.renderLink(pr.html_url, title) + `
  • `; + }) + ); + lines.push(`
`); + } + lines.push(``); - return lines.join('\n'); - } + return lines.join('\n'); + } - renderTranslationStatusByPage(statusByPage: PageTranslationStatus[]) { - const lines: string[] = []; + renderTranslationStatusByPage(statusByPage: PageTranslationStatus[]) { + const lines: string[] = []; - lines.push('
'); - lines.push(''); + lines.push('
'); + lines.push('
'); - lines.push(''); - lines.push(['Page', ...this.targetLanguages].map((col) => ``).join('')); - lines.push(''); + lines.push(''); + lines.push(['Page', ...this.targetLanguages].map((col) => ``).join('')); + lines.push(''); - lines.push(''); - const spacer = `\n${this.targetLanguages - .map(() => ``) - .join('\n')}\n`; - lines.push(spacer); - statusByPage.forEach((content) => { - const cols = []; - cols.push(this.renderLink(content.githubUrl, content.subpath)); - cols.push( - ...this.targetLanguages.map((lang) => { - const translation = content.translations[lang]!; - if (translation.isMissing) - return ``; - if (translation.isOutdated) - return ``; - return ``; - }) - ); - lines.push(`\n${cols.map((col) => ``).join('\n')}\n`); - }); - lines.push(spacer); - lines.push(''); + lines.push(''); + const spacer = `\n${this.targetLanguages + .map(() => ``) + .join('\n')}\n`; + lines.push(spacer); + statusByPage.forEach((content) => { + const cols = []; + cols.push(this.renderLink(content.githubUrl, content.subpath)); + cols.push( + ...this.targetLanguages.map((lang) => { + const translation = content.translations[lang]!; + if (translation.isMissing) + return ``; + if (translation.isOutdated) + return ``; + return ``; + }) + ); + lines.push(`\n${cols.map((col) => ``).join('\n')}\n`); + }); + lines.push(spacer); + lines.push(''); - lines.push('
${col}
${col}
${col}
${col}
'); + lines.push(''); - lines.push(`\n❌ Missing   🔄 Needs updating   ✔ Completed`); - lines.push('
'); + lines.push(`\n❌ Missing   🔄 Needs updating   ✔ Completed`); + lines.push(''); - return lines.join('\n'); - } + return lines.join('\n'); + } - /** - * Render a link to a pre-filled GitHub UI for creating a new file. - * - * @param lang Language tag to create page for - * @param filename Subpath of page to create - */ - renderCreatePageButton(lang: string, filename: string): string { - // We include `lang` twice because GitHub eats the last path segment when setting filename. - const createUrl = new URL( - `https://github.com/${this.githubRepo}/new/${this.githubRef}/src/content/docs` - ); - createUrl.searchParams.set('filename', lang + '/' + filename); - createUrl.searchParams.set('value', '---\ntitle:\ndescription:\n---\n'); - return this.renderLink(createUrl.href, `Create\xa0page\xa0+`, 'create-button'); - } + /** + * Render a link to a pre-filled GitHub UI for creating a new file. + * + * @param lang Language tag to create page for + * @param filename Subpath of page to create + */ + renderCreatePageButton(lang: string, filename: string): string { + // We include `lang` twice because GitHub eats the last path segment when setting filename. + const createUrl = new URL( + `https://github.com/${this.githubRepo}/new/${this.githubRef}/src/content/docs` + ); + createUrl.searchParams.set('filename', lang + '/' + filename); + createUrl.searchParams.set('value', '---\ntitle:\ndescription:\n---\n'); + return this.renderLink(createUrl.href, `Create\xa0page\xa0+`, 'create-button'); + } - /** - * Render a progress bar with emoji. - */ - renderProgressBar( - total: number, - outdated: number, - missing: number, - { size = 20 }: { size?: number } = {} - ) { - const outdatedLength = Math.round((outdated / total) * size); - const missingLength = Math.round((missing / total) * size); - const doneLength = size - outdatedLength - missingLength; - return ( - '' - ); - } + /** + * Render a progress bar with emoji. + */ + renderProgressBar( + total: number, + outdated: number, + missing: number, + { size = 20 }: { size?: number } = {} + ) { + const outdatedLength = Math.round((outdated / total) * size); + const missingLength = Math.round((missing / total) * size); + const doneLength = size - outdatedLength - missingLength; + return ( + '' + ); + } - renderLink(href: string, text: string, className = ''): string { - return `${escape(text)}`; - } + renderLink(href: string, text: string, className = ''): string { + return `${escape(text)}`; + } } function toUtcString(date: string) { - return new Date(date).toISOString(); + return new Date(date).toISOString(); } function tryGetFrontMatterBlock(filePath: string): string { - const contents = fs.readFileSync(filePath, 'utf8'); - const matches = contents.match(/^\s*---([\S\s]*?)\n---/); - if (!matches) return ''; - return matches[1]; + const contents = fs.readFileSync(filePath, 'utf8'); + const matches = contents.match(/^\s*---([\S\s]*?)\n---/); + if (!matches) return ''; + return matches[1]; } diff --git a/packages/i18n-tracker/lib/translation-status/template.html b/packages/i18n-tracker/lib/translation-status/template.html index 980a712c0..03a34dfa1 100644 --- a/packages/i18n-tracker/lib/translation-status/template.html +++ b/packages/i18n-tracker/lib/translation-status/template.html @@ -1,285 +1,285 @@ - - - - - + + + + + - Tauri Docs Translation Status - - - - - - + Tauri Docs Translation Status + + + + + + - - + .main-container { + position: relative; + } + + - -
-
-

Tauri Docs Translation Status

+ +
+
+

Tauri Docs Translation Status

-

- If you're interested in helping us translate - v2.tauri.app into one of the languages listed below, - you've come to the right place! This auto-updating page always lists all the content that - could use your help right now. -

+

+ If you're interested in helping us translate + v2.tauri.app into one of the languages listed below, + you've come to the right place! This auto-updating page always lists all the content that + could use your help right now. +

-

- Read the - Translations Guide - for how to translate a document. Before starting a new translation, be sure to check the - existing Tauri Docs PRs to see if this page has already been - translated, and consider reviewing any open PRs in your language! -

+

+ Read the + Translations Guide + for how to translate a document. Before starting a new translation, be sure to check the + existing Tauri Docs PRs to see if this page has already been + translated, and consider reviewing any open PRs in your language! +

-

- Translation progress by language -

- +

+ Translation progress by language +

+ -

- Translations that need reviews -

- +

+ Translations that need reviews +

+ -

- Translation status by content -

-
- - -
- +

+ Translation status by content +

+
+ + +
+ diff --git a/packages/i18n-tracker/lib/translation-status/types.ts b/packages/i18n-tracker/lib/translation-status/types.ts index a245b96c3..16d33e631 100644 --- a/packages/i18n-tracker/lib/translation-status/types.ts +++ b/packages/i18n-tracker/lib/translation-status/types.ts @@ -1,28 +1,28 @@ export type PageIndex = { - [language: string]: { - [pagePath: string]: PageData; - }; + [language: string]: { + [pagePath: string]: PageData; + }; }; export type PageData = { - lastChange: string; - lastCommitMsg: string; - lastMajorChange: string; - lastMajorCommitMsg: string; - i18nReady?: boolean; + lastChange: string; + lastCommitMsg: string; + lastMajorChange: string; + lastMajorCommitMsg: string; + i18nReady?: boolean; }; export type PageTranslationStatus = { - subpath: string; - sourcePage: PageData; - githubUrl: string; - translations: { - [language: string]: { - page: PageData; - isMissing: boolean; - isOutdated: boolean; - githubUrl: string; - sourceHistoryUrl: string; - }; - }; + subpath: string; + sourcePage: PageData; + githubUrl: string; + translations: { + [language: string]: { + page: PageData; + isMissing: boolean; + isOutdated: boolean; + githubUrl: string; + sourceHistoryUrl: string; + }; + }; }; diff --git a/packages/js-api-generator/build.ts b/packages/js-api-generator/build.ts index ae70a561c..bdf1baad9 100644 --- a/packages/js-api-generator/build.ts +++ b/packages/js-api-generator/build.ts @@ -1,198 +1,198 @@ import { - Application, - DeclarationReflection, - Options, - PageEvent, - Reflection, - SignatureReflection, - TSConfigReader, - type TypeDocOptions, + Application, + DeclarationReflection, + Options, + PageEvent, + Reflection, + SignatureReflection, + TSConfigReader, + type TypeDocOptions, } from 'typedoc'; import { - MarkdownPageEvent, - MarkdownTheme, - MarkdownThemeContext, - type MarkdownApplication, - type PluginOptions, + MarkdownPageEvent, + MarkdownTheme, + MarkdownThemeContext, + type MarkdownApplication, + type PluginOptions, } from 'typedoc-plugin-markdown'; import { existsSync } from 'node:fs'; const typeDocConfigBaseOptions: Partial = { - // TypeDoc options - // https://typedoc.org/options/ - githubPages: false, - hideGenerator: true, - theme: 'tauri-theme', - plugin: ['typedoc-plugin-mdn-links', 'typedoc-plugin-markdown'], - readme: 'none', - logLevel: 'Warn', - parametersFormat: 'table', - // typedoc-plugin-markdown options - // https://github.com/tgreyuk/typedoc-plugin-markdown/blob/next/packages/typedoc-plugin-markdown/docs/usage/options.md - outputFileStrategy: 'modules', - flattenOutputFiles: true, - entryFileName: 'index.md', - hidePageHeader: true, - hidePageTitle: true, - hideBreadcrumbs: true, - useCodeBlocks: true, - propertiesFormat: 'table', - typeDeclarationFormat: 'table', - useHTMLAnchors: true, + // TypeDoc options + // https://typedoc.org/options/ + githubPages: false, + hideGenerator: true, + theme: 'tauri-theme', + plugin: ['typedoc-plugin-mdn-links', 'typedoc-plugin-markdown'], + readme: 'none', + logLevel: 'Warn', + parametersFormat: 'table', + // typedoc-plugin-markdown options + // https://github.com/tgreyuk/typedoc-plugin-markdown/blob/next/packages/typedoc-plugin-markdown/docs/usage/options.md + outputFileStrategy: 'modules', + flattenOutputFiles: true, + entryFileName: 'index.md', + hidePageHeader: true, + hidePageTitle: true, + hideBreadcrumbs: true, + useCodeBlocks: true, + propertiesFormat: 'table', + typeDeclarationFormat: 'table', + useHTMLAnchors: true, }; async function generator() { - if (existsSync('../tauri/tooling/api/node_modules')) { - const coreJsOptions: Partial = { - entryPoints: ['../tauri/tooling/api/src/index.ts'], - tsconfig: '../tauri/tooling/api/tsconfig.json', - gitRevision: 'dev', - publicPath: '/reference/javascript/api/', - basePath: '/reference/javascript/api/', - ...typeDocConfigBaseOptions, - }; + if (existsSync('../tauri/tooling/api/node_modules')) { + const coreJsOptions: Partial = { + entryPoints: ['../tauri/tooling/api/src/index.ts'], + tsconfig: '../tauri/tooling/api/tsconfig.json', + gitRevision: 'dev', + publicPath: '/reference/javascript/api/', + basePath: '/reference/javascript/api/', + ...typeDocConfigBaseOptions, + }; - await generateDocs(coreJsOptions); - } else { - console.log( - 'Tauri V2 submodule is not initialized, respective API routes will not be rendered.' - ); - } + await generateDocs(coreJsOptions); + } else { + console.log( + 'Tauri V2 submodule is not initialized, respective API routes will not be rendered.' + ); + } - const plugins = [ - 'authenticator', - 'autostart', - 'barcode-scanner', - 'biometric', - 'cli', - 'clipboard-manager', - 'deep-link', - 'dialog', - 'fs', - 'global-shortcut', - 'http', - 'log', - 'nfc', - 'notification', - 'os', - 'positioner', - 'process', - 'shell', - 'sql', - 'store', - 'stronghold', - 'updater', - 'upload', - 'websocket', - 'window-state', - ]; + const plugins = [ + 'authenticator', + 'autostart', + 'barcode-scanner', + 'biometric', + 'cli', + 'clipboard-manager', + 'deep-link', + 'dialog', + 'fs', + 'global-shortcut', + 'http', + 'log', + 'nfc', + 'notification', + 'os', + 'positioner', + 'process', + 'shell', + 'sql', + 'store', + 'stronghold', + 'updater', + 'upload', + 'websocket', + 'window-state', + ]; - if (existsSync('../plugins-workspace/node_modules')) { - plugins.forEach(async (plugin) => { - const pluginJsOptions: Partial = { - entryPoints: [`../plugins-workspace/plugins/${plugin}/guest-js/index.ts`], - tsconfig: `../plugins-workspace/plugins/${plugin}/tsconfig.json`, - gitRevision: 'v2', - publicPath: `/reference/javascript/`, - basePath: `/reference/javascript/`, - ...typeDocConfigBaseOptions, - // Must go after to override base - entryFileName: `${plugin}.md`, - }; + if (existsSync('../plugins-workspace/node_modules')) { + plugins.forEach(async (plugin) => { + const pluginJsOptions: Partial = { + entryPoints: [`../plugins-workspace/plugins/${plugin}/guest-js/index.ts`], + tsconfig: `../plugins-workspace/plugins/${plugin}/tsconfig.json`, + gitRevision: 'v2', + publicPath: `/reference/javascript/`, + basePath: `/reference/javascript/`, + ...typeDocConfigBaseOptions, + // Must go after to override base + entryFileName: `${plugin}.md`, + }; - await generateDocs(pluginJsOptions); - }); - } else { - console.log( - 'Plugins workspace submodule is not initialized, respective API routes will not be rendered.' - ); - } + await generateDocs(pluginJsOptions); + }); + } else { + console.log( + 'Plugins workspace submodule is not initialized, respective API routes will not be rendered.' + ); + } - if (existsSync('../tauri/tooling/api/node_modules')) { - const coreJsOptions: Partial = { - entryPoints: ['../tauri/tooling/api/src/index.ts'], - tsconfig: '../tauri/tooling/api/tsconfig.json', - gitRevision: 'dev', - publicPath: '/reference/javascript/api/', - basePath: '/reference/javascript/api/', - ...typeDocConfigBaseOptions, - }; + if (existsSync('../tauri/tooling/api/node_modules')) { + const coreJsOptions: Partial = { + entryPoints: ['../tauri/tooling/api/src/index.ts'], + tsconfig: '../tauri/tooling/api/tsconfig.json', + gitRevision: 'dev', + publicPath: '/reference/javascript/api/', + basePath: '/reference/javascript/api/', + ...typeDocConfigBaseOptions, + }; - await generateDocs(coreJsOptions); - } else { - console.log( - 'Tauri V2 submodule is not initialized, respective API routes will not be rendered.' - ); - } + await generateDocs(coreJsOptions); + } else { + console.log( + 'Tauri V2 submodule is not initialized, respective API routes will not be rendered.' + ); + } } // Adapted from https://github.com/HiDeoo/starlight-typedoc async function generateDocs(options: Partial) { - const outputDir = `../../src/content/docs${options.publicPath}`; + const outputDir = `../../src/content/docs${options.publicPath}`; - const app = await Application.bootstrapWithPlugins(options); - app.options.addReader(new TSConfigReader()); - // @ts-ignore - app.renderer.defineTheme('tauri-theme', TauriTheme); + const app = await Application.bootstrapWithPlugins(options); + app.options.addReader(new TSConfigReader()); + // @ts-ignore + app.renderer.defineTheme('tauri-theme', TauriTheme); - app.renderer.on(PageEvent.END, (event: PageEvent) => { - pageEventEnd(event); - }); + app.renderer.on(PageEvent.END, (event: PageEvent) => { + pageEventEnd(event); + }); - const project = await app.convert(); + const project = await app.convert(); - if (project) { - await app.generateDocs(project, outputDir); - } + if (project) { + await app.generateDocs(project, outputDir); + } } // Adds frontmatter to the top of the file // Adapted from https://github.com/HiDeoo/starlight-typedoc function pageEventEnd(event: PageEvent) { - if (!event.contents) { - return; - } - const frontmatter = [ - '---', - `title: "${event.model.name}"`, - 'editUrl: false', - 'sidebar:', - ` label: "${event.model.name.replace('@tauri-apps/plugin-', '')}"`, - '---', - '', - event.contents, - ]; - event.contents = frontmatter.join('\n'); + if (!event.contents) { + return; + } + const frontmatter = [ + '---', + `title: "${event.model.name}"`, + 'editUrl: false', + 'sidebar:', + ` label: "${event.model.name.replace('@tauri-apps/plugin-', '')}"`, + '---', + '', + event.contents, + ]; + event.contents = frontmatter.join('\n'); } class TauriThemeRenderContext extends MarkdownThemeContext { - constructor(theme: MarkdownTheme, page: MarkdownPageEvent, options: Options) { - super(theme, page, options); - this.partials = { - ...this.partials, - // Formats `@source` to be a single line - sources: (model: DeclarationReflection | SignatureReflection, options: object) => { - if (!model.sources) { - return ''; - } - let label = model.sources.length > 1 ? '**Sources**: ' : '**Source**: '; - const sources = model.sources.map((source) => `${source.url}`); - return label + sources.join(', '); - }, - }; - } + constructor(theme: MarkdownTheme, page: MarkdownPageEvent, options: Options) { + super(theme, page, options); + this.partials = { + ...this.partials, + // Formats `@source` to be a single line + sources: (model: DeclarationReflection | SignatureReflection, options: object) => { + if (!model.sources) { + return ''; + } + let label = model.sources.length > 1 ? '**Sources**: ' : '**Source**: '; + const sources = model.sources.map((source) => `${source.url}`); + return label + sources.join(', '); + }, + }; + } - // Adapted from https://github.com/HiDeoo/starlight-typedoc/blob/d95072e218004276942a5132ec8a4e3561425903/packages/starlight-typedoc/src/libs/theme.ts#L28 - override getRelativeUrl = (url: string) => { - url = super.getRelativeUrl(url).replaceAll('.md', '').replaceAll('.', '').toLowerCase(); - return url; - }; + // Adapted from https://github.com/HiDeoo/starlight-typedoc/blob/d95072e218004276942a5132ec8a4e3561425903/packages/starlight-typedoc/src/libs/theme.ts#L28 + override getRelativeUrl = (url: string) => { + url = super.getRelativeUrl(url).replaceAll('.md', '').replaceAll('.', '').toLowerCase(); + return url; + }; } // Overrides and extensions based on https://github.com/tgreyuk/typedoc-plugin-markdown/blob/next/packages/typedoc-plugin-markdown/docs/usage/customizing.md class TauriTheme extends MarkdownTheme { - getRenderContext(page: MarkdownPageEvent): MarkdownThemeContext { - return new TauriThemeRenderContext(this, page, this.application.options); - } + getRenderContext(page: MarkdownPageEvent): MarkdownThemeContext { + return new TauriThemeRenderContext(this, page, this.application.options); + } } generator(); diff --git a/packages/releases-generator/build.ts b/packages/releases-generator/build.ts index 042dd0e43..b898e0795 100644 --- a/packages/releases-generator/build.ts +++ b/packages/releases-generator/build.ts @@ -2,131 +2,131 @@ import { writeFileSync, mkdirSync } from 'node:fs'; import { join } from 'node:path'; const note = - '\n# NOTE: This file is auto-generated in packages/releases-generator/build.ts\n# For corrections please edit it directly'; + '\n# NOTE: This file is auto-generated in packages/releases-generator/build.ts\n# For corrections please edit it directly'; const packages = [ - { - name: 'tauri', - url: 'https://raw.githubusercontent.com/tauri-apps/tauri/dev/core/tauri/CHANGELOG.md', - tag: 'https://github.com/tauri-apps/tauri/release/tag', - }, - { - name: '@tauri-apps/api', - url: 'https://raw.githubusercontent.com/tauri-apps/tauri/dev/tooling/api/CHANGELOG.md', - tag: 'https://github.com/tauri-apps/tauri/release/tag', - }, - { - name: 'tauri-cli', - url: 'https://raw.githubusercontent.com/tauri-apps/tauri/dev/tooling/cli/CHANGELOG.md', - tag: 'https://github.com/tauri-apps/tauri/release/tag', - }, - { - name: '@tauri-apps/cli', - url: 'https://raw.githubusercontent.com/tauri-apps/tauri/dev/tooling/cli/node/CHANGELOG.md', - tag: 'https://github.com/tauri-apps/tauri/release/tag', - }, - { - name: 'tauri-bundler', - url: 'https://raw.githubusercontent.com/tauri-apps/tauri/dev/tooling/bundler/CHANGELOG.md', - tag: 'https://github.com/tauri-apps/tauri/release/tag', - }, - { - name: 'wry', - url: 'https://raw.githubusercontent.com/tauri-apps/wry/dev/CHANGELOG.md', - tag: 'https://github.com/tauri-apps/wry/release/tag', - }, - { - name: 'tao', - url: 'https://raw.githubusercontent.com/tauri-apps/tao/dev/CHANGELOG.md', - tag: 'https://github.com/tauri-apps/tao/release/tag', - }, + { + name: 'tauri', + url: 'https://raw.githubusercontent.com/tauri-apps/tauri/dev/core/tauri/CHANGELOG.md', + tag: 'https://github.com/tauri-apps/tauri/release/tag', + }, + { + name: '@tauri-apps/api', + url: 'https://raw.githubusercontent.com/tauri-apps/tauri/dev/tooling/api/CHANGELOG.md', + tag: 'https://github.com/tauri-apps/tauri/release/tag', + }, + { + name: 'tauri-cli', + url: 'https://raw.githubusercontent.com/tauri-apps/tauri/dev/tooling/cli/CHANGELOG.md', + tag: 'https://github.com/tauri-apps/tauri/release/tag', + }, + { + name: '@tauri-apps/cli', + url: 'https://raw.githubusercontent.com/tauri-apps/tauri/dev/tooling/cli/node/CHANGELOG.md', + tag: 'https://github.com/tauri-apps/tauri/release/tag', + }, + { + name: 'tauri-bundler', + url: 'https://raw.githubusercontent.com/tauri-apps/tauri/dev/tooling/bundler/CHANGELOG.md', + tag: 'https://github.com/tauri-apps/tauri/release/tag', + }, + { + name: 'wry', + url: 'https://raw.githubusercontent.com/tauri-apps/wry/dev/CHANGELOG.md', + tag: 'https://github.com/tauri-apps/wry/release/tag', + }, + { + name: 'tao', + url: 'https://raw.githubusercontent.com/tauri-apps/tao/dev/CHANGELOG.md', + tag: 'https://github.com/tauri-apps/tao/release/tag', + }, ]; const baseDir = '../../src/content/docs/release'; let latestVersions: { - [key: string]: string; + [key: string]: string; } = {}; async function generator() { - for (const pkg of packages) { - const response = await fetch(pkg.url); - const responseText: string = await response.text(); - const releases = responseText - .split('## \\[') - .filter((item) => !item.includes('# Changelog')) - .map((section) => { - const [version, ...c] = section.split('\n'); - const contents = c.join('\n'); - return { - version: version.replace('\\[', '').replace(']', ''), - notes: contents, - }; - }) - .filter(({ version }) => !version.includes('Not Published')); + for (const pkg of packages) { + const response = await fetch(pkg.url); + const responseText: string = await response.text(); + const releases = responseText + .split('## \\[') + .filter((item) => !item.includes('# Changelog')) + .map((section) => { + const [version, ...c] = section.split('\n'); + const contents = c.join('\n'); + return { + version: version.replace('\\[', '').replace(']', ''), + notes: contents, + }; + }) + .filter(({ version }) => !version.includes('Not Published')); - mkdirSync(join(baseDir, pkg.name), { recursive: true }); - // - /* - * Write files for each version - */ - const len = releases.length; - for (let i = 0; i < len; i++) { - /** - * Deal with next-prev labels - */ - const thisVersion = releases[i].version; + mkdirSync(join(baseDir, pkg.name), { recursive: true }); + // + /* + * Write files for each version + */ + const len = releases.length; + for (let i = 0; i < len; i++) { + /** + * Deal with next-prev labels + */ + const thisVersion = releases[i].version; - if (i === 0) { - // latest version - latestVersions[pkg.name] = `v${thisVersion}`; - } - // - const pageFrontmatter = [ - note, - `title: '${pkg.name}@${thisVersion}'`, - `description: '${thisVersion}'`, - `slug: 'release/${pkg.name}/v${thisVersion}'`, - `tableOfContents: false`, - `editUrl: 'https://github.com/tauri-apps/tauri-docs/packages/releases-generator/build.ts'`, - 'pagefind: false', - 'sidebar:', - ` label: ${thisVersion}`, - ` order: ${semverToInt(thisVersion)}`, - ]; + if (i === 0) { + // latest version + latestVersions[pkg.name] = `v${thisVersion}`; + } + // + const pageFrontmatter = [ + note, + `title: '${pkg.name}@${thisVersion}'`, + `description: '${thisVersion}'`, + `slug: 'release/${pkg.name}/v${thisVersion}'`, + `tableOfContents: false`, + `editUrl: 'https://github.com/tauri-apps/tauri-docs/packages/releases-generator/build.ts'`, + 'pagefind: false', + 'sidebar:', + ` label: ${thisVersion}`, + ` order: ${semverToInt(thisVersion)}`, + ]; - const frontmatter = ['---', ...pageFrontmatter, '---'].join('\n'); - // - const indexLink = `[Return](/release)`; - const viewInGitHub = `View on GitHub`; - const linksDiv = `
${indexLink}${viewInGitHub}
`; - // - const sidebar = `\nimport ReleaseSidebar from '@components/list/ReleaseSidebar.astro'; + const frontmatter = ['---', ...pageFrontmatter, '---'].join('\n'); + // + const indexLink = `[Return](/release)`; + const viewInGitHub = `View on GitHub`; + const linksDiv = `
${indexLink}${viewInGitHub}
`; + // + const sidebar = `\nimport ReleaseSidebar from '@components/list/ReleaseSidebar.astro'; \n\n\n`; - writeFileSync( - join(baseDir, pkg.name, `v${thisVersion}.mdx`), - `${frontmatter}\n${linksDiv}\n${entitify(releases[i].notes)}` - ); - } - } + writeFileSync( + join(baseDir, pkg.name, `v${thisVersion}.mdx`), + `${frontmatter}\n${linksDiv}\n${entitify(releases[i].notes)}` + ); + } + } - // Generate index page - const extraNote = - '# To quickly preview changes, you can edit this file, them make sure you copy the changes over the source build.ts script\n'; - const indexPage = [ - '---', - note, - extraNote, - `title: 'Tauri Core Ecosystem Releases'`, - `editUrl: 'https://github.com/tauri-apps/tauri-docs/packages/releases-generator/build.ts'`, - 'tableOfContents: false', - 'sidebar:', - ' label: Overview', - ' order: -1000000', - '---', - ].join('\n'); + // Generate index page + const extraNote = + '# To quickly preview changes, you can edit this file, them make sure you copy the changes over the source build.ts script\n'; + const indexPage = [ + '---', + note, + extraNote, + `title: 'Tauri Core Ecosystem Releases'`, + `editUrl: 'https://github.com/tauri-apps/tauri-docs/packages/releases-generator/build.ts'`, + 'tableOfContents: false', + 'sidebar:', + ' label: Overview', + ' order: -1000000', + '---', + ].join('\n'); - const indexPageContent = `import { LinkCard, CardGrid } from '@astrojs/starlight/components';\n + const indexPageContent = `import { LinkCard, CardGrid } from '@astrojs/starlight/components';\n @@ -137,55 +137,55 @@ async function generator() { `; - writeFileSync(join(baseDir, 'index.mdx'), `${indexPage}\n${indexPageContent}`); + writeFileSync(join(baseDir, 'index.mdx'), `${indexPage}\n${indexPageContent}`); } function entitify(str: string): string { - return str - .replace(/[&<>"']/g, function (entity) { - switch (entity) { - case '&': - return '&'; - case '<': - return '<'; - case '>': - return '>'; - case '"': - return '"'; - case "'": - return '''; - default: - return entity; - } - }) - .replace(/\$\{/g, '$\\{'); + return str + .replace(/[&<>"']/g, function (entity) { + switch (entity) { + case '&': + return '&'; + case '<': + return '<'; + case '>': + return '>'; + case '"': + return '"'; + case "'": + return '''; + default: + return entity; + } + }) + .replace(/\$\{/g, '$\\{'); } const PRE_RELEASE_VALUES: any = { - alpha: 1, - 'beta-rc': 100, - beta: 1000, - rc: 100000, + alpha: 1, + 'beta-rc': 100, + beta: 1000, + rc: 100000, }; function semverToInt(semver: string) { - const BASE = 1000000000; - let [version, preRelease] = semver.split('-'); - const [major, minor, patch] = version.split('.').map(Number); - let preReleaseValue = 0; - if (preRelease) { - const match = preRelease.split('.'); - if (match) { - const identifier = match[0]; - const number = match[1] !== undefined ? parseInt(match[1]) : 0; - preReleaseValue = PRE_RELEASE_VALUES[identifier] + number; - } - } - return BASE - (major * 100000000 + minor * 1000000 + patch * 10000 + preReleaseValue); + const BASE = 1000000000; + let [version, preRelease] = semver.split('-'); + const [major, minor, patch] = version.split('.').map(Number); + let preReleaseValue = 0; + if (preRelease) { + const match = preRelease.split('.'); + if (match) { + const identifier = match[0]; + const number = match[1] !== undefined ? parseInt(match[1]) : 0; + preReleaseValue = PRE_RELEASE_VALUES[identifier] + number; + } + } + return BASE - (major * 100000000 + minor * 1000000 + patch * 10000 + preReleaseValue); } if (process.env.CONTEXT === 'production' || process.env.HEAD?.startsWith('release-pages')) { - generator(); + generator(); } else { - console.info('Skipping `/release` pages build'); + console.info('Skipping `/release` pages build'); } diff --git a/public/navigate.js b/public/navigate.js index 5deb73662..7a3074c1f 100644 --- a/public/navigate.js +++ b/public/navigate.js @@ -1,45 +1,45 @@ async function chapterNavigation() { - let navigating = false; - document.addEventListener('keydown', function (e) { - if (navigating) return; - if (e.altKey || e.ctrlKey || e.metaKey) { - return; - } - if (window.search && document.activeElement === window.search) { - return; - } + let navigating = false; + document.addEventListener('keydown', function (e) { + if (navigating) return; + if (e.altKey || e.ctrlKey || e.metaKey) { + return; + } + if (window.search && document.activeElement === window.search) { + return; + } - switch (e.key) { - case 'ArrowLeft': - e.preventDefault(); - let previousButton = document.querySelector('a[rel="prev"]'); - if (!previousButton && window.location.pathname !== '/') previousButton = { href: '/' }; + switch (e.key) { + case 'ArrowLeft': + e.preventDefault(); + let previousButton = document.querySelector('a[rel="prev"]'); + if (!previousButton && window.location.pathname !== '/') previousButton = { href: '/' }; - if (document.referrer.includes(window.location.host)) - if (previousButton) { - window.location.href = previousButton.href; - navigating = true; - } - break; - case 'ArrowRight': - e.preventDefault(); - let nextButton = document.querySelector('a[rel="next"]'); - if (!nextButton && window.location.pathname === '/') nextButton = { href: '/start/' }; + if (document.referrer.includes(window.location.host)) + if (previousButton) { + window.location.href = previousButton.href; + navigating = true; + } + break; + case 'ArrowRight': + e.preventDefault(); + let nextButton = document.querySelector('a[rel="next"]'); + if (!nextButton && window.location.pathname === '/') nextButton = { href: '/start/' }; - if (nextButton) { - window.location.href = nextButton.href; - navigating = true; - } - break; - } - }); + if (nextButton) { + window.location.href = nextButton.href; + navigating = true; + } + break; + } + }); } window.addEventListener('DOMContentLoaded', () => { - chapterNavigation(); + chapterNavigation(); }); window.onload = function () { - document.body.setAttribute('tabindex', '-1'); - document.body.focus(); + document.body.setAttribute('tabindex', '-1'); + document.body.focus(); }; diff --git a/src/components/AwesomeTauri.astro b/src/components/AwesomeTauri.astro index 90f253750..cd311345a 100644 --- a/src/components/AwesomeTauri.astro +++ b/src/components/AwesomeTauri.astro @@ -9,11 +9,11 @@ import { readFile } from 'fs/promises'; const md = await createMarkdownProcessor(); const res = readFile( - join( - dirname(dirname(dirname(fileURLToPath(import.meta.url)))), - 'packages/awesome-tauri/README.md' - ), - 'utf-8' + join( + dirname(dirname(dirname(fileURLToPath(import.meta.url)))), + 'packages/awesome-tauri/README.md' + ), + 'utf-8' ); const content = await md.render(await res); const dom = new JSDOM('' + content.code); @@ -21,56 +21,56 @@ const document = dom.window.document; let categories = document.querySelectorAll('h3'); let cards = []; const sections = { - plugins: 'Plugins', - 'plugins-no-official': 'Plugins', - integrations: 'Integrations', - articles: 'Articles', - guides: 'Guides', - tutorials: 'Tutorials', - templates: 'Templates', - 'applications-audio-video': 'Audio & Video', - 'applications-chatgpt-clients': 'ChatGPT clients', - 'applications-data': 'Data', - 'applications-developer-tools': 'Developer tools', - 'applications-email-feeds': 'Email & Feeds', - 'applications-file-management': 'File management', - 'applications-finance': 'Finance', - 'applications-gaming': 'Gaming', - 'applications-information': 'Information', - 'applications-learning': 'Learning', - 'applications-networking': 'Networking', - 'applications-office-writing': 'Office & Writing', - 'applications-productivity': 'Productivity', - 'applications-search': 'Search', - 'applications-security': 'Security', - 'applications-social-media': 'Social media', - 'applications-utilities': 'Utilities', + plugins: 'Plugins', + 'plugins-no-official': 'Plugins', + integrations: 'Integrations', + articles: 'Articles', + guides: 'Guides', + tutorials: 'Tutorials', + templates: 'Templates', + 'applications-audio-video': 'Audio & Video', + 'applications-chatgpt-clients': 'ChatGPT clients', + 'applications-data': 'Data', + 'applications-developer-tools': 'Developer tools', + 'applications-email-feeds': 'Email & Feeds', + 'applications-file-management': 'File management', + 'applications-finance': 'Finance', + 'applications-gaming': 'Gaming', + 'applications-information': 'Information', + 'applications-learning': 'Learning', + 'applications-networking': 'Networking', + 'applications-office-writing': 'Office & Writing', + 'applications-productivity': 'Productivity', + 'applications-search': 'Search', + 'applications-security': 'Security', + 'applications-social-media': 'Social media', + 'applications-utilities': 'Utilities', }; for (const header of categories) { - if (header.textContent === sections[section]) { - let list = header.nextSibling.nextSibling as HTMLElement; - for (const entry: HTMLLinkElement of list.children) { - if (section.includes('-no-official')) { - let img = entry.children[1]; - if (img && img.src && img.src.includes('official')) continue; - img = entry.children[2]; - if (img && img.src && img.src.includes('official')) continue; - } - cards.push({ - href: entry.children[0].href, - name: entry.children[0].textContent, - description: entry.textContent.split(' - ')[1], - }); - } - } + if (header.textContent === sections[section]) { + let list = header.nextSibling.nextSibling as HTMLElement; + for (const entry: HTMLLinkElement of list.children) { + if (section.includes('-no-official')) { + let img = entry.children[1]; + if (img && img.src && img.src.includes('official')) continue; + img = entry.children[2]; + if (img && img.src && img.src.includes('official')) continue; + } + cards.push({ + href: entry.children[0].href, + name: entry.children[0].textContent, + description: entry.textContent.split(' - ')[1], + }); + } + } } --- - { - cards.map((card) => ( - - )) - } + { + cards.map((card) => ( + + )) + } diff --git a/src/components/CardGridSearch.astro b/src/components/CardGridSearch.astro index 71c8a5598..0b3680fb3 100644 --- a/src/components/CardGridSearch.astro +++ b/src/components/CardGridSearch.astro @@ -6,7 +6,7 @@ */ interface Props { - placeholder?: string; + placeholder?: string; } const { placeholder = 'Search features and community resources...' } = Astro.props; @@ -14,49 +14,49 @@ const { placeholder = 'Search features and community resources...' } = Astro.pro --- -
- - + + +
+
diff --git a/src/components/CommandTabs.astro b/src/components/CommandTabs.astro index 0a61b1f94..9b7107cd2 100644 --- a/src/components/CommandTabs.astro +++ b/src/components/CommandTabs.astro @@ -3,42 +3,42 @@ import { Tabs, TabItem } from '@astrojs/starlight/components'; import { Code } from '@astrojs/starlight/components'; interface Props { - npm?: string; - yarn?: string; - pnpm?: string; - cargo?: string; + npm?: string; + yarn?: string; + pnpm?: string; + cargo?: string; } const { npm, yarn, pnpm, cargo } = Astro.props; --- - { - npm && ( - - - - ) - } - { - yarn && ( - - - - ) - } - { - pnpm && ( - - - - ) - } - { - cargo && ( - - - - ) - } + { + npm && ( + + + + ) + } + { + yarn && ( + + + + ) + } + { + pnpm && ( + + + + ) + } + { + cargo && ( + + + + ) + } diff --git a/src/components/Demo.astro b/src/components/Demo.astro index 62cee983c..b4016ecc9 100644 --- a/src/components/Demo.astro +++ b/src/components/Demo.astro @@ -4,5 +4,5 @@ const enabled = process.env.TAURI_DEBUG && Astro.slots.has('default'); --- - {enabled ? :

Try it in the Tauri Docs app (coming soon)

} + {enabled ? :

Try it in the Tauri Docs app (coming soon)

}
diff --git a/src/components/Feedback.astro b/src/components/Feedback.astro index 56771a908..836d927c4 100644 --- a/src/components/Feedback.astro +++ b/src/components/Feedback.astro @@ -7,8 +7,8 @@ const CONTENT_SET_ID = '54faa8e2-cd0d-4997-9a3c-d9fed28f358a'; --- diff --git a/src/components/PluginLinks.astro b/src/components/PluginLinks.astro index 3c886626d..17e7719bd 100644 --- a/src/components/PluginLinks.astro +++ b/src/components/PluginLinks.astro @@ -2,8 +2,8 @@ type Plugin = 'notification'; interface Props { - plugin: Plugin; - showJsLinks?: boolean; + plugin: Plugin; + showJsLinks?: boolean; } const { plugin, showJsLinks = true } = Astro.props; const github = `https://github.com/tauri-apps/plugins-workspace/tree/v2/plugins/${plugin}`; @@ -15,93 +15,93 @@ const hasApiLinks = jsApi || docsrs; ---
- - - - GitHub - { - npm && ( - - - - - npm - - ) - } - { - cratesio && ( - - - - - crates.io - - ) - } - { - hasApiLinks && ( -
- API Reference - {jsApi && ( - - - - - - - - - - - - - )} - {docsrs && ( - - - - - - )} -
- ) - } + + + + GitHub + { + npm && ( + + + + + npm + + ) + } + { + cratesio && ( + + + + + crates.io + + ) + } + { + hasApiLinks && ( +
+ API Reference + {jsApi && ( + + + + + + + + + + + + + )} + {docsrs && ( + + + + + + )} +
+ ) + }
diff --git a/src/components/Stub.astro b/src/components/Stub.astro index f22dc17ca..bed6d4957 100644 --- a/src/components/Stub.astro +++ b/src/components/Stub.astro @@ -5,19 +5,19 @@ const baseUrl = 'https://github.com/tauri-apps/tauri-docs/tree/v2'; --- -

- This is a stub and is waiting for contributions. Get involved by - visiting us on GitHub or joining us on Discord. -

+

+ This is a stub and is waiting for contributions. Get involved by + visiting us on GitHub or joining us on Discord. +

- { - Astro.slots.has('default') && ( - <> -
Here are some ideas to get you started:
- - - ) - } + { + Astro.slots.has('default') && ( + <> +
Here are some ideas to get you started:
+ + + ) + }
diff --git a/src/components/UpgradeBadge.astro b/src/components/UpgradeBadge.astro index f1fc4705a..d508d525e 100644 --- a/src/components/UpgradeBadge.astro +++ b/src/components/UpgradeBadge.astro @@ -7,30 +7,30 @@ interface Props extends HTMLAttributes<'a'> {} --- diff --git a/src/components/list/Community.astro b/src/components/list/Community.astro index b371e4580..904a93297 100644 --- a/src/components/list/Community.astro +++ b/src/components/list/Community.astro @@ -1,29 +1,29 @@ --- import { LinkCard, CardGrid } from '@astrojs/starlight/components'; type Entry = { - name: string; - description: string; - href: string; + name: string; + description: string; + href: string; }; const list: Entry[] = [ - { - name: 'Have something to share?', - description: 'Open a pull request to show us your amazing resource', - href: 'https://github.com/tauri-apps/tauri-docs/pulls', - }, - { - name: 'Github OAuth with Lucia', - description: 'Authenticate users with a simple JS server', - href: 'https://lucia-auth.com/guidebook/github-oauth-native/tauri', - }, + { + name: 'Have something to share?', + description: 'Open a pull request to show us your amazing resource', + href: 'https://github.com/tauri-apps/tauri-docs/pulls', + }, + { + name: 'Github OAuth with Lucia', + description: 'Authenticate users with a simple JS server', + href: 'https://lucia-auth.com/guidebook/github-oauth-native/tauri', + }, ]; --- - { - list - .sort((a, b) => a.name.localeCompare(b.name)) - .map((item) => ) - } + { + list + .sort((a, b) => a.name.localeCompare(b.name)) + .map((item) => ) + } diff --git a/src/components/list/Directory.astro b/src/components/list/Directory.astro index ed8eb69aa..98c96a3f0 100644 --- a/src/components/list/Directory.astro +++ b/src/components/list/Directory.astro @@ -1,45 +1,45 @@ --- import config from 'virtual:starlight/user-config'; import { - stripLeadingAndTrailingSlashes, - ensureTrailingSlash, + stripLeadingAndTrailingSlashes, + ensureTrailingSlash, } from 'node_modules/@astrojs/starlight/utils/path'; import { LinkCard, CardGrid } from '@astrojs/starlight/components'; import { routes, type Route } from 'node_modules/@astrojs/starlight/utils/routing'; interface Props { - /** - * Slug relative to /src - e.g "/zh-cn/features" - * - * Note: leading and trailing slashes are dropped "/features/" === "features" - */ - slug: string; - /** - * Filter out pages by title - case insensitive - */ - filterOutByTitle?: string[]; - /** - * Filter out pages by file name - case insensitive - */ - filterOutByFileName?: string[]; - /** - * Force alphabetical order - by default it sorts by `frontmatter.sidebar.order`, then alphabetically. - * - * Use this to ignore sidebar order - */ - sortAlphabetically?: boolean; + /** + * Slug relative to /src - e.g "/zh-cn/features" + * + * Note: leading and trailing slashes are dropped "/features/" === "features" + */ + slug: string; + /** + * Filter out pages by title - case insensitive + */ + filterOutByTitle?: string[]; + /** + * Filter out pages by file name - case insensitive + */ + filterOutByFileName?: string[]; + /** + * Force alphabetical order - by default it sorts by `frontmatter.sidebar.order`, then alphabetically. + * + * Use this to ignore sidebar order + */ + sortAlphabetically?: boolean; } function hasSidebarOrder(page: Route): number | undefined { - return page.entry.data.sidebar.order; + return page.entry.data.sidebar.order; } function alphaSort(a: Route, b: Route): number { - return a.entry.data.title.localeCompare(b.entry.data.title); + return a.entry.data.title.localeCompare(b.entry.data.title); } function compareOrder(a: Route, b: Route): boolean { - return a.entry.data.sidebar.order > b.entry.data.sidebar.order; + return a.entry.data.sidebar.order > b.entry.data.sidebar.order; } let { slug } = Astro.props; @@ -53,7 +53,7 @@ let [currentPageLocale] = stripLeadingAndTrailingSlashes(Astro.url.pathname).spl // Ensure currentPageLocale is a locale when it's page is on default locale if (!localesList.includes(currentPageLocale)) { - currentPageLocale = defaultLocale; + currentPageLocale = defaultLocale; } const locale = currentPageLocale; @@ -62,7 +62,7 @@ const pageLang = ensureTrailingSlash(locale); // Ensure the locale is ignore if passed on `slug` let [sliceLocale] = stripLeadingAndTrailingSlashes(slug).split('/'); if (localesList.includes(sliceLocale)) { - slug = slug.slice(sliceLocale.length + 1); + slug = slug.slice(sliceLocale.length + 1); } // Localize `slug` to the current page locale slug = locale === defaultLocale ? slug : pageLang + slug; @@ -71,14 +71,14 @@ let fallbackList: Route[] = []; let mainList: Route[] = []; routes.forEach((page) => { - // `page.slug` is the slug of the current page being looped, `slug` is a prop - if (page.slug.startsWith(slug)) { - if (page.isFallback) { - fallbackList.push(page); - } else if (page.slug !== slug) { - mainList.push(page); - } - } + // `page.slug` is the slug of the current page being looped, `slug` is a prop + if (page.slug.startsWith(slug)) { + if (page.isFallback) { + fallbackList.push(page); + } else if (page.slug !== slug) { + mainList.push(page); + } + } }); /** @@ -86,86 +86,86 @@ routes.forEach((page) => { */ if (filterOutByTitle.length > 0) { - fallbackList = fallbackList.filter( - (page) => !filterOutByTitle.some((val) => page.entry.data.title.includes(val)) - ); - mainList = mainList.filter( - (page) => !filterOutByTitle.some((val) => page.entry.data.title.includes(val)) - ); + fallbackList = fallbackList.filter( + (page) => !filterOutByTitle.some((val) => page.entry.data.title.includes(val)) + ); + mainList = mainList.filter( + (page) => !filterOutByTitle.some((val) => page.entry.data.title.includes(val)) + ); } if (filterOutByFileName.length > 0) { - fallbackList = fallbackList.filter( - (page) => !filterOutByFileName.some((val) => page.entry.id.includes(val)) - ); - mainList = mainList.filter( - (page) => !filterOutByFileName.some((val) => page.entry.id.includes(val)) - ); + fallbackList = fallbackList.filter( + (page) => !filterOutByFileName.some((val) => page.entry.id.includes(val)) + ); + mainList = mainList.filter( + (page) => !filterOutByFileName.some((val) => page.entry.id.includes(val)) + ); } if (!sortAlphabetically) { - // dumb luck this works, now why? - const sortVal = locale === defaultLocale ? 1 : -1; - // Sort list following sidebar order - mainList.sort((a, b) => { - if (!hasSidebarOrder(a) && !hasSidebarOrder(b)) { - return alphaSort(a, b); - } - if (compareOrder(a, b)) { - return sortVal; - } else { - return -sortVal; - } - }); - // Sort list following sidebar order - fallbackList.sort((a, b) => { - if (!hasSidebarOrder(a) && !hasSidebarOrder(b)) { - return alphaSort(a, b); - } - if (compareOrder(a, b)) { - return -sortVal; - } else { - return sortVal; - } - }); + // dumb luck this works, now why? + const sortVal = locale === defaultLocale ? 1 : -1; + // Sort list following sidebar order + mainList.sort((a, b) => { + if (!hasSidebarOrder(a) && !hasSidebarOrder(b)) { + return alphaSort(a, b); + } + if (compareOrder(a, b)) { + return sortVal; + } else { + return -sortVal; + } + }); + // Sort list following sidebar order + fallbackList.sort((a, b) => { + if (!hasSidebarOrder(a) && !hasSidebarOrder(b)) { + return alphaSort(a, b); + } + if (compareOrder(a, b)) { + return -sortVal; + } else { + return sortVal; + } + }); } else { - // Sort alphabetically - mainList.sort((a, b) => alphaSort(a, b)); - fallbackList.sort((a, b) => alphaSort(a, b)); + // Sort alphabetically + mainList.sort((a, b) => alphaSort(a, b)); + fallbackList.sort((a, b) => alphaSort(a, b)); } --- - { - mainList.map((item) => ( - - )) - } - { - locale !== defaultLocale && - fallbackList.map((item) => ( - - )) - } + { + mainList.map((item) => ( + + )) + } + { + locale !== defaultLocale && + fallbackList.map((item) => ( + + )) + } diff --git a/src/components/list/ReleaseSidebar.astro b/src/components/list/ReleaseSidebar.astro index 7df62eeed..6bda03a4c 100644 --- a/src/components/list/ReleaseSidebar.astro +++ b/src/components/list/ReleaseSidebar.astro @@ -5,24 +5,24 @@ import { Icon } from '@astrojs/starlight/components'; import semver from 'semver'; interface Props { - /** - * Package name - */ - packageName: string; - /** - * Slug relative to /src - e.g "/zh-cn/features" - * - * Note: leading and trailing slashes are dropped "/features/" === "features" - */ - slug: string; - /** - * Filter out pages by title - case insensitive - */ - filterOutByTitle?: string[]; - /** - * Filter out pages by file name - case insensitive - */ - filterOutByFileName?: string[]; + /** + * Package name + */ + packageName: string; + /** + * Slug relative to /src - e.g "/zh-cn/features" + * + * Note: leading and trailing slashes are dropped "/features/" === "features" + */ + slug: string; + /** + * Filter out pages by title - case insensitive + */ + filterOutByTitle?: string[]; + /** + * Filter out pages by file name - case insensitive + */ + filterOutByFileName?: string[]; } let { slug } = Astro.props; @@ -33,11 +33,11 @@ slug = stripLeadingAndTrailingSlashes(slug.toLowerCase()); let mainList: Route[] = []; routes.forEach((page) => { - // `page.slug` is the slug of the current page being looped, - // `slug` is this component prop - if (page.slug.startsWith(slug + '/')) { - mainList.push(page); - } + // `page.slug` is the slug of the current page being looped, + // `slug` is this component prop + if (page.slug.startsWith(slug + '/')) { + mainList.push(page); + } }); /** @@ -45,237 +45,237 @@ routes.forEach((page) => { */ if (filterOutByTitle.length > 0) { - mainList = mainList.filter( - (page) => !filterOutByTitle.some((val) => page.entry.data.title.includes(val)) - ); + mainList = mainList.filter( + (page) => !filterOutByTitle.some((val) => page.entry.data.title.includes(val)) + ); } if (filterOutByFileName.length > 0) { - mainList = mainList.filter( - (page) => !filterOutByFileName.some((val) => page.entry.id.includes(val)) - ); + mainList = mainList.filter( + (page) => !filterOutByFileName.some((val) => page.entry.id.includes(val)) + ); } function sortVersions(a: Route, b: Route): number { - const t1 = a.entry.data.title; - const t2 = b.entry.data.title; - const [package1, version1] = t1.split('@').filter((w) => w.length > 0); - const [package2, version2] = t2.split('@').filter((w) => w.length > 0); - if (package1 === package2) { - return semver.lt(version1, version2) ? -1 : semver.gt(version1, version2) ? 1 : 0; - } else { - return package1.localeCompare(package2); - } + const t1 = a.entry.data.title; + const t2 = b.entry.data.title; + const [package1, version1] = t1.split('@').filter((w) => w.length > 0); + const [package2, version2] = t2.split('@').filter((w) => w.length > 0); + if (package1 === package2) { + return semver.lt(version1, version2) ? -1 : semver.gt(version1, version2) ? 1 : 0; + } else { + return package1.localeCompare(package2); + } } mainList.sort((a, b) => sortVersions(b, a)); ---
-
-
-

Changelogs:
{packageName}

-
-
- { - mainList.map((item) => ( - <> - {item.entry.data.description} - - )) - } -
-
+
+
+

Changelogs:
{packageName}

+
+
+ { + mainList.map((item) => ( + <> + {item.entry.data.description} + + )) + } +
+
- + diff --git a/src/components/overrides/Footer.astro b/src/components/overrides/Footer.astro index 0ce4665c2..d513c8798 100644 --- a/src/components/overrides/Footer.astro +++ b/src/components/overrides/Footer.astro @@ -11,13 +11,13 @@ const year = new Date().getFullYear();

© {year} Tauri Contributors. CC-BY / MIT

diff --git a/src/components/overrides/PageFrame.astro b/src/components/overrides/PageFrame.astro index 60b808614..d531ae0d5 100644 --- a/src/components/overrides/PageFrame.astro +++ b/src/components/overrides/PageFrame.astro @@ -6,96 +6,96 @@ const { labels } = Astro.props; ---
-
- -
+
+ +
diff --git a/src/components/overrides/Sidebar.astro b/src/components/overrides/Sidebar.astro index 7fba21e03..dbba161ff 100644 --- a/src/components/overrides/Sidebar.astro +++ b/src/components/overrides/Sidebar.astro @@ -12,107 +12,107 @@ import { AstroError } from 'astro/errors'; // 2. Create a new derived set of `Astro.props` that only contains one set of sidebar entries // 3. Check if the current page being rendered is current page to determine if this sidebar group should be selected const multiSidebarConfig: [string, boolean, Props][] = Astro.props.sidebar.map((entry) => { - if (entry.type !== 'group') { - throw new AstroError( - `\`${entry.label}\` cannot be used with multiple Starlight sidebars. + if (entry.type !== 'group') { + throw new AstroError( + `\`${entry.label}\` cannot be used with multiple Starlight sidebars. Each top-level \`sidebar\` item in the Starlight config must be either a group or autogenerated. See https://starlight.astro.build/guides/sidebar/#groups and https://starlight.astro.build/guides/sidebar/#autogenerated-groups` - ); - } + ); + } - // Recursively check if a group of sidebar entries contains the current page - const findIfIsCurrent = (entry: (typeof Astro.props.sidebar)[number]): boolean => { - if (entry.type === 'link') { - return entry.isCurrent; - } - return entry.entries.some((item) => findIfIsCurrent(item)); - }; + // Recursively check if a group of sidebar entries contains the current page + const findIfIsCurrent = (entry: (typeof Astro.props.sidebar)[number]): boolean => { + if (entry.type === 'link') { + return entry.isCurrent; + } + return entry.entries.some((item) => findIfIsCurrent(item)); + }; - const isCurrentPage = findIfIsCurrent(entry); + const isCurrentPage = findIfIsCurrent(entry); - return [entry.label, isCurrentPage, { ...Astro.props, sidebar: [...entry.entries] }]; + return [entry.label, isCurrentPage, { ...Astro.props, sidebar: [...entry.entries] }]; }); let foundCurrentPage = false; for (const page of multiSidebarConfig) { - if (page[1]) { - foundCurrentPage = true; - break; - } + if (page[1]) { + foundCurrentPage = true; + break; + } } if (!foundCurrentPage && multiSidebarConfig.length > 0) { - multiSidebarConfig[0][1] = true; + multiSidebarConfig[0][1] = true; } if (!multiSidebarConfig.some(([_label, isCurrentPage, _config]) => isCurrentPage)) { - multiSidebarConfig[0][1] = true; + multiSidebarConfig[0][1] = true; } ---
- { - multiSidebarConfig.map(([label, isCurrentPage, config]) => ( - <> - -
- - - -
- - )) - } + { + multiSidebarConfig.map(([label, isCurrentPage, config]) => ( + <> + +
+ + + +
+ + )) + }
diff --git a/src/components/overrides/SiteTitle.astro b/src/components/overrides/SiteTitle.astro index 7fa286cbc..0d053fd62 100644 --- a/src/components/overrides/SiteTitle.astro +++ b/src/components/overrides/SiteTitle.astro @@ -10,150 +10,150 @@ import { Icon } from '@astrojs/starlight/components'; const curLocale = Astro.props.locale; type Link = { - title: string; - value: string; - transfer: boolean; + title: string; + value: string; + transfer: boolean; }; const links: Link[] = [ - { - title: 'Guides', - value: '/start/', - transfer: true, - }, - { - title: 'References', - value: '/reference/acl/', - transfer: true, - }, - { - title: 'Blog', - value: '/blog', - transfer: false, - }, - { - title: 'Releases', - value: '/release/', - transfer: true, - }, + { + title: 'Guides', + value: '/start/', + transfer: true, + }, + { + title: 'References', + value: '/reference/acl/', + transfer: true, + }, + { + title: 'Blog', + value: '/blog', + transfer: false, + }, + { + title: 'Releases', + value: '/release/', + transfer: true, + }, ]; --- <> - + - - - + + + diff --git a/src/content/config.ts b/src/content/config.ts index cdb83fcc2..7550b18ee 100644 --- a/src/content/config.ts +++ b/src/content/config.ts @@ -3,6 +3,6 @@ import { docsSchema, i18nSchema } from '@astrojs/starlight/schema'; import { blogSchema } from 'starlight-blog/schema'; export const collections = { - docs: defineCollection({ schema: docsSchema({ extend: blogSchema() }) }), - i18n: defineCollection({ type: 'data', schema: i18nSchema() }), + docs: defineCollection({ schema: docsSchema({ extend: blogSchema() }) }), + i18n: defineCollection({ type: 'data', schema: i18nSchema() }), }; diff --git a/src/content/docs/about/index.mdx b/src/content/docs/about/index.mdx index 0b0bb1739..be03562fd 100644 --- a/src/content/docs/about/index.mdx +++ b/src/content/docs/about/index.mdx @@ -11,19 +11,19 @@ If you're looking for a quick technical overview and to start building an app th import { LinkCard, CardGrid } from '@astrojs/starlight/components'; - - - + + + diff --git a/src/content/docs/blog/tauri-1-1.mdx b/src/content/docs/blog/tauri-1-1.mdx index f22196eaf..24ccbbbe2 100644 --- a/src/content/docs/blog/tauri-1-1.mdx +++ b/src/content/docs/blog/tauri-1-1.mdx @@ -18,10 +18,10 @@ After 113 pull requests and nearly two months of work, the Tauri team is pleased You can update the dependencies with: ## What's New in 1.1.0 @@ -79,20 +79,20 @@ In the 1.0 releases Tauri supports the `JSON` configuration format by default, a ```json title=tauri.conf.json { - "build": { - "devPath": "http://localhost:8000", - "distDir": "../dist" - } + "build": { + "devPath": "http://localhost:8000", + "distDir": "../dist" + } } ``` ```json5 { - build: { - // devServer URL (comments are allowed!) - devPath: 'http://localhost:8000', - distDir: '../dist', - }, + build: { + // devServer URL (comments are allowed!) + devPath: 'http://localhost:8000', + distDir: '../dist', + }, } ``` diff --git a/src/content/docs/blog/tauri-1-2.mdx b/src/content/docs/blog/tauri-1-2.mdx index 172908a10..bdbb22628 100644 --- a/src/content/docs/blog/tauri-1-2.mdx +++ b/src/content/docs/blog/tauri-1-2.mdx @@ -18,10 +18,10 @@ The Tauri team is happy to announce the 1.2.0 release. It includes a security fi Make sure to update both NPM and Cargo dependencies to the 1.2.0 release. You can update the dependencies with: ## What's in 1.2.0 diff --git a/src/content/docs/blog/tauri-1-3.mdx b/src/content/docs/blog/tauri-1-3.mdx index 59156a47a..0871d8148 100644 --- a/src/content/docs/blog/tauri-1-3.mdx +++ b/src/content/docs/blog/tauri-1-3.mdx @@ -20,10 +20,10 @@ The Tauri team is excited to announce the 1.3 release. This version includes sec Make sure to update both NPM and Cargo dependencies to the 1.3.0 release. You can update the dependencies with: ## What's in 1.3.0 diff --git a/src/content/docs/blog/tauri-1-4.mdx b/src/content/docs/blog/tauri-1-4.mdx index 392d2712f..8490e35dd 100644 --- a/src/content/docs/blog/tauri-1-4.mdx +++ b/src/content/docs/blog/tauri-1-4.mdx @@ -20,10 +20,10 @@ The Tauri team is excited to announce the 1.4 release. This version includes sev Make sure to update both NPM and Cargo dependencies to the 1.4.0 release. You can update the dependencies with: ## What's in 1.4.0 diff --git a/src/content/docs/blog/tauri-1-5.mdx b/src/content/docs/blog/tauri-1-5.mdx index 93fdc0398..2d11664da 100644 --- a/src/content/docs/blog/tauri-1-5.mdx +++ b/src/content/docs/blog/tauri-1-5.mdx @@ -20,10 +20,10 @@ The Tauri team is excited to announce the 1.5 release. This version includes sev Make sure to update both NPM and Cargo dependencies to the 1.5.0 release. You can update the dependencies with: ## What's in 1.5.0 diff --git a/src/content/docs/blog/tauri-1-6.mdx b/src/content/docs/blog/tauri-1-6.mdx index 013d9d034..1a463c754 100644 --- a/src/content/docs/blog/tauri-1-6.mdx +++ b/src/content/docs/blog/tauri-1-6.mdx @@ -18,10 +18,10 @@ The Tauri team is happy to announce the 1.6 release. This version includes sever Make sure to update both NPM and Cargo dependencies to the 1.6.0 release. You can update the dependencies with: ## What's in 1.6.0 diff --git a/src/content/docs/blog/tauri-2-0-0-alpha-4.mdx b/src/content/docs/blog/tauri-2-0-0-alpha-4.mdx index 4eef79848..f2620bfd0 100644 --- a/src/content/docs/blog/tauri-2-0-0-alpha-4.mdx +++ b/src/content/docs/blog/tauri-2-0-0-alpha-4.mdx @@ -20,10 +20,10 @@ A new alpha release for the 2.0 has been published. This release includes all ch Make sure to update both NPM and Cargo dependencies to the latest alpha release. You can update the NPM dependencies with: @@ -120,7 +120,7 @@ pub fn init() -> TauriPlugin { ```js import { invoke } from '@tauri-apps/api/tauri'; invoke('plugin:example|ping', { value: 'Tauri' }).then(({ value }) => - console.log('Response', value) + console.log('Response', value) ); ``` diff --git a/src/content/docs/blog/tauri-mobile-alpha.mdx b/src/content/docs/blog/tauri-mobile-alpha.mdx index 4dc5fd9d0..e7d25b3a7 100644 --- a/src/content/docs/blog/tauri-mobile-alpha.mdx +++ b/src/content/docs/blog/tauri-mobile-alpha.mdx @@ -20,10 +20,10 @@ Tauri mobile is here! The first alpha release 2.0.0-alpha.0 has been published. Make sure to update both NPM and Cargo dependencies to the 2.0.0-alpha.0 release. You can update the dependencies with: diff --git a/src/content/docs/concept/Inter-Process Communication/index.mdx b/src/content/docs/concept/Inter-Process Communication/index.mdx index 9b8f32550..678fae84d 100644 --- a/src/content/docs/concept/Inter-Process Communication/index.mdx +++ b/src/content/docs/concept/Inter-Process Communication/index.mdx @@ -15,14 +15,14 @@ Inter-Process Communication (IPC) allows isolated processes to communicate secur Learn more above the specific IPC patterns in the following guides: - - + + Tauri uses a particular style of Inter-Process Communication called [Asynchronous Message Passing], where processes exchange _requests_ and _responses_ serialized using some simple data representation. Message Passing should sound familiar to anyone with web development experience, as this paradigm is used for client-server communication on the internet. diff --git a/src/content/docs/concept/_recipes/bridge.mdx b/src/content/docs/concept/_recipes/bridge.mdx index e41131886..15771ba46 100644 --- a/src/content/docs/concept/_recipes/bridge.mdx +++ b/src/content/docs/concept/_recipes/bridge.mdx @@ -7,49 +7,49 @@ import Rater from '@theme/Rater'; import useBaseUrl from '@docusaurus/useBaseUrl';
-
- - - - - - - - - - - - - - - - - -
Ease of Use - -
Extensibility - -
Performance - -
Security - -
-
-
- Bridge -
-
- Pros: -
    -
  • Highly configurable
  • -
  • No Rust skills required
  • -
- Cons: -
    -
  • Some WebAPIs unavailable
  • -
  • Challenge to implement
  • -
-
+
+ + + + + + + + + + + + + + + + + +
Ease of Use + +
Extensibility + +
Performance + +
Security + +
+
+
+ Bridge +
+
+ Pros: +
    +
  • Highly configurable
  • +
  • No Rust skills required
  • +
+ Cons: +
    +
  • Some WebAPIs unavailable
  • +
  • Challenge to implement
  • +
+
## Description @@ -93,97 +93,97 @@ Here's what you need to add to your tauri.conf.json file: ```json { - "tauri": { - "allowlist": { - "all": false, - "clipboard": { - "all": false, - "readText": false, - "writeText": false - }, - "dialog": { - "all": false, - "ask": false, - "confirm": false, - "message": false, - "open": false, - "save": false - }, - "fs": { - "all": false, - "copyFile": false, - "createDir": false, - "readDir": false, - "readFile": false, - "removeDir": false, - "removeFile": false, - "renameFile": false, - "scope": [], - "writeFile": false - }, - "globalShortcut": { - "all": false - }, - "http": { - "all": false, - "request": false, - "scope": [] - }, - "notification": { - "all": false - }, - "os": { - "all": false - }, - "path": { - "all": false - }, - "process": { - "all": false, - "exit": false, - "relaunch": false, - "relaunchDangerousAllowSymlinkMacos": false - }, - "protocol": { - "all": false, - "asset": false, - "assetScope": [] - }, - "shell": { - "all": false, - "execute": false, - "open": false, - "scope": [], - "sidecar": false - }, - "window": { - "all": false, - "center": false, - "close": false, - "create": false, - "hide": false, - "maximize": false, - "minimize": false, - "print": false, - "requestUserAttention": false, - "setAlwaysOnTop": false, - "setDecorations": false, - "setFocus": false, - "setFullscreen": false, - "setIcon": false, - "setMaxSize": false, - "setMinSize": false, - "setPosition": false, - "setResizable": false, - "setSize": false, - "setSkipTaskbar": false, - "setTitle": false, - "show": false, - "startDragging": false, - "unmaximize": false, - "unminimize": false - } - } - } + "tauri": { + "allowlist": { + "all": false, + "clipboard": { + "all": false, + "readText": false, + "writeText": false + }, + "dialog": { + "all": false, + "ask": false, + "confirm": false, + "message": false, + "open": false, + "save": false + }, + "fs": { + "all": false, + "copyFile": false, + "createDir": false, + "readDir": false, + "readFile": false, + "removeDir": false, + "removeFile": false, + "renameFile": false, + "scope": [], + "writeFile": false + }, + "globalShortcut": { + "all": false + }, + "http": { + "all": false, + "request": false, + "scope": [] + }, + "notification": { + "all": false + }, + "os": { + "all": false + }, + "path": { + "all": false + }, + "process": { + "all": false, + "exit": false, + "relaunch": false, + "relaunchDangerousAllowSymlinkMacos": false + }, + "protocol": { + "all": false, + "asset": false, + "assetScope": [] + }, + "shell": { + "all": false, + "execute": false, + "open": false, + "scope": [], + "sidecar": false + }, + "window": { + "all": false, + "center": false, + "close": false, + "create": false, + "hide": false, + "maximize": false, + "minimize": false, + "print": false, + "requestUserAttention": false, + "setAlwaysOnTop": false, + "setDecorations": false, + "setFocus": false, + "setFullscreen": false, + "setIcon": false, + "setMaxSize": false, + "setMinSize": false, + "setPosition": false, + "setResizable": false, + "setSize": false, + "setSkipTaskbar": false, + "setTitle": false, + "show": false, + "startDragging": false, + "unmaximize": false, + "unminimize": false + } + } + } } ``` diff --git a/src/content/docs/concept/_recipes/cloudbridge.mdx b/src/content/docs/concept/_recipes/cloudbridge.mdx index 6fa9435a9..f2fb5bd7e 100644 --- a/src/content/docs/concept/_recipes/cloudbridge.mdx +++ b/src/content/docs/concept/_recipes/cloudbridge.mdx @@ -7,49 +7,49 @@ import Rater from '@theme/Rater'; import useBaseUrl from '@docusaurus/useBaseUrl';
-
- - - - - - - - - - - - - - - - - -
Ease of Use - -
Extensibility - -
Performance - -
Security - -
-
-
- Cloudbridge -
-
- Pros: -
    -
  • All available features
  • -
  • No Rust skills required
  • -
- Cons: -
    -
  • Largest bundle size
  • -
  • Hard to separate concerns
  • -
-
+
+ + + + + + + + + + + + + + + + + +
Ease of Use + +
Extensibility + +
Performance + +
Security + +
+
+
+ Cloudbridge +
+
+ Pros: +
    +
  • All available features
  • +
  • No Rust skills required
  • +
+ Cons: +
    +
  • Largest bundle size
  • +
  • Hard to separate concerns
  • +
+
## Description diff --git a/src/content/docs/concept/_recipes/cloudish.mdx b/src/content/docs/concept/_recipes/cloudish.mdx index b2e170c78..16355b300 100644 --- a/src/content/docs/concept/_recipes/cloudish.mdx +++ b/src/content/docs/concept/_recipes/cloudish.mdx @@ -7,49 +7,49 @@ import Rater from '@theme/Rater'; import useBaseUrl from '@docusaurus/useBaseUrl';
-
- - - - - - - - - - - - - - - - - -
Ease of Use - -
Extensibility - -
Performance - -
Security - -
-
-
- Cloudish -
-
- Pros: -
    -
  • Similar to a SPA web-app
  • -
  • No Rust skills required
  • -
- Cons: -
    -
  • No access to Rust API
  • -
  • Uses a localhost server
  • -
-
+
+ + + + + + + + + + + + + + + + + +
Ease of Use + +
Extensibility + +
Performance + +
Security + +
+
+
+ Cloudish +
+
+ Pros: +
    +
  • Similar to a SPA web-app
  • +
  • No Rust skills required
  • +
+ Cons: +
    +
  • No access to Rust API
  • +
  • Uses a localhost server
  • +
+
## Description diff --git a/src/content/docs/concept/_recipes/glui.mdx b/src/content/docs/concept/_recipes/glui.mdx index c656d08e6..f07cff9b7 100644 --- a/src/content/docs/concept/_recipes/glui.mdx +++ b/src/content/docs/concept/_recipes/glui.mdx @@ -12,48 +12,48 @@ This pattern is not available for now. import Rater from '@theme/Rater';
-
- - - - - - - - - - - - - - - - - -
Ease of Use - -
Extensibility - -
Performance - -
Security - -
-
-
- GLUI -
-
- Pros: -
    -
  • Framebuffer FTW
  • -
  • Window events rigged
  • -
- Cons: -
    -
  • Broken on your machine
  • -
-
+
+ + + + + + + + + + + + + + + + + +
Ease of Use + +
Extensibility + +
Performance + +
Security + +
+
+
+ GLUI +
+
+ Pros: +
    +
  • Framebuffer FTW
  • +
  • Window events rigged
  • +
+ Cons: +
    +
  • Broken on your machine
  • +
+
## Description diff --git a/src/content/docs/concept/_recipes/hermit.mdx b/src/content/docs/concept/_recipes/hermit.mdx index fb1eb6afb..43a23da0a 100644 --- a/src/content/docs/concept/_recipes/hermit.mdx +++ b/src/content/docs/concept/_recipes/hermit.mdx @@ -7,49 +7,49 @@ import Rater from '@theme/Rater'; import useBaseUrl from '@docusaurus/useBaseUrl';
-
- - - - - - - - - - - - - - - - - -
Ease of Use - -
Extensibility - -
Performance - -
Security - -
-
-
- Hermit -
-
- Pros: -
    -
  • Quick to make
  • -
  • Smallest size
  • -
- Cons: -
    -
  • No remote resources
  • -
  • No access to API
  • -
-
+
+ + + + + + + + + + + + + + + + + +
Ease of Use + +
Extensibility + +
Performance + +
Security + +
+
+
+ Hermit +
+
+ Pros: +
    +
  • Quick to make
  • +
  • Smallest size
  • +
+ Cons: +
    +
  • No remote resources
  • +
  • No access to API
  • +
+
## Description diff --git a/src/content/docs/concept/_recipes/lockdown.mdx b/src/content/docs/concept/_recipes/lockdown.mdx index 8ab6f3f4b..4fe2abae6 100644 --- a/src/content/docs/concept/_recipes/lockdown.mdx +++ b/src/content/docs/concept/_recipes/lockdown.mdx @@ -7,49 +7,49 @@ import Rater from '@theme/Rater'; import useBaseUrl from '@docusaurus/useBaseUrl';
-
- - - - - - - - - - - - - - - - - -
Ease of Use - -
Extensibility - -
Performance - -
Security - -
-
-
- Lockdown -
-
- Pros: -
    -
  • Highest security rating
  • -
  • Elegant and powerful
  • -
- Cons: -
    -
  • Rust skills required
  • -
  • No remote resources
  • -
-
+
+ + + + + + + + + + + + + + + + + +
Ease of Use + +
Extensibility + +
Performance + +
Security + +
+
+
+ Lockdown +
+
+ Pros: +
    +
  • Highest security rating
  • +
  • Elegant and powerful
  • +
+ Cons: +
    +
  • Rust skills required
  • +
  • No remote resources
  • +
+
## Description diff --git a/src/content/docs/concept/_recipes/multiwin.mdx b/src/content/docs/concept/_recipes/multiwin.mdx index 98744af46..36bbc9985 100644 --- a/src/content/docs/concept/_recipes/multiwin.mdx +++ b/src/content/docs/concept/_recipes/multiwin.mdx @@ -7,48 +7,48 @@ import useBaseUrl from '@docusaurus/useBaseUrl'; import Rater from '@theme/Rater';
-
- - - - - - - - - - - - - - - - - -
Ease of Use - -
Extensibility - -
Performance - -
Security - -
-
-
- Multiwin -
-
- Pros: -
    -
  • Windows can be spawned or destroyed at runtime
  • -
  • Separation of concerns
  • -
- Cons: -
    -
  • Somewhat complex
  • -
-
+
+ + + + + + + + + + + + + + + + + +
Ease of Use + +
Extensibility + +
Performance + +
Security + +
+
+
+ Multiwin +
+
+ Pros: +
    +
  • Windows can be spawned or destroyed at runtime
  • +
  • Separation of concerns
  • +
+ Cons: +
    +
  • Somewhat complex
  • +
+
## Description diff --git a/src/content/docs/concept/index.mdx b/src/content/docs/concept/index.mdx index 2464e1f23..2db6792fe 100644 --- a/src/content/docs/concept/index.mdx +++ b/src/content/docs/concept/index.mdx @@ -13,34 +13,34 @@ import { CardGrid, LinkCard } from '@astrojs/starlight/components'; Tauri has a variety of topics that are considered to be core concepts, things any developer should be aware of when developing their applications. Here's a variety of topics that you should get more intimately familiar with if you want to get the most out of the framework. - - - - - - + + + + + + diff --git a/src/content/docs/develop/Debug/index.mdx b/src/content/docs/develop/Debug/index.mdx index 79a5635b0..d8a611988 100644 --- a/src/content/docs/develop/Debug/index.mdx +++ b/src/content/docs/develop/Debug/index.mdx @@ -106,10 +106,10 @@ By default, the inspector is only enabled in development and debug builds unless To create a debug build, run the `tauri build --debug` command. Like the normal build and dev processes, building takes some time the first time you run this command but is significantly faster on subsequent runs. diff --git a/src/content/docs/develop/Debug/vscode.mdx b/src/content/docs/develop/Debug/vscode.mdx index b4c244051..0e4ceb65f 100644 --- a/src/content/docs/develop/Debug/vscode.mdx +++ b/src/content/docs/develop/Debug/vscode.mdx @@ -23,36 +23,36 @@ Create a `.vscode/launch.json` file and paste the below JSON contents into it: ```json title=".vscode/launch.json" { - // Use IntelliSense to learn about possible attributes. - // Hover to view descriptions of existing attributes. - // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 - "version": "0.2.0", - "configurations": [ - { - "type": "lldb", - "request": "launch", - "name": "Tauri Development Debug", - "cargo": { - "args": [ - "build", - "--manifest-path=./src-tauri/Cargo.toml", - "--no-default-features" - ] - }, - // task for the `beforeDevCommand` if used, must be configured in `.vscode/tasks.json` - "preLaunchTask": "ui:dev" - }, - { - "type": "lldb", - "request": "launch", - "name": "Tauri Production Debug", - "cargo": { - "args": ["build", "--release", "--manifest-path=./src-tauri/Cargo.toml"] - }, - // task for the `beforeBuildCommand` if used, must be configured in `.vscode/tasks.json` - "preLaunchTask": "ui:build" - } - ] + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "type": "lldb", + "request": "launch", + "name": "Tauri Development Debug", + "cargo": { + "args": [ + "build", + "--manifest-path=./src-tauri/Cargo.toml", + "--no-default-features" + ] + }, + // task for the `beforeDevCommand` if used, must be configured in `.vscode/tasks.json` + "preLaunchTask": "ui:dev" + }, + { + "type": "lldb", + "request": "launch", + "name": "Tauri Production Debug", + "cargo": { + "args": ["build", "--release", "--manifest-path=./src-tauri/Cargo.toml"] + }, + // task for the `beforeBuildCommand` if used, must be configured in `.vscode/tasks.json` + "preLaunchTask": "ui:build" + } + ] } ``` @@ -62,29 +62,29 @@ Note that it does not use the Tauri CLI, so exclusive CLI features are not execu ```json title=".vscode/tasks.json" { - // See https://go.microsoft.com/fwlink/?LinkId=733558 - // for the documentation about the tasks.json format - "version": "2.0.0", - "tasks": [ - { - "label": "ui:dev", - "type": "shell", - // `dev` keeps running in the background - // ideally you should also configure a `problemMatcher` - // see https://code.visualstudio.com/docs/editor/tasks#_can-a-background-task-be-used-as-a-prelaunchtask-in-launchjson - "isBackground": true, - // change this to your `beforeDevCommand`: - "command": "yarn", - "args": ["dev"] - }, - { - "label": "ui:build", - "type": "shell", - // change this to your `beforeBuildCommand`: - "command": "yarn", - "args": ["build"] - } - ] + // See https://go.microsoft.com/fwlink/?LinkId=733558 + // for the documentation about the tasks.json format + "version": "2.0.0", + "tasks": [ + { + "label": "ui:dev", + "type": "shell", + // `dev` keeps running in the background + // ideally you should also configure a `problemMatcher` + // see https://code.visualstudio.com/docs/editor/tasks#_can-a-background-task-be-used-as-a-prelaunchtask-in-launchjson + "isBackground": true, + // change this to your `beforeDevCommand`: + "command": "yarn", + "args": ["dev"] + }, + { + "label": "ui:build", + "type": "shell", + // change this to your `beforeBuildCommand`: + "command": "yarn", + "args": ["build"] + } + ] } ``` diff --git a/src/content/docs/develop/Plugins/index.mdx b/src/content/docs/develop/Plugins/index.mdx index 2f58d5743..b17245098 100644 --- a/src/content/docs/develop/Plugins/index.mdx +++ b/src/content/docs/develop/Plugins/index.mdx @@ -41,10 +41,10 @@ To bootstrap a new plugin project, run `plugin new`. If you do not need the NPM After installing, you can run the following to create a plugin project: This will initialize the plugin at the directory `tauri-plugin-[name]` and, depending on the used CLI flags, the resulting project will look like this: diff --git a/src/content/docs/develop/Tests/WebDriver/Example/index.mdx b/src/content/docs/develop/Tests/WebDriver/Example/index.mdx index 8813da101..b4fb63e0a 100644 --- a/src/content/docs/develop/Tests/WebDriver/Example/index.mdx +++ b/src/content/docs/develop/Tests/WebDriver/Example/index.mdx @@ -41,30 +41,30 @@ First, let's create our Tauri `distDir` that we know we will need once building ```html - - - Hello Tauri! - - - -

Hello, Tauri!

- + /* Vertically and horizontally center children of the body tag */ + display: flex; + justify-content: center; + align-items: center; + } + + + +

Hello, Tauri!

+ ``` @@ -150,26 +150,26 @@ here. ```json { - "build": { - "distDir": "dist" - }, - "tauri": { - "bundle": { - "identifier": "studio.tauri.hello_tauri_webdriver", - "icon": ["icon.png"] - }, - "allowlist": { - "all": false - }, - "windows": [ - { - "width": 800, - "height": 600, - "resizable": true, - "fullscreen": false - } - ] - } + "build": { + "distDir": "dist" + }, + "tauri": { + "bundle": { + "identifier": "studio.tauri.hello_tauri_webdriver", + "icon": ["icon.png"] + }, + "allowlist": { + "all": false + }, + "windows": [ + { + "width": 800, + "height": 600, + "resizable": true, + "fullscreen": false + } + ] + } } ``` @@ -187,7 +187,7 @@ will also run our WebDriver tests with a release profile. Run `cargo run --relea see the following application pop up.
- Hello Tauri Webdriver + Hello Tauri Webdriver
_Note: If you are modifying the application and want to use the Devtools, then run it without `--release` and "Inspect diff --git a/src/content/docs/develop/Tests/WebDriver/Example/selenium.mdx b/src/content/docs/develop/Tests/WebDriver/Example/selenium.mdx index c338c30b8..31b4b6deb 100644 --- a/src/content/docs/develop/Tests/WebDriver/Example/selenium.mdx +++ b/src/content/docs/develop/Tests/WebDriver/Example/selenium.mdx @@ -38,17 +38,17 @@ guide on how to set it up from scratch. ```json { - "name": "selenium", - "version": "1.0.0", - "private": true, - "scripts": { - "test": "mocha" - }, - "dependencies": { - "chai": "^4.3.4", - "mocha": "^9.0.3", - "selenium-webdriver": "^4.0.0-beta.4" - } + "name": "selenium", + "version": "1.0.0", + "private": true, + "scripts": { + "test": "mocha" + }, + "dependencies": { + "chai": "^4.3.4", + "mocha": "^9.0.3", + "selenium-webdriver": "^4.0.0-beta.4" + } } ``` @@ -62,8 +62,8 @@ that we will be using to run the tests. [Mocha] as the testing framework, [Chai] If you want to install the dependencies from scratch, just run the following command. I suggest also adding a `"test": "mocha"` item in the `package.json` `"scripts"` key so that running Mocha can be called @@ -90,13 +90,13 @@ const { Builder, By, Capabilities } = require('selenium-webdriver'); // create the path to the expected application binary const application = path.resolve( - __dirname, - '..', - '..', - '..', - 'target', - 'release', - 'hello-tauri-webdriver' + __dirname, + '..', + '..', + '..', + 'target', + 'release', + 'hello-tauri-webdriver' ); // keep track of the webdriver instance we create @@ -106,61 +106,61 @@ let driver; let tauriDriver; before(async function () { - // set timeout to 2 minutes to allow the program to build if it needs to - this.timeout(120000); + // set timeout to 2 minutes to allow the program to build if it needs to + this.timeout(120000); - // ensure the program has been built - spawnSync('cargo', ['build', '--release']); + // ensure the program has been built + spawnSync('cargo', ['build', '--release']); - // start tauri-driver - tauriDriver = spawn( - path.resolve(os.homedir(), '.cargo', 'bin', 'tauri-driver'), - [], - { stdio: [null, process.stdout, process.stderr] } - ); + // start tauri-driver + tauriDriver = spawn( + path.resolve(os.homedir(), '.cargo', 'bin', 'tauri-driver'), + [], + { stdio: [null, process.stdout, process.stderr] } + ); - const capabilities = new Capabilities(); - capabilities.set('tauri:options', { application }); - capabilities.setBrowserName('wry'); + const capabilities = new Capabilities(); + capabilities.set('tauri:options', { application }); + capabilities.setBrowserName('wry'); - // start the webdriver client - driver = await new Builder() - .withCapabilities(capabilities) - .usingServer('http://127.0.0.1:4444/') - .build(); + // start the webdriver client + driver = await new Builder() + .withCapabilities(capabilities) + .usingServer('http://127.0.0.1:4444/') + .build(); }); after(async function () { - // stop the webdriver session - await driver.quit(); + // stop the webdriver session + await driver.quit(); - // kill the tauri-driver process - tauriDriver.kill(); + // kill the tauri-driver process + tauriDriver.kill(); }); describe('Hello Tauri', () => { - it('should be cordial', async () => { - const text = await driver.findElement(By.css('body > h1')).getText(); - expect(text).to.match(/^[hH]ello/); - }); + it('should be cordial', async () => { + const text = await driver.findElement(By.css('body > h1')).getText(); + expect(text).to.match(/^[hH]ello/); + }); - it('should be excited', async () => { - const text = await driver.findElement(By.css('body > h1')).getText(); - expect(text).to.match(/!$/); - }); + it('should be excited', async () => { + const text = await driver.findElement(By.css('body > h1')).getText(); + expect(text).to.match(/!$/); + }); - it('should be easy on the eyes', async () => { - // selenium returns color css values as rgb(r, g, b) - const text = await driver - .findElement(By.css('body')) - .getCssValue('background-color'); + it('should be easy on the eyes', async () => { + // selenium returns color css values as rgb(r, g, b) + const text = await driver + .findElement(By.css('body')) + .getCssValue('background-color'); - const rgb = text.match(/^rgb\((?\d+), (?\d+), (?\d+)\)$/).groups; - expect(rgb).to.have.all.keys('r', 'g', 'b'); + const rgb = text.match(/^rgb\((?\d+), (?\d+), (?\d+)\)$/).groups; + expect(rgb).to.have.all.keys('r', 'g', 'b'); - const luma = 0.2126 * rgb.r + 0.7152 * rgb.g + 0.0722 * rgb.b; - expect(luma).to.be.lessThan(100); - }); + const luma = 0.2126 * rgb.r + 0.7152 * rgb.g + 0.0722 * rgb.b; + expect(luma).to.be.lessThan(100); + }); }); ``` diff --git a/src/content/docs/develop/Tests/WebDriver/Example/webdriverio.mdx b/src/content/docs/develop/Tests/WebDriver/Example/webdriverio.mdx index 08b7fe767..2da9eee92 100644 --- a/src/content/docs/develop/Tests/WebDriver/Example/webdriverio.mdx +++ b/src/content/docs/develop/Tests/WebDriver/Example/webdriverio.mdx @@ -38,20 +38,20 @@ guide on setting it up from scratch. ```json { - "name": "webdriverio", - "version": "1.0.0", - "private": true, - "scripts": { - "test": "wdio run wdio.conf.js" - }, - "dependencies": { - "@wdio/cli": "^7.9.1" - }, - "devDependencies": { - "@wdio/local-runner": "^7.9.1", - "@wdio/mocha-framework": "^7.9.1", - "@wdio/spec-reporter": "^7.9.0" - } + "name": "webdriverio", + "version": "1.0.0", + "private": true, + "scripts": { + "test": "wdio run wdio.conf.js" + }, + "dependencies": { + "@wdio/cli": "^7.9.1" + }, + "devDependencies": { + "@wdio/local-runner": "^7.9.1", + "@wdio/mocha-framework": "^7.9.1", + "@wdio/spec-reporter": "^7.9.0" + } } ``` @@ -91,36 +91,36 @@ const { spawn, spawnSync } = require('child_process'); let tauriDriver; exports.config = { - specs: ['./develop/tests/specs/**/*.js'], - maxInstances: 1, - capabilities: [ - { - maxInstances: 1, - 'tauri:options': { - application: '../../target/release/hello-tauri-webdriver', - }, - }, - ], - reporters: ['spec'], - framework: 'mocha', - mochaOpts: { - ui: 'bdd', - timeout: 60000, - }, + specs: ['./develop/tests/specs/**/*.js'], + maxInstances: 1, + capabilities: [ + { + maxInstances: 1, + 'tauri:options': { + application: '../../target/release/hello-tauri-webdriver', + }, + }, + ], + reporters: ['spec'], + framework: 'mocha', + mochaOpts: { + ui: 'bdd', + timeout: 60000, + }, - // ensure the rust project is built since we expect this binary to exist for the webdriver sessions - onPrepare: () => spawnSync('cargo', ['build', '--release']), + // ensure the rust project is built since we expect this binary to exist for the webdriver sessions + onPrepare: () => spawnSync('cargo', ['build', '--release']), - // ensure we are running `tauri-driver` before the session starts so that we can proxy the webdriver requests - beforeSession: () => - (tauriDriver = spawn( - path.resolve(os.homedir(), '.cargo', 'bin', 'tauri-driver'), - [], - { stdio: [null, process.stdout, process.stderr] } - )), + // ensure we are running `tauri-driver` before the session starts so that we can proxy the webdriver requests + beforeSession: () => + (tauriDriver = spawn( + path.resolve(os.homedir(), '.cargo', 'bin', 'tauri-driver'), + [], + { stdio: [null, process.stdout, process.stderr] } + )), - // clean up the `tauri-driver` process we spawned at the start of the session - afterSession: () => tauriDriver.kill(), + // clean up the `tauri-driver` process we spawned at the start of the session + afterSession: () => tauriDriver.kill(), }; ``` @@ -138,35 +138,35 @@ run them as it sees fit. Let's create our spec now in the directory we specified ```js // calculates the luma from a hex color `#abcdef` function luma(hex) { - if (hex.startsWith('#')) { - hex = hex.substring(1); - } + if (hex.startsWith('#')) { + hex = hex.substring(1); + } - const rgb = parseInt(hex, 16); - const r = (rgb >> 16) & 0xff; - const g = (rgb >> 8) & 0xff; - const b = (rgb >> 0) & 0xff; - return 0.2126 * r + 0.7152 * g + 0.0722 * b; + const rgb = parseInt(hex, 16); + const r = (rgb >> 16) & 0xff; + const g = (rgb >> 8) & 0xff; + const b = (rgb >> 0) & 0xff; + return 0.2126 * r + 0.7152 * g + 0.0722 * b; } describe('Hello Tauri', () => { - it('should be cordial', async () => { - const header = await $('body > h1'); - const text = await header.getText(); - expect(text).toMatch(/^[hH]ello/); - }); + it('should be cordial', async () => { + const header = await $('body > h1'); + const text = await header.getText(); + expect(text).toMatch(/^[hH]ello/); + }); - it('should be excited', async () => { - const header = await $('body > h1'); - const text = await header.getText(); - expect(text).toMatch(/!$/); - }); + it('should be excited', async () => { + const header = await $('body > h1'); + const text = await header.getText(); + expect(text).toMatch(/!$/); + }); - it('should be easy on the eyes', async () => { - const body = await $('body'); - const backgroundColor = await body.getCSSProperty('background-color'); - expect(luma(backgroundColor.parsed.hex)).toBeLessThan(100); - }); + it('should be easy on the eyes', async () => { + const body = await $('body'); + const backgroundColor = await body.getCSSProperty('background-color'); + expect(luma(backgroundColor.parsed.hex)).toBeLessThan(100); + }); }); ``` diff --git a/src/content/docs/develop/Tests/WebDriver/index.mdx b/src/content/docs/develop/Tests/WebDriver/index.mdx index 3a6159151..192e9a348 100644 --- a/src/content/docs/develop/Tests/WebDriver/index.mdx +++ b/src/content/docs/develop/Tests/WebDriver/index.mdx @@ -60,15 +60,15 @@ can look at https://github.com/chippers/hello_tauri. import { LinkCard, CardGrid } from '@astrojs/starlight/components'; - - - + + + ## Continuous Integration (CI) @@ -76,8 +76,8 @@ import { LinkCard, CardGrid } from '@astrojs/starlight/components'; The above examples also comes with a CI script to test with GitHub actions, but you may still be interested in the below WebDriver CI guide as it explains the concept a bit more. [webdriver]: https://www.w3.org/TR/webdriver/ diff --git a/src/content/docs/develop/calling-rust.mdx b/src/content/docs/develop/calling-rust.mdx index f6ac1b0cd..9ee7d0743 100644 --- a/src/content/docs/develop/calling-rust.mdx +++ b/src/content/docs/develop/calling-rust.mdx @@ -119,8 +119,8 @@ If the command returns an error, the promise will reject, otherwise, it resolves ```js invoke('my_custom_command') - .then((message) => console.log(message)) - .catch((error) => console.error(error)); + .then((message) => console.log(message)) + .catch((error) => console.error(error)); ``` As mentioned above, everything returned from commands must implement [`serde::Serialize`], including errors. @@ -231,7 +231,7 @@ Since invoking the command from JavaScript already returns a promise, it works j ```js invoke('my_custom_command', { value: 'Hello, Async!' }).then(() => - console.log('Completed!') + console.log('Completed!') ); ``` @@ -379,12 +379,12 @@ import { invoke } from '@tauri-apps/api/core'; // Invocation from JavaScript invoke('my_custom_command', { - number: 42, + number: 42, }) - .then((res) => - console.log(`Message: ${res.message}, Other Val: ${res.other_val}`) - ) - .catch((e) => console.error(e)); + .then((res) => + console.log(`Message: ${res.message}, Other Val: ${res.other_val}`) + ) + .catch((e) => console.error(e)); ``` [`async_runtime::spawn`]: https://docs.rs/tauri/2.0.0-beta/tauri/async_runtime/fn.spawn.html diff --git a/src/content/docs/develop/development-cycle.mdx b/src/content/docs/develop/development-cycle.mdx index 07e02de35..19687205a 100644 --- a/src/content/docs/develop/development-cycle.mdx +++ b/src/content/docs/develop/development-cycle.mdx @@ -24,10 +24,10 @@ Every framework has its own development tooling. It is outside of the scope of t ### 2. Start Tauri Development Window The first time you run this command, the Rust package manager takes several minutes to download and build all the required packages. Since they are cached, subsequent builds are much faster, as only your code needs rebuilding. diff --git a/src/content/docs/develop/sidecar.mdx b/src/content/docs/develop/sidecar.mdx index 92555a8b9..aef19ba65 100644 --- a/src/content/docs/develop/sidecar.mdx +++ b/src/content/docs/develop/sidecar.mdx @@ -17,15 +17,15 @@ Here is a sample to illustrate the configuration. This is not a complete `tauri. ```json title="src-tauri/tauri.conf.json" { - "tauri": { - "bundle": { - "externalBin": [ - "/absolute/path/to/sidecar", - "relative/path/to/binary", - "binaries/my-sidecar" - ] - } - } + "tauri": { + "bundle": { + "externalBin": [ + "/absolute/path/to/sidecar", + "relative/path/to/binary", + "binaries/my-sidecar" + ] + } + } } ``` @@ -59,23 +59,23 @@ const fs = require('fs'); let extension = ''; if (process.platform === 'win32') { - extension = '.exe'; + extension = '.exe'; } async function main() { - const rustInfo = (await execa('rustc', ['-vV'])).stdout; - const targetTriple = /host: (\S+)/g.exec(rustInfo)[1]; - if (!targetTriple) { - console.error('Failed to determine platform target triple'); - } - fs.renameSync( - `src-tauri/binaries/sidecar${extension}`, - `src-tauri/binaries/sidecar-${targetTriple}${extension}` - ); + const rustInfo = (await execa('rustc', ['-vV'])).stdout; + const targetTriple = /host: (\S+)/g.exec(rustInfo)[1]; + if (!targetTriple) { + console.error('Failed to determine platform target triple'); + } + fs.renameSync( + `src-tauri/binaries/sidecar${extension}`, + `src-tauri/binaries/sidecar-${targetTriple}${extension}` + ); } main().catch((e) => { - throw e; + throw e; }); ``` @@ -130,38 +130,38 @@ First, define the arguments that need to be passed to the sidecar command in `sr ```json title="src-tauri/capabilities/main.json" ins={14-31} { - "$schema": "../gen/schemas/desktop-schema.json", - "identifier": "default", - "description": "Capability for the main window", - "windows": ["main"], - "permissions": [ - "path:default", - "event:default", - "window:default", - "app:default", - "resources:default", - "menu:default", - "tray:default", - { - "identifier": "shell:allow-execute", - "allow": [ - { - "args": [ - "arg1", - "-a", - "--arg2", - { - "validator": "\\S+" - } - ], - "cmd": "", - "name": "binaries/my-sidecar", - "sidecar": true - } - ] - }, - "shell:allow-open" - ] + "$schema": "../gen/schemas/desktop-schema.json", + "identifier": "default", + "description": "Capability for the main window", + "windows": ["main"], + "permissions": [ + "path:default", + "event:default", + "window:default", + "app:default", + "resources:default", + "menu:default", + "tray:default", + { + "identifier": "shell:allow-execute", + "allow": [ + { + "args": [ + "arg1", + "-a", + "--arg2", + { + "validator": "\\S+" + } + ], + "cmd": "", + "name": "binaries/my-sidecar", + "sidecar": true + } + ] + }, + "shell:allow-open" + ] } ``` @@ -192,10 +192,10 @@ import { Command } from '@tauri-apps/plugin-shell'; // `binaries/my-sidecar` is the EXACT value specified on `tauri.conf.json > tauri > bundle > externalBin` // notice that the args array matches EXACTLY what is specified on `tauri.conf.json`. const command = Command.sidecar('binaries/my-sidecar', [ - 'arg1', - '-a', - '--arg2', - 'any-string-that-matches-the-validator', + 'arg1', + '-a', + '--arg2', + 'any-string-that-matches-the-validator', ]); const output = await command.execute(); ``` diff --git a/src/content/docs/develop/updating-dependencies.mdx b/src/content/docs/develop/updating-dependencies.mdx index 0f4487652..f7e3da43e 100644 --- a/src/content/docs/develop/updating-dependencies.mdx +++ b/src/content/docs/develop/updating-dependencies.mdx @@ -16,25 +16,25 @@ import CommandTabs from '@components/CommandTabs.astro'; If you are using the `tauri` package: You can also detect what the latest version of Tauri is on the command line, using: Alternatively, if you are using the `vue-cli-plugin-tauri` approach: ## Update Cargo Packages diff --git a/src/content/docs/es/index.mdx b/src/content/docs/es/index.mdx index c44af1a39..dcacc1b99 100644 --- a/src/content/docs/es/index.mdx +++ b/src/content/docs/es/index.mdx @@ -27,35 +27,35 @@ hero: import { Card, CardGrid } from '@astrojs/starlight/components';
- -
-
+ +
+
- - Trae tu stack web existente a Tauri o comienza ese nuevo proyecto de en - sueño. Tauri soporta cualquier framework frontend, por lo que no necesitas - cambiar tu stack. - - - Construye tu aplicación para Linux, macOS, Windows, Android e iOS - todo - desde una sola base de código. - - - Escribe tu frontend en JavaScript, la lógica de la aplicación en Rust, e - integra profundamente en el sistema con Swift y Kotlin. - - - Frente a la mente del equipo de Tauri que impulsa nuestras mayores - prioridades y mayores innovaciones. - - - Al usar el renderizador web nativo del sistema operativo, el tamaño de una - aplicación Tauri puede ser tan pequeño como 600KB. - - - Con el rendimiento y la seguridad en el centro, Rust es el lenguaje para la - próxima generación de aplicaciones. - + + Trae tu stack web existente a Tauri o comienza ese nuevo proyecto de en + sueño. Tauri soporta cualquier framework frontend, por lo que no necesitas + cambiar tu stack. + + + Construye tu aplicación para Linux, macOS, Windows, Android e iOS - todo + desde una sola base de código. + + + Escribe tu frontend en JavaScript, la lógica de la aplicación en Rust, e + integra profundamente en el sistema con Swift y Kotlin. + + + Frente a la mente del equipo de Tauri que impulsa nuestras mayores + prioridades y mayores innovaciones. + + + Al usar el renderizador web nativo del sistema operativo, el tamaño de una + aplicación Tauri puede ser tan pequeño como 600KB. + + + Con el rendimiento y la seguridad en el centro, Rust es el lenguaje para la + próxima generación de aplicaciones. + diff --git a/src/content/docs/es/plugin/dialog.mdx b/src/content/docs/es/plugin/dialog.mdx index 384bf8b83..dfe6b8eef 100644 --- a/src/content/docs/es/plugin/dialog.mdx +++ b/src/content/docs/es/plugin/dialog.mdx @@ -93,8 +93,8 @@ import { ask } from '@tauri-apps/plugin-dialog'; // Crea un diálogo de Sí/No const answer = await ask('This action cannot be reverted. Are you sure?', { - title: 'Tauri', - type: 'warning', + title: 'Tauri', + type: 'warning', }); console.log(answer); @@ -112,8 +112,8 @@ import { confirm } from '@tauri-apps/plugin-dialog'; // Crea un diálogo de confirmación Ok/Cancelar const confirmation = await confirm( - 'This action cannot be reverted. Are you sure?', - { title: 'Tauri', type: 'warning' } + 'This action cannot be reverted. Are you sure?', + { title: 'Tauri', type: 'warning' } ); console.log(confirmation); @@ -146,8 +146,8 @@ import { open } from '@tauri-apps/plugin-dialog'; // Abre un diálogo const file = await open({ - multiple: false, - directory: false, + multiple: false, + directory: false, }); console.log(file); // Imprime la ruta y el nombre del archivo en la consola @@ -163,12 +163,12 @@ Abre un diálogo de guardar archivo/directorio. import { save } from '@tauri-apps/plugin-dialog'; // Indica para guardar un 'My Filter' con extensión .png o .jpeg const path = await save({ - filters: [ - { - name: 'My Filter', - extensions: ['png', 'jpeg'], - }, - ], + filters: [ + { + name: 'My Filter', + extensions: ['png', 'jpeg'], + }, + ], }); console.log(path); // Imprime la ruta escogida diff --git a/src/content/docs/es/plugin/index.mdx b/src/content/docs/es/plugin/index.mdx index b25497ab9..baf239d05 100644 --- a/src/content/docs/es/plugin/index.mdx +++ b/src/content/docs/es/plugin/index.mdx @@ -13,10 +13,10 @@ Tauri viene con el objetivo de ser extensible. En esta página encontrarás: - **[Recursos de la Comunidad](#recursos-de-la-comunidad)**: Más plugins y fórmulas creadas por la comunidad de Tauri - ## Características - - ## Recursos de la comunidad - + ## Características + + ## Recursos de la comunidad + :::tip[¿Tienes algo genial que compartir?] diff --git a/src/content/docs/es/start/frontend/index.mdx b/src/content/docs/es/start/frontend/index.mdx index 55e4cce91..facb09a04 100644 --- a/src/content/docs/es/start/frontend/index.mdx +++ b/src/content/docs/es/start/frontend/index.mdx @@ -18,21 +18,21 @@ Si un framework no aparece en esta lista puede que funcione con Tauri sin necesi ## JavaScript - - - - - - + + + + + + ## Rust - - - - + + + + ## Checklist de Configuración diff --git a/src/content/docs/es/start/frontend/nextjs.mdx b/src/content/docs/es/start/frontend/nextjs.mdx index c8bedc3b1..8bbf882fc 100644 --- a/src/content/docs/es/start/frontend/nextjs.mdx +++ b/src/content/docs/es/start/frontend/nextjs.mdx @@ -19,9 +19,9 @@ Next.js es un framework para React. Aprende más sobre Next.js en https://nextjs 1. Instala `internal-ip` para el desarrollo móvil: 2. Actualiza la configuración de Tauri: @@ -32,12 +32,12 @@ Next.js es un framework para React. Aprende más sobre Next.js en https://nextjs ```json // tauri.conf.json { - "build": { - "beforeDevCommand": "npm run dev", - "beforeBuildCommand": "npm run build", - "devPath": "http://localhost:3000", - "distDir": "../dist" - } + "build": { + "beforeDevCommand": "npm run dev", + "beforeBuildCommand": "npm run build", + "devPath": "http://localhost:3000", + "distDir": "../dist" + } } ``` @@ -47,12 +47,12 @@ Next.js es un framework para React. Aprende más sobre Next.js en https://nextjs ```json // tauri.conf.json { - "build": { - "beforeDevCommand": "yarn dev", - "beforeBuildCommand": "yarn generate", - "devPath": "http://localhost:3000", - "distDir": "../dist" - } + "build": { + "beforeDevCommand": "yarn dev", + "beforeBuildCommand": "yarn generate", + "devPath": "http://localhost:3000", + "distDir": "../dist" + } } ``` @@ -62,12 +62,12 @@ Next.js es un framework para React. Aprende más sobre Next.js en https://nextjs ```json // tauri.conf.json { - "build": { - "beforeDevCommand": "pnpm dev", - "beforeBuildCommand": "pnpm generate", - "devPath": "http://localhost:3000", - "distDir": "../dist" - } + "build": { + "beforeDevCommand": "pnpm dev", + "beforeBuildCommand": "pnpm generate", + "devPath": "http://localhost:3000", + "distDir": "../dist" + } } ``` @@ -80,24 +80,24 @@ Next.js es un framework para React. Aprende más sobre Next.js en https://nextjs // next.conf.ts const isProd = process.env.NODE_ENV === 'production'; module.exports = async (phase, { defaultConfig }) => { - let internalHost = null; - // En modo de desarrollo usamos internal-ip para servir los archivos - if (!isProd) { - const { internalIpV4 } = await import('internal-ip'); - internalHost = await internalIpV4(); - } - const nextConfig = { - // Aségurate de que Next.js use SSG en lugar de SSR - // https://nextjs.org/docs/pages/building-your-application/deploying/static-exports - output: 'export', - // Nota: Esta función experimental es necesaria para usar NextJS Image en modo SSG. - // Consulta https://nextjs.org/docs/messages/export-image-api para ver diferentes soluciones. - images: { - unoptimized: true, - }, - // Configura assetPrefix o el servidor no resolverá correctamente tus archivos. - assetPrefix: isProd ? null : `http://${internalHost}:3000`, - }; - return nextConfig; + let internalHost = null; + // En modo de desarrollo usamos internal-ip para servir los archivos + if (!isProd) { + const { internalIpV4 } = await import('internal-ip'); + internalHost = await internalIpV4(); + } + const nextConfig = { + // Aségurate de que Next.js use SSG en lugar de SSR + // https://nextjs.org/docs/pages/building-your-application/deploying/static-exports + output: 'export', + // Nota: Esta función experimental es necesaria para usar NextJS Image en modo SSG. + // Consulta https://nextjs.org/docs/messages/export-image-api para ver diferentes soluciones. + images: { + unoptimized: true, + }, + // Configura assetPrefix o el servidor no resolverá correctamente tus archivos. + assetPrefix: isProd ? null : `http://${internalHost}:3000`, + }; + return nextConfig; }; ``` diff --git a/src/content/docs/es/start/frontend/nuxt.mdx b/src/content/docs/es/start/frontend/nuxt.mdx index fb02d4eb3..f9cbf1756 100644 --- a/src/content/docs/es/start/frontend/nuxt.mdx +++ b/src/content/docs/es/start/frontend/nuxt.mdx @@ -25,12 +25,12 @@ Aprende más sobre Nuxt en https://nuxt.com. Esta guía es precisa a partir de N ```json // tauri.conf.json { - "build": { - "beforeDevCommand": "npm run dev", - "beforeBuildCommand": "npm run generate", - "devPath": "http://localhost:3000", - "distDir": "../dist" - } + "build": { + "beforeDevCommand": "npm run dev", + "beforeBuildCommand": "npm run generate", + "devPath": "http://localhost:3000", + "distDir": "../dist" + } } ``` @@ -40,12 +40,12 @@ Aprende más sobre Nuxt en https://nuxt.com. Esta guía es precisa a partir de N ```json // tauri.conf.json { - "build": { - "beforeDevCommand": "yarn dev", - "beforeBuildCommand": "yarn generate", - "devPath": "http://localhost:3000", - "distDir": "../dist" - } + "build": { + "beforeDevCommand": "yarn dev", + "beforeBuildCommand": "yarn generate", + "devPath": "http://localhost:3000", + "distDir": "../dist" + } } ``` @@ -55,12 +55,12 @@ Aprende más sobre Nuxt en https://nuxt.com. Esta guía es precisa a partir de N ```json // tauri.conf.json { - "build": { - "beforeDevCommand": "pnpm dev", - "beforeBuildCommand": "pnpm generate", - "devPath": "http://localhost:3000", - "distDir": "../dist" - } + "build": { + "beforeDevCommand": "pnpm dev", + "beforeBuildCommand": "pnpm generate", + "devPath": "http://localhost:3000", + "distDir": "../dist" + } } ``` @@ -72,31 +72,31 @@ Aprende más sobre Nuxt en https://nuxt.com. Esta guía es precisa a partir de N ```ts export default defineNuxtConfig({ - // (opcional) Habilita las herramientas de desarrollo de Nuxt - devtools: { enabled: true }, - // Habilita SSG - ssr: false, - vite: { - // Mejor soporte para la salida de Tauri CLI - clearScreen: false, - // Habilita las variables de entorno - // Las variables de entorno adicionales se pueden encontrar en - // https://tauri.app/2/reference/environment-variables/ - envPrefix: ['VITE_', 'TAURI_'], - server: { - // Tauri requiere un puerto consistente - strictPort: true, - // Habilita el servidor de desarrollo para pueda ser accedido por otros dispositivos para el desarrollo móvil - host: '0.0.0.0', - hmr: { - // Usa un websocket para la recarga rápida en móviles - protocol: 'ws', - // Asegúrate de que esté disponible en la red - host: '0.0.0.0', - // Usa un puerto específico para hmr - port: 5183, - }, - }, - }, + // (opcional) Habilita las herramientas de desarrollo de Nuxt + devtools: { enabled: true }, + // Habilita SSG + ssr: false, + vite: { + // Mejor soporte para la salida de Tauri CLI + clearScreen: false, + // Habilita las variables de entorno + // Las variables de entorno adicionales se pueden encontrar en + // https://tauri.app/2/reference/environment-variables/ + envPrefix: ['VITE_', 'TAURI_'], + server: { + // Tauri requiere un puerto consistente + strictPort: true, + // Habilita el servidor de desarrollo para pueda ser accedido por otros dispositivos para el desarrollo móvil + host: '0.0.0.0', + hmr: { + // Usa un websocket para la recarga rápida en móviles + protocol: 'ws', + // Asegúrate de que esté disponible en la red + host: '0.0.0.0', + // Usa un puerto específico para hmr + port: 5183, + }, + }, + }, }); ``` diff --git a/src/content/docs/es/start/frontend/trunk.mdx b/src/content/docs/es/start/frontend/trunk.mdx index 19245daab..b8c8ea594 100644 --- a/src/content/docs/es/start/frontend/trunk.mdx +++ b/src/content/docs/es/start/frontend/trunk.mdx @@ -19,15 +19,15 @@ Trunk es una herramienta de empaquetado de aplicaciones web WASM para Rust. Obt ```json // tauri.conf.json { - "build": { - "beforeDevCommand": "trunk serve", - "beforeBuildCommand": "trunk build", - "devPath": "http://localhost:8080", - "distDir": "../dist" - }, - "app": { - "withGlobalTauri": true - } + "build": { + "beforeDevCommand": "trunk serve", + "beforeBuildCommand": "trunk build", + "devPath": "http://localhost:8080", + "distDir": "../dist" + }, + "app": { + "withGlobalTauri": true + } } ``` diff --git a/src/content/docs/fr/develop/Debug/application.mdx b/src/content/docs/fr/develop/Debug/application.mdx index 6423dfd55..2382bedcc 100644 --- a/src/content/docs/fr/develop/Debug/application.mdx +++ b/src/content/docs/fr/develop/Debug/application.mdx @@ -73,10 +73,10 @@ Par défaut, l'inspecteur n'est activé que dans les versions de développement Pour créer une version de débogage, exécutez la commande `tauri build --debug`. Comme les processus de construction et de développement normaux, la construction prend un certain temps la première fois que vous exécutez cette commande, mais est beaucoup plus rapide lors des exécutions suivantes. L'application groupée finale a la console de développement activée et est placée dans `src-tauri/target/debug/bundle`. diff --git a/src/content/docs/fr/develop/Debug/index.mdx b/src/content/docs/fr/develop/Debug/index.mdx index c72fd787d..ea03f01fb 100644 --- a/src/content/docs/fr/develop/Debug/index.mdx +++ b/src/content/docs/fr/develop/Debug/index.mdx @@ -6,13 +6,13 @@ description: Conseils et astuces pour votre débogage import { LinkCard, CardGrid } from '@astrojs/starlight/components'; - - - + + + diff --git a/src/content/docs/fr/develop/Debug/vs-code.mdx b/src/content/docs/fr/develop/Debug/vs-code.mdx index 986241ec8..f7b33f48f 100644 --- a/src/content/docs/fr/develop/Debug/vs-code.mdx +++ b/src/content/docs/fr/develop/Debug/vs-code.mdx @@ -14,36 +14,36 @@ Créez un fichier `.vscode/launch.json` et collez-y le contenu JSON ci-dessous : ```json title=".vscode/launch.json" { - // Utilisez IntelliSense pour en savoir plus sur les attributs possibles. - // Survolez pour afficher les descriptions des attributs existants. - // Pour plus d'informations, visitez : https://go.microsoft.com/fwlink/?linkid=830387 - "version": "0.2.0", - "configurations": [ - { - "type": "lldb", - "request": "launch", - "name": "Débogage de la production de Tauri", - "cargo": { - "args": [ - "build", - "--manifest-path=./src-tauri/Cargo.toml", - "--no-default-features" - ] - }, - // La tâche pour `beforeDevCommand` si elle est utilisée, doit être configurée dans `.vscode/tasks.json` - "preLaunchTask": "ui:dev" - }, - { - "type": "lldb", - "request": "launch", - "name": "Debug de production de Tauri", - "cargo": { - "args": ["build", "--release", "--manifest-path=./src-tauri/Cargo.toml"] - }, - // La tâche pour `beforeBuildCommand` si elle est utilisée, doit être configurée dans `.vscode/tasks.json` - "preLaunchTask": "ui:build" - } - ] + // Utilisez IntelliSense pour en savoir plus sur les attributs possibles. + // Survolez pour afficher les descriptions des attributs existants. + // Pour plus d'informations, visitez : https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "type": "lldb", + "request": "launch", + "name": "Débogage de la production de Tauri", + "cargo": { + "args": [ + "build", + "--manifest-path=./src-tauri/Cargo.toml", + "--no-default-features" + ] + }, + // La tâche pour `beforeDevCommand` si elle est utilisée, doit être configurée dans `.vscode/tasks.json` + "preLaunchTask": "ui:dev" + }, + { + "type": "lldb", + "request": "launch", + "name": "Debug de production de Tauri", + "cargo": { + "args": ["build", "--release", "--manifest-path=./src-tauri/Cargo.toml"] + }, + // La tâche pour `beforeBuildCommand` si elle est utilisée, doit être configurée dans `.vscode/tasks.json` + "preLaunchTask": "ui:build" + } + ] } ``` @@ -53,29 +53,29 @@ Notez qu'il n'utilise pas la CLI Tauri, donc les fonctionnalités CLI exclusives ```json title=".vscode/tasks.json" { - // See https://go.microsoft.com/fwlink/?LinkId=733558 - // for the documentation about the tasks.json format - "version": "2.0.0", - "tasks": [ - { - "label": "ui:dev", - "type": "shell", - // `dev` keeps running in the background - // ideally you should also configure a `problemMatcher` - // see https://code.visualstudio.com/docs/editor/tasks#_can-a-background-task-be-used-as-a-prelaunchtask-in-launchjson - "isBackground": true, - // change this to your `beforeDevCommand`: - "command": "yarn", - "args": ["dev"] - }, - { - "label": "ui:build", - "type": "shell", - // change this to your `beforeBuildCommand`: - "command": "yarn", - "args": ["build"] - } - ] + // See https://go.microsoft.com/fwlink/?LinkId=733558 + // for the documentation about the tasks.json format + "version": "2.0.0", + "tasks": [ + { + "label": "ui:dev", + "type": "shell", + // `dev` keeps running in the background + // ideally you should also configure a `problemMatcher` + // see https://code.visualstudio.com/docs/editor/tasks#_can-a-background-task-be-used-as-a-prelaunchtask-in-launchjson + "isBackground": true, + // change this to your `beforeDevCommand`: + "command": "yarn", + "args": ["dev"] + }, + { + "label": "ui:build", + "type": "shell", + // change this to your `beforeBuildCommand`: + "command": "yarn", + "args": ["build"] + } + ] } ``` diff --git a/src/content/docs/fr/develop/development-cycle.mdx b/src/content/docs/fr/develop/development-cycle.mdx index 0c837fab3..0408fd819 100644 --- a/src/content/docs/fr/develop/development-cycle.mdx +++ b/src/content/docs/fr/develop/development-cycle.mdx @@ -17,10 +17,10 @@ Chaque framework possède ses propres outils de développement. Il n'entre pas d ### 2. Démarrer la fenêtre de développement de Tauri La première fois que vous exécutez cette commande, le gestionnaire de packages Rust prend plusieurs minutes pour télécharger et créer tous les packages requis. Comme ils sont mis en cache, les builds suivants sont beaucoup plus rapides, car seul votre code a besoin d'être reconstruit. diff --git a/src/content/docs/fr/develop/index.mdx b/src/content/docs/fr/develop/index.mdx index a53e7a32f..70627ecc8 100644 --- a/src/content/docs/fr/develop/index.mdx +++ b/src/content/docs/fr/develop/index.mdx @@ -6,12 +6,12 @@ description: Concepts de base pour le développement avec Tauri import { LinkCard, CardGrid } from '@astrojs/starlight/components'; - - + + diff --git a/src/content/docs/fr/develop/updating-dependencies.mdx b/src/content/docs/fr/develop/updating-dependencies.mdx index 25412e86c..bad7bc510 100644 --- a/src/content/docs/fr/develop/updating-dependencies.mdx +++ b/src/content/docs/fr/develop/updating-dependencies.mdx @@ -9,25 +9,25 @@ import CommandTabs from '@components/CommandTabs.astro'; Si vous utilisez le package `tauri` : Vous pouvez également détecter la dernière version de Tauri sur la ligne de commande, en utilisant : Sinon, si vous utilisez l'approche `vue-cli-plugin-tauri` : ## Mettre à jour les packages Cargo diff --git a/src/content/docs/fr/index.mdx b/src/content/docs/fr/index.mdx index 9e19b3dca..be27ef469 100644 --- a/src/content/docs/fr/index.mdx +++ b/src/content/docs/fr/index.mdx @@ -30,35 +30,35 @@ hero: import { Card, CardGrid } from '@astrojs/starlight/components';
- -
-
+ +
+
- - Importez votre configuration web existant dans Tauri ou démarrez votre - nouveau projet de rêve. Tauri supporte n'importe quel framework frontend, - vous n'avez donc pas besoin de changer votre configuration. - - - Développez vos applications pour Linux, macOS, Windows, Android et iOS - - tout cela à partir du même code. - - - Écrivez votre frontend en Javascript, la logique de l'application en Rust, - puis intégrez le tout profondément dans le système avec Swift et Kotlin. - - - C'est la première préoccupation de l'équipe Tauri, qui dirige nos priorités - et nos plus grandes innovations. - - - En utilisant le moteur de rendu web natif du système d'exploitation, le - poids d'une application Tauri peut atteindre 600 Ko. - - - Avec la performance et la sécurité au cœur de ses priorités, Rust est le - langage de la nouvelle génération d'applications. - + + Importez votre configuration web existant dans Tauri ou démarrez votre + nouveau projet de rêve. Tauri supporte n'importe quel framework frontend, + vous n'avez donc pas besoin de changer votre configuration. + + + Développez vos applications pour Linux, macOS, Windows, Android et iOS - + tout cela à partir du même code. + + + Écrivez votre frontend en Javascript, la logique de l'application en Rust, + puis intégrez le tout profondément dans le système avec Swift et Kotlin. + + + C'est la première préoccupation de l'équipe Tauri, qui dirige nos priorités + et nos plus grandes innovations. + + + En utilisant le moteur de rendu web natif du système d'exploitation, le + poids d'une application Tauri peut atteindre 600 Ko. + + + Avec la performance et la sécurité au cœur de ses priorités, Rust est le + langage de la nouvelle génération d'applications. + diff --git a/src/content/docs/fr/plugin/notification.mdx b/src/content/docs/fr/plugin/notification.mdx index 233d62424..400c9f73f 100644 --- a/src/content/docs/fr/plugin/notification.mdx +++ b/src/content/docs/fr/plugin/notification.mdx @@ -88,9 +88,9 @@ Suivez ces étapes pour envoyer une notification: ```js import { - isPermissionGranted, - requestPermission, - sendNotification, + isPermissionGranted, + requestPermission, + sendNotification, } from '@tauri-apps/plugin-notification'; // Avez-vous la permission d'envoyer une notification ? @@ -98,13 +98,13 @@ let permissionGranted = await isPermissionGranted(); // Le cas échéant on la demande if (!permissionGranted) { - const permission = await requestPermission(); - permissionGranted = permission === 'granted'; + const permission = await requestPermission(); + permissionGranted = permission === 'granted'; } // Une fois la permission obtenue, on envoie la notification if (permissionGranted) { - sendNotification({ title: 'Tauri', body: 'Tauri est incroyable!' }); + sendNotification({ title: 'Tauri', body: 'Tauri est incroyable!' }); } ``` diff --git a/src/content/docs/fr/start/frontend/index.mdx b/src/content/docs/fr/start/frontend/index.mdx index c710b9cb1..7d0a41677 100644 --- a/src/content/docs/fr/start/frontend/index.mdx +++ b/src/content/docs/fr/start/frontend/index.mdx @@ -19,21 +19,21 @@ Un framework manque à la liste ? Il peut fonctionner avec Tauri sans configurat ## JavaScript - - - - - - + + + + + + ## Rust - - - - + + + + ## Instructions de Configuration diff --git a/src/content/docs/fr/start/frontend/nextjs.mdx b/src/content/docs/fr/start/frontend/nextjs.mdx index 1b87a99f6..b4b9a3ce1 100644 --- a/src/content/docs/fr/start/frontend/nextjs.mdx +++ b/src/content/docs/fr/start/frontend/nextjs.mdx @@ -20,9 +20,9 @@ Next.js est un framework React. Apprenez-en plus au sujet de Next.js sur https:/ 1. Installez `internal-ip` pour le développement mobile : 2. Mettez à jour la configuration de Tauri : @@ -33,12 +33,12 @@ Next.js est un framework React. Apprenez-en plus au sujet de Next.js sur https:/ ```json // tauri.conf.json { - "build": { - "beforeDevCommand": "npm run dev", - "beforeBuildCommand": "npm run build", - "devPath": "http://localhost:3000", - "distDir": "../dist" - } + "build": { + "beforeDevCommand": "npm run dev", + "beforeBuildCommand": "npm run build", + "devPath": "http://localhost:3000", + "distDir": "../dist" + } } ``` @@ -48,12 +48,12 @@ Next.js est un framework React. Apprenez-en plus au sujet de Next.js sur https:/ ```json // tauri.conf.json { - "build": { - "beforeDevCommand": "yarn dev", - "beforeBuildCommand": "yarn generate", - "devPath": "http://localhost:3000", - "distDir": "../dist" - } + "build": { + "beforeDevCommand": "yarn dev", + "beforeBuildCommand": "yarn generate", + "devPath": "http://localhost:3000", + "distDir": "../dist" + } } ``` @@ -63,12 +63,12 @@ Next.js est un framework React. Apprenez-en plus au sujet de Next.js sur https:/ ```json // tauri.conf.json { - "build": { - "beforeDevCommand": "pnpm dev", - "beforeBuildCommand": "pnpm generate", - "devPath": "http://localhost:3000", - "distDir": "../dist" - } + "build": { + "beforeDevCommand": "pnpm dev", + "beforeBuildCommand": "pnpm generate", + "devPath": "http://localhost:3000", + "distDir": "../dist" + } } ``` @@ -81,25 +81,25 @@ Next.js est un framework React. Apprenez-en plus au sujet de Next.js sur https:/ // next.conf.ts const isProd = process.env.NODE_ENV === 'production'; module.exports = async (phase, { defaultConfig }) => { - let internalHost = null; - // En mode développement, on utilise "internal-ip" pour se servir des assets. + let internalHost = null; + // En mode développement, on utilise "internal-ip" pour se servir des assets. - if (!isProd) { - const { internalIpV4 } = await import('internal-ip'); - internalHost = await internalIpV4(); - } - const nextConfig = { - // Assurez-vous que Next.js utilise SSG au lieu de SSR - // https://nextjs.org/docs/pages/building-your-application/deploying/static-exports - output: 'export', - // Note: Cette fonctionnalité expérimentale est requise pour utiliser NextJS Image en mode SSG. - // Voir https://nextjs.org/docs/messages/export-image-api pour des solutions différentes. - images: { - unoptimized: true, - }, - // Configurez assetPrefix sinon le server ne résoudra pas correctement vos assets. - assetPrefix: isProd ? null : `http://${internalHost}:3000`, - }; - return nextConfig; + if (!isProd) { + const { internalIpV4 } = await import('internal-ip'); + internalHost = await internalIpV4(); + } + const nextConfig = { + // Assurez-vous que Next.js utilise SSG au lieu de SSR + // https://nextjs.org/docs/pages/building-your-application/deploying/static-exports + output: 'export', + // Note: Cette fonctionnalité expérimentale est requise pour utiliser NextJS Image en mode SSG. + // Voir https://nextjs.org/docs/messages/export-image-api pour des solutions différentes. + images: { + unoptimized: true, + }, + // Configurez assetPrefix sinon le server ne résoudra pas correctement vos assets. + assetPrefix: isProd ? null : `http://${internalHost}:3000`, + }; + return nextConfig; }; ``` diff --git a/src/content/docs/fr/start/frontend/nuxt.mdx b/src/content/docs/fr/start/frontend/nuxt.mdx index fc73603ec..624e23a79 100644 --- a/src/content/docs/fr/start/frontend/nuxt.mdx +++ b/src/content/docs/fr/start/frontend/nuxt.mdx @@ -25,12 +25,12 @@ Apprenez-en plus au sujet de Nuxt sur https://nuxt.com. Ce guide est valable à ```json // tauri.conf.json { - "build": { - "beforeDevCommand": "npm run dev", - "beforeBuildCommand": "npm run generate", - "devPath": "http://localhost:3000", - "distDir": "../dist" - } + "build": { + "beforeDevCommand": "npm run dev", + "beforeBuildCommand": "npm run generate", + "devPath": "http://localhost:3000", + "distDir": "../dist" + } } ``` @@ -40,12 +40,12 @@ Apprenez-en plus au sujet de Nuxt sur https://nuxt.com. Ce guide est valable à ```json // tauri.conf.json { - "build": { - "beforeDevCommand": "yarn dev", - "beforeBuildCommand": "yarn generate", - "devPath": "http://localhost:3000", - "distDir": "../dist" - } + "build": { + "beforeDevCommand": "yarn dev", + "beforeBuildCommand": "yarn generate", + "devPath": "http://localhost:3000", + "distDir": "../dist" + } } ``` @@ -55,12 +55,12 @@ Apprenez-en plus au sujet de Nuxt sur https://nuxt.com. Ce guide est valable à ```json // tauri.conf.json { - "build": { - "beforeDevCommand": "pnpm dev", - "beforeBuildCommand": "pnpm generate", - "devPath": "http://localhost:3000", - "distDir": "../dist" - } + "build": { + "beforeDevCommand": "pnpm dev", + "beforeBuildCommand": "pnpm generate", + "devPath": "http://localhost:3000", + "distDir": "../dist" + } } ``` @@ -72,32 +72,32 @@ Apprenez-en plus au sujet de Nuxt sur https://nuxt.com. Ce guide est valable à ```ts export default defineNuxtConfig({ - // (optionnel) Activez les outils de développement Nuxt - devtools: { enabled: true }, - // Activez SSG - ssr: false, - vite: { - // Meilleur compatibilité pour la sortie "Tauri CLI" - clearScreen: false, - // Activez les variables d'environnement - // Vous pouvez trouver les variables d'environnements additionnelles sur - // https://tauri.app/2/reference/environment-variables/ - envPrefix: ['VITE_', 'TAURI_'], - server: { - // Tauri requiert un port constant - strictPort: true, - // Active le serveur de développement pour être visible par les autres appareils pour le développement mobile - host: '0.0.0.0', - hmr: { - // Utilisez le websocket pour le rechargement à chaud + // (optionnel) Activez les outils de développement Nuxt + devtools: { enabled: true }, + // Activez SSG + ssr: false, + vite: { + // Meilleur compatibilité pour la sortie "Tauri CLI" + clearScreen: false, + // Activez les variables d'environnement + // Vous pouvez trouver les variables d'environnements additionnelles sur + // https://tauri.app/2/reference/environment-variables/ + envPrefix: ['VITE_', 'TAURI_'], + server: { + // Tauri requiert un port constant + strictPort: true, + // Active le serveur de développement pour être visible par les autres appareils pour le développement mobile + host: '0.0.0.0', + hmr: { + // Utilisez le websocket pour le rechargement à chaud - protocol: 'ws', - // Assurez-vous que ce soit disponible sur le réseau - host: '0.0.0.0', - // Utilisez un port spécifique pour hmr - port: 5183, - }, - }, - }, + protocol: 'ws', + // Assurez-vous que ce soit disponible sur le réseau + host: '0.0.0.0', + // Utilisez un port spécifique pour hmr + port: 5183, + }, + }, + }, }); ``` diff --git a/src/content/docs/fr/start/frontend/trunk.mdx b/src/content/docs/fr/start/frontend/trunk.mdx index 3e37e4863..07037ec68 100644 --- a/src/content/docs/fr/start/frontend/trunk.mdx +++ b/src/content/docs/fr/start/frontend/trunk.mdx @@ -27,15 +27,15 @@ Vous devrez utiliser `cargo install --git https://github.com/amrbashir/trunk` po ```json // tauri.conf.json { - "build": { - "beforeDevCommand": "trunk serve", - "beforeBuildCommand": "trunk build", - "devPath": "http://localhost:8080", - "distDir": "../dist" - }, - "app": { - "withGlobalTauri": true - } + "build": { + "beforeDevCommand": "trunk serve", + "beforeBuildCommand": "trunk build", + "devPath": "http://localhost:8080", + "distDir": "../dist" + }, + "app": { + "withGlobalTauri": true + } } ``` diff --git a/src/content/docs/fr/start/migrate/from-tauri-1.mdx b/src/content/docs/fr/start/migrate/from-tauri-1.mdx index aa14a47cd..df8aed17e 100644 --- a/src/content/docs/fr/start/migrate/from-tauri-1.mdx +++ b/src/content/docs/fr/start/migrate/from-tauri-1.mdx @@ -14,13 +14,13 @@ Ce guide vous explique comment mettre à niveau votre application basée sur Tau Tauri v2 contient la commande `migrate` qui simplifie votre migration: @@ -130,9 +130,9 @@ fn main() { ```json // package.json { - "dependencies": { - "@tauri-apps/plugin-app": "^2.0.0" - } + "dependencies": { + "@tauri-apps/plugin-app": "^2.0.0" + } } ``` @@ -190,9 +190,9 @@ fn main() { ```json // package.json { - "dependencies": { - "@tauri-apps/plugin-cli": "^2.0.0" - } + "dependencies": { + "@tauri-apps/plugin-cli": "^2.0.0" + } } ``` @@ -241,9 +241,9 @@ fn main() { ```json // package.json { - "dependencies": { - "@tauri-apps/plugin-clipboard-manager": "^2.0.0" - } + "dependencies": { + "@tauri-apps/plugin-clipboard-manager": "^2.0.0" + } } ``` @@ -299,21 +299,21 @@ fn main() { ```json // package.json { - "dependencies": { - "@tauri-apps/plugin-dialog": "^2.0.0" - } + "dependencies": { + "@tauri-apps/plugin-dialog": "^2.0.0" + } } ``` ```js import { save } from '@tauri-apps/plugin-dialog'; const filePath = await save({ - filters: [ - { - name: 'Image', - extensions: ['png', 'jpeg'], - }, - ], + filters: [ + { + name: 'Image', + extensions: ['png', 'jpeg'], + }, + ], }); ``` @@ -365,9 +365,9 @@ fn main() { ```json // package.json { - "dependencies": { - "@tauri-apps/plugin-fs": "^2.0.0" - } + "dependencies": { + "@tauri-apps/plugin-fs": "^2.0.0" + } } ``` @@ -411,16 +411,16 @@ fn main() { ```json // package.json { - "dependencies": { - "@tauri-apps/plugin-global-shortcut": "^2.0.0" - } + "dependencies": { + "@tauri-apps/plugin-global-shortcut": "^2.0.0" + } } ``` ```js import { register } from '@tauri-apps/plugin-global-shortcut'; await register('CommandOrControl+Shift+C', () => { - console.log('Shortcut triggered'); + console.log('Shortcut triggered'); }); ``` @@ -468,16 +468,16 @@ fn main() { ```json // package.json { - "dependencies": { - "@tauri-apps/plugin-http": "^2.0.0" - } + "dependencies": { + "@tauri-apps/plugin-http": "^2.0.0" + } } ``` ```js import { fetch } from '@tauri-apps/plugin-http'; const response = await fetch( - 'https://raw.githubusercontent.com/tauri-apps/tauri/dev/package.json' + 'https://raw.githubusercontent.com/tauri-apps/tauri/dev/package.json' ); ``` @@ -534,9 +534,9 @@ fn main() { ```json // package.json { - "dependencies": { - "@tauri-apps/plugin-notification": "^2.0.0" - } + "dependencies": { + "@tauri-apps/plugin-notification": "^2.0.0" + } } ``` @@ -714,9 +714,9 @@ fn main() { ```json // package.json { - "dependencies": { - "@tauri-apps/plugin-os": "^2.0.0" - } + "dependencies": { + "@tauri-apps/plugin-os": "^2.0.0" + } } ``` @@ -769,9 +769,9 @@ fn main() { ```json // package.json { - "dependencies": { - "@tauri-apps/plugin-process": "^2.0.0" - } + "dependencies": { + "@tauri-apps/plugin-process": "^2.0.0" + } } ``` @@ -828,9 +828,9 @@ fn main() { ```json // package.json { - "dependencies": { - "@tauri-apps/plugin-shell": "^2.0.0" - } + "dependencies": { + "@tauri-apps/plugin-shell": "^2.0.0" + } } ``` @@ -1009,9 +1009,9 @@ fn main() { ```json // package.json { - "dependencies": { - "@tauri-apps/plugin-updater": "^2.0.0" - } + "dependencies": { + "@tauri-apps/plugin-updater": "^2.0.0" + } } ``` @@ -1021,13 +1021,13 @@ import { relaunch } from '@tauri-apps/plugin-process'; const update = await check(); if (update.response.available) { - console.log( - `Update to ${update.response.latestVersion} available! Date: ${update.response.date}` - ); - console.log(`Release notes: ${update.response.body}`); - await update.downloadAndInstall(); - // nécéssite le plugin `process` - await relaunch(); + console.log( + `Update to ${update.response.latestVersion} available! Date: ${update.response.date}` + ); + console.log(`Release notes: ${update.response.body}`); + await update.downloadAndInstall(); + // nécéssite le plugin `process` + await relaunch(); } ``` @@ -1096,9 +1096,9 @@ fn main() { ```json // package.json { - "dependencies": { - "@tauri-apps/plugin-window": "^2.0.0" - } + "dependencies": { + "@tauri-apps/plugin-window": "^2.0.0" + } } ``` diff --git a/src/content/docs/index.mdx b/src/content/docs/index.mdx index 417305b5b..831ea0743 100644 --- a/src/content/docs/index.mdx +++ b/src/content/docs/index.mdx @@ -31,41 +31,41 @@ import { Card, CardGrid, LinkCard } from '@astrojs/starlight/components'; import Cta from '@fragments/cta.mdx';
- -
-
+ +
+
- - - + + +
- - Bring your existing web stack to Tauri or start that new dream project. - Tauri supports any frontend framework so you don't need to change your - stack. - - - Build your app for Linux, macOS, Windows, Android and iOS - all from a - single codebase. - - - Write your frontend in JavaScript, application logic in Rust, and integrate - deep into the system with Swift and Kotlin. - - - Front-of-mind for the Tauri Team that drives our highest priorities and - biggest innovations. - - - By using the OS's native web renderer, the size of a Tauri app can be little - as 600KB. - - - With performance and security at the center, Rust is the language for the - next generation of apps. - + + Bring your existing web stack to Tauri or start that new dream project. + Tauri supports any frontend framework so you don't need to change your + stack. + + + Build your app for Linux, macOS, Windows, Android and iOS - all from a + single codebase. + + + Write your frontend in JavaScript, application logic in Rust, and integrate + deep into the system with Swift and Kotlin. + + + Front-of-mind for the Tauri Team that drives our highest priorities and + biggest innovations. + + + By using the OS's native web renderer, the size of a Tauri app can be little + as 600KB. + + + With performance and security at the center, Rust is the language for the + next generation of apps. + diff --git a/src/content/docs/it/develop/debug/vs-code.mdx b/src/content/docs/it/develop/debug/vs-code.mdx index d1772550d..767fe2f77 100644 --- a/src/content/docs/it/develop/debug/vs-code.mdx +++ b/src/content/docs/it/develop/debug/vs-code.mdx @@ -13,36 +13,36 @@ Crea un file `.vscode/launch.json` e incolla il contenuto JSON sottostante in es ```json title=".vscode/launch.json" { - // Use IntelliSense to learn about possible attributes. - // Hover to view descriptions of existing attributes. - // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 - "version": "0.2.0", - "configurations": [ - { - "type": "lldb", - "request": "launch", - "name": "Tauri Development Debug", - "cargo": { - "args": [ - "build", - "--manifest-path=./src-tauri/Cargo.toml", - "--no-default-features" - ] - }, - // task for the `beforeDevCommand` if used, must be configured in `.vscode/tasks.json` - "preLaunchTask": "ui:dev" - }, - { - "type": "lldb", - "request": "launch", - "name": "Tauri Production Debug", - "cargo": { - "args": ["build", "--release", "--manifest-path=./src-tauri/Cargo.toml"] - }, - // task for the `beforeBuildCommand` if used, must be configured in `.vscode/tasks.json` - "preLaunchTask": "ui:build" - } - ] + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "type": "lldb", + "request": "launch", + "name": "Tauri Development Debug", + "cargo": { + "args": [ + "build", + "--manifest-path=./src-tauri/Cargo.toml", + "--no-default-features" + ] + }, + // task for the `beforeDevCommand` if used, must be configured in `.vscode/tasks.json` + "preLaunchTask": "ui:dev" + }, + { + "type": "lldb", + "request": "launch", + "name": "Tauri Production Debug", + "cargo": { + "args": ["build", "--release", "--manifest-path=./src-tauri/Cargo.toml"] + }, + // task for the `beforeBuildCommand` if used, must be configured in `.vscode/tasks.json` + "preLaunchTask": "ui:build" + } + ] } ``` @@ -52,29 +52,29 @@ Nota che non utilizza il Tauri CLI, quindi le esclusive funzioni CLI non vengono ```json title=".vscode/tasks.json" { - // See https://go.microsoft.com/fwlink/?LinkId=733558 - // for the documentation about the tasks.json format - "version": "2.0.0", - "tasks": [ - { - "label": "ui:dev", - "type": "shell", - // `dev` keeps running in the background - // ideally you should also configure a `problemMatcher` - // see https://code.visualstudio.com/docs/editor/tasks#_can-a-background-task-be-used-as-a-prelaunchtask-in-launchjson - "isBackground": true, - // change this to your `beforeDevCommand`: - "command": "yarn", - "args": ["dev"] - }, - { - "label": "ui:build", - "type": "shell", - // change this to your `beforeBuildCommand`: - "command": "yarn", - "args": ["build"] - } - ] + // See https://go.microsoft.com/fwlink/?LinkId=733558 + // for the documentation about the tasks.json format + "version": "2.0.0", + "tasks": [ + { + "label": "ui:dev", + "type": "shell", + // `dev` keeps running in the background + // ideally you should also configure a `problemMatcher` + // see https://code.visualstudio.com/docs/editor/tasks#_can-a-background-task-be-used-as-a-prelaunchtask-in-launchjson + "isBackground": true, + // change this to your `beforeDevCommand`: + "command": "yarn", + "args": ["dev"] + }, + { + "label": "ui:build", + "type": "shell", + // change this to your `beforeBuildCommand`: + "command": "yarn", + "args": ["build"] + } + ] } ``` diff --git a/src/content/docs/plugin/barcode-scanner.mdx b/src/content/docs/plugin/barcode-scanner.mdx index b9d0c1326..776e485c0 100644 --- a/src/content/docs/plugin/barcode-scanner.mdx +++ b/src/content/docs/plugin/barcode-scanner.mdx @@ -93,11 +93,11 @@ See [Access Control List](/reference/acl/) for more information. ```json title="src-tauri/capabilities/mobile.json" { - "$schema": "../gen/schemas/mobile-schema.json", - "identifier": "mobile-capability", - "windows": ["main"], - "platforms": ["iOS", "android"], - "permissions": ["barcode-scanner:allow-scan", "barcode-scanner:allow-cancel"] + "$schema": "../gen/schemas/mobile-schema.json", + "identifier": "mobile-capability", + "windows": ["main"], + "platforms": ["iOS", "android"], + "permissions": ["barcode-scanner:allow-scan", "barcode-scanner:allow-cancel"] } ``` diff --git a/src/content/docs/plugin/cli.mdx b/src/content/docs/plugin/cli.mdx index c3ae86d11..83d8b5145 100644 --- a/src/content/docs/plugin/cli.mdx +++ b/src/content/docs/plugin/cli.mdx @@ -86,33 +86,33 @@ Under `tauri.conf.json`, you have the following structure to configure the inter ```json title="src-tauri/tauri.conf.json" { - "plugins": { - "cli": { - "description": "Tauri CLI Plugin Example", - "args": [ - { - "short": "v", - "name": "verbose", - "description": "Verbosity level" - } - ], - "subcommands": { - "run": { - "description": "Run the application", - "args": [ - { - "name": "debug", - "description": "Run application in debug mode" - }, - { - "name": "release", - "description": "Run application in release mode" - } - ] - } - } - } - } + "plugins": { + "cli": { + "description": "Tauri CLI Plugin Example", + "args": [ + { + "short": "v", + "name": "verbose", + "description": "Verbosity level" + } + ], + "subcommands": { + "run": { + "description": "Run the application", + "args": [ + { + "name": "debug", + "description": "Run application in debug mode" + }, + { + "name": "release", + "description": "Run application in release mode" + } + ] + } + } + } + } } ``` @@ -134,18 +134,18 @@ A positional argument is identified by its position in the list of arguments. Wi ```json title="src-tauri/tauri.conf.json" { - "args": [ - { - "name": "source", - "index": 1, - "takesValue": true - }, - { - "name": "destination", - "index": 2, - "takesValue": true - } - ] + "args": [ + { + "name": "source", + "index": 1, + "takesValue": true + }, + { + "name": "destination", + "index": 2, + "takesValue": true + } + ] } ``` @@ -157,15 +157,15 @@ A named argument is a (key, value) pair where the key identifies the value. With ```json title="tauri-src/tauri.conf.json" { - "args": [ - { - "name": "type", - "short": "t", - "takesValue": true, - "multiple": true, - "possibleValues": ["foo", "bar"] - } - ] + "args": [ + { + "name": "type", + "short": "t", + "takesValue": true, + "multiple": true, + "possibleValues": ["foo", "bar"] + } + ] } ``` @@ -177,12 +177,12 @@ A flag argument is a standalone key whose presence or absence provides informati ```json title="tauri-src/tauri.conf.json" { - "args": [ - { - "name": "verbose", - "short": "v" - } - ] + "args": [ + { + "name": "verbose", + "short": "v" + } + ] } ``` @@ -222,14 +222,14 @@ import { getMatches } from '@tauri-apps/plugin-cli'; const matches = await getMatches(); if (matches.subcommand?.name === 'run') { - // `./your-app run $ARGS` was executed - const args = matches.subcommand.matches.args; - if (args.debug?.value === true) { - // `./your-app run --debug` was executed - } - if (args.release?.value === true) { - // `./your-app run --release` was executed - } + // `./your-app run $ARGS` was executed + const args = matches.subcommand.matches.args; + if (args.debug?.value === true) { + // `./your-app run --debug` was executed + } + if (args.release?.value === true) { + // `./your-app run --release` was executed + } } ``` @@ -272,11 +272,11 @@ See [Access Control List](/reference/acl/) for more information. ```json title="src-tauri/capabilities/main.json" ins={6} { - "$schema": "../gen/schemas/desktop-schema.json", - "identifier": "main-capability", - "description": "Capability for the main window", - "windows": ["main"], - "permissions": ["cli:default"] + "$schema": "../gen/schemas/desktop-schema.json", + "identifier": "main-capability", + "description": "Capability for the main window", + "windows": ["main"], + "permissions": ["cli:default"] } ``` diff --git a/src/content/docs/plugin/deep-linking.mdx b/src/content/docs/plugin/deep-linking.mdx index 47f7b975f..1645dc26e 100644 --- a/src/content/docs/plugin/deep-linking.mdx +++ b/src/content/docs/plugin/deep-linking.mdx @@ -102,19 +102,19 @@ For [universal links](https://developer.apple.com/documentation/xcode/allowing-a ```json title=".well-known/apple-app-site-association" { - "applinks": { - "details": [ - { - "appIDs": ["$DEVELOPMENT_TEAM_ID.$APP_BUNDLE_ID"], - "components": [ - { - "/": "/open/*", - "comment": "Matches any URL whose path starts with /open/" - } - ] - } - ] - } + "applinks": { + "details": [ + { + "appIDs": ["$DEVELOPMENT_TEAM_ID.$APP_BUNDLE_ID"], + "components": [ + { + "/": "/open/*", + "comment": "Matches any URL whose path starts with /open/" + } + ] + } + ] + } } ``` @@ -146,14 +146,14 @@ Under `tauri.conf.json > plugins > deep-link`, configure the domains you want to ```json title="tauri.conf.json" { - "plugins": { - "deep-link": { - "domains": [ - { "host": "your.website.com", "pathPrefix": ["/open"] }, - { "host": "another.site.br" } - ] - } - } + "plugins": { + "deep-link": { + "domains": [ + { "host": "your.website.com", "pathPrefix": ["/open"] }, + { "host": "another.site.br" } + ] + } + } } ``` @@ -168,7 +168,7 @@ The deep-link plugin is available in both JavaScript and Rust. import { onOpenUrl } from '@tauri-apps/plugin-deep-link'; await onOpenUrl((urls) => { - console.log('deep link:', urls); + console.log('deep link:', urls); }); ``` @@ -205,15 +205,15 @@ See [Access Control List](/reference/acl/) for more information. ```json title="src-tauri/capabilities/main.json" ins={9} { - "$schema": "../gen/schemas/mobile-schema.json", - "identifier": "mobile-capability", - "windows": ["main"], - "platforms": ["iOS", "android"], - "permissions": [ - // Usually you will need event:default to listen to the deep-link event - "event:default", - "deep-link:default" - ] + "$schema": "../gen/schemas/mobile-schema.json", + "identifier": "mobile-capability", + "windows": ["main"], + "platforms": ["iOS", "android"], + "permissions": [ + // Usually you will need event:default to listen to the deep-link event + "event:default", + "deep-link:default" + ] } ``` diff --git a/src/content/docs/plugin/dialog.mdx b/src/content/docs/plugin/dialog.mdx index c879594e3..1013ad58b 100644 --- a/src/content/docs/plugin/dialog.mdx +++ b/src/content/docs/plugin/dialog.mdx @@ -96,8 +96,8 @@ import { ask } from '@tauri-apps/plugin-dialog'; // Create a Yes/No dialog const answer = await ask('This action cannot be reverted. Are you sure?', { - title: 'Tauri', - kind: 'warning', + title: 'Tauri', + kind: 'warning', }); console.log(answer); @@ -115,8 +115,8 @@ import { confirm } from '@tauri-apps/plugin-dialog'; // Creates a confirmation Ok/Cancel dialog const confirmation = await confirm( - 'This action cannot be reverted. Are you sure?', - { title: 'Tauri', kind: 'warning' } + 'This action cannot be reverted. Are you sure?', + { title: 'Tauri', kind: 'warning' } ); console.log(confirmation); @@ -149,8 +149,8 @@ import { open } from '@tauri-apps/plugin-dialog'; // Open a dialog const file = await open({ - multiple: false, - directory: false, + multiple: false, + directory: false, }); console.log(file); // Prints file path and name to the console @@ -166,12 +166,12 @@ Open a file/directory save dialog. import { save } from '@tauri-apps/plugin-dialog'; // Prompt to save a 'My Filter' with extension .png or .jpeg const path = await save({ - filters: [ - { - name: 'My Filter', - extensions: ['png', 'jpeg'], - }, - ], + filters: [ + { + name: 'My Filter', + extensions: ['png', 'jpeg'], + }, + ], }); console.log(path); // Prints the chosen path diff --git a/src/content/docs/plugin/file-system.mdx b/src/content/docs/plugin/file-system.mdx index 42549559e..ed1cda7c2 100644 --- a/src/content/docs/plugin/file-system.mdx +++ b/src/content/docs/plugin/file-system.mdx @@ -133,17 +133,17 @@ See [Access Control List](/reference/acl/) for more information. ```json title="src-tauri/capabilities/main.json" ins={7-11} { - "$schema": "../gen/schemas/desktop-schema.json", - "identifier": "main-capability", - "description": "Capability for the main window", - "windows": ["main"], - "permissions": [ - "fs:default", - { - "identifier": "fs:allow-exists", - "allow": [{ "path": "$APPDATA/*" }] - } - ] + "$schema": "../gen/schemas/desktop-schema.json", + "identifier": "main-capability", + "description": "Capability for the main window", + "windows": ["main"], + "permissions": [ + "fs:default", + { + "identifier": "fs:allow-exists", + "allow": [{ "path": "$APPDATA/*" }] + } + ] } ``` @@ -464,16 +464,16 @@ To allow any `fs` command to access specific scopes: ```json title="src-tauri/capabilities/main.json" {7-10} { - "$schema": "../gen/schemas/desktop-schema.json", - "identifier": "main-capability", - "description": "Capability for the main window", - "windows": ["main"], - "permissions": [ - { - "identifier": "fs:scope", - "allow": [{ "path": "$APPDATA" }, { "path": "$APPDATA/**" }] - } - ] + "$schema": "../gen/schemas/desktop-schema.json", + "identifier": "main-capability", + "description": "Capability for the main window", + "windows": ["main"], + "permissions": [ + { + "identifier": "fs:scope", + "allow": [{ "path": "$APPDATA" }, { "path": "$APPDATA/**" }] + } + ] } ``` @@ -481,19 +481,19 @@ To allow specific `fs` command to access specific scopes: ```json title="src-tauri/capabilities/main.json" {7-14} { - "$schema": "../gen/schemas/desktop-schema.json", - "identifier": "main-capability", - "description": "Capability for the main window", - "windows": ["main"], - "permissions": [ - { - "identifier": "fs:allow-rename", - "allow": [{ "path": "$HOME/**" }] - }, - { - "identifier": "fs:allow-exists", - "allow": [{ "path": "$APPDATA/*" }] - } - ] + "$schema": "../gen/schemas/desktop-schema.json", + "identifier": "main-capability", + "description": "Capability for the main window", + "windows": ["main"], + "permissions": [ + { + "identifier": "fs:allow-rename", + "allow": [{ "path": "$HOME/**" }] + }, + { + "identifier": "fs:allow-exists", + "allow": [{ "path": "$APPDATA/*" }] + } + ] } ``` diff --git a/src/content/docs/plugin/global-shortcut.mdx b/src/content/docs/plugin/global-shortcut.mdx index 64c6e6503..fd3588f7d 100644 --- a/src/content/docs/plugin/global-shortcut.mdx +++ b/src/content/docs/plugin/global-shortcut.mdx @@ -90,7 +90,7 @@ The global-shortcut plugin is available in both JavaScript and Rust. import { register } from '@tauri-apps/plugin-global-shortcut'; await register('CommandOrControl+Shift+C', () => { - console.log('Shortcut triggered'); + console.log('Shortcut triggered'); }); ``` @@ -136,15 +136,15 @@ See [Access Control List](/reference/acl/) for more information. ```json title="src-tauri/capabilities/main.json" ins={7-9} { - "$schema": "../gen/schemas/desktop-schema.json", - "identifier": "main-capability", - "description": "Capability for the main window", - "windows": ["main"], - "permissions": [ - "global-shortcut:allow-is-registered", - "global-shortcut:allow-register", - "global-shortcut:allow-unregister" - ] + "$schema": "../gen/schemas/desktop-schema.json", + "identifier": "main-capability", + "description": "Capability for the main window", + "windows": ["main"], + "permissions": [ + "global-shortcut:allow-is-registered", + "global-shortcut:allow-register", + "global-shortcut:allow-unregister" + ] } ``` diff --git a/src/content/docs/plugin/http-client.mdx b/src/content/docs/plugin/http-client.mdx index 2ab62c882..b0d39f4f6 100644 --- a/src/content/docs/plugin/http-client.mdx +++ b/src/content/docs/plugin/http-client.mdx @@ -75,13 +75,13 @@ The http plugin is available in both as an JavaScript API and in Rust as a [reqw ```json //src-tauri/capabilities/base.json { - "permissions": [ - { - "identifier": "http:default", - "allow": [{ "url": "https://*.tauri.app" }], - "deny": [{ "url": "https://private.tauri.app" }] - } - ] + "permissions": [ + { + "identifier": "http:default", + "allow": [{ "url": "https://*.tauri.app" }], + "deny": [{ "url": "https://private.tauri.app" }] + } + ] } ``` @@ -94,7 +94,7 @@ The http plugin is available in both as an JavaScript API and in Rust as a [reqw // Send a GET request const response = await fetch('http://test.tauri.app/data.json', { - method: 'GET', + method: 'GET', }); console.log(response.status); // e.g. 200 console.log(response.statusText); // e.g. "OK" diff --git a/src/content/docs/plugin/index.mdx b/src/content/docs/plugin/index.mdx index 30e426f95..dc184a6ff 100644 --- a/src/content/docs/plugin/index.mdx +++ b/src/content/docs/plugin/index.mdx @@ -17,16 +17,16 @@ Tauri comes with extensibility in mind. On this page you'll find: - **[Community Resources](#community-resources)**: More plugins and recipes built by the Tauri community - ## Features - - ## Community Resources - - ### Plugins - - ### Integrations - + ## Features + + ## Community Resources + + ### Plugins + + ### Integrations + diff --git a/src/content/docs/plugin/logging.mdx b/src/content/docs/plugin/logging.mdx index b70233901..715ce9a1a 100644 --- a/src/content/docs/plugin/logging.mdx +++ b/src/content/docs/plugin/logging.mdx @@ -132,11 +132,11 @@ See [Access Control List](/reference/acl/) for more information. ```json title="src-tauri/capabilities/main.json" ins={6} { - "$schema": "../gen/schemas/desktop-schema.json", - "identifier": "main-capability", - "description": "Capability for the main window", - "windows": ["main"], - "permissions": ["log:default"] + "$schema": "../gen/schemas/desktop-schema.json", + "identifier": "main-capability", + "description": "Capability for the main window", + "windows": ["main"], + "permissions": ["log:default"] } ``` diff --git a/src/content/docs/plugin/notification.mdx b/src/content/docs/plugin/notification.mdx index ec9a9b8c2..266abc4a2 100644 --- a/src/content/docs/plugin/notification.mdx +++ b/src/content/docs/plugin/notification.mdx @@ -92,9 +92,9 @@ Follow these steps to send a notification: ```js import { - isPermissionGranted, - requestPermission, - sendNotification, + isPermissionGranted, + requestPermission, + sendNotification, } from '@tauri-apps/plugin-notification'; // Do you have permission to send a notification? @@ -102,13 +102,13 @@ let permissionGranted = await isPermissionGranted(); // If not we need to request it if (!permissionGranted) { - const permission = await requestPermission(); - permissionGranted = permission === 'granted'; + const permission = await requestPermission(); + permissionGranted = permission === 'granted'; } // Once permission has been granted we can send the notification if (permissionGranted) { - sendNotification({ title: 'Tauri', body: 'Tauri is awesome!' }); + sendNotification({ title: 'Tauri', body: 'Tauri is awesome!' }); } ``` diff --git a/src/content/docs/plugin/shell.mdx b/src/content/docs/plugin/shell.mdx index 527863881..374a2a42b 100644 --- a/src/content/docs/plugin/shell.mdx +++ b/src/content/docs/plugin/shell.mdx @@ -85,8 +85,8 @@ The shell plugin is available in both JavaScript and Rust. import { Command } from '@tauri-apps/plugin-shell'; let result = await Command.create('exec-sh', [ - '-c', - "echo 'Hello World!'", + '-c', + "echo 'Hello World!'", ]).execute(); console.log(result); ``` @@ -125,28 +125,28 @@ See [Access Control List](/reference/acl/) for more information. ```json title="src-tauri/capabilities/main.json" ins={6-23} { - "$schema": "../gen/schemas/desktop-schema.json", - "identifier": "main-capability", - "description": "Capability for the main window", - "windows": ["main"], - "permissions": [ - { - "identifier": "shell:allow-execute", - "allow": [ - { - "name": "exec-sh", - "cmd": "sh", - "args": [ - "-c", - { - "validator": "\\S+" - } - ], - "sidecar": false - } - ] - } - ] + "$schema": "../gen/schemas/desktop-schema.json", + "identifier": "main-capability", + "description": "Capability for the main window", + "windows": ["main"], + "permissions": [ + { + "identifier": "shell:allow-execute", + "allow": [ + { + "name": "exec-sh", + "cmd": "sh", + "args": [ + "-c", + { + "validator": "\\S+" + } + ], + "sidecar": false + } + ] + } + ] } ``` diff --git a/src/content/docs/plugin/sql.mdx b/src/content/docs/plugin/sql.mdx index 7001d76c6..ae00f3c3e 100644 --- a/src/content/docs/plugin/sql.mdx +++ b/src/content/docs/plugin/sql.mdx @@ -44,20 +44,20 @@ branch = "v2" Then, you have to add JavaScript Guest bindings using your preferred JavaScript package manager. - - - - - - + + + + + + ## Usage @@ -230,11 +230,11 @@ See [Access Control List](/reference/acl/) for more information. ```json title="src-tauri/capabilities/main.json" ins={7-8} { - "$schema": "../gen/schemas/desktop-schema.json", - "identifier": "main-capability", - "description": "Capability for the main window", - "windows": ["main"], - "permissions": ["sql:allow-load", "sql:allow-execute"] + "$schema": "../gen/schemas/desktop-schema.json", + "identifier": "main-capability", + "description": "Capability for the main window", + "windows": ["main"], + "permissions": ["sql:allow-load", "sql:allow-execute"] } ``` diff --git a/src/content/docs/plugin/store.mdx b/src/content/docs/plugin/store.mdx index 4531a817a..1adc659c6 100644 --- a/src/content/docs/plugin/store.mdx +++ b/src/content/docs/plugin/store.mdx @@ -146,16 +146,16 @@ See [Access Control List](/reference/acl/) for more information. ```json title="src-tauri/capabilities/main.json" ins={6-11} { - "$schema": "../gen/schemas/desktop-schema.json", - "identifier": "main-capability", - "description": "Capability for the main window", - "windows": ["main"], - "permissions": [ - "store:allow-get", - "store:allow-set", - "store:allow-save", - "store:allow-load" - ] + "$schema": "../gen/schemas/desktop-schema.json", + "identifier": "main-capability", + "description": "Capability for the main window", + "windows": ["main"], + "permissions": [ + "store:allow-get", + "store:allow-set", + "store:allow-save", + "store:allow-load" + ] } ``` diff --git a/src/content/docs/plugin/updater.mdx b/src/content/docs/plugin/updater.mdx index e1372b826..297790ad3 100644 --- a/src/content/docs/plugin/updater.mdx +++ b/src/content/docs/plugin/updater.mdx @@ -13,5 +13,5 @@ import PluginLinks from '@components/PluginLinks.astro'; - Based on https://github.com/tauri-apps/plugins-workspace/tree/plugins/updater + Based on https://github.com/tauri-apps/plugins-workspace/tree/plugins/updater diff --git a/src/content/docs/plugin/upload.mdx b/src/content/docs/plugin/upload.mdx index 0c26cd3f3..0839add81 100644 --- a/src/content/docs/plugin/upload.mdx +++ b/src/content/docs/plugin/upload.mdx @@ -74,10 +74,10 @@ Here's an example of how you can use the plugin to upload and download files: import { upload } from '@tauri-apps/plugin-upload'; upload( - 'https://example.com/file-upload', - './path/to/my/file.txt', - (progress, total) => console.log(`Uploaded ${progress} of ${total} bytes`), // a callback that will be called with the upload progress - { 'Content-Type': 'text/plain' } // optional headers to send with the request + 'https://example.com/file-upload', + './path/to/my/file.txt', + (progress, total) => console.log(`Uploaded ${progress} of ${total} bytes`), // a callback that will be called with the upload progress + { 'Content-Type': 'text/plain' } // optional headers to send with the request ); ``` @@ -85,9 +85,9 @@ upload( import { download } from '@tauri-apps/plugin-upload'; download( - 'https://example.com/file-download-link', - './path/to/save/my/file.txt', - (progress, total) => console.log(`Downloaded ${progress} of ${total} bytes`), // a callback that will be called with the download progress - { 'Content-Type': 'text/plain' } // optional headers to send with the request + 'https://example.com/file-download-link', + './path/to/save/my/file.txt', + (progress, total) => console.log(`Downloaded ${progress} of ${total} bytes`), // a callback that will be called with the download progress + { 'Content-Type': 'text/plain' } // optional headers to send with the request ); ``` diff --git a/src/content/docs/plugin/websocket.mdx b/src/content/docs/plugin/websocket.mdx index a64d40e23..14347c088 100644 --- a/src/content/docs/plugin/websocket.mdx +++ b/src/content/docs/plugin/websocket.mdx @@ -87,7 +87,7 @@ import WebSocket from '@tauri-apps/plugin-websocket'; const ws = await WebSocket.connect('ws://127.0.0.1:8080'); ws.addListener((msg) => { - console.log('Received Message:', msg); + console.log('Received Message:', msg); }); await ws.send('Hello World!'); @@ -103,11 +103,11 @@ See [Access Control List](/reference/acl/) for more information. ```json title="src-tauri/capabilities/main.json" ins={6} { - "$schema": "../gen/schemas/desktop-schema.json", - "identifier": "main-capability", - "description": "Capability for the main window", - "windows": ["main"], - "permissions": ["websocket:default"] + "$schema": "../gen/schemas/desktop-schema.json", + "identifier": "main-capability", + "description": "Capability for the main window", + "windows": ["main"], + "permissions": ["websocket:default"] } ``` diff --git a/src/content/docs/plugin/window-customization.mdx b/src/content/docs/plugin/window-customization.mdx index c938f60a3..83d5939f4 100644 --- a/src/content/docs/plugin/window-customization.mdx +++ b/src/content/docs/plugin/window-customization.mdx @@ -57,11 +57,11 @@ See [Access Control List](/reference/acl/) for more information. ```json title="src-tauri/capabilities/main.json" ins={7-8} { - "$schema": "../gen/schemas/desktop-schema.json", - "identifier": "main-capability", - "description": "Capability for the main window", - "windows": ["main"], - "permissions": ["window:default", "window:allow-start-dragging"] + "$schema": "../gen/schemas/desktop-schema.json", + "identifier": "main-capability", + "description": "Capability for the main window", + "windows": ["main"], + "permissions": ["window:default", "window:allow-start-dragging"] } ``` @@ -80,27 +80,27 @@ Add this CSS sample to keep it at the top of the screen and style the buttons: ```css .titlebar { - height: 30px; - background: #329ea3; - user-select: none; - display: flex; - justify-content: flex-end; - position: fixed; - top: 0; - left: 0; - right: 0; + height: 30px; + background: #329ea3; + user-select: none; + display: flex; + justify-content: flex-end; + position: fixed; + top: 0; + left: 0; + right: 0; } .titlebar-button { - display: inline-flex; - justify-content: center; - align-items: center; - width: 30px; - height: 30px; - user-select: none; - -webkit-user-select: none; + display: inline-flex; + justify-content: center; + align-items: center; + width: 30px; + height: 30px; + user-select: none; + -webkit-user-select: none; } .titlebar-button:hover { - background: #5bbec3; + background: #5bbec3; } ``` @@ -110,21 +110,21 @@ Put this at the top of your `` tag: ```html
-
- minimize -
-
- maximize -
-
- close -
+
+ minimize +
+
+ maximize +
+
+ close +
``` @@ -140,14 +140,14 @@ import { Window } from '@tauri-apps/api/window'; const appWindow = new Window('main'); document - .getElementById('titlebar-minimize') - ?.addEventListener('click', () => appWindow.minimize()); + .getElementById('titlebar-minimize') + ?.addEventListener('click', () => appWindow.minimize()); document - .getElementById('titlebar-maximize') - ?.addEventListener('click', () => appWindow.toggleMaximize()); + .getElementById('titlebar-maximize') + ?.addEventListener('click', () => appWindow.toggleMaximize()); document - .getElementById('titlebar-close') - ?.addEventListener('click', () => appWindow.close()); + .getElementById('titlebar-close') + ?.addEventListener('click', () => appWindow.close()); ``` ### (macOS) Transparent Titlebar with Custom Window Background Color diff --git a/src/content/docs/plugin/window-state.mdx b/src/content/docs/plugin/window-state.mdx index 44ad506a8..79c8d6f05 100644 --- a/src/content/docs/plugin/window-state.mdx +++ b/src/content/docs/plugin/window-state.mdx @@ -35,10 +35,10 @@ Use your project's package manager to add the dependency: {' '} @@ -98,8 +98,8 @@ Similarly you can manually restore a window's state from disk: ```javascript import { - restoreStateCurrent, - StateFlags, + restoreStateCurrent, + StateFlags, } from '@tauri-apps/plugin-window-state'; restoreStateCurrent(StateFlags.ALL); diff --git a/src/content/docs/reference/acl.mdx b/src/content/docs/reference/acl.mdx index fe1114616..c2e6b4620 100644 --- a/src/content/docs/reference/acl.mdx +++ b/src/content/docs/reference/acl.mdx @@ -20,20 +20,20 @@ The following JSON defines a capability that enables default functionality for c ```json title="src-tauri/capabilities/main.json { - "$schema": "../gen/schemas/desktop-schema.json", - "identifier": "main-capability", - "description": "Capability for the main window", - "windows": ["main"], - "permissions": [ - "path:default", - "event:default", - "window:default", - "app:default", - "resources:default", - "menu:default", - "tray:default", - "window:allow-set-title" - ] + "$schema": "../gen/schemas/desktop-schema.json", + "identifier": "main-capability", + "description": "Capability for the main window", + "windows": ["main"], + "permissions": [ + "path:default", + "event:default", + "window:default", + "app:default", + "resources:default", + "menu:default", + "tray:default", + "window:allow-set-title" + ] } ``` @@ -47,11 +47,11 @@ For example, let's define a capability for desktop. Note it enables permissions ```json title="src-tauri/capabilities/desktop.json { - "$schema": "../gen/schemas/desktop-schema.json", - "identifier": "desktop-capability", - "windows": ["main"], - "platforms": ["linux", "macOS", "windows"], - "permissions": ["global-shortcut:allow-register"] + "$schema": "../gen/schemas/desktop-schema.json", + "identifier": "desktop-capability", + "windows": ["main"], + "platforms": ["linux", "macOS", "windows"], + "permissions": ["global-shortcut:allow-register"] } ``` @@ -59,15 +59,15 @@ And define a capability for mobile. Note it enables permissions on plugins that ```json title="src-tauri/capabilities/mobile.json { - "$schema": "../gen/schemas/mobile-schema.json", - "identifier": "mobile-capability", - "windows": ["main"], - "platforms": ["iOS", "android"], - "permissions": [ - "nfc:allow-scan", - "biometric:allow-authenticate", - "barcode-scanner:allow-scan" - ] + "$schema": "../gen/schemas/mobile-schema.json", + "identifier": "mobile-capability", + "windows": ["main"], + "platforms": ["iOS", "android"], + "permissions": [ + "nfc:allow-scan", + "biometric:allow-authenticate", + "barcode-scanner:allow-scan" + ] } ``` @@ -81,11 +81,11 @@ In the example above we defined specific capabilities for desktop and mobile, an ```json title="src-tauri/capabilities/linux.json { - "$schema": "../gen/schemas/linux-schema.json", - "identifier": "linux-capability", - "windows": ["main"], - "platforms": ["iOS", "android"], - "permissions": ["dbus::call"] + "$schema": "../gen/schemas/linux-schema.json", + "identifier": "linux-capability", + "windows": ["main"], + "platforms": ["iOS", "android"], + "permissions": ["dbus::call"] } ``` @@ -115,12 +115,12 @@ Let's study some examples for official plugins: ```json title="src-tauri/capabilities/base.json { - "permissions": [ - { - "identifier": "fs:scope", - "allow": [{ "path": "$APPDATA" }, { "path": "$APPDATA/**" }] - } - ] + "permissions": [ + { + "identifier": "fs:scope", + "allow": [{ "path": "$APPDATA" }, { "path": "$APPDATA/**" }] + } + ] } ``` @@ -132,12 +132,12 @@ Let's study some examples for official plugins: ```json title="src-tauri/capabilities/base.json { - "permissions": [ - { - "identifier": "fs:allow-rename", - "allow": [{ "path": "$HOME/**" }] - } - ] + "permissions": [ + { + "identifier": "fs:allow-rename", + "allow": [{ "path": "$HOME/**" }] + } + ] } ``` @@ -145,13 +145,13 @@ Let's study some examples for official plugins: ```json title="src-tauri/capabilities/base.json { - "permissions": [ - { - "identifier": "http:default", - "allow": [{ "url": "https://*.tauri.app" }], - "deny": [{ "url": "https://private.tauri.app" }] - } - ] + "permissions": [ + { + "identifier": "http:default", + "allow": [{ "url": "https://*.tauri.app" }], + "deny": [{ "url": "https://private.tauri.app" }] + } + ] } ``` diff --git a/src/content/docs/reference/cli.mdx b/src/content/docs/reference/cli.mdx index 541932e5f..b237de5b4 100644 --- a/src/content/docs/reference/cli.mdx +++ b/src/content/docs/reference/cli.mdx @@ -12,10 +12,10 @@ The Tauri command line interface (CLI) is the way to interact with Tauri through You can add the Tauri CLI to your current project using your package manager of choice: {/* TODO: 2.0 */} @@ -47,10 +47,10 @@ For CLI commands related to developing plugins visit the [Develop a Tauri Plugin ## `build` ``` @@ -94,10 +94,10 @@ Options: ## `dev` ``` @@ -131,10 +131,10 @@ If you have entered a command to the `build.beforeDevCommand` property, this one ## `icon` ``` @@ -157,10 +157,10 @@ Options: ## `info` ``` @@ -180,10 +180,10 @@ Options: ## `init` ``` @@ -225,10 +225,10 @@ Options: ## `add` ``` @@ -251,10 +251,10 @@ Options: ## `signer` ``` @@ -276,10 +276,10 @@ Options: ## `completions` ``` @@ -432,10 +432,10 @@ Add-Content -Path $profile -Value '& "$PSScriptRoot\_tauri.ps1"' ## `android` ``` @@ -459,10 +459,10 @@ Options: ## `ios` ``` @@ -486,10 +486,10 @@ Options: ## `migrate` ``` @@ -506,10 +506,10 @@ Options: ## `permission` ``` @@ -591,10 +591,10 @@ Options: ## `capability` ``` @@ -634,10 +634,10 @@ Options: ## `help` ``` diff --git a/src/content/docs/security/capabilities.mdx b/src/content/docs/security/capabilities.mdx index 0eac3b7ac..75ad39579 100644 --- a/src/content/docs/security/capabilities.mdx +++ b/src/content/docs/security/capabilities.mdx @@ -43,20 +43,20 @@ for core plugins and the `window.setTitle` API. ```json title="src-tauri/capabilities/main.json { - "$schema": "./schemas/desktop-schema.json", - "identifier": "main-capability", - "description": "Capability for the main window", - "windows": ["main"], - "permissions": [ - "path:default", - "event:default", - "window:default", - "app:default", - "resources:default", - "menu:default", - "tray:default", - "window:allow-set-title" - ] + "$schema": "./schemas/desktop-schema.json", + "identifier": "main-capability", + "description": "Capability for the main window", + "windows": ["main"], + "permissions": [ + "path:default", + "event:default", + "window:default", + "app:default", + "resources:default", + "menu:default", + "tray:default", + "window:allow-set-title" + ] } ``` @@ -72,11 +72,11 @@ capability files in the `capabilities` directory. ```json title=src-tauri/tauri.conf.json { - "app": { - "security": { - "capabilities": ["my-capability", "main-capability"] - } - } + "app": { + "security": { + "capabilities": ["my-capability", "main-capability"] + } + } } ``` @@ -84,19 +84,19 @@ Inline capabilities can be mixed with pre-defined capabilities. ```json title=src-tauri/tauri.conf.json { - "app": { - "security": { - "capabilities": [ - { - "identifier": "my-capability", - "description": "My application capability used for all windows", - "windows": ["*"], - "permissions": ["fs:default", "allow-home-read-extended"] - }, - "my-second-capability" - ] - } - } + "app": { + "security": { + "capabilities": [ + { + "identifier": "my-capability", + "description": "My application capability used for all windows", + "windows": ["*"], + "permissions": ["fs:default", "allow-home-read-extended"] + }, + "my-second-capability" + ] + } + } } ``` @@ -111,11 +111,11 @@ Note it enables permissions on plugins that are only available on desktop: ```json title="src-tauri/capabilities/desktop.json { - "$schema": "./schemas/desktop-schema.json", - "identifier": "desktop-capability", - "windows": ["main"], - "platforms": ["linux", "macOS", "windows"], - "permissions": ["global-shortcut:allow-register"] + "$schema": "./schemas/desktop-schema.json", + "identifier": "desktop-capability", + "windows": ["main"], + "platforms": ["linux", "macOS", "windows"], + "permissions": ["global-shortcut:allow-register"] } ``` @@ -124,15 +124,15 @@ Note it enables permissions on plugins that are only available on mobile: ```json title="src-tauri/capabilities/mobile.json { - "$schema": "./schemas/mobile-schema.json", - "identifier": "mobile-capability", - "windows": ["main"], - "platforms": ["iOS", "android"], - "permissions": [ - "nfc:allow-scan", - "biometric:allow-authenticate", - "barcode-scanner:allow-scan" - ] + "$schema": "./schemas/mobile-schema.json", + "identifier": "mobile-capability", + "windows": ["main"], + "platforms": ["iOS", "android"], + "permissions": [ + "nfc:allow-scan", + "biometric:allow-authenticate", + "barcode-scanner:allow-scan" + ] } ``` diff --git a/src/content/docs/security/index.mdx b/src/content/docs/security/index.mdx index 3f50900e2..68d536c46 100644 --- a/src/content/docs/security/index.mdx +++ b/src/content/docs/security/index.mdx @@ -48,10 +48,10 @@ in the capabilities configuration. Learn more about the individual components and boundary enforcement: - - - - + + + + Tauri allows developers to choose their own frontend stack and framework. @@ -59,11 +59,11 @@ This means that we cannot provide a hardening guide for every frontend stack of of choice, but Tauri provides generic features to control and contain the attack surface. - - + + ## Ecosystem @@ -78,13 +78,13 @@ can face and what we plan to improve or harden in the future, you can check out the following documents: - - - - + + + + ## Coordinated Disclosure diff --git a/src/content/docs/start/create-project.mdx b/src/content/docs/start/create-project.mdx index bcb3ffe6a..906fc1be2 100644 --- a/src/content/docs/start/create-project.mdx +++ b/src/content/docs/start/create-project.mdx @@ -42,16 +42,16 @@ After `create-tauri-app` has complete you can navigate into your project's folde import CommandTabs from '@components/CommandTabs.astro'; diff --git a/src/content/docs/start/frontend/index.mdx b/src/content/docs/start/frontend/index.mdx index 4e8df84a5..2960f9ec5 100644 --- a/src/content/docs/start/frontend/index.mdx +++ b/src/content/docs/start/frontend/index.mdx @@ -32,21 +32,21 @@ Below is a checklist of common scenarios needed to integrate a frontend with Tau For most projects we recommend [Vite](https://vitejs.dev/) for SPA frameworks such as React, Vue, Svelte, and Solid, but also for plain JavaScript or TypeScript projects. Most other guides listed here show how to use Meta-Frameworks as they are typically designed for SSR and therefore require special configuration. - - - - - - + + + + + + ## Rust - - - - + + + +
diff --git a/src/content/docs/start/frontend/nextjs.mdx b/src/content/docs/start/frontend/nextjs.mdx index 37afa9572..69d096840 100644 --- a/src/content/docs/start/frontend/nextjs.mdx +++ b/src/content/docs/start/frontend/nextjs.mdx @@ -19,9 +19,9 @@ Next.js is a React framework. Learn more about Next.js at https://nextjs.org. Th 1. Install `internal-ip` version 7 for mobile development. Version 8.0.0 does **not** work! 2. Update Tauri configuration: @@ -32,12 +32,12 @@ Next.js is a React framework. Learn more about Next.js at https://nextjs.org. Th ```json // tauri.conf.json { - "build": { - "beforeDevCommand": "npm run dev", - "beforeBuildCommand": "npm run build", - "devUrl": "http://localhost:3000", - "frontendDist": "../dist" - } + "build": { + "beforeDevCommand": "npm run dev", + "beforeBuildCommand": "npm run build", + "devUrl": "http://localhost:3000", + "frontendDist": "../dist" + } } ``` @@ -47,12 +47,12 @@ Next.js is a React framework. Learn more about Next.js at https://nextjs.org. Th ```json // tauri.conf.json { - "build": { - "beforeDevCommand": "yarn dev", - "beforeBuildCommand": "yarn generate", - "devUrl": "http://localhost:3000", - "frontendDist": "../dist" - } + "build": { + "beforeDevCommand": "yarn dev", + "beforeBuildCommand": "yarn generate", + "devUrl": "http://localhost:3000", + "frontendDist": "../dist" + } } ``` @@ -62,12 +62,12 @@ Next.js is a React framework. Learn more about Next.js at https://nextjs.org. Th ```json // tauri.conf.json { - "build": { - "beforeDevCommand": "pnpm dev", - "beforeBuildCommand": "pnpm generate", - "devUrl": "http://localhost:3000", - "frontendDist": "../dist" - } + "build": { + "beforeDevCommand": "pnpm dev", + "beforeBuildCommand": "pnpm generate", + "devUrl": "http://localhost:3000", + "frontendDist": "../dist" + } } ``` @@ -84,21 +84,21 @@ const isProd = process.env.NODE_ENV === 'production'; let internalHost = null; if (!isProd) { - const { internalIpV4 } = await import('internal-ip'); - internalHost = await internalIpV4(); + const { internalIpV4 } = await import('internal-ip'); + internalHost = await internalIpV4(); } const nextConfig = { - // Ensure Next.js uses SSG instead of SSR - // https://nextjs.org/docs/pages/building-your-application/deploying/static-exports - output: 'export', - // Note: This feature is required to use the Next.js Image component in SSG mode. - // See https://nextjs.org/docs/messages/export-image-api for different workarounds. - images: { - unoptimized: true, - }, - // Configure assetPrefix or else the server won't properly resolve your assets. - assetPrefix: isProd ? null : `http://${internalHost}:3000`, + // Ensure Next.js uses SSG instead of SSR + // https://nextjs.org/docs/pages/building-your-application/deploying/static-exports + output: 'export', + // Note: This feature is required to use the Next.js Image component in SSG mode. + // See https://nextjs.org/docs/messages/export-image-api for different workarounds. + images: { + unoptimized: true, + }, + // Configure assetPrefix or else the server won't properly resolve your assets. + assetPrefix: isProd ? null : `http://${internalHost}:3000`, }; export default nextConfig; diff --git a/src/content/docs/start/frontend/nuxt.mdx b/src/content/docs/start/frontend/nuxt.mdx index f1c4a2528..81a050d0e 100644 --- a/src/content/docs/start/frontend/nuxt.mdx +++ b/src/content/docs/start/frontend/nuxt.mdx @@ -25,12 +25,12 @@ Learn more about Nuxt at https://nuxt.com. This guide is accurate as of Nuxt 3.7 ```json // tauri.conf.json { - "build": { - "beforeDevCommand": "npm run dev", - "beforeBuildCommand": "npm run generate", - "devUrl": "http://localhost:3000", - "frontendDist": "../dist" - } + "build": { + "beforeDevCommand": "npm run dev", + "beforeBuildCommand": "npm run generate", + "devUrl": "http://localhost:3000", + "frontendDist": "../dist" + } } ``` @@ -40,12 +40,12 @@ Learn more about Nuxt at https://nuxt.com. This guide is accurate as of Nuxt 3.7 ```json // tauri.conf.json { - "build": { - "beforeDevCommand": "yarn dev", - "beforeBuildCommand": "yarn generate", - "devUrl": "http://localhost:3000", - "frontendDist": "../dist" - } + "build": { + "beforeDevCommand": "yarn dev", + "beforeBuildCommand": "yarn generate", + "devUrl": "http://localhost:3000", + "frontendDist": "../dist" + } } ``` @@ -55,12 +55,12 @@ Learn more about Nuxt at https://nuxt.com. This guide is accurate as of Nuxt 3.7 ```json // tauri.conf.json { - "build": { - "beforeDevCommand": "pnpm dev", - "beforeBuildCommand": "pnpm generate", - "devUrl": "http://localhost:3000", - "frontendDist": "../dist" - } + "build": { + "beforeDevCommand": "pnpm dev", + "beforeBuildCommand": "pnpm generate", + "devUrl": "http://localhost:3000", + "frontendDist": "../dist" + } } ``` @@ -72,31 +72,31 @@ Learn more about Nuxt at https://nuxt.com. This guide is accurate as of Nuxt 3.7 ```ts export default defineNuxtConfig({ - // (optional) Enable the Nuxt devtools - devtools: { enabled: true }, - // Enable SSG - ssr: false, - vite: { - // Better support for Tauri CLI output - clearScreen: false, - // Enable environment variables - // Additional environment variables can be found at - // https://tauri.app/2/reference/environment-variables/ - envPrefix: ['VITE_', 'TAURI_'], - server: { - // Tauri requires a consistent port - strictPort: true, - // Enables the development server to be discoverable by other devices for mobile development - host: '0.0.0.0', - hmr: { - // Use websocket for mobile hot reloading - protocol: 'ws', - // Make sure it's available on the network - host: '0.0.0.0', - // Use a specific port for hmr - port: 5183, - }, - }, - }, + // (optional) Enable the Nuxt devtools + devtools: { enabled: true }, + // Enable SSG + ssr: false, + vite: { + // Better support for Tauri CLI output + clearScreen: false, + // Enable environment variables + // Additional environment variables can be found at + // https://tauri.app/2/reference/environment-variables/ + envPrefix: ['VITE_', 'TAURI_'], + server: { + // Tauri requires a consistent port + strictPort: true, + // Enables the development server to be discoverable by other devices for mobile development + host: '0.0.0.0', + hmr: { + // Use websocket for mobile hot reloading + protocol: 'ws', + // Make sure it's available on the network + host: '0.0.0.0', + // Use a specific port for hmr + port: 5183, + }, + }, + }, }); ``` diff --git a/src/content/docs/start/frontend/sveltekit.mdx b/src/content/docs/start/frontend/sveltekit.mdx index 341625a1f..0456745ca 100644 --- a/src/content/docs/start/frontend/sveltekit.mdx +++ b/src/content/docs/start/frontend/sveltekit.mdx @@ -18,9 +18,9 @@ SvelteKit is a meta-framework for Svelte. Learn more about SvelteKit at https:// 1. Install `@sveltejs/adapter-static`: 2. Update Tauri configuration: @@ -31,12 +31,12 @@ SvelteKit is a meta-framework for Svelte. Learn more about SvelteKit at https:// ```json // tauri.conf.json { - "build": { - "beforeDevCommand": "npm run dev", - "beforeBuildCommand": "npm run build", - "devUrl": "http://localhost:5173", - "frontendDist": "../build" - } + "build": { + "beforeDevCommand": "npm run dev", + "beforeBuildCommand": "npm run build", + "devUrl": "http://localhost:5173", + "frontendDist": "../build" + } } ``` @@ -46,12 +46,12 @@ SvelteKit is a meta-framework for Svelte. Learn more about SvelteKit at https:// ```json // tauri.conf.json { - "build": { - "beforeDevCommand": "yarn dev", - "beforeBuildCommand": "yarn build", - "devUrl": "http://localhost:5173", - "frontendDist": "../build" - } + "build": { + "beforeDevCommand": "yarn dev", + "beforeBuildCommand": "yarn build", + "devUrl": "http://localhost:5173", + "frontendDist": "../build" + } } ``` @@ -61,12 +61,12 @@ SvelteKit is a meta-framework for Svelte. Learn more about SvelteKit at https:// ```json // tauri.conf.json { - "build": { - "beforeDevCommand": "pnpm dev", - "beforeBuildCommand": "pnpm build", - "devUrl": "http://localhost:5173", - "frontendDist": "../build" - } + "build": { + "beforeDevCommand": "pnpm dev", + "beforeBuildCommand": "pnpm build", + "devUrl": "http://localhost:5173", + "frontendDist": "../build" + } } ``` @@ -81,13 +81,13 @@ import { vitePreprocess } from '@sveltejs/vite-plugin-svelte'; /** @type {import('@sveltejs/kit').Config} */ const config = { - // Consult https://kit.svelte.dev/docs/integrations#preprocessors - // for more information about preprocessors - preprocess: vitePreprocess(), + // Consult https://kit.svelte.dev/docs/integrations#preprocessors + // for more information about preprocessors + preprocess: vitePreprocess(), - kit: { - adapter: adapter(), - }, + kit: { + adapter: adapter(), + }, }; export default config; diff --git a/src/content/docs/start/frontend/trunk.mdx b/src/content/docs/start/frontend/trunk.mdx index a72cc7b3e..f986bd8b8 100644 --- a/src/content/docs/start/frontend/trunk.mdx +++ b/src/content/docs/start/frontend/trunk.mdx @@ -19,15 +19,15 @@ Trunk is a WASM web application bundler for Rust. Learn more about Trunk at http ```json // tauri.conf.json { - "build": { - "beforeDevCommand": "trunk serve", - "beforeBuildCommand": "trunk build", - "devUrl": "http://localhost:8080", - "frontendDist": "../dist" - }, - "app": { - "withGlobalTauri": true - } + "build": { + "beforeDevCommand": "trunk serve", + "beforeBuildCommand": "trunk build", + "devUrl": "http://localhost:8080", + "frontendDist": "../dist" + }, + "app": { + "withGlobalTauri": true + } } ``` diff --git a/src/content/docs/start/migrate/from-tauri-1.mdx b/src/content/docs/start/migrate/from-tauri-1.mdx index bb102890c..83cbb71bf 100644 --- a/src/content/docs/start/migrate/from-tauri-1.mdx +++ b/src/content/docs/start/migrate/from-tauri-1.mdx @@ -53,13 +53,13 @@ fn main() { The Tauri v2 CLI includes a `migrate` command that automates most of the process and helps you finish the migration: @@ -234,9 +234,9 @@ fn main() { ```json // package.json { - "dependencies": { - "@tauri-apps/plugin-cli": "^2.0.0" - } + "dependencies": { + "@tauri-apps/plugin-cli": "^2.0.0" + } } ``` @@ -285,9 +285,9 @@ fn main() { ```json // package.json { - "dependencies": { - "@tauri-apps/plugin-clipboard-manager": "^2.0.0" - } + "dependencies": { + "@tauri-apps/plugin-clipboard-manager": "^2.0.0" + } } ``` @@ -343,21 +343,21 @@ fn main() { ```json // package.json { - "dependencies": { - "@tauri-apps/plugin-dialog": "^2.0.0" - } + "dependencies": { + "@tauri-apps/plugin-dialog": "^2.0.0" + } } ``` ```js import { save } from '@tauri-apps/plugin-dialog'; const filePath = await save({ - filters: [ - { - name: 'Image', - extensions: ['png', 'jpeg'], - }, - ], + filters: [ + { + name: 'Image', + extensions: ['png', 'jpeg'], + }, + ], }); ``` @@ -409,9 +409,9 @@ fn main() { ```json // package.json { - "dependencies": { - "@tauri-apps/plugin-fs": "^2.0.0" - } + "dependencies": { + "@tauri-apps/plugin-fs": "^2.0.0" + } } ``` @@ -467,16 +467,16 @@ fn main() { ```json // package.json { - "dependencies": { - "@tauri-apps/plugin-global-shortcut": "^2.0.0" - } + "dependencies": { + "@tauri-apps/plugin-global-shortcut": "^2.0.0" + } } ``` ```js import { register } from '@tauri-apps/plugin-global-shortcut'; await register('CommandOrControl+Shift+C', () => { - console.log('Shortcut triggered'); + console.log('Shortcut triggered'); }); ``` @@ -532,16 +532,16 @@ fn main() { ```json // package.json { - "dependencies": { - "@tauri-apps/plugin-http": "^2.0.0" - } + "dependencies": { + "@tauri-apps/plugin-http": "^2.0.0" + } } ``` ```js import { fetch } from '@tauri-apps/plugin-http'; const response = await fetch( - 'https://raw.githubusercontent.com/tauri-apps/tauri/dev/package.json' + 'https://raw.githubusercontent.com/tauri-apps/tauri/dev/package.json' ); ``` @@ -598,9 +598,9 @@ fn main() { ```json // package.json { - "dependencies": { - "@tauri-apps/plugin-notification": "^2.0.0" - } + "dependencies": { + "@tauri-apps/plugin-notification": "^2.0.0" + } } ``` @@ -776,9 +776,9 @@ fn main() { ```json // package.json { - "dependencies": { - "@tauri-apps/plugin-os": "^2.0.0" - } + "dependencies": { + "@tauri-apps/plugin-os": "^2.0.0" + } } ``` @@ -831,9 +831,9 @@ fn main() { ```json // package.json { - "dependencies": { - "@tauri-apps/plugin-process": "^2.0.0" - } + "dependencies": { + "@tauri-apps/plugin-process": "^2.0.0" + } } ``` @@ -890,9 +890,9 @@ fn main() { ```json // package.json { - "dependencies": { - "@tauri-apps/plugin-shell": "^2.0.0" - } + "dependencies": { + "@tauri-apps/plugin-shell": "^2.0.0" + } } ``` @@ -1073,9 +1073,9 @@ fn main() { ```json // package.json { - "dependencies": { - "@tauri-apps/plugin-updater": "^2.0.0" - } + "dependencies": { + "@tauri-apps/plugin-updater": "^2.0.0" + } } ``` @@ -1085,11 +1085,11 @@ import { relaunch } from '@tauri-apps/plugin-process'; const update = await check(); if (update?.available) { - console.log(`Update to ${update.version} available! Date: ${update.date}`); - console.log(`Release notes: ${update.body}`); - await update.downloadAndInstall(); - // requires the `process` plugin - await relaunch(); + console.log(`Update to ${update.version} available! Date: ${update.date}`); + console.log(`Release notes: ${update.body}`); + await update.downloadAndInstall(); + // requires the `process` plugin + await relaunch(); } ``` diff --git a/src/content/docs/start/migrate/index.mdx b/src/content/docs/start/migrate/index.mdx index 60906ffbe..ef4410e32 100644 --- a/src/content/docs/start/migrate/index.mdx +++ b/src/content/docs/start/migrate/index.mdx @@ -13,7 +13,7 @@ Learn about common scenarios and steps to upgrade from Tauri 1.0 or migrate from import { LinkCard, CardGrid } from '@astrojs/starlight/components'; - - - + + + diff --git a/src/content/docs/zh-cn/develop/Debug/application.mdx b/src/content/docs/zh-cn/develop/Debug/application.mdx index 7b57641b9..38dd24346 100644 --- a/src/content/docs/zh-cn/develop/Debug/application.mdx +++ b/src/content/docs/zh-cn/develop/Debug/application.mdx @@ -78,10 +78,10 @@ tauri::Builder::default() 要创建调试构建,请运行 `tauri build --debug` 命令. 与正常的构建和开发过程一样,首次运行此命令需要一些时间,但在后续运行中速度显著提高。 diff --git a/src/content/docs/zh-cn/develop/Debug/index.mdx b/src/content/docs/zh-cn/develop/Debug/index.mdx index ef793fece..4aef84297 100644 --- a/src/content/docs/zh-cn/develop/Debug/index.mdx +++ b/src/content/docs/zh-cn/develop/Debug/index.mdx @@ -6,7 +6,7 @@ description: 调试工作流程的技巧和窍门 import { LinkCard, CardGrid } from '@astrojs/starlight/components'; - - - + + + diff --git a/src/content/docs/zh-cn/develop/Debug/vs-code.mdx b/src/content/docs/zh-cn/develop/Debug/vs-code.mdx index c0c1fb944..badc88d12 100644 --- a/src/content/docs/zh-cn/develop/Debug/vs-code.mdx +++ b/src/content/docs/zh-cn/develop/Debug/vs-code.mdx @@ -19,36 +19,36 @@ title: 在 VS Code 中调试 ```json title=".vscode/launch.json" { - // Use IntelliSense to learn about possible attributes. - // Hover to view descriptions of existing attributes. - // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 - "version": "0.2.0", - "configurations": [ - { - "type": "lldb", - "request": "launch", - "name": "Tauri Development Debug", - "cargo": { - "args": [ - "build", - "--manifest-path=./src-tauri/Cargo.toml", - "--no-default-features" - ] - }, - // task for the `beforeDevCommand` if used, must be configured in `.vscode/tasks.json` - "preLaunchTask": "ui:dev" - }, - { - "type": "lldb", - "request": "launch", - "name": "Tauri Production Debug", - "cargo": { - "args": ["build", "--release", "--manifest-path=./src-tauri/Cargo.toml"] - }, - // task for the `beforeBuildCommand` if used, must be configured in `.vscode/tasks.json` - "preLaunchTask": "ui:build" - } - ] + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "type": "lldb", + "request": "launch", + "name": "Tauri Development Debug", + "cargo": { + "args": [ + "build", + "--manifest-path=./src-tauri/Cargo.toml", + "--no-default-features" + ] + }, + // task for the `beforeDevCommand` if used, must be configured in `.vscode/tasks.json` + "preLaunchTask": "ui:dev" + }, + { + "type": "lldb", + "request": "launch", + "name": "Tauri Production Debug", + "cargo": { + "args": ["build", "--release", "--manifest-path=./src-tauri/Cargo.toml"] + }, + // task for the `beforeBuildCommand` if used, must be configured in `.vscode/tasks.json` + "preLaunchTask": "ui:build" + } + ] } ``` @@ -58,29 +58,29 @@ title: 在 VS Code 中调试 ```json title=".vscode/tasks.json" { - // See https://go.microsoft.com/fwlink/?LinkId=733558 - // for the documentation about the tasks.json format - "version": "2.0.0", - "tasks": [ - { - "label": "ui:dev", - "type": "shell", - // `dev` keeps running in the background - // ideally you should also configure a `problemMatcher` - // see https://code.visualstudio.com/docs/editor/tasks#_can-a-background-task-be-used-as-a-prelaunchtask-in-launchjson - "isBackground": true, - // change this to your `beforeDevCommand`: - "command": "yarn", - "args": ["dev"] - }, - { - "label": "ui:build", - "type": "shell", - // change this to your `beforeBuildCommand`: - "command": "yarn", - "args": ["build"] - } - ] + // See https://go.microsoft.com/fwlink/?LinkId=733558 + // for the documentation about the tasks.json format + "version": "2.0.0", + "tasks": [ + { + "label": "ui:dev", + "type": "shell", + // `dev` keeps running in the background + // ideally you should also configure a `problemMatcher` + // see https://code.visualstudio.com/docs/editor/tasks#_can-a-background-task-be-used-as-a-prelaunchtask-in-launchjson + "isBackground": true, + // change this to your `beforeDevCommand`: + "command": "yarn", + "args": ["dev"] + }, + { + "label": "ui:build", + "type": "shell", + // change this to your `beforeBuildCommand`: + "command": "yarn", + "args": ["build"] + } + ] } ``` diff --git a/src/content/docs/zh-cn/develop/Plugins/index.mdx b/src/content/docs/zh-cn/develop/Plugins/index.mdx index d85b3b74f..305543568 100644 --- a/src/content/docs/zh-cn/develop/Plugins/index.mdx +++ b/src/content/docs/zh-cn/develop/Plugins/index.mdx @@ -40,10 +40,10 @@ Tauri 插件具有一个前缀(Rust 包使用 `tauri-plugin-` 前缀,NPM 包 要引导创建一个新的插件项目,请运行 `plugin init`。如果不需要相应的 NPM 程序包,请使用 `--no-api` 命令行标志。 这会初始化插件,并且生成如下所示的代码: diff --git a/src/content/docs/zh-cn/develop/Tests/index.mdx b/src/content/docs/zh-cn/develop/Tests/index.mdx index cb5240a97..e7ceb24f0 100644 --- a/src/content/docs/zh-cn/develop/Tests/index.mdx +++ b/src/content/docs/zh-cn/develop/Tests/index.mdx @@ -8,6 +8,6 @@ Tauri 运行时内外测试技术 import { LinkCard, CardGrid } from '@astrojs/starlight/components'; - - + + diff --git a/src/content/docs/zh-cn/develop/Tests/webdriver/example/selenium.mdx b/src/content/docs/zh-cn/develop/Tests/webdriver/example/selenium.mdx index dade448ee..80b6cada3 100644 --- a/src/content/docs/zh-cn/develop/Tests/webdriver/example/selenium.mdx +++ b/src/content/docs/zh-cn/develop/Tests/webdriver/example/selenium.mdx @@ -28,17 +28,17 @@ import CommandTabs from '@components/CommandTabs.astro'; ```json { - "name": "selenium", - "version": "1.0.0", - "private": true, - "scripts": { - "test": "mocha" - }, - "dependencies": { - "chai": "^4.3.4", - "mocha": "^9.0.3", - "selenium-webdriver": "^4.0.0-beta.4" - } + "name": "selenium", + "version": "1.0.0", + "private": true, + "scripts": { + "test": "mocha" + }, + "dependencies": { + "chai": "^4.3.4", + "mocha": "^9.0.3", + "selenium-webdriver": "^4.0.0-beta.4" + } } ``` @@ -50,8 +50,8 @@ import CommandTabs from '@components/CommandTabs.astro'; 如果你想从头安装依赖关系,只需运行以下命令。 我建议将 `"test": "mocha"` 命令添加到 `package.json` 的 `"scripts"` 中,这样运行 Mocha 只需要执行 @@ -75,13 +75,13 @@ const { Builder, By, Capabilities } = require('selenium-webdriver'); // create the path to the expected application binary const application = path.resolve( - __dirname, - '..', - '..', - '..', - 'target', - 'release', - 'hello-tauri-webdriver' + __dirname, + '..', + '..', + '..', + 'target', + 'release', + 'hello-tauri-webdriver' ); // keep track of the webdriver instance we create @@ -91,61 +91,61 @@ let driver; let tauriDriver; before(async function () { - // set timeout to 2 minutes to allow the program to build if it needs to - this.timeout(120000); + // set timeout to 2 minutes to allow the program to build if it needs to + this.timeout(120000); - // ensure the program has been built - spawnSync('cargo', ['build', '--release']); + // ensure the program has been built + spawnSync('cargo', ['build', '--release']); - // start tauri-driver - tauriDriver = spawn( - path.resolve(os.homedir(), '.cargo', 'bin', 'tauri-driver'), - [], - { stdio: [null, process.stdout, process.stderr] } - ); + // start tauri-driver + tauriDriver = spawn( + path.resolve(os.homedir(), '.cargo', 'bin', 'tauri-driver'), + [], + { stdio: [null, process.stdout, process.stderr] } + ); - const capabilities = new Capabilities(); - capabilities.set('tauri:options', { application }); - capabilities.setBrowserName('wry'); + const capabilities = new Capabilities(); + capabilities.set('tauri:options', { application }); + capabilities.setBrowserName('wry'); - // start the webdriver client - driver = await new Builder() - .withCapabilities(capabilities) - .usingServer('http://127.0.0.1:4444/') - .build(); + // start the webdriver client + driver = await new Builder() + .withCapabilities(capabilities) + .usingServer('http://127.0.0.1:4444/') + .build(); }); after(async function () { - // stop the webdriver session - await driver.quit(); + // stop the webdriver session + await driver.quit(); - // kill the tauri-driver process - tauriDriver.kill(); + // kill the tauri-driver process + tauriDriver.kill(); }); describe('Hello Tauri', () => { - it('should be cordial', async () => { - const text = await driver.findElement(By.css('body > h1')).getText(); - expect(text).to.match(/^[hH]ello/); - }); + it('should be cordial', async () => { + const text = await driver.findElement(By.css('body > h1')).getText(); + expect(text).to.match(/^[hH]ello/); + }); - it('should be excited', async () => { - const text = await driver.findElement(By.css('body > h1')).getText(); - expect(text).to.match(/!$/); - }); + it('should be excited', async () => { + const text = await driver.findElement(By.css('body > h1')).getText(); + expect(text).to.match(/!$/); + }); - it('should be easy on the eyes', async () => { - // selenium returns color css values as rgb(r, g, b) - const text = await driver - .findElement(By.css('body')) - .getCssValue('background-color'); + it('should be easy on the eyes', async () => { + // selenium returns color css values as rgb(r, g, b) + const text = await driver + .findElement(By.css('body')) + .getCssValue('background-color'); - const rgb = text.match(/^rgb\((?\d+), (?\d+), (?\d+)\)$/).groups; - expect(rgb).to.have.all.keys('r', 'g', 'b'); + const rgb = text.match(/^rgb\((?\d+), (?\d+), (?\d+)\)$/).groups; + expect(rgb).to.have.all.keys('r', 'g', 'b'); - const luma = 0.2126 * rgb.r + 0.7152 * rgb.g + 0.0722 * rgb.b; - expect(luma).to.be.lessThan(100); - }); + const luma = 0.2126 * rgb.r + 0.7152 * rgb.g + 0.0722 * rgb.b; + expect(luma).to.be.lessThan(100); + }); }); ``` diff --git a/src/content/docs/zh-cn/develop/Tests/webdriver/index.mdx b/src/content/docs/zh-cn/develop/Tests/webdriver/index.mdx index c8b559fdb..ab25dace2 100644 --- a/src/content/docs/zh-cn/develop/Tests/webdriver/index.mdx +++ b/src/content/docs/zh-cn/develop/Tests/webdriver/index.mdx @@ -40,12 +40,12 @@ Make sure to grab the version of [Microsoft Edge Driver][] that matches your Win import { LinkCard, CardGrid } from '@astrojs/starlight/components'; - - - + + + ## 持续集成 (CI) diff --git a/src/content/docs/zh-cn/develop/development-cycle.mdx b/src/content/docs/zh-cn/develop/development-cycle.mdx index bbe0c1fe5..3703aa3b2 100644 --- a/src/content/docs/zh-cn/develop/development-cycle.mdx +++ b/src/content/docs/zh-cn/develop/development-cycle.mdx @@ -17,10 +17,10 @@ import CommandTabs from '@components/CommandTabs.astro'; ### 2. 启动 Tauri 开发窗口 第一次运行此命令时,Rust 包管理器需要几分钟来下载和构建所有必需的包。 由于它们是缓存的,因此后续构建要快得多,因为只有新的代码需要重新构建。 diff --git a/src/content/docs/zh-cn/develop/index.mdx b/src/content/docs/zh-cn/develop/index.mdx index 5446c6548..2f950e7a3 100644 --- a/src/content/docs/zh-cn/develop/index.mdx +++ b/src/content/docs/zh-cn/develop/index.mdx @@ -6,9 +6,9 @@ description: C使用 Tauri 开发的核心概念 import { LinkCard, CardGrid } from '@astrojs/starlight/components'; - - + + diff --git a/src/content/docs/zh-cn/develop/updating-dependencies.mdx b/src/content/docs/zh-cn/develop/updating-dependencies.mdx index 3e588e198..a1b76b601 100644 --- a/src/content/docs/zh-cn/develop/updating-dependencies.mdx +++ b/src/content/docs/zh-cn/develop/updating-dependencies.mdx @@ -9,25 +9,25 @@ import CommandTabs from '@components/CommandTabs.astro'; 如果您正在使用 `tauri` 包: 您还可以通过以下方式检测最新版本的 Tauri 在命令行上: 或者,如果您正在使用 `vue-cli-plugin-tauri` 方法: ## 更新 Cargo 包 diff --git a/src/content/docs/zh-cn/index.mdx b/src/content/docs/zh-cn/index.mdx index c1a6cd66c..766580465 100644 --- a/src/content/docs/zh-cn/index.mdx +++ b/src/content/docs/zh-cn/index.mdx @@ -24,30 +24,30 @@ hero: import { Card, CardGrid } from '@astrojs/starlight/components';
- -
-
+ +
+
- - 将你现有的网络技术栈带到 Tauri 或开始新的项目。 Tauri - 支持任何前端框架,所以你不需要改变你的技术栈。 - - - 使用单个代码库为 Linux、macOS、Windows、Android 和 iOS 构建你的应用程序。 - - - 用 JavaScript 编写前端,用 Rust 编写应用程序逻辑,并使用 Swift 和 Kotlin - 在系统中深入集成。 - - - Tauri 团队的首要目标,推动我们的首要任务和最大的创新。 - - - 使用操作系统的本地网页渲染器,Tauri 应用的体积可以达到最小 600KB。 - - - 以性能和安全性为中心,Rust 是下一代应用程序的语言。 - + + 将你现有的网络技术栈带到 Tauri 或开始新的项目。 Tauri + 支持任何前端框架,所以你不需要改变你的技术栈。 + + + 使用单个代码库为 Linux、macOS、Windows、Android 和 iOS 构建你的应用程序。 + + + 用 JavaScript 编写前端,用 Rust 编写应用程序逻辑,并使用 Swift 和 Kotlin + 在系统中深入集成。 + + + Tauri 团队的首要目标,推动我们的首要任务和最大的创新。 + + + 使用操作系统的本地网页渲染器,Tauri 应用的体积可以达到最小 600KB。 + + + 以性能和安全性为中心,Rust 是下一代应用程序的语言。 + diff --git a/src/content/docs/zh-cn/plugin/autostart.mdx b/src/content/docs/zh-cn/plugin/autostart.mdx index 45e5079cd..c0cf8fc2a 100644 --- a/src/content/docs/zh-cn/plugin/autostart.mdx +++ b/src/content/docs/zh-cn/plugin/autostart.mdx @@ -29,10 +29,10 @@ import CommandTabs from '@components/CommandTabs.astro'; {' '} diff --git a/src/content/docs/zh-cn/plugin/barcode-scanner.mdx b/src/content/docs/zh-cn/plugin/barcode-scanner.mdx index c43f38bcf..4955a880e 100644 --- a/src/content/docs/zh-cn/plugin/barcode-scanner.mdx +++ b/src/content/docs/zh-cn/plugin/barcode-scanner.mdx @@ -34,10 +34,10 @@ _这个插件要求 Rust 版本至少是 **1.64**_ {' '} @@ -89,11 +89,11 @@ scan({ windowed: true, formats: [Format.QRCode] }); ```json title="src-tauri/capabilities/mobile.json" { - "$schema": "./schemas/mobile-schema.json", - "identifier": "mobile-capability", - "windows": ["main"], - "platforms": ["iOS", "android"], - "permissions": ["barcode-scanner:allow-scan", "barcode-scanner:allow-cancel"] + "$schema": "./schemas/mobile-schema.json", + "identifier": "mobile-capability", + "windows": ["main"], + "platforms": ["iOS", "android"], + "permissions": ["barcode-scanner:allow-scan", "barcode-scanner:allow-cancel"] } ``` diff --git a/src/content/docs/zh-cn/plugin/cli.mdx b/src/content/docs/zh-cn/plugin/cli.mdx index 82e5487be..713381a0d 100644 --- a/src/content/docs/zh-cn/plugin/cli.mdx +++ b/src/content/docs/zh-cn/plugin/cli.mdx @@ -31,10 +31,10 @@ _这个插件要求 Rust 版本至少是 **1.75**_ {' '} @@ -78,33 +78,33 @@ fn run() { ```json title="src-tauri/tauri.conf.json" { - "plugins": { - "cli": { - "description": "Tauri CLI Plugin Example", - "args": [ - { - "short": "v", - "name": "verbose", - "description": "Verbosity level" - } - ], - "subcommands": { - "run": { - "description": "Run the application", - "args": [ - { - "name": "debug", - "description": "Run application in debug mode" - }, - { - "name": "release", - "description": "Run application in release mode" - } - ] - } - } - } - } + "plugins": { + "cli": { + "description": "Tauri CLI Plugin Example", + "args": [ + { + "short": "v", + "name": "verbose", + "description": "Verbosity level" + } + ], + "subcommands": { + "run": { + "description": "Run the application", + "args": [ + { + "name": "debug", + "description": "Run application in debug mode" + }, + { + "name": "release", + "description": "Run application in release mode" + } + ] + } + } + } + } } ``` @@ -126,18 +126,18 @@ fn run() { ```json title="src-tauri/tauri.conf.json" { - "args": [ - { - "name": "source", - "index": 1, - "takesValue": true - }, - { - "name": "destination", - "index": 2, - "takesValue": true - } - ] + "args": [ + { + "name": "source", + "index": 1, + "takesValue": true + }, + { + "name": "destination", + "index": 2, + "takesValue": true + } + ] } ``` @@ -149,15 +149,15 @@ fn run() { ```json title="tauri-src/tauri.conf.json" { - "args": [ - { - "name": "type", - "short": "t", - "takesValue": true, - "multiple": true, - "possibleValues": ["foo", "bar"] - } - ] + "args": [ + { + "name": "type", + "short": "t", + "takesValue": true, + "multiple": true, + "possibleValues": ["foo", "bar"] + } + ] } ``` @@ -169,12 +169,12 @@ fn run() { ```json title="tauri-src/tauri.conf.json" { - "args": [ - { - "name": "verbose", - "short": "v" - } - ] + "args": [ + { + "name": "verbose", + "short": "v" + } + ] } ``` @@ -214,14 +214,14 @@ import { getMatches } from '@tauri-apps/plugin-cli'; const matches = await getMatches(); if (matches.subcommand?.name === 'run') { - // `./your-app run $ARGS` was executed - const args = matches.subcommand.matches.args; - if (args.debug?.value === true) { - // `./your-app run --debug` was executed - } - if (args.release?.value === true) { - // `./your-app run --release` was executed - } + // `./your-app run $ARGS` was executed + const args = matches.subcommand.matches.args; + if (args.debug?.value === true) { + // `./your-app run --debug` was executed + } + if (args.release?.value === true) { + // `./your-app run --release` was executed + } } ``` @@ -264,11 +264,11 @@ fn run() { ```json title="src-tauri/capabilities/main.json" ins={6} { - "$schema": "./schemas/desktop-schema.json", - "identifier": "main-capability", - "description": "Capability for the main window", - "windows": ["main"], - "permissions": ["cli:default"] + "$schema": "./schemas/desktop-schema.json", + "identifier": "main-capability", + "description": "Capability for the main window", + "windows": ["main"], + "permissions": ["cli:default"] } ``` diff --git a/src/content/docs/zh-cn/plugin/commands.mdx b/src/content/docs/zh-cn/plugin/commands.mdx index 61f524823..190cdf6b6 100644 --- a/src/content/docs/zh-cn/plugin/commands.mdx +++ b/src/content/docs/zh-cn/plugin/commands.mdx @@ -114,8 +114,8 @@ fn my_custom_command() -> Result { ```js invoke('my_custom_command') - .then((message) => console.log(message)) - .catch((error) => console.error(error)); + .then((message) => console.log(message)) + .catch((error) => console.error(error)); ``` 如上所述,从命令返回的所有内容都必须实现 [`serde::Serialize`],包括错误。 @@ -228,7 +228,7 @@ async fn my_custom_command(value: &str) -> Result { ```js invoke('my_custom_command', { value: 'Hello, Async!' }).then(() => - console.log('Completed!') + console.log('Completed!') ); ``` @@ -375,12 +375,12 @@ import { invoke } from '@tauri-apps/api/core'; // 从 JavaScript 调用 invoke('my_custom_command', { - number: 42, + number: 42, }) - .then((res) => - console.log(`Message: ${res.message}, Other Val: ${res.other_val}`) - ) - .catch((e) => console.error(e)); + .then((res) => + console.log(`Message: ${res.message}, Other Val: ${res.other_val}`) + ) + .catch((e) => console.error(e)); ``` [`async_runtime::spawn`]: https://docs.rs/tauri/2.0.0-beta/tauri/async_runtime/fn.spawn.html diff --git a/src/content/docs/zh-cn/plugin/deep-linking.mdx b/src/content/docs/zh-cn/plugin/deep-linking.mdx index 77330392d..85a135bd2 100644 --- a/src/content/docs/zh-cn/plugin/deep-linking.mdx +++ b/src/content/docs/zh-cn/plugin/deep-linking.mdx @@ -34,10 +34,10 @@ _这个插件要求 Rust 版本至少是 **1.75**_ {' '} @@ -98,19 +98,19 @@ fn run() { ```json title=".well-known/apple-app-site-association" { - "applinks": { - "details": [ - { - "appIDs": ["$DEVELOPMENT_TEAM_ID.$APP_BUNDLE_ID"], - "components": [ - { - "/": "/open/*", - "comment": "Matches any URL whose path starts with /open/" - } - ] - } - ] - } + "applinks": { + "details": [ + { + "appIDs": ["$DEVELOPMENT_TEAM_ID.$APP_BUNDLE_ID"], + "components": [ + { + "/": "/open/*", + "comment": "Matches any URL whose path starts with /open/" + } + ] + } + ] + } } ``` @@ -142,14 +142,14 @@ fn run() { ```json title="tauri.conf.json" { - "plugins": { - "deep-link": { - "domains": [ - { "host": "your.website.com", "pathPrefix": ["/open"] }, - { "host": "another.site.br" } - ] - } - } + "plugins": { + "deep-link": { + "domains": [ + { "host": "your.website.com", "pathPrefix": ["/open"] }, + { "host": "another.site.br" } + ] + } + } } ``` @@ -164,7 +164,7 @@ deep-link 有 JavaScript 和 Rust 两种版本。 import { onOpenUrl } from '@tauri-apps/plugin-deep-link'; await onOpenUrl((urls) => { - console.log('deep link:', urls); + console.log('deep link:', urls); }); ``` @@ -201,15 +201,15 @@ fn run() { ```json title="src-tauri/capabilities/main.json" ins={9} { - "$schema": "./schemas/mobile-schema.json", - "identifier": "mobile-capability", - "windows": ["main"], - "platforms": ["iOS", "android"], - "permissions": [ - // 通常需要 event:default 来监听 deep-link 事件 - "event:default", - "deep-link:default" - ] + "$schema": "./schemas/mobile-schema.json", + "identifier": "mobile-capability", + "windows": ["main"], + "platforms": ["iOS", "android"], + "permissions": [ + // 通常需要 event:default 来监听 deep-link 事件 + "event:default", + "deep-link:default" + ] } ``` diff --git a/src/content/docs/zh-cn/plugin/dialog.mdx b/src/content/docs/zh-cn/plugin/dialog.mdx index 2aba20763..ecda40263 100644 --- a/src/content/docs/zh-cn/plugin/dialog.mdx +++ b/src/content/docs/zh-cn/plugin/dialog.mdx @@ -93,8 +93,8 @@ import { ask } from '@tauri-apps/plugin-dialog'; // 创建 Yes/No 对话框 const answer = await ask('This action cannot be reverted. Are you sure?', { - title: 'Tauri', - type: 'warning', + title: 'Tauri', + type: 'warning', }); console.log(answer); @@ -112,8 +112,8 @@ import { confirm } from '@tauri-apps/plugin-dialog'; // Creates a confirmation Ok/Cancel dialog const confirmation = await confirm( - 'This action cannot be reverted. Are you sure?', - { title: 'Tauri', type: 'warning' } + 'This action cannot be reverted. Are you sure?', + { title: 'Tauri', type: 'warning' } ); console.log(confirmation); @@ -146,8 +146,8 @@ import { open } from '@tauri-apps/plugin-dialog'; // Open a dialog const file = await open({ - multiple: false, - directory: false, + multiple: false, + directory: false, }); console.log(file); // Prints file path and name to the console @@ -163,12 +163,12 @@ console.log(file); import { save } from '@tauri-apps/plugin-dialog'; // Prompt to save a 'My Filter' with extension .png or .jpeg const path = await save({ - filters: [ - { - name: 'My Filter', - extensions: ['png', 'jpeg'], - }, - ], + filters: [ + { + name: 'My Filter', + extensions: ['png', 'jpeg'], + }, + ], }); console.log(path); // Prints the chosen path diff --git a/src/content/docs/zh-cn/plugin/file-system.mdx b/src/content/docs/zh-cn/plugin/file-system.mdx index 6ee204e64..230b9e811 100644 --- a/src/content/docs/zh-cn/plugin/file-system.mdx +++ b/src/content/docs/zh-cn/plugin/file-system.mdx @@ -31,10 +31,10 @@ _这个插件要求 Rust 版本至少是 **1.75**_ { ' ' } @@ -125,17 +125,17 @@ fn run() { ```json title="src-tauri/capabilities/main.json" ins={7-11} { - "$schema": "../gen/schemas/desktop-schema.json", - "identifier": "main-capability", - "description": "Capability for the main window", - "windows": ["main"], - "permissions": [ - "fs:default", - { - "identifier": "fs:allow-exists", - "allow": [{ "path": "$APPDATA/*" }] - } - ] + "$schema": "../gen/schemas/desktop-schema.json", + "identifier": "main-capability", + "description": "Capability for the main window", + "windows": ["main"], + "permissions": [ + "fs:default", + { + "identifier": "fs:allow-exists", + "allow": [{ "path": "$APPDATA/*" }] + } + ] } ``` @@ -456,16 +456,16 @@ fn run() { ```json title="src-tauri/capabilities/main.json" {7-10} { - "$schema": "../gen/schemas/desktop-schema.json", - "identifier": "main-capability", - "description": "Capability for the main window", - "windows": ["main"], - "permissions": [ - { - "identifier": "fs:scope", - "allow": [{ "path": "$APPDATA" }, { "path": "$APPDATA/**" }] - } - ] + "$schema": "../gen/schemas/desktop-schema.json", + "identifier": "main-capability", + "description": "Capability for the main window", + "windows": ["main"], + "permissions": [ + { + "identifier": "fs:scope", + "allow": [{ "path": "$APPDATA" }, { "path": "$APPDATA/**" }] + } + ] } ``` @@ -473,19 +473,19 @@ fn run() { ```json title="src-tauri/capabilities/main.json" {7-14} { - "$schema": "../gen/schemas/desktop-schema.json", - "identifier": "main-capability", - "description": "Capability for the main window", - "windows": ["main"], - "permissions": [ - { - "identifier": "fs:allow-rename", - "allow": [{ "path": "$HOME/**" }] - }, - { - "identifier": "fs:allow-exists", - "allow": [{ "path": "$APPDATA/*" }] - } - ] + "$schema": "../gen/schemas/desktop-schema.json", + "identifier": "main-capability", + "description": "Capability for the main window", + "windows": ["main"], + "permissions": [ + { + "identifier": "fs:allow-rename", + "allow": [{ "path": "$HOME/**" }] + }, + { + "identifier": "fs:allow-exists", + "allow": [{ "path": "$APPDATA/*" }] + } + ] } ``` diff --git a/src/content/docs/zh-cn/plugin/global-shortcut.mdx b/src/content/docs/zh-cn/plugin/global-shortcut.mdx index 6be5fa83d..68c70284b 100644 --- a/src/content/docs/zh-cn/plugin/global-shortcut.mdx +++ b/src/content/docs/zh-cn/plugin/global-shortcut.mdx @@ -31,10 +31,10 @@ _这个插件要求 Rust 版本至少是 **1.75**_ { ' ' } @@ -82,7 +82,7 @@ fn run() { import { register } from '@tauri-apps/plugin-global-shortcut'; await register('CommandOrControl+Shift+C', () => { - console.log('Shortcut triggered'); + console.log('Shortcut triggered'); }); ``` @@ -128,15 +128,15 @@ fn run() { ```json title="src-tauri/capabilities/main.json" ins={7-9} { - "$schema": "./schemas/desktop-schema.json", - "identifier": "main-capability", - "description": "Capability for the main window", - "windows": ["main"], - "permissions": [ - "global-shortcut:allow-is-registered", - "global-shortcut:allow-register", - "global-shortcut:allow-unregister" - ] + "$schema": "./schemas/desktop-schema.json", + "identifier": "main-capability", + "description": "Capability for the main window", + "windows": ["main"], + "permissions": [ + "global-shortcut:allow-is-registered", + "global-shortcut:allow-register", + "global-shortcut:allow-unregister" + ] } ``` diff --git a/src/content/docs/zh-cn/plugin/http-client.mdx b/src/content/docs/zh-cn/plugin/http-client.mdx index 4b3ff953c..733f79b01 100644 --- a/src/content/docs/zh-cn/plugin/http-client.mdx +++ b/src/content/docs/zh-cn/plugin/http-client.mdx @@ -67,11 +67,11 @@ http 插件既有 JavaScript API 版本,也有 Rust [reqwest](https://docs.rs/ ```json //tauri.conf.json { - "plugins": { - "http": { - "scope": ["http://my.api.host/*"] - } - } + "plugins": { + "http": { + "scope": ["http://my.api.host/*"] + } + } } ``` @@ -82,7 +82,7 @@ import { fetch } from '@tauri-apps/plugin-http'; // Send a GET request const response = await fetch('http://my.api.host/data.json', { - method: 'GET', + method: 'GET', }); console.log(response.status); // e.g. 200 console.log(response.statusText); // e.g. "OK" diff --git a/src/content/docs/zh-cn/plugin/index.mdx b/src/content/docs/zh-cn/plugin/index.mdx index e66998940..cdf6f4c2f 100644 --- a/src/content/docs/zh-cn/plugin/index.mdx +++ b/src/content/docs/zh-cn/plugin/index.mdx @@ -15,16 +15,16 @@ Tauri 考虑到了可扩展性。在此页面上,你可以找到: - **[社区资源](#社区资源)**:更多由 Tauri 社区创作的插件和秘诀 - ## 特性 - - ## 社区资源 - - ### 插件 - - ### 集成 - + ## 特性 + + ## 社区资源 + + ### 插件 + + ### 集成 + diff --git a/src/content/docs/zh-cn/plugin/logging.mdx b/src/content/docs/zh-cn/plugin/logging.mdx index 12cd09f73..a26e94951 100644 --- a/src/content/docs/zh-cn/plugin/logging.mdx +++ b/src/content/docs/zh-cn/plugin/logging.mdx @@ -32,10 +32,10 @@ _这个插件要求 Rust 版本至少是 **1.75**_ { ' ' } @@ -120,11 +120,11 @@ detach(); ```json title="src-tauri/capabilities/main.json" ins={6} { - "$schema": "./schemas/desktop-schema.json", - "identifier": "main-capability", - "description": "Capability for the main window", - "windows": ["main"], - "permissions": ["log:default"] + "$schema": "./schemas/desktop-schema.json", + "identifier": "main-capability", + "description": "Capability for the main window", + "windows": ["main"], + "permissions": ["log:default"] } ``` diff --git a/src/content/docs/zh-cn/plugin/notification.mdx b/src/content/docs/zh-cn/plugin/notification.mdx index b56143d31..c122500d6 100644 --- a/src/content/docs/zh-cn/plugin/notification.mdx +++ b/src/content/docs/zh-cn/plugin/notification.mdx @@ -86,9 +86,9 @@ import Stub from '@components/Stub.astro'; ```js import { - isPermissionGranted, - requestPermission, - sendNotification, + isPermissionGranted, + requestPermission, + sendNotification, } from '@tauri-apps/plugin-notification'; // 你有发送通知的权限吗? @@ -96,13 +96,13 @@ let permissionGranted = await isPermissionGranted(); // 如果没有,我们需要请求它 if (!permissionGranted) { - const permission = await requestPermission(); - permissionGranted = permission === 'granted'; + const permission = await requestPermission(); + permissionGranted = permission === 'granted'; } // 一旦获得许可,我们就可以发送通知 if (permissionGranted) { - sendNotification({ title: 'Tauri', body: 'Tauri is awesome!' }); + sendNotification({ title: 'Tauri', body: 'Tauri is awesome!' }); } ``` diff --git a/src/content/docs/zh-cn/plugin/shell.mdx b/src/content/docs/zh-cn/plugin/shell.mdx index c42784003..918603ca1 100644 --- a/src/content/docs/zh-cn/plugin/shell.mdx +++ b/src/content/docs/zh-cn/plugin/shell.mdx @@ -81,8 +81,8 @@ Shell 插件有 JavaScript 和 Rust 两种版本。 import { Command } from '@tauri-apps/plugin-shell'; let result = await Command.create('exec-sh', [ - '-c', - "echo 'Hello World!'", + '-c', + "echo 'Hello World!'", ]).execute(); console.log(result); ``` @@ -121,28 +121,28 @@ if output.status.success() { ```json title="src-tauri/capabilities/main.json" ins={6-23} { - "$schema": "../gen/schemas/desktop-schema.json", - "identifier": "main-capability", - "description": "Capability for the main window", - "windows": ["main"], - "permissions": [ - { - "identifier": "shell:allow-execute", - "allow": [ - { - "name": "exec-sh", - "cmd": "sh", - "args": [ - "-c", - { - "validator": "\\S+" - } - ], - "sidecar": false - } - ] - } - ] + "$schema": "../gen/schemas/desktop-schema.json", + "identifier": "main-capability", + "description": "Capability for the main window", + "windows": ["main"], + "permissions": [ + { + "identifier": "shell:allow-execute", + "allow": [ + { + "name": "exec-sh", + "cmd": "sh", + "args": [ + "-c", + { + "validator": "\\S+" + } + ], + "sidecar": false + } + ] + } + ] } ``` diff --git a/src/content/docs/zh-cn/plugin/sql.mdx b/src/content/docs/zh-cn/plugin/sql.mdx index f0e95d497..b09128d36 100644 --- a/src/content/docs/zh-cn/plugin/sql.mdx +++ b/src/content/docs/zh-cn/plugin/sql.mdx @@ -41,20 +41,20 @@ branch = "v2" 然后,你必须使用你喜欢的 JavaScript 包管理器添加 JavaScript Guest 绑定。 - - - - - - + + + + + + ## 用法 diff --git a/src/content/docs/zh-cn/plugin/store.mdx b/src/content/docs/zh-cn/plugin/store.mdx index 233645dbc..24b0d1770 100644 --- a/src/content/docs/zh-cn/plugin/store.mdx +++ b/src/content/docs/zh-cn/plugin/store.mdx @@ -142,16 +142,16 @@ pub fn run() { ```json title="src-tauri/capabilities/main.json" ins={6-11} { - "$schema": "../gen/schemas/desktop-schema.json", - "identifier": "main-capability", - "description": "Capability for the main window", - "windows": ["main"], - "permissions": [ - "store:allow-get", - "store:allow-set", - "store:allow-save", - "store:allow-load" - ] + "$schema": "../gen/schemas/desktop-schema.json", + "identifier": "main-capability", + "description": "Capability for the main window", + "windows": ["main"], + "permissions": [ + "store:allow-get", + "store:allow-set", + "store:allow-save", + "store:allow-load" + ] } ``` diff --git a/src/content/docs/zh-cn/plugin/upload.mdx b/src/content/docs/zh-cn/plugin/upload.mdx index 9a0dbcc4f..77f281a49 100644 --- a/src/content/docs/zh-cn/plugin/upload.mdx +++ b/src/content/docs/zh-cn/plugin/upload.mdx @@ -70,10 +70,10 @@ _这个插件要求 Rust 版本至少是 **1.75**_ import { upload } from '@tauri-apps/plugin-upload'; upload( - 'https://example.com/file-upload', - './path/to/my/file.txt', - (progress, total) => console.log(`Uploaded ${progress} of ${total} bytes`), // 上传进度时调用的回调函数 - { 'Content-Type': 'text/plain' } // 与请求一起发送的可选头信息 + 'https://example.com/file-upload', + './path/to/my/file.txt', + (progress, total) => console.log(`Uploaded ${progress} of ${total} bytes`), // 上传进度时调用的回调函数 + { 'Content-Type': 'text/plain' } // 与请求一起发送的可选头信息 ); ``` @@ -81,9 +81,9 @@ upload( import { download } from '@tauri-apps/plugin-upload'; download( - 'https://example.com/file-download-link', - './path/to/save/my/file.txt', - (progress, total) => console.log(`Downloaded ${progress} of ${total} bytes`), // 下载进度时调用的回调函数 - { 'Content-Type': 'text/plain' } // 与请求一起发送的可选头信息 + 'https://example.com/file-download-link', + './path/to/save/my/file.txt', + (progress, total) => console.log(`Downloaded ${progress} of ${total} bytes`), // 下载进度时调用的回调函数 + { 'Content-Type': 'text/plain' } // 与请求一起发送的可选头信息 ); ``` diff --git a/src/content/docs/zh-cn/plugin/websocket.mdx b/src/content/docs/zh-cn/plugin/websocket.mdx index ef50d51e7..462b31f3b 100644 --- a/src/content/docs/zh-cn/plugin/websocket.mdx +++ b/src/content/docs/zh-cn/plugin/websocket.mdx @@ -83,7 +83,7 @@ import WebSocket from '@tauri-apps/plugin-websocket'; const ws = await WebSocket.connect('ws://127.0.0.1:8080'); ws.addListener((msg) => { - console.log('Received Message:', msg); + console.log('Received Message:', msg); }); await ws.send('Hello World!'); @@ -99,11 +99,11 @@ await ws.disconnect(); ```json title="src-tauri/capabilities/main.json" ins={6} { - "$schema": "../gen/schemas/desktop-schema.json", - "identifier": "main-capability", - "description": "Capability for the main window", - "windows": ["main"], - "permissions": ["websocket:default"] + "$schema": "../gen/schemas/desktop-schema.json", + "identifier": "main-capability", + "description": "Capability for the main window", + "windows": ["main"], + "permissions": ["websocket:default"] } ``` diff --git a/src/content/docs/zh-cn/plugin/window-customization.mdx b/src/content/docs/zh-cn/plugin/window-customization.mdx index 7e6e3f655..abecf8c85 100644 --- a/src/content/docs/zh-cn/plugin/window-customization.mdx +++ b/src/content/docs/zh-cn/plugin/window-customization.mdx @@ -54,11 +54,11 @@ Tauri 提供了许多自定义应用程序窗口外观的选项。您可以创 ```json title="src-tauri/capabilities/main.json" ins={7-8} { - "$schema": "../gen/schemas/desktop-schema.json", - "identifier": "main-capability", - "description": "Capability for the main window", - "windows": ["main"], - "permissions": ["window:default", "window:allow-start-dragging"] + "$schema": "../gen/schemas/desktop-schema.json", + "identifier": "main-capability", + "description": "Capability for the main window", + "windows": ["main"], + "permissions": ["window:default", "window:allow-start-dragging"] } ``` @@ -77,27 +77,27 @@ Tauri 提供了许多自定义应用程序窗口外观的选项。您可以创 ```css .titlebar { - height: 30px; - background: #329ea3; - user-select: none; - display: flex; - justify-content: flex-end; - position: fixed; - top: 0; - left: 0; - right: 0; + height: 30px; + background: #329ea3; + user-select: none; + display: flex; + justify-content: flex-end; + position: fixed; + top: 0; + left: 0; + right: 0; } .titlebar-button { - display: inline-flex; - justify-content: center; - align-items: center; - width: 30px; - height: 30px; - user-select: none; - -webkit-user-select: none; + display: inline-flex; + justify-content: center; + align-items: center; + width: 30px; + height: 30px; + user-select: none; + -webkit-user-select: none; } .titlebar-button:hover { - background: #5bbec3; + background: #5bbec3; } ``` @@ -107,21 +107,21 @@ Tauri 提供了许多自定义应用程序窗口外观的选项。您可以创 ```html
-
- minimize -
-
- maximize -
-
- close -
+
+ minimize +
+
+ maximize +
+
+ close +
``` @@ -137,14 +137,14 @@ import { Window } from '@tauri-apps/api/window'; const appWindow = new Window('main'); document - .getElementById('titlebar-minimize') - ?.addEventListener('click', () => appWindow.minimize()); + .getElementById('titlebar-minimize') + ?.addEventListener('click', () => appWindow.minimize()); document - .getElementById('titlebar-maximize') - ?.addEventListener('click', () => appWindow.toggleMaximize()); + .getElementById('titlebar-maximize') + ?.addEventListener('click', () => appWindow.toggleMaximize()); document - .getElementById('titlebar-close') - ?.addEventListener('click', () => appWindow.close()); + .getElementById('titlebar-close') + ?.addEventListener('click', () => appWindow.close()); ``` ### (macOS) 具有自定义窗口背景颜色的透明标题栏 diff --git a/src/content/docs/zh-cn/plugin/window-state.mdx b/src/content/docs/zh-cn/plugin/window-state.mdx index 045fa190b..00cc27ac7 100644 --- a/src/content/docs/zh-cn/plugin/window-state.mdx +++ b/src/content/docs/zh-cn/plugin/window-state.mdx @@ -31,10 +31,10 @@ _这个插件要求 Rust 版本至少是 **1.75**_ {' '} @@ -90,8 +90,8 @@ saveWindowState(StateFlags.ALL); ```javascript import { - restoreStateCurrent, - StateFlags, + restoreStateCurrent, + StateFlags, } from '@tauri-apps/plugin-window-state'; restoreStateCurrent(StateFlags.ALL); diff --git a/src/content/docs/zh-cn/reference/acl.mdx b/src/content/docs/zh-cn/reference/acl.mdx index fe0b6ebac..d23806486 100644 --- a/src/content/docs/zh-cn/reference/acl.mdx +++ b/src/content/docs/zh-cn/reference/acl.mdx @@ -17,20 +17,20 @@ title: 访问控制列表 ```json title="src-tauri/capabilities/main.json { - "$schema": "../gen/schemas/desktop-schema.json", - "identifier": "main-capability", - "description": "Capability for the main window", - "windows": ["main"], - "permissions": [ - "path:default", - "event:default", - "window:default", - "app:default", - "resources:default", - "menu:default", - "tray:default", - "window:allow-set-title" - ] + "$schema": "../gen/schemas/desktop-schema.json", + "identifier": "main-capability", + "description": "Capability for the main window", + "windows": ["main"], + "permissions": [ + "path:default", + "event:default", + "window:default", + "app:default", + "resources:default", + "menu:default", + "tray:default", + "window:allow-set-title" + ] } ``` @@ -43,11 +43,11 @@ title: 访问控制列表 ```json title="src-tauri/capabilities/desktop.json { - "$schema": "../gen/schemas/desktop-schema.json", - "identifier": "desktop-capability", - "windows": ["main"], - "platforms": ["linux", "macOS", "windows"], - "permissions": ["global-shortcut:allow-register"] + "$schema": "../gen/schemas/desktop-schema.json", + "identifier": "desktop-capability", + "windows": ["main"], + "platforms": ["linux", "macOS", "windows"], + "permissions": ["global-shortcut:allow-register"] } ``` @@ -55,15 +55,15 @@ title: 访问控制列表 ```json title="src-tauri/capabilities/mobile.json { - "$schema": "../gen/schemas/mobile-schema.json", - "identifier": "mobile-capability", - "windows": ["main"], - "platforms": ["iOS", "android"], - "permissions": [ - "nfc:allow-scan", - "biometric:allow-authenticate", - "barcode-scanner:allow-scan" - ] + "$schema": "../gen/schemas/mobile-schema.json", + "identifier": "mobile-capability", + "windows": ["main"], + "platforms": ["iOS", "android"], + "permissions": [ + "nfc:allow-scan", + "biometric:allow-authenticate", + "barcode-scanner:allow-scan" + ] } ``` @@ -77,11 +77,11 @@ Tauri 生成一个 JSON 模式,包含应用程序可用的所有权限,这 ```json title="src-tauri/capabilities/linux.json { - "$schema": "../gen/schemas/linux-schema.json", - "identifier": "linux-capability", - "windows": ["main"], - "platforms": ["iOS", "android"], - "permissions": ["dbus::call"] + "$schema": "../gen/schemas/linux-schema.json", + "identifier": "linux-capability", + "windows": ["main"], + "platforms": ["iOS", "android"], + "permissions": ["dbus::call"] } ``` @@ -111,12 +111,12 @@ Tauri 生成一个 JSON 模式,包含应用程序可用的所有权限,这 ```json title="src-tauri/capabilities/base.json { - "permissions": [ - { - "identifier": "fs:scope", - "allow": [{ "path": "$APPDATA" }, { "path": "$APPDATA/**" }] - } - ] + "permissions": [ + { + "identifier": "fs:scope", + "allow": [{ "path": "$APPDATA" }, { "path": "$APPDATA/**" }] + } + ] } ``` @@ -128,12 +128,12 @@ Tauri 生成一个 JSON 模式,包含应用程序可用的所有权限,这 ```json title="src-tauri/capabilities/base.json { - "permissions": [ - { - "identifier": "fs:allow-rename", - "allow": [{ "path": "$HOME/**" }] - } - ] + "permissions": [ + { + "identifier": "fs:allow-rename", + "allow": [{ "path": "$HOME/**" }] + } + ] } ``` @@ -141,13 +141,13 @@ Tauri 生成一个 JSON 模式,包含应用程序可用的所有权限,这 ```json title="src-tauri/capabilities/base.json { - "permissions": [ - { - "identifier": "http:default", - "allow": [{ "url": "https://*.tauri.app" }], - "deny": [{ "url": "https://private.tauri.app" }] - } - ] + "permissions": [ + { + "identifier": "http:default", + "allow": [{ "url": "https://*.tauri.app" }], + "deny": [{ "url": "https://private.tauri.app" }] + } + ] } ``` diff --git a/src/content/docs/zh-cn/start/frontend/index.mdx b/src/content/docs/zh-cn/start/frontend/index.mdx index 5f26c1e3c..8622093ce 100644 --- a/src/content/docs/zh-cn/start/frontend/index.mdx +++ b/src/content/docs/zh-cn/start/frontend/index.mdx @@ -18,21 +18,21 @@ Tauri 与前端无关,支持大多数开箱即用的前端框架。但是, ## JavaScript - - - - - - + + + + + + ## Rust - - - - + + + + ## 配置清单 diff --git a/src/content/docs/zh-cn/start/frontend/nextjs.mdx b/src/content/docs/zh-cn/start/frontend/nextjs.mdx index 13a8d55f1..d629dfd66 100644 --- a/src/content/docs/zh-cn/start/frontend/nextjs.mdx +++ b/src/content/docs/zh-cn/start/frontend/nextjs.mdx @@ -19,9 +19,9 @@ Next.js 是一个 React 框架。在 https://nextjs.org 获取更多有关 Next. 1. 安装 `internal-ip` 以用于移动端开发: 2. 更新 Tauri 配置: @@ -32,12 +32,12 @@ Next.js 是一个 React 框架。在 https://nextjs.org 获取更多有关 Next. ```json // tauri.conf.json { - "build": { - "beforeDevCommand": "npm run dev", - "beforeBuildCommand": "npm run build", - "devPath": "http://localhost:3000", - "distDir": "../dist" - } + "build": { + "beforeDevCommand": "npm run dev", + "beforeBuildCommand": "npm run build", + "devPath": "http://localhost:3000", + "distDir": "../dist" + } } ``` @@ -47,12 +47,12 @@ Next.js 是一个 React 框架。在 https://nextjs.org 获取更多有关 Next. ```json // tauri.conf.json { - "build": { - "beforeDevCommand": "yarn dev", - "beforeBuildCommand": "yarn generate", - "devPath": "http://localhost:3000", - "distDir": "../dist" - } + "build": { + "beforeDevCommand": "yarn dev", + "beforeBuildCommand": "yarn generate", + "devPath": "http://localhost:3000", + "distDir": "../dist" + } } ``` @@ -62,12 +62,12 @@ Next.js 是一个 React 框架。在 https://nextjs.org 获取更多有关 Next. ```json // tauri.conf.json { - "build": { - "beforeDevCommand": "pnpm dev", - "beforeBuildCommand": "pnpm generate", - "devPath": "http://localhost:3000", - "distDir": "../dist" - } + "build": { + "beforeDevCommand": "pnpm dev", + "beforeBuildCommand": "pnpm generate", + "devPath": "http://localhost:3000", + "distDir": "../dist" + } } ``` @@ -80,24 +80,24 @@ Next.js 是一个 React 框架。在 https://nextjs.org 获取更多有关 Next. // next.conf.ts const isProd = process.env.NODE_ENV === 'production'; module.exports = async (phase, { defaultConfig }) => { - let internalHost = null; - // 在开发模式下,我们使用 internal-ip 提供资产 - if (!isProd) { - const { internalIpV4 } = await import('internal-ip'); - internalHost = await internalIpV4(); - } - const nextConfig = { - // 确保 Next.js 使用 SSG 而不是 SSR - // https://nextjs.org/docs/pages/building-your-application/deploying/static-exports - output: 'export', - // 注意:在 SSG 模式下使用 NextJS Image 需要此实验功能。 - // 查阅 https://nextjs.org/docs/messages/export-image-api 以获得不同的解决方案。 - images: { - unoptimized: true, - }, - // 配置 assetPrefix,否则服务器将无法正确解析你的资产。 - assetPrefix: isProd ? null : `http://${internalHost}:3000`, - }; - return nextConfig; + let internalHost = null; + // 在开发模式下,我们使用 internal-ip 提供资产 + if (!isProd) { + const { internalIpV4 } = await import('internal-ip'); + internalHost = await internalIpV4(); + } + const nextConfig = { + // 确保 Next.js 使用 SSG 而不是 SSR + // https://nextjs.org/docs/pages/building-your-application/deploying/static-exports + output: 'export', + // 注意:在 SSG 模式下使用 NextJS Image 需要此实验功能。 + // 查阅 https://nextjs.org/docs/messages/export-image-api 以获得不同的解决方案。 + images: { + unoptimized: true, + }, + // 配置 assetPrefix,否则服务器将无法正确解析你的资产。 + assetPrefix: isProd ? null : `http://${internalHost}:3000`, + }; + return nextConfig; }; ``` diff --git a/src/content/docs/zh-cn/start/frontend/nuxt.mdx b/src/content/docs/zh-cn/start/frontend/nuxt.mdx index b649820df..b8c3462fe 100644 --- a/src/content/docs/zh-cn/start/frontend/nuxt.mdx +++ b/src/content/docs/zh-cn/start/frontend/nuxt.mdx @@ -25,12 +25,12 @@ import { Tabs, TabItem } from '@astrojs/starlight/components'; ```json // tauri.conf.json { - "build": { - "beforeDevCommand": "npm run dev", - "beforeBuildCommand": "npm run generate", - "devPath": "http://localhost:3000", - "distDir": "../dist" - } + "build": { + "beforeDevCommand": "npm run dev", + "beforeBuildCommand": "npm run generate", + "devPath": "http://localhost:3000", + "distDir": "../dist" + } } ``` @@ -40,12 +40,12 @@ import { Tabs, TabItem } from '@astrojs/starlight/components'; ```json // tauri.conf.json { - "build": { - "beforeDevCommand": "yarn dev", - "beforeBuildCommand": "yarn generate", - "devPath": "http://localhost:3000", - "distDir": "../dist" - } + "build": { + "beforeDevCommand": "yarn dev", + "beforeBuildCommand": "yarn generate", + "devPath": "http://localhost:3000", + "distDir": "../dist" + } } ``` @@ -55,12 +55,12 @@ import { Tabs, TabItem } from '@astrojs/starlight/components'; ```json // tauri.conf.json { - "build": { - "beforeDevCommand": "pnpm dev", - "beforeBuildCommand": "pnpm generate", - "devPath": "http://localhost:3000", - "distDir": "../dist" - } + "build": { + "beforeDevCommand": "pnpm dev", + "beforeBuildCommand": "pnpm generate", + "devPath": "http://localhost:3000", + "distDir": "../dist" + } } ``` @@ -72,31 +72,31 @@ import { Tabs, TabItem } from '@astrojs/starlight/components'; ```ts export default defineNuxtConfig({ - // (可选) 启用 Nuxt 调试工具 - devtools: { enabled: true }, - // 启用 SSG - ssr: false, - vite: { - // 为 Tauri 命令输出提供更好的支持 - clearScreen: false, - // 启用环境变量 - // 其他环境变量可以在如下网页中获知: - // https://tauri.app/2/reference/environment-variables/ - envPrefix: ['VITE_', 'TAURI_'], - server: { - // Tauri需要一个确定的端口 - strictPort: true, - // 使开发服务器能够被用于移动开发的其他设备发现 - host: '0.0.0.0', - hmr: { - // 使用 websocket 以支持移动端热重载 - protocol: 'ws', - // 确保它在网络上可用 - host: '0.0.0.0', - // 使用 hmr 的特定端口 - port: 5183, - }, - }, - }, + // (可选) 启用 Nuxt 调试工具 + devtools: { enabled: true }, + // 启用 SSG + ssr: false, + vite: { + // 为 Tauri 命令输出提供更好的支持 + clearScreen: false, + // 启用环境变量 + // 其他环境变量可以在如下网页中获知: + // https://tauri.app/2/reference/environment-variables/ + envPrefix: ['VITE_', 'TAURI_'], + server: { + // Tauri需要一个确定的端口 + strictPort: true, + // 使开发服务器能够被用于移动开发的其他设备发现 + host: '0.0.0.0', + hmr: { + // 使用 websocket 以支持移动端热重载 + protocol: 'ws', + // 确保它在网络上可用 + host: '0.0.0.0', + // 使用 hmr 的特定端口 + port: 5183, + }, + }, + }, }); ``` diff --git a/src/content/docs/zh-cn/start/frontend/trunk.mdx b/src/content/docs/zh-cn/start/frontend/trunk.mdx index a9f56b9e4..5f9ecfe72 100644 --- a/src/content/docs/zh-cn/start/frontend/trunk.mdx +++ b/src/content/docs/zh-cn/start/frontend/trunk.mdx @@ -19,15 +19,15 @@ Trunk 是一个用于 Rust 的 WASM 网页应用打包器。 前往 https://trun ```json // tauri.conf.json { - "build": { - "beforeDevCommand": "trunk serve", - "beforeBuildCommand": "trunk build", - "devPath": "http://localhost:8080", - "distDir": "../dist" - }, - "app": { - "withGlobalTauri": true - } + "build": { + "beforeDevCommand": "trunk serve", + "beforeBuildCommand": "trunk build", + "devPath": "http://localhost:8080", + "distDir": "../dist" + }, + "app": { + "withGlobalTauri": true + } } ``` diff --git a/src/content/docs/zh-cn/start/migrate/from-tauri-1.mdx b/src/content/docs/zh-cn/start/migrate/from-tauri-1.mdx index 937e67755..44289f0e1 100644 --- a/src/content/docs/zh-cn/start/migrate/from-tauri-1.mdx +++ b/src/content/docs/zh-cn/start/migrate/from-tauri-1.mdx @@ -52,13 +52,13 @@ fn main() { Tauri v2 的命令行工具包括一个 `migrate` 命令,可自动执行大部分流程,并帮助你完成迁移: @@ -233,9 +233,9 @@ fn main() { ```json // package.json { - "dependencies": { - "@tauri-apps/plugin-cli": "^2.0.0" - } + "dependencies": { + "@tauri-apps/plugin-cli": "^2.0.0" + } } ``` @@ -284,9 +284,9 @@ fn main() { ```json // package.json { - "dependencies": { - "@tauri-apps/plugin-clipboard-manager": "^2.0.0" - } + "dependencies": { + "@tauri-apps/plugin-clipboard-manager": "^2.0.0" + } } ``` @@ -342,21 +342,21 @@ fn main() { ```json // package.json { - "dependencies": { - "@tauri-apps/plugin-dialog": "^2.0.0" - } + "dependencies": { + "@tauri-apps/plugin-dialog": "^2.0.0" + } } ``` ```js import { save } from '@tauri-apps/plugin-dialog'; const filePath = await save({ - filters: [ - { - name: 'Image', - extensions: ['png', 'jpeg'], - }, - ], + filters: [ + { + name: 'Image', + extensions: ['png', 'jpeg'], + }, + ], }); ``` @@ -408,9 +408,9 @@ fn main() { ```json // package.json { - "dependencies": { - "@tauri-apps/plugin-fs": "^2.0.0" - } + "dependencies": { + "@tauri-apps/plugin-fs": "^2.0.0" + } } ``` @@ -466,16 +466,16 @@ fn main() { ```json // package.json { - "dependencies": { - "@tauri-apps/plugin-global-shortcut": "^2.0.0" - } + "dependencies": { + "@tauri-apps/plugin-global-shortcut": "^2.0.0" + } } ``` ```js import { register } from '@tauri-apps/plugin-global-shortcut'; await register('CommandOrControl+Shift+C', () => { - console.log('Shortcut triggered'); + console.log('Shortcut triggered'); }); ``` @@ -531,16 +531,16 @@ fn main() { ```json // package.json { - "dependencies": { - "@tauri-apps/plugin-http": "^2.0.0" - } + "dependencies": { + "@tauri-apps/plugin-http": "^2.0.0" + } } ``` ```js import { fetch } from '@tauri-apps/plugin-http'; const response = await fetch( - 'https://raw.githubusercontent.com/tauri-apps/tauri/dev/package.json' + 'https://raw.githubusercontent.com/tauri-apps/tauri/dev/package.json' ); ``` @@ -597,9 +597,9 @@ fn main() { ```json // package.json { - "dependencies": { - "@tauri-apps/plugin-notification": "^2.0.0" - } + "dependencies": { + "@tauri-apps/plugin-notification": "^2.0.0" + } } ``` @@ -781,9 +781,9 @@ fn main() { ```json // package.json { - "dependencies": { - "@tauri-apps/plugin-os": "^2.0.0" - } + "dependencies": { + "@tauri-apps/plugin-os": "^2.0.0" + } } ``` @@ -836,9 +836,9 @@ fn main() { ```json // package.json { - "dependencies": { - "@tauri-apps/plugin-process": "^2.0.0" - } + "dependencies": { + "@tauri-apps/plugin-process": "^2.0.0" + } } ``` @@ -895,9 +895,9 @@ fn main() { ```json // package.json { - "dependencies": { - "@tauri-apps/plugin-shell": "^2.0.0" - } + "dependencies": { + "@tauri-apps/plugin-shell": "^2.0.0" + } } ``` @@ -1079,9 +1079,9 @@ fn main() { ```json // package.json { - "dependencies": { - "@tauri-apps/plugin-updater": "^2.0.0" - } + "dependencies": { + "@tauri-apps/plugin-updater": "^2.0.0" + } } ``` @@ -1091,11 +1091,11 @@ import { relaunch } from '@tauri-apps/plugin-process'; const update = await check(); if (update?.available) { - console.log(`Update to ${update.version} available! Date: ${update.date}`); - console.log(`Release notes: ${update.body}`); - await update.downloadAndInstall(); - // 需要 `process` 插件 - await relaunch(); + console.log(`Update to ${update.version} available! Date: ${update.date}`); + console.log(`Release notes: ${update.body}`); + await update.downloadAndInstall(); + // 需要 `process` 插件 + await relaunch(); } ``` diff --git a/src/content/docs/zh-cn/start/migrate/index.mdx b/src/content/docs/zh-cn/start/migrate/index.mdx index e92063683..357a1cd7b 100644 --- a/src/content/docs/zh-cn/start/migrate/index.mdx +++ b/src/content/docs/zh-cn/start/migrate/index.mdx @@ -7,16 +7,16 @@ title: 更新和迁移 import { LinkCard, CardGrid } from '@astrojs/starlight/components'; - - - + + + diff --git a/src/pages/feed.xml.ts b/src/pages/feed.xml.ts index 5484cd263..0cf468105 100644 --- a/src/pages/feed.xml.ts +++ b/src/pages/feed.xml.ts @@ -8,41 +8,41 @@ import rss from '@astrojs/rss'; // Ternary is just so typescript won't complain const exclude = config.isMultilingual - ? Object.keys(config.locales).concat('references', 'rss', 'releases') - : []; + ? Object.keys(config.locales).concat('references', 'rss', 'releases') + : []; // https://docs.astro.build/en/reference/api-reference/#endpoint-context export async function GET(context: APIContext) { - const pages = await getCollection('docs', ({ id }) => { - return !exclude.some((path) => id.startsWith(path)); - }); - pages.sort((a, b) => { - const dateA = a.data.date; - const dateB = b.data.date; - if (dateA && dateB) { - if (dateA < dateB) return 1; - if (dateA > dateB) return -1; - return 0; - } else return 0; - }); + const pages = await getCollection('docs', ({ id }) => { + return !exclude.some((path) => id.startsWith(path)); + }); + pages.sort((a, b) => { + const dateA = a.data.date; + const dateB = b.data.date; + if (dateA && dateB) { + if (dateA < dateB) return 1; + if (dateA > dateB) return -1; + return 0; + } else return 0; + }); - return rss({ - title: 'Tauri RSS', - description: 'The cross-platform app building toolkit', - site: context.site as URL, - items: pages.map((post) => ({ - title: post.data.title, - pubDate: post.id.startsWith('blog') ? post.data.date : getTimestamp(post.id), - description: post.id.startsWith('blog') ? post.data.excerpt : post.data.description, - link: `/${post.slug}/`, - })), - }); + return rss({ + title: 'Tauri RSS', + description: 'The cross-platform app building toolkit', + site: context.site as URL, + items: pages.map((post) => ({ + title: post.data.title, + pubDate: post.id.startsWith('blog') ? post.data.date : getTimestamp(post.id), + description: post.id.startsWith('blog') ? post.data.excerpt : post.data.description, + link: `/${post.slug}/`, + })), + }); } function getTimestamp(id: string): any { - try { - return getNewestCommitDate(join('src', 'content', 'docs', id)); - } catch (e) { - return new Date(); - } + try { + return getNewestCommitDate(join('src', 'content', 'docs', id)); + } catch (e) { + return new Date(); + } } diff --git a/src/pages/pages.xml.ts b/src/pages/pages.xml.ts index 7cd6280bc..59a08f360 100644 --- a/src/pages/pages.xml.ts +++ b/src/pages/pages.xml.ts @@ -8,41 +8,41 @@ import rss from '@astrojs/rss'; // Ternary is just so typescript won't complain const exclude = config.isMultilingual - ? Object.keys(config.locales).concat('blog', 'references', 'rss', 'releases') - : []; + ? Object.keys(config.locales).concat('blog', 'references', 'rss', 'releases') + : []; // https://docs.astro.build/en/reference/api-reference/#endpoint-context export async function GET(context: APIContext) { - const posts = await getCollection('docs', ({ id }) => { - return !exclude.some((path) => id.startsWith(path)); - }); + const posts = await getCollection('docs', ({ id }) => { + return !exclude.some((path) => id.startsWith(path)); + }); - posts.sort((a, b) => { - const dateA = a.data.date; - const dateB = b.data.date; - if (dateA && dateB) { - if (dateA < dateB) return 1; - if (dateA > dateB) return -1; - return 0; - } else return 0; - }); + posts.sort((a, b) => { + const dateA = a.data.date; + const dateB = b.data.date; + if (dateA && dateB) { + if (dateA < dateB) return 1; + if (dateA > dateB) return -1; + return 0; + } else return 0; + }); - return rss({ - title: 'Tauri Docs', - description: 'The cross-platform app building toolkit', - site: context.site as URL, - items: posts.map((post) => ({ - pubDate: getTimestamp(post.id), - ...post.data, - link: `/${post.slug}/`, - })), - }); + return rss({ + title: 'Tauri Docs', + description: 'The cross-platform app building toolkit', + site: context.site as URL, + items: posts.map((post) => ({ + pubDate: getTimestamp(post.id), + ...post.data, + link: `/${post.slug}/`, + })), + }); } function getTimestamp(id: string): any { - try { - return getNewestCommitDate(join('src', 'content', 'docs', id)); - } catch (e) { - return new Date(); - } + try { + return getNewestCommitDate(join('src', 'content', 'docs', id)); + } catch (e) { + return new Date(); + } } diff --git a/src/styles/custom.scss b/src/styles/custom.scss index d2d235559..9055618ce 100644 --- a/src/styles/custom.scss +++ b/src/styles/custom.scss @@ -2,146 +2,146 @@ @import url('./overrides.scss'); .content details { - padding: 0 1rem; + padding: 0 1rem; } .content details[open] { - background-color: var(--sl-color-gray-6); - padding-bottom: rem; + background-color: var(--sl-color-gray-6); + padding-bottom: rem; } .content summary { - cursor: pointer; - padding: 1rem 0; + cursor: pointer; + padding: 1rem 0; } /* Heading link styling */ .heading-link::after { - content: '#'; - padding-inline-start: 0.25em; - opacity: 0; - transition: var(--tauri-transition-speed); + content: '#'; + padding-inline-start: 0.25em; + opacity: 0; + transition: var(--tauri-transition-speed); } .heading-link:hover::after { - color: var(--sl-color-text-accent); - opacity: 1; + color: var(--sl-color-text-accent); + opacity: 1; } .heading-link { - text-decoration: none; - color: var(--sl-color-white) !important; + text-decoration: none; + color: var(--sl-color-white) !important; } @media (min-width: 50rem) { - .hero { - padding-block: clamp(2.5rem, calc(1rem + 10vmin), 5rem); - } + .hero { + padding-block: clamp(2.5rem, calc(1rem + 10vmin), 5rem); + } } /* Index hero background */ .hero-bg { - position: absolute; - top: 0; - left: 0; - width: 100%; - height: 100%; - display: block; - z-index: -1; - opacity: 0.7; - overflow: hidden; - background: linear-gradient(-90deg, var(--sl-color-gray-6) 1px, transparent 1px), - linear-gradient(var(--sl-color-gray-6) 1px, transparent 1px), - linear-gradient(-90deg, var(--sl-color-gray-6) 1px, transparent 1px), - linear-gradient(var(--sl-color-gray-6) 1px, transparent 1px), - linear-gradient(transparent 6px, transparent 6px, transparent 156px, transparent 156px), - linear-gradient(-90deg, var(--sl-color-gray-6) 1px, transparent 1px), - linear-gradient(-90deg, transparent 6px, transparent 6px, transparent 156px, transparent 156px), - linear-gradient(var(--sl-color-gray-6) 1px, transparent 1px), transparent; - background-size: - 32px 32px, - 32px 32px, - 256px 256px, - 256px 256px, - 256px 256px, - 256px 256px, - 256px 256px, - 256px 256px; + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + display: block; + z-index: -1; + opacity: 0.7; + overflow: hidden; + background: linear-gradient(-90deg, var(--sl-color-gray-6) 1px, transparent 1px), + linear-gradient(var(--sl-color-gray-6) 1px, transparent 1px), + linear-gradient(-90deg, var(--sl-color-gray-6) 1px, transparent 1px), + linear-gradient(var(--sl-color-gray-6) 1px, transparent 1px), + linear-gradient(transparent 6px, transparent 6px, transparent 156px, transparent 156px), + linear-gradient(-90deg, var(--sl-color-gray-6) 1px, transparent 1px), + linear-gradient(-90deg, transparent 6px, transparent 6px, transparent 156px, transparent 156px), + linear-gradient(var(--sl-color-gray-6) 1px, transparent 1px), transparent; + background-size: + 32px 32px, + 32px 32px, + 256px 256px, + 256px 256px, + 256px 256px, + 256px 256px, + 256px 256px, + 256px 256px; } /* Transition hero background grid smoothly to page background color. */ .hero-bg::after { - content: ''; - position: absolute; - inset: 70% 0 0; - background: linear-gradient(transparent, var(--sl-color-bg)); + content: ''; + position: absolute; + inset: 70% 0 0; + background: linear-gradient(transparent, var(--sl-color-bg)); } .bg-grad { - position: absolute; - top: -50%; - left: 50%; - width: 150vh; - height: 150vh; - opacity: 0.3; - background: radial-gradient(circle, var(--sl-color-accent) 0%, var(--sl-color-bg) 70%); - animation: 6s intro; + position: absolute; + top: -50%; + left: 50%; + width: 150vh; + height: 150vh; + opacity: 0.3; + background: radial-gradient(circle, var(--sl-color-accent) 0%, var(--sl-color-bg) 70%); + animation: 6s intro; } .bg-grad-red { - position: absolute; - top: 0%; - left: -50%; - width: 150vh; - height: 150vh; - opacity: 0.3; - background: radial-gradient(circle, var(--sl-color-orange) 0%, var(--sl-color-bg) 70%); - animation: 14s intro; + position: absolute; + top: 0%; + left: -50%; + width: 150vh; + height: 150vh; + opacity: 0.3; + background: radial-gradient(circle, var(--sl-color-orange) 0%, var(--sl-color-bg) 70%); + animation: 14s intro; } /* Tauri logo on index page */ .hero > img { - animation: 3s intro; - opacity: 0.4; + animation: 3s intro; + opacity: 0.4; } .sl-markdown-content .inline-icon { - display: inline-block; + display: inline-block; } html[data-theme='light'] .hero > img { - filter: invert(1); + filter: invert(1); } @keyframes intro { - 0% { - scale: 1.4; - opacity: 0; - } + 0% { + scale: 1.4; + opacity: 0; + } - 80% { - scale: 0.9; - } + 80% { + scale: 0.9; + } - 100% { - } + 100% { + } } @media (prefers-reduced-motion) { - * { - transition: none !important; - } + * { + transition: none !important; + } } .lp-cta-card { - max-width: 750px; - margin: auto; + max-width: 750px; + margin: auto; } article.card { - border-radius: 0.5rem; + border-radius: 0.5rem; } body { - overflow-y: scroll; + overflow-y: scroll; } diff --git a/src/styles/overrides.scss b/src/styles/overrides.scss index ec11820e2..a8ed8fc97 100644 --- a/src/styles/overrides.scss +++ b/src/styles/overrides.scss @@ -1,6 +1,6 @@ .expressive-code > figure > pre { - border-radius: 0.5rem; + border-radius: 0.5rem; } .starlight-aside { - border-radius: 0.5rem; + border-radius: 0.5rem; } diff --git a/src/styles/theme.scss b/src/styles/theme.scss index 0d5a592b1..0b9e022d3 100644 --- a/src/styles/theme.scss +++ b/src/styles/theme.scss @@ -1,26 +1,26 @@ :root { - --sl-hue-orange: 42; - --sl-color-orange-low: hsl(var(--sl-hue-orange), 100%, 15%); - --sl-color-orange: hsl(var(--sl-hue-orange), 100%, 60%); - --sl-color-orange-high: hsl(var(--sl-hue-orange), 100%, 90%); - --sl-hue-blue: 186; - --sl-color-blue-low: hsl(var(--sl-hue-blue), 72%, 15%); - --sl-color-blue: hsl(var(--sl-hue-blue), 72%, 50%); - --sl-color-blue-high: hsl(var(--sl-hue-blue), 72%, 90%); - --sl-hue-accent: var(--sl-hue-blue); - --sl-color-accent-low: var(--sl-color-blue-low); - --sl-color-accent: var(--sl-color-blue); - --sl-color-accent-high: var(--sl-color-blue-high); + --sl-hue-orange: 42; + --sl-color-orange-low: hsl(var(--sl-hue-orange), 100%, 15%); + --sl-color-orange: hsl(var(--sl-hue-orange), 100%, 60%); + --sl-color-orange-high: hsl(var(--sl-hue-orange), 100%, 90%); + --sl-hue-blue: 186; + --sl-color-blue-low: hsl(var(--sl-hue-blue), 72%, 15%); + --sl-color-blue: hsl(var(--sl-hue-blue), 72%, 50%); + --sl-color-blue-high: hsl(var(--sl-hue-blue), 72%, 90%); + --sl-hue-accent: var(--sl-hue-blue); + --sl-color-accent-low: var(--sl-color-blue-low); + --sl-color-accent: var(--sl-color-blue); + --sl-color-accent-high: var(--sl-color-blue-high); - --sl-color-white: #ffffff; - --sl-color-gray-1: #eeeeee; - --sl-color-gray-2: #c2c2c2; - --sl-color-gray-3: #8b8b8b; - --sl-color-gray-4: #585858; - --sl-color-gray-5: #383838; - --sl-color-gray-6: #272727; - --sl-color-black: #181818; + --sl-color-white: #ffffff; + --sl-color-gray-1: #eeeeee; + --sl-color-gray-2: #c2c2c2; + --sl-color-gray-3: #8b8b8b; + --sl-color-gray-4: #585858; + --sl-color-gray-5: #383838; + --sl-color-gray-6: #272727; + --sl-color-black: #181818; - /* Custom */ - --tauri-transition-speed: 200ms; + /* Custom */ + --tauri-transition-speed: 200ms; }