@tooee/renderers 0.1.20 → 0.1.22

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.
@@ -0,0 +1,307 @@
1
+ import { useCallback, useMemo, useRef, type ReactNode, type RefObject } from "react"
2
+ import type { ResolvedTheme } from "@tooee/themes"
3
+ import type { MouseEvent, SyntaxStyle, TextBufferRenderable } from "@opentui/core"
4
+ import type { Tokens } from "marked"
5
+ import { renderMermaidForTerminal } from "./mermaid.js"
6
+
7
+ // ---------------------------------------------------------------------------
8
+ // Public custom code block renderer API
9
+ // ---------------------------------------------------------------------------
10
+
11
+ /**
12
+ * Extract the fence type from a fence info string: the first
13
+ * whitespace-separated word, lowercased. Returns "" for bare fences.
14
+ * Matches common Markdown behavior (marked may include extra info-string
15
+ * content after the language).
16
+ */
17
+ export function getFenceType(info?: string): string {
18
+ return (info ?? "").trim().split(/\s+/)[0]?.toLowerCase() ?? ""
19
+ }
20
+
21
+ /**
22
+ * Opt-in horizontal panning hooks for wide block content. Attach `register`
23
+ * as a ref and `onMouseScroll` as the `onMouseScroll` handler on the block's
24
+ * text-buffer renderable (`<text>` or `<code>`, usually with
25
+ * `wrapMode="none"`) to get the same panning behavior as built-in code and
26
+ * mermaid blocks: h/l in cursor mode and shift+wheel pan via `scrollX`.
27
+ */
28
+ export interface CodeBlockHScroll {
29
+ register: (node: TextBufferRenderable | null) => void
30
+ onMouseScroll: (event: MouseEvent) => void
31
+ }
32
+
33
+ export interface CodeBlockRendererProps {
34
+ /** Fence body text. */
35
+ text: string
36
+ /**
37
+ * Matched fence type: the first whitespace-separated word of the fence
38
+ * info string, lowercased ("" for bare fences).
39
+ */
40
+ lang: string
41
+ /** Full raw fence info string ("" when absent), for renderer options. */
42
+ info: string
43
+ theme: ResolvedTheme
44
+ syntax: SyntaxStyle
45
+ /** Left indentation (columns) when the block is nested inside a list. */
46
+ indent: number
47
+ /** Index of this block in the flattened block list. */
48
+ blockIndex: number
49
+ /** Horizontal panning hooks for wide content (optional to use). */
50
+ hScroll: CodeBlockHScroll
51
+ }
52
+
53
+ /**
54
+ * Renders a fenced code block for a registered fence type.
55
+ *
56
+ * Renderers draw their own chrome; wrap output in `CodeBlockChrome` to get
57
+ * the standard bordered-box styling. Return `null` (or throw) to fall back
58
+ * to the default syntax-highlighted code block — prefer returning `null`
59
+ * from an explicit failure check (see the mermaid renderer) over throwing.
60
+ *
61
+ * Renderers are invoked as plain functions during render (the same contract
62
+ * as `ContentRenderer` in `@tooee/view`), so hooks are allowed but the
63
+ * renderer registered for a given fence type must call the same hooks on
64
+ * every render.
65
+ */
66
+ export type CodeBlockRenderer = (props: CodeBlockRendererProps) => ReactNode
67
+
68
+ /**
69
+ * The standard bordered-box chrome used by built-in code and mermaid blocks.
70
+ * Custom renderers can wrap their content in this to match the default look.
71
+ */
72
+ export function CodeBlockChrome({
73
+ theme,
74
+ indent,
75
+ children,
76
+ }: {
77
+ theme: ResolvedTheme
78
+ indent: number
79
+ children?: ReactNode
80
+ }) {
81
+ return (
82
+ <box
83
+ style={{
84
+ marginTop: 0,
85
+ marginBottom: 1,
86
+ marginLeft: 1 + indent,
87
+ marginRight: 1,
88
+ border: true,
89
+ borderColor: theme.border,
90
+ backgroundColor: theme.backgroundElement,
91
+ flexDirection: "column",
92
+ }}
93
+ >
94
+ {children}
95
+ </box>
96
+ )
97
+ }
98
+
99
+ // ---------------------------------------------------------------------------
100
+ // Default renderer (syntax-highlighted code block)
101
+ // ---------------------------------------------------------------------------
102
+
103
+ /**
104
+ * The default syntax-highlighted code block. Also used as the fallback when
105
+ * a custom renderer returns `null` or throws.
106
+ */
107
+ export const defaultCodeBlockRenderer: CodeBlockRenderer = ({
108
+ text,
109
+ info,
110
+ theme,
111
+ syntax,
112
+ indent,
113
+ hScroll,
114
+ }) => {
115
+ const lineCount = text.split("\n").length
116
+ // Code lines never wrap (wrapMode "none") — wide code blocks and ASCII
117
+ // diagrams pan horizontally via the renderable's own viewport (`scrollX`)
118
+ // instead of word-wrapping into an unreadable mess. Blocks that fit render
119
+ // exactly as before, with scrollX clamped to 0.
120
+ return (
121
+ <CodeBlockChrome theme={theme} indent={indent}>
122
+ <code
123
+ ref={hScroll.register}
124
+ content={text}
125
+ filetype={info}
126
+ syntaxStyle={syntax}
127
+ wrapMode="none"
128
+ onMouseScroll={hScroll.onMouseScroll}
129
+ style={{ height: lineCount }}
130
+ />
131
+ </CodeBlockChrome>
132
+ )
133
+ }
134
+
135
+ // ---------------------------------------------------------------------------
136
+ // Built-in mermaid renderer
137
+ // ---------------------------------------------------------------------------
138
+
139
+ /**
140
+ * Built-in renderer for ```mermaid fences: renders the diagram as styled
141
+ * terminal text. Falls back to the default code block (returns `null`) when
142
+ * the diagram cannot be rendered. Registered by default under "mermaid";
143
+ * user entries for "mermaid" override it.
144
+ */
145
+ export const mermaidCodeBlockRenderer: CodeBlockRenderer = ({ text, theme, indent, hScroll }) => {
146
+ const mermaidTheme = useMemo(
147
+ () => ({
148
+ fg: theme.markdownText,
149
+ border: theme.border,
150
+ line: theme.textMuted,
151
+ arrow: theme.accent,
152
+ accent: theme.accent,
153
+ bg: theme.backgroundElement,
154
+ corner: theme.borderActive,
155
+ junction: theme.borderSubtle,
156
+ }),
157
+ [theme],
158
+ )
159
+ const result = useMemo(
160
+ () => renderMermaidForTerminal(text, { mode: "ansi", theme: mermaidTheme }),
161
+ [text, mermaidTheme],
162
+ )
163
+
164
+ if (!result.ok) return null
165
+
166
+ const lineCount = result.text.split("\n").length
167
+ // Diagram lines never wrap (wrapMode "none"). Wide diagrams pan via the
168
+ // text renderable's own viewport (`scrollX`), which the native renderer
169
+ // clips with correct style-run alignment. Translating a natural-width text
170
+ // inside a nested scrollbox instead exercises the scissor-clip path, which
171
+ // misplaces fg colors at some offsets (each fully clipped style chunk after
172
+ // the first bleeds a phantom column into view). Diagrams that fit render
173
+ // exactly as before, with scrollX clamped to 0.
174
+ return (
175
+ <CodeBlockChrome theme={theme} indent={indent}>
176
+ <text
177
+ ref={hScroll.register}
178
+ content={result.content}
179
+ wrapMode="none"
180
+ onMouseScroll={hScroll.onMouseScroll}
181
+ style={{ fg: theme.markdownText, height: lineCount }}
182
+ />
183
+ </CodeBlockChrome>
184
+ )
185
+ }
186
+
187
+ /** Built-in code block renderers, merged under user-provided entries. */
188
+ export const DEFAULT_CODE_BLOCK_RENDERERS: Record<string, CodeBlockRenderer> = {
189
+ mermaid: mermaidCodeBlockRenderer,
190
+ }
191
+
192
+ // ---------------------------------------------------------------------------
193
+ // Horizontal panning registration
194
+ // ---------------------------------------------------------------------------
195
+
196
+ /**
197
+ * Registration and shift+wheel panning for a horizontally scrollable block.
198
+ *
199
+ * `register` is a React ref callback that (de)registers the block's
200
+ * text-buffer renderable in the `hScrollableBlocksRef` registry under its
201
+ * block index, so the owning subview can pan the block under the nav cursor.
202
+ *
203
+ * `handleMouseScroll` remaps shift+vertical-wheel to horizontal panning
204
+ * (ScrollBox does this remap; the text-buffer renderable's built-in scroll
205
+ * handling only pans on real horizontal wheel directions). The event is not
206
+ * stopped, so plain vertical wheel keeps bubbling to the surrounding
207
+ * row-document.
208
+ */
209
+ function useHScrollableBlock(
210
+ blockIndex: number,
211
+ hScrollableBlocksRef?: RefObject<Map<number, TextBufferRenderable>>,
212
+ ) {
213
+ const nodeRef = useRef<TextBufferRenderable | null>(null)
214
+ const register = useCallback(
215
+ (node: TextBufferRenderable | null) => {
216
+ nodeRef.current = node
217
+ const map = hScrollableBlocksRef?.current
218
+ if (!map) return
219
+ if (node) map.set(blockIndex, node)
220
+ else map.delete(blockIndex)
221
+ },
222
+ [hScrollableBlocksRef, blockIndex],
223
+ )
224
+
225
+ const handleMouseScroll = useCallback((event: MouseEvent) => {
226
+ const node = nodeRef.current
227
+ if (!node || !event.scroll || !event.modifiers.shift) return
228
+ const { direction, delta } = event.scroll
229
+ if (direction === "up") node.scrollX -= delta
230
+ else if (direction === "down") node.scrollX += delta
231
+ }, [])
232
+
233
+ return { register, handleMouseScroll }
234
+ }
235
+
236
+ // ---------------------------------------------------------------------------
237
+ // Dispatching block component
238
+ // ---------------------------------------------------------------------------
239
+
240
+ /**
241
+ * Renders a fenced code block, dispatching to a registered custom renderer
242
+ * for the fence type when one exists, and falling back to the default
243
+ * syntax-highlighted code block when there is no match, the renderer
244
+ * returns `null`, or the renderer throws.
245
+ */
246
+ export function CodeBlock({
247
+ token,
248
+ blockIndex,
249
+ theme,
250
+ syntax,
251
+ indent,
252
+ hScrollableBlocksRef,
253
+ renderers,
254
+ }: {
255
+ token: Tokens.Code
256
+ blockIndex: number
257
+ theme: ResolvedTheme
258
+ syntax: SyntaxStyle
259
+ indent: number
260
+ hScrollableBlocksRef?: RefObject<Map<number, TextBufferRenderable>>
261
+ renderers?: Record<string, CodeBlockRenderer>
262
+ }): ReactNode {
263
+ const { register, handleMouseScroll } = useHScrollableBlock(blockIndex, hScrollableBlocksRef)
264
+
265
+ const rendererProps: CodeBlockRendererProps = {
266
+ text: token.text,
267
+ lang: getFenceType(token.lang),
268
+ info: token.lang ?? "",
269
+ theme,
270
+ syntax,
271
+ indent,
272
+ blockIndex,
273
+ hScroll: { register, onMouseScroll: handleMouseScroll },
274
+ }
275
+
276
+ const custom = rendererProps.lang !== "" ? renderers?.[rendererProps.lang] : undefined
277
+ if (custom && custom !== defaultCodeBlockRenderer) {
278
+ // Keyed by fence type so a type change remounts the custom renderer
279
+ // (renderers may use hooks; see CodeBlockRenderer docs).
280
+ return (
281
+ <CustomCodeBlock key={rendererProps.lang} renderer={custom} rendererProps={rendererProps} />
282
+ )
283
+ }
284
+
285
+ return defaultCodeBlockRenderer(rendererProps)
286
+ }
287
+
288
+ /**
289
+ * Invokes a custom renderer, falling back to the default code block when it
290
+ * returns `null` or throws. Isolated in its own component so renderer hooks
291
+ * have a stable home that remounts when the fence type changes.
292
+ */
293
+ function CustomCodeBlock({
294
+ renderer,
295
+ rendererProps,
296
+ }: {
297
+ renderer: CodeBlockRenderer
298
+ rendererProps: CodeBlockRendererProps
299
+ }): ReactNode {
300
+ let node: ReactNode = null
301
+ try {
302
+ node = renderer(rendererProps)
303
+ } catch {
304
+ node = null
305
+ }
306
+ return node ?? defaultCodeBlockRenderer(rendererProps)
307
+ }
package/src/index.ts CHANGED
@@ -1,11 +1,21 @@
1
1
  export { MarkdownView, flattenTokens } from "./MarkdownView.js"
