Commit aab7b2f903
Unsigned
Layout: unified · split
docs/.vitepress/configs/markdown/index.ts +12 −3
| @@ -14,13 +14,18 @@ import { imgLazyload } from '@mdit/plugin-img-lazyload' | |||
| 14 | import { imgSize } from '@mdit/plugin-img-size' | 14 | import { imgSize } from '@mdit/plugin-img-size' |
| 15 | import MdReg from 'markdown-it-regexp' | 15 | import MdReg from 'markdown-it-regexp' |
| 16 | import type { MarkdownRenderer } from 'vitepress' | 16 | import type { MarkdownRenderer } from 'vitepress' |
| 17 | import { tabsMarkdownPlugin } from 'vitepress-plugin-tabs' | 17 | import { |
| 18 | getTabAnchor, | ||
| 19 | getTabHeadingAnchor, | ||
| 20 | parseTabLabel | ||
| 21 | } from '../../utils/tabAnchors' | ||
| 18 | import { getTooltip } from '../../utils/tooltips' | 22 | import { getTooltip } from '../../utils/tooltips' |
| 19 | import { headersPlugin } from '../markdown/headers' | 23 | import { headersPlugin } from '../markdown/headers' |
| 20 | import { emojiRender } from './emoji' | 24 | import { emojiRender } from './emoji' |
| 21 | import { nestedContainersPlugin } from './nestedContainers' | 25 | import { nestedContainersPlugin } from './nestedContainers' |
| 22 | import { scrapeTablePlugin } from './scrapeTablePlugin' | 26 | import { scrapeTablePlugin } from './scrapeTablePlugin' |
| 23 | import markdownSteps from './steps' | 27 | import markdownSteps from './steps' |
| 28 | import { tabsMarkdownPlugin } from './tabs' | ||
| 24 | 29 | ||
| 25 | export function configureMarkdown(md: MarkdownRenderer) { | 30 | export function configureMarkdown(md: MarkdownRenderer) { |
| 26 | md.use(emojiRender) | 31 | md.use(emojiRender) |
| @@ -142,6 +147,7 @@ function injectSearchHeadings(src: string) { | |||
| 142 | const containerStack: string[] = [] | 147 | const containerStack: string[] = [] |
| 143 | const headingStack: (SearchHeading | undefined)[] = [] | 148 | const headingStack: (SearchHeading | undefined)[] = [] |
| 144 | const tabResetStack: (SearchHeading | undefined)[] = [] | 149 | const tabResetStack: (SearchHeading | undefined)[] = [] |
| 150 | const tabAnchorCounts = new Map<string, number>() | ||
| 145 | const getCurrentHeading = () => { | 151 | const getCurrentHeading = () => { |
| 146 | for (let i = headingStack.length - 1; i >= 0; i--) { | 152 | for (let i = headingStack.length - 1; i >= 0; i--) { |
| 147 | if (headingStack[i]) return headingStack[i] | 153 | if (headingStack[i]) return headingStack[i] |
| @@ -200,14 +206,17 @@ function injectSearchHeadings(src: string) { | |||
| 200 | const tabMatch = lines[i].match(/^(\s*)==\s+(.+)$/) | 206 | const tabMatch = lines[i].match(/^(\s*)==\s+(.+)$/) |
| 201 | if (tabMatch && containerStack.includes('tabs')) { | 207 | if (tabMatch && containerStack.includes('tabs')) { |
| 202 | const [, indent, title] = tabMatch | 208 | const [, indent, title] = tabMatch |
| 203 | const headingTitle = title.trim() | 209 | const parsed = parseTabLabel(title) |
| 210 | const headingTitle = parsed.label | ||
| 204 | if (!headingTitle) continue | 211 | if (!headingTitle) continue |
| 212 | const anchor = getTabAnchor(title, tabAnchorCounts) | ||
| 213 | const headingAnchor = getTabHeadingAnchor(anchor) | ||
| 205 | 214 | ||
| 206 | lines.splice( | 215 | lines.splice( |
| 207 | i + 1, | 216 | i + 1, |
| 208 | 0, | 217 | 0, |
| 209 | '', | 218 | '', |
| 210 | `${indent}### ${headingTitle} {.tab-search-heading .ignore-header}`, | 219 | `${indent}### ${headingTitle} {#${headingAnchor} .tab-search-heading .ignore-header}`, |
| 211 | '' | 220 | '' |
| 212 | ) | 221 | ) |
| 213 | i += 3 | 222 | i += 3 |
docs/.vitepress/configs/markdown/tabs.ts added +216
| @@ -0,0 +1,216 @@ | |||
| 1 | import type { MarkdownRenderer } from 'vitepress' | ||
| 2 | import { getUniqueAnchor, parseTabLabel } from '../../utils/tabAnchors' | ||
| 3 | |||
| 4 | function 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 | |||
| 111 | const tabMarkerCode = '='.charCodeAt(0) | ||
| 112 | const minTabMarkerLen = 2 | ||
| 113 | |||
| 114 | const 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 | |||
| 181 | function parseTabsParams(input: string) { | ||
| 182 | return { shareStateKey: input.match(/key:(\S+)/)?.[1] } | ||
| 183 | } | ||
| 184 | |||
| 185 | function getTabAnchorCounts(env: any) { | ||
| 186 | env.__tabAnchorCounts ??= new Map<string, number>() | ||
| 187 | return env.__tabAnchorCounts as Map<string, number> | ||
| 188 | } | ||
| 189 | |||
| 190 | export 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 @@ | |||
| 1 | import { writeFileSync } from 'node:fs' | 1 | import { writeFileSync } from 'node:fs' |
| 2 | import { join } from 'node:path' | 2 | import { join } from 'node:path' |
| 3 | import { renderEmojiShortcodes } from '../configs/markdown/emoji' | 3 | import { renderEmojiShortcodes } from '../configs/markdown/emoji' |
| 4 | import { | ||
| 5 | getTabAnchor, | ||
| 6 | getTabHeadingAnchor, | ||
| 7 | parseTabLabel, | ||
| 8 | slugifyAnchor, | ||
| 9 | stripHeadingMarkup | ||
| 10 | } from '../utils/tabAnchors' | ||
| 4 | 11 | ||
| 5 | export interface PageLink { | 12 | export interface PageLink { |
| 6 | href: string | 13 | href: string |
| @@ -8,82 +15,142 @@ export interface PageLink { | |||
| 8 | pageId: string | 15 | pageId: string |
| 9 | anchor: string | 16 | anchor: string |
| 10 | titles: string[] | 17 | titles: string[] |
| 18 | tabs?: string[] | ||
| 11 | } | 19 | } |
| 12 | 20 | ||
| 13 | function extractLinksFromMarkdown(src: string, pageId: string): PageLink[] { | 21 | export interface TabTarget { |
| 14 | const results: PageLink[] = [] | 22 | pageId: string |
| 15 | const seen = new Set<string>() | 23 | anchor: string |
| 24 | tabs: string[] | ||
| 25 | } | ||
| 26 | |||
| 27 | interface PageSearchMetadata { | ||
| 28 | links: PageLink[] | ||
| 29 | tabTargets: TabTarget[] | ||
| 30 | } | ||
| 31 | |||
| 32 | function 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>() | ||
| 16 | const headingStack: string[] = [] | 39 | const headingStack: string[] = [] |
| 17 | const slugCounts = new Map<string, number>() | 40 | const slugCounts = new Map<string, number>() |
| 41 | const tabAnchorCounts = new Map<string, number>() | ||
| 18 | const containerStack: string[] = [] | 42 | const containerStack: string[] = [] |
| 43 | const tabPath: string[] = [] | ||
| 44 | const tabResetStack: { | ||
| 45 | anchor: string | ||
| 46 | headings: string[] | ||
| 47 | }[] = [] | ||
| 19 | const collapsibleStack: { | 48 | const collapsibleStack: { |
| 20 | anchor: string | 49 | anchor: string |
| 21 | headings: string[] | 50 | headings: string[] |
| 22 | }[] = [] | 51 | }[] = [] |
| 23 | let currentAnchor = '' | 52 | let currentAnchor = '' |
| 24 | 53 | ||
| 25 | // Strip frontmatter | ||
| 26 | const body = src.startsWith('---') | 54 | const body = src.startsWith('---') |
| 27 | ? src.replace(/^---[\s\S]*?---\n?/, '') | 55 | ? src.replace(/^---[\s\S]*?---\n?/, '') |
| 28 | : src | 56 | : src |
| 29 | const lines = body.split('\n') | 57 | const lines = body.split('\n') |
| 30 | 58 | ||
| 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 | |||
| 55 | const getAnchor = (text: string) => { | 59 | const getAnchor = (text: string) => { |
| 56 | const slug = slugify(text) | 60 | const slug = slugifyAnchor(text) |
| 57 | const count = slugCounts.get(slug) ?? 0 | 61 | const count = slugCounts.get(slug) ?? 0 |
| 58 | slugCounts.set(slug, count + 1) | 62 | slugCounts.set(slug, count + 1) |
| 59 | return count === 0 ? slug : `${slug}-${count}` | 63 | return count === 0 ? slug : `${slug}-${count}` |
| 60 | } | 64 | } |
| 61 | 65 | ||
| 62 | const setHeading = (level: number, text: string) => { | 66 | const getCurrentTabPath = () => tabPath.filter(Boolean) |
| 63 | headingStack[level] = text | 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 | ||
| 64 | headingStack.length = level + 1 | 79 | headingStack.length = level + 1 |
| 65 | currentAnchor = getAnchor(text) | 80 | currentAnchor = anchor || getAnchor(title) |
| 81 | recordTabTarget(currentAnchor) | ||
| 66 | } | 82 | } |
| 67 | 83 | ||
| 68 | const getTitles = () => headingStack.filter(Boolean) | 84 | const getTitles = () => headingStack.filter(Boolean) |
| 69 | 85 | ||
| 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 | |||
| 70 | for (let i = 0; i < lines.length; i++) { | 118 | for (let i = 0; i < lines.length; i++) { |
| 71 | const line = lines[i] | 119 | const line = lines[i] |
| 72 | 120 | ||
| 73 | const containerOpenMatch = line.match(/^\s*:{3,}\s*([A-Za-z][\w-]*)\b/) | 121 | const containerOpenMatch = line.match(/^\s*:{3,}\s*([A-Za-z][\w-]*)\b/) |
| 74 | if (containerOpenMatch) { | 122 | 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 | } | ||
| 76 | } else if (/^\s*:{3,}\s*$/.test(line)) { | 131 | } 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 | } | ||
| 78 | } | 138 | } |
| 79 | 139 | ||
| 80 | const tabMatch = line.match(/^\s*==\s+(.+)$/) | 140 | const tabMatch = line.match(/^\s*==\s+(.+)$/) |
| 81 | if (tabMatch && containerStack.includes('tabs')) { | 141 | if (tabMatch && containerStack.includes('tabs')) { |
| 82 | const title = tabMatch[1].trim() | 142 | const rawTitle = tabMatch[1] |
| 83 | if (title) { | 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 | |||
| 84 | // The markdown renderer injects a hidden H3 for each tab label. | 151 | // The markdown renderer injects a hidden H3 for each tab label. |
| 85 | // Mirror that heading so URL search deep-links to the selected tab. | 152 | // Mirror that heading so search can deep-link to the selected tab. |
| 86 | setHeading(2, title) | 153 | setHeading(2, parsed.label, headingAnchor) |
| 87 | } | 154 | } |
| 88 | continue | 155 | continue |
| 89 | } | 156 | } |
| @@ -116,62 +183,34 @@ function extractLinksFromMarkdown(src: string, pageId: string): PageLink[] { | |||
| 116 | 183 | ||
| 117 | if (/^\s*<\/Collapsible>\s*$/i.test(line)) { | 184 | if (/^\s*<\/Collapsible>\s*$/i.test(line)) { |
| 118 | const previous = collapsibleStack.pop() | 185 | const previous = collapsibleStack.pop() |
| 119 | if (previous) { | 186 | if (previous) restoreHeadingState(previous) |
| 120 | currentAnchor = previous.anchor | ||
| 121 | headingStack.length = 0 | ||
| 122 | headingStack.push(...previous.headings) | ||
| 123 | } | ||
| 124 | continue | 187 | continue |
| 125 | } | 188 | } |
| 126 | 189 | ||
| 127 | // Heading: ## Title or === Title (setext-style ignored, ATX only) | ||
| 128 | const headingMatch = line.match(/^(#{1,6})\s+(.+)/) | 190 | const headingMatch = line.match(/^(#{1,6})\s+(.+)/) |
| 129 | if (headingMatch) { | 191 | if (headingMatch) { |
| 130 | const level = headingMatch[1].length - 1 | 192 | const level = headingMatch[1].length - 1 |
| 131 | const text = headingMatch[2].trim() | 193 | setHeading(level, headingMatch[2].trim()) |
| 132 | setHeading(level, text) | ||
| 133 | continue | 194 | continue |
| 134 | } | 195 | } |
| 135 | 196 | ||
| 136 | // Markdown links: [text](https://...) | ||
| 137 | const linkRE = /\[([^\]]*)\]\((https?:\/\/[^)]+)\)/g | 197 | const linkRE = /\[([^\]]*)\]\((https?:\/\/[^)]+)\)/g |
| 138 | let m: RegExpExecArray | null | 198 | let m: RegExpExecArray | null |
| 139 | while ((m = linkRE.exec(line)) !== null) { | 199 | while ((m = linkRE.exec(line)) !== null) { |
| 140 | const linkText = renderEmojiShortcodes(m[1].trim()) | 200 | pushLink(m[2].trim(), 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 | }) | ||
| 152 | } | 201 | } |
| 153 | 202 | ||
| 154 | // Bare angle-bracket URLs: <https://...> | ||
| 155 | const bareRE = /<(https?:\/\/[^>]+)>/g | 203 | const bareRE = /<(https?:\/\/[^>]+)>/g |
| 156 | while ((m = bareRE.exec(line)) !== null) { | 204 | while ((m = bareRE.exec(line)) !== null) { |
| 157 | const href = m[1].trim() | 205 | const href = m[1].trim() |
| 158 | const key = href + '\x00' + currentAnchor | 206 | pushLink(href, href) |
| 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 | }) | ||
| 168 | } | 207 | } |
| 169 | } | 208 | } |
| 170 | 209 | ||
| 171 | return results | 210 | return { links, tabTargets: [...tabTargets.values()] } |
| 172 | } | 211 | } |
| 173 | 212 | ||
| 174 | const collectedByPage = new Map<string, PageLink[]>() | 213 | const collectedByPage = new Map<string, PageSearchMetadata>() |
| 175 | 214 | ||
| 176 | function getPageId(page: string) { | 215 | function getPageId(page: string) { |
| 177 | return '/' + page.replace(/\.md$/, '').replace(/\/index$/, '/') | 216 | return '/' + page.replace(/\.md$/, '').replace(/\/index$/, '/') |
| @@ -181,9 +220,14 @@ function getDedupedLinks() { | |||
| 181 | const seen = new Set<string>() | 220 | const seen = new Set<string>() |
| 182 | const deduped: PageLink[] = [] | 221 | const deduped: PageLink[] = [] |
| 183 | 222 | ||
| 184 | for (const links of collectedByPage.values()) { | 223 | for (const metadata of collectedByPage.values()) { |
| 185 | for (const link of links) { | 224 | for (const link of metadata.links) { |
| 186 | const key = link.href + '\x00' + link.pageId + '\x00' + link.anchor | 225 | const key = [ |
| 226 | link.href, | ||
| 227 | link.pageId, | ||
| 228 | link.anchor, | ||
| 229 | link.tabs?.join('/') ?? '' | ||
| 230 | ].join('\x00') | ||
| 187 | if (seen.has(key)) continue | 231 | if (seen.has(key)) continue |
| 188 | seen.add(key) | 232 | seen.add(key) |
| 189 | deduped.push(link) | 233 | deduped.push(link) |
| @@ -193,16 +237,43 @@ function getDedupedLinks() { | |||
| 193 | return deduped | 237 | return deduped |
| 194 | } | 238 | } |
| 195 | 239 | ||
| 240 | function 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 | |||
| 196 | export function collectPageLinks(src: string, page: string) { | 260 | export function collectPageLinks(src: string, page: string) { |
| 197 | const pageId = getPageId(page) | 261 | const pageId = getPageId(page) |
| 198 | collectedByPage.set(pageId, extractLinksFromMarkdown(src, pageId)) | 262 | collectedByPage.set(pageId, extractSearchMetadataFromMarkdown(src, pageId)) |
| 199 | } | 263 | } |
| 200 | 264 | ||
| 201 | export function writeUrlSearchIndex(outDir: string) { | 265 | export function writeUrlSearchIndex(outDir: string) { |
| 202 | const deduped = getDedupedLinks() | 266 | const links = getDedupedLinks() |
| 203 | const outPath = join(outDir, 'url-search-index.json') | 267 | const linksPath = join(outDir, 'url-search-index.json') |
| 204 | writeFileSync(outPath, JSON.stringify(deduped), 'utf-8') | 268 | writeFileSync(linksPath, JSON.stringify(links), 'utf-8') |
| 205 | console.log(`[url-search] wrote ${deduped.length} links → ${outPath}`) | 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 | ) | ||
| 206 | } | 277 | } |
| 207 | 278 | ||
| 208 | export function urlSearchDevPlugin() { | 279 | export function urlSearchDevPlugin() { |
| @@ -217,6 +288,14 @@ export function urlSearchDevPlugin() { | |||
| 217 | res.end(JSON.stringify(deduped)) | 288 | res.end(JSON.stringify(deduped)) |
| 218 | } | 289 | } |
| 219 | ) | 290 | ) |
| 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 | ) | ||
| 220 | } | 299 | } |
| 221 | } | 300 | } |
| 222 | } | 301 | } |
docs/.vitepress/theme/Layout.vue +146 −128
| @@ -66,7 +66,6 @@ if (!import.meta.env.SSR) { | |||
| 66 | typeof event.detail?.query === 'string' | 66 | typeof event.detail?.query === 'string' |
| 67 | ? event.detail.query | 67 | ? event.detail.query |
| 68 | : '' | 68 | : '' |
| 69 | tryOpenCollapsibles() | ||
| 70 | }) | 69 | }) |
| 71 | } | 70 | } |
| 72 | 71 | ||
| @@ -103,166 +102,160 @@ const getScrollTargetForAnchor = (target: HTMLElement) => { | |||
| 103 | return target | 102 | return target |
| 104 | } | 103 | } |
| 105 | 104 | ||
| 106 | const getHeadingAnchor = (heading: HTMLElement) => { | 105 | const TAB_QUERY_PARAM = 'tabs' |
| 107 | const href = heading.querySelector<HTMLAnchorElement>('a[href^="#"]') | ||
| 108 | ?.getAttribute('href') | ||
| 109 | 106 | ||
| 110 | if (href?.startsWith('#') && href.length > 1) return href.slice(1) | 107 | const 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 | } | ||
| 111 | 116 | ||
| 112 | return heading.id || undefined | 117 | const 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)}` : ''}` | ||
| 113 | } | 133 | } |
| 114 | 134 | ||
| 115 | const getSelectedTabHeadingAnchor = (tabs: HTMLElement) => { | 135 | const getSelectedTabAnchor = (tabs: HTMLElement) => |
| 116 | const selectedTab = tabs.querySelector<HTMLButtonElement>( | 136 | tabs.querySelector<HTMLButtonElement>( |
| 117 | '.plugin-tabs--tab[aria-selected="true"]' | 137 | '.plugin-tabs--tab[aria-selected="true"][data-tab-anchor]' |
| 118 | ) | 138 | )?.dataset.tabAnchor |
| 119 | const panelId = selectedTab?.getAttribute('aria-controls') | 139 | |
| 120 | const panel = panelId | 140 | const getPanelForTabButton = (button: HTMLButtonElement) => { |
| 121 | ? document.getElementById(panelId) | 141 | const panelId = button.getAttribute('aria-controls') |
| 122 | : tabs.querySelector<HTMLElement>('.plugin-tabs--content') | 142 | return panelId ? document.getElementById(panelId) : undefined |
| 123 | const heading = panel?.querySelector<HTMLElement>('.tab-search-heading') | 143 | } |
| 144 | |||
| 145 | const 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 | } | ||
| 124 | 156 | ||
| 125 | return heading ? getHeadingAnchor(heading) : undefined | 157 | return groups |
| 158 | .map((group) => getSelectedTabAnchor(group)) | ||
| 159 | .filter((tab): tab is string => Boolean(tab)) | ||
| 126 | } | 160 | } |
| 127 | 161 | ||
| 128 | const updateHashForSelectedTab = async (tabs: HTMLElement) => { | 162 | const updateQueryForSelectedTab = async (tabs: HTMLElement) => { |
| 129 | await nextTick() | 163 | await nextTick() |
| 130 | await nextFrame() | 164 | await nextFrame() |
| 131 | 165 | ||
| 132 | const anchor = getSelectedTabHeadingAnchor(tabs) | 166 | const tabPath = getTabPathForGroup(tabs) |
| 133 | if (!anchor || window.location.hash.slice(1) === anchor) return | 167 | if (!tabPath.length) return |
| 134 | 168 | ||
| 135 | window.history.pushState( | 169 | const nextUrl = buildUrlWithTabs(tabPath) |
| 136 | null, | 170 | const currentUrl = |
| 137 | '', | 171 | `${window.location.pathname}${window.location.search}${window.location.hash}` |
| 138 | `${window.location.pathname}${window.location.search}#${anchor}` | 172 | if (nextUrl === currentUrl) return |
| 139 | ) | 173 | |
| 174 | window.history.pushState(null, '', nextUrl) | ||
| 140 | } | 175 | } |
| 141 | 176 | ||
| 142 | const queueHashUpdateForTabSelection = (target: EventTarget | null) => { | 177 | const queueTabQueryUpdateForSelection = (target: EventTarget | null) => { |
| 143 | if (!(target instanceof HTMLElement)) return | 178 | if (!(target instanceof HTMLElement)) return |
| 144 | 179 | ||
| 145 | const button = target.closest<HTMLButtonElement>( | 180 | const button = target.closest<HTMLButtonElement>( |
| 146 | '.plugin-tabs--tab[role="tab"]' | 181 | '.plugin-tabs--tab[role="tab"]' |
| 147 | ) | 182 | ) |
| 148 | const tabs = button?.closest<HTMLElement>('.plugin-tabs') | 183 | const tabs = button?.closest<HTMLElement>('.plugin-tabs') |
| 149 | if (tabs) void updateHashForSelectedTab(tabs) | 184 | if (tabs) void updateQueryForSelectedTab(tabs) |
| 150 | } | ||
| 151 | |||
| 152 | const 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 | }) | ||
| 168 | } | 185 | } |
| 169 | 186 | ||
| 170 | const selectTabContainingAnchor = async (hash: string) => { | 187 | const selectTabsByPath = async (tabPath: string[]) => { |
| 171 | const tabsList = document.querySelectorAll<HTMLElement>('.plugin-tabs') | 188 | let root: ParentNode = document |
| 189 | let selectedTabs: HTMLElement | undefined | ||
| 172 | 190 | ||
| 173 | for (let i = 0, len = tabsList.length; i < len; i++) { | 191 | for (const anchor of tabPath) { |
| 174 | const tabs = tabsList[i] | 192 | const button = root.querySelector<HTMLButtonElement>( |
| 175 | const selectedTab = tabs.querySelector<HTMLButtonElement>( | 193 | `.plugin-tabs--tab[role="tab"][data-tab-anchor="${CSS.escape(anchor)}"]` |
| 176 | '.plugin-tabs--tab[aria-selected="true"]' | ||
| 177 | ) | ||
| 178 | const buttons = tabs.querySelectorAll<HTMLButtonElement>( | ||
| 179 | '.plugin-tabs--tab[role="tab"]' | ||
| 180 | ) | 194 | ) |
| 195 | if (!button) return selectedTabs | ||
| 196 | |||
| 197 | const tabs = button.closest<HTMLElement>('.plugin-tabs') | ||
| 198 | if (!tabs) return selectedTabs | ||
| 181 | 199 | ||
| 182 | for (let j = 0, buttonsLen = buttons.length; j < buttonsLen; j++) { | 200 | selectedTabs = tabs |
| 183 | buttons[j].click() | 201 | if (button.getAttribute('aria-selected') !== 'true') { |
| 202 | button.click() | ||
| 184 | await nextTick() | 203 | await nextTick() |
| 185 | await nextFrame() | 204 | await nextFrame() |
| 186 | |||
| 187 | const target = getTargetByHash(hash) | ||
| 188 | if (target) return target | ||
| 189 | } | 205 | } |
| 190 | 206 | ||
| 191 | selectedTab?.click() | 207 | root = getPanelForTabButton(button) ?? tabs |
| 192 | await nextTick() | ||
| 193 | } | 208 | } |
| 194 | } | ||
| 195 | |||
| 196 | const getTabsInSearchScope = (target: HTMLElement) => { | ||
| 197 | const tabs = new Set<HTMLElement>() | ||
| 198 | const closestTabs = target.closest<HTMLElement>('.plugin-tabs') | ||
| 199 | if (closestTabs) tabs.add(closestTabs) | ||
| 200 | 209 | ||
| 201 | const tagName = target.tagName | 210 | return selectedTabs |
| 202 | if (tagName.length === 2 && tagName[0] === 'H') { | 211 | } |
| 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 | ||
| 213 | 212 | ||
| 214 | if (sibling.matches('.plugin-tabs')) tabs.add(sibling as HTMLElement) | 213 | const selectLegacyTabHash = async (hash: string) => { |
| 215 | sibling.querySelectorAll<HTMLElement>('.plugin-tabs').forEach((tab) => { | 214 | const button = document.querySelector<HTMLButtonElement>( |
| 216 | tabs.add(tab) | 215 | `.plugin-tabs--tab[role="tab"][data-tab-anchor="${CSS.escape(hash)}"]` |
| 217 | }) | 216 | ) |
| 217 | if (!button) return | ||
| 218 | 218 | ||
| 219 | sibling = sibling.nextElementSibling | 219 | if (button.getAttribute('aria-selected') !== 'true') { |
| 220 | } | 220 | button.click() |
| 221 | } | 221 | await nextTick() |
| 222 | await nextFrame() | ||
| 222 | } | 223 | } |
| 223 | 224 | ||
| 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 | ||
| 225 | } | 230 | } |
| 226 | 231 | ||
| 227 | const selectTabContainingQuery = async (target: HTMLElement, query: string) => { | 232 | const getSelectedTabScrollTarget = (tabs: HTMLElement) => { |
| 228 | const terms = getSearchTerms(query) | 233 | const selectedTab = tabs.querySelector<HTMLButtonElement>( |
| 229 | if (!terms.length) return | 234 | '.plugin-tabs--tab[aria-selected="true"]' |
| 230 | 235 | ) | |
| 231 | for (const tabs of getTabsInSearchScope(target)) { | 236 | return selectedTab ? getPanelForTabButton(selectedTab) ?? tabs : tabs |
| 232 | const selectedTab = tabs.querySelector<HTMLButtonElement>( | 237 | } |
| 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 | } | ||
| 253 | 238 | ||
| 254 | selectedTab?.click() | 239 | const scrollToElement = (target: HTMLElement, smooth = true) => { |
| 255 | await nextTick() | 240 | requestAnimationFrame(() => { |
| 256 | } | 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 | }) | ||
| 257 | } | 255 | } |
| 258 | 256 | ||
| 259 | const openCollapsibles = async (target: HTMLElement) => { | 257 | const openCollapsibles = async (target: HTMLElement) => { |
| 260 | await selectTabContainingQuery(target, searchQuery) | 258 | const activeTarget = target |
| 261 | await nextTick() | ||
| 262 | await nextFrame() | ||
| 263 | |||
| 264 | const hashTarget = getTargetByHash(window.location.hash.slice(1)) | ||
| 265 | const activeTarget = hashTarget ?? target | ||
| 266 | let scrollTarget = getScrollTargetForAnchor(activeTarget) | 259 | let scrollTarget = getScrollTargetForAnchor(activeTarget) |
| 267 | let el: HTMLElement | null = activeTarget | 260 | let el: HTMLElement | null = activeTarget |
| 268 | 261 | ||
| @@ -329,18 +322,29 @@ const tryOpenAnchoredContent = async () => { | |||
| 329 | await nextTick() | 322 | await nextTick() |
| 330 | await nextFrame() | 323 | await nextFrame() |
| 331 | 324 | ||
| 325 | const requestedTabs = getRequestedTabPath() | ||
| 326 | const selectedTabs = requestedTabs.length | ||
| 327 | ? await selectTabsByPath(requestedTabs) | ||
| 328 | : undefined | ||
| 332 | const hash = window.location.hash.slice(1) | 329 | const hash = window.location.hash.slice(1) |
| 330 | |||
| 333 | if (!hash) { | 331 | if (!hash) { |
| 334 | resetSearchNavigation() | 332 | resetSearchNavigation() |
| 333 | if (selectedTabs) { | ||
| 334 | scrollToElement(getSelectedTabScrollTarget(selectedTabs), false) | ||
| 335 | } | ||
| 335 | return | 336 | return |
| 336 | } | 337 | } |
| 337 | 338 | ||
| 338 | let target = getTargetByHash(hash) | 339 | let target = getTargetByHash(hash) |
| 339 | let selectedTabForHash = false | ||
| 340 | 340 | ||
| 341 | if (!target) { | 341 | if (!target && !requestedTabs.length) { |
| 342 | target = await selectTabContainingAnchor(hash) | 342 | const legacyTabs = await selectLegacyTabHash(hash) |
| 343 | selectedTabForHash = Boolean(target) | 343 | if (legacyTabs) { |
| 344 | resetSearchNavigation() | ||
| 345 | scrollToElement(getSelectedTabScrollTarget(legacyTabs), false) | ||
| 346 | return | ||
| 347 | } | ||
| 344 | } | 348 | } |
| 345 | 349 | ||
| 346 | if (!target) { | 350 | if (!target) { |
| @@ -355,7 +359,20 @@ const tryOpenAnchoredContent = async () => { | |||
| 355 | } | 359 | } |
| 356 | 360 | ||
| 357 | if ( | 361 | 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 || | ||
| 359 | target.classList.contains('tab-search-heading') | 376 | target.classList.contains('tab-search-heading') |
| 360 | ) { | 377 | ) { |
| 361 | scrollToElement(getScrollTargetForAnchor(target), false) | 378 | scrollToElement(getScrollTargetForAnchor(target), false) |
| @@ -364,6 +381,7 @@ const tryOpenAnchoredContent = async () => { | |||
| 364 | 381 | ||
| 365 | onMounted(tryOpenAnchoredContent) | 382 | onMounted(tryOpenAnchoredContent) |
| 366 | watch(() => route.data, tryOpenAnchoredContent, { flush: 'post' }) | 383 | watch(() => route.data, tryOpenAnchoredContent, { flush: 'post' }) |
| 384 | watch(() => route.query, tryOpenAnchoredContent, { flush: 'post' }) | ||
| 367 | watch(() => route.hash, tryOpenAnchoredContent, { flush: 'post' }) | 385 | watch(() => route.hash, tryOpenAnchoredContent, { flush: 'post' }) |
| 368 | 386 | ||
| 369 | function onSidebarEnter() { | 387 | function onSidebarEnter() { |
| @@ -559,7 +577,7 @@ onMounted(() => { | |||
| 559 | 577 | ||
| 560 | useEventListener(document, 'click', (e: MouseEvent) => { | 578 | useEventListener(document, 'click', (e: MouseEvent) => { |
| 561 | if (!e.isTrusted) return | 579 | if (!e.isTrusted) return |
| 562 | queueHashUpdateForTabSelection(e.target) | 580 | queueTabQueryUpdateForSelection(e.target) |
| 563 | }) | 581 | }) |
| 564 | 582 | ||
| 565 | useEventListener(document, 'keydown', (e: KeyboardEvent) => { | 583 | useEventListener(document, 'keydown', (e: KeyboardEvent) => { |
| @@ -567,7 +585,7 @@ onMounted(() => { | |||
| 567 | return | 585 | return |
| 568 | } | 586 | } |
| 569 | 587 | ||
| 570 | queueHashUpdateForTabSelection(e.target) | 588 | queueTabQueryUpdateForSelection(e.target) |
| 571 | }) | 589 | }) |
| 572 | 590 | ||
| 573 | onUnmounted(() => { | 591 | onUnmounted(() => { |
docs/.vitepress/theme/components/Search.vue +28 −56
| @@ -48,13 +48,13 @@ import { | |||
| 48 | TextAlignStart | 48 | TextAlignStart |
| 49 | } from 'lucide-vue-next' | 49 | } from 'lucide-vue-next' |
| 50 | import Mark from 'mark.js/dist/mark.es6.js' | 50 | import Mark from 'mark.js/dist/mark.es6.js' |
| 51 | import { enhanceAppWithTabs } from 'vitepress-plugin-tabs/client' | ||
| 52 | import { sidebar } from '../../configs/constants' | 51 | import { sidebar } from '../../configs/constants' |
| 53 | import type { PageLink } from '../../plugins/urlSearchPlugin' | 52 | import type { PageLink } from '../../plugins/urlSearchPlugin' |
| 54 | import { LRUCache } from '../composables/search/lru-cache' | 53 | import { LRUCache } from '../composables/search/lru-cache' |
| 55 | import { createSearchTranslate } from '../composables/search/translation' | 54 | import { createSearchTranslate } from '../composables/search/translation' |
| 56 | import { useData } from '../composables/search/use-data' | 55 | import { useData } from '../composables/search/use-data' |
| 57 | import { LowEndDeviceModeStorageKey } from '../constants' | 56 | import { LowEndDeviceModeStorageKey } from '../constants' |
| 57 | import { enhanceAppWithTabs } from './tabs' | ||
| 58 | 58 | ||
| 59 | export interface FooterTranslations { | 59 | export interface FooterTranslations { |
| 60 | selectText?: string | 60 | selectText?: string |
| @@ -81,6 +81,7 @@ const resultsEl = shallowRef<HTMLElement>() | |||
| 81 | 81 | ||
| 82 | /* Search */ | 82 | /* Search */ |
| 83 | interface Result { | 83 | interface Result { |
| 84 | tabs?: string[] | ||
| 84 | title: string | 85 | title: string |
| 85 | titles: string[] | 86 | titles: string[] |
| 86 | text?: string | 87 | text?: string |
| @@ -280,6 +281,7 @@ const urlMatches = shallowRef<PageLink[]>([]) | |||
| 280 | const urlPageGroupCounts = shallowRef<PageGroupCount[]>([]) | 281 | const urlPageGroupCounts = shallowRef<PageGroupCount[]>([]) |
| 281 | 282 | ||
| 282 | interface UrlResult { | 283 | interface UrlResult { |
| 284 | tabs?: string[] | ||
| 283 | href: string | 285 | href: string |
| 284 | linkText: string | 286 | linkText: string |
| 285 | pageId: string | 287 | pageId: string |
| @@ -340,6 +342,7 @@ const filteredUrlResults = computed((): UrlResult[] => { | |||
| 340 | pageId: link.pageId, | 342 | pageId: link.pageId, |
| 341 | anchor: link.anchor, | 343 | anchor: link.anchor, |
| 342 | titles: link.titles, | 344 | titles: link.titles, |
| 345 | tabs: link.tabs, | ||
| 343 | highlighted: highlightUrl(link.href, query) | 346 | highlighted: highlightUrl(link.href, query) |
| 344 | }) | 347 | }) |
| 345 | } | 348 | } |
| @@ -969,7 +972,7 @@ function buildDocExcerpt( | |||
| 969 | const map = new Map<string, string>() | 972 | const map = new Map<string, string>() |
| 970 | const app = createApp(comp) | 973 | const app = createApp(comp) |
| 971 | app.config.warnHandler = () => {} | 974 | app.config.warnHandler = () => {} |
| 972 | enhanceAppWithTabs(app) | 975 | enhanceAppWithTabs(app, { renderAll: true }) |
| 973 | app.provide(dataSymbol, vitePressData) | 976 | app.provide(dataSymbol, vitePressData) |
| 974 | Object.defineProperties(app.config.globalProperties, { | 977 | Object.defineProperties(app.config.globalProperties, { |
| 975 | $frontmatter: { | 978 | $frontmatter: { |
| @@ -986,7 +989,6 @@ function buildDocExcerpt( | |||
| 986 | const div = document.createElement('div') | 989 | const div = document.createElement('div') |
| 987 | try { | 990 | try { |
| 988 | app.mount(div) | 991 | app.mount(div) |
| 989 | await selectExcerptTabs(div, filterTextValue) | ||
| 990 | const headings = div.querySelectorAll('h1, h2, h3, h4, h5, h6') | 992 | const headings = div.querySelectorAll('h1, h2, h3, h4, h5, h6') |
| 991 | headings.forEach((heading) => { | 993 | headings.forEach((heading) => { |
| 992 | const href = heading.querySelector('a')?.getAttribute('href') | 994 | const href = heading.querySelector('a')?.getAttribute('href') |
| @@ -1298,13 +1300,6 @@ async function fetchExcerpt(id: string) { | |||
| 1298 | const nextFrame = () => | 1300 | const nextFrame = () => |
| 1299 | new Promise<void>((resolve) => requestAnimationFrame(() => resolve())) | 1301 | new Promise<void>((resolve) => requestAnimationFrame(() => resolve())) |
| 1300 | 1302 | ||
| 1301 | const getSearchTerms = (query: string) => | ||
| 1302 | query | ||
| 1303 | .toLowerCase() | ||
| 1304 | .split(/\s+/) | ||
| 1305 | .map((term) => term.trim()) | ||
| 1306 | .filter(Boolean) | ||
| 1307 | |||
| 1308 | function hasExcerptPreview(html?: string) { | 1303 | function hasExcerptPreview(html?: string) { |
| 1309 | if (!html) return false | 1304 | if (!html) return false |
| 1310 | return Boolean( | 1305 | return Boolean( |
| @@ -1316,48 +1311,6 @@ function hasExcerptPreview(html?: string) { | |||
| 1316 | ) | 1311 | ) |
| 1317 | } | 1312 | } |
| 1318 | 1313 | ||
| 1319 | async 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 | |||
| 1361 | /* Search input focus */ | 1314 | /* Search input focus */ |
| 1362 | 1315 | ||
| 1363 | const searchInput = ref<HTMLInputElement>() | 1316 | const searchInput = ref<HTMLInputElement>() |
| @@ -1487,12 +1440,31 @@ onKeyStroke('Tab', (event) => { | |||
| 1487 | 1440 | ||
| 1488 | const router = useRouter() | 1441 | const router = useRouter() |
| 1489 | 1442 | ||
| 1443 | function 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 | |||
| 1451 | function 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 | |||
| 1490 | function navigateToUrlResult(item: UrlResult) { | 1463 | function navigateToUrlResult(item: UrlResult) { |
| 1491 | window.dispatchEvent( | 1464 | window.dispatchEvent( |
| 1492 | new CustomEvent('search-nav', { detail: { query: filterText.value } }) | 1465 | new CustomEvent('search-nav', { detail: { query: filterText.value } }) |
| 1493 | ) | 1466 | ) |
| 1494 | const dest = item.anchor ? item.pageId + '#' + item.anchor : item.pageId | 1467 | router.go(buildResultHref(item.pageId, item.tabs, item.anchor)) |
| 1495 | router.go(dest) | ||
| 1496 | showSearch.value = false | 1468 | showSearch.value = false |
| 1497 | } | 1469 | } |
| 1498 | 1470 | ||
| @@ -1533,7 +1505,7 @@ onKeyStroke('Enter', (e) => { | |||
| 1533 | detail: { query: filterText.value } | 1505 | detail: { query: filterText.value } |
| 1534 | }) | 1506 | }) |
| 1535 | ) | 1507 | ) |
| 1536 | router.go(selectedPackage.id) | 1508 | router.go(getSearchResultHref(selectedPackage)) |
| 1537 | showSearch.value = false | 1509 | showSearch.value = false |
| 1538 | } | 1510 | } |
| 1539 | }) | 1511 | }) |
| @@ -1992,7 +1964,7 @@ function onMouseMove(e: MouseEvent) { | |||
| 1992 | v-bind="resultMotion(index)" | 1964 | v-bind="resultMotion(index)" |
| 1993 | > | 1965 | > |
| 1994 | <a | 1966 | <a |
| 1995 | :href="p.id" | 1967 | :href="getSearchResultHref(p)" |
| 1996 | class="result" | 1968 | class="result" |
| 1997 | :class="{ | 1969 | :class="{ |
| 1998 | selected: selectedIndex === index + 1 | 1970 | selected: selectedIndex === index + 1 |
docs/.vitepress/theme/components/tabs/PluginTabs.vue added +107
| @@ -0,0 +1,107 @@ | |||
| 1 | <script setup lang="ts"> | ||
| 2 | import { computed, ref, toRef, useId, useSlots } from 'vue' | ||
| 3 | import { useIsPrint, useStabilizeScrollPosition } from './composables' | ||
| 4 | import { provideTabsSingleState, useTabsSelectedState } from './state' | ||
| 5 | |||
| 6 | defineOptions({ name: 'PluginTabs' }) | ||
| 7 | |||
| 8 | const props = defineProps<{ sharedStateKey?: string }>() | ||
| 9 | |||
| 10 | interface TabItem { | ||
| 11 | anchor: string | ||
| 12 | label: string | ||
| 13 | } | ||
| 14 | |||
| 15 | const isPrint = useIsPrint() | ||
| 16 | const slots = useSlots() | ||
| 17 | const 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 | }) | ||
| 35 | const tabLabels = computed(() => tabItems.value.map((item) => item.label)) | ||
| 36 | const { selected, select } = useTabsSelectedState( | ||
| 37 | tabLabels, | ||
| 38 | toRef(props, 'sharedStateKey') | ||
| 39 | ) | ||
| 40 | const tablist = ref<HTMLElement>() | ||
| 41 | const { stabilizeScrollPosition } = useStabilizeScrollPosition(tablist) | ||
| 42 | const selectStable = stabilizeScrollPosition(select) | ||
| 43 | const buttonRefs = ref<HTMLButtonElement[]>([]) | ||
| 44 | const uid = useId() | ||
| 45 | |||
| 46 | provideTabsSingleState({ uid, selected }) | ||
| 47 | |||
| 48 | function getTabButtonId(item: TabItem) { | ||
| 49 | return `tab-${item.anchor}-${uid}` | ||
| 50 | } | ||
| 51 | |||
| 52 | function getTabPanelId(item: TabItem) { | ||
| 53 | return `panel-${item.anchor}-${uid}` | ||
| 54 | } | ||
| 55 | |||
| 56 | async 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"> | ||
| 2 | import { computed } from 'vue' | ||
| 3 | import { useIsPrint } from './composables' | ||
| 4 | import { useTabsRenderAll, useTabsSingleState } from './state' | ||
| 5 | |||
| 6 | defineOptions({ name: 'PluginTabsTab' }) | ||
| 7 | |||
| 8 | const props = defineProps<{ | ||
| 9 | anchor: string | ||
| 10 | label: string | ||
| 11 | }>() | ||
| 12 | |||
| 13 | const { selected, uid } = useTabsSingleState() | ||
| 14 | const isPrint = useIsPrint() | ||
| 15 | const renderAll = useTabsRenderAll() | ||
| 16 | const isActive = computed(() => | ||
| 17 | selected.value === props.label || Boolean(isPrint.value) || renderAll | ||
| 18 | ) | ||
| 19 | const panelId = computed(() => `panel-${props.anchor}-${uid}`) | ||
| 20 | const 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 @@ | |||
| 1 | import { nextTick, onBeforeMount, onUnmounted, type Ref, ref } from 'vue' | ||
| 2 | |||
| 3 | export 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 | |||
| 22 | export 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 @@ | |||
| 1 | import type { App } from 'vue' | ||
| 2 | import PluginTabs from './PluginTabs.vue' | ||
| 3 | import PluginTabsTab from './PluginTabsTab.vue' | ||
| 4 | import { provideTabsSharedState } from './state' | ||
| 5 | |||
| 6 | export interface EnhanceTabsOptions { | ||
| 7 | renderAll?: boolean | ||
| 8 | } | ||
| 9 | |||
| 10 | export 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 @@ | |||
| 1 | import type { App, ComputedRef, InjectionKey, Ref } from 'vue' | ||
| 2 | import { computed, inject, onMounted, provide, reactive, ref, watch } from 'vue' | ||
| 3 | |||
| 4 | const sharedStateKey: InjectionKey<{ content?: Record<string, string> }> = | ||
| 5 | Symbol('vitepress:tabSharedState') | ||
| 6 | const singleStateKey: InjectionKey<{ | ||
| 7 | selected: ComputedRef<string> | ||
| 8 | uid: string | ||
| 9 | }> = Symbol('vitepress:tabSingleState') | ||
| 10 | const renderAllKey: InjectionKey<boolean> = Symbol('wotaku:tabsRenderAll') | ||
| 11 | |||
| 12 | const localStorageKey = 'vitepress:tabsSharedState' | ||
| 13 | const ls = typeof localStorage !== 'undefined' ? localStorage : null | ||
| 14 | |||
| 15 | function 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 | |||
| 27 | function setLocalStorageValue(value: Record<string, string>) { | ||
| 28 | if (!ls) return | ||
| 29 | ls.setItem(localStorageKey, JSON.stringify(value)) | ||
| 30 | } | ||
| 31 | |||
| 32 | export 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 | |||
| 49 | export 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 | |||
| 97 | export function provideTabsSingleState(state: { | ||
| 98 | selected: ComputedRef<string> | ||
| 99 | uid: string | ||
| 100 | }) { | ||
| 101 | provide(singleStateKey, state) | ||
| 102 | } | ||
| 103 | |||
| 104 | export 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 | |||
| 112 | export function useTabsRenderAll() { | ||
| 113 | return inject(renderAllKey, false) | ||
| 114 | } | ||
docs/.vitepress/theme/index.ts +5 −5
| @@ -10,7 +10,6 @@ import DefaultTheme from 'vitepress/theme' | |||
| 10 | import './styles/style.scss' | 10 | import './styles/style.scss' |
| 11 | import { NolebasePagePropertiesPlugin } from '@nolebase/vitepress-plugin-page-properties/client' | 11 | import { NolebasePagePropertiesPlugin } from '@nolebase/vitepress-plugin-page-properties/client' |
| 12 | import FloatingVue from 'floating-vue' | 12 | import FloatingVue from 'floating-vue' |
| 13 | import { enhanceAppWithTabs } from 'vitepress-plugin-tabs/client' | ||
| 14 | import '@nolebase/vitepress-plugin-enhanced-readabilities/client/style.css' | 13 | import '@nolebase/vitepress-plugin-enhanced-readabilities/client/style.css' |
| 15 | import '@nolebase/vitepress-plugin-page-properties/client/style.css' | 14 | import '@nolebase/vitepress-plugin-page-properties/client/style.css' |
| 16 | import 'floating-vue/dist/style.css' | 15 | import 'floating-vue/dist/style.css' |
| @@ -18,16 +17,17 @@ import Authors from './components/Authors.vue' | |||
| 18 | import Tooltip from './components/Tooltip.vue' | 17 | import Tooltip from './components/Tooltip.vue' |
| 19 | import { createMediumZoomProvider } from './composables/medium-zoom' | 18 | import { createMediumZoomProvider } from './composables/medium-zoom' |
| 20 | import 'virtual:uno.css' | 19 | import 'virtual:uno.css' |
| 21 | import Feedback from './components/Feedback.vue' | ||
| 22 | import Fb from './components/Fb.vue' | ||
| 23 | import Collapsible from './components/Collapsible.vue' | 20 | import Collapsible from './components/Collapsible.vue' |
| 21 | import Fb from './components/Fb.vue' | ||
| 22 | import Feedback from './components/Feedback.vue' | ||
| 24 | import ScrapeTable from './components/ScrapeTable.vue' | 23 | import ScrapeTable from './components/ScrapeTable.vue' |
| 25 | import Layout from './Layout.vue' | 24 | import Layout from './Layout.vue' |
| 26 | import './styles/tooltip-hint.css' | 25 | import './styles/tooltip-hint.css' |
| 27 | import './styles/steps.css' | 26 | import './styles/steps.css' |
| 28 | import Block from './components/Block.vue' | 27 | import Block from './components/Block.vue' |
| 29 | import LinkInline from './components/LinkInline.vue' | ||
| 30 | import Highlight from './components/Highlight.vue' | 28 | import Highlight from './components/Highlight.vue' |
| 29 | import LinkInline from './components/LinkInline.vue' | ||
| 30 | import { enhanceAppWithTabs } from './components/tabs' | ||
| 31 | 31 | ||
| 32 | export default { | 32 | export default { |
| 33 | extends: DefaultTheme, | 33 | extends: DefaultTheme, |
| @@ -107,4 +107,4 @@ export default { | |||
| 107 | ] | 107 | ] |
| 108 | ) | 108 | ) |
| 109 | } | 109 | } |
| 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 { | |||
| 1649 | border-top: none !important; | 1649 | border-top: none !important; |
| 1650 | } | 1650 | } |
| 1651 | 1651 | ||
| 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 | |||
| 1652 | .vp-doc .collapsible-search-heading, | 1745 | .vp-doc .collapsible-search-heading, |
| 1653 | .vp-doc .tab-search-heading { | 1746 | .vp-doc .tab-search-heading { |
| 1654 | position: absolute; | 1747 | position: absolute; |
docs/.vitepress/theme/workers/searchWorker.ts +77 −6
| @@ -4,9 +4,10 @@ import MiniSearch, { | |||
| 4 | type SearchResult | 4 | type SearchResult |
| 5 | } from 'minisearch' | 5 | } from 'minisearch' |
| 6 | 6 | ||
| 7 | import type { PageLink } from '../../plugins/urlSearchPlugin' | 7 | import type { PageLink, TabTarget } from '../../plugins/urlSearchPlugin' |
| 8 | 8 | ||
| 9 | interface Result { | 9 | interface Result { |
| 10 | tabs?: string[] | ||
| 10 | title: string | 11 | title: string |
| 11 | titles: string[] | 12 | titles: string[] |
| 12 | text?: string | 13 | text?: string |
| @@ -63,6 +64,8 @@ let searchIndexKey = '' | |||
| 63 | let urlLinks: PageLink[] = [] | 64 | let urlLinks: PageLink[] = [] |
| 64 | let urlLinkHrefsLower: string[] = [] | 65 | let urlLinkHrefsLower: string[] = [] |
| 65 | let urlLinksPromise: Promise<void> | null = null | 66 | let urlLinksPromise: Promise<void> | null = null |
| 67 | let tabTargetMap = new Map<string, string[]>() | ||
| 68 | let tabTargetsPromise: Promise<void> | null = null | ||
| 66 | let pageOrder = new Map<string, number>() | 69 | let pageOrder = new Map<string, number>() |
| 67 | let docOrder = new Map<string, number>() | 70 | let docOrder = new Map<string, number>() |
| 68 | 71 | ||
| @@ -100,6 +103,20 @@ function getPageKey(id: string) { | |||
| 100 | return id.split('#')[0].replace(/\/$/, '') | 103 | return id.split('#')[0].replace(/\/$/, '') |
| 101 | } | 104 | } |
| 102 | 105 | ||
| 106 | function getAnchorKey(pageId: string, anchor: string) { | ||
| 107 | return `${pageId.replace(/\/$/, '')}\x00${anchor}` | ||
| 108 | } | ||
| 109 | |||
| 110 | function 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 | |||
| 103 | function getPageOrder(key: string) { | 120 | function getPageOrder(key: string) { |
| 104 | return pageOrder.get(key) ?? Number.MAX_SAFE_INTEGER | 121 | return pageOrder.get(key) ?? Number.MAX_SAFE_INTEGER |
| 105 | } | 122 | } |
| @@ -164,11 +181,28 @@ function withLinkPathTitles( | |||
| 164 | return { | 181 | return { |
| 165 | ...result, | 182 | ...result, |
| 166 | title: stripMarkdown(link.linkText), | 183 | title: stripMarkdown(link.linkText), |
| 167 | titles: link.titles | 184 | titles: link.titles, |
| 185 | ...(link.tabs?.length ? { tabs: link.tabs } : {}) | ||
| 168 | } | 186 | } |
| 169 | }) | 187 | }) |
| 170 | } | 188 | } |
| 171 | 189 | ||
| 190 | function 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 | |||
| 197 | function 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 | |||
| 172 | function rebuildDocOrder(index: MiniSearch<Result>) { | 206 | function rebuildDocOrder(index: MiniSearch<Result>) { |
| 173 | const map = new Map<string, number>() | 207 | const map = new Map<string, number>() |
| 174 | const ids = (index as any)._documentIds | 208 | const ids = (index as any)._documentIds |
| @@ -243,8 +277,10 @@ async function textSearch(message: TextSearchRequest) { | |||
| 243 | (r) => !seen.has(r.id) && r.match && Object.keys(r.match).length > 0 | 277 | (r) => !seen.has(r.id) && r.match && Object.keys(r.match).length > 0 |
| 244 | ) | 278 | ) |
| 245 | const results = [...top, ...titleHits].sort(compareByPageAndDoc) | 279 | const results = [...top, ...titleHits].sort(compareByPageAndDoc) |
| 246 | await ensureUrlLinks() | 280 | await ensureSearchMetadata() |
| 247 | const displayResults = withLinkPathTitles(results, message.query) | 281 | const displayResults = withTabMetadata( |
| 282 | withLinkPathTitles(results, message.query) | ||
| 283 | ) | ||
| 248 | const terms = new Set<string>() | 284 | const terms = new Set<string>() |
| 249 | for (const result of displayResults) { | 285 | for (const result of displayResults) { |
| 250 | for (const term in result.match) terms.add(term) | 286 | for (const term in result.match) terms.add(term) |
| @@ -280,9 +316,39 @@ async function ensureUrlLinks() { | |||
| 280 | await urlLinksPromise | 316 | await urlLinksPromise |
| 281 | } | 317 | } |
| 282 | 318 | ||
| 319 | async 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 | |||
| 345 | async function ensureSearchMetadata() { | ||
| 346 | await Promise.all([ensureUrlLinks(), ensureTabTargets()]) | ||
| 347 | } | ||
| 348 | |||
| 283 | async function urlSearch(message: UrlSearchRequest) { | 349 | async function urlSearch(message: UrlSearchRequest) { |
| 284 | setPageOrder(message.pageOrderEntries) | 350 | setPageOrder(message.pageOrderEntries) |
| 285 | await ensureUrlLinks() | 351 | await ensureSearchMetadata() |
| 286 | 352 | ||
| 287 | const query = message.query.trim().toLowerCase() | 353 | const query = message.query.trim().toLowerCase() |
| 288 | if (!query) return { matches: [], pageGroups: [] } | 354 | if (!query) return { matches: [], pageGroups: [] } |
| @@ -294,7 +360,12 @@ async function urlSearch(message: UrlSearchRequest) { | |||
| 294 | 360 | ||
| 295 | const link = urlLinks[i] | 361 | const link = urlLinks[i] |
| 296 | 362 | ||
| 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 | } | ||
| 298 | const existing = pageGroups.get(link.pageId) | 369 | const existing = pageGroups.get(link.pageId) |
| 299 | if (existing) existing.count++ | 370 | if (existing) existing.count++ |
| 300 | else pageGroups.set(link.pageId, { key: link.pageId, count: 1 }) | 371 | else pageGroups.set(link.pageId, { key: link.pageId, count: 1 }) |
docs/.vitepress/utils/tabAnchors.ts added +61
| @@ -0,0 +1,61 @@ | |||
| 1 | const rControl = /[\u0000-\u001f]/g | ||
| 2 | const rSpecial = /[\s~`!@#$%^&*()\-_+=[\]{}|\\;:"'“”‘’<>,.?/]+/g | ||
| 3 | const rCombining = /[\u0300-\u036F]/g | ||
| 4 | |||
| 5 | export interface ParsedTabLabel { | ||
| 6 | anchor?: string | ||
| 7 | label: string | ||
| 8 | } | ||
| 9 | |||
| 10 | export 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 | |||
| 20 | export 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 | |||
| 32 | export 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 | |||
| 43 | export 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 | |||
| 51 | export 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 | |||
| 59 | export function getTabHeadingAnchor(tabAnchor: string) { | ||
| 60 | return `tab-${tabAnchor}` | ||
| 61 | } | ||
package.json −1
| @@ -50,7 +50,6 @@ | |||
| 50 | "vite": "^7.2.2", | 50 | "vite": "^7.2.2", |
| 51 | "vite-plugin-virtual": "^0.4.0", | 51 | "vite-plugin-virtual": "^0.4.0", |
| 52 | "vitepress": "2.0.0-alpha.12", | 52 | "vitepress": "2.0.0-alpha.12", |
| 53 | "vitepress-plugin-tabs": "^0.7.3", | ||
| 54 | "vue": "^3.5.24", | 53 | "vue": "^3.5.24", |
| 55 | "zod": "^4.1.11" | 54 | "zod": "^4.1.11" |
| 56 | }, | 55 | }, |
pnpm-lock.yaml −19
| @@ -119,9 +119,6 @@ importers: | |||
| 119 | vitepress: | 119 | vitepress: |
| 120 | specifier: 2.0.0-alpha.12 | 120 | specifier: 2.0.0-alpha.12 |
| 121 | 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) | 121 | 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)) | ||
| 125 | vue: | 122 | vue: |
| 126 | specifier: ^3.5.24 | 123 | specifier: ^3.5.24 |
| 127 | version: 3.5.24(typescript@5.6.3) | 124 | version: 3.5.24(typescript@5.6.3) |
| @@ -3582,12 +3579,6 @@ packages: | |||
| 3582 | yaml: | 3579 | yaml: |
| 3583 | optional: true | 3580 | optional: true |
| 3584 | 3581 | ||
| 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 | |||
| 3591 | vitepress@2.0.0-alpha.12: | 3582 | vitepress@2.0.0-alpha.12: |
| 3592 | resolution: {integrity: sha512-yZwCwRRepcpN5QeAhwSnEJxS3I6zJcVixqL1dnm6km4cnriLpQyy2sXQDsE5Ti3pxGPbhU51nTMwI+XC1KNnJg==} | 3583 | resolution: {integrity: sha512-yZwCwRRepcpN5QeAhwSnEJxS3I6zJcVixqL1dnm6km4cnriLpQyy2sXQDsE5Ti3pxGPbhU51nTMwI+XC1KNnJg==} |
| 3593 | hasBin: true | 3584 | hasBin: true |
| @@ -3603,9 +3594,6 @@ packages: | |||
| 3603 | postcss: | 3594 | postcss: |
| 3604 | optional: true | 3595 | optional: true |
| 3605 | 3596 | ||
| 3606 | vscode-uri@3.1.0: | ||
| 3607 | resolution: {integrity: sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ==} | ||
| 3608 | |||
| 3609 | vue-demi@0.14.10: | 3597 | vue-demi@0.14.10: |
| 3610 | resolution: {integrity: sha512-nMZBOwuzabUO0nLgIcc6rycZEebF6eeUfaiQx9+WSk8e29IbLvPU9feI6tqW4kTo3hvoYAJkMh8n8D0fuISphg==} | 3598 | resolution: {integrity: sha512-nMZBOwuzabUO0nLgIcc6rycZEebF6eeUfaiQx9+WSk8e29IbLvPU9feI6tqW4kTo3hvoYAJkMh8n8D0fuISphg==} |
| 3611 | engines: {node: '>=12'} | 3599 | engines: {node: '>=12'} |
| @@ -7073,11 +7061,6 @@ snapshots: | |||
| 7073 | sass: 1.93.3 | 7061 | sass: 1.93.3 |
| 7074 | terser: 5.44.1 | 7062 | terser: 5.44.1 |
| 7075 | 7063 | ||
| 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 | |||
| 7081 | 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): | 7064 | 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): |
| 7082 | dependencies: | 7065 | dependencies: |
| 7083 | '@docsearch/css': 4.3.1 | 7066 | '@docsearch/css': 4.3.1 |
| @@ -7126,8 +7109,6 @@ snapshots: | |||
| 7126 | - universal-cookie | 7109 | - universal-cookie |
| 7127 | - yaml | 7110 | - yaml |
| 7128 | 7111 | ||
| 7129 | vscode-uri@3.1.0: {} | ||
| 7130 | |||
| 7131 | vue-demi@0.14.10(vue@3.5.24(typescript@5.6.3)): | 7112 | vue-demi@0.14.10(vue@3.5.24(typescript@5.6.3)): |
| 7132 | dependencies: | 7113 | dependencies: |
| 7133 | vue: 3.5.24(typescript@5.6.3) | 7114 | vue: 3.5.24(typescript@5.6.3) |