English
theme-helper
Helpers for VuePress theme authors.
The package provides the shared parts of a theme feature that only depends on the pages of a site: reading the pages, normalizing them into a fixed data shape and generating data for the client. The theme keeps its own options, its own item shape and its own rendering.
Currently it provides the generate the sidebar from the file structure and the edit link features, and the page data extension that both of them need.
Usage
npm i @vuepress/theme-helper@nextThe package is used by @vuepress/theme-default and @vuepress/theme-classic. A theme author can depend on it to support the sidebar structure and the edit link features.
Guide
Generating the sidebar from the file structure
The feature has two sides: the node side generates the data from the pages, and the client side resolves the data into the items of the theme. A theme describes its own items with a helper created by createSidebarStructureHelper():
import {
createSidebarStructureHelper,
extendsPageData,
} from '@vuepress/theme-helper'
import type { MyThemeItem } from '../shared/index.js'
const sidebarHelper = createSidebarStructureHelper<MyThemeItem>({
// the theme data, used to find the scopes that use `'structure'`
themeData: resolveThemeData(options),
// how a group item is shaped in the theme options
childrenKey: 'children',
prefixKey: 'prefix',
sorter: options.sidebarSorter,
// customize the item of a page
pageInfoGetter: (info, page, defaults) => ({
...defaults,
// `badge` is a custom frontmatter field of the theme, the helper does not
// know it
...(page?.frontmatter.badge ? { badge: page.frontmatter.badge } : {}),
}),
// customize the item of a directory
dirInfoGetter: (info, _page, defaults) => ({
...defaults,
// the default theme uses `collapsed` instead of `collapsible` / `expanded`
...(info.collapsible ? { collapsed: !info.expanded } : {}),
}),
})
export const myTheme = (options: MyThemeOptions = {}): Theme => ({
name: 'my-theme',
onPrepared: (app) => sidebarHelper.prepare(app),
onWatched: (app, watchers) => {
sidebarHelper.watch(app, watchers)
},
})The helper finds the scopes from the theme data, by looking for the 'structure' value of the sidebar option and for the children: 'structure' group items. You can provide a custom getScopes() when the sidebar option is shaped differently.
The getters receive the normalized SidebarInfo of the item, its page (the README.md page for a directory), and the default item that the helper would generate. The item is built from the normalized fields, see Normalized sidebar information. A getter adds the fields of the theme and can return null to skip the item. The children of a directory are attached by the helper, under childrenKey.
prepare() writes @temp/theme-helper/sidebar.js, which exports the generated data keyed by route scope. It must be called even when there is no scope, so that the generated module exists. watch() watches the generated pages in dev and regenerates the data, and it registers a watcher only when there is at least one scope.
In the client, getSidebarStructure() reads the data of a scope and returns the items customized by the getters:
import { getSidebarStructure } from '@vuepress/theme-helper/client'
import type { MyThemeItem } from '../shared/index.js'
const guideItems = getSidebarStructure<MyThemeItem>('/guide/')The scope is normalized, so '/guide/', '/guide' and 'guide/' all resolve to the same data.
Normalized sidebar information
getSidebarInfo() reads the pages and normalizes every page and directory into the same data shape, so a theme does not need to walk the pages itself:
- a page becomes a
SidebarFileInfowithtext,link,icon,date(normalized to aDate),orderandpageData; - a directory becomes a
SidebarDirInfowith the same fields, pluscollapsible,expanded,childrenand thepageDataof itsREADME.md(ornull).
The default item generated by the helper is built from these fields: it always contains text, contains link and icon when the page or directory has them, and a directory item additionally contains collapsible and expanded. A theme maps the normalized fields to its own item fields in its getters, e.g. the default theme converts collapsible and expanded into its own collapsed field.
Default frontmatter mapping
The built-in info builder reads some frontmatter fields and normalizes them into the internal keys of the same name. They are the default convention of the helper, not a requirement of a theme: a theme can read any other frontmatter in its own getters, and the normalized data does not depend on these fields.
| Field | Where | Normalized as |
|---|---|---|
shortTitle | any page | text, it falls back to the page title |
icon | any page | icon |
order | any page | order, null when it is not set |
date | any page | date, parsed as a Date |
index | any page | the page is skipped when it is false |
dir | README.md | the fields of the group, see below |
The dir options of a directory are read from the frontmatter of its README.md:
---
dir:
text: Guide
icon: guide
collapsible: true
expanded: false
link: true
index: true
order: 1
---text: normalized to thetextof the group, it falls back to the title of theREADME.mdpage.icon: normalized to theiconof the group.collapsible: normalized to thecollapsibleof the group,trueby default.expanded: normalized to theexpandedof the group,falseby default. It only takes effect when the group is collapsible.link: whether theREADME.mdpage is the link of the group instead of a child item,falseby default.index: set it tofalseto hide the whole directory from the sidebar.order: normalized to theorderof the group,nullwhen it is not set.
Sorting the items
getSidebarSorter() converts the sidebarSorter option of the theme into comparator functions. The option accepts a keyword, a function, or an array of them:
export default defineUserConfig({
theme: defaultTheme({
sidebarSorter: ['readme', 'order', 'title', 'filename'],
}),
})The keywords are:
'readme': put theREADME.mdpage of a directory first.'order': sort by the normalizedorder: the positive values ascending, then the items without an order, then the negative values ascending, so-2comes before-1.'date'and'date-desc': sort by the normalizeddate, ascending and descending.'filename': sort by the file name with a natural order, and put a file before a directory of the same name.'title': sort by the item text with a natural order.
A function receives two SidebarInfo items and returns a number, like the callback of Array.prototype.sort(). The default is ['readme', 'order', 'title', 'filename'].
Generating the edit link
The edit link is generated from the repository options of the theme and the relative file path of the page. A theme calls extendsPageData() in the extendsPage hook to save the relative file path and the page title, then uses useEditLink() in the client:
import { extendsPageData } from '@vuepress/theme-helper'
export const myTheme = (): Theme => ({
extendsPage: (page) => {
extendsPageData(page)
},
})import { useEditLink } from '@vuepress/theme-helper/client'
const editLink = useEditLink()The theme options are typed by EditLinkOptions, and the page frontmatter can override editLink and editLinkPattern. The default patterns of the supported repositories are provided by EDIT_LINK_PATTERNS.
Extending the page data
extendsPageData() saves the relative file path of the page into page.data.filePathRelative, and the page title into page.routeMeta.title. Themes use them to generate the edit link and the links of the navbar and the sidebar.
Node API
extendsPageData
pageRequired
PageThe page to extend, usually the argument of the extendsPage hook.
It saves the relative file path into page.data.filePathRelative, and the page title into page.routeMeta.title.
createSidebarStructureHelper
Creates a helper that generates the sidebar data of the theme from the file structure. It is the recommended API, and the low-level functions below build on the same pipeline.
themeDataRequired
objectThe theme data, i.e. the root options and the locales options of the theme.
getScopes
(themeData: object) => string[]A custom function that returns the route scopes to generate, it replaces the scopes detected from the sidebar option.
childrenKey
stringDefault
'children'The key of the field that holds the children of a group item.
prefixKey
stringDefault
'prefix'The key of the field that holds the prefix of a group item.
sorter
SidebarSorterThe sorter option of the theme.
pageInfoGetter
(info: SidebarFileInfo, page: Page | undefined, defaults: Item) => Partial<Item> | nullCustomizes the item of a page. It receives the default item, and can return null to skip the page.
dirInfoGetter
(info: SidebarDirInfo, readmePage: Page | null, defaults: Item) => Partial<Item> | nullCustomizes the item of a directory. It receives the default item, and can return null to skip the directory.
The helper returns:
scopes: the normalized scopes.getData(app): the generatedSidebarStructureData<Item>.prepare(app): writes the generated data to@temp/theme-helper/sidebar.js.watch(app, watchers): watches the generated pages in dev and regenerates the data, with a watcher registered only when there is at least one scope.
getSidebarStructureScopes
themeDataRequired
objectThe theme data, i.e. the root options and the locales options of the theme. The root options are merged with the matching locale options, like the client does.
childrenKeyRequired
stringThe key of the field that holds the children of a group item, e.g. 'items' or 'children'.
prefixKeyRequired
stringThe key of the field that holds the prefix of a group item, e.g. 'base' or 'prefix'.
It returns the normalized scopes, e.g. ['/', '/guide/']. A sidebar option accepts the special value 'structure', and a group item accepts children: 'structure' (or items: 'structure'), scoped by its prefix.
getStructureInfo
pagesRequired
Page[]The pages of the site.
scopeRequired
stringThe route scope as a file path, without a leading slash and with a trailing slash, e.g. 'guide/' or '' for the root.
It returns the directory structure of the scope: StructureDirInfo and StructureFileInfo items, nested and sorted by path.
getSidebarInfo
pagesRequired
Page[]The pages of the site.
sortersRequired
SidebarSorterFunction[]The comparator functions, usually resolved by getSidebarSorter().
scopeRequired
stringThe route scope as a file path, without a leading slash and with a trailing slash.
It converts the structure of the scope to normalized SidebarInfo items: hidden pages are skipped, and the text, link, icon, date, order and the group state of every item are resolved by the default frontmatter mapping.
getSidebarStructureData
scopesRequired
string[]The route scopes, as returned by getSidebarStructureScopes().
sorter
SidebarSorterThe sorter option of the theme.
childrenKey
stringDefault
'children'The key of the field that holds the children of a group item.
pageInfoGetter
SidebarPageInfoGetterThe getter of the items of the pages.
dirInfoGetter
SidebarDirInfoGetterThe getter of the items of the directories.
It returns the generated SidebarStructureData<Item>, keyed by the normalized scope. The default item always contains text, contains link and icon when the page or directory has them, and the one of a directory also contains collapsible and expanded, so the getters of the theme add or override the fields of its own items.
prepareSidebarData
It accepts the same options as getSidebarStructureData(), and writes @temp/theme-helper/sidebar.js with the generated data.
watchSidebarData
It accepts the same options as getSidebarStructureData(), and watches the generated pages of the app in dev. The watcher is added to the watchers argument of the onWatched hook.
Client API
getSidebarStructure
const items = getSidebarStructure<MyThemeItem>('/guide/')It returns the generated items of a scope, typed by the generic parameter, or an empty array when the scope is not generated.
sidebarData
The raw SidebarStructureData read from the generated module, keyed by the normalized scope.
useEditLink
const editLink: ComputedRef<{ text: string; link: string } | null> =
useEditLink()It resolves the edit link of the current page from the theme data and the page frontmatter. It returns null when the edit link is disabled or cannot be resolved.
resolveEditLink
docsRepoRequired
stringThe link or owner/repo of the documentation repository.
docsBranchRequired
stringThe branch of the documentation repository.
docsDirRequired
stringThe directory of the documentation in the repository.
filePathRelativeRequired
string | nullThe relative file path of the page.
editLinkPattern
stringThe custom pattern of the edit link, it overrides the default pattern of the repository.
It returns the edit link, or null when it cannot be resolved. The EDIT_LINK_PATTERNS constant provides the default patterns of the supported repositories.
resolveRepoType
const repoType: RepoType = resolveRepoType('vuepress/ecosystem') // 'GitHub'It resolves the type of a repository: 'GitHub', 'GitLab', 'Gitee', 'Bitbucket' or null.
useData
const { theme, frontmatter, page } = useData<
MyThemeData,
MyFrontmatter,
MyPageData
>()It combines useThemeLocaleData(), usePageFrontmatter() and usePageData() into a single object. The generic parameters type the theme locale data, the page frontmatter and the page data.
Types
The types of the shared conventions are exported from the package root and the shared entry:
EditLinkOptions,EditLinkThemeData,EditLinkFrontmatter,EditLinkPageData: the options, the theme data, the frontmatter and the page data of the edit link. A theme can extend them in its own types.SidebarItemInfo,SidebarFileInfo,SidebarDirInfo,SidebarInfo: the normalized information of a page or a directory.SidebarFrontmatter,SidebarDirOptions: the default frontmatter fields and the directory group options read by the built-ingetSidebarInfo().SidebarStructureData,SidebarStructureItem,SidebarStructureHelper,SidebarStructureHelperOptions,SidebarPageInfoGetter,SidebarDirInfoGetter,SidebarSorter,SidebarSorterFunction,SidebarSorterKeyword: the types of the generated sidebar data.
