@tooee/renderers 0.7.2 → 0.8.0

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 (126) hide show
  1. package/dist/code-blocks.d.ts +2 -1
  2. package/dist/code-blocks.d.ts.map +1 -1
  3. package/dist/code-blocks.js +20 -18
  4. package/dist/code-blocks.js.map +1 -1
  5. package/dist/code-view.d.ts +2 -1
  6. package/dist/code-view.d.ts.map +1 -1
  7. package/dist/code-view.js.map +1 -1
  8. package/dist/command-palette.d.ts +2 -1
  9. package/dist/command-palette.d.ts.map +1 -1
  10. package/dist/command-palette.js +16 -23
  11. package/dist/command-palette.js.map +1 -1
  12. package/dist/context-menu.d.ts +2 -1
  13. package/dist/context-menu.d.ts.map +1 -1
  14. package/dist/context-menu.js +50 -15
  15. package/dist/context-menu.js.map +1 -1
  16. package/dist/index.d.ts +3 -3
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +1 -1
  19. package/dist/index.js.map +1 -1
  20. package/dist/markdown/blocks/blockquote.d.ts +11 -0
  21. package/dist/markdown/blocks/blockquote.d.ts.map +1 -0
  22. package/dist/markdown/blocks/blockquote.js +26 -0
  23. package/dist/markdown/blocks/blockquote.js.map +1 -0
  24. package/dist/markdown/blocks/flat-block.d.ts +20 -0
  25. package/dist/markdown/blocks/flat-block.d.ts.map +1 -0
  26. package/dist/markdown/blocks/flat-block.js +52 -0
  27. package/dist/markdown/blocks/flat-block.js.map +1 -0
  28. package/dist/markdown/blocks/heading.d.ts +11 -0
  29. package/dist/markdown/blocks/heading.d.ts.map +1 -0
  30. package/dist/markdown/blocks/heading.js +23 -0
  31. package/dist/markdown/blocks/heading.js.map +1 -0
  32. package/dist/markdown/blocks/horizontal-rule.d.ts +7 -0
  33. package/dist/markdown/blocks/horizontal-rule.d.ts.map +1 -0
  34. package/dist/markdown/blocks/horizontal-rule.js +5 -0
  35. package/dist/markdown/blocks/horizontal-rule.js.map +1 -0
  36. package/dist/markdown/blocks/list-line.d.ts +10 -0
  37. package/dist/markdown/blocks/list-line.d.ts.map +1 -0
  38. package/dist/markdown/blocks/list-line.js +21 -0
  39. package/dist/markdown/blocks/list-line.js.map +1 -0
  40. package/dist/markdown/blocks/paragraph.d.ts +12 -0
  41. package/dist/markdown/blocks/paragraph.d.ts.map +1 -0
  42. package/dist/markdown/blocks/paragraph.js +27 -0
  43. package/dist/markdown/blocks/paragraph.js.map +1 -0
  44. package/dist/markdown/blocks/table.d.ts +7 -0
  45. package/dist/markdown/blocks/table.d.ts.map +1 -0
  46. package/dist/markdown/blocks/table.js +30 -0
  47. package/dist/markdown/blocks/table.js.map +1 -0
  48. package/dist/markdown/chunks.d.ts +5 -0
  49. package/dist/markdown/chunks.d.ts.map +1 -0
  50. package/dist/markdown/chunks.js +29 -0
  51. package/dist/markdown/chunks.js.map +1 -0
  52. package/dist/markdown/inline.d.ts +8 -0
  53. package/dist/markdown/inline.d.ts.map +1 -0
  54. package/dist/markdown/inline.js +27 -0
  55. package/dist/markdown/inline.js.map +1 -0
  56. package/dist/markdown/links.d.ts +11 -0
  57. package/dist/markdown/links.d.ts.map +1 -0
  58. package/dist/markdown/links.js +107 -0
  59. package/dist/markdown/links.js.map +1 -0
  60. package/dist/markdown/plain-text.d.ts +4 -0
  61. package/dist/markdown/plain-text.d.ts.map +1 -0
  62. package/dist/markdown/plain-text.js +21 -0
  63. package/dist/markdown/plain-text.js.map +1 -0
  64. package/dist/markdown/tokens.d.ts +32 -0
  65. package/dist/markdown/tokens.d.ts.map +1 -0
  66. package/dist/markdown/tokens.js +25 -0
  67. package/dist/markdown/tokens.js.map +1 -0
  68. package/dist/markdown/visit-inline.d.ts +17 -0
  69. package/dist/markdown/visit-inline.d.ts.map +1 -0
  70. package/dist/markdown/visit-inline.js +61 -0
  71. package/dist/markdown/visit-inline.js.map +1 -0
  72. package/dist/markdown-blocks.d.ts.map +1 -1
  73. package/dist/markdown-blocks.js +6 -4
  74. package/dist/markdown-blocks.js.map +1 -1
  75. package/dist/markdown-images.d.ts.map +1 -1
  76. package/dist/markdown-images.js +14 -5
  77. package/dist/markdown-images.js.map +1 -1
  78. package/dist/markdown-view.d.ts +10 -32
  79. package/dist/markdown-view.d.ts.map +1 -1
  80. package/dist/markdown-view.js +9 -468
  81. package/dist/markdown-view.js.map +1 -1
  82. package/dist/mermaid.d.ts +5 -4
  83. package/dist/mermaid.d.ts.map +1 -1
  84. package/dist/mermaid.js +5 -5
  85. package/dist/mermaid.js.map +1 -1
  86. package/dist/parsers.d.ts +6 -13
  87. package/dist/parsers.d.ts.map +1 -1
  88. package/dist/parsers.js +66 -46
  89. package/dist/parsers.js.map +1 -1
  90. package/dist/row-document-renderable.d.ts +7 -6
  91. package/dist/row-document-renderable.d.ts.map +1 -1
  92. package/dist/row-document-renderable.js +2 -7
  93. package/dist/row-document-renderable.js.map +1 -1
  94. package/dist/table-types.d.ts +4 -0
  95. package/dist/table-types.d.ts.map +1 -1
  96. package/dist/table.d.ts +4 -1
  97. package/dist/table.d.ts.map +1 -1
  98. package/dist/table.js +30 -23
  99. package/dist/table.js.map +1 -1
  100. package/package.json +7 -5
  101. package/src/code-blocks.tsx +28 -26
  102. package/src/code-view.tsx +2 -1
  103. package/src/command-palette.tsx +46 -31
  104. package/src/context-menu.tsx +54 -15
  105. package/src/index.ts +7 -3
  106. package/src/markdown/blocks/blockquote.tsx +53 -0
  107. package/src/markdown/blocks/flat-block.tsx +119 -0
  108. package/src/markdown/blocks/heading.tsx +53 -0
  109. package/src/markdown/blocks/horizontal-rule.tsx +16 -0
  110. package/src/markdown/blocks/list-line.tsx +52 -0
  111. package/src/markdown/blocks/paragraph.tsx +90 -0
  112. package/src/markdown/blocks/table.tsx +55 -0
  113. package/src/markdown/chunks.ts +42 -0
  114. package/src/markdown/inline.tsx +45 -0
  115. package/src/markdown/links.ts +133 -0
  116. package/src/markdown/plain-text.ts +22 -0
  117. package/src/markdown/tokens.ts +53 -0
  118. package/src/markdown/visit-inline.ts +82 -0
  119. package/src/markdown-blocks.ts +6 -4
  120. package/src/markdown-images.ts +15 -6
  121. package/src/markdown-view.tsx +20 -845
  122. package/src/mermaid.ts +11 -9
  123. package/src/parsers.ts +86 -62
  124. package/src/row-document-renderable.ts +13 -15
  125. package/src/table-types.ts +5 -0
  126. package/src/table.tsx +36 -30
