forked from TanStack/tanstack.com
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtransformTabsComponent.ts
More file actions
471 lines (396 loc) · 11.9 KB
/
transformTabsComponent.ts
File metadata and controls
471 lines (396 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
import { toString } from 'hast-util-to-string'
import { headingLevel, isHeading, slugify } from './helpers'
export type VariantHandler = (
node: HastNode,
attributes: Record<string, string>,
) => boolean
type InstallMode = 'install' | 'dev-install'
type HastNode = {
type: string
tagName: string
properties?: Record<string, unknown>
children?: HastNode[]
}
type TabDescriptor = {
slug: string
name: string
}
type TabExtraction = {
tabs: TabDescriptor[]
panels: HastNode[][]
}
type PackageManagerExtraction = {
packagesByFramework: Record<string, string[][]>
mode: InstallMode
}
type FilesExtraction = {
files: Array<{
title: string
code: string
language: string
preNode: HastNode
}>
}
type FrameworkExtraction = {
codeBlocksByFramework: Record<
string,
Array<{
title: string
code: string
language: string
preNode: HastNode
}>
>
contentByFramework: Record<string, HastNode[]>
}
type FrameworkCodeBlock = {
title: string
code: string
language: string
preNode: HastNode
}
function parseAttributes(node: HastNode): Record<string, string> {
const rawAttributes = node.properties?.['data-attributes']
if (typeof rawAttributes === 'string') {
try {
return JSON.parse(rawAttributes)
} catch {
return {}
}
}
return {}
}
function resolveMode(attributes: Record<string, string>): InstallMode {
const mode = attributes.mode?.toLowerCase()
if (mode === 'dev-install') return 'dev-install'
if (mode === 'local-install') return 'local-install'
return 'install'
}
function normalizeFrameworkKey(key: string): string {
return key.trim().toLowerCase()
}
// Helper to extract text from nodes (used for code content)
function extractText(nodes: any[]): string {
let text = ''
for (const node of nodes) {
if (node.type === 'text') {
text += node.value
} else if (node.type === 'element' && node.children) {
text += extractText(node.children)
}
}
return text
}
/**
* Parse a line like "react: @tanstack/react-query @tanstack/react-query-devtools"
* Returns { framework: 'react', packages: '@tanstack/react-query @tanstack/react-query-devtools' }
*/
function parseFrameworkLine(text: string): {
framework: string
packages: string[]
} | null {
const colonIndex = text.indexOf(':')
if (colonIndex === -1) {
return null
}
const framework = normalizeFrameworkKey(text.slice(0, colonIndex))
const packagesStr = text.slice(colonIndex + 1).trim()
const packages = packagesStr.split(/\s+/).filter(Boolean)
if (!framework || packages.length === 0) {
return null
}
return { framework, packages }
}
function extractPackageManagerData(
node: HastNode,
mode: InstallMode,
): PackageManagerExtraction | null {
const children = node.children ?? []
const packagesByFramework: Record<string, string[][]> = {}
const allText = extractText(children)
const lines = allText.split('\n')
for (const line of lines) {
const trimmed = line.trim()
if (!trimmed) continue
const parsed = parseFrameworkLine(trimmed)
if (parsed) {
// Each line becomes a separate entry (array of packages)
// Multiple packages on same line = install together
// Multiple lines = install separately
if (packagesByFramework[parsed.framework]) {
packagesByFramework[parsed.framework].push(parsed.packages)
} else {
packagesByFramework[parsed.framework] = [parsed.packages]
}
}
}
if (Object.keys(packagesByFramework).length === 0) {
return null
}
return { packagesByFramework, mode }
}
/**
* Extract code block data (language, title, code) from a <pre> element.
* Extracts title from data-code-title (set by rehypeCodeMeta).
*/
function extractCodeBlockData(preNode: HastNode): {
language: string
title: string
code: string
} | null {
// Find the <code> child
const codeNode = preNode.children?.find(
(c: HastNode) => c.type === 'element' && c.tagName === 'code',
)
if (!codeNode) return null
// Extract language from className
let language = 'plaintext'
const className = codeNode.properties?.className
if (Array.isArray(className)) {
const langClass = className.find((c) => String(c).startsWith('language-'))
if (langClass) {
language = String(langClass).replace('language-', '')
}
}
let title = ''
const props = preNode.properties || {}
if (typeof props['dataCodeTitle'] === 'string') {
title = props['dataCodeTitle'] as string
} else if (typeof props['data-code-title'] === 'string') {
title = props['data-code-title']
} else if (typeof props['dataFilename'] === 'string') {
title = props['dataFilename'] as string
} else if (typeof props['data-filename'] === 'string') {
title = props['data-filename']
}
// Extract code content
const code = extractText(codeNode.children || [])
return { language, title, code }
}
/**
* Extract files data for variant="files" tabs.
* Parses consecutive code blocks and creates file tabs.
*/
function extractFilesData(node: HastNode): FilesExtraction | null {
const children = node.children ?? []
const files: FilesExtraction['files'] = []
for (const child of children) {
if (child.type === 'element' && child.tagName === 'pre') {
const codeBlockData = extractCodeBlockData(child)
if (!codeBlockData) continue
files.push({
title: codeBlockData.title || 'Untitled',
code: codeBlockData.code,
language: codeBlockData.language,
preNode: child,
})
}
}
if (files.length === 0) {
return null
}
return { files }
}
/**
* Extract framework-specific content for variant="framework" tabs.
* Groups all content (code blocks and general content) by framework headings.
*/
function extractFrameworkData(node: HastNode): FrameworkExtraction | null {
const children = node.children ?? []
const codeBlocksByFramework: Record<string, FrameworkCodeBlock[]> = {}
const contentByFramework: Record<string, HastNode[]> = {}
let currentFramework: string | null = null
for (const child of children) {
if (isHeading(child)) {
currentFramework = toString(child as any)
.trim()
.toLowerCase()
// Initialize arrays for this framework
if (currentFramework && !contentByFramework[currentFramework]) {
contentByFramework[currentFramework] = []
codeBlocksByFramework[currentFramework] = []
}
continue
}
// Skip if no framework heading found yet
if (!currentFramework) continue
// Add all content to contentByFramework
contentByFramework[currentFramework].push(child)
// Look for <pre> elements (code blocks) under current framework
if (child.type === 'element' && child.tagName === 'pre') {
const codeBlockData = extractCodeBlockData(child)
if (!codeBlockData) continue
codeBlocksByFramework[currentFramework].push({
title: codeBlockData.title || 'Untitled',
code: codeBlockData.code,
language: codeBlockData.language,
preNode: child,
})
}
}
// Return null only if no frameworks found at all
if (Object.keys(contentByFramework).length === 0) {
return null
}
return { codeBlocksByFramework, contentByFramework }
}
function extractTabPanels(node: HastNode): TabExtraction | null {
const children = node.children ?? []
const headings = children.filter(isHeading)
let sectionStarted = false
let largestHeadingLevel = Infinity
headings.forEach((heading: HastNode) => {
largestHeadingLevel = Math.min(largestHeadingLevel, headingLevel(heading))
})
const tabs: TabDescriptor[] = []
const panels: HastNode[][] = []
let currentPanel: HastNode[] | null = null
children.forEach((child: any) => {
if (isHeading(child)) {
const level = headingLevel(child)
if (!sectionStarted) {
if (level !== largestHeadingLevel) {
return
}
sectionStarted = true
}
if (level === largestHeadingLevel) {
if (currentPanel) {
panels.push(currentPanel)
}
const headingId =
typeof child.properties?.id === 'string'
? child.properties.id
: slugify(toString(child as any), `tab-${tabs.length + 1}`)
tabs.push({
slug: headingId,
name: toString(child as any),
})
currentPanel = []
return
}
}
if (sectionStarted) {
if (!currentPanel) {
currentPanel = []
}
currentPanel.push(child)
}
})
if (currentPanel) {
panels.push(currentPanel)
}
if (!tabs.length) {
return null
}
return { tabs, panels }
}
export function transformTabsComponent(node: HastNode) {
const attributes = parseAttributes(node)
const variant = attributes.variant?.toLowerCase()
// Handle package-manager variant
if (variant === 'package-manager' || variant === 'package-managers') {
const mode = resolveMode(attributes)
const result = extractPackageManagerData(node, mode)
if (!result) {
return
}
// Remove children so package managers don't show up in TOC
node.children = []
// Store metadata for the React component
node.properties = node.properties || {}
node.properties['data-package-manager-meta'] = JSON.stringify({
packagesByFramework: result.packagesByFramework,
mode: result.mode,
})
return
}
// Handle files variant
if (variant === 'files') {
const result = extractFilesData(node)
if (!result) {
return
}
// Store metadata for the React component (without preNodes to avoid circular refs)
node.properties = node.properties || {}
node.properties['data-files-meta'] = JSON.stringify({
files: result.files.map((f) => ({
title: f.title,
code: f.code,
language: f.language,
})),
})
// Create tab headings from file titles
const tabs = result.files.map((file, index) => ({
slug: `file-${index}`,
name: file.title,
}))
node.properties['data-attributes'] = JSON.stringify({ tabs })
// Create panel elements with original preNodes
node.children = result.files.map((file, index) => ({
type: 'element',
tagName: 'md-tab-panel',
properties: {
'data-tab-slug': `file-${index}`,
'data-tab-index': String(index),
},
// Use the original preNode which already has data-code-title from rehypeCodeMeta
children: [file.preNode],
}))
return
}
if (variant === 'framework') {
const result = extractFrameworkData(node)
if (!result) {
return
}
node.properties = node.properties || {}
node.properties['data-framework-meta'] = JSON.stringify({
codeBlocksByFramework: Object.fromEntries(
Object.entries(result.codeBlocksByFramework).map(([fw, blocks]) => [
fw,
blocks.map((b) => ({
title: b.title,
code: b.code,
language: b.language,
})),
]),
),
})
// Store available frameworks for the component
const availableFrameworks = Object.keys(result.contentByFramework)
node.properties['data-available-frameworks'] =
JSON.stringify(availableFrameworks)
node.children = availableFrameworks.map((fw) => {
const content = result.contentByFramework[fw] || []
return {
type: 'element',
tagName: 'md-tab-panel',
properties: {
'data-framework': fw,
},
children: content,
}
})
return
}
// Handle default tabs variant
const result = extractTabPanels(node)
if (!result) {
return
}
const panelElements = result.panels.map((panelChildren, index) => ({
type: 'element',
tagName: 'md-tab-panel',
properties: {
'data-tab-slug': result.tabs[index]?.slug ?? `tab-${index + 1}`,
'data-tab-index': String(index),
},
children: panelChildren,
}))
node.properties = {
...node.properties,
'data-attributes': JSON.stringify({ tabs: result.tabs }),
}
node.children = panelElements
}