Merge branch 'main' into doc-zh

pull/2249/head
vanch 3 years ago
commit 88592c9e81

@ -30,6 +30,8 @@ After cloning the repo, run:
```sh
# install the dependencies of the project
$ pnpm install
# setup git hooks
$ pnpm simple-git-hooks
```
### Setup VitePress Dev Environment

@ -14,6 +14,7 @@ concurrency:
jobs:
action:
if: github.repository == 'vuejs/vitepress'
runs-on: ubuntu-latest
steps:
- uses: dessant/lock-threads@v4

@ -7,6 +7,7 @@ on:
jobs:
release:
if: github.repository == 'vuejs/vitepress'
runs-on: ubuntu-latest
steps:

@ -5,3 +5,5 @@ pnpm-lock.yaml
cache
template
temp
!CHANGELOG.md
.temp

File diff suppressed because it is too large Load Diff

@ -87,6 +87,14 @@ export default defineConfig({
title: 'Example',
description: 'An example app using VitePress.',
themeConfig: {
sidebar
sidebar,
search: {
provider: 'local',
options: {
exclude(relativePath) {
return relativePath.startsWith('local-search/excluded')
}
}
}
}
})

@ -0,0 +1 @@
# Local search config excluded

@ -0,0 +1,5 @@
---
search: false
---
# Local search frontmatter excluded

@ -0,0 +1 @@
# Local search included

@ -0,0 +1,31 @@
describe('local search', () => {
beforeEach(async () => {
await goto('/')
})
test('exclude content from search results', async () => {
await page.locator('#local-search button').click()
const input = await page.waitForSelector('input#localsearch-input')
await input.type('local')
await page.waitForSelector('ul#localsearch-list', { state: 'visible' })
const searchResults = page.locator('#localsearch-list')
expect(await searchResults.locator('li[role=option]').count()).toBe(1)
expect(
await searchResults.filter({ hasText: 'Local search included' }).count()
).toBe(1)
expect(
await searchResults.filter({ hasText: 'Local search excluded' }).count()
).toBe(0)
expect(
await searchResults
.filter({ hasText: 'Local search frontmatter excluded' })
.count()
).toBe(0)
})
})

@ -1,7 +1,11 @@
# Foo
This is before region
<!-- #region snippet -->
## Region
this is region
<!-- #endregion snippet -->
This is a region
<!-- #endregion snippet -->
This is after region

@ -180,3 +180,19 @@ export default config
## Markdown At File Inclusion
<!--@include: @/markdown-extensions/bar.md-->
## Markdown Nested File Inclusion
<!--@include: ./nested-include.md-->
## Markdown File Inclusion with Range
<!--@include: ./foo.md{6,8}-->
## Markdown File Inclusion with Range without Start
<!--@include: ./foo.md{,8}-->
## Markdown File Inclusion with Range without End
<!--@include: ./foo.md{6,}-->

