@tooee/renderers 0.2.4 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/dist/code-blocks.d.ts +6 -6
  2. package/dist/code-blocks.d.ts.map +1 -1
  3. package/dist/code-blocks.js +52 -42
  4. package/dist/code-blocks.js.map +1 -1
  5. package/dist/{CodeView.d.ts → code-view.d.ts} +3 -3
  6. package/dist/code-view.d.ts.map +1 -0
  7. package/dist/{CodeView.js → code-view.js} +5 -5
  8. package/dist/code-view.js.map +1 -0
  9. package/dist/{CommandPalette.d.ts → command-palette.d.ts} +2 -2
  10. package/dist/command-palette.d.ts.map +1 -0
  11. package/dist/{CommandPalette.js → command-palette.js} +27 -24
  12. package/dist/command-palette.js.map +1 -0
  13. package/dist/{ContextMenu.d.ts → context-menu.d.ts} +2 -2
  14. package/dist/context-menu.d.ts.map +1 -0
  15. package/dist/{ContextMenu.js → context-menu.js} +24 -14
  16. package/dist/context-menu.js.map +1 -0
  17. package/dist/{DecorationLayer.d.ts → decoration-layer.d.ts} +2 -2
  18. package/dist/decoration-layer.d.ts.map +1 -0
  19. package/dist/decoration-layer.js +2 -0
  20. package/dist/decoration-layer.js.map +1 -0
  21. package/dist/{DocumentBindings.d.ts → document-bindings.d.ts} +4 -4
  22. package/dist/document-bindings.d.ts.map +1 -0
  23. package/dist/document-bindings.js +2 -0
  24. package/dist/document-bindings.js.map +1 -0
  25. package/dist/index.d.ts +16 -15
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +9 -9
  28. package/dist/index.js.map +1 -1
  29. package/dist/markdown-blocks.d.ts +9 -13
  30. package/dist/markdown-blocks.d.ts.map +1 -1
  31. package/dist/markdown-blocks.js +98 -79
  32. package/dist/markdown-blocks.js.map +1 -1
  33. package/dist/{MarkdownView.d.ts → markdown-view.d.ts} +13 -13
  34. package/dist/markdown-view.d.ts.map +1 -0
  35. package/dist/markdown-view.js +455 -0
  36. package/dist/markdown-view.js.map +1 -0
  37. package/dist/mermaid.d.ts +6 -6
  38. package/dist/mermaid.d.ts.map +1 -1
  39. package/dist/mermaid.js +56 -26
  40. package/dist/mermaid.js.map +1 -1
  41. package/dist/parsers.d.ts +5 -5
  42. package/dist/parsers.d.ts.map +1 -1
  43. package/dist/parsers.js +64 -44
  44. package/dist/parsers.js.map +1 -1
  45. package/dist/{RowDocumentRenderable.d.ts → row-document-renderable.d.ts} +15 -11
  46. package/dist/row-document-renderable.d.ts.map +1 -0
  47. package/dist/{RowDocumentRenderable.js → row-document-renderable.js} +110 -62
  48. package/dist/row-document-renderable.js.map +1 -0
  49. package/dist/row-document.d.ts +1 -1
  50. package/dist/row-document.d.ts.map +1 -1
  51. package/dist/row-document.js +1 -1
  52. package/dist/row-document.js.map +1 -1
  53. package/dist/source.d.ts +6 -6
  54. package/dist/source.d.ts.map +1 -1
  55. package/dist/source.js +35 -26
  56. package/dist/source.js.map +1 -1
  57. package/dist/table-types.d.ts.map +1 -1
  58. package/dist/{Table.d.ts → table.d.ts} +6 -6
  59. package/dist/table.d.ts.map +1 -0
  60. package/dist/{Table.js → table.js} +65 -35
  61. package/dist/table.js.map +1 -0
  62. package/dist/text-table.d.ts.map +1 -1
  63. package/dist/text-table.js.map +1 -1
  64. package/dist/use-gutter-palette.d.ts +3 -0
  65. package/dist/use-gutter-palette.d.ts.map +1 -0
  66. package/dist/{useGutterPalette.js → use-gutter-palette.js} +4 -4
  67. package/dist/use-gutter-palette.js.map +1 -0
  68. package/package.json +5 -5
  69. package/src/code-blocks.tsx +122 -106
  70. package/src/{CodeView.tsx → code-view.tsx} +19 -14
  71. package/src/command-palette.tsx +163 -0
  72. package/src/context-menu.tsx +157 -0
  73. package/src/decoration-layer.ts +11 -0
  74. package/src/document-bindings.ts +16 -0
  75. package/src/index.ts +24 -23
  76. package/src/markdown-blocks.ts +178 -138
  77. package/src/markdown-view.tsx +853 -0
  78. package/src/mermaid.ts +122 -70
  79. package/src/parsers.ts +141 -103
  80. package/src/row-document-renderable.ts +672 -0
  81. package/src/row-document.ts +4 -4
  82. package/src/source.ts +92 -72
  83. package/src/table-types.ts +4 -4
  84. package/src/table.tsx +346 -0
  85. package/src/text-table.ts +4 -4
  86. package/src/use-gutter-palette.ts +15 -0
  87. package/dist/CodeView.d.ts.map +0 -1
  88. package/dist/CodeView.js.map +0 -1
  89. package/dist/CommandPalette.d.ts.map +0 -1
  90. package/dist/CommandPalette.js.map +0 -1
  91. package/dist/ContextMenu.d.ts.map +0 -1
  92. package/dist/ContextMenu.js.map +0 -1
  93. package/dist/DecorationLayer.d.ts.map +0 -1
  94. package/dist/DecorationLayer.js +0 -2
  95. package/dist/DecorationLayer.js.map +0 -1
  96. package/dist/DocumentBindings.d.ts.map +0 -1
  97. package/dist/DocumentBindings.js +0 -2
  98. package/dist/DocumentBindings.js.map +0 -1
  99. package/dist/MarkdownView.d.ts.map +0 -1
  100. package/dist/MarkdownView.js +0 -360
  101. package/dist/MarkdownView.js.map +0 -1
  102. package/dist/RowDocumentRenderable.d.ts.map +0 -1
  103. package/dist/RowDocumentRenderable.js.map +0 -1
  104. package/dist/Table.d.ts.map +0 -1
  105. package/dist/Table.js.map +0 -1
  106. package/dist/useGutterPalette.d.ts +0 -3
  107. package/dist/useGutterPalette.d.ts.map +0 -1
  108. package/dist/useGutterPalette.js.map +0 -1
  109. package/src/CommandPalette.tsx +0 -147
  110. package/src/ContextMenu.tsx +0 -132
  111. package/src/DecorationLayer.ts +0 -11
  112. package/src/DocumentBindings.ts +0 -16
  113. package/src/MarkdownView.tsx +0 -738
  114. package/src/RowDocumentRenderable.ts +0 -593
  115. package/src/Table.tsx +0 -300
  116. package/src/useGutterPalette.ts +0 -15