2
2
  export type { FlatBlock } from "./MarkdownView.js"
3
+ export {
4
+ CodeBlockChrome,
5
+ defaultCodeBlockRenderer,
6
+ mermaidCodeBlockRenderer,
7
+ DEFAULT_CODE_BLOCK_RENDERERS,
8
+ getFenceType,
9
+ } from "./code-blocks.js"
10
+ export type { CodeBlockRenderer, CodeBlockRendererProps, CodeBlockHScroll } from "./code-blocks.js"
3
11
  export { CodeView } from "./CodeView.js"
4
12
  export { Table, computeColumnWidths, isNumeric, sampleRows } from "./Table.js"
5
13
  export type { TableProps, ColumnWidthOptions } from "./Table.js"
6
14
  export type { ColumnDef, TableRow } from "./table-types.js"
7
15
  export { CommandPalette } from "./CommandPalette.js"
8
16
  export type { CommandPaletteEntry } from "./CommandPalette.js"
17
+ export { ContextMenu } from "./ContextMenu.js"
18
+ export type { ContextMenuEntry } from "./ContextMenu.js"
9
19
  export { parseCSV, parseTSV, parseJSON, parseAuto, detectFormat } from "./parsers.js"
10
20
  export type { Format, ParsedTable } from "./parsers.js"
11
21
  export { RowDocumentRenderable } from "./RowDocumentRenderable.js"