@ -5,6 +5,8 @@ const getClassList = async (locator: Locator) => {
return className?.split(' ').filter(Boolean) ?? []
}
const trim = (str?: string | null) => str?.replace(/\u200B/g, '').trim()
beforeEach(async () => {
await goto('/markdown-extensions/')
})
@ -63,7 +65,7 @@ describe('Table of Contents', () => {
test('render toc', async () => {
const items = page.locator('#table-of-contents + nav ul li')
const count = await items.count()
expect(count).toBe(24)
expect(count).toBe(35)
})
})
@ -161,7 +163,7 @@ describe('Line Numbers', () => {
describe('Import Code Snippets', () => {
test('basic', async () => {
const lines = page.locator('#basic-code-snippet + div code > span')
expect(await lines.count()).toBe(7)
expect(await lines.count()).toBe(11)
})
test('specify region', async () => {
@ -214,7 +216,7 @@ describe('Code Groups', () => {
// blocks
const blocks = div.locator('.blocks > div')
expect(await blocks.nth(0).locator('code > span').count()).toBe(7)
expect(await blocks.nth(0).locator('code > span').count()).toBe(11)
expect(await getClassList(blocks.nth(1))).toContain('line-numbers-mode')
expect(await getClassList(blocks.nth(1))).toContain('language-ts')
expect(await blocks.nth(1).locator('code > span').count()).toBe(3)
@ -229,8 +231,47 @@ describe('Markdown File Inclusion', () => {
const h1 = page.locator('#markdown-file-inclusion + h1')
expect(await h1.getAttribute('id')).toBe('foo')
})
test('render markdown using @', async () => {
const h1 = page.locator('#markdown-at-file-inclusion + h1')
expect(await h1.getAttribute('id')).toBe('bar')
})
test('render markdown using nested inclusion', async () => {
const h1 = page.locator('#markdown-nested-file-inclusion + h1')
expect(await h1.getAttribute('id')).toBe('foo-1')
})
test('render markdown using nested inclusion inside sub folder', async () => {
const h1 = page.locator('#after-foo + h1')
expect(await h1.getAttribute('id')).toBe('inside-sub-folder')
const h2 = page.locator('#after-foo + h1 + h2')
expect(await h2.getAttribute('id')).toBe('sub-sub')
const h3 = page.locator('#after-foo + h1 + h2 + h3')
expect(await h3.getAttribute('id')).toBe('sub-sub-sub')
})
test('support selecting range', async () => {
const h2 = page.locator('#markdown-file-inclusion-with-range + h2')
expect(trim(await h2.textContent())).toBe('Region')
const p = page.locator('#markdown-file-inclusion-with-range + h2 + p')
expect(trim(await p.textContent())).toBe('This is a region')
})
test('support selecting range without specifying start', async () => {
const p = page.locator(
'#markdown-file-inclusion-with-range-without-start ~ p'
)
expect(trim(await p.nth(0).textContent())).toBe('This is before region')
expect(trim(await p.nth(1).textContent())).toBe('This is a region')
})
test('support selecting range without specifying end', async () => {
const p = page.locator(
'#markdown-file-inclusion-with-range-without-end ~ p'
)
expect(trim(await p.nth(0).textContent())).toBe('This is a region')
expect(trim(await p.nth(1).textContent())).toBe('This is after region')
})
})

@ -0,0 +1,5 @@
<!--@include: ./foo.md-->
### After Foo
<!--@include: ./subfolder/inside-subfolder.md-->

@ -0,0 +1,3 @@
# Inside sub folder
<!--@include: ./subsub/subsub.md-->

@ -0,0 +1,3 @@
## Sub sub
<!--@include: ./subsubsub/subsubsub.md-->

@ -1,6 +1,14 @@
{
"name": "tests-e2e",
"private": true,
"type": "module",
"scripts": {
"test": "vitest run",
"watch": "DEBUG=1 vitest",
"site:dev": "vitepress",
"site:build": "vitepress build",
"site:preview": "vitepress preview"
},
"devDependencies": {
"vitepress": "workspace:*"
}

@ -5,7 +5,7 @@ const timeout = 60_000
export default defineConfig({
test: {
setupFiles: ['vitestSetup.ts'],
globalSetup: ['__tests__/e2e/vitestGlobalSetup.ts'],
globalSetup: ['vitestGlobalSetup.ts'],
testTimeout: timeout,
hookTimeout: timeout,
teardownTimeout: timeout,

@ -7,7 +7,7 @@ import type { Server } from 'net'
let browserServer: BrowserServer
let server: ViteDevServer | Server
const root = '__tests__/e2e'
const root = '.'
export async function setup() {
browserServer = await chromium.launchServer({

@ -1,57 +1,50 @@
import { chromium, type Browser, type Page } from 'playwright-chromium'
import { fileURLToPath } from 'url'
import path from 'path'
import fs from 'fs-extra'
import {
scaffold,
build,
createServer,
serve,
ScaffoldThemeType,
type ScaffoldOptions
} from 'vitepress'
import type { ViteDevServer } from 'vite'
import type { Server } from 'net'
import getPort from 'get-port'
import { chromium } from 'playwright-chromium'
import { fileURLToPath, URL } from 'url'
import { createServer, scaffold, ScaffoldThemeType } from 'vitepress'
let browser: Browser
let page: Page
const root = fileURLToPath(new URL('./.temp', import.meta.url))
beforeAll(async () => {
browser = await chromium.connect(process.env['WS_ENDPOINT']!)
page = await browser.newPage()
const browser = await chromium.launch({
headless: !process.env.DEBUG,
args: process.env.CI
? ['--no-sandbox', '--disable-setuid-sandbox']
: undefined
})
const page = await browser.newPage()
const themes = [
ScaffoldThemeType.Default,
ScaffoldThemeType.DefaultCustom,
ScaffoldThemeType.Custom
]
const usingTs = [false, true]
const variations = themes.flatMap((theme) =>
usingTs.map(
(useTs) => [`${theme}${useTs ? ' + ts' : ''}`, { theme, useTs }] as const
)
)
afterAll(async () => {
await page.close()
await browser.close()
})
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), 'temp')
async function testVariation(options: ScaffoldOptions) {
fs.removeSync(root)
scaffold({
...options,
root
})
test.each(variations)('init %s', async (_, { theme, useTs }) => {
await fs.remove(root)
scaffold({ root, theme, useTs, injectNpmScripts: false })
let server: ViteDevServer | Server
const port = await getPort()
const server = await createServer(root, { port })
await server.listen()
async function goto(path: string) {
await page.goto(`http://localhost:${port}${path}`)
await page.waitForSelector('#app div')
}
if (process.env['VITE_TEST_BUILD']) {
await build(root)
server = (await serve({ root, port })).server
} else {
server = await createServer(root, { port })
await server!.listen()
}
try {
await goto('/')
expect(await page.textContent('h1')).toMatch('My Awesome Project')
@ -66,33 +59,10 @@ async function testVariation(options: ScaffoldOptions) {
await page.click('a[href="/api-examples.html"]')
await page.waitForSelector('pre code')
expect(await page.textContent('h1')).toMatch('Runtime API Examples')
} finally {
fs.removeSync(root)
if ('ws' in server) {
await server.close()
} else {
await new Promise<void>((resolve, reject) => {
server.close((error) => (error ? reject(error) : resolve()))
})
}
}
}
const themes = [
ScaffoldThemeType.Default,
ScaffoldThemeType.DefaultCustom,
ScaffoldThemeType.Custom
]
const usingTs = [false, true]
for (const theme of themes) {
for (const useTs of usingTs) {
test(`${theme}${useTs ? ` + TypeScript` : ``}`, () =>
testVariation({
root: '.',
theme,
useTs,
injectNpmScripts: false
}))
// teardown
} finally {
await fs.remove(root)
await server.close()
}
}
})

@ -1,6 +1,11 @@
{
"name": "tests-init",
"private": true,
"type": "module",
"scripts": {
"test": "vitest run",
"watch": "DEBUG=1 vitest"
},
"devDependencies": {
"vitepress": "workspace:*"
}

@ -1,20 +1,9 @@
import { dirname, resolve } from 'path'
import { fileURLToPath } from 'url'
import { defineConfig } from 'vitest/config'
const dir = dirname(fileURLToPath(import.meta.url))
const timeout = 60_000
export default defineConfig({
resolve: {
alias: {
node: resolve(dir, '../../src/node')
}
},
test: {
watchExclude: ['**/node_modules/**', '**/temp/**'],
globalSetup: ['__tests__/init/vitestGlobalSetup.ts'],
testTimeout: timeout,
hookTimeout: timeout,
teardownTimeout: timeout,

@ -1,17 +0,0 @@
import { chromium, type BrowserServer } from 'playwright-chromium'
let browserServer: BrowserServer
export async function setup() {
browserServer = await chromium.launchServer({
headless: !process.env.DEBUG,
args: process.env.CI
? ['--no-sandbox', '--disable-setuid-sandbox']
: undefined
})
process.env['WS_ENDPOINT'] = browserServer.wsEndpoint()
}
export async function teardown() {
await browserServer.close()
}

@ -1,17 +1,26 @@
import { dirname, resolve } from 'path'
import { fileURLToPath } from 'url'
import { defineConfig } from 'vitest/config'
import vue from '@vitejs/plugin-vue'
const dir = dirname(fileURLToPath(import.meta.url))
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'@siteData': resolve(dir, './shims.ts'),
client: resolve(dir, '../../src/client'),
node: resolve(dir, '../../src/node'),
vitepress: resolve(dir, '../../src/client')
}
alias: [
{ find: '@siteData', replacement: resolve(dir, './shims.ts') },
{ find: 'client', replacement: resolve(dir, '../../src/client') },
{ find: 'node', replacement: resolve(dir, '../../src/node') },
{
find: /^vitepress$/,
replacement: resolve(dir, '../../src/client/index.js')
},
{
find: /^vitepress\/theme$/,
replacement: resolve(dir, '../../src/client/theme-default/index.js')
}
]
},
test: {
globals: true

@ -12,6 +12,13 @@ export default defineConfig({
lastUpdated: true,
cleanUrls: true,
sitemap: {
hostname: 'https://vitepress.dev',
transformItems(items) {
return items.filter((item) => !item.url.includes('migration'))
}
},
head: [
['meta', { name: 'theme-color', content: '#3c8772' }],
[
@ -157,6 +164,10 @@ function sidebarGuide() {
{
text: 'MPA Mode',
link: '/guide/mpa-mode'
},
{
text: 'Sitemap Generation',
link: '/guide/sitemap-generation'
}
]
},

@ -31,6 +31,20 @@ There is one exception to this: if you have an HTML page in `public` and link to
- [/pure.html](/pure.html)
- <pathname:///pure.html>
Note that `pathname://` is only supported in Markdown links. Also, `pathname://` will open the link in a new tab by default. You can use `target="_self"` instead to open it in the same tab:
**Input**
```md
[Link to pure.html](/pure.html){target="_self"}
<!-- there is no need to specify pathname:// if the target is explicitly specified -->
```
**Output**
[Link to pure.html](/pure.html){target="_self"}
## Base URL
If your site is deployed to a non-root URL, you will need to set the `base` option in `.vitepress/config.js`. For example, if you plan to deploy your site to `https://foo.github.io/bar/`, then `base` should be set to `'/bar/'` (it should always start and end with a slash).

@ -23,7 +23,7 @@ The loader module is evaluated only in Node.js, so you can import Node APIs and
You can then import data from this file in `.md` pages and `.vue` components using the `data` named export:
```html
```vue
<script setup>
import { data } from './example.data.js'
</script>
@ -70,7 +70,7 @@ export default {
// watchedFiles will be an array of absolute paths of the matched files.
// generate an array of blog post metadata that can be used to render
// a list in the theme layout
return watchedFiles.map(file => {
return watchedFiles.map((file) => {
return parse(fs.readFileSync(file, 'utf-8'), {
columns: true,
skip_empty_lines: true
@ -91,7 +91,7 @@ import { createContentLoader } from 'vitepress'
export default createContentLoader('posts/*.md', /* options */)
```
The helper takes a glob pattern relative to [project root](./routing#project-root), and returns a `{ watch, load }` data loader object that can be used as the default export in a data loader file. It also implements caching based on file modified timestamps to improve dev performance.
The helper takes a glob pattern relative to the [source directory](./routing#source-directory), and returns a `{ watch, load }` data loader object that can be used as the default export in a data loader file. It also implements caching based on file modified timestamps to improve dev performance.
Note the loader only works with Markdown files - matched non-Markdown files will be skipped.
@ -147,9 +147,9 @@ export default createContentLoader('posts/*.md', {
// the final result is what will be shipped to the client.
return rawData.sort((a, b) => {
return +new Date(b.frontmatter.date) - +new Date(a.frontmatter.date)
}).map(page => {
page.src // raw markdown source
page.html // rendered full page HTML
}).map((page) => {
page.src // raw markdown source
page.html // rendered full page HTML
page.excerpt // rendered excerpt HTML (content above first `---`)
return {/* ... */}
})
@ -159,7 +159,7 @@ export default createContentLoader('posts/*.md', {
Check out how it is used in the [Vue.js blog](https://github.com/vuejs/blog/blob/main/.vitepress/theme/posts.data.ts).
The `createContentLoader` API can also be used inside [build hooks](/reference/site-config#build-hooks):
The `createContentLoader` API can also be used inside [build hooks](../reference/site-config#build-hooks):
```js
// .vitepress/config.js
@ -171,6 +171,48 @@ export default {
}
```
**Types**
```ts
interface ContentOptions<T = ContentData[]> {
/**
* Include src?
* @default false
*/
includeSrc?: boolean
/**
* Render src to HTML and include in data?
* @default false
*/
render?: boolean
/**
* If `boolean`, whether to parse and include excerpt? (rendered as HTML)
*
* If `function`, control how the excerpt is extracted from the content.
*
* If `string`, define a custom separator to be used for extracting the
* excerpt. Default separator is `---` if `excerpt` is `true`.
*
* @see https://github.com/jonschlinkert/gray-matter#optionsexcerpt
* @see https://github.com/jonschlinkert/gray-matter#optionsexcerpt_separator
*
* @default false
*/
excerpt?:
| boolean
| ((file: { data: { [key: string]: any }; content: string; excerpt?: string }, options?: any) => void)
| string
/**
* Transform the data. Note the data will be inlined as JSON in the client
* bundle if imported from components or markdown files.
*/
transform?: (data: ContentData[]) => T | Promise<T>
}
```
## Typed Data Loaders
When using TypeScript, you can type your loader and `data` export like so:

@ -45,7 +45,7 @@ The following guides are based on some shared assumptions:
}
```
Now the `docs:preview` method will launch the server at `http://localhost:8080`.
Now the `docs:preview` method will launch the server at `http://localhost:8080`.
## Setting a Public Base Path
@ -65,7 +65,7 @@ This `4f283b18` hash is generated from the content of this file. The same hashed
Cache-Control: max-age=31536000,immutable
```
:::details Example Netlify `_headers` file
::: details Example Netlify `_headers` file
```
/assets/*
@ -73,13 +73,13 @@ Cache-Control: max-age=31536000,immutable
cache-control: immutable
```
Note: the `_headers` file should be placed in the [public directory](/guide/asset-handling#the-public-directory) - in our case, `docs/public/_headers` - so that it is copied verbatim to the output directory.
Note: the `_headers` file should be placed in the [public directory](./asset-handling#the-public-directory) - in our case, `docs/public/_headers` - so that it is copied verbatim to the output directory.
[Netlify custom headers documentation](https://docs.netlify.com/routing/headers/)
:::
:::details Example Vercel config in `vercel.json`
::: details Example Vercel config in `vercel.json`
```json
{
@ -119,65 +119,87 @@ Don't enable options like _Auto Minify_ for HTML code. It will remove comments f
### GitHub Pages
1. In your theme config file, `docs/.vitepress/config.js`, set the `base` property to the name of your GitHub repository. 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.
2. Create a file named `deploy.yml` inside `.github/workflows` directory of your project with the following content:
1. Create a file named `deploy.yml` inside `.github/workflows` directory of your project with some content like this:
```yaml
name: Deploy
# Sample workflow for building and deploying a VitePress site to GitHub Pages
#
name: Deploy VitePress site to Pages
on:
workflow_dispatch: {}
# 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
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:
deploy:
# Build job
build:
runs-on: ubuntu-latest
permissions:
pages: write
id-token: write
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- uses: actions/checkout@v3
- name: Checkout
uses: actions/checkout@v3
with:
fetch-depth: 0
- uses: actions/setup-node@v3
fetch-depth: 0 # Not needed if lastUpdated is not enabled
# - uses: pnpm/action-setup@v2 # Uncomment this if you're using pnpm
- name: Setup Node
uses: actions/setup-node@v3
with:
node-version: 16
cache: npm
- run: npm ci
- name: Build
run: npm run docs:build
- uses: actions/configure-pages@v2
- uses: actions/upload-pages-artifact@v1
node-version: 18
cache: npm # or pnpm / yarn
- name: Setup Pages
uses: actions/configure-pages@v3
- name: Install dependencies
run: npm ci # or pnpm install / yarn install
- name: Build with VitePress
run: npm run docs:build # or pnpm docs:build / yarn docs:build
- name: Upload artifact
uses: actions/upload-pages-artifact@v2
with:
path: docs/.vitepress/dist
- name: Deploy
# 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@v1
uses: actions/deploy-pages@v2
```
::: tip
Please replace the corresponding branch name. For example, if the branch you want to build is `master`, then you should replace `main` with `master` in the above file.
::: warning
Make sure the `base` option in your VitePress is properly configured. See [Setting a Public Base Path](#setting-a-public-base-path) for more details.
:::
3. In your repository's Settings under Pages menu item, select `GitHub Actions` in Build and deployment's Source.
4. Now commit your code and push it to the `main` branch.
2. In your repository's settings under "Pages" menu item, select "GitHub Actions" in "Build and deployment > Source".
5. Wait for actions to complete.
6. In your repository's Settings under Pages menu item, click `Visit site`, then you can see your site. Your docs will automatically deploy each time you push.
3. Push your changes to the `main` branch and wait for the GitHub Actions workflow to complete. You should see your site deployed to `https://<username>.github.io/[repository]/` or `https://<custom-domain>/` depending on your settings. Your site will automatically be deployed on every push to the `main` branch.
### GitLab Pages
1. Set `outDir` in `docs/.vitepress/config.js` to `../public`.
2. Still in your config file, `docs/.vitepress/config.js`, set the `base` property to the name of your GitLab repository. If you plan to deploy your site to `https://foo.gitlab.io/bar/`, then you should set base to `'/bar/'`. It should always start and end with a slash.
1. Set `outDir` in VitePress config to `../public`. Configure `base` option to `'/<repository>/'` if you want to deploy to `https://<username>.gitlab.io/<repository>/`.
3. Create a file called `.gitlab-ci.yml` in the root of your project with the content below. This will build and deploy your site whenever you make changes to your content:
2. Create a file named `.gitlab-ci.yml` in the root of your project with the content below. This will build and deploy your site whenever you make changes to your content:
```yaml
image: node:16
@ -186,25 +208,7 @@ Don't enable options like _Auto Minify_ for HTML code. It will remove comments f
paths:
- node_modules/
script:
- npm install
- npm run docs:build
artifacts:
paths:
- public
only:
- main
```
4. Alternatively, if you want to use an _alpine_ version of node, you have to install `git` manually. In that case, the code above modifies to this:
```yaml
image: node:16-alpine
pages:
cache:
paths:
- node_modules/
before_script:
- apk add git
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:

@ -10,7 +10,7 @@ However, there are a number of cases where configuration alone won't be enough.
These advanced customizations will require using a custom theme that "extends" the default theme.
:::tip
::: tip
Before proceeding, make sure to first read [Using a Custom Theme](./custom-theme) to understand how custom themes work.
:::
@ -58,11 +58,11 @@ export default DefaultTheme
}
```
:::warning
If you are using optional components like the [Team Page](/reference/default-theme-team-page) components, make sure to also import them from `vitepress/theme-without-fonts`!
::: warning
If you are using optional components like the [Team Page](../reference/default-theme-team-page) components, make sure to also import them from `vitepress/theme-without-fonts`!
:::
If your font is a local file referenced via `@font-face`, it will be processed as an asset and included under `.vitepress/dist/assets` with hashed filename. To preload this file, use the [transformHead](/reference/site-config#transformhead) build hook:
If your font is a local file referenced via `@font-face`, it will be processed as an asset and included under `.vitepress/dist/assets` with hashed filename. To preload this file, use the [transformHead](../reference/site-config#transformhead) build hook:
```js
// .vitepress/config.js

@ -22,7 +22,7 @@ $ npm install -D vitepress
```
```sh [pnpm]
$ pnpm add -D vitepress
$ pnpm add -D vitepress@latest
```
```sh [yarn]
@ -38,7 +38,8 @@ If using PNPM, you will notice a missing peer warning for `@docsearch/js`. This
"pnpm": {
"peerDependencyRules": {
"ignoreMissing": [
"@algolia/client-search"
"@algolia/client-search",
"search-insights"
]
}
}
@ -57,7 +58,7 @@ $ npx vitepress init
```
```sh [pnpm]
$ pnpm exec vitepress init
$ pnpm dlx vitepress init
```
:::
@ -68,7 +69,7 @@ You will be greeted with a few simple questions:
<img src="./vitepress-init.png" alt="vitepress init screenshot" style="border-radius:8px">
</p>
:::tip Vue as Peer Dependency
::: tip Vue as Peer Dependency
If you intend to perform customization that uses Vue components or APIs, you should also explicitly install `vue` as a peer dependency.
:::
@ -91,7 +92,7 @@ Assuming you chose to scaffold the VitePress project in `./docs`, the generated
The `docs` directory is considered the **project root** of the VitePress site. The `.vitepress` directory is a reserved location for VitePress' config file, dev server cache, build output, and optional theme customization code.
:::tip
::: tip
By default, VitePress stores its dev server cache in `.vitepress/cache`, and the production build output in `.vitepress/dist`. If using Git, you should add them to your `.gitignore` file. These locations can also be [configured](../reference/site-config#outdir).
:::

@ -566,7 +566,12 @@ It also supports [line highlighting](#line-highlighting-in-code-blocks):
<<< @/snippets/snippet.js{2}
::: tip
The value of `@` corresponds to the source root. By default it's the VitePress project root, unless `srcDir` is configured.
The value of `@` corresponds to the source root. By default it's the VitePress project root, unless `srcDir` is configured. Alternatively, you can also import from relative paths:
```md
<<< ../snippets/snippet.js
```
:::
You can also use a [VS Code region](https://code.visualstudio.com/docs/editor/codebasics#_folding) to only include the corresponding part of the code file. You can provide a custom region name after a `#` following the filepath:
@ -691,10 +696,10 @@ You can also [import snippets](#import-code-snippets) in code groups:
## Markdown File Inclusion
You can include a markdown file in another markdown file.
You can include a markdown file in another markdown file, even nested.
::: tip
You can also prefix the markdown path with `@`, it will act as the source root. By default it's the VitePress project root, unless `srcDir` is configured.
You can also prefix the markdown path with `@`, it will act as the source root. By default, it's the VitePress project root, unless `srcDir` is configured.
:::
For example, you can include a relative markdown file using this:
@ -733,6 +738,42 @@ Some getting started stuff.
Can be created using `.foorc.json`.
```
It also supports selecting a line range:
**Input**
```md
# Docs
## Basics
<!--@include: ./parts/basics.md{3,}-->
```
**Part file** (`parts/basics.md`)
```md
Some getting started stuff.
### Configuration
Can be created using `.foorc.json`.
```
**Equivalent code**
```md
# Docs
## Basics
### Configuration
Can be created using `.foorc.json`.
```
The format of the selected line range can be: `{3,}`, `{,10}`, `{1,10}`
::: warning
Note that this does not throw errors if your file is not present. Hence, when using this feature make sure that the contents are being rendered as expected.
:::

@ -97,7 +97,7 @@ Learn more about linking to assets such images in [Asset Handling](asset-handlin
## Generating Clean URL
:::warning Server Support Required
::: warning Server Support Required
To serve clean URLs with VitePress, server-side support is required.
:::
@ -172,7 +172,7 @@ export default {
The rewrite paths are compiled using the `path-to-regexp` package - consult [its documentation](https://github.com/pillarjs/path-to-regexp#parameters) for more advanced syntax.
:::warning Relative Links with Rewrites
::: warning Relative Links with Rewrites
When rewrites are enabled, **relative links should be based on the rewritten paths**. For example, in order to create a relative link from `packages/pkg-a/src/pkg-a-code.md` to `packages/pkg-b/src/pkg-b-code.md`, you should use:
@ -327,17 +327,15 @@ Instead, you can pass such content to each page using the `content` property on
```js
export default {
paths() {
async paths() {
const posts = await (await fetch('https://my-cms.com/blog-posts')).json()
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 // raw Markdown or HTML
}
})
}
return posts.map((post) => {
return {
params: { id: post.id },
content: post.content // raw Markdown or HTML
}
})
}
}
```

@ -0,0 +1,53 @@
# Sitemap Generation
VitePress comes with out-of-the-box support for generating a `sitemap.xml` file for your site. To enable it, add the following to your `.vitepress/config.js`:
```ts
import { defineConfig } from 'vitepress'
export default defineConfig({
sitemap: {
hostname: 'https://example.com'
}
})
```
To have `<lastmod>` tags in your `sitemap.xml`, you can enable the [`lastUpdated`](../reference/default-theme-last-updated) option.
## Options
Sitemap support is powered by the [`sitemap`](https://www.npmjs.com/package/sitemap) module. You can pass any options supported by it to the `sitemap` option in your config file. These will be passed directly to the `SitemapStream` constructor. Refer to the [`sitemap` documentation](https://www.npmjs.com/package/sitemap#options-you-can-pass) for more details. Example:
```ts
import { defineConfig } from 'vitepress'
export default defineConfig({
sitemap: {
hostname: 'https://example.com',
lastmodDateOnly: false
}
})
```
## `transformItems` Hook
You can use the `sitemap.transformItems` hook to modify the sitemap items before they are written to the `sitemap.xml` file. This hook is called with an array of sitemap items and expects an array of sitemap items to be returned. Example:
```ts
import { defineConfig } from 'vitepress'
export default defineConfig({
sitemap: {
hostname: 'https://example.com',
transformItems: (items) => {
// add new items or modify/filter existing items
items.push({
url: '/extra-page',
changefreq: 'monthly',
priority: 0.8
})
return items
}
}
})
```

@ -48,7 +48,7 @@ if (!import.meta.env.SSR) {
}
```
Since [`Theme.enhanceApp`](/guide/custom-theme#theme-interface) can be async, you can conditionally import and register Vue plugins that access browser APIs on import:
Since [`Theme.enhanceApp`](./custom-theme#theme-interface) can be async, you can conditionally import and register Vue plugins that access browser APIs on import:
```js
// .vitepress/theme/index.js

@ -4,7 +4,7 @@ In VitePress, each Markdown file is compiled into HTML and then processed as a [
It's worth noting that VitePress leverages Vue's compiler to automatically detect and optimize the purely static parts of the Markdown content. Static contents are optimized into single placeholder nodes and eliminated from the page's JavaScript payload for initial visits. They are also skipped during client-side hydration. In short, you only pay for the dynamic parts on any given page.
:::tip SSR Compatibility
::: tip SSR Compatibility
All Vue usage needs to be SSR-compatible. See [SSR Compatibility](./ssr-compat) for details and common workarounds.
:::
@ -67,7 +67,7 @@ The count is: {{ count }}
</style>
```
:::warning Avoid `<style scoped>` in Markdown
::: warning Avoid `<style scoped>` in Markdown
When used in Markdown, `<style scoped>` requires adding special attributes to every element on the current page, which will significantly bloat the page size. `<style module>` is preferred when locally-scoped styling is needed in a page.
:::
@ -244,6 +244,7 @@ Vitepress currently has SSG support for teleports to body only. For other target
<script setup>
import ModalDemo from '../components/ModalDemo.vue'
import ComponentInHeader from '../components/ComponentInHeader.vue'
</script>
<style>

@ -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, especially those that need to embed interactive demos. It powers this page you are reading right now, along with the documentation for [Vite](https://vitejs.dev/), [Pinia](https://pinia.vuejs.org/), [VueUse](https://vueuse.org/), [Rollup](https://rollupjs.org/), [Mermaid](https://mermaid.js.org/), [Wikimedia Codex](https://doc.wikimedia.org/codex/latest/), and many more.
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).
The [official Vue.js documentation](https://vuejs.org/) is also based on VitePress, but uses a custom theme shared between multiple translations.

@ -11,7 +11,7 @@ hero:
actions:
- theme: brand
text: Get Started
link: /guide/what-is-vitepress
link: /guide/getting-started
- theme: alt
text: View on GitHub
link: https://github.com/vuejs/vitepress
@ -20,10 +20,10 @@ features:
- icon: 📝
title: Focus on Your Content
details: Effortlessly create beautiful documentation sites with just markdown.
- icon: <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><g fill="none"><path fill="url(#a)" d="m29.884 6.146-13.142 23.5a.714.714 0 0 1-1.244.005L2.096 6.148a.714.714 0 0 1 .746-1.057l13.156 2.352a.714.714 0 0 0 .253 0l12.881-2.348a.714.714 0 0 1 .752 1.05z"/><path fill="url(#b)" d="M22.264 2.007 12.54 3.912a.357.357 0 0 0-.288.33l-.598 10.104a.357.357 0 0 0 .437.369l2.707-.625a.357.357 0 0 1 .43.42l-.804 3.939a.357.357 0 0 0 .454.413l1.672-.508a.357.357 0 0 1 .454.414l-1.279 6.187c-.08.387.435.598.65.267l.143-.222 7.925-15.815a.357.357 0 0 0-.387-.51l-2.787.537a.357.357 0 0 1-.41-.45l1.818-6.306a.357.357 0 0 0-.412-.45z"/><defs><linearGradient id="a" x1="6" x2="235" y1="33" y2="344" gradientTransform="translate(1.34 1.894) scale(.07142)" gradientUnits="userSpaceOnUse"><stop stop-color="#41D1FF"/><stop offset="1" stop-color="#BD34FE"/></linearGradient><linearGradient id="b" x1="194.651" x2="236.076" y1="8.818" y2="292.989" gradientTransform="translate(1.34 1.894) scale(.07142)" gradientUnits="userSpaceOnUse"><stop stop-color="#FFEA83"/><stop offset=".083" stop-color="#FFDD35"/><stop offset="1" stop-color="#FFA800"/></linearGradient></defs></g></svg>
- icon: <svg xmlns="http://www.w3.org/2000/svg" width="30" viewBox="0 0 256 256.32"><defs><linearGradient id="a" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"/><stop offset="100%" stop-color="#BD34FE"/></linearGradient><linearGradient id="b" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"/><stop offset="8.333%" stop-color="#FFDD35"/><stop offset="100%" stop-color="#FFA800"/></linearGradient></defs><path fill="url(#a)" d="M255.153 37.938 134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"/><path fill="url(#b)" d="M185.432.063 96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028 72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"/></svg>
title: Enjoy the Vite DX
details: Instant server start, lightning fast hot updates, and leverage Vite ecosystem plugins.
- icon: <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><path fill="#41b883" d="M24.4 3.925H30l-14 24.15L2 3.925h10.71l3.29 5.6 3.22-5.6Z"/><path fill="#41b883" d="m2 3.925 14 24.15 14-24.15h-5.6L16 18.415 7.53 3.925Z"/><path fill="#35495e" d="M7.53 3.925 16 18.485l8.4-14.56h-5.18L16 9.525l-3.29-5.6Z"/></svg>
- icon: <svg xmlns="http://www.w3.org/2000/svg" width="30" viewBox="0 0 256 220.8"><path fill="#41B883" d="M204.8 0H256L128 220.8 0 0h97.92L128 51.2 157.44 0h47.36Z"/><path fill="#41B883" d="m0 0 128 220.8L256 0h-51.2L128 132.48 50.56 0H0Z"/><path fill="#35495E" d="M50.56 0 128 133.12 204.8 0h-47.36L128 51.2 97.92 0H50.56Z"/></svg>
title: Customize with Vue
details: Use Vue syntax and components directly in markdown, or build custom themes with Vue.
- icon: 🚀

@ -1,6 +1,12 @@
{
"name": "docs",
"private": true,
"type": "module",
"scripts": {
"dev": "vitepress",
"build": "vitepress build",
"preview": "vitepress preview"
},
"devDependencies": {
"vitepress": "workspace:*"
}

@ -1,4 +1,4 @@
<!DOCTYPE html>
<!doctype html>
<html>
<head>
<title>Plain HTML page | VitePress</title>

@ -16,14 +16,14 @@ vitepress dev [root]
### Options
| Option | Description |
| - | - |
| `--open [path]` | Open browser on startup (`boolean \| string`) |
| `--port <port>` | Specify port (`number`) |
| `--base <path>` | Public base path (default: `/`) (`string`) |
| `--cors` | Enable CORS |
| `--strictPort` | Exit if specified port is already in use (`boolean`) |
| `--force` | Force the optimizer to ignore the cache and re-bundle (`boolean`) |
| Option | Description |
| --------------- | ----------------------------------------------------------------- |
| `--open [path]` | Open browser on startup (`boolean \| string`) |
| `--port <port>` | Specify port (`number`) |
| `--base <path>` | Public base path (default: `/`) (`string`) |
| `--cors` | Enable CORS |
| `--strictPort` | Exit if specified port is already in use (`boolean`) |
| `--force` | Force the optimizer to ignore the cache and re-bundle (`boolean`) |
## `vitepress build`
@ -37,14 +37,14 @@ vitepress build [root]
### Options
| Option | Description |
| - | - |
| `--mpa` (experimental) | Build in [MPA mode](../guide/mpa-mode) without client-side hydration (`boolean`) |
| `--base <path>` | Public base path (default: `/`) (`string`) |
| `--target <target>` | Transpile target (default: `"modules"`) (`string`) |
| `--outDir <dir>` | Output directory (default: `.vitepress/dist`) (`string`) |
| Option | Description |
| ------------------------------ | ------------------------------------------------------------------------------------------------------------------- |
| `--mpa` (experimental) | Build in [MPA mode](../guide/mpa-mode) without client-side hydration (`boolean`) |
| `--base <path>` | Public base path (default: `/`) (`string`) |
| `--target <target>` | Transpile target (default: `"modules"`) (`string`) |
| `--outDir <dir>` | Output directory relative to **cwd** (default: `<root>/.vitepress/dist`) (`string`) |
| `--minify [minifier]` | Enable/disable minification, or specify minifier to use (default: `"esbuild"`) (`boolean \| "terser" \| "esbuild"`) |
| `--assetsInlineLimit <number>` | Static asset base64 inline threshold in bytes (default: `4096`) (`number`) |
| `--assetsInlineLimit <number>` | Static asset base64 inline threshold in bytes (default: `4096`) (`number`) |
## `vitepress preview`
@ -58,10 +58,10 @@ vitepress preview [root]
### Options
| Option | Description |
| - | - |
| `--base <path>` | Public base path (default: `/`) (`string`) |
| `--port <port>` | Specify port (`number`) |
| Option | Description |
| --------------- | ------------------------------------------ |
| `--base <path>` | Public base path (default: `/`) (`string`) |
| `--port <port>` | Specify port (`number`) |
## `vitepress init`

@ -214,7 +214,9 @@ export default {
icon: {
svg: '<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Dribbble</title><path d="M12...6.38z"/></svg>'
},
link: '...'
link: '...',
// You can include a custom label for accessibility too (optional but recommended):
ariaLabel: 'cool link'
}
]
}
@ -225,6 +227,7 @@ export default {
interface SocialLink {
icon: SocialLinkIcon
link: string
ariaLabel?: string
}
type SocialLinkIcon =
@ -243,6 +246,7 @@ type SocialLinkIcon =
## footer
- Type: `Footer`
- Can be overridden per page via [frontmatter](./frontmatter-config#footer)
Footer configuration. You can add a message or copyright text on the footer, however, it will only be displayed when the page doesn't contain a sidebar. This is due to design concerns.
@ -289,21 +293,41 @@ export interface EditLink {
}
```
## lastUpdatedText
## lastUpdated
- Type: `string`
- Default: `Last updated`
- Type: `LastUpdatedOptions`
The prefix text showing right before the last updated time.
Allows customization for the last updated text and date format.
```ts
export default {
themeConfig: {
lastUpdatedText: 'Updated Date'
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
}
```
## algolia
- Type: `AlgoliaSearch`
@ -348,7 +372,7 @@ Learn more in [Default Theme: Carbon Ads](./default-theme-carbon-ads)
- Type: `DocFooter`
Can be used to customize text appearing above previous and next links. Helpful if not writing docs in English.
Can be used to customize text appearing above previous and next links. Helpful if not writing docs in English. Also can be used to disable prev/next links globally. If you want to selectively enable/disable prev/next links, you can use [frontmatter](./default-theme-prev-next-links).
```js
export default {
@ -363,8 +387,8 @@ export default {
```ts
export interface DocFooter {
prev?: string
next?: string
prev?: string | false
next?: string | false
}
```
@ -395,3 +419,10 @@ Can be used to customize the label of the return to top button. This label is on
- Default: `Change language`
Can be used to customize the aria-label of the language toggle button in navbar. This is only used if you're using [i18n](../guide/i18n).
## externalLinkIcon
- Type: `boolean`
- Default: `false`
Whether to show an external link icon next to external links in markdown.

@ -41,3 +41,13 @@ Only inline elements can be used in `message` and `copyright` as they are render
:::
Note that footer will not be displayed when the [SideBar](./default-theme-sidebar) is visible.
## Frontmatter Config
This can be disabled per-page using the `footer` option on frontmatter:
```yaml
---
footer: false
---
```

@ -139,6 +139,11 @@ interface Feature {
//
// e.g. `Learn more`, `Visit page`, etc.
linkText?: string
// Link rel attribute for the `link` option.
//
// e.g. `external`
rel?: string
}
type FeatureIcon =

@ -2,6 +2,10 @@
The update time of the last content will be displayed in the lower right corner of the page. To enable it, add `lastUpdated` options to your config.
::: tip
You need to commit the markdown file to see the updated time.
:::
## Site-Level Config
```js
@ -20,3 +24,4 @@ lastUpdated: false
---
```
Also refer [Default Theme: Last Updated](./default-theme-last-updated#last-updated) for more details. Any truthy value at theme-level will also enable the feature unless explicitly disabled at site or page level.

@ -1,3 +1,7 @@
---
outline: deep
---
# Search
## Local Search
@ -58,6 +62,60 @@ export default defineConfig({
})
```
### miniSearch options
You can configure MiniSearch like this:
```ts
import { defineConfig } from 'vitepress'
export default defineConfig({
themeConfig: {
search: {
provider: 'local',
options: {
miniSearch: {
/**
* @type {Pick<import('minisearch').Options, 'extractField' | 'tokenize' | 'processTerm'>}
*/
options: {
/* ... */
},
/**
* @type {import('minisearch').SearchOptions}
* @default
* { fuzzy: 0.2, prefix: true, boost: { title: 4, text: 2, titles: 1 } }
*/
searchOptions: {
/* ... */
}
}
}
}
}
})
```
Learn more in [MiniSearch docs](https://lucaong.github.io/minisearch/classes/_minisearch_.minisearch.html).
### Excluding pages from search
You can exclude pages from search by adding `search: false` to the frontmatter of the page. Alternatively, you can also pass `exclude` function to `themeConfig.search.options` to exclude pages based on their path relative to `srcDir`:
```ts
import { defineConfig } from 'vitepress'
export default defineConfig({
themeConfig: {
search: {
options: {
exclude: (path) => path.startsWith('/some/path')
}
}
}
})
```
## 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:
@ -145,6 +203,114 @@ 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.
### Crawler Config
Here is an example config based on what this site uses:
```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: '',
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: '<span class="algolia-docsearch-suggestion--highlight">',
highlightPostTag: '</span>',
minWordSizefor1Typo: 3,
minWordSizefor2Typos: 7,
allowTyposOnNumericTokens: false,
minProximity: 1,
ignorePlurals: true,
advancedSyntax: true,
attributeCriteriaComputedByMinProximity: true,
removeWordsIfNoResults: 'allOptional'
}
}
})
```
<style>
img[src="/search.png"] {
width: 100%;

@ -180,3 +180,36 @@ export default {
}
}
```
## `useSidebar` <Badge type="info" text="composable" />
Returns sidebar-related data. The returned object has the following type:
```ts
export interface DocSidebar {
isOpen: Ref<boolean>
sidebar: ComputedRef<DefaultTheme.SidebarItem[]>
sidebarGroups: ComputedRef<DefaultTheme.SidebarItem[]>
hasSidebar: ComputedRef<boolean>
hasAside: ComputedRef<boolean>
leftAside: ComputedRef<boolean>
isSidebarEnabled: ComputedRef<boolean>
open: () => void
close: () => void
toggle: () => void
}
```
**Example:**
```vue
<script setup>
import { useSidebar } from 'vitepress/theme'
const { hasSidebar } = useSidebar()
</script>
<template>
<div v-if="hasSidebar">Only show when sidebar exists</div>
</template>
```

@ -86,7 +86,7 @@ type HeadConfig =
The following frontmatter options are only applicable when using the default theme.
### layout <Badge type="info" text="default theme only" />
### layout
- Type: `doc | home | page`
- Default: `doc`
@ -103,15 +103,41 @@ layout: doc
---
```
### hero <Badge type="info" text="default theme only" /> <Badge type="info" text="Home page only" />
### hero <Badge type="info" text="home page only" />
Defines contents of home hero section when `layout` is set to `home`. More details in [Default Theme: Home Page](./default-theme-home-page).
### features <Badge type="info" text="default theme only" /> <Badge type="info" text="Home page only" />
### features <Badge type="info" text="home page only" />
Defines items to display in features section when `layout` is set to `home`. More details in [Default Theme: Home Page](./default-theme-home-page).
### aside <Badge type="info" text="default theme only" />
### navbar
- Type: `boolean`
- Default: `true`
Whether to display [navbar](./default-theme-nav).
```yaml
---
navbar: false
---
```
### sidebar
- Type: `boolean`
- Default: `true`
Whether to display [sidebar](./default-theme-sidebar).
```yaml
---
sidebar: false
---
```
### aside
- Type: `boolean | 'left'`
- Default: `true`
@ -128,19 +154,19 @@ aside: false
---
```
### outline <Badge type="info" text="default theme only" />
### outline
- Type: `number | [number, number] | 'deep' | false`
- Default: `2`
The levels of header in the outline to display for the page. It's same as [config.themeConfig.outline](./default-theme-config#outline), and it overrides the theme config.
### lastUpdated <Badge type="info" text="default theme only" />
### lastUpdated
- Type: `boolean`
- Default: `true`
Whether to display [Last Updated](./default-theme-last-updated) text in the footer of the current page.
Whether to display [last updated](./default-theme-last-updated) text in the footer of the current page.
```yaml
---
@ -148,15 +174,48 @@ lastUpdated: false
---
```
### editLink <Badge type="info" text="default theme only" />
### editLink
- Type: `boolean`
- Default: `true`
Whether to display [Edit Link](./default-theme-edit-link) in the footer of the current page.
Whether to display [edit link](./default-theme-edit-link) in the footer of the current page.
```yaml
---
editLink: false
---
```
### footer
- Type: `boolean`
- Default: `true`
Whether to display [footer](./default-theme-footer).
```yaml
---
footer: false
---
```
### pageClass
- Type: `string`
Add extra class name to a specific page.
```yaml
---
pageClass: custom-page-class
---
```
Then you can customize styles of this specific page in `.vitepress/theme/custom.css` file:
```css
.custom-page-class {
  /* page-specific styles */
}
```

@ -86,8 +86,27 @@ Returns the VitePress router instance so you can programmatically navigate to an
```ts
interface Router {
/**
* Current route.
*/
route: Route
go: (href?: string) => Promise<void>
/**
* Navigate to a new URL.
*/
go: (to?: string) => Promise<void>
/**
* Called before the route changes. Return `false` to cancel the navigation.
*/
onBeforeRouteChange?: (to: string) => Awaitable<void | boolean>
/**
* Called before the page component is loaded (after the history state is
* updated). Return `false` to cancel the navigation.
*/
onBeforePageLoad?: (to: string) => Awaitable<void | boolean>
/**
* Called after the route changes.
*/
onAfterRouteChanged?: (to: string) => Awaitable<void>
}
```
@ -122,7 +141,7 @@ If you are using or demoing components that are not SSR-friendly (for example, c
</ClientOnly>
```
- Related: [SSR Compatibility](/guide/ssr-compat)
- Related: [SSR Compatibility](../guide/ssr-compat)
## `$frontmatter` <Badge type="info" text="template global" />

@ -290,6 +290,19 @@ export default {
}
```
### assetsDir
- Type: `string`
- Default: `assets`
The directory for assets files. See also: [assetsDir](https://vitejs.dev/config/build-options.html#build-assetsdir).
```ts
export default {
assetsDir: 'static'
}
```
### cacheDir
- Type: `string`

@ -3,4 +3,4 @@
[build]
publish = "docs/.vitepress/dist"
command = "pnpm docs-build"
command = "pnpm docs:build"

@ -1,9 +1,9 @@
{
"name": "vitepress",
"version": "1.0.0-beta.1",
"version": "1.0.0-beta.7",
"description": "Vite & Vue powered static site generator",
"type": "module",
"packageManager": "pnpm@8.5.1",
"packageManager": "pnpm@8.6.11",
"main": "dist/node/index.js",
"types": "types/index.d.ts",
"exports": {
@ -55,51 +55,54 @@
"url": "https://github.com/vuejs/vitepress/issues"
},
"scripts": {
"dev": "rimraf dist && run-s dev-shared dev-start",
"dev-start": "run-p dev-client dev-node dev-watch",
"dev-client": "tsc --sourcemap -w -p src/client",
"dev-node": "DEV=true pnpm build-node -w",
"dev-shared": "node scripts/copyShared",
"dev-watch": "node scripts/watchAndCopy",
"build": "run-s build-prepare build-client build-node",
"build-prepare": "rimraf dist && node scripts/copyShared",
"build-client": "vue-tsc --noEmit -p src/client && tsc -p src/client && node scripts/copyClient",
"build-node": "tsc -p src/node --noEmit && rollup --config rollup.config.ts --configPlugin esbuild",
"dev": "rimraf dist && run-s dev:shared dev:start",
"dev:start": "run-p dev:client dev:node dev:watch",
"dev:client": "tsc --sourcemap -w -p src/client",
"dev:node": "DEV=true pnpm build:node -w",
"dev:shared": "node scripts/copyShared",
"dev:watch": "node scripts/watchAndCopy",
"build": "run-s build:prepare build:client build:node",
"build:prepare": "rimraf dist && node scripts/copyShared",
"build:client": "vue-tsc --noEmit -p src/client && tsc -p src/client && node scripts/copyClient",
"build:node": "tsc -p src/node --noEmit && rollup --config rollup.config.ts --configPlugin esbuild",
"test": "run-p --aggregate-output test:unit test:e2e test:init",
"test:unit": "vitest run -r __tests__/unit",
"test:unit:watch": "vitest -r __tests__/unit",
"test:e2e": "run-s test:e2e-dev test:e2e-build",
"test:e2e:site:dev": "pnpm -F=tests-e2e site:dev",
"test:e2e:site:build": "pnpm -F=tests-e2e site:build",
"test:e2e:site:preview": "pnpm -F=tests-e2e site:preview",
"test:e2e-dev": "pnpm -F=tests-e2e test",
"test:e2e-dev:watch": "pnpm -F=tests-e2e watch",
"test:e2e-build": "VITE_TEST_BUILD=1 pnpm test:e2e-dev",
"test:e2e-build:watch": "VITE_TEST_BUILD=1 pnpm test:e2e-dev:watch",
"test:init": "pnpm -F=tests-init test",
"test:init:watch": "pnpm -F=tests-init watch",
"docs": "run-p dev docs:dev",
"docs:dev": "wait-on -d 100 dist/node/cli.js && pnpm -F=docs dev",
"docs:debug": "NODE_OPTIONS='--inspect-brk' pnpm docs:dev",
"docs:build": "run-s build docs:build:only",
"docs:build:only": "pnpm -F=docs build",
"docs:preview": "pnpm -F=docs preview",
"format": "prettier --check --write .",
"format-fail": "prettier --check .",
"check": "run-s format-fail build test",
"test": "run-s test-unit test-e2e test-e2e-build",
"test-unit": "vitest run -r __tests__/unit",
"test-e2e": "vitest run -r __tests__/e2e",
"test-e2e-build": "VITE_TEST_BUILD=1 pnpm test-e2e",
"test-init": "vitest run -r __tests__/init",
"test-init-build": "VITE_TEST_BUILD=1 pnpm test-init",
"debug-e2e": "DEBUG=1 vitest -r __tests__/e2e",
"debug-e2e-build": "VITE_TEST_BUILD=1 pnpm debug-e2e",
"unit-dev": "vitest -r __tests__/unit",
"e2e-dev": "wait-on -d 100 dist/node/cli.js && node ./bin/vitepress dev __tests__/e2e",
"format:fail": "prettier --check .",
"check": "run-s format:fail build test",
"changelog": "conventional-changelog -p angular -i CHANGELOG.md -s",
"release": "node scripts/release.js",
"docs": "run-p dev docs-dev",
"docs-dev": "wait-on -d 100 dist/node/cli.js && node ./bin/vitepress dev docs",
"docs-debug": "node --inspect-brk ./bin/vitepress dev docs",
"docs-build": "run-s build docs-build-only",
"docs-build-only": "node ./bin/vitepress build docs",
"docs-preview": "node ./bin/vitepress preview docs"
"release": "node scripts/release.js"
},
"dependencies": {
"@docsearch/css": "^3.4.0",
"@docsearch/js": "^3.4.0",
"@docsearch/css": "^3.5.1",
"@docsearch/js": "^3.5.1",
"@vitejs/plugin-vue": "^4.2.3",
"@vue/devtools-api": "^6.5.0",
"@vueuse/core": "^10.1.2",
"@vueuse/integrations": "^10.1.2",
"@vueuse/core": "^10.3.0",
"@vueuse/integrations": "^10.3.0",
"body-scroll-lock": "4.0.0-beta.0",
"focus-trap": "^7.4.3",
"focus-trap": "^7.5.2",
"mark.js": "8.11.1",
"minisearch": "^6.1.0",
"shiki": "^0.14.2",
"vite": "^4.3.9",
"shiki": "^0.14.3",
"vite": "^4.4.8",
"vue": "^3.3.4"
},
"devDependencies": {
@ -112,9 +115,9 @@
"@mdit-vue/plugin-toc": "^0.12.0",
"@mdit-vue/shared": "^0.12.0",
"@rollup/plugin-alias": "^5.0.0",
"@rollup/plugin-commonjs": "^25.0.0",
"@rollup/plugin-commonjs": "^25.0.3",
"@rollup/plugin-json": "^6.0.0",
"@rollup/plugin-node-resolve": "^15.0.2",
"@rollup/plugin-node-resolve": "^15.1.0",
"@rollup/plugin-replace": "^5.0.2",
"@types/body-scroll-lock": "^3.1.0",
"@types/compression": "^1.7.2",
@ -125,27 +128,28 @@
"@types/mark.js": "^8.11.8",
"@types/markdown-it": "^12.2.3",
"@types/markdown-it-attrs": "^4.1.0",
"@types/markdown-it-container": "^2.0.5",
"@types/markdown-it-container": "^2.0.6",
"@types/markdown-it-emoji": "^2.0.2",
"@types/micromatch": "^4.0.2",
"@types/minimist": "^1.2.2",
"@types/node": "^20.2.5",
"@types/node": "^20.4.6",
"@types/prompts": "^2.4.4",
"@vue/shared": "^3.3.4",
"chokidar": "^3.5.3",
"compression": "^1.7.4",
"conventional-changelog-cli": "^2.2.2",
"conventional-changelog-cli": "^2",
"cross-spawn": "^7.0.3",
"debug": "^4.3.4",
"esbuild": "^0.17.19",
"esbuild": "^0.18.17",
"escape-html": "^1.0.3",
"execa": "^7.1.1",
"fast-glob": "^3.2.12",
"execa": "^7.2.0",
"fast-glob": "^3.3.1",
"fs-extra": "^11.1.1",
"get-port": "^6.1.2",
"get-port": "^7.0.0",
"gray-matter": "^4.0.3",
"lint-staged": "^13.2.2",
"lint-staged": "^13.2.3",
"lodash.template": "^4.5.0",
"lru-cache": "^9.1.1",
"lru-cache": "^10.0.0",
"markdown-it": "^13.0.1",
"markdown-it-anchor": "^8.6.7",
"markdown-it-attrs": "^4.1.6",
@ -155,36 +159,30 @@
"minimist": "^1.2.8",
"nanoid": "^4.0.2",
"npm-run-all": "^4.1.5",
"ora": "^6.3.1",
"ora": "^7.0.1",
"path-to-regexp": "^6.2.1",
"picocolors": "^1.0.0",
"pkg-dir": "^7.0.0",
"playwright-chromium": "^1.34.3",
"playwright-chromium": "^1.36.2",
"polka": "1.0.0-next.22",
"prettier": "^2.8.8",
"prettier": "^3.0.1",
"prompts": "^2.4.2",
"punycode": "^2.3.0",
"rimraf": "^5.0.1",
"rollup": "^3.23.0",
"rollup-plugin-dts": "^5.3.0",
"rollup": "^3.27.0",
"rollup-plugin-dts": "^5.3.1",
"rollup-plugin-esbuild": "^5.0.0",
"semver": "^7.5.1",
"semver": "^7.5.4",
"shiki-processor": "^0.1.3",
"simple-git-hooks": "^2.8.1",
"simple-git-hooks": "^2.9.0",
"sirv": "^2.0.3",
"supports-color": "^9.3.1",
"typescript": "^5.0.4",
"vitest": "^0.31.1",
"vue-tsc": "^1.6.5",
"sitemap": "^7.1.1",
"supports-color": "^9.4.0",
"typescript": "^5.1.6",
"vitest": "^0.34.1",
"vue-tsc": "^1.8.8",
"wait-on": "^7.0.1"
},
"pnpm": {
"peerDependencyRules": {
"ignoreMissing": [
"@algolia/client-search"
]
}
},
"simple-git-hooks": {
"pre-commit": "pnpm lint-staged"
},

File diff suppressed because it is too large Load Diff

@ -1,5 +1,5 @@
import { defineComponent, h } from 'vue'
import { useRoute } from '../router'
import { useData, useRoute } from 'vitepress'
import { contentUpdatedCallbacks } from '../utils'
const runCbs = () => contentUpdatedCallbacks.forEach((fn) => fn())
@ -11,14 +11,19 @@ export const Content = defineComponent({
},
setup(props) {
const route = useRoute()
const { site } = useData()
return () =>
h(props.as, { style: { position: 'relative' } }, [
route.component
? h(route.component, {
onVnodeMounted: runCbs,
onVnodeUpdated: runCbs
})
: '404 Page Not Found'
])
h(
props.as,
site.value.contentProps ?? { style: { position: 'relative' } },
[
route.component
? h(route.component, {
onVnodeMounted: runCbs,
onVnodeUpdated: runCbs
})
: '404 Page Not Found'
]
)
}
})

@ -1,6 +1,17 @@
import { inBrowser } from 'vitepress'
import { inBrowser, onContentUpdated } from 'vitepress'
export function useCodeGroups() {
if (import.meta.env.DEV) {
onContentUpdated(() => {
document.querySelectorAll('.vp-code-group > .blocks').forEach((el) => {
Array.from(el.children).forEach((child) => {
child.classList.remove('active')
})
el.children[0].classList.add('active')
})
})
}
if (inBrowser) {
window.addEventListener('click', (e) => {
const el = e.target as HTMLInputElement
@ -8,17 +19,24 @@ export function useCodeGroups() {
if (el.matches('.vp-code-group input')) {
// input <- .tabs <- .vp-code-group
const group = el.parentElement?.parentElement
const i = Array.from(group?.querySelectorAll('input') || []).indexOf(el)
if (!group) return
const i = Array.from(group.querySelectorAll('input')).indexOf(el)
if (i < 0) return
const blocks = group.querySelector('.blocks')
if (!blocks) return
const current = Array.from(blocks.children).find((child) =>
child.classList.contains('active')
)
if (!current) return
const current = group?.querySelector('div[class*="language-"].active')
const next = group?.querySelectorAll(
'div[class*="language-"]:not(.language-id)'
)?.[i]
const next = blocks.children[i]
if (!next || current === next) return
if (current && next && current !== next) {
current.classList.remove('active')
next.classList.add('active')
}
current.classList.remove('active')
next.classList.add('active')
}
})
}

@ -2,13 +2,12 @@ import { inBrowser } from 'vitepress'
export function useCopyCode() {
if (inBrowser) {
const timeoutIdMap: Map<HTMLElement, NodeJS.Timeout> = new Map()
const timeoutIdMap: WeakMap<HTMLElement, NodeJS.Timeout> = new WeakMap()
window.addEventListener('click', (e) => {
const el = e.target as HTMLElement
if (el.matches('div[class*="language-"] > button.copy')) {
const parent = el.parentElement
const sibling = el.nextElementSibling
?.nextElementSibling as HTMLPreElement | null
const sibling = el.nextElementSibling?.nextElementSibling
if (!parent || !sibling) {
return
}

@ -37,9 +37,15 @@ export function useUpdateHead(route: Route, siteDataByRouteRef: Ref<SiteData>) {
// update title and description
document.title = createTitle(siteData, pageData)
document
.querySelector(`meta[name=description]`)!
.setAttribute('content', pageDescription || siteData.description)
const description = pageDescription || siteData.description
let metaDescriptionElement = document.querySelector(
`meta[name=description]`
)
if (metaDescriptionElement) {
metaDescriptionElement.setAttribute('content', description)
} else {
createHeadElement(['meta', { name: 'description', content: description }])
}
updateHeadTags(
mergeHead(siteData.head, filterOutHeadDescription(frontmatterHead))

@ -66,7 +66,7 @@ export function usePrefetch() {
if (!hasFetched.has(pathname)) {
hasFetched.add(pathname)
const pageChunkPath = pathToFile(pathname)
doFetch(pageChunkPath)
if (pageChunkPath) doFetch(pageChunkPath)
}
}
})
@ -76,7 +76,6 @@ export function usePrefetch() {
document
.querySelectorAll<HTMLAnchorElement | SVGAElement>('#app a')
.forEach((link) => {
const { target } = link
const { hostname, pathname } = new URL(
link.href instanceof SVGAnimatedString
? link.href.animVal
@ -91,7 +90,7 @@ export function usePrefetch() {
if (
// only prefetch same tab navigation, since a new tab will load
// the lean js chunk instead.
target !== `_blank` &&
link.target !== '_blank' &&
// only prefetch inbound links
hostname === location.hostname
) {

@ -1,23 +1,22 @@
import RawTheme from '@theme/index'
import {
type App,
createApp as createClientApp,
createSSRApp,
defineComponent,
h,
onMounted,
watchEffect
watchEffect,
type App
} from 'vue'
import RawTheme from '@theme/index'
import { inBrowser, pathToFile } from './utils'
import { type Router, RouterSymbol, createRouter, scrollTo } from './router'
import { siteDataRef, useData } from './data'
import { useUpdateHead } from './composables/head'
import { usePrefetch } from './composables/preFetch'
import { dataSymbol, initData } from './data'
import { Content } from './components/Content'
import { ClientOnly } from './components/ClientOnly'
import { useCopyCode } from './composables/copyCode'
import { Content } from './components/Content'
import { useCodeGroups } from './composables/codeGroups'
import { useCopyCode } from './composables/copyCode'
import { useUpdateHead } from './composables/head'
import { usePrefetch } from './composables/preFetch'
import { dataSymbol, initData, siteDataRef, useData } from './data'
import { RouterSymbol, createRouter, scrollTo, type Router } from './router'
import { inBrowser, pathToFile } from './utils'
function resolveThemeExtends(theme: typeof RawTheme): typeof RawTheme {
if (theme.extends) {
@ -60,7 +59,7 @@ const VitePressApp = defineComponent({
useCodeGroups()
if (Theme.setup) Theme.setup()
return () => h(Theme.Layout)
return () => h(Theme.Layout!)
}
})
@ -123,6 +122,8 @@ function newRouter(): Router {
return createRouter((path) => {
let pageFilePath = pathToFile(path)
if (!pageFilePath) return null
if (isInitialPageLoad) {
initialPath = pageFilePath
}
@ -152,7 +153,9 @@ if (inBrowser) {
// scroll to hash on new tab during dev
if (import.meta.env.DEV && location.hash) {
const target = document.querySelector(decodeURIComponent(location.hash))
const target = document.getElementById(
decodeURIComponent(location.hash).slice(1)
)
if (target) {
scrollTo(target, location.hash)
}

@ -12,9 +12,26 @@ export interface Route {
}
export interface Router {
/**
* Current route.
*/
route: Route
go: (href?: string) => Promise<void>
onBeforeRouteChange?: (to: string) => Awaitable<void>
/**
* Navigate to a new URL.
*/
go: (to?: string) => Promise<void>
/**
* Called before the route changes. Return `false` to cancel the navigation.
*/
onBeforeRouteChange?: (to: string) => Awaitable<void | boolean>
/**
* Called before the page component is loaded (after the history state is
* updated). Return `false` to cancel the navigation.
*/
onBeforePageLoad?: (to: string) => Awaitable<void | boolean>
/**
* Called after the route changes.
*/
onAfterRouteChanged?: (to: string) => Awaitable<void>
}
@ -22,7 +39,7 @@ export const RouterSymbol: InjectionKey<Router> = Symbol()
// we are just using URL to parse the pathname and hash - the base doesn't
// matter and is only passed to support same-host hrefs.
const fakeHost = `http://a.com`
const fakeHost = 'http://a.com'
const getDefaultRoute = (): Route => ({
path: '/',
@ -36,7 +53,7 @@ interface PageModule {
}
export function createRouter(
loadPageModule: (path: string) => Promise<PageModule>,
loadPageModule: (path: string) => Awaitable<PageModule | null>,
fallbackComponent?: Component
): Router {
const route = reactive(getDefaultRoute())
@ -47,7 +64,7 @@ export function createRouter(
}
async function go(href: string = inBrowser ? location.href : '/') {
await router.onBeforeRouteChange?.(href)
if ((await router.onBeforeRouteChange?.(href)) === false) return
const url = new URL(href, fakeHost)
if (!siteDataRef.value.cleanUrls) {
// ensure correct deep link so page refresh lands on correct files.
@ -69,10 +86,14 @@ export function createRouter(
let latestPendingPath: string | null = null
async function loadPage(href: string, scrollPosition = 0, isRetry = false) {
if ((await router.onBeforePageLoad?.(href)) === false) return
const targetLoc = new URL(href, fakeHost)
const pendingPath = (latestPendingPath = targetLoc.pathname)
try {
let page = await loadPageModule(pendingPath)
if (!page) {
throw new Error(`Page not found: ${pendingPath}`)
}
if (latestPendingPath === pendingPath) {
latestPendingPath = null
@ -104,8 +125,8 @@ export function createRouter(
if (targetLoc.hash && !scrollPosition) {
let target: HTMLElement | null = null
try {
target = document.querySelector(
decodeURIComponent(targetLoc.hash)
target = document.getElementById(
decodeURIComponent(targetLoc.hash).slice(1)
)
} catch (e) {
console.warn(e)
@ -120,7 +141,10 @@ export function createRouter(
}
}
} catch (err: any) {
if (!/fetch/.test(err.message) && !/^\/404(\.html|\/)?$/.test(href)) {
if (
!/fetch|Page not found/.test(err.message) &&
!/^\/404(\.html|\/)?$/.test(href)
) {
console.error(err)
}
@ -176,7 +200,7 @@ export function createRouter(
!e.shiftKey &&
!e.altKey &&
!e.metaKey &&
target !== `_blank` &&
!target &&
origin === currentUrl.origin &&
// don't intercept if non-html extension is present
!(extMatch && extMatch[0] !== '.html')
@ -238,7 +262,7 @@ export function scrollTo(el: Element, hash: string, smooth = false) {
try {
target = el.classList.contains('header-anchor')
? el
: document.querySelector(decodeURIComponent(hash))
: document.getElementById(decodeURIComponent(hash).slice(1))
} catch (e) {
console.warn(e)
}
@ -269,15 +293,21 @@ export function scrollTo(el: Element, hash: string, smooth = false) {
offset +
targetPadding
// only smooth scroll if distance is smaller than screen height.
if (!smooth || Math.abs(targetTop - window.scrollY) > window.innerHeight) {
window.scrollTo(0, targetTop)
} else {
window.scrollTo({
left: 0,
top: targetTop,
behavior: 'smooth'
})
function scrollToTarget() {
if (
!smooth ||
Math.abs(targetTop - window.scrollY) > window.innerHeight
) {
window.scrollTo(0, targetTop)
} else {
window.scrollTo({
left: 0,
top: targetTop,
behavior: 'smooth'
})
}
}
requestAnimationFrame(scrollToTarget)
}
}

@ -9,7 +9,7 @@ export interface EnhanceAppContext {
}
export interface Theme {
Layout: Component
Layout?: Component
enhanceApp?: (ctx: EnhanceAppContext) => Awaitable<void>
extends?: Theme

@ -18,7 +18,7 @@ export { inBrowser } from '../shared'
/**
* Join two paths by resolving the slash collision.
*/
export function joinPath(base: string, path: string): string {
export function joinPath(base: string, path: string) {
return `${base}${path}`.replace(/\/+/g, '/')
}
@ -31,7 +31,7 @@ export function withBase(path: string) {
/**
* Converts a url path to the corresponding js chunk filename.
*/
export function pathToFile(path: string): string {
export function pathToFile(path: string) {
let pagePath = path.replace(/\.html$/, '')
pagePath = decodeURIComponent(pagePath)
pagePath = pagePath.replace(/\/$/, '/index') // /foo/ -> /foo/index
@ -57,7 +57,8 @@ export function pathToFile(path: string): string {
: pagePath.slice(0, -3) + '_index.md'
pageHash = __VP_HASH_MAP__[pagePath.toLowerCase()]
}
pagePath = `${base}assets/${pagePath}.${pageHash}.js`
if (!pageHash) return null
pagePath = `${base}${__ASSETS_DIR__}/${pagePath}.${pageHash}.js`
} else {
// ssr build uses much simpler name mapping
pagePath = `./${sanitizeFileName(

@ -12,7 +12,7 @@ export type { EnhanceAppContext, Theme } from './app/theme'
export type { HeadConfig, Header, PageData, SiteData } from '../../types/shared'
// composables
export { useData } from './app/data'
export { useData, dataSymbol } from './app/data'
export { useRoute, useRouter } from './app/router'
// utilities

@ -3,6 +3,7 @@ declare const __VP_LOCAL_SEARCH__: boolean
declare const __ALGOLIA__: boolean
declare const __CARBON__: boolean
declare const __VUE_PROD_DEVTOOLS__: boolean
declare const __ASSETS_DIR__: string
declare module '*.vue' {
import type { DefineComponent } from 'vue'

@ -1,15 +1,15 @@
<script setup lang="ts">
import { computed, provide, useSlots, watch } from 'vue'
import { useRoute } from 'vitepress'
import { useData } from './composables/data'
import { useSidebar, useCloseSidebarOnEscape } from './composables/sidebar'
import VPSkipLink from './components/VPSkipLink.vue'
import { computed, provide, useSlots, watch } from 'vue'
import VPBackdrop from './components/VPBackdrop.vue'
import VPNav from './components/VPNav.vue'
import VPLocalNav from './components/VPLocalNav.vue'
import VPSidebar from './components/VPSidebar.vue'
import VPContent from './components/VPContent.vue'
import VPFooter from './components/VPFooter.vue'
import VPLocalNav from './components/VPLocalNav.vue'
import VPNav from './components/VPNav.vue'
import VPSidebar from './components/VPSidebar.vue'
import VPSkipLink from './components/VPSkipLink.vue'
import { useData } from './composables/data'
import { useCloseSidebarOnEscape, useSidebar } from './composables/sidebar'
const {
isOpen: isSidebarOpen,
@ -34,11 +34,11 @@ provide('hero-image-slot-exists', heroImageSlotExists)
</script>
<template>
<div v-if="frontmatter.layout !== false" class="Layout">
<div v-if="frontmatter.layout !== false" class="Layout" :class="frontmatter.pageClass" >
<slot name="layout-top" />
<VPSkipLink />
<VPBackdrop class="backdrop" :show="isSidebarOpen" @click="closeSidebar" />
<VPNav>
<VPNav v-if="frontmatter.navbar !== false">
<template #nav-bar-title-before><slot name="nav-bar-title-before" /></template>
<template #nav-bar-title-after><slot name="nav-bar-title-after" /></template>
<template #nav-bar-content-before><slot name="nav-bar-content-before" /></template>
@ -56,7 +56,7 @@ provide('hero-image-slot-exists', heroImageSlotExists)
<VPContent>
<template #page-top><slot name="page-top" /></template>
<template #page-bottom><slot name="page-bottom" /></template>
<template #not-found><slot name="not-found" /></template>
<template #home-hero-before><slot name="home-hero-before" /></template>
<template #home-hero-info><slot name="home-hero-info" /></template>

@ -4,7 +4,7 @@ import { withBase } from 'vitepress'
import { useData } from './composables/data'
import { useLangs } from './composables/langs'
const { site } = useData()
const { site, theme } = useData()
const { localeLinks } = useLangs({ removeCurrent: false })
const root = ref('/')
@ -22,16 +22,23 @@ onMounted(() => {
<template>
<div class="NotFound">
<p class="code">404</p>
<h1 class="title">PAGE NOT FOUND</h1>
<p class="code">{{ theme.notFound?.code ?? '404' }}</p>
<h1 class="title">{{ theme.notFound?.title ?? 'PAGE NOT FOUND' }}</h1>
<div class="divider" />
<blockquote class="quote">
But if you don't change your direction, and if you keep looking, you may end up where you are heading.
{{
theme.notFound?.quote ??
"But if you don't change your direction, and if you keep looking, you may end up where you are heading."
}}
</blockquote>
<div class="action">
<a class="link" :href="withBase(root)" aria-label="go to home">
Take me home
<a
class="link"
:href="withBase(root)"
:aria-label="theme.notFound?.linkLabel ?? 'go to home'"
>
{{ theme.notFound?.linkText ?? 'Take me home' }}
</a>
</div>
</div>
@ -90,7 +97,9 @@ onMounted(() => {
font-size: 14px;
font-weight: 500;
color: var(--vp-c-brand);
transition: border-color 0.25s, color 0.25s;
transition:
border-color 0.25s,
color 0.25s;
}
.link:hover {

@ -30,7 +30,7 @@ h3 .VPBadge,
h4 .VPBadge,
h5 .VPBadge,
h6 .VPBadge {
vertical-align: top;
vertical-align: text-top;
}
h2 .VPBadge {

@ -1,10 +1,10 @@
<script setup lang="ts">
import NotFound from '../NotFound.vue'
import { useData } from '../composables/data'
import { useSidebar } from '../composables/sidebar'
import VPPage from './VPPage.vue'
import VPHome from './VPHome.vue'
import VPDoc from './VPDoc.vue'
import NotFound from '../NotFound.vue'
import VPHome from './VPHome.vue'
import VPPage from './VPPage.vue'
const { page, frontmatter } = useData()
const { hasSidebar } = useSidebar()

@ -1,11 +1,14 @@
<script setup lang="ts">
import { useRoute } from 'vitepress'
import { computed } from 'vue'
import { useData } from '../composables/data'
import { useSidebar } from '../composables/sidebar'
import VPDocAside from './VPDocAside.vue'
import VPDocFooter from './VPDocFooter.vue'
import VPDocOutlineDropdown from './VPDocOutlineDropdown.vue'
const { theme } = useData()
const route = useRoute()
const { hasSidebar, hasAside, leftAside } = useSidebar()
@ -42,7 +45,13 @@ const pageName = computed(() =>
<slot name="doc-before" />
<VPDocOutlineDropdown />
<main class="main">
<Content class="vp-doc" :class="pageName" />
<Content
class="vp-doc"
:class="[
pageName,
theme.externalLinkIcon && 'external-link-icon-enabled'
]"
/>
</main>
<VPDocFooter>
<template #doc-footer-before><slot name="doc-footer-before" /></template>
@ -65,7 +74,7 @@ const pageName = computed(() =>
display: none;
}
@media (min-width: 960px) and (max-width: 1280px) {
@media (min-width: 960px) and (max-width: 1279px) {
.VPDoc .VPDocOutlineDropdown {
display: block;
}
@ -193,4 +202,9 @@ const pageName = computed(() =>
.VPDoc.has-aside .content-container {
max-width: 688px;
}
.external-link-icon-enabled :is(.vp-doc a[href*='://'], .vp-doc a[target='_blank'])::after {
content: '';
color: currentColor;
}
</style>

@ -41,20 +41,20 @@ const showFooter = computed(() => {
</div>
</div>
<div v-if="control.prev?.link || control.next?.link" class="prev-next">
<nav v-if="control.prev?.link || control.next?.link" class="prev-next">
<div class="pager">
<a v-if="control.prev?.link" class="pager-link prev" :href="normalizeLink(control.prev.link)">
<span class="desc" v-html="theme.docFooter?.prev || 'Previous page'"></span>
<span class="title" v-html="control.prev.text"></span>
</a>
</div>
<div class="pager" :class="{ 'has-prev': control.prev?.link }">
<div class="pager">
<a v-if="control.next?.link" class="pager-link next" :href="normalizeLink(control.next.link)">
<span class="desc" v-html="theme.docFooter?.next || 'Next page'"></span>
<span class="title" v-html="control.next.text"></span>
</a>
</div>
</div>
</nav>
</footer>
</template>
@ -101,29 +101,14 @@ const showFooter = computed(() => {
.prev-next {
border-top: 1px solid var(--vp-c-divider);
padding-top: 24px;
display: grid;
grid-row-gap: 8px;
}
@media (min-width: 640px) {
.prev-next {
display: flex;
}
}
.pager.has-prev {
padding-top: 8px;
}
@media (min-width: 640px) {
.pager {
display: flex;
flex-direction: column;
flex-shrink: 0;
width: 50%;
}
.pager.has-prev {
padding-top: 0;
padding-left: 16px;
grid-template-columns: repeat(2, 1fr);
grid-column-gap: 16px;
}
}

@ -2,7 +2,7 @@
import { ref, computed, watchEffect, onMounted } from 'vue'
import { useData } from '../composables/data'
const { theme, page, lang } = useData()
const { theme, page } = useData()
const date = computed(() => new Date(page.value.lastUpdated!))
const isoDatetime = computed(() => date.value.toISOString())
@ -12,14 +12,20 @@ const datetime = ref('')
// potential differences in timezones of the server and clients
onMounted(() => {
watchEffect(() => {
datetime.value = date.value.toLocaleString(lang.value)
datetime.value = new Intl.DateTimeFormat(
undefined,
theme.value.lastUpdated?.formatOptions ?? {
dateStyle: 'short',
timeStyle: 'short'
}
).format(date.value)
})
})
</script>
<template>
<p class="VPLastUpdated">
{{ theme.lastUpdatedText || 'Last updated' }}:
{{ theme.lastUpdated?.text || theme.lastUpdatedText || 'Last updated' }}:
<time :datetime="isoDatetime">{{ datetime }}</time>
</p>
</template>

@ -7,10 +7,8 @@ defineProps<{
}>()
function onClick({ target: el }: Event) {
const id = '#' + (el as HTMLAnchorElement).href!.split('#')[1]
const heading = document.querySelector<HTMLAnchorElement>(
decodeURIComponent(id)
)
const id = (el as HTMLAnchorElement).href!.split('#')[1]
const heading = document.getElementById(decodeURIComponent(id))
heading?.focus()
}
</script>

@ -10,11 +10,12 @@ defineProps<{
details?: string
link?: string
linkText?: string
rel?: string
}>()
</script>
<template>
<VPLink class="VPFeature" :href="link" :no-icon="true">
<VPLink class="VPFeature" :href="link" :rel="rel" :no-icon="true" :tag="link ? 'a' : 'div'">
<article class="box">
<VPImage
v-if="typeof icon === 'object'"

@ -9,6 +9,7 @@ export interface Feature {
details: string
link?: string
linkText?: string
rel?: string
}
const props = defineProps<{
@ -48,6 +49,7 @@ const grid = computed(() => {
:details="feature.details"
:link="feature.link"
:link-text="feature.linkText"
:rel="feature.rel"
/>
</div>
</div>

@ -2,12 +2,12 @@
import { useData } from '../composables/data'
import { useSidebar } from '../composables/sidebar'
const { theme } = useData()
const { theme, frontmatter } = useData()
const { hasSidebar } = useSidebar()
</script>
<template>
<footer v-if="theme.footer" class="VPFooter" :class="{ 'has-sidebar': hasSidebar }">
<footer v-if="theme.footer && frontmatter.footer !== false" class="VPFooter" :class="{ 'has-sidebar': hasSidebar }">
<div class="container">
<p v-if="theme.footer.message" class="message" v-html="theme.footer.message"></p>
<p v-if="theme.footer.copyright" class="copyright" v-html="theme.footer.copyright"></p>
@ -47,7 +47,4 @@ const { hasSidebar } = useSidebar()
font-weight: 500;
color: var(--vp-c-text-2);
}
.message { order: 2; }
.copyright { order: 1; }
</style>

@ -27,10 +27,10 @@ const heroImageSlotExists = inject('hero-image-slot-exists') as Ref<boolean>
<div class="main">
<slot name="home-hero-info">
<h1 v-if="name" class="name">
<span class="clip">{{ name }}</span>
<span v-html="name" class="clip"></span>
</h1>
<p v-if="text" class="text">{{ text }}</p>
<p v-if="tagline" class="tagline">{{ tagline }}</p>
<p v-if="text" v-html="text" class="text"></p>
<p v-if="tagline" v-html="tagline" class="tagline"></p>
</slot>
<div v-if="actions" class="actions">

@ -1,7 +1,6 @@
<script lang="ts" setup>
import { computed } from 'vue'
import { normalizeLink } from '../support/utils'
import VPIconExternalLink from './icons/VPIconExternalLink.vue'
import { EXTERNAL_URL_RE } from '../../shared'
const props = defineProps<{
@ -12,7 +11,7 @@ const props = defineProps<{
rel?: string
}>()
const tag = computed(() => props.tag ?? props.href ? 'a' : 'span')
const tag = computed(() => props.tag ?? (props.href ? 'a' : 'span'))
const isExternal = computed(() => props.href && EXTERNAL_URL_RE.test(props.href))
</script>
@ -20,25 +19,15 @@ const isExternal = computed(() => props.href && EXTERNAL_URL_RE.test(props.href)
<component
:is="tag"
class="VPLink"
:class="{ link: href }"
:class="{
link: href,
'vp-external-link-icon': isExternal,
'no-icon': noIcon
}"
:href="href ? normalizeLink(href) : undefined"
:target="target || (isExternal ? '_blank' : undefined)"
:rel="rel || (isExternal ? 'noreferrer' : undefined)"
:target="target ?? (isExternal ? '_blank' : undefined)"
:rel="rel ?? (isExternal ? 'noreferrer' : undefined)"
>
<slot />
<VPIconExternalLink v-if="isExternal && !noIcon" class="icon" />
</component>
</template>
<style scoped>
.icon {
display: inline-block;
margin-top: -1px;
margin-left: 4px;
width: 11px;
height: 11px;
fill: var(--vp-c-text-3);
transition: fill 0.25s;
flex-shrink: 0;
}
</style>

@ -1,8 +1,12 @@
<script lang="ts" setup>
import { useWindowScroll } from '@vueuse/core'
import { onContentUpdated } from 'vitepress'
import { computed, shallowRef, ref, onMounted } from 'vue'
import { useData } from '../composables/data'
import { useSidebar } from '../composables/sidebar'
import VPIconAlignLeft from './icons/VPIconAlignLeft.vue'
import { getHeaders, type MenuItem } from '../composables/outline'
import VPLocalNavOutlineDropdown from './VPLocalNavOutlineDropdown.vue'
import VPIconAlignLeft from './icons/VPIconAlignLeft.vue'
defineProps<{
open: boolean
@ -14,10 +18,41 @@ defineEmits<{
const { theme, frontmatter } = useData()
const { hasSidebar } = useSidebar()
const { y } = useWindowScroll()
const headers = shallowRef<MenuItem[]>([])
const navHeight = ref(0)
onMounted(() => {
navHeight.value = parseInt(
getComputedStyle(document.documentElement).getPropertyValue(
'--vp-nav-height'
)
)
})
onContentUpdated(() => {
headers.value = getHeaders(frontmatter.value.outline ?? theme.value.outline)
})
const empty = computed(() => {
return headers.value.length === 0 && !hasSidebar.value
})
const classes = computed(() => {
return {
VPLocalNav: true,
fixed: empty.value,
'reached-top': y.value >= navHeight.value
}
})
</script>
<template>
<div class="VPLocalNav" v-if="frontmatter.layout !== 'home'">
<div
v-if="frontmatter.layout !== 'home' && (!empty || y >= navHeight)"
:class="classes"
>
<button
v-if="hasSidebar"
class="menu"
@ -31,7 +66,7 @@ const { hasSidebar } = useSidebar()
</span>
</button>
<VPLocalNavOutlineDropdown />
<VPLocalNavOutlineDropdown :headers="headers" :navHeight="navHeight" />
</div>
</template>
@ -45,11 +80,19 @@ const { hasSidebar } = useSidebar()
display: flex;
justify-content: space-between;
align-items: center;
border-top: 1px solid var(--vp-c-gutter);
border-bottom: 1px solid var(--vp-c-gutter);
padding-top: var(--vp-layout-top-height, 0px);
width: 100%;
background-color: var(--vp-local-nav-bg-color);
transition: border-color 0.5s, background-color 0.5s;
}
.VPLocalNav.fixed {
position: fixed;
}
.VPLocalNav.reached-top {
border-top-color: transparent;
}
@media (min-width: 960px) {

@ -1,12 +1,17 @@
<script setup lang="ts">
import { ref, nextTick, shallowRef } from 'vue'
import { onContentUpdated } from 'vitepress'
import { nextTick, ref } from 'vue'
import { useData } from '../composables/data'
import { getHeaders, resolveTitle, type MenuItem } from '../composables/outline'
import { resolveTitle, type MenuItem } from '../composables/outline'
import VPDocOutlineItem from './VPDocOutlineItem.vue'
import { onContentUpdated } from 'vitepress'
import VPIconChevronRight from './icons/VPIconChevronRight.vue'
const { frontmatter, theme } = useData()
const props = defineProps<{
headers: MenuItem[]
navHeight: number
}>()
const { theme } = useData()
const open = ref(false)
const vh = ref(0)
const items = ref<HTMLDivElement>()
@ -17,7 +22,7 @@ onContentUpdated(() => {
function toggle() {
open.value = !open.value
vh.value = window.innerHeight + Math.min(window.scrollY - 64, 0)
vh.value = window.innerHeight + Math.min(window.scrollY - props.navHeight, 0)
}
function onItemClick(e: Event) {
@ -36,14 +41,6 @@ function scrollToTop() {
open.value = false
window.scrollTo({ top: 0, left: 0, behavior: 'smooth' })
}
const headers = shallowRef<MenuItem[]>([])
onContentUpdated(() => {
headers.value = getHeaders(
frontmatter.value.outline ?? theme.value.outline
)
})
</script>
<template>

@ -12,7 +12,7 @@ import {
import { useFocusTrap } from '@vueuse/integrations/useFocusTrap'
import Mark from 'mark.js/src/vanilla.js'
import MiniSearch, { type SearchResult } from 'minisearch'
import { useRouter } from 'vitepress'
import { useRouter, dataSymbol } from 'vitepress'
import {
computed,
createApp,
@ -27,7 +27,6 @@ import {
type Ref
} from 'vue'
import type { ModalTranslations } from '../../../../types/local-search'
import { dataSymbol } from '../../app/data'
import { pathToFile } from '../../app/utils'
import { useData } from '../composables/data'
import { createTranslate } from '../support/translation'
@ -81,8 +80,12 @@ const searchIndex = computedAsync(async () =>
searchOptions: {
fuzzy: 0.2,
prefix: true,
boost: { title: 4, text: 2, titles: 1 }
}
boost: { title: 4, text: 2, titles: 1 },
...(theme.value.search?.provider === 'local' &&
theme.value.search.options?.miniSearch?.searchOptions)
},
...(theme.value.search?.provider === 'local' &&
theme.value.search.options?.miniSearch?.options)
}
)
)
@ -101,13 +104,15 @@ const filterText = disableQueryPersistence.value
const showDetailedList = useLocalStorage(
'vitepress:local-search-detailed-list',
false
theme.value.search?.provider === 'local' &&
theme.value.search.options?.detailedView === true
)
const disableDetailedView = computed(() => {
return (
theme.value.search?.provider === 'local' &&
theme.value.search.options?.disableDetailedView === true
(theme.value.search.options?.disableDetailedView === true ||
theme.value.search.options?.detailedView === false)
)
})
@ -119,8 +124,6 @@ watchEffect(() => {
const results: Ref<(SearchResult & Result)[]> = shallowRef([])
const headingRegex = /<h(\d*).*?>.*?<a.*? href="#(.*?)".*?>.*?<\/a><\/h\1>/gi
const enableNoResults = ref(false)
watch(filterText, () => {
@ -158,12 +161,10 @@ debouncedWatch(
const mapId = id.slice(0, id.indexOf('#'))
let map = c.get(mapId)
if (map) continue
else {
map = new Map()
c.set(mapId, map)
}
map = new Map()
c.set(mapId, map)
const comp = mod.default ?? mod
if (comp?.render) {
if (comp?.render || comp?.setup) {
const app = createApp(comp)
// Silence warnings about missing components
app.config.warnHandler = () => {}
@ -182,14 +183,17 @@ debouncedWatch(
})
const div = document.createElement('div')
app.mount(div)
const sections = div.innerHTML.split(headingRegex)
const headings = div.querySelectorAll('h1, h2, h3, h4, h5, h6')
headings.forEach((el) => {
const href = el.querySelector('a')?.getAttribute('href')
const anchor = href?.startsWith('#') && href.slice(1)
if (!anchor) return
let html = ''
while ((el = el.nextElementSibling!) && !/^h[1-6]$/i.test(el.tagName))
html += el.outerHTML
map!.set(anchor, html)
})
app.unmount()
sections.shift()
for (let i = 0; i < sections.length; i += 3) {
const anchor = sections[i + 1]
const html = sections[i + 2]
map.set(anchor, html)
}
}
if (canceled) return
}
@ -232,6 +236,7 @@ debouncedWatch(
async function fetchExcerpt(id: string) {
const file = pathToFile(id.slice(0, id.indexOf('#')))
try {
if (!file) throw new Error(`Cannot find file for id: ${id}`)
return { id, mod: await import(/*@vite-ignore*/ file) }
} catch (e) {
console.error(e)
@ -242,10 +247,12 @@ async function fetchExcerpt(id: string) {
/* Search input focus */
const searchInput = ref<HTMLInputElement>()
function focusSearchInput() {
const disableReset = computed(() => {
return filterText.value?.length <= 0
})
function focusSearchInput(select = true) {
searchInput.value?.focus()
searchInput.value?.select()
select && searchInput.value?.select()
}
onMounted(() => {
@ -260,11 +267,11 @@ function onSearchBarClick(event: PointerEvent) {
/* Search keyboard selection */
const selectedIndex = ref(0)
const selectedIndex = ref(-1)
const disableMouseOver = ref(false)
watch(results, () => {
selectedIndex.value = 0
watch(results, (r) => {
selectedIndex.value = r.length ? 0 : -1
scrollToSelectedResult()
})
@ -361,6 +368,11 @@ onBeforeUnmount(() => {
isLocked.value = false
})
function resetSearch() {
filterText.value = ''
nextTick().then(() => focusSearchInput(false))
}
function formMarkRegex(terms: Set<string>) {
return new RegExp(
[...terms]
@ -378,29 +390,47 @@ function formMarkRegex(terms: Set<string>) {
<template>
<Teleport to="body">
<div ref="el" class="VPLocalSearchBox" aria-modal="true">
<div
ref="el"
role="button"
:aria-owns="results?.length ? 'localsearch-list' : undefined"
aria-expanded="true"
aria-haspopup="listbox"
aria-labelledby="localsearch-label"
class="VPLocalSearchBox"
>
<div class="backdrop" @click="$emit('close')" />
<div class="shell">
<div class="search-bar" @pointerup="onSearchBarClick($event)">
<svg
class="search-icon"
width="18"
height="18"
viewBox="0 0 24 24"
aria-hidden="true"
<form
class="search-bar"
@pointerup="onSearchBarClick($event)"
@submit.prevent=""
>
<label
:title="placeholder"
id="localsearch-label"
for="localsearch-input"
>
<g
fill="none"
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
<svg
class="search-icon"
width="18"
height="18"
viewBox="0 0 24 24"
aria-hidden="true"
>
<circle cx="11" cy="11" r="8" />
<path d="m21 21l-4.35-4.35" />
</g>
</svg>
<g
fill="none"
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
>
<circle cx="11" cy="11" r="8" />
<path d="m21 21l-4.35-4.35" />
</g>
</svg>
</label>
<div class="search-actions before">
<button
class="back-button"
@ -428,6 +458,8 @@ function formMarkRegex(terms: Set<string>) {
ref="searchInput"
v-model="filterText"
:placeholder="placeholder"
id="localsearch-input"
aria-labelledby="localsearch-label"
class="search-input"
/>
<div class="search-actions">
@ -436,7 +468,9 @@ function formMarkRegex(terms: Set<string>) {
class="toggle-layout-button"
:class="{ 'detailed-list': showDetailedList }"
:title="$t('modal.displayDetails')"
@click="showDetailedList = !showDetailedList"
@click="
selectedIndex > -1 && (showDetailedList = !showDetailedList)
"
>
<svg
width="18"
@ -457,8 +491,10 @@ function formMarkRegex(terms: Set<string>) {
<button
class="clear-button"
type="reset"
:disabled="disableReset"
:title="$t('modal.resetButtonTitle')"
@click="filterText = ''"
@click="resetSearch"
>
<svg
width="18"
@ -477,65 +513,76 @@ function formMarkRegex(terms: Set<string>) {
</svg>
</button>
</div>
</div>
</form>
<div
<ul
ref="resultsEl"
:id="results?.length ? 'localsearch-list' : undefined"
:role="results?.length ? 'listbox' : undefined"
:aria-labelledby="results?.length ? 'localsearch-label' : undefined"
class="results"
@mousemove="disableMouseOver = false"
>
<a
<li
v-for="(p, index) in results"
:key="p.id"
:href="p.id"
class="result"
:class="{
selected: selectedIndex === index
}"
:aria-label="[...p.titles, p.title].join(' > ')"
@mouseenter="!disableMouseOver && (selectedIndex = index)"
@focusin="selectedIndex = index"
@click="$emit('close')"
role="option"
:aria-selected="selectedIndex === index ? 'true' : 'false'"
>
<div>
<div class="titles">
<span class="title-icon">#</span>
<span v-for="(t, index) in p.titles" :key="index" class="title">
<span class="text" v-html="t" />
<svg width="18" height="18" viewBox="0 0 24 24">
<path
fill="none"
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="m9 18l6-6l-6-6"
/>
</svg>
</span>
<span class="title main">
<span class="text" v-html="p.title" />
</span>
</div>
<a
:href="p.id"
class="result"
:class="{
selected: selectedIndex === index
}"
:aria-label="[...p.titles, p.title].join(' > ')"
@mouseenter="!disableMouseOver && (selectedIndex = index)"
@focusin="selectedIndex = index"
@click="$emit('close')"
>
<div>
<div class="titles">
<span class="title-icon">#</span>
<span
v-for="(t, index) in p.titles"
:key="index"
class="title"
>
<span class="text" v-html="t" />
<svg width="18" height="18" viewBox="0 0 24 24">
<path
fill="none"
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="m9 18l6-6l-6-6"
/>
</svg>
</span>
<span class="title main">
<span class="text" v-html="p.title" />
</span>
</div>
<div v-if="showDetailedList" class="excerpt-wrapper">
<div v-if="p.text" class="excerpt" inert>
<div class="vp-doc" v-html="p.text" />
<div v-if="showDetailedList" class="excerpt-wrapper">
<div v-if="p.text" class="excerpt" inert>
<div class="vp-doc" v-html="p.text" />
</div>
<div class="excerpt-gradient-bottom" />
<div class="excerpt-gradient-top" />
</div>
<div class="excerpt-gradient-bottom" />
<div class="excerpt-gradient-top" />
</div>
</div>
</a>
<div
</a>
</li>
<li
v-if="filterText && !results.length && enableNoResults"
class="no-results"
>
{{ $t('modal.noResultsText') }} "<strong>{{ filterText }}</strong
>"
</div>
</div>
</li>
</ul>
<div class="search-keyboard-shortcuts">
<span>
@ -693,11 +740,15 @@ function formMarkRegex(terms: Set<string>) {
padding: 8px;
}
.search-actions button:hover,
.search-actions button:not([disabled]):hover,
.toggle-layout-button.detailed-list {
color: var(--vp-c-brand);
}
.search-actions button.clear-button:disabled {
opacity: 0.37;
}
.search-keyboard-shortcuts {
font-size: 0.8rem;
opacity: 75%;

@ -1,15 +1,15 @@
<script lang="ts" setup>
import { computed } from 'vue'
import { useWindowScroll } from '@vueuse/core'
import { computed } from 'vue'
import { useSidebar } from '../composables/sidebar'
import VPNavBarTitle from './VPNavBarTitle.vue'
import VPNavBarSearch from './VPNavBarSearch.vue'
import VPNavBarMenu from './VPNavBarMenu.vue'
import VPNavBarTranslations from './VPNavBarTranslations.vue'
import VPNavBarAppearance from './VPNavBarAppearance.vue'
import VPNavBarSocialLinks from './VPNavBarSocialLinks.vue'
import VPNavBarExtra from './VPNavBarExtra.vue'
import VPNavBarHamburger from './VPNavBarHamburger.vue'
import VPNavBarMenu from './VPNavBarMenu.vue'
import VPNavBarSearch from './VPNavBarSearch.vue'
import VPNavBarSocialLinks from './VPNavBarSocialLinks.vue'
import VPNavBarTitle from './VPNavBarTitle.vue'
import VPNavBarTranslations from './VPNavBarTranslations.vue'
defineProps<{
isScreenOpen: boolean
@ -62,15 +62,10 @@ const classes = computed(() => ({
border-bottom: 1px solid transparent;
padding: 0 8px 0 24px;
height: var(--vp-nav-height);
transition: border-color 0.5s, background-color 0.5s;
pointer-events: none;
white-space: nowrap;
}
.VPNavBar.has-sidebar {
border-bottom-color: var(--vp-c-gutter);
}
@media (min-width: 768px) {
.VPNavBar {
padding: 0 32px;
@ -79,7 +74,6 @@ const classes = computed(() => ({
@media (min-width: 960px) {
.VPNavBar.has-sidebar {
border-bottom-color: transparent;
padding: 0;
}

@ -26,6 +26,7 @@ const { theme, localeIndex } = useData()
// payload), we delay initializing it until the user has actually clicked or
// hit the hotkey to invoke it.
const loaded = ref(false)
const actuallyLoaded = ref(false)
const buttonText = computed(() => {
const options = theme.value.search?.options ?? theme.value.algolia
@ -169,9 +170,10 @@ const provider = __ALGOLIA__ ? 'algolia' : __VP_LOCAL_SEARCH__ ? 'local' : ''
<VPAlgoliaSearchBox
v-if="loaded"
:algolia="theme.search?.options ?? theme.algolia"
@vue:beforeMount="actuallyLoaded = true"
/>
<div v-else id="docsearch">
<div v-if="!actuallyLoaded" id="docsearch">
<VPNavBarSearchButton :placeholder="buttonText" @click="load" />
</div>
</template>

@ -1,7 +1,7 @@
<script setup lang="ts">
import { useData } from '../composables/data'
import { useSidebar } from '../composables/sidebar'
import { useLangs } from '../composables/langs'
import { useSidebar } from '../composables/sidebar'
import { normalizeLink } from '../support/utils'
import VPImage from './VPImage.vue'
@ -47,6 +47,6 @@ const { currentLang } = useLangs()
:deep(.logo) {
margin-right: 8px;
height: 24px;
height: var(--vp-nav-logo-height);
}
</style>

@ -27,7 +27,7 @@ function unlockBodyScroll() {
@enter="lockBodyScroll"
@after-leave="unlockBodyScroll"
>
<div v-if="open" class="VPNavScreen" ref="screen">
<div v-if="open" class="VPNavScreen" ref="screen" id="VPNavScreen">
<div class="container">
<slot name="nav-screen-content-before" />
<VPNavScreenMenu class="menu" />

@ -1,6 +1,6 @@
<script lang="ts" setup>
import { clearAllBodyScrollLocks, disableBodyScroll } from 'body-scroll-lock'
import { ref, watchPostEffect } from 'vue'
import { disableBodyScroll, clearAllBodyScrollLocks } from 'body-scroll-lock'
import { useSidebar } from '../composables/sidebar'
import VPSidebarItem from './VPSidebarItem.vue'

@ -193,6 +193,7 @@ function onCaretClick() {
color: var(--vp-c-text-3);
cursor: pointer;
transition: color 0.25s;
flex-shrink: 0;
}
.item:hover .caret {

@ -8,8 +8,8 @@ const backToTop = ref()
watch(() => route.path, () => backToTop.value.focus())
function focusOnTargetAnchor({ target }: Event) {
const el = document.querySelector<HTMLAnchorElement>(
decodeURIComponent((target as HTMLAnchorElement).hash)
const el = document.getElementById(
decodeURIComponent((target as HTMLAnchorElement).hash).slice(1)
)
if (el) {

@ -6,6 +6,7 @@ import { icons } from '../support/socialIcons'
const props = defineProps<{
icon: DefaultTheme.SocialLinkIcon
link: string
ariaLabel?: string
}>()
const svg = computed(() => {
@ -16,9 +17,9 @@ const svg = computed(() => {
<template>
<a
class="VPSocialLink"
class="VPSocialLink no-icon"
:href="link"
:aria-label="typeof icon === 'string' ? icon : ''"
:aria-label="ariaLabel ?? (typeof icon === 'string' ? icon : '')"
target="_blank"
rel="noopener"
v-html="svg"

@ -10,10 +10,11 @@ defineProps<{
<template>
<div class="VPSocialLinks">
<VPSocialLink
v-for="{ link, icon } in links"
v-for="{ link, icon, ariaLabel } in links"
:key="link"
:icon="icon"
:link="link"
:ariaLabel="ariaLabel"
/>
</div>
</template>

@ -1,13 +0,0 @@
<template>
<svg
xmlns="http://www.w3.org/2000/svg"
aria-hidden="true"
focusable="false"
height="24px"
viewBox="0 0 24 24"
width="24px"
>
<path d="M0 0h24v24H0V0z" fill="none" />
<path d="M9 5v2h6.59L4 18.59 5.41 20 17 8.41V15h2V5H9z" />
</svg>
</template>

@ -1,5 +1,5 @@
import { computed } from 'vue'
import { useMediaQuery } from '@vueuse/core'
import { computed } from 'vue'
import { useSidebar } from './sidebar'
export function useAside() {

@ -43,7 +43,7 @@ function normalizeLink(
? link.replace(/\/$/, '') +
ensureStartingSlash(
path
.replace(/(^|\/)?index.md$/, '$1')
.replace(/(^|\/)index\.md$/, '$1')
.replace(/\.md$/, addExt ? '.html' : '')
)
: link

@ -1,7 +1,7 @@
import type { DefaultTheme } from 'vitepress/theme'
import { onMounted, onUnmounted, onUpdated, type Ref } from 'vue'
import type { Header } from '../../shared'
import { useAside } from '../composables/aside'
import { useAside } from './aside'
import { throttleAndDebounce } from '../support/utils'
// magic number to avoid repeated retrieval

@ -14,37 +14,43 @@ export function usePrevNext() {
return isActive(page.value.relativePath, link.link)
})
const hidePrev =
(theme.value.docFooter?.prev === false && !frontmatter.value.prev) ||
frontmatter.value.prev === false
const hideNext =
(theme.value.docFooter?.next === false && !frontmatter.value.next) ||
frontmatter.value.next === false
return {
prev:
frontmatter.value.prev === false
? undefined
: {
text:
(typeof frontmatter.value.prev === 'string'
? frontmatter.value.prev
: typeof frontmatter.value.prev === 'object'
? frontmatter.value.prev.text
: undefined) ?? candidates[index - 1]?.text,
link:
(typeof frontmatter.value.prev === 'object'
? frontmatter.value.prev.link
: undefined) ?? candidates[index - 1]?.link
},
next:
frontmatter.value.next === false
? undefined
: {
text:
(typeof frontmatter.value.next === 'string'
? frontmatter.value.next
: typeof frontmatter.value.next === 'object'
? frontmatter.value.next.text
: undefined) ?? candidates[index + 1]?.text,
link:
(typeof frontmatter.value.next === 'object'
? frontmatter.value.next.link
: undefined) ?? candidates[index + 1]?.link
}
prev: hidePrev
? undefined
: {
text:
(typeof frontmatter.value.prev === 'string'
? frontmatter.value.prev
: typeof frontmatter.value.prev === 'object'
? frontmatter.value.prev.text
: undefined) ?? candidates[index - 1]?.text,
link:
(typeof frontmatter.value.prev === 'object'
? frontmatter.value.prev.link
: undefined) ?? candidates[index - 1]?.link
},
next: hideNext
? undefined
: {
text:
(typeof frontmatter.value.next === 'string'
? frontmatter.value.next
: typeof frontmatter.value.next === 'object'
? frontmatter.value.next.text
: undefined) ?? candidates[index + 1]?.text,
link:
(typeof frontmatter.value.next === 'object'
? frontmatter.value.next.link
: undefined) ?? candidates[index + 1]?.link
}
} as {
prev?: { text?: string; link?: string }
next?: { text?: string; link?: string }

@ -11,16 +11,7 @@
background-color: var(--vp-code-tab-bg);
overflow-x: auto;
overflow-y: hidden;
}
.vp-code-group .tabs::after {
position: absolute;
right: 0;
bottom: 0;
left: 0;
height: 1px;
background-color: var(--vp-code-tab-divider);
content: '';
box-shadow: inset 0 -1px var(--vp-code-tab-divider);
}
@media (min-width: 640px) {
@ -75,13 +66,19 @@
background-color: var(--vp-code-tab-active-bar-color);
}
.vp-code-group div[class*='language-'] {
.vp-code-group div[class*='language-'],
.vp-block {
display: none;
margin-top: 0 !important;
border-top-left-radius: 0 !important;
border-top-right-radius: 0 !important;
}
.vp-code-group div[class*='language-'].active {
.vp-code-group div[class*='language-'].active,
.vp-block.active {
display: block;
}
.vp-block {
padding: 20px 24px;
}

@ -36,13 +36,16 @@
}
.vp-doc .header-anchor {
float: left;
position: absolute;
top: 0;
left: 0;
margin-left: -0.87em;
padding-right: 0.23em;
font-weight: 500;
user-select: none;
opacity: 0;
transition: color 0.25s, opacity 0.25s;
transition:
color 0.25s,
opacity 0.25s;
}
.vp-doc .header-anchor:before {
@ -72,6 +75,10 @@
}
}
.vp-doc h2 .header-anchor {
top: 24px;
}
/**
* Paragraph and inline elements
* -------------------------------------------------------------------------- */
@ -224,6 +231,7 @@
.vp-doc .custom-block div[class*='language-'] {
margin: 8px 0;
border-radius: 8px;
}
.vp-doc .custom-block div[class*='language-'] code {
@ -231,6 +239,11 @@
background-color: transparent;
}
.vp-doc .custom-block .vp-code-group .tabs {
margin: 0;
border-radius: 8px 8px 0 0;
}
/**
* Code
* -------------------------------------------------------------------------- */
@ -245,7 +258,9 @@
padding: 3px 6px;
color: var(--vp-c-text-code);
background-color: var(--vp-c-mute);
transition: color 0.5s, background-color 0.5s;
transition:
color 0.5s,
background-color 0.5s;
}
.vp-doc h1 > code,
@ -263,7 +278,8 @@
color: var(--vp-c-brand-dark);
}
.vp-doc div[class*='language-'] {
.vp-doc div[class*='language-'],
.vp-block {
position: relative;
margin: 16px -24px;
background-color: var(--vp-code-block-bg);
@ -272,7 +288,8 @@
}
@media (min-width: 640px) {
.vp-doc div[class*='language-'] {
.vp-doc div[class*='language-'],
.vp-block {
border-radius: 8px;
margin: 16px 0;
}
@ -362,12 +379,16 @@
.vp-doc [class*='language-'] .has-focused-lines .line:not(.has-focus) {
filter: blur(0.095rem);
opacity: 0.4;
transition: filter 0.35s, opacity 0.35s;
transition:
filter 0.35s,
opacity 0.35s;
}
.vp-doc [class*='language-'] .has-focused-lines .line:not(.has-focus) {
opacity: 0.7;
transition: filter 0.35s, opacity 0.35s;
transition:
filter 0.35s,
opacity 0.35s;
}
.vp-doc [class*='language-']:hover .has-focused-lines .line:not(.has-focus) {
@ -415,7 +436,9 @@
line-height: var(--vp-code-line-height);
font-size: var(--vp-code-font-size);
color: var(--vp-code-line-number-color);
transition: border-color 0.5s, color 0.5s;
transition:
border-color 0.5s,
color 0.5s;
}
.vp-doc [class*='language-'] > button.copy {
@ -437,7 +460,10 @@
background-position: 50%;
background-size: 20px;
background-repeat: no-repeat;
transition: border-color 0.25s, background-color 0.25s, opacity 0.25s;
transition:
border-color 0.25s,
background-color 0.25s,
opacity 0.25s;
}
.vp-doc [class*='language-']:hover > button.copy,
@ -492,7 +518,9 @@
font-size: 12px;
font-weight: 500;
color: var(--vp-c-code-dimm);
transition: color 0.4s, opacity 0.4s;
transition:
color 0.4s,
opacity 0.4s;
}
.vp-doc [class*='language-']:hover > button.copy + span.lang,
@ -522,3 +550,22 @@
margin: 0 !important;
max-width: calc((100% - 24px) / 2) !important;
}
/* prettier-ignore */
:is(.vp-external-link-icon, .vp-doc a[href*='://'], .vp-doc a[target='_blank']):not(.no-icon)::after {
display: inline-block;
margin-top: -1px;
margin-left: 4px;
width: 11px;
height: 11px;
background: currentColor;
color: var(--vp-c-text-3);
flex-shrink: 0;
--icon: url("data:image/svg+xml, %3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' %3E%3Cpath d='M0 0h24v24H0V0z' fill='none' /%3E%3Cpath d='M9 5v2h6.59L4 18.59 5.41 20 17 8.41V15h2V5H9z' /%3E%3C/svg%3E");
-webkit-mask-image: var(--icon);
mask-image: var(--icon);
}
.vp-external-link-icon::after {
content: '';
}

@ -361,6 +361,7 @@
--vp-nav-height: 64px;
--vp-nav-bg-color: var(--vp-c-bg);
--vp-nav-screen-bg-color: var(--vp-c-bg);
--vp-nav-logo-height: 24px;
}
/**

@ -33,7 +33,7 @@ export function normalizeLink(url: string): string {
}
const { site } = useData()
const { pathname, search, hash } = new URL(url, 'http://example.com')
const { pathname, search, hash } = new URL(url, 'http://a.com')
const normalizedPath =
pathname.endsWith('/') || pathname.endsWith('.html')

@ -23,6 +23,8 @@ export { default as VPTeamPageTitle } from './components/VPTeamPageTitle.vue'
export { default as VPTeamPageSection } from './components/VPTeamPageSection.vue'
export { default as VPTeamMembers } from './components/VPTeamMembers.vue'
export { useSidebar } from './composables/sidebar'
const theme: Theme = {
Layout,
enhanceApp: ({ app }) => {

@ -1,16 +1,18 @@
import { createHash } from 'crypto'
import fs from 'fs-extra'
import path from 'path'
import ora from 'ora'
import type { BuildOptions } from 'vite'
import type { OutputChunk, OutputAsset } from 'rollup'
import { resolveConfig } from '../config'
import { renderPage } from './render'
import { bundle, okMark, failMark } from './bundle'
import { createRequire } from 'module'
import { pathToFileURL } from 'url'
import path from 'path'
import { packageDirectorySync } from 'pkg-dir'
import { serializeFunctions } from '../utils/fnSerialize'
import type { HeadConfig } from '../shared'
import { rimraf } from 'rimraf'
import { pathToFileURL } from 'url'
import type { BuildOptions, Rollup } from 'vite'
import { resolveConfig, type SiteConfig } from '../config'
import { slash, type HeadConfig } from '../shared'
import { deserializeFunctions, serializeFunctions } from '../utils/fnSerialize'
import { task } from '../utils/task'
import { bundle } from './bundle'
import { generateSitemap } from './generateSitemap'
import { renderPage } from './render'
export async function build(
root?: string,
@ -32,6 +34,11 @@ export async function build(
delete buildOptions.mpa
}
if (buildOptions.outDir) {
siteConfig.outDir = path.resolve(process.cwd(), buildOptions.outDir)
delete buildOptions.outDir
}
try {
const { clientResult, serverResult, pageToHashMap } = await bundle(
siteConfig,
@ -41,10 +48,7 @@ export async function build(
const entryPath = path.join(siteConfig.tempDir, 'app.js')
const { render } = await import(pathToFileURL(entryPath).toString())
const spinner = ora()
spinner.start('rendering pages...')
try {
await task('rendering pages', async () => {
const appChunk =
clientResult &&
(clientResult.output.find(
@ -52,15 +56,15 @@ export async function build(
chunk.type === 'chunk' &&
chunk.isEntry &&
chunk.facadeModuleId?.endsWith('.js')
) as OutputChunk)
) as Rollup.OutputChunk)
const cssChunk = (
siteConfig.mpa ? serverResult : clientResult
siteConfig.mpa ? serverResult : clientResult!
).output.find(
(chunk) => chunk.type === 'asset' && chunk.fileName.endsWith('.css')
) as OutputAsset
) as Rollup.OutputAsset
const assets = (siteConfig.mpa ? serverResult : clientResult).output
const assets = (siteConfig.mpa ? serverResult : clientResult!).output
.filter(
(chunk) => chunk.type === 'asset' && !chunk.fileName.endsWith('.css')
)
@ -78,6 +82,8 @@ export async function build(
chunk.moduleIds.some((id) => id.includes('client/theme-default'))
)
const metadataScript = generateMetadataScript(pageToHashMap, siteConfig)
if (isDefaultTheme) {
const fontURL = assets.find((file) =>
/inter-roman-latin\.\w+\.woff2/.test(file)
@ -96,15 +102,6 @@ export async function build(
}
}
// We embed the hash map and site config strings into each page directly
// so that it doesn't alter the main chunk's hash on every build.
// It's also embedded as a string and JSON.parsed from the client because
// it's faster than embedding as JS object literal.
const hashMapString = JSON.stringify(JSON.stringify(pageToHashMap))
const siteDataString = JSON.stringify(
JSON.stringify(serializeFunctions({ ...siteConfig.site, head: [] }))
)
await Promise.all(
['404.md', ...siteConfig.pages]
.map((page) => siteConfig.rewrites.map[page] || page)
@ -118,20 +115,11 @@ export async function build(
cssChunk,
assets,
pageToHashMap,
hashMapString,
siteDataString,
metadataScript,
additionalHeadTags
)
)
)
} catch (e) {
spinner.stopAndPersist({
symbol: failMark
})
throw e
}
spinner.stopAndPersist({
symbol: okMark
})
// emit page hash map for the case where a user session is open
@ -142,10 +130,10 @@ export async function build(
)
} finally {
unlinkVue()
if (!process.env.DEBUG)
fs.rmSync(siteConfig.tempDir, { recursive: true, force: true })
if (!process.env.DEBUG) await rimraf(siteConfig.tempDir)
}
await generateSitemap(siteConfig)
await siteConfig.buildEnd?.(siteConfig)
siteConfig.logger.info(
@ -168,3 +156,51 @@ function linkVue() {
}
return () => {}
}
function generateMetadataScript(
pageToHashMap: Record<string, string>,
config: SiteConfig
) {
if (config.mpa) {
return { html: '', inHead: false }
}
// We embed the hash map and site config strings into each page directly
// so that it doesn't alter the main chunk's hash on every build.
// It's also embedded as a string and JSON.parsed from the client because
// it's faster than embedding as JS object literal.
const hashMapString = JSON.stringify(JSON.stringify(pageToHashMap))
const siteDataString = JSON.stringify(
JSON.stringify(serializeFunctions({ ...config.site, head: [] }))
)
const metadataContent = `window.__VP_HASH_MAP__=JSON.parse(${hashMapString});${
siteDataString.includes('_vp-fn_')
? `${deserializeFunctions.toString()};window.__VP_SITE_DATA__=deserializeFunctions(JSON.parse(${siteDataString}));`
: `window.__VP_SITE_DATA__=JSON.parse(${siteDataString});`
}`
if (!config.metaChunk) {
return { html: `<script>${metadataContent}</script>`, inHead: false }
}
const metadataFile = path.join(
config.assetsDir,
'chunks',
`metadata.${createHash('sha256')
.update(metadataContent)
.digest('hex')
.slice(0, 8)}.js`
)
const resolvedMetadataFile = path.join(config.outDir, metadataFile)
const metadataFileURL = slash(`${config.site.base}${metadataFile}`)
fs.ensureDirSync(path.dirname(resolvedMetadataFile))
fs.writeFileSync(resolvedMetadataFile, metadataContent)
return {
html: `<script type="module" src="${metadataFileURL}"></script>`,
inHead: true
}
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save