-
-
Notifications
You must be signed in to change notification settings - Fork 405
Expand file tree
/
Copy pathrender.ts
More file actions
482 lines (411 loc) · 14.9 KB
/
render.ts
File metadata and controls
482 lines (411 loc) · 14.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
472
473
474
475
476
477
478
479
480
481
482
/**
* HTML Rendering
*
* Functions for rendering documentation nodes as HTML.
*
* @module server/utils/docs/render
*/
import type { DenoDocNode, JsDocTag } from '#shared/types/deno-doc'
import { highlightCodeBlock } from '../shiki'
import { formatParam, formatType, getNodeSignature } from './format'
import { groupMergedByKind } from './processing'
import { escapeHtml, createSymbolId, parseJsDocLinks, renderMarkdown } from './text'
import type { MergedSymbol, SymbolLookup } from './types'
// =============================================================================
// Configuration
// =============================================================================
/** Maximum number of overload signatures to display per symbol */
const MAX_OVERLOAD_SIGNATURES = 5
/** Maximum number of items to show in TOC per category before truncating */
const MAX_TOC_ITEMS_PER_KIND = 50
/** Order in which symbol kinds are displayed */
const KIND_DISPLAY_ORDER = [
'function',
'class',
'interface',
'typeAlias',
'variable',
'enum',
'namespace',
] as const
/** Human-readable titles for symbol kinds */
const KIND_TITLES: Record<string, string> = {
function: 'Functions',
class: 'Classes',
interface: 'Interfaces',
typeAlias: 'Type Aliases',
variable: 'Variables',
enum: 'Enums',
namespace: 'Namespaces',
}
// =============================================================================
// Main Rendering Functions
// =============================================================================
/**
* Render all documentation nodes as HTML.
*/
export async function renderDocNodes(
symbols: MergedSymbol[],
symbolLookup: SymbolLookup,
): Promise<string> {
const grouped = groupMergedByKind(symbols)
const sectionPromises = KIND_DISPLAY_ORDER.map(async kind => {
const kindSymbols = grouped[kind]
if (!kindSymbols || kindSymbols.length === 0) return ''
return renderKindSection(kind, kindSymbols, symbolLookup)
})
const sections = await Promise.all(sectionPromises)
return sections.filter(Boolean).join('\n')
}
/**
* Render a section for a specific symbol kind.
*/
async function renderKindSection(
kind: string,
symbols: MergedSymbol[],
symbolLookup: SymbolLookup,
): Promise<string> {
const title = KIND_TITLES[kind] || kind
const lines: string[] = []
const renderedSymbols = await Promise.all(
symbols.map(symbol => renderMergedSymbol(symbol, symbolLookup)),
)
lines.push(`<section class="docs-section" id="section-${kind}">`)
lines.push(`<h2 class="docs-section-title">${title}</h2>`)
lines.push(...renderedSymbols)
lines.push(`</section>`)
return lines.join('\n')
}
/**
* Render a merged symbol (with all its overloads).
*/
async function renderMergedSymbol(
symbol: MergedSymbol,
symbolLookup: SymbolLookup,
): Promise<string> {
const primaryNode = symbol.nodes[0]
if (!primaryNode) return '' // Safety check - should never happen
const lines: string[] = []
const id = createSymbolId(symbol.kind, symbol.name)
const hasOverloads = symbol.nodes.length > 1
lines.push(`<article class="docs-symbol" id="${id}">`)
// Header
lines.push(`<header class="docs-symbol-header">`)
lines.push(
`<a href="#${id}" class="docs-anchor" aria-label="Link to ${escapeHtml(symbol.name)}">#</a>`,
)
lines.push(`<h3 class="docs-symbol-name">${escapeHtml(symbol.name)}</h3>`)
lines.push(`<span class="docs-badge docs-badge--${symbol.kind}">${symbol.kind}</span>`)
if (primaryNode.functionDef?.isAsync) {
lines.push(`<span class="docs-badge docs-badge--async">async</span>`)
}
if (hasOverloads) {
lines.push(`<span class="docs-overload-count">${symbol.nodes.length} overloads</span>`)
}
lines.push(`</header>`)
// Signatures
const signatures = symbol.nodes
.slice(0, hasOverloads ? MAX_OVERLOAD_SIGNATURES : 1)
.map(n => getNodeSignature(n))
.filter(Boolean) as string[]
const description = symbol.jsDoc?.doc?.trim()
const signaturePromise =
signatures.length > 0 ? highlightCodeBlock(signatures.join('\n'), 'typescript') : null
const descriptionPromise = description ? renderMarkdown(description, symbolLookup) : null
const jsDocTagsPromise =
symbol.jsDoc?.tags && symbol.jsDoc.tags.length > 0
? renderJsDocTags(symbol.jsDoc.tags, symbolLookup)
: null
const [highlightedSignature, renderedDescription, renderedJsDocTags] = await Promise.all([
signaturePromise,
descriptionPromise,
jsDocTagsPromise,
])
if (highlightedSignature) {
lines.push(`<div class="docs-signature">${highlightedSignature}</div>`)
if (symbol.nodes.length > MAX_OVERLOAD_SIGNATURES) {
const remaining = symbol.nodes.length - MAX_OVERLOAD_SIGNATURES
lines.push(`<p class="docs-more-overloads">+ ${remaining} more overloads</p>`)
}
}
// Description
if (renderedDescription) {
lines.push(`<div class="docs-description">${renderedDescription}</div>`)
}
// JSDoc tags
if (renderedJsDocTags) {
lines.push(renderedJsDocTags)
}
// Type-specific members
if (symbol.kind === 'class' && primaryNode.classDef) {
lines.push(renderClassMembers(primaryNode.classDef))
} else if (symbol.kind === 'interface' && primaryNode.interfaceDef) {
lines.push(renderInterfaceMembers(primaryNode.interfaceDef))
} else if (symbol.kind === 'enum' && primaryNode.enumDef) {
lines.push(renderEnumMembers(primaryNode.enumDef))
}
lines.push(`</article>`)
return lines.join('\n')
}
/**
* Render JSDoc tags (params, returns, examples, etc.)
*/
async function renderJsDocTags(tags: JsDocTag[], symbolLookup: SymbolLookup): Promise<string> {
const lines: string[] = []
const params = tags.filter(t => t.kind === 'param')
const returns = tags.find(t => t.kind === 'return')
const examples = tags.filter(t => t.kind === 'example')
const deprecated = tags.find(t => t.kind === 'deprecated')
const see = tags.filter(t => t.kind === 'see')
const deprecatedMessagePromise = deprecated?.doc
? renderMarkdown(deprecated.doc.replace(/\n/g, ' '), symbolLookup)
: null
const examplePromises = examples.map(async example => {
if (!example.doc) return ''
const langMatch = example.doc.match(/```(\w+)?/)
const lang = langMatch?.[1] || 'typescript'
const code = example.doc.replace(/```\w*\n?/g, '').trim()
return highlightCodeBlock(code, lang)
})
const [renderedDeprecatedMessage, ...renderedExamples] = await Promise.all([
deprecatedMessagePromise,
...examplePromises,
])
// Deprecated warning
if (deprecated) {
lines.push(`<div class="docs-deprecated">`)
lines.push(`<strong>Deprecated</strong>`)
if (renderedDeprecatedMessage) {
// We remove new lines because they look weird when rendered into the deprecated block
// I think markdown is actually supposed to collapse single new lines automatically but this function doesn't do that so if that changes remove this
lines.push(`<div class="docs-deprecated-message">${renderedDeprecatedMessage}</div>`)
}
lines.push(`</div>`)
}
// Parameters
if (params.length > 0) {
lines.push(`<div class="docs-params">`)
lines.push(`<h4>Parameters</h4>`)
lines.push(`<dl>`)
for (const param of params) {
lines.push(
`<dt><code>${escapeHtml(param.name || '')}${param.optional ? '?' : ''}</code></dt>`,
)
if (param.doc) {
lines.push(`<dd>${parseJsDocLinks(param.doc, symbolLookup)}</dd>`)
}
}
lines.push(`</dl>`)
lines.push(`</div>`)
}
// Returns
if (returns?.doc) {
lines.push(`<div class="docs-returns">`)
lines.push(`<h4>Returns</h4>`)
lines.push(`<p>${parseJsDocLinks(returns.doc, symbolLookup)}</p>`)
lines.push(`</div>`)
}
// Examples (with syntax highlighting)
if (examples.length > 0 && renderedExamples.some(Boolean)) {
lines.push(`<div class="docs-examples">`)
lines.push(`<h4>Example${examples.length > 1 ? 's' : ''}</h4>`)
lines.push(...renderedExamples.filter(Boolean))
lines.push(`</div>`)
}
// See also
if (see.length > 0) {
lines.push(`<div class="docs-see">`)
lines.push(`<h4>See Also</h4>`)
lines.push(`<ul>`)
for (const s of see) {
if (s.doc) {
lines.push(`<li>${parseJsDocLinks(s.doc, symbolLookup)}</li>`)
}
}
lines.push(`</ul>`)
lines.push(`</div>`)
}
return lines.join('\n')
}
// =============================================================================
// Member Rendering
// =============================================================================
type DefinitionListItem = {
signature: string
description?: string
}
function renderMemberList(title: string, items: DefinitionListItem[]): string {
const lines: string[] = []
if (items.length === 0) {
return ''
}
lines.push(`<div class="docs-members">`)
lines.push(`<h4>${title}</h4>`)
lines.push(`<dl>`)
for (const item of items) {
lines.push(`<dt><code>${escapeHtml(item.signature)}</code></dt>`)
if (item.description) {
lines.push(`<dd>${escapeHtml(item.description.split('\n')[0] ?? '')}</dd>`)
}
}
lines.push(`</dl>`)
lines.push(`</div>`)
return lines.join('\n')
}
/**
* Render class members (constructor, properties, methods).
*/
function renderClassMembers(def: NonNullable<DenoDocNode['classDef']>): string {
const lines: string[] = []
const { constructors, properties, methods } = def
if (constructors && constructors.length > 0) {
lines.push(`<div class="docs-members">`)
lines.push(`<h4>Constructor</h4>`)
for (const ctor of constructors) {
const params = ctor.params?.map(p => formatParam(p)).join(', ') || ''
lines.push(`<pre><code>constructor(${escapeHtml(params)})</code></pre>`)
}
lines.push(`</div>`)
}
if (properties && properties.length > 0) {
const propertyItems: DefinitionListItem[] = properties.map(prop => {
const modifiers: string[] = []
if (prop.isStatic) modifiers.push('static')
if (prop.readonly) modifiers.push('readonly')
const modStr = modifiers.length > 0 ? `${modifiers.join(' ')} ` : ''
const type = formatType(prop.tsType)
const opt = prop.optional ? '?' : ''
const typeStr = type ? `: ${type}` : ''
return {
signature: `${modStr}${prop.name}${opt}${typeStr}`,
description: prop.jsDoc?.doc,
}
})
lines.push(renderMemberList('Properties', propertyItems))
}
const getters = methods?.filter(m => m.kind === 'getter') || []
const regularMethods = methods?.filter(m => m.kind !== 'getter') || []
if (getters.length > 0) {
const getterItems: DefinitionListItem[] = getters.map(getter => {
const ret = formatType(getter.functionDef?.returnType) || 'unknown'
const staticStr = getter.isStatic ? 'static ' : ''
return {
signature: `${staticStr}get ${getter.name}: ${ret}`,
description: getter.jsDoc?.doc,
}
})
lines.push(renderMemberList('Getters', getterItems))
}
if (regularMethods.length > 0) {
const methodItems: DefinitionListItem[] = regularMethods.map(method => {
const params = method.functionDef?.params?.map(p => formatParam(p)).join(', ') || ''
const ret = formatType(method.functionDef?.returnType) || 'void'
const staticStr = method.isStatic ? 'static ' : ''
return {
signature: `${staticStr}${method.name}(${params}): ${ret}`,
description: method.jsDoc?.doc,
}
})
lines.push(renderMemberList('Methods', methodItems))
}
return lines.join('\n')
}
/**
* Render interface members (properties, methods).
*/
function renderInterfaceMembers(def: NonNullable<DenoDocNode['interfaceDef']>): string {
const lines: string[] = []
const { properties, methods } = def
if (properties && properties.length > 0) {
lines.push(`<div class="docs-members">`)
lines.push(`<h4>Properties</h4>`)
lines.push(`<dl>`)
for (const prop of properties) {
const type = formatType(prop.tsType)
const opt = prop.optional ? '?' : ''
const ro = prop.readonly ? 'readonly ' : ''
lines.push(
`<dt><code>${escapeHtml(ro)}${escapeHtml(prop.name)}${opt}: ${escapeHtml(type)}</code></dt>`,
)
if (prop.jsDoc?.doc) {
lines.push(`<dd>${escapeHtml(prop.jsDoc.doc.split('\n')[0] ?? '')}</dd>`)
}
}
lines.push(`</dl>`)
lines.push(`</div>`)
}
if (methods && methods.length > 0) {
lines.push(`<div class="docs-members">`)
lines.push(`<h4>Methods</h4>`)
lines.push(`<dl>`)
for (const method of methods) {
const params = method.params?.map(p => formatParam(p)).join(', ') || ''
const ret = formatType(method.returnType) || 'void'
lines.push(
`<dt><code>${escapeHtml(method.name)}(${escapeHtml(params)}): ${escapeHtml(ret)}</code></dt>`,
)
if (method.jsDoc?.doc) {
lines.push(`<dd>${escapeHtml(method.jsDoc.doc.split('\n')[0] ?? '')}</dd>`)
}
}
lines.push(`</dl>`)
lines.push(`</div>`)
}
return lines.join('\n')
}
/**
* Render enum members.
*/
function renderEnumMembers(def: NonNullable<DenoDocNode['enumDef']>): string {
const lines: string[] = []
const { members } = def
if (members && members.length > 0) {
lines.push(`<div class="docs-members">`)
lines.push(`<h4>Members</h4>`)
lines.push(`<ul class="docs-enum-members">`)
for (const member of members) {
lines.push(`<li><code>${escapeHtml(member.name)}</code></li>`)
}
lines.push(`</ul>`)
lines.push(`</div>`)
}
return lines.join('\n')
}
// =============================================================================
// Table of Contents
// =============================================================================
/**
* Render table of contents.
*/
export function renderToc(symbols: MergedSymbol[]): string {
const grouped = groupMergedByKind(symbols)
const lines: string[] = []
lines.push(`<nav class="toc text-sm" aria-label="Table of contents">`)
lines.push(`<ul class="space-y-3">`)
for (const kind of KIND_DISPLAY_ORDER) {
const kindSymbols = grouped[kind]
if (!kindSymbols || kindSymbols.length === 0) continue
const title = KIND_TITLES[kind] || kind
lines.push(`<li>`)
lines.push(
`<a href="#section-${kind}" class="font-semibold text-fg-muted hover:text-fg block mb-1">${title} <span class="text-fg-subtle font-normal">(${kindSymbols.length})</span></a>`,
)
const showSymbols = kindSymbols.slice(0, MAX_TOC_ITEMS_PER_KIND)
lines.push(`<ul class="ps-3 space-y-0.5 border-is border-border/50">`)
for (const symbol of showSymbols) {
const id = createSymbolId(symbol.kind, symbol.name)
lines.push(
`<li><a href="#${id}" class="text-fg-subtle hover:text-fg font-mono text-xs block py-0.5 truncate">${escapeHtml(symbol.name)}</a></li>`,
)
}
if (kindSymbols.length > MAX_TOC_ITEMS_PER_KIND) {
const remaining = kindSymbols.length - MAX_TOC_ITEMS_PER_KIND
lines.push(`<li class="text-fg-subtle text-xs py-0.5">... and ${remaining} more</li>`)
}
lines.push(`</ul>`)
lines.push(`</li>`)
}
lines.push(`</ul>`)
lines.push(`</nav>`)
return lines.join('\n')
}