diff --git a/.github/workflows/cr.yml b/.github/workflows/cr.yml index 7dd5c4c78..7cc01dbb9 100644 --- a/.github/workflows/cr.yml +++ b/.github/workflows/cr.yml @@ -38,11 +38,11 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 - - uses: pnpm/action-setup@v3 - - uses: actions/setup-node@v4 + - uses: actions/checkout@v5 + - uses: pnpm/action-setup@v4 + - uses: actions/setup-node@v6 with: - node-version: 22 + node-version: 24 cache: pnpm - run: pnpm install - run: pnpm build diff --git a/.github/workflows/release-tag.yml b/.github/workflows/release-tag.yml index 84a034870..1c6750008 100644 --- a/.github/workflows/release-tag.yml +++ b/.github/workflows/release-tag.yml @@ -12,7 +12,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Create Release for Tag id: release_tag diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml index f5826155d..dd47c33f4 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 51d3fffe8..a89cc38cd 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -18,22 +18,22 @@ jobs: strategy: matrix: os: [ubuntu-latest] - node_version: [20, 22, latest] + node_version: [20, 22, 24, latest] include: - os: windows-latest - node_version: 22 + node_version: 24 runs-on: ${{ matrix.os }} steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Install pnpm - uses: pnpm/action-setup@v3 + uses: pnpm/action-setup@v4 - name: Set node version to ${{ matrix.node_version }} - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 with: node-version: ${{ matrix.node_version }} cache: pnpm diff --git a/.npmrc b/.npmrc deleted file mode 100644 index ab9530723..000000000 --- a/.npmrc +++ /dev/null @@ -1,2 +0,0 @@ -shell-emulator=true -auto-install-peers=false diff --git a/CHANGELOG.md b/CHANGELOG.md index 756e4b5ec..c11088337 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,142 @@ -# [2.0.0-alpha.7](https://github.com/vuejs/vitepress/compare/v2.0.0-alpha.6...v2.0.0-alpha.7) (2025-06-24) +## [2.0.0-alpha.16](https://github.com/vuejs/vitepress/compare/v2.0.0-alpha.15...v2.0.0-alpha.16) (2026-01-31) + +### Bug Fixes + +- always log error when failed to fetch page ([66cf64e](https://github.com/vuejs/vitepress/commit/66cf64e6d127dd8473e582d11e1133acda6c3bc8)) +- **theme:** add fallback for `heroImageSlotExists` ([#5076](https://github.com/vuejs/vitepress/issues/5076)) ([f119b18](https://github.com/vuejs/vitepress/commit/f119b18e39b545f39e29358913fe9ed1fd69bc55)) +- **theme:** align badges in h1 and h2 ([#5087](https://github.com/vuejs/vitepress/issues/5087)) (closes [#5063](https://github.com/vuejs/vitepress/issues/5063)) ([b200865](https://github.com/vuejs/vitepress/commit/b2008654ffaf0d8f8c425e88592e9ed2f8791506)) +- **theme:** highlight active link in mobile nav menu ([#5086](https://github.com/vuejs/vitepress/issues/5086)) (closes [#5068](https://github.com/vuejs/vitepress/issues/5068), closes [#5074](https://github.com/vuejs/vitepress/issues/5074)) ([923aa90](https://github.com/vuejs/vitepress/commit/923aa902523739bfb9d77aed376ebc73c32eeb33)) +- **theme:** overflow clip is buggy on safari ([8ed6ea0](https://github.com/vuejs/vitepress/commit/8ed6ea048cb49256e3302de2de0edfbe635afd32)), closes [#5050](https://github.com/vuejs/vitepress/issues/5050) [#5039](https://github.com/vuejs/vitepress/issues/5039) [#5027](https://github.com/vuejs/vitepress/issues/5027) +- **theme:** remove margin between code groups and blocks in markdown containers ([a28e171](https://github.com/vuejs/vitepress/commit/a28e171604605713a221d0eb2bbdce211930d94f)), closes [#5099](https://github.com/vuejs/vitepress/issues/5099) + +### Features + +- **theme:** upgrade DocSearch to 4.5 with sidepanel ([#5092](https://github.com/vuejs/vitepress/issues/5092)) ([0d646a6](https://github.com/vuejs/vitepress/commit/0d646a66cd44e97adef516a6a36e03365f179906)) +- **theme:** use `@layer __vitepress_base` to wrap the styles in base.css ([#4905](https://github.com/vuejs/vitepress/issues/4905)) ([f8d8c0d](https://github.com/vuejs/vitepress/commit/f8d8c0d712fba4728c750e1f44c5ba9596979ba1)) + +## [2.0.0-alpha.15](https://github.com/vuejs/vitepress/compare/v2.0.0-alpha.14...v2.0.0-alpha.15) (2025-11-22) + +### Bug Fixes + +- **theme:** navbar overflowing on mobile devices ([06f0e1a](https://github.com/vuejs/vitepress/commit/06f0e1a5c92e36d86fd2e037c335af04d75384e7)), closes [#5039](https://github.com/vuejs/vitepress/issues/5039) + +## [2.0.0-alpha.14](https://github.com/vuejs/vitepress/compare/v2.0.0-alpha.13...v2.0.0-alpha.14) (2025-11-21) + +### Bug Fixes + +- log dead links in dev mode too ([179ee62](https://github.com/vuejs/vitepress/commit/179ee621d99b3c14e2e098e3b786465cbeaeab9a)), closes [#4419](https://github.com/vuejs/vitepress/issues/4419) +- **theme:** sidebar alignment when scrollbar is there on page ([0ee7158](https://github.com/vuejs/vitepress/commit/0ee71588de2b1691b1a9287aa1daa729197fd3ca)), closes [#5027](https://github.com/vuejs/vitepress/issues/5027) + +### Features + +- **client:** emit `vitepress:codeGroupTabActivate` custom event when a code group tab is activated ([dfb02a4](https://github.com/vuejs/vitepress/commit/dfb02a479f19afbee9e292b15c3c2beef271e57f)), closes [#5023](https://github.com/vuejs/vitepress/issues/5023) + +## [2.0.0-alpha.13](https://github.com/vuejs/vitepress/compare/v2.0.0-alpha.12...v2.0.0-alpha.13) (2025-11-13) + +### Bug Fixes + +- **client,a11y:** improve focus handling and scrolling behavior in router ([#4943](https://github.com/vuejs/vitepress/issues/4943)) ([d46107f](https://github.com/vuejs/vitepress/commit/d46107fa254d662d297b1362aa0d3b898ef96e2c)) +- disable markdown-it-attrs for fenced code blocks ([0899618](https://github.com/vuejs/vitepress/commit/089961855653f862b71747e8179ef2647e06d626)) +- git log parsing when there are empty commits in history ([#4965](https://github.com/vuejs/vitepress/issues/4965)) ([612c458](https://github.com/vuejs/vitepress/commit/612c45895df79a0c0e87ca040564bfe88ce04f62)) +- print full path in dead links check ([2b77fb3](https://github.com/vuejs/vitepress/commit/2b77fb3a72058129edbaddd3c6f0f6ee24f983d5)), closes [#4919](https://github.com/vuejs/vitepress/issues/4919) +- rename `markdown.cjkFriendly` to `markdown.cjkFriendlyEmphasis` ([bce0b53](https://github.com/vuejs/vitepress/commit/bce0b53659fa3a57b2ed8431a0861939dadd118a)), closes [#4952](https://github.com/vuejs/vitepress/issues/4952) +- respect markdown.cache = false on build too ([6d7422f](https://github.com/vuejs/vitepress/commit/6d7422f8fa321c641b1d5be3fa0c382400a2b78f)) +- simplify lang extraction logic; use markdown-it plugins in type-safe manner; bump deps ([4e548f5](https://github.com/vuejs/vitepress/commit/4e548f542469a366f327cdef1530bdb1a31542ad)) +- **theme:** add lang and dir attributes to language picker ([f0b29d7](https://github.com/vuejs/vitepress/commit/f0b29d7ef32a33f61c355d19561176411ede4b48)) +- **theme:** adjust margin of code blocks inside containers ([82fac5d](https://github.com/vuejs/vitepress/commit/82fac5d22c9e2b28d18dafcd458741a4b4d7a86b)), closes [#4921](https://github.com/vuejs/vitepress/issues/4921) +- **theme:** avoid use of `:where` in selector list for now ([c2eaccd](https://github.com/vuejs/vitepress/commit/c2eaccd0d2109a6c64cee9fe615e48daaf4eda0e)), closes [#4923](https://github.com/vuejs/vitepress/issues/4923) +- **theme:** disable whitespace wrapping for VPBadge ([#4968](https://github.com/vuejs/vitepress/issues/4968)) ([113d230](https://github.com/vuejs/vitepress/commit/113d2304784586028d9733036ccb585374731397)) +- **theme:** use nav height css var for curtain top in sidebar ([#4993](https://github.com/vuejs/vitepress/issues/4993)) ([be260fd](https://github.com/vuejs/vitepress/commit/be260fda6efc1d6c4b56219d7a17a19ab7a4ba76)) + +### Features + +- export cacheAllGitTimestamps and getGitTimestamp ([31d87e2](https://github.com/vuejs/vitepress/commit/31d87e27387ebdceb22c047cc5f821761276d5f7)) +- **i18n,a11y:** change last update logic ([#4935](https://github.com/vuejs/vitepress/issues/4935)) ([187bf25](https://github.com/vuejs/vitepress/commit/187bf250e6496554fca0b070a5aba55484f7fc0b)) +- **markdown:** support custom display-name for fenced code blocks ([#4960](https://github.com/vuejs/vitepress/issues/4960)) ([3d61619](https://github.com/vuejs/vitepress/commit/3d61619ec0f0458c7ae04e7954b72a8e2ff399c0)) +- prevent `$` symbol selection in shell code ([#5025](https://github.com/vuejs/vitepress/issues/5025)) ([bf2715e](https://github.com/vuejs/vitepress/commit/bf2715ed67f290726fc6d4c85c203ca8f74cc907)) +- **theme:** allow passing functions for nav links ([#4963](https://github.com/vuejs/vitepress/issues/4963)) ([34cfa91](https://github.com/vuejs/vitepress/commit/34cfa91b6f14d8adfaa2d3c9f3eb6ad8b889ef1c)) + +### Performance Improvements + +- make a single git call for timestamps instead of calling it for each file ([#4958](https://github.com/vuejs/vitepress/issues/4958)) ([6dfcdd3](https://github.com/vuejs/vitepress/commit/6dfcdd3fe8dc73e7b4ad7783df9530dedac1f6bd)) + +### BREAKING CHANGES + +- `markdown-it-attrs` is disabled for fenced code blocks. For most users no change is required. If you want to add classes to code blocks, do it using shiki transformers instead. +- Rename `cjkFriendly` to `cjkFriendlyEmphasis` in your vitepress config. Most people should be unaffected unless they want to disable the CJK emphasis behavior added v2.0.0-alpha.12. + +## [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 @@ -20,7 +158,7 @@ - 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) +## [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 diff --git a/README.md b/README.md index aedcd4876..c6533b30c 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # 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)](https://www.npmjs.com/package/vitepress) +[![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/data-loading/data.test.ts b/__tests__/e2e/data-loading/data.test.ts index fafc403ac..21cfa061c 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 12a8bc32c..a1cb6fefd 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__/e2e/local-search/local-search.test.ts b/__tests__/e2e/local-search/local-search.test.ts index 492136b68..9496dc6bf 100644 --- a/__tests__/e2e/local-search/local-search.test.ts +++ b/__tests__/e2e/local-search/local-search.test.ts @@ -4,7 +4,7 @@ describe('local search', () => { }) test('exclude content from search results', async () => { - await page.locator('#local-search button').click() + await page.locator('.VPNavBarSearchButton').click() const input = await page.waitForSelector('input#localsearch-input') await input.type('local') diff --git a/__tests__/unit/client/theme-default/support/docsearch.test.ts b/__tests__/unit/client/theme-default/support/docsearch.test.ts new file mode 100644 index 000000000..4da8f113f --- /dev/null +++ b/__tests__/unit/client/theme-default/support/docsearch.test.ts @@ -0,0 +1,196 @@ +import { + buildAskAiConfig, + hasAskAi, + hasKeywordSearch, + mergeLangFacetFilters, + validateCredentials +} from 'client/theme-default/support/docsearch' + +describe('client/theme-default/support/docsearch', () => { + describe('mergeLangFacetFilters', () => { + test('adds a lang facet filter when none is provided', () => { + expect(mergeLangFacetFilters(undefined, 'en')).toEqual(['lang:en']) + }) + + test('replaces existing lang facet filters', () => { + expect(mergeLangFacetFilters('lang:fr', 'en')).toEqual(['lang:en']) + expect(mergeLangFacetFilters(['foo', 'lang:fr'], 'en')).toEqual([ + 'foo', + 'lang:en' + ]) + }) + + test('handles nested facet filters (OR conditions)', () => { + expect( + mergeLangFacetFilters([['tag:foo', 'tag:bar'], 'lang:fr'], 'en') + ).toEqual([['tag:foo', 'tag:bar'], 'lang:en']) + }) + + test('removes empty nested arrays', () => { + expect(mergeLangFacetFilters([['lang:fr'], 'other'], 'en')).toEqual([ + 'other', + 'lang:en' + ]) + }) + + test('handles multiple lang filters in nested arrays', () => { + expect( + mergeLangFacetFilters([['lang:fr', 'tag:foo'], 'bar'], 'en') + ).toEqual([['tag:foo'], 'bar', 'lang:en']) + }) + }) + + describe('hasKeywordSearch', () => { + test('returns true when all credentials are provided', () => { + expect( + hasKeywordSearch({ + appId: 'app', + apiKey: 'key', + indexName: 'index' + }) + ).toBe(true) + }) + + test('returns false when any credential is missing', () => { + expect( + hasKeywordSearch({ + appId: undefined, + apiKey: 'key', + indexName: 'index' + }) + ).toBe(false) + expect( + hasKeywordSearch({ + appId: 'app', + apiKey: undefined, + indexName: 'index' + }) + ).toBe(false) + expect( + hasKeywordSearch({ + appId: 'app', + apiKey: 'key', + indexName: undefined + }) + ).toBe(false) + }) + }) + + describe('hasAskAi', () => { + test('returns true for valid string assistantId', () => { + expect(hasAskAi('assistant123')).toBe(true) + }) + + test('returns false for empty string assistantId', () => { + expect(hasAskAi('')).toBe(false) + }) + + test('returns true for object with assistantId', () => { + expect(hasAskAi({ assistantId: 'assistant123' } as any)).toBe(true) + }) + + test('returns false for object without assistantId', () => { + expect(hasAskAi({ assistantId: null } as any)).toBe(false) + expect(hasAskAi({} as any)).toBe(false) + }) + + test('returns false for undefined', () => { + expect(hasAskAi(undefined)).toBe(false) + }) + }) + + describe('validateCredentials', () => { + test('validates complete credentials', () => { + const result = validateCredentials({ + appId: 'app', + apiKey: 'key', + indexName: 'index' + }) + expect(result.valid).toBe(true) + expect(result.appId).toBe('app') + expect(result.apiKey).toBe('key') + expect(result.indexName).toBe('index') + }) + + test('invalidates incomplete credentials', () => { + expect( + validateCredentials({ + appId: undefined, + apiKey: 'key', + indexName: 'index' + }).valid + ).toBe(false) + }) + }) + + describe('buildAskAiConfig', () => { + test('builds config from string assistantId', () => { + const result = buildAskAiConfig( + 'assistant123', + { + appId: 'app', + apiKey: 'key', + indexName: 'index' + } as any, + 'en' + ) + expect(result.assistantId).toBe('assistant123') + expect(result.appId).toBe('app') + expect(result.apiKey).toBe('key') + expect(result.indexName).toBe('index') + }) + + test('builds config from object with overrides', () => { + const result = buildAskAiConfig( + { + assistantId: 'assistant123', + appId: 'custom-app', + apiKey: 'custom-key', + indexName: 'custom-index' + } as any, + { + appId: 'default-app', + apiKey: 'default-key', + indexName: 'default-index' + } as any, + 'en' + ) + expect(result.assistantId).toBe('assistant123') + expect(result.appId).toBe('custom-app') + expect(result.apiKey).toBe('custom-key') + expect(result.indexName).toBe('custom-index') + }) + + test('merges facet filters with lang', () => { + const result = buildAskAiConfig( + { + assistantId: 'assistant123', + searchParameters: { + facetFilters: ['tag:docs'] + } + } as any, + { + appId: 'app', + apiKey: 'key', + indexName: 'index' + } as any, + 'en' + ) + expect(result.searchParameters?.facetFilters).toContain('tag:docs') + expect(result.searchParameters?.facetFilters).toContain('lang:en') + }) + + test('always adds lang facet filter to searchParameters', () => { + const result = buildAskAiConfig( + 'assistant123', + { + appId: 'app', + apiKey: 'key', + indexName: 'index' + } as any, + 'en' + ) + expect(result.searchParameters?.facetFilters).toEqual(['lang:en']) + }) + }) +}) 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 000000000..c781b64c0 --- /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 000000000..609a4463a --- /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/client.d.ts b/client.d.ts index 440251f70..32fcebe2f 100644 --- a/client.d.ts +++ b/client.d.ts @@ -3,3 +3,12 @@ /// export * from './dist/client/index.js' + +declare global { + interface WindowEventMap { + 'vitepress:codeGroupTabActivate': Event & { + /** code block element that was activated */ + detail: Element + } + } +} diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts index 1bf4ab948..4c65ec7e8 100644 --- a/docs/.vitepress/config.ts +++ b/docs/.vitepress/config.ts @@ -26,10 +26,13 @@ export default defineConfig({ markdown: { math: true, codeTransformers: [ - // We use `[!!code` in demo to prevent transformation, here we revert it back. + // We use `[!!code` and `@@include` in demo to prevent transformation, + // here we revert it back. { postprocess(code) { - return code.replace(/\[\!\!code/g, '[!code') + return code + .replaceAll('[!!code', '[!code') + .replaceAll('@@include', '@include') } } ], @@ -52,6 +55,8 @@ export default defineConfig({ return 'Скопировать код' case 'zh': return '复制代码' + case 'ja': + return 'コードをコピー' default: return 'Copy code' } @@ -115,7 +120,11 @@ export default defineConfig({ options: { appId: '8J64VVRP8K', apiKey: '52f578a92b88ad6abde815aae2b0ad7c', - indexName: 'vitepress' + indexName: 'vitepress', + askAi: { + assistantId: 'YaVSonfX5bS8', + sidePanel: true + } } }, @@ -123,13 +132,14 @@ export default defineConfig({ }, locales: { - root: { label: 'English' }, - zh: { label: '简体中文' }, - pt: { label: 'Português' }, - ru: { label: 'Русский' }, - es: { label: 'Español' }, - ko: { label: '한국어' }, - fa: { label: 'فارسی' } + 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: { diff --git a/docs/config.ts b/docs/config.ts index a09a3a67c..8620d955e 100644 --- a/docs/config.ts +++ b/docs/config.ts @@ -5,7 +5,6 @@ const require = createRequire(import.meta.url) const pkg = require('vitepress/package.json') export default defineAdditionalConfig({ - lang: 'en-US', 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 ed6331c1a..7433fbf52 100644 --- a/docs/en/guide/deploy.md +++ b/docs/en/guide/deploy.md @@ -105,7 +105,7 @@ Note: the `vercel.json` file should be placed at the root of your **repository** ## Platform Guides -### Netlify / Vercel / Cloudflare Pages / AWS Amplify / Render +### Netlify / Vercel / Cloudflare Pages / AWS Amplify / Render {#generic} Set up a new project and change these settings using your dashboard: @@ -153,17 +153,17 @@ Don't enable options like _Auto Minify_ for HTML code. It will remove comments f runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: fetch-depth: 0 # Not needed if lastUpdated is not enabled - # - uses: pnpm/action-setup@v3 # Uncomment this block if you're using pnpm + # - uses: pnpm/action-setup@v4 # 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 + uses: actions/setup-node@v6 with: - node-version: 22 + node-version: 24 cache: npm # or pnpm / yarn - name: Setup Pages uses: actions/configure-pages@v4 @@ -221,7 +221,9 @@ Don't enable options like _Auto Minify_ for HTML code. It will remove comments f - main ``` -### Azure Static Web Apps + + +### Azure 1. Follow the [official documentation](https://docs.microsoft.com/en-us/azure/static-web-apps/build-configuration). @@ -231,6 +233,10 @@ Don't enable options like _Auto Minify_ for HTML code. It will remove comments f - **`output_location`**: `docs/.vitepress/dist` - **`app_build_command`**: `npm run docs:build` +### 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). + ### Firebase 1. Create `firebase.json` and `.firebaserc` at the root of your project: @@ -262,14 +268,6 @@ Don't enable options like _Auto Minify_ for HTML code. It will remove comments f firebase deploy ``` -### Surge - -1. After running `npm run docs:build`, run this command to deploy: - - ```sh - npx surge docs/.vitepress/dist - ``` - ### Heroku 1. Follow documentation and guide given in [`heroku-buildpack-static`](https://elements.heroku.com/buildpacks/heroku/heroku-buildpack-static). @@ -282,11 +280,11 @@ Don't enable options like _Auto Minify_ for HTML code. It will remove comments f } ``` -### Edgio +### Hostinger -Refer [Creating and Deploying a VitePress App To Edgio](https://docs.edg.io/guides/vitepress). +You can deploy your VitePress project with [Hostinger](https://www.hostinger.com/web-apps-hosting) by following these [instructions](https://www.hostinger.com/support/how-to-deploy-a-nodejs-website-in-hostinger/). While configuring build settings, choose VitePress as the framework and adjust the root directory to `./docs`. -### Kinsta Static Site Hosting +### Kinsta You can deploy your VitePress website on [Kinsta](https://kinsta.com/static-site-hosting/) by following these [instructions](https://kinsta.com/docs/vitepress-static-site-example/). @@ -294,6 +292,14 @@ 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). +### Surge + +1. After running `npm run docs:build`, run this command to deploy: + + ```sh + npx surge docs/.vitepress/dist + ``` + ### 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 21af5dd77..4d18d8c5f 100644 --- a/docs/en/guide/extending-default-theme.md +++ b/docs/en/guide/extending-default-theme.md @@ -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/en/guide/getting-started.md b/docs/en/guide/getting-started.md index 01b64a1bd..79cb3180d 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 89d826d51..a60f764e3 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 @@ -793,7 +793,7 @@ For example, you can include a relative markdown file using this: ## Basics - + ``` **Part file** (`parts/basics.md`) @@ -829,7 +829,7 @@ It also supports selecting a line range: ## Basics - + ``` **Part file** (`parts/basics.md`) @@ -865,8 +865,8 @@ You can also use a [VS Code region](https://code.visualstudio.com/docs/editor/co ## Basics - - + + ``` **Part file** (`parts/basics.md`) @@ -917,7 +917,7 @@ You can include the `My Base Section` section like this: ```md ## My Extended Section - + ``` **Equivalent code** @@ -941,7 +941,7 @@ Here, `my-base-section` is the generated id of the heading element. In case it's and include it like this: ```md - + ``` ## Math Equations @@ -949,7 +949,7 @@ and include it like this: This is currently opt-in. To enable it, you need to install `markdown-it-mathjax3` and set `markdown.math` to `true` in your config file: ```sh -npm add -D markdown-it-mathjax3 +npm add -D markdown-it-mathjax3@^4 ``` ```ts [.vitepress/config.ts] diff --git a/docs/en/guide/routing.md b/docs/en/guide/routing.md index 1f3569a7c..bacdbf6b5 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 a498d17ec..0a5d76f89 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=/%22vitepress%22:+/+path:/(?:package%7Cdeno)%5C.jsonc?$/+NOT+is:fork+NOT+is:archived&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 61a2b003d..f05e92006 100644 --- a/docs/en/index.md +++ b/docs/en/index.md @@ -4,14 +4,14 @@ layout: home hero: name: VitePress text: Vite & Vue Powered Static Site Generator - tagline: Markdown to Beautiful Docs in Minutes + tagline: Markdown to beautiful docs in minutes 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 @@ -21,7 +21,7 @@ hero: features: - icon: 📝 - title: Focus on Your Content + title: Focus on your content details: Effortlessly create beautiful documentation sites with just markdown. - icon: title: Enjoy the Vite DX @@ -30,6 +30,6 @@ features: title: Customize with Vue details: Use Vue syntax and components directly in markdown, or build custom themes with Vue. - icon: 🚀 - title: Ship Fast Sites + title: Ship fast sites details: Fast initial load with static HTML, fast post-load navigation with client-side routing. --- diff --git a/docs/en/reference/default-theme-config.md b/docs/en/reference/default-theme-config.md index 39c3fcf79..4868cda32 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 diff --git a/docs/en/reference/default-theme-last-updated.md b/docs/en/reference/default-theme-last-updated.md index 556032699..4e62f39dd 100644 --- a/docs/en/reference/default-theme-last-updated.md +++ b/docs/en/reference/default-theme-last-updated.md @@ -11,7 +11,7 @@ To fix this in **GitHub Actions**, use the following in your workflow: ```yaml{4} - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: fetch-depth: 0 ``` diff --git a/docs/en/reference/default-theme-nav.md b/docs/en/reference/default-theme-nav.md index b55a63cb1..f7be114db 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 d647e32ed..d9e00a1d6 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' @@ -29,6 +29,7 @@ Alternatively, you can use [Algolia DocSearch](#algolia-search) or some communit - - - +- ### i18n {#local-search-i18n} @@ -178,7 +179,7 @@ export default defineConfig({ 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 (await md.renderAsync(`# ${env.frontmatter.title}`)) + html return html } } @@ -189,7 +190,7 @@ export default defineConfig({ ## Algolia Search -VitePress supports searching your docs site using [Algolia DocSearch](https://docsearch.algolia.com/docs/what-is-docsearch). Refer their getting started guide. In your `.vitepress/config.ts` you'll need to provide at least the following to make it work: +VitePress supports searching your docs site using [Algolia DocSearch](https://docsearch.algolia.com/docs/what-is-docsearch). Refer to their getting started guide. In your `.vitepress/config.ts` you'll need to provide at least the following to make it work: ```ts import { defineConfig } from 'vitepress' @@ -212,6 +213,19 @@ export default defineConfig({ You can use a config like this to use multilingual search: +
+View full example + +<<< @/snippets/algolia-i18n.ts + +
+ +Refer [official Algolia docs](https://docsearch.algolia.com/docs/api#translations) to learn more about them. To quickly get started, you can also copy the translations used by this site from [our GitHub repo](https://github.com/search?q=repo:vuejs/vitepress+%22function+searchOptions%22&type=code). + +### 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' @@ -223,46 +237,50 @@ export default defineConfig({ appId: '...', apiKey: '...', indexName: '...', - locales: { - zh: { - placeholder: '搜索文档', - translations: { - button: { - buttonText: '搜索文档', - buttonAriaLabel: '搜索文档' - }, - modal: { - searchBox: { - resetButtonTitle: '清除查询条件', - resetButtonAriaLabel: '清除查询条件', - cancelButtonText: '取消', - cancelButtonAriaLabel: '取消' - }, - startScreen: { - recentSearchesTitle: '搜索历史', - noRecentSearchesText: '没有搜索历史', - saveRecentSearchButtonTitle: '保存至搜索历史', - removeRecentSearchButtonTitle: '从搜索历史中移除', - favoriteSearchesTitle: '收藏', - removeFavoriteSearchButtonTitle: '从收藏中移除' - }, - errorScreen: { - titleText: '无法获取结果', - helpText: '你可能需要检查你的网络连接' - }, - footer: { - selectText: '选择', - navigateText: '切换', - closeText: '关闭', - searchByText: '搜索提供者' - }, - noResultsScreen: { - noResultsText: '无法找到相关结果', - suggestedQueryText: '你可以尝试查询', - reportMissingResultsText: '你认为该查询应该有结果?', - reportMissingResultsLinkText: '点击反馈' - } - } + // 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 you want to default to keyword search and do not want to use Ask AI, omit the `askAi` property. +::: + +### Ask AI Side Panel {#ask-ai-side-panel} + +DocSearch v4.5+ supports an optional **Ask AI side panel**. When enabled, it can be opened with **Ctrl/Cmd+I** by default. The [Sidepanel API Reference](https://docsearch.algolia.com/docs/sidepanel/api-reference) contains the full list of options. + +```ts +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + search: { + provider: 'algolia', + options: { + appId: '...', + apiKey: '...', + indexName: '...', + askAi: { + assistantId: 'XXXYYY', + sidePanel: { + panel: { + variant: 'floating', // or 'inline' + side: 'right', + width: '360px', + expandedWidth: '580px', + suggestedQuestions: true } } } @@ -272,112 +290,70 @@ 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. +If you need to disable the keyboard shortcut, use the `keyboardShortcuts` option at the sidepanel root level: -### Crawler Config +```ts +import { defineConfig } from 'vitepress' -Here is an example config based on what this site uses: +export default defineConfig({ + themeConfig: { + search: { + provider: 'algolia', + options: { + appId: '...', + apiKey: '...', + indexName: '...', + askAi: { + assistantId: 'XXXYYY', + sidePanel: { + keyboardShortcuts: { + 'Ctrl/Cmd+I': false + } + } + } + } + } + } +}) +``` + +#### Mode (auto / sidePanel / hybrid / modal) {#ask-ai-mode} + +You can optionally control how VitePress integrates keyword search and Ask AI: + +- `mode: 'auto'` (default): infer `hybrid` when keyword search is configured, otherwise `sidePanel` when Ask AI side panel is configured. +- `mode: 'sidePanel'`: force side panel only (hides the keyword search button). +- `mode: 'hybrid'`: enable keyword search modal + Ask AI side panel (requires keyword search configuration). +- `mode: 'modal'`: keep Ask AI inside the DocSearch modal (even if you configured the side panel). + +#### Ask AI only (no keyword search) {#ask-ai-only} + +If you want to use **Ask AI side panel only**, you can omit top-level keyword search config and provide credentials under `askAi`: ```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 - }) +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + search: { + provider: 'algolia', + options: { + mode: 'sidePanel', + askAi: { + assistantId: 'XXXYYY', + appId: '...', + apiKey: '...', + indexName: '...', + sidePanel: 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' - } } }) ``` + +### Crawler Config + +Here is an example config based on what this site uses: + +<<< @/snippets/algolia-crawler.js diff --git a/docs/en/reference/runtime-api.md b/docs/en/reference/runtime-api.md index d55165f50..ca1f39874 100644 --- a/docs/en/reference/runtime-api.md +++ b/docs/en/reference/runtime-api.md @@ -49,7 +49,7 @@ interface PageData { titleTemplate?: string | boolean description: string relativePath: string - filePath: string, + filePath: string headers: Header[] frontmatter: Record params?: Record diff --git a/docs/en/reference/site-config.md b/docs/en/reference/site-config.md index 8cf5e2647..70df8a317 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: @@ -333,7 +333,7 @@ export default { - Type: `string` - Default: `/` -The base URL the site will be deployed at. You will need to set this if you plan to deploy your site under a sub path, for example, GitHub pages. If you plan to deploy your site to `https://foo.github.io/bar/`, then you should set base to `'/bar/'`. It should always start and end with a slash. +The base URL the site will be deployed at. You will need to set this if you plan to deploy your site under a sub path, for example, GitHub pages. If you plan to deploy your site to `https://foo.github.io/bar/`, then you should set base to `'/bar/'`. It should always start and end with a slash. Relative bases are not supported. The base is automatically prepended to all the URLs that start with / in other options, so you only need to specify it once. @@ -439,7 +439,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/es/config.ts b/docs/es/config.ts index 099edba64..fee383613 100644 --- a/docs/es/config.ts +++ b/docs/es/config.ts @@ -5,8 +5,7 @@ const require = createRequire(import.meta.url) const pkg = require('vitepress/package.json') export default defineAdditionalConfig({ - lang: 'es-CO', - description: 'Generador de Sitios Estaticos desarrollado con Vite y Vue.', + description: 'Generador de Sitios Estáticos desarrollado con Vite y Vue.', themeConfig: { nav: nav(), @@ -25,7 +24,7 @@ export default defineAdditionalConfig({ 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: { @@ -38,7 +37,7 @@ export default defineAdditionalConfig({ }, lastUpdated: { - text: 'Actualizado en' + text: 'Actualizado el' }, notFound: { @@ -46,7 +45,7 @@ export default defineAdditionalConfig({ 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 casa' + linkText: 'Llévame a inicio' }, langMenuLabel: 'Cambiar Idioma', @@ -62,7 +61,7 @@ export default defineAdditionalConfig({ function nav(): DefaultTheme.NavItem[] { return [ { - text: 'Guia', + text: 'Guía', link: '/es/guide/what-is-vitepress', activeMatch: '/es/guide/' }, @@ -74,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' @@ -93,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' } @@ -136,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' } @@ -167,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' } ] } @@ -178,7 +181,6 @@ function sidebarReference(): DefaultTheme.SidebarItem[] { function searchOptions(): Partial { return { - placeholder: 'Buscar documentos', translations: { button: { buttonText: 'Buscar', @@ -186,35 +188,143 @@ function searchOptions(): Partial { }, modal: { searchBox: { - resetButtonTitle: 'Limpiar búsqueda', - resetButtonAriaLabel: 'Limpiar búsqueda', - cancelButtonText: 'Cancelar', - cancelButtonAriaLabel: 'Cancelar' + clearButtonTitle: 'Limpiar', + clearButtonAriaLabel: 'Borrar la consulta', + closeButtonText: 'Cerrar', + closeButtonAriaLabel: 'Cerrar', + placeholderText: 'Buscar en la documentación o preguntar a Ask AI', + placeholderTextAskAi: 'Haz otra pregunta...', + placeholderTextAskAiStreaming: 'Respondiendo...', + searchInputLabel: 'Buscar', + backToKeywordSearchButtonText: + 'Volver a la búsqueda por palabras clave', + backToKeywordSearchButtonAriaLabel: + 'Volver a la búsqueda por palabras clave', + newConversationPlaceholder: 'Haz una pregunta', + conversationHistoryTitle: 'Mi historial de conversaciones', + startNewConversationText: 'Iniciar una nueva conversación', + viewConversationHistoryText: 'Historial de conversaciones', + threadDepthErrorPlaceholder: 'Se alcanzó el límite de conversación' }, - startScreen: { - recentSearchesTitle: 'Historial de búsqueda', - noRecentSearchesText: 'Ninguna búsqueda reciente', - saveRecentSearchButtonTitle: 'Guardar en el historial de búsqueda', - removeRecentSearchButtonTitle: 'Borrar del historial de búsqueda', - favoriteSearchesTitle: 'Favoritos', - removeFavoriteSearchButtonTitle: 'Borrar de favoritos' - }, - errorScreen: { - titleText: 'No fue posible obtener resultados', - helpText: 'Verifique su conexión de red' + newConversation: { + newConversationTitle: '¿Cómo puedo ayudarte hoy?', + newConversationDescription: + 'Busco en tu documentación para ayudarte a encontrar guías de configuración, detalles de funciones y consejos de solución de problemas rápidamente.' }, footer: { selectText: 'Seleccionar', + submitQuestionText: 'Enviar pregunta', + selectKeyAriaLabel: 'Tecla Enter', navigateText: 'Navegar', + navigateUpKeyAriaLabel: 'Flecha arriba', + navigateDownKeyAriaLabel: 'Flecha abajo', closeText: 'Cerrar', - searchByText: 'Busqueda por' + backToSearchText: 'Volver a la búsqueda', + closeKeyAriaLabel: 'Tecla Escape', + poweredByText: 'Con la tecnología de' + }, + errorScreen: { + titleText: 'No se pueden obtener resultados', + helpText: 'Puede que quieras comprobar tu conexión de red.' + }, + startScreen: { + recentSearchesTitle: 'Recientes', + noRecentSearchesText: 'No hay búsquedas recientes', + saveRecentSearchButtonTitle: 'Guardar esta búsqueda', + removeRecentSearchButtonTitle: 'Eliminar esta búsqueda del historial', + favoriteSearchesTitle: 'Favoritos', + removeFavoriteSearchButtonTitle: + 'Eliminar esta búsqueda de favoritos', + recentConversationsTitle: 'Conversaciones recientes', + removeRecentConversationButtonTitle: + 'Eliminar esta conversación del historial' }, noResultsScreen: { - noResultsText: 'No fue posible encontrar resultados', - suggestedQueryText: 'Puede intentar una nueva búsqueda', + noResultsText: 'No se encontraron resultados para', + suggestedQueryText: 'Intenta buscar', reportMissingResultsText: - 'Deberian haber resultados para esa consulta?', - reportMissingResultsLinkText: 'Click para enviar feedback' + '¿Crees que esta consulta debería devolver resultados?', + reportMissingResultsLinkText: 'Avísanos.' + }, + resultsScreen: { + askAiPlaceholder: 'Preguntar a la IA: ', + noResultsAskAiPlaceholder: + '¿No lo encontraste en la documentación? Pide ayuda a Ask AI: ' + }, + askAiScreen: { + disclaimerText: + 'Las respuestas se generan con IA y pueden contener errores. Verifícalas.', + relatedSourcesText: 'Fuentes relacionadas', + thinkingText: 'Pensando...', + copyButtonText: 'Copiar', + copyButtonCopiedText: '¡Copiado!', + copyButtonTitle: 'Copiar', + likeButtonTitle: 'Me gusta', + dislikeButtonTitle: 'No me gusta', + thanksForFeedbackText: '¡Gracias por tu comentario!', + preToolCallText: 'Buscando...', + duringToolCallText: 'Buscando...', + afterToolCallText: 'Buscado', + stoppedStreamingText: 'Has detenido esta respuesta', + errorTitleText: 'Error de chat', + threadDepthExceededMessage: + 'Esta conversación se ha cerrado para mantener respuestas precisas.', + startNewConversationButtonText: 'Iniciar una nueva conversación' + } + } + }, + askAi: { + sidePanel: { + button: { + translations: { + buttonText: 'Preguntar a la IA', + buttonAriaLabel: 'Preguntar a la IA' + } + }, + panel: { + translations: { + header: { + title: 'Preguntar a la IA', + conversationHistoryTitle: 'Mi historial de conversaciones', + newConversationText: 'Iniciar una nueva conversación', + viewConversationHistoryText: 'Historial de conversaciones' + }, + promptForm: { + promptPlaceholderText: 'Haz una pregunta', + promptAnsweringText: 'Respondiendo...', + promptAskAnotherQuestionText: 'Haz otra pregunta', + promptDisclaimerText: + 'Las respuestas se generan con IA y pueden contener errores.', + promptLabelText: + 'Pulsa Enter para enviar, o Shift+Enter para una nueva línea.', + promptAriaLabelText: 'Entrada de prompt' + }, + conversationScreen: { + preToolCallText: 'Buscando...', + searchingText: 'Buscando...', + toolCallResultText: 'Buscado', + conversationDisclaimer: + 'Las respuestas se generan con IA y pueden contener errores. Verifícalas.', + reasoningText: 'Razonando...', + thinkingText: 'Pensando...', + relatedSourcesText: 'Fuentes relacionadas', + stoppedStreamingText: 'Has detenido esta respuesta', + copyButtonText: 'Copiar', + copyButtonCopiedText: '¡Copiado!', + likeButtonTitle: 'Me gusta', + dislikeButtonTitle: 'No me gusta', + thanksForFeedbackText: '¡Gracias por tu comentario!', + errorTitleText: 'Error de chat' + }, + newConversationScreen: { + titleText: '¿Cómo puedo ayudarte hoy?', + introductionText: + 'Busco en tu documentación para ayudarte a encontrar guías de configuración, detalles de funciones y consejos de solución de problemas rápidamente.' + }, + logo: { + poweredByText: 'Con la tecnología de' + } + } } } } diff --git a/docs/es/guide/deploy.md b/docs/es/guide/deploy.md index 5d2c9c06d..f2f713842 100644 --- a/docs/es/guide/deploy.md +++ b/docs/es/guide/deploy.md @@ -105,13 +105,13 @@ Nota: el archivo `vercel.json` debe ser colocado en la raiz de su **repositório ## Guias de Plataforma {#platform-guides} -### Netlify / Vercel / Cloudflare Pages / AWS Amplify / Render +### Netlify / Vercel / Cloudflare Pages / AWS Amplify / Render {#generic} Configure un nuevo proyecto y altere estas configuraciones usando su panel: - **Comando de Compilación:** `npm run docs:build` - **directorio de Salida:** `docs/.vitepress/dist` -- **Versión de Node:** `18` (o superior) +- **Versión de Node:** `20` (o superior) ::: warning No active opciones como _Auto Minify_ para código HTML. Eso removera comentarios de salida que tiene significado para Vue. Habrán errores de incompatibilidad de hidratación se fueran removidos. @@ -153,26 +153,24 @@ No active opciones como _Auto Minify_ para código HTML. Eso removera comentario runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: fetch-depth: 0 # No necesario se lastUpdated no estuviera habilitado - # - uses: pnpm/action-setup@v3 # Desconecte eso si estuviera usando pnpm + # - uses: pnpm/action-setup@v4 # Desconecte eso si estuviera usando pnpm # with: # version: 9 # - uses: oven-sh/setup-bun@v1 # Desconecte eso se estuviera usando Bun - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 with: - node-version: 22 + node-version: 24 cache: npm # o pnpm / yarn - name: Setup Pages uses: actions/configure-pages@v4 - name: Install dependencies run: npm ci # o pnpm install / yarn install / bun install - - name: Build with VitePress - run: | - npm run docs:build # o pnpm docs:build / yarn docs:build / bun run docs:build - touch docs/.vitepress/dist/.nojekyll + - name: Build with VitePress + run: npm run docs:build # o pnpm docs:build / yarn docs:build / bun run docs:build - name: Upload artifact uses: actions/upload-pages-artifact@v3 with: @@ -192,6 +190,7 @@ No active opciones como _Auto Minify_ para código HTML. Eso removera comentario uses: actions/deploy-pages@v4 ``` + ::: warning Asegurese de que la opción `base` en su VitePress esté configurada correctamentse. Vea [Configuranco un Path base Público](#setting-a-public-base-path) para más detalles. ::: @@ -201,7 +200,7 @@ No active opciones como _Auto Minify_ para código HTML. Eso removera comentario ### GitLab Pages -1. Defina `outDir` en la configuración VitePress como `../public`. Configure la opción `base` para `'//'` se desea implantar en `https://.gitlab.io//`. +1. Defina `outDir` en la configuración VitePress como `../public`. Configure la opción `base` para `'//'` se desea implantar en `https://.gitlab.io//`. No necesita `base` si está implementando en un dominio personalizado, páginas de usuario o grupo, o si la configuración "Use unique domain" está habilitada en GitLab. 2. Cree un archivo llamado `.gitlab-ci.yml` en la raiz del proyecto con el contenido abajo. Esto construirá e implantará su sitio siempre que haga alteraciones en el contenido. @@ -222,7 +221,7 @@ No active opciones como _Auto Minify_ para código HTML. Eso removera comentario - main ``` -### Azure Static Web Apps {#azure-static-web-apps} +### Azure 1. Siga la [documentación oficial](https://docs.microsoft.com/en-us/azure/static-web-apps/build-configuration). @@ -232,7 +231,11 @@ No active opciones como _Auto Minify_ para código HTML. Eso removera comentario - **`output_location`**: `docs/.vitepress/dist` - **`app_build_command`**: `npm run docs:build` -### Firebase {#firebase} +### CloudRay + +Puedes desplegar tu proyecto VitePress con [CloudRay](https://cloudray.io/) siguiendo estas [instrucciones](https://cloudray.io/articles/how-to-deploy-vitepress-site). + +### Firebase 1. Cree `firebase.json` y `.firebaserc` en la raiz de su proyecto: @@ -263,14 +266,6 @@ No active opciones como _Auto Minify_ para código HTML. Eso removera comentario firebase deploy ``` -### Surge - -1. Después de ejecutar `npm run docs:build`, ejecute este comando para implantar: - - ```sh - npx surge docs/.vitepress/dist - ``` - ### Heroku 1. Siga la documentación y el guia proporcionados por [`heroku-buildpack-static`](https://elements.heroku.com/buildpacks/heroku/heroku-buildpack-static). @@ -283,10 +278,66 @@ No active opciones como _Auto Minify_ para código HTML. Eso removera comentario } ``` -### Edgio +### Hostinger -Consulte [Crear e Implantar una Aplicación VitePress en Edgio](https://docs.edg.io/guides/vitepress). +Puedes desplegar tu proyecto VitePress con [Hostinger](https://www.hostinger.com/web-apps-hosting) siguiendo estas [instrucciones](https://www.hostinger.com/support/how-to-deploy-a-nodejs-website-in-hostinger/). Al configurar los ajustes de compilación, elige VitePress como framework y ajusta el directorio raíz a `./docs`. -### Kinsta Static Site Hosting {#kinsta-static-site-hosting} +### Kinsta Puede implantar su sitio VitePress em [Kinsta](https://kinsta.com/static-site-hosting/) siguiendo estas [instrucciones](https://kinsta.com/docs/vitepress-static-site-example/). + +### Stormkit + +Puedes desplegar tu proyecto VitePress en [Stormkit](https://www.stormkit.io) siguiendo estas [instrucciones](https://stormkit.io/blog/how-to-deploy-vitepress). + +### Surge + +1. Después de ejecutar `npm run docs:build`, ejecute este comando para implantar: + + ```sh + npx surge docs/.vitepress/dist + ``` + +### Nginx + +Aquí hay un ejemplo de configuración de bloque de servidor Nginx. Esta configuración incluye compresión gzip para recursos comunes basados en texto, reglas para servir los archivos estáticos de su sitio VitePress con encabezados de caché adecuados, así como el manejo de `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"; + } + } +} +``` + +Esta configuración asume que su sitio VitePress compilado está ubicado en el directorio `/app` de su servidor. Ajuste la directiva `root` según corresponda si los archivos de su sitio se encuentran en otro lugar. + +::: warning No predeterminar index.html +La resolución de try_files no debe predeterminar index.html como en otras aplicaciones Vue. Esto resultará en un estado de página inválido. +::: + +Se puede encontrar más información en la [documentación oficial de nginx](https://nginx.org/en/docs/), en estos issues [#2837](https://github.com/vuejs/vitepress/discussions/2837), [#3235](https://github.com/vuejs/vitepress/issues/3235) así como en este [post del blog](https://blog.mehdi.cc/articles/vitepress-cleanurls-on-nginx-environment#readings) de Mehdi Merah. diff --git a/docs/es/guide/extending-default-theme.md b/docs/es/guide/extending-default-theme.md index 85bf8de87..b0705de3d 100644 --- a/docs/es/guide/extending-default-theme.md +++ b/docs/es/guide/extending-default-theme.md @@ -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 e9ed1526e..056071d53 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 00f973edd..b76eb0ac0 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/] }) ``` @@ -773,7 +773,7 @@ Por ejemplo, puede incluir un archivo markdown relativo usando esto: ## Conceptos Básicos - + ``` **Archivo de Parte** (`parts/basics.md`) @@ -809,7 +809,7 @@ También soporta la selección de un intervalo de lineas: ## Conceptos Básicos - + ``` **Archivo de Parte** (`parts/basics.md`) @@ -844,7 +844,7 @@ Observe que esto no genera errores si el archivo no está presente. Por lo tanto Esto es actualmente opcional. Para activarlo, necesita instalar `markdown-it-mathjax3` y definir `markdown.math` como `true` en su archivo de configuración: ```sh -npm add -D markdown-it-mathjax3 +npm add -D markdown-it-mathjax3@^4 ``` ```ts [.vitepress/config.ts] diff --git a/docs/es/guide/ssr-compat.md b/docs/es/guide/ssr-compat.md index 7f701eb82..81abdf773 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/ja/guide/cms.md b/docs/ja/guide/cms.md new file mode 100644 index 000000000..9e3ceb06a --- /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 000000000..9f11bba04 --- /dev/null +++ b/docs/ja/guide/custom-theme.md @@ -0,0 +1,211 @@ +# カスタムテーマを使う {#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 000000000..def21ad6a --- /dev/null +++ b/docs/ja/guide/data-loading.md @@ -0,0 +1,210 @@ +# ビルド時のデータの読み込み {#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 000000000..5e6a6cdca --- /dev/null +++ b/docs/ja/guide/deploy.md @@ -0,0 +1,342 @@ +--- +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 {#generic} + +新しいプロジェクトを作成し、ダッシュボードで次の設定に変更します。 + +- **Build Command:** `npm run docs:build` +- **Output Directory:** `docs/.vitepress/dist` +- **Node Version:** `20`(以上) + +::: warning +HTML の _Auto Minify_ のようなオプションを有効にしないでください。Vue にとって意味のあるコメントが出力から削除され、削除されるとハイドレーションの不整合エラーが発生する可能性があります。 +::: + +### 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@v5 + with: + fetch-depth: 0 # Not needed if lastUpdated is not enabled + # - uses: pnpm/action-setup@v4 # 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@v6 + with: + node-version: 24 + 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 + +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 + +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` + +### CloudRay + +[CloudRay](https://cloudray.io/) でのデプロイ方法は [こちらの手順](https://cloudray.io/articles/how-to-deploy-vitepress-site) を参照してください。 + +### 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 + ``` + +### Heroku + +1. [`heroku-buildpack-static`](https://elements.heroku.com/buildpacks/heroku/heroku-buildpack-static) のドキュメントとガイドに従います。 + +2. プロジェクトのルートに `static.json` を作成し、以下を記述します。 + + ```json [static.json] + { + "root": "docs/.vitepress/dist" + } + ``` + +### Hostinger + +[Hostinger](https://www.hostinger.com/web-apps-hosting) を使用して VitePress プロジェクトをデプロイするには、こちらの [手順](https://www.hostinger.com/support/how-to-deploy-a-nodejs-website-in-hostinger/) に従ってください。ビルド設定の構成では、フレームワークに VitePress を選択し、ルートディレクトリを `./docs` に調整してください。 + +### Kinsta + +[VitePress](https://kinsta.com/static-site-hosting/) を [こちらの手順](https://kinsta.com/docs/vitepress-static-site-example/) に従ってデプロイできます。 + +### Stormkit + +[VitePress プロジェクトを Stormkit にデプロイ](https://stormkit.io/blog/how-to-deploy-vitepress) する手順を参照してください。 + +### Surge + +1. `npm run docs:build` の後、次のコマンドでデプロイします。 + + ```sh + npx surge docs/.vitepress/dist + ``` + +### 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 000000000..fc5ce184f --- /dev/null +++ b/docs/ja/guide/extending-default-theme.md @@ -0,0 +1,334 @@ +--- +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 000000000..46c52e85f --- /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 000000000..54455823c --- /dev/null +++ b/docs/ja/guide/markdown.md @@ -0,0 +1,1037 @@ +# 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 は多くのプログラミング言語をサポートしています。コードブロックの先頭のバッククォートに有効な言語エイリアスを付けるだけで利用できます。 + +**入力** + +````md +```js +export default { + name: 'MyComponent', + // ... +} +``` +```` + +````md +```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} + +**入力** + +````md +```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}` + +**入力** + +````md +```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]` コメントを使って行内を直接ハイライトできます。 + +**入力** + +````md +```js +export default { + data() { + return { + msg: 'ハイライト!' // [!code highlight] + } + } +} +``` +```` + +**出力** + +```js +export default { + data() { + return { + msg: 'ハイライト!' // [!code highlight] + } + } +} +``` + +## コードブロックでのフォーカス {#focus-in-code-blocks} + +`// [!code focus]` コメントを行に付けると、その行にフォーカスし、他の部分がぼかされます。 + +また、`// [!code focus:]` を使ってフォーカスする行数を指定することもできます。 + +**入力** + +````md +```js +export default { + data() { + return { + msg: 'フォーカス!' // [!!code focus] + } + } +} +``` +```` + +**出力** + +```js +export default { + data() { + return { + msg: 'フォーカス!' // [!code focus] + } + } +} +``` + +## コードブロックのカラー差分表示 {#colored-diffs-in-code-blocks} + +`// [!code --]` または `// [!code ++]` コメントを行に付けると、その行に差分(削除/追加)スタイルを適用できます。コードブロックの色付けは維持されます。 + +**入力** + +````md +```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]` コメントを付けると、その行が対応する色で表示されます。 + +**入力** + +````md +```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` から始まることを意味します。 + +**入力** + +````md +```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@^4 +``` + +```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 000000000..a63251a4c --- /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 000000000..0d2e46457 --- /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 000000000..f72a2aade --- /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 000000000..d71d245fc --- /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 000000000..75d433286 --- /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=/%22vitepress%22:+/+path:/(?:package%7Cdeno)%5C.jsonc?$/+NOT+is:fork+NOT+is:archived&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 000000000..00058c585 --- /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 000000000..bb304fd1e --- /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 000000000..505269432 --- /dev/null +++ b/docs/ja/reference/default-theme-badge.md @@ -0,0 +1,69 @@ +# バッジ {#badge} + +バッジを使うと、見出しにステータスを追加できます。たとえば、そのセクションの種類や対応バージョンを示すのに便利です。 + +## 使い方 {#usage} + +グローバルに利用可能な `Badge` コンポーネントを使用します。 + +```md +### Title +### Title +### Title +### Title +``` + +上記のコードは次のように表示されます: + +### Title +### Title +### Title +### Title + +## 子要素のカスタマイズ {#custom-children} + +`` は子要素(`children`)を受け取り、バッジ内に表示できます。 + +```md +### 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 000000000..42d6329b0 --- /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 000000000..7fe4cc487 --- /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 000000000..a5b40dbd6 --- /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 000000000..f8226c89f --- /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 000000000..011456f81 --- /dev/null +++ b/docs/ja/reference/default-theme-home-page.md @@ -0,0 +1,189 @@ +# ホームページ {#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 000000000..82dfc6de7 --- /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@v5 + 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 000000000..e241d03ec --- /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 000000000..207bf9e91 --- /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 000000000..7b15d699c --- /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 000000000..f77603611 --- /dev/null +++ b/docs/ja/reference/default-theme-search.md @@ -0,0 +1,360 @@ +--- +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: { + ja: { // 既定ロケールを翻訳する場合は `root` にしてください + translations: { + button: { + buttonText: '検索', + buttonAriaLabel: '検索' + }, + modal: { + displayDetails: '詳細一覧を表示', + resetButtonTitle: '検索をリセット', + backButtonTitle: '検索を閉じる', + noResultsText: '結果が見つかりません', + footer: { + selectText: '選択', + selectKeyAriaLabel: 'Enter', + navigateText: '移動', + navigateUpKeyAriaLabel: '上矢印', + navigateDownKeyAriaLabel: '下矢印', + closeText: '閉じる', + closeKeyAriaLabel: 'Esc' + } + } + } + } + } + } + } + } +}) +``` + +### miniSearch のオプション {#minisearch-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} + +多言語検索の設定例です。 + +

+クリックして展開 + +<<< @/snippets/algolia-i18n.ts + +
+ +詳しくは[公式 Algolia ドキュメント](https://docsearch.algolia.com/docs/api#translations)を参照してください。すぐに始めるには、このサイトで使っている翻訳を[GitHub リポジトリ](https://github.com/search?q=repo:vuejs/vitepress+%22function+searchOptions%22&type=code)からコピーすることもできます。 + +### 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: "あなたのアシスタントID" + // または + askAi: { + // 最低限、Algolia から受け取った assistantId を指定する必要があります + assistantId: 'XXXYYY', + // 任意の上書き — 省略した場合は上位の appId/apiKey/indexName を再利用 + // apiKey: '...', + // appId: '...', + // indexName: '...' + } + } + } + } +}) +``` + +::: warning 注意 +キーワード検索を既定にして Ask AI を使わない場合は、`askAi` を指定しないでください。 +::: + +### Ask AI サイドパネル {#ask-ai-side-panel} + +DocSearch v4.5+ はオプションの **Ask AI サイドパネル**をサポートしています。有効にすると、デフォルトで **Ctrl/Cmd+I** で開くことができます。[サイドパネル API リファレンス](https://docsearch.algolia.com/docs/sidepanel/api-reference)にオプションの完全なリストがあります。 + +```ts +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + search: { + provider: 'algolia', + options: { + appId: '...', + apiKey: '...', + indexName: '...', + askAi: { + assistantId: 'XXXYYY', + sidePanel: { + // @docsearch/sidepanel-js SidepanelProps API をミラー + panel: { + variant: 'floating', // または 'inline' + side: 'right', + width: '360px', + expandedWidth: '580px', + suggestedQuestions: true + } + } + } + } + } + } +}) +``` + +キーボードショートカットを無効にする必要がある場合は、サイドパネルの `keyboardShortcuts` オプションを使用してください: + +```ts +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + search: { + provider: 'algolia', + options: { + appId: '...', + apiKey: '...', + indexName: '...', + askAi: { + assistantId: 'XXXYYY', + sidePanel: { + keyboardShortcuts: { + 'Ctrl/Cmd+I': false + } + } + } + } + } + } +}) +``` + +#### モード (auto / sidePanel / hybrid / modal) {#ask-ai-mode} + +VitePress がキーワード検索と Ask AI を統合する方法をオプションで制御できます: + +- `mode: 'auto'`(デフォルト):キーワード検索が設定されている場合は `hybrid` を推論し、それ以外の場合は Ask AI サイドパネルが設定されている場合は `sidePanel` を推論します。 +- `mode: 'sidePanel'`:サイドパネルのみを強制(キーワード検索ボタンを非表示)。 +- `mode: 'hybrid'`:キーワード検索モーダル + Ask AI サイドパネルを有効化(キーワード検索設定が必要)。 +- `mode: 'modal'`:Ask AI を DocSearch モーダル内に保持(サイドパネルを設定した場合でも)。 + +#### Ask AI のみ(キーワード検索なし) {#ask-ai-only} + +**Ask AI サイドパネルのみ**を使用する場合は、トップレベルのキーワード検索設定を省略し、`askAi` の下に認証情報を提供できます: + +```ts +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + search: { + provider: 'algolia', + options: { + mode: 'sidePanel', + askAi: { + assistantId: 'XXXYYY', + appId: '...', + apiKey: '...', + indexName: '...', + sidePanel: true + } + } + } + } +}) +``` + +### クローラー設定 {#crawler-config} + +このサイトで使用している設定を元にした例です。 + +<<< @/snippets/algolia-crawler.js diff --git a/docs/ja/reference/default-theme-sidebar.md b/docs/ja/reference/default-theme-sidebar.md new file mode 100644 index 000000000..ddd87383c --- /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 000000000..5f02d4d0d --- /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 000000000..e6b8b5ca1 --- /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 000000000..afcad68d8 --- /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 000000000..acea9ca7f --- /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/ko/config.ts b/docs/ko/config.ts index 78b5c3f3d..4a076036c 100644 --- a/docs/ko/config.ts +++ b/docs/ko/config.ts @@ -5,7 +5,6 @@ const require = createRequire(import.meta.url) const pkg = require('vitepress/package.json') export default defineAdditionalConfig({ - lang: 'ko-KR', description: 'Vite 및 Vue 기반 정적 사이트 생성기.', themeConfig: { @@ -74,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' @@ -220,7 +223,6 @@ function sidebarReference(): DefaultTheme.SidebarItem[] { function searchOptions(): Partial { return { - placeholder: '문서 검색', translations: { button: { buttonText: '검색', @@ -228,34 +230,136 @@ function searchOptions(): Partial { }, modal: { searchBox: { - resetButtonTitle: '검색 지우기', - resetButtonAriaLabel: '검색 지우기', - cancelButtonText: '취소', - cancelButtonAriaLabel: '취소' + clearButtonTitle: '지우기', + clearButtonAriaLabel: '검색어 지우기', + closeButtonText: '닫기', + closeButtonAriaLabel: '닫기', + placeholderText: '문서를 검색하거나 Ask AI에 질문', + placeholderTextAskAi: '다른 질문하기...', + placeholderTextAskAiStreaming: '답변 중...', + searchInputLabel: '검색', + backToKeywordSearchButtonText: '키워드 검색으로 돌아가기', + backToKeywordSearchButtonAriaLabel: '키워드 검색으로 돌아가기', + newConversationPlaceholder: '질문하기', + conversationHistoryTitle: '내 대화 기록', + startNewConversationText: '새 대화 시작', + viewConversationHistoryText: '대화 기록', + threadDepthErrorPlaceholder: '대화 한도에 도달했습니다' }, - startScreen: { - recentSearchesTitle: '검색 기록', - noRecentSearchesText: '최근 검색 없음', - saveRecentSearchButtonTitle: '검색 기록에 저장', - removeRecentSearchButtonTitle: '검색 기록에서 삭제', - favoriteSearchesTitle: '즐겨찾기', - removeFavoriteSearchButtonTitle: '즐겨찾기에서 삭제' - }, - errorScreen: { - titleText: '결과를 가져올 수 없습니다', - helpText: '네트워크 연결을 확인하세요' + newConversation: { + newConversationTitle: '오늘 무엇을 도와드릴까요?', + newConversationDescription: + '문서를 검색해 설정 가이드, 기능 설명, 문제 해결 팁을 빠르게 찾아드립니다.' }, footer: { selectText: '선택', - navigateText: '탐색', + submitQuestionText: '질문 제출', + selectKeyAriaLabel: 'Enter 키', + navigateText: '이동', + navigateUpKeyAriaLabel: '위 화살표', + navigateDownKeyAriaLabel: '아래 화살표', closeText: '닫기', - searchByText: '검색 기준' + backToSearchText: '검색으로 돌아가기', + closeKeyAriaLabel: 'Escape 키', + poweredByText: '제공' + }, + errorScreen: { + titleText: '결과를 불러올 수 없습니다', + helpText: '네트워크 연결을 확인해 주세요.' + }, + startScreen: { + recentSearchesTitle: '최근', + noRecentSearchesText: '최근 검색이 없습니다', + saveRecentSearchButtonTitle: '이 검색 저장', + removeRecentSearchButtonTitle: '기록에서 이 검색 제거', + favoriteSearchesTitle: '즐겨찾기', + removeFavoriteSearchButtonTitle: '즐겨찾기에서 이 검색 제거', + recentConversationsTitle: '최근 대화', + removeRecentConversationButtonTitle: '기록에서 이 대화 제거' }, noResultsScreen: { - noResultsText: '결과를 찾을 수 없습니다', - suggestedQueryText: '새로운 검색을 시도할 수 있습니다', - reportMissingResultsText: '해당 검색어에 대한 결과가 있어야 합니까?', - reportMissingResultsLinkText: '피드백 보내기 클릭' + noResultsText: '다음에 대한 결과를 찾을 수 없습니다', + suggestedQueryText: '다음을 검색해 보세요', + reportMissingResultsText: '이 검색은 결과가 있어야 하나요?', + reportMissingResultsLinkText: '알려주세요.' + }, + resultsScreen: { + askAiPlaceholder: 'AI에게 묻기: ', + noResultsAskAiPlaceholder: '문서에서 찾지 못했나요? Ask AI에 문의: ' + }, + askAiScreen: { + disclaimerText: + '답변은 AI가 생성하며 오류가 있을 수 있습니다. 확인해 주세요.', + relatedSourcesText: '관련 출처', + thinkingText: '생각 중...', + copyButtonText: '복사', + copyButtonCopiedText: '복사됨!', + copyButtonTitle: '복사', + likeButtonTitle: '좋아요', + dislikeButtonTitle: '싫어요', + thanksForFeedbackText: '피드백 감사합니다!', + preToolCallText: '검색 중...', + duringToolCallText: '검색 중...', + afterToolCallText: '검색함', + stoppedStreamingText: '이 응답을 중지했습니다', + errorTitleText: '채팅 오류', + threadDepthExceededMessage: + '정확성을 유지하기 위해 이 대화는 종료되었습니다.', + startNewConversationButtonText: '새 대화 시작' + } + } + }, + askAi: { + sidePanel: { + button: { + translations: { + buttonText: 'AI에게 묻기', + buttonAriaLabel: 'AI에게 묻기' + } + }, + panel: { + translations: { + header: { + title: 'AI에게 묻기', + conversationHistoryTitle: '내 대화 기록', + newConversationText: '새 대화 시작', + viewConversationHistoryText: '대화 기록' + }, + promptForm: { + promptPlaceholderText: '질문하기', + promptAnsweringText: '답변 중...', + promptAskAnotherQuestionText: '다른 질문하기', + promptDisclaimerText: + '답변은 AI가 생성하며 오류가 있을 수 있습니다.', + promptLabelText: 'Enter로 전송, Shift+Enter로 줄바꿈.', + promptAriaLabelText: '프롬프트 입력' + }, + conversationScreen: { + preToolCallText: '검색 중...', + searchingText: '검색 중...', + toolCallResultText: '검색함', + conversationDisclaimer: + '답변은 AI가 생성하며 오류가 있을 수 있습니다. 확인해 주세요.', + reasoningText: '추론 중...', + thinkingText: '생각 중...', + relatedSourcesText: '관련 출처', + stoppedStreamingText: '이 응답을 중지했습니다', + copyButtonText: '복사', + copyButtonCopiedText: '복사됨!', + likeButtonTitle: '좋아요', + dislikeButtonTitle: '싫어요', + thanksForFeedbackText: '피드백 감사합니다!', + errorTitleText: '채팅 오류' + }, + newConversationScreen: { + titleText: '오늘 무엇을 도와드릴까요?', + introductionText: + '문서를 검색해 설정 가이드, 기능 설명, 문제 해결 팁을 빠르게 찾아드립니다.' + }, + logo: { + poweredByText: '제공' + } + } } } } diff --git a/docs/ko/guide/deploy.md b/docs/ko/guide/deploy.md index 7a57a8ad1..d2e622284 100644 --- a/docs/ko/guide/deploy.md +++ b/docs/ko/guide/deploy.md @@ -105,13 +105,13 @@ Cache-Control: max-age=31536000,immutable ## 플랫폼 가이드 {#platform-guides} -### Netlify / Vercel / Cloudflare Pages / AWS Amplify / Render +### Netlify / Vercel / Cloudflare Pages / AWS Amplify / Render {#generic} 새 프로젝트를 설정하고 대시보드를 사용하여 다음 설정을 변경하세요: - **빌드 명령어:** `npm run docs:build` - **출력 디렉토리:** `docs/.vitepress/dist` -- **노드 버전:** `18` (또는 그 이상) +- **노드 버전:** `20` (또는 그 이상) ::: warning HTML 코드에 대해 _Auto Minify_ 옵션을 활성화하지 마세요. 이는 Vue에 의미가 있는 주석을 출력에서 제거할 것입니다. 제거되면 하이드레이션 불일치 오류가 발생할 수 있습니다. @@ -152,17 +152,17 @@ HTML 코드에 대해 _Auto Minify_ 옵션을 활성화하지 마세요. 이는 runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: fetch-depth: 0 # lastUpdated가 활성화되지 않은 경우 필요하지 않음 - # - uses: pnpm/action-setup@v3 # pnpm을 사용하는 경우 주석 해제 + # - uses: pnpm/action-setup@v4 # pnpm을 사용하는 경우 주석 해제 # with: # version: 9 # - uses: oven-sh/setup-bun@v1 # Bun을 사용하는 경우 주석 해제 - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 with: - node-version: 22 + node-version: 24 cache: npm # 또는 pnpm / yarn - name: Setup Pages uses: actions/configure-pages@v4 @@ -220,7 +220,7 @@ HTML 코드에 대해 _Auto Minify_ 옵션을 활성화하지 마세요. 이는 - main ``` -### Azure 정적 Web 앱 {#azure-static-web-apps} +### Azure 1. [공식 문서](https://docs.microsoft.com/en-us/azure/static-web-apps/build-configuration)를 따르세요. @@ -230,7 +230,11 @@ HTML 코드에 대해 _Auto Minify_ 옵션을 활성화하지 마세요. 이는 - **`output_location`**: `docs/.vitepress/dist` - **`app_build_command`**: `npm run docs:build` -### Firebase {#firebase} +### CloudRay + +[CloudRay](https://cloudray.io/)로 VitePress 프로젝트를 배포하려면 이 [지침](https://cloudray.io/articles/how-to-deploy-vitepress-site)을 따르세요. + +### Firebase 1. 프로젝트 루트에 `firebase.json`과 `.firebaserc`를 생성하세요: @@ -261,14 +265,6 @@ HTML 코드에 대해 _Auto Minify_ 옵션을 활성화하지 마세요. 이는 firebase deploy ``` -### Surge - -1. `npm run docs:build`를 실행한 후, 배포하기 위해 이 명령어를 실행하세요: - - ```sh - npx surge docs/.vitepress/dist - ``` - ### Heroku 1. [`heroku-buildpack-static`](https://elements.heroku.com/buildpacks/heroku/heroku-buildpack-static)에 제공된 문서와 가이드를 따르세요. @@ -281,11 +277,11 @@ HTML 코드에 대해 _Auto Minify_ 옵션을 활성화하지 마세요. 이는 } ``` -### Edgio +### Hostinger -[Edgio에 VitePress 앱 생성 및 배포하기](https://docs.edg.io/guides/vitepress)를 참고하세요. +[Hostinger](https://www.hostinger.com/web-apps-hosting)로 VitePress 프로젝트를 배포하려면 이 [지침](https://www.hostinger.com/support/how-to-deploy-a-nodejs-website-in-hostinger/)을 따르세요. 빌드 설정을 구성할 때 프레임워크로 VitePress를 선택하고 루트 디렉터리를 `./docs`로 조정하세요. -### Kinsta 정적 사이트 호스팅 {#kinsta-static-site-hosting} +### Kinsta [VitePress](https://kinsta.com/static-site-hosting/) 웹사이트를 [Kinsta](https://kinsta.com/static-site-hosting/)에 배포하려면 이 [지침](https://kinsta.com/docs/vitepress-static-site-example/)을 따르세요. @@ -293,6 +289,14 @@ HTML 코드에 대해 _Auto Minify_ 옵션을 활성화하지 마세요. 이는 [VitePress](https://stormkit.io) 프로젝트를 [Stormkit](https://www.stormkit.io)에 배포하려면 이 [지침](https://stormkit.io/blog/how-to-deploy-vitepress)을 따르세요. +### Surge + +1. `npm run docs:build`를 실행한 후, 배포하기 위해 이 명령어를 실행하세요: + + ```sh + npx surge docs/.vitepress/dist + ``` + ### Nginx 다음은 Nginx 서버 블록 구성의 예입니다. 이 설정은 일반적인 텍스트 기반 에셋에 대한 gzip 압축, VitePress 사이트의 정적 파일을 적절한 캐싱 헤더와 함께 제공하는 규칙 및 `cleanUrls: true`를 처리하는 규칙을 포함합니다. diff --git a/docs/ko/guide/extending-default-theme.md b/docs/ko/guide/extending-default-theme.md index 0207e0494..b8b795e6f 100644 --- a/docs/ko/guide/extending-default-theme.md +++ b/docs/ko/guide/extending-default-theme.md @@ -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 ac7e7ca61..632e90788 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 5f03bbf6d..4584d1bda 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/] }) ``` @@ -771,7 +771,7 @@ export default config ## Basics - + ``` **해당 파일** (`parts/basics.md`) @@ -807,7 +807,7 @@ Can be created using `.foorc.json`. ## Basics - + ``` **해당 파일** (`parts/basics.md`) @@ -843,8 +843,8 @@ Can be created using `.foorc.json`. ## Basics - - + + ``` **해당 파일** (`parts/basics.md`) @@ -880,7 +880,7 @@ Can be created using `.foorc.json`. 선택 사항입니다. 활성화하려면 `markdown-it-mathjax3`를 설치하고 설정 파일에서 `markdown.math`를 `true`로 설정해야 합니다: ```sh -npm add -D markdown-it-mathjax3 +npm add -D markdown-it-mathjax3@^4 ``` ```ts [.vitepress/config.ts] diff --git a/docs/ko/guide/what-is-vitepress.md b/docs/ko/guide/what-is-vitepress.md index 9ad43c451..d6c7d6307 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=/%22vitepress%22:+/+path:/(?:package%7Cdeno)%5C.jsonc?$/+NOT+is:fork+NOT+is:archived&type=code) 문서는 모두 이 테마를 기반으로 합니다. [Vue.js 공식 문서](https://vuejs.org/)도 VitePress 기반으로 되어 있으며, 여러 번역본에 걸쳐 공유되는 커스텀 테마를 사용합니다. diff --git a/docs/ko/index.md b/docs/ko/index.md index ae7df4c8f..aa8be95b7 100644 --- a/docs/ko/index.md +++ b/docs/ko/index.md @@ -8,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/default-theme-config.md b/docs/ko/reference/default-theme-config.md index b0df33617..66b2f4e01 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 cdfdc7eff..433c2e074 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 69b633aa1..0ee68e365 100644 --- a/docs/ko/reference/default-theme-search.md +++ b/docs/ko/reference/default-theme-search.md @@ -39,7 +39,7 @@ export default defineConfig({ provider: 'local', options: { locales: { - ko: { // 기본 로케일을 번역하려면 이것을 `root`로 만드십시오. + ko: { // 기본 로케일을 번역하려면 `root`로 설정하세요 translations: { button: { buttonText: '검색', @@ -47,17 +47,17 @@ export default defineConfig({ }, modal: { displayDetails: '상세 목록 표시', - resetButtonTitle: '검색 지우기', + resetButtonTitle: '검색 재설정', backButtonTitle: '검색 닫기', - noResultsText: '결과를 찾을 수 없습니다', + noResultsText: '결과가 없습니다', footer: { selectText: '선택', - selectKeyAriaLabel: '선택하기', - navigateText: '탐색', - navigateUpKeyAriaLabel: '위로', - navigateDownKeyAriaLabel: '아래로', + selectKeyAriaLabel: 'Enter', + navigateText: '이동', + navigateUpKeyAriaLabel: '위쪽 화살표', + navigateDownKeyAriaLabel: '아래쪽 화살표', closeText: '닫기', - closeKeyAriaLabel: 'esc' + closeKeyAriaLabel: 'Esc' } } } @@ -69,7 +69,7 @@ export default defineConfig({ }) ``` -### MiniSearch 옵션 {#mini-search-options} +### MiniSearch 옵션 {#minisearch-options} MiniSearch를 다음과 같이 구성할 수 있습니다: @@ -123,7 +123,7 @@ export default defineConfig({ * @param {import('markdown-it-async')} md */ async _render(src, env, md) { - // return html string + // HTML 문자열을 반환 } } } @@ -174,7 +174,7 @@ export default defineConfig({ 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 (await md.renderAsync(`# ${env.frontmatter.title}`)) + html return html } } @@ -208,6 +208,19 @@ export default defineConfig({ 다국어 검색을 사용하려면 다음과 같이 구성해야 합니다: +
+클릭하여 펼치기 + +<<< @/snippets/algolia-i18n.ts + +
+ +자세한 내용은 [공식 Algolia 문서](https://docsearch.algolia.com/docs/api#translations)를 참고하세요. 빠르게 시작하려면 이 사이트에서 사용하는 번역을 [GitHub 저장소](https://github.com/search?q=repo:vuejs/vitepress+%22function+searchOptions%22&type=code)에서 복사할 수도 있습니다. + +### Algolia Ask AI 지원 {#ask-ai} + +**Ask AI** 기능을 사용하려면 `askAi` 옵션을 추가하세요: + ```ts import { defineConfig } from 'vitepress' @@ -219,46 +232,51 @@ export default defineConfig({ appId: '...', apiKey: '...', indexName: '...', - locales: { - ko: { - placeholder: '문서 검색', - translations: { - button: { - buttonText: '검색', - buttonAriaLabel: '검색' - }, - modal: { - searchBox: { - resetButtonTitle: '검색 지우기', - resetButtonAriaLabel: '검색 지우기', - cancelButtonText: '취소', - cancelButtonAriaLabel: '취소' - }, - startScreen: { - recentSearchesTitle: '검색 기록', - noRecentSearchesText: '최근 검색 없음', - saveRecentSearchButtonTitle: '검색 기록에 저장', - removeRecentSearchButtonTitle: '검색 기록에서 삭제', - favoriteSearchesTitle: '즐겨찾기', - removeFavoriteSearchButtonTitle: '즐겨찾기에서 삭제' - }, - errorScreen: { - titleText: '결과를 가져올 수 없습니다', - helpText: '네트워크 연결을 확인하세요' - }, - footer: { - selectText: '선택', - navigateText: '탐색', - closeText: '닫기', - searchByText: '검색 기준' - }, - noResultsScreen: { - noResultsText: '결과를 찾을 수 없습니다', - suggestedQueryText: '새로운 검색을 시도할 수 있습니다', - reportMissingResultsText: '해당 검색어에 대한 결과가 있어야 합니까?', - reportMissingResultsLinkText: '피드백 보내기 클릭' - } - } + // askAi: "내-어시스턴트-ID" + // 또는 + askAi: { + // 최소한 Algolia에서 받은 assistantId를 제공해야 합니다 + assistantId: 'XXXYYY', + // 선택적 재정의 — 생략하면 상위 appId/apiKey/indexName 값이 재사용됩니다 + // apiKey: '...', + // appId: '...', + // indexName: '...' + } + } + } + } +}) +``` + +::: warning 참고 +Ask AI를 사용하지 않으려면 `askAi` 옵션을 생략하면 됩니다. +::: + +### Ask AI 사이드 패널 {#ask-ai-side-panel} + +DocSearch v4.5+는 선택적 **Ask AI 사이드 패널**을 지원합니다. 활성화되면 기본적으로 **Ctrl/Cmd+I**로 열 수 있습니다. [사이드 패널 API 참조](https://docsearch.algolia.com/docs/sidepanel/api-reference)에 전체 옵션 목록이 있습니다. + +```ts +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + search: { + provider: 'algolia', + options: { + appId: '...', + apiKey: '...', + indexName: '...', + askAi: { + assistantId: 'XXXYYY', + sidePanel: { + // @docsearch/sidepanel-js SidepanelProps API 반영 + panel: { + variant: 'floating', // 또는 'inline' + side: 'right', + width: '360px', + expandedWidth: '580px', + suggestedQuestions: true } } } @@ -268,112 +286,70 @@ export default defineConfig({ }) ``` -[이 옵션들](https://github.com/vuejs/vitepress/blob/main/types/docsearch.d.ts)은 재작성 할 수 있습니다. 이에 대해 자세히 알고 싶다면 Algolia 공식 문서를 참고하세요. +키보드 단축키를 비활성화해야 하는 경우 사이드 패널의 `keyboardShortcuts` 옵션을 사용하세요: -### 크롤러 구성 {#crawler-config} +```ts +import { defineConfig } from 'vitepress' -이 사이트에서 사용하는 예제 구성을 소개합니다: +export default defineConfig({ + themeConfig: { + search: { + provider: 'algolia', + options: { + appId: '...', + apiKey: '...', + indexName: '...', + askAi: { + assistantId: 'XXXYYY', + sidePanel: { + keyboardShortcuts: { + 'Ctrl/Cmd+I': false + } + } + } + } + } + } +}) +``` + +#### 모드 (auto / sidePanel / hybrid / modal) {#ask-ai-mode} + +VitePress가 키워드 검색과 Ask AI를 통합하는 방식을 선택적으로 제어할 수 있습니다: + +- `mode: 'auto'` (기본값): 키워드 검색이 구성된 경우 `hybrid`를 추론하고, 그렇지 않으면 Ask AI 사이드 패널이 구성된 경우 `sidePanel`을 추론합니다. +- `mode: 'sidePanel'`: 사이드 패널만 강제 (키워드 검색 버튼 숨김). +- `mode: 'hybrid'`: 키워드 검색 모달 + Ask AI 사이드 패널 활성화 (키워드 검색 구성 필요). +- `mode: 'modal'`: Ask AI를 DocSearch 모달 내부에 유지 (사이드 패널을 구성한 경우에도). + +#### Ask AI만 (키워드 검색 없음) {#ask-ai-only} + +**Ask AI 사이드 패널만** 사용하려면 최상위 키워드 검색 구성을 생략하고 `askAi` 아래에 자격 증명을 제공할 수 있습니다: ```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 - }) +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + search: { + provider: 'algolia', + options: { + mode: 'sidePanel', + askAi: { + assistantId: 'XXXYYY', + appId: '...', + apiKey: '...', + indexName: '...', + sidePanel: 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' - } } }) ``` + +### 크롤러 구성 {#crawler-config} + +이 사이트에서 사용하는 예제 구성을 소개합니다: + +<<< @/snippets/algolia-crawler.js diff --git a/docs/ko/reference/runtime-api.md b/docs/ko/reference/runtime-api.md index e9a8e5307..ee7a4ba3c 100644 --- a/docs/ko/reference/runtime-api.md +++ b/docs/ko/reference/runtime-api.md @@ -49,7 +49,7 @@ interface PageData { titleTemplate?: string | boolean description: string relativePath: string - filePath: string, + filePath: string headers: Header[] frontmatter: Record params?: Record diff --git a/docs/ko/reference/site-config.md b/docs/ko/reference/site-config.md index 25dbcc017..ba02bd590 100644 --- a/docs/ko/reference/site-config.md +++ b/docs/ko/reference/site-config.md @@ -439,7 +439,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 4f93f4dca..2de958b9e 100644 --- a/docs/lunaria.config.json +++ b/docs/lunaria.config.json @@ -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 98f666051..62f5a4bf5 100644 --- a/docs/package.json +++ b/docs/package.json @@ -15,7 +15,7 @@ "open-cli": "^8.0.0", "postcss-rtlcss": "^5.7.1", "vitepress": "workspace:*", - "vitepress-plugin-group-icons": "^1.6.0", - "vitepress-plugin-llms": "^1.5.1" + "vitepress-plugin-group-icons": "^1.7.1", + "vitepress-plugin-llms": "^1.11.0" } } diff --git a/docs/pt/config.ts b/docs/pt/config.ts index 4926e697f..5f71d84fa 100644 --- a/docs/pt/config.ts +++ b/docs/pt/config.ts @@ -5,7 +5,6 @@ const require = createRequire(import.meta.url) const pkg = require('vitepress/package.json') export default defineAdditionalConfig({ - lang: 'pt-BR', description: 'Gerador de Site Estático desenvolvido com Vite e Vue.', themeConfig: { @@ -74,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' @@ -175,43 +178,150 @@ function sidebarReference(): DefaultTheme.SidebarItem[] { function searchOptions(): Partial { return { - placeholder: 'Pesquisar documentos', translations: { button: { - buttonText: 'Pesquisar', - buttonAriaLabel: 'Pesquisar' + buttonText: 'Buscar', + buttonAriaLabel: 'Buscar' }, modal: { searchBox: { - resetButtonTitle: 'Limpar pesquisa', - resetButtonAriaLabel: 'Limpar pesquisa', - cancelButtonText: 'Cancelar', - cancelButtonAriaLabel: 'Cancelar' + clearButtonTitle: 'Limpar', + clearButtonAriaLabel: 'Limpar a consulta', + closeButtonText: 'Fechar', + closeButtonAriaLabel: 'Fechar', + placeholderText: 'Buscar na documentação ou perguntar ao Ask AI', + placeholderTextAskAi: 'Faça outra pergunta...', + placeholderTextAskAiStreaming: 'Respondendo...', + searchInputLabel: 'Buscar', + backToKeywordSearchButtonText: + 'Voltar para a busca por palavra-chave', + backToKeywordSearchButtonAriaLabel: + 'Voltar para a busca por palavra-chave', + newConversationPlaceholder: 'Faça uma pergunta', + conversationHistoryTitle: 'Meu histórico de conversas', + startNewConversationText: 'Iniciar uma nova conversa', + viewConversationHistoryText: 'Histórico de conversas', + threadDepthErrorPlaceholder: 'Limite de conversa atingido' }, - startScreen: { - 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' - }, - errorScreen: { - titleText: 'Não foi possível obter resultados', - helpText: 'Verifique a sua conexão de rede' + newConversation: { + newConversationTitle: 'Como posso ajudar hoje?', + newConversationDescription: + 'Eu busco na sua documentação para ajudar a encontrar guias de configuração, detalhes de funcionalidades e dicas de solução de problemas rapidamente.' }, footer: { selectText: 'Selecionar', + submitQuestionText: 'Enviar pergunta', + selectKeyAriaLabel: 'Tecla Enter', navigateText: 'Navegar', + navigateUpKeyAriaLabel: 'Seta para cima', + navigateDownKeyAriaLabel: 'Seta para baixo', closeText: 'Fechar', - searchByText: 'Pesquisa por' + backToSearchText: 'Voltar à busca', + closeKeyAriaLabel: 'Tecla Escape', + poweredByText: 'Com tecnologia de' + }, + errorScreen: { + titleText: 'Não foi possível obter resultados', + helpText: 'Talvez você queira verificar sua conexão de rede.' + }, + startScreen: { + recentSearchesTitle: 'Recentes', + noRecentSearchesText: 'Nenhuma pesquisa recente', + saveRecentSearchButtonTitle: 'Salvar esta pesquisa', + removeRecentSearchButtonTitle: 'Remover esta pesquisa do histórico', + favoriteSearchesTitle: 'Favoritos', + removeFavoriteSearchButtonTitle: + 'Remover esta pesquisa dos favoritos', + recentConversationsTitle: 'Conversas recentes', + removeRecentConversationButtonTitle: + 'Remover esta conversa do histórico' }, noResultsScreen: { - noResultsText: 'Não foi possível encontrar resultados', - suggestedQueryText: 'Você pode tentar uma nova consulta', + noResultsText: 'Nenhum resultado encontrado para', + suggestedQueryText: 'Tente pesquisar por', reportMissingResultsText: - 'Deveriam haver resultados para essa consulta?', - reportMissingResultsLinkText: 'Clique para enviar feedback' + 'Acha que esta consulta deveria retornar resultados?', + reportMissingResultsLinkText: 'Avise-nos.' + }, + resultsScreen: { + askAiPlaceholder: 'Perguntar à IA: ', + noResultsAskAiPlaceholder: + 'Não encontrou nos documentos? Peça ajuda ao Ask AI: ' + }, + askAiScreen: { + disclaimerText: + 'As respostas são geradas por IA e podem conter erros. Verifique.', + relatedSourcesText: 'Fontes relacionadas', + thinkingText: 'Pensando...', + copyButtonText: 'Copiar', + copyButtonCopiedText: 'Copiado!', + copyButtonTitle: 'Copiar', + likeButtonTitle: 'Curtir', + dislikeButtonTitle: 'Não curtir', + thanksForFeedbackText: 'Obrigado pelo seu feedback!', + preToolCallText: 'Buscando...', + duringToolCallText: 'Buscando...', + afterToolCallText: 'Pesquisado', + stoppedStreamingText: 'Você interrompeu esta resposta', + errorTitleText: 'Erro no chat', + threadDepthExceededMessage: + 'Esta conversa foi encerrada para manter respostas precisas.', + startNewConversationButtonText: 'Iniciar uma nova conversa' + } + } + }, + askAi: { + sidePanel: { + button: { + translations: { + buttonText: 'Perguntar à IA', + buttonAriaLabel: 'Perguntar à IA' + } + }, + panel: { + translations: { + header: { + title: 'Perguntar à IA', + conversationHistoryTitle: 'Meu histórico de conversas', + newConversationText: 'Iniciar uma nova conversa', + viewConversationHistoryText: 'Histórico de conversas' + }, + promptForm: { + promptPlaceholderText: 'Faça uma pergunta', + promptAnsweringText: 'Respondendo...', + promptAskAnotherQuestionText: 'Faça outra pergunta', + promptDisclaimerText: + 'As respostas são geradas por IA e podem conter erros.', + promptLabelText: + 'Pressione Enter para enviar ou Shift+Enter para nova linha.', + promptAriaLabelText: 'Entrada do prompt' + }, + conversationScreen: { + preToolCallText: 'Buscando...', + searchingText: 'Buscando...', + toolCallResultText: 'Pesquisado', + conversationDisclaimer: + 'As respostas são geradas por IA e podem conter erros. Verifique.', + reasoningText: 'Raciocinando...', + thinkingText: 'Pensando...', + relatedSourcesText: 'Fontes relacionadas', + stoppedStreamingText: 'Você interrompeu esta resposta', + copyButtonText: 'Copiar', + copyButtonCopiedText: 'Copiado!', + likeButtonTitle: 'Curtir', + dislikeButtonTitle: 'Não curtir', + thanksForFeedbackText: 'Obrigado pelo seu feedback!', + errorTitleText: 'Erro no chat' + }, + newConversationScreen: { + titleText: 'Como posso ajudar hoje?', + introductionText: + 'Eu busco na sua documentação para ajudar a encontrar guias de configuração, detalhes de funcionalidades e dicas de solução de problemas rapidamente.' + }, + logo: { + poweredByText: 'Com tecnologia de' + } + } } } } diff --git a/docs/pt/guide/deploy.md b/docs/pt/guide/deploy.md index b112bf7d5..7821c7ab8 100644 --- a/docs/pt/guide/deploy.md +++ b/docs/pt/guide/deploy.md @@ -105,13 +105,13 @@ Nota: o arquivo `vercel.json` deve ser colocado na raiz do seu **repositório**. ## Guias de Plataforma {#platform-guides} -### Netlify / Vercel / Cloudflare Pages / AWS Amplify / Render +### Netlify / Vercel / Cloudflare Pages / AWS Amplify / Render {#generic} Configure um novo projeto e altere estas configurações usando seu painel: - **Comando de Compilação:** `npm run docs:build` - **Diretório de Saída:** `docs/.vitepress/dist` -- **Versão do Node:** `18` (ou superior) +- **Versão do Node:** `20` (ou superior) ::: warning Não ative opções como _Auto Minify_ para código HTML. Isso removerá comentários da saída que têm significado para Vue. Haverão erros de incompatibilidade de hidratação se forem removidos. @@ -153,26 +153,24 @@ Não ative opções como _Auto Minify_ para código HTML. Isso removerá coment runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: fetch-depth: 0 # Não necessário se lastUpdated não estiver habilitado - # - uses: pnpm/action-setup@v3 # Descomente isso se estiver usando pnpm + # - uses: pnpm/action-setup@v4 # Descomente isso se estiver usando pnpm # with: # version: 9 # - uses: oven-sh/setup-bun@v1 # Descomente isso se estiver usando Bun - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 with: - node-version: 22 + node-version: 24 cache: npm # ou pnpm / yarn - name: Setup Pages uses: actions/configure-pages@v4 - name: Install dependencies run: npm ci # ou pnpm install / yarn install / bun install - - name: Build with VitePress - run: | - npm run docs:build # ou pnpm docs:build / yarn docs:build / bun run docs:build - touch docs/.vitepress/dist/.nojekyll + - name: Build with VitePress + run: npm run docs:build # ou pnpm docs:build / yarn docs:build / bun run docs:build - name: Upload artifact uses: actions/upload-pages-artifact@v3 with: @@ -202,7 +200,7 @@ Não ative opções como _Auto Minify_ para código HTML. Isso removerá coment ### GitLab Pages -1. Defina `outDir` na configuração VitePress como `../public`. Configure a opção `base` para `'//'` se você deseja implantar em `https://.gitlab.io//`. +1. Defina `outDir` na configuração VitePress como `../public`. Configure a opção `base` para `'//'` se você deseja implantar em `https://.gitlab.io//`. Você não precisa de `base` se estiver implantando em um domínio personalizado, páginas de usuário ou grupo, ou se a configuração "Use unique domain" estiver habilitada no GitLab. 2. Crie um arquivo chamado `.gitlab-ci.yml` na raiz do seu projeto com o conteúdo abaixo. Isso construirá e implantará seu site sempre que você fizer alterações no conteúdo: @@ -223,7 +221,7 @@ Não ative opções como _Auto Minify_ para código HTML. Isso removerá coment - main ``` -### Azure Static Web Apps {#azure-static-web-apps} +### Azure 1. Siga a [documentação oficial](https://docs.microsoft.com/en-us/azure/static-web-apps/build-configuration). @@ -233,7 +231,11 @@ Não ative opções como _Auto Minify_ para código HTML. Isso removerá coment - **`output_location`**: `docs/.vitepress/dist` - **`app_build_command`**: `npm run docs:build` -### Firebase {#firebase} +### CloudRay + +Você pode implantar seu projeto VitePress com a [CloudRay](https://cloudray.io/) seguindo estas [instruções](https://cloudray.io/articles/how-to-deploy-vitepress-site). + +### Firebase 1. Crie `firebase.json` e `.firebaserc` na raiz do seu projeto: @@ -264,14 +266,6 @@ Não ative opções como _Auto Minify_ para código HTML. Isso removerá coment firebase deploy ``` -### Surge - -1. Após executar `npm run docs:build`, execute este comando para implantar: - - ```sh - npx surge docs/.vitepress/dist - ``` - ### Heroku 1. Siga a documentação e o guia fornecidos em [`heroku-buildpack-static`](https://elements.heroku.com/buildpacks/heroku/heroku-buildpack-static). @@ -284,10 +278,66 @@ Não ative opções como _Auto Minify_ para código HTML. Isso removerá coment } ``` -### Edgio +### Hostinger -Consulte [Criar e Implantar um Aplicativo VitePress no Edgio](https://docs.edg.io/guides/vitepress). +Você pode implantar seu projeto VitePress com a [Hostinger](https://www.hostinger.com/web-apps-hosting) seguindo estas [instruções](https://www.hostinger.com/support/how-to-deploy-a-nodejs-website-in-hostinger/). Ao configurar as opções de build, escolha VitePress como framework e ajuste o diretório raiz para `./docs`. -### Kinsta Static Site Hosting {#kinsta-static-site-hosting} +### Kinsta Você pode implantar seu site VitePress em [Kinsta](https://kinsta.com/static-site-hosting/) seguindo estas [instruções](https://kinsta.com/docs/vitepress-static-site-example/). + +### Stormkit + +Você pode implantar seu projeto VitePress na [Stormkit](https://www.stormkit.io) seguindo estas [instruções](https://stormkit.io/blog/how-to-deploy-vitepress). + +### Surge + +1. Após executar `npm run docs:build`, execute este comando para implantar: + + ```sh + npx surge docs/.vitepress/dist + ``` + +### Nginx + +Aqui está um exemplo de configuração de bloco de servidor Nginx. Essa configuração inclui compressão gzip para ativos comuns baseados em texto, regras para servir os arquivos estáticos do seu site VitePress com cabeçalhos de cache apropriados, assim como lidar com `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"; + } + } +} +``` + +Essa configuração presume que o site VitePress compilado está localizado no diretório `/app` no seu servidor. Ajuste a diretiva `root` de acordo caso os arquivos do site estejam em outro lugar. + +::: warning Não use index.html por padrão +A resolução de try_files não deve padronizar para index.html como em outras aplicações Vue. Isso resultará em um estado de página inválido. +::: + +Mais informações podem ser encontradas na [documentação oficial do nginx](https://nginx.org/en/docs/), nestas issues [#2837](https://github.com/vuejs/vitepress/discussions/2837), [#3235](https://github.com/vuejs/vitepress/issues/3235) assim como neste [post do blog](https://blog.mehdi.cc/articles/vitepress-cleanurls-on-nginx-environment#readings) de Mehdi Merah. diff --git a/docs/pt/guide/extending-default-theme.md b/docs/pt/guide/extending-default-theme.md index aa918b487..f3175f836 100644 --- a/docs/pt/guide/extending-default-theme.md +++ b/docs/pt/guide/extending-default-theme.md @@ -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 e6668cb2f..c0dba3a9a 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 b52452598..bfcc591f6 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/] }) ``` @@ -771,7 +771,7 @@ Por exemplo, você pode incluir um arquivo markdown relativo usando isto: ## Conceitos Básicos - + ``` **Arquivo da Parte** (`parts/basics.md`) @@ -807,7 +807,7 @@ Também suporta a seleção de um intervalo de linhas: ## Conceitos Básicos - + ``` **Arquivo da Parte** (`parts/basics.md`) @@ -843,7 +843,7 @@ Observe que isso não gera erros se o arquivo não estiver presente. Portanto, a Isso é atualmente opcional. Para ativá-lo, você precisa instalar `markdown-it-mathjax3` e definir `markdown.math` como `true` no seu arquivo de configuração: ```sh -npm add -D markdown-it-mathjax3 +npm add -D markdown-it-mathjax3@^4 ``` ```ts [.vitepress/config.ts] diff --git a/docs/pt/guide/using-vue.md b/docs/pt/guide/using-vue.md index 226d90d21..a034108d9 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 734cd4178..2ccd319d0 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=/%22vitepress%22:+/+path:/(?:package%7Cdeno)%5C.jsonc?$/+NOT+is:fork+NOT+is:archived&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 67cab365b..236d7c006 100644 --- a/docs/pt/index.md +++ b/docs/pt/index.md @@ -8,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/default-theme-config.md b/docs/pt/reference/default-theme-config.md index 54e53e4a6..a1ac180f4 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 5f0d23997..fefc96618 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 c16406cb2..44c5b8acc 100644 --- a/docs/pt/reference/default-theme-search.md +++ b/docs/pt/reference/default-theme-search.md @@ -39,18 +39,25 @@ export default defineConfig({ provider: 'local', options: { locales: { - zh: { + pt: { // torne isto `root` se quiser traduzir a localidade padrão translations: { button: { - buttonText: '搜索文档', - buttonAriaLabel: '搜索文档' + buttonText: 'Pesquisar', + buttonAriaLabel: 'Pesquisar' }, modal: { - noResultsText: '无法找到相关结果', - resetButtonTitle: '清除查询条件', + displayDetails: 'Mostrar lista detalhada', + resetButtonTitle: 'Redefinir pesquisa', + backButtonTitle: 'Fechar pesquisa', + noResultsText: 'Nenhum resultado', footer: { - selectText: '选择', - navigateText: '切换' + selectText: 'Selecionar', + selectKeyAriaLabel: 'Enter', + navigateText: 'Navegar', + navigateUpKeyAriaLabel: 'Seta para cima', + navigateDownKeyAriaLabel: 'Seta para baixo', + closeText: 'Fechar', + closeKeyAriaLabel: 'Esc' } } } @@ -62,7 +69,7 @@ export default defineConfig({ }) ``` -### Opções MiniSearch {#mini-search-options} +### Opções MiniSearch {#minisearch-options} Você pode configurar o MiniSearch assim: @@ -116,7 +123,7 @@ export default defineConfig({ * @param {import('markdown-it-async')} md */ async _render(src, env, md) { - // retorne a string HTML + // retorna uma string HTML } } } @@ -141,7 +148,7 @@ export default defineConfig({ async _render(src, env, md) { const html = await md.renderAsync(src, env) if (env.frontmatter?.search === false) return '' - if (env.relativePath.startsWith('algum/caminho')) return '' + if (env.relativePath.startsWith('some/path')) return '' return html } } @@ -167,7 +174,7 @@ export default defineConfig({ 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 (await md.renderAsync(`# ${env.frontmatter.title}`)) + html return html } } @@ -197,10 +204,23 @@ export default defineConfig({ }) ``` -### i18n {#algolia-search-i18n} {#algolia-search-i18n} +### i18n {#algolia-search-i18n} Você pode usar uma configuração como esta para usar a pesquisa multilínguas: +

+Clique para expandir + +<<< @/snippets/algolia-i18n.ts + +
+ +Consulte a [documentação oficial da Algolia](https://docsearch.algolia.com/docs/api#translations) para saber mais. Para começar rapidamente, você também pode copiar as traduções usadas por este site do [nosso repositório no GitHub](https://github.com/search?q=repo:vuejs/vitepress+%22function+searchOptions%22&type=code). + +### Suporte ao Algolia Ask AI {#ask-ai} + +Se quiser incluir o **Ask AI**, adicione `askAi` em `options`: + ```ts import { defineConfig } from 'vitepress' @@ -212,46 +232,51 @@ export default defineConfig({ appId: '...', apiKey: '...', indexName: '...', - locales: { - zh: { - placeholder: '搜索文档', - translations: { - button: { - buttonText: '搜索文档', - buttonAriaLabel: '搜索文档' - }, - modal: { - searchBox: { - resetButtonTitle: '清除查询条件', - resetButtonAriaLabel: '清除查询条件', - cancelButtonText: '取消', - cancelButtonAriaLabel: '取消' - }, - startScreen: { - recentSearchesTitle: '搜索历史', - noRecentSearchesText: '没有搜索历史', - saveRecentSearchButtonTitle: '保存至搜索历史', - removeRecentSearchButtonTitle: '从搜索历史中移除', - favoriteSearchesTitle: '收藏', - removeFavoriteSearchButtonTitle: '从收藏中移除' - }, - errorScreen: { - titleText: '无法获取结果', - helpText: '你可能需要检查你的网络连接' - }, - footer: { - selectText: '选择', - navigateText: '切换', - closeText: '关闭', - searchByText: '搜索提供者' - }, - noResultsScreen: { - noResultsText: '无法找到相关结果', - suggestedQueryText: '你可以尝试查询', - reportMissingResultsText: '你认为该查询应该有结果?', - reportMissingResultsLinkText: '点击反馈' - } - } + // askAi: "SEU-ID-DO-ASSISTENTE" + // OU + askAi: { + // no mínimo, você deve fornecer o assistantId recebido da Algolia + assistantId: 'XXXYYY', + // substituições opcionais — se omitidas, os valores appId/apiKey/indexName de nível superior são reutilizados + // apiKey: '...', + // appId: '...', + // indexName: '...' + } + } + } + } +}) +``` + +::: warning Nota +Caso queira apenas a pesquisa por palavra-chave, omita `askAi`. +::: + +### Painel Lateral do Ask AI {#ask-ai-side-panel} + +O DocSearch v4.5+ suporta um **painel lateral do Ask AI** opcional. Quando habilitado, pode ser aberto com **Ctrl/Cmd+I** por padrão. A [Referência da API do Painel Lateral](https://docsearch.algolia.com/docs/sidepanel/api-reference) contém a lista completa de opções. + +```ts +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + search: { + provider: 'algolia', + options: { + appId: '...', + apiKey: '...', + indexName: '...', + askAi: { + assistantId: 'XXXYYY', + sidePanel: { + // Espelha a API do @docsearch/sidepanel-js SidepanelProps + panel: { + variant: 'floating', // ou 'inline' + side: 'right', + width: '360px', + expandedWidth: '580px', + suggestedQuestions: true } } } @@ -261,112 +286,70 @@ export default defineConfig({ }) ``` -[Essas opções](https://github.com/vuejs/vitepress/blob/main/types/docsearch.d.ts) podem ser sobrepostas. Consulte a documentação oficial Algolia para obter mais informações sobre elas. +Se precisar desabilitar o atalho de teclado, use a opção `keyboardShortcuts` do painel lateral: -### Configuração _Crawler_ {#crawler-config} +```ts +import { defineConfig } from 'vitepress' -Aqui está um exemplo de configuração baseado na qual este site usa: +export default defineConfig({ + themeConfig: { + search: { + provider: 'algolia', + options: { + appId: '...', + apiKey: '...', + indexName: '...', + askAi: { + assistantId: 'XXXYYY', + sidePanel: { + keyboardShortcuts: { + 'Ctrl/Cmd+I': false + } + } + } + } + } + } +}) +``` + +#### Modo (auto / sidePanel / hybrid / modal) {#ask-ai-mode} + +Você pode controlar opcionalmente como o VitePress integra a pesquisa por palavra-chave e o Ask AI: + +- `mode: 'auto'` (padrão): infere `hybrid` quando a pesquisa por palavra-chave está configurada, caso contrário `sidePanel` quando o painel lateral do Ask AI está configurado. +- `mode: 'sidePanel'`: força apenas o painel lateral (oculta o botão de pesquisa por palavra-chave). +- `mode: 'hybrid'`: habilita o modal de pesquisa por palavra-chave + painel lateral do Ask AI (requer configuração de pesquisa por palavra-chave). +- `mode: 'modal'`: mantém o Ask AI dentro do modal do DocSearch (mesmo se você configurou o painel lateral). + +#### Apenas Ask AI (sem pesquisa por palavra-chave) {#ask-ai-only} + +Se quiser usar **apenas o painel lateral do Ask AI**, você pode omitir a configuração de pesquisa por palavra-chave de nível superior e fornecer as credenciais em `askAi`: ```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 - }) +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + search: { + provider: 'algolia', + options: { + mode: 'sidePanel', + askAi: { + assistantId: 'XXXYYY', + appId: '...', + apiKey: '...', + indexName: '...', + sidePanel: 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' - } } }) ``` + +### Configuração _Crawler_ {#crawler-config} + +Aqui está um exemplo de configuração baseado na qual este site usa: + +<<< @/snippets/algolia-crawler.js diff --git a/docs/pt/reference/runtime-api.md b/docs/pt/reference/runtime-api.md index ed6476ac4..559e2fed5 100644 --- a/docs/pt/reference/runtime-api.md +++ b/docs/pt/reference/runtime-api.md @@ -45,7 +45,7 @@ interface PageData { titleTemplate?: string | boolean description: string relativePath: string - filePath: string, + filePath: string headers: Header[] frontmatter: Record params?: Record diff --git a/docs/pt/reference/site-config.md b/docs/pt/reference/site-config.md index 092819014..662813115 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: @@ -439,7 +439,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. @@ -594,7 +594,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`. ::: @@ -662,7 +662,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. ::: @@ -679,7 +679,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/ru/config.ts b/docs/ru/config.ts index 739cfbf2a..515cffba4 100644 --- a/docs/ru/config.ts +++ b/docs/ru/config.ts @@ -5,7 +5,6 @@ const require = createRequire(import.meta.url) const pkg = require('vitepress/package.json') export default defineAdditionalConfig({ - lang: 'ru-RU', description: 'Генератор статических сайтов на основе Vite и Vue.', themeConfig: { @@ -72,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' @@ -175,7 +178,6 @@ function sidebarReference(): DefaultTheme.SidebarItem[] { function searchOptions(): Partial { return { - placeholder: 'Поиск в документации', translations: { button: { buttonText: 'Поиск', @@ -183,35 +185,141 @@ function searchOptions(): Partial { }, modal: { searchBox: { - resetButtonTitle: 'Сбросить поиск', - resetButtonAriaLabel: 'Сбросить поиск', - cancelButtonText: 'Отменить поиск', - cancelButtonAriaLabel: 'Отменить поиск' + clearButtonTitle: 'Очистить', + clearButtonAriaLabel: 'Очистить запрос', + closeButtonText: 'Закрыть', + closeButtonAriaLabel: 'Закрыть', + placeholderText: 'Поиск по документации или задайте вопрос Ask AI', + placeholderTextAskAi: 'Задайте другой вопрос...', + placeholderTextAskAiStreaming: 'Отвечаю...', + searchInputLabel: 'Поиск', + backToKeywordSearchButtonText: 'Назад к поиску по ключевым словам', + backToKeywordSearchButtonAriaLabel: + 'Назад к поиску по ключевым словам', + newConversationPlaceholder: 'Задайте вопрос', + conversationHistoryTitle: 'Моя история разговоров', + startNewConversationText: 'Начать новый разговор', + viewConversationHistoryText: 'История разговоров', + threadDepthErrorPlaceholder: 'Достигнут лимит разговора' }, - startScreen: { - recentSearchesTitle: 'История поиска', - noRecentSearchesText: 'Нет истории поиска', - saveRecentSearchButtonTitle: 'Сохранить в истории поиска', - removeRecentSearchButtonTitle: 'Удалить из истории поиска', - favoriteSearchesTitle: 'Избранное', - removeFavoriteSearchButtonTitle: 'Удалить из избранного' + newConversation: { + newConversationTitle: 'Чем могу помочь сегодня?', + newConversationDescription: + 'Я ищу по вашей документации, чтобы быстро помочь найти руководства по настройке, детали функций и советы по устранению неполадок.' + }, + footer: { + selectText: 'Выбрать', + submitQuestionText: 'Отправить вопрос', + selectKeyAriaLabel: 'Клавиша Enter', + navigateText: 'Навигация', + navigateUpKeyAriaLabel: 'Стрелка вверх', + navigateDownKeyAriaLabel: 'Стрелка вниз', + closeText: 'Закрыть', + backToSearchText: 'Назад к поиску', + closeKeyAriaLabel: 'Клавиша Escape', + poweredByText: 'При поддержке' }, errorScreen: { - titleText: 'Невозможно получить результаты', - helpText: 'Вам может потребоваться проверить подключение к Интернету' + titleText: 'Не удалось получить результаты', + helpText: 'Возможно, стоит проверить подключение к сети.' }, - footer: { - selectText: 'выбрать', - navigateText: 'перейти', - closeText: 'закрыть', - searchByText: 'поставщик поиска' + startScreen: { + recentSearchesTitle: 'Недавние', + noRecentSearchesText: 'Нет недавних поисков', + saveRecentSearchButtonTitle: 'Сохранить этот поиск', + removeRecentSearchButtonTitle: 'Удалить этот поиск из истории', + favoriteSearchesTitle: 'Избранное', + removeFavoriteSearchButtonTitle: 'Удалить этот поиск из избранного', + recentConversationsTitle: 'Недавние разговоры', + removeRecentConversationButtonTitle: + 'Удалить этот разговор из истории' }, noResultsScreen: { - noResultsText: 'Нет результатов для', - suggestedQueryText: 'Вы можете попытаться узнать', + noResultsText: 'Не найдено результатов для', + suggestedQueryText: 'Попробуйте поискать', reportMissingResultsText: - 'Считаете, что поиск даёт ложные результаты?', - reportMissingResultsLinkText: 'Нажмите на кнопку «Обратная связь»' + 'Считаете, что по этому запросу должны быть результаты?', + reportMissingResultsLinkText: 'Сообщите нам.' + }, + resultsScreen: { + askAiPlaceholder: 'Спросить ИИ: ', + noResultsAskAiPlaceholder: + 'Не нашли в документации? Попросите Ask AI помочь: ' + }, + askAiScreen: { + disclaimerText: + 'Ответы генерируются ИИ и могут содержать ошибки. Проверьте их.', + relatedSourcesText: 'Связанные источники', + thinkingText: 'Думаю...', + copyButtonText: 'Копировать', + copyButtonCopiedText: 'Скопировано!', + copyButtonTitle: 'Копировать', + likeButtonTitle: 'Нравится', + dislikeButtonTitle: 'Не нравится', + thanksForFeedbackText: 'Спасибо за отзыв!', + preToolCallText: 'Ищу...', + duringToolCallText: 'Ищу...', + afterToolCallText: 'Искал', + stoppedStreamingText: 'Вы остановили этот ответ', + errorTitleText: 'Ошибка чата', + threadDepthExceededMessage: + 'Этот разговор закрыт, чтобы сохранить точность ответов.', + startNewConversationButtonText: 'Начать новый разговор' + } + } + }, + askAi: { + sidePanel: { + button: { + translations: { + buttonText: 'Спросить ИИ', + buttonAriaLabel: 'Спросить ИИ' + } + }, + panel: { + translations: { + header: { + title: 'Спросить ИИ', + conversationHistoryTitle: 'Моя история разговоров', + newConversationText: 'Начать новый разговор', + viewConversationHistoryText: 'История разговоров' + }, + promptForm: { + promptPlaceholderText: 'Задайте вопрос', + promptAnsweringText: 'Отвечаю...', + promptAskAnotherQuestionText: 'Задайте другой вопрос', + promptDisclaimerText: + 'Ответы генерируются ИИ и могут содержать ошибки.', + promptLabelText: + 'Нажмите Enter, чтобы отправить, или Shift+Enter для новой строки.', + promptAriaLabelText: 'Ввод запроса' + }, + conversationScreen: { + preToolCallText: 'Ищу...', + searchingText: 'Ищу...', + toolCallResultText: 'Искал', + conversationDisclaimer: + 'Ответы генерируются ИИ и могут содержать ошибки. Проверьте их.', + reasoningText: 'Рассуждаю...', + thinkingText: 'Думаю...', + relatedSourcesText: 'Связанные источники', + stoppedStreamingText: 'Вы остановили этот ответ', + copyButtonText: 'Копировать', + copyButtonCopiedText: 'Скопировано!', + likeButtonTitle: 'Нравится', + dislikeButtonTitle: 'Не нравится', + thanksForFeedbackText: 'Спасибо за отзыв!', + errorTitleText: 'Ошибка чата' + }, + newConversationScreen: { + titleText: 'Чем могу помочь сегодня?', + introductionText: + 'Я ищу по вашей документации, чтобы быстро помочь найти руководства по настройке, детали функций и советы по устранению неполадок.' + }, + logo: { + poweredByText: 'При поддержке' + } + } } } } diff --git a/docs/ru/guide/deploy.md b/docs/ru/guide/deploy.md index ff12be6c9..3b310524a 100644 --- a/docs/ru/guide/deploy.md +++ b/docs/ru/guide/deploy.md @@ -105,7 +105,7 @@ Cache-Control: max-age=31536000,immutable ## Руководства по платформам {#platform-guides} -### Netlify / Vercel / Cloudflare Pages / AWS Amplify / Render {#netlify-vercel-cloudflare-pages-aws-amplify-render} +### Netlify / Vercel / Cloudflare Pages / AWS Amplify / Render {#generic} Создайте новый проект и измените эти настройки с помощью панели управления: @@ -117,7 +117,7 @@ Cache-Control: max-age=31536000,immutable Не включайте такие опции, как _Auto Minify_ для HTML-кода. Он удалит из вывода комментарии, которые имеют значение для Vue. При их удалении могут возникать ошибки несоответствия гидратации. ::: -### GitHub Pages {#github-pages} +### GitHub Pages 1. Создайте файл с именем `deploy.yml` в директории `.github/workflows` вашего проекта с примерно таким содержанием: @@ -153,17 +153,17 @@ Cache-Control: max-age=31536000,immutable runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: fetch-depth: 0 # Не требуется, если функция lastUpdated не включена - # - uses: pnpm/action-setup@v3 # Раскомментируйте, если вы используете pnpm + # - uses: pnpm/action-setup@v4 # Раскомментируйте, если вы используете pnpm # with: # version: 9 # - uses: oven-sh/setup-bun@v1 # Раскомментируйте, если вы используете Bun - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 with: - node-version: 22 + node-version: 24 cache: npm # или pnpm / yarn - name: Setup Pages uses: actions/configure-pages@v4 @@ -198,7 +198,7 @@ Cache-Control: max-age=31536000,immutable 3. Внесите свои изменения в ветку `main` и дождитесь завершения процесса GitHub Actions. Вы должны увидеть, что ваш сайт развёрнут по адресу `https://.github.io/[repository]/` или `https:///` в зависимости от ваших настроек. Ваш сайт будет автоматически разворачиваться при каждом внесении изменений в ветке `main`. -### GitLab Pages {#gitlab-pages} +### GitLab Pages 1. Установите значение `../public` для параметра `outDir` в конфигурации VitePress. Настройте опцию `base` на `'/<репозиторий>/'`, если вы хотите развернуть ваш проект по адресу `https://<имя пользователя>.gitlab.io/<репозиторий>/`. Вам не нужна опция `base`, если вы выполняете развёртывание на личном домене, страницах пользователя или группы, или если в GitLab включен параметр «Использовать уникальный домен». @@ -221,7 +221,7 @@ Cache-Control: max-age=31536000,immutable - main ``` -### Статические веб-приложения Azure {#azure-static-web-apps} +### Azure 1. Следуйте [официальной документации](https://docs.microsoft.com/ru-ru/azure/static-web-apps/build-configuration). @@ -231,7 +231,11 @@ Cache-Control: max-age=31536000,immutable - **`output_location`**: `docs/.vitepress/dist` - **`app_build_command`**: `npm run docs:build` -### Firebase {#firebase} +### CloudRay + +Вы можете развернуть свой проект VitePress с [CloudRay](https://cloudray.io/), следуя этим [инструкциям](https://cloudray.io/articles/how-to-deploy-vitepress-site). + +### Firebase 1. Создайте `firebase.json` и `.firebaserc` в корне вашего проекта: @@ -262,15 +266,7 @@ Cache-Control: max-age=31536000,immutable firebase deploy ``` -### Surge {#surge} - -1. После запуска `npm run docs:build` выполните эту команду для развёртывания: - - ```sh - npx surge docs/.vitepress/dist - ``` - -### Heroku {#heroku} +### Heroku 1. Следуйте документации и руководству, приведённому в [`heroku-buildpack-static`](https://elements.heroku.com/buildpacks/heroku/heroku-buildpack-static). @@ -282,11 +278,11 @@ Cache-Control: max-age=31536000,immutable } ``` -### Edgio {#edgio} +### Hostinger -См. [Создание и развёртывание приложения VitePress в Edgio](https://docs.edg.io/applications/v6/sites_frameworks/getting_started/vitepress). +Вы можете развернуть свой проект VitePress на [Hostinger](https://www.hostinger.com/web-apps-hosting), следуя этим [инструкциям](https://www.hostinger.com/support/how-to-deploy-a-nodejs-website-in-hostinger/). При настройке параметров сборки выберите VitePress в качестве фреймворка и укажите корневой каталог `./docs`. -### Хостинг статических файлов Kinsta {#kinsta-static-site-hosting} +### Kinsta Вы можете развернуть свой сайт VitePress на [Kinsta](https://kinsta.com/static-site-hosting/), следуя этим [инструкциям](https://kinsta.com/docs/vitepress-static-site-example/). @@ -294,6 +290,14 @@ Cache-Control: max-age=31536000,immutable Вы можете развернуть свой проект VitePress на [Stormkit](https://www.stormkit.io), следуя следующим [инструкциям](https://stormkit.io/blog/how-to-deploy-vitepress). +### Surge + +1. После запуска `npm run docs:build` выполните эту команду для развёртывания: + + ```sh + npx surge docs/.vitepress/dist + ``` + ### Nginx Вот пример конфигурации блока сервера Nginx. Эта настройка включает сжатие gzip для общих текстовых ресурсов, правила обслуживания статических файлов вашего сайта VitePress с правильными заголовками кэширования и обработку параметра `cleanUrls: true`. diff --git a/docs/ru/guide/extending-default-theme.md b/docs/ru/guide/extending-default-theme.md index 4443b8828..b1497ced1 100644 --- a/docs/ru/guide/extending-default-theme.md +++ b/docs/ru/guide/extending-default-theme.md @@ -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 21e8dcb03..4ca5ff8c6 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 dbb398ac9..6e0cd5670 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/] }) ``` @@ -795,7 +795,7 @@ export default config ## Основы - + ``` **Файл части** (`parts/basics.md`) @@ -831,7 +831,7 @@ export default config ## Основы - + ``` **Файл части** (`parts/basics.md`) @@ -867,8 +867,8 @@ export default config ## Основы - - + + ``` **Часть файла** (`parts/basics.md`) @@ -919,7 +919,7 @@ export default config ```md ## Мой дополнительный раздел - + ``` **Соответствующий код** @@ -943,7 +943,7 @@ export default config и включить его следующим образом: ```md - + ``` ## Математические уравнения {#math-equations} @@ -951,7 +951,7 @@ export default config В настоящее время эта фича предоставляется по желанию. Чтобы включить её, вам нужно установить `markdown-it-mathjax3` и установить значение `true` для опции `markdown.math` в вашем файле конфигурации: ```sh -npm add -D markdown-it-mathjax3 +npm add -D markdown-it-mathjax3@^4 ``` ```ts [.vitepress/config.ts] diff --git a/docs/ru/guide/what-is-vitepress.md b/docs/ru/guide/what-is-vitepress.md index 1bcc3e18e..90b07e9e5 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://ru.wikipedia.org/wiki/%D0%93%D0%B5%D0%BD%D0%B5%D1%80%D0%B0%D1%82%D0%BE%D1%80%D1%8B_%D1%81%D1%82%D0%B0%D1%82%D0%B8%D1%87%D0%B5%D1%81%D0%BA%D0%B8%D1%85_%D1%81%D0%B0%D0%B9%D1%82%D0%BE%D0%B2) (ГСС), предназначенный для быстрого создания сайтов, ориентированных на контент. В двух словах, VitePress берёт ваш исходный контент, написанный на [Markdown](https://ru.wikipedia.org/wiki/Markdown), применяет к нему тему и генерирует статические HTML-страницы, которые можно легко развернуть в любом месте.
@@ -12,13 +12,13 @@ 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://vite-docs.ru/), [Rollup](https://rollupjs.org/), [Pinia](https://pinia-ru.netlify.app), [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=/%22vitepress%22:+/+path:/(?:package%7Cdeno)%5C.jsonc?$/+NOT+is:fork+NOT+is:archived&type=code). - [Официальная документация Vue.js](https://vuejs.org/) также основана на VitePress, но использует пользовательскую тему, разделяемую между несколькими переводами. + [Официальная документация Vue.js](https://vuejs.org/) также основана на VitePress, но использует кастомную тему, общую для нескольких переводов. - **Блоги, портфолио и маркетинговые сайты** - VitePress поддерживает [полностью кастомизированные темы](./custom-theme), при этом разработчики могут использовать стандартное приложение Vite + Vue. То, что он построен на базе Vite, также означает, что вы можете напрямую использовать плагины Vite из его богатой экосистемы. Кроме того, VitePress предоставляет гибкие API для [загрузки данных](./data-loading) (локальной или удаленной) и [динамической генерации маршрутов](./routing#dynamic-routes). С его помощью можно построить практически всё, что угодно, если данные могут быть определены во время сборки. + VitePress поддерживает [полностью кастомизированные темы](./custom-theme), при этом разработчики могут использовать стандартное приложение Vite + Vue. То, что он построен на базе Vite, также означает, что вы можете напрямую использовать плагины Vite из его богатой экосистемы. Кроме того, VitePress предоставляет гибкие API для [загрузки данных](./data-loading) (локальной или удалённой) и [динамической генерации маршрутов](./routing#dynamic-routes). С его помощью можно построить практически всё, что угодно, если данные могут быть определены во время сборки. Официальный [блог Vue.js](https://blog.vuejs.org/) — это простой блог, который генерирует свою индексную страницу на основе локального контента. @@ -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 e5bc77327..faa45e785 100644 --- a/docs/ru/index.md +++ b/docs/ru/index.md @@ -8,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/default-theme-config.md b/docs/ru/reference/default-theme-config.md index 2eb955709..27b704438 100644 --- a/docs/ru/reference/default-theme-config.md +++ b/docs/ru/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/ru/reference/default-theme-last-updated.md b/docs/ru/reference/default-theme-last-updated.md index 4a0509f42..88c91afe0 100644 --- a/docs/ru/reference/default-theme-last-updated.md +++ b/docs/ru/reference/default-theme-last-updated.md @@ -11,7 +11,7 @@ VitePress отображает время «последнего обновле ```yaml{4} - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: fetch-depth: 0 ``` diff --git a/docs/ru/reference/default-theme-nav.md b/docs/ru/reference/default-theme-nav.md index 41257de85..edfb9a9e0 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 bab3fa9e7..16bad58d3 100644 --- a/docs/ru/reference/default-theme-search.md +++ b/docs/ru/reference/default-theme-search.md @@ -29,6 +29,7 @@ export default defineConfig({ - - - +- ### i18n {#local-search-i18n} @@ -43,25 +44,25 @@ export default defineConfig({ provider: 'local', options: { locales: { - ru: { // используйте ключ `root`, если хотите перевести локаль по умолчанию + ru: { // используйте `root`, если хотите перевести локаль по умолчанию translations: { button: { buttonText: 'Поиск', buttonAriaLabel: 'Поиск' }, modal: { - displayDetails: 'Отобразить подробный список', + displayDetails: 'Показать подробный список', resetButtonTitle: 'Сбросить поиск', backButtonTitle: 'Закрыть поиск', - noResultsText: 'Нет результатов по запросу', + noResultsText: 'Нет результатов', footer: { - selectText: 'выбрать', - selectKeyAriaLabel: 'выбрать', - navigateText: 'перейти', - navigateUpKeyAriaLabel: 'стрелка вверх', - navigateDownKeyAriaLabel: 'стрелка вниз', - closeText: 'закрыть', - closeKeyAriaLabel: 'esc' + selectText: 'Выбрать', + selectKeyAriaLabel: 'Enter', + navigateText: 'Навигация', + navigateUpKeyAriaLabel: 'Стрелка вверх', + navigateDownKeyAriaLabel: 'Стрелка вниз', + closeText: 'Закрыть', + closeKeyAriaLabel: 'Esc' } } } @@ -127,7 +128,7 @@ export default defineConfig({ * @param {import('markdown-it-async')} md */ async _render(src, env, md) { - // возвращаем html + // вернуть строку HTML } } } @@ -178,7 +179,7 @@ export default defineConfig({ 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 (await md.renderAsync(`# ${env.frontmatter.title}`)) + html return html } } @@ -212,6 +213,19 @@ export default defineConfig({ Пример конфигурации для использования многоязычного поиска: +
+Нажмите, чтобы развернуть + +<<< @/snippets/algolia-i18n.ts + +
+ +Подробности см. в [официальной документации Algolia](https://docsearch.algolia.com/docs/api#translations). Чтобы быстрее начать, можно также скопировать переводы, используемые на этом сайте, из [нашего репозитория GitHub](https://github.com/search?q=repo:vuejs/vitepress+%22function+searchOptions%22&type=code). + +### Поддержка Ask AI в Algolia {#ask-ai} + +Если вы хотите добавить функцию **Ask AI**, передайте параметр `askAi` (или любые из его отдельных полей) внутри объекта `options`: + ```ts import { defineConfig } from 'vitepress' @@ -223,49 +237,51 @@ export default defineConfig({ appId: '...', apiKey: '...', indexName: '...', - locales: { - ru: { - placeholder: 'Поиск в документации', - translations: { - button: { - buttonText: 'Поиск', - buttonAriaLabel: 'Поиск' - }, - modal: { - searchBox: { - resetButtonTitle: 'Сбросить поиск', - resetButtonAriaLabel: 'Сбросить поиск', - cancelButtonText: 'Отменить поиск', - cancelButtonAriaLabel: 'Отменить поиск' - }, - startScreen: { - recentSearchesTitle: 'История поиска', - noRecentSearchesText: 'Нет истории поиска', - saveRecentSearchButtonTitle: 'Сохранить в истории поиска', - removeRecentSearchButtonTitle: 'Удалить из истории поиска', - favoriteSearchesTitle: 'Избранное', - removeFavoriteSearchButtonTitle: 'Удалить из избранного' - }, - errorScreen: { - titleText: 'Невозможно получить результаты', - helpText: - 'Вам может потребоваться проверить подключение к Интернету' - }, - footer: { - selectText: 'выбрать', - navigateText: 'перейти', - closeText: 'закрыть', - searchByText: 'поставщик поиска' - }, - noResultsScreen: { - noResultsText: 'Нет результатов для', - suggestedQueryText: 'Вы можете попытаться узнать', - reportMissingResultsText: - 'Считаете, что поиск даёт ложные результаты?', - reportMissingResultsLinkText: - 'Нажмите на кнопку «Обратная связь»' - } - } + // askAi: "ВАШ-ID-АССИСТЕНТА" + // ИЛИ + askAi: { + // как минимум нужно указать assistantId, полученный от Algolia + assistantId: 'XXXYYY', + // необязательные переопределения — если их нет, используются значения appId/apiKey/indexName верхнего уровня + // apiKey: '...', + // appId: '...', + // indexName: '...' + } + } + } + } +}) +``` + +::: warning Примечание +Если вы хотите использовать обычный поиск по ключевым словам без Ask AI, просто не указывайте свойство `askAi` +::: + +### Боковая панель Ask AI {#ask-ai-side-panel} + +DocSearch v4.5+ поддерживает опциональную **боковую панель Ask AI**. Когда она включена, её можно открыть с помощью **Ctrl/Cmd+I** по умолчанию. [Справочник API боковой панели](https://docsearch.algolia.com/docs/sidepanel/api-reference) содержит полный список опций. + +```ts +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + search: { + provider: 'algolia', + options: { + appId: '...', + apiKey: '...', + indexName: '...', + askAi: { + assistantId: 'XXXYYY', + sidePanel: { + // Отражает API @docsearch/sidepanel-js SidepanelProps + panel: { + variant: 'floating', // или 'inline' + side: 'right', + width: '360px', + expandedWidth: '580px', + suggestedQuestions: true } } } @@ -275,112 +291,70 @@ export default defineConfig({ }) ``` -[Эти параметры](https://github.com/vuejs/vitepress/blob/main/types/docsearch.d.ts) можно переопределить. Чтобы узнать о них больше, обратитесь к официальной документации Algolia. +Если вам нужно отключить сочетание клавиш, используйте опцию `keyboardShortcuts` боковой панели: -### Конфигурация поискового робота {#crawler-config} +```ts +import { defineConfig } from 'vitepress' -Вот пример конфигурации, основанной на той, что используется на этом сайте: +export default defineConfig({ + themeConfig: { + search: { + provider: 'algolia', + options: { + appId: '...', + apiKey: '...', + indexName: '...', + askAi: { + assistantId: 'XXXYYY', + sidePanel: { + keyboardShortcuts: { + 'Ctrl/Cmd+I': false + } + } + } + } + } + } +}) +``` + +#### Режим (auto / sidePanel / hybrid / modal) {#ask-ai-mode} + +Вы можете опционально контролировать, как VitePress интегрирует поиск по ключевым словам и Ask AI: + +- `mode: 'auto'` (по умолчанию): выводит `hybrid`, когда настроен поиск по ключевым словам, иначе `sidePanel`, когда настроена боковая панель Ask AI. +- `mode: 'sidePanel'`: принудительно использовать только боковую панель (скрывает кнопку поиска по ключевым словам). +- `mode: 'hybrid'`: включает модальное окно поиска по ключевым словам + боковую панель Ask AI (требует настройки поиска по ключевым словам). +- `mode: 'modal'`: сохраняет Ask AI внутри модального окна DocSearch (даже если вы настроили боковую панель). + +#### Только Ask AI (без поиска по ключевым словам) {#ask-ai-only} + +Если вы хотите использовать **только боковую панель Ask AI**, вы можете опустить конфигурацию поиска по ключевым словам верхнего уровня и предоставить учётные данные в `askAi`: ```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 - }) +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + search: { + provider: 'algolia', + options: { + mode: 'sidePanel', + askAi: { + assistantId: 'XXXYYY', + appId: '...', + apiKey: '...', + indexName: '...', + sidePanel: 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' - } } }) ``` + +### Конфигурация поискового робота {#crawler-config} + +Вот пример конфигурации, основанной на той, что используется на этом сайте: + +<<< @/snippets/algolia-crawler.js diff --git a/docs/ru/reference/site-config.md b/docs/ru/reference/site-config.md index 50bd132cd..74508e044 100644 --- a/docs/ru/reference/site-config.md +++ b/docs/ru/reference/site-config.md @@ -24,7 +24,7 @@ export default { } ``` -:::details Динамическая (асинхронная) конфигурация +::: details Динамическая (асинхронная) конфигурация Если вам нужно генерировать конфигурацию динамически, вы также можете экспортировать функцию по умолчанию. Например: @@ -439,7 +439,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/snippets/algolia-crawler.js b/docs/snippets/algolia-crawler.js new file mode 100644 index 000000000..054afa56c --- /dev/null +++ b/docs/snippets/algolia-crawler.js @@ -0,0 +1,101 @@ +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/snippets/algolia-i18n.ts b/docs/snippets/algolia-i18n.ts new file mode 100644 index 000000000..c57816c38 --- /dev/null +++ b/docs/snippets/algolia-i18n.ts @@ -0,0 +1,155 @@ +import { defineConfig } from 'vitepress' + +export default defineConfig({ + themeConfig: { + search: { + provider: 'algolia', + options: { + appId: '...', + apiKey: '...', + indexName: '...', + locales: { + zh: { + translations: { + button: { + buttonText: '搜索', + buttonAriaLabel: '搜索' + }, + modal: { + searchBox: { + clearButtonTitle: '清除', + clearButtonAriaLabel: '清除查询', + closeButtonText: '关闭', + closeButtonAriaLabel: '关闭', + placeholderText: '搜索文档或向 AI 提问', + placeholderTextAskAi: '再问一个问题...', + placeholderTextAskAiStreaming: '正在回答...', + searchInputLabel: '搜索', + backToKeywordSearchButtonText: '返回关键词搜索', + backToKeywordSearchButtonAriaLabel: '返回关键词搜索', + newConversationPlaceholder: '提问', + conversationHistoryTitle: '我的对话历史', + startNewConversationText: '开始新的对话', + viewConversationHistoryText: '对话历史', + threadDepthErrorPlaceholder: '对话已达上限' + }, + newConversation: { + newConversationTitle: '我今天能帮你什么?', + newConversationDescription: + '我会搜索你的文档,快速帮你找到设置指南、功能细节和故障排除提示。' + }, + footer: { + selectText: '选择', + submitQuestionText: '提交问题', + selectKeyAriaLabel: '回车键', + navigateText: '导航', + navigateUpKeyAriaLabel: '向上箭头', + navigateDownKeyAriaLabel: '向下箭头', + closeText: '关闭', + backToSearchText: '返回搜索', + closeKeyAriaLabel: 'Esc 键', + poweredByText: '由…提供支持' + }, + errorScreen: { + titleText: '无法获取结果', + helpText: '你可能需要检查网络连接。' + }, + startScreen: { + recentSearchesTitle: '最近', + noRecentSearchesText: '暂无最近搜索', + saveRecentSearchButtonTitle: '保存此搜索', + removeRecentSearchButtonTitle: '从历史记录中移除此搜索', + favoriteSearchesTitle: '收藏', + removeFavoriteSearchButtonTitle: '从收藏中移除此搜索', + recentConversationsTitle: '最近对话', + removeRecentConversationButtonTitle: '从历史记录中移除此对话' + }, + noResultsScreen: { + noResultsText: '未找到相关结果', + suggestedQueryText: '尝试搜索', + reportMissingResultsText: '认为此查询应该有结果?', + reportMissingResultsLinkText: '告诉我们。' + }, + resultsScreen: { + askAiPlaceholder: '询问 AI:', + noResultsAskAiPlaceholder: '文档里没找到?让 Ask AI 帮忙:' + }, + askAiScreen: { + disclaimerText: '回答由 AI 生成,可能会出错。请核实。', + relatedSourcesText: '相关来源', + thinkingText: '思考中...', + copyButtonText: '复制', + copyButtonCopiedText: '已复制!', + copyButtonTitle: '复制', + likeButtonTitle: '喜欢', + dislikeButtonTitle: '不喜欢', + thanksForFeedbackText: '感谢你的反馈!', + preToolCallText: '搜索中...', + duringToolCallText: '搜索中...', + afterToolCallText: '已搜索', + stoppedStreamingText: '你已停止此回复', + errorTitleText: '聊天错误', + threadDepthExceededMessage: '为保持回答准确,此对话已关闭。', + startNewConversationButtonText: '开始新的对话' + } + } + }, + askAi: { + sidePanel: { + button: { + translations: { + buttonText: '询问 AI', + buttonAriaLabel: '询问 AI' + } + }, + panel: { + translations: { + header: { + title: '询问 AI', + conversationHistoryTitle: '我的对话历史', + newConversationText: '开始新的对话', + viewConversationHistoryText: '对话历史' + }, + promptForm: { + promptPlaceholderText: '提问', + promptAnsweringText: '正在回答...', + promptAskAnotherQuestionText: '再问一个问题', + promptDisclaimerText: '回答由 AI 生成,可能会出错。', + promptLabelText: '按回车发送,Shift+回车换行。', + promptAriaLabelText: '问题输入' + }, + conversationScreen: { + preToolCallText: '搜索中...', + searchingText: '搜索中...', + toolCallResultText: '已搜索', + conversationDisclaimer: + '回答由 AI 生成,可能会出错。请核实。', + reasoningText: '推理中...', + thinkingText: '思考中...', + relatedSourcesText: '相关来源', + stoppedStreamingText: '你已停止此回复', + copyButtonText: '复制', + copyButtonCopiedText: '已复制!', + likeButtonTitle: '喜欢', + dislikeButtonTitle: '不喜欢', + thanksForFeedbackText: '感谢你的反馈!', + errorTitleText: '聊天错误' + }, + newConversationScreen: { + titleText: '我今天能帮你什么?', + introductionText: + '我会搜索你的文档,快速帮你找到设置指南、功能细节和故障排除提示。' + }, + logo: { + poweredByText: '由…提供支持' + } + } + } + } + } + } + } + } + } + } +}) diff --git a/docs/zh/config.ts b/docs/zh/config.ts index 22fb8b951..91687c542 100644 --- a/docs/zh/config.ts +++ b/docs/zh/config.ts @@ -5,7 +5,6 @@ const require = createRequire(import.meta.url) const pkg = require('vitepress/package.json') export default defineAdditionalConfig({ - lang: 'zh-Hans', description: '由 Vite 和 Vue 驱动的静态站点生成器', themeConfig: { @@ -25,7 +24,7 @@ export default defineAdditionalConfig({ footer: { message: '基于 MIT 许可发布', - copyright: `版权所有 © 2019-${new Date().getFullYear()} 尤雨溪` + copyright: '版权所有 © 2019-至今 尤雨溪' }, docFooter: { @@ -74,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' @@ -168,42 +171,139 @@ function sidebarReference(): DefaultTheme.SidebarItem[] { function searchOptions(): Partial { return { - placeholder: '搜索文档', translations: { button: { - buttonText: '搜索文档', - buttonAriaLabel: '搜索文档' + buttonText: '搜索', + buttonAriaLabel: '搜索' }, modal: { searchBox: { - resetButtonTitle: '清除查询条件', - resetButtonAriaLabel: '清除查询条件', - cancelButtonText: '取消', - cancelButtonAriaLabel: '取消' - }, - startScreen: { - recentSearchesTitle: '搜索历史', - noRecentSearchesText: '没有搜索历史', - saveRecentSearchButtonTitle: '保存至搜索历史', - removeRecentSearchButtonTitle: '从搜索历史中移除', - favoriteSearchesTitle: '收藏', - removeFavoriteSearchButtonTitle: '从收藏中移除' + clearButtonTitle: '清除', + clearButtonAriaLabel: '清除查询', + closeButtonText: '关闭', + closeButtonAriaLabel: '关闭', + placeholderText: '搜索文档或向 AI 提问', + placeholderTextAskAi: '再问一个问题...', + placeholderTextAskAiStreaming: '正在回答...', + searchInputLabel: '搜索', + backToKeywordSearchButtonText: '返回关键词搜索', + backToKeywordSearchButtonAriaLabel: '返回关键词搜索', + newConversationPlaceholder: '提问', + conversationHistoryTitle: '我的对话历史', + startNewConversationText: '开始新的对话', + viewConversationHistoryText: '对话历史', + threadDepthErrorPlaceholder: '对话已达上限' }, - errorScreen: { - titleText: '无法获取结果', - helpText: '你可能需要检查你的网络连接' + newConversation: { + newConversationTitle: '我今天能帮你什么?', + newConversationDescription: + '我会搜索你的文档,快速帮你找到设置指南、功能细节和故障排除提示。' }, footer: { selectText: '选择', - navigateText: '切换', + submitQuestionText: '提交问题', + selectKeyAriaLabel: '回车键', + navigateText: '导航', + navigateUpKeyAriaLabel: '向上箭头', + navigateDownKeyAriaLabel: '向下箭头', closeText: '关闭', - searchByText: '搜索提供者' + backToSearchText: '返回搜索', + closeKeyAriaLabel: 'Esc 键', + poweredByText: '由…提供支持' + }, + errorScreen: { + titleText: '无法获取结果', + helpText: '你可能需要检查网络连接。' + }, + startScreen: { + recentSearchesTitle: '最近', + noRecentSearchesText: '暂无最近搜索', + saveRecentSearchButtonTitle: '保存此搜索', + removeRecentSearchButtonTitle: '从历史记录中移除此搜索', + favoriteSearchesTitle: '收藏', + removeFavoriteSearchButtonTitle: '从收藏中移除此搜索', + recentConversationsTitle: '最近对话', + removeRecentConversationButtonTitle: '从历史记录中移除此对话' }, noResultsScreen: { - noResultsText: '无法找到相关结果', - suggestedQueryText: '你可以尝试查询', - reportMissingResultsText: '你认为该查询应该有结果?', - reportMissingResultsLinkText: '点击反馈' + noResultsText: '未找到相关结果', + suggestedQueryText: '尝试搜索', + reportMissingResultsText: '认为此查询应该有结果?', + reportMissingResultsLinkText: '告诉我们。' + }, + resultsScreen: { + askAiPlaceholder: '询问 AI:', + noResultsAskAiPlaceholder: '文档里没找到?让 Ask AI 帮忙:' + }, + askAiScreen: { + disclaimerText: '回答由 AI 生成,可能会出错。请核实。', + relatedSourcesText: '相关来源', + thinkingText: '思考中...', + copyButtonText: '复制', + copyButtonCopiedText: '已复制!', + copyButtonTitle: '复制', + likeButtonTitle: '喜欢', + dislikeButtonTitle: '不喜欢', + thanksForFeedbackText: '感谢你的反馈!', + preToolCallText: '搜索中...', + duringToolCallText: '搜索中...', + afterToolCallText: '已搜索', + stoppedStreamingText: '你已停止此回复', + errorTitleText: '聊天错误', + threadDepthExceededMessage: '为保持回答准确,此对话已关闭。', + startNewConversationButtonText: '开始新的对话' + } + } + }, + askAi: { + sidePanel: { + button: { + translations: { + buttonText: '询问 AI', + buttonAriaLabel: '询问 AI' + } + }, + panel: { + translations: { + header: { + title: '询问 AI', + conversationHistoryTitle: '我的对话历史', + newConversationText: '开始新的对话', + viewConversationHistoryText: '对话历史' + }, + promptForm: { + promptPlaceholderText: '提问', + promptAnsweringText: '正在回答...', + promptAskAnotherQuestionText: '再问一个问题', + promptDisclaimerText: '回答由 AI 生成,可能会出错。', + promptLabelText: '按回车发送,Shift+回车换行。', + promptAriaLabelText: '问题输入' + }, + conversationScreen: { + preToolCallText: '搜索中...', + searchingText: '搜索中...', + toolCallResultText: '已搜索', + conversationDisclaimer: '回答由 AI 生成,可能会出错。请核实。', + reasoningText: '推理中...', + thinkingText: '思考中...', + relatedSourcesText: '相关来源', + stoppedStreamingText: '你已停止此回复', + copyButtonText: '复制', + copyButtonCopiedText: '已复制!', + likeButtonTitle: '喜欢', + dislikeButtonTitle: '不喜欢', + thanksForFeedbackText: '感谢你的反馈!', + errorTitleText: '聊天错误' + }, + newConversationScreen: { + titleText: '我今天能帮你什么?', + introductionText: + '我会搜索你的文档,快速帮你找到设置指南、功能细节和故障排除提示。' + }, + logo: { + poweredByText: '由…提供支持' + } + } } } } diff --git a/docs/zh/guide/deploy.md b/docs/zh/guide/deploy.md index 54ed13d41..c0fafe388 100644 --- a/docs/zh/guide/deploy.md +++ b/docs/zh/guide/deploy.md @@ -105,7 +105,7 @@ Cache-Control: max-age=31536000,immutable ## 各平台部署指南 {#platform-guides} -### Netlify / Vercel / Cloudflare Pages / AWS Amplify / Render +### Netlify / Vercel / Cloudflare Pages / AWS Amplify / Render {#generic} 使用仪表板创建新项目并更改这些设置: @@ -153,17 +153,17 @@ Cache-Control: max-age=31536000,immutable runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: fetch-depth: 0 # 如果未启用 lastUpdated,则不需要 - # - uses: pnpm/action-setup@v3 # 如果使用 pnpm,请取消此区域注释 + # - uses: pnpm/action-setup@v4 # 如果使用 pnpm,请取消此区域注释 # with: # version: 9 # - uses: oven-sh/setup-bun@v1 # 如果使用 Bun,请取消注释 - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 with: - node-version: 22 + node-version: 24 cache: npm # 或 pnpm / yarn - name: Setup Pages uses: actions/configure-pages@v4 @@ -200,7 +200,7 @@ Cache-Control: max-age=31536000,immutable ### GitLab Pages -1. 如果你想部署到 `https:// .gitlab.io/ /`,将 VitePress 配置中的 `outDir` 设置为 `../public`。将 `base` 选项配置为 `'//'`。 +1. 如果你想部署到 `https:// .gitlab.io/ /`,将 VitePress 配置中的 `outDir` 设置为 `../public`。将 `base` 选项配置为 `'//'`。如果你部署到自定义域名、用户或组织页面,或在 GitLab 中启用了“Use unique domain”设置,则不需要 `base`。 2. 在项目的根目录中创建一个名为 `.gitlab-ci.yml` 的文件,其中包含以下内容。每当你更改内容时,这都会构建和部署你的站点: @@ -221,7 +221,7 @@ Cache-Control: max-age=31536000,immutable - main ``` -### Azure 静态 web 应用 {#azure-static-web-apps} +### Azure 1. 参考[官方文档](https://docs.microsoft.com/en-us/azure/static-web-apps/build-configuration)。 @@ -231,7 +231,11 @@ Cache-Control: max-age=31536000,immutable - **`output_location`**: `docs/.vitepress/dist` - **`app_build_command`**: `npm run docs:build` -### Firebase {#firebase} +### CloudRay + +你可以按照这些[说明](https://cloudray.io/articles/how-to-deploy-vitepress-site)使用 [CloudRay](https://cloudray.io/) 部署你的 VitePress 项目。 + +### Firebase 1. 在项目的根目录下创建 `firebase.json` 和 `.firebaserc`: @@ -262,14 +266,6 @@ Cache-Control: max-age=31536000,immutable firebase deploy ``` -### Surge - -1. 运行 `npm run docs:build` 后,运行此命令进行部署: - - ```sh - npx surge docs/.vitepress/dist - ``` - ### Heroku 1. 参考 [`heroku-buildpack-static`](https://elements.heroku.com/buildpacks/heroku/heroku-buildpack-static) 中给出的文档和指南。 @@ -282,11 +278,11 @@ Cache-Control: max-age=31536000,immutable } ``` -### Edgio +### Hostinger -请参阅[创建并部署 VitePress 应用程序到 Edgio](https://docs.edg.io/guides/vitepress)。 +你可以按照这些[说明](https://www.hostinger.com/support/how-to-deploy-a-nodejs-website-in-hostinger/)使用 [Hostinger](https://www.hostinger.com/web-apps-hosting) 部署你的 VitePress 项目。在配置构建设置时,选择 VitePress 作为框架,并将根目录调整为 `./docs`。 -### Kinsta 静态站点托管 {#kinsta-static-site-hosting} +### Kinsta 你可以按照这些[说明](https://kinsta.com/docs/vitepress-static-site-example/) 在 [Kinsta](https://kinsta.com/static-site-hosting/) 上部署 VitePress 站点。 @@ -294,6 +290,14 @@ Cache-Control: max-age=31536000,immutable 你可以按照这些[说明](https://stormkit.io/blog/how-to-deploy-vitepress)将你的 VitePress 项目部署到 [Stormkit](https://www.stormkit.io)。 +### Surge + +1. 运行 `npm run docs:build` 后,运行此命令进行部署: + + ```sh + npx surge docs/.vitepress/dist + ``` + ### Nginx 下面是一个 Nginx 服务器块配置示例。此配置包括对基于文本的常见资源的 gzip 压缩、使用适当缓存头为 VitePress 站点静态文件提供服务的规则以及处理 `cleanUrls: true` 的方法。 @@ -308,20 +312,20 @@ server { index index.html; location / { - # content location + # 内容位置 root /app; - # exact matches -> reverse clean urls -> folders -> not found + # 完全匹配 -> 反向清理 url -> 文件夹 -> 没有发现 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 + # 在此设置中,如果文件夹没有 index.html,就会引发 403 错误 error_page 403 /404.html; - # adjust caching headers - # files in the assets folder have hashes filenames + # 调整缓存标头 + # assets 文件夹中的文件都有哈希文件名 location ~* ^/assets/ { expires 1y; add_header Cache-Control "public, immutable"; diff --git a/docs/zh/guide/extending-default-theme.md b/docs/zh/guide/extending-default-theme.md index 4d19eea29..6218247d2 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)以了解其工作原理。 ::: @@ -55,8 +55,8 @@ export default DefaultTheme ```css /* .vitepress/theme/my-fonts.css */ :root { - --vp-font-family-base: /* normal text font */ - --vp-font-family-mono: /* code font */ + --vp-font-family-base: /* 普通文本字体 */ + --vp-font-family-mono: /* 代码字体 */ } ``` @@ -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 2d6453c95..183b32df6 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 308c49dfe..8f4694682 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} @@ -771,7 +771,7 @@ export default config ## Basics - + ``` **Part file** (`parts/basics.md`) @@ -807,7 +807,7 @@ Can be created using `.foorc.json`. ## Basics - + ``` **Part file** (`parts/basics.md`) @@ -843,7 +843,7 @@ Can be created using `.foorc.json`. 现在这是可选的。要启用它,需要安装 `markdown-it-mathjax3`,在配置文件中设置`markdown.math` 为 `true`: ```sh -npm add -D markdown-it-mathjax3 +npm add -D markdown-it-mathjax3@^4 ``` ```ts [.vitepress/config.ts] diff --git a/docs/zh/guide/routing.md b/docs/zh/guide/routing.md index 563323171..c48722ad0 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 be181feea..f9acaad49 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/VPDocFooterLastUpdated.vue b/src/client/theme-default/components/VPDocFooterLastUpdated.vue index 5ec3cfeb1..576a87d41 100644 --- a/src/client/theme-default/components/VPDocFooterLastUpdated.vue +++ b/src/client/theme-default/components/VPDocFooterLastUpdated.vue @@ -1,26 +1,38 @@ @@ -28,7 +40,7 @@ onMounted(() => { diff --git a/src/client/theme-default/components/VPDocOutlineItem.vue b/src/client/theme-default/components/VPDocOutlineItem.vue index c945fc21a..4cff1b384 100644 --- a/src/client/theme-default/components/VPDocOutlineItem.vue +++ b/src/client/theme-default/components/VPDocOutlineItem.vue @@ -5,18 +5,12 @@ defineProps<{ headers: DefaultTheme.OutlineItem[] root?: boolean }>() - -function onClick({ target: el }: Event) { - const id = (el as HTMLAnchorElement).href!.split('#')[1] - const heading = document.getElementById(decodeURIComponent(id)) - heading?.focus({ preventScroll: true }) -}