@tooee/renderers 0.2.4 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/dist/code-blocks.d.ts +6 -6
  2. package/dist/code-blocks.d.ts.map +1 -1
  3. package/dist/code-blocks.js +52 -42
  4. package/dist/code-blocks.js.map +1 -1
  5. package/dist/{CodeView.d.ts → code-view.d.ts} +3 -3
  6. package/dist/code-view.d.ts.map +1 -0
  7. package/dist/{CodeView.js → code-view.js} +5 -5
  8. package/dist/code-view.js.map +1 -0
  9. package/dist/{CommandPalette.d.ts → command-palette.d.ts} +2 -2
  10. package/dist/command-palette.d.ts.map +1 -0
  11. package/dist/{CommandPalette.js → command-palette.js} +27 -24
  12. package/dist/command-palette.js.map +1 -0
  13. package/dist/{ContextMenu.d.ts → context-menu.d.ts} +2 -2
  14. package/dist/context-menu.d.ts.map +1 -0
  15. package/dist/{ContextMenu.js → context-menu.js} +24 -14
  16. package/dist/context-menu.js.map +1 -0
  17. package/dist/{DecorationLayer.d.ts → decoration-layer.d.ts} +2 -2
  18. package/dist/decoration-layer.d.ts.map +1 -0
  19. package/dist/decoration-layer.js +2 -0
  20. package/dist/decoration-layer.js.map +1 -0
  21. package/dist/{DocumentBindings.d.ts → document-bindings.d.ts} +4 -4
  22. package/dist/document-bindings.d.ts.map +1 -0
  23. package/dist/document-bindings.js +2 -0
  24. package/dist/document-bindings.js.map +1 -0
  25. package/dist/index.d.ts +16 -15
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +9 -9
  28. package/dist/index.js.map +1 -1
  29. package/dist/markdown-blocks.d.ts +9 -13
  30. package/dist/markdown-blocks.d.ts.map +1 -1
  31. package/dist/markdown-blocks.js +98 -79
  32. package/dist/markdown-blocks.js.map +1 -1
  33. package/dist/{MarkdownView.d.ts → markdown-view.d.ts} +13 -13
  34. package/dist/markdown-view.d.ts.map +1 -0
  35. package/dist/markdown-view.js +455 -0
  36. package/dist/markdown-view.js.map +1 -0
  37. package/dist/mermaid.d.ts +6 -6
  38. package/dist/mermaid.d.ts.map +1 -1
  39. package/dist/mermaid.js +56 -26
  40. package/dist/mermaid.js.map +1 -1
  41. package/dist/parsers.d.ts +5 -5
  42. package/dist/parsers.d.ts.map +1 -1
  43. package/dist/parsers.js +64 -44
  44. package/dist/parsers.js.map +1 -1
  45. package/dist/{RowDocumentRenderable.d.ts → row-document-renderable.d.ts} +15 -11
  46. package/dist/row-document-renderable.d.ts.map +1 -0
  47. package/dist/{RowDocumentRenderable.js → row-document-renderable.js} +110 -62
  48. package/dist/row-document-renderable.js.map +1 -0
  49. package/dist/row-document.d.ts +1 -1
  50. package/dist/row-document.d.ts.map +1 -1
  51. package/dist/row-document.js +1 -1
  52. package/dist/row-document.js.map +1 -1
  53. package/dist/source.d.ts +6 -6
  54. package/dist/source.d.ts.map +1 -1
  55. package/dist/source.js +35 -26
  56. package/dist/source.js.map +1 -1
  57. package/dist/table-types.d.ts.map +1 -1
  58. package/dist/{Table.d.ts → table.d.ts} +6 -6
  59. package/dist/table.d.ts.map +1 -0
  60. package/dist/{Table.js → table.js} +65 -35
  61. package/dist/table.js.map +1 -0
  62. package/dist/text-table.d.ts.map +1 -1
  63. package/dist/text-table.js.map +1 -1
  64. package/dist/use-gutter-palette.d.ts +3 -0
  65. package/dist/use-gutter-palette.d.ts.map +1 -0
  66. package/dist/{useGutterPalette.js → use-gutter-palette.js} +4 -4
  67. package/dist/use-gutter-palette.js.map +1 -0
  68. package/package.json +5 -5
  69. package/src/code-blocks.tsx +122 -106
  70. package/src/{CodeView.tsx → code-view.tsx} +19 -14
  71. package/src/command-palette.tsx +163 -0
  72. package/src/context-menu.tsx +157 -0
  73. package/src/decoration-layer.ts +11 -0
  74. package/src/document-bindings.ts +16 -0
  75. package/src/index.ts +24 -23
  76. package/src/markdown-blocks.ts +178 -138
  77. package/src/markdown-view.tsx +853 -0
  78. package/src/mermaid.ts +122 -70
  79. package/src/parsers.ts +141 -103
  80. package/src/row-document-renderable.ts +672 -0
  81. package/src/row-document.ts +4 -4
  82. package/src/source.ts +92 -72
  83. package/src/table-types.ts +4 -4
  84. package/src/table.tsx +346 -0
  85. package/src/text-table.ts +4 -4
  86. package/src/use-gutter-palette.ts +15 -0
  87. package/dist/CodeView.d.ts.map +0 -1
  88. package/dist/CodeView.js.map +0 -1
  89. package/dist/CommandPalette.d.ts.map +0 -1
  90. package/dist/CommandPalette.js.map +0 -1
  91. package/dist/ContextMenu.d.ts.map +0 -1
  92. package/dist/ContextMenu.js.map +0 -1
  93. package/dist/DecorationLayer.d.ts.map +0 -1
  94. package/dist/DecorationLayer.js +0 -2
  95. package/dist/DecorationLayer.js.map +0 -1
  96. package/dist/DocumentBindings.d.ts.map +0 -1
  97. package/dist/DocumentBindings.js +0 -2
  98. package/dist/DocumentBindings.js.map +0 -1
  99. package/dist/MarkdownView.d.ts.map +0 -1
  100. package/dist/MarkdownView.js +0 -360
  101. package/dist/MarkdownView.js.map +0 -1
  102. package/dist/RowDocumentRenderable.d.ts.map +0 -1
  103. package/dist/RowDocumentRenderable.js.map +0 -1
  104. package/dist/Table.d.ts.map +0 -1
  105. package/dist/Table.js.map +0 -1
  106. package/dist/useGutterPalette.d.ts +0 -3
  107. package/dist/useGutterPalette.d.ts.map +0 -1
  108. package/dist/useGutterPalette.js.map +0 -1
  109. package/src/CommandPalette.tsx +0 -147
  110. package/src/ContextMenu.tsx +0 -132
  111. package/src/DecorationLayer.ts +0 -11
  112. package/src/DocumentBindings.ts +0 -16
  113. package/src/MarkdownView.tsx +0 -738
  114. package/src/RowDocumentRenderable.ts +0 -593
  115. package/src/Table.tsx +0 -300
  116. package/src/useGutterPalette.ts +0 -15