@@ -1,53 +1,27 @@
1
- import type { Token, Tokens } from "marked";
2
- import { useEffect, useMemo, useState } from "react";
3
- import { useTerminalDimensions } from "@opentui/react";
1
+ import { useMemo } from "react";
4
2
  import type { ReactNode, RefObject } from "react";
3
+ import type { TextBufferRenderable } from "@opentui/core";
4
+ import { useTerminalDimensions } from "@opentui/react";
5
5
  import { useTheme } from "@tooee/themes";
6
- import type { ResolvedTheme } from "@tooee/themes";
7
- import {
8
- bold as boldChunk,
9
- italic as italicChunk,
10
- underline as underlineChunk,
11
- parseColor,
12
- } from "@opentui/core";
13
- import type {
14
- SyntaxStyle,
15
- TextBufferRenderable,
16
- TextTableContent,
17
- TextTableCellContent,
18
- TextChunk,
19
- MouseEvent,
20
- } from "@opentui/core";
6
+ import { DEFAULT_CODE_BLOCK_RENDERERS } from "./code-blocks.js";
7
+ import type { CodeBlockRenderer } from "./code-blocks.js";
21
8
  import type { DocumentBindings } from "./document-bindings.js";
9
+ import { flattenMarkdown } from "./markdown-blocks.js";
10
+ import type { FlatBlock } from "./markdown-blocks.js";
11
+ import { FlatBlockRenderer } from "./markdown/blocks/flat-block.js";
12
+ import type { MarkdownLinkHandler } from "./markdown/links.js";
22
13
  import {
23
14
  DEFAULT_SIGN_COLUMN_WIDTH,
24
15
  computeRowDocumentGutterWidth,
25
16
  } from "./row-document-renderable.js";
26
17
  import { useGutterPalette } from "./use-gutter-palette.js";
27
- import { CodeBlock, DEFAULT_CODE_BLOCK_RENDERERS } from "./code-blocks.js";
28
- import type { CodeBlockRenderer } from "./code-blocks.js";
29
- import { checkboxMarker, flattenMarkdown } from "./markdown-blocks.js";
30
- import type { FlatBlock } from "./markdown-blocks.js";
31
- import { resolveMarkdownImageSource, splitMarkdownImages } from "./markdown-images.js";
32
- import type { MarkdownImageEmbed } from "./markdown-images.js";
33
18
  import "./row-document.js";
