@tooee/renderers 0.2.3 → 0.3.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 (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} +20 -6
  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 +5 -5
  38. package/dist/mermaid.d.ts.map +1 -1
  39. package/dist/mermaid.js +33 -25
  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 +94 -71
  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 -275
  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 -541
  114. package/src/RowDocumentRenderable.ts +0 -593
  115. package/src/Table.tsx +0 -300
  116. package/src/useGutterPalette.ts +0 -15
@@ -1,132 +0,0 @@
1
- import { useState, useCallback } from "react"
2
- import { useKeyboard, useTerminalDimensions } from "@opentui/react"
3
- import { useTheme } from "@tooee/themes"
4
-
5
- export interface ContextMenuEntry {
6
- id: string
7
- title: string
8
- hotkey?: string
9
- }
10
-
11
- interface ContextMenuProps {
12
- entries: ContextMenuEntry[]
13
- /** Anchor coordinates (screen space) — usually the click position. */
14
- x: number
15
- y: number
16
- onSelect: (id: string) => void
17
- onClose: () => void
18
- }
19
-
20
- const MIN_WIDTH = 16
21
- const HPAD = 2 // 1 cell padding each side
22
- const BORDER = 2
23
-
24
- /**
25
- * A positioned, keyboard-navigable mini action menu shown on right-click.
26
- *
27
- * Renders a full-screen transparent backdrop (click-outside dismisses) and a
28
- * bordered panel anchored near the cursor, clamped to stay on screen. Mouse is
29
- * additive: j/k + arrows move, Enter invokes, Escape closes (handled by the
30
- * overlay layer), click selects.
31
- */
32
- export function ContextMenu({ entries, x, y, onSelect, onClose }: ContextMenuProps) {
33
- const { theme } = useTheme()
34
- const { width: termWidth, height: termHeight } = useTerminalDimensions()
35
- const [activeIndex, setActiveIndex] = useState(0)
36
-
37
- const select = useCallback(
38
- (index: number) => {
39
- const entry = entries[index]
40
- if (entry) onSelect(entry.id)
41
- },
42
- [entries, onSelect],
43
- )
44
-
45
- useKeyboard((key) => {
46
- if (key.name === "up" || key.raw === "k") {
47
- key.preventDefault()
48
- setActiveIndex((i) => Math.max(0, i - 1))
49
- } else if (key.name === "down" || key.raw === "j") {
50
- key.preventDefault()
51
- setActiveIndex((i) => Math.min(entries.length - 1, i + 1))
52
- } else if (key.name === "return") {
53
- key.preventDefault()
54
- select(activeIndex)
55
- }
56
- // Escape is handled by the overlay layer (dismissOnEscape).
57
- })
58
-
59
- // Size the panel from its contents (terminal cell width, not code units,
60
- // so wide glyphs like CJK and emoji are counted correctly).
61
- const longest = entries.reduce((max, e) => {
62
- const w = Bun.stringWidth(e.title) + (e.hotkey ? Bun.stringWidth(e.hotkey) + 2 : 0)
63
- return Math.max(max, w)
64
- }, 0)
65
- const innerWidth = Math.max(MIN_WIDTH, longest)
66
- const panelWidth = innerWidth + HPAD + BORDER
67
- const panelHeight = Math.max(1, entries.length) + BORDER
68
-
69
- // Clamp on-screen: flip left/up when the anchor is near the right/bottom edge.
70
- let left = x
71
- if (left + panelWidth > termWidth) left = Math.max(0, termWidth - panelWidth)
72
- let top = y
73
- if (top + panelHeight > termHeight) top = Math.max(0, termHeight - panelHeight)
74
-
75
- return (
76
- <box position="absolute" left={0} top={0} width={termWidth} height={termHeight}>
77
- {/* Backdrop: click outside the menu dismisses it. */}
78
- <box
79
- position="absolute"
80
- left={0}
81
- top={0}
82
- width={termWidth}
83
- height={termHeight}
84
- backgroundColor="transparent"
85
- onMouseDown={(event) => {
86
- event.preventDefault()
87
- onClose()
88
- }}
89
- />
90
- <box
91
- position="absolute"
92
- left={left}
93
- top={top}
94
- width={panelWidth}
95
- flexDirection="column"
96
- backgroundColor={theme.backgroundPanel}
97
- border
98
- borderColor={theme.borderActive}
99
- >
100
- {entries.length === 0 ? (
101
- <box height={1} paddingLeft={1} paddingRight={1}>
102
- <text content="No actions" fg={theme.textMuted} />
103
- </box>
104
- ) : (
105
- entries.map((entry, i) => (
106
- <box
107
- key={entry.id}
108
- flexDirection="row"
109
- height={1}
110
- paddingLeft={1}
111
- paddingRight={1}
112
- backgroundColor={i === activeIndex ? theme.backgroundElement : undefined}
113
- onMouseDown={(event) => {
114
- if (event.button !== 0) return
115
- event.preventDefault()
116
- event.stopPropagation()
117
- onSelect(entry.id)
118
- }}
119
- >
120
- <text
121
- content={entry.title}
122
- fg={i === activeIndex ? theme.primary : theme.text}
123
- style={{ flexGrow: 1 }}
124
- />
125
- {entry.hotkey && <text content={` ${entry.hotkey}`} fg={theme.textMuted} />}
126
- </box>
127
- ))
128
- )}
129
- </box>
130
- </box>
131
- )
132
- }
@@ -1,11 +0,0 @@
1
- export interface RowDecoration {
2
- row: number
3
- background?: string
4
- gutterBackground?: string
5
- sign?: { text: string; fg?: string }
6
- }
7
-
8
- export interface DecorationLayer {
9
- readonly priority: number
10
- forVisibleRows(from: number, to: number): Iterable<RowDecoration>
11
- }
@@ -1,16 +0,0 @@
1
- import type { RefObject } from "react"
2
- import type { MouseEvent } from "@opentui/core"
3
- import type { DecorationLayer } from "./DecorationLayer.js"
4
- import type { RowDocumentRenderable } from "./RowDocumentRenderable.js"
5
-
6
- /**
7
- * The narrow projection a row renderer needs from a document controller:
8
- * geometry access, the layers to paint, and the bound mouse handler. Renderers
9
- * never see the controller's row type — this type lives here so a renderer can
10
- * accept bindings without depending on `@tooee/shell`.
11
- */
12
- export interface DocumentBindings {
13
- ref: RefObject<RowDocumentRenderable | null>
14
- decorations: readonly DecorationLayer[]
15
- onMouseDown(event: MouseEvent): void
16
- }
@@ -1,541 +0,0 @@
1
- import { type Token, type Tokens } from "marked"
2
- import { useMemo, type ReactNode, type RefObject } from "react"
3
- import { useTheme, type ResolvedTheme } from "@tooee/themes"
4
- import {
5
- bold as boldChunk,
6
- italic as italicChunk,
7
- underline as underlineChunk,
8
- parseColor,
9
- } from "@opentui/core"
10
- import type {
11
- SyntaxStyle,
12
- TextBufferRenderable,
13
- TextTableContent,
14
- TextTableCellContent,
15
- TextChunk,
16
- } from "@opentui/core"
17
- import type { DocumentBindings } from "./DocumentBindings.js"
18
- import { DEFAULT_SIGN_COLUMN_WIDTH } from "./RowDocumentRenderable.js"
19
- import { useGutterPalette } from "./useGutterPalette.js"
20
- import { CodeBlock, DEFAULT_CODE_BLOCK_RENDERERS, type CodeBlockRenderer } from "./code-blocks.js"
21
- import { flattenMarkdown, type FlatBlock } from "./markdown-blocks.js"
22
- import "./row-document.js"
23
- import "./text-table.js"
24
-
25
- // ---------------------------------------------------------------------------
26
- // Types
27
- // ---------------------------------------------------------------------------
28
-
29
- interface MarkdownViewProps {
30
- content: string
31
- /**
32
- * Pre-flattened blocks to render, normally the exact array a subview passed
33
- * to its document controller. When supplied, `content` is *not* lexed again,
34
- * so the rendered rows and the controller's navigation rows cannot drift.
35
- * Omit it and `MarkdownView` flattens `content` itself for static callers.
36
- */
37
- blocks?: readonly FlatBlock[]
38
- showLineNumbers?: boolean
39
- /**
40
- * Binds the row document to a document controller: its ref, the decoration
41
- * layers to paint, and the mouse handler. Rows are flattened *block* indices —
42
- * the same unit `j`/`k` move between and copy operates on. Omit it to render
43
- * a static, non-interactive document.
44
- *
45
- * Blocks are per-child renderables, but their markup varies across renderer
46
- * branches (box/text/null with differing margins), so the controller maps
47
- * clicks by screen-Y rather than per-child handlers. Clicks bubble up from
48
- * block children (including custom code blocks) unless a custom renderer
49
- * stops propagation.
50
- */
51
- document?: DocumentBindings
52
- /**
53
- * Registry of horizontally scrollable blocks, keyed by block index. Blocks
54
- * that can overflow horizontally (mermaid diagrams and code blocks)
55
- * register their text-buffer renderable here so the owning subview can
56
- * drive horizontal panning (`scrollX`) for the block under the nav cursor
57
- * (h/l in cursor mode).
58
- */
59
- hScrollableBlocksRef?: RefObject<Map<number, TextBufferRenderable>>
60
- /**
61
- * Custom renderers for fenced code blocks, keyed by fence type. A fence's
62
- * type is the first whitespace-separated word of its info string, matched
63
- * case-insensitively. Entries are merged over the built-in defaults
64
- * (currently `mermaid`), so built-ins can be overridden. Unmatched types —
65
- * and renderers that return `null` or throw — fall back to the default
66
- * syntax-highlighted code block.
67
- */
68
- codeBlockRenderers?: Record<string, CodeBlockRenderer>
69
- }
70
-
71
- // ---------------------------------------------------------------------------
72
- // Component
73
- // ---------------------------------------------------------------------------
74
-
75
- export function MarkdownView({
76
- content,
77
- blocks: providedBlocks,
78
- showLineNumbers = true,
79
- document,
80
- hScrollableBlocksRef,
81
- codeBlockRenderers,
82
- }: MarkdownViewProps) {
83
- const { theme, syntax } = useTheme()
84
- const palette = useGutterPalette()
85
- const blocks = useMemo(
86
- () => providedBlocks ?? flattenMarkdown(content),
87
- [providedBlocks, content],
88
- )
89
-
90
- // Merge user renderers over built-in defaults, normalizing keys to
91
- // lowercase so registration matches fence types case-insensitively.
92
- const mergedCodeBlockRenderers = useMemo(() => {
93
- const merged: Record<string, CodeBlockRenderer> = { ...DEFAULT_CODE_BLOCK_RENDERERS }
94
- for (const [key, renderer] of Object.entries(codeBlockRenderers ?? {})) {
95
- merged[key.trim().toLowerCase()] = renderer
96
- }
97
- return merged
98
- }, [codeBlockRenderers])
99
-
100
- const blockElements = useMemo(
101
- () =>
102
- blocks.map((block, index) => (
103
- <FlatBlockRenderer
104
- key={index}
105
- block={block}
106
- blockIndex={index}
107
- theme={theme}
108
- syntax={syntax}
109
- hScrollableBlocksRef={hScrollableBlocksRef}
110
- codeBlockRenderers={mergedCodeBlockRenderers}
111
- />
112
- )),
113
- [blocks, theme, syntax, hScrollableBlocksRef, mergedCodeBlockRenderers],
114
- )
115
-
116
- return (
117
- <row-document
118
- ref={document?.ref}
119
- showLineNumbers={showLineNumbers}
120
- palette={palette}
121
- decorations={document?.decorations}
122
- signColumnWidth={DEFAULT_SIGN_COLUMN_WIDTH}
123
- style={{ flexGrow: 1 }}
124
- onMouseDown={document?.onMouseDown}
125
- >
126
- {blockElements}
127
- </row-document>
128
- )
129
- }
130
-
131
- // ---------------------------------------------------------------------------
132
- // Block renderer (flat)
133
- // ---------------------------------------------------------------------------
134
-
135
- function FlatBlockRenderer({
136
- block,
137
- blockIndex,
138
- theme,
139
- syntax,
140
- hScrollableBlocksRef,
141
- codeBlockRenderers,
142
- }: {
143
- block: FlatBlock
144
- blockIndex: number
145
- theme: ResolvedTheme
146
- syntax: SyntaxStyle
147
- hScrollableBlocksRef?: RefObject<Map<number, TextBufferRenderable>>
148
- codeBlockRenderers?: Record<string, CodeBlockRenderer>
149
- }): ReactNode {
150
- const { token, indent, bullet } = block
151
-
152
- // List item line (has bullet)
153
- if (bullet !== undefined) {
154
- return <ListLineRenderer block={block} theme={theme} />
155
- }
156
-
157
- // Regular block token
158
- switch (token.type) {
159
- case "heading":
160
- return <HeadingRenderer token={token as Tokens.Heading} theme={theme} indent={indent} />
161
- case "paragraph":
162
- return <ParagraphRenderer token={token as Tokens.Paragraph} theme={theme} indent={indent} />
163
- case "code":
164
- return (
165
- <CodeBlock
166
- token={token as Tokens.Code}
167
- blockIndex={blockIndex}
168
- theme={theme}
169
- syntax={syntax}
170
- indent={indent}
171
- hScrollableBlocksRef={hScrollableBlocksRef}
172
- renderers={codeBlockRenderers}
173
- />
174
- )
175
- case "blockquote":
176
- return <BlockquoteRenderer token={token as Tokens.Blockquote} theme={theme} indent={indent} />
177
- case "table":
178
- return <MarkdownTableRenderer token={token as Tokens.Table} indent={indent} />
179
- case "hr":
180
- return <HorizontalRule theme={theme} indent={indent} />
181
- case "space":
182
- case "html":
183
- return null
184
- default:
185
- if ("text" in token && typeof token.text === "string") {
186
- return (
187
- <text
188
- content={token.text}
189
- style={{
190
- fg: theme.markdownText,
191
- marginBottom: 1,
192
- marginTop: 0,
193
- marginLeft: 1 + indent,
194
- marginRight: 1,
195
- }}
196
- />
197
- )
198
- }
199
- return null
200
- }
201
- }
202
-
203
- // ---------------------------------------------------------------------------
204
- // List line renderer
205
- // ---------------------------------------------------------------------------
206
-
207
- function ListLineRenderer({ block, theme }: { block: FlatBlock; theme: ResolvedTheme }) {
208
- const { token, indent, bullet, checked } = block
209
- const checkboxPrefix = checked !== undefined ? (checked ? "[x] " : "[ ] ") : ""
210
-
211
- // Get inline tokens from the text/paragraph token
212
- const inlineTokens: Token[] = "tokens" in token && Array.isArray(token.tokens) ? token.tokens : []
213
-
214
- const hasText = "text" in token && typeof token.text === "string" && token.text.length > 0
215
- const hasContent = inlineTokens.length > 0 || hasText
216
-
217
- return (
218
- <box style={{ marginLeft: 1 + indent, marginRight: 1 }}>
219
- <text style={{ fg: theme.markdownText }}>
220
- <span fg={theme.markdownListItem}>{bullet}</span>
221
- {checkboxPrefix !== "" && (
222
- <span fg={checked ? theme.accent : theme.textMuted}>{checkboxPrefix}</span>
223
- )}
224
- {hasContent &&
225
- (inlineTokens.length > 0 ? (
226
- <InlineTokens tokens={inlineTokens} theme={theme} />
227
- ) : hasText ? (
228
- "text" in token ? (
229
- (token as { text: string }).text
230
- ) : (
231
- ""
232
- )
233
- ) : null)}
234
- </text>
235
- </box>
236
- )
237
- }
238
-
239
- // ---------------------------------------------------------------------------
240
- // Block renderers
241
- // ---------------------------------------------------------------------------
242
-
243
- function HeadingRenderer({
244
- token,
245
- theme,
246
- indent,
247
- }: {
248
- token: Tokens.Heading
249
- theme: ResolvedTheme
250
- indent: number
251
- }) {
252
- const headingColors: Record<number, string> = {
253
- 1: theme.markdownHeading,
254
- 2: theme.secondary,
255
- 3: theme.accent,
256
- 4: theme.text,
257
- 5: theme.textMuted,
258
- 6: theme.textMuted,
259
- }
260
-
261
- const prefixes: Record<number, string> = {
262
- 1: "# ",
263
- 2: "## ",
264
- 3: "### ",
265
- 4: "#### ",
266
- 5: "##### ",
267
- 6: "###### ",
268
- }
269
-
270
- return (
271
- <box style={{ marginTop: 1, marginBottom: 1, marginLeft: indent }}>
272
- <text style={{ fg: headingColors[token.depth] || theme.text }}>
273
- <span fg={theme.textMuted}>{prefixes[token.depth]}</span>
274
- <strong>
275
- <InlineTokens tokens={token.tokens || []} theme={theme} />
276
- </strong>
277
- </text>
278
- </box>
279
- )
280
- }
281
-
282
- function ParagraphRenderer({
283
- token,
284
- theme,
285
- indent,
286
- }: {
287
- token: Tokens.Paragraph
288
- theme: ResolvedTheme
289
- indent: number
290
- }) {
291
- return (
292
- <box style={{ marginBottom: 1, marginLeft: 1 + indent, marginRight: 1 }}>
293
- <text style={{ fg: theme.markdownText }}>
294
- <InlineTokens tokens={token.tokens || []} theme={theme} />
295
- </text>
296
- </box>
297
- )
298
- }
299
-
300
- function BlockquoteRenderer({
301
- token,
302
- theme,
303
- indent,
304
- }: {
305
- token: Tokens.Blockquote
306
- theme: ResolvedTheme
307
- indent: number
308
- }) {
309
- // Collect inline tokens from blockquote's child paragraphs/text
310
- const inlineTokens: Token[] = []
311
- if (token.tokens) {
312
- for (const child of token.tokens) {
313
- if ("tokens" in child && Array.isArray(child.tokens)) {
314
- if (inlineTokens.length > 0) {
315
- inlineTokens.push({ type: "text", raw: "\n", text: "\n" } as Token)
316
- }
317
- inlineTokens.push(...(child.tokens as Token[]))
318
- } else if ("text" in child && typeof child.text === "string") {
319
- inlineTokens.push(child)
320
- }
321
- }
322
- }
323
-
324
- return (
325
- <box
326
- style={{
327
- marginTop: 0,
328
- marginBottom: 1,
329
- marginLeft: 1 + indent,
330
- marginRight: 1,
331
- paddingLeft: 2,
332
- }}
333
- >
334
- <text style={{ fg: theme.markdownBlockQuote }} content="│ " />
335
- <text style={{ fg: theme.textMuted }}>
336
- <InlineTokens tokens={inlineTokens} theme={theme} />
337
- </text>
338
- </box>
339
- )
340
- }
341
-
342
- function MarkdownTableRenderer({ token, indent }: { token: Tokens.Table; indent: number }) {
343
- const { theme } = useTheme()
344
-
345
- const content: TextTableContent = useMemo(() => {
346
- const headerRow: TextTableCellContent[] = token.header.map((cell) => {
347
- const chunks = inlineTokensToChunks(cell.tokens, theme)
348
- // Wrap header chunks in bold
349
- return chunks.length > 0
350
- ? chunks.map((c) => boldChunk(c))
351
- : [boldChunk(getPlainText(cell.tokens).trim())]
352
- })
353
- const dataRows = token.rows.map((row) =>
354
- row.map((cell) => {
355
- const chunks = inlineTokensToChunks(cell.tokens, theme)
356
- return chunks.length > 0
357
- ? chunks
358
- : ([
359
- { __isChunk: true as const, text: getPlainText(cell.tokens) },
360
- ] as TextTableCellContent)
361
- }),
362
- )
363
- return [headerRow, ...dataRows]
364
- }, [token, theme])
365
-
366
- return (
367
- <box style={{ marginLeft: 1 + indent, marginRight: 1, marginBottom: 1 }}>
368
- <text-table
369
- content={content}
370
- wrapMode="word"
371
- columnWidthMode="content"
372
- cellPadding={0}
373
- border={true}
374
- borderStyle="single"
375
- borderColor={theme.border}
376
- fg={theme.text}
377
- />
378
- </box>
379
- )
380
- }
381
-
382
- function HorizontalRule({ theme, indent }: { theme: ResolvedTheme; indent: number }) {
383
- return (
384
- <box style={{ marginTop: 0, marginBottom: 1, marginLeft: 1 + indent, marginRight: 1 }}>
385
- <text style={{ fg: theme.markdownHorizontalRule }} content={"─".repeat(40)} />
386
- </box>
387
- )
388
- }
389
-
390
- // ---------------------------------------------------------------------------
391
- // Inline token rendering (React elements)
392
- // ---------------------------------------------------------------------------
393
-
394
- function InlineTokens({ tokens, theme }: { tokens: Token[]; theme: ResolvedTheme }): ReactNode {
395
- const result: ReactNode[] = []
396
-
397
- for (let i = 0; i < tokens.length; i++) {
398
- const token = tokens[i]
399
- if (!token) continue
400
- const key = i
401
-
402
- switch (token.type) {
403
- case "text":
404
- result.push((token as Tokens.Text).text)
405
- break
406
- case "strong":
407
- result.push(
408
- <strong key={key}>
409
- <InlineTokens tokens={(token as Tokens.Strong).tokens || []} theme={theme} />
410
- </strong>,
411
- )
412
- break
413
- case "em":
414
- result.push(
415
- <em key={key}>
416
- <InlineTokens tokens={(token as Tokens.Em).tokens || []} theme={theme} />
417
- </em>,
418
- )
419
- break
420
- case "codespan":
421
- result.push(
422
- <span key={key} fg={theme.markdownCode} bg={theme.backgroundPanel}>
423
- {` ${(token as Tokens.Codespan).text} `}
424
- </span>,
425
- )
426
- break
427
- case "link": {
428
- const linkToken = token as Tokens.Link
429
- result.push(
430
- <u key={key}>
431
- <a href={linkToken.href} fg={theme.markdownLink}>
432
- <InlineTokens tokens={linkToken.tokens || []} theme={theme} />
433
- </a>
434
- </u>,
435
- )
436
- break
437
- }
438
- case "del":
439
- result.push(
440
- <span key={key} fg={theme.textMuted}>
441
- {"~"}
442
- <InlineTokens tokens={(token as Tokens.Del).tokens || []} theme={theme} />
443
- {"~"}
444
- </span>,
445
- )
446
- break
447
- case "image": {
448
- const imgToken = token as Tokens.Image
449
- result.push(
450
- <span key={key} fg={theme.textMuted}>
451
- {imgToken.text || imgToken.href}
452
- </span>,
453
- )
454
- break
455
- }
456
- case "br":
457
- result.push("\n")
458
- break
459
- case "escape":
460
- result.push((token as Tokens.Escape).text)
461
- break
462
- case "space":
463
- result.push(" ")
464
- break
465
- default:
466
- if ("text" in token && typeof (token as { text?: string }).text === "string") {
467
- result.push((token as { text: string }).text)
468
- }
469
- break
470
- }
471
- }
472
-
473
- return <>{result}</>
474
- }
475
-
476
- // ---------------------------------------------------------------------------
477
- // Inline token rendering (TextChunks — for text-table cells)
478
- // ---------------------------------------------------------------------------
479
-
480
- function inlineTokensToChunks(tokens: Token[], theme: ResolvedTheme): TextChunk[] {
481
- const chunks: TextChunk[] = []
482
-
483
- for (const token of tokens) {
484
- switch (token.type) {
485
- case "text":
486
- chunks.push({ __isChunk: true as const, text: (token as Tokens.Text).text })
487
- break
488
- case "strong":
489
- for (const sub of inlineTokensToChunks((token as Tokens.Strong).tokens || [], theme)) {
490
- chunks.push(boldChunk(sub))
491
- }
492
- break
493
- case "em":
494
- for (const sub of inlineTokensToChunks((token as Tokens.Em).tokens || [], theme)) {
495
- chunks.push(italicChunk(sub))
496
- }
497
- break
498
- case "codespan":
499
- chunks.push({
500
- __isChunk: true as const,
501
- text: ` ${(token as Tokens.Codespan).text} `,
502
- fg: parseColor(theme.markdownCode),
503
- bg: parseColor(theme.backgroundPanel),
504
- })
505
- break
506
- case "link": {
507
- const linkToken = token as Tokens.Link
508
- for (const sub of inlineTokensToChunks(linkToken.tokens || [], theme)) {
509
- chunks.push(underlineChunk({ ...sub, fg: parseColor(theme.markdownLink) }))
510
- }
511
- break
512
- }
513
- case "escape":
514
- chunks.push({ __isChunk: true as const, text: (token as Tokens.Escape).text })
515
- break
516
- default:
517
- if ("text" in token && typeof (token as { text?: string }).text === "string") {
518
- chunks.push({ __isChunk: true as const, text: (token as { text: string }).text })
519
- }
520
- break
521
- }
522
- }
523
-
524
- return chunks
525
- }
526
-
527
- // ---------------------------------------------------------------------------
528
- // Plain text extraction (only for width computation, not rendering)
529
- // ---------------------------------------------------------------------------
530
-
531
- function getPlainText(tokens: Token[]): string {
532
- return tokens
533
- .map((token) => {
534
- if (token.type === "text") return token.text
535
- if (token.type === "codespan") return (token as Tokens.Codespan).text
536
- if ("tokens" in token && token.tokens) return getPlainText(token.tokens as Token[])
537
- if ("text" in token) return (token as { text: string }).text
538
- return ""
539
- })
540
- .join("")
541
- }