Commit aab7b2f903

aab7b2f903aa19f3cbdad38bd33ab89883c8a889

parent: e579b625b2

Unsigned

taskylizard <75871323+taskylizard@users.noreply.github.com> · 2026-06-09 15:07 UTC

completely rework tabs and search fixes

Layout: unified · split

docs/.vitepress/configs/markdown/index.ts +12 −3
@@ -14,13 +14,18 @@ import { imgLazyload } from '@mdit/plugin-img-lazyload'
1414import { imgSize } from '@mdit/plugin-img-size'
1515import MdReg from 'markdown-it-regexp'
1616import type { MarkdownRenderer } from 'vitepress'
17import { tabsMarkdownPlugin } from 'vitepress-plugin-tabs'
17import {
18 getTabAnchor,
19 getTabHeadingAnchor,
20 parseTabLabel
21} from '../../utils/tabAnchors'
1822import { getTooltip } from '../../utils/tooltips'
1923import { headersPlugin } from '../markdown/headers'
2024import { emojiRender } from './emoji'
2125import { nestedContainersPlugin } from './nestedContainers'
2226import { scrapeTablePlugin } from './scrapeTablePlugin'
2327import markdownSteps from './steps'
28import { tabsMarkdownPlugin } from './tabs'
2429
2530export function configureMarkdown(md: MarkdownRenderer) {
2631 md.use(emojiRender)
@@ -142,6 +147,7 @@ function injectSearchHeadings(src: string) {
142147 const containerStack: string[] = []
143148 const headingStack: (SearchHeading | undefined)[] = []
144149 const tabResetStack: (SearchHeading | undefined)[] = []
150 const tabAnchorCounts = new Map<string, number>()
145151 const getCurrentHeading = () => {
146152 for (let i = headingStack.length - 1; i >= 0; i--) {
147153 if (headingStack[i]) return headingStack[i]
@@ -200,14 +206,17 @@ function injectSearchHeadings(src: string) {
200206 const tabMatch = lines[i].match(/^(\s*)==\s+(.+)$/)
201207 if (tabMatch && containerStack.includes('tabs')) {
202208 const [, indent, title] = tabMatch
203 const headingTitle = title.trim()
209 const parsed = parseTabLabel(title)
210 const headingTitle = parsed.label
204211 if (!headingTitle) continue
212 const anchor = getTabAnchor(title, tabAnchorCounts)
213 const headingAnchor = getTabHeadingAnchor(anchor)
205214
206215 lines.splice(
207216 i + 1,
208217 0,
209218 '',
210 `${indent}### ${headingTitle} {.tab-search-heading .ignore-header}`,
219 `${indent}### ${headingTitle} {#${headingAnchor} .tab-search-heading .ignore-header}`,
211220 ''
212221 )
213222 i += 3
docs/.vitepress/configs/markdown/tabs.ts added +216
@@ -0,0 +1,216 @@
1import type { MarkdownRenderer } from 'vitepress'
2import { getUniqueAnchor, parseTabLabel } from '../../utils/tabAnchors'
3
4function containerPlugin(md: MarkdownRenderer, name: string, options: any) {
5 function validateDefault(params: string) {
6 return params.trim().split(' ', 2)[0] === name
7 }
8
9 function renderDefault(
10 tokens: any[],
11 idx: number,
12 opts: any,
13 env: any,
14 slf: any
15 ) {
16 if (tokens[idx].nesting === 1) tokens[idx].attrJoin('class', name)
17 return slf.renderToken(tokens, idx, opts, env, slf)
18 }
19
20 const minMarkers = 3
21 const markerStr = options.marker || ':'
22 const markerChar = markerStr.charCodeAt(0)
23 const markerLen = markerStr.length
24 const validate = options.validate || validateDefault
25 const render = options.render || renderDefault
26
27 function container(
28 state: any,
29 startLine: number,
30 endLine: number,
31 silent: boolean
32 ) {
33 let pos
34 let autoClosed = false
35 let start = state.bMarks[startLine] + state.tShift[startLine]
36 let max = state.eMarks[startLine]
37
38 if (markerChar !== state.src.charCodeAt(start)) return false
39
40 for (pos = start + 1; pos <= max; pos++) {
41 if (markerStr[(pos - start) % markerLen] !== state.src[pos]) break
42 }
43
44 const markerCount = Math.floor((pos - start) / markerLen)
45 if (markerCount < minMarkers) return false
46
47 pos -= (pos - start) % markerLen
48 const markup = state.src.slice(start, pos)
49 const params = state.src.slice(pos, max)
50
51 if (!validate(params, markup)) return false
52 if (silent) return true
53
54 let nextLine = startLine
55 for (;;) {
56 nextLine++
57 if (nextLine >= endLine) break
58
59 start = state.bMarks[nextLine] + state.tShift[nextLine]
60 max = state.eMarks[nextLine]
61
62 if (start < max && state.sCount[nextLine] < state.blkIndent) break
63 if (markerChar !== state.src.charCodeAt(start)) continue
64 if (state.sCount[nextLine] - state.blkIndent >= 4) continue
65
66 for (pos = start + 1; pos <= max; pos++) {
67 if (markerStr[(pos - start) % markerLen] !== state.src[pos]) break
68 }
69 if (Math.floor((pos - start) / markerLen) < markerCount) continue
70
71 pos -= (pos - start) % markerLen
72 pos = state.skipSpaces(pos)
73 if (pos < max) continue
74
75 autoClosed = true
76 break
77 }
78
79 const oldParent = state.parentType
80 const oldLineMax = state.lineMax
81
82 state.parentType = 'container'
83 state.lineMax = nextLine
84
85 const tokenOpen = state.push(`container_${name}_open`, 'div', 1)
86 tokenOpen.markup = markup
87 tokenOpen.block = true
88 tokenOpen.info = params
89 tokenOpen.map = [startLine, nextLine]
90
91 state.md.block.tokenize(state, startLine + 1, nextLine)
92
93 const tokenClose = state.push(`container_${name}_close`, 'div', -1)
94 tokenClose.markup = state.src.slice(start, pos)
95 tokenClose.block = true
96
97 state.parentType = oldParent
98 state.lineMax = oldLineMax
99 state.line = nextLine + (autoClosed ? 1 : 0)
100
101 return true
102 }
103
104 md.block.ruler.before('fence', `container_${name}`, container, {
105 alt: ['paragraph', 'reference', 'blockquote', 'list']
106 })
107 md.renderer.rules[`container_${name}_open`] = render
108 md.renderer.rules[`container_${name}_close`] = render
109}
110
111const tabMarkerCode = '='.charCodeAt(0)
112const minTabMarkerLen = 2
113
114const ruleBlockTab = (
115 state: any,
116 startLine: number,
117 endLine: number,
118 silent: boolean
119) => {
120 let pos = state.bMarks[startLine] + state.tShift[startLine]
121 const max = state.eMarks[startLine]
122
123 if (state.parentType !== 'container') return false
124 if (pos + minTabMarkerLen > max) return false
125
126 const marker = state.src.charCodeAt(pos)
127 if (marker !== tabMarkerCode) return false
128
129 const mem = pos
130 pos = state.skipChars(pos + 1, marker)
131 const tabMarkerLen = pos - mem
132 if (tabMarkerLen < minTabMarkerLen - 1) return false
133 if (silent) return true
134
135 let nextLine = startLine
136 let endStart = mem
137 let endPos = pos
138
139 for (;;) {
140 nextLine++
141 if (nextLine >= endLine) break
142
143 endStart = state.bMarks[nextLine] + state.tShift[nextLine]
144 const lineMax = state.eMarks[nextLine]
145
146 if (endStart < lineMax && state.sCount[nextLine] < state.blkIndent) break
147 if (state.src.charCodeAt(endStart) !== tabMarkerCode) continue
148
149 const p = state.skipChars(endStart + 1, marker)
150 if (p - endStart !== tabMarkerLen) continue
151
152 endPos = p
153 break
154 }
155
156 const oldParent = state.parentType
157 const oldLineMax = state.lineMax
158
159 state.parentType = 'tab'
160 state.lineMax = nextLine
161
162 const startToken = state.push('tab_open', 'div', 1)
163 startToken.markup = state.src.slice(mem, pos)
164 startToken.block = true
165 startToken.info = state.src.slice(pos, max).trimStart()
166 startToken.map = [startLine, nextLine - 1]
167
168 state.md.block.tokenize(state, startLine + 1, nextLine)
169
170 const endToken = state.push('tab_close', 'div', -1)
171 endToken.markup = state.src.slice(endStart, endPos)
172 endToken.block = true
173
174 state.parentType = oldParent
175 state.lineMax = oldLineMax
176 state.line = nextLine
177
178 return true
179}
180
181function parseTabsParams(input: string) {
182 return { shareStateKey: input.match(/key:(\S+)/)?.[1] }
183}
184
185function getTabAnchorCounts(env: any) {
186 env.__tabAnchorCounts ??= new Map<string, number>()
187 return env.__tabAnchorCounts as Map<string, number>
188}
189
190export function tabsMarkdownPlugin(md: MarkdownRenderer) {
191 containerPlugin(md, 'tabs', {
192 render(tokens: any[], index: number) {
193 const token = tokens[index]
194 if (token.nesting !== 1) return '</PluginTabs>\n'
195
196 const params = parseTabsParams(token.info)
197 const sharedState = params.shareStateKey
198 ? ` sharedStateKey="${md.utils.escapeHtml(params.shareStateKey)}"`
199 : ''
200 return `<PluginTabs${sharedState}>\n`
201 }
202 })
203
204 md.block.ruler.after('container_tabs', 'tab', ruleBlockTab)
205
206 md.renderer.rules.tab_open = (tokens, index, _options, env) => {
207 const parsed = parseTabLabel(tokens[index].info)
208 const anchor = parsed.anchor ||
209 getUniqueAnchor(parsed.label, getTabAnchorCounts(env))
210
211 return `<PluginTabsTab label="${
212 md.utils.escapeHtml(parsed.label)
213 }" anchor="${md.utils.escapeHtml(anchor)}">\n`
214 }
215 md.renderer.rules.tab_close = () => '</PluginTabsTab>\n'
216}
docs/.vitepress/plugins/urlSearchPlugin.ts +159 −80
@@ -1,6 +1,13 @@
11import { writeFileSync } from 'node:fs'
22import { join } from 'node:path'
33import { renderEmojiShortcodes } from '../configs/markdown/emoji'
4import {
5 getTabAnchor,
6 getTabHeadingAnchor,
7 parseTabLabel,
8 slugifyAnchor,
9 stripHeadingMarkup
10} from '../utils/tabAnchors'
411
512export interface PageLink {
613 href: string
@@ -8,82 +15,142 @@ export interface PageLink {
815 pageId: string
916 anchor: string
1017 titles: string[]
18 tabs?: string[]
1119}
1220
13function extractLinksFromMarkdown(src: string, pageId: string): PageLink[] {
14 const results: PageLink[] = []
15 const seen = new Set<string>()
21export interface TabTarget {
22 pageId: string
23 anchor: string
24 tabs: string[]
25}
26
27interface PageSearchMetadata {
28 links: PageLink[]
29 tabTargets: TabTarget[]
30}
31
32function extractSearchMetadataFromMarkdown(
33 src: string,
34 pageId: string
35): PageSearchMetadata {
36 const links: PageLink[] = []
37 const seenLinks = new Set<string>()
38 const tabTargets = new Map<string, TabTarget>()
1639 const headingStack: string[] = []
1740 const slugCounts = new Map<string, number>()
41 const tabAnchorCounts = new Map<string, number>()
1842 const containerStack: string[] = []
43 const tabPath: string[] = []
44 const tabResetStack: {
45 anchor: string
46 headings: string[]
47 }[] = []
1948 const collapsibleStack: {
2049 anchor: string
2150 headings: string[]
2251 }[] = []
2352 let currentAnchor = ''
2453
25 // Strip frontmatter
2654 const body = src.startsWith('---')
2755 ? src.replace(/^---[\s\S]*?---\n?/, '')
2856 : src
2957 const lines = body.split('\n')
3058
31 const rControl = /[\u0000-\u001f]/g
32 const rSpecial = /[\s~`!@#$%^&*()\-_+=[\]{}|\\;:"'“”‘’<>,.?/]+/g
33 const rCombining = /[\u0300-\u036F]/g
34
35 const stripHeadingMarkup = (value: string) =>
36 value
37 .replace(/\{[^}]*\}\s*$/, '')
38 .replace(/<[^>]*>/g, '')
39 .replace(/`([^`]+)`/g, '$1')
40 .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
41 .replace(/[*_~]/g, '')
42 .trim()
43
44 const slugify = (value: string) =>
45 stripHeadingMarkup(value)
46 .normalize('NFKD')
47 .replace(rCombining, '')
48 .replace(rControl, '')
49 .replace(rSpecial, '-')
50 .replace(/-{2,}/g, '-')
51 .replace(/^-+|-+$/g, '')
52 .replace(/^(\d)/, '_$1')
53 .toLowerCase()
54
5559 const getAnchor = (text: string) => {
56 const slug = slugify(text)
60 const slug = slugifyAnchor(text)
5761 const count = slugCounts.get(slug) ?? 0
5862 slugCounts.set(slug, count + 1)
5963 return count === 0 ? slug : `${slug}-${count}`
6064 }
6165
62 const setHeading = (level: number, text: string) => {
63 headingStack[level] = text
66 const getCurrentTabPath = () => tabPath.filter(Boolean)
67
68 const recordTabTarget = (anchor: string) => {
69 const tabs = getCurrentTabPath()
70 if (!anchor || !tabs.length) return
71 tabTargets.set(anchor, { pageId, anchor, tabs })
72 }
73
74 const setHeading = (level: number, text: string, anchor?: string) => {
75 const title = stripHeadingMarkup(text)
76 if (!title) return
77
78 headingStack[level] = title
6479 headingStack.length = level + 1
65 currentAnchor = getAnchor(text)
80 currentAnchor = anchor || getAnchor(title)
81 recordTabTarget(currentAnchor)
6682 }
6783
6884 const getTitles = () => headingStack.filter(Boolean)
6985
86 const restoreHeadingState = (state: {
87 anchor: string
88 headings: string[]
89 }) => {
90 currentAnchor = state.anchor
91 headingStack.length = 0
92 headingStack.push(...state.headings)
93 }
94
95 const getTabsDepth = () =>
96 containerStack.filter((name) => name === 'tabs').length
97
98 const pushLink = (href: string, linkText: string) => {
99 const tabs = getCurrentTabPath()
100 const key = [
101 href,
102 currentAnchor,
103 tabs.join('/')
104 ].join('\x00')
105 if (seenLinks.has(key)) return
106
107 seenLinks.add(key)
108 links.push({
109 href,
110 linkText,
111 pageId,
112 anchor: currentAnchor,
113 titles: getTitles(),
114 ...(tabs.length ? { tabs } : {})
115 })
116 }
117
70118 for (let i = 0; i < lines.length; i++) {
71119 const line = lines[i]
72120
73121 const containerOpenMatch = line.match(/^\s*:{3,}\s*([A-Za-z][\w-]*)\b/)
74122 if (containerOpenMatch) {
75 containerStack.push(containerOpenMatch[1].toLowerCase())
123 const containerName = containerOpenMatch[1].toLowerCase()
124 containerStack.push(containerName)
125 if (containerName === 'tabs') {
126 tabResetStack.push({
127 anchor: currentAnchor,
128 headings: [...headingStack]
129 })
130 }
76131 } else if (/^\s*:{3,}\s*$/.test(line)) {
77 containerStack.pop()
132 const closed = containerStack.pop()
133 if (closed === 'tabs') {
134 tabPath.length = getTabsDepth()
135 const resetState = tabResetStack.pop()
136 if (resetState) restoreHeadingState(resetState)
137 }
78138 }
79139
80140 const tabMatch = line.match(/^\s*==\s+(.+)$/)
81141 if (tabMatch && containerStack.includes('tabs')) {
82 const title = tabMatch[1].trim()
83 if (title) {
142 const rawTitle = tabMatch[1]
143 const parsed = parseTabLabel(rawTitle)
144 if (parsed.label) {
145 const depth = getTabsDepth()
146 const anchor = getTabAnchor(rawTitle, tabAnchorCounts)
147 const headingAnchor = getTabHeadingAnchor(anchor)
148 tabPath[depth - 1] = anchor
149 tabPath.length = depth
150
84151 // The markdown renderer injects a hidden H3 for each tab label.
85 // Mirror that heading so URL search deep-links to the selected tab.
86 setHeading(2, title)
152 // Mirror that heading so search can deep-link to the selected tab.
153 setHeading(2, parsed.label, headingAnchor)
87154 }
88155 continue
89156 }
@@ -116,62 +183,34 @@ function extractLinksFromMarkdown(src: string, pageId: string): PageLink[] {
116183
117184 if (/^\s*<\/Collapsible>\s*$/i.test(line)) {
118185 const previous = collapsibleStack.pop()
119 if (previous) {
120 currentAnchor = previous.anchor
121 headingStack.length = 0
122 headingStack.push(...previous.headings)
123 }
186 if (previous) restoreHeadingState(previous)
124187 continue
125188 }
126189
127 // Heading: ## Title or === Title (setext-style ignored, ATX only)
128190 const headingMatch = line.match(/^(#{1,6})\s+(.+)/)
129191 if (headingMatch) {
130192 const level = headingMatch[1].length - 1
131 const text = headingMatch[2].trim()
132 setHeading(level, text)
193 setHeading(level, headingMatch[2].trim())
133194 continue
134195 }
135196
136 // Markdown links: [text](https://...)
137197 const linkRE = /\[([^\]]*)\]\((https?:\/\/[^)]+)\)/g
138198 let m: RegExpExecArray | null
139199 while ((m = linkRE.exec(line)) !== null) {
140 const linkText = renderEmojiShortcodes(m[1].trim())
141 const href = m[2].trim()
142 const key = href + '\x00' + currentAnchor
143 if (seen.has(key)) continue
144 seen.add(key)
145 results.push({
146 href,
147 linkText,
148 pageId,
149 anchor: currentAnchor,
150 titles: getTitles()
151 })
200 pushLink(m[2].trim(), renderEmojiShortcodes(m[1].trim()))
152201 }
153202
154 // Bare angle-bracket URLs: <https://...>
155203 const bareRE = /<(https?:\/\/[^>]+)>/g
156204 while ((m = bareRE.exec(line)) !== null) {
157205 const href = m[1].trim()
158 const key = href + '\x00' + currentAnchor
159 if (seen.has(key)) continue
160 seen.add(key)
161 results.push({
162 href,
163 linkText: href,
164 pageId,
165 anchor: currentAnchor,
166 titles: getTitles()
167 })
206 pushLink(href, href)
168207 }
169208 }
170209
171 return results
210 return { links, tabTargets: [...tabTargets.values()] }
172211}
173212
174const collectedByPage = new Map<string, PageLink[]>()
213const collectedByPage = new Map<string, PageSearchMetadata>()
175214
176215function getPageId(page: string) {
177216 return '/' + page.replace(/\.md$/, '').replace(/\/index$/, '/')
@@ -181,9 +220,14 @@ function getDedupedLinks() {
181220 const seen = new Set<string>()
182221 const deduped: PageLink[] = []
183222
184 for (const links of collectedByPage.values()) {
185 for (const link of links) {
186 const key = link.href + '\x00' + link.pageId + '\x00' + link.anchor
223 for (const metadata of collectedByPage.values()) {
224 for (const link of metadata.links) {
225 const key = [
226 link.href,
227 link.pageId,
228 link.anchor,
229 link.tabs?.join('/') ?? ''
230 ].join('\x00')
187231 if (seen.has(key)) continue
188232 seen.add(key)
189233 deduped.push(link)
@@ -193,16 +237,43 @@ function getDedupedLinks() {
193237 return deduped
194238}
195239
240function getDedupedTabTargets() {
241 const seen = new Set<string>()
242 const deduped: TabTarget[] = []
243
244 for (const metadata of collectedByPage.values()) {
245 for (const target of metadata.tabTargets) {
246 const key = [
247 target.pageId,
248 target.anchor,
249 target.tabs.join('/')
250 ].join('\x00')
251 if (seen.has(key)) continue
252 seen.add(key)
253 deduped.push(target)
254 }
255 }
256
257 return deduped
258}
259
196260export function collectPageLinks(src: string, page: string) {
197261 const pageId = getPageId(page)
198 collectedByPage.set(pageId, extractLinksFromMarkdown(src, pageId))
262 collectedByPage.set(pageId, extractSearchMetadataFromMarkdown(src, pageId))
199263}
200264
201265export function writeUrlSearchIndex(outDir: string) {
202 const deduped = getDedupedLinks()
203 const outPath = join(outDir, 'url-search-index.json')
204 writeFileSync(outPath, JSON.stringify(deduped), 'utf-8')
205 console.log(`[url-search] wrote ${deduped.length} links → ${outPath}`)
266 const links = getDedupedLinks()
267 const linksPath = join(outDir, 'url-search-index.json')
268 writeFileSync(linksPath, JSON.stringify(links), 'utf-8')
269 console.log(`[url-search] wrote ${links.length} links -> ${linksPath}`)
270
271 const tabTargets = getDedupedTabTargets()
272 const tabTargetsPath = join(outDir, 'tab-search-index.json')
273 writeFileSync(tabTargetsPath, JSON.stringify(tabTargets), 'utf-8')
274 console.log(
275 `[url-search] wrote ${tabTargets.length} tab targets -> ${tabTargetsPath}`
276 )
206277}
207278
208279export function urlSearchDevPlugin() {
@@ -217,6 +288,14 @@ export function urlSearchDevPlugin() {
217288 res.end(JSON.stringify(deduped))
218289 }
219290 )
291 server.middlewares.use(
292 '/tab-search-index.json',
293 (_req: any, res: any) => {
294 const deduped = getDedupedTabTargets()
295 res.setHeader('Content-Type', 'application/json')
296 res.end(JSON.stringify(deduped))
297 }
298 )
220299 }
221300 }
222301}
docs/.vitepress/theme/Layout.vue +146 −128
@@ -66,7 +66,6 @@ if (!import.meta.env.SSR) {
6666 typeof event.detail?.query === 'string'
6767 ? event.detail.query
6868 : ''
69 tryOpenCollapsibles()
7069 })
7170}
7271
@@ -103,166 +102,160 @@ const getScrollTargetForAnchor = (target: HTMLElement) => {
103102 return target
104103}
105104
106const getHeadingAnchor = (heading: HTMLElement) => {
107 const href = heading.querySelector<HTMLAnchorElement>('a[href^="#"]')
108 ?.getAttribute('href')
105const TAB_QUERY_PARAM = 'tabs'
109106
110 if (href?.startsWith('#') && href.length > 1) return href.slice(1)
107const getRequestedTabPath = () => {
108 const value = new URLSearchParams(window.location.search).get(
109 TAB_QUERY_PARAM
110 )
111 return value
112 ?.split(',')
113 .map((tab) => tab.trim())
114 .filter(Boolean) ?? []
115}
111116
112 return heading.id || undefined
117const buildUrlWithTabs = (tabs: string[], hash = '') => {
118 const params = new URLSearchParams(window.location.search)
119 params.delete(TAB_QUERY_PARAM)
120
121 const queryParts = [
122 params.toString(),
123 tabs.length
124 ? `${TAB_QUERY_PARAM}=${
125 tabs.map((tab) => encodeURIComponent(tab)).join(',')
126 }`
127 : ''
128 ].filter(Boolean)
129
130 return `${window.location.pathname}${
131 queryParts.length ? `?${queryParts.join('&')}` : ''
132 }${hash ? `#${encodeURIComponent(hash)}` : ''}`
113133}
114134
115const getSelectedTabHeadingAnchor = (tabs: HTMLElement) => {
116 const selectedTab = tabs.querySelector<HTMLButtonElement>(
117 '.plugin-tabs--tab[aria-selected="true"]'
118 )
119 const panelId = selectedTab?.getAttribute('aria-controls')
120 const panel = panelId
121 ? document.getElementById(panelId)
122 : tabs.querySelector<HTMLElement>('.plugin-tabs--content')
123 const heading = panel?.querySelector<HTMLElement>('.tab-search-heading')
135const getSelectedTabAnchor = (tabs: HTMLElement) =>
136 tabs.querySelector<HTMLButtonElement>(
137 '.plugin-tabs--tab[aria-selected="true"][data-tab-anchor]'
138 )?.dataset.tabAnchor
139
140const getPanelForTabButton = (button: HTMLButtonElement) => {
141 const panelId = button.getAttribute('aria-controls')
142 return panelId ? document.getElementById(panelId) : undefined
143}
144
145const getTabPathForGroup = (tabs: HTMLElement) => {
146 const groups: HTMLElement[] = []
147 let currentTabs: HTMLElement | null = tabs
148
149 while (currentTabs) {
150 groups.unshift(currentTabs)
151 const parentPanel = currentTabs.parentElement?.closest<HTMLElement>(
152 '.plugin-tabs--content[data-tab-anchor]'
153 )
154 currentTabs = parentPanel?.closest<HTMLElement>('.plugin-tabs') ?? null
155 }
124156
125 return heading ? getHeadingAnchor(heading) : undefined
157 return groups
158 .map((group) => getSelectedTabAnchor(group))
159 .filter((tab): tab is string => Boolean(tab))
126160}
127161
128const updateHashForSelectedTab = async (tabs: HTMLElement) => {
162const updateQueryForSelectedTab = async (tabs: HTMLElement) => {
129163 await nextTick()
130164 await nextFrame()
131165
132 const anchor = getSelectedTabHeadingAnchor(tabs)
133 if (!anchor || window.location.hash.slice(1) === anchor) return
166 const tabPath = getTabPathForGroup(tabs)
167 if (!tabPath.length) return
134168
135 window.history.pushState(
136 null,
137 '',
138 `${window.location.pathname}${window.location.search}#${anchor}`
139 )
169 const nextUrl = buildUrlWithTabs(tabPath)
170 const currentUrl =
171 `${window.location.pathname}${window.location.search}${window.location.hash}`
172 if (nextUrl === currentUrl) return
173
174 window.history.pushState(null, '', nextUrl)
140175}
141176
142const queueHashUpdateForTabSelection = (target: EventTarget | null) => {
177const queueTabQueryUpdateForSelection = (target: EventTarget | null) => {
143178 if (!(target instanceof HTMLElement)) return
144179
145180 const button = target.closest<HTMLButtonElement>(
146181 '.plugin-tabs--tab[role="tab"]'
147182 )
148183 const tabs = button?.closest<HTMLElement>('.plugin-tabs')
149 if (tabs) void updateHashForSelectedTab(tabs)
150}
151
152const scrollToElement = (target: HTMLElement, smooth = true) => {
153 requestAnimationFrame(() => {
154 requestAnimationFrame(() => {
155 const navBar = document.querySelector<HTMLElement>('.VPNavBar')
156 const navOffset = navBar ? navBar.offsetHeight : 0
157 window.scrollTo({
158 top: target.getBoundingClientRect().top + window.scrollY - navOffset,
159 behavior: smooth &&
160 !window.matchMedia('(prefers-reduced-motion: reduce)').matches
161 ? 'smooth'
162 : 'auto'
163 })
164 target.setAttribute('tabindex', '-1')
165 target.focus({ preventScroll: true })
166 })
167 })
184 if (tabs) void updateQueryForSelectedTab(tabs)
168185}
169186
170const selectTabContainingAnchor = async (hash: string) => {
171 const tabsList = document.querySelectorAll<HTMLElement>('.plugin-tabs')
187const selectTabsByPath = async (tabPath: string[]) => {
188 let root: ParentNode = document
189 let selectedTabs: HTMLElement | undefined
172190
173 for (let i = 0, len = tabsList.length; i < len; i++) {
174 const tabs = tabsList[i]
175 const selectedTab = tabs.querySelector<HTMLButtonElement>(
176 '.plugin-tabs--tab[aria-selected="true"]'
177 )
178 const buttons = tabs.querySelectorAll<HTMLButtonElement>(
179 '.plugin-tabs--tab[role="tab"]'
191 for (const anchor of tabPath) {
192 const button = root.querySelector<HTMLButtonElement>(
193 `.plugin-tabs--tab[role="tab"][data-tab-anchor="${CSS.escape(anchor)}"]`
180194 )
195 if (!button) return selectedTabs
196
197 const tabs = button.closest<HTMLElement>('.plugin-tabs')
198 if (!tabs) return selectedTabs
181199
182 for (let j = 0, buttonsLen = buttons.length; j < buttonsLen; j++) {
183 buttons[j].click()
200 selectedTabs = tabs
201 if (button.getAttribute('aria-selected') !== 'true') {
202 button.click()
184203 await nextTick()
185204 await nextFrame()
186
187 const target = getTargetByHash(hash)
188 if (target) return target
189205 }
190206
191 selectedTab?.click()
192 await nextTick()
207 root = getPanelForTabButton(button) ?? tabs
193208 }
194}
195
196const getTabsInSearchScope = (target: HTMLElement) => {
197 const tabs = new Set<HTMLElement>()
198 const closestTabs = target.closest<HTMLElement>('.plugin-tabs')
199 if (closestTabs) tabs.add(closestTabs)
200209
201 const tagName = target.tagName
202 if (tagName.length === 2 && tagName[0] === 'H') {
203 const level = +tagName[1]
204 if (level >= 1 && level <= 6) {
205 let sibling = target.nextElementSibling
206
207 while (sibling) {
208 const siblingTag = sibling.tagName
209 if (
210 siblingTag.length === 2 && siblingTag[0] === 'H' &&
211 +siblingTag[1] <= level
212 ) break
210 return selectedTabs
211}
213212
214 if (sibling.matches('.plugin-tabs')) tabs.add(sibling as HTMLElement)
215 sibling.querySelectorAll<HTMLElement>('.plugin-tabs').forEach((tab) => {
216 tabs.add(tab)
217 })
213const selectLegacyTabHash = async (hash: string) => {
214 const button = document.querySelector<HTMLButtonElement>(
215 `.plugin-tabs--tab[role="tab"][data-tab-anchor="${CSS.escape(hash)}"]`
216 )
217 if (!button) return
218218
219 sibling = sibling.nextElementSibling
220 }
221 }
219 if (button.getAttribute('aria-selected') !== 'true') {
220 button.click()
221 await nextTick()
222 await nextFrame()
222223 }
223224
224 return [...tabs]
225 const tabs = button.closest<HTMLElement>('.plugin-tabs')
226 if (tabs) {
227 window.history.replaceState(null, '', buildUrlWithTabs([hash]))
228 }
229 return tabs
225230}
226231
227const selectTabContainingQuery = async (target: HTMLElement, query: string) => {
228 const terms = getSearchTerms(query)
229 if (!terms.length) return
230
231 for (const tabs of getTabsInSearchScope(target)) {
232 const selectedTab = tabs.querySelector<HTMLButtonElement>(
233 '.plugin-tabs--tab[aria-selected="true"]'
234 )
235 const buttons = tabs.querySelectorAll<HTMLButtonElement>(
236 '.plugin-tabs--tab[role="tab"]'
237 )
238
239 for (let i = 0, len = buttons.length; i < len; i++) {
240 const button = buttons[i]
241 button.click()
242 await nextTick()
243 await nextFrame()
244
245 const panelId = button.getAttribute('aria-controls')
246 const panel = panelId
247 ? document.getElementById(panelId)
248 : tabs.querySelector<HTMLElement>('.plugin-tabs--content')
249 const text = panel?.textContent?.toLowerCase() ?? ''
250
251 if (terms.every((term) => text.includes(term))) return
252 }
232const getSelectedTabScrollTarget = (tabs: HTMLElement) => {
233 const selectedTab = tabs.querySelector<HTMLButtonElement>(
234 '.plugin-tabs--tab[aria-selected="true"]'
235 )
236 return selectedTab ? getPanelForTabButton(selectedTab) ?? tabs : tabs
237}
253238
254 selectedTab?.click()
255 await nextTick()
256 }
239const scrollToElement = (target: HTMLElement, smooth = true) => {
240 requestAnimationFrame(() => {
241 requestAnimationFrame(() => {
242 const navBar = document.querySelector<HTMLElement>('.VPNavBar')
243 const navOffset = navBar ? navBar.offsetHeight : 0
244 window.scrollTo({
245 top: target.getBoundingClientRect().top + window.scrollY - navOffset,
246 behavior: smooth &&
247 !window.matchMedia('(prefers-reduced-motion: reduce)').matches
248 ? 'smooth'
249 : 'auto'
250 })
251 target.setAttribute('tabindex', '-1')
252 target.focus({ preventScroll: true })
253 })
254 })
257255}
258256
259257const openCollapsibles = async (target: HTMLElement) => {
260 await selectTabContainingQuery(target, searchQuery)
261 await nextTick()
262 await nextFrame()
263
264 const hashTarget = getTargetByHash(window.location.hash.slice(1))
265 const activeTarget = hashTarget ?? target
258 const activeTarget = target
266259 let scrollTarget = getScrollTargetForAnchor(activeTarget)
267260 let el: HTMLElement | null = activeTarget
268261
@@ -329,18 +322,29 @@ const tryOpenAnchoredContent = async () => {
329322 await nextTick()
330323 await nextFrame()
331324
325 const requestedTabs = getRequestedTabPath()
326 const selectedTabs = requestedTabs.length
327 ? await selectTabsByPath(requestedTabs)
328 : undefined
332329 const hash = window.location.hash.slice(1)
330
333331 if (!hash) {
334332 resetSearchNavigation()
333 if (selectedTabs) {
334 scrollToElement(getSelectedTabScrollTarget(selectedTabs), false)
335 }
335336 return
336337 }
337338
338339 let target = getTargetByHash(hash)
339 let selectedTabForHash = false
340340
341 if (!target) {
342 target = await selectTabContainingAnchor(hash)
343 selectedTabForHash = Boolean(target)
341 if (!target && !requestedTabs.length) {
342 const legacyTabs = await selectLegacyTabHash(hash)
343 if (legacyTabs) {
344 resetSearchNavigation()
345 scrollToElement(getSelectedTabScrollTarget(legacyTabs), false)
346 return
347 }
344348 }
345349
346350 if (!target) {
@@ -355,7 +359,20 @@ const tryOpenAnchoredContent = async () => {
355359 }
356360
357361 if (
358 selectedTabForHash ||
362 !requestedTabs.length && target.classList.contains('tab-search-heading')
363 ) {
364 const tabs = target.closest<HTMLElement>('.plugin-tabs')
365 if (tabs) {
366 window.history.replaceState(
367 null,
368 '',
369 buildUrlWithTabs(getTabPathForGroup(tabs))
370 )
371 }
372 }
373
374 if (
375 selectedTabs ||
359376 target.classList.contains('tab-search-heading')
360377 ) {
361378 scrollToElement(getScrollTargetForAnchor(target), false)
@@ -364,6 +381,7 @@ const tryOpenAnchoredContent = async () => {
364381
365382onMounted(tryOpenAnchoredContent)
366383watch(() => route.data, tryOpenAnchoredContent, { flush: 'post' })
384watch(() => route.query, tryOpenAnchoredContent, { flush: 'post' })
367385watch(() => route.hash, tryOpenAnchoredContent, { flush: 'post' })
368386
369387function onSidebarEnter() {
@@ -559,7 +577,7 @@ onMounted(() => {
559577
560578 useEventListener(document, 'click', (e: MouseEvent) => {
561579 if (!e.isTrusted) return
562 queueHashUpdateForTabSelection(e.target)
580 queueTabQueryUpdateForSelection(e.target)
563581 })
564582
565583 useEventListener(document, 'keydown', (e: KeyboardEvent) => {
@@ -567,7 +585,7 @@ onMounted(() => {
567585 return
568586 }
569587
570 queueHashUpdateForTabSelection(e.target)
588 queueTabQueryUpdateForSelection(e.target)
571589 })
572590
573591 onUnmounted(() => {
docs/.vitepress/theme/components/Search.vue +28 −56
@@ -48,13 +48,13 @@ import {
4848 TextAlignStart
4949} from 'lucide-vue-next'
5050import Mark from 'mark.js/dist/mark.es6.js'
51import { enhanceAppWithTabs } from 'vitepress-plugin-tabs/client'
5251import { sidebar } from '../../configs/constants'
5352import type { PageLink } from '../../plugins/urlSearchPlugin'
5453import { LRUCache } from '../composables/search/lru-cache'
5554import { createSearchTranslate } from '../composables/search/translation'
5655import { useData } from '../composables/search/use-data'
5756import { LowEndDeviceModeStorageKey } from '../constants'
57import { enhanceAppWithTabs } from './tabs'
5858
5959export interface FooterTranslations {
6060 selectText?: string
@@ -81,6 +81,7 @@ const resultsEl = shallowRef<HTMLElement>()
8181
8282/* Search */
8383interface Result {
84 tabs?: string[]
8485 title: string
8586 titles: string[]
8687 text?: string
@@ -280,6 +281,7 @@ const urlMatches = shallowRef<PageLink[]>([])
280281const urlPageGroupCounts = shallowRef<PageGroupCount[]>([])
281282
282283interface UrlResult {
284 tabs?: string[]
283285 href: string
284286 linkText: string
285287 pageId: string
@@ -340,6 +342,7 @@ const filteredUrlResults = computed((): UrlResult[] => {
340342 pageId: link.pageId,
341343 anchor: link.anchor,
342344 titles: link.titles,
345 tabs: link.tabs,
343346 highlighted: highlightUrl(link.href, query)
344347 })
345348 }
@@ -969,7 +972,7 @@ function buildDocExcerpt(
969972 const map = new Map<string, string>()
970973 const app = createApp(comp)
971974 app.config.warnHandler = () => {}
972 enhanceAppWithTabs(app)
975 enhanceAppWithTabs(app, { renderAll: true })
973976 app.provide(dataSymbol, vitePressData)
974977 Object.defineProperties(app.config.globalProperties, {
975978 $frontmatter: {
@@ -986,7 +989,6 @@ function buildDocExcerpt(
986989 const div = document.createElement('div')
987990 try {
988991 app.mount(div)
989 await selectExcerptTabs(div, filterTextValue)
990992 const headings = div.querySelectorAll('h1, h2, h3, h4, h5, h6')
991993 headings.forEach((heading) => {
992994 const href = heading.querySelector('a')?.getAttribute('href')
@@ -1298,13 +1300,6 @@ async function fetchExcerpt(id: string) {
12981300const nextFrame = () =>
12991301 new Promise<void>((resolve) => requestAnimationFrame(() => resolve()))
13001302
1301const getSearchTerms = (query: string) =>
1302 query
1303 .toLowerCase()
1304 .split(/\s+/)
1305 .map((term) => term.trim())
1306 .filter(Boolean)
1307
13081303function hasExcerptPreview(html?: string) {
13091304 if (!html) return false
13101305 return Boolean(
@@ -1316,48 +1311,6 @@ function hasExcerptPreview(html?: string) {
13161311 )
13171312}
13181313
1319async function selectExcerptTabs(root: HTMLElement, query: string) {
1320 const terms = getSearchTerms(query)
1321 if (!terms.length) return
1322
1323 const tabs = root.querySelectorAll<HTMLElement>('.plugin-tabs')
1324
1325 for (let i = 0; i < tabs.length; i++) {
1326 const tab = tabs[i]
1327 const selectedTab = tab.querySelector<HTMLButtonElement>(
1328 '.plugin-tabs--tab[aria-selected="true"]'
1329 )
1330 const buttons = tab.querySelectorAll<HTMLButtonElement>(
1331 '.plugin-tabs--tab[role="tab"]'
1332 )
1333
1334 let found = false
1335
1336 for (let j = 0; j < buttons.length; j++) {
1337 const button = buttons[j]
1338 button.click()
1339 await nextTick()
1340 await nextFrame()
1341
1342 const panelId = button.getAttribute('aria-controls')
1343 const panel = panelId
1344 ? root.querySelector<HTMLElement>(`#${CSS.escape(panelId)}`)
1345 : tab.querySelector<HTMLElement>('.plugin-tabs--content')
1346 const text = panel?.textContent?.toLowerCase() ?? ''
1347
1348 if (terms.every((term) => text.includes(term))) {
1349 found = true
1350 break
1351 }
1352 }
1353
1354 if (!found) {
1355 selectedTab?.click()
1356 await nextTick()
1357 }
1358 }
1359}
1360
13611314/* Search input focus */
13621315
13631316const searchInput = ref<HTMLInputElement>()
@@ -1487,12 +1440,31 @@ onKeyStroke('Tab', (event) => {
14871440
14881441const router = useRouter()
14891442
1443function buildResultHref(pageId: string, tabs?: string[], anchor = '') {
1444 const query = tabs?.length
1445 ? `?tabs=${tabs.map((tab) => encodeURIComponent(tab)).join(',')}`
1446 : ''
1447 const hash = anchor ? `#${encodeURIComponent(anchor)}` : ''
1448 return `${pageId}${query}${hash}`
1449}
1450
1451function getSearchResultHref(item: SearchResult & Result) {
1452 const id = String(item.id)
1453 const hashIndex = id.indexOf('#')
1454 if (hashIndex < 0) return buildResultHref(id, item.tabs)
1455
1456 return buildResultHref(
1457 id.slice(0, hashIndex),
1458 item.tabs,
1459 id.slice(hashIndex + 1)
1460 )
1461}
1462
14901463function navigateToUrlResult(item: UrlResult) {
14911464 window.dispatchEvent(
14921465 new CustomEvent('search-nav', { detail: { query: filterText.value } })
14931466 )
1494 const dest = item.anchor ? item.pageId + '#' + item.anchor : item.pageId
1495 router.go(dest)
1467 router.go(buildResultHref(item.pageId, item.tabs, item.anchor))
14961468 showSearch.value = false
14971469}
14981470
@@ -1533,7 +1505,7 @@ onKeyStroke('Enter', (e) => {
15331505 detail: { query: filterText.value }
15341506 })
15351507 )
1536 router.go(selectedPackage.id)
1508 router.go(getSearchResultHref(selectedPackage))
15371509 showSearch.value = false
15381510 }
15391511})
@@ -1992,7 +1964,7 @@ function onMouseMove(e: MouseEvent) {
19921964 v-bind="resultMotion(index)"
19931965 >
19941966 <a
1995 :href="p.id"
1967 :href="getSearchResultHref(p)"
19961968 class="result"
19971969 :class="{
19981970 selected: selectedIndex === index + 1
docs/.vitepress/theme/components/tabs/PluginTabs.vue added +107
@@ -0,0 +1,107 @@
1<script setup lang="ts">
2import { computed, ref, toRef, useId, useSlots } from 'vue'
3import { useIsPrint, useStabilizeScrollPosition } from './composables'
4import { provideTabsSingleState, useTabsSelectedState } from './state'
5
6defineOptions({ name: 'PluginTabs' })
7
8const props = defineProps<{ sharedStateKey?: string }>()
9
10interface TabItem {
11 anchor: string
12 label: string
13}
14
15const isPrint = useIsPrint()
16const slots = useSlots()
17const tabItems = computed<TabItem[]>(() => {
18 const defaultSlot = slots.default?.()
19 if (!defaultSlot) return []
20
21 return defaultSlot
22 .filter((vnode) => {
23 if (!vnode.props) return false
24 if (typeof vnode.type !== 'object') return false
25
26 const type = vnode.type as { __name?: string; name?: string }
27 return type.__name === 'PluginTabsTab' || type.name === 'PluginTabsTab'
28 })
29 .map((vnode) => ({
30 anchor: String(vnode.props?.anchor ?? ''),
31 label: String(vnode.props?.label ?? '')
32 }))
33 .filter((item) => item.anchor && item.label)
34})
35const tabLabels = computed(() => tabItems.value.map((item) => item.label))
36const { selected, select } = useTabsSelectedState(
37 tabLabels,
38 toRef(props, 'sharedStateKey')
39)
40const tablist = ref<HTMLElement>()
41const { stabilizeScrollPosition } = useStabilizeScrollPosition(tablist)
42const selectStable = stabilizeScrollPosition(select)
43const buttonRefs = ref<HTMLButtonElement[]>([])
44const uid = useId()
45
46provideTabsSingleState({ uid, selected })
47
48function getTabButtonId(item: TabItem) {
49 return `tab-${item.anchor}-${uid}`
50}
51
52function getTabPanelId(item: TabItem) {
53 return `panel-${item.anchor}-${uid}`
54}
55
56async function onKeydown(e: KeyboardEvent) {
57 const currentIndex = tabItems.value.findIndex(
58 (item) => item.label === selected.value
59 )
60 let selectIndex: number | undefined
61
62 if (e.key === 'ArrowLeft') {
63 selectIndex = currentIndex >= 1
64 ? currentIndex - 1
65 : tabItems.value.length - 1
66 } else if (e.key === 'ArrowRight') {
67 selectIndex = currentIndex < tabItems.value.length - 1
68 ? currentIndex + 1
69 : 0
70 }
71
72 if (selectIndex === undefined || !tabItems.value[selectIndex]) return
73
74 e.preventDefault()
75 await selectStable(tabItems.value[selectIndex].label)
76 buttonRefs.value[selectIndex]?.focus()
77}
78</script>
79
80<template>
81 <div class="plugin-tabs">
82 <div
83 ref="tablist"
84 class="plugin-tabs--tab-list"
85 role="tablist"
86 @keydown="onKeydown"
87 >
88 <button
89 v-for="item in tabItems"
90 :id="getTabButtonId(item)"
91 ref="buttonRefs"
92 :key="item.anchor"
93 type="button"
94 role="tab"
95 class="plugin-tabs--tab"
96 :data-tab-anchor="item.anchor"
97 :aria-selected="item.label === selected && !isPrint"
98 :aria-controls="getTabPanelId(item)"
99 :tabindex="item.label === selected ? 0 : -1"
100 @click="selectStable(item.label)"
101 >
102 {{ item.label }}
103 </button>
104 </div>
105 <slot />
106 </div>
107</template>
docs/.vitepress/theme/components/tabs/PluginTabsTab.vue added +36
@@ -0,0 +1,36 @@
1<script setup lang="ts">
2import { computed } from 'vue'
3import { useIsPrint } from './composables'
4import { useTabsRenderAll, useTabsSingleState } from './state'
5
6defineOptions({ name: 'PluginTabsTab' })
7
8const props = defineProps<{
9 anchor: string
10 label: string
11}>()
12
13const { selected, uid } = useTabsSingleState()
14const isPrint = useIsPrint()
15const renderAll = useTabsRenderAll()
16const isActive = computed(() =>
17 selected.value === props.label || Boolean(isPrint.value) || renderAll
18)
19const panelId = computed(() => `panel-${props.anchor}-${uid}`)
20const buttonId = computed(() => `tab-${props.anchor}-${uid}`)
21</script>
22
23<template>
24 <div
25 v-if="isActive"
26 :id="panelId"
27 class="plugin-tabs--content"
28 role="tabpanel"
29 tabindex="0"
30 :data-tab-anchor="anchor"
31 :aria-labelledby="buttonId"
32 :data-is-print="isPrint || undefined"
33 >
34 <slot />
35 </div>
36</template>
docs/.vitepress/theme/components/tabs/composables.ts added +48
@@ -0,0 +1,48 @@
1import { nextTick, onBeforeMount, onUnmounted, type Ref, ref } from 'vue'
2
3export function useIsPrint() {
4 const matchMedia = typeof window !== 'undefined'
5 ? window.matchMedia('print')
6 : undefined
7 const value = ref(matchMedia?.matches)
8 const listener = () => {
9 value.value = matchMedia?.matches
10 }
11
12 onBeforeMount(() => {
13 matchMedia?.addEventListener('change', listener)
14 })
15 onUnmounted(() => {
16 matchMedia?.removeEventListener('change', listener)
17 })
18
19 return value
20}
21
22export function useStabilizeScrollPosition(
23 target: Ref<HTMLElement | undefined>
24) {
25 if (typeof document === 'undefined') {
26 return {
27 stabilizeScrollPosition:
28 <T extends (...args: any[]) => any>(func: T) =>
29 async (...args: Parameters<T>) => func(...args)
30 }
31 }
32
33 const scrollableElement = document.documentElement
34 const stabilizeScrollPosition =
35 <T extends (...args: any[]) => any>(func: T) =>
36 async (...args: Parameters<T>) => {
37 const result = func(...args)
38 const element = target.value
39 if (!element) return result
40
41 const offset = element.offsetTop - scrollableElement.scrollTop
42 await nextTick()
43 scrollableElement.scrollTop = element.offsetTop - offset
44 return result
45 }
46
47 return { stabilizeScrollPosition }
48}
docs/.vitepress/theme/components/tabs/index.ts added +17
@@ -0,0 +1,17 @@
1import type { App } from 'vue'
2import PluginTabs from './PluginTabs.vue'
3import PluginTabsTab from './PluginTabsTab.vue'
4import { provideTabsSharedState } from './state'
5
6export interface EnhanceTabsOptions {
7 renderAll?: boolean
8}
9
10export function enhanceAppWithTabs(
11 app: App,
12 options: EnhanceTabsOptions = {}
13) {
14 provideTabsSharedState(app, Boolean(options.renderAll))
15 app.component('PluginTabs', PluginTabs)
16 app.component('PluginTabsTab', PluginTabsTab)
17}
docs/.vitepress/theme/components/tabs/state.ts added +114
@@ -0,0 +1,114 @@
1import type { App, ComputedRef, InjectionKey, Ref } from 'vue'
2import { computed, inject, onMounted, provide, reactive, ref, watch } from 'vue'
3
4const sharedStateKey: InjectionKey<{ content?: Record<string, string> }> =
5 Symbol('vitepress:tabSharedState')
6const singleStateKey: InjectionKey<{
7 selected: ComputedRef<string>
8 uid: string
9}> = Symbol('vitepress:tabSingleState')
10const renderAllKey: InjectionKey<boolean> = Symbol('wotaku:tabsRenderAll')
11
12const localStorageKey = 'vitepress:tabsSharedState'
13const ls = typeof localStorage !== 'undefined' ? localStorage : null
14
15function getLocalStorageValue() {
16 const rawValue = ls?.getItem(localStorageKey)
17 if (rawValue) {
18 try {
19 return JSON.parse(rawValue)
20 } catch {
21 /* ignore invalid stored state */
22 }
23 }
24 return {}
25}
26
27function setLocalStorageValue(value: Record<string, string>) {
28 if (!ls) return
29 ls.setItem(localStorageKey, JSON.stringify(value))
30}
31
32export function provideTabsSharedState(app: App, renderAll = false) {
33 const state = reactive<{ content?: Record<string, string> }>({})
34
35 watch(
36 () => state.content,
37 (newStateContent, oldStateContent) => {
38 if (newStateContent && oldStateContent) {
39 setLocalStorageValue(newStateContent)
40 }
41 },
42 { deep: true }
43 )
44
45 app.provide(sharedStateKey, state)
46 app.provide(renderAllKey, renderAll)
47}
48
49export function useTabsSelectedState(
50 acceptValues: ComputedRef<string[]>,
51 sharedStateName: Ref<string | undefined>
52) {
53 const sharedState = inject(sharedStateKey)
54 if (!sharedState) {
55 throw new Error('[wotaku-tabs] TabsSharedState should be injected')
56 }
57
58 onMounted(() => {
59 if (!sharedState.content) sharedState.content = getLocalStorageValue()
60 })
61
62 const nonSharedState = ref<string>()
63 const selected = computed({
64 get() {
65 const key = sharedStateName.value
66 const values = acceptValues.value
67
68 if (key) {
69 const value = sharedState.content?.[key]
70 if (value && values.includes(value)) return value
71 } else if (
72 nonSharedState.value && values.includes(nonSharedState.value)
73 ) {
74 return nonSharedState.value
75 }
76
77 return values[0]
78 },
79 set(value) {
80 const key = sharedStateName.value
81 if (key) {
82 if (sharedState.content) sharedState.content[key] = value
83 } else {
84 nonSharedState.value = value
85 }
86 }
87 })
88
89 return {
90 selected,
91 select(value: string) {
92 selected.value = value
93 }
94 }
95}
96
97export function provideTabsSingleState(state: {
98 selected: ComputedRef<string>
99 uid: string
100}) {
101 provide(singleStateKey, state)
102}
103
104export function useTabsSingleState() {
105 const state = inject(singleStateKey)
106 if (!state) {
107 throw new Error('[wotaku-tabs] TabsSingleState should be injected')
108 }
109 return state
110}
111
112export function useTabsRenderAll() {
113 return inject(renderAllKey, false)
114}
docs/.vitepress/theme/index.ts +5 −5
@@ -10,7 +10,6 @@ import DefaultTheme from 'vitepress/theme'
1010import './styles/style.scss'
1111import { NolebasePagePropertiesPlugin } from '@nolebase/vitepress-plugin-page-properties/client'
1212import FloatingVue from 'floating-vue'
13import { enhanceAppWithTabs } from 'vitepress-plugin-tabs/client'
1413import '@nolebase/vitepress-plugin-enhanced-readabilities/client/style.css'
1514import '@nolebase/vitepress-plugin-page-properties/client/style.css'
1615import 'floating-vue/dist/style.css'
@@ -18,16 +17,17 @@ import Authors from './components/Authors.vue'
1817import Tooltip from './components/Tooltip.vue'
1918import { createMediumZoomProvider } from './composables/medium-zoom'
2019import 'virtual:uno.css'
21import Feedback from './components/Feedback.vue'
22import Fb from './components/Fb.vue'
2320import Collapsible from './components/Collapsible.vue'
21import Fb from './components/Fb.vue'
22import Feedback from './components/Feedback.vue'
2423import ScrapeTable from './components/ScrapeTable.vue'
2524import Layout from './Layout.vue'
2625import './styles/tooltip-hint.css'
2726import './styles/steps.css'
2827import Block from './components/Block.vue'
29import LinkInline from './components/LinkInline.vue'
3028import Highlight from './components/Highlight.vue'
29import LinkInline from './components/LinkInline.vue'
30import { enhanceAppWithTabs } from './components/tabs'
3131
3232export default {
3333 extends: DefaultTheme,
@@ -107,4 +107,4 @@ export default {
107107 ]
108108 )
109109 }
110} satisfies Theme
\ No newline at end of file
110} satisfies Theme
docs/.vitepress/theme/styles/style.scss +93
@@ -1649,6 +1649,99 @@ html.reduce-blur-effects {
16491649 border-top: none !important;
16501650}
16511651
1652:root {
1653 --vp-plugin-tabs-tab-text-color: var(--vp-c-text-2);
1654 --vp-plugin-tabs-tab-active-text-color: var(--vp-c-text-1);
1655 --vp-plugin-tabs-tab-hover-text-color: var(--vp-c-text-1);
1656 --vp-plugin-tabs-tab-bg: var(--vp-c-bg-soft);
1657 --vp-plugin-tabs-tab-divider: var(--vp-c-divider);
1658 --vp-plugin-tabs-tab-active-bar-color: var(--vp-c-brand-1);
1659}
1660
1661.plugin-tabs {
1662 margin: 16px 0;
1663 background-color: var(--vp-plugin-tabs-tab-bg);
1664 border-radius: 8px;
1665}
1666
1667.plugin-tabs--tab-list {
1668 position: relative;
1669 padding: 0 12px;
1670 overflow-x: auto;
1671 overflow-y: hidden;
1672}
1673
1674.plugin-tabs--tab-list::after {
1675 content: "";
1676 position: absolute;
1677 right: 0;
1678 bottom: 0;
1679 left: 0;
1680 height: 2px;
1681 background-color: var(--vp-plugin-tabs-tab-divider);
1682}
1683
1684.plugin-tabs--tab {
1685 position: relative;
1686 padding: 0 12px;
1687 border-bottom: 2px solid transparent;
1688 color: var(--vp-plugin-tabs-tab-text-color);
1689 font-size: 14px;
1690 font-weight: 500;
1691 line-height: 48px;
1692 white-space: nowrap;
1693 transition: color 0.25s;
1694}
1695
1696.plugin-tabs--tab[aria-selected="true"] {
1697 color: var(--vp-plugin-tabs-tab-active-text-color);
1698}
1699
1700.plugin-tabs--tab:hover {
1701 color: var(--vp-plugin-tabs-tab-hover-text-color);
1702}
1703
1704.plugin-tabs--tab::after {
1705 content: "";
1706 position: absolute;
1707 z-index: 1;
1708 right: 8px;
1709 bottom: -2px;
1710 left: 8px;
1711 height: 2px;
1712 background-color: transparent;
1713 transition: background-color 0.25s;
1714}
1715
1716.plugin-tabs--tab[aria-selected="true"]::after {
1717 background-color: var(--vp-plugin-tabs-tab-active-bar-color);
1718}
1719
1720.plugin-tabs--content {
1721 padding: 16px;
1722}
1723
1724.plugin-tabs--content[data-is-print="true"]:not(:last-child) {
1725 border-bottom: 2px solid var(--vp-plugin-tabs-tab-divider);
1726}
1727
1728.plugin-tabs--content > :first-child:first-child {
1729 margin-top: 0;
1730}
1731
1732.plugin-tabs--content > :last-child:last-child {
1733 margin-bottom: 0;
1734}
1735
1736.plugin-tabs--content > div[class*="language-"] {
1737 margin: 16px 0;
1738 border-radius: 8px;
1739}
1740
1741:root:not(.dark) .plugin-tabs--content div[class*="language-"] {
1742 background-color: var(--vp-c-bg);
1743}
1744
16521745.vp-doc .collapsible-search-heading,
16531746.vp-doc .tab-search-heading {
16541747 position: absolute;
docs/.vitepress/theme/workers/searchWorker.ts +77 −6
@@ -4,9 +4,10 @@ import MiniSearch, {
44 type SearchResult
55} from 'minisearch'
66
7import type { PageLink } from '../../plugins/urlSearchPlugin'
7import type { PageLink, TabTarget } from '../../plugins/urlSearchPlugin'
88
99interface Result {
10 tabs?: string[]
1011 title: string
1112 titles: string[]
1213 text?: string
@@ -63,6 +64,8 @@ let searchIndexKey = ''
6364let urlLinks: PageLink[] = []
6465let urlLinkHrefsLower: string[] = []
6566let urlLinksPromise: Promise<void> | null = null
67let tabTargetMap = new Map<string, string[]>()
68let tabTargetsPromise: Promise<void> | null = null
6669let pageOrder = new Map<string, number>()
6770let docOrder = new Map<string, number>()
6871
@@ -100,6 +103,20 @@ function getPageKey(id: string) {
100103 return id.split('#')[0].replace(/\/$/, '')
101104}
102105
106function getAnchorKey(pageId: string, anchor: string) {
107 return `${pageId.replace(/\/$/, '')}\x00${anchor}`
108}
109
110function getResultLocation(id: unknown) {
111 const value = String(id)
112 const hashIndex = value.indexOf('#')
113
114 return {
115 anchor: hashIndex >= 0 ? value.slice(hashIndex + 1) : '',
116 pageId: getPageKey(value)
117 }
118}
119
103120function getPageOrder(key: string) {
104121 return pageOrder.get(key) ?? Number.MAX_SAFE_INTEGER
105122}
@@ -164,11 +181,28 @@ function withLinkPathTitles(
164181 return {
165182 ...result,
166183 title: stripMarkdown(link.linkText),
167 titles: link.titles
184 titles: link.titles,
185 ...(link.tabs?.length ? { tabs: link.tabs } : {})
168186 }
169187 })
170188}
171189
190function getTabsForResult(result: WorkerSearchResult) {
191 if (result.tabs?.length) return result.tabs
192
193 const { pageId, anchor } = getResultLocation(result.id)
194 return tabTargetMap.get(getAnchorKey(pageId, anchor))
195}
196
197function withTabMetadata(results: WorkerSearchResult[]) {
198 if (!tabTargetMap.size) return results
199
200 return results.map((result) => {
201 const tabs = getTabsForResult(result)
202 return tabs?.length ? { ...result, tabs } : result
203 })
204}
205
172206function rebuildDocOrder(index: MiniSearch<Result>) {
173207 const map = new Map<string, number>()
174208 const ids = (index as any)._documentIds
@@ -243,8 +277,10 @@ async function textSearch(message: TextSearchRequest) {
243277 (r) => !seen.has(r.id) && r.match && Object.keys(r.match).length > 0
244278 )
245279 const results = [...top, ...titleHits].sort(compareByPageAndDoc)
246 await ensureUrlLinks()
247 const displayResults = withLinkPathTitles(results, message.query)
280 await ensureSearchMetadata()
281 const displayResults = withTabMetadata(
282 withLinkPathTitles(results, message.query)
283 )
248284 const terms = new Set<string>()
249285 for (const result of displayResults) {
250286 for (const term in result.match) terms.add(term)
@@ -280,9 +316,39 @@ async function ensureUrlLinks() {
280316 await urlLinksPromise
281317}
282318
319async function ensureTabTargets() {
320 if (tabTargetMap.size > 0) return
321 if (tabTargetsPromise) {
322 await tabTargetsPromise
323 return
324 }
325
326 tabTargetsPromise = fetch('/tab-search-index.json')
327 .then((r) => r.json())
328 .then((data: TabTarget[]) => {
329 tabTargetMap = new Map(
330 data.map((target) => [
331 getAnchorKey(target.pageId, target.anchor),
332 target.tabs
333 ])
334 )
335 })
336 .catch(() => {
337 tabTargetMap = new Map()
338 })
339 .finally(() => {
340 tabTargetsPromise = null
341 })
342 await tabTargetsPromise
343}
344
345async function ensureSearchMetadata() {
346 await Promise.all([ensureUrlLinks(), ensureTabTargets()])
347}
348
283349async function urlSearch(message: UrlSearchRequest) {
284350 setPageOrder(message.pageOrderEntries)
285 await ensureUrlLinks()
351 await ensureSearchMetadata()
286352
287353 const query = message.query.trim().toLowerCase()
288354 if (!query) return { matches: [], pageGroups: [] }
@@ -294,7 +360,12 @@ async function urlSearch(message: UrlSearchRequest) {
294360
295361 const link = urlLinks[i]
296362
297 matches.push(link)
363 if (link.tabs?.length) {
364 matches.push(link)
365 } else {
366 const tabs = tabTargetMap.get(getAnchorKey(link.pageId, link.anchor))
367 matches.push(tabs?.length ? { ...link, tabs } : link)
368 }
298369 const existing = pageGroups.get(link.pageId)
299370 if (existing) existing.count++
300371 else pageGroups.set(link.pageId, { key: link.pageId, count: 1 })
docs/.vitepress/utils/tabAnchors.ts added +61
@@ -0,0 +1,61 @@
1const rControl = /[\u0000-\u001f]/g
2const rSpecial = /[\s~`!@#$%^&*()\-_+=[\]{}|\\;:"'“”‘’<>,.?/]+/g
3const rCombining = /[\u0300-\u036F]/g
4
5export interface ParsedTabLabel {
6 anchor?: string
7 label: string
8}
9
10export function stripHeadingMarkup(value: string) {
11 return value
12 .replace(/\{[^}]*\}\s*$/, '')
13 .replace(/<[^>]*>/g, '')
14 .replace(/`([^`]+)`/g, '$1')
15 .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
16 .replace(/[*_~]/g, '')
17 .trim()
18}
19
20export function slugifyAnchor(value: string) {
21 return stripHeadingMarkup(value)
22 .normalize('NFKD')
23 .replace(rCombining, '')
24 .replace(rControl, '')
25 .replace(rSpecial, '-')
26 .replace(/-{2,}/g, '-')
27 .replace(/^-+|-+$/g, '')
28 .replace(/^(\d)/, '_$1')
29 .toLowerCase()
30}
31
32export function parseTabLabel(value: string): ParsedTabLabel {
33 const trimmed = value.trim()
34 const match = trimmed.match(/\s+\{#([^}\s]+)\}\s*$/)
35 if (!match) return { label: trimmed }
36
37 return {
38 anchor: match[1],
39 label: trimmed.slice(0, match.index).trim()
40 }
41}
42
43export function getUniqueAnchor(base: string, counts: Map<string, number>) {
44 const fallback = 'tab'
45 const slug = slugifyAnchor(base) || fallback
46 const count = counts.get(slug) ?? 0
47 counts.set(slug, count + 1)
48 return count === 0 ? slug : `${slug}-${count}`
49}
50
51export function getTabAnchor(
52 rawLabel: string,
53 counts: Map<string, number>
54) {
55 const parsed = parseTabLabel(rawLabel)
56 return parsed.anchor || getUniqueAnchor(parsed.label, counts)
57}
58
59export function getTabHeadingAnchor(tabAnchor: string) {
60 return `tab-${tabAnchor}`
61}
package.json −1
@@ -50,7 +50,6 @@
5050 "vite": "^7.2.2",
5151 "vite-plugin-virtual": "^0.4.0",
5252 "vitepress": "2.0.0-alpha.12",
53 "vitepress-plugin-tabs": "^0.7.3",
5453 "vue": "^3.5.24",
5554 "zod": "^4.1.11"
5655 },
pnpm-lock.yaml −19
@@ -119,9 +119,6 @@ importers:
119119 vitepress:
120120 specifier: 2.0.0-alpha.12
121121 version: 2.0.0-alpha.12(@types/node@22.19.0)(change-case@5.4.4)(esbuild@0.25.12)(jiti@2.6.1)(less@4.4.2)(oxc-minify@0.96.0)(postcss@8.5.6)(sass@1.93.3)(terser@5.44.1)(typescript@5.6.3)
122 vitepress-plugin-tabs:
123 specifier: ^0.7.3
124 version: 0.7.3(vitepress@2.0.0-alpha.12(@types/node@22.19.0)(change-case@5.4.4)(esbuild@0.25.12)(jiti@2.6.1)(less@4.4.2)(oxc-minify@0.96.0)(postcss@8.5.6)(sass@1.93.3)(terser@5.44.1)(typescript@5.6.3))(vue@3.5.24(typescript@5.6.3))
125122 vue:
126123 specifier: ^3.5.24
127124 version: 3.5.24(typescript@5.6.3)
@@ -3582,12 +3579,6 @@ packages:
35823579 yaml:
35833580 optional: true
35843581
3585 vitepress-plugin-tabs@0.7.3:
3586 resolution: {integrity: sha512-CkUz49UrTLcVOszuiHIA7ZBvfsg9RluRkFjRG1KvCg/NwuOTLZwcBRv7vBB3vMlDp0bWXIFOIwdI7bE93cV3Hw==}
3587 peerDependencies:
3588 vitepress: ^1.0.0
3589 vue: ^3.5.0
3590
35913582 vitepress@2.0.0-alpha.12:
35923583 resolution: {integrity: sha512-yZwCwRRepcpN5QeAhwSnEJxS3I6zJcVixqL1dnm6km4cnriLpQyy2sXQDsE5Ti3pxGPbhU51nTMwI+XC1KNnJg==}
35933584 hasBin: true
@@ -3603,9 +3594,6 @@ packages:
36033594 postcss:
36043595 optional: true
36053596
3606 vscode-uri@3.1.0:
3607 resolution: {integrity: sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ==}
3608
36093597 vue-demi@0.14.10:
36103598 resolution: {integrity: sha512-nMZBOwuzabUO0nLgIcc6rycZEebF6eeUfaiQx9+WSk8e29IbLvPU9feI6tqW4kTo3hvoYAJkMh8n8D0fuISphg==}
36113599 engines: {node: '>=12'}
@@ -7073,11 +7061,6 @@ snapshots:
70737061 sass: 1.93.3
70747062 terser: 5.44.1
70757063
7076 vitepress-plugin-tabs@0.7.3(vitepress@2.0.0-alpha.12(@types/node@22.19.0)(change-case@5.4.4)(esbuild@0.25.12)(jiti@2.6.1)(less@4.4.2)(oxc-minify@0.96.0)(postcss@8.5.6)(sass@1.93.3)(terser@5.44.1)(typescript@5.6.3))(vue@3.5.24(typescript@5.6.3)):
7077 dependencies:
7078 vitepress: 2.0.0-alpha.12(@types/node@22.19.0)(change-case@5.4.4)(esbuild@0.25.12)(jiti@2.6.1)(less@4.4.2)(oxc-minify@0.96.0)(postcss@8.5.6)(sass@1.93.3)(terser@5.44.1)(typescript@5.6.3)
7079 vue: 3.5.24(typescript@5.6.3)
7080
70817064 vitepress@2.0.0-alpha.12(@types/node@22.19.0)(change-case@5.4.4)(esbuild@0.25.12)(jiti@2.6.1)(less@4.4.2)(oxc-minify@0.96.0)(postcss@8.5.6)(sass@1.93.3)(terser@5.44.1)(typescript@5.6.3):
70827065 dependencies:
70837066 '@docsearch/css': 4.3.1
@@ -7126,8 +7109,6 @@ snapshots:
71267109 - universal-cookie
71277110 - yaml
71287111
7129 vscode-uri@3.1.0: {}
7130
71317112 vue-demi@0.14.10(vue@3.5.24(typescript@5.6.3)):
71327113 dependencies:
71337114 vue: 3.5.24(typescript@5.6.3)