34
19
  import "./text-table.js";
35
20
 
36
- // ---------------------------------------------------------------------------
37
- // Types
38
- // ---------------------------------------------------------------------------
39
-
40
- export type MarkdownLinkHandler = (href: string) => unknown;
21
+ export { inlineLinkAtPosition } from "./markdown/links.js";
22
+ export type { InlineLinkPosition, MarkdownLinkHandler } from "./markdown/links.js";
41
23
 
42
- export interface InlineLinkPosition {
43
- line: number;
44
- column: number;
45
- }
46
-
47
- /** Markdown soft line endings separate prose words without forcing a rendered break. */
48
- const normalizeSoftLineEndings = function normalizeSoftLineEndings(value: string): string {
49
- return value.replaceAll("\n", " ");
50
- };
24
+ type CodeBlockRendererRegistry = Record<string, CodeBlockRenderer>;
51
25
 
52
26
  interface MarkdownViewProps {
53
27
  content: string;
@@ -61,7 +35,7 @@ interface MarkdownViewProps {
61
35
  showLineNumbers?: boolean;
62
36
  /**
63
37
  * Binds the row document to a document controller: its ref, the decoration
64
- * layers to paint, and the mouse handler. Rows are flattened *block* indices —
38
+ * layers to paint, and the mouse handler. Rows are flattened *block* indices,
65
39
  * the same unit `j`/`k` move between and copy operates on. Omit it to render
66
40
  * a static, non-interactive document.
67
41
  *
@@ -72,171 +46,16 @@ interface MarkdownViewProps {
72
46
  * stops propagation.
73
47
  */
74
48
  document?: DocumentBindings;
75
- /**
76
- * Registry of horizontally scrollable blocks, keyed by block index. Blocks
77
- * that can overflow horizontally (mermaid diagrams and code blocks)
78
- * register their text-buffer renderable here so the owning subview can
79
- * drive horizontal panning (`scrollX`) for the block under the nav cursor
80
- * (h/l in cursor mode).
81
- */
49
+ /** Registry of horizontally scrollable blocks, keyed by block index. */
82
50
  hScrollableBlocksRef?: RefObject<Map<number, TextBufferRenderable>>;
83
- /**
84
- * Custom renderers for fenced code blocks, keyed by fence type. A fence's
85
- * type is the first whitespace-separated word of its info string, matched
86
- * case-insensitively. Entries are merged over the built-in defaults
87
- * (currently `mermaid`), so built-ins can be overridden. Unmatched types —
88
- * and renderers that return `null` or throw — fall back to the default
89
- * syntax-highlighted code block.
90
- */
91
- codeBlockRenderers?: Record<string, CodeBlockRenderer>;
92
- /**
93
- * Called when the primary mouse button activates inline Markdown link text.
94
- * Return `true` when the host handled the href; handled clicks do not bubble
95
- * to document row selection. Unhandled links retain their native OSC-8 href.
96
- */
51
+ /** Custom fenced-code renderers merged over the built-in defaults. */
52
+ codeBlockRenderers?: CodeBlockRendererRegistry;
53
+ /** Called when the primary mouse button activates inline Markdown link text. */
97
54
  onLinkActivate?: MarkdownLinkHandler;
98
55
  /** Directory used to resolve relative standard Markdown and Obsidian image embeds. */
99
56
  imageBasePath?: string;
100
57
  }
101
58
 
102
- // ---------------------------------------------------------------------------
103
- // Inline link hit testing
104
- // ---------------------------------------------------------------------------
105
-
106
- /** Resolve a rendered text position to the Markdown link occupying that cell. */
107
- export const inlineLinkAtPosition = function inlineLinkAtPosition(
108
- tokens: readonly Token[],
109
- position: InlineLinkPosition,
110
- initialColumn = 0,
111
- ): string | null {
112
- let line = 0;
113
- let column = initialColumn;
114
- let found: string | null = null;
115
-
116
- const advanceText = (value: string, href?: string): void => {
117
- const parts = value.split("\n");
118
- for (const [index, part] of parts.entries()) {
119
- const width = Bun.stringWidth(part);
120
- if (
121
- href !== undefined &&
122
- line === position.line &&
123
- position.column >= column &&
124
- position.column < column + width
125
- ) {
126
- found = href;
127
- }
128
- column += width;
129
- if (index < parts.length - 1) {
130
- line += 1;
131
- column = 0;
132
- }
133
- }
134
- };
135
-
136
- const visit = (items: readonly Token[], href?: string): void => {
137
- for (const token of items) {
138
- if (found !== null) {
139
- return;
140
- }
141
- switch (token.type) {
142
- case "text": {
143
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
144
- advanceText(normalizeSoftLineEndings((token as Tokens.Text).text), href);
145
- break;
146
- }
147
- case "link": {
148
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
149
- const link = token as Tokens.Link;
150
- visit(link.tokens, link.href);
151
- break;
152
- }
153
- case "strong": {
154
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
155
- visit((token as Tokens.Strong).tokens, href);
156
- break;
157
- }
158
- case "em": {
159
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
160
- visit((token as Tokens.Em).tokens, href);
161
- break;
162
- }
163
- case "del": {
164
- advanceText("~", href);
165
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
166
- visit((token as Tokens.Del).tokens, href);
167
- advanceText("~", href);
168
- break;
169
- }
170
- case "codespan": {
171
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
172
- advanceText(` ${(token as Tokens.Codespan).text} `, href);
173
- break;
174
- }
175
- case "br": {
176
- advanceText("\n", href);
177
- break;
178
- }
179
- case "space": {
180
- advanceText(" ", href);
181
- break;
182
- }
183
- default: {
184
- if ("text" in token && typeof token.text === "string") {
185
- advanceText(token.text, href);
186
- }
187
- }
188
- }
189
- }
190
- };
191
-
192
- visit(tokens);
193
- return found;
194
- };
195
-
196
- const linkMouseHandler = function linkMouseHandler(
197
- tokens: readonly Token[],
198
- onLinkActivate: MarkdownLinkHandler | undefined,
199
- initialColumn = 0,
200
- ): ((event: MouseEvent) => void) | undefined {
201
- if (onLinkActivate === undefined) {
202
- return undefined;
203
- }
204
- return (event: MouseEvent): void => {
205
- if (event.button !== 0) {
206
- return;
207
- }
208
- const { target } = event;
209
- if (target === null || target === undefined || !("lineInfo" in target)) {
210
- return;
211
- }
212
- // 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
213
- const text = target as TextBufferRenderable;
214
- const visualLine = event.y - text.y;
215
- const sourceLine = text.lineInfo.lineSources[visualLine];
216
- const startColumn = text.lineInfo.lineStartCols[visualLine];
217
- if (sourceLine === undefined || startColumn === undefined) {
218
- return;
219
- }
220
- const href = inlineLinkAtPosition(
221
- tokens,
222
- {
223
- column: startColumn + event.x - text.x,
224
- line: sourceLine,
225
- },
226
- initialColumn,
227
- );
228
- if (href === null || onLinkActivate(href) !== true) {
229
- return;
230
- }
231
- event.preventDefault();
232
- event.stopPropagation();
233
- };
234
- };
235
-
236
- // ---------------------------------------------------------------------------
237
- // Component
238
- // ---------------------------------------------------------------------------
239
-
240
59
  /** Columns held back from the measured width for the scrollbar and right edge. */
241
60
  const MARKDOWN_SCROLLBAR_RESERVE = 2;
242
61
 
@@ -258,8 +77,6 @@ export const MarkdownView = function MarkdownView({
258
77
  [providedBlocks, content],
259
78
  );
260
79
 
261
- // Blocks that must be told their width (diff fences) need the columns left
262
- // after the row-document gutter and the scrollbar.
263
80
  const contentWidth = Math.max(
264
81
  1,
265
82
  terminalWidth -
@@ -271,21 +88,18 @@ export const MarkdownView = function MarkdownView({
271
88
  MARKDOWN_SCROLLBAR_RESERVE,
272
89
  );
273
90
 
274
- // Merge user renderers over built-in defaults, normalizing keys to
275
- // lowercase so registration matches fence types case-insensitively.
276
91
  const mergedCodeBlockRenderers = useMemo(() => {
277
- const merged: Record<string, CodeBlockRenderer> = { ...DEFAULT_CODE_BLOCK_RENDERERS };
92
+ const entries = new Map(Object.entries(DEFAULT_CODE_BLOCK_RENDERERS));
278
93
  for (const [key, renderer] of Object.entries(codeBlockRenderers ?? {})) {
279
- merged[key.trim().toLowerCase()] = renderer;
94
+ entries.set(key.trim().toLowerCase(), renderer);
280
95
  }
281
- return merged;
96
+ return Object.fromEntries(entries);
282
97
  }, [codeBlockRenderers]);
283
98
 
284
99
  const blockElements = useMemo(
285
100
  () =>
286
101
  blocks.map(
287
102
  (block, index): ReactNode => (
288
- // oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): preserve deliberate top-down renderer organization
289
103
  <FlatBlockRenderer
290
104
  key={index}
291
105
  block={block}
@@ -326,642 +140,3 @@ export const MarkdownView = function MarkdownView({
326
140
  </row-document>
327
141
  );
328
142
  };
329
-
330
- // ---------------------------------------------------------------------------
331
- // Block renderer (flat)
332
- // ---------------------------------------------------------------------------
333
-
334
- const FlatBlockRenderer = function FlatBlockRenderer({
335
- block,
336
- blockIndex,
337
- theme,
338
- syntax,
339
- contentWidth,
340
- hScrollableBlocksRef,
341
- codeBlockRenderers,
342
- onLinkActivate,
343
- imageBasePath,
344
- }: {
345
- block: FlatBlock;
346
- blockIndex: number;
347
- theme: ResolvedTheme;
348
- syntax: SyntaxStyle;
349
- contentWidth: number;
350
- hScrollableBlocksRef?: RefObject<Map<number, TextBufferRenderable>>;
351
- codeBlockRenderers?: Record<string, CodeBlockRenderer>;
352
- onLinkActivate?: MarkdownLinkHandler;
353
- imageBasePath?: string;
354
- }): ReactNode {
355
- const { token, indent, bullet } = block;
356
-
357
- // List item line (has bullet)
358
- if (bullet !== undefined) {
359
- // oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): preserve deliberate top-down renderer organization
360
- return <ListLineRenderer block={block} theme={theme} onLinkActivate={onLinkActivate} />;
361
- }
362
-
363
- // Regular block token
364
- switch (token.type) {
365
- case "heading": {
366
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
367
- const headingToken = token as Tokens.Heading;
368
- return (
369
- // oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): preserve deliberate top-down renderer organization
370
- <HeadingRenderer
371
- token={headingToken}
372
- theme={theme}
373
- indent={indent}
374
- onLinkActivate={onLinkActivate}
375
- />
376
- );
377
- }
378
- case "paragraph": {
379
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
380
- const paragraphToken = token as Tokens.Paragraph;
381
- return (
382
- // oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): preserve deliberate top-down renderer organization
383
- <ParagraphRenderer
384
- token={paragraphToken}
385
- theme={theme}
386
- indent={indent}
387
- onLinkActivate={onLinkActivate}
388
- imageBasePath={imageBasePath}
389
- />
390
- );
391
- }
392
- case "code": {
393
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
394
- const codeToken = token as Tokens.Code;
395
- return (
396
- <CodeBlock
397
- token={codeToken}
398
- blockIndex={blockIndex}
399
- theme={theme}
400
- syntax={syntax}
401
- indent={indent}
402
- contentWidth={contentWidth}
403
- hScrollableBlocksRef={hScrollableBlocksRef}
404
- renderers={codeBlockRenderers}
405
- />
406
- );
407
- }
408
- case "blockquote": {
409
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
410
- const blockquoteToken = token as Tokens.Blockquote;
411
- return (
412
- // oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): preserve deliberate top-down renderer organization
413
- <BlockquoteRenderer
414
- token={blockquoteToken}
415
- theme={theme}
416
- indent={indent}
417
- onLinkActivate={onLinkActivate}
418
- />
419
- );
420
- }
421
- case "table": {
422
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
423
- const tableToken = token as Tokens.Table;
424
- // oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): preserve deliberate top-down renderer organization
425
- return <MarkdownTableRenderer token={tableToken} indent={indent} />;
426
- }
427
- case "hr": {
428
- // oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): preserve deliberate top-down renderer organization
429
- return <HorizontalRule theme={theme} indent={indent} />;
430
- }
431
- case "space":
432
- case "html": {
433
- return null;
434
- }
435
- default: {
436
- if ("text" in token && typeof token.text === "string") {
437
- return (
438
- <text
439
- content={token.text}
440
- style={{
441
- fg: theme.markdownText,
442
- marginBottom: 1,
443
- marginLeft: 1 + indent,
444
- marginRight: 1,
445
- marginTop: 0,
446
- }}
447
- />
448
- );
449
- }
450
- return null;
451
- }
452
- }
453
- };
454
-
455
- // ---------------------------------------------------------------------------
456
- // List line renderer
457
- // ---------------------------------------------------------------------------
458
-
459
- const ListLineRenderer = function ListLineRenderer({
460
- block,
461
- theme,
462
- onLinkActivate,
463
- }: {
464
- block: FlatBlock;
465
- theme: ResolvedTheme;
466
- onLinkActivate?: MarkdownLinkHandler;
467
- }): ReactNode {
468
- const { token, indent, bullet, checked } = block;
469
- const checkboxPrefix = checkboxMarker(checked);
470
-
471
- // Get inline tokens from the text/paragraph token
472
- const inlineTokens: Token[] =
473
- "tokens" in token && Array.isArray(token.tokens) ? token.tokens : [];
474
-
475
- const hasText = "text" in token && typeof token.text === "string" && token.text.length > 0;
476
- const hasContent = inlineTokens.length > 0 || hasText;
477
-
478
- let content: ReactNode = null;
479
- if (inlineTokens.length > 0) {
480
- // oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): preserve deliberate top-down renderer organization
481
- content = <InlineTokens tokens={inlineTokens} theme={theme} />;
482
- } else if (hasText) {
483
- const tokenText: unknown = "text" in token ? token.text : "";
484
- content = typeof tokenText === "string" ? tokenText : "";
485
- }
486
-
487
- return (
488
- <box style={{ marginLeft: 1 + indent, marginRight: 1 }}>
489
- <text
490
- style={{ fg: theme.markdownText }}
491
- onMouseDown={linkMouseHandler(
492
- inlineTokens,
493
- onLinkActivate,
494
- Bun.stringWidth(`${bullet}${checkboxPrefix}`),
495
- )}
496
- >
497
- <span fg={theme.markdownListItem}>{bullet}</span>
498
- {checkboxPrefix !== "" && (
499
- <span fg={checked === true ? theme.accent : theme.textMuted}>{checkboxPrefix}</span>
500
- )}
501
- {hasContent && content}
502
- </text>
503
- </box>
504
- );
505
- };
506
-
507
- // ---------------------------------------------------------------------------
508
- // Block renderers
509
- // ---------------------------------------------------------------------------
510
-
511
- const HeadingRenderer = function HeadingRenderer({
512
- token,
513
- theme,
514
- indent,
515
- onLinkActivate,
516
- }: {
517
- token: Tokens.Heading;
518
- theme: ResolvedTheme;
519
- indent: number;
520
- onLinkActivate?: MarkdownLinkHandler;
521
- }): ReactNode {
522
- const headingColors: Record<number, string> = {
523
- 1: theme.markdownHeading,
524
- 2: theme.secondary,
525
- 3: theme.accent,
526
- 4: theme.text,
527
- 5: theme.textMuted,
528
- 6: theme.textMuted,
529
- };
530
-
531
- const prefixes: Record<number, string> = {
532
- 1: "# ",
533
- 2: "## ",
534
- 3: "### ",
535
- 4: "#### ",
536
- 5: "##### ",
537
- 6: "###### ",
538
- };
539
-
540
- return (
541
- <box style={{ marginBottom: 1, marginLeft: indent, marginTop: 1 }}>
542
- <text
543
- style={{ fg: headingColors[token.depth] || theme.text }}
544
- onMouseDown={linkMouseHandler(
545
- token.tokens,
546
- onLinkActivate,
547
- Bun.stringWidth(prefixes[token.depth] || ""),
548
- )}
549
- >
550
- <span fg={theme.textMuted}>{prefixes[token.depth]}</span>
551
- <strong>
552
- {/* oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): preserve deliberate top-down renderer organization */}
553
- <InlineTokens tokens={token.tokens} theme={theme} />
554
- </strong>
555
- </text>
556
- </box>
557
- );
558
- };
559
-
560
- const ParagraphRenderer = function ParagraphRenderer({
561
- token,
562
- theme,
563
- indent,
564
- onLinkActivate,
565
- imageBasePath,
566
- }: {
567
- token: Tokens.Paragraph;
568
- theme: ResolvedTheme;
569
- indent: number;
570
- onLinkActivate?: MarkdownLinkHandler;
571
- imageBasePath?: string;
572
- }): ReactNode {
573
- const segments = splitMarkdownImages(token.tokens);
574
- return (
575
- <box
576
- style={{
577
- flexDirection: "column",
578
- marginBottom: 1,
579
- marginLeft: 1 + indent,
580
- marginRight: 1,
581
- }}
582
- >
583
- {segments.map(
584
- (segment, index): ReactNode =>
585
- segment.type === "image" ? (
586
- // oxlint-disable-next-line no-use-before-define -- Keep paragraph rendering before its image helper.
587
- <MarkdownImage key={index} image={segment} basePath={imageBasePath} theme={theme} />
588
- ) : (
589
- <text
590
- key={index}
591
- style={{ fg: theme.markdownText }}
592
- onMouseDown={linkMouseHandler(segment.tokens, onLinkActivate)}
593
- >
594
- {/* oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): preserve deliberate top-down renderer organization */}
595
- <InlineTokens tokens={segment.tokens} theme={theme} />
596
- </text>
597
- ),
598
- )}
599
- </box>
600
- );
601
- };
602
-
603
- const MarkdownImage = function MarkdownImage({
604
- image,
605
- basePath,
606
- theme,
607
- }: {
608
- image: MarkdownImageEmbed;
609
- basePath?: string;
610
- theme: ResolvedTheme;
611
- }): ReactNode {
612
- const source = resolveMarkdownImageSource(image.source, basePath);
613
- const [state, setState] = useState<"loading" | "loaded" | "error">("loading");
614
-
615
- useEffect(() => {
616
- setState("loading");
617
- }, [source]);
618
-
619
- return (
620
- <box style={{ flexDirection: "column" }}>
621
- {state === "loading" && (
622
- <text content={`Loading image: ${image.alt ?? image.source}`} fg={theme.textMuted} />
623
- )}
624
- {state === "error" && (
625
- <text content={`Image failed to load: ${image.alt ?? image.source}`} fg={theme.error} />
626
- )}
627
- <image
628
- source={source}
629
- fit="fit"
630
- protocol="auto"
631
- onLoad={() => {
632
- setState("loaded");
633
- }}
634
- onError={() => {
635
- setState("error");
636
- }}
637
- style={{ height: image.height ?? 12, width: image.width ?? "100%" }}
638
- />
639
- </box>
640
- );
641
- };
642
-
643
- const BlockquoteRenderer = function BlockquoteRenderer({
644
- token,
645
- theme,
646
- indent,
647
- onLinkActivate,
648
- }: {
649
- token: Tokens.Blockquote;
650
- theme: ResolvedTheme;
651
- indent: number;
652
- onLinkActivate?: MarkdownLinkHandler;
653
- }): ReactNode {
654
- // Collect inline tokens from blockquote's child paragraphs/text
655
- const inlineTokens: Token[] = [];
656
- for (const child of token.tokens) {
657
- if ("tokens" in child && Array.isArray(child.tokens)) {
658
- if (inlineTokens.length > 0) {
659
- inlineTokens.push({ raw: "\n", type: "br" });
660
- }
661
- inlineTokens.push(...child.tokens);
662
- } else if ("text" in child && typeof child.text === "string") {
663
- inlineTokens.push(child);
664
- }
665
- }
666
-
667
- return (
668
- <box
669
- border={["left"]}
670
- borderColor={theme.markdownBlockQuote}
671
- borderStyle="single"
672
- style={{
673
- marginBottom: 1,
674
- marginLeft: 1 + indent,
675
- marginRight: 1,
676
- marginTop: 0,
677
- paddingLeft: 1,
678
- }}
679
- >
680
- <text
681
- style={{ fg: theme.textMuted }}
682
- onMouseDown={linkMouseHandler(inlineTokens, onLinkActivate)}
683
- >
684
- {/* oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): preserve deliberate top-down renderer organization */}
685
- <InlineTokens tokens={inlineTokens} theme={theme} />
686
- </text>
687
- </box>
688
- );
689
- };
690
-
691
- const MarkdownTableRenderer = function MarkdownTableRenderer({
692
- token,
693
- indent,
694
- }: {
695
- token: Tokens.Table;
696
- indent: number;
697
- }): ReactNode {
698
- const { theme } = useTheme();
699
-
700
- const content: TextTableContent = useMemo(() => {
701
- const headerRow: TextTableCellContent[] = token.header.map((cell) => {
702
- // oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): preserve deliberate top-down renderer organization
703
- const chunks = inlineTokensToChunks(cell.tokens, theme);
704
- // Wrap header chunks in bold
705
- return chunks.length > 0
706
- ? chunks.map((c) => boldChunk(c))
707
- : [
708
- // oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): preserve deliberate top-down renderer organization
709
- boldChunk(getPlainText(cell.tokens).trim()),
710
- ];
711
- });
712
- const dataRows = token.rows.map((row) =>
713
- row.map((cell) => {
714
- // oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): preserve deliberate top-down renderer organization
715
- const chunks = inlineTokensToChunks(cell.tokens, theme);
716
- return chunks.length > 0
717
- ? chunks
718
- : ([
719
- // oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): preserve deliberate top-down renderer organization
720
- { __isChunk: true as const, text: getPlainText(cell.tokens) },
721
- ] as TextTableCellContent);
722
- }),
723
- );
724
- return [headerRow, ...dataRows];
725
- }, [token, theme]);
726
-
727
- return (
728
- <box style={{ marginBottom: 1, marginLeft: 1 + indent, marginRight: 1 }}>
729
- <text-table
730
- content={content}
731
- wrapMode="word"
732
- columnWidthMode="content"
733
- cellPadding={0}
734
- border={true}
735
- borderStyle="single"
736
- borderColor={theme.border}
737
- fg={theme.text}
738
- />
739
- </box>
740
- );
741
- };
742
-
743
- const HorizontalRule = function HorizontalRule({
744
- theme,
745
- indent,
746
- }: {
747
- theme: ResolvedTheme;
748
- indent: number;
749
- }): ReactNode {
750
- return (
751
- <box style={{ marginBottom: 1, marginLeft: 1 + indent, marginRight: 1, marginTop: 0 }}>
752
- <text style={{ fg: theme.markdownHorizontalRule }} content={"─".repeat(40)} />
753
- </box>
754
- );
755
- };
756
-
757
- // ---------------------------------------------------------------------------
758
- // Inline token rendering (React elements)
759
- // ---------------------------------------------------------------------------
760
-
761
- const InlineTokens = function InlineTokens({
762
- tokens,
763
- theme,
764
- }: {
765
- tokens: Token[];
766
- theme: ResolvedTheme;
767
- }): ReactNode {
768
- const result: ReactNode[] = [];
769
-
770
- for (let i = 0; i < tokens.length; i += 1) {
771
- const token = tokens[i];
772
- if (token === undefined) {
773
- continue;
774
- }
775
- const key = i;
776
-
777
- switch (token.type) {
778
- case "text": {
779
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
780
- result.push(normalizeSoftLineEndings((token as Tokens.Text).text));
781
- break;
782
- }
783
- case "strong": {
784
- result.push(
785
- <strong key={key}>
786
- {/* oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): preserve deliberate top-down renderer organization */}
787
- {/* oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep */}
788
- <InlineTokens tokens={(token as Tokens.Strong).tokens} theme={theme} />
789
- </strong>,
790
- );
791
- break;
792
- }
793
- case "em": {
794
- result.push(
795
- <em key={key}>
796
- {/* oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): preserve deliberate top-down renderer organization */}
797
- {/* oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep */}
798
- <InlineTokens tokens={(token as Tokens.Em).tokens} theme={theme} />
799
- </em>,
800
- );
801
- break;
802
- }
803
- case "codespan": {
804
- result.push(
805
- <span key={key} fg={theme.markdownCode} bg={theme.backgroundPanel}>
806
- {/* oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep */}
807
- {` ${(token as Tokens.Codespan).text} `}
808
- </span>,
809
- );
810
- break;
811
- }
812
- case "link": {
813
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
814
- const linkToken = token as Tokens.Link;
815
- result.push(
816
- <u key={key}>
817
- <a href={linkToken.href} fg={theme.markdownLink}>
818
- {/* oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): preserve deliberate top-down renderer organization */}
819
- <InlineTokens tokens={linkToken.tokens} theme={theme} />
820
- </a>
821
- </u>,
822
- );
823
- break;
824
- }
825
- case "del": {
826
- result.push(
827
- <span key={key} fg={theme.textMuted}>
828
- ~
829
- {/* oxlint-disable-next-line no-use-before-define -- Deferred(lint-sweep): preserve deliberate top-down renderer organization */}
830
- {/* oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep */}
831
- <InlineTokens tokens={(token as Tokens.Del).tokens} theme={theme} />~
832
- </span>,
833
- );
834
- break;
835
- }
836
- case "image": {
837
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
838
- const imgToken = token as Tokens.Image;
839
- result.push(
840
- <span key={key} fg={theme.textMuted}>
841
- {imgToken.text || imgToken.href}
842
- </span>,
843
- );
844
- break;
845
- }
846
- case "br": {
847
- result.push("\n");
848
- break;
849
- }
850
- case "escape": {
851
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
852
- result.push((token as Tokens.Escape).text);
853
- break;
854
- }
855
- case "space": {
856
- result.push(" ");
857
- break;
858
- }
859
- default: {
860
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
861
- if ("text" in token && typeof (token as { text?: string }).text === "string") {
862
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
863
- result.push((token as { text: string }).text);
864
- }
865
- break;
866
- }
867
- }
868
- }
869
-
870
- return result;
871
- };
872
-
873
- // ---------------------------------------------------------------------------
874
- // Inline token rendering (TextChunks — for text-table cells)
875
- // ---------------------------------------------------------------------------
876
-
877
- const inlineTokensToChunks = function inlineTokensToChunks(
878
- tokens: Token[],
879
- theme: ResolvedTheme,
880
- ): TextChunk[] {
881
- const chunks: TextChunk[] = [];
882
-
883
- for (const token of tokens) {
884
- switch (token.type) {
885
- case "text": {
886
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
887
- chunks.push({ __isChunk: true as const, text: (token as Tokens.Text).text });
888
- break;
889
- }
890
- case "strong": {
891
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
892
- for (const sub of inlineTokensToChunks((token as Tokens.Strong).tokens, theme)) {
893
- chunks.push(boldChunk(sub));
894
- }
895
- break;
896
- }
897
- case "em": {
898
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
899
- for (const sub of inlineTokensToChunks((token as Tokens.Em).tokens, theme)) {
900
- chunks.push(italicChunk(sub));
901
- }
902
- break;
903
- }
904
- case "codespan": {
905
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
906
- const codespanToken = token as Tokens.Codespan;
907
- chunks.push({
908
- __isChunk: true as const,
909
- bg: parseColor(theme.backgroundPanel),
910
- fg: parseColor(theme.markdownCode),
911
- text: ` ${codespanToken.text} `,
912
- });
913
- break;
914
- }
915
- case "link": {
916
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
917
- const linkToken = token as Tokens.Link;
918
- for (const sub of inlineTokensToChunks(linkToken.tokens, theme)) {
919
- chunks.push(underlineChunk({ ...sub, fg: parseColor(theme.markdownLink) }));
920
- }
921
- break;
922
- }
923
- case "escape": {
924
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
925
- chunks.push({ __isChunk: true as const, text: (token as Tokens.Escape).text });
926
- break;
927
- }
928
- default: {
929
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
930
- if ("text" in token && typeof (token as { text?: string }).text === "string") {
931
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
932
- chunks.push({ __isChunk: true as const, text: (token as { text: string }).text });
933
- }
934
- break;
935
- }
936
- }
937
- }
938
-
939
- return chunks;
940
- };
941
-
942
- // ---------------------------------------------------------------------------
943
- // Plain text extraction (only for width computation, not rendering)
944
- // ---------------------------------------------------------------------------
945
-
946
- const getPlainText = function getPlainText(tokens: Token[]): string {
947
- return tokens
948
- .map((token) => {
949
- if (token.type === "text") {
950
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
951
- return (token as { text: string }).text;
952
- }
953
- if (token.type === "codespan") {
954
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Deferred(lint-sweep): marked token narrowing; schema-based validation in a later sweep
955
- return (token as Tokens.Codespan).text;
956
- }
957
- if ("tokens" in token && token.tokens) {
958
- return getPlainText(token.tokens);
959
- }
960
- if ("text" in token) {
961
- const tokenText: unknown = token.text;
962
- return typeof tokenText === "string" ? tokenText : "";
963
- }
964
- return "";
965
- })
966
- .join("");
967
- };