diff --git a/.github/contributing.md b/.github/contributing.md index 24a4a745..5738cbc2 100644 --- a/.github/contributing.md +++ b/.github/contributing.md @@ -23,7 +23,7 @@ Hi! We're really excited that you are interested in contributing to VitePress. B ## Development Setup -You will need [pnpm](https://pnpm.io) +You will need [Node.js](https://nodejs.org) v20 or higher and [pnpm](https://pnpm.io). After cloning the repo, run: diff --git a/.github/workflows/cr.yml b/.github/workflows/cr.yml index b8b833ef..7dd5c4c7 100644 --- a/.github/workflows/cr.yml +++ b/.github/workflows/cr.yml @@ -9,6 +9,7 @@ on: types: [opened, synchronize, labeled, ready_for_review] paths-ignore: - '.github/**' + - '!.github/workflows/cr.yml' - '__tests__/**' - 'art/**' - 'docs/**' @@ -17,6 +18,7 @@ on: branches: [main] paths-ignore: - '.github/**' + - '!.github/workflows/cr.yml' - '__tests__/**' - 'art/**' - 'docs/**' diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml index f5826155..dd47c33f 100644 --- a/.github/workflows/stale.yml +++ b/.github/workflows/stale.yml @@ -1,12 +1,14 @@ name: Close stale issues and PRs on: + schedule: + - cron: '0 12 1,15 * *' workflow_dispatch: jobs: stale: runs-on: ubuntu-latest steps: - - uses: actions/stale@v9 + - uses: actions/stale@v10 with: days-before-stale: 30 days-before-close: -1 diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index dc527e35..51d3fffe 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -18,7 +18,7 @@ jobs: strategy: matrix: os: [ubuntu-latest] - node_version: [18, 20, 22] + node_version: [20, 22, latest] include: - os: windows-latest node_version: 22 diff --git a/.npmrc b/.npmrc deleted file mode 100644 index ab953072..00000000 --- a/.npmrc +++ /dev/null @@ -1,2 +0,0 @@ -shell-emulator=true -auto-install-peers=false diff --git a/CHANGELOG.md b/CHANGELOG.md index 387e81e0..e31cdc19 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,146 @@ +## [2.0.0-alpha.12](https://github.com/vuejs/vitepress/compare/v2.0.0-alpha.11...v2.0.0-alpha.12) (2025-08-20) + +### Bug Fixes + +- **hmr:** don't load config twice on server restart ([d1a8061](https://github.com/vuejs/vitepress/commit/d1a8061eb438c730ccc62ce2d7158dbe89cc5292)) +- **hmr:** no need for server restart on theme change ([d3a1567](https://github.com/vuejs/vitepress/commit/d3a15673bd0846c7837bcc4ff5a2e3239a02f1f9)) +- **hmr:** hmr not working for snippet imports in dynamic routes ([914467e](https://github.com/vuejs/vitepress/commit/914467e17fb759a9722951a3fd7568eb3bc4d4e6)) +- **theme:** fix local nav alignment and increase touch area ([43b36c0](https://github.com/vuejs/vitepress/commit/43b36c0c19c2b4696f8c38fdaf4318786ea7ae8e)) +- **theme:** nav background doesn't extend fully and gap after sidebar with non-overlay scrollbars ([7df3052](https://github.com/vuejs/vitepress/commit/7df30525121a28a46cc6c802f3155ccff8effaca)), closes [#4653](https://github.com/vuejs/vitepress/issues/4653) +- **theme:** use clipboard-check instead of clipboard-copy for code copied icon ([1c8815d](https://github.com/vuejs/vitepress/commit/1c8815d53ed2d56b07938260df6566f1514f4bfc)) + +### Features + +- add markdown-it-cjk-friendly ([9fc8462](https://github.com/vuejs/vitepress/commit/9fc8462726ccf1cdb78b6171c9f1f5964e79ca22)), closes [#3762](https://github.com/vuejs/vitepress/issues/3762) [#4752](https://github.com/vuejs/vitepress/issues/4752) +- make postcssIsolateStyles idempotent ([0944777](https://github.com/vuejs/vitepress/commit/094477789328b80cff45cd973efa16b6a4db0a27)) + +### BREAKING CHANGES + +- [markdown-it-cjk-friendly](https://www.npmjs.com/package/markdown-it-cjk-friendly) is enabled by default. This intentionally deviates from the official commonmark spec for the benefit of CJK users. **For most users, no change is required.** If you were using hacks to patch `scanDelims`, you can remove those. To disable the plugin, set `markdown: { cjkFriendly: false }` in your vitepress config. +- `includeFiles` option in `postcssIsolateStyles` now defaults to `[/vp-doc\.css/, /base\.css/]`. You can remove explicit `includeFiles` if you were using it just to run it on `vp-doc.css`. To revert back to older behavior pass `includeFiles: [/base\.css/]`. The underlying implementation is changed and `transform` and `exclude` options are no longer supported. Use `postcss-prefix-selector` directly if you've advanced use cases. + +## [2.0.0-alpha.11](https://github.com/vuejs/vitepress/compare/v2.0.0-alpha.10...v2.0.0-alpha.11) (2025-08-14) + +### Bug Fixes + +- hmr working only once for markdown files ([8d8a5ac](https://github.com/vuejs/vitepress/commit/8d8a5ac281f090cd097bece792d9dd3ef00e5545)), closes [#4909](https://github.com/vuejs/vitepress/issues/4909) +- html entities encoded twice in toc plugin ([8abbe29](https://github.com/vuejs/vitepress/commit/8abbe298d545de17d34a9bc1eb72af4c5a4b41b8)), closes [#4908](https://github.com/vuejs/vitepress/issues/4908) + +## [2.0.0-alpha.10](https://github.com/vuejs/vitepress/compare/v2.0.0-alpha.9...v2.0.0-alpha.10) (2025-08-11) + +### Bug Fixes + +- **client:** base not stripped from relativePath in 404 pages ([b840877](https://github.com/vuejs/vitepress/commit/b840877aa83a5a24ffc1222e8a5a3dbf3e5105e8)), closes [#4850](https://github.com/vuejs/vitepress/issues/4850) +- hmr of style blocks in dynamic routes ([#4903](https://github.com/vuejs/vitepress/issues/4903)) ([3d0fafb](https://github.com/vuejs/vitepress/commit/3d0fafba545f4b5028cf43d86027dd44dab14421)) +- make paths in `watchedFiles` absolute as mentioned in the docs ([318c14f](https://github.com/vuejs/vitepress/commit/318c14fa7c9fb949d74b7d9fae416e917766cf05)) +- module graph causing unnecessary route regeneration on every update ([fc267ae](https://github.com/vuejs/vitepress/commit/fc267ae6b787e163d41666e090089821377ead43)) +- preserve externally added dynamic routes and pages ([fc267ae](https://github.com/vuejs/vitepress/commit/fc267ae6b787e163d41666e090089821377ead43)) +- **search:** input placeholder being cut off in smaller viewports ([162c6a6](https://github.com/vuejs/vitepress/commit/162c6a69bf56945daa20d126aa034c59ee0c8a2e)) +- **search:** style tweaks for when searches are empty ([8b23217](https://github.com/vuejs/vitepress/commit/8b232171cc321bd3dc86b4357622815269f0b6f4)) +- **types:** externalize markdown-it types ([5bf835b](https://github.com/vuejs/vitepress/commit/5bf835b5074e9567852d552bfb5115c6456026e8)) +- **types:** pass generics deeply to user config ([777e2ca](https://github.com/vuejs/vitepress/commit/777e2caaacd93ce41b046f6c9d5ba80cc43ba37c)) + +### Features + +- add source param to the deadlink check fn ([#4870](https://github.com/vuejs/vitepress/issues/4870)) ([8c027c2](https://github.com/vuejs/vitepress/commit/8c027c2a7c443074fd0d4890f7736b444f9254aa)) +- **theme:** add `rel="me"` to social links by default ([#4873](https://github.com/vuejs/vitepress/issues/4873)) ([34886c6](https://github.com/vuejs/vitepress/commit/34886c667d1305a79d64c957f8c52931ea122f47)) + +## [2.0.0-alpha.9](https://github.com/vuejs/vitepress/compare/v2.0.0-alpha.8...v2.0.0-alpha.9) (2025-07-26) + +### Bug Fixes + +- **md:** pass container option to gitHubAlertsPlugin ([#4848](https://github.com/vuejs/vitepress/issues/4848)) ([52f0eaa](https://github.com/vuejs/vitepress/commit/52f0eaa0849344aa45efbf7258a6287597e55a9a)) +- **theme:** remove duplicate text in sponsors grid ([3c51b22](https://github.com/vuejs/vitepress/commit/3c51b22ac98a12f193081d23799cb9f3f2ecf682)), closes [#4854](https://github.com/vuejs/vitepress/issues/4854) + +### Features + +- **search:** upgrade search to DocSearch v4-beta ([#4843](https://github.com/vuejs/vitepress/issues/4843)) ([ac61abe](https://github.com/vuejs/vitepress/commit/ac61abe7d7be5ef8b6939f18192896538eba1b8c)) + +### BREAKING CHANGES + +- **search:** Uses DocSearch v4 beta. No change is required if you're not customizing the styles of navbar search button or modal. DocSearch AI features are in private beta, you can apply for them at https://forms.gle/iyfb5pC2CiiwszUKA + +## [2.0.0-alpha.8](https://github.com/vuejs/vitepress/compare/v2.0.0-alpha.7...v2.0.0-alpha.8) (2025-07-08) + +### Bug Fixes + +- adjust glob logic to always resolve glob relative to base ([5d41785](https://github.com/vuejs/vitepress/commit/5d41785ff7b016b08f587f1ef3318fc18d58f6ab)), closes [#4822](https://github.com/vuejs/vitepress/issues/4822) +- **build:** ignore escaped `:` when splitting selector in `postcssIsolateStyles` ([#4830](https://github.com/vuejs/vitepress/issues/4830)) ([a629b03](https://github.com/vuejs/vitepress/commit/a629b03f0ee8a29d73a18481399d7de1c992faf2)) +- font preload not being generated in rolldown-vite ([ed387e8](https://github.com/vuejs/vitepress/commit/ed387e89d42a08c15a9f45c9c5e11c6750245490)) +- **theme:** remove extra slash when concatenating base with sidebar links ([c8fc80e](https://github.com/vuejs/vitepress/commit/c8fc80e438fffd98feaf7c72263bc3077792c4a2)) + +## [2.0.0-alpha.7](https://github.com/vuejs/vitepress/compare/v2.0.0-alpha.6...v2.0.0-alpha.7) (2025-06-24) + +### Bug Fixes + +- **local-search:** parse headings with non-anchor `a` tags as titles properly ([#4809](https://github.com/vuejs/vitepress/issues/4809)) ([5359903](https://github.com/vuejs/vitepress/commit/53599039a01af6d8e17a6a6e9cea5c222cc5948c)) +- resolve pages after setting global vitepress config ([56ba65e](https://github.com/vuejs/vitepress/commit/56ba65e1301454df88f9a3856fa1a70dc052d314)), closes [#4803](https://github.com/vuejs/vitepress/issues/4803) + +### Features + +- **router:** add `replace` option to `useRouter` for history management ([#4788](https://github.com/vuejs/vitepress/issues/4788)) ([23541b4](https://github.com/vuejs/vitepress/commit/23541b4f83726cdac09ffcaf9141bba871cda690)), closes [#4787](https://github.com/vuejs/vitepress/issues/4787) +- consistent glob options across content, data, and path loaders ([#4808](https://github.com/vuejs/vitepress/issues/4808)) ([7619521](https://github.com/vuejs/vitepress/commit/76195212596cd54095240246b7e78075ac3cbc27)), closes [#4807](https://github.com/vuejs/vitepress/issues/4807) +- bump to vite 7 ([2ecd607](https://github.com/vuejs/vitepress/commit/2ecd607af15222eeddf0b888a72d0f913f5a3cd2)) + +### Performance Improvements + +- render pages in contentLoader asynchronously ([36148a0](https://github.com/vuejs/vitepress/commit/36148a0bcf3a73d1fe3f0c5f33337b679f700053)) + +### BREAKING CHANGES + +- Only `cwd`, `ignore`, `dot` and `debug` are supported in `globOptions` of `createContentLoader`. If you want to pass other options, you still can but you might need to suppress type errors. +- Uses vite 7. See [vite migration guide](https://vite.dev/guide/migration.html) for more info. For most of the users no change is required. VitePress should work same as earlier, except for maybe some type mismatches if you're using third-party plugins. You can suppress them using `@ts-expect-error` or `as any` and report the issues at respective repositories. + +## [2.0.0-alpha.6](https://github.com/vuejs/vitepress/compare/v2.0.0-alpha.5...v2.0.0-alpha.6) (2025-06-12) + +### Bug Fixes + +- allow AdditionalConfigLoader to return void ([906a44a](https://github.com/vuejs/vitepress/commit/906a44a3ad488a46804757326af95cfb8cac6b75)) +- **build:** avoiding creating separate chunks for vite public assets ([21f24b9](https://github.com/vuejs/vitepress/commit/21f24b9994ea4807ac7e0be38408e9aaa3abe8a9)) +- **build:** emit lean chunks after vite has done processing ([26cb685](https://github.com/vuejs/vitepress/commit/26cb685adf54f07fe3e9fd7bfd49a0ff79956923)), closes [#4737](https://github.com/vuejs/vitepress/issues/4737) +- **client:** properly skip removed lines when copying code blocks ([c128baf](https://github.com/vuejs/vitepress/commit/c128baf0c41d5113c1b876f691e0185201b1f500)) +- disable appearance scripts in zero-js mode ([e7f9d05](https://github.com/vuejs/vitepress/commit/e7f9d05c3e2ef4f4c1db3b2c17e586f0fc26a6f6)), closes [#4766](https://github.com/vuejs/vitepress/issues/4766) +- don't preload dynamic imports ([801648a](https://github.com/vuejs/vitepress/commit/801648a4c9d91e7f96302932ac9247d5bdd64ef7)), closes [#4770](https://github.com/vuejs/vitepress/issues/4770) +- gather additional config files even if root .vitepress/config is not present ([26f178c](https://github.com/vuejs/vitepress/commit/26f178cfaa330a017bb69b1ec6bd482d63a100a9)) +- set `preserveEntrySignatures` for rolldown-vite ([#4784](https://github.com/vuejs/vitepress/issues/4784)) ([4351bc0](https://github.com/vuejs/vitepress/commit/4351bc0b831277401e08b350d7d7c0ab9ea0c9ed)) +- skip fields not supported by rolldown for rolldown-vite ([#4747](https://github.com/vuejs/vitepress/issues/4747)) ([4e3fce4](https://github.com/vuejs/vitepress/commit/4e3fce40c9bab261f3c5e31833475c3e2c6ba0cf)) +- **theme/regression:** code blocks not aligned properly in rtl layouts ([a643347](https://github.com/vuejs/vitepress/commit/a64334753079a5b874a482508d9ee255d2a0ea38)) +- **theme:** hide native search input cancel button ([#4723](https://github.com/vuejs/vitepress/issues/4723)) ([2c4944f](https://github.com/vuejs/vitepress/commit/2c4944f06ccf46fcf58fb18a1819fd167c9533cc)) +- **theme:** prevent error in handleSearchHotKey method ([#4782](https://github.com/vuejs/vitepress/issues/4782)) ([21fcecc](https://github.com/vuejs/vitepress/commit/21fcecce0581d0c461bc15e03429f61ff444a655)) +- use v-pre for mathjax instead of isCustomElement ([c9b8928](https://github.com/vuejs/vitepress/commit/c9b89282f3573998cfc4103bbddbd73d2529cb66)) + +### Features + +- use `oxc-minify` instead of `transformWithEsbuild` when rolldown-vite is used ([#4748](https://github.com/vuejs/vitepress/issues/4748)) ([7c1dc48](https://github.com/vuejs/vitepress/commit/7c1dc48b2fd08e128f7bbe26690fb6534dfb4b95)) + +## [2.0.0-alpha.5](https://github.com/vuejs/vitepress/compare/v2.0.0-alpha.4...v2.0.0-alpha.5) (2025-04-21) + +### Bug Fixes + +- don't remove shiki styles from `pre` and remove unnecessary transformers (#4652) ([db58af5](https://github.com/vuejs/vitepress/commit/db58af5c66e563e7663084057a9853d8f2da984c)), closes [#4652](https://github.com/vuejs/vitepress/issues/4652) +- normalize url fragments in internal links to correctly resolve to anchors ([#4628](https://github.com/vuejs/vitepress/issues/4628)) ([e25d080](https://github.com/vuejs/vitepress/commit/e25d0805505db2f1116e99d38a488d5cb39ed426)), closes [#4605](https://github.com/vuejs/vitepress/issues/4605) +- **theme-default:** ensure proper sizing of SVG hero images ([#4639](https://github.com/vuejs/vitepress/issues/4639)) ([7d94481](https://github.com/vuejs/vitepress/commit/7d9448192079e59493aa5c1e86cdf6d6deae8e36)) + +### Features + +- add `isHome` frontmatter option (#4673) ([544cd81](https://github.com/vuejs/vitepress/commit/544cd8125985b9e3af7fee68ea9592d159799e01)), closes [#4673](https://github.com/vuejs/vitepress/issues/4673) +- add `custom-block-title-default` class when default title is used for containers ([#4643](https://github.com/vuejs/vitepress/issues/4643)) ([63079bf](https://github.com/vuejs/vitepress/commit/63079bff03b15861d174199f7361a2aff84380e0)) +- add `dir=ltr` by default on code block pre elements instead of relying on css ([19faa16](https://github.com/vuejs/vitepress/commit/19faa16169b44f52bedf1401b4a97b2a8ffdeacb)) +- **default-theme:** make VPButton slottable ([#4689](https://github.com/vuejs/vitepress/issues/4689)) ([0b70397](https://github.com/vuejs/vitepress/commit/0b7039719782e85119ad22be5c89ef3d233ffaae)) +- support distributed config files ([#4660](https://github.com/vuejs/vitepress/issues/4660)) ([c5e2e4d](https://github.com/vuejs/vitepress/commit/c5e2e4db818c06f3c1b458753f22fb6ec1609628)) +- **theme:** make "Take me home" button's link customizable ([#4658](https://github.com/vuejs/vitepress/issues/4658)) ([0267dca](https://github.com/vuejs/vitepress/commit/0267dcafa20beea24ef359d24bb1fa99e1ffda49)) + +### Performance Improvements + +- call `module.enableCompileCache()` ([70de34c](https://github.com/vuejs/vitepress/commit/70de34c0387d9668ada3ea9a795f9ebee3535f5b)) +- hoist expensive operations in useLayout ([e5ab067](https://github.com/vuejs/vitepress/commit/e5ab0676a9a8dc607e213eb691439b2e4ee472b7)) + +### BREAKING CHANGES + +- `useLocalNav` and `useSidebar` are removed in favor of `useLayout`. To migrate, just do find and replace. Sidebar controls are no longer exported, but we didn't find any usage on GitHub. If there is demand, we can export respective composables later. `DefaultTheme.DocSidebar` and `DefaultTheme.DocLocalNav` types are also removed. +- `vp-adaptive-theme` class is no longer added to code blocks when there is single theme. Theme authors supporting single code theme can use `.shiki:not(.shiki-themes)` as selector. Alternatively, it might be better to use the bg/fg variables set on the `.shiki` block to keep things generic. +- `vp-code` class is no longer added to code blocks. Use `.shiki` or `pre.shiki` or `[class*='language-'] pre` instead. People not customizing their themes are not affected. + ## [2.0.0-alpha.4](https://github.com/vuejs/vitepress/compare/v2.0.0-alpha.3...v2.0.0-alpha.4) (2025-03-09) ### Bug Fixes @@ -2198,7 +2341,6 @@ This version uses Vue 3.2.0. ### BREAKING CHANGES - Some config options have changed. - - `vueOptions` renamed to `vue` - `alias` option has been removed. Use `vite.resovle.alias` instead. @@ -2216,7 +2358,6 @@ This version uses Vue 3.2.0. ### BREAKING CHANGES - The following methods are removed. - - `useSiteData` - `useSiteDataByRoute` - `usePageData` diff --git a/README.md b/README.md index 134226a4..c6533b30 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # VitePress 📝💨 -[![test](https://github.com/vuejs/vitepress/workflows/Test/badge.svg)](https://github.com/vuejs/vitepress/actions) -[![npm](https://img.shields.io/npm/v/vitepress)](https://www.npmjs.com/package/vitepress) +[![test](https://github.com/vuejs/vitepress/actions/workflows/test.yml/badge.svg?branch=main)](https://github.com/vuejs/vitepress/actions/workflows/test.yml) +[![npm](https://img.shields.io/npm/v/vitepress/next)](https://www.npmjs.com/package/vitepress/v/next) [![nightly releases](https://img.shields.io/badge/nightly-releases-orange)](https://nightly.akryum.dev/vuejs/vitepress) [![chat](https://img.shields.io/badge/chat-discord-blue?logo=discord)](https://chat.vuejs.org) diff --git a/__tests__/e2e/.vitepress/theme/components/ApiPreference.vue b/__tests__/e2e/.vitepress/theme/components/ApiPreference.vue index 12207764..c286640b 100644 --- a/__tests__/e2e/.vitepress/theme/components/ApiPreference.vue +++ b/__tests__/e2e/.vitepress/theme/components/ApiPreference.vue @@ -30,7 +30,7 @@ function removeSpaces(str: string) { diff --git a/__tests__/e2e/data-loading/data.test.ts b/__tests__/e2e/data-loading/data.test.ts index fafc403a..21cfa061 100644 --- a/__tests__/e2e/data-loading/data.test.ts +++ b/__tests__/e2e/data-loading/data.test.ts @@ -52,9 +52,7 @@ describe('static data file support in vite 3', () => { await page.waitForFunction( () => document.querySelector('pre#basic')?.textContent === - JSON.stringify([{ a: false }, { b: true }], null, 2), - undefined, - { timeout: 3000 } + JSON.stringify([{ a: false }, { b: true }], null, 2) ) } finally { await fs.writeFile(a, JSON.stringify({ a: true }, null, 2) + '\n') @@ -67,9 +65,7 @@ describe('static data file support in vite 3', () => { await page.waitForFunction( () => document.querySelector('pre#basic')?.textContent === - JSON.stringify([{ a: true }], null, 2), - undefined, - { timeout: 3000 } + JSON.stringify([{ a: true }], null, 2) ) err = false } finally { @@ -83,9 +79,7 @@ describe('static data file support in vite 3', () => { await page.waitForFunction( () => document.querySelector('pre#basic')?.textContent === - JSON.stringify([{ a: true }, { b: false }], null, 2), - undefined, - { timeout: 3000 } + JSON.stringify([{ a: true }, { b: false }], null, 2) ) } finally { await fs.writeFile(b, JSON.stringify({ b: true }, null, 2) + '\n') diff --git a/__tests__/e2e/dynamic-routes/[id].paths.ts b/__tests__/e2e/dynamic-routes/[id].paths.ts index 12a8bc32..a1cb6fef 100644 --- a/__tests__/e2e/dynamic-routes/[id].paths.ts +++ b/__tests__/e2e/dynamic-routes/[id].paths.ts @@ -6,7 +6,7 @@ export default defineRoutes({ // console.log('watchedFiles', watchedFiles) return paths }, - watch: ['**/data-loading/**/*.json'], + watch: ['../data-loading/**/*.json'], async transformPageData(pageData) { // console.log('transformPageData', pageData.filePath) pageData.title += ' - transformed' diff --git a/__tests__/unit/node/postcss/__snapshots__/isolateStyles.test.ts.snap b/__tests__/unit/node/postcss/__snapshots__/isolateStyles.test.ts.snap new file mode 100644 index 00000000..c781b64c --- /dev/null +++ b/__tests__/unit/node/postcss/__snapshots__/isolateStyles.test.ts.snap @@ -0,0 +1,77 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`node/postcss/isolateStyles > transforms selectors and skips keyframes 1`] = ` +" +/* simple classes */ +.example:not(:where(.vp-raw, .vp-raw *)) { color: red; } +.class-a:not(:where(.vp-raw, .vp-raw *)) { color: coral; } +.class-b:not(:where(.vp-raw, .vp-raw *)) { color: deepskyblue; } + +/* escaped colon in class */ +.baz\\:not\\(.bar\\):not(:where(.vp-raw, .vp-raw *)) { display: block; } +.disabled\\:opacity-50:not(:where(.vp-raw, .vp-raw *)):disabled { opacity: .5; } + +/* pseudos (class + element) */ +.button:not(:where(.vp-raw, .vp-raw *)):hover { color: pink; } +.button:not(:where(.vp-raw, .vp-raw *)):focus:hover { color: hotpink; } +.item:not(:where(.vp-raw, .vp-raw *))::before { content: '•'; } +:not(:where(.vp-raw, .vp-raw *))::first-letter { color: pink; } +:not(:where(.vp-raw, .vp-raw *))::before { content: ''; } + +/* universal + :not */ +*:not(:where(.vp-raw, .vp-raw *)) { background-color: red; } +*:not(:where(.vp-raw, .vp-raw *)):not(.b) { text-transform: uppercase; } + +/* combinators */ +.foo:hover .bar:not(:where(.vp-raw, .vp-raw *)) { background: blue; } +ul > li.active:not(:where(.vp-raw, .vp-raw *)) { color: green; } +a + b ~ c:not(:where(.vp-raw, .vp-raw *)) { color: orange; } + +/* ids + attribute selectors */ +#wow:not(:where(.vp-raw, .vp-raw *)) { color: yellow; } +[data-world] .d:not(:where(.vp-raw, .vp-raw *)) { padding: 10px 20px; } + +/* :root and chained tags */ +:not(:where(.vp-raw, .vp-raw *)):root { --bs-blue: #0d6efd; } +:root .a:not(:where(.vp-raw, .vp-raw *)) { --bs-green: #bada55; } +html:not(:where(.vp-raw, .vp-raw *)) { margin: 0; } +body:not(:where(.vp-raw, .vp-raw *)) { padding: 0; } +html body div:not(:where(.vp-raw, .vp-raw *)) { color: blue; } + +/* grouping with commas */ +.a:not(:where(.vp-raw, .vp-raw *)), .b:not(:where(.vp-raw, .vp-raw *)) { color: red; } + +/* multiple repeated groups to ensure stability */ +.a:not(:where(.vp-raw, .vp-raw *)), .b:not(:where(.vp-raw, .vp-raw *)) { color: coral; } +.a:not(:where(.vp-raw, .vp-raw *)) { animation: glow 1s linear infinite alternate; } + +/* nested blocks */ +.foo:not(:where(.vp-raw, .vp-raw *)) { + svg:not(:where(.vp-raw, .vp-raw *)) { display: none; } + .bar:not(:where(.vp-raw, .vp-raw *)) { display: inline; } +} + +/* standalone pseudos */ +:not(:where(.vp-raw, .vp-raw *)):first-child { color: pink; } +:not(:where(.vp-raw, .vp-raw *)):hover { color: blue; } +:not(:where(.vp-raw, .vp-raw *)):active { color: red; } + +/* keyframes (should be ignored) */ +@keyframes fade { + from { opacity: 0; } + to { opacity: 1; } +} +@-webkit-keyframes glow { + from { color: coral; } + to { color: red; } +} +@-moz-keyframes glow { + from { color: coral; } + to { color: red; } +} +@-o-keyframes glow { + from { color: coral; } + to { color: red; } +} +" +`; diff --git a/__tests__/unit/node/postcss/isolateStyles.test.ts b/__tests__/unit/node/postcss/isolateStyles.test.ts new file mode 100644 index 00000000..609a4463 --- /dev/null +++ b/__tests__/unit/node/postcss/isolateStyles.test.ts @@ -0,0 +1,93 @@ +import { postcssIsolateStyles } from 'node/postcss/isolateStyles' +import postcss from 'postcss' + +const INPUT_CSS = ` +/* simple classes */ +.example { color: red; } +.class-a { color: coral; } +.class-b { color: deepskyblue; } + +/* escaped colon in class */ +.baz\\:not\\(.bar\\) { display: block; } +.disabled\\:opacity-50:disabled { opacity: .5; } + +/* pseudos (class + element) */ +.button:hover { color: pink; } +.button:focus:hover { color: hotpink; } +.item::before { content: '•'; } +::first-letter { color: pink; } +::before { content: ''; } + +/* universal + :not */ +* { background-color: red; } +*:not(.b) { text-transform: uppercase; } + +/* combinators */ +.foo:hover .bar { background: blue; } +ul > li.active { color: green; } +a + b ~ c { color: orange; } + +/* ids + attribute selectors */ +#wow { color: yellow; } +[data-world] .d { padding: 10px 20px; } + +/* :root and chained tags */ +:root { --bs-blue: #0d6efd; } +:root .a { --bs-green: #bada55; } +html { margin: 0; } +body { padding: 0; } +html body div { color: blue; } + +/* grouping with commas */ +.a, .b { color: red; } + +/* multiple repeated groups to ensure stability */ +.a, .b { color: coral; } +.a { animation: glow 1s linear infinite alternate; } + +/* nested blocks */ +.foo { + svg { display: none; } + .bar { display: inline; } +} + +/* standalone pseudos */ +:first-child { color: pink; } +:hover { color: blue; } +:active { color: red; } + +/* keyframes (should be ignored) */ +@keyframes fade { + from { opacity: 0; } + to { opacity: 1; } +} +@-webkit-keyframes glow { + from { color: coral; } + to { color: red; } +} +@-moz-keyframes glow { + from { color: coral; } + to { color: red; } +} +@-o-keyframes glow { + from { color: coral; } + to { color: red; } +} +` + +describe('node/postcss/isolateStyles', () => { + test('transforms selectors and skips keyframes', () => { + const out = run(INPUT_CSS) + expect(out.css).toMatchSnapshot() + }) + + test('idempotent (running twice produces identical CSS)', () => { + const first = run(INPUT_CSS).css + const second = run(first).css + expect(second).toBe(first) + }) +}) + +function run(css: string, from = 'src/styles/vp-doc.css') { + return postcss([postcssIsolateStyles()]).process(css, { from }) +} diff --git a/bin/vitepress.js b/bin/vitepress.js index 7c50ec90..9cf31ae0 100755 --- a/bin/vitepress.js +++ b/bin/vitepress.js @@ -1,2 +1,16 @@ #!/usr/bin/env node +// @ts-check + +import module from 'node:module' + +// https://github.com/vitejs/vite/blob/6c8a5a27e645a182f5b03a4ed6aa726eab85993f/packages/vite/bin/vite.js#L48-L63 +try { + module.enableCompileCache?.() + setTimeout(() => { + try { + module.flushCompileCache?.() + } catch {} + }, 10 * 1000).unref() +} catch {} + import('../dist/node/cli.js') diff --git a/docs/.vitepress/config/shared.ts b/docs/.vitepress/config.ts similarity index 56% rename from docs/.vitepress/config/shared.ts rename to docs/.vitepress/config.ts index 1f4961d2..7be361c8 100644 --- a/docs/.vitepress/config/shared.ts +++ b/docs/.vitepress/config.ts @@ -1,17 +1,18 @@ -import { defineConfig } from 'vitepress' +import { + defineConfig, + resolveSiteDataByRoute, + type HeadConfig +} from 'vitepress' import { groupIconMdPlugin, groupIconVitePlugin, localIconLoader } from 'vitepress-plugin-group-icons' -import { search as esSearch } from './es' -import { search as faSearch } from './fa' -import { search as koSearch } from './ko' -import { search as ptSearch } from './pt' -import { search as ruSearch } from './ru' -import { search as zhSearch } from './zh' +import llmstxt from 'vitepress-plugin-llms' + +const prod = !!process.env.NETLIFY -export const shared = defineConfig({ +export default defineConfig({ title: 'VitePress', rewrites: { @@ -51,6 +52,8 @@ export const shared = defineConfig({ return 'Скопировать код' case 'zh': return '复制代码' + case 'ja': + return 'コードをコピー' default: return 'Copy code' } @@ -71,18 +74,35 @@ export const shared = defineConfig({ } }, - /* prettier-ignore */ head: [ - ['link', { rel: 'icon', type: 'image/svg+xml', href: '/vitepress-logo-mini.svg' }], - ['link', { rel: 'icon', type: 'image/png', href: '/vitepress-logo-mini.png' }], + [ + 'link', + { rel: 'icon', type: 'image/svg+xml', href: '/vitepress-logo-mini.svg' } + ], + [ + 'link', + { rel: 'icon', type: 'image/png', href: '/vitepress-logo-mini.png' } + ], ['meta', { name: 'theme-color', content: '#5f67ee' }], ['meta', { property: 'og:type', content: 'website' }], - ['meta', { property: 'og:locale', content: 'en' }], - ['meta', { property: 'og:title', content: 'VitePress | Vite & Vue Powered Static Site Generator' }], ['meta', { property: 'og:site_name', content: 'VitePress' }], - ['meta', { property: 'og:image', content: 'https://vitepress.dev/vitepress-og.jpg' }], + [ + 'meta', + { + property: 'og:image', + content: 'https://vitepress.dev/vitepress-og.jpg' + } + ], ['meta', { property: 'og:url', content: 'https://vitepress.dev/' }], - ['script', { src: 'https://cdn.usefathom.com/script.js', 'data-site': 'AZBRSFGG', 'data-spa': 'auto', defer: '' }] + [ + 'script', + { + src: 'https://cdn.usefathom.com/script.js', + 'data-site': 'AZBRSFGG', + 'data-spa': 'auto', + defer: '' + } + ] ], themeConfig: { @@ -98,30 +118,57 @@ export const shared = defineConfig({ appId: '8J64VVRP8K', apiKey: '52f578a92b88ad6abde815aae2b0ad7c', indexName: 'vitepress', - locales: { - ...zhSearch, - ...ptSearch, - ...ruSearch, - ...esSearch, - ...koSearch, - ...faSearch - } + askAi: 'YaVSonfX5bS8' } }, carbonAds: { code: 'CEBDT27Y', placement: 'vuejsorg' } }, + + locales: { + root: { label: 'English', lang: 'en-US', dir: 'ltr' }, + zh: { label: '简体中文', lang: 'zh-Hans', dir: 'ltr' }, + pt: { label: 'Português', lang: 'pt-BR', dir: 'ltr' }, + ru: { label: 'Русский', lang: 'ru-RU', dir: 'ltr' }, + es: { label: 'Español', lang: 'es', dir: 'ltr' }, + ko: { label: '한국어', lang: 'ko-KR', dir: 'ltr' }, + fa: { label: 'فارسی', lang: 'fa-IR', dir: 'rtl' }, + ja: { label: '日本語', lang: 'ja', dir: 'ltr' } + }, + vite: { plugins: [ groupIconVitePlugin({ customIcon: { vitepress: localIconLoader( import.meta.url, - '../../public/vitepress-logo-mini.svg' + '../public/vitepress-logo-mini.svg' ), firebase: 'logos:firebase' } - }) - ] - } + }), + prod && + llmstxt({ + workDir: 'en', + ignoreFiles: ['index.md'] + }) + ], + experimental: { + enableNativePlugin: true + } + }, + + transformPageData: prod + ? (pageData, ctx) => { + const site = resolveSiteDataByRoute( + ctx.siteConfig.site, + pageData.relativePath + ) + const title = `${pageData.title || site.title} | ${pageData.description || site.description}` + ;((pageData.frontmatter.head ??= []) as HeadConfig[]).push( + ['meta', { property: 'og:locale', content: site.lang }], + ['meta', { property: 'og:title', content: title }] + ) + } + : undefined }) diff --git a/docs/.vitepress/config/index.ts b/docs/.vitepress/config/index.ts deleted file mode 100644 index 08a81fb9..00000000 --- a/docs/.vitepress/config/index.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { defineConfig } from 'vitepress' -import { shared } from './shared' -import { en } from './en' -import { zh } from './zh' -import { pt } from './pt' -import { ru } from './ru' -import { es } from './es' -import { ko } from './ko' -import { fa } from './fa' - -export default defineConfig({ - ...shared, - locales: { - root: { label: 'English', ...en }, - zh: { label: '简体中文', ...zh }, - pt: { label: 'Português', ...pt }, - ru: { label: 'Русский', ...ru }, - es: { label: 'Español', ...es }, - ko: { label: '한국어', ...ko }, - fa: { label: 'فارسی', ...fa } - } -}) diff --git a/docs/.vitepress/theme/styles.css b/docs/.vitepress/theme/styles.css index ce1c75d2..2635e80d 100644 --- a/docs/.vitepress/theme/styles.css +++ b/docs/.vitepress/theme/styles.css @@ -1,5 +1,3 @@ -@import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@100..900&display=swap'); - :root:where(:lang(fa)) { --vp-font-family-base: 'Vazirmatn', 'Inter', ui-sans-serif, system-ui, sans-serif, diff --git a/docs/.vitepress/config/en.ts b/docs/config.ts similarity index 94% rename from docs/.vitepress/config/en.ts rename to docs/config.ts index 1f619347..8620d955 100644 --- a/docs/.vitepress/config/en.ts +++ b/docs/config.ts @@ -1,11 +1,10 @@ import { createRequire } from 'module' -import { defineConfig, type DefaultTheme } from 'vitepress' +import { defineAdditionalConfig, type DefaultTheme } from 'vitepress' const require = createRequire(import.meta.url) const pkg = require('vitepress/package.json') -export const en = defineConfig({ - lang: 'en-US', +export default defineAdditionalConfig({ description: 'Vite & Vue powered static site generator.', themeConfig: { @@ -43,6 +42,10 @@ function nav(): DefaultTheme.NavItem[] { { text: pkg.version, items: [ + { + text: '1.6.4', + link: 'https://vuejs.github.io/vitepress/v1/' + }, { text: 'Changelog', link: 'https://github.com/vuejs/vitepress/blob/main/CHANGELOG.md' diff --git a/docs/en/guide/deploy.md b/docs/en/guide/deploy.md index a4093df2..29d2e1b4 100644 --- a/docs/en/guide/deploy.md +++ b/docs/en/guide/deploy.md @@ -111,7 +111,7 @@ Set up a new project and change these settings using your dashboard: - **Build Command:** `npm run docs:build` - **Output Directory:** `docs/.vitepress/dist` -- **Node Version:** `18` (or above) +- **Node Version:** `20` (or above) ::: warning Don't enable options like _Auto Minify_ for HTML code. It will remove comments from output which have meaning to Vue. You may see hydration mismatch errors if they get removed. @@ -163,7 +163,7 @@ Don't enable options like _Auto Minify_ for HTML code. It will remove comments f - name: Setup Node uses: actions/setup-node@v4 with: - node-version: 20 + node-version: 22 cache: npm # or pnpm / yarn - name: Setup Pages uses: actions/configure-pages@v4 @@ -294,6 +294,10 @@ You can deploy your VitePress website on [Kinsta](https://kinsta.com/static-site You can deploy your VitePress project to [Stormkit](https://www.stormkit.io) by following these [instructions](https://stormkit.io/blog/how-to-deploy-vitepress). +### CloudRay + +You can deploy your VitePress project with [CloudRay](https://cloudray.io/) by following these [instructions](https://cloudray.io/articles/how-to-deploy-vitepress-site). + ### Nginx Here is a example of an Nginx server block configuration. This setup includes gzip compression for common text-based assets, rules for serving your VitePress site's static files with proper caching headers as well as handling `cleanUrls: true`. diff --git a/docs/en/guide/extending-default-theme.md b/docs/en/guide/extending-default-theme.md index 799d1773..4d18d8c5 100644 --- a/docs/en/guide/extending-default-theme.md +++ b/docs/en/guide/extending-default-theme.md @@ -70,7 +70,7 @@ If your font is a local file referenced via `@font-face`, it will be processed a export default { transformHead({ assets }) { // adjust the regex accordingly to match your font - const myFontFile = assets.find(file => /font-name\.\w+\.woff2/) + const myFontFile = assets.find(file => /font-name\.[\w-]+\.woff2/.test(file)) if (myFontFile) { return [ [ @@ -252,6 +252,7 @@ provide('toggle-appearance', async ({ clientX: x, clientY: y }: MouseEvent) => { { duration: 300, easing: 'ease-in', + fill: 'forwards', pseudoElement: `::view-transition-${isDark.value ? 'old' : 'new'}(root)` } ) @@ -319,7 +320,7 @@ export default defineConfig({ { find: /^.*\/VPNavBar\.vue$/, replacement: fileURLToPath( - new URL('./components/CustomNavBar.vue', import.meta.url) + new URL('./theme/components/CustomNavBar.vue', import.meta.url) ) } ] diff --git a/docs/en/guide/getting-started.md b/docs/en/guide/getting-started.md index 01b64a1b..79cb3180 100644 --- a/docs/en/guide/getting-started.md +++ b/docs/en/guide/getting-started.md @@ -18,39 +18,19 @@ VitePress can be used on its own, or be installed into an existing project. In b ::: code-group ```sh [npm] -$ npm add -D vitepress +$ npm add -D vitepress@next ``` ```sh [pnpm] -$ pnpm add -D vitepress +$ pnpm add -D vitepress@next ``` ```sh [yarn] -$ yarn add -D vitepress -``` - -```sh [yarn (pnp)] -$ yarn add -D vitepress vue +$ yarn add -D vitepress@next vue ``` ```sh [bun] -$ bun add -D vitepress -``` - -::: - -::: details Getting missing peer deps warnings? -If using PNPM, you will notice a missing peer warning for `@docsearch/js`. This does not prevent VitePress from working. If you wish to suppress this warning, add the following to your `package.json`: - -```json -"pnpm": { - "peerDependencyRules": { - "ignoreMissing": [ - "@algolia/client-search", - "search-insights" - ] - } -} +$ bun add -D vitepress@next ``` ::: diff --git a/docs/en/guide/markdown.md b/docs/en/guide/markdown.md index bbd2b2a3..e1be3e6b 100644 --- a/docs/en/guide/markdown.md +++ b/docs/en/guide/markdown.md @@ -277,11 +277,11 @@ Wraps in a `
` } ``` - It uses [`postcss-prefix-selector`](https://github.com/RadValentin/postcss-prefix-selector) under the hood. You can pass its options like this: + You can pass its options like this: ```js postcssIsolateStyles({ - includeFiles: [/vp-doc\.css/] // defaults to /base\.css/ + includeFiles: [/custom\.css/] // defaults to [/vp-doc\.css/, /base\.css/] }) ``` @@ -365,7 +365,7 @@ export default { A [list of valid languages](https://shiki.style/languages) is available on Shiki's repository. -You may also customize syntax highlight theme in app config. Please see [`markdown` options](../reference/site-config#markdown) for more details. +You may also customize syntax highlight theme, configure language aliases, and set custom language labels in app config. Please see [`markdown` options](../reference/site-config#markdown) for more details. ## Line Highlighting in Code Blocks @@ -781,7 +781,7 @@ You can also [import snippets](#import-code-snippets) in code groups: You can include a markdown file in another markdown file, even nested. ::: tip -You can also prefix the markdown path with `@`, it will act as the source root. By default, it's the VitePress project root, unless `srcDir` is configured. +You can also prefix the markdown path with `@`, and it will act as the source root. By default, the source root is the VitePress project root, unless `srcDir` is configured. ::: For example, you can include a relative markdown file using this: diff --git a/docs/en/guide/routing.md b/docs/en/guide/routing.md index 1f3569a7..bacdbf6b 100644 --- a/docs/en/guide/routing.md +++ b/docs/en/guide/routing.md @@ -336,6 +336,46 @@ export default { } ``` +### Watching Template and Data Files + +When generating page content from templates or external data sources, you can use the watch option to automatically rebuild pages when those files change during development: + +```js +// posts/[slug].paths.js +import fs from 'node:fs' +import { renderTemplate } from './templates/renderer.js' + +export default { + // Watch for changes to template files and data sources + watch: [ + './templates/**/*.njk', // Template files + '../data/**/*.json' // Data files + ], + + paths(watchedFiles) { + // watchedFiles will be an array of absolute paths of the matched files + // Read data files to generate routes + const dataFiles = watchedFiles.filter(file => file.endsWith('.json')) + + return dataFiles.map(file => { + const data = JSON.parse(fs.readFileSync(file, 'utf-8')) + + return { + params: { slug: data.slug }, + content: renderTemplate(data) // Use template to generate content + } + }) + } +} +``` + +The `watch` option works the same way as in [data loaders](./data-loading#data-from-local-files): + +- Accepts [glob patterns](https://github.com/mrmlnc/fast-glob#pattern-syntax) to match files +- Patterns are relative to the `.paths.js` file itself +- Changes to watched files trigger page regeneration and HMR during development +- In production builds, all pages are generated once regardless of watch configuration + ### Accessing Params in Page You can use the params to pass additional data to each page. The Markdown route file can access the current page params in Vue expressions via the `$params` global property: diff --git a/docs/en/guide/what-is-vitepress.md b/docs/en/guide/what-is-vitepress.md index a498d17e..3407c76d 100644 --- a/docs/en/guide/what-is-vitepress.md +++ b/docs/en/guide/what-is-vitepress.md @@ -12,7 +12,7 @@ Just want to try it out? Skip to the [Quickstart](./getting-started). - **Documentation** - VitePress ships with a default theme designed for technical documentation. It powers this page you are reading right now, along with the documentation for [Vite](https://vitejs.dev/), [Rollup](https://rollupjs.org/), [Pinia](https://pinia.vuejs.org/), [VueUse](https://vueuse.org/), [Vitest](https://vitest.dev/), [D3](https://d3js.org/), [UnoCSS](https://unocss.dev/), [Iconify](https://iconify.design/) and [many more](https://www.vuetelescope.com/explore?framework.slug=vitepress). + VitePress ships with a default theme designed for technical documentation. It powers this page you are reading right now, along with the documentation for [Vite](https://vitejs.dev/), [Rollup](https://rollupjs.org/), [Pinia](https://pinia.vuejs.org/), [VueUse](https://vueuse.org/), [Vitest](https://vitest.dev/), [D3](https://d3js.org/), [UnoCSS](https://unocss.dev/), [Iconify](https://iconify.design/) and [many more](https://github.com/search?q=/"vitepress":+/+language:json&type=code). The [official Vue.js documentation](https://vuejs.org/) is also based on VitePress, but uses a custom theme shared between multiple translations. @@ -50,8 +50,8 @@ Unlike many traditional SSGs where each navigation results in a full page reload ## What About VuePress? -VitePress is the spiritual successor of VuePress. The original VuePress was based on Vue 2 and webpack. With Vue 3 and Vite under the hood, VitePress provides significantly better DX, better production performance, a more polished default theme, and a more flexible customization API. +VitePress is the spiritual successor of VuePress 1. The original VuePress 1 was based on Vue 2 and webpack. With Vue 3 and Vite under the hood, VitePress provides significantly better DX, better production performance, a more polished default theme, and a more flexible customization API. -The API difference between VitePress and VuePress mostly lies in theming and customization. If you are using VuePress 1 with the default theme, it should be relatively straightforward to migrate to VitePress. +The API difference between VitePress and VuePress 1 mostly lies in theming and customization. If you are using VuePress 1 with the default theme, it should be relatively straightforward to migrate to VitePress. -There has also been effort invested into VuePress 2, which also supports Vue 3 and Vite with more compatibility with VuePress 1. However, maintaining two SSGs in parallel isn't sustainable, so the Vue team has decided to focus on VitePress as the main recommended SSG in the long run. +Maintaining two SSGs in parallel isn't sustainable, so the Vue team has decided to focus on VitePress as the main recommended SSG in the long run. Now VuePress 1 has been deprecated, and VuePress 2 has been handed over to the VuePress community team for further development and maintenance. diff --git a/docs/en/index.md b/docs/en/index.md index c91ce953..6c49a313 100644 --- a/docs/en/index.md +++ b/docs/en/index.md @@ -1,9 +1,6 @@ --- layout: home -title: VitePress -titleTemplate: Vite & Vue Powered Static Site Generator - hero: name: VitePress text: Vite & Vue Powered Static Site Generator @@ -11,10 +8,10 @@ hero: actions: - theme: brand text: What is VitePress? - link: /guide/what-is-vitepress + link: ./guide/what-is-vitepress - theme: alt text: Quickstart - link: /guide/getting-started + link: ./guide/getting-started - theme: alt text: GitHub link: https://github.com/vuejs/vitepress diff --git a/docs/en/reference/cli.md b/docs/en/reference/cli.md index 85517620..9f2cadfa 100644 --- a/docs/en/reference/cli.md +++ b/docs/en/reference/cli.md @@ -43,7 +43,6 @@ vitepress build [root] | `--base ` | Public base path (default: `/`) (`string`) | | `--target ` | Transpile target (default: `"modules"`) (`string`) | | `--outDir ` | Output directory relative to **cwd** (default: `/.vitepress/dist`) (`string`) | -| `--minify [minifier]` | Enable/disable minification, or specify minifier to use (default: `"esbuild"`) (`boolean \| "terser" \| "esbuild"`) | | `--assetsInlineLimit ` | Static asset base64 inline threshold in bytes (default: `4096`) (`number`) | ## `vitepress preview` diff --git a/docs/en/reference/default-theme-config.md b/docs/en/reference/default-theme-config.md index c8afc554..4868cda3 100644 --- a/docs/en/reference/default-theme-config.md +++ b/docs/en/reference/default-theme-config.md @@ -89,7 +89,7 @@ type NavItem = NavItemWithLink | NavItemWithChildren interface NavItemWithLink { text: string - link: string + link: string | ((payload: PageData) => string) activeMatch?: string target?: string rel?: string @@ -457,3 +457,38 @@ Can be used to customize the label of the skip to content link. This link is sho - Default: `false` Whether to show an external link icon next to external links in markdown. + +## `useLayout` + +Returns layout-related data. The returned object has the following type: + +```ts +interface { + isHome: ComputedRef + + sidebar: Readonly> + sidebarGroups: ComputedRef + hasSidebar: ComputedRef + isSidebarEnabled: ComputedRef + + hasAside: ComputedRef + leftAside: ComputedRef + + headers: Readonly> + hasLocalNav: ComputedRef +} +``` + +**Example:** + +```vue + + + +``` diff --git a/docs/en/reference/default-theme-last-updated.md b/docs/en/reference/default-theme-last-updated.md index 00fed72a..55603269 100644 --- a/docs/en/reference/default-theme-last-updated.md +++ b/docs/en/reference/default-theme-last-updated.md @@ -2,8 +2,27 @@ The update time of the last content will be displayed in the lower right corner of the page. To enable it, add `lastUpdated` options to your config. -::: tip -You need to commit the markdown file to see the updated time. +::: info +VitePress displays the "last updated" time using the timestamp of the most recent Git commit for each file. To enable this, the Markdown file must be committed to Git. + +Internally, VitePress runs `git log -1 --pretty="%ai"` on each file to retrieve its timestamp. If all pages show the same update time, it's likely due to shallow cloning (common in CI environments), which limits Git history. + +To fix this in **GitHub Actions**, use the following in your workflow: + +```yaml{4} +- name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 +``` + +Other CI/CD platforms have similar settings. + +If such options aren't available, you can prepend the `docs:build` command in your `package.json` with a manual fetch: + +```json +"docs:build": "git fetch --unshallow && vitepress build docs" +``` ::: ## Site-Level Config diff --git a/docs/en/reference/default-theme-nav.md b/docs/en/reference/default-theme-nav.md index b55a63cb..f7be114d 100644 --- a/docs/en/reference/default-theme-nav.md +++ b/docs/en/reference/default-theme-nav.md @@ -55,6 +55,8 @@ export default { The `text` is the actual text displayed in nav, and the `link` is the link that will be navigated to when the text is clicked. For the link, set path to the actual file without `.md` prefix, and always start with `/`. +The `link` can also be a function that accepts [`PageData`](./runtime-api#usedata) as the argument and returns the path. + Nav links can also be dropdown menus. To do this, set `items` key on link option. ```js diff --git a/docs/en/reference/default-theme-search.md b/docs/en/reference/default-theme-search.md index d647e32e..6bc2f446 100644 --- a/docs/en/reference/default-theme-search.md +++ b/docs/en/reference/default-theme-search.md @@ -6,7 +6,7 @@ outline: deep ## Local Search -VitePress supports fuzzy full-text search using a in-browser index thanks to [minisearch](https://github.com/lucaong/minisearch/). To enable this feature, simply set the `themeConfig.search.provider` option to `'local'` in your `.vitepress/config.ts` file: +VitePress supports fuzzy full-text search using an in-browser index thanks to [minisearch](https://github.com/lucaong/minisearch/). To enable this feature, simply set the `themeConfig.search.provider` option to `'local'` in your `.vitepress/config.ts` file: ```ts import { defineConfig } from 'vitepress' @@ -233,10 +233,16 @@ export default defineConfig({ }, modal: { searchBox: { - resetButtonTitle: '清除查询条件', - resetButtonAriaLabel: '清除查询条件', - cancelButtonText: '取消', - cancelButtonAriaLabel: '取消' + clearButtonTitle: '清除查询条件', + clearButtonAriaLabel: '清除查询条件', + closeButtonText: '关闭', + closeButtonAriaLabel: '关闭', + placeholderText: '搜索文档', + placeholderTextAskAi: '向 AI 提问:', + placeholderTextAskAiStreaming: '回答中...', + searchInputLabel: '搜索', + backToKeywordSearchButtonText: '返回关键字搜索', + backToKeywordSearchButtonAriaLabel: '返回关键字搜索' }, startScreen: { recentSearchesTitle: '搜索历史', @@ -244,23 +250,48 @@ export default defineConfig({ saveRecentSearchButtonTitle: '保存至搜索历史', removeRecentSearchButtonTitle: '从搜索历史中移除', favoriteSearchesTitle: '收藏', - removeFavoriteSearchButtonTitle: '从收藏中移除' + removeFavoriteSearchButtonTitle: '从收藏中移除', + recentConversationsTitle: '最近的对话', + removeRecentConversationButtonTitle: '从历史记录中删除对话' }, errorScreen: { titleText: '无法获取结果', helpText: '你可能需要检查你的网络连接' }, - footer: { - selectText: '选择', - navigateText: '切换', - closeText: '关闭', - searchByText: '搜索提供者' - }, noResultsScreen: { noResultsText: '无法找到相关结果', suggestedQueryText: '你可以尝试查询', reportMissingResultsText: '你认为该查询应该有结果?', reportMissingResultsLinkText: '点击反馈' + }, + resultsScreen: { + askAiPlaceholder: '向 AI 提问: ' + }, + askAiScreen: { + disclaimerText: '答案由 AI 生成,可能不准确,请自行验证。', + relatedSourcesText: '相关来源', + thinkingText: '思考中...', + copyButtonText: '复制', + copyButtonCopiedText: '已复制!', + copyButtonTitle: '复制', + likeButtonTitle: '赞', + dislikeButtonTitle: '踩', + thanksForFeedbackText: '感谢你的反馈!', + preToolCallText: '搜索中...', + duringToolCallText: '搜索 ', + afterToolCallText: '已搜索' + }, + footer: { + selectText: '选择', + submitQuestionText: '提交问题', + selectKeyAriaLabel: 'Enter 键', + navigateText: '切换', + navigateUpKeyAriaLabel: '向上箭头', + navigateDownKeyAriaLabel: '向下箭头', + closeText: '关闭', + backToSearchText: '返回搜索', + closeKeyAriaLabel: 'Esc 键', + poweredByText: '搜索提供者' } } } @@ -274,6 +305,43 @@ export default defineConfig({ [These options](https://github.com/vuejs/vitepress/blob/main/types/docsearch.d.ts) can be overridden. Refer official Algolia docs to learn more about them. +### Algolia Ask AI Support {#ask-ai} + +If you would like to include **Ask AI**, pass the `askAi` option (or any of the partial fields) inside `options`: + +```ts +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + search: { + provider: 'algolia', + options: { + appId: '...', + apiKey: '...', + indexName: '...', + // askAi: "YOUR-ASSISTANT-ID" + // OR + askAi: { + // at minimum you must provide the assistantId you received from Algolia + assistantId: 'XXXYYY', + // optional overrides – if omitted, the top-level appId/apiKey/indexName values are reused + // apiKey: '...', + // appId: '...', + // indexName: '...' + } + } + } + } +}) +``` + +::: warning Note +If want to default to keyword search and do not want to use Ask AI, just omit the `askAi` property +::: + +The translations for the Ask AI UI live under `options.translations.modal.askAiScreen` and `options.translations.resultsScreen` — see the [type definitions](https://github.com/vuejs/vitepress/blob/main/types/docsearch.d.ts) for all keys. + ### Crawler Config Here is an example config based on what this site uses: diff --git a/docs/en/reference/default-theme-sidebar.md b/docs/en/reference/default-theme-sidebar.md index 9a64a074..67893cf6 100644 --- a/docs/en/reference/default-theme-sidebar.md +++ b/docs/en/reference/default-theme-sidebar.md @@ -180,36 +180,3 @@ export default { } } ``` - -## `useSidebar` - -Returns sidebar-related data. The returned object has the following type: - -```ts -export interface DocSidebar { - isOpen: Ref - sidebar: ComputedRef - sidebarGroups: ComputedRef - hasSidebar: ComputedRef - hasAside: ComputedRef - leftAside: ComputedRef - isSidebarEnabled: ComputedRef - open: () => void - close: () => void - toggle: () => void -} -``` - -**Example:** - -```vue - - - -``` diff --git a/docs/en/reference/default-theme-team-page.md b/docs/en/reference/default-theme-team-page.md index 29b071ff..6c37c6a7 100644 --- a/docs/en/reference/default-theme-team-page.md +++ b/docs/en/reference/default-theme-team-page.md @@ -53,12 +53,12 @@ const members = [ Say hello to our awesome team. - + ``` The above will display a team member in card looking element. It should display something similar to below. - + `` component comes in 2 different sizes, `small` and `medium`. While it boils down to your preference, usually `small` size should fit better when used in doc page. Also, you may add more properties to each member such as adding "description" or "sponsor" button. Learn more about it in [``](#vpteammembers). @@ -107,9 +107,7 @@ const members = [ team, some of whom have chosen to be featured below. - + ``` diff --git a/docs/en/reference/frontmatter-config.md b/docs/en/reference/frontmatter-config.md index 955d4ad7..4d6f86c0 100644 --- a/docs/en/reference/frontmatter-config.md +++ b/docs/en/reference/frontmatter-config.md @@ -225,3 +225,16 @@ Then you can customize styles of this specific page in `.vitepress/theme/custom. /* page-specific styles */ } ``` + +### isHome + +- Type: `boolean` + +The default theme relies on checks like `frontmatter.layout === 'home'` to determine if the current page is the home page.\ +This is useful when you want to force show the home page elements in a custom layout. + +```yaml +--- +isHome: true +--- +``` diff --git a/docs/en/reference/site-config.md b/docs/en/reference/site-config.md index 3bc90316..a3ed65e3 100644 --- a/docs/en/reference/site-config.md +++ b/docs/en/reference/site-config.md @@ -24,7 +24,7 @@ export default { } ``` -:::details Dynamic (Async) Config +::: details Dynamic (Async) Config If you need to dynamically generate the config, you can also default export a function. For example: @@ -458,7 +458,7 @@ export default { ### ignoreDeadLinks -- Type: `boolean | 'localhostLinks' | (string | RegExp | ((link: string) => boolean))[]` +- Type: `boolean | 'localhostLinks' | (string | RegExp | ((link: string, source: string) => boolean))[]` - Default: `false` When set to `true`, VitePress will not fail builds due to dead links. diff --git a/docs/.vitepress/config/es.ts b/docs/es/config.ts similarity index 65% rename from docs/.vitepress/config/es.ts rename to docs/es/config.ts index d30fc89f..934c1dcf 100644 --- a/docs/.vitepress/config/es.ts +++ b/docs/es/config.ts @@ -1,16 +1,17 @@ import { createRequire } from 'module' -import { defineConfig, type DefaultTheme } from 'vitepress' +import { defineAdditionalConfig, type DefaultTheme } from 'vitepress' const require = createRequire(import.meta.url) const pkg = require('vitepress/package.json') -export const es = defineConfig({ - lang: 'es-CO', - description: 'Generador de Sitios Estaticos desarrollado con Vite y Vue.', +export default defineAdditionalConfig({ + description: 'Generador de Sitios Estáticos desarrollado con Vite y Vue.', themeConfig: { nav: nav(), + search: { options: searchOptions() }, + sidebar: { '/es/guide/': { base: '/es/guide/', items: sidebarGuide() }, '/es/reference/': { base: '/es/reference/', items: sidebarReference() } @@ -23,7 +24,7 @@ export const es = defineConfig({ footer: { message: 'Liberado bajo la licencia MIT', - copyright: `Derechos reservados © 2019-${new Date().getFullYear()} Evan You` + copyright: 'Todos los derechos reservados © 2019-PRESENTE Evan You' }, docFooter: { @@ -36,11 +37,15 @@ export const es = defineConfig({ }, lastUpdated: { - text: 'Actualizado en', - formatOptions: { - dateStyle: 'short', - timeStyle: 'medium' - } + text: 'Actualizado el' + }, + + notFound: { + title: 'PÁGINA NO ENCONTRADA', + quote: + 'Pero si no cambias de dirección y sigues buscando, podrías terminar donde te diriges.', + linkLabel: 'ir a inicio', + linkText: 'Llévame a inicio' }, langMenuLabel: 'Cambiar Idioma', @@ -56,7 +61,7 @@ export const es = defineConfig({ function nav(): DefaultTheme.NavItem[] { return [ { - text: 'Guia', + text: 'Guía', link: '/es/guide/what-is-vitepress', activeMatch: '/es/guide/' }, @@ -68,6 +73,10 @@ function nav(): DefaultTheme.NavItem[] { { text: pkg.version, items: [ + { + text: '1.6.4', + link: 'https://vuejs.github.io/vitepress/v1/es/' + }, { text: 'Registro de cambios', link: 'https://github.com/vuejs/vitepress/blob/main/CHANGELOG.md' @@ -87,7 +96,7 @@ function sidebarGuide(): DefaultTheme.SidebarItem[] { text: 'Introducción', collapsed: false, items: [ - { text: 'Qué es VitePress?', link: 'what-is-vitepress' }, + { text: '¿Qué es VitePress?', link: 'what-is-vitepress' }, { text: 'Iniciando', link: 'getting-started' }, { text: 'Enrutamiento', link: 'routing' }, { text: 'Despliegue', link: 'deploy' } @@ -130,7 +139,7 @@ function sidebarGuide(): DefaultTheme.SidebarItem[] { ] }, { - text: 'Configuración y Referencia del API', + text: 'Configuración y Referencia de la API', base: '/es/reference/', link: 'site-config' } @@ -161,7 +170,7 @@ function sidebarReference(): DefaultTheme.SidebarItem[] { { text: 'Links Anterior / Siguiente', link: 'prev-next-links' }, { text: 'Editar Link', link: 'edit-link' }, { text: 'Sello temporal de actualización', link: 'last-updated' }, - { text: 'Busqueda', link: 'search' }, + { text: 'Búsqueda', link: 'search' }, { text: 'Carbon Ads', link: 'carbon-ads' } ] } @@ -170,8 +179,8 @@ function sidebarReference(): DefaultTheme.SidebarItem[] { ] } -export const search: DefaultTheme.AlgoliaSearchOptions['locales'] = { - es: { +function searchOptions(): Partial { + return { placeholder: 'Buscar documentos', translations: { button: { @@ -180,10 +189,17 @@ export const search: DefaultTheme.AlgoliaSearchOptions['locales'] = { }, modal: { searchBox: { - resetButtonTitle: 'Limpiar búsqueda', - resetButtonAriaLabel: 'Limpiar búsqueda', - cancelButtonText: 'Cancelar', - cancelButtonAriaLabel: 'Cancelar' + clearButtonTitle: 'Limpiar búsqueda', + clearButtonAriaLabel: 'Limpiar búsqueda', + closeButtonText: 'Cerrar', + closeButtonAriaLabel: 'Cerrar', + placeholderText: undefined, + placeholderTextAskAi: undefined, + placeholderTextAskAiStreaming: 'Respondiendo...', + backToKeywordSearchButtonText: + 'Volver a la búsqueda por palabras clave', + backToKeywordSearchButtonAriaLabel: + 'Volver a la búsqueda por palabras clave' }, startScreen: { recentSearchesTitle: 'Historial de búsqueda', @@ -191,24 +207,52 @@ export const search: DefaultTheme.AlgoliaSearchOptions['locales'] = { saveRecentSearchButtonTitle: 'Guardar en el historial de búsqueda', removeRecentSearchButtonTitle: 'Borrar del historial de búsqueda', favoriteSearchesTitle: 'Favoritos', - removeFavoriteSearchButtonTitle: 'Borrar de favoritos' + removeFavoriteSearchButtonTitle: 'Borrar de favoritos', + recentConversationsTitle: 'Conversaciones recientes', + removeRecentConversationButtonTitle: + 'Eliminar esta conversación del historial' }, errorScreen: { titleText: 'No fue posible obtener resultados', helpText: 'Verifique su conexión de red' }, - footer: { - selectText: 'Seleccionar', - navigateText: 'Navegar', - closeText: 'Cerrar', - searchByText: 'Busqueda por' - }, noResultsScreen: { noResultsText: 'No fue posible encontrar resultados', suggestedQueryText: 'Puede intentar una nueva búsqueda', reportMissingResultsText: - 'Deberian haber resultados para esa consulta?', + '¿Deberían haber resultados para esta consulta?', reportMissingResultsLinkText: 'Click para enviar feedback' + }, + resultsScreen: { + askAiPlaceholder: 'Preguntar a la IA: ' + }, + askAiScreen: { + disclaimerText: + 'Las respuestas son generadas por IA y pueden contener errores. Verifica las respuestas.', + relatedSourcesText: 'Fuentes relacionadas', + thinkingText: 'Pensando...', + copyButtonText: 'Copiar', + copyButtonCopiedText: '¡Copiado!', + copyButtonTitle: 'Copiar', + likeButtonTitle: 'Me gusta', + dislikeButtonTitle: 'No me gusta', + thanksForFeedbackText: '¡Gracias por tu opinión!', + preToolCallText: 'Buscando...', + duringToolCallText: 'Buscando ', + afterToolCallText: 'Búsqueda de', + aggregatedToolCallText: 'Búsqueda de' + }, + footer: { + selectText: 'Seleccionar', + submitQuestionText: 'Enviar pregunta', + selectKeyAriaLabel: 'Tecla Enter', + navigateText: 'Navegar', + navigateUpKeyAriaLabel: 'Flecha arriba', + navigateDownKeyAriaLabel: 'Flecha abajo', + closeText: 'Cerrar', + backToSearchText: 'Volver a la búsqueda', + closeKeyAriaLabel: 'Tecla Escape', + poweredByText: 'Búsqueda por' } } } diff --git a/docs/es/guide/deploy.md b/docs/es/guide/deploy.md index 005f05c9..5d2c9c06 100644 --- a/docs/es/guide/deploy.md +++ b/docs/es/guide/deploy.md @@ -163,7 +163,7 @@ No active opciones como _Auto Minify_ para código HTML. Eso removera comentario - name: Setup Node uses: actions/setup-node@v4 with: - node-version: 20 + node-version: 22 cache: npm # o pnpm / yarn - name: Setup Pages uses: actions/configure-pages@v4 diff --git a/docs/es/guide/extending-default-theme.md b/docs/es/guide/extending-default-theme.md index 87452b63..b0705de3 100644 --- a/docs/es/guide/extending-default-theme.md +++ b/docs/es/guide/extending-default-theme.md @@ -70,7 +70,7 @@ Si su fuente es un archivo local referenciado via `@font-face`, ella será proce export default { transformHead({ assets }) { // ajuste el regex para corresponder a su fuente - const myFontFile = assets.find(file => /font-name\.\w+\.woff2/) + const myFontFile = assets.find(file => /font-name\.[\w-]+\.woff2/.test(file)) if (myFontFile) { return [ [ @@ -251,6 +251,7 @@ provide('toggle-appearance', async ({ clientX: x, clientY: y }: MouseEvent) => { { duration: 300, easing: 'ease-in', + fill: 'forwards', pseudoElement: `::view-transition-${isDark.value ? 'old' : 'new'}(root)` } ) diff --git a/docs/es/guide/getting-started.md b/docs/es/guide/getting-started.md index e9ed1526..056071d5 100644 --- a/docs/es/guide/getting-started.md +++ b/docs/es/guide/getting-started.md @@ -18,35 +18,19 @@ VitePress puede ser usado solo, o ser instalado en un proyecto ya existente. En ::: code-group ```sh [npm] -$ npm add -D vitepress +$ npm add -D vitepress@next ``` ```sh [pnpm] -$ pnpm add -D vitepress +$ pnpm add -D vitepress@next ``` ```sh [yarn] -$ yarn add -D vitepress +$ yarn add -D vitepress@next ``` ```sh [bun] -$ bun add -D vitepress -``` - -::: - -::: details Recibiendo avisos sobre dependencias ausentes? -Si usa PNPM, percibirá un aviso de ausencia de `@docsearch/js`. Esto no evita que VitePress funcione. Si desea eliminar este aviso, adicione lo siguiente en su `package.json`: - -```json -"pnpm": { - "peerDependencyRules": { - "ignoreMissing": [ - "@algolia/client-search", - "search-insights" - ] - } -} +$ bun add -D vitepress@next ``` ::: diff --git a/docs/es/guide/markdown.md b/docs/es/guide/markdown.md index 00f973ed..ebbd0d5e 100644 --- a/docs/es/guide/markdown.md +++ b/docs/es/guide/markdown.md @@ -256,11 +256,11 @@ La clase `vp-raw` también puede ser usada directamente en elementos. El aislami } ``` - El utiliza [`postcss-prefix-selector`](https://github.com/postcss/postcss-load-config) internamente. Puede pasar opciones así: + Puede pasar opciones así: ```js postcssIsolateStyles({ - includeFiles: [/vp-doc\.css/] // o padrão é /base\.css/ + includeFiles: [/custom\.css/] // o padrão é [/vp-doc\.css/, /base\.css/] }) ``` diff --git a/docs/es/guide/ssr-compat.md b/docs/es/guide/ssr-compat.md index 7f701eb8..81abdf77 100644 --- a/docs/es/guide/ssr-compat.md +++ b/docs/es/guide/ssr-compat.md @@ -4,13 +4,13 @@ outline: deep # Compatibilidad SSR {#ssr-compatibility} -VitePress pre-interpreta la aplicación en Node.js durante la compilación del producción, utilizando las capacidades de Interpretación del lado del servidor (SSR) de Vue. Esto significa que todo el código personalizado en los componentes del tema está sujeto a la compatibilidad SSR. +VitePress pre-renderiza la aplicación en Node.js durante la compilación de producción, utilizando las capacidades de Renderizado del Lado del Servidor (SSR) de Vue. Esto significa que todo el código personalizado en los componentes del tema está sujeto a la Compatibilidad con SSR. -La [sección SSR en la documentación Vue oficial](https://vuejs.org/guide/scaling-up/ssr.html) proporciona más contexto sobre lo que es SSR, la relación entre SSR / SSG y notas comunes sobre escribir código amigable con SSR. La regla general es acceder apenas APIs deln navegador / DOM en los hooks `beforeMount` o `mounted` de los componentes Vue. +La [sección SSR en la documentación Vue oficial](https://vuejs.org/guide/scaling-up/ssr.html) proporciona más contexto sobre lo que es SSR, la relación entre SSR / SSG y notas comunes sobre escribir código amigable para SSR. La regla general es acceder a las APIs del navegador / DOM solo en los hooks `beforeMount` o `mounted` de los componentes de Vue. ## `` -Se está usando o demostrando componentes que no son compatibles con SSR (por ejemplo, contienen directivas personalizadas), puede envolverlos en el componente embutido ``: +Si está usando o demostrando componentes que no son compatibles con SSR (por ejemplo, contienen directivas personalizadas), puede envolverlos en el componente incorporado ``: ```md @@ -20,7 +20,7 @@ Se está usando o demostrando componentes que no son compatibles con SSR (por ej ## Bibliotecas que Acceden el API del Navegador en la Importación {#libraries-that-access-browser-api-on-import} -Algunos componentes o bibliotecas acceden APIs del navegador **en la Importación**. Para usar código que asume un ambiente de navegador en la importación, necesita importarlo dinámicamente. +Algunos componentes o librerías acceden a las APIs del navegador **al momento de ser importados**. Para usar código que asume un entorno de navegador en la importación, necesita importarlos dinámicamente. ### Importando en el Hook `mounted` {#importing-in-mounted-hook} @@ -29,7 +29,7 @@ Algunos componentes o bibliotecas acceden APIs del navegador **en la Importació import { onMounted } from 'vue' onMounted(() => { - import('./lib-que-accede-window-en-la-importacion').then((module) => { + import('./lib-que-accede-a-window-en-la-importacion').then((module) => { // usar código }) }) @@ -38,17 +38,17 @@ onMounted(() => { ### Importación Condicional {#conditional-import} -Puede también importar condicionalmente usando el flag `import.meta.env.SSR` (parte de las [variables de entorno Vite](https://vitejs.dev/guide/env-and-mode.html#env-variables)): +También puede importar una dependencia condicionalmente utilizando la bandera `import.meta.env.SSR` (que forma parte de las [variables de entorno Vite](https://vitejs.dev/guide/env-and-mode.html#env-variables)): ```js if (!import.meta.env.SSR) { - import('./lib-que-accede-window-en-la-importacion').then((module) => { + import('./lib-que-accede-a-window-en-la-importacion').then((module) => { // usar código }) } ``` -Como [`Theme.enhanceApp`](./custom-theme#theme-interface) puede ser asíncrono, puede importar condicionalmente y registrar plugins Vue que acceden APIs del navegador en la importación: +Dado que [`Theme.enhanceApp`](./custom-theme#theme-interface) puede ser asíncrono, puede importar y registrar condicionalmente plugins de Vue que accedan a las APIs del navegador al ser importados: ```js [.vitepress/theme/index.js] /** @type {import('vitepress').Theme} */ @@ -56,7 +56,7 @@ export default { // ... async enhanceApp({ app }) { if (!import.meta.env.SSR) { - const plugin = await import('plugin-que-accede-window-en-la-importacion') + const plugin = await import('plugin-que-accede-a-window-en-la-importacion') app.use(plugin.default) } } @@ -71,7 +71,7 @@ export default { // ... async enhanceApp({ app }) { if (!import.meta.env.SSR) { - const plugin = await import('plugin-que-accede-window-en-la-importacion') + const plugin = await import('plugin-que-accede-a-window-en-la-importacion') app.use(plugin.default) } } @@ -80,14 +80,14 @@ export default { ### `defineClientComponent` -VitePress proporciona un auxiliar de conveniencia para importar componentes Vue que acceden APIs del navegador en la importación. +VitePress proporciona un auxiliar de conveniencia (helper) para importar componentes Vue que acceden a las APIs del navegador al ser importados. ```vue @@ -96,7 +96,7 @@ const ClientComp = defineClientComponent(() => { ``` -Puede también pasar propiedades/hijos/_slots_ para el componente objetivo: +Puede pasar propiedades/hijos/_slots_ al componente objetivo: ```vue - - -``` diff --git a/docs/es/reference/default-theme-team-page.md b/docs/es/reference/default-theme-team-page.md index 1f6492a8..996e8f18 100644 --- a/docs/es/reference/default-theme-team-page.md +++ b/docs/es/reference/default-theme-team-page.md @@ -53,12 +53,12 @@ const members = [ Saluda a nuestro increible equipo. - + ``` El código anterior mostrará a un miembro del equipo en un elemento similar a una tarjeta. Debería mostrar algo similar a lo siguiente. - + El componente `` viene en dos tamaños diferentes, pequeño `small` y médio `medium`. Si bien es una cuestión de preferencia, generalmente el tamaño `small` debería encajar mejor cuando se use en la página del documento. Además, puede agregar más propiedades a cada miembro, como agregar el botón "descripción" o "patrocinador". Obtenga más información sobre en [``](#vpteammembers). @@ -107,9 +107,7 @@ const members = [ Algunos de los miembros han elegido aparecer a continuación. - + ``` diff --git a/docs/es/reference/site-config.md b/docs/es/reference/site-config.md index 1a123ee2..c7223ad6 100644 --- a/docs/es/reference/site-config.md +++ b/docs/es/reference/site-config.md @@ -24,7 +24,7 @@ export default { } ``` -:::details Configuración dinámica (Assíncrona) +::: details Configuración dinámica (Assíncrona) Si necesitas generar dinamicamente la configuración, también puedes exportar por defecto una función. Por ejemplo: @@ -458,7 +458,7 @@ export default { ### ignoreDeadLinks -- Tipo: `boolean | 'localhostLinks' | (string | RegExp | ((link: string) => boolean))[]` +- Tipo: `boolean | 'localhostLinks' | (string | RegExp | ((link: string, source: string) => boolean))[]` - Predeterminado: `false` Cuando se establece en `true`, VitePress no dejará de compilarse debido a links rotos. @@ -613,7 +613,7 @@ export default { `transformHead` es un enlace de compilación para transformar el encabezado antes de generar cada página. Esto le permite agregar entradas de encabezado que no se pueden agregar estáticamente a la configuración de VitePress. Sólo necesita devolver entradas adicionales, que se fusionarán automáticamente con las existentes. -:::warning +::: warning No mutes ningún elemento dentro `context`. ::: @@ -681,7 +681,7 @@ export default { - Tipo: `(code: string, id: string, context: TransformContext) => Awaitable` `transformHtml` es un gancho de compilación para transformar el contenido de cada página antes de guardarla en el disco. -:::warning +::: warning No mute ningún elemento dentro del `context`. Además, modificar el contenido HTML puede provocar problemas de hidratación en tiempo de ejecución. ::: @@ -698,7 +698,7 @@ export default { `transformPageData` es un gancho para transformar los datos de cada página. Puedes hacer mutaciones directamente en `pageData` o devolver valores modificados que se fusionarán con los datos de la página. -:::warning +::: warning No mute ningún elemento dentro del `context` y tenga cuidado ya que esto puede afectar el rendimiento del servidor de desarrollo, especialmente si tiene algunas solicitudes de red o cálculos pesados (como generar imágenes) en el gancho. Puede consultar `process.env.NODE_ENV === 'production'` para ver la lógica condicional. ::: diff --git a/docs/.vitepress/config/fa.ts b/docs/fa/config.ts similarity index 56% rename from docs/.vitepress/config/fa.ts rename to docs/fa/config.ts index 5c91d0bc..97a005f0 100644 --- a/docs/.vitepress/config/fa.ts +++ b/docs/fa/config.ts @@ -1,25 +1,24 @@ import { createRequire } from 'module' -import { defineConfig, type DefaultTheme } from 'vitepress' +import { defineAdditionalConfig, type DefaultTheme } from 'vitepress' const require = createRequire(import.meta.url) const pkg = require('vitepress/package.json') -export const fa = defineConfig({ - title: 'ویت‌پرس', - lang: 'fa-IR', - description: 'Vite & Vue powered static site generator.', - dir: 'rtl', - markdown: { - container: { - tipLabel: 'نکته', - warningLabel: 'هشدار', - dangerLabel: 'خطر', - infoLabel: 'اطلاعات', - detailsLabel: 'جزئیات' - } - }, +export default defineAdditionalConfig({ + description: 'ژنراتور استاتیک وب‌سایت با Vite و Vue', + + // prettier-ignore + head: [ + ['link', { rel: 'preconnect', href: 'https://fonts.googleapis.com' }], + ['link', { rel: 'preconnect', href: 'https://fonts.gstatic.com', crossorigin: '' }], + ['link', { href: 'https://fonts.googleapis.com/css2?family=Vazirmatn:wght@100..900&display=swap', rel: 'stylesheet' }], + ], + themeConfig: { nav: nav(), + + search: { options: searchOptions() }, + sidebar: { '/fa/guide/': { base: '/fa/guide/', items: sidebarGuide() }, '/fa/reference/': { base: '/fa/reference/', items: sidebarReference() } @@ -45,11 +44,15 @@ export const fa = defineConfig({ }, lastUpdated: { - text: 'آخرین به‌روزرسانی‌', - formatOptions: { - dateStyle: 'short', - timeStyle: 'medium' - } + text: 'آخرین به‌روزرسانی‌' + }, + + notFound: { + title: 'صفحه پیدا نشد', + quote: + 'اما اگر جهت خود را تغییر ندهید و همچنان به جستجو ادامه دهید، ممکن است در نهایت به جایی برسید که در حال رفتن به آن هستید.', + linkLabel: 'برو به خانه', + linkText: 'من را به خانه ببر' }, langMenuLabel: 'تغییر زبان', @@ -58,14 +61,6 @@ export const fa = defineConfig({ darkModeSwitchLabel: 'تم تاریک', lightModeSwitchTitle: 'رفتن به حالت روشن', darkModeSwitchTitle: 'رفتن به حالت تاریک', - notFound: { - linkLabel: 'بازگشت به خانه', - linkText: 'بازگشت به خانه', - title: 'صفحه مورد نظر یافت نشد', - code: '۴۰۴', - quote: - 'اما اگر جهت خود را تغییر ندهید و اگر ادامه دهید به دنبال چیزی که دنبال می‌کنید، ممکن است در نهایت به جایی که در حال رفتن به سمتش هستید، برسید.' - }, siteTitle: 'ویت‌پرس' } }) @@ -85,6 +80,10 @@ function nav(): DefaultTheme.NavItem[] { { text: pkg.version, items: [ + { + text: '1.6.4', + link: 'https://vuejs.github.io/vitepress/v1/fa/' + }, { text: 'Changelog', link: 'https://github.com/vuejs/vitepress/blob/main/CHANGELOG.md' @@ -181,8 +180,8 @@ function sidebarReference(): DefaultTheme.SidebarItem[] { ] } -export const search: DefaultTheme.AlgoliaSearchOptions['locales'] = { - fa: { +function searchOptions(): Partial { + return { placeholder: 'جستجوی مستندات', translations: { button: { @@ -191,31 +190,67 @@ export const search: DefaultTheme.AlgoliaSearchOptions['locales'] = { }, modal: { searchBox: { - resetButtonTitle: 'آغاز مجدد جستجو', - resetButtonAriaLabel: 'آغاز مجدد جستجو', - cancelButtonText: 'لغو', - cancelButtonAriaLabel: 'لغو' + clearButtonTitle: 'پاک کردن جستجو', + clearButtonAriaLabel: 'پاک کردن جستجو', + closeButtonText: 'بستن', + closeButtonAriaLabel: 'بستن', + placeholderText: 'جستجوی مستندات', + placeholderTextAskAi: 'از هوش مصنوعی بپرسید: ', + placeholderTextAskAiStreaming: 'در حال پاسخ...', + searchInputLabel: 'جستجو', + backToKeywordSearchButtonText: 'بازگشت به جستجوی کلیدواژه', + backToKeywordSearchButtonAriaLabel: 'بازگشت به جستجوی کلیدواژه' }, startScreen: { - recentSearchesTitle: 'جستجو‌های اخیر', - noRecentSearchesText: 'تاریخچه جستجویی یافت نشد.', - saveRecentSearchButtonTitle: 'ذخیره تاریخچه جستجو', - removeRecentSearchButtonTitle: 'حذف تاریخچه جستجو', - favoriteSearchesTitle: 'موارد دلخواه', - removeFavoriteSearchButtonTitle: 'حذف مورد دلخواه' + recentSearchesTitle: 'جستجوهای اخیر', + noRecentSearchesText: 'هیچ جستجوی اخیر', + saveRecentSearchButtonTitle: 'ذخیره در تاریخچه جستجو', + removeRecentSearchButtonTitle: 'حذف از تاریخچه جستجو', + favoriteSearchesTitle: 'علاقه‌مندی‌ها', + removeFavoriteSearchButtonTitle: 'حذف از علاقه‌مندی‌ها', + recentConversationsTitle: 'گفتگوهای اخیر', + removeRecentConversationButtonTitle: 'حذف این گفتگو از تاریخچه' }, errorScreen: { - titleText: 'نتیجه‌ای یافت نشد برای', + titleText: 'عدم امکان دریافت نتایج', helpText: 'اتصال شبکه خود را بررسی کنید' }, + noResultsScreen: { + noResultsText: 'هیچ نتیجه‌ای یافت نشد', + suggestedQueryText: 'می‌توانید جستجوی دیگری امتحان کنید', + reportMissingResultsText: 'فکر می‌کنید باید نتیجه‌ای نمایش داده شود؟', + reportMissingResultsLinkText: 'برای ارسال بازخورد کلیک کنید' + }, + resultsScreen: { + askAiPlaceholder: 'از هوش مصنوعی بپرسید: ' + }, + askAiScreen: { + disclaimerText: + 'پاسخ‌ها توسط هوش مصنوعی تولید می‌شوند و ممکن است خطا داشته باشند. لطفاً بررسی کنید.', + relatedSourcesText: 'منابع مرتبط', + thinkingText: 'در حال پردازش...', + copyButtonText: 'کپی', + copyButtonCopiedText: 'کپی شد!', + copyButtonTitle: 'کپی', + likeButtonTitle: 'پسندیدم', + dislikeButtonTitle: 'نپسندیدم', + thanksForFeedbackText: 'از بازخورد شما سپاسگزاریم!', + preToolCallText: 'در حال جستجو...', + duringToolCallText: 'در حال جستجو برای ', + afterToolCallText: 'جستجو انجام شد', + aggregatedToolCallText: 'جستجو انجام شد' + }, footer: { selectText: 'انتخاب', - navigateText: 'رفتن', + submitQuestionText: 'ارسال پرسش', + selectKeyAriaLabel: 'کلید Enter', + navigateText: 'حرکت', + navigateUpKeyAriaLabel: 'کلید جهت بالا', + navigateDownKeyAriaLabel: 'کلید جهت پایین', closeText: 'بستن', - searchByText: ' جستجو با ' - }, - noResultsScreen: { - noResultsText: 'نتیجه‌ای یافت نشد برای' + backToSearchText: 'بازگشت به جستجو', + closeKeyAriaLabel: 'کلید Escape', + poweredByText: 'جستجو توسط' } } } diff --git a/docs/fa/guide/deploy.md b/docs/fa/guide/deploy.md index dcc74f69..1b89f334 100644 --- a/docs/fa/guide/deploy.md +++ b/docs/fa/guide/deploy.md @@ -161,7 +161,7 @@ Cache-Control: max-age=31536000,immutable - name: Setup Node uses: actions/setup-node@v4 with: - node-version: 20 + node-version: 22 cache: npm # or pnpm / yarn - name: Setup Pages uses: actions/configure-pages@v4 diff --git a/docs/fa/guide/extending-default-theme.md b/docs/fa/guide/extending-default-theme.md index e4d35270..a35193c8 100644 --- a/docs/fa/guide/extending-default-theme.md +++ b/docs/fa/guide/extending-default-theme.md @@ -70,7 +70,7 @@ export default DefaultTheme export default { transformHead({ assets }) { // منظور شده برای همسان سازی font خود، regex مورد نیاز را تنظیم کنید - const myFontFile = assets.find(file => /font-name\.\w+\.woff2/) + const myFontFile = assets.find(file => /font-name\.[\w-]+\.woff2/.test(file)) if (myFontFile) { return [ [ @@ -254,6 +254,7 @@ provide('toggle-appearance', async ({ clientX: x, clientY: y }: MouseEvent) => { { duration: 300, easing: 'ease-in', + fill: 'forwards', pseudoElement: `::view-transition-${isDark.value ? 'old' : 'new'}(root)` } ) diff --git a/docs/fa/guide/getting-started.md b/docs/fa/guide/getting-started.md index 66c949ae..394c5ecb 100644 --- a/docs/fa/guide/getting-started.md +++ b/docs/fa/guide/getting-started.md @@ -18,40 +18,19 @@ ::: code-group ```sh [npm] -$ npm add -D vitepress +$ npm add -D vitepress@next ``` ```sh [pnpm] -$ pnpm add -D vitepress +$ pnpm add -D vitepress@next ``` ```sh [yarn] -$ yarn add -D vitepress -``` - -```sh [yarn (pnp)] -$ yarn add -D vitepress vue +$ yarn add -D vitepress@next vue ``` ```sh [bun] -$ bun add -D vitepress -``` - -::: - -::: details درباره peer dependency های ناموجود هشدار دریافت می‌کنید؟ - -اگر از PNPM استفاده می‌کنید، متوجه هشدار peer dependency برای `@docsearch/js` خواهید شد. این مسئله جلوی عملکرد ویت‌پرس را نمی‌گیرد. اگر می‌خواهید این هشدار را نادیده بگیرید، موارد زیر را به `package.json` خود اضافه کنید: - -```json -"pnpm": { - "peerDependencyRules": { - "ignoreMissing": [ - "@algolia/client-search", - "search-insights" - ] - } -} +$ bun add -D vitepress@next ``` ::: diff --git a/docs/fa/guide/markdown.md b/docs/fa/guide/markdown.md index 1d2ca9f9..4e17bd31 100644 --- a/docs/fa/guide/markdown.md +++ b/docs/fa/guide/markdown.md @@ -255,11 +255,11 @@ export default defineConfig({ } ``` - این از [`postcss-prefix-selector`](https://github.com/postcss/postcss-load-config) استفاده می‌کند. می‌توانید گزینه‌های آن را به این صورت پاس بدهید: + می‌توانید گزینه‌های آن را به این صورت پاس بدهید: ```js postcssIsolateStyles({ - includeFiles: [/vp-doc\.css/] // به طور پیش‌فرض /base\.css/ + includeFiles: [/custom\.css/] // به طور پیش‌فرض [/vp-doc\.css/, /base\.css/] }) ``` diff --git a/docs/fa/guide/what-is-vitepress.md b/docs/fa/guide/what-is-vitepress.md index 1522f603..1d3d7f7f 100644 --- a/docs/fa/guide/what-is-vitepress.md +++ b/docs/fa/guide/what-is-vitepress.md @@ -12,7 +12,7 @@ - **مستندسازی** - ویت‌پرس با یک تم پیش‌فرض طراحی شده برای مستندات فنی ارائه می‌شود. این صفحه‌ای که اکنون در حال خواندن آن هستید و همچنین مستندات [Vite](https://vitejs.dev/)، [Rollup](https://rollupjs.org/)، [Pinia](https://pinia.vuejs.org/)، [VueUse](https://vueuse.org/)، [Vitest](https://vitest.dev/)، [D3](https://d3js.org/)، [UnoCSS](https://unocss.dev/)، [Iconify](https://iconify.design/) و [بسیاری دیگر](https://www.vuetelescope.com/explore?framework.slug=vitepress) با استفاده از ویت‌پرس ساخته شده‌اند. + ویت‌پرس با یک تم پیش‌فرض طراحی شده برای مستندات فنی ارائه می‌شود. این صفحه‌ای که اکنون در حال خواندن آن هستید و همچنین مستندات [Vite](https://vitejs.dev/)، [Rollup](https://rollupjs.org/)، [Pinia](https://pinia.vuejs.org/)، [VueUse](https://vueuse.org/)، [Vitest](https://vitest.dev/)، [D3](https://d3js.org/)، [UnoCSS](https://unocss.dev/)، [Iconify](https://iconify.design/) و [بسیاری دیگر](https://github.com/search?q=/"vitepress":+/+language:json&type=code) با استفاده از ویت‌پرس ساخته شده‌اند. [مستندات رسمی Vue.js](https://vuejs.org/) نیز بر پایه ویت‌پرس ساخته شده است، اما از یک تم سفارشی که بین چندین ترجمه مشترک است استفاده می‌کند. diff --git a/docs/fa/index.md b/docs/fa/index.md index cd6552ba..8fa79bd3 100644 --- a/docs/fa/index.md +++ b/docs/fa/index.md @@ -1,9 +1,6 @@ --- layout: home -title: ویت‌پرس -titleTemplate: Vite & Vue Powered Static Site Generator - hero: name: ویت‌پرس text: سازنده سایت‌های ایستا به کمک Vite و Vue diff --git a/docs/fa/reference/cli.md b/docs/fa/reference/cli.md index c8ad10ff..506190b0 100644 --- a/docs/fa/reference/cli.md +++ b/docs/fa/reference/cli.md @@ -43,7 +43,6 @@ vitepress build [root] | `--base ` | مسیر پایه عمومی (پیش‌فرض: `/`) (`string`) | | `--target ` | هدف ترنسپایل (پیش‌فرض: `"modules"`) (`string`) | | `--outDir ` | دایرکتوری خروجی نسبت به **cwd** (پیش‌فرض: `/.vitepress/dist`) (`string`) | -| `--minify [minifier]` | فعال یا غیرفعال کردن فشرده‌سازی، یا تعیین فشرده‌سازی برای استفاده (پیش‌فرض: `"esbuild"`) (`boolean \| "terser" \| "esbuild"`) | | `--assetsInlineLimit ` | آستانه تبدیل پایه ۶۴ استاتیک به بایت (پیش‌فرض: `4096`) (`number`) | ## `vitepress preview` {#vitepress-preview} diff --git a/docs/fa/reference/default-theme-config.md b/docs/fa/reference/default-theme-config.md index 1040f79b..9208db8d 100644 --- a/docs/fa/reference/default-theme-config.md +++ b/docs/fa/reference/default-theme-config.md @@ -89,7 +89,7 @@ type NavItem = NavItemWithLink | NavItemWithChildren interface NavItemWithLink { text: string - link: string + link: string | ((payload: PageData) => string) activeMatch?: string target?: string rel?: string diff --git a/docs/fa/reference/default-theme-nav.md b/docs/fa/reference/default-theme-nav.md index eafc5b53..c847a231 100644 --- a/docs/fa/reference/default-theme-nav.md +++ b/docs/fa/reference/default-theme-nav.md @@ -55,6 +55,8 @@ export default { `text` متن واقعی است که در ناوبری نمایش داده می‌شود و `link` لینکی است که هنگام کلیک بر روی متن به آن ناوبری می‌شود. برای لینک، مسیر را به صورت واقعی بدون پیشوند `.md` تنظیم کنید و همیشه با `/` شروع کنید. +`link` همچنین می‌تواند تابعی باشد که [`PageData`](./runtime-api#usedata) را به عنوان آرگومان بپذیرد و مسیر را برگرداند. + لینک‌های ناوبری همچنین می‌توانند منوهای کشویی باشند. برای این کار، کلید `items` را در گزینه لینک تنظیم کنید. ```js diff --git a/docs/fa/reference/default-theme-search.md b/docs/fa/reference/default-theme-search.md index 2694a291..033e145e 100644 --- a/docs/fa/reference/default-theme-search.md +++ b/docs/fa/reference/default-theme-search.md @@ -212,9 +212,7 @@ export default defineConfig({ import { defineConfig } from 'vitepress' export default defineConfig({ - themeConfig: - - { + themeConfig: { search: { provider: 'algolia', options: { @@ -223,40 +221,40 @@ export default defineConfig({ indexName: '...', locales: { zh: { - placeholder: 'جستجو در مستندات', + placeholder: '搜索文档', translations: { button: { - buttonText: 'جستجو در مستندات', - buttonAriaLabel: 'جستجو در مستندات' + buttonText: '搜索文档', + buttonAriaLabel: '搜索文档' }, modal: { searchBox: { - resetButtonTitle: 'پاک کردن شرایط جستجو', - resetButtonAriaLabel: 'پاک کردن شرایط جستجو', - cancelButtonText: 'لغو', - cancelButtonAriaLabel: 'لغو' + resetButtonTitle: '清除搜索条件', + resetButtonAriaLabel: '清除搜索条件', + cancelButtonText: '取消', + cancelButtonAriaLabel: '取消' }, startScreen: { - recentSearchesTitle: 'تاریخچه جستجو', - noRecentSearchesText: 'هیچ تاریخچه جستجویی وجود ندارد', - saveRecentSearchButtonTitle: 'ذخیره در تاریخچه جستجو', - removeRecentSearchButtonTitle: 'حذف از تاریخچه جستجو' + recentSearchesTitle: '最近搜索', + noRecentSearchesText: '没有最近搜索', + saveRecentSearchButtonTitle: '保存到最近搜索', + removeRecentSearchButtonTitle: '从最近搜索中删除' }, errorScreen: { - titleText: 'نمایش نتایج امکان‌پذیر نیست', - helpText: 'شما ممکن است نیاز به بررسی اتصال اینترنت خود داشته باشید' + titleText: '无法显示结果', + helpText: '您可能需要检查您的互联网连接' }, footer: { - selectText: 'انتخاب', - navigateText: 'جابجایی', - closeText: 'بستن', - searchByText: 'جستجو توسط' + selectText: '选择', + navigateText: '导航', + closeText: '关闭', + searchByText: '搜索由' }, noResultsScreen: { - noResultsText: 'نتیجه‌ای پیدا نشد', - suggestedQueryText: 'می‌توانید امتحان کنید', - reportMissingResultsText: 'فکر می‌کنید باید نتایجی وجود داشته باشد؟', - reportMissingResultsLinkText: 'برای بازخورد کلیک کنید' + noResultsText: '没有找到结果', + suggestedQueryText: '您可以尝试', + reportMissingResultsText: '您认为应该有结果吗?', + reportMissingResultsLinkText: '点击这里报告' } } } @@ -377,3 +375,22 @@ new Crawler({ } }) ``` + +### پشتیبانی Algolia Ask AI {#ask-ai} + +برای فعال‌سازی **Ask AI** کافی است گزینه `askAi` را اضافه کنید: + +```ts +options: { + appId: '...', + apiKey: '...', + indexName: '...', + askAi: { + assistantId: 'XXXYYY' + } +} +``` + +::: warning نکته +اگر فقط به جستجوی کلمات کلیدی نیاز دارید، `askAi` را اضافه نکنید. +::: diff --git a/docs/fa/reference/default-theme-sidebar.md b/docs/fa/reference/default-theme-sidebar.md index cba65dff..96433c2d 100644 --- a/docs/fa/reference/default-theme-sidebar.md +++ b/docs/fa/reference/default-theme-sidebar.md @@ -178,38 +178,3 @@ export default { } } ``` - -## `useSidebar` {#usesidebar} - -داده‌های مربوط به نوار کناری را برمی‌گرداند. شیء برگردانده شده دارای نوع‌های زیر است: - -```ts -export interface DocSidebar { - isOpen: Ref - sidebar: ComputedRef - sidebarGroups: ComputedRef - hasSidebar: ComputedRef - hasAside: ComputedRef - leftAside: ComputedRef - isSidebarEnabled: ComputedRef - open: () => void - close: () => void - toggle: () => void -} -``` - -**مثال:** - -```vue - - - -``` diff --git a/docs/fa/reference/default-theme-team-page.md b/docs/fa/reference/default-theme-team-page.md index ccd9738d..57fc2814 100644 --- a/docs/fa/reference/default-theme-team-page.md +++ b/docs/fa/reference/default-theme-team-page.md @@ -53,12 +53,12 @@ const members = [ با سلام به تیم فوق‌العاده‌ی ما خوش آمدید. - + ``` بالا به صورت عنصری با شکل کارتی اعضای تیم را نمایش می‌دهد. باید به شکل زیر نمایش داده شود. - + کامپوننت `` دارای دو اندازه مختلف، `small` و `medium` است. معمولاً اندازه `small` برای استفاده در صفحات مستندات مناسب‌تر است. همچنین می‌توانید ویژگی‌های بیشتری برای هر عضو اضافه کنید مانند "توضیحات" یا "دکمه حامی". جهت کسب اطلاعات بیشتر به [``](#vpteammembers) مراجعه کنید. @@ -106,9 +106,7 @@ const members = [ توسعه ویت‌پرس توسط تیمی بین‌المللی راهنمایی می‌شود، برخی از اعضا که انتخاب کرده‌اند تا در زیر نمایش داده شوند. - + ``` diff --git a/docs/fa/reference/site-config.md b/docs/fa/reference/site-config.md index 72343ffa..d3e0ebac 100644 --- a/docs/fa/reference/site-config.md +++ b/docs/fa/reference/site-config.md @@ -24,7 +24,7 @@ export default { } ``` -:::details تنظیمات پویا (غیرهمزمان) +::: details تنظیمات پویا (غیرهمزمان) اگر نیاز دارید به طور پویا تنظیمات را تولید کنید، می‌توانید یک تابع صادر کنید. به عنوان مثال: @@ -354,7 +354,7 @@ export default { وقتی تنظیم شود به `true`، ویت‌پرس `.html` انتهایی را از URL ها حذف می‌کند. همچنین ببینید [تولید URL تمیز](../guide/routing#generating-clean-url). -::: هشدار نیاز به پشتیبانی سرور +::: warning هشدار نیاز به پشتیبانی سرور فعال کردن این ممکن است نیاز به پیکربندی اضافی در پلتفرم میزبان شما داشته باشد. برای اینکه کار کند، سرور شما باید بتواند `/foo.html` را زمانی که `/foo` بازدید می‌شود **بدون ریدایرکت** سرو کند. ::: @@ -441,7 +441,7 @@ export default { ### ignoreDeadLinks -- نوع: `boolean | 'localhostLinks' | (string | RegExp | ((link: string) => boolean))[]` +- نوع: `boolean | 'localhostLinks' | (string | RegExp | ((link: string, source: string) => boolean))[]` - پیش‌فرض: `false` زمانی که به `true` تنظیم شود، ویت‌پرس به دلیل لینک‌های مرده ساخت‌ها را شکست نخواهد داد. diff --git a/docs/ja/config.ts b/docs/ja/config.ts new file mode 100644 index 00000000..4f6ef26d --- /dev/null +++ b/docs/ja/config.ts @@ -0,0 +1,225 @@ +import { createRequire } from 'module' +import { defineAdditionalConfig, type DefaultTheme } from 'vitepress' + +const require = createRequire(import.meta.url) +const pkg = require('vitepress/package.json') + +export default defineAdditionalConfig({ + description: 'Vite と Vue による静的サイトジェネレーター', + + themeConfig: { + nav: nav(), + + search: { options: searchOptions() }, + + sidebar: { + '/ja/guide/': { base: '/ja/guide/', items: sidebarGuide() }, + '/ja/reference/': { base: '/ja/reference/', items: sidebarReference() } + }, + + editLink: { + pattern: 'https://github.com/vuejs/vitepress/edit/main/docs/:path', + text: 'GitHub でこのページを編集' + }, + + footer: { + message: 'MIT ライセンスの下で公開されています。', + copyright: 'Copyright © 2019-present Evan You' + } + } +}) + +function nav(): DefaultTheme.NavItem[] { + return [ + { + text: 'ガイド', + link: '/ja/guide/what-is-vitepress', + activeMatch: '/guide/' + }, + { + text: 'リファレンス', + link: '/ja/reference/site-config', + activeMatch: '/reference/' + }, + { + text: pkg.version, + items: [ + { + text: '1.6.4', + link: 'https://vuejs.github.io/vitepress/v1/' + }, + { + text: '更新履歴', + link: 'https://github.com/vuejs/vitepress/blob/main/CHANGELOG.md' + }, + { + text: 'コントリビュート方法', + link: 'https://github.com/vuejs/vitepress/blob/main/.github/contributing.md' + } + ] + } + ] +} + +function sidebarGuide(): DefaultTheme.SidebarItem[] { + return [ + { + text: '導入', + collapsed: false, + items: [ + { text: 'VitePress とは?', link: 'what-is-vitepress' }, + { text: 'はじめに', link: 'getting-started' }, + { text: 'ルーティング', link: 'routing' }, + { text: 'デプロイ', link: 'deploy' } + ] + }, + { + text: '執筆', + collapsed: false, + items: [ + { text: 'Markdown 拡張', link: 'markdown' }, + { text: 'アセットの取り扱い', link: 'asset-handling' }, + { text: 'フロントマター', link: 'frontmatter' }, + { text: 'Markdown で Vue を使う', link: 'using-vue' }, + { text: '多言語対応', link: 'i18n' } + ] + }, + { + text: 'カスタマイズ', + collapsed: false, + items: [ + { text: 'カスタムテーマを使う', link: 'custom-theme' }, + { + text: 'デフォルトテーマの拡張', + link: 'extending-default-theme' + }, + { text: 'ビルド時のデータ読み込み', link: 'data-loading' }, + { text: 'SSR 互換性', link: 'ssr-compat' }, + { text: 'CMS との接続', link: 'cms' } + ] + }, + { + text: '実験的機能', + collapsed: false, + items: [ + { text: 'MPA モード', link: 'mpa-mode' }, + { text: 'サイトマップ生成', link: 'sitemap-generation' } + ] + }, + { + text: '設定 & API リファレンス', + base: '/ja/reference/', + link: 'site-config' + } + ] +} + +function sidebarReference(): DefaultTheme.SidebarItem[] { + return [ + { + text: 'リファレンス', + items: [ + { text: 'サイト設定', link: 'site-config' }, + { text: 'Frontmatter 設定', link: 'frontmatter-config' }, + { text: 'ランタイム API', link: 'runtime-api' }, + { text: 'CLI', link: 'cli' }, + { + text: 'デフォルトテーマ', + base: '/ja/reference/default-theme-', + items: [ + { text: '概要', link: 'config' }, + { text: 'ナビゲーション', link: 'nav' }, + { text: 'サイドバー', link: 'sidebar' }, + { text: 'ホームページ', link: 'home-page' }, + { text: 'フッター', link: 'footer' }, + { text: 'レイアウト', link: 'layout' }, + { text: 'バッジ', link: 'badge' }, + { text: 'チームページ', link: 'team-page' }, + { text: '前 / 次 リンク', link: 'prev-next-links' }, + { text: '編集リンク', link: 'edit-link' }, + { text: '最終更新日時', link: 'last-updated' }, + { text: '検索', link: 'search' }, + { text: 'Carbon 広告', link: 'carbon-ads' } + ] + } + ] + } + ] +} + +function searchOptions(): Partial { + return { + placeholder: 'ドキュメントを検索', + translations: { + button: { + buttonText: '検索', + buttonAriaLabel: '検索' + }, + modal: { + searchBox: { + clearButtonTitle: '検索をクリア', + clearButtonAriaLabel: '検索をクリア', + closeButtonText: '閉じる', + closeButtonAriaLabel: '閉じる', + placeholderText: 'ドキュメントを検索', + placeholderTextAskAi: 'AI に質問: ', + placeholderTextAskAiStreaming: '回答を作成中...', + searchInputLabel: '検索', + backToKeywordSearchButtonText: 'キーワード検索に戻る', + backToKeywordSearchButtonAriaLabel: 'キーワード検索に戻る' + }, + startScreen: { + recentSearchesTitle: '検索履歴', + noRecentSearchesText: '最近の検索はありません', + saveRecentSearchButtonTitle: '検索履歴に保存', + removeRecentSearchButtonTitle: '検索履歴から削除', + favoriteSearchesTitle: 'お気に入り', + removeFavoriteSearchButtonTitle: 'お気に入りから削除', + recentConversationsTitle: '最近の会話', + removeRecentConversationButtonTitle: '会話履歴から削除' + }, + errorScreen: { + titleText: '結果を取得できません', + helpText: 'ネットワーク接続を確認してください' + }, + noResultsScreen: { + noResultsText: '結果が見つかりません', + suggestedQueryText: '別の検索語を試してください', + reportMissingResultsText: '結果があるはずだと思いますか?', + reportMissingResultsLinkText: 'フィードバックを送る' + }, + resultsScreen: { + askAiPlaceholder: 'AI に質問: ' + }, + askAiScreen: { + disclaimerText: + 'AI が生成した回答には誤りが含まれる可能性があります。必ずご確認ください。', + relatedSourcesText: '関連ソース', + thinkingText: '考え中...', + copyButtonText: 'コピー', + copyButtonCopiedText: 'コピーしました!', + copyButtonTitle: 'コピー', + likeButtonTitle: 'いいね', + dislikeButtonTitle: 'よくない', + thanksForFeedbackText: 'フィードバックありがとうございます!', + preToolCallText: '検索中...', + duringToolCallText: '検索中 ', + afterToolCallText: '検索完了', + aggregatedToolCallText: '検索完了' + }, + footer: { + selectText: '選択', + submitQuestionText: '質問を送信', + selectKeyAriaLabel: 'Enter キー', + navigateText: '移動', + navigateUpKeyAriaLabel: '上矢印キー', + navigateDownKeyAriaLabel: '下矢印キー', + closeText: '閉じる', + backToSearchText: '検索に戻る', + closeKeyAriaLabel: 'Esc キー', + poweredByText: '提供: ' + } + } + } + } +} diff --git a/docs/ja/guide/asset-handling.md b/docs/ja/guide/asset-handling.md new file mode 100644 index 00000000..694318c4 --- /dev/null +++ b/docs/ja/guide/asset-handling.md @@ -0,0 +1,66 @@ +# アセットの取り扱い {#asset-handling} + +## 静的アセットの参照 {#referencing-static-assets} + +すべての Markdown ファイルは Vue コンポーネントにコンパイルされ、[Vite](https://vitejs.dev/guide/assets.html) によって処理されます。Markdown 内では、相対 URL を使ってアセットを参照することが **推奨されます**。 + +```md +![画像](./image.png) +``` + +Markdown ファイル内、テーマの `*.vue` コンポーネント内、スタイルや通常の `.css` ファイル内でも、アセットはプロジェクトルートを基準とした絶対パス、またはファイルシステムを基準とした相対パスで参照できます。後者は Vite、Vue CLI、あるいは webpack の `file-loader` を使ったことがある場合に慣れ親しんだ挙動です。 + +一般的な画像、メディア、フォントファイルタイプは自動的にアセットとして検出され、含まれます。 + +::: tip リンクされたファイルはアセットとして扱われません +Markdown ファイル内のリンクで参照された PDF やその他のドキュメントは、自動的にアセットとして扱われません。これらのリンクファイルにアクセスできるようにするには、手動でプロジェクトの [`public`](#the-public-directory) ディレクトリに配置する必要があります。 +::: + +絶対パスを含むすべての参照されたアセットは、プロダクションビルド時にハッシュ化されたファイル名で出力ディレクトリにコピーされます。参照されないアセットはコピーされません。4kb 未満の画像アセットは base64 としてインライン化されます(これは [`vite`](../reference/site-config#vite) 設定オプションで変更可能です)。 + +すべての **静的な** パス参照(絶対パスを含む)は、作業ディレクトリの構造を基準にする必要があります。 + +## Public ディレクトリ {#the-public-directory} + +Markdown やテーマコンポーネントで直接参照されない静的アセットを提供する必要がある場合や、特定のファイルをオリジナルのファイル名のまま提供したい場合があります。 +例えば `robots.txt`、favicon、PWA 用アイコンなどです。 + +これらのファイルは [ソースディレクトリ](./routing#source-directory) 配下の `public` ディレクトリに配置できます。たとえばプロジェクトルートが `./docs` で、デフォルトのソースディレクトリを使用している場合、`public` ディレクトリは `./docs/public` になります。 + +`public` に配置されたアセットは、出力ディレクトリのルートにそのままコピーされます。 + +なお、`public` 内のファイルはルート絶対パスで参照する必要があります。例えば `public/icon.png` は常に `/icon.png` として参照しなければなりません。 + +## ベース URL {#base-url} + +サイトをルート以外の URL にデプロイする場合、`.vitepress/config.js` で `base` オプションを設定する必要があります。 +例えば `https://foo.github.io/bar/` にデプロイする場合、`base` は `'/bar/'` と設定します(必ずスラッシュで開始・終了する必要があります)。 + +すべての静的アセットパスは `base` 設定値に応じて自動的に調整されます。 +例えば Markdown 内で `public` 配下のアセットを絶対参照した場合: + +```md +![画像](/image-inside-public.png) +``` + +この場合は `base` の設定値を変更しても、参照を修正する必要はありません。 + +ただし、テーマコンポーネントで動的にアセットをリンクする場合(例:テーマ設定値に基づいた画像の `src`)は注意が必要です。 + +```vue + +``` + +この場合は、VitePress が提供する [`withBase` ヘルパー](../reference/runtime-api#withbase) でパスをラップすることを推奨します。 + +```vue + + + +``` diff --git a/docs/ja/guide/cms.md b/docs/ja/guide/cms.md new file mode 100644 index 00000000..191312df --- /dev/null +++ b/docs/ja/guide/cms.md @@ -0,0 +1,56 @@ +--- +outline: deep +--- + +# CMS との接続 {#connecting-to-a-cms} + +## 全体のワークフロー {#general-workflow} + +VitePress を CMS と接続する際は、主に [動的ルーティング](./routing#dynamic-routes) を中心に考えることになります。先にその仕組みを理解しておいてください。 + +CMS ごとに動作が異なるため、ここでは各自の環境に合わせて調整できる汎用的なワークフローのみを示します。 + +1. CMS が認証を必要とする場合は、API トークンを格納するための `.env` を作成し、次のように読み込みます。 + + ```js + // posts/[id].paths.js + import { loadEnv } from 'vitepress' + + const env = loadEnv('', process.cwd()) + ``` + +2. CMS から必要なデータを取得し、適切なパスデータの形式に整形します。 + + ```js + export default { + async paths() { + // 必要に応じて各 CMS のクライアントライブラリを使用 + const data = await (await fetch('https://my-cms-api', { + headers: { + // 必要ならトークン + } + })).json() + + return data.map(entry => { + return { + params: { id: entry.id, /* title, authors, date など */ }, + content: entry.content + } + }) + } + } + ``` + +3. ページ内でコンテンツをレンダリングします。 + + ```md + # {{ $params.title }} + + - {{ $params.date }} に {{ $params.author }} が作成 + + + ``` + +## 連携ガイドの募集 {#integration-guides} + +特定の CMS と VitePress の連携ガイドを書かれた方は、下部の「Edit this page」リンクからぜひ投稿してください! diff --git a/docs/ja/guide/custom-theme.md b/docs/ja/guide/custom-theme.md new file mode 100644 index 00000000..0095ca8a --- /dev/null +++ b/docs/ja/guide/custom-theme.md @@ -0,0 +1,213 @@ +# カスタムテーマを使う {#using-a-custom-theme} + +## テーマの解決 {#theme-resolving} + +カスタムテーマを有効にするには、`.vitepress/theme/index.js` または `.vitepress/theme/index.ts` ファイル(「テーマエントリファイル」)を作成します。 + +``` +. +├─ docs # プロジェクトルート +│ ├─ .vitepress +│ │ ├─ theme +│ │ │ └─ index.js # テーマエントリ +│ │ └─ config.js # 設定ファイル +│ └─ index.md +└─ package.json +``` + +VitePress はテーマエントリファイルを検出すると、常にデフォルトテーマではなくカスタムテーマを使用します。ただし、[デフォルトテーマを拡張](./extending-default-theme) してその上で高度なカスタマイズを行うことも可能です。 + +## テーマインターフェース {#theme-interface} + +VitePress のカスタムテーマは次のインターフェースを持つオブジェクトとして定義されます。 + +```ts +interface Theme { +/** + * すべてのページに適用されるルートレイアウトコンポーネント + * @required + */ +Layout: Component +/** + * Vue アプリインスタンスを拡張 + * @optional + */ +enhanceApp?: (ctx: EnhanceAppContext) => Awaitable +/** + * 別のテーマを拡張し、そのテーマの `enhanceApp` を先に実行 + * @optional + */ +extends?: Theme +} + +interface EnhanceAppContext { +app: App // Vue アプリインスタンス +router: Router // VitePress のルーターインスタンス +siteData: Ref // サイト全体のメタデータ +} +``` + +テーマエントリファイルでは、このテーマをデフォルトエクスポートとして公開します。 + +```js [.vitepress/theme/index.js] + +// テーマエントリでは Vue ファイルを直接インポートできます +// VitePress は @vitejs/plugin-vue をあらかじめ設定済みです +import Layout from './Layout.vue' + +export default { +Layout, +enhanceApp({ app, router, siteData }) { + // ... +} +} +``` + +デフォルトエクスポートはカスタムテーマにおける唯一の契約であり、必須なのは `Layout` プロパティだけです。つまり、VitePress のテーマは単一の Vue コンポーネントでも成り立ちます。 + +レイアウトコンポーネントの内部は通常の Vite + Vue 3 アプリケーションと同じように動作します。なお、テーマは [SSR 対応](./ssr-compat) である必要があります。 + +## レイアウトの構築 {#building-a-layout} + +最も基本的なレイアウトコンポーネントには [``](../reference/runtime-api#content) コンポーネントを含める必要があります。 + +```vue [.vitepress/theme/Layout.vue] + +``` + +上記のレイアウトは、すべてのページの Markdown を単純に HTML として描画します。最初の改善点として 404 エラー処理を追加できます。 + +```vue{1-4,9-12} + + + +``` + +[`useData()`](../reference/runtime-api#usedata) ヘルパーを使うと、条件によってレイアウトを切り替えるために必要なすべてのランタイムデータを取得できます。アクセスできるデータのひとつにフロントマターがあります。これを利用すると、ページごとにレイアウトを制御できます。例えば、ユーザーが特別なホームページレイアウトを使いたい場合は以下のように記述します。 + + ```md +--- +layout: home +--- + ``` + +テーマ側を次のように調整します。 + +```vue{3,12-14} + + + +``` + +もちろんレイアウトをさらにコンポーネントに分割することもできます。 + +```vue{3-5,12-15} + + + +``` + +利用可能なすべての機能は [Runtime API リファレンス](../reference/runtime-api) を参照してください。さらに [ビルド時データ読み込み](./data-loading) を活用すれば、ブログ記事一覧ページのようなデータ駆動型のレイアウトも実現できます。 + +## カスタムテーマの配布 {#distributing-a-custom-theme} + +最も簡単な配布方法は [GitHub のテンプレートリポジトリ](https://docs.github.com/en/repositories/creating-and-managing-repositories/creating-a-template-repository) として提供することです。 + +npm パッケージとして配布する場合は、次の手順を踏みます。 + +1. パッケージエントリでテーマオブジェクトをデフォルトエクスポートとして公開する。 +2. 必要であればテーマ設定の型定義を `ThemeConfig` として公開する。 +3. テーマが VitePress 設定の調整を必要とする場合は、パッケージのサブパス(例:`my-theme/config`)としてその設定を公開し、ユーザーが拡張できるようにする。 +4. 設定ファイルやフロントマターを通じて、テーマ設定オプションを文書化する。 +5. テーマの利用方法を明確に説明する(以下を参照)。 + +## カスタムテーマの利用 {#consuming-a-custom-theme} + + +外部テーマを利用するには、カスタムテーマエントリからインポートして再エクスポートします。 + +```js [.vitepress/theme/index.js] +import Theme from 'awesome-vitepress-theme' + +export default Theme +``` + +テーマを拡張する必要がある場合: + +```js [.vitepress/theme/index.js] +import Theme from 'awesome-vitepress-theme' + +export default { +extends: Theme, +enhanceApp(ctx) { + // ... +} +} +``` + +テーマが特別な VitePress 設定を必要とする場合は、設定ファイルも拡張する必要があります。 + +```ts [.vitepress/config.ts] +import baseConfig from 'awesome-vitepress-theme/config' + +export default { +// 必要に応じてテーマの基本設定を拡張 +extends: baseConfig +} +``` + +テーマがテーマ設定用の型を提供している場合: + +```ts [.vitepress/config.ts] +import baseConfig from 'awesome-vitepress-theme/config' +import { defineConfigWithTheme } from 'vitepress' +import type { ThemeConfig } from 'awesome-vitepress-theme' + +export default defineConfigWithTheme({ +extends: baseConfig, +themeConfig: { + // 型は `ThemeConfig` +} +}) +``` diff --git a/docs/ja/guide/data-loading.md b/docs/ja/guide/data-loading.md new file mode 100644 index 00000000..469999d7 --- /dev/null +++ b/docs/ja/guide/data-loading.md @@ -0,0 +1,212 @@ +# ビルド時のデータの読み込み {#build-time-data-loading} + +VitePress には **データローダー (data loaders)** という機能があり、任意のデータを読み込み、ページやコンポーネントからインポートすることができます。データの読み込みは **ビルド時のみ** 実行され、最終的な JavaScript バンドルには JSON としてシリアライズされたデータが含まれます。 + +データローダーはリモートデータの取得や、ローカルファイルに基づいたメタデータの生成に利用できます。たとえば、ローカルの API ページをすべて解析して API エントリのインデックスを自動生成するといったことが可能です。 + +## 基本的な使い方 {#basic-usage} + +データローダーファイルは `.data.js` または `.data.ts` で終わる必要があります。ファイルは `load()` メソッドを持つオブジェクトをデフォルトエクスポートします。 + +```js [example.data.js] +export default { +load() { + return { + hello: 'world' + } +} +} +``` + +ローダーモジュールは Node.js 上でのみ評価されるため、Node API や npm 依存関係を自由に利用できます。 + +その後、このファイルから `.md` ページや `.vue` コンポーネントで `data` という名前のエクスポートを使ってデータをインポートできます。 + +```vue + + +
{{ data }}
+``` + +出力: + +```json +{ + "hello": "world" +} +``` + +データローダー自体は `data` を直接エクスポートしていないことに気づくでしょう。これは VitePress が裏側で `load()` を呼び出し、その結果を暗黙的に `data` として公開しているためです。 + +ローダーが非同期でも動作します。 + +```js +export default { + async load() { + // リモートデータを取得 + return (await fetch('...')).json() + } +} +``` + +## ローカルファイルからのデータ {#data-from-local-files} + +ローカルファイルに基づいたデータを生成する必要がある場合は、データローダー内で `watch` オプションを使用し、ファイルの変更をホットリロードに反映させることが推奨されます。 + +`watch` では [glob パターン](https://github.com/mrmlnc/fast-glob#pattern-syntax) を利用して複数ファイルをマッチさせることができ、パターンはローダーファイルからの相対パスで指定できます。`load()` 関数にはマッチしたファイルの絶対パスが渡されます。 + +以下は CSV ファイルを読み込み [csv-parse](https://github.com/adaltas/node-csv/tree/master/packages/csv-parse/) を使って JSON に変換する例です。このコードはビルド時にのみ実行されるため、CSV パーサーがクライアントに送られることはありません。 + +```js +import fs from 'node:fs' +import { parse } from 'csv-parse/sync' + +export default { + watch: ['./data/*.csv'], + load(watchedFiles) { + return watchedFiles.map((file) => { + return parse(fs.readFileSync(file, 'utf-8'), { + columns: true, + skip_empty_lines: true + }) + }) + } +} +``` + +## `createContentLoader` + +コンテンツ中心のサイトを構築する場合、ブログ記事や API ページなどを一覧表示する「アーカイブ」や「インデックス」ページが必要になることがよくあります。これはデータローダー API を使って直接実装できますが、あまりにも一般的なケースなので VitePress では `createContentLoader` というヘルパーが用意されています。 + +```js [posts.data.js] +import { createContentLoader } from 'vitepress' + +export default createContentLoader('posts/*.md', /* options */) +``` + +このヘルパーは [ソースディレクトリ](./routing#source-directory) からの相対 glob パターンを受け取り、`{ watch, load }` を返すデータローダーオブジェクトを生成します。これをデータローダーファイルのデフォルトエクスポートにできます。開発時のパフォーマンスを向上させるために、ファイルの更新時刻に基づくキャッシュも行われます。 + +このローダーは Markdown ファイルにのみ対応し、それ以外のファイルは無視されます。 + +読み込まれるデータは `ContentData[]` 型の配列です。 + +```ts +interface ContentData { + url: string // ページのマッピング URL(例: /posts/hello.html) + frontmatter: Record // ページのフロントマター + + src: string | undefined + html: string | undefined + excerpt: string | undefined +} +``` + +デフォルトでは `url` と `frontmatter` のみが提供されます。これは読み込まれたデータがクライアントバンドルに JSON としてインライン化されるため、サイズに注意する必要があるためです。 + +以下はデータを使って最小限のブログインデックスページを構築する例です。 + +```vue + + + +``` + +### オプション {#options} + +デフォルトデータが要件に合わない場合は、オプションで変換処理を追加できます。 + +```js [posts.data.js] +import { createContentLoader } from 'vitepress' + +export default createContentLoader('posts/*.md', { + includeSrc: true, // 生の markdown ソースを含める? + render: true, // レンダリングされた HTML を含める? + excerpt: true, // 抜粋を含める? + + transform(rawData) { + return rawData + .sort((a, b) => { + return +new Date(b.frontmatter.date) - +new Date(a.frontmatter.date) + }) + .map((page) => { + page.src // 生の markdown ソース + page.html // レンダリングされた HTML + page.excerpt // 抜粋 HTML(最初の `---` までの内容) + return {/* ... */} + }) + } +}) +``` + +[Vue.js ブログ](https://github.com/vuejs/blog/blob/main/.vitepress/theme/posts.data.ts) での使用例も参考になります。 + +`createContentLoader` API は [ビルドフック](../reference/site-config#build-hooks) 内でも利用可能です。 + +```js [.vitepress/config.js] +export default { + async buildEnd() { + const posts = await createContentLoader('posts/*.md').load() + // メタデータを基にファイルを生成(例: RSS フィード) + } +} +``` + +**型定義** + +```ts +interface ContentOptions { + includeSrc?: boolean + render?: boolean + excerpt?: + | boolean + | ((file: { data: { [key: string]: any }; content: string; excerpt?: string }, options?: any) => void) + | string + transform?: (data: ContentData[]) => T | Promise +} +``` + +## 型付きデータローダー {#typed-data-loaders} + + +TypeScript を使用する場合は、ローダーと `data` エクスポートを型付けできます。 + +```ts +import { defineLoader } from 'vitepress' + +export interface Data { + // データ型 +} + +declare const data: Data +export { data } + +export default defineLoader({ + watch: ['...'], + async load(): Promise { + // ... + } +}) +``` + +## 設定情報の取得 {#configuration} + + +ローダー内で設定情報を取得するには次のようにします。 + +```ts +import type { SiteConfig } from 'vitepress' + +const config: SiteConfig = (globalThis as any).VITEPRESS_CONFIG +``` diff --git a/docs/ja/guide/deploy.md b/docs/ja/guide/deploy.md new file mode 100644 index 00000000..38029e9c --- /dev/null +++ b/docs/ja/guide/deploy.md @@ -0,0 +1,348 @@ +--- +outline: deep +--- + +# VitePress サイトをデプロイする {#deploy-your-vitepress-site} + + +以下のガイドは、次の前提に基づいています。 + +- VitePress のサイトはプロジェクトの `docs` ディレクトリ内にある。 +- デフォルトのビルド出力ディレクトリ(`.vitepress/dist`)を使用している。 +- VitePress はプロジェクトのローカル依存としてインストールされており、`package.json` に次のスクリプトが設定されている。 + +```json [package.json] + { + "scripts": { + "docs:build": "vitepress build docs", + "docs:preview": "vitepress preview docs" + } + } +``` + +## ローカルでビルドしてテストする {#build-and-test-locally} + + +1. 次のコマンドでドキュメントをビルドします。 + + ```sh + $ npm run docs:build + ``` + +2. ビルド後、次のコマンドでローカルプレビューします。 + + ```sh + $ npm run docs:preview + ``` + + `preview` コマンドはローカルの静的 Web サーバーを起動し、出力ディレクトリ `.vitepress/dist` を `http://localhost:4173` で配信します。プロダクションへプッシュする前に見た目を確認できます。 + +3. `--port` 引数でサーバーのポートを設定できます。 + + ```json + { + "scripts": { + "docs:preview": "vitepress preview docs --port 8080" + } + } + ``` + + これで `docs:preview` は `http://localhost:8080` でサーバーを起動します。 + +## 公開ベースパスの設定 {#setting-a-public-base-path} + + +デフォルトでは、サイトはドメインのルートパス(`/`)にデプロイされることを想定しています。サイトをサブパス、例:`https://mywebsite.com/blog/` で配信する場合は、VitePress の設定で [`base`](../reference/site-config#base) オプションを `'/blog/'` に設定してください。 + +**例:** GitHub(または GitLab)Pages に `user.github.io/repo/` としてデプロイするなら、`base` を `/repo/` に設定します。 + +## HTTP キャッシュヘッダー {#http-cache-headers} + + +本番サーバーの HTTP ヘッダーを制御できる場合は、`cache-control` ヘッダーを設定して、再訪時のパフォーマンスを向上させましょう。 + +本番ビルドでは静的アセット(JavaScript、CSS、`public` 以外のインポートアセット)にハッシュ付きファイル名が使用されます。ブラウザの開発者ツールのネットワークタブで本番プレビューを確認すると、`app.4f283b18.js` のようなファイルが見られます。 + +この `4f283b18` ハッシュはファイル内容から生成されます。同じハッシュの URL は同じ内容を必ず返し、内容が変われば URL も変わります。したがって、これらのファイルには最も強いキャッシュヘッダーを安全に適用できます。これらのファイルは出力ディレクトリ内の `assets/` 配下に配置されるため、次のヘッダーを設定できます。 + +``` +Cache-Control: max-age=31536000,immutable +``` + +::: details Netlify の `_headers` ファイル例 + +``` +/assets/* + cache-control: max-age=31536000 + cache-control: immutable +``` + +注:`_headers` ファイルは [public ディレクトリ](./asset-handling#the-public-directory) に配置します(この例では `docs/public/_headers`)。そうすると、ビルド出力にそのままコピーされます。 + +[Netlify のカスタムヘッダードキュメント](https://docs.netlify.com/routing/headers/) + +::: + +::: details `vercel.json` による Vercel 設定例 + +```json + { + "headers": [ + { + "source": "/assets/(.*)", + "headers": [ + { + "key": "Cache-Control", + "value": "max-age=31536000, immutable" + } + ] + } + ] + } +``` + +注:`vercel.json` は **リポジトリのルート** に配置してください。 + +[Vercel のヘッダー設定ドキュメント](https://vercel.com/docs/concepts/projects/project-configuration#headers) + +::: + +## プラットフォーム別ガイド {#platform-guides} + + +### Netlify / Vercel / Cloudflare Pages / AWS Amplify / Render {#netlify-vercel-cloudflare-pages-aws-amplify-render} + +新しいプロジェクトを作成し、ダッシュボードで次の設定に変更します。 + +- **Build Command:** `npm run docs:build` +- **Output Directory:** `docs/.vitepress/dist` +- **Node Version:** `20`(以上) + +::: warning +HTML の _Auto Minify_ のようなオプションを有効にしないでください。Vue にとって意味のあるコメントが出力から削除され、削除されるとハイドレーションの不整合エラーが発生する可能性があります。 +::: + +### GitHub Pages {#github-pages} + +1. プロジェクトの `.github/workflows` ディレクトリに `deploy.yml` を作成し、以下の内容を記述します。 + + ```yaml [.github/workflows/deploy.yml] + # Sample workflow for building and deploying a VitePress site to GitHub Pages + # + name: Deploy VitePress site to Pages + + on: + # Runs on pushes targeting the `main` branch. Change this to `master` if you're + # using the `master` branch as the default branch. + push: + branches: [main] + + # Allows you to run this workflow manually from the Actions tab + workflow_dispatch: + + # Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages + permissions: + contents: read + pages: write + id-token: write + + # Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued. + # However, do NOT cancel in-progress runs as we want to allow these production deployments to complete. + concurrency: + group: pages + cancel-in-progress: false + + jobs: + # Build job + build: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 # Not needed if lastUpdated is not enabled + # - uses: pnpm/action-setup@v3 # Uncomment this block if you're using pnpm + # with: + # version: 9 # Not needed if you've set "packageManager" in package.json + # - uses: oven-sh/setup-bun@v1 # Uncomment this if you're using Bun + - name: Setup Node + uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm # or pnpm / yarn + - name: Setup Pages + uses: actions/configure-pages@v4 + - name: Install dependencies + run: npm ci # or pnpm install / yarn install / bun install + - name: Build with VitePress + run: npm run docs:build # or pnpm docs:build / yarn docs:build / bun run docs:build + - name: Upload artifact + uses: actions/upload-pages-artifact@v3 + with: + path: docs/.vitepress/dist + + # Deployment job + deploy: + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + needs: build + runs-on: ubuntu-latest + name: Deploy + steps: + - name: Deploy to GitHub Pages + id: deployment + uses: actions/deploy-pages@v4 + ``` + + ::: warning + VitePress の `base` オプションが正しく設定されていることを確認してください。詳細は [公開ベースパスの設定](#公開ベースパスの設定) を参照してください。 + ::: + +2. リポジトリ設定の「Pages」メニューで、「Build and deployment > Source」を「GitHub Actions」に設定します。 + +3. 変更を `main` ブランチにプッシュし、GitHub Actions の完了を待ちます。設定に応じて、サイトは `https://.github.io/[repository]/` または `https:///` にデプロイされます。以後、`main` へのプッシュごとに自動デプロイされます。 + +### GitLab Pages {#gitlab-pages} + +1. VitePress の設定で `outDir` を `../public` に設定します。`https://.gitlab.io//` にデプロイする場合は `base` を `'//'` に設定します。カスタムドメイン、ユーザー/グループページ、または GitLab の「Use unique domain」を有効にしている場合は `base` は不要です。 + +2. プロジェクトのルートに `.gitlab-ci.yml` を作成して、以下を追加します。これにより、コンテンツを更新するたびにサイトがビルド・デプロイされます。 + + ```yaml [.gitlab-ci.yml] + image: node:18 + pages: + cache: + paths: + - node_modules/ + script: + # - apk add git # Uncomment this if you're using small docker images like alpine and have lastUpdated enabled + - npm install + - npm run docs:build + artifacts: + paths: + - public + only: + - main + ``` + +### Azure Static Web Apps {#azure-static-web-apps} + +1. [公式ドキュメント](https://docs.microsoft.com/en-us/azure/static-web-apps/build-configuration) に従います。 + +2. 設定ファイルで次の値を指定します(`api_location` のように不要なものは削除)。 + + - **`app_location`**: `/` + - **`output_location`**: `docs/.vitepress/dist` + - **`app_build_command`**: `npm run docs:build` + +### Firebase {#firebase} + +1. プロジェクトのルートに `firebase.json` と `.firebaserc` を作成します。 + + `firebase.json`: + + ```json [firebase.json] + { + "hosting": { + "public": "docs/.vitepress/dist", + "ignore": [] + } + } + ``` + + `.firebaserc`: + + ```json [.firebaserc] + { + "projects": { + "default": "" + } + } + ``` + +2. `npm run docs:build` の後、次のコマンドでデプロイします。 + + ```sh + firebase deploy + ``` + +### Surge {#surge} + +1. `npm run docs:build` の後、次のコマンドでデプロイします。 + + ```sh + npx surge docs/.vitepress/dist + ``` + +### Heroku {#heroku} + +1. [`heroku-buildpack-static`](https://elements.heroku.com/buildpacks/heroku/heroku-buildpack-static) のドキュメントとガイドに従います。 + +2. プロジェクトのルートに `static.json` を作成し、以下を記述します。 + + ```json [static.json] + { + "root": "docs/.vitepress/dist" + } + ``` + +### Edgio {#edgio} + +[Creating and Deploying a VitePress App To Edgio](https://docs.edg.io/guides/vitepress) を参照してください。 + +### Kinsta Static Site Hosting {#kinsta-static-site-hosting} + +[VitePress](https://kinsta.com/static-site-hosting/) を [こちらの手順](https://kinsta.com/docs/vitepress-static-site-example/) に従ってデプロイできます。 + +### Stormkit {#stormkit} + +[VitePress プロジェクトを Stormkit にデプロイ](https://stormkit.io/blog/how-to-deploy-vitepress) する手順を参照してください。 + +### CloudRay {#cloudray} + +[CloudRay](https://cloudray.io/) でのデプロイ方法は [こちらの手順](https://cloudray.io/articles/how-to-deploy-vitepress-site) を参照してください。 + +### Nginx {#nginx} + +以下は Nginx サーバーブロックの設定例です。一般的なテキスト系アセットの gzip 圧縮、VitePress サイトの静的ファイル配信における適切なキャッシュヘッダー、そして `cleanUrls: true` のハンドリングを含みます。 + +```nginx +server { + gzip on; + gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; + + listen 80; + server_name _; + index index.html; + + location / { + # content location + root /app; + + # exact matches -> reverse clean urls -> folders -> not found + try_files $uri $uri.html $uri/ =404; + + # non existent pages + error_page 404 /404.html; + + # a folder without index.html raises 403 in this setup + error_page 403 /404.html; + + # adjust caching headers + # files in the assets folder have hashes filenames + location ~* ^/assets/ { + expires 1y; + add_header Cache-Control "public, immutable"; + } + } +} +``` + +この設定は、ビルド済みの VitePress サイトがサーバー上の `/app` ディレクトリに配置されていることを想定しています。サイトのファイルが別の場所にある場合は、`root` ディレクティブを適宜変更してください。 + +::: warning index.html をデフォルトにしない +`try_files` の解決先を、他の Vue アプリのように index.html にフォールバックさせないでください。不正なページ状態になります。 +::: + +詳細は [公式 nginx ドキュメント](https://nginx.org/en/docs/)、Issue [#2837](https://github.com/vuejs/vitepress/discussions/2837)、[#3235](https://github.com/vuejs/vitepress/issues/3235)、および Mehdi Merah 氏の [ブログ記事](https://blog.mehdi.cc/articles/vitepress-cleanurls-on-nginx-environment#readings) を参照してください。 diff --git a/docs/ja/guide/extending-default-theme.md b/docs/ja/guide/extending-default-theme.md new file mode 100644 index 00000000..6047ac91 --- /dev/null +++ b/docs/ja/guide/extending-default-theme.md @@ -0,0 +1,332 @@ +--- +outline: deep +--- + +# デフォルトテーマの拡張 {#extending-the-default-theme} + +VitePress のデフォルトテーマはドキュメント向けに最適化されており、カスタマイズ可能です。利用できるオプションの一覧は [デフォルトテーマの概要](../reference/default-theme-config) を参照してください。 + +しかし、設定だけでは不十分なケースもあります。例えば: + +1. CSS のスタイルを微調整したい +2. グローバルコンポーネントの登録など、Vue アプリインスタンスを変更したい +3. レイアウトのスロット経由でテーマに独自コンテンツを挿入したい + +これらの高度なカスタマイズには、デフォルトテーマを「拡張」するカスタムテーマを使用する必要があります。 + +::: tip +先に [カスタムテーマの使用](./custom-theme) を読み、カスタムテーマの仕組みを理解してから進めてください。 +::: + +## CSS のカスタマイズ {#customizing-css} + +デフォルトテーマの CSS は、ルートレベルの CSS 変数をオーバーライドすることでカスタマイズできます。 + +```js [.vitepress/theme/index.js] +import DefaultTheme from 'vitepress/theme' +import './custom.css' + +export default DefaultTheme +``` + +```css +/* .vitepress/theme/custom.css */ +:root { + --vp-c-brand-1: #646cff; + --vp-c-brand-2: #747bff; +} +``` + +上書き可能な [デフォルトテーマの CSS 変数](https://github.com/vuejs/vitepress/blob/main/src/client/theme-default/styles/vars.css) を参照してください。 + +## フォントを変更する {#using-different-fonts} + +VitePress はデフォルトフォントとして [Inter](https://rsms.me/inter/) を使用し、ビルド出力にフォントを含めます。プロダクションでは自動でプリロードもされます。しかし、別のメインフォントを使いたい場合には望ましくないことがあります。 + +Inter をビルド出力に含めたくない場合は、`vitepress/theme-without-fonts` からテーマをインポートします。 + +```js [.vitepress/theme/index.js] +import DefaultTheme from 'vitepress/theme-without-fonts' +import './my-fonts.css' + +export default DefaultTheme +``` + +```css +/* .vitepress/theme/my-fonts.css */ +:root { + --vp-font-family-base: /* 通常テキスト用フォント */ + --vp-font-family-mono: /* コード用フォント */ +} +``` + +::: warning +[Team Page](../reference/default-theme-team-page) などのオプションコンポーネントを使う場合も、必ず `vitepress/theme-without-fonts` からインポートしてください。 +::: + +フォントが `@font-face` で参照されるローカルファイルの場合、アセットとして処理され、ハッシュ付きファイル名で `.vitepress/dist/assets` に出力されます。このファイルをプリロードするには、[transformHead](../reference/site-config#transformhead) ビルドフックを使います。 + +```js [.vitepress/config.js] +export default { + transformHead({ assets }) { + // 使うフォントに合わせて正規表現を調整 + const myFontFile = assets.find(file => /font-name\.[\w-]+\.woff2/.test(file)) + if (myFontFile) { + return [ + [ + 'link', + { + rel: 'preload', + href: myFontFile, + as: 'font', + type: 'font/woff2', + crossorigin: '' + } + ] + ] + } + } +} +``` + +## グローバルコンポーネントの登録 {#registering-global-components} + +```js [.vitepress/theme/index.js] +import DefaultTheme from 'vitepress/theme' + +/** @type {import('vitepress').Theme} */ +export default { + extends: DefaultTheme, + enhanceApp({ app }) { + // 独自のグローバルコンポーネントを登録 + app.component('MyGlobalComponent' /* ... */) + } +} +``` + +TypeScript を使う場合: + +```ts [.vitepress/theme/index.ts] +import type { Theme } from 'vitepress' +import DefaultTheme from 'vitepress/theme' + +export default { + extends: DefaultTheme, + enhanceApp({ app }) { + // 独自のグローバルコンポーネントを登録 + app.component('MyGlobalComponent' /* ... */) + } +} satisfies Theme +``` + +Vite を使っているため、Vite の [glob import 機能](https://vitejs.dev/guide/features.html#glob-import) を利用してディレクトリ内のコンポーネントを自動登録することもできます。 + +## レイアウトスロット {#layout-slots} + +デフォルトテーマの `` コンポーネントには、ページ内の特定の位置にコンテンツを挿入するためのスロットがいくつか用意されています。以下は、アウトラインの前にコンポーネントを挿入する例です。 + +```js [.vitepress/theme/index.js] +import DefaultTheme from 'vitepress/theme' +import MyLayout from './MyLayout.vue' + +export default { + extends: DefaultTheme, + // スロットを注入するラッパーコンポーネントで Layout を上書き + Layout: MyLayout +} +``` + +```vue [.vitepress/theme/MyLayout.vue] + + + +``` + +レンダーファンクションを使う方法もあります。 + +```js [.vitepress/theme/index.js] +import { h } from 'vue' +import DefaultTheme from 'vitepress/theme' +import MyComponent from './MyComponent.vue' + +export default { + extends: DefaultTheme, + Layout() { + return h(DefaultTheme.Layout, null, { + 'aside-outline-before': () => h(MyComponent) + }) + } +} +``` + +デフォルトテーマレイアウトで利用可能なスロットの一覧: + +- フロントマターで `layout: 'doc'`(デフォルト)を有効にしているとき: + - `doc-top` + - `doc-bottom` + - `doc-footer-before` + - `doc-before` + - `doc-after` + - `sidebar-nav-before` + - `sidebar-nav-after` + - `aside-top` + - `aside-bottom` + - `aside-outline-before` + - `aside-outline-after` + - `aside-ads-before` + - `aside-ads-after` +- フロントマターで `layout: 'home'` を有効にしているとき: + - `home-hero-before` + - `home-hero-info-before` + - `home-hero-info` + - `home-hero-info-after` + - `home-hero-actions-after` + - `home-hero-image` + - `home-hero-after` + - `home-features-before` + - `home-features-after` +- フロントマターで `layout: 'page'` を有効にしているとき: + - `page-top` + - `page-bottom` +- 404(Not Found)ページ: + - `not-found` +- 常に利用可能: + - `layout-top` + - `layout-bottom` + - `nav-bar-title-before` + - `nav-bar-title-after` + - `nav-bar-content-before` + - `nav-bar-content-after` + - `nav-screen-content-before` + - `nav-screen-content-after` + +## View Transitions API の利用 + +### 外観切り替え時(ライト/ダーク) {#on-appearance-toggle} + +カラーモード切り替え時にカスタムトランジションを提供するよう、デフォルトテーマを拡張できます。例: + +```vue [.vitepress/theme/Layout.vue] + + + + + +``` + +結果(**注意!**:点滅や急な動き、明るい光を含みます): + +
+デモ + +![Appearance Toggle Transition Demo](/appearance-toggle-transition.webp) + +
+ +詳細は [Chrome Docs](https://developer.chrome.com/docs/web-platform/view-transitions/) を参照してください。 + +### ルート遷移時 {#on-route-change} + +近日公開。 + +## 内部コンポーネントの置き換え {#overriding-internal-components} + +Vite の [エイリアス](https://vitejs.dev/config/shared-options.html#resolve-alias) を使って、デフォルトテーマのコンポーネントを独自のものに置き換えられます。 + +```ts +import { fileURLToPath, URL } from 'node:url' +import { defineConfig } from 'vitepress' + +export default defineConfig({ + vite: { + resolve: { + alias: [ + { + find: /^.*\/VPNavBar\.vue$/, + replacement: fileURLToPath( + new URL('./theme/components/CustomNavBar.vue', import.meta.url) + ) + } + ] + } + } +}) +``` + +正確なコンポーネント名は [ソースコード](https://github.com/vuejs/vitepress/tree/main/src/client/theme-default/components) を参照してください。内部コンポーネントであるため、マイナーリリース間で名称が更新される可能性があります。 diff --git a/docs/ja/guide/frontmatter.md b/docs/ja/guide/frontmatter.md new file mode 100644 index 00000000..0c5ddcb5 --- /dev/null +++ b/docs/ja/guide/frontmatter.md @@ -0,0 +1,48 @@ +# フロントマター {#frontmatter} + +## 使い方 {#usage} + +VitePress はすべての Markdown ファイルで YAML フロントマターをサポートしており、[gray-matter](https://github.com/jonschlinkert/gray-matter) で解析します。フロントマターは Markdown ファイルの先頭(` + + +``` + +## RTL サポート(実験的){#rtl-support-experimental} + +RTL をサポートするには、設定で `dir: 'rtl'` を指定し、、または のような RTLCSS 系の PostCSS プラグインを使用してください。CSS の詳細度の問題を避けるため、PostCSS プラグインでは `:where([dir="ltr"])` と `:where([dir="rtl"])` を接頭辞として使うよう設定してください。 diff --git a/docs/ja/guide/markdown.md b/docs/ja/guide/markdown.md new file mode 100644 index 00000000..966ce72c --- /dev/null +++ b/docs/ja/guide/markdown.md @@ -0,0 +1,1040 @@ +# Markdown 拡張 {#markdown-extensions} + +VitePress には組み込みの Markdown 拡張機能が用意されています。 + +## 見出しアンカー {#header-anchors} + +見出しには自動的にアンカーリンクが付与されます。アンカーのレンダリングは `markdown.anchor` オプションで設定できます。 + +### カスタムアンカー {#custom-anchors} + +自動生成ではなく任意のアンカーを指定したい場合は、見出しの末尾にサフィックスを追加します。 + + ```md + # カスタムアンカーを使う {#my-anchor} + ``` + +これにより、デフォルトの `#using-custom-anchors` ではなく `#my-anchor` でその見出しにリンクできます。 + +## リンク {#links} + +内部リンクと外部リンクは特別に処理されます。 + +### 内部リンク {#internal-links} + +内部リンクは SPA ナビゲーションのためにルーターリンクへ変換されます。また、各サブディレクトリにある `index.md` は自動的に `index.html` に変換され、URL は対応する `/` になります。 + +次のようなディレクトリ構成があるとします。 + + ``` + . + ├─ index.md + ├─ foo + │ ├─ index.md + │ ├─ one.md + │ └─ two.md + └─ bar + ├─ index.md + ├─ three.md + └─ four.md + ``` + +そして、現在編集中のファイルが `foo/one.md` の場合: + + ```md + [Home](/) + [foo](/foo/) + [foo の見出し](./#heading) + [bar - three](../bar/three) + [bar - three](../bar/three.md) + [bar - four](../bar/four.html) + ``` + +### ページサフィックス {#page-suffix} + +ページと内部リンクはデフォルトで `.html` サフィックス付きで生成されます。 + +### 外部リンク {#external-links} + +外部リンクには自動的に `target="_blank" rel="noreferrer"` が付与されます。 + +- [vuejs.org](https://vuejs.org) +- [VitePress on GitHub](https://github.com/vuejs/vitepress) + +## フロントマター {#frontmatter} + +[YAML フロントマター](https://jekyllrb.com/docs/front-matter/) をそのままサポートしています。 + + ```yaml + --- + title: ハッカーのようにブログを書く + lang: ja-JP + --- + ``` + +このデータはページ内や、カスタム/テーマコンポーネントからも利用できます。詳しくは [Frontmatter](../reference/frontmatter-config) を参照してください。 + +## GitHub 風テーブル {#github-style-tables} + +**入力** + + ```md + | テーブル | は | クール | + | -------------- | :---------: | ------: | + | 3列目は | 右寄せ | $1600 | + | 2列目は | 中央 | $12 | + | シマ模様 | neat です | $1 | + ``` + +**出力** + +| テーブル | は | クール | +| -------- | :----: | ------: | +| 3列目は | 右寄せ | \$1600 | +| 2列目は | 中央 | \$12 | +| シマ模様 | neatです | \$1 | + +## 絵文字 :tada: {#emoji} + +**入力** + + ``` + :tada: :100: + ``` + +**出力** + +:tada: :100: + +すべての絵文字の [一覧はこちら](https://github.com/markdown-it/markdown-it-emoji/blob/master/lib/data/full.mjs)。 + +## 目次 {#table-of-contents} + +**入力** + + ``` + [[toc]] + ``` + +**出力** + +[[toc]] + +TOC のレンダリングは `markdown.toc` オプションで設定できます。 + +## カスタムコンテナ {#custom-containers} + +タイプ、タイトル、内容を指定してカスタムコンテナを定義できます。 + +### デフォルトタイトル {#default-title} + +**入力** + + ```md + ::: info + これは情報ボックスです。 + ::: + + ::: tip + これはヒントです。 + ::: + + ::: warning + これは警告です。 + ::: + + ::: danger + これは危険の警告です。 + ::: + + ::: details + これは詳細ブロックです。 + ::: + ``` + +**出力** + +::: info +これは情報ボックスです。 +::: + +::: tip +これはヒントです。 +::: + +::: warning +これは警告です。 +::: + +::: danger +これは危険の警告です。 +::: + +::: details +これは詳細ブロックです。 +::: + +### カスタムタイトル {#custom-title} + +コンテナの「タイプ」の直後に文字列を追加することで、タイトルをカスタマイズできます。 + +**入力** + + ````md + ::: danger 停止 + 危険地帯。先に進まないでください。 + ::: + + ::: details クリックしてコードを表示/非表示 + ```js + console.log('こんにちは、VitePress!') + ``` + ::: + ```` + +**出力** + +::: danger 停止 +危険地帯。先に進まないでください。 +::: + +::: details クリックしてコードを表示/非表示 + ```js + console.log('こんにちは、VitePress!') + ``` +::: + +また、英語以外で執筆する場合などは、サイト設定に以下を追加してタイトル文字列をグローバルに上書きできます。 + + ```ts + // config.ts + export default defineConfig({ + // ... + markdown: { + container: { + tipLabel: 'ヒント', + warningLabel: '警告', + dangerLabel: '危険', + infoLabel: '情報', + detailsLabel: '詳細' + } + } + // ... + }) + ``` + +### 追加属性 {#additional-attributes} + +カスタムコンテナには追加の属性を付与できます。この機能には [markdown-it-attrs](https://github.com/arve0/markdown-it-attrs) を使用しており、ほぼすべての Markdown 要素でサポートされます。たとえば `open` 属性を付けると、details ブロックをデフォルトで開いた状態にできます。 + +**入力** + + ````md + ::: details クリックしてコードを表示/非表示 {open} + ```js + console.log('こんにちは、VitePress!') + ``` + ::: + ```` + +**出力** + +::: details クリックしてコードを表示/非表示 {open} + ```js + console.log('こんにちは、VitePress!') + ``` +::: + +### `raw` + +これは、VitePress でのスタイルやルーターの衝突を防ぐための特別なコンテナです。コンポーネントライブラリのドキュメント化に特に有用です。より強力な分離が必要であれば、[whyframe](https://whyframe.dev/docs/integrations/vitepress) も検討してください。 + +**構文** + + ```md + ::: raw + Wraps in a `
` + ::: + ``` + +`vp-raw` クラスは要素に直接付与することも可能です。スタイルの分離は現在オプトインです。 + +- お好みのパッケージマネージャで `postcss` をインストールします: + + ```sh + $ npm add -D postcss + ``` + +- `docs/postcss.config.mjs` を作成し、次を追加します: + + ```js + import { postcssIsolateStyles } from 'vitepress' + + export default { + plugins: [postcssIsolateStyles()] + } + ``` + + オプションは次のように渡せます: + + ```js + postcssIsolateStyles({ + includeFiles: [/custom\.css/] // 既定は [/vp-doc\.css/, /base\.css/] + }) + ``` + +## GitHub 形式のアラート {#github-flavored-alerts} + +VitePress は [GitHub 形式のアラート](https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax#alerts) をコールアウトとしてレンダリングできます。表示は [カスタムコンテナ](#custom-containers) と同様です。 + +**入力** + + + ```md + > [!NOTE] + > 流し読みでも目に留めてほしい情報を強調します。 + + > [!TIP] + > 成功の手助けとなる任意の情報です。 + + > [!IMPORTANT] + > 成功に必須の重要情報です。 + + > [!WARNING] + > 危険性があるため即時の注意が必要な重要情報です。 + + > [!CAUTION] + > 行動による望ましくない結果の可能性です。 + +``` + +**出力** + + + > [!NOTE] + > 流し読みでも目に留めてほしい情報を強調します。 + + > [!TIP] + > 成功の手助けとなる任意の情報です。 + + > [!IMPORTANT] + > 成功に必須の重要情報です。 + + > [!WARNING] + > 危険性があるため即時の注意が必要な重要情報です。 + + > [!CAUTION] + > 行動による望ましくない結果の可能性です。 + + +## コードブロックのシンタックスハイライト {#syntax-highlighting-in-code-blocks} + +VitePress は [Shiki](https://github.com/shikijs/shiki) を使って、Markdown のコードブロックに色付きのシンタックスハイライトを適用します。Shiki は多くのプログラミング言語をサポートしています。コードブロックの先頭のバッククォートに有効な言語エイリアスを付けるだけで利用できます。 + +**入力** + + ```` + ```js + export default { + name: 'MyComponent', + // ... + } + ``` +```` + ```` + ```html +
    +
  • + {{ todo.text }} +
  • +
+ ``` + ```` + +**出力** + + ```js + export default { + name: 'MyComponent', + // ... + } + ``` + ```html +
    +
  • + {{ todo.text }} +
  • +
+ ``` + +有効な言語の [一覧](https://shiki.style/languages) は Shiki のリポジトリで確認できます。 + +また、シンタックスハイライトのテーマ変更、言語エイリアスの設定、言語ラベルのカスタマイズなどはアプリ設定の [`markdown` オプション](../reference/site-config#markdown) で行えます。 + +## コードブロックの行ハイライト {#line-highlighting-in-code-blocks} + +**入力** + + ```` + ```js{4} + export default { + data () { + return { + msg: 'ハイライト!' + } + } + } + ``` + ```` + +**出力** + + ```js{4} + export default { + data () { + return { + msg: 'ハイライト!' + } + } + } + ``` + +単一行だけでなく、複数の単一行や範囲、あるいはその組み合わせも指定できます: + +- 行範囲の例: `{5-8}`, `{3-10}`, `{10-17}` +- 複数の単一行: `{4,7,9}` +- 行範囲+単一行: `{4,7-13,16,23-27,40}` + +**入力** + + ```` + ```js{1,4,6-8} + export default { // Highlighted + data () { + return { + msg: `Highlighted! + This line isn't highlighted, + but this and the next 2 are.`, + motd: 'VitePress is awesome', + lorem: 'ipsum' + } + } + } + ``` + ```` + +**出力** + + + ```js{1,4,6-8} + export default { // Highlighted + data () { + return { + msg: `Highlighted! + This line isn't highlighted, + but this and the next 2 are.`, + motd: 'VitePress is awesome', + lorem: 'ipsum' + } + } + } + ``` + +代替案として、`// [!code highlight]` コメントを使って行内を直接ハイライトできます。 + +**入力** + + ``` + ```js + export default { + data () { + return { + msg: 'ハイライト!' // [!code highlight] + } + } + } + ``` + +**出力** + + + ```js + export default { + data () { + return { + msg: 'ハイライト!' // [!code highlight] + } + } + } + ``` + +## コードブロックでのフォーカス {#focus-in-code-blocks} + +`// [!code focus]` コメントを行に付けると、その行にフォーカスし、他の部分がぼかされます。 + +また、`// [!code focus:]` を使ってフォーカスする行数を指定することもできます。 + +**入力** + + ```` + ```js + export default { + data () { + return { + msg: 'フォーカス!' // [!!code focus] + } + } + } + ``` + ```` + +**出力** + +```js +export default { + data() { + return { + msg: 'フォーカス!' // [!code focus] + } + } +} +``` + +## コードブロックのカラー差分表示 {#colored-diffs-in-code-blocks} + +`// [!code --]` または `// [!code ++]` コメントを行に付けると、その行に差分(削除/追加)スタイルを適用できます。コードブロックの色付けは維持されます。 + +**入力** + + ```` + ```js + export default { + data () { + return { + msg: 'Removed' // [!!code --] + msg: 'Added' // [!!code ++] + } + } + } + ``` + ```` + +**出力** + +```js +export default { + data () { + return { + msg: 'Removed' // [!code --] + msg: 'Added' // [!code ++] + } + } +} +``` + +## コードブロック内のエラー/警告表示 {#errors-and-warnings-in-code-blocks} + +行に `// [!code warning]` または `// [!code error]` コメントを付けると、その行が対応する色で表示されます。 + +**入力** + + ```` + ```js + export default { + data () { + return { + msg: 'Error', // [!!code error] + msg: 'Warning' // [!!code warning] + } + } + } + ``` + ```` + +**出力** + +```js +export default { + data() { + return { + msg: 'Error', // [!code error] + msg: 'Warning' // [!code warning] + } + } +} +``` + +## 行番号 {#line-numbers} + +設定で、各コードブロックに行番号を表示できます: + + ```js + export default { + markdown: { + lineNumbers: true + } + } + ``` + +詳しくは [`markdown` オプション](../reference/site-config#markdown) を参照してください。 + +設定値を上書きするために、フェンス付きコードブロックに `:line-numbers` / `:no-line-numbers` マークを付与できます。 + +また、`:line-numbers` の後ろに `=` を付けて開始行番号を指定できます。例:`:line-numbers=2` は行番号が `2` から始まることを意味します。 + +**入力** + + ```` + ```ts {1} + // 既定では line-numbers は無効 + const line2 = 'This is line 2' + const line3 = 'This is line 3' + ``` + + ```ts:line-numbers {1} + // line-numbers が有効 + const line2 = 'This is line 2' + const line3 = 'This is line 3' + ``` + + ```ts:line-numbers=2 {1} + // line-numbers が有効で、2 から開始 + const line3 = 'This is line 3' + const line4 = 'This is line 4' + ``` + ```` + +**出力** + + ```ts {1} + // 既定では line-numbers は無効 + const line2 = 'This is line 2' + const line3 = 'This is line 3' + ``` + + ```ts:line-numbers {1} + // line-numbers が有効 + const line2 = 'This is line 2' + const line3 = 'This is line 3' + ``` + + ```ts:line-numbers=2 {1} + // line-numbers が有効で、2 から開始 + const line3 = 'This is line 3' + const line4 = 'This is line 4' + ``` + +## コードスニペットのインポート {#import-code-snippets} + +既存ファイルから、次の構文でコードスニペットをインポートできます: + + ```md + <<< @/filepath + ``` + +また、[行のハイライト](#line-highlighting-in-code-blocks)にも対応しています: + + ```md + <<< @/filepath{highlightLines} + ``` + +**入力** + + ```md + <<< @/snippets/snippet.js{2} + ``` + +**コードファイル** + +<<< @/snippets/snippet.js + +**出力** + +<<< @/snippets/snippet.js{2} + +::: tip +`@` の値はソースルートを表します。既定では VitePress プロジェクトのルートですが、`srcDir` を設定している場合はその値になります。代替として、相対パスからのインポートも可能です: + + ```md + <<< ../snippets/snippet.js + ``` +::: + +また、[VS Code のリージョン](https://code.visualstudio.com/docs/editor/codebasics#_folding)を利用して、コードファイルの該当部分のみを取り込むことができます。ファイルパスの後ろに `#` を付けてカスタムリージョン名を指定します: + +**入力** + + ```md + <<< @/snippets/snippet-with-region.js#snippet{1} + ``` + +**コードファイル** + +<<< @/snippets/snippet-with-region.js + +**出力** + +<<< @/snippets/snippet-with-region.js#snippet{1} + +中括弧(`{}`)の中で言語を指定することもできます: + + ```md + <<< @/snippets/snippet.cs{c#} + + + + <<< @/snippets/snippet.cs{1,2,4-6 c#} + + + + <<< @/snippets/snippet.cs{1,2,4-6 c#:line-numbers} + ``` + +これは、ファイル拡張子からソース言語を推論できない場合に有用です。 + +## コードグループ {#code-groups} + +複数のコードブロックを、次のようにグループ化できます。 + +**入力** + + ````md + ::: code-group + + ```js [config.js] + /** + * @type {import('vitepress').UserConfig} + */ + const config = { + // ... + } + + export default config + ``` + + ```ts [config.ts] + import type { UserConfig } from 'vitepress' + + const config: UserConfig = { + // ... + } + + export default config + ``` + + ::: + ```` + +**出力** + + + ::: code-group + + ```js [config.js] + /** + * @type {import('vitepress').UserConfig} + */ + const config = { + // ... + } + + export default config + ``` + + ```ts [config.ts] + import type { UserConfig } from 'vitepress' + + const config: UserConfig = { + // ... + } + + export default config + ``` + + ::: + +コードグループ内でも [スニペットのインポート](#import-code-snippets) が可能です: + +**入力** + + ```md + ::: code-group + + + + <<< @/snippets/snippet.js + + + + <<< @/snippets/snippet-with-region.js#snippet{1,2 ts:line-numbers} [リージョン付きスニペット] + + ::: + ``` + +**出力** + +::: code-group + +<<< @/snippets/snippet.js + +<<< @/snippets/snippet-with-region.js#snippet{1,2 ts:line-numbers} [リージョン付きスニペット] + +::: + +## Markdown ファイルのインクルード {#markdown-file-inclusion} + +ある Markdown ファイルの中に、別の Markdown ファイルを取り込めます(入れ子も可能)。 + +::: tip +Markdown パスの先頭に `@` を付けることもでき、その場合はソースルートとして扱われます。既定では VitePress プロジェクトのルートですが、`srcDir` を設定している場合はその値になります。 +::: + +例えば、相対パスの Markdown ファイルを次のように取り込めます。 + +**入力** + + ```md + # ドキュメント + + ## 基本 + + + ``` + +**パートファイル**(`parts/basics.md`) + + ```md + はじめに知っておきたいこと。 + + ### 設定 + + `.foorc.json` を使用して作成できます。 + ``` + +**等価なコード** + + ```md + # ドキュメント + + ## 基本 + + はじめに知っておきたいこと。 + + ### 設定 + + `.foorc.json` を使用して作成できます。 + ``` + +行範囲の選択にも対応しています。 + +**入力** + + ```md:line-numbers + # ドキュメント + + ## 基本 + + + ``` + +**パートファイル**(`parts/basics.md`) + + ```md:line-numbers + はじめに知っておきたいこと。 + + ### 設定 + + `.foorc.json` を使って作成できます。 + ``` + +**等価なコード** + + ```md:line-numbers + # ドキュメント + + ## 基本 + + ### 設定 + + `.foorc.json` を使って作成できます。 + ``` + +選択できる行範囲の書式は、`{3,}`、`{,10}`、`{1,10}` のいずれかです。 + +[VS Code のリージョン](https://code.visualstudio.com/docs/editor/codebasics#_folding)を使って、コードファイルの該当部分だけを取り込むこともできます。ファイルパスの後ろに `#` を付けて、カスタムリージョン名を指定します。 + +**入力** + + ```md:line-numbers + # ドキュメント + + ## 基本 + + + + ``` + +**パートファイル**(`parts/basics.md`) + + ```md:line-numbers + + ## 使用例 1 + + ## 使用例 2 + + ## 使用例 3 + + ``` + +**等価なコード** + + ```md:line-numbers + # ドキュメント + + ## 基本 + + ## 使用例 1 + + ## 使用例 3 + ``` + +::: warning +ファイルが存在しない場合でもエラーは発生しません。したがって、この機能を使う際は、期待どおりに内容がレンダリングされているか必ず確認してください。 +::: + +VS Code のリージョンの代わりに、ヘッダーアンカーを使ってファイル内の特定セクションだけを取り込むこともできます。たとえば、Markdown ファイルに次のようなヘッダーがある場合: + + ```md + ## ベースのセクション + + ここに本文。 + + ### サブセクション + + ここに本文(サブ)。 + + ## 別のセクション + + `ベースのセクション` の外側の内容。 + ``` + +`ベースのセクション` を次のように取り込めます: + + ```md + ## 拡張セクション + + ``` + +**等価なコード** + + ```md + ## 拡張セクション + + ここに本文。 + + ### サブセクション + + ここに本文(サブ)。 + ``` + +ここで `my-base-section` は見出し要素から生成される ID です。推測しづらい場合は、パートファイルをブラウザで開いて見出しのアンカー(ホバー時に見出しの左に表示される `#` 記号)をクリックし、URL バーで ID を確認してください。あるいはブラウザの開発者ツールで要素を検査して確認できます。別案として、パートファイル側で明示的に ID を指定できます: + + ```md + ## ベースのセクション {#custom-id} + ``` + +そして次のように取り込みます: + + ```md + + ``` + +## 数式 {#math-equations} + +この機能はオプトインです。利用するには `markdown-it-mathjax3` をインストールし、設定ファイルで `markdown.math` を `true` に設定します。 + + ```sh + npm add -D markdown-it-mathjax3 + ``` + + ```ts [.vitepress/config.ts] + export default { + markdown: { + math: true + } + } + ``` + +**入力** + + ```md + もし $a \ne 0$ のとき、$(ax^2 + bx + c = 0)$ の解は 2 つ存在し、次式で与えられます + $$ x = {-b \pm \sqrt{b^2-4ac} \over 2a} $$ + + **マクスウェル方程式:** + + | 方程式 | 説明 | + | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | + | $\nabla \cdot \vec{\mathbf{B}} = 0$ | 磁束密度 $\vec{\mathbf{B}}$ の発散は 0 | + | $\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} = \vec{\mathbf{0}}$ | 電場 $\vec{\mathbf{E}}$ の回転は、磁束密度 $\vec{\mathbf{B}}$ の時間変化に比例 | + | $\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} = \frac{4\pi}{c}\vec{\mathbf{j}} \nabla \cdot \vec{\mathbf{E}} = 4 \pi \rho$ | _え?_ | + ``` + +**出力** + + もし $a \ne 0$ のとき、$(ax^2 + bx + c = 0)$ の解は 2 つ存在し、次式で与えられます + $$ x = {-b \pm \sqrt{b^2-4ac} \over 2a} $$ + + **マクスウェル方程式:** + + | 方程式 | 説明 | + | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | + | $\nabla \cdot \vec{\mathbf{B}} = 0$ | 磁束密度 $\vec{\mathbf{B}}$ の発散は 0 | + | $\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} = \vec{\mathbf{0}}$ | 電場 $\vec{\mathbf{E}}$ の回転は、磁束密度 $\vec{\mathbf{B}}$ の時間変化に比例 | + | $\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} = \frac{4\pi}{c}\vec{\mathbf{j}} \nabla \cdot \vec{\mathbf{E}} = 4 \pi \rho$ | _え?_ | + +## 画像の遅延読み込み {#image-lazy-loading} + +Markdown で追加した各画像に対して遅延読み込みを有効化するには、設定ファイルで `lazyLoading` を `true` にします: + + ```js + export default { + markdown: { + image: { + // 既定では画像の遅延読み込みは無効 + lazyLoading: true + } + } + } + ``` + +## 高度な設定 {#advanced-configuration} + +VitePress は Markdown レンダラーとして [markdown-it](https://github.com/markdown-it/markdown-it) を使用しています。上記の多くの拡張はカスタムプラグインとして実装されています。`.vitepress/config.js` の `markdown` オプションを使って、`markdown-it` のインスタンスをさらにカスタマイズできます。 + + ```js + import { defineConfig } from 'vitepress' + import markdownItAnchor from 'markdown-it-anchor' + import markdownItFoo from 'markdown-it-foo' + + export default defineConfig({ + markdown: { + // markdown-it-anchor のオプション + // https://github.com/valeriangalliat/markdown-it-anchor#usage + anchor: { + permalink: markdownItAnchor.permalink.headerLink() + }, + + // @mdit-vue/plugin-toc のオプション + // https://github.com/mdit-vue/mdit-vue/tree/main/packages/plugin-toc#options + toc: { level: [1, 2] }, + + config: (md) => { + // markdown-it のプラグインをもっと使えます! + md.use(markdownItFoo) + } + } + }) + ``` + +設定可能なプロパティの完全な一覧は、[設定リファレンス: アプリ設定](../reference/site-config#markdown) を参照してください。 diff --git a/docs/ja/guide/mpa-mode.md b/docs/ja/guide/mpa-mode.md new file mode 100644 index 00000000..312cc3f7 --- /dev/null +++ b/docs/ja/guide/mpa-mode.md @@ -0,0 +1,23 @@ +# MPA モード {#mpa-mode} + +MPA(Multi-Page Application)モードは、コマンドラインの `vitepress build --mpa`、または設定で `mpa: true` を指定することで有効化できます。 + +MPA モードでは、既定で **あらゆるページが JavaScript を含まずに** レンダリングされます。結果として、本番サイトは監査ツールにおける初回訪問のパフォーマンススコアが向上しやすくなります。 + +一方、SPA のナビゲーションがないため、ページ間リンクはフルリロードになります。読み込み後のページ遷移は、SPA モードのような即時性はありません。 + +また、「既定で JS なし」ということは、実質的に Vue をサーバーサイドのテンプレート言語としてのみ使うことを意味します。ブラウザ側ではイベントハンドラがアタッチされないため、インタラクティブ性はありません。クライアントサイドの JavaScript を読み込むには、特別な ` + + # Hello + ``` + +` + ``` + +### 生コンテンツのレンダリング {#rendering-raw-content} + +ページに渡したパラメータはクライアント JavaScript のペイロードにシリアライズされます。そのため、リモート CMS から取得した生の Markdown や HTML など、重いデータをパラメータに含めるのは避けてください。 + +代わりに、各パスオブジェクトの `content` プロパティでコンテンツを渡せます: + + ```js + export default { + async paths() { + const posts = await (await fetch('https://my-cms.com/blog-posts')).json() + + return posts.map((post) => { + return { + params: { id: post.id }, + content: post.content // 生の Markdown または HTML + } + }) + } + } + ``` + +そのうえで、Markdown ファイル内で次の特別な構文を使って、そのコンテンツを埋め込みます: + + ```md + + ``` diff --git a/docs/ja/guide/sitemap-generation.md b/docs/ja/guide/sitemap-generation.md new file mode 100644 index 00000000..db44942c --- /dev/null +++ b/docs/ja/guide/sitemap-generation.md @@ -0,0 +1,58 @@ +# サイトマップ生成 {#sitemap-generation} + +VitePress には、サイト用の `sitemap.xml` を生成する機能が標準で用意されています。有効化するには、`.vitepress/config.js` に次を追加します。 + + ```ts + export default { + sitemap: { + hostname: 'https://example.com' + } + } + ``` + +`siteamp.xml` に `` タグを含めるには、[`lastUpdated`](../reference/default-theme-last-updated) オプションを有効にします。 + +## オプション {#options} + +サイトマップ生成は [`sitemap`](https://www.npmjs.com/package/sitemap) モジュールで行われます。設定ファイルの `sitemap` に、このモジュールがサポートする任意のオプションを渡せます。指定した値はそのまま `SitemapStream` コンストラクタに渡されます。詳しくは [`sitemap` のドキュメント](https://www.npmjs.com/package/sitemap#options-you-can-pass) を参照してください。例: + + ```ts + export default { + sitemap: { + hostname: 'https://example.com', + lastmodDateOnly: false + } + } + ``` + +設定で `base` を使っている場合は、`hostname` にもそれを付与してください: + + ```ts + export default { + base: '/my-site/', + sitemap: { + hostname: 'https://example.com/my-site/' + } + } + ``` + +## `transformItems` フック {#transformitems-hook} + +`siteamp.xml` に書き出す直前にサイトマップ項目を加工するには、`sitemap.transformItems` フックを使います。このフックはサイトマップ項目の配列を受け取り、配列を返す必要があります。例: + + ```ts + export default { + sitemap: { + hostname: 'https://example.com', + transformItems: (items) => { + // 既存項目の追加・変更・フィルタリングが可能 + items.push({ + url: '/extra-page', + changefreq: 'monthly', + priority: 0.8 + }) + return items + } + } + } + ``` diff --git a/docs/ja/guide/ssr-compat.md b/docs/ja/guide/ssr-compat.md new file mode 100644 index 00000000..d756d6d1 --- /dev/null +++ b/docs/ja/guide/ssr-compat.md @@ -0,0 +1,135 @@ +--- +outline: deep +--- + +# SSR 互換性 {#ssr-compatibility} + +VitePress は本番ビルド時に、Node.js 上で Vue のサーバーサイドレンダリング(SSR)機能を使ってアプリを事前レンダリングします。つまり、テーマコンポーネント内のすべてのカスタムコードは SSR 互換性の対象になります。 + +[公式 Vue ドキュメントの SSR セクション](https://vuejs.org/guide/scaling-up/ssr.html)では、SSR とは何か、SSR と SSG の関係、そして SSR に優しいコードを書く際の一般的な注意点が解説されています。経験則としては、**ブラウザ / DOM API へのアクセスは Vue コンポーネントの `beforeMount` または `mounted` フック内に限定** するのが安全です。 + +## `` {#clientonly} + +SSR に適さないコンポーネント(例:カスタムディレクティブを含むなど)を使用・デモする場合は、組み込みの `` コンポーネントでラップできます。 + + ```md + + + + ``` + +## インポート時に Browser API にアクセスするライブラリ {#libraries-that-access-browser-api-on-import} + +一部のコンポーネントやライブラリは **インポート時に** ブラウザ API にアクセスします。インポート時にブラウザ環境を前提とするコードを使うには、動的インポートが必要です。 + +### mounted フック内でのインポート {#importing-in-mounted-hook} + + ```vue + + ``` + +### 条件付きインポート {#conditional-import} + +[`import.meta.env.SSR`](https://vitejs.dev/guide/env-and-mode.html#env-variables) フラグ(Vite の環境変数の一部)を使って、依存関係を条件付きでインポートすることもできます。 + + ```js + if (!import.meta.env.SSR) { + import('./lib-that-access-window-on-import').then((module) => { + // ここでコードを利用 + }) + } + ``` + +[`Theme.enhanceApp`](./custom-theme#theme-interface) は非同期にできるため、**インポート時に Browser API に触れる Vue プラグイン** を条件付きでインポート・登録できます。 + + ```js [.vitepress/theme/index.js] + /** @type {import('vitepress').Theme} */ + export default { + // ... + async enhanceApp({ app }) { + if (!import.meta.env.SSR) { + const plugin = await import('plugin-that-access-window-on-import') + app.use(plugin.default) + } + } + } + ``` + +TypeScript を使う場合: + + ```ts [.vitepress/theme/index.ts] + import type { Theme } from 'vitepress' + + export default { + // ... + async enhanceApp({ app }) { + if (!import.meta.env.SSR) { + const plugin = await import('plugin-that-access-window-on-import') + app.use(plugin.default) + } + } + } satisfies Theme + ``` + +### `defineClientComponent` + +VitePress は、**インポート時に Browser API にアクセスする Vue コンポーネント** を読み込むためのユーティリティを提供します。 + + ```vue + + + + ``` + +ターゲットコンポーネントに props / children / slots を渡すこともできます。 + + ```vue + + + + ``` + +ターゲットコンポーネントは、ラッパーコンポーネントの mounted フックで初めてインポートされます。 diff --git a/docs/ja/guide/using-vue.md b/docs/ja/guide/using-vue.md new file mode 100644 index 00000000..65f2383e --- /dev/null +++ b/docs/ja/guide/using-vue.md @@ -0,0 +1,288 @@ +# MarkdownでVueを使う {#using-vue-in-markdown} + +VitePress では、各 Markdown ファイルはまず HTML にコンパイルされ、その後 [Vue の単一ファイルコンポーネント(SFC)](https://vuejs.org/guide/scaling-up/sfc.html) として処理されます。つまり、Markdown 内で Vue のあらゆる機能が使えます。動的テンプレート、Vue コンポーネントの利用、` + + ## Markdown コンテンツ + + 現在の値: {{ count }} + + + + + ``` + +::: warning Markdown での ` + ``` + +## Teleport の利用 {#using-teleports} + +現時点で VitePress は、SSG における Teleport を **body** へのみサポートしています。その他のターゲットへ Teleport したい場合は、組み込みの `` でラップするか、[`postRender` フック](../reference/site-config#postrender)で最終ページ HTML の適切な位置に Teleport のマークアップを注入してください。 + + + +::: details +<<< @/components/ModalDemo.vue +::: + + ```md + + +
+ // ... +
+
+
+ ``` + + + + + +## VS Code の IntelliSense サポート {#vs-code-intellisense-support} + + + +Vue は [Vue - Official VS Code plugin](https://marketplace.visualstudio.com/items?itemName=Vue.volar) により、標準で IntelliSense を提供します。ただし `.md` ファイルでも有効にするには、設定ファイルをいくつか調整する必要があります。 + +1. tsconfig/jsconfig の `include` と `vueCompilerOptions.vitePressExtensions` に `.md` パターンを追加します。 + + ::: code-group + ```json [tsconfig.json] + { + "include": [ + "docs/**/*.ts", + "docs/**/*.vue", + "docs/**/*.md", + ], + "vueCompilerOptions": { + "vitePressExtensions": [".md"], + }, + } + ``` + ::: + +2. VS Code の設定で、`vue.server.includeLanguages` に `markdown` を追加します。 + + ::: code-group + ```json [.vscode/settings.json] + { + "vue.server.includeLanguages": ["vue", "markdown"] + } + ``` + ::: diff --git a/docs/ja/guide/what-is-vitepress.md b/docs/ja/guide/what-is-vitepress.md new file mode 100644 index 00000000..8d96c80c --- /dev/null +++ b/docs/ja/guide/what-is-vitepress.md @@ -0,0 +1,57 @@ +# VitePress とは? {#what-is-vitepress} + +VitePress は、高速でコンテンツ中心の Web サイトを構築するための [静的サイトジェネレーター(SSG)](https://en.wikipedia.org/wiki/Static_site_generator) です。要するに、VitePress は [Markdown](https://en.wikipedia.org/wiki/Markdown) で書かれたソースコンテンツにテーマを適用し、どこにでも簡単にデプロイできる静的 HTML ページを生成します。 + +
+ +まずは試してみたい? [クイックスタート](./getting-started) へどうぞ。 + +
+ +## ユースケース {#use-cases} + +- **ドキュメント** + + VitePress には技術ドキュメント向けに設計されたデフォルトテーマが同梱されています。今あなたが読んでいるこのページのほか、[Vite](https://vitejs.dev/)、[Rollup](https://rollupjs.org/)、[Pinia](https://pinia.vuejs.org/)、[VueUse](https://vueuse.org/)、[Vitest](https://vitest.dev/)、[D3](https://d3js.org/)、[UnoCSS](https://unocss.dev/)、[Iconify](https://iconify.design/) など、[まだまだたくさん](https://github.com/search?q=/"vitepress":+/+language:json&type=code)のドキュメントサイトで使われています。 + + [公式の Vue.js ドキュメント](https://vuejs.org/) も VitePress をベースにしています(複数言語で共有されるカスタムテーマを使用)。 + +- **ブログ/ポートフォリオ/マーケティングサイト** + + VitePress は [フルカスタムテーマ](./custom-theme) をサポートし、標準的な Vite + Vue アプリ同様の開発体験を提供します。Vite 上に構築されているため、豊富なエコシステムから Vite プラグインを直接活用できます。さらに、[データの読み込み](./data-loading)(ローカル/リモート)や [ルートの動的生成](./routing#dynamic-routes) のための柔軟な API も提供します。ビルド時にデータが確定できる限り、ほとんど何でも構築できます。 + + 公式の [Vue.js ブログ](https://blog.vuejs.org/) は、ローカルコンテンツに基づいてインデックスページを生成するシンプルなブログです。 + +## 開発体験 {#developer-experience} + +VitePress は、Markdown コンテンツを扱う際の優れた開発体験(DX)を目指しています。 + +- **[Vite 駆動](https://vitejs.dev/)**:即時サーバー起動、編集はページリロードなしで常に瞬時(<100ms)に反映。 + +- **[ビルトインの Markdown 拡張](./markdown)**:Frontmatter、表、シンタックスハイライト…必要なものはひと通り。特にコードブロック周りの機能が充実しており、高度な技術ドキュメントに最適です。 + +- **[Vue 拡張 Markdown](./using-vue)**:各 Markdown ページは Vue の [単一ファイルコンポーネント(SFC)](https://vuejs.org/guide/scaling-up/sfc.html) としても機能します。HTML と 100% 互換な Vue テンプレートを活かし、Vue のテンプレート機能やインポートしたコンポーネントで静的コンテンツにインタラクションを埋め込めます。 + +## パフォーマンス {#performance} + +多くの従来型 SSG と異なり、VitePress で生成されたサイトは **初回訪問では静的 HTML** を返し、その後のサイト内ナビゲーションは [シングルページアプリケーション(SPA)](https://en.wikipedia.org/wiki/Single-page_application) として動作します。これはパフォーマンス面で最適なバランスだと考えています。 + +- **初期ロードが速い** + + どのページへの初回訪問でも、静的な事前レンダリング HTML が配信され、高速な読み込みと最適な SEO を実現します。続いて JavaScript バンドルが読み込まれ、ページが Vue の SPA に「ハイドレート」されます。SPA のハイドレーションは遅いという通説に反し、Vue 3 の素のパフォーマンスとコンパイラ最適化により非常に高速です。[PageSpeed Insights](https://pagespeed.web.dev/report?url=https%3A%2F%2Fvitepress.dev%2F) でも、VitePress サイトは低速回線のローエンド端末でもほぼ満点のスコアを達成できます。 + +- **読み込み後のナビゲーションが速い** + + さらに重要なのは、初回ロード**後**の体験が向上することです。サイト内の以降の移動ではフルリロードは発生せず、遷移先のコンテンツを取得して動的に更新します。VitePress はビューポート内のリンクに対してページチャンクを自動プリフェッチするため、ほとんどの場合で遷移は「即時」に感じられます。 + +- **インタラクションのペナルティなし** + + 静的 Markdown に埋め込まれた動的な Vue 部分をハイドレートできるよう、各 Markdown ページは Vue コンポーネントとして処理され JavaScript にコンパイルされます。一見非効率に思えますが、Vue コンパイラは静的部分と動的部分を賢く分離し、ハイドレーションのコストとペイロードを最小化します。初回ロードでは静的部分は自動的に JS ペイロードから除外され、ハイドレーションでもスキップされます。 + +## VuePress はどうなるの? {#what-about-vuepress} + +VitePress は VuePress 1 の精神的後継です。元の VuePress 1 は Vue 2 と webpack をベースとしていました。VitePress は内部に Vue 3 と Vite を採用し、開発体験・本番性能・完成度の高いデフォルトテーマ・より柔軟なカスタマイズ API を提供します。 + +VitePress と VuePress 1 の API の違いは主にテーマやカスタマイズ周りにあります。VuePress 1 でデフォルトテーマを使っている場合は、比較的容易に移行できます。 + +2 つの SSG を並行して維持するのは現実的ではないため、Vue チームは長期的に VitePress を推奨 SSG とする方針に集中しています。現在、VuePress 1 は非推奨となり、VuePress 2 は今後の開発・保守を VuePress コミュニティチームに委ねています。 diff --git a/docs/ja/index.md b/docs/ja/index.md new file mode 100644 index 00000000..00058c58 --- /dev/null +++ b/docs/ja/index.md @@ -0,0 +1,35 @@ +--- +layout: home + +hero: + name: VitePress + text: Vite & Vue をベースにした静的サイトジェネレーター + tagline: Markdown から美しいドキュメントを数分で + actions: + - theme: brand + text: VitePress とは? + link: ./guide/what-is-vitepress + - theme: alt + text: クイックスタート + link: ./guide/getting-started + - theme: alt + text: GitHub + link: https://github.com/vuejs/vitepress + image: + src: /vitepress-logo-large.svg + alt: VitePress + +features: + - icon: 📝 + title: コンテンツに集中 + details: Markdown だけで、美しいドキュメントサイトを簡単に作成できます。 + - icon: + title: Vite の開発体験を享受 + details: 即時サーバー起動、超高速ホットリロード、そして Vite エコシステムのプラグイン活用。 + - icon: + title: Vue でカスタマイズ + details: Markdown 内で直接 Vue 構文やコンポーネントを利用したり、Vue で独自テーマを構築できます。 + - icon: 🚀 + title: 高速サイトを公開 + details: 静的 HTML による高速初期ロードと、クライアントサイドルーティングによる快適なページ遷移。 +--- diff --git a/docs/ja/reference/cli.md b/docs/ja/reference/cli.md new file mode 100644 index 00000000..78d06b8b --- /dev/null +++ b/docs/ja/reference/cli.md @@ -0,0 +1,73 @@ +# コマンドラインインターフェイス {#command-line-interface} + +## `vitepress dev` + +指定したディレクトリをルートとして VitePress の開発サーバーを起動します。既定はカレントディレクトリです。カレントディレクトリで実行する場合、`dev` コマンドは省略できます。 + +### 使い方 {#usage} + + ```sh + # カレントディレクトリで起動(`dev` を省略) + vitepress + + # サブディレクトリで起動 + vitepress dev [root] + ``` + +### オプション {#options} + +| オプション | 説明 | +| ------------------ | -------------------------------------------------------------------- | +| `--open [path]` | 起動時にブラウザを開く(`boolean \| string`) | +| `--port ` | ポート番号を指定(`number`) | +| `--base ` | 公開時のベースパス(既定: `/`)(`string`) | +| `--cors` | CORS を有効化 | +| `--strictPort` | 指定ポートが使用中なら終了(`boolean`) | +| `--force` | 最適化時にキャッシュを無視して再バンドル(`boolean`) | + +## `vitepress build` + +本番用に VitePress サイトをビルドします。 + +### 使い方 {#usage-1} + + ```sh + vitepress build [root] + ``` + +### オプション {#options-1} + +| オプション | 説明 | +| ----------------------------- | -------------------------------------------------------------------------------------------------- | +| `--mpa`(実験的) | クライアント側ハイドレーションなしの [MPA モード](../guide/mpa-mode) でビルド(`boolean`) | +| `--base ` | 公開時のベースパス(既定: `/`)(`string`) | +| `--target ` | トランスパイルターゲット(既定: `"modules"`)(`string`) | +| `--outDir ` | 出力先ディレクトリ(**cwd** からの相対)(既定: `/.vitepress/dist`)(`string`) | +| `--assetsInlineLimit `| 静的アセットを base64 インライン化する閾値(バイト)(既定: `4096`)(`number`) | + +## `vitepress preview` + +本番ビルドをローカルでプレビューします。 + +### 使い方 {#usage-2} + + ```sh + vitepress preview [root] + ``` + +### オプション {#options-2} + +| オプション | 説明 | +| ------------------ | ----------------------------------------- | +| `--base ` | 公開時のベースパス(既定: `/`)(`string`) | +| `--port ` | ポート番号を指定(`number`) | + +## `vitepress init` + +カレントディレクトリで [セットアップウィザード](../guide/getting-started#setup-wizard) を起動します。 + +### 使い方 {#usage-3} + + ```sh + vitepress init + ``` diff --git a/docs/ja/reference/default-theme-badge.md b/docs/ja/reference/default-theme-badge.md new file mode 100644 index 00000000..034f1a2f --- /dev/null +++ b/docs/ja/reference/default-theme-badge.md @@ -0,0 +1,69 @@ +# バッジ {#badge} + +バッジを使うと、見出しにステータスを追加できます。たとえば、そのセクションの種類や対応バージョンを示すのに便利です。 + +## 使い方 {#usage} + +グローバルに利用可能な `Badge` コンポーネントを使用します。 + + ```html + ### Title + ### Title + ### Title + ### Title + ``` + +上記のコードは次のように表示されます: + +### Title +### Title +### Title +### Title + +## 子要素のカスタマイズ {#custom-children} + +`` は子要素(`children`)を受け取り、バッジ内に表示できます。 + + ```html + ### Title custom element + ``` + +### Title custom element + +## 種類ごとの色をカスタマイズ {#customize-type-color} + +CSS 変数を上書きすることで、バッジのスタイルをカスタマイズできます。以下はデフォルト値です: + + ```css + :root { + --vp-badge-info-border: transparent; + --vp-badge-info-text: var(--vp-c-text-2); + --vp-badge-info-bg: var(--vp-c-default-soft); + + --vp-badge-tip-border: transparent; + --vp-badge-tip-text: var(--vp-c-brand-1); + --vp-badge-tip-bg: var(--vp-c-brand-soft); + + --vp-badge-warning-border: transparent; + --vp-badge-warning-text: var(--vp-c-warning-1); + --vp-badge-warning-bg: var(--vp-c-warning-soft); + + --vp-badge-danger-border: transparent; + --vp-badge-danger-text: var(--vp-c-danger-1); + --vp-badge-danger-bg: var(--vp-c-danger-soft); + } + ``` + +## `` + +`` コンポーネントは次の props を受け取ります。 + + ```ts + interface Props { + // `` が渡された場合、この値は無視されます。 + text?: string + + // 既定値は `tip`。 + type?: 'info' | 'tip' | 'warning' | 'danger' + } + ``` diff --git a/docs/ja/reference/default-theme-carbon-ads.md b/docs/ja/reference/default-theme-carbon-ads.md new file mode 100644 index 00000000..222c80b3 --- /dev/null +++ b/docs/ja/reference/default-theme-carbon-ads.md @@ -0,0 +1,22 @@ +# Carbon 広告 {#carbon-ads} + +VitePress は [Carbon Ads](https://www.carbonads.net/) をネイティブにサポートしています。設定で Carbon Ads の認証情報を定義すると、ページ上に広告が表示されます。 + + ```js + export default { + themeConfig: { + carbonAds: { + code: 'your-carbon-code', + placement: 'your-carbon-placement' + } + } + } + ``` + +これらの値は、次のように Carbon の CDN スクリプトを呼び出すために使用されます。 + + ```js + `//cdn.carbonads.com/carbon.js?serve=${code}&placement=${placement}` + ``` + +Carbon Ads の設定について詳しくは、[Carbon Ads のウェブサイト](https://www.carbonads.net/)を参照してください。 diff --git a/docs/ja/reference/default-theme-config.md b/docs/ja/reference/default-theme-config.md new file mode 100644 index 00000000..bb37d13a --- /dev/null +++ b/docs/ja/reference/default-theme-config.md @@ -0,0 +1,494 @@ +# デフォルトテーマの設定 {#default-theme-config} + +テーマ設定では、テーマのカスタマイズができます。設定ファイルの `themeConfig` オプションで定義します。 + + ```ts + export default { + lang: 'en-US', + title: 'VitePress', + description: 'Vite & Vue powered static site generator.', + + // テーマ関連の設定 + themeConfig: { + logo: '/logo.svg', + nav: [...], + sidebar: { ... } + } + } + ``` + +**このページで説明するオプションは、デフォルトテーマにのみ適用されます。** テーマによって期待する設定は異なります。カスタムテーマを使用する場合、ここで定義したテーマ設定オブジェクトはテーマへ渡され、テーマ側がそれに基づいて条件付きの挙動を定義できます。 + +## i18nRouting + +- 型: `boolean` + +ロケールを `zh` のように切り替えると、URL は `/foo`(または `/en/foo/`)から `/zh/foo` に変わります。`themeConfig.i18nRouting` を `false` に設定すると、この挙動を無効化できます。 + +## logo + +- 型: `ThemeableImage` + +サイトタイトルの直前に、ナビゲーションバーに表示されるロゴ。パス文字列、またはライト/ダークモードで異なるロゴを設定するオブジェクトを受け取ります。 + + ```ts + export default { + themeConfig: { + logo: '/logo.svg' + } + } + ``` + + ```ts + type ThemeableImage = + | string + | { src: string; alt?: string } + | { light: string; dark: string; alt?: string } + ``` + +## siteTitle + +- 型: `string | false` + +ナビゲーション内の既定サイトタイトル(アプリ設定の `title`)を置き換えます。`false` の場合、ナビのタイトルを非表示にします。ロゴ自体にサイト名が含まれている場合に便利です。 + + ```ts + export default { + themeConfig: { + siteTitle: 'Hello World' + } + } + ``` + +## nav + +- 型: `NavItem` + +ナビゲーションメニューの設定。[デフォルトテーマ: ナビ](./default-theme-nav#navigation-links) を参照してください。 + + ```ts + export default { + themeConfig: { + nav: [ + { text: 'Guide', link: '/guide' }, + { + text: 'Dropdown Menu', + items: [ + { text: 'Item A', link: '/item-1' }, + { text: 'Item B', link: '/item-2' }, + { text: 'Item C', link: '/item-3' } + ] + } + ] + } + } + ``` + + ```ts + type NavItem = NavItemWithLink | NavItemWithChildren + + interface NavItemWithLink { + text: string + link: string | ((payload: PageData) => string) + activeMatch?: string + target?: string + rel?: string + noIcon?: boolean + } + + interface NavItemChildren { + text?: string + items: NavItemWithLink[] + } + + interface NavItemWithChildren { + text?: string + items: (NavItemChildren | NavItemWithLink)[] + activeMatch?: string + } + ``` + +## sidebar + +- 型: `Sidebar` + +サイドバーメニューの設定。[デフォルトテーマ: サイドバー](./default-theme-sidebar) を参照してください。 + + ```ts + export default { + themeConfig: { + sidebar: [ + { + text: 'Guide', + items: [ + { text: 'Introduction', link: '/introduction' }, + { text: 'Getting Started', link: '/getting-started' }, + ... + ] + } + ] + } + } + ``` + + ```ts + export type Sidebar = SidebarItem[] | SidebarMulti + + export interface SidebarMulti { + [path: string]: SidebarItem[] | { items: SidebarItem[]; base: string } + } + + export type SidebarItem = { + /** + * 項目のテキストラベル + */ + text?: string + + /** + * 項目のリンク + */ + link?: string + + /** + * 子項目 + */ + items?: SidebarItem[] + + /** + * 指定しない場合、グループは折りたたみ不可。 + * + * `true` なら折りたたみ可能でデフォルト折りたたみ + * + * `false` なら折りたたみ可能だがデフォルト展開 + */ + collapsed?: boolean + + /** + * 子項目のベースパス + */ + base?: string + + /** + * 前/次リンクのフッターに表示するテキストをカスタマイズ + */ + docFooterText?: string + + rel?: string + target?: string + } + ``` + +## aside + +- 型: `boolean | 'left'` +- 既定値: `true` +- ページごとに [frontmatter](./frontmatter-config#aside) で上書き可能 + +`false` でサイドコンテナの描画を無効化。\ +`true` で右側に表示。\ +`left` で左側に表示。 + +すべてのビューポートで無効にしたい場合は、代わりに `outline: false` を使用してください。 + +## outline + +- 型: `Outline | Outline['level'] | false` +- レベルはページごとに [frontmatter](./frontmatter-config#outline) で上書き可能 + +`false` でアウトラインコンテナの描画を無効化。詳細は以下を参照: + + ```ts + interface Outline { + /** + * アウトラインに表示する見出しレベル + * 単一の数値なら、そのレベルのみ表示 + * タプルなら最小レベルと最大レベル + * `'deep'` は `[2, 6]` と同じ(`

` 〜 `

` を表示) + * + * @default 2 + */ + level?: number | [number, number] | 'deep' + + /** + * アウトラインに表示するタイトル + * + * @default 'On this page' + */ + label?: string + } + ``` + +## socialLinks + +- 型: `SocialLink[]` + +ナビゲーションにアイコン付きのソーシャルリンクを表示します。 + + ```ts + export default { + themeConfig: { + socialLinks: [ + // simple-icons (https://simpleicons.org/) の任意のアイコンを指定可能 + { icon: 'github', link: 'https://github.com/vuejs/vitepress' }, + { icon: 'twitter', link: '...' }, + // SVG 文字列を渡してカスタムアイコンも可 + { + icon: { + svg: 'Dribbble' + }, + link: '...', + // アクセシビリティ向けにカスタムラベルも指定可(推奨) + ariaLabel: 'cool link' + } + ] + } + } + ``` + + ```ts + interface SocialLink { + icon: string | { svg: string } + link: string + ariaLabel?: string + } + ``` + +## footer + +- 型: `Footer` +- ページごとに [frontmatter](./frontmatter-config#footer) で上書き可能 + +フッター設定。メッセージや著作権表示を追加できますが、ページにサイドバーがある場合はデザイン上表示されません。 + + ```ts + export default { + themeConfig: { + footer: { + message: 'Released under the MIT License.', + copyright: 'Copyright © 2019-present Evan You' + } + } + } + ``` + + ```ts + export interface Footer { + message?: string + copyright?: string + } + ``` + +## editLink + +- 型: `EditLink` +- ページごとに [frontmatter](./frontmatter-config#editlink) で上書き可能 + +「このページを編集」リンクを表示します(GitHub/GitLab など)。詳細は [デフォルトテーマ: 編集リンク](./default-theme-edit-link) を参照。 + + ```ts + export default { + themeConfig: { + editLink: { + pattern: 'https://github.com/vuejs/vitepress/edit/main/docs/:path', + text: 'Edit this page on GitHub' + } + } + } + ``` + + ```ts + export interface EditLink { + pattern: string + text?: string + } + ``` + +## lastUpdated + +- 型: `LastUpdatedOptions` + +最終更新の文言と日付フォーマットをカスタマイズします。 + + ```ts + export default { + themeConfig: { + lastUpdated: { + text: 'Updated at', + formatOptions: { + dateStyle: 'full', + timeStyle: 'medium' + } + } + } + } + ``` + + ```ts + export interface LastUpdatedOptions { + /** + * @default 'Last updated' + */ + text?: string + + /** + * @default + * { dateStyle: 'short', timeStyle: 'short' } + */ + formatOptions?: Intl.DateTimeFormatOptions & { forceLocale?: boolean } + } + ``` + +## algolia + +- 型: `AlgoliaSearch` + +[Algolia DocSearch](https://docsearch.algolia.com/docs/what-is-docsearch) によるサイト内検索の設定。[デフォルトテーマ: 検索](./default-theme-search) を参照。 + + ```ts + export interface AlgoliaSearchOptions extends DocSearchProps { + locales?: Record> + } + ``` + +完全なオプションは[こちら](https://github.com/vuejs/vitepress/blob/main/types/docsearch.d.ts)。 + +## carbonAds {#carbon-ads} + +- 型: `CarbonAdsOptions` + +[Carbon Ads](https://www.carbonads.net/) を表示します。 + + ```ts + export default { + themeConfig: { + carbonAds: { + code: 'your-carbon-code', + placement: 'your-carbon-placement' + } + } + } + ``` + + ```ts + export interface CarbonAdsOptions { + code: string + placement: string + } + ``` + +詳細は [デフォルトテーマ: Carbon Ads](./default-theme-carbon-ads) を参照。 + +## docFooter + +- 型: `DocFooter` + +前/次リンクの上に表示される文言をカスタマイズします。英語以外のドキュメントで便利。前/次リンク自体をグローバルに無効化することも可能。ページごとに切り替えたい場合は [frontmatter](./default-theme-prev-next-links) を使用します。 + + ```ts + export default { + themeConfig: { + docFooter: { + prev: 'Pagina prior', + next: 'Proxima pagina' + } + } + } + ``` + + ```ts + export interface DocFooter { + prev?: string | false + next?: string | false + } + ``` + +## darkModeSwitchLabel + +- 型: `string` +- 既定値: `Appearance` + +ダークモード切替スイッチのラベル(モバイル表示のみ)をカスタマイズします。 + +## lightModeSwitchTitle + +- 型: `string` +- 既定値: `Switch to light theme` + +ホバー時に表示されるライトモード切替のタイトルをカスタマイズします。 + +## darkModeSwitchTitle + +- 型: `string` +- 既定値: `Switch to dark theme` + +ホバー時に表示されるダークモード切替のタイトルをカスタマイズします。 + +## sidebarMenuLabel + +- 型: `string` +- 既定値: `Menu` + +サイドバーメニューのラベル(モバイル表示のみ)をカスタマイズします。 + +## returnToTopLabel + +- 型: `string` +- 既定値: `Return to top` + +トップに戻るボタンのラベル(モバイル表示のみ)をカスタマイズします。 + +## langMenuLabel + +- 型: `string` +- 既定値: `Change language` + +ナビバーの言語切替ボタンの aria-label をカスタマイズします。[i18n](../guide/i18n) を使う場合に有効です。 + +## skipToContentLabel + +- 型: `string` +- 既定値: `Skip to content` + +コンテンツへスキップリンクのラベルをカスタマイズします。キーボード操作時に表示されます。 + +## externalLinkIcon + +- 型: `boolean` +- 既定値: `false` + +Markdown 内の外部リンクの横に外部リンクアイコンを表示するかどうか。 + +## `useLayout` + +レイアウト関連のデータを返します。返り値の型は次のとおりです。 + + ```ts + interface { + isHome: ComputedRef + + sidebar: Readonly> + sidebarGroups: ComputedRef + hasSidebar: ComputedRef + isSidebarEnabled: ComputedRef + + hasAside: ComputedRef + leftAside: ComputedRef + + headers: Readonly> + hasLocalNav: ComputedRef + } + ``` + +**例:** + + ```vue + + + + ``` diff --git a/docs/ja/reference/default-theme-edit-link.md b/docs/ja/reference/default-theme-edit-link.md new file mode 100644 index 00000000..03573944 --- /dev/null +++ b/docs/ja/reference/default-theme-edit-link.md @@ -0,0 +1,60 @@ +# 編集リンク {#edit-link} + +## サイトレベルの設定 {#site-level-config} + +編集リンクは、GitHub や GitLab などの Git 管理サービスでそのページを編集できるリンクを表示します。有効化するには、設定に `themeConfig.editLink` オプションを追加します。 + + ```js + export default { + themeConfig: { + editLink: { + pattern: 'https://github.com/vuejs/vitepress/edit/main/docs/:path' + } + } + } + ``` + +`pattern` オプションはリンクの URL 構造を定義します。`:path` はページパスに置き換えられます。 + +また、引数に [`PageData`](./runtime-api#usedata) を受け取り、URL 文字列を返す純粋関数を指定することもできます。 + + ```js + export default { + themeConfig: { + editLink: { + pattern: ({ filePath }) => { + if (filePath.startsWith('packages/')) { + return `https://github.com/acme/monorepo/edit/main/${filePath}` + } else { + return `https://github.com/acme/monorepo/edit/main/docs/${filePath}` + } + } + } + } + } + ``` + +この関数はブラウザでシリアライズされ実行されるため、副作用を持たず、スコープ外のものへアクセスしないでください。 + +既定では、ドキュメント下部に「Edit this page」というリンクテキストが表示されます。`text` オプションでこの文言をカスタマイズできます。 + + ```js + export default { + themeConfig: { + editLink: { + pattern: 'https://github.com/vuejs/vitepress/edit/main/docs/:path', + text: 'GitHub でこのページを編集' + } + } + } + ``` + +## フロントマターでの設定 {#frontmatter-config} + +ページごとに無効化するには、フロントマターで `editLink` オプションを使用します。 + + ```yaml + --- + editLink: false + --- + ``` diff --git a/docs/ja/reference/default-theme-footer.md b/docs/ja/reference/default-theme-footer.md new file mode 100644 index 00000000..f8226c89 --- /dev/null +++ b/docs/ja/reference/default-theme-footer.md @@ -0,0 +1,55 @@ +# フッター {#footer} + +`themeConfig.footer` を設定すると、ページ下部にグローバルフッターが表示されます。 + +```ts +export default { + themeConfig: { + footer: { + message: 'Released under the MIT License.', + copyright: 'Copyright © 2019-present Evan You' + } + } +} +``` + +```ts +export interface Footer { + // 著作権表示の直前に表示されるメッセージ + message?: string + + // 実際の著作権表記 + copyright?: string +} +``` + +上記の設定は HTML 文字列にも対応しています。たとえば、フッター内のテキストにリンクを含めたい場合は、次のように設定できます。 + +```ts +export default { + themeConfig: { + footer: { + message: 'Released under the MIT License.', + copyright: 'Copyright © 2019-present Evan You' + } + } +} +``` + +::: warning +`message` と `copyright` は `

` 要素内にレンダリングされるため、 +使用できるのはインライン要素のみです。ブロック要素を追加したい場合は、 +[`layout-bottom`](../guide/extending-default-theme#layout-slots) スロットの利用を検討してください。 +::: + +なお、[SideBar](./default-theme-sidebar) が表示されている場合はフッターは表示されません。 + +## フロントマターでの設定 {#frontmatter-config} + +ページ単位で無効化するには、フロントマターの `footer` オプションを使用します。 + +```yaml +--- +footer: false +--- +``` diff --git a/docs/ja/reference/default-theme-home-page.md b/docs/ja/reference/default-theme-home-page.md new file mode 100644 index 00000000..e472a478 --- /dev/null +++ b/docs/ja/reference/default-theme-home-page.md @@ -0,0 +1,188 @@ +# ホームページ {#home-page} + +VitePress のデフォルトテーマにはホームページ用レイアウトが用意されています([このサイトのトップページ](../) でも使われています)。[フロントマター](./frontmatter-config) に `layout: home` を指定すれば、任意のページで利用できます。 + +```yaml +--- +layout: home +--- +``` + +ただし、この指定だけでは多くのことは起きません。`hero` や `features` などの追加オプションを設定して、ホームページにあらかじめ用意された複数の「セクション」を配置できます。 + +## ヒーローセクション {#hero-section} + +ヒーローセクションはホームページの最上部に表示されます。設定例は次のとおりです。 + +```yaml +--- +layout: home + +hero: + name: VitePress + text: Vite & Vue powered static site generator. + tagline: 概要テキスト... + image: + src: /logo.png + alt: VitePress + actions: + - theme: brand + text: はじめる + link: /guide/what-is-vitepress + - theme: alt + text: GitHub で見る + link: https://github.com/vuejs/vitepress +--- +``` + +```ts +interface Hero { + // `text` の上に表示される短い文字列。ブランドカラーで表示。 + // 製品名のような短い文言を想定。 + name?: string + + // ヒーローセクションのメインテキスト。`h1` として出力。 + text: string + + // `text` の下に表示されるタグライン。 + tagline?: string + + // テキストとタグラインの横に表示する画像。 + image?: ThemeableImage + + // ヒーローに表示するアクションボタン。 + actions?: HeroAction[] +} + +type ThemeableImage = + | string + | { src: string; alt?: string } + | { light: string; dark: string; alt?: string } + +interface HeroAction { + // ボタンのカラーテーマ。既定は `brand`。 + theme?: 'brand' | 'alt' + + // ボタンのラベル。 + text: string + + // ボタンのリンク先。 + link: string + + // a 要素の target 属性。 + target?: string + + // a 要素の rel 属性。 + rel?: string +} +``` + +### name の色をカスタマイズする {#customizing-the-name-color} + +`name` にはブランドカラー(`--vp-c-brand-1`)が使われますが、`--vp-home-hero-name-color` 変数を上書きして色を変更できます。 + +```css +:root { + --vp-home-hero-name-color: blue; +} +``` + +さらに、`--vp-home-hero-name-background` を組み合わせると、`name` にグラデーションを適用できます。 + +```css +:root { + --vp-home-hero-name-color: transparent; + --vp-home-hero-name-background: -webkit-linear-gradient(120deg, #bd34fe, #41d1ff); +} +``` + +## フィーチャーセクション {#features-section} + +フィーチャーセクションでは、ヒーロー直下に任意の数の機能説明を並べられます。フロントマターに `features` オプションを指定して設定します。 + +各フィーチャーにはアイコン(絵文字または画像)を指定できます。アイコンが画像(svg, png, jpeg など)の場合は、**適切な幅・高さ** を指定してください。必要に応じて説明テキストや実サイズ、ライト/ダーク用の差し替えも指定できます。 + +```yaml +--- +layout: home + +features: + - icon: 🛠️ + title: いつでもシンプル&ミニマル + details: 概要テキスト... + - icon: + src: /cool-feature-icon.svg + title: もうひとつの便利機能 + details: 概要テキスト... + - icon: + dark: /dark-feature-icon.svg + light: /light-feature-icon.svg + title: さらに別の機能 + details: 概要テキスト... +--- +``` + +```ts +interface Feature { + // 各フィーチャーボックスに表示するアイコン。 + icon?: FeatureIcon + + // フィーチャーのタイトル。 + title: string + + // フィーチャーの詳細説明。 + details: string + + // フィーチャーをクリックしたときのリンク(内部・外部どちらも可)。 + // + // 例: `guide/reference/default-theme-home-page` や `https://example.com` + link?: string + + // フィーチャー内に表示するリンクテキスト。 + // `link` と併用するのが最適。 + // + // 例: `Learn more`, `Visit page` など + linkText?: string + + // `link` 用の rel 属性。 + // + // 例: `external` + rel?: string + + // `link` 用の target 属性。 + target?: string +} + +type FeatureIcon = + | string + | { src: string; alt?: string; width?: string; height: string } + | { + light: string + dark: string + alt?: string + width?: string + height: string + } +``` + +## Markdown コンテンツ {#markdown-content} + +`---` で区切るフロントマターの下に Markdown を書くだけで、ホームページに追加コンテンツを表示できます。 + +````md +--- +layout: home + +hero: + name: VitePress + text: Vite & Vue powered static site generator. +--- + +## はじめに + +`npx` を使えば、すぐに VitePress を始められます! + +```sh +npm init +npx vitepress init +``` diff --git a/docs/ja/reference/default-theme-last-updated.md b/docs/ja/reference/default-theme-last-updated.md new file mode 100644 index 00000000..2c85f2a8 --- /dev/null +++ b/docs/ja/reference/default-theme-last-updated.md @@ -0,0 +1,46 @@ +# 最終更新日時 {#last-updated} + +ページ右下に、コンテンツの最終更新時刻を表示できます。有効化するには、設定に `lastUpdated` オプションを追加します。 + +::: info +VitePress は各ファイルの **直近の Git コミットのタイムスタンプ** を用いて「最終更新」を表示します。これを有効にするには、対象の Markdown ファイルが Git にコミットされている必要があります。 + +内部的には、各ファイルに対して `git log -1 --pretty="%ai"` を実行してタイムスタンプを取得します。すべてのページで同じ更新時刻が表示される場合、(CI 環境でよくある)**浅いクローン(shallow clone)** により Git の履歴が取得できていない可能性があります。 + +**GitHub Actions** での修正例は次のとおりです。 + +```yaml{4} +- name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 +``` + +他の CI/CD プラットフォームでも同様の設定が用意されています。 + +もしそのようなオプションが使えない場合は、`package.json` のビルドスクリプトで手動フェッチを前置してください。 + +```json +"docs:build": "git fetch --unshallow && vitepress build docs" +``` +::: + +## サイトレベルの設定 {#site-level-config} + +```js +export default { + lastUpdated: true +} +``` + +## フロントマターでの設定 {#frontmatter-config} + +ページ単位で無効化するには、フロントマターで `lastUpdated` を指定します。 + +```yaml +--- +lastUpdated: false +--- +``` + +より詳しくは [デフォルトテーマ: 最終更新](./default-theme-config#lastupdated) を参照してください。テーマレベルで truthy な値を設定すると、サイトまたはページで明示的に無効化しない限り、この機能は有効になります。 diff --git a/docs/ja/reference/default-theme-layout.md b/docs/ja/reference/default-theme-layout.md new file mode 100644 index 00000000..e241d03e --- /dev/null +++ b/docs/ja/reference/default-theme-layout.md @@ -0,0 +1,62 @@ +# レイアウト {#layout} + +ページの [フロントマター](./frontmatter-config) の `layout` オプションでページのレイアウトを選択できます。利用可能なレイアウトは `doc`、`page`、`home` の 3 種類です。何も指定しない場合は `doc` として扱われます。 + +```yaml +--- +layout: doc +--- +``` + +## Doc レイアウト {#doc-layout} + +`doc` は既定のレイアウトで、Markdown 全体を「ドキュメント」風にスタイリングします。コンテンツ全体を `vp-doc` という CSS クラスでラップし、その配下の要素にスタイルを適用します。 + +`p` や `h2` などほぼすべての汎用要素に特別なスタイルが当たります。そのため、Markdown 内にカスタム HTML を追加した場合も、これらのスタイルの影響を受ける点に注意してください。 + +また、以下のようなドキュメント特有の機能も提供します。これらはこのレイアウトでのみ有効になります。 + +- 編集リンク(Edit Link) +- 前後リンク(Prev / Next Link) +- アウトライン(Outline) +- [Carbon 広告](./default-theme-carbon-ads) + +## Page レイアウト {#page-layout} + +`page` は「ブランクページ」として扱われます。Markdown はパースされ、[Markdown 拡張](../guide/markdown) も `doc` と同様に機能しますが、既定のスタイルは適用されません。 + +このレイアウトでは、VitePress テーマにマークアップを干渉させず、すべてを自分でスタイルできます。独自のカスタムページを作成したい場合に便利です。 + +なお、このレイアウトでも、ページがサイドバー設定に一致する場合はサイドバーが表示されます。 + +## Home レイアウト {#home-layout} + +`home` はテンプレート化された「ホームページ」を生成します。このレイアウトでは、`hero` や `features` などの追加オプションでコンテンツをさらにカスタマイズできます。詳しくは [デフォルトテーマ: ホームページ](./default-theme-home-page) を参照してください。 + +## レイアウトなし {#no-layout} + +レイアウトを一切適用したくない場合は、フロントマターで `layout: false` を指定します。これは(既定でサイドバー/ナビバー/フッターなしの)完全にカスタマイズ可能なランディングページを作りたい場合に役立ちます。 + +## カスタムレイアウト {#custom-layout} + +カスタムレイアウトを使用することもできます。 + +```md +--- +layout: foo +--- +``` + +これは、コンテキストに登録された `foo` という名前のコンポーネントを探します。たとえば、`.vitepress/theme/index.ts` でグローバル登録できます。 + +```ts +import DefaultTheme from 'vitepress/theme' +import Foo from './Foo.vue' + +export default { + extends: DefaultTheme, + enhanceApp({ app }) { + app.component('foo', Foo) + } +} +``` diff --git a/docs/ja/reference/default-theme-nav.md b/docs/ja/reference/default-theme-nav.md new file mode 100644 index 00000000..207bf9e9 --- /dev/null +++ b/docs/ja/reference/default-theme-nav.md @@ -0,0 +1,215 @@ +# ナビゲーション {#nav} + +ナビはページ上部に表示されるナビゲーションバーです。サイトタイトル、グローバルメニューリンクなどを含みます。 + +## サイトタイトルとロゴ {#site-title-and-logo} + +既定では、ナビには [`config.title`](./site-config#title) の値が表示されます。ナビに表示する文字列を変更したい場合は、`themeConfig.siteTitle` にカスタム文字列を指定します。 + +```js +export default { + themeConfig: { + siteTitle: 'My Custom Title' + } +} +``` + +サイトのロゴがある場合は、画像へのパスを渡すと表示できます。ロゴは `public` 直下に配置し、絶対パスで指定してください。 + +```js +export default { + themeConfig: { + logo: '/my-logo.svg' + } +} +``` + +ロゴを追加すると、サイトタイトルと並んで表示されます。ロゴだけを表示したい場合は、`siteTitle` を `false` に設定してタイトル文字列を非表示にできます。 + +```js +export default { + themeConfig: { + logo: '/my-logo.svg', + siteTitle: false + } +} +``` + +ダーク/ライトモードでロゴを切り替えたり、`alt` 属性を付けたい場合は、ロゴにオブジェクトを渡すこともできます。詳細は [`themeConfig.logo`](./default-theme-config#logo) を参照してください。 + +## ナビゲーションリンク {#navigation-links} + +`themeConfig.nav` オプションでナビにリンクを追加できます。 + +```js +export default { + themeConfig: { + nav: [ + { text: 'Guide', link: '/guide' }, + { text: 'Config', link: '/config' }, + { text: 'Changelog', link: 'https://github.com/...' } + ] + } +} +``` + +`text` はナビに表示される文字列、`link` はクリック時に遷移するリンクです。内部リンクは `.md` 拡張子を付けず、必ず `/` で始めるようにしてください。 + +`link` には、[`PageData`](./runtime-api#usedata) を受け取ってパスを返す関数を指定することもできます。 + +ナビリンクはドロップダウンメニューにもできます。リンクオプションに `items` を設定してください。 + +```js +export default { + themeConfig: { + nav: [ + { text: 'Guide', link: '/guide' }, + { + text: 'Dropdown Menu', + items: [ + { text: 'Item A', link: '/item-1' }, + { text: 'Item B', link: '/item-2' }, + { text: 'Item C', link: '/item-3' } + ] + } + ] + } +} +``` + +なお、ドロップダウンのタイトル(上の例の `Dropdown Menu`)には `link` は設定できません。ドロップダウンを開くボタンになるためです。 + +さらに、ドロップダウン内を「セクション」に分けることもできます(入れ子の `items` を使います)。 + +```js +export default { + themeConfig: { + nav: [ + { text: 'Guide', link: '/guide' }, + { + text: 'Dropdown Menu', + items: [ + { + // セクションのタイトル + text: 'Section A Title', + items: [ + { text: 'Section A Item A', link: '...' }, + { text: 'Section B Item B', link: '...' } + ] + } + ] + }, + { + text: 'Dropdown Menu', + items: [ + { + // タイトルは省略することも可能 + items: [ + { text: 'Section A Item A', link: '...' }, + { text: 'Section B Item B', link: '...' } + ] + } + ] + } + ] + } +} +``` + +### リンクの「アクティブ」状態をカスタマイズ {#customize-link-s-active-state} + +現在のページが特定のパス配下にあるとき、該当するナビ項目がハイライトされます。一致させるパスをカスタマイズしたい場合は、`activeMatch` に **正規表現文字列** を指定します。 + +```js +export default { + themeConfig: { + nav: [ + // ユーザーが `/config/` 配下にいるときにアクティブになる + { + text: 'Guide', + link: '/guide', + activeMatch: '/config/' + } + ] + } +} +``` + +::: warning +`activeMatch` は正規表現 **オブジェクト** ではなく、**文字列** で指定してください。ビルド時のシリアライズの都合で `RegExp` は使用できません。 +::: + +### リンクの `target` と `rel` をカスタマイズ {#customize-link-s-target-and-rel-attributes} + +既定では、リンクが外部かどうかに応じて VitePress が `target` と `rel` を自動設定します。必要であれば明示的に指定することもできます。 + +```js +export default { + themeConfig: { + nav: [ + { + text: 'Merchandise', + link: 'https://www.thegithubshop.com/', + target: '_self', + rel: 'sponsored' + } + ] + } +} +``` + +## ソーシャルリン� {#social-links} + +[`socialLinks`](./default-theme-config#sociallinks) を参照してください。 + +## カスタムコンポーネント {#custom-components} + +`component` オプションを使って、ナビゲーションバーにカスタムコンポーネントを配置できます。`component` には Vue コンポーネント名を指定し、[Theme.enhanceApp](../guide/custom-theme#theme-interface) で **グローバル登録** しておく必要があります。 + +```js [.vitepress/config.js] +export default { + themeConfig: { + nav: [ + { + text: 'My Menu', + items: [ + { + component: 'MyCustomComponent', + // コンポーネントに渡す任意の props + props: { + title: 'My Custom Component' + } + } + ] + }, + { + component: 'AnotherCustomComponent' + } + ] + } +} +``` + +次に、コンポーネントをグローバル登録します。 + +```js [.vitepress/theme/index.js] +import DefaultTheme from 'vitepress/theme' + +import MyCustomComponent from './components/MyCustomComponent.vue' +import AnotherCustomComponent from './components/AnotherCustomComponent.vue' + +/** @type {import('vitepress').Theme} */ +export default { + extends: DefaultTheme, + enhanceApp({ app }) { + app.component('MyCustomComponent', MyCustomComponent) + app.component('AnotherCustomComponent', AnotherCustomComponent) + } +} +``` + +コンポーネントはナビゲーションバー内にレンダリングされます。VitePress は次の追加 props をコンポーネントに提供します。 + +- `screenMenu`: モバイルのナビメニュー内にあるかどうかを示す任意の boolean + +e2e テスト内の例は[こちら](https://github.com/vuejs/vitepress/tree/main/__tests__/e2e/.vitepress)を参照してください。 diff --git a/docs/ja/reference/default-theme-prev-next-links.md b/docs/ja/reference/default-theme-prev-next-links.md new file mode 100644 index 00000000..7b15d699 --- /dev/null +++ b/docs/ja/reference/default-theme-prev-next-links.md @@ -0,0 +1,43 @@ +# 前/次リンク {#prev-next-links} + +ドキュメントのフッターに表示される「前のページ」「次のページ」のテキストとリンクをカスタマイズできます。サイドバーに表示しているタイトルとは別の文言を使いたい場合や、フッターを無効化したり、サイドバーに含まれていないページへリンクしたい場合に便利です。 + +## prev + +- 型: `string | false | { text?: string; link?: string }` + +- 詳細: + + 前のページへのリンクに表示するテキスト/リンクを指定します。フロントマターで設定しない場合は、サイドバー設定から自動推測されます。 + +- 例: + + - テキストだけをカスタマイズ: + + ```yaml + --- + prev: 'Get Started | Markdown' + --- + ``` + + - テキストとリンクの両方をカスタマイズ: + + ```yaml + --- + prev: + text: 'Markdown' + link: '/guide/markdown' + --- + ``` + + - 前のページを非表示にする: + + ```yaml + --- + prev: false + --- + ``` + +## next + +`prev` と同様ですが、次のページ用の設定です。 diff --git a/docs/ja/reference/default-theme-search.md b/docs/ja/reference/default-theme-search.md new file mode 100644 index 00000000..e15de4ef --- /dev/null +++ b/docs/ja/reference/default-theme-search.md @@ -0,0 +1,451 @@ +--- +outline: deep +--- + +# 検索 {#search} + +## ローカル検索 {#local-search} + +VitePress は、[minisearch](https://github.com/lucaong/minisearch/) によるブラウザ内インデックスを使った曖昧一致の全文検索をサポートします。有効化するには、`.vitepress/config.ts` で `themeConfig.search.provider` を `'local'` に設定します。 + +```ts +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + search: { + provider: 'local' + } + } +}) +``` + +表示例: + +![screenshot of the search modal](/search.png) + +代わりに [Algolia DocSearch](#algolia-search) や、次のコミュニティ製プラグインを使うこともできます。 + +- +- +- + +### i18n {#local-search-i18n} + +多言語検索を行う設定例です。 + +```ts +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + search: { + provider: 'local', + options: { + locales: { + zh: { // 既定ロケールの文言も翻訳したい場合はこれを `root` に + translations: { + button: { + buttonText: '搜索', + buttonAriaLabel: '搜索' + }, + modal: { + displayDetails: '显示详细列表', + resetButtonTitle: '重置搜索', + backButtonTitle: '关闭搜索', + noResultsText: '没有结果', + footer: { + selectText: '选择', + selectKeyAriaLabel: '输入', + navigateText: '导航', + navigateUpKeyAriaLabel: '上箭头', + navigateDownKeyAriaLabel: '下箭头', + closeText: '关闭', + closeKeyAriaLabel: 'esc' + } + } + } + } + } + } + } + } +}) +``` + +### miniSearch のオプション {#mini-search-options} + +MiniSearch の設定例です。 + +```ts +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + search: { + provider: 'local', + options: { + miniSearch: { + /** + * @type {Pick} + */ + options: { + /* ... */ + }, + /** + * @type {import('minisearch').SearchOptions} + * @default + * { fuzzy: 0.2, prefix: true, boost: { title: 4, text: 2, titles: 1 } } + */ + searchOptions: { + /* ... */ + } + } + } + } + } +}) +``` + +詳しくは [MiniSearch のドキュメント](https://lucaong.github.io/minisearch/classes/MiniSearch.MiniSearch.html) を参照してください。 + +### コンテンツレンダラーのカスタマイズ {#custom-content-renderer} + +インデックス前に Markdown コンテンツをレンダリングする関数をカスタマイズできます。 + +```ts +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + search: { + provider: 'local', + options: { + /** + * @param {string} src + * @param {import('vitepress').MarkdownEnv} env + * @param {import('markdown-it-async')} md + */ + async _render(src, env, md) { + // HTML 文字列を返す + } + } + } + } +}) +``` + +この関数はクライアント側のサイトデータからは除外されるため、Node.js の API を使用できます。 + +#### 例: 検索対象からページを除外する {#example-excluding-pages-from-search} + +フロントマターに `search: false` を追加すると、そのページを検索対象から除外できます。あるいは次のようにもできます。 + +```ts +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + search: { + provider: 'local', + options: { + async _render(src, env, md) { + const html = await md.renderAsync(src, env) + if (env.frontmatter?.search === false) return '' + if (env.relativePath.startsWith('some/path')) return '' + return html + } + } + } + } +}) +``` + +::: warning 注意 +カスタムの `_render` 関数を提供する場合、`search: false` の処理は自分で行う必要があります。また、`env` は `md.renderAsync` の呼び出し前には完全ではないため、`frontmatter` などの任意プロパティのチェックはその後に行ってください。 +::: + +#### 例: コンテンツの変換 — 見出しアンカーを追加 {#example-transforming-content-adding-anchors} + +```ts +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + search: { + provider: 'local', + options: { + async _render(src, env, md) { + const html = await md.renderAsync(src, env) + if (env.frontmatter?.title) + return await md.renderAsync(`# ${env.frontmatter.title}`) + html + return html + } + } + } + } +}) +``` + +## Algolia 検索 {#algolia-search} + +VitePress は [Algolia DocSearch](https://docsearch.algolia.com/docs/what-is-docsearch) によるサイト検索をサポートします。導入は公式のガイドを参照してください。`.vitepress/config.ts` では最低限次の設定が必要です。 + +```ts +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + search: { + provider: 'algolia', + options: { + appId: '...', + apiKey: '...', + indexName: '...' + } + } + } +}) +``` + +### i18n {#algolia-search-i18n} + +多言語検索の設定例です。 + +```ts +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + search: { + provider: 'algolia', + options: { + appId: '...', + apiKey: '...', + indexName: '...', + locales: { + zh: { + placeholder: '搜索文档', + translations: { + button: { + buttonText: '搜索文档', + buttonAriaLabel: '搜索文档' + }, + modal: { + searchBox: { + clearButtonTitle: '清除查询条件', + clearButtonAriaLabel: '清除查询条件', + closeButtonText: '关闭', + closeButtonAriaLabel: '关闭', + placeholderText: '搜索文档', + placeholderTextAskAi: '向 AI 提问:', + placeholderTextAskAiStreaming: '回答中...', + searchInputLabel: '搜索', + backToKeywordSearchButtonText: '返回关键字搜索', + backToKeywordSearchButtonAriaLabel: '返回关键字搜索' + }, + startScreen: { + recentSearchesTitle: '搜索历史', + noRecentSearchesText: '没有搜索历史', + saveRecentSearchButtonTitle: '保存至搜索历史', + removeRecentSearchButtonTitle: '从搜索历史中移除', + favoriteSearchesTitle: '收藏', + removeFavoriteSearchButtonTitle: '从收藏中移除', + recentConversationsTitle: '最近的对话', + removeRecentConversationButtonTitle: '从历史记录中删除对话' + }, + errorScreen: { + titleText: '无法获取结果', + helpText: '你可能需要检查你的网络连接' + }, + noResultsScreen: { + noResultsText: '无法找到相关结果', + suggestedQueryText: '你可以尝试查询', + reportMissingResultsText: '你认为该查询应该有结果?', + reportMissingResultsLinkText: '点击反馈' + }, + resultsScreen: { + askAiPlaceholder: '向 AI 提问: ' + }, + askAiScreen: { + disclaimerText: '答案由 AI 生成,可能不准确,请自行验证。', + relatedSourcesText: '相关来源', + thinkingText: '思考中...', + copyButtonText: '复制', + copyButtonCopiedText: '已复制!', + copyButtonTitle: '复制', + likeButtonTitle: '赞', + dislikeButtonTitle: '踩', + thanksForFeedbackText: '感谢你的反馈!', + preToolCallText: '搜索中...', + duringToolCallText: '搜索 ', + afterToolCallText: '已搜索' + }, + footer: { + selectText: '选择', + submitQuestionText: '提交问题', + selectKeyAriaLabel: 'Enter 键', + navigateText: '切换', + navigateUpKeyAriaLabel: '向上箭头', + navigateDownKeyAriaLabel: '向下箭头', + closeText: '关闭', + backToSearchText: '返回搜索', + closeKeyAriaLabel: 'Esc 键', + poweredByText: '搜索提供者' + } + } + } + } + } + } + } + } +}) +``` + +[これらのオプション](https://github.com/vuejs/vitepress/blob/main/types/docsearch.d.ts) は上書きできます。詳細は Algolia の公式ドキュメントを参照してください。 + +### Algolia Ask AI のサポート {#ask-ai} + +**Ask AI** を有効にするには、`options` 内に `askAi` オプション(またはその一部)を指定します。 + +```ts +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + search: { + provider: 'algolia', + options: { + appId: '...', + apiKey: '...', + indexName: '...', + // askAi: "YOUR-ASSISTANT-ID" + // または + askAi: { + // 少なくとも Algolia から受け取った assistantId を指定 + assistantId: 'XXXYYY', + // 任意の上書き — 省略時は上位の appId/apiKey/indexName を再利用 + // apiKey: '...', + // appId: '...', + // indexName: '...' + } + } + } + } +}) +``` + +::: warning 注意 +キーワード検索を既定にして Ask AI を使わない場合は、`askAi` を指定しないでください。 +::: + +Ask AI UI の翻訳は `options.translations.modal.askAiScreen` と `options.translations.resultsScreen` にあります。すべてのキーは[型定義](https://github.com/vuejs/vitepress/blob/main/types/docsearch.d.ts)を参照してください。 + +### クローラー設定 {#crawler-config} + +このサイトで使用している設定を元にした例です。 + +```ts +new Crawler({ + appId: '...', + apiKey: '...', + rateLimit: 8, + startUrls: ['https://vitepress.dev/'], + renderJavaScript: false, + sitemaps: [], + exclusionPatterns: [], + ignoreCanonicalTo: false, + discoveryPatterns: ['https://vitepress.dev/**'], + schedule: 'at 05:10 on Saturday', + actions: [ + { + indexName: 'vitepress', + pathsToMatch: ['https://vitepress.dev/**'], + recordExtractor: ({ $, helpers }) => { + return helpers.docsearch({ + recordProps: { + lvl1: '.content h1', + content: '.content p, .content li', + lvl0: { + selectors: 'section.has-active div h2', + defaultValue: 'Documentation' + }, + lvl2: '.content h2', + lvl3: '.content h3', + lvl4: '.content h4', + lvl5: '.content h5' + }, + indexHeadings: true + }) + } + } + ], + initialIndexSettings: { + vitepress: { + attributesForFaceting: ['type', 'lang'], + attributesToRetrieve: ['hierarchy', 'content', 'anchor', 'url'], + attributesToHighlight: ['hierarchy', 'hierarchy_camel', 'content'], + attributesToSnippet: ['content:10'], + camelCaseAttributes: ['hierarchy', 'hierarchy_radio', 'content'], + searchableAttributes: [ + 'unordered(hierarchy_radio_camel.lvl0)', + 'unordered(hierarchy_radio.lvl0)', + 'unordered(hierarchy_radio_camel.lvl1)', + 'unordered(hierarchy_radio.lvl1)', + 'unordered(hierarchy_radio_camel.lvl2)', + 'unordered(hierarchy_radio.lvl2)', + 'unordered(hierarchy_radio_camel.lvl3)', + 'unordered(hierarchy_radio.lvl3)', + 'unordered(hierarchy_radio_camel.lvl4)', + 'unordered(hierarchy_radio.lvl4)', + 'unordered(hierarchy_radio_camel.lvl5)', + 'unordered(hierarchy_radio.lvl5)', + 'unordered(hierarchy_radio_camel.lvl6)', + 'unordered(hierarchy_radio.lvl6)', + 'unordered(hierarchy_camel.lvl0)', + 'unordered(hierarchy.lvl0)', + 'unordered(hierarchy_camel.lvl1)', + 'unordered(hierarchy.lvl1)', + 'unordered(hierarchy_camel.lvl2)', + 'unordered(hierarchy.lvl2)', + 'unordered(hierarchy_camel.lvl3)', + 'unordered(hierarchy.lvl3)', + 'unordered(hierarchy_camel.lvl4)', + 'unordered(hierarchy.lvl4)', + 'unordered(hierarchy_camel.lvl5)', + 'unordered(hierarchy.lvl5)', + 'unordered(hierarchy_camel.lvl6)', + 'unordered(hierarchy.lvl6)', + 'content' + ], + distinct: true, + attributeForDistinct: 'url', + customRanking: [ + 'desc(weight.pageRank)', + 'desc(weight.level)', + 'asc(weight.position)' + ], + ranking: [ + 'words', + 'filters', + 'typo', + 'attribute', + 'proximity', + 'exact', + 'custom' + ], + highlightPreTag: '', + highlightPostTag: '', + minWordSizefor1Typo: 3, + minWordSizefor2Typos: 7, + allowTyposOnNumericTokens: false, + minProximity: 1, + ignorePlurals: true, + advancedSyntax: true, + attributeCriteriaComputedByMinProximity: true, + removeWordsIfNoResults: 'allOptional' + } + } +}) +``` diff --git a/docs/ja/reference/default-theme-sidebar.md b/docs/ja/reference/default-theme-sidebar.md new file mode 100644 index 00000000..ddd87383 --- /dev/null +++ b/docs/ja/reference/default-theme-sidebar.md @@ -0,0 +1,180 @@ +# サイドバー {#sidebar} + +サイドバーはドキュメントの主要なナビゲーションブロックです。[`themeConfig.sidebar`](./default-theme-config#sidebar) でメニューを設定できます。 + +```js +export default { + themeConfig: { + sidebar: [ + { + text: 'Guide', + items: [ + { text: 'Introduction', link: '/introduction' }, + { text: 'Getting Started', link: '/getting-started' }, + ... + ] + } + ] + } +} +``` + +## 基本 {#the-basics} + +最もシンプルな構成は、リンクの配列を 1 つ渡す方法です。第 1 階層のアイテムがサイドバーの「セクション」を表します。各セクションは `text`(セクションのタイトル)と、実際のナビゲーションリンクである `items` を持ちます。 + +```js +export default { + themeConfig: { + sidebar: [ + { + text: 'Section Title A', + items: [ + { text: 'Item A', link: '/item-a' }, + { text: 'Item B', link: '/item-b' }, + ... + ] + }, + { + text: 'Section Title B', + items: [ + { text: 'Item C', link: '/item-c' }, + { text: 'Item D', link: '/item-d' }, + ... + ] + } + ] + } +} +``` + +各 `link` は `/` で始まる実ファイルへのパスを指定します。リンクの末尾を `/` で終わらせると、対応するディレクトリの `index.md` が表示されます。 + +```js +export default { + themeConfig: { + sidebar: [ + { + text: 'Guide', + items: [ + // `/guide/index.md` を表示 + { text: 'Introduction', link: '/guide/' } + ] + } + ] + } +} +``` + +サイドバーのアイテムは、ルートから数えて最大 6 階層まで入れ子にできます。7 階層以上は無視され、表示されません。 + +```js +export default { + themeConfig: { + sidebar: [ + { + text: 'Level 1', + items: [ + { + text: 'Level 2', + items: [ + { + text: 'Level 3', + items: [ + ... + ] + } + ] + } + ] + } + ] + } +} +``` + +## 複数のサイドバー {#multiple-sidebars} + +ページのパスに応じて異なるサイドバーを表示できます。たとえば、このサイトのように「Guide」セクションと「Config」セクションでナビゲーションを分けたい場合に便利です。 + +まず、対象のセクションごとにディレクトリを分けてページを配置します。 + +``` +. +├─ guide/ +│ ├─ index.md +│ ├─ one.md +│ └─ two.md +└─ config/ + ├─ index.md + ├─ three.md + └─ four.md +``` + +次に、各セクション用のサイドバーを設定します。この場合、配列ではなくオブジェクトを渡します。 + +```js +export default { + themeConfig: { + sidebar: { + // ユーザーが `guide` ディレクトリ配下にいるときに表示 + '/guide/': [ + { + text: 'Guide', + items: [ + { text: 'Index', link: '/guide/' }, + { text: 'One', link: '/guide/one' }, + { text: 'Two', link: '/guide/two' } + ] + } + ], + + // ユーザーが `config` ディレクトリ配下にいるときに表示 + '/config/': [ + { + text: 'Config', + items: [ + { text: 'Index', link: '/config/' }, + { text: 'Three', link: '/config/three' }, + { text: 'Four', link: '/config/four' } + ] + } + ] + } + } +} +``` + +## 折りたたみ可能なサイドバーグループ {#collapsible-sidebar-groups} + +サイドバーグループに `collapsed` オプションを追加すると、各セクションの開閉トグルが表示されます。 + +```js +export default { + themeConfig: { + sidebar: [ + { + text: 'Section Title A', + collapsed: false, + items: [...] + } + ] + } +} +``` + +既定ではすべてのセクションが「開いた」状態です。初回表示時に「閉じた」状態にしたい場合は、`collapsed` を `true` に設定します。 + +```js +export default { + themeConfig: { + sidebar: [ + { + text: 'Section Title A', + collapsed: true, + items: [...] + } + ] + } +} +``` diff --git a/docs/ja/reference/default-theme-team-page.md b/docs/ja/reference/default-theme-team-page.md new file mode 100644 index 00000000..5f02d4d0 --- /dev/null +++ b/docs/ja/reference/default-theme-team-page.md @@ -0,0 +1,255 @@ + + +# チームページ {#team-page} + +チームを紹介したい場合は、Team コンポーネント群を使ってチームページを構成できます。使い方は 2 通りあり、ドキュメントページに埋め込む方法と、専用のチームページを作成する方法があります。 + +## ページ内にメンバー一覧を表示する {#show-team-members-in-a-page} + +任意のページでチームメンバーの一覧を表示するには、`vitepress/theme` からエクスポートされている `` コンポーネントを使用します。 + +```html + + +# 私たちのチーム + +私たちの素晴らしいチームを紹介します。 + + +``` + +上記のように、カード風の要素でメンバーが表示されます。下図のような見た目になります。 + + + +`` コンポーネントには `small` と `medium` の 2 種類のサイズがあります。好みによりますが、ドキュメントページ内で使う場合は `small` が馴染みやすいことが多いでしょう。各メンバーに「説明文」や「スポンサー」ボタンなど、追加のプロパティを付けることもできます。詳細は [``](#vpteammembers) を参照してください。 + +小規模なチームで専用ページまでは不要な場合や、文脈上の参考として一部のメンバーのみを紹介したい場合は、ドキュメントページへ埋め込む方法が適しています。 + +メンバーが多い場合や、より広いスペースで紹介したい場合は、[専用のチームページを作成する](#専用のチームページを作成する) ことを検討してください。 + +## 専用のチームページを作成する {#create-a-full-team-page} + +ドキュメントページにメンバーを追加する代わりに、カスタムの [ホームページ](./default-theme-home-page) と同様、専用のチームページを作成することもできます。 + +まず新しい md ファイルを作成します。ファイル名は任意ですが、ここでは `team.md` とします。このファイルでフロントマターに `layout: page` を設定し、その後 `TeamPage` コンポーネント群を使ってページを構成します。 + +```html +--- +layout: page +--- + + + + + + + + + +``` + +専用のチームページを作る際は、必ずすべてのチーム関連コンポーネントを `` でラップしてください。レイアウトや余白などが適切に適用されます。 + +`` はページタイトルのセクションを追加します。タイトルは `

` 見出しになります。`#title` と `#lead` スロットでチームについて説明を書きましょう。 + +`` はドキュメントページで使う場合と同様に、メンバー一覧を表示します。 + +### セクションを追加してメンバーを分ける {#add-sections-to-divide-team-members} + +チームページに「セクション」を追加できます。たとえば、コアメンバーとコミュニティパートナーなど、役割ごとにメンバーを分けて説明しやすくできます。 + +そのためには、先ほど作成した `team.md` に `` コンポーネントを追加します。 + +```html +--- +layout: page +--- + + + + + + + + + + + + + + +``` + +`` は `VPTeamPageTitle` と同様に `#title` と `#lead` のスロットを持ち、さらにメンバー表示用の `#members` スロットを備えます。 + +`#members` スロット内に `` を配置するのを忘れないでください。 + +## `` + +`` コンポーネントは、与えられたメンバー配列を表示します。 + +```html + +``` + +```ts +interface Props { + // 各メンバーカードのサイズ。既定は `medium`。 + size?: 'small' | 'medium' + + // 表示するメンバー一覧。 + members: TeamMember[] +} + +interface TeamMember { + // メンバーのアバター画像 + avatar: string + + // メンバー名 + name: string + + // 名前の下に表示する肩書き(例: Developer, Software Engineer など) + title?: string + + // 所属組織名 + org?: string + + // 所属組織への URL + orgLink?: string + + // メンバーの説明 + desc?: string + + // ソーシャルリンク(例: GitHub, Twitter など) + // Social Links オブジェクトを渡せます。 + // 参照: https://vitepress.dev/reference/default-theme-config.html#sociallinks + links?: SocialLink[] + + // メンバーのスポンサー用 URL + sponsor?: string + + // スポンサーボタンのテキスト。既定は 'Sponsor' + actionText?: string +} +``` + +## `` + +専用のチームページを作成する際のルートコンポーネントです。単一のスロットのみを受け取り、渡されたチーム関連コンポーネント全体に適切なスタイルを適用します。 + +## `` + +ページの「タイトル」セクションを追加します。`` の直下に置くのが最適です。`#title` と `#lead` のスロットを受け取ります。 + +```html + + + + + + +``` + +## `` + +チームページ内に「セクション」を作成します。`#title`、`#lead`、`#members` の各スロットを受け取ります。`` の中に必要な数だけ追加できます。 + +```html + + ... + + + + + + +``` diff --git a/docs/ja/reference/frontmatter-config.md b/docs/ja/reference/frontmatter-config.md new file mode 100644 index 00000000..e6b8b5ca --- /dev/null +++ b/docs/ja/reference/frontmatter-config.md @@ -0,0 +1,240 @@ +--- +outline: deep +--- + +# フロントマター設定 {#frontmatter-config} + +フロントマターはページ単位の設定を可能にします。各 Markdown ファイルで、サイト全体やテーマレベルの設定を上書きできます。フロントマターでしか定義できない項目もあります。 + +使用例: + +```md +--- +title: Docs with VitePress +editLink: true +--- +``` + +Vue の式内では、グローバル `$frontmatter` を介してフロントマターデータにアクセスできます。 + +```md +{{ $frontmatter.title }} +``` + +## title + +- 型: `string` + +ページのタイトルです。[config.title](./site-config#title) と同じ意味で、サイトレベルの設定を上書きします。 + +```yaml +--- +title: VitePress +--- +``` + +## titleTemplate + +- 型: `string | boolean` + +タイトルのサフィックスです。[config.titleTemplate](./site-config#titletemplate) と同じ意味で、サイトレベルの設定を上書きします。 + +```yaml +--- +title: VitePress +titleTemplate: Vite & Vue powered static site generator +--- +``` + +## description + +- 型: `string` + +ページの説明です。[config.description](./site-config#description) と同じ意味で、サイトレベルの設定を上書きします。 + +```yaml +--- +description: VitePress +--- +``` + +## head + +- 型: `HeadConfig[]` + +現在のページに追加で挿入する `` タグを指定します。サイトレベル設定で挿入されたタグの後に追加されます。 + +```yaml +--- +head: + - - meta + - name: description + content: hello + - - meta + - name: keywords + content: super duper SEO +--- +``` + +```ts +type HeadConfig = + | [string, Record] + | [string, Record, string] +``` + +## デフォルトテーマ専用 {#default-theme-only} + +以下のフロントマター項目は、デフォルトテーマ使用時にのみ適用されます。 + +### layout + +- 型: `doc | home | page` +- 既定値: `doc` + +ページのレイアウトを決めます。 + +- `doc` — Markdown コンテンツにドキュメント向けの既定スタイルを適用します。 +- `home` — 「ホームページ」用の特別なレイアウト。`hero` や `features` を追加指定して、ランディングページを素早く構築できます。 +- `page` — `doc` と似ていますが、コンテンツにスタイルを適用しません。完全にカスタムなページを作りたい場合に便利です。 + +```yaml +--- +layout: doc +--- +``` + +### hero + +`layout: home` のときのヒーローセクションの内容を定義します。詳しくは [デフォルトテーマ: ホームページ](./default-theme-home-page) を参照。 + +### features + +`layout: home` のときのフィーチャーセクションに表示する項目を定義します。詳しくは [デフォルトテーマ: ホームページ](./default-theme-home-page) を参照。 + +### navbar + +- 型: `boolean` +- 既定値: `true` + +[ナビゲーションバー](./default-theme-nav) を表示するかどうか。 + +```yaml +--- +navbar: false +--- +``` + +### sidebar + +- 型: `boolean` +- 既定値: `true` + +[サイドバー](./default-theme-sidebar) を表示するかどうか。 + +```yaml +--- +sidebar: false +--- +``` + +### aside + +- 型: `boolean | 'left'` +- 既定値: `true` + +`doc` レイアウトでの aside コンポーネントの位置を定義します。 + +この値を `false` にすると aside コンテナを表示しません。\ +`true` にすると右側に表示します。\ +`'left'` にすると左側に表示します。 + +```yaml +--- +aside: false +--- +``` + +### outline + +- 型: `number | [number, number] | 'deep' | false` +- 既定値: `2` + +ページのアウトラインに表示する見出しレベルです。[config.themeConfig.outline.level](./default-theme-config#outline) と同じ意味で、サイトレベルの設定を上書きします。 + +```yaml +--- +outline: [2, 4] +--- +``` + +### lastUpdated + +- 型: `boolean | Date` +- 既定値: `true` + +現在のページのフッターに[最終更新](./default-theme-last-updated)を表示するかどうか。日時を指定した場合は、その日時が Git の最終更新時刻の代わりに表示されます。 + +```yaml +--- +lastUpdated: false +--- +``` + +### editLink + +- 型: `boolean` +- 既定値: `true` + +現在のページのフッターに[編集リンク](./default-theme-edit-link)を表示するかどうか。 + +```yaml +--- +editLink: false +--- +``` + +### footer + +- 型: `boolean` +- 既定値: `true` + +[フッター](./default-theme-footer) を表示するかどうか。 + +```yaml +--- +footer: false +--- +``` + +### pageClass + +- 型: `string` + +特定のページに追加のクラス名を付与します。 + +```yaml +--- +pageClass: custom-page-class +--- +``` + +その後、`.vitepress/theme/custom.css` でこのページ専用のスタイルを記述できます。 + +```css +.custom-page-class { + /* ページ固有のスタイル */ +} +``` + +### isHome + +- 型: `boolean` + +デフォルトテーマは通常、`frontmatter.layout === 'home'` のチェックに基づいてホームページかどうかを判断します。\ +カスタムレイアウトでホームページ用の要素を強制的に表示したい場合に便利です。 + +```yaml +--- +isHome: true +--- +``` diff --git a/docs/ja/reference/runtime-api.md b/docs/ja/reference/runtime-api.md new file mode 100644 index 00000000..b73b8503 --- /dev/null +++ b/docs/ja/reference/runtime-api.md @@ -0,0 +1,173 @@ +# ランタイム API {#runtime-api} + +VitePress には、アプリのデータへアクセスするための組み込み API がいくつか用意されています。さらに、グローバルに使用できる組み込みコンポーネントも提供されています。 + +ヘルパーメソッドは `vitepress` からグローバルインポートでき、主にカスタムテーマの Vue コンポーネントで使われます。Markdown ファイルは Vue の [Single File Component](https://vuejs.org/guide/scaling-up/sfc.html) にコンパイルされるため、`.md` ファイル内でも使用できます。 + +`use*` で始まるメソッドは [Vue 3 Composition API](https://vuejs.org/guide/introduction.html#composition-api) の関数(Composable)で、`setup()` または ` + + +``` + +## `useRoute` + +現在のルートオブジェクトを返します。型は次のとおりです。 + +```ts +interface Route { + path: string + data: PageData + component: Component | null +} +``` + +## `useRouter` + +VitePress のルーターインスタンスを返し、プログラムで別ページへ遷移できます。 + +```ts +interface Router { + /** + * 現在のルート + */ + route: Route + /** + * 新しい URL へ遷移 + */ + go: (to?: string) => Promise + /** + * ルートが変わる前に呼ばれる。`false` を返すと遷移をキャンセル + */ + onBeforeRouteChange?: (to: string) => Awaitable + /** + * ページコンポーネントが読み込まれる前(履歴が更新された後)に呼ばれる。 + * `false` を返すと遷移をキャンセル + */ + onBeforePageLoad?: (to: string) => Awaitable + /** + * ページコンポーネントが読み込まれた後(更新前)に呼ばれる + */ + onAfterPageLoad?: (to: string) => Awaitable + /** + * ルートが変わった後に呼ばれる + */ + onAfterRouteChange?: (to: string) => Awaitable +} +``` + +## `withBase` + +- **型**: `(path: string) => string` + +設定された [`base`](./site-config#base) を指定の URL パスに付与します。[Base URL](../guide/asset-handling#base-url) も参照。 + +## `` + +レンダリング済みの Markdown コンテンツを表示します。[独自テーマの作成時](../guide/custom-theme) に便利です。 + +```vue + +``` + +## `` + +スロット内容をクライアント側でのみレンダリングします。 + +VitePress アプリは静的ビルド時に Node.js 上でサーバーレンダリングされるため、Vue の使用はユニバーサルコードの要件に従う必要があります。要するに、ブラウザ/DOM API へのアクセスは beforeMount / mounted フック内に限定してください。 + +SSR 非対応(例: カスタムディレクティブを含む)なコンポーネントを使用・デモする場合は、`ClientOnly` でラップできます。 + +```vue-html + + + +``` + +- 関連: [SSR 互換性](../guide/ssr-compat) + +## `$frontmatter` + +Vue の式内で現在ページの [フロントマター](../guide/frontmatter) に直接アクセスします。 + +```md +--- +title: Hello +--- + +# {{ $frontmatter.title }} +``` + +## `$params` + +Vue の式内で現在ページの [動的ルートのパラメータ](../guide/routing#dynamic-routes) に直接アクセスします。 + +```md +- package name: {{ $params.pkg }} +- version: {{ $params.version }} +``` diff --git a/docs/ja/reference/site-config.md b/docs/ja/reference/site-config.md new file mode 100644 index 00000000..acea9ca7 --- /dev/null +++ b/docs/ja/reference/site-config.md @@ -0,0 +1,722 @@ +--- +outline: deep +--- + +# サイト設定 {#site-config} + +サイト設定では、サイト全体のグローバル設定を定義します。アプリ設定オプションは、使用するテーマに関係なく、すべての VitePress サイトに適用されます。たとえば、ベースディレクトリやサイトのタイトルなどです。 + +## 概要 {#overview} + +### 設定ファイルの解決 {#config-resolution} + +設定ファイルは常に `/.vitepress/config.[ext]` から解決されます。`` は VitePress の[プロジェクトルート](../guide/routing#root-and-source-directory)で、`[ext]` にはサポートされる拡張子が入ります。TypeScript はそのまま使えます。サポートされる拡張子は `.js`、`.ts`、`.mjs`、`.mts` です。 + +設定ファイルでは ES Modules 構文の使用を推奨します。設定オブジェクトをデフォルトエクスポートしてください。 + +```ts +export default { + // アプリレベルの設定 + lang: 'en-US', + title: 'VitePress', + description: 'Vite & Vue powered static site generator.', + ... +} +``` + +::: details 動的(非同期)設定 + +設定を動的に生成する必要がある場合は、関数をデフォルトエクスポートすることもできます。例: + +```ts +import { defineConfig } from 'vitepress' + +export default async () => { + const posts = await (await fetch('https://my-cms.com/blog-posts')).json() + + return defineConfig({ + // アプリレベル設定 + lang: 'en-US', + title: 'VitePress', + description: 'Vite & Vue powered static site generator.', + + // テーマレベル設定 + themeConfig: { + sidebar: [ + ...posts.map((post) => ({ + text: post.name, + link: `/posts/${post.name}` + })) + ] + } + }) +} +``` + +トップレベル `await` も使用できます。例: + +```ts +import { defineConfig } from 'vitepress' + +const posts = await (await fetch('https://my-cms.com/blog-posts')).json() + +export default defineConfig({ + // アプリレベル設定 + lang: 'en-US', + title: 'VitePress', + description: 'Vite & Vue powered static site generator.', + + // テーマレベル設定 + themeConfig: { + sidebar: [ + ...posts.map((post) => ({ + text: post.name, + link: `/posts/${post.name}` + })) + ] + } +}) +``` + +::: + +### 設定のインテリセンス {#config-intellisense} + +`defineConfig` ヘルパーを使うと、TypeScript による補完が効きます。対応 IDE であれば、JavaScript と TypeScript のどちらでも動作します。 + +```js +import { defineConfig } from 'vitepress' + +export default defineConfig({ + // ... +}) +``` + +### 型付きのテーマ設定 {#typed-theme-config} + +デフォルトでは、`defineConfig` はデフォルトテーマのテーマ設定型を想定します。 + +```ts +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + // 型は `DefaultTheme.Config` + } +}) +``` + +カスタムテーマを使用しており、そのテーマ設定に型チェックを効かせたい場合は、代わりに `defineConfigWithTheme` を使い、ジェネリクスでカスタムテーマの設定型を渡してください。 + +```ts +import { defineConfigWithTheme } from 'vitepress' +import type { ThemeConfig } from 'your-theme' + +export default defineConfigWithTheme({ + themeConfig: { + // 型は `ThemeConfig` + } +}) +``` + +### Vite・Vue・Markdown の設定 {#vite-vue-markdown-config} + +- **Vite** + + Vite の設定は VitePress 設定の [vite](#vite) オプションで行えます。別途 Vite の設定ファイルを作る必要はありません。 + +- **Vue** + + VitePress には公式の Vue プラグイン([@vitejs/plugin-vue](https://github.com/vitejs/vite-plugin-vue))が同梱されています。オプションは VitePress 設定の [vue](#vue) から指定できます。 + +- **Markdown** + + 既定の [Markdown-It](https://github.com/markdown-it/markdown-it) インスタンスは、VitePress 設定の [markdown](#markdown) オプションでカスタマイズできます。 + +## サイトメタデータ {#site-metadata} + +### title + +- 型: `string` +- 既定値: `VitePress` +- ページ単位での上書き: [frontmatter](./frontmatter-config#title) + +サイトのタイトル。デフォルトテーマではナビバーに表示されます。 + +[`titleTemplate`](#titletemplate) を定義していない場合、個々のページタイトルの既定のサフィックスとしても使われます。各ページの最終タイトルは、そのページの最初の `

` 見出しのテキストに、グローバルの `title` をサフィックスとして結合したものになります。次の設定とページ内容の例: + +```ts +export default { + title: 'My Awesome Site' +} +``` + +```md +# Hello +``` + +このページのタイトルは `Hello | My Awesome Site` になります。 + +### titleTemplate + +- 型: `string | boolean` +- ページ単位での上書き: [frontmatter](./frontmatter-config#titletemplate) + +各ページタイトルのサフィックス、またはタイトル全体のカスタマイズができます。例: + +```ts +export default { + title: 'My Awesome Site', + titleTemplate: 'Custom Suffix' +} +``` + +```md +# Hello +``` + +このページのタイトルは `Hello | Custom Suffix` になります。 + +タイトルの描画方法を完全にカスタマイズするには、`titleTemplate` 内で `:title` シンボルを使います。 + +```ts +export default { + titleTemplate: ':title - Custom Suffix' +} +``` + +ここで `:title` はページ先頭の `

` から推論されたテキストに置き換えられます。先ほどの例では `Hello - Custom Suffix` になります。 + +`false` を設定するとタイトルのサフィックスを無効にできます。 + +### description + +- 型: `string` +- 既定値: `A VitePress site` +- ページ単位での上書き: [frontmatter](./frontmatter-config#description) + +サイトの説明。ページの HTML に `` タグとして出力されます。 + +```ts +export default { + description: 'A VitePress site' +} +``` + +### head + +- 型: `HeadConfig[]` +- 既定値: `[]` +- ページ単位での追加: [frontmatter](./frontmatter-config#head) + +ページ HTML の `` に追加で出力する要素。ユーザーが追加したタグは、VitePress のタグの後、`` の直前にレンダリングされます。 + +```ts +type HeadConfig = + | [string, Record] + | [string, Record, string] +``` + +#### 例: favicon を追加 {#example-adding-a-favicon} + +```ts +export default { + head: [['link', { rel: 'icon', href: '/favicon.ico' }]] +} // favicon.ico は public に配置。base を設定している場合は /base/favicon.ico を利用 + +/* 出力結果: + +*/ +``` + +#### 例: Google Fonts を追加 {#example-adding-google-fonts} + +```ts +export default { + head: [ + [ + 'link', + { rel: 'preconnect', href: 'https://fonts.googleapis.com' } + ], + [ + 'link', + { rel: 'preconnect', href: 'https://fonts.gstatic.com', crossorigin: '' } + ], + [ + 'link', + { href: 'https://fonts.googleapis.com/css2?family=Roboto&display=swap', rel: 'stylesheet' } + ] + ] +} + +/* 出力結果: + + + +*/ +``` + +#### 例: Service Worker を登録 {#example-registering-a-service-worker} + +```ts +export default { + head: [ + [ + 'script', + { id: 'register-sw' }, + `;(() => { + if ('serviceWorker' in navigator) { + navigator.serviceWorker.register('/sw.js') + } + })()` + ] + ] +} + +/* 出力結果: + +*/ +``` + +#### 例: Google Analytics を使用 {#example-using-google-analytics} + +```ts +export default { + head: [ + [ + 'script', + { async: '', src: 'https://www.googletagmanager.com/gtag/js?id=TAG_ID' } + ], + [ + 'script', + {}, + `window.dataLayer = window.dataLayer || []; + function gtag(){dataLayer.push(arguments);} + gtag('js', new Date()); + gtag('config', 'TAG_ID');` + ] + ] +} + +/* 出力結果: + + +*/ +``` + +### lang + +- 型: `string` +- 既定値: `en-US` + +サイトの言語属性。ページ HTML の `` として出力されます。 + +```ts +export default { + lang: 'en-US' +} +``` + +### base + +- 型: `string` +- 既定値: `/` + +サイトをデプロイするベース URL。GitHub Pages などサブパス配下にデプロイする場合に設定が必要です。たとえば `https://foo.github.io/bar/` にデプロイする場合、`base` は `'/bar/'` にします。先頭と末尾は必ずスラッシュにしてください。 + +`/` で始まる他のオプション内の URL には、この `base` が自動的に付与されます。1 回設定すれば十分です。 + +```ts +export default { + base: '/base/' +} +``` + +## ルーティング {#routing} + +### cleanUrls + +- 型: `boolean` +- 既定値: `false` + +`true` にすると、URL の末尾の `.html` を削除します。あわせて [クリーン URL の生成](../guide/routing#generating-clean-url) も参照してください。 + +::: warning サーバ設定が必要 +ホスティング環境によっては追加の設定が必要です。`/foo` へのアクセス時に **リダイレクトなしで** `/foo.html` を返せるサーバ設定が必要です。 +::: + +### rewrites + +- 型: `Record` + +ディレクトリと URL のカスタム対応を定義します。詳しくは [ルーティング: ルートのリライト](../guide/routing#route-rewrites) を参照。 + +```ts +export default { + rewrites: { + 'source/:page': 'destination/:page' + } +} +``` + +## ビルド {#build} + +### srcDir + +- 型: `string` +- 既定値: `.` + +Markdown ページを置くディレクトリ(プロジェクトルートからの相対パス)。[ルートとソースディレクトリ](../guide/routing#root-and-source-directory) も参照。 + +```ts +export default { + srcDir: './src' +} +``` + +### srcExclude + +- 型: `string[]` +- 既定値: `undefined` + +ソースとして除外したい Markdown ファイルにマッチする [glob パターン](https://github.com/mrmlnc/fast-glob#pattern-syntax)。 + +```ts +export default { + srcExclude: ['**/README.md', '**/TODO.md'] +} +``` + +### outDir + +- 型: `string` +- 既定値: `./.vitepress/dist` + +ビルド出力先([プロジェクトルート](../guide/routing#root-and-source-directory) からの相対パス)。 + +```ts +export default { + outDir: '../public' +} +``` + +### assetsDir + +- 型: `string` +- 既定値: `assets` + +生成されるアセットを配置するサブディレクトリ名。パスは [`outDir`](#outdir) の内部で、相対解決されます。 + +```ts +export default { + assetsDir: 'static' +} +``` + +### cacheDir + +- 型: `string` +- 既定値: `./.vitepress/cache` + +キャッシュファイル用ディレクトリ([プロジェクトルート](../guide/routing#root-and-source-directory) からの相対パス)。参考: [cacheDir](https://vitejs.dev/config/shared-options.html#cachedir) + +```ts +export default { + cacheDir: './.vitepress/.vite' +} +``` + +### ignoreDeadLinks + +- 型: `boolean | 'localhostLinks' | (string | RegExp | ((link: string, source: string) => boolean))[]` +- 既定値: `false` + +`true` にすると、デッドリンクがあってもビルド失敗にしません。 + +`'localhostLinks'` にすると、`localhost` へのリンクはチェック対象外にしつつ、その他のデッドリンクではビルドを失敗させます。 + +```ts +export default { + ignoreDeadLinks: true +} +``` + +正確な URL 文字列、正規表現、カスタムフィルタ関数の配列として指定することもできます。 + +```ts +export default { + ignoreDeadLinks: [ + // 正確に "/playground" を無視 + '/playground', + // すべての localhost リンクを無視 + /^https?:\/\/localhost/, + // パスに "/repl/" を含むリンクを無視 + /\/repl\//, + // カスタム関数: "ignore" を含むリンクを無視 + (url) => { + return url.toLowerCase().includes('ignore') + } + ] +} +``` + +### metaChunk + +- 型: `boolean` +- 既定値: `false` + +`true` にすると、各ページのメタデータを初期 HTML にインラインせず、別の JavaScript チャンクに抽出します。これにより各ページの HTML ペイロードが小さくなり、メタデータをキャッシュ可能にすることで、多数のページがあるサイトでサーバ帯域を削減できます。 + +### mpa + +- 型: `boolean` +- 既定値: `false` + +`true` にすると、本番アプリは [MPA モード](../guide/mpa-mode) でビルドされます。MPA モードは既定でクライアント JavaScript を 0kb で配信する代わりに、クライアントサイドのナビゲーションを無効にし、相互作用には明示的な opt-in が必要です。 + +## テーマ関連 {#theming} + +### appearance + +- 型: `boolean | 'dark' | 'force-dark' | 'force-auto' | import('@vueuse/core').UseDarkOptions` +- 既定値: `true` + +ダークモードを有効にするか(`` に `.dark` クラスを付与)。 + +- `true` の場合、ユーザーの環境設定に従います。 +- `dark` の場合、ユーザーが切り替えない限りダークを既定にします。 +- `false` の場合、ユーザーはテーマを切り替えできません。 +- `'force-dark'` の場合、常にダークで固定(切替不可)。 +- `'force-auto'` の場合、常にユーザーの環境設定に従い(切替不可)。 + +このオプションは、ローカルストレージの `vitepress-theme-appearance` から設定を復元するインラインスクリプトを挿入します。これにより、ページ描画前に `.dark` クラスを適用してフリッカを防ぎます。 + +`appearance.initialValue` は `'dark' | undefined` のみサポート。Ref や getter は使えません。 + +### lastUpdated + +- 型: `boolean` +- 既定値: `false` + +Git を使って各ページの最終更新時刻を取得します。タイムスタンプは各ページのデータに含まれ、[`useData`](./runtime-api#usedata) から参照できます。 + +デフォルトテーマ使用時にこのオプションを有効にすると、各ページの最終更新時刻が表示されます。テキストは [`themeConfig.lastUpdatedText`](./default-theme-config#lastupdatedtext) でカスタマイズ可能です。 + +## カスタマイズ {#customization} + +### markdown + +- 型: `MarkdownOption` + +Markdown パーサの設定。VitePress はパーサに [Markdown-it](https://github.com/markdown-it/markdown-it)、構文ハイライトに [Shiki](https://github.com/shikijs/shiki) を使用しています。必要に応じて Markdown 関連の各種オプションを指定できます。 + +```js +export default { + markdown: {...} +} +``` + +利用可能なオプションは [型定義と JSDoc](https://github.com/vuejs/vitepress/blob/main/src/node/markdown/markdown.ts) を参照してください。 + +### vite + +- 型: `import('vite').UserConfig` + +内部の Vite 開発サーバ/バンドラへ生の [Vite Config](https://vitejs.dev/config/) を渡します。 + +```js +export default { + vite: { + // Vite の設定 + } +} +``` + +### vue + +- 型: `import('@vitejs/plugin-vue').Options` + +内部の `@vitejs/plugin-vue` インスタンスへオプションをそのまま渡します。 + +```js +export default { + vue: { + // @vitejs/plugin-vue のオプション + } +} +``` + +## ビルドフック {#build-hooks} + +VitePress のビルドフックを使うと、サイトに機能や振る舞いを追加できます。 + +- サイトマップ +- 検索インデックス +- PWA +- Teleport + +### buildEnd + +- 型: `(siteConfig: SiteConfig) => Awaitable` + +`buildEnd` はビルド CLI フックです。ビルド(SSG)が完了した後、VitePress CLI プロセスが終了する前に実行されます。 + +```ts +export default { + async buildEnd(siteConfig) { + // ... + } +} +``` + +### postRender + +- 型: `(context: SSGContext) => Awaitable` + +`postRender` は SSG のレンダリング完了時に呼ばれるビルドフックです。SSG 中の teleport コンテンツの処理に利用できます。 + +```ts +export default { + async postRender(context) { + // ... + } +} +``` + +```ts +interface SSGContext { + content: string + teleports?: Record + [key: string]: any +} +``` + +### transformHead + +- 型: `(context: TransformContext) => Awaitable` + +`transformHead` は、各ページを生成する前に head を変換するためのビルドフックです。設定ファイルでは静的に追加できない head 要素を追加できます。追加分のみ返せば、既存のものと自動でマージされます。 + +::: warning +`context` 内の値は変更しないでください。 +::: + +```ts +export default { + async transformHead(context) { + // ... + } +} +``` + +```ts +interface TransformContext { + page: string // 例: index.md(srcDir からの相対) + assets: string[] // 解決済みの公開 URL(非 js/css アセット) + siteConfig: SiteConfig + siteData: SiteData + pageData: PageData + title: string + description: string + head: HeadConfig[] + content: string +} +``` + +このフックは静的サイト生成時のみ呼ばれ、開発中には呼ばれません。開発中に動的な head 要素を追加したい場合は、代わりに [`transformPageData`](#transformpagedata) を使用できます。 + +```ts +export default { + transformPageData(pageData) { + pageData.frontmatter.head ??= [] + pageData.frontmatter.head.push([ + 'meta', + { + name: 'og:title', + content: + pageData.frontmatter.layout === 'home' + ? `VitePress` + : `${pageData.title} | VitePress` + } + ]) + } +} +``` + +#### 例: 正規 URL の `` を追加 {#example-adding-a-canonical-url-link} + +```ts +export default { + transformPageData(pageData) { + const canonicalUrl = `https://example.com/${pageData.relativePath}` + .replace(/index\.md$/, '') + .replace(/\.md$/, '.html') + + pageData.frontmatter.head ??= [] + pageData.frontmatter.head.push([ + 'link', + { rel: 'canonical', href: canonicalUrl } + ]) + } +} +``` + +### transformHtml + +- 型: `(code: string, id: string, context: TransformContext) => Awaitable` + +`transformHtml` は、各ページの内容をディスクへ保存する前に変換するためのビルドフックです。 + +::: warning +`context` 内の値は変更しないでください。また、HTML を変更すると実行時のハイドレーション問題を引き起こす可能性があります。 +::: + +```ts +export default { + async transformHtml(code, id, context) { + // ... + } +} +``` + +### transformPageData + +- 型: `(pageData: PageData, context: TransformPageContext) => Awaitable | { [key: string]: any } | void>` + +`transformPageData` は各ページの `pageData` を変換するためのフックです。`pageData` を直接変更するか、変更値を返してマージさせることができます。 + +::: warning +`context` 内の値は変更しないでください。ネットワークリクエストや重い計算(画像生成など)を行うと開発サーバのパフォーマンスに影響します。`process.env.NODE_ENV === 'production'` を用いた条件分岐を検討してください。 +::: + +```ts +export default { + async transformPageData(pageData, { siteConfig }) { + pageData.contributors = await getPageContributors(pageData.relativePath) + } + + // あるいはマージ用の値を返す + async transformPageData(pageData, { siteConfig }) { + return { + contributors: await getPageContributors(pageData.relativePath) + } + } +} +``` + +```ts +interface TransformPageContext { + siteConfig: SiteConfig +} +``` diff --git a/docs/.vitepress/config/ko.ts b/docs/ko/config.ts similarity index 69% rename from docs/.vitepress/config/ko.ts rename to docs/ko/config.ts index faebabf4..b2fbecf3 100644 --- a/docs/.vitepress/config/ko.ts +++ b/docs/ko/config.ts @@ -1,16 +1,17 @@ import { createRequire } from 'module' -import { defineConfig, type DefaultTheme } from 'vitepress' +import { defineAdditionalConfig, type DefaultTheme } from 'vitepress' const require = createRequire(import.meta.url) const pkg = require('vitepress/package.json') -export const ko = defineConfig({ - lang: 'ko-KR', +export default defineAdditionalConfig({ description: 'Vite 및 Vue 기반 정적 사이트 생성기.', themeConfig: { nav: nav(), + search: { options: searchOptions() }, + sidebar: { '/ko/guide/': { base: '/ko/guide/', items: sidebarGuide() }, '/ko/reference/': { base: '/ko/reference/', items: sidebarReference() } @@ -39,6 +40,14 @@ export const ko = defineConfig({ text: '업데이트 날짜' }, + notFound: { + title: '페이지를 찾을 수 없습니다', + quote: + '방향을 바꾸지 않고 계속 찾다 보면 결국 당신이 가고 있는 곳에 도달할 수도 있습니다.', + linkLabel: '홈으로 가기', + linkText: '집으로 데려가줘' + }, + langMenuLabel: '언어 변경', returnToTopLabel: '맨 위로 돌아가기', sidebarMenuLabel: '사이드바 메뉴', @@ -64,6 +73,10 @@ function nav(): DefaultTheme.NavItem[] { { text: pkg.version, items: [ + { + text: '1.6.4', + link: 'https://vuejs.github.io/vitepress/v1/ko/' + }, { text: '변경 로그', link: 'https://github.com/vuejs/vitepress/blob/main/CHANGELOG.md' @@ -208,8 +221,8 @@ function sidebarReference(): DefaultTheme.SidebarItem[] { ] } -export const search: DefaultTheme.AlgoliaSearchOptions['locales'] = { - ko: { +function searchOptions(): Partial { + return { placeholder: '문서 검색', translations: { button: { @@ -218,10 +231,16 @@ export const search: DefaultTheme.AlgoliaSearchOptions['locales'] = { }, modal: { searchBox: { - resetButtonTitle: '검색 지우기', - resetButtonAriaLabel: '검색 지우기', - cancelButtonText: '취소', - cancelButtonAriaLabel: '취소' + clearButtonTitle: '검색 지우기', + clearButtonAriaLabel: '검색 지우기', + closeButtonText: '닫기', + closeButtonAriaLabel: '닫기', + placeholderText: '문서 검색', + placeholderTextAskAi: 'AI에게 물어보기: ', + placeholderTextAskAiStreaming: '답변 작성 중...', + searchInputLabel: '검색', + backToKeywordSearchButtonText: '키워드 검색으로 돌아가기', + backToKeywordSearchButtonAriaLabel: '키워드 검색으로 돌아가기' }, startScreen: { recentSearchesTitle: '검색 기록', @@ -229,23 +248,50 @@ export const search: DefaultTheme.AlgoliaSearchOptions['locales'] = { saveRecentSearchButtonTitle: '검색 기록에 저장', removeRecentSearchButtonTitle: '검색 기록에서 삭제', favoriteSearchesTitle: '즐겨찾기', - removeFavoriteSearchButtonTitle: '즐겨찾기에서 삭제' + removeFavoriteSearchButtonTitle: '즐겨찾기에서 삭제', + recentConversationsTitle: '최근 대화', + removeRecentConversationButtonTitle: '대화를 기록에서 삭제' }, errorScreen: { titleText: '결과를 가져올 수 없습니다', helpText: '네트워크 연결을 확인하세요' }, + noResultsScreen: { + noResultsText: '결과를 찾을 수 없습니다', + suggestedQueryText: '다른 검색어를 시도해 보세요', + reportMissingResultsText: '결과가 있어야 한다고 생각하나요?', + reportMissingResultsLinkText: '피드백 보내기' + }, + resultsScreen: { + askAiPlaceholder: 'AI에게 물어보기: ' + }, + askAiScreen: { + disclaimerText: + 'AI가 생성한 답변으로 오류가 있을 수 있습니다. 반드시 확인하세요.', + relatedSourcesText: '관련 소스', + thinkingText: '생각 중...', + copyButtonText: '복사', + copyButtonCopiedText: '복사됨!', + copyButtonTitle: '복사', + likeButtonTitle: '좋아요', + dislikeButtonTitle: '싫어요', + thanksForFeedbackText: '피드백 감사합니다!', + preToolCallText: '검색 중...', + duringToolCallText: '검색 중 ', + afterToolCallText: '검색 완료', + aggregatedToolCallText: '검색 완료' + }, footer: { selectText: '선택', + submitQuestionText: '질문 보내기', + selectKeyAriaLabel: 'Enter 키', navigateText: '탐색', + navigateUpKeyAriaLabel: '위쪽 화살표', + navigateDownKeyAriaLabel: '아래쪽 화살표', closeText: '닫기', - searchByText: '검색 기준' - }, - noResultsScreen: { - noResultsText: '결과를 찾을 수 없습니다', - suggestedQueryText: '새로운 검색을 시도할 수 있습니다', - reportMissingResultsText: '해당 검색어에 대한 결과가 있어야 합니까?', - reportMissingResultsLinkText: '피드백 보내기 클릭' + backToSearchText: '검색으로 돌아가기', + closeKeyAriaLabel: 'Esc 키', + poweredByText: '제공: ' } } } diff --git a/docs/ko/guide/deploy.md b/docs/ko/guide/deploy.md index 797015da..7a57a8ad 100644 --- a/docs/ko/guide/deploy.md +++ b/docs/ko/guide/deploy.md @@ -162,7 +162,7 @@ HTML 코드에 대해 _Auto Minify_ 옵션을 활성화하지 마세요. 이는 - name: Setup Node uses: actions/setup-node@v4 with: - node-version: 20 + node-version: 22 cache: npm # 또는 pnpm / yarn - name: Setup Pages uses: actions/configure-pages@v4 diff --git a/docs/ko/guide/extending-default-theme.md b/docs/ko/guide/extending-default-theme.md index 6e64646f..b8b795e6 100644 --- a/docs/ko/guide/extending-default-theme.md +++ b/docs/ko/guide/extending-default-theme.md @@ -70,7 +70,7 @@ export default DefaultTheme export default { transformHead({ assets }) { // 폰트를 매칭하기 위해 정규식을 적절히 조정하세요 - const myFontFile = assets.find(file => /font-name\.\w+\.woff2/) + const myFontFile = assets.find(file => /font-name\.[\w-]+\.woff2/.test(file)) if (myFontFile) { return [ [ @@ -252,6 +252,7 @@ provide('toggle-appearance', async ({ clientX: x, clientY: y }: MouseEvent) => { { duration: 300, easing: 'ease-in', + fill: 'forwards', pseudoElement: `::view-transition-${isDark.value ? 'old' : 'new'}(root)` } ) diff --git a/docs/ko/guide/getting-started.md b/docs/ko/guide/getting-started.md index ac7e7ca6..632e9078 100644 --- a/docs/ko/guide/getting-started.md +++ b/docs/ko/guide/getting-started.md @@ -19,39 +19,19 @@ VitePress는 단독으로 사용하거나 기존 프로젝트에 설치할 수 ::: code-group ```sh [npm] -$ npm add -D vitepress +$ npm add -D vitepress@next ``` ```sh [pnpm] -$ pnpm add -D vitepress +$ pnpm add -D vitepress@next ``` ```sh [yarn] -$ yarn add -D vitepress -``` - -```sh [yarn (pnp)] -$ yarn add -D vitepress vue +$ yarn add -D vitepress@next vue ``` ```sh [bun] -$ bun add -D vitepress -``` - -::: - -::: details "missing peer deps" 경고가 표시되나요? -PNPM을 사용하는 경우 `@docsearch/js`에 대한 "missing peer deps" 경고가 표시됩니다. 이는 VitePress가 작동하는 것을 방해하지 않습니다. 이 경고를 억제하려면 `package.json`에 다음을 추가합니다: - -```json -"pnpm": { - "peerDependencyRules": { - "ignoreMissing": [ - "@algolia/client-search", - "search-insights" - ] - } -} +$ bun add -D vitepress@next ``` ::: diff --git a/docs/ko/guide/markdown.md b/docs/ko/guide/markdown.md index 5f03bbf6..f2003ca6 100644 --- a/docs/ko/guide/markdown.md +++ b/docs/ko/guide/markdown.md @@ -255,11 +255,11 @@ export default defineConfig({ } ``` - 이것은 기본적으로 [`postcss-prefix-selector`](https://github.com/RadValentin/postcss-prefix-selector)를 사용합니다. 다음과 같이 옵션을 전달할 수 있습니다: + 다음과 같이 옵션을 전달할 수 있습니다: ```js postcssIsolateStyles({ - includeFiles: [/vp-doc\.css/] // 기본값은 /base\.css/ + includeFiles: [/custom\.css/] // 기본값은 [/vp-doc\.css/, /base\.css/] }) ``` diff --git a/docs/ko/guide/using-vue.md b/docs/ko/guide/using-vue.md index 5c65eeb7..0146352a 100644 --- a/docs/ko/guide/using-vue.md +++ b/docs/ko/guide/using-vue.md @@ -125,7 +125,7 @@ import CustomComponent from '../components/CustomComponent.vue' 컴포넌트가 대부분의 페이지에서 사용될 경우, Vue 앱 인스턴스를 커스텀하여 전역적으로 등록할 수 있습니다. [기본 테마 확장](./extending-default-theme#registering-global-components)의 관련 섹션을 예제를 참고하세요. ::: warning 중요 -커스텀 컴포넌트의 이름에 하이픈이 포함되어 있거나 파스칼케이스(PascalCase)e인지 확인하세요. 그렇지 않으면 인라인 요소로 처리되어 `

` 태그 안에 래핑됩니다. `

`는 블록 엘리먼트를 내부에 배치할 수 없기 때문에 하이드레이션 불일치가 발생합니다. +커스텀 컴포넌트의 이름에 하이픈이 포함되어 있거나 파스칼케이스(PascalCase)인지 확인하세요. 그렇지 않으면 인라인 요소로 처리되어 `

` 태그 안에 래핑됩니다. `

`는 블록 엘리먼트를 내부에 배치할 수 없기 때문에 하이드레이션 불일치가 발생합니다. ::: ### 헤더에 컴포넌트 사용하기 {#using-components-in-headers} diff --git a/docs/ko/guide/what-is-vitepress.md b/docs/ko/guide/what-is-vitepress.md index 9ad43c45..a2ed0dee 100644 --- a/docs/ko/guide/what-is-vitepress.md +++ b/docs/ko/guide/what-is-vitepress.md @@ -12,7 +12,7 @@ VitePress는 빠르고 컨텐츠 중심의 웹사이트를 구축하기 위해 - **문서화** - VitePress는 기술 문서를 위해 설계된 기본 테마가 함께 제공됩니다. 지금 읽고 있는 이 페이지와 [Vite](https://vitejs.dev/), [Rollup](https://rollupjs.org/), [Pinia](https://pinia.vuejs.org/), [VueUse](https://vueuse.org/), [Vitest](https://vitest.dev/), [D3](https://d3js.org/), [UnoCSS](https://unocss.dev/), [Iconify](https://iconify.design/) 및 [다양한 프로젝트](https://www.vuetelescope.com/explore?framework.slug=vitepress) 문서는 모두 이 테마를 기반으로 합니다. + VitePress는 기술 문서를 위해 설계된 기본 테마가 함께 제공됩니다. 지금 읽고 있는 이 페이지와 [Vite](https://vitejs.dev/), [Rollup](https://rollupjs.org/), [Pinia](https://pinia.vuejs.org/), [VueUse](https://vueuse.org/), [Vitest](https://vitest.dev/), [D3](https://d3js.org/), [UnoCSS](https://unocss.dev/), [Iconify](https://iconify.design/) 및 [다양한 프로젝트](https://github.com/search?q=/"vitepress":+/+language:json&type=code) 문서는 모두 이 테마를 기반으로 합니다. [Vue.js 공식 문서](https://vuejs.org/)도 VitePress 기반으로 되어 있으며, 여러 번역본에 걸쳐 공유되는 커스텀 테마를 사용합니다. diff --git a/docs/ko/index.md b/docs/ko/index.md index 3ddaa07d..aa8be95b 100644 --- a/docs/ko/index.md +++ b/docs/ko/index.md @@ -1,9 +1,6 @@ --- layout: home -title: VitePress -titleTemplate: Vite & Vue 기반 정적 사이트 생성기 - hero: name: VitePress text: Vite & Vue 기반 정적 사이트 생성기 @@ -11,10 +8,10 @@ hero: actions: - theme: brand text: VitePress란 무엇인가? - link: /ko/guide/what-is-vitepress + link: ./guide/what-is-vitepress - theme: alt text: 빠른 시작 - link: /ko/guide/getting-started + link: ./guide/getting-started - theme: alt text: GitHub link: https://github.com/vuejs/vitepress diff --git a/docs/ko/reference/cli.md b/docs/ko/reference/cli.md index 4a76bd01..b81cb165 100644 --- a/docs/ko/reference/cli.md +++ b/docs/ko/reference/cli.md @@ -43,7 +43,6 @@ vitepress build [root] | `--base ` | Public 기본 경로 (기본값: `/`) (`string`) | | `--target ` | 트랜스파일 대상 (기본값: `"modules"`) (`string`) | | `--outDir

` | **cwd** 기준 출력 디렉터리 (기본값: `/.vitepress/dist`) (`string`) | -| `--minify [minifier]` | minify 활성화/비활성화 또는 사용할 minify 도구 지정 (기본값: `"esbuild"`) (`boolean \| "terser" \| "esbuild"`) | | `--assetsInlineLimit `| 바이트 단위의 정적 에셋 base64 인라인 임계값 (기본값: `4096`) (`number`) | ## `vitepress preview` diff --git a/docs/ko/reference/default-theme-config.md b/docs/ko/reference/default-theme-config.md index b0df3361..66b2f4e0 100644 --- a/docs/ko/reference/default-theme-config.md +++ b/docs/ko/reference/default-theme-config.md @@ -89,7 +89,7 @@ type NavItem = NavItemWithLink | NavItemWithChildren interface NavItemWithLink { text: string - link: string + link: string | ((payload: PageData) => string) activeMatch?: string target?: string rel?: string diff --git a/docs/ko/reference/default-theme-nav.md b/docs/ko/reference/default-theme-nav.md index cdfdc7ef..433c2e07 100644 --- a/docs/ko/reference/default-theme-nav.md +++ b/docs/ko/reference/default-theme-nav.md @@ -55,6 +55,8 @@ export default { `text`는 네비게이션 바에 표시되는 실제 텍스트이며, `link`는 텍스트를 클릭했을 때 이동할 링크입니다. 링크의 경로는 `.md` 접미사 없이 실제 파일 경로로 설정하며, 항상 `/`로 시작해야 합니다. +`link`는 또한 [`PageData`](./runtime-api#usedata)를 인자로 받아 경로를 반환하는 함수가 될 수도 있습니다. + 네비게이션 바 링크는 드롭다운 메뉴가 될 수 있습니다. 이를 위해 `link` 옵션에 `items` 키를 설정합니다. ```js diff --git a/docs/ko/reference/default-theme-search.md b/docs/ko/reference/default-theme-search.md index 69b633aa..03eda030 100644 --- a/docs/ko/reference/default-theme-search.md +++ b/docs/ko/reference/default-theme-search.md @@ -377,3 +377,20 @@ new Crawler({ } }) ``` + +### Algolia Ask AI 지원 {#ask-ai} + +**Ask AI** 기능을 사용하려면 `askAi` 옵션을 추가하세요: + +```ts +options: { + appId: '...', + apiKey: '...', + indexName: '...', + askAi: { assistantId: 'XXXYYY' } +} +``` + +::: warning 참고 +Ask AI를 사용하지 않으려면 `askAi` 옵션을 생략하면 됩니다. +::: diff --git a/docs/ko/reference/default-theme-sidebar.md b/docs/ko/reference/default-theme-sidebar.md index 21e19ccc..8e4709cd 100644 --- a/docs/ko/reference/default-theme-sidebar.md +++ b/docs/ko/reference/default-theme-sidebar.md @@ -180,36 +180,3 @@ export default { } } ``` - -## `useSidebar` - -사이드바 관련 데이터를 반환합니다. 반환된 객체는 다음과 같은 타입을 가집니다: - -```ts -export interface DocSidebar { - isOpen: Ref - sidebar: ComputedRef - sidebarGroups: ComputedRef - hasSidebar: ComputedRef - hasAside: ComputedRef - leftAside: ComputedRef - isSidebarEnabled: ComputedRef - open: () => void - close: () => void - toggle: () => void -} -``` - -**예제:** - -```vue - - - -``` diff --git a/docs/ko/reference/default-theme-team-page.md b/docs/ko/reference/default-theme-team-page.md index 2123f349..b4fddb0f 100644 --- a/docs/ko/reference/default-theme-team-page.md +++ b/docs/ko/reference/default-theme-team-page.md @@ -53,12 +53,12 @@ const members = [ Say hello to our awesome team. - + ``` 위 코드는 카드 형태의 엘리먼트로 팀 구성원을 표시합니다. 아래와 비슷한 형태로 표시됩니다. - + `` 컴포넌트는 `small`과 `medium` 두 가지 크기로 제공됩니다. 개인의 선호도에 따라 선택할 수 있지만, 일반적으로 `small` 사이즈가 문서 페이지에 더 적합합니다. 또한, 각 구성원에 "설명"이나 "후원" 버튼과 같은 프로퍼티를 추가할 수도 있습니다. 자세한 내용은 [``](#vpteammembers)에서 확인할 수 있습니다. @@ -107,9 +107,7 @@ const members = [ team, some of whom have chosen to be featured below. - + ``` diff --git a/docs/ko/reference/site-config.md b/docs/ko/reference/site-config.md index 949b8452..ad5a717d 100644 --- a/docs/ko/reference/site-config.md +++ b/docs/ko/reference/site-config.md @@ -458,7 +458,7 @@ export default { ### ignoreDeadLinks -- 타입: `boolean | 'localhostLinks' | (string | RegExp | ((link: string) => boolean))[]` +- 타입: `boolean | 'localhostLinks' | (string | RegExp | ((link: string, source: string) => boolean))[]` - 기본값: `false` `true`로 설정하면, 빌드 시 죽은 링크로 인해 실패하지 않습니다. diff --git a/docs/lunaria.config.json b/docs/lunaria.config.json index 60abdd98..2de958b9 100644 --- a/docs/lunaria.config.json +++ b/docs/lunaria.config.json @@ -6,8 +6,8 @@ }, "files": [ { - "location": ".vitepress/config/{en,zh,pt,ru,es,ko,fa}.ts", - "pattern": ".vitepress/config/@lang.ts", + "location": "**/config.ts", + "pattern": "@lang/@path", "type": "universal" }, { @@ -44,6 +44,10 @@ { "label": "فارسی", "lang": "fa" + }, + { + "label": "日本語", + "lang": "ja" } ], "outDir": ".vitepress/dist/_translations", diff --git a/docs/package.json b/docs/package.json index d3c19d0c..f0aa0873 100644 --- a/docs/package.json +++ b/docs/package.json @@ -13,8 +13,9 @@ "@lunariajs/core": "^0.1.1", "markdown-it-mathjax3": "^4.3.2", "open-cli": "^8.0.0", - "postcss-rtlcss": "^5.6.0", + "postcss-rtlcss": "^5.7.1", "vitepress": "workspace:*", - "vitepress-plugin-group-icons": "^1.3.6" + "vitepress-plugin-group-icons": "^1.6.3", + "vitepress-plugin-llms": "^1.7.3" } } diff --git a/docs/.vitepress/config/pt.ts b/docs/pt/config.ts similarity index 67% rename from docs/.vitepress/config/pt.ts rename to docs/pt/config.ts index 12cb52fa..ae71473d 100644 --- a/docs/.vitepress/config/pt.ts +++ b/docs/pt/config.ts @@ -1,16 +1,17 @@ import { createRequire } from 'module' -import { defineConfig, type DefaultTheme } from 'vitepress' +import { defineAdditionalConfig, type DefaultTheme } from 'vitepress' const require = createRequire(import.meta.url) const pkg = require('vitepress/package.json') -export const pt = defineConfig({ - lang: 'pt-BR', +export default defineAdditionalConfig({ description: 'Gerador de Site Estático desenvolvido com Vite e Vue.', themeConfig: { nav: nav(), + search: { options: searchOptions() }, + sidebar: { '/pt/guide/': { base: '/pt/guide/', items: sidebarGuide() }, '/pt/reference/': { base: '/pt/reference/', items: sidebarReference() } @@ -36,11 +37,15 @@ export const pt = defineConfig({ }, lastUpdated: { - text: 'Atualizado em', - formatOptions: { - dateStyle: 'short', - timeStyle: 'medium' - } + text: 'Atualizado em' + }, + + notFound: { + title: 'PÁGINA NÃO ENCONTRADA', + quote: + 'Mas se você não mudar de direção e continuar procurando, pode acabar onde está indo.', + linkLabel: 'ir para a página inicial', + linkText: 'Me leve para casa' }, langMenuLabel: 'Alterar Idioma', @@ -68,6 +73,10 @@ function nav(): DefaultTheme.NavItem[] { { text: pkg.version, items: [ + { + text: '1.6.4', + link: 'https://vuejs.github.io/vitepress/v1/pt/' + }, { text: 'Registro de Mudanças', link: 'https://github.com/vuejs/vitepress/blob/main/CHANGELOG.md' @@ -167,8 +176,8 @@ function sidebarReference(): DefaultTheme.SidebarItem[] { ] } -export const search: DefaultTheme.AlgoliaSearchOptions['locales'] = { - pt: { +function searchOptions(): Partial { + return { placeholder: 'Pesquisar documentos', translations: { button: { @@ -177,35 +186,69 @@ export const search: DefaultTheme.AlgoliaSearchOptions['locales'] = { }, modal: { searchBox: { - resetButtonTitle: 'Limpar pesquisa', - resetButtonAriaLabel: 'Limpar pesquisa', - cancelButtonText: 'Cancelar', - cancelButtonAriaLabel: 'Cancelar' + clearButtonTitle: 'Limpar pesquisa', + clearButtonAriaLabel: 'Limpar pesquisa', + closeButtonText: 'Fechar', + closeButtonAriaLabel: 'Fechar', + placeholderText: 'Pesquisar documentos', + placeholderTextAskAi: 'Pergunte à IA: ', + placeholderTextAskAiStreaming: 'Respondendo...', + searchInputLabel: 'Pesquisar', + backToKeywordSearchButtonText: 'Voltar à pesquisa por palavras-chave', + backToKeywordSearchButtonAriaLabel: + 'Voltar à pesquisa por palavras-chave' }, startScreen: { - recentSearchesTitle: 'Histórico de Pesquisa', + recentSearchesTitle: 'Histórico de pesquisa', noRecentSearchesText: 'Nenhuma pesquisa recente', saveRecentSearchButtonTitle: 'Salvar no histórico de pesquisas', removeRecentSearchButtonTitle: 'Remover do histórico de pesquisas', favoriteSearchesTitle: 'Favoritos', - removeFavoriteSearchButtonTitle: 'Remover dos favoritos' + removeFavoriteSearchButtonTitle: 'Remover dos favoritos', + recentConversationsTitle: 'Conversas recentes', + removeRecentConversationButtonTitle: + 'Remover esta conversa do histórico' }, errorScreen: { titleText: 'Não foi possível obter resultados', - helpText: 'Verifique a sua conexão de rede' + helpText: 'Verifique sua conexão de rede' + }, + noResultsScreen: { + noResultsText: 'Nenhum resultado encontrado', + suggestedQueryText: 'Você pode tentar uma nova consulta', + reportMissingResultsText: 'Acha que deveria haver resultados?', + reportMissingResultsLinkText: 'Clique para enviar feedback' + }, + resultsScreen: { + askAiPlaceholder: 'Pergunte à IA: ' + }, + askAiScreen: { + disclaimerText: + 'As respostas são geradas por IA e podem conter erros. Verifique as respostas.', + relatedSourcesText: 'Fontes relacionadas', + thinkingText: 'Pensando...', + copyButtonText: 'Copiar', + copyButtonCopiedText: 'Copiado!', + copyButtonTitle: 'Copiar', + likeButtonTitle: 'Curtir', + dislikeButtonTitle: 'Não curtir', + thanksForFeedbackText: 'Obrigado pelo feedback!', + preToolCallText: 'Pesquisando...', + duringToolCallText: 'Pesquisando ', + afterToolCallText: 'Pesquisa concluída', + aggregatedToolCallText: 'Pesquisa concluída' }, footer: { selectText: 'Selecionar', + submitQuestionText: 'Enviar pergunta', + selectKeyAriaLabel: 'Tecla Enter', navigateText: 'Navegar', + navigateUpKeyAriaLabel: 'Seta para cima', + navigateDownKeyAriaLabel: 'Seta para baixo', closeText: 'Fechar', - searchByText: 'Pesquisa por' - }, - noResultsScreen: { - noResultsText: 'Não foi possível encontrar resultados', - suggestedQueryText: 'Você pode tentar uma nova consulta', - reportMissingResultsText: - 'Deveriam haver resultados para essa consulta?', - reportMissingResultsLinkText: 'Clique para enviar feedback' + backToSearchText: 'Voltar à pesquisa', + closeKeyAriaLabel: 'Tecla Escape', + poweredByText: 'Pesquisa por' } } } diff --git a/docs/pt/guide/deploy.md b/docs/pt/guide/deploy.md index 9a03631b..b112bf7d 100644 --- a/docs/pt/guide/deploy.md +++ b/docs/pt/guide/deploy.md @@ -163,7 +163,7 @@ Não ative opções como _Auto Minify_ para código HTML. Isso removerá coment - name: Setup Node uses: actions/setup-node@v4 with: - node-version: 20 + node-version: 22 cache: npm # ou pnpm / yarn - name: Setup Pages uses: actions/configure-pages@v4 diff --git a/docs/pt/guide/extending-default-theme.md b/docs/pt/guide/extending-default-theme.md index 08aea50a..f3175f83 100644 --- a/docs/pt/guide/extending-default-theme.md +++ b/docs/pt/guide/extending-default-theme.md @@ -70,7 +70,7 @@ Se a sua fonte é um arquivo local referenciado via `@font-face`, ela será proc export default { transformHead({ assets }) { // ajuste o regex para corresponder à sua fonte - const myFontFile = assets.find(file => /font-name\.\w+\.woff2/) + const myFontFile = assets.find(file => /font-name\.[\w-]+\.woff2/.test(file)) if (myFontFile) { return [ [ @@ -251,6 +251,7 @@ provide('toggle-appearance', async ({ clientX: x, clientY: y }: MouseEvent) => { { duration: 300, easing: 'ease-in', + fill: 'forwards', pseudoElement: `::view-transition-${isDark.value ? 'old' : 'new'}(root)` } ) diff --git a/docs/pt/guide/getting-started.md b/docs/pt/guide/getting-started.md index e6668cb2..c0dba3a9 100644 --- a/docs/pt/guide/getting-started.md +++ b/docs/pt/guide/getting-started.md @@ -18,39 +18,19 @@ VitePress pode ser usado sozinho, ou ser instalado em um projeto já existente. ::: code-group ```sh [npm] -$ npm add -D vitepress +$ npm add -D vitepress@next ``` ```sh [pnpm] -$ pnpm add -D vitepress +$ pnpm add -D vitepress@next ``` ```sh [yarn] -$ yarn add -D vitepress -``` - -```sh [yarn (pnp)] -$ yarn add -D vitepress vue +$ yarn add -D vitepress@next vue ``` ```sh [bun] -$ bun add -D vitepress -``` - -::: - -::: details Está recebendo avisos sobre dependências correspondentes ausentes? -Se usar PNPM, você perceberá um aviso de ausência de `@docsearch/js`. Isso não evita que o VitePress funcione. Se você deseja suprimir este aviso, adicione o seguinte no seu `package.json`: - -```json -"pnpm": { - "peerDependencyRules": { - "ignoreMissing": [ - "@algolia/client-search", - "search-insights" - ] - } -} +$ bun add -D vitepress@next ``` ::: diff --git a/docs/pt/guide/markdown.md b/docs/pt/guide/markdown.md index b5245259..c4186270 100644 --- a/docs/pt/guide/markdown.md +++ b/docs/pt/guide/markdown.md @@ -255,11 +255,11 @@ A classe `vp-raw` também pode ser usada diretamente em elementos. O isolamento } ``` - Ele utiliza [`postcss-prefix-selector`](https://github.com/postcss/postcss-load-config) internamente. Você pode passar opções assim: + Você pode passar opções assim: ```js postcssIsolateStyles({ - includeFiles: [/vp-doc\.css/] // o padrão é /base\.css/ + includeFiles: [/custom\.css/] // o padrão é [/vp-doc\.css/, /base\.css/] }) ``` diff --git a/docs/pt/guide/using-vue.md b/docs/pt/guide/using-vue.md index 226d90d2..a034108d 100644 --- a/docs/pt/guide/using-vue.md +++ b/docs/pt/guide/using-vue.md @@ -128,7 +128,7 @@ Se um componente for usado na maioria das páginas, eles podem ser registrados g Certifique-se de que o nome de um componente personalizado contenha um hífen ou esteja em PascalCase. Caso contrário, ele será tratado como um elemento alinhado e envolvido dentro de uma tag `

`, o que levará a uma incompatibilidade de hidratação pois `

` não permite que elementos de bloco sejam colocados dentro dele. ::: -### Usando Componentes Em Cabeçalhos {#using-components-in-headers} +### Usando Componentes Em Cabeçalhos {#using-components-in-headers} Você pode usar componentes Vue nos cabeçalhos, mas observe a diferença entre as seguintes sintaxes: diff --git a/docs/pt/guide/what-is-vitepress.md b/docs/pt/guide/what-is-vitepress.md index 734cd417..c447fd02 100644 --- a/docs/pt/guide/what-is-vitepress.md +++ b/docs/pt/guide/what-is-vitepress.md @@ -12,7 +12,7 @@ Quer apenas experimentar? Pule para o [Início Rápido](./getting-started). - **Documentação** - VitePress vem com um tema padrão projetado para documentação técnica. Ele alimenta esta página que você está lendo agora, juntamente com a documentação [Vite](https://vitejs.dev/), [Rollup](https://rollupjs.org/), [Pinia](https://pinia.vuejs.org/), [VueUse](https://vueuse.org/), [Vitest](https://vitest.dev/), [D3](https://d3js.org/), [UnoCSS](https://unocss.dev/), [Iconify](https://iconify.design/) e [muitos outros](https://www.vuetelescope.com/explore?framework.slug=vitepress). + VitePress vem com um tema padrão projetado para documentação técnica. Ele alimenta esta página que você está lendo agora, juntamente com a documentação [Vite](https://vitejs.dev/), [Rollup](https://rollupjs.org/), [Pinia](https://pinia.vuejs.org/), [VueUse](https://vueuse.org/), [Vitest](https://vitest.dev/), [D3](https://d3js.org/), [UnoCSS](https://unocss.dev/), [Iconify](https://iconify.design/) e [muitos outros](https://github.com/search?q=/"vitepress":+/+language:json&type=code). A [documentação oficial Vue.js](https://vuejs.org/) também é baseada em VitePress, mas usa um tema personalizado compartilhado entre várias traduções. diff --git a/docs/pt/index.md b/docs/pt/index.md index 71fff26b..236d7c00 100644 --- a/docs/pt/index.md +++ b/docs/pt/index.md @@ -1,9 +1,6 @@ --- layout: home -title: VitePress -titleTemplate: Gerador de Site Estático desenvolvido com Vite & Vue - hero: name: VitePress text: Gerador de Site Estático Vite & Vue @@ -11,10 +8,10 @@ hero: actions: - theme: brand text: O que é VitePress? - link: /pt/guide/what-is-vitepress + link: ./guide/what-is-vitepress - theme: alt text: Iniciar - link: /pt/guide/getting-started + link: ./guide/getting-started - theme: alt text: GitHub link: https://github.com/vuejs/vitepress diff --git a/docs/pt/reference/cli.md b/docs/pt/reference/cli.md index 6d7f0006..c6ff9bb4 100644 --- a/docs/pt/reference/cli.md +++ b/docs/pt/reference/cli.md @@ -43,7 +43,6 @@ vitepress build [root] | `--base ` | Caminho base público (padrão: `/`) (`string`) | | `--target ` | Transpila o alvo (padrão: `"modules"`) (`string`) | | `--outDir

` | Diretório de saída relativo ao **cwd** (padrão: `/.vitepress/dist`) (`string`) | -| `--minify [minifier]` | Habilita/desabilita minificação, ou especifica um minificador para usar (padrão: `"esbuild"`) (`boolean \| "terser" \| "esbuild"`) | | `--assetsInlineLimit ` | Limite em bytes para alinhar ativos em base64 (padrão: `4096`) (`number`) | ## `vitepress preview` diff --git a/docs/pt/reference/default-theme-config.md b/docs/pt/reference/default-theme-config.md index 54e53e4a..a1ac180f 100644 --- a/docs/pt/reference/default-theme-config.md +++ b/docs/pt/reference/default-theme-config.md @@ -89,7 +89,7 @@ type NavItem = NavItemWithLink | NavItemWithChildren interface NavItemWithLink { text: string - link: string + link: string | ((payload: PageData) => string) activeMatch?: string target?: string rel?: string diff --git a/docs/pt/reference/default-theme-nav.md b/docs/pt/reference/default-theme-nav.md index 5f0d2399..fefc9661 100644 --- a/docs/pt/reference/default-theme-nav.md +++ b/docs/pt/reference/default-theme-nav.md @@ -55,6 +55,8 @@ export default { `text` é o próprio texto mostrado na navegação, e o `link` é o link para o qual será navegado quando o texto for clicado. Para o link, defina o caminho para o próprio arquivo sem o prefixo `.md` e sempre comece com `/`. +O `link` também pode ser uma função que aceita [`PageData`](./runtime-api#usedata) como argumento e retorna o caminho. + Links de navegação também podem ser menus _dropdown_. Para fazer isso, defina a chave `items` na opção do link. ```js diff --git a/docs/pt/reference/default-theme-search.md b/docs/pt/reference/default-theme-search.md index c16406cb..4db22900 100644 --- a/docs/pt/reference/default-theme-search.md +++ b/docs/pt/reference/default-theme-search.md @@ -370,3 +370,20 @@ new Crawler({ } }) ``` + +### Suporte ao Algolia Ask AI {#ask-ai} + +Se quiser incluir o **Ask AI**, adicione `askAi` em `options`: + +```ts +options: { + appId: '...', + apiKey: '...', + indexName: '...', + askAi: { assistantId: 'XXXYYY' } +} +``` + +::: warning Nota +Caso queira apenas a pesquisa por palavra-chave, omita `askAi`. +::: diff --git a/docs/pt/reference/default-theme-sidebar.md b/docs/pt/reference/default-theme-sidebar.md index 62c3b3b1..0d8baf8d 100644 --- a/docs/pt/reference/default-theme-sidebar.md +++ b/docs/pt/reference/default-theme-sidebar.md @@ -180,36 +180,3 @@ export default { } } ``` - -## `useSidebar` - -Retorna dados relacionados à barra lateral. O objeto retornado tem o seguinte tipo: - -```ts -export interface DocSidebar { - isOpen: Ref - sidebar: ComputedRef - sidebarGroups: ComputedRef - hasSidebar: ComputedRef - hasAside: ComputedRef - leftAside: ComputedRef - isSidebarEnabled: ComputedRef - open: () => void - close: () => void - toggle: () => void -} -``` - -**Exemplo:** - -```vue - - - -``` diff --git a/docs/pt/reference/default-theme-team-page.md b/docs/pt/reference/default-theme-team-page.md index 1daa47a5..32a9db0d 100644 --- a/docs/pt/reference/default-theme-team-page.md +++ b/docs/pt/reference/default-theme-team-page.md @@ -53,12 +53,12 @@ const members = [ Diga olá à nossa equipe incrível. - + ``` O código acima exibirá um membro da equipe em um elemento tipo cartão. Ele deve exibir algo semelhante ao abaixo. - + O componente `` vem em 2 tamanhos diferentes, pequeno `small` e médio `medium`. Enquanto é uma questão de preferência, geralmente o tamanho `small` deve encaixar melhor quando usado na página de documento. Além disso, você pode adicionar mais propriedades a cada membro, como adicionar o botão "descrição" ou "patrocinador". Saiba mais sobre em [``](#vpteammembers). @@ -107,9 +107,7 @@ const members = [ alguns dos membros escolheram ser apresentados abaixo. - + ``` diff --git a/docs/pt/reference/site-config.md b/docs/pt/reference/site-config.md index 84b8493a..6f344017 100644 --- a/docs/pt/reference/site-config.md +++ b/docs/pt/reference/site-config.md @@ -24,7 +24,7 @@ export default { } ``` -:::details Configuração Dinâmica (Assíncrona) +::: details Configuração Dinâmica (Assíncrona) Se você precisar gerar dinamicamente a configuração, também pode exportar por padrão uma função. Por exemplo: @@ -458,7 +458,7 @@ export default { ### ignoreDeadLinks -- Tipo: `boolean | 'localhostLinks' | (string | RegExp | ((link: string) => boolean))[]` +- Tipo: `boolean | 'localhostLinks' | (string | RegExp | ((link: string, source: string) => boolean))[]` - Padrão: `false` Quando definido como `true`, VitePress não falhará na compilação devido a links quebrados. @@ -613,7 +613,7 @@ export default { `transformHead` é um gancho de compilação para transformar o cabeçalho antes de gerar cada página. Isso permite adicionar entradas no cabeçalho que não podem ser adicionadas estaticamente à configuração VitePress. Você só precisa retornar entradas extras, que serão mescladas automaticamente com as existentes. -:::warning +::: warning Não faça mutações em qualquer item dentro de `context`. ::: @@ -681,7 +681,7 @@ export default { - Tipo: `(code: string, id: string, context: TransformContext) => Awaitable` `transformHtml` é um gancho de compilação para transformar o conteúdo de cada página antes de salvá-lo no disco. -:::warning +::: warning Não faça mutações em qualquer item dentro de `context`. Além disso, modificar o conteúdo HTML pode causar problemas de hidratação em tempo de execução. ::: @@ -698,7 +698,7 @@ export default { `transformPageData` é um gancho para transformar os dados de cada página. Você pode fazer mutações diretamente em `pageData` ou retornar valores alterados que serão mesclados nos dados da página. -:::warning +::: warning Não faça mutações em qualquer item dentro de `context` e tenha cuidado pois isso pode impactar no desempenho do servidor de desenvolvimento, especialmente se você tiver algumas solicitações de rede ou computações pesadas (como gerar imagens) no gancho. Você pode verificar `process.env.NODE_ENV === 'production'` para lógica condicional. ::: diff --git a/docs/.vitepress/config/ru.ts b/docs/ru/config.ts similarity index 65% rename from docs/.vitepress/config/ru.ts rename to docs/ru/config.ts index b75b1b77..e196d193 100644 --- a/docs/.vitepress/config/ru.ts +++ b/docs/ru/config.ts @@ -1,16 +1,17 @@ import { createRequire } from 'module' -import { defineConfig, type DefaultTheme } from 'vitepress' +import { defineAdditionalConfig, type DefaultTheme } from 'vitepress' const require = createRequire(import.meta.url) const pkg = require('vitepress/package.json') -export const ru = defineConfig({ - lang: 'ru-RU', +export default defineAdditionalConfig({ description: 'Генератор статических сайтов на основе Vite и Vue.', themeConfig: { nav: nav(), + search: { options: searchOptions() }, + sidebar: { '/ru/guide/': { base: '/ru/guide/', items: sidebarGuide() }, '/ru/reference/': { base: '/ru/reference/', items: sidebarReference() } @@ -37,6 +38,14 @@ export const ru = defineConfig({ text: 'Обновлено' }, + notFound: { + title: 'СТРАНИЦА НЕ НАЙДЕНА', + quote: + 'Но если ты не изменишь направление и продолжишь искать, ты можешь оказаться там, куда направляешься.', + linkLabel: 'перейти на главную', + linkText: 'Отведи меня домой' + }, + darkModeSwitchLabel: 'Оформление', lightModeSwitchTitle: 'Переключить на светлую тему', darkModeSwitchTitle: 'Переключить на тёмную тему', @@ -62,6 +71,10 @@ function nav(): DefaultTheme.NavItem[] { { text: pkg.version, items: [ + { + text: '1.6.4', + link: 'https://vuejs.github.io/vitepress/v1/ru/' + }, { text: 'Изменения', link: 'https://github.com/vuejs/vitepress/blob/main/CHANGELOG.md' @@ -163,8 +176,8 @@ function sidebarReference(): DefaultTheme.SidebarItem[] { ] } -export const search: DefaultTheme.AlgoliaSearchOptions['locales'] = { - ru: { +function searchOptions(): Partial { + return { placeholder: 'Поиск в документации', translations: { button: { @@ -173,10 +186,18 @@ export const search: DefaultTheme.AlgoliaSearchOptions['locales'] = { }, modal: { searchBox: { - resetButtonTitle: 'Сбросить поиск', - resetButtonAriaLabel: 'Сбросить поиск', - cancelButtonText: 'Отменить поиск', - cancelButtonAriaLabel: 'Отменить поиск' + clearButtonTitle: 'Очистить поиск', + clearButtonAriaLabel: 'Очистить поиск', + closeButtonText: 'Закрыть', + closeButtonAriaLabel: 'Закрыть', + placeholderText: 'Поиск в документации', + placeholderTextAskAi: 'Задайте вопрос ИИ: ', + placeholderTextAskAiStreaming: 'Формируется ответ...', + searchInputLabel: 'Поиск', + backToKeywordSearchButtonText: + 'Вернуться к поиску по ключевым словам', + backToKeywordSearchButtonAriaLabel: + 'Вернуться к поиску по ключевым словам' }, startScreen: { recentSearchesTitle: 'История поиска', @@ -184,24 +205,50 @@ export const search: DefaultTheme.AlgoliaSearchOptions['locales'] = { saveRecentSearchButtonTitle: 'Сохранить в истории поиска', removeRecentSearchButtonTitle: 'Удалить из истории поиска', favoriteSearchesTitle: 'Избранное', - removeFavoriteSearchButtonTitle: 'Удалить из избранного' + removeFavoriteSearchButtonTitle: 'Удалить из избранного', + recentConversationsTitle: 'Недавние диалоги', + removeRecentConversationButtonTitle: 'Удалить этот диалог из истории' }, errorScreen: { titleText: 'Невозможно получить результаты', - helpText: 'Вам может потребоваться проверить подключение к Интернету' + helpText: 'Проверьте подключение к Интернету' + }, + noResultsScreen: { + noResultsText: 'Ничего не найдено', + suggestedQueryText: 'Попробуйте изменить запрос', + reportMissingResultsText: 'Считаете, что результаты должны быть?', + reportMissingResultsLinkText: 'Сообщите об этом' + }, + resultsScreen: { + askAiPlaceholder: 'Задайте вопрос ИИ: ' + }, + askAiScreen: { + disclaimerText: + 'Ответы генерируются ИИ и могут содержать ошибки. Проверяйте информацию.', + relatedSourcesText: 'Связанные источники', + thinkingText: 'Думаю...', + copyButtonText: 'Копировать', + copyButtonCopiedText: 'Скопировано!', + copyButtonTitle: 'Копировать', + likeButtonTitle: 'Нравится', + dislikeButtonTitle: 'Не нравится', + thanksForFeedbackText: 'Спасибо за отзыв!', + preToolCallText: 'Поиск...', + duringToolCallText: 'Поиск ', + afterToolCallText: 'Поиск завершён', + aggregatedToolCallText: 'Поиск завершён' }, footer: { selectText: 'выбрать', + submitQuestionText: 'Отправить вопрос', + selectKeyAriaLabel: 'Клавиша Enter', navigateText: 'перейти', + navigateUpKeyAriaLabel: 'Стрелка вверх', + navigateDownKeyAriaLabel: 'Стрелка вниз', closeText: 'закрыть', - searchByText: 'поставщик поиска' - }, - noResultsScreen: { - noResultsText: 'Нет результатов для', - suggestedQueryText: 'Вы можете попытаться узнать', - reportMissingResultsText: - 'Считаете, что поиск даёт ложные результаты?', - reportMissingResultsLinkText: 'Нажмите на кнопку «Обратная связь»' + backToSearchText: 'Вернуться к поиску', + closeKeyAriaLabel: 'Клавиша Esc', + poweredByText: 'поиск от' } } } diff --git a/docs/ru/guide/deploy.md b/docs/ru/guide/deploy.md index 0de4fbe0..ff12be6c 100644 --- a/docs/ru/guide/deploy.md +++ b/docs/ru/guide/deploy.md @@ -111,7 +111,7 @@ Cache-Control: max-age=31536000,immutable - **Build Command:** `npm run docs:build` - **Output Directory:** `docs/.vitepress/dist` -- **Node Version:** `18` (или выше) +- **Node Version:** `20` (или выше) ::: warning ПРЕДУПРЕЖДЕНИЕ Не включайте такие опции, как _Auto Minify_ для HTML-кода. Он удалит из вывода комментарии, которые имеют значение для Vue. При их удалении могут возникать ошибки несоответствия гидратации. @@ -163,7 +163,7 @@ Cache-Control: max-age=31536000,immutable - name: Setup Node uses: actions/setup-node@v4 with: - node-version: 20 + node-version: 22 cache: npm # или pnpm / yarn - name: Setup Pages uses: actions/configure-pages@v4 diff --git a/docs/ru/guide/extending-default-theme.md b/docs/ru/guide/extending-default-theme.md index a8f0acc7..b1497ced 100644 --- a/docs/ru/guide/extending-default-theme.md +++ b/docs/ru/guide/extending-default-theme.md @@ -70,7 +70,7 @@ export default DefaultTheme export default { transformHead({ assets }) { // настраиваем regex соответствующим образом, чтобы он соответствовал вашему шрифту - const myFontFile = assets.find((file) => /font-name\.\w+\.woff2/) + const myFontFile = assets.find(file => /font-name\.[\w-]+\.woff2/.test(file)) if (myFontFile) { return [ [ @@ -253,6 +253,7 @@ provide('toggle-appearance', async ({ clientX: x, clientY: y }: MouseEvent) => { { duration: 300, easing: 'ease-in', + fill: 'forwards', pseudoElement: `::view-transition-${isDark.value ? 'old' : 'new'}(root)` } ) diff --git a/docs/ru/guide/getting-started.md b/docs/ru/guide/getting-started.md index 21e8dcb0..4ca5ff8c 100644 --- a/docs/ru/guide/getting-started.md +++ b/docs/ru/guide/getting-started.md @@ -18,39 +18,19 @@ VitePress можно использовать самостоятельно ил ::: code-group ```sh [npm] -$ npm add -D vitepress +$ npm add -D vitepress@next ``` ```sh [pnpm] -$ pnpm add -D vitepress +$ pnpm add -D vitepress@next ``` ```sh [yarn] -$ yarn add -D vitepress -``` - -```sh [yarn (pnp)] -$ yarn add -D vitepress vue +$ yarn add -D vitepress@next vue ``` ```sh [bun] -$ bun add -D vitepress -``` - -::: - -::: details Получаете предупреждения об отсутствующих зависимостях? -Если вы используете PNPM, вы заметите предупреждение об отсутствующем пакете `@docsearch/js`. Это не мешает работе VitePress. Если вы хотите подавить это предупреждение, добавьте следующее в ваш `package.json`: - -```json -"pnpm": { - "peerDependencyRules": { - "ignoreMissing": [ - "@algolia/client-search", - "search-insights" - ] - } -} +$ bun add -D vitepress@next ``` ::: diff --git a/docs/ru/guide/markdown.md b/docs/ru/guide/markdown.md index b67e1355..2bd1a5c1 100644 --- a/docs/ru/guide/markdown.md +++ b/docs/ru/guide/markdown.md @@ -281,11 +281,11 @@ console.log('Привет, VitePress!') } ``` - Он использует [`postcss-prefix-selector`](https://github.com/postcss/postcss-load-config) под капотом. Вы можете передать ему параметры следующим образом: + Вы можете передать ему параметры следующим образом: ```js postcssIsolateStyles({ - includeFiles: [/vp-doc\.css/] // по умолчанию /base\.css/ + includeFiles: [/custom\.css/] // по умолчанию [/vp-doc\.css/, /base\.css/] }) ``` @@ -783,7 +783,7 @@ export default config Вы можете включить файл Markdown в другой файл Markdown, даже вложенный. ::: tip СОВЕТ -Вы также можете добавить в префикс пути к Markdown символ `@`, он будет выступать в качестве корня источника. По умолчанию это корень проекта VitePress, если не настроена опция `srcDir`. +Вы также можете добавить префикс `@` к пути Markdown, и он будет считаться корневой папкой исходников. По умолчанию корневая папка исходников совпадает с корнем проекта VitePress, если не настроен параметр `srcDir`. ::: Например, вы можете включить относительный файл Markdown следующим образом: diff --git a/docs/ru/guide/what-is-vitepress.md b/docs/ru/guide/what-is-vitepress.md index 1bcc3e18..715ecc89 100644 --- a/docs/ru/guide/what-is-vitepress.md +++ b/docs/ru/guide/what-is-vitepress.md @@ -1,6 +1,6 @@ # Что такое VitePress? {#what-is-vitepress} -VitePress — это [Генератор статических сайтов](https://en.wikipedia.org/wiki/Static_site_generator) (ГСС), предназначенный для быстрого создания сайтов, ориентированных на контент. В двух словах, VitePress берёт ваш исходный контент, написанный в [Markdown](https://ru.wikipedia.org/wiki/Markdown), применяет к нему тему и генерирует статические HTML-страницы, которые можно легко развернуть в любом месте. +VitePress — это [Генератор статических сайтов](https://en.wikipedia.org/wiki/Static_site_generator) (ГСС), предназначенный для быстрого создания сайтов, ориентированных на контент. В двух словах, VitePress берёт ваш исходный контент, написанный на [Markdown](https://ru.wikipedia.org/wiki/Markdown), применяет к нему тему и генерирует статические HTML-страницы, которые можно легко развернуть в любом месте.
@@ -12,7 +12,7 @@ VitePress — это [Генератор статических сайтов](ht - **Документация** - VitePress поставляется с темой по умолчанию, предназначенной для технической документации. Она содержит эту страницу, которую вы сейчас читаете, а также документацию по [Vite](https://vitejs.dev/), [Rollup](https://rollupjs.org/), [Pinia](https://pinia.vuejs.org/), [VueUse](https://vueuse.org/), [Vitest](https://vitest.dev/), [D3](https://d3js.org/), [UnoCSS](https://unocss.dev/), [Iconify](https://iconify.design/) и [многое другое](https://www.vuetelescope.com/explore?framework.slug=vitepress). + VitePress поставляется с темой по умолчанию, предназначенной для технической документации. Она содержит эту страницу, которую вы сейчас читаете, а также документацию по [Vite](https://vitejs.dev/), [Rollup](https://rollupjs.org/), [Pinia](https://pinia.vuejs.org/), [VueUse](https://vueuse.org/), [Vitest](https://vitest.dev/), [D3](https://d3js.org/), [UnoCSS](https://unocss.dev/), [Iconify](https://iconify.design/) и [многое другое](https://github.com/search?q=/"vitepress":+/+language:json&type=code). [Официальная документация Vue.js](https://vuejs.org/) также основана на VitePress, но использует пользовательскую тему, разделяемую между несколькими переводами. @@ -50,8 +50,8 @@ VitePress стремится обеспечить отличные возмож ## Что насчёт VuePress? {#what-about-vuepress} -VitePress — это духовный наследник VuePress. Оригинальный VuePress был основан на Vue 2 и webpack. Благодаря Vue 3 и Vite под капотом, VitePress обеспечивает значительно лучший опыт разработки, лучшую производительность, более отточенную тему по умолчанию и более гибкий API для настройки. +VitePress — это духовный преемник VuePress 1. Оригинальный VuePress 1 был основан на Vue 2 и webpack. С Vue 3 и Vite под капотом VitePress обеспечивает значительно лучший опыт разработки (DX), лучшую производительность в продакшене, более отточенную стандартную тему и более гибкий API для кастомизации. -Разница в API между VitePress и VuePress заключается в основном в тематическом оформлении и настройке. Если вы используете VuePress 1 с темой по умолчанию, то переход на VitePress будет относительно простым. +Различия в API между VitePress и VuePress 1 в основном касаются тем и кастомизации. Если вы используете VuePress 1 со стандартной темой, миграция на VitePress должна быть относительно простой. -Также были приложены усилия для создания VuePress 2, который также поддерживает Vue 3 и Vite с большей совместимостью с VuePress 1. Однако поддерживать два генератора параллельно не представляется возможным, поэтому команда Vue решила сосредоточиться на VitePress как основном рекомендуемом генераторе статических сайтов в долгосрочной перспективе. +Поддержка двух генераторов статических сайтов (SSG) параллельно не является устойчивой, поэтому команда Vue решила сосредоточиться на VitePress как на основном рекомендуемом SSG в долгосрочной перспективе. Теперь VuePress 1 признан устаревшим, а VuePress 2 передан команде сообщества VuePress для дальнейшей разработки и поддержки. diff --git a/docs/ru/index.md b/docs/ru/index.md index 77f2072a..faa45e78 100644 --- a/docs/ru/index.md +++ b/docs/ru/index.md @@ -1,9 +1,6 @@ --- layout: home -title: VitePress -titleTemplate: Генератор статических сайтов на основе Vite и Vue - hero: name: VitePress text: Генератор статических сайтов на основе Vite и Vue @@ -11,10 +8,10 @@ hero: actions: - theme: brand text: Что такое VitePress? - link: /ru/guide/what-is-vitepress + link: ./guide/what-is-vitepress - theme: alt text: Первые шаги - link: /ru/guide/getting-started + link: ./guide/getting-started - theme: alt text: GitHub link: https://github.com/vuejs/vitepress diff --git a/docs/ru/reference/cli.md b/docs/ru/reference/cli.md index 93954da2..5884a7e8 100644 --- a/docs/ru/reference/cli.md +++ b/docs/ru/reference/cli.md @@ -43,7 +43,6 @@ vitepress build [root] | `--base ` | Публичный базовый путь (по умолчанию: `/`) (`string`) | | `--target ` | Транспилировать цель (по умолчанию: `"modules"`) (`string`) | | `--outDir ` | Выходной каталог относительно **cwd** (по умолчанию: `/.vitepress/dist`) (`string`) | -| `--minify [minifier]` | Включить/выключить минификацию или задать используемый минификатор (по умолчанию: `"esbuild"`) (`boolean \| "terser" \| "esbuild"`) | | `--assetsInlineLimit ` | Статический встроенный порог ресурса base64 в байтах (по умолчанию: `4096`) (`number`) | ## `vitepress preview` {#vitepress-preview} diff --git a/docs/ru/reference/default-theme-config.md b/docs/ru/reference/default-theme-config.md index 348791c0..27b70443 100644 --- a/docs/ru/reference/default-theme-config.md +++ b/docs/ru/reference/default-theme-config.md @@ -19,13 +19,13 @@ export default { **Параметры, описанные на этой странице, применимы только к теме по умолчанию.** Разные темы предполагают разные конфигурации темы. При использовании пользовательской темы объект конфигурации темы будет передан теме, чтобы она могла определить условное поведение на его основе. -## i18nRouting {#i18nrouting} +## i18nRouting - Тип: `boolean` При смене локали на `ru` URL изменится с `/foo` (или `/en/foo/`) на `/ru/foo`. Вы можете отключить это поведение, установив для параметра `themeConfig.i18nRouting` значение `false`. -## logo {#logo} +## logo - Тип: `ThemeableImage` @@ -46,7 +46,7 @@ type ThemeableImage = | { light: string; dark: string; alt?: string } ``` -## siteTitle {#sitetitle} +## siteTitle - Тип: `string | false` @@ -60,7 +60,7 @@ export default { } ``` -## nav {#nav} +## nav - Тип: `NavItem` @@ -89,7 +89,7 @@ type NavItem = NavItemWithLink | NavItemWithChildren interface NavItemWithLink { text: string - link: string + link: string | ((payload: PageData) => string) activeMatch?: string target?: string rel?: string @@ -108,7 +108,7 @@ interface NavItemWithChildren { } ``` -## sidebar {#sidebar} +## sidebar - Тип: `Sidebar` @@ -135,7 +135,7 @@ export default { export type Sidebar = SidebarItem[] | SidebarMulti export interface SidebarMulti { - [path: string]: SidebarItem[] + [path: string]: SidebarItem[] | { items: SidebarItem[]; base: string } } export type SidebarItem = { @@ -162,10 +162,23 @@ export type SidebarItem = { * Если `false`, группа сворачивается, но по умолчанию разворачивается */ collapsed?: boolean + + /** + * Базовый путь для дочерних элементов + */ + base?: string + + /** + * Настройте текст, который отображается в футере предыдущей/следующей страницы + */ + docFooterText?: string + + rel?: string + target?: string } ``` -## aside {#aside} +## aside - Тип: `boolean | 'left'` - По умолчанию: `true` @@ -177,7 +190,7 @@ export type SidebarItem = { Если вы хотите отключить его для всех режимов просмотра, используйте `aside: false`. -## outline {#outline} +## outline - Тип: `Outline | Outline['level'] | false` - Уровень можно переопределить для каждой страницы с помощью [метаданных](./frontmatter-config#outline) @@ -205,7 +218,7 @@ interface Outline { } ``` -## socialLinks {#sociallinks} +## socialLinks - Тип: `SocialLink[]` @@ -215,6 +228,7 @@ interface Outline { export default { themeConfig: { socialLinks: [ + // Можно добавить любую иконку из simple-icons (https://simpleicons.org/): { icon: 'github', link: 'https://github.com/vuejs/vitepress' }, { icon: 'twitter', link: '...' }, // Можно добавить пользовательские иконки, передав SVG в виде строки: @@ -239,7 +253,7 @@ interface SocialLink { } ``` -## footer {#footer} +## footer - Тип: `Footer` - Можно переопределить для каждой страницы с помощью [метаданных](./frontmatter-config#footer) @@ -264,7 +278,7 @@ export interface Footer { } ``` -## editLink {#editlink} +## editLink - Тип: `EditLink` - Можно переопределить для каждой страницы с помощью [метаданных](./frontmatter-config#editlink) @@ -289,7 +303,7 @@ export interface EditLink { } ``` -## lastUpdated {#lastupdated} +## lastUpdated - Тип: `LastUpdatedOptions` @@ -324,7 +338,7 @@ export interface LastUpdatedOptions { } ``` -## algolia {#algolia} +## algolia - Тип: `AlgoliaSearch` @@ -364,7 +378,7 @@ export interface CarbonAdsOptions { Подробнее в главе [Тема по умолчанию: Carbon Ads](./default-theme-carbon-ads) -## docFooter {#docfooter} +## docFooter - Тип: `DocFooter` @@ -388,47 +402,47 @@ export interface DocFooter { } ``` -## darkModeSwitchLabel {#darkmodeswitchlabel} +## darkModeSwitchLabel - Тип: `string` - По умолчанию: `Appearance` Можно использовать для настройки надписи переключателя тёмного режима. Этот ярлык отображается только в мобильном представлении. -## lightModeSwitchTitle {#lightmodeswitchtitle} +## lightModeSwitchTitle - Тип: `string` - По умолчанию: `Switch to light theme` Может использоваться для настройки заголовка переключателя светлого режима, который появляется при наведении курсора. -## darkModeSwitchTitle {#darkmodeswitchtitle} +## darkModeSwitchTitle - Тип: `string` - По умолчанию: `Switch to dark theme` Можно использовать для настройки заголовка переключателя тёмного режима, который появляется при наведении курсора. -## sidebarMenuLabel {#sidebarmenulabel} +## sidebarMenuLabel - Тип: `string` - По умолчанию: `Menu` Может использоваться для настройки метки бокового меню. Эта метка отображается только в мобильном представлении. -## returnToTopLabel {#returntotoplabel} +## returnToTopLabel - Тип: `string` - По умолчанию: `Return to top` Может использоваться для настройки метки кнопки возврата наверх. Эта метка отображается только в мобильном представлении. -## langMenuLabel {#langmenulabel} +## langMenuLabel - Тип: `string` - По умолчанию: `Change language` -Можно использовать для настройки aria-метки кнопки переключения языка в панели навигации. Это используется только в том случае, если вы используете [i18n](../guide/i18n). +Можно использовать для настройки aria-метки кнопки переключения языка в панели навигации. Применяется только в том случае, если вы используете [i18n](../guide/i18n). ## skipToContentLabel @@ -437,9 +451,44 @@ export interface DocFooter { Можно использовать для настройки метки ссылки перехода к содержимому. Эта ссылка отображается, когда пользователь перемещается по сайту с помощью клавиатуры. -## externalLinkIcon {#externallinkicon} +## externalLinkIcon - Тип: `boolean` - По умолчанию: `false` Отображать ли значок внешней ссылки рядом с внешними ссылками в Markdown. + +## `useLayout` + +Возвращает данные, относящиеся к макету. Возвращаемый объект имеет следующий тип: + +```ts +interface { + isHome: ComputedRef + + sidebar: Readonly> + sidebarGroups: ComputedRef + hasSidebar: ComputedRef + isSidebarEnabled: ComputedRef + + hasAside: ComputedRef + leftAside: ComputedRef + + headers: Readonly> + hasLocalNav: ComputedRef +} +``` + +**Пример:** + +```vue + + + +``` diff --git a/docs/ru/reference/default-theme-last-updated.md b/docs/ru/reference/default-theme-last-updated.md index 7d926dc5..4a0509f4 100644 --- a/docs/ru/reference/default-theme-last-updated.md +++ b/docs/ru/reference/default-theme-last-updated.md @@ -2,8 +2,27 @@ Время последнего обновления содержимого будет отображаться в правом нижнем углу страницы. Чтобы включить его, добавьте опцию `lastUpdated` в свой конфиг. -::: tip Совет -Чтобы увидеть обновленное время, необходимо зафиксировать файл Markdown. +::: info ПРИМЕЧАНИЕ +VitePress отображает время «последнего обновления» на основе временной метки последнего Git-коммита для каждого файла. Для работы этой функции Markdown-файл должен быть закоммичен в Git. + +Внутри VitePress выполняет команду `git log -1 --pretty="%ai"` для каждого файла, чтобы получить его временную метку. Если все страницы показывают одинаковое время обновления, вероятно, это связано с поверхностным клонированием (часто встречается в CI-средах), которое ограничивает историю Git. + +Чтобы исправить это в **GitHub Actions**, добавьте следующее в ваш workflow-файл: + +```yaml{4} +- name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 +``` + +Другие CI/CD-платформы имеют аналогичные настройки. + +Если такие опции недоступны, вы можете добавить принудительный fetch перед командой `docs:build` в вашем `package.json`: + +```json +"docs:build": "git fetch --unshallow && vitepress build docs" +``` ::: ## Настройка в файле конфигурации {#site-level-config} diff --git a/docs/ru/reference/default-theme-nav.md b/docs/ru/reference/default-theme-nav.md index 41257de8..edfb9a9e 100644 --- a/docs/ru/reference/default-theme-nav.md +++ b/docs/ru/reference/default-theme-nav.md @@ -55,6 +55,8 @@ export default { `text` — это текст, отображаемый в навигации, а `link` — это ссылка, на которую будет осуществлён переход при нажатии на текст. Для ссылки задайте путь к фактическому файлу без префикса `.md` и всегда начинайте с `/`. +`link` также может быть функцией, которая принимает [`PageData`](./runtime-api#usedata) в качестве аргумента и возвращает путь. + Навигационные ссылки также могут быть выпадающими меню. Для этого установите ключ `items` вместо ключа `link`: ```js diff --git a/docs/ru/reference/default-theme-search.md b/docs/ru/reference/default-theme-search.md index bab3fa9e..9cdc9438 100644 --- a/docs/ru/reference/default-theme-search.md +++ b/docs/ru/reference/default-theme-search.md @@ -233,10 +233,16 @@ export default defineConfig({ }, modal: { searchBox: { - resetButtonTitle: 'Сбросить поиск', - resetButtonAriaLabel: 'Сбросить поиск', - cancelButtonText: 'Отменить поиск', - cancelButtonAriaLabel: 'Отменить поиск' + clearButtonTitle: 'Очистить поиск', + clearButtonAriaLabel: 'Очистить поиск', + closeButtonText: 'Закрыть', + closeButtonAriaLabel: 'Закрыть', + placeholderText: 'Поиск в документации', + placeholderTextAskAi: 'Задайте вопрос ИИ:', + placeholderTextAskAiStreaming: 'Формируется ответ...', + searchInputLabel: 'Поиск', + backToKeywordSearchButtonText: 'Вернуться к поиску по ключевым словам', + backToKeywordSearchButtonAriaLabel: 'Вернуться к поиску по ключевым словам' }, startScreen: { recentSearchesTitle: 'История поиска', @@ -244,26 +250,48 @@ export default defineConfig({ saveRecentSearchButtonTitle: 'Сохранить в истории поиска', removeRecentSearchButtonTitle: 'Удалить из истории поиска', favoriteSearchesTitle: 'Избранное', - removeFavoriteSearchButtonTitle: 'Удалить из избранного' + removeFavoriteSearchButtonTitle: 'Удалить из избранного', + recentConversationsTitle: 'Последние диалоги', + removeRecentConversationButtonTitle: 'Удалить диалог из истории' }, errorScreen: { titleText: 'Невозможно получить результаты', - helpText: - 'Вам может потребоваться проверить подключение к Интернету' + helpText: 'Проверьте подключение к Интернету' + }, + noResultsScreen: { + noResultsText: 'Ничего не найдено', + suggestedQueryText: 'Попробуйте изменить запрос', + reportMissingResultsText: 'Считаете, что результаты должны быть?', + reportMissingResultsLinkText: 'Сообщите об этом' + }, + resultsScreen: { + askAiPlaceholder: 'Задайте вопрос ИИ: ' + }, + askAiScreen: { + disclaimerText: 'Ответ сгенерирован ИИ и может быть неточным. Пожалуйста, проверьте информацию самостоятельно.', + relatedSourcesText: 'Связанные источники', + thinkingText: 'Думаю...', + copyButtonText: 'Копировать', + copyButtonCopiedText: 'Скопировано!', + copyButtonTitle: 'Копировать', + likeButtonTitle: 'Нравится', + dislikeButtonTitle: 'Не нравится', + thanksForFeedbackText: 'Спасибо за ваш отзыв!', + preToolCallText: 'Идёт поиск...', + duringToolCallText: 'Поиск ', + afterToolCallText: 'Поиск выполнен' }, footer: { selectText: 'выбрать', + submitQuestionText: 'Отправить вопрос', + selectKeyAriaLabel: 'Клавиша Enter', navigateText: 'перейти', + navigateUpKeyAriaLabel: 'Стрелка вверх', + navigateDownKeyAriaLabel: 'Стрелка вниз', closeText: 'закрыть', - searchByText: 'поставщик поиска' - }, - noResultsScreen: { - noResultsText: 'Нет результатов для', - suggestedQueryText: 'Вы можете попытаться узнать', - reportMissingResultsText: - 'Считаете, что поиск даёт ложные результаты?', - reportMissingResultsLinkText: - 'Нажмите на кнопку «Обратная связь»' + backToSearchText: 'Вернуться к поиску', + closeKeyAriaLabel: 'Клавиша Esc', + poweredByText: 'поиск от' } } } @@ -277,6 +305,43 @@ export default defineConfig({ [Эти параметры](https://github.com/vuejs/vitepress/blob/main/types/docsearch.d.ts) можно переопределить. Чтобы узнать о них больше, обратитесь к официальной документации Algolia. +### Поддержка Ask AI в Algolia {#ask-ai} + +Если вы хотите добавить функцию **Ask AI**, передайте параметр `askAi` (или любые из его отдельных полей) внутри объекта `options`: + +```ts +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + search: { + provider: 'algolia', + options: { + appId: '...', + apiKey: '...', + indexName: '...', + // askAi: "ID-ВАШЕГО-АССИСТЕНТА" + // ИЛИ + askAi: { + // минимум вы должны указать assistantId, полученный от Algolia + assistantId: 'XXXYYY', + // опциональные переопределения – если не указаны, используются значения appId/apiKey/indexName верхнего уровня + // apiKey: '...', + // appId: '...', + // indexName: '...' + } + } + } + } +}) +``` + +::: warning Примечание +Если вы хотите использовать обычный поиск по ключевым словам без Ask AI, просто не указывайте свойство `askAi` +::: + +Переводы для интерфейса Ask AI находятся в `options.translations.modal.askAiScreen` и `options.translations.resultsScreen` — полный список ключей смотрите в [типах](https://github.com/vuejs/vitepress/blob/main/types/docsearch.d.ts). + ### Конфигурация поискового робота {#crawler-config} Вот пример конфигурации, основанной на той, что используется на этом сайте: @@ -383,4 +448,4 @@ new Crawler({ } } }) -``` +``` \ No newline at end of file diff --git a/docs/ru/reference/default-theme-sidebar.md b/docs/ru/reference/default-theme-sidebar.md index 92fd89c1..bdc6e338 100644 --- a/docs/ru/reference/default-theme-sidebar.md +++ b/docs/ru/reference/default-theme-sidebar.md @@ -178,36 +178,3 @@ export default { } } ``` - -## `useSidebar` {#usesidebar} - -Возвращает данные, связанные с сайдбаром. Возвращаемый объект имеет следующий тип: - -```ts -export interface DocSidebar { - isOpen: Ref - sidebar: ComputedRef - sidebarGroups: ComputedRef - hasSidebar: ComputedRef - hasAside: ComputedRef - leftAside: ComputedRef - isSidebarEnabled: ComputedRef - open: () => void - close: () => void - toggle: () => void -} -``` - -**Пример:** - -```vue - - - -``` diff --git a/docs/ru/reference/default-theme-team-page.md b/docs/ru/reference/default-theme-team-page.md index 0eebaa24..615692bb 100644 --- a/docs/ru/reference/default-theme-team-page.md +++ b/docs/ru/reference/default-theme-team-page.md @@ -51,12 +51,12 @@ const members = [ # Поприветствуйте нашу замечательную команду - + ``` Вышеуказанное отобразит члена команды в виде карточки. Должно отобразиться что-то похожее на то, что показано ниже. - + Компонент `` поставляется в двух различных размерах, `small` и `medium`. Хотя это зависит от ваших предпочтений, обычно размер `small` лучше подходит для использования на странице с макетом `doc`. Кроме того, вы можете добавить дополнительные свойства для карточки члена команды, например, добавить «описание» или кнопку «спонсировать». Подробнее об этом в секции [``](#vpteammembers). @@ -104,7 +104,7 @@ layout: page которой представлены ниже. - + ``` diff --git a/docs/ru/reference/frontmatter-config.md b/docs/ru/reference/frontmatter-config.md index e16ed837..70151fd7 100644 --- a/docs/ru/reference/frontmatter-config.md +++ b/docs/ru/reference/frontmatter-config.md @@ -21,7 +21,7 @@ editLink: true {{ $frontmatter.title }} ``` -## title {#title} +## title - Тип: `string` @@ -33,7 +33,7 @@ title: VitePress --- ``` -## titleTemplate {#titletemplate} +## titleTemplate - Тип: `string | boolean` @@ -46,7 +46,7 @@ titleTemplate: Генератор статических сайтов на ос --- ``` -## description {#description} +## description - Тип: `string` @@ -58,7 +58,7 @@ description: VitePress --- ``` -## head {#head} +## head - Тип: `HeadConfig[]` @@ -86,7 +86,7 @@ type HeadConfig = Следующие параметры метаданных применимы только при использовании темы по умолчанию. -### layout {#layout} +### layout - Тип: `doc | home | page` - По умолчанию: `doc` @@ -103,15 +103,15 @@ layout: doc --- ``` -### hero {#hero} +### hero Определяет содержимое секции `hero`, когда `layout` имеет значение `home`. Подробнее в главе [Тема по умолчанию: Главная страница](./default-theme-home-page). -### features {#features} +### features Определяет элементы для отображения в секции `features`, когда `layout` имеет значение `home`. Подробнее в главе [Тема по умолчанию: Главная страница](./default-theme-home-page). -### navbar {#navbar} +### navbar - Тип: `boolean` - По умолчанию: `true` @@ -124,7 +124,7 @@ navbar: false --- ``` -### sidebar {#sidebar} +### sidebar - Тип: `boolean` - По умолчанию: `true` @@ -137,7 +137,7 @@ sidebar: false --- ``` -### aside {#aside} +### aside - Тип: `boolean | 'left'` - По умолчанию: `true` @@ -154,7 +154,7 @@ aside: false --- ``` -### outline {#outline} +### outline - Тип: `number | [number, number] | 'deep' | false` - По умолчанию: `2` @@ -167,7 +167,7 @@ outline: [2, 4] --- ``` -### lastUpdated {#lastupdated} +### lastUpdated - Тип: `boolean | Date` - По умолчанию: `true` @@ -180,7 +180,7 @@ lastUpdated: false --- ``` -### editLink {#editlink} +### editLink - Тип: `boolean` - По умолчанию: `true` @@ -193,7 +193,7 @@ editLink: false --- ``` -### footer {#footer} +### footer - Тип: `boolean` - По умолчанию: `true` @@ -206,7 +206,7 @@ footer: false --- ``` -### pageClass {#pageclass} +### pageClass - Тип: `string` @@ -225,3 +225,16 @@ pageClass: custom-page-class /* стили для конкретной страницы */ } ``` + +### isHome + +- Тип: `boolean` + +Стандартная тема полагается на проверки типа `frontmatter.layout === 'home'`, чтобы определить, является ли текущая страница домашней (главной).\ +Это полезно, когда вы хотите принудительно показывать элементы домашней страницы в пользовательском макете. + +```yaml +--- +isHome: true +--- +``` diff --git a/docs/ru/reference/site-config.md b/docs/ru/reference/site-config.md index 27a72060..bc6a829f 100644 --- a/docs/ru/reference/site-config.md +++ b/docs/ru/reference/site-config.md @@ -10,7 +10,7 @@ outline: deep ### Разрешение конфигурации {#config-resolution} -Файл конфигурации всегда разрешается из `/.vitepress/config.[ext]`, где `` — это корень вашего [проекта](../guide/routing#root-and-source-directory) VitePress, а `[ext]` — одно из поддерживаемых расширений файла. TypeScript поддерживается из коробки. Поддерживаемые расширения включают `.js`, `.ts`, `.mjs` и `.mts`. +Конфигурация всегда считывается из файла `/.vitepress/config.[ext]`, где `` — это корень вашего [проекта](../guide/routing#root-and-source-directory) VitePress, а `[ext]` — одно из поддерживаемых расширений файла. TypeScript поддерживается из коробки. Поддерживаемые расширения включают `.js`, `.ts`, `.mjs` и `.mts`. В файлах конфигурации рекомендуется использовать синтаксис ES-модулей. Файл конфигурации должен по умолчанию экспортировать объект: @@ -24,7 +24,7 @@ export default { } ``` -:::details Динамическая (асинхронная) конфигурация +::: details Динамическая (асинхронная) конфигурация Если вам нужно генерировать конфигурацию динамически, вы также можете экспортировать функцию по умолчанию. Например: @@ -458,7 +458,7 @@ export default { ### ignoreDeadLinks {#ignoredeadlinks} -- Тип: `boolean | 'localhostLinks' | (string | RegExp | ((link: string) => boolean))[]` +- Тип: `boolean | 'localhostLinks' | (string | RegExp | ((link: string, source: string) => boolean))[]` - По умолчанию: `false` Если установлено значение `true`, VitePress не будет завершать сборку из-за неработающих ссылок. diff --git a/docs/.vitepress/config/zh.ts b/docs/zh/config.ts similarity index 68% rename from docs/.vitepress/config/zh.ts rename to docs/zh/config.ts index e9d5fbcd..f6bbdf02 100644 --- a/docs/.vitepress/config/zh.ts +++ b/docs/zh/config.ts @@ -1,16 +1,17 @@ import { createRequire } from 'module' -import { defineConfig, type DefaultTheme } from 'vitepress' +import { defineAdditionalConfig, type DefaultTheme } from 'vitepress' const require = createRequire(import.meta.url) const pkg = require('vitepress/package.json') -export const zh = defineConfig({ - lang: 'zh-Hans', +export default defineAdditionalConfig({ description: '由 Vite 和 Vue 驱动的静态站点生成器', themeConfig: { nav: nav(), + search: { options: searchOptions() }, + sidebar: { '/zh/guide/': { base: '/zh/guide/', items: sidebarGuide() }, '/zh/reference/': { base: '/zh/reference/', items: sidebarReference() } @@ -23,7 +24,7 @@ export const zh = defineConfig({ footer: { message: '基于 MIT 许可发布', - copyright: `版权所有 © 2019-${new Date().getFullYear()} 尤雨溪` + copyright: '版权所有 © 2019-至今 尤雨溪' }, docFooter: { @@ -36,11 +37,15 @@ export const zh = defineConfig({ }, lastUpdated: { - text: '最后更新于', - formatOptions: { - dateStyle: 'short', - timeStyle: 'medium' - } + text: '最后更新于' + }, + + notFound: { + title: '页面未找到', + quote: + '但如果你不改变方向,并且继续寻找,你可能最终会到达你所前往的地方。', + linkLabel: '前往首页', + linkText: '带我回首页' }, langMenuLabel: '多语言', @@ -68,6 +73,10 @@ function nav(): DefaultTheme.NavItem[] { { text: pkg.version, items: [ + { + text: '1.6.4', + link: 'https://vuejs.github.io/vitepress/v1/zh/' + }, { text: '更新日志', link: 'https://github.com/vuejs/vitepress/blob/main/CHANGELOG.md' @@ -160,8 +169,8 @@ function sidebarReference(): DefaultTheme.SidebarItem[] { ] } -export const search: DefaultTheme.AlgoliaSearchOptions['locales'] = { - zh: { +function searchOptions(): Partial { + return { placeholder: '搜索文档', translations: { button: { @@ -170,10 +179,16 @@ export const search: DefaultTheme.AlgoliaSearchOptions['locales'] = { }, modal: { searchBox: { - resetButtonTitle: '清除查询条件', - resetButtonAriaLabel: '清除查询条件', - cancelButtonText: '取消', - cancelButtonAriaLabel: '取消' + clearButtonTitle: '清除查询条件', + clearButtonAriaLabel: '清除查询条件', + closeButtonText: '关闭', + closeButtonAriaLabel: '关闭', + placeholderText: '搜索文档', + placeholderTextAskAi: '向 AI 提问:', + placeholderTextAskAiStreaming: '回答中...', + searchInputLabel: '搜索', + backToKeywordSearchButtonText: '返回关键字搜索', + backToKeywordSearchButtonAriaLabel: '返回关键字搜索' }, startScreen: { recentSearchesTitle: '搜索历史', @@ -181,23 +196,49 @@ export const search: DefaultTheme.AlgoliaSearchOptions['locales'] = { saveRecentSearchButtonTitle: '保存至搜索历史', removeRecentSearchButtonTitle: '从搜索历史中移除', favoriteSearchesTitle: '收藏', - removeFavoriteSearchButtonTitle: '从收藏中移除' + removeFavoriteSearchButtonTitle: '从收藏中移除', + recentConversationsTitle: '最近的对话', + removeRecentConversationButtonTitle: '从历史记录中删除对话' }, errorScreen: { titleText: '无法获取结果', helpText: '你可能需要检查你的网络连接' }, - footer: { - selectText: '选择', - navigateText: '切换', - closeText: '关闭', - searchByText: '搜索提供者' - }, noResultsScreen: { noResultsText: '无法找到相关结果', suggestedQueryText: '你可以尝试查询', reportMissingResultsText: '你认为该查询应该有结果?', reportMissingResultsLinkText: '点击反馈' + }, + resultsScreen: { + askAiPlaceholder: '向 AI 提问: ' + }, + askAiScreen: { + disclaimerText: '答案由 AI 生成,可能不准确,请自行验证。', + relatedSourcesText: '相关来源', + thinkingText: '思考中...', + copyButtonText: '复制', + copyButtonCopiedText: '已复制!', + copyButtonTitle: '复制', + likeButtonTitle: '赞', + dislikeButtonTitle: '踩', + thanksForFeedbackText: '感谢你的反馈!', + preToolCallText: '搜索中...', + duringToolCallText: '搜索 ', + afterToolCallText: '已搜索', + aggregatedToolCallText: '已搜索' + }, + footer: { + selectText: '选择', + submitQuestionText: '提交问题', + selectKeyAriaLabel: 'Enter 键', + navigateText: '切换', + navigateUpKeyAriaLabel: '向上箭头', + navigateDownKeyAriaLabel: '向下箭头', + closeText: '关闭', + backToSearchText: '返回搜索', + closeKeyAriaLabel: 'Esc 键', + poweredByText: '搜索提供者' } } } diff --git a/docs/zh/guide/deploy.md b/docs/zh/guide/deploy.md index db68276c..54ed13d4 100644 --- a/docs/zh/guide/deploy.md +++ b/docs/zh/guide/deploy.md @@ -111,7 +111,7 @@ Cache-Control: max-age=31536000,immutable - **构建命令:** `npm run docs:build` - **输出目录:** `docs/.vitepress/dist` -- **node 版本:** `18` (或更高版本) +- **node 版本:** `20` (或更高版本) ::: warning 不要为 HTML 代码启用 _Auto Minify_ 等选项。它将从输出中删除对 Vue 有意义的注释。如果被删除,你可能会看到激活不匹配错误。 @@ -163,7 +163,7 @@ Cache-Control: max-age=31536000,immutable - name: Setup Node uses: actions/setup-node@v4 with: - node-version: 20 + node-version: 22 cache: npm # 或 pnpm / yarn - name: Setup Pages uses: actions/configure-pages@v4 diff --git a/docs/zh/guide/extending-default-theme.md b/docs/zh/guide/extending-default-theme.md index a40613f7..a23cebd1 100644 --- a/docs/zh/guide/extending-default-theme.md +++ b/docs/zh/guide/extending-default-theme.md @@ -14,7 +14,7 @@ VitePress 默认的主题已经针对文档进行了优化,并且可以进行 这些高级自定义配置将需要使用自定义主题来“拓展”默认主题。 -:::tip +::: tip 在继续之前,请确保首先阅读[自定义主题](./custom-theme)以了解其工作原理。 ::: @@ -70,7 +70,7 @@ export default DefaultTheme export default { transformHead({ assets }) { // 相应地调整正则表达式以匹配字体 - const myFontFile = assets.find(file => /font-name\.\w+\.woff2/) + const myFontFile = assets.find(file => /font-name\.[\w-]+\.woff2/.test(file)) if (myFontFile) { return [ [ @@ -251,6 +251,7 @@ provide('toggle-appearance', async ({ clientX: x, clientY: y }: MouseEvent) => { { duration: 300, easing: 'ease-in', + fill: 'forwards', pseudoElement: `::view-transition-${isDark.value ? 'old' : 'new'}(root)` } ) @@ -288,7 +289,7 @@ provide('toggle-appearance', async ({ clientX: x, clientY: y }: MouseEvent) => { ``` -Result (**warning!**: flashing colors, sudden movements, bright lights): +结果(**注意!**:画面闪烁、快速闪现、强光刺激):
Demo diff --git a/docs/zh/guide/getting-started.md b/docs/zh/guide/getting-started.md index 2d6453c9..183b32df 100644 --- a/docs/zh/guide/getting-started.md +++ b/docs/zh/guide/getting-started.md @@ -18,39 +18,19 @@ VitePress 可以单独使用,也可以安装到现有项目中。在这两种 ::: code-group ```sh [npm] -$ npm add -D vitepress +$ npm add -D vitepress@next ``` ```sh [pnpm] -$ pnpm add -D vitepress +$ pnpm add -D vitepress@next ``` ```sh [yarn] -$ yarn add -D vitepress -``` - -```sh [yarn (pnp)] -$ yarn add -D vitepress vue +$ yarn add -D vitepress@next vue ``` ```sh [bun] -$ bun add -D vitepress -``` - -::: - -::: details 遇到了 missing peer deps 警告? -如果使用 PNPM,会注意到对 `@docsearch/js` 的 missing peer deps 警告。这不会影响 VitePress 运行。如果希望禁止显示此警告,请将以下内容添加到 `package.json`: - -```json -"pnpm": { - "peerDependencyRules": { - "ignoreMissing": [ - "@algolia/client-search", - "search-insights" - ] - } -} +$ bun add -D vitepress@next ``` ::: @@ -89,7 +69,7 @@ $ bun vitepress init <<< @/snippets/init.ansi -:::tip Vue 作为 peer dependency +::: tip Vue 作为 peer dependency 如果打算使用 Vue 组件或 API 进行自定义,还应该明确地将 `vue` 安装为 dependency。 ::: @@ -112,7 +92,7 @@ $ bun vitepress init `docs` 目录作为 VitePress 站点的项目**根目录**。`.vitepress` 目录是 VitePress 配置文件、开发服务器缓存、构建输出和可选主题自定义代码的位置。 -:::tip +::: tip 默认情况下,VitePress 将其开发服务器缓存存储在 `.vitepress/cache` 中,并将生产构建输出存储在 `.vitepress/dist` 中。如果使用 Git,应该将它们添加到 `.gitignore` 文件中。也可以手动[配置](../reference/site-config#outdir)这些位置。 ::: diff --git a/docs/zh/guide/markdown.md b/docs/zh/guide/markdown.md index 308c49df..a401774c 100644 --- a/docs/zh/guide/markdown.md +++ b/docs/zh/guide/markdown.md @@ -255,11 +255,11 @@ Wraps in a `
` } ``` - 它在底层使用 [`postcss-prefix-selector`](https://github.com/postcss/postcss-load-config)。你可以像这样传递它的选项: + 你可以像这样传递它的选项: ```js postcssIsolateStyles({ - includeFiles: [/vp-doc\.css/] // 默认为 /base\.css/ + includeFiles: [/custom\.css/] // 默认为 [/vp-doc\.css/, /base\.css/] }) ``` @@ -343,7 +343,7 @@ export default { 在 Shiki 的代码仓库中,可以找到[合法的编程语言列表](https://shiki.style/languages)。 -还可以全局配置中自定义语法高亮主题。有关详细信息,参见 [`markdown` 选项](../reference/site-config#markdown)得到更多信息。 +还可以在全局配置中自定义语法高亮主题、配置语言别名和自定义语言标签。有关详细信息,参见 [`markdown` 选项](../reference/site-config#markdown)得到更多信息。 ## 在代码块中实现行高亮 {#line-highlighting-in-code-blocks} diff --git a/docs/zh/guide/routing.md b/docs/zh/guide/routing.md index 56332317..c48722ad 100644 --- a/docs/zh/guide/routing.md +++ b/docs/zh/guide/routing.md @@ -123,7 +123,7 @@ src/getting-started.md --> /getting-started.html ## 生成简洁的 URL {#generating-clean-url} -:::warning 需要服务器支持 +::: warning 需要服务器支持 要使 VitePress 提供简洁 URL,需要服务器端支持。 ::: diff --git a/docs/zh/guide/using-vue.md b/docs/zh/guide/using-vue.md index be181fee..f9acaad4 100644 --- a/docs/zh/guide/using-vue.md +++ b/docs/zh/guide/using-vue.md @@ -67,7 +67,7 @@ The count is: {{ count }} ``` -:::warning 避免在 Markdown 中使用 ` diff --git a/src/client/theme-default/components/VPNavBarSearchButton.vue b/src/client/theme-default/components/VPNavBarSearchButton.vue index 7a6e16f9..ee371028 100644 --- a/src/client/theme-default/components/VPNavBarSearchButton.vue +++ b/src/client/theme-default/components/VPNavBarSearchButton.vue @@ -2,7 +2,7 @@ import type { ButtonTranslations } from '../../../../types/local-search' import { createSearchTranslate } from '../support/translation' -// Button-Translations +// button translations const defaultTranslations: { button: ButtonTranslations } = { button: { buttonText: 'Search', @@ -14,200 +14,134 @@ const translate = createSearchTranslate(defaultTranslations) diff --git a/src/client/theme-default/components/VPNavBarTitle.vue b/src/client/theme-default/components/VPNavBarTitle.vue index 1e1ef3d7..9679f8a5 100644 --- a/src/client/theme-default/components/VPNavBarTitle.vue +++ b/src/client/theme-default/components/VPNavBarTitle.vue @@ -2,12 +2,12 @@ import { computed } from 'vue' import { useData } from '../composables/data' import { useLangs } from '../composables/langs' -import { useSidebar } from '../composables/sidebar' +import { useLayout } from '../composables/layout' import { normalizeLink } from '../support/utils' import VPImage from './VPImage.vue' const { site, theme } = useData() -const { hasSidebar } = useSidebar() +const { hasSidebar } = useLayout() const { currentLang } = useLangs() const link = computed(() => @@ -34,8 +34,8 @@ const target = computed(() =>
diff --git a/src/client/theme-default/components/VPNavScreenMenu.vue b/src/client/theme-default/components/VPNavScreenMenu.vue index d88bb6f5..04716429 100644 --- a/src/client/theme-default/components/VPNavScreenMenu.vue +++ b/src/client/theme-default/components/VPNavScreenMenu.vue @@ -9,7 +9,7 @@ const { theme } = useData()