package/src/source.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { Key } from "react"
1
+ import type { Key } from "react";
2
2
 
3
3
  // ---------------------------------------------------------------------------
4
4
  // Source-coordinate types
@@ -6,9 +6,9 @@ import type { Key } from "react"
6
6
 
7
7
  /** A point in the original source. Offsets and columns are UTF-16 code-unit indices. */
8
8
  export interface SourcePoint {
9
- offset: number
10
- line: number
11
- column: number
9
+ offset: number;
10
+ line: number;
11
+ column: number;
12
12
  }
13
13
 
14
14
  /**
@@ -20,49 +20,54 @@ export interface SourcePoint {
20
20
  * cover the following line.
21
21
  */
22
22
  export interface SourceSpan {
23
- sourceId?: string
24
- start: SourcePoint
25
- end: SourcePoint
26
- lastLine: number
23
+ sourceId?: string;
24
+ start: SourcePoint;
25
+ end: SourcePoint;
26
+ lastLine: number;
27
27
 
28
28
  /** Exact original substring in `[start.offset, end.offset)`. */
29
- text: string
29
+ text: string;
30
30
 
31
31
  /** Complete physical source lines touched by the span, without newline normalization. */
32
- lineText: string
32
+ lineText: string;
33
33
  }
34
34
 
35
35
  /** A rendered row can be synthetic, have one source, or relate two/more sources. */
36
36
  export interface DocumentRowSource {
37
- primary: SourceSpan
38
- related?: readonly SourceSpan[]
37
+ primary: SourceSpan;
38
+ related?: readonly SourceSpan[];
39
39
  }
40
40
 
41
41
  /** The live anchor a document controller resolves for a rendered/navigation row. */
42
42
  export interface DocumentRowAnchor<T> {
43
- row: T
44
- index: number
45
- key: Key
43
+ row: T;
44
+ index: number;
45
+ key: Key;
46
46
 
47
47
  /** The same semantic text used by default search and copy. */
48
- text: string
48
+ text: string;
49
49
 
50
50
  /** `null` for generated rows with no meaningful source coordinate. */
51
- source: DocumentRowSource | null
51
+ source: DocumentRowSource | null;
52
52
  }
