Commit 2e0bd5e0a1

2e0bd5e0a1db9938b01543ddc7fe7e38811cb54e

parent: c8bed61516

Unsigned

taskylizard <75871323+taskylizard@users.noreply.github.com> · 2026-06-08 19:49 UTC

search tabs linking

Layout: unified · split

docs/.vitepress/configs/markdown/index.ts +85 −3
@@ -98,10 +98,10 @@ function span(
98function renderHighlight(md: MarkdownRenderer) { 98function renderHighlight(md: MarkdownRenderer) {
99 const original = md.render.bind(md) 99 const original = md.render.bind(md)
100 md.render = (src, env) => { 100 md.render = (src, env) => {
101 const withCollapsibleHeadings = injectCollapsibleSearchHeadings(src) 101 const withSearchHeadings = injectSearchHeadings(src)
102 102
103 // Replace [||text||](url) — linked pill 103 // Replace [||text||](url) — linked pill
104 let replaced = withCollapsibleHeadings.replace( 104 let replaced = withSearchHeadings.replace(
105 /\[([!x]?)\|\|(.+?)\|\|\]\((.+?)\)/g, 105 /\[([!x]?)\|\|(.+?)\|\|\]\((.+?)\)/g,
106 (_, prefix, cont, url) => { 106 (_, prefix, cont, url) => {
107 const variant = prefix === '!' 107 const variant = prefix === '!'
@@ -126,10 +126,92 @@ function renderHighlight(md: MarkdownRenderer) {
126 } 126 }
127} 127}
128 128
129function injectCollapsibleSearchHeadings(src: string) { 129interface SearchHeading {
130 level: number
131 title: string
132}
133
134function getHeadingTitle(value: string) {
135 return value.replace(/\s+\{[^}]*\}\s*$/, '').trim()
136}
137
138function injectSearchHeadings(src: string) {
130 const lines = src.split('\n') 139 const lines = src.split('\n')
140 const containerStack: string[] = []
141 const headingStack: (SearchHeading | undefined)[] = []
142 const tabResetStack: (SearchHeading | undefined)[] = []
143 const getCurrentHeading = () => {
144 for (let i = headingStack.length - 1; i >= 0; i--) {
145 if (headingStack[i]) return headingStack[i]
146 }
147 }
148 const isHeadingLine = (line: string | undefined) =>
149 /^#{1,6}\s+/.test(line?.trim() ?? '')
131 150
132 for (let i = 0; i < lines.length; i++) { 151 for (let i = 0; i < lines.length; i++) {
152 const headingMatch = lines[i].match(/^(#{1,6})\s+(.+)/)
153 if (headingMatch && !containerStack.includes('tabs')) {
154 const level = headingMatch[1].length
155 const title = getHeadingTitle(headingMatch[2])
156 if (title) {
157 headingStack[level - 1] = { level, title }
158 headingStack.length = level
159 }
160 }
161
162 const containerOpenMatch = lines[i].match(
163 /^\s*:{3,}\s*([A-Za-z][\w-]*)\b/
164 )
165 if (containerOpenMatch) {
166 const containerName = containerOpenMatch[1].toLowerCase()
167 containerStack.push(containerName)
168 if (containerName === 'tabs') tabResetStack.push(getCurrentHeading())
169 } else if (/^\s*:{3,}\s*$/.test(lines[i])) {
170 const closed = containerStack.pop()
171 if (closed === 'tabs') {
172 const resetHeading = tabResetStack.pop()
173 let nextLine = i + 1
174 while (nextLine < lines.length && lines[nextLine].trim() === '') {
175 nextLine++
176 }
177
178 if (
179 resetHeading && nextLine < lines.length &&
180 !isHeadingLine(lines[nextLine])
181 ) {
182 const indent = lines[i].match(/^(\s*):{3,}\s*$/)?.[1] ?? ''
183 lines.splice(
184 i + 1,
185 0,
186 '',
187 `${indent}${
188 '#'.repeat(resetHeading.level)
189 } ${resetHeading.title} {.tab-search-heading .ignore-header}`,
190 ''
191 )
192 i += 3
193 }
194 }
195 continue
196 }
197
198 const tabMatch = lines[i].match(/^(\s*)==\s+(.+)$/)
199 if (tabMatch && containerStack.includes('tabs')) {
200 const [, indent, title] = tabMatch
201 const headingTitle = title.trim()
202 if (!headingTitle) continue
203
204 lines.splice(
205 i + 1,
206 0,
207 '',
208 `${indent}### ${headingTitle} {.tab-search-heading .ignore-header}`,
209 ''
210 )
211 i += 3
212 continue
213 }
214
133 const match = lines[i].match( 215 const match = lines[i].match(
134 /^(\s*)<Collapsible\b(?=[^>]*\btitle=(['"])(.*?)\2)[^>]*>\s*$/i 216 /^(\s*)<Collapsible\b(?=[^>]*\btitle=(['"])(.*?)\2)[^>]*>\s*$/i
135 ) 217 )
docs/.vitepress/plugins/urlSearchPlugin.ts +20 −31
@@ -16,10 +16,6 @@ function extractLinksFromMarkdown(src: string, pageId: string): PageLink[] {
16 const headingStack: string[] = [] 16 const headingStack: string[] = []
17 const slugCounts = new Map<string, number>() 17 const slugCounts = new Map<string, number>()
18 const containerStack: string[] = [] 18 const containerStack: string[] = []
19 const tabStack: {
20 title: string
21 headings: string[]
22 }[] = []
23 const collapsibleStack: { 19 const collapsibleStack: {
24 anchor: string 20 anchor: string
25 headings: string[] 21 headings: string[]
@@ -32,7 +28,11 @@ function extractLinksFromMarkdown(src: string, pageId: string): PageLink[] {
32 : src 28 : src
33 const lines = body.split('\n') 29 const lines = body.split('\n')
34 30
35 const slugify = (value: string) => 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 36 value
37 .replace(/\{[^}]*\}\s*$/, '') 37 .replace(/\{[^}]*\}\s*$/, '')
38 .replace(/<[^>]*>/g, '') 38 .replace(/<[^>]*>/g, '')
@@ -40,11 +40,17 @@ function extractLinksFromMarkdown(src: string, pageId: string): PageLink[] {
40 .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1') 40 .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
41 .replace(/[*_~]/g, '') 41 .replace(/[*_~]/g, '')
42 .trim() 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')
43 .toLowerCase() 53 .toLowerCase()
44 .replace(/[^\w\s-]/g, '')
45 .replace(/\s+/g, '-')
46 .replace(/-+/g, '-')
47 .replace(/^-|-$/g, '')
48 54
49 const getAnchor = (text: string) => { 55 const getAnchor = (text: string) => {
50 const slug = slugify(text) 56 const slug = slugify(text)
@@ -59,19 +65,7 @@ function extractLinksFromMarkdown(src: string, pageId: string): PageLink[] {
59 currentAnchor = getAnchor(text) 65 currentAnchor = getAnchor(text)
60 } 66 }
61 67
62 const getActiveTab = () => 68 const getTitles = () => headingStack.filter(Boolean)
63 tabStack.length ? tabStack[tabStack.length - 1] : undefined
64
65 const getTitles = () => {
66 const tab = getActiveTab()
67 if (!tab) return headingStack.filter(Boolean)
68
69 const baseHeadings = tab.headings.filter(Boolean)
70 const nestedHeadings = headingStack
71 .slice(tab.headings.length)
72 .filter(Boolean)
73 return [...baseHeadings, tab.title, ...nestedHeadings]
74 }
75 69
76 for (let i = 0; i < lines.length; i++) { 70 for (let i = 0; i < lines.length; i++) {
77 const line = lines[i] 71 const line = lines[i]
@@ -80,21 +74,16 @@ function extractLinksFromMarkdown(src: string, pageId: string): PageLink[] {
80 if (containerOpenMatch) { 74 if (containerOpenMatch) {
81 containerStack.push(containerOpenMatch[1].toLowerCase()) 75 containerStack.push(containerOpenMatch[1].toLowerCase())
82 } else if (/^\s*:{3,}\s*$/.test(line)) { 76 } else if (/^\s*:{3,}\s*$/.test(line)) {
83 const closed = containerStack.pop() 77 containerStack.pop()
84 if (closed === 'tabs') tabStack.pop()
85 } 78 }
86 79
87 const tabMatch = line.match(/^\s*==\s+(.+)$/) 80 const tabMatch = line.match(/^\s*==\s+(.+)$/)
88 if (tabMatch && containerStack.includes('tabs')) { 81 if (tabMatch && containerStack.includes('tabs')) {
89 const title = tabMatch[1].trim() 82 const title = tabMatch[1].trim()
90 if (title) { 83 if (title) {
91 const tab = getActiveTab() 84 // The markdown renderer injects a hidden H3 for each tab label.
92 if (tab) { 85 // Mirror that heading so URL search deep-links to the selected tab.
93 tab.title = title 86 setHeading(2, title)
94 tab.headings = [...headingStack]
95 } else {
96 tabStack.push({ title, headings: [...headingStack] })
97 }
98 } 87 }
99 continue 88 continue
100 } 89 }
docs/.vitepress/theme/Layout.vue +112 −36
@@ -80,6 +80,73 @@ const getSearchTerms = (query: string) =>
80 .map((term) => term.trim()) 80 .map((term) => term.trim())
81 .filter(Boolean) 81 .filter(Boolean)
82 82
83const getTargetByHash = (hash: string) => {
84 const ids = [hash]
85 try {
86 const decoded = decodeURIComponent(hash)
87 if (decoded !== hash) ids.unshift(decoded)
88 } catch {
89 /* keep the raw hash */
90 }
91
92 for (const id of ids) {
93 const target = document.getElementById(id)
94 if (target) return target
95 }
96}
97
98const getScrollTargetForAnchor = (target: HTMLElement) => {
99 if (target.classList.contains('tab-search-heading')) {
100 return target.closest<HTMLElement>('.plugin-tabs') ?? target
101 }
102
103 return target
104}
105
106const scrollToElement = (target: HTMLElement, smooth = true) => {
107 requestAnimationFrame(() => {
108 requestAnimationFrame(() => {
109 const navBar = document.querySelector<HTMLElement>('.VPNavBar')
110 const navOffset = navBar ? navBar.offsetHeight : 0
111 window.scrollTo({
112 top: target.getBoundingClientRect().top + window.scrollY - navOffset,
113 behavior: smooth &&
114 !window.matchMedia('(prefers-reduced-motion: reduce)').matches
115 ? 'smooth'
116 : 'auto'
117 })
118 target.setAttribute('tabindex', '-1')
119 target.focus({ preventScroll: true })
120 })
121 })
122}
123
124const selectTabContainingAnchor = async (hash: string) => {
125 const tabsList = document.querySelectorAll<HTMLElement>('.plugin-tabs')
126
127 for (let i = 0, len = tabsList.length; i < len; i++) {
128 const tabs = tabsList[i]
129 const selectedTab = tabs.querySelector<HTMLButtonElement>(
130 '.plugin-tabs--tab[aria-selected="true"]'
131 )
132 const buttons = tabs.querySelectorAll<HTMLButtonElement>(
133 '.plugin-tabs--tab[role="tab"]'
134 )
135
136 for (let j = 0, buttonsLen = buttons.length; j < buttonsLen; j++) {
137 buttons[j].click()
138 await nextTick()
139 await nextFrame()
140
141 const target = getTargetByHash(hash)
142 if (target) return target
143 }
144
145 selectedTab?.click()
146 await nextTick()
147 }
148}
149
83const getTabsInSearchScope = (target: HTMLElement) => { 150const getTabsInSearchScope = (target: HTMLElement) => {
84 const tabs = new Set<HTMLElement>() 151 const tabs = new Set<HTMLElement>()
85 const closestTabs = target.closest<HTMLElement>('.plugin-tabs') 152 const closestTabs = target.closest<HTMLElement>('.plugin-tabs')
@@ -144,7 +211,7 @@ const selectTabContainingQuery = async (target: HTMLElement, query: string) => {
144} 211}
145 212
146const openCollapsibles = async (target: HTMLElement) => { 213const openCollapsibles = async (target: HTMLElement) => {
147 let scrollTarget = target 214 let scrollTarget = getScrollTargetForAnchor(target)
148 let el: HTMLElement | null = target 215 let el: HTMLElement | null = target
149 216
150 while ((el = el.closest('details'))) { 217 while ((el = el.closest('details'))) {
@@ -195,47 +262,54 @@ const openCollapsibles = async (target: HTMLElement) => {
195 262
196 await selectTabContainingQuery(target, searchQuery) 263 await selectTabContainingQuery(target, searchQuery)
197 264
198 requestAnimationFrame(() => { 265 scrollToElement(scrollTarget)
199 requestAnimationFrame(() => { 266}
200 const navBar = document.querySelector<HTMLElement>('.VPNavBar') 267
201 const navOffset = navBar ? navBar.offsetHeight : 0 268const resetSearchNavigation = () => {
202 window.scrollTo({ 269 searchNavigated = false
203 top: scrollTarget.getBoundingClientRect().top + window.scrollY - 270 searchQuery = ''
204 navOffset,
205 behavior: window.matchMedia('(prefers-reduced-motion: reduce)').matches
206 ? 'auto'
207 : 'smooth'
208 })
209 scrollTarget.setAttribute('tabindex', '-1')
210 scrollTarget.focus({ preventScroll: true })
211 })
212 })
213} 271}
214 272
215const tryOpenCollapsibles = async () => { 273const tryOpenAnchoredContent = async () => {
216 if (!searchNavigated) return
217 await nextTick() 274 await nextTick()
275 await nextFrame()
218 276
219 requestAnimationFrame(() => { 277 const hash = window.location.hash.slice(1)
220 const hash = window.location.hash.slice(1) 278 if (!hash) {
221 if (!hash) { 279 resetSearchNavigation()
222 searchNavigated = false 280 return
223 return 281 }
224 }
225 282
226 const id = decodeURIComponent(hash) 283 let target = getTargetByHash(hash)
227 const target = document.getElementById(id) || document.getElementById(hash) 284 let selectedTabForHash = false
228 285
229 if (target) { 286 if (!target) {
230 openCollapsibles(target) 287 target = await selectTabContainingAnchor(hash)
231 searchNavigated = false 288 selectedTabForHash = Boolean(target)
232 searchQuery = '' 289 }
233 } 290
234 }) 291 if (!target) {
292 if (searchNavigated) resetSearchNavigation()
293 return
294 }
295
296 if (searchNavigated) {
297 await openCollapsibles(target)
298 resetSearchNavigation()
299 return
300 }
301
302 if (
303 selectedTabForHash ||
304 target.classList.contains('tab-search-heading')
305 ) {
306 scrollToElement(getScrollTargetForAnchor(target), false)
307 }
235} 308}
236 309
237watch(() => route.data, tryOpenCollapsibles, { flush: 'post' }) 310onMounted(tryOpenAnchoredContent)
238watch(() => route.hash, tryOpenCollapsibles, { flush: 'post' }) 311watch(() => route.data, tryOpenAnchoredContent, { flush: 'post' })
312watch(() => route.hash, tryOpenAnchoredContent, { flush: 'post' })
239 313
240function onSidebarEnter() { 314function onSidebarEnter() {
241 sidebarRef.value?.focus() 315 sidebarRef.value?.focus()
@@ -375,7 +449,9 @@ const reloadTakodachi = () => {
375function initTitleOnly() { 449function initTitleOnly() {
376 document.querySelectorAll('.custom-block').forEach(block => { 450 document.querySelectorAll('.custom-block').forEach(block => {
377 const children = [...block.children] 451 const children = [...block.children]
378 const hasOnlyTitle = children.every(el => el.classList.contains('custom-block-title')) 452 const hasOnlyTitle = children.every(el =>
453 el.classList.contains('custom-block-title')
454 )
379 if (hasOnlyTitle) block.classList.add('title-only') 455 if (hasOnlyTitle) block.classList.add('title-only')
380 }) 456 })
381} 457}
@@ -637,4 +713,4 @@ onUnmounted(() => {
637 </span> 713 </span>
638 </template> 714 </template>
639 </Layout> 715 </Layout>
640</template>\ No newline at end of file 716</template>
docs/.vitepress/theme/styles/style.scss +2 −1
@@ -1649,7 +1649,8 @@ html.reduce-blur-effects {
1649 border-top: none !important; 1649 border-top: none !important;
1650} 1650}
1651 1651
1652.vp-doc .collapsible-search-heading { 1652.vp-doc .collapsible-search-heading,
1653.vp-doc .tab-search-heading {
1653 position: absolute; 1654 position: absolute;
1654 width: 1px; 1655 width: 1px;
1655 height: 1px; 1656 height: 1px;