@tooee/renderers 0.1.20 → 0.1.21

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.
@@ -1,6 +1,6 @@
1
1
  import { useState, useMemo, useCallback } from "react"
2
2
  import { useCommand } from "@tooee/commands"
3
- import { useTheme } from "@tooee/themes"
3
+ import { useTheme, CloseButton } from "@tooee/themes"
4
4
  import { fuzzyMatch } from "@tooee/fuzzy"
5
5
 
6
6
  export interface CommandPaletteEntry {
@@ -112,6 +112,7 @@ export function CommandPalette({ commands, onSelect, onClose }: CommandPalettePr
112
112
  style={{ flexGrow: 1 }}
113
113
  />
114
114
  <text content={` ${filtered.length}`} fg={theme.textMuted} />
115
+ <CloseButton onClose={onClose} />
115
116
  </box>
116
117
 
117
118
  {/* Separator */}
@@ -127,6 +128,13 @@ export function CommandPalette({ commands, onSelect, onClose }: CommandPalettePr
127
128
  paddingRight={1}
128
129
  height={1}
129
130
  backgroundColor={i === activeIndex ? theme.backgroundElement : undefined}
131
+ onMouseDown={(event) => {
132
+ // Left-click runs the entry — same code path as Enter.
133
+ if (event.button !== 0) return
134
+ event.preventDefault()
135
+ event.stopPropagation()
136
+ onSelect(entry.id)
137
+ }}
130
138
  >
131
139
  <text content={entry.title} fg={theme.text} style={{ flexGrow: 1 }} />
132
140
  {entry.hotkey && <text content={entry.hotkey} fg={theme.textMuted} />}
@@ -0,0 +1,132 @@
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
+ }
@@ -7,11 +7,18 @@ import {
7
7
  underline as underlineChunk,
8
8
  parseColor,
9
9
  } from "@opentui/core"
10
- import type { SyntaxStyle, TextTableContent, TextTableCellContent, TextChunk } from "@opentui/core"
10
+ import type {
11
+ MouseEvent,
12
+ SyntaxStyle,
13
+ TextBufferRenderable,
14
+ TextTableContent,
15
+ TextTableCellContent,
16
+ TextChunk,
17
+ } from "@opentui/core"
11
18
  import type { MarkState } from "@tooee/marks"
12
19
  import { DEFAULT_SIGN_COLUMN_WIDTH, type RowDocumentRenderable } from "./RowDocumentRenderable.js"
13
20
  import { useGutterPalette } from "./useGutterPalette.js"
14
- import { isMermaidFence, renderMermaidForTerminal } from "./mermaid.js"
21
+ import { CodeBlock, DEFAULT_CODE_BLOCK_RENDERERS, type CodeBlockRenderer } from "./code-blocks.js"
15
22
  import "./row-document.js"
16
23
  import "./text-table.js"
17
24
 
@@ -24,6 +31,33 @@ interface MarkdownViewProps {
24
31
  showLineNumbers?: boolean
25
32
  marks?: MarkState
26
33
  docRef?: RefObject<RowDocumentRenderable | null>
34
+ /**
35
+ * Registry of horizontally scrollable blocks, keyed by block index. Blocks
36
+ * that can overflow horizontally (mermaid diagrams and code blocks)
37
+ * register their text-buffer renderable here so the owning subview can
38
+ * drive horizontal panning (`scrollX`) for the block under the nav cursor
39
+ * (h/l in cursor mode).
40
+ */
41
+ hScrollableBlocksRef?: RefObject<Map<number, TextBufferRenderable>>
42
+ /**
43
+ * Custom renderers for fenced code blocks, keyed by fence type. A fence's
44
+ * type is the first whitespace-separated word of its info string, matched
45
+ * case-insensitively. Entries are merged over the built-in defaults
46
+ * (currently `mermaid`), so built-ins can be overridden. Unmatched types —
47
+ * and renderers that return `null` or throw — fall back to the default
48
+ * syntax-highlighted code block.
49
+ */
50
+ codeBlockRenderers?: Record<string, CodeBlockRenderer>
51
+ /**
52
+ * Left-click on a block (additive; keyboard navigation is unaffected). The
53
+ * row index is the flattened *block* index, matching the view's `nav` model
54
+ * and the copy/selection unit — clicking selects the same block `j`/`k` move
55
+ * between. Clicks inside a custom-rendered code block bubble up here too,
56
+ * unless the custom renderer stops propagation on its own mouse handlers.
57
+ */
58
+ onRowClick?: (index: number) => void
59
+ /** Right-click on a block — receives the block index and click coordinates. */
60
+ onRowContextMenu?: (index: number, x: number, y: number) => void
27
61
  }
28
62
 
29
63
  /**
@@ -141,20 +175,61 @@ export function MarkdownView({
141
175
  showLineNumbers = true,
142
176
  marks,
143
177
  docRef,
178
+ hScrollableBlocksRef,
179
+ codeBlockRenderers,
180
+ onRowClick,
181
+ onRowContextMenu,
144
182
  }: MarkdownViewProps) {
145
183
  const { theme, syntax } = useTheme()
146
184
  const palette = useGutterPalette()
147
185
  const tokens = useMemo(() => marked.lexer(content), [content])
148
186
  const blocks = useMemo(() => flattenTokens(tokens), [tokens])
149
187
 
188
+ // Merge user renderers over built-in defaults, normalizing keys to
189
+ // lowercase so registration matches fence types case-insensitively.
190
+ const mergedCodeBlockRenderers = useMemo(() => {
191
+ const merged: Record<string, CodeBlockRenderer> = { ...DEFAULT_CODE_BLOCK_RENDERERS }
192
+ for (const [key, renderer] of Object.entries(codeBlockRenderers ?? {})) {
193
+ merged[key.trim().toLowerCase()] = renderer
194
+ }
195
+ return merged
196
+ }, [codeBlockRenderers])
197
+
150
198
  const blockElements = useMemo(
151
199
  () =>
152
200
  blocks.map((block, index) => (
153
- <FlatBlockRenderer key={index} block={block} theme={theme} syntax={syntax} />
201
+ <FlatBlockRenderer
202
+ key={index}
203
+ block={block}
204
+ blockIndex={index}
205
+ theme={theme}
206
+ syntax={syntax}
207
+ hScrollableBlocksRef={hScrollableBlocksRef}
208
+ codeBlockRenderers={mergedCodeBlockRenderers}
209
+ />
154
210
  )),
155
- [blocks, theme, syntax],
211
+ [blocks, theme, syntax, hScrollableBlocksRef, mergedCodeBlockRenderers],
156
212
  )
157
213
 
214
+ // A single handler on the row-document maps the click's screen-Y to a block
215
+ // index. Blocks are per-child renderables, but their markup varies across
216
+ // renderer branches (box/text/null with differing margins), so mapping by
217
+ // screen-Y avoids wrapping every branch and keeps gutter/line-number geometry
218
+ // intact. Clicks bubble up from block children (including custom code blocks).
219
+ const handleMouseDown =
220
+ onRowClick || onRowContextMenu
221
+ ? (event: MouseEvent) => {
222
+ const row = docRef?.current?.getRowAtScreenY(event.y)
223
+ if (row == null) return
224
+ if (event.button === 0) {
225
+ onRowClick?.(row)
226
+ } else if (event.button === 2) {
227
+ event.preventDefault()
228
+ onRowContextMenu?.(row, event.x, event.y)
229
+ }
230
+ }
231
+ : undefined
232
+
158
233
  return (
159
234
  <row-document
160
235
  ref={docRef}
@@ -163,6 +238,7 @@ export function MarkdownView({
163
238
  decorations={marks?.sets}
164
239
  signColumnWidth={DEFAULT_SIGN_COLUMN_WIDTH}
165
240
  style={{ flexGrow: 1 }}
241
+ onMouseDown={handleMouseDown}
166
242
  >
167
243
  {blockElements}
168
244
  </row-document>
@@ -175,12 +251,18 @@ export function MarkdownView({
175
251
 
176
252
  function FlatBlockRenderer({
177
253
  block,
254
+ blockIndex,
178
255
  theme,
179
256
  syntax,
257
+ hScrollableBlocksRef,
258
+ codeBlockRenderers,
180
259
  }: {
181
260
  block: FlatBlock
261
+ blockIndex: number
182
262
  theme: ResolvedTheme
183
263
  syntax: SyntaxStyle
264
+ hScrollableBlocksRef?: RefObject<Map<number, TextBufferRenderable>>
265
+ codeBlockRenderers?: Record<string, CodeBlockRenderer>
184
266
  }): ReactNode {
185
267
  const { token, indent, bullet } = block
186
268
 
@@ -195,16 +277,18 @@ function FlatBlockRenderer({
195
277
  return <HeadingRenderer token={token as Tokens.Heading} theme={theme} indent={indent} />
196
278
  case "paragraph":
197
279
  return <ParagraphRenderer token={token as Tokens.Paragraph} theme={theme} indent={indent} />
198
- case "code": {
199
- const codeToken = token as Tokens.Code
200
- if (isMermaidFence(codeToken.lang)) {
201
- return (
202
- <MermaidBlockRenderer token={codeToken} theme={theme} syntax={syntax} indent={indent} />
203
- )
204
- }
205
-
206
- return <CodeBlockRenderer token={codeToken} theme={theme} syntax={syntax} indent={indent} />
207
- }
280
+ case "code":
281
+ return (
282
+ <CodeBlock
283
+ token={token as Tokens.Code}
284
+ blockIndex={blockIndex}
285
+ theme={theme}
286
+ syntax={syntax}
287
+ indent={indent}
288
+ hScrollableBlocksRef={hScrollableBlocksRef}
289
+ renderers={codeBlockRenderers}
290
+ />
291
+ )
208
292
  case "blockquote":
209
293
  return <BlockquoteRenderer token={token as Tokens.Blockquote} theme={theme} indent={indent} />
210
294
  case "table":
@@ -330,93 +414,6 @@ function ParagraphRenderer({
330
414
  )
331
415
  }
332
416
 
333
- function CodeBlockRenderer({
334
- token,
335
- theme,
336
- syntax,
337
- indent,
338
- }: {
339
- token: Tokens.Code
340
- theme: ResolvedTheme
341
- syntax: SyntaxStyle
342
- indent: number
343
- }) {
344
- const lineCount = token.text.split("\n").length
345
- return (
346
- <box
347
- style={{
348
- marginTop: 0,
349
- marginBottom: 1,
350
- marginLeft: 1 + indent,
351
- marginRight: 1,
352
- border: true,
353
- borderColor: theme.border,
354
- backgroundColor: theme.backgroundElement,
355
- flexDirection: "column",
356
- }}
357
- >
358
- <code
359
- content={token.text}
360
- filetype={token.lang}
361
- syntaxStyle={syntax}
362
- style={{ height: lineCount }}
363
- />
364
- </box>
365
- )
366
- }
367
-
368
- function MermaidBlockRenderer({
369
- token,
370
- theme,
371
- syntax,
372
- indent,
373
- }: {
374
- token: Tokens.Code
375
- theme: ResolvedTheme
376
- syntax: SyntaxStyle
377
- indent: number
378
- }) {
379
- const mermaidTheme = useMemo(
380
- () => ({
381
- fg: theme.markdownText,
382
- border: theme.border,
383
- line: theme.textMuted,
384
- arrow: theme.accent,
385
- accent: theme.accent,
386
- bg: theme.backgroundElement,
387
- corner: theme.borderActive,
388
- junction: theme.borderSubtle,
389
- }),
390
- [theme],
391
- )
392
- const result = useMemo(
393
- () => renderMermaidForTerminal(token.text, { mode: "ansi", theme: mermaidTheme }),
394
- [token.text, mermaidTheme],
395
- )
396
-
397
- if (!result.ok) {
398
- return <CodeBlockRenderer token={token} theme={theme} syntax={syntax} indent={indent} />
399
- }
400
-
401
- const lineCount = result.text.split("\n").length
402
- return (
403
- <box
404
- style={{
405
- marginTop: 0,
406
- marginBottom: 1,
407
- marginLeft: 1 + indent,
408
- marginRight: 1,
409
- border: true,
410
- borderColor: theme.border,
411
- backgroundColor: theme.backgroundElement,
412
- flexDirection: "column",
413
- }}
414
- >
415
- <text content={result.content} style={{ fg: theme.markdownText, height: lineCount }} />
416
- </box>
417
- )
418
- }
419
-
420
417
  function BlockquoteRenderer({
421
418
  token,
422
419
  theme,
@@ -201,6 +201,26 @@ export class RowDocumentRenderable extends ScrollBoxRenderable {
201
201
  return 0
202
202
  }
203
203
 
204
+ /**
205
+ * Map an absolute terminal Y coordinate (as delivered on a `MouseEvent`) to a
206
+ * logical row index. Returns `null` when the Y is above/below the scroll
207
+ * viewport or past the last rendered content row, so callers can ignore clicks
208
+ * that land on empty space. Clicks that land in an inter-row margin gap resolve
209
+ * to the nearest row above (via `getRowAtVirtualY`).
210
+ *
211
+ * Works for both multi-child mode (row = child index, e.g. a markdown block)
212
+ * and provider mode (row = source line, e.g. a code line): geometry is
213
+ * recomputed every frame in `renderSelf`, so `_virtualRowToRow` is current by
214
+ * the time a click is processed.
215
+ */
216
+ getRowAtScreenY(screenY: number): number | null {
217
+ const localY = screenY - this.viewport.y
218
+ if (localY < 0 || localY >= this.viewport.height) return null
219
+ const virtualY = Math.floor(this.scrollTop) + localY
220
+ if (virtualY < 0 || virtualY >= this._virtualRowToRow.length) return null
221
+ return this.getRowAtVirtualY(virtualY)
222
+ }
223
+
204
224
  getVisibleRange(): {
205
225
  virtualTop: number
206
226
  virtualBottom: number
package/src/Table.tsx CHANGED
@@ -1,6 +1,7 @@
1
1
  import { useTerminalDimensions } from "@opentui/react"
2
2
  import { useTheme } from "@tooee/themes"
3
- import { useMemo, type RefObject } from "react"
3
+ import { useMemo, useRef, type RefObject } from "react"
4
+ import type { MouseEvent } from "@opentui/core"
4
5
  import type { MarkState } from "@tooee/marks"
5
6
  import type { ColumnDef, TableRow } from "./table-types.js"
6
7
  import {
@@ -28,6 +29,10 @@ export interface TableProps {
28
29
  docRef?: RefObject<RowDocumentRenderable | null>
29
30
  /** Column width mode: "content" sizes to content (default), "fill" expands to fill available width */
30
31
  columnWidthMode?: "content" | "fill"
32
+ /** Left-click on a data row (additive; keyboard navigation is unaffected). */
33
+ onRowClick?: (index: number) => void
34
+ /** Right-click on a data row — receives the row index and click coordinates. */
35
+ onRowContextMenu?: (index: number, x: number, y: number) => void
31
36
  }
32
37
 
33
38
  const PADDING = 1
@@ -151,10 +156,14 @@ export function Table({
151
156
  marks,
152
157
  docRef,
153
158
  columnWidthMode = "content",
159
+ onRowClick,
160
+ onRowContextMenu,
154
161
  }: TableProps) {
155
162
  const { theme } = useTheme()
156
163
  const palette = useGutterPalette()
157
164
  const { width: terminalWidth } = useTerminalDimensions()
165
+ const internalDocRef = useRef<RowDocumentRenderable | null>(null)
166
+ const rowDocumentRef = docRef ?? internalDocRef
158
167
 
159
168
  // Compute available content width: start with total space, subtract margins and gutter
160
169
  const gutterWidth = useMemo(
@@ -236,6 +245,23 @@ export function Table({
236
245
  [normalizedRows, colWidths, alignments, theme.text],
237
246
  )
238
247
 
248
+ // Use the shared RowDocumentRenderable screen-Y mapper for table rows too.
249
+ // This keeps table, code, and markdown mouse handling on one code path and
250
+ // avoids per-row mouse closures in the virtualized row tree.
251
+ const handleMouseDown =
252
+ onRowClick || onRowContextMenu
253
+ ? (event: MouseEvent) => {
254
+ const row = rowDocumentRef.current?.getRowAtScreenY(event.y)
255
+ if (row == null) return
256
+ if (event.button === 0) {
257
+ onRowClick?.(row)
258
+ } else if (event.button === 2) {
259
+ event.preventDefault()
260
+ onRowContextMenu?.(row, event.x, event.y)
261
+ }
262
+ }
263
+ : undefined
264
+
239
265
  return (
240
266
  <box
241
267
  style={{
@@ -272,7 +298,7 @@ export function Table({
272
298
 
273
299
  {/* Scrollable data rows */}
274
300
  <row-document
275
- ref={docRef}
301
+ ref={rowDocumentRef}
276
302
  mode="multi"
277
303
  rowChildOffset={0}
278
304
  showGutter={true}
@@ -281,6 +307,7 @@ export function Table({
281
307
  palette={palette}
282
308
  decorations={marks?.sets}
283
309
  style={{ flexGrow: 1 }}
310
+ onMouseDown={handleMouseDown}
284
311
  >
285
312
  {rowElements}
286
313
  </row-document>