@@ -0,0 +1,853 @@
1
+ import type { Token, Tokens } from "marked";
2
+ import { useMemo } from "react";
3
+ import type { ReactNode, RefObject } from "react";
4
+ import { useTheme } from "@tooee/themes";
5
+ import type { ResolvedTheme } from "@tooee/themes";
6
+ import {
7
+ bold as boldChunk,
8
+ italic as italicChunk,
9
+ underline as underlineChunk,
10
+ parseColor,
11
+ } from "@opentui/core";
12
+ import type {
13
+ SyntaxStyle,
14
+ TextBufferRenderable,
15
+ TextTableContent,
16
+ TextTableCellContent,
17
+ TextChunk,
18
+ MouseEvent,
19
+ } from "@opentui/core";
20
+ import type { DocumentBindings } from "./document-bindings.js";
21
+ import { DEFAULT_SIGN_COLUMN_WIDTH } from "./row-document-renderable.js";
22
+ import { useGutterPalette } from "./use-gutter-palette.js";
23
+ import { CodeBlock, DEFAULT_CODE_BLOCK_RENDERERS } from "./code-blocks.js";
24
+ import type { CodeBlockRenderer } from "./code-blocks.js";
25
+ import { checkboxMarker, flattenMarkdown } from "./markdown-blocks.js";
26
+ import type { FlatBlock } from "./markdown-blocks.js";
27
+ import "./row-document.js";
28
+ import "./text-table.js";
29
+
30
+ // ---------------------------------------------------------------------------
31
+ // Types
32
+ // ---------------------------------------------------------------------------
33
+
34
+ export type MarkdownLinkHandler = (href: string) => unknown;
35
+
36
+ export interface InlineLinkPosition {
37
+ line: number;
38
+ column: number;
39
+ }
40
+
41
+ interface MarkdownViewProps {
42
+ content: string;
43
+ /**
44
+ * Pre-flattened blocks to render, normally the exact array a subview passed
45
+ * to its document controller. When supplied, `content` is *not* lexed again,
46
+ * so the rendered rows and the controller's navigation rows cannot drift.
47
+ * Omit it and `MarkdownView` flattens `content` itself for static callers.
48
+ */
49
+ blocks?: readonly FlatBlock[];
50
+ showLineNumbers?: boolean;
51
+ /**
52
+ * Binds the row document to a document controller: its ref, the decoration
53
+ * layers to paint, and the mouse handler. Rows are flattened *block* indices —
54
+ * the same unit `j`/`k` move between and copy operates on. Omit it to render
55
+ * a static, non-interactive document.
56
+ *
57
+ * Blocks are per-child renderables, but their markup varies across renderer
58
+ * branches (box/text/null with differing margins), so the controller maps
59
+ * clicks by screen-Y rather than per-child handlers. Clicks bubble up from
60
+ * block children (including custom code blocks) unless a custom renderer
61
+ * stops propagation.
62
+ */
63
+ document?: DocumentBindings;
64
+ /**
65
+ * Registry of horizontally scrollable blocks, keyed by block index. Blocks
66
+ * that can overflow horizontally (mermaid diagrams and code blocks)
67
+ * register their text-buffer renderable here so the owning subview can
68
+ * drive horizontal panning (`scrollX`) for the block under the nav cursor
69
+ * (h/l in cursor mode).
70
+ */
71
+ hScrollableBlocksRef?: RefObject<Map<number, TextBufferRenderable>>;
72
+ /**
73
+ * Custom renderers for fenced code blocks, keyed by fence type. A fence's
74
+ * type is the first whitespace-separated word of its info string, matched
75
+ * case-insensitively. Entries are merged over the built-in defaults
76
+ * (currently `mermaid`), so built-ins can be overridden. Unmatched types —
77
+ * and renderers that return `null` or throw — fall back to the default
78
+ * syntax-highlighted code block.
79
+ */
80
+ codeBlockRenderers?: Record<string, CodeBlockRenderer>;
81
+ /**
82
+ * Called when the primary mouse button activates inline Markdown link text.
83
+ * Return `true` when the host handled the href; handled clicks do not bubble
84
+ * to document row selection. Unhandled links retain their native OSC-8 href.
85
+ */
86
+ onLinkActivate?: MarkdownLinkHandler;
87
+ }
88
+
89
+ // ---------------------------------------------------------------------------
90
+ // Inline link hit testing
91
+ // ---------------------------------------------------------------------------
92
+
93
+ /** Resolve a rendered text position to the Markdown link occupying that cell. */
94
+ export const inlineLinkAtPosition = function inlineLinkAtPosition(
95
+ tokens: readonly Token[],
96
+ position: InlineLinkPosition,
97
+ initialColumn = 0,
98
+ ): string | null {
99
+ let line = 0;
100
+ let column = initialColumn;
101
+ let found: string | null = null;
102
+
103
+ const advanceText = (value: string, href?: string): void => {
104
+ const parts = value.split("\n");
105
+ for (const [index, part] of parts.entries()) {
106
+ const width = Bun.stringWidth(part);
107
+ if (
108
+ href !== undefined &&
109
+ line === position.line &&
110
+ position.column >= column &&
111
+ position.column < column + width
112
+ ) {
113
+ found = href;
114
+ }
115
+ column += width;
116
+ if (index < parts.length - 1) {
117
+ line += 1;
118
+ column = 0;
119
+ }
120
+ }
121
+ };
122
+
123
+ const visit = (items: readonly Token[], href?: string): void => {
124
+ for (const token of items) {
125
+ if (found !== null) {
126
+ return;
127
+ }
128
+ switch (token.type) {
129
+ case "link": {
130
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
131
+ const link = token as Tokens.Link;
132
+ visit(link.tokens, link.href);
133
+ break;
134
+ }
135
+ case "strong": {
136
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
137
+ visit((token as Tokens.Strong).tokens, href);
138
+ break;
139
+ }
140
+ case "em": {
141
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
142
+ visit((token as Tokens.Em).tokens, href);
143
+ break;
144
+ }
145
+ case "del": {
146
+ advanceText("~", href);
147
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
148
+ visit((token as Tokens.Del).tokens, href);
149
+ advanceText("~", href);
150
+ break;
151
+ }
152
+ case "codespan": {
153
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
154
+ advanceText(` ${(token as Tokens.Codespan).text} `, href);
155
+ break;
156
+ }
157
+ case "br": {
158
+ advanceText("\n", href);
159
+ break;
160
+ }
161
+ case "space": {
162
+ advanceText(" ", href);
163
+ break;
164
+ }
165
+ default: {
166
+ if ("text" in token && typeof token.text === "string") {
167
+ advanceText(token.text, href);
168
+ }
169
+ }
170
+ }
171
+ }
172
+ };
173
+
174
+ visit(tokens);
175
+ return found;
176
+ };
177
+
178
+ const linkMouseHandler = function linkMouseHandler(
179
+ tokens: readonly Token[],
180
+ onLinkActivate: MarkdownLinkHandler | undefined,
181
+ initialColumn = 0,
182
+ ): ((event: MouseEvent) => void) | undefined {
183
+ if (onLinkActivate === undefined) {
184
+ return undefined;
185
+ }
186
+ return (event: MouseEvent): void => {
187
+ if (event.button !== 0) {
188
+ return;
189
+ }
190
+ const { target } = event;
191
+ if (target === null || target === undefined || !("lineInfo" in target)) {
192
+ return;
193
+ }
194
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- OpenTUI mouse targets are renderables; lineInfo narrows this to a text buffer at the framework boundary
195
+ const text = target as TextBufferRenderable;
196
+ const visualLine = event.y - text.y;
197
+ const sourceLine = text.lineInfo.lineSources[visualLine];
198
+ const startColumn = text.lineInfo.lineStartCols[visualLine];
199
+ if (sourceLine === undefined || startColumn === undefined) {
200
+ return;
201
+ }
202
+ const href = inlineLinkAtPosition(
203
+ tokens,
204
+ {
205
+ column: startColumn + event.x - text.x,
206
+ line: sourceLine,
207
+ },
208
+ initialColumn,
209
+ );
210
+ if (href === null || onLinkActivate(href) !== true) {
211
+ return;
212
+ }
213
+ event.preventDefault();
214
+ event.stopPropagation();
215
+ };
216
+ };
217
+
218
+ // ---------------------------------------------------------------------------
219
+ // Component
220
+ // ---------------------------------------------------------------------------
221
+
222
+ export const MarkdownView = function MarkdownView({
223
+ content,
224
+ blocks: providedBlocks,
225
+ showLineNumbers = true,
226
+ document,
227
+ hScrollableBlocksRef,
228
+ codeBlockRenderers,
229
+ onLinkActivate,
230
+ }: MarkdownViewProps): ReactNode {
231
+ const { theme, syntax } = useTheme();
232
+ const palette = useGutterPalette();
233
+ const blocks = useMemo(
234
+ () => providedBlocks ?? flattenMarkdown(content),
235
+ [providedBlocks, content],
236
+ );
237
+
238
+ // Merge user renderers over built-in defaults, normalizing keys to
239
+ // lowercase so registration matches fence types case-insensitively.
240
+ const mergedCodeBlockRenderers = useMemo(() => {
241
+ const merged: Record<string, CodeBlockRenderer> = { ...DEFAULT_CODE_BLOCK_RENDERERS };
242
+ for (const [key, renderer] of Object.entries(codeBlockRenderers ?? {})) {
243
+ merged[key.trim().toLowerCase()] = renderer;
244
+ }
245
+ return merged;
246
+ }, [codeBlockRenderers]);
247
+
248
+ const blockElements = useMemo(
249
+ () =>
250
+ blocks.map(
251
+ (block, index): ReactNode => (
252
+ // oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): preserve deliberate top-down renderer organization
253
+ <FlatBlockRenderer
254
+ key={index}
255
+ block={block}
256
+ blockIndex={index}
257
+ theme={theme}
258
+ syntax={syntax}
259
+ hScrollableBlocksRef={hScrollableBlocksRef}
260
+ codeBlockRenderers={mergedCodeBlockRenderers}
261
+ onLinkActivate={onLinkActivate}
262
+ />
263
+ ),
264
+ ),
265
+ [blocks, theme, syntax, hScrollableBlocksRef, mergedCodeBlockRenderers, onLinkActivate],
266
+ );
267
+
268
+ return (
269
+ <row-document
270
+ ref={document?.ref}
271
+ showLineNumbers={showLineNumbers}
272
+ palette={palette}
273
+ decorations={document?.decorations}
274
+ signColumnWidth={DEFAULT_SIGN_COLUMN_WIDTH}
275
+ style={{ flexGrow: 1 }}
276
+ onMouseDown={document?.onMouseDown}
277
+ >
278
+ {blockElements}
279
+ </row-document>
280
+ );
281
+ };
282
+
283
+ // ---------------------------------------------------------------------------
284
+ // Block renderer (flat)
285
+ // ---------------------------------------------------------------------------
286
+
287
+ const FlatBlockRenderer = function FlatBlockRenderer({
288
+ block,
289
+ blockIndex,
290
+ theme,
291
+ syntax,
292
+ hScrollableBlocksRef,
293
+ codeBlockRenderers,
294
+ onLinkActivate,
295
+ }: {
296
+ block: FlatBlock;
297
+ blockIndex: number;
298
+ theme: ResolvedTheme;
299
+ syntax: SyntaxStyle;
300
+ hScrollableBlocksRef?: RefObject<Map<number, TextBufferRenderable>>;
301
+ codeBlockRenderers?: Record<string, CodeBlockRenderer>;
302
+ onLinkActivate?: MarkdownLinkHandler;
303
+ }): ReactNode {
304
+ const { token, indent, bullet } = block;
305
+
306
+ // List item line (has bullet)
307
+ if (bullet !== undefined) {
308
+ // oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): preserve deliberate top-down renderer organization
309
+ return <ListLineRenderer block={block} theme={theme} onLinkActivate={onLinkActivate} />;
310
+ }
311
+
312
+ // Regular block token
313
+ switch (token.type) {
314
+ case "heading": {
315
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
316
+ const headingToken = token as Tokens.Heading;
317
+ return (
318
+ // oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): preserve deliberate top-down renderer organization
319
+ <HeadingRenderer
320
+ token={headingToken}
321
+ theme={theme}
322
+ indent={indent}
323
+ onLinkActivate={onLinkActivate}
324
+ />
325
+ );
326
+ }
327
+ case "paragraph": {
328
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
329
+ const paragraphToken = token as Tokens.Paragraph;
330
+ return (
331
+ // oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): preserve deliberate top-down renderer organization
332
+ <ParagraphRenderer
333
+ token={paragraphToken}
334
+ theme={theme}
335
+ indent={indent}
336
+ onLinkActivate={onLinkActivate}
337
+ />
338
+ );
339
+ }
340
+ case "code": {
341
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
342
+ const codeToken = token as Tokens.Code;
343
+ return (
344
+ <CodeBlock
345
+ token={codeToken}
346
+ blockIndex={blockIndex}
347
+ theme={theme}
348
+ syntax={syntax}
349
+ indent={indent}
350
+ hScrollableBlocksRef={hScrollableBlocksRef}
351
+ renderers={codeBlockRenderers}
352
+ />
353
+ );
354
+ }
355
+ case "blockquote": {
356
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
357
+ const blockquoteToken = token as Tokens.Blockquote;
358
+ return (
359
+ // oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): preserve deliberate top-down renderer organization
360
+ <BlockquoteRenderer
361
+ token={blockquoteToken}
362
+ theme={theme}
363
+ indent={indent}
364
+ onLinkActivate={onLinkActivate}
365
+ />
366
+ );
367
+ }
368
+ case "table": {
369
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
370
+ const tableToken = token as Tokens.Table;
371
+ // oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): preserve deliberate top-down renderer organization
372
+ return <MarkdownTableRenderer token={tableToken} indent={indent} />;
373
+ }
374
+ case "hr": {
375
+ // oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): preserve deliberate top-down renderer organization
376
+ return <HorizontalRule theme={theme} indent={indent} />;
377
+ }
378
+ case "space":
379
+ case "html": {
380
+ return null;
381
+ }
382
+ default: {
383
+ if ("text" in token && typeof token.text === "string") {
384
+ return (
385
+ <text
386
+ content={token.text}
387
+ style={{
388
+ fg: theme.markdownText,
389
+ marginBottom: 1,
390
+ marginLeft: 1 + indent,
391
+ marginRight: 1,
392
+ marginTop: 0,
393
+ }}
394
+ />
395
+ );
396
+ }
397
+ return null;
398
+ }
399
+ }
400
+ };
401
+
402
+ // ---------------------------------------------------------------------------
403
+ // List line renderer
404
+ // ---------------------------------------------------------------------------
405
+
406
+ const ListLineRenderer = function ListLineRenderer({
407
+ block,
408
+ theme,
409
+ onLinkActivate,
410
+ }: {
411
+ block: FlatBlock;
412
+ theme: ResolvedTheme;
413
+ onLinkActivate?: MarkdownLinkHandler;
414
+ }): ReactNode {
415
+ const { token, indent, bullet, checked } = block;
416
+ const checkboxPrefix = checkboxMarker(checked);
417
+
418
+ // Get inline tokens from the text/paragraph token
419
+ const inlineTokens: Token[] =
420
+ "tokens" in token && Array.isArray(token.tokens) ? token.tokens : [];
421
+
422
+ const hasText = "text" in token && typeof token.text === "string" && token.text.length > 0;
423
+ const hasContent = inlineTokens.length > 0 || hasText;
424
+
425
+ let content: ReactNode = null;
426
+ if (inlineTokens.length > 0) {
427
+ // oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): preserve deliberate top-down renderer organization
428
+ content = <InlineTokens tokens={inlineTokens} theme={theme} />;
429
+ } else if (hasText) {
430
+ const tokenText: unknown = "text" in token ? token.text : "";
431
+ content = typeof tokenText === "string" ? tokenText : "";
432
+ }
433
+
434
+ return (
435
+ <box style={{ marginLeft: 1 + indent, marginRight: 1 }}>
436
+ <text
437
+ style={{ fg: theme.markdownText }}
438
+ onMouseDown={linkMouseHandler(
439
+ inlineTokens,
440
+ onLinkActivate,
441
+ Bun.stringWidth(`${bullet}${checkboxPrefix}`),
442
+ )}
443
+ >
444
+ <span fg={theme.markdownListItem}>{bullet}</span>
445
+ {checkboxPrefix !== "" && (
446
+ <span fg={checked === true ? theme.accent : theme.textMuted}>{checkboxPrefix}</span>
447
+ )}
448
+ {hasContent && content}
449
+ </text>
450
+ </box>
451
+ );
452
+ };
453
+
454
+ // ---------------------------------------------------------------------------
455
+ // Block renderers
456
+ // ---------------------------------------------------------------------------
457
+
458
+ const HeadingRenderer = function HeadingRenderer({
459
+ token,
460
+ theme,
461
+ indent,
462
+ onLinkActivate,
463
+ }: {
464
+ token: Tokens.Heading;
465
+ theme: ResolvedTheme;
466
+ indent: number;
467
+ onLinkActivate?: MarkdownLinkHandler;
468
+ }): ReactNode {
469
+ const headingColors: Record<number, string> = {
470
+ 1: theme.markdownHeading,
471
+ 2: theme.secondary,
472
+ 3: theme.accent,
473
+ 4: theme.text,
474
+ 5: theme.textMuted,
475
+ 6: theme.textMuted,
476
+ };
477
+
478
+ const prefixes: Record<number, string> = {
479
+ 1: "# ",
480
+ 2: "## ",
481
+ 3: "### ",
482
+ 4: "#### ",
483
+ 5: "##### ",
484
+ 6: "###### ",
485
+ };
486
+
487
+ return (
488
+ <box style={{ marginBottom: 1, marginLeft: indent, marginTop: 1 }}>
489
+ <text
490
+ style={{ fg: headingColors[token.depth] || theme.text }}
491
+ onMouseDown={linkMouseHandler(
492
+ token.tokens,
493
+ onLinkActivate,
494
+ Bun.stringWidth(prefixes[token.depth] || ""),
495
+ )}
496
+ >
497
+ <span fg={theme.textMuted}>{prefixes[token.depth]}</span>
498
+ <strong>
499
+ {/* oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): preserve deliberate top-down renderer organization */}
500
+ <InlineTokens tokens={token.tokens} theme={theme} />
501
+ </strong>
502
+ </text>
503
+ </box>
504
+ );
505
+ };
506
+
507
+ const ParagraphRenderer = function ParagraphRenderer({
508
+ token,
509
+ theme,
510
+ indent,
511
+ onLinkActivate,
512
+ }: {
513
+ token: Tokens.Paragraph;
514
+ theme: ResolvedTheme;
515
+ indent: number;
516
+ onLinkActivate?: MarkdownLinkHandler;
517
+ }): ReactNode {
518
+ return (
519
+ <box style={{ marginBottom: 1, marginLeft: 1 + indent, marginRight: 1 }}>
520
+ <text
521
+ style={{ fg: theme.markdownText }}
522
+ onMouseDown={linkMouseHandler(token.tokens, onLinkActivate)}
523
+ >
524
+ {/* oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): preserve deliberate top-down renderer organization */}
525
+ <InlineTokens tokens={token.tokens} theme={theme} />
526
+ </text>
527
+ </box>
528
+ );
529
+ };
530
+
531
+ const BlockquoteRenderer = function BlockquoteRenderer({
532
+ token,
533
+ theme,
534
+ indent,
535
+ onLinkActivate,
536
+ }: {
537
+ token: Tokens.Blockquote;
538
+ theme: ResolvedTheme;
539
+ indent: number;
540
+ onLinkActivate?: MarkdownLinkHandler;
541
+ }): ReactNode {
542
+ // Collect inline tokens from blockquote's child paragraphs/text
543
+ const inlineTokens: Token[] = [];
544
+ for (const child of token.tokens) {
545
+ if ("tokens" in child && Array.isArray(child.tokens)) {
546
+ if (inlineTokens.length > 0) {
547
+ inlineTokens.push({ raw: "\n", text: "\n", type: "text" });
548
+ }
549
+ inlineTokens.push(...child.tokens);
550
+ } else if ("text" in child && typeof child.text === "string") {
551
+ inlineTokens.push(child);
552
+ }
553
+ }
554
+
555
+ return (
556
+ <box
557
+ style={{
558
+ marginBottom: 1,
559
+ marginLeft: 1 + indent,
560
+ marginRight: 1,
561
+ marginTop: 0,
562
+ paddingLeft: 2,
563
+ }}
564
+ >
565
+ <text style={{ fg: theme.markdownBlockQuote }} content="│ " />
566
+ <text
567
+ style={{ fg: theme.textMuted }}
568
+ onMouseDown={linkMouseHandler(inlineTokens, onLinkActivate)}
569
+ >
570
+ {/* oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): preserve deliberate top-down renderer organization */}
571
+ <InlineTokens tokens={inlineTokens} theme={theme} />
572
+ </text>
573
+ </box>
574
+ );
575
+ };
576
+
577
+ const MarkdownTableRenderer = function MarkdownTableRenderer({
578
+ token,
579
+ indent,
580
+ }: {
581
+ token: Tokens.Table;
582
+ indent: number;
583
+ }): ReactNode {
584
+ const { theme } = useTheme();
585
+
586
+ const content: TextTableContent = useMemo(() => {
587
+ const headerRow: TextTableCellContent[] = token.header.map((cell) => {
588
+ // oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): preserve deliberate top-down renderer organization
589
+ const chunks = inlineTokensToChunks(cell.tokens, theme);
590
+ // Wrap header chunks in bold
591
+ return chunks.length > 0
592
+ ? chunks.map((c) => boldChunk(c))
593
+ : [
594
+ // oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): preserve deliberate top-down renderer organization
595
+ boldChunk(getPlainText(cell.tokens).trim()),
596
+ ];
597
+ });
598
+ const dataRows = token.rows.map((row) =>
599
+ row.map((cell) => {
600
+ // oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): preserve deliberate top-down renderer organization
601
+ const chunks = inlineTokensToChunks(cell.tokens, theme);
602
+ return chunks.length > 0
603
+ ? chunks
604
+ : ([
605
+ // oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): preserve deliberate top-down renderer organization
606
+ { __isChunk: true as const, text: getPlainText(cell.tokens) },
607
+ ] as TextTableCellContent);
608
+ }),
609
+ );
610
+ return [headerRow, ...dataRows];
611
+ }, [token, theme]);
612
+
613
+ return (
614
+ <box style={{ marginBottom: 1, marginLeft: 1 + indent, marginRight: 1 }}>
615
+ <text-table
616
+ content={content}
617
+ wrapMode="word"
618
+ columnWidthMode="content"
619
+ cellPadding={0}
620
+ border={true}
621
+ borderStyle="single"
622
+ borderColor={theme.border}
623
+ fg={theme.text}
624
+ />
625
+ </box>
626
+ );
627
+ };
628
+
629
+ const HorizontalRule = function HorizontalRule({
630
+ theme,
631
+ indent,
632
+ }: {
633
+ theme: ResolvedTheme;
634
+ indent: number;
635
+ }): ReactNode {
636
+ return (
637
+ <box style={{ marginBottom: 1, marginLeft: 1 + indent, marginRight: 1, marginTop: 0 }}>
638
+ <text style={{ fg: theme.markdownHorizontalRule }} content={"─".repeat(40)} />
639
+ </box>
640
+ );
641
+ };
642
+
643
+ // ---------------------------------------------------------------------------
644
+ // Inline token rendering (React elements)
645
+ // ---------------------------------------------------------------------------
646
+
647
+ const InlineTokens = function InlineTokens({
648
+ tokens,
649
+ theme,
650
+ }: {
651
+ tokens: Token[];
652
+ theme: ResolvedTheme;
653
+ }): ReactNode {
654
+ const result: ReactNode[] = [];
655
+
656
+ for (let i = 0; i < tokens.length; i += 1) {
657
+ const token = tokens[i];
658
+ if (token === undefined) {
659
+ continue;
660
+ }
661
+ const key = i;
662
+
663
+ switch (token.type) {
664
+ case "text": {
665
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
666
+ result.push((token as Tokens.Text).text);
667
+ break;
668
+ }
669
+ case "strong": {
670
+ result.push(
671
+ <strong key={key}>
672
+ {/* oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): preserve deliberate top-down renderer organization */}
673
+ {/* oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep */}
674
+ <InlineTokens tokens={(token as Tokens.Strong).tokens} theme={theme} />
675
+ </strong>,
676
+ );
677
+ break;
678
+ }
679
+ case "em": {
680
+ result.push(
681
+ <em key={key}>
682
+ {/* oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): preserve deliberate top-down renderer organization */}
683
+ {/* oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep */}
684
+ <InlineTokens tokens={(token as Tokens.Em).tokens} theme={theme} />
685
+ </em>,
686
+ );
687
+ break;
688
+ }
689
+ case "codespan": {
690
+ result.push(
691
+ <span key={key} fg={theme.markdownCode} bg={theme.backgroundPanel}>
692
+ {/* oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep */}
693
+ {` ${(token as Tokens.Codespan).text} `}
694
+ </span>,
695
+ );
696
+ break;
697
+ }
698
+ case "link": {
699
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
700
+ const linkToken = token as Tokens.Link;
701
+ result.push(
702
+ <u key={key}>
703
+ <a href={linkToken.href} fg={theme.markdownLink}>
704
+ {/* oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): preserve deliberate top-down renderer organization */}
705
+ <InlineTokens tokens={linkToken.tokens} theme={theme} />
706
+ </a>
707
+ </u>,
708
+ );
709
+ break;
710
+ }
711
+ case "del": {
712
+ result.push(
713
+ <span key={key} fg={theme.textMuted}>
714
+ ~
715
+ {/* oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): preserve deliberate top-down renderer organization */}
716
+ {/* oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep */}
717
+ <InlineTokens tokens={(token as Tokens.Del).tokens} theme={theme} />~
718
+ </span>,
719
+ );
720
+ break;
721
+ }
722
+ case "image": {
723
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
724
+ const imgToken = token as Tokens.Image;
725
+ result.push(
726
+ <span key={key} fg={theme.textMuted}>
727
+ {imgToken.text || imgToken.href}
728
+ </span>,
729
+ );
730
+ break;
731
+ }
732
+ case "br": {
733
+ result.push("\n");
734
+ break;
735
+ }
736
+ case "escape": {
737
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
738
+ result.push((token as Tokens.Escape).text);
739
+ break;
740
+ }
741
+ case "space": {
742
+ result.push(" ");
743
+ break;
744
+ }
745
+ default: {
746
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
747
+ if ("text" in token && typeof (token as { text?: string }).text === "string") {
748
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
749
+ result.push((token as { text: string }).text);
750
+ }
751
+ break;
752
+ }
753
+ }
754
+ }
755
+
756
+ return result;
757
+ };
758
+
759
+ // ---------------------------------------------------------------------------
760
+ // Inline token rendering (TextChunks — for text-table cells)
761
+ // ---------------------------------------------------------------------------
762
+
763
+ const inlineTokensToChunks = function inlineTokensToChunks(
764
+ tokens: Token[],
765
+ theme: ResolvedTheme,
766
+ ): TextChunk[] {
767
+ const chunks: TextChunk[] = [];
768
+
769
+ for (const token of tokens) {
770
+ switch (token.type) {
771
+ case "text": {
772
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
773
+ chunks.push({ __isChunk: true as const, text: (token as Tokens.Text).text });
774
+ break;
775
+ }
776
+ case "strong": {
777
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
778
+ for (const sub of inlineTokensToChunks((token as Tokens.Strong).tokens, theme)) {
779
+ chunks.push(boldChunk(sub));
780
+ }
781
+ break;
782
+ }
783
+ case "em": {
784
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
785
+ for (const sub of inlineTokensToChunks((token as Tokens.Em).tokens, theme)) {
786
+ chunks.push(italicChunk(sub));
787
+ }
788
+ break;
789
+ }
790
+ case "codespan": {
791
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
792
+ const codespanToken = token as Tokens.Codespan;
793
+ chunks.push({
794
+ __isChunk: true as const,
795
+ bg: parseColor(theme.backgroundPanel),
796
+ fg: parseColor(theme.markdownCode),
797
+ text: ` ${codespanToken.text} `,
798
+ });
799
+ break;
800
+ }
801
+ case "link": {
802
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
803
+ const linkToken = token as Tokens.Link;
804
+ for (const sub of inlineTokensToChunks(linkToken.tokens, theme)) {
805
+ chunks.push(underlineChunk({ ...sub, fg: parseColor(theme.markdownLink) }));
806
+ }
807
+ break;
808
+ }
809
+ case "escape": {
810
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
811
+ chunks.push({ __isChunk: true as const, text: (token as Tokens.Escape).text });
812
+ break;
813
+ }
814
+ default: {
815
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
816
+ if ("text" in token && typeof (token as { text?: string }).text === "string") {
817
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
818
+ chunks.push({ __isChunk: true as const, text: (token as { text: string }).text });
819
+ }
820
+ break;
821
+ }
822
+ }
823
+ }
824
+
825
+ return chunks;
826
+ };
827
+
828
+ // ---------------------------------------------------------------------------
829
+ // Plain text extraction (only for width computation, not rendering)
830
+ // ---------------------------------------------------------------------------
831
+
832
+ const getPlainText = function getPlainText(tokens: Token[]): string {
833
+ return tokens
834
+ .map((token) => {
835
+ if (token.type === "text") {
836
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
837
+ return (token as { text: string }).text;
838
+ }
839
+ if (token.type === "codespan") {
840
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
841
+ return (token as Tokens.Codespan).text;
842
+ }
843
+ if ("tokens" in token && token.tokens) {
844
+ return getPlainText(token.tokens);
845
+ }
846
+ if ("text" in token) {
847
+ const tokenText: unknown = token.text;
848
+ return typeof tokenText === "string" ? tokenText : "";
849
+ }
850
+ return "";
851
+ })
852
+ .join("");
853
+ };