53
53
 
54
54
  // ---------------------------------------------------------------------------
55
55
  // Line index and span construction
56
56
  // ---------------------------------------------------------------------------
57
57
 
58
+ const LINE_FEED_CODE = 10;
59
+ const CARRIAGE_RETURN_CODE = 13;
60
+
58
61
  /** Offsets of the first character of every physical line. */
59
- function buildLineStarts(text: string): number[] {
60
- const starts = [0]
61
- for (let i = 0; i < text.length; i++) {
62
- if (text.charCodeAt(i) === 10 /* \n */) starts.push(i + 1)
62
+ const buildLineStarts = function buildLineStarts(text: string): number[] {
63
+ const starts = [0];
64
+ for (let i = 0; i < text.length; i += 1) {
65
+ if (text.codePointAt(i) === LINE_FEED_CODE) {
66
+ starts.push(i + 1);
67
+ }
63
68
  }
64
- return starts
65
- }
69
+ return starts;
70
+ };
66
71
 
67
72
  /**
68
73
  * A CRLF-aware line-start index over an original source string. A `\r\n` is one
@@ -70,43 +75,49 @@ function buildLineStarts(text: string): number[] {
70
75
  * `\r\n` string, so the `\r` counts as a column on the preceding line.
71
76
  */
72
77
  export class SourceIndex {
73
- readonly lineStarts: number[]
74
-
75
- constructor(
76
- readonly text: string,
77
- readonly sourceId?: string,
78
- ) {
79
- this.lineStarts = buildLineStarts(text)
78
+ readonly lineStarts: number[];
79
+ readonly text: string;
80
+ readonly sourceId?: string;
81
+
82
+ constructor(text: string, sourceId?: string) {
83
+ this.text = text;
84
+ this.sourceId = sourceId;
85
+ this.lineStarts = buildLineStarts(text);
80
86
  }
81
87
 
82
88
  /** The physical line index (0-based) containing `offset`, via binary search. */
83
89
  lineAt(offset: number): number {
84
- const starts = this.lineStarts
85
- let lo = 0
86
- let hi = starts.length - 1
90
+ const starts = this.lineStarts;
91
+ let lo = 0;
92
+ let hi = starts.length - 1;
87
93
  while (lo < hi) {
88
- const mid = (lo + hi + 1) >> 1
89
- if (starts[mid]! <= offset) lo = mid
90
- else hi = mid - 1
94
+ const mid = Math.floor((lo + hi + 1) / 2);
95
+ if (starts[mid] <= offset) {
96
+ lo = mid;
97
+ } else {
98
+ hi = mid - 1;
99
+ }
91
100
  }
92
- return lo
101
+ return lo;
93
102
  }
94
103
 
95
104
  point(offset: number): SourcePoint {
96
- const line = this.lineAt(offset)
97
- return { offset, line, column: offset - this.lineStarts[line]! }
105
+ const line = this.lineAt(offset);
106
+ return { column: offset - this.lineStarts[line], line, offset };
98
107
  }
99
108
 
100
109
  /** End offset of a line's content, excluding its `\n`/`\r\n` delimiter. */
101
110
  lineContentEnd(line: number): number {
102
- const starts = this.lineStarts
103
- const nextStart = line + 1 < starts.length ? starts[line + 1]! : this.text.length
104
- let end = nextStart
105
- if (end > starts[line]! && this.text.charCodeAt(end - 1) === 10) {
106
- end--
107
- if (end > starts[line]! && this.text.charCodeAt(end - 1) === 13 /* \r */) end--
111
+ const starts = this.lineStarts;
112
+ const nextStart = line + 1 < starts.length ? starts[line + 1] : this.text.length;
113
+ let end = nextStart;
114
+ if (end > starts[line] && this.text.codePointAt(end - 1) === LINE_FEED_CODE) {
115
+ end -= 1;
116
+ if (end > starts[line] && this.text.codePointAt(end - 1) === CARRIAGE_RETURN_CODE) {
117
+ end -= 1;
118
+ }
108
119
  }
109
- return end
120
+ return end;
110
121
  }
111
122
 
112
123
  /**
@@ -116,27 +127,33 @@ export class SourceIndex {
116
127
  * line. `text` and `lineText` preserve original characters.
117
128
  */
118
129
  span(rawStart: number, rawEnd: number, trimTrailingNewlines = true): SourceSpan {
119
- let end = rawEnd
130
+ let end = rawEnd;
120
131
  if (trimTrailingNewlines) {
121
- while (end > rawStart && this.text.charCodeAt(end - 1) === 10) {
122
- end--
123
- if (end > rawStart && this.text.charCodeAt(end - 1) === 13) end--
132
+ while (end > rawStart && this.text.codePointAt(end - 1) === 10) {
133
+ end -= 1;
134
+ if (end > rawStart && this.text.codePointAt(end - 1) === 13) {
135
+ end -= 1;
136
+ }
124
137
  }
125
138
  }
126
- if (end < rawStart) end = rawStart
139
+ if (end < rawStart) {
140
+ end = rawStart;
141
+ }
127
142
 
128
- const start = this.point(rawStart)
129
- const endPoint = this.point(end)
130
- const lastLine = end > rawStart ? this.lineAt(end - 1) : start.line
143
+ const start = this.point(rawStart);
144
+ const endPoint = this.point(end);
145
+ const lastLine = end > rawStart ? this.lineAt(end - 1) : start.line;
131
146
  const span: SourceSpan = {
132
- start,
133
147
  end: endPoint,
134
148
  lastLine,
149
+ lineText: this.text.slice(this.lineStarts[start.line], this.lineContentEnd(lastLine)),
150
+ start,
135
151
  text: this.text.slice(rawStart, end),
136
- lineText: this.text.slice(this.lineStarts[start.line]!, this.lineContentEnd(lastLine)),
152
+ };
153
+ if (this.sourceId !== undefined) {
154
+ span.sourceId = this.sourceId;
137
155
  }
138
- if (this.sourceId !== undefined) span.sourceId = this.sourceId
139
- return span
156
+ return span;
140
157
  }
141
158
  }
142
159
 
@@ -145,8 +162,8 @@ export class SourceIndex {
145
162
  // ---------------------------------------------------------------------------
146
163
 
147
164
  export interface SourceLineRow {
148
- text: string
149
- source: DocumentRowSource
165
+ text: string;
166
+ source: DocumentRowSource;
150
167
  }
151
168
 
152
169
  /**
@@ -156,22 +173,25 @@ export interface SourceLineRow {
156
173
  * its newline delimiter; CRLF is one line break while offsets keep addressing
157
174
  * the original `\r\n` string.
158
175
  */
159
- export function sourceLines(source: string, options?: { sourceId?: string }): SourceLineRow[] {
160
- const index = new SourceIndex(source, options?.sourceId)
161
- const rows: SourceLineRow[] = []
162
- for (let line = 0; line < index.lineStarts.length; line++) {
163
- const start = index.lineStarts[line]!
164
- const end = index.lineContentEnd(line)
176
+ export const sourceLines = function sourceLines(
177
+ source: string,
178
+ options?: { sourceId?: string },
179
+ ): SourceLineRow[] {
180
+ const index = new SourceIndex(source, options?.sourceId);
181
+ const rows: SourceLineRow[] = [];
182
+ for (let line = 0; line < index.lineStarts.length; line += 1) {
183
+ const start = index.lineStarts[line];
184
+ const end = index.lineContentEnd(line);
165
185
  rows.push({
166
- text: source.slice(start, end),
167
186
  source: { primary: index.span(start, end, false) },
168
- })
187
+ text: source.slice(start, end),
188
+ });
169
189
  }
170
- return rows
171
- }
190
+ return rows;
191
+ };
172
192
 
173
193
  /** Adapter for `sourceLines()` rows: identity mapping in row/line space. */
174
194
  export const sourceLineAdapter = {
175
- getText: (row: SourceLineRow): string => row.text,
176
195
  getSource: (row: SourceLineRow): DocumentRowSource => row.source,
177
- }
196
+ getText: (row: SourceLineRow): string => row.text,
197
+ };
@@ -1,7 +1,7 @@
1
1
  export interface ColumnDef {
2
- key: string
3
- header?: string
4
- align?: "left" | "right"
2
+ key: string;
3
+ header?: string;
4
+ align?: "left" | "right";
5
5
  }
6
6
 
7
- export type TableRow = Record<string, unknown>
7
+ export type TableRow = Record<string, unknown>;
package/src/table.tsx ADDED
@@ -0,0 +1,346 @@
1
+ import { useTerminalDimensions } from "@opentui/react";
2
+ import { useTheme } from "@tooee/themes";
3
+ import { useMemo, useRef } from "react";
4
+ import type { DocumentBindings } from "./document-bindings.js";
5
+ import type { ColumnDef, TableRow } from "./table-types.js";
6
+ import {
7
+ DEFAULT_SIGN_COLUMN_WIDTH,
8
+ computeRowDocumentGutterWidth,
9
+ } from "./row-document-renderable.js";
10
+ import type { RowDocumentRenderable } from "./row-document-renderable.js";
11
+ import { useGutterPalette } from "./use-gutter-palette.js";
12
+ import "./row-document.js";
13
+
14
+ export interface TableProps {
15
+ columns: ColumnDef[];
16
+ rows: TableRow[];
17
+ /** Maximum width for the table. If not provided, uses terminal width. */
18
+ maxWidth?: number;
19
+ /** Minimum width for any column (default: 4) */
20
+ minColumnWidth?: number;
21
+ /** Maximum width for any column (default: 50) */
22
+ maxColumnWidth?: number;
23
+ /** Number of rows to sample for width calculation (default: 100) */
24
+ sampleSize?: number;
25
+ /** Show line numbers in the gutter (default: true) */
26
+ showLineNumbers?: boolean;
27
+ /**
28
+ * Binds the data rows to a document controller: its ref, the decoration
29
+ * layers to paint, and the mouse handler. Rows are data-row indices; the
30
+ * fixed header sits outside the row document. Omit it to render a static,
31
+ * non-interactive table.
32
+ */
33
+ document?: DocumentBindings;
34
+ /** Column width mode: "content" sizes to content (default), "fill" expands to fill available width */
35
+ columnWidthMode?: "content" | "fill";
36
+ }
37
+
38
+ const PADDING = 1;
39
+ const TABLE_MARGIN = 1;
40
+ const DEFAULT_MIN_COL_WIDTH = 4;
41
+ const DEFAULT_MAX_COL_WIDTH = 80;
42
+ const DEFAULT_SAMPLE_SIZE = 100;
43
+
44
+ const isNumeric = function isNumeric(value: string): boolean {
45
+ return /^\s*-?[\d,]+\.?\d*\s*$/u.test(value);
46
+ };
47
+
48
+ interface ColumnWidthOptions {
49
+ minColumnWidth: number;
50
+ maxColumnWidth: number;
51
+ sampleSize: number;
52
+ columnWidthMode?: "content" | "fill";
53
+ }
54
+
55
+ const sampleRows = function sampleRows(rows: string[][], sampleSize: number): string[][] {
56
+ if (rows.length <= sampleSize) {
57
+ return rows;
58
+ }
59
+ // Sample evenly distributed rows for representative widths
60
+ const step = rows.length / sampleSize;
61
+ const sampled: string[][] = [];
62
+ for (let i = 0; i < sampleSize; i += 1) {
63
+ sampled.push(rows[Math.floor(i * step)]);
64
+ }
65
+ return sampled;
66
+ };
67
+
68
+ const computeColumnWidths = function computeColumnWidths(
69
+ headers: string[],
70
+ rows: string[][],
71
+ maxWidth: number,
72
+ options: ColumnWidthOptions,
73
+ ): number[] {
74
+ const { minColumnWidth, maxColumnWidth, sampleSize } = options;
75
+ const colCount = headers.length;
76
+
77
+ // Sample rows for performance on large tables
78
+ const sampledRows = sampleRows(rows, sampleSize);
79
+
80
+ // Calculate natural width for each column (header + content + padding)
81
+ // Use Bun.stringWidth for correct display width with CJK/emoji
82
+ const naturalWidths = headers.map((header, col) => {
83
+ const headerLen = Bun.stringWidth(header);
84
+ let maxRowLen = 0;
85
+ const sampledRowCount = sampledRows.length;
86
+ for (let rowIndex = 0; rowIndex < sampledRowCount; rowIndex += 1) {
87
+ if (rowIndex in sampledRows) {
88
+ const row = sampledRows[rowIndex];
89
+ maxRowLen = Math.max(maxRowLen, Bun.stringWidth(row[col] ?? ""));
90
+ }
91
+ }
92
+ const contentWidth = Math.max(headerLen, maxRowLen);
93
+ // Apply min/max constraints before adding padding
94
+ const constrainedWidth = Math.min(maxColumnWidth, Math.max(minColumnWidth, contentWidth));
95
+ return constrainedWidth + PADDING * 2;
96
+ });
97
+
98
+ // No border overhead -- flexbox rows don't have border characters
99
+ const totalNatural = naturalWidths.reduce((a, b) => a + b, 0);
100
+
101
+ // If everything fits, use natural widths (or distribute extra space in fill mode)
102
+ if (totalNatural <= maxWidth) {
103
+ if (options.columnWidthMode === "fill" && totalNatural < maxWidth) {
104
+ const extra = maxWidth - totalNatural;
105
+ const perCol = Math.floor(extra / colCount);
106
+ const remainder = extra - perCol * colCount;
107
+ return naturalWidths.map((w, i) => w + perCol + (i < remainder ? 1 : 0));
108
+ }
109
+ return naturalWidths;
110
+ }
111
+
112
+ const available = maxWidth;
113
+ const minColWidthWithPadding = minColumnWidth + PADDING * 2;
114
+
115
+ // Extreme case: not even minimum widths fit
116
+ if (maxWidth <= colCount * minColWidthWithPadding) {
117
+ return naturalWidths.map(() =>
118
+ Math.max(minColWidthWithPadding, Math.floor(available / colCount)),
119
+ );
120
+ }
121
+
122
+ // Give compact columns their natural width, distribute rest proportionally
123
+ const compact: boolean[] = naturalWidths.map((w) => w <= 20);
124
+ const compactTotal = naturalWidths.reduce((sum, w, i) => sum + (compact[i] ? w : 0), 0);
125
+ const remaining = available - compactTotal;
126
+ const longTotal = naturalWidths.reduce((sum, w, i) => sum + (compact[i] ? 0 : w), 0);
127
+
128
+ if (longTotal === 0 || remaining <= 0) {
129
+ // All compact or no space left -- distribute evenly
130
+ const total = naturalWidths.reduce((a, b) => a + b, 0);
131
+ return naturalWidths.map((w) =>
132
+ Math.max(minColWidthWithPadding, Math.floor((w / total) * available)),
133
+ );
134
+ }
135
+
136
+ return naturalWidths.map((w, i) => {
137
+ if (compact[i]) {
138
+ return w;
139
+ }
140
+ return Math.max(minColWidthWithPadding, Math.floor((w / longTotal) * remaining));
141
+ });
142
+ };
143
+
144
+ const formatCellValue = function formatCellValue(value: unknown): string {
145
+ if (value === null || value === undefined) {
146
+ return "";
147
+ }
148
+ if (typeof value === "string") {
149
+ return value;
150
+ }
151
+ if (typeof value === "number" || typeof value === "boolean") {
152
+ return String(value);
153
+ }
154
+ if (value instanceof Date) {
155
+ return value.toISOString();
156
+ }
157
+ if (typeof value === "string") {
158
+ return value;
159
+ }
160
+ if (
161
+ typeof value === "number" ||
162
+ typeof value === "bigint" ||
163
+ typeof value === "boolean" ||
164
+ typeof value === "symbol"
165
+ ) {
166
+ return value.toString();
167
+ }
168
+ if (value === null || value === undefined) {
169
+ return String(value);
170
+ }
171
+ if (typeof value === "function") {
172
+ return Function.prototype.toString.call(value);
173
+ }
174
+ try {
175
+ return JSON.stringify(value);
176
+ } catch {
177
+ return Array.isArray(value) ? value.join(",") : Object.prototype.toString.call(value);
178
+ }
179
+ };
180
+
181
+ export const Table = function Table({
182
+ columns,
183
+ rows,
184
+ maxWidth,
185
+ minColumnWidth = DEFAULT_MIN_COL_WIDTH,
186
+ maxColumnWidth = DEFAULT_MAX_COL_WIDTH,
187
+ sampleSize = DEFAULT_SAMPLE_SIZE,
188
+ showLineNumbers = true,
189
+ document,
190
+ columnWidthMode = "content",
191
+ }: TableProps): React.ReactNode {
192
+ const { theme } = useTheme();
193
+ const palette = useGutterPalette();
194
+ const { width: terminalWidth } = useTerminalDimensions();
195
+ const internalDocRef = useRef<RowDocumentRenderable | null>(null);
196
+ const rowDocumentRef = document?.ref ?? internalDocRef;
197
+
198
+ // Compute available content width: start with total space, subtract margins and gutter
199
+ const gutterWidth = useMemo(
200
+ () =>
201
+ computeRowDocumentGutterWidth({
202
+ rowCount: rows.length,
203
+ showLineNumbers,
204
+ signColumnWidth: DEFAULT_SIGN_COLUMN_WIDTH,
205
+ }),
206
+ [showLineNumbers, rows.length],
207
+ );
208
+ const effectiveMaxWidth = Math.max(
209
+ 0,
210
+ (maxWidth ?? terminalWidth) - TABLE_MARGIN * 2 - gutterWidth,
211
+ );
212
+
213
+ const headers = useMemo(() => columns.map((column) => column.header ?? column.key), [columns]);
214
+ const normalizedRows = useMemo(
215
+ () => rows.map((row) => columns.map((column) => formatCellValue(row[column.key]))),
216
+ [columns, rows],
217
+ );
218
+
219
+ const colWidths = useMemo(
220
+ () =>
221
+ computeColumnWidths(headers, normalizedRows, effectiveMaxWidth, {
222
+ columnWidthMode,
223
+ maxColumnWidth,
224
+ minColumnWidth,
225
+ sampleSize,
226
+ }),
227
+ [
228
+ headers,
229
+ normalizedRows,
230
+ effectiveMaxWidth,
231
+ minColumnWidth,
232
+ maxColumnWidth,
233
+ sampleSize,
234
+ columnWidthMode,
235
+ ],
236
+ );
237
+
238
+ // Detect right-aligned columns: explicit align prop or auto-detect numeric
239
+ const alignments = useMemo(
240
+ () =>
241
+ columns.map((column, colIdx) => {
242
+ if (column.align === "right") {
243
+ return true;
244
+ }
245
+ if (column.align === "left") {
246
+ return false;
247
+ }
248
+ const sampleValues = normalizedRows.slice(0, 10).map((row) => row[colIdx] ?? "");
249
+ const numericCount = sampleValues.filter(isNumeric).length;
250
+ return numericCount > sampleValues.length / 2;
251
+ }),
252
+ [columns, normalizedRows],
253
+ );
254
+
255
+ const rowElements = useMemo(
256
+ () =>
257
+ normalizedRows.map(
258
+ (row, i): React.ReactNode => (
259
+ <box key={i} style={{ flexDirection: "row" }}>
260
+ {row.map((cell, j): React.ReactNode => {
261
+ const contentWidth = colWidths[j] - PADDING * 2;
262
+ const cellWidth = Bun.stringWidth(cell);
263
+ const displayCell =
264
+ alignments[j] && cellWidth <= contentWidth
265
+ ? " ".repeat(contentWidth - cellWidth) + cell
266
+ : cell;
267
+ return (
268
+ <text
269
+ key={j}
270
+ content={displayCell}
271
+ wrapMode="word"
272
+ style={{
273
+ paddingLeft: PADDING,
274
+ paddingRight: PADDING,
275
+ width: colWidths[j],
276
+ }}
277
+ fg={theme.text}
278
+ />
279
+ );
280
+ })}
281
+ </box>
282
+ ),
283
+ ),
284
+ [normalizedRows, colWidths, alignments, theme.text],
285
+ );
286
+
287
+ return (
288
+ <box
289
+ style={{
290
+ flexDirection: "column",
291
+ flexGrow: 1,
292
+ marginBottom: TABLE_MARGIN,
293
+ marginLeft: TABLE_MARGIN,
294
+ marginRight: TABLE_MARGIN,
295
+ }}
296
+ >
297
+ {/* Fixed header row — outside row-document so it stays visible */}
298
+ <box style={{ flexDirection: "row", flexShrink: 0, paddingLeft: gutterWidth }}>
299
+ {headers.map(
300
+ (h, i): React.ReactNode => (
301
+ <text
302
+ key={i}
303
+ content={h}
304
+ style={{ paddingLeft: PADDING, paddingRight: PADDING, width: colWidths[i] }}
305
+ fg={theme.primary}
306
+ />
307
+ ),
308
+ )}
309
+ </box>
310
+
311
+ {/* Fixed header underline */}
312
+ <box style={{ flexDirection: "row", flexShrink: 0, paddingLeft: gutterWidth }}>
313
+ {colWidths.map(
314
+ (w, i): React.ReactNode => (
315
+ <text
316
+ key={i}
317
+ content={"\u2500".repeat(w - PADDING * 2)}
318
+ style={{ paddingLeft: PADDING, paddingRight: PADDING, width: w }}
319
+ fg={theme.border}
320
+ />
321
+ ),
322
+ )}
323
+ </box>
324
+
325
+ {/* Scrollable data rows */}
326
+ <row-document
327
+ ref={rowDocumentRef}
328
+ mode="multi"
329
+ rowChildOffset={0}
330
+ showGutter={true}
331
+ showLineNumbers={showLineNumbers}
332
+ signColumnWidth={DEFAULT_SIGN_COLUMN_WIDTH}
333
+ palette={palette}
334
+ decorations={document?.decorations}
335
+ style={{ flexGrow: 1 }}
336
+ onMouseDown={document?.onMouseDown}
337
+ >
338
+ {rowElements}
339
+ </row-document>
340
+ </box>
341
+ );
342
+ };
343
+
344
+ // Exported for testing and MarkdownView
345
+ export { computeColumnWidths, isNumeric, sampleRows };
346
+ export type { ColumnWidthOptions };
package/src/text-table.ts CHANGED
@@ -1,10 +1,10 @@
1
- import { extend } from "@opentui/react"
2
- import { TextTableRenderable } from "@opentui/core"
1
+ import { extend } from "@opentui/react";
2
+ import { TextTableRenderable } from "@opentui/core";
3
3
 
4
- extend({ "text-table": TextTableRenderable })
4
+ extend({ "text-table": TextTableRenderable });
5
5
 
6
6
  declare module "@opentui/react" {
7
7
  interface OpenTUIComponents {
8
- "text-table": typeof TextTableRenderable
8
+ "text-table": typeof TextTableRenderable;
9
9
  }
10
10
  }
@@ -0,0 +1,15 @@
1
+ import { useMemo } from "react";
2
+ import { useTheme } from "@tooee/themes";
3
+ import type { RowDocumentPalette } from "./row-document-renderable.js";
4
+
5
+ export const useGutterPalette = function useGutterPalette(): RowDocumentPalette {
6
+ const { theme } = useTheme();
7
+
8
+ return useMemo(
9
+ () => ({
10
+ gutterBg: theme.backgroundElement,
11
+ gutterFg: theme.textMuted,
12
+ }),
13
+ [theme.textMuted, theme.backgroundElement],
14
+ );
15
+ };
@@ -1 +0,0 @@
1
- {"version":3,"file":"CodeView.d.ts","sourceRoot":"","sources":["../src/CodeView.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAA;AAG7D,OAAO,mBAAmB,CAAA;AAE1B,UAAU,aAAa;IACrB,OAAO,EAAE,MAAM,CAAA;IACf,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,eAAe,CAAC,EAAE,OAAO,CAAA;IACzB;;;;;;;;;OASG;IACH,QAAQ,CAAC,EAAE,gBAAgB,CAAA;CAC5B;AAED,wBAAgB,QAAQ,CAAC,EAAE,OAAO,EAAE,QAAQ,EAAE,eAAsB,EAAE,QAAQ,EAAE,EAAE,aAAa,6BAiB9F"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"CodeView.js","sourceRoot":"","sources":["../src/CodeView.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAA;AAExC,OAAO,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAA;AACtE,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAA;AACxD,OAAO,mBAAmB,CAAA;AAmB1B,MAAM,UAAU,QAAQ,CAAC,EAAE,OAAO,EAAE,QAAQ,EAAE,eAAe,GAAG,IAAI,EAAE,QAAQ,EAAiB;IAC7F,MAAM,EAAE,MAAM,EAAE,GAAG,QAAQ,EAAE,CAAA;IAC7B,MAAM,OAAO,GAAG,gBAAgB,EAAE,CAAA;IAElC,OAAO,CACL,uBACE,GAAG,EAAE,QAAQ,EAAE,GAAG,EAClB,eAAe,EAAE,eAAe,EAChC,OAAO,EAAE,OAAO,EAChB,WAAW,EAAE,QAAQ,EAAE,WAAW,EAClC,eAAe,EAAE,yBAAyB,EAC1C,KAAK,EAAE,EAAE,QAAQ,EAAE,CAAC,EAAE,EACtB,WAAW,EAAE,QAAQ,EAAE,WAAW,YAElC,eAAM,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,GAAI,GACtD,CAChB,CAAA;AACH,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"CommandPalette.d.ts","sourceRoot":"","sources":["../src/CommandPalette.tsx"],"names":[],"mappings":"AAKA,MAAM,WAAW,mBAAmB;IAClC,EAAE,EAAE,MAAM,CAAA;IACV,KAAK,EAAE,MAAM,CAAA;IACb,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,IAAI,CAAC,EAAE,MAAM,CAAA;CACd;AAED,UAAU,mBAAmB;IAC3B,QAAQ,EAAE,mBAAmB,EAAE,CAAA;IAC/B,QAAQ,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,IAAI,CAAA;IACrC,OAAO,EAAE,MAAM,IAAI,CAAA;CACpB;AAED,wBAAgB,cAAc,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,EAAE,mBAAmB,6BA+HlF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"CommandPalette.js","sourceRoot":"","sources":["../src/CommandPalette.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,OAAO,CAAA;AACtD,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AAC5C,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,eAAe,CAAA;AACrD,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAA;AAgBzC,MAAM,UAAU,cAAc,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAuB;IACjF,MAAM,EAAE,KAAK,EAAE,GAAG,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