@tooee/renderers 0.11.0 → 0.13.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 (104) hide show
  1. package/dist/chooser/choose-filter.d.ts.map +1 -1
  2. package/dist/chooser/choose-filter.js.map +1 -1
  3. package/dist/chooser/choose-highlighted-text.d.ts.map +1 -1
  4. package/dist/chooser/choose-highlighted-text.js.map +1 -1
  5. package/dist/chooser/choose-list.d.ts.map +1 -1
  6. package/dist/chooser/choose-list.js.map +1 -1
  7. package/dist/chooser/choose-store.d.ts +3 -3
  8. package/dist/chooser/choose-store.d.ts.map +1 -1
  9. package/dist/chooser/choose-store.js.map +1 -1
  10. package/dist/chooser/chooser.d.ts.map +1 -1
  11. package/dist/chooser/chooser.js.map +1 -1
  12. package/dist/chooser/source.d.ts.map +1 -1
  13. package/dist/chooser/source.js.map +1 -1
  14. package/dist/chooser/use-choose.d.ts.map +1 -1
  15. package/dist/chooser/use-choose.js.map +1 -1
  16. package/dist/code-blocks.d.ts.map +1 -1
  17. package/dist/code-blocks.js.map +1 -1
  18. package/dist/command-palette.d.ts.map +1 -1
  19. package/dist/command-palette.js.map +1 -1
  20. package/dist/context-menu.d.ts.map +1 -1
  21. package/dist/context-menu.js.map +1 -1
  22. package/dist/index.d.ts +2 -1
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +1 -0
  25. package/dist/index.js.map +1 -1
  26. package/dist/markdown/blocks/blockquote.d.ts.map +1 -1
  27. package/dist/markdown/blocks/blockquote.js.map +1 -1
  28. package/dist/markdown/blocks/flat-block.d.ts.map +1 -1
  29. package/dist/markdown/blocks/flat-block.js.map +1 -1
  30. package/dist/markdown/blocks/heading.d.ts.map +1 -1
  31. package/dist/markdown/blocks/heading.js.map +1 -1
  32. package/dist/markdown/blocks/list-line.d.ts.map +1 -1
  33. package/dist/markdown/blocks/list-line.js.map +1 -1
  34. package/dist/markdown/blocks/paragraph.d.ts.map +1 -1
  35. package/dist/markdown/blocks/paragraph.js.map +1 -1
  36. package/dist/markdown/blocks/table.d.ts.map +1 -1
  37. package/dist/markdown/blocks/table.js.map +1 -1
  38. package/dist/markdown/links.d.ts.map +1 -1
  39. package/dist/markdown/links.js.map +1 -1
  40. package/dist/markdown/plain-text.d.ts +1 -1
  41. package/dist/markdown/plain-text.d.ts.map +1 -1
  42. package/dist/markdown/plain-text.js +1 -1
  43. package/dist/markdown/plain-text.js.map +1 -1
  44. package/dist/markdown/table-links.d.ts.map +1 -1
  45. package/dist/markdown/table-links.js.map +1 -1
  46. package/dist/markdown/tokens.d.ts.map +1 -1
  47. package/dist/markdown/tokens.js.map +1 -1
  48. package/dist/markdown/visit-inline.d.ts.map +1 -1
  49. package/dist/markdown/visit-inline.js.map +1 -1
  50. package/dist/markdown-blocks.d.ts.map +1 -1
  51. package/dist/markdown-blocks.js.map +1 -1
  52. package/dist/markdown-images.d.ts.map +1 -1
  53. package/dist/markdown-images.js.map +1 -1
  54. package/dist/markdown-view.d.ts +6 -1
  55. package/dist/markdown-view.d.ts.map +1 -1
  56. package/dist/markdown-view.js +2 -2
  57. package/dist/markdown-view.js.map +1 -1
  58. package/dist/mermaid.d.ts.map +1 -1
  59. package/dist/mermaid.js +8 -4
  60. package/dist/mermaid.js.map +1 -1
  61. package/dist/parsers.d.ts.map +1 -1
  62. package/dist/parsers.js.map +1 -1
  63. package/dist/row-document-renderable.d.ts +11 -1
  64. package/dist/row-document-renderable.d.ts.map +1 -1
  65. package/dist/row-document-renderable.js +16 -7
  66. package/dist/row-document-renderable.js.map +1 -1
  67. package/dist/source.d.ts.map +1 -1
  68. package/dist/source.js.map +1 -1
  69. package/dist/table.d.ts.map +1 -1
  70. package/dist/table.js.map +1 -1
  71. package/dist/text-table-internals.d.ts.map +1 -1
  72. package/dist/text-table-internals.js.map +1 -1
  73. package/package.json +6 -6
  74. package/src/chooser/choose-filter.tsx +1 -0
  75. package/src/chooser/choose-highlighted-text.tsx +2 -0
  76. package/src/chooser/choose-list.tsx +6 -0
  77. package/src/chooser/choose-store.ts +20 -3
  78. package/src/chooser/chooser.tsx +2 -0
  79. package/src/chooser/source.ts +5 -0
  80. package/src/chooser/use-choose.ts +44 -0
  81. package/src/code-blocks.tsx +14 -0
  82. package/src/command-palette.tsx +4 -0
  83. package/src/context-menu.tsx +13 -0
  84. package/src/index.ts +44 -0
  85. package/src/markdown/blocks/blockquote.tsx +2 -0
  86. package/src/markdown/blocks/flat-block.tsx +13 -0
  87. package/src/markdown/blocks/heading.tsx +1 -0
  88. package/src/markdown/blocks/list-line.tsx +3 -0
  89. package/src/markdown/blocks/paragraph.tsx +1 -0
  90. package/src/markdown/blocks/table.tsx +7 -0
  91. package/src/markdown/links.ts +26 -0
  92. package/src/markdown/plain-text.ts +6 -1
  93. package/src/markdown/table-links.ts +12 -0
  94. package/src/markdown/tokens.ts +2 -0
  95. package/src/markdown/visit-inline.ts +20 -0
  96. package/src/markdown-blocks.ts +31 -0
  97. package/src/markdown-images.ts +21 -0
  98. package/src/markdown-view.tsx +11 -1
  99. package/src/mermaid.ts +21 -4
  100. package/src/parsers.ts +39 -0
  101. package/src/row-document-renderable.ts +72 -7
  102. package/src/source.ts +18 -0
  103. package/src/table.tsx +32 -0
  104. package/src/text-table-internals.ts +12 -0
@@ -45,6 +45,7 @@ export const checkboxMarker = function checkboxMarker(checked: boolean | undefin
45
45
  if (checked === undefined) {
46
46
  return "";
47
47
  }
48
+
48
49
  return checked ? "[x] " : "[ ] ";
49
50
  };
50
51
 
@@ -56,12 +57,15 @@ export const checkboxMarker = function checkboxMarker(checked: boolean | undefin
56
57
  */
57
58
  export const getFlatBlockText = function getFlatBlockText(block: FlatBlock): string {
58
59
  const { raw } = block.token;
60
+
59
61
  if (raw.length > 0) {
60
62
  return raw;
61
63
  }
64
+
62
65
  if (block.bullet !== undefined) {
63
66
  return block.bullet + checkboxMarker(block.checked);
64
67
  }
68
+
65
69
  return block.source?.primary.text ?? "";
66
70
  };
67
71
 
@@ -89,10 +93,13 @@ class MarkdownResolver {
89
93
  /** Resolve `raw` at/after the cursor within `[cursor, bound]`, then advance. */
90
94
  resolveRaw(raw: string, bound: number): DocumentRowSource | null {
91
95
  const match = this.findRaw(raw, bound);
96
+
92
97
  if (!match) {
93
98
  return null;
94
99
  }
100
+
95
101
  this.cursor = match.end;
102
+
96
103
  return { primary: this.index.span(match.start, match.end) };
97
104
  }
98
105
 
@@ -112,9 +119,11 @@ class MarkdownResolver {
112
119
  if (raw.length === 0) {
113
120
  return null;
114
121
  }
122
+
115
123
  const md = this.markdown;
116
124
 
117
125
  const exact = md.indexOf(raw, this.cursor);
126
+
118
127
  if (exact !== -1 && exact + raw.length <= bound) {
119
128
  return { end: exact + raw.length, start: exact };
120
129
  }
@@ -124,20 +133,26 @@ class MarkdownResolver {
124
133
  }
125
134
 
126
135
  const firstSegment = raw.slice(0, raw.indexOf("\n"));
136
+
127
137
  if (firstSegment.length === 0) {
128
138
  return null;
129
139
  }
130
140
 
131
141
  let from = this.cursor;
142
+
132
143
  for (;;) {
133
144
  const start = md.indexOf(firstSegment, from);
145
+
134
146
  if (start === -1 || start >= bound) {
135
147
  return null;
136
148
  }
149
+
137
150
  const end = this.matchFlexibleNewlines(raw, start, bound);
151
+
138
152
  if (end !== -1) {
139
153
  return { end, start };
140
154
  }
155
+
141
156
  from = start + 1;
142
157
  }
143
158
  }
@@ -148,8 +163,10 @@ class MarkdownResolver {
148
163
  const { length } = md;
149
164
  let h = start;
150
165
  let n = 0;
166
+
151
167
  while (n < raw.length) {
152
168
  const code = raw.codePointAt(n);
169
+
153
170
  if (code === LINE_FEED_CODE) {
154
171
  if (h + 1 < length && md.codePointAt(h) === 13 && md.codePointAt(h + 1) === 10) {
155
172
  h += 2;
@@ -158,6 +175,7 @@ class MarkdownResolver {
158
175
  } else {
159
176
  return -1;
160
177
  }
178
+
161
179
  n += 1;
162
180
  } else if (h < length && md.codePointAt(h) === code) {
163
181
  h += 1;
@@ -166,6 +184,7 @@ class MarkdownResolver {
166
184
  return -1;
167
185
  }
168
186
  }
187
+
169
188
  return h <= bound ? h : -1;
170
189
  }
171
190
 
@@ -175,19 +194,25 @@ class MarkdownResolver {
175
194
  const lineEnd = nl === -1 ? itemEnd : Math.min(nl, itemEnd);
176
195
  const firstLine = this.markdown.slice(itemStart, lineEnd);
177
196
  const match = LIST_MARKER.exec(firstLine);
197
+
178
198
  if (!match) {
179
199
  return { primary: this.index.span(itemStart, itemStart, false) };
180
200
  }
201
+
181
202
  const markerStart = itemStart + (match.groups?.indent ?? "").length;
182
203
  let spanEnd = itemStart + match[0].length;
204
+
183
205
  while (spanEnd > markerStart) {
184
206
  const code = this.markdown.codePointAt(spanEnd - 1);
207
+
185
208
  // Continue while the character is a space or tab.
186
209
  if (code !== 32 && code !== 9) {
187
210
  break;
188
211
  }
212
+
189
213
  spanEnd -= 1;
190
214
  }
215
+
191
216
  return { primary: this.index.span(markerStart, spanEnd, false) };
192
217
  }
193
218
  }
@@ -215,8 +240,10 @@ const flattenList = function flattenList(
215
240
 
216
241
  let itemStart: number | null = null;
217
242
  let itemEnd = bound;
243
+
218
244
  if (res) {
219
245
  const loc = res.locate(item.raw, bound);
246
+
220
247
  if (loc) {
221
248
  itemStart = loc.start;
222
249
  itemEnd = loc.end;
@@ -276,6 +303,7 @@ const flattenListItem = function flattenListItem(
276
303
  if (!bulletUsed) {
277
304
  emitBulletMarker();
278
305
  }
306
+
279
307
  // SAFETY: Marked creates a List token for the adjacent token.type branch.
280
308
  // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Marked's broad Token fallback prevents discriminator narrowing
281
309
  flattenList(token as Tokens.List, indent + bullet.length, out, res, itemEnd);
@@ -284,6 +312,7 @@ const flattenListItem = function flattenListItem(
284
312
  if (!bulletUsed) {
285
313
  emitBulletMarker();
286
314
  }
315
+
287
316
  out.push({
288
317
  indent: indent + bullet.length,
289
318
  source: res ? res.resolveRaw(token.raw ?? "", itemEnd) : null,
@@ -309,6 +338,7 @@ const flattenWalk = function flattenWalk(
309
338
  if (token.type === "space") {
310
339
  continue;
311
340
  }
341
+
312
342
  if (token.type === "list") {
313
343
  // SAFETY: Marked creates a List token for the adjacent token.type branch.
314
344
  // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Marked's broad Token fallback prevents discriminator narrowing
@@ -337,5 +367,6 @@ export const flattenMarkdown = function flattenMarkdown(
337
367
  const res = new MarkdownResolver(markdown, options?.sourceId);
338
368
  const out: FlatBlock[] = [];
339
369
  flattenWalk(marked.lexer(markdown), 0, out, res, markdown.length);
370
+
340
371
  return out.filter((block) => block.token.type !== "html");
341
372
  };
@@ -3,7 +3,9 @@ import path from "node:path";
3
3
  import type { Token, Tokens } from "marked";
4
4
 
5
5
  const OBSIDIAN_IMAGE_EMBED = /!\[\[(?<target>[^\]|]+)(?:\|(?<display>[^\]]+))?\]\]/gu;
6
+
6
7
  const IMAGE_DIMENSIONS = /^(?<width>\d+)(?:x(?<height>\d+))?$/u;
8
+
7
9
  const URL_SCHEME = /^[a-z][a-z\d+.-]*:/iu;
8
10
 
9
11
  export interface MarkdownImageEmbed {
@@ -23,6 +25,7 @@ const obsidianEmbed = function obsidianEmbed(
23
25
  ): MarkdownImageEmbed {
24
26
  const source = target.trim();
25
27
  const dimensions = display?.trim().match(IMAGE_DIMENSIONS);
28
+
26
29
  if (dimensions?.groups?.width !== undefined) {
27
30
  return {
28
31
  height: dimensions.groups.height === undefined ? undefined : Number(dimensions.groups.height),
@@ -30,7 +33,9 @@ const obsidianEmbed = function obsidianEmbed(
30
33
  width: Number(dimensions.groups.width),
31
34
  };
32
35
  }
36
+
33
37
  const alt = display?.trim();
38
+
34
39
  return { alt: alt === undefined || alt === "" ? undefined : alt, source };
35
40
  };
36
41
 
@@ -39,17 +44,21 @@ export const parseObsidianImageEmbed = function parseObsidianImageEmbed(
39
44
  value: string
40
45
  ): MarkdownImageEmbed | null {
41
46
  const match = /^!\[\[(?<target>[^\]|]+)(?:\|(?<display>[^\]]+))?\]\]$/u.exec(value.trim());
47
+
42
48
  if (match?.groups?.target === undefined) {
43
49
  return null;
44
50
  }
51
+
45
52
  return obsidianEmbed(match.groups.target, match.groups.display);
46
53
  };
47
54
 
48
55
  const splitTextToken = function splitTextToken(text: string): MarkdownInlineSegment[] {
49
56
  const segments: MarkdownInlineSegment[] = [];
50
57
  let cursor = 0;
58
+
51
59
  for (const match of text.matchAll(OBSIDIAN_IMAGE_EMBED)) {
52
60
  const { index } = match;
61
+
53
62
  if (index > cursor) {
54
63
  segments.push({
55
64
  tokens: [
@@ -62,18 +71,23 @@ const splitTextToken = function splitTextToken(text: string): MarkdownInlineSegm
62
71
  type: "text",
63
72
  });
64
73
  }
74
+
65
75
  const target = match.groups?.target;
76
+
66
77
  if (target !== undefined) {
67
78
  segments.push({ ...obsidianEmbed(target, match.groups?.display), type: "image" });
68
79
  }
80
+
69
81
  cursor = index + match[0].length;
70
82
  }
83
+
71
84
  if (cursor < text.length) {
72
85
  segments.push({
73
86
  tokens: [{ raw: text.slice(cursor), text: text.slice(cursor), type: "text" }],
74
87
  type: "text",
75
88
  });
76
89
  }
90
+
77
91
  return segments.length > 0
78
92
  ? segments
79
93
  : [{ tokens: [{ raw: text, text, type: "text" }], type: "text" }];
@@ -106,11 +120,13 @@ export const splitMarkdownImages = function splitMarkdownImages(
106
120
  });
107
121
  continue;
108
122
  }
123
+
109
124
  if (token.type === "text") {
110
125
  // SAFETY: Marked creates a Text token for the adjacent token.type branch.
111
126
  // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Marked's broad Token fallback prevents discriminator narrowing
112
127
  const textToken = token as Tokens.Text;
113
128
  const parts = splitTextToken(textToken.text);
129
+
114
130
  for (const part of parts) {
115
131
  if (part.type === "text") {
116
132
  pendingText.push(...part.tokens);
@@ -119,11 +135,15 @@ export const splitMarkdownImages = function splitMarkdownImages(
119
135
  result.push(part);
120
136
  }
121
137
  }
138
+
122
139
  continue;
123
140
  }
141
+
124
142
  pendingText.push(token);
125
143
  }
144
+
126
145
  flushText();
146
+
127
147
  return result;
128
148
  };
129
149
 
@@ -135,5 +155,6 @@ export const resolveMarkdownImageSource = function resolveMarkdownImageSource(
135
155
  if (path.isAbsolute(source) || URL_SCHEME.test(source)) {
136
156
  return source;
137
157
  }
158
+
138
159
  return path.resolve(basePath ?? process.cwd(), source);
139
160
  };
@@ -20,6 +20,7 @@ import "./row-document.js";
20
20
  import "./text-table.js";
21
21
 
22
22
  export { inlineLinkAtPosition } from "./markdown/links.js";
23
+
23
24
  export type { InlineLinkPosition, MarkdownLinkHandler } from "./markdown/links.js";
24
25
 
25
26
  type CodeBlockRendererRegistry = Record<string, CodeBlockRenderer>;
@@ -65,6 +66,11 @@ interface MarkdownViewProps {
65
66
  onLinkActivate?: MarkdownLinkHandler;
66
67
  /** Directory used to resolve relative standard Markdown and Obsidian image embeds. */
67
68
  imageBasePath?: string;
69
+ /**
70
+ * Columns the view may use, when it shares the terminal width with a side
71
+ * panel. Defaults to the terminal width.
72
+ */
73
+ width?: number;
68
74
  }
69
75
 
70
76
  /** Columns held back from the measured width for the scrollbar and right edge. */
@@ -81,10 +87,12 @@ export const MarkdownView = function MarkdownView({
81
87
  codeBlockRenderers,
82
88
  onLinkActivate,
83
89
  imageBasePath,
90
+ width,
84
91
  }: MarkdownViewProps): ReactNode {
85
92
  const { theme, syntax } = useTheme();
86
93
  const palette = useGutterPalette();
87
94
  const { width: terminalWidth } = useTerminalDimensions();
95
+
88
96
  const blocks = useMemo(
89
97
  () => providedBlocks ?? flattenMarkdown(content),
90
98
  [providedBlocks, content]
@@ -92,7 +100,7 @@ export const MarkdownView = function MarkdownView({
92
100
 
93
101
  const contentWidth = Math.max(
94
102
  1,
95
- terminalWidth -
103
+ (width ?? terminalWidth) -
96
104
  computeRowDocumentGutterWidth({
97
105
  rowCount: blocks.length,
98
106
  rowNumbers,
@@ -104,9 +112,11 @@ export const MarkdownView = function MarkdownView({
104
112
 
105
113
  const mergedCodeBlockRenderers = useMemo(() => {
106
114
  const entries = new Map(Object.entries(DEFAULT_CODE_BLOCK_RENDERERS));
115
+
107
116
  for (const [key, renderer] of Object.entries(codeBlockRenderers ?? {})) {
108
117
  entries.set(key.trim().toLowerCase(), renderer);
109
118
  }
119
+
110
120
  return Object.fromEntries(entries);
111
121
  }, [codeBlockRenderers]);
112
122
 
package/src/mermaid.ts CHANGED
@@ -34,8 +34,11 @@ export interface AnsiStyledText {
34
34
  // an edge cannot be routed. Keep synchronous work within a conservative budget;
35
35
  // MarkdownView will visibly fall back to the original Mermaid source instead.
36
36
  const MAX_SOURCE_LENGTH = 20_000;
37
+
37
38
  const MAX_SOURCE_LINES = 300;
39
+
38
40
  const MAX_FLOWCHART_EDGES = 32;
41
+
39
42
  const MIN_UNSAFE_CYCLIC_FAN_DEGREE = 3;
40
43
 
41
44
  // oxlint-disable-next-line no-control-regex -- ANSI SGR sequences start with the ESC control character
@@ -59,12 +62,15 @@ const hasDirectedPath = function hasDirectedPath(
59
62
 
60
63
  while (pending.length > 0) {
61
64
  const node = pending.pop();
65
+
62
66
  if (node === undefined) {
63
67
  continue;
64
68
  }
69
+
65
70
  if (node === target) {
66
71
  return true;
67
72
  }
73
+
68
74
  if (visited.has(node)) {
69
75
  continue;
70
76
  }
@@ -91,12 +97,17 @@ const hasUnsafeCyclicFanTopology = function hasUnsafeCyclicFanTopology(
91
97
  outgoingDegree.set(edge.source, (outgoingDegree.get(edge.source) ?? 0) + 1);
92
98
  }
93
99
 
94
- const fanInNodes = [...incomingDegree]
100
+ const fanInNodes = incomingDegree
101
+ .entries()
95
102
  .filter(([, degree]) => degree >= MIN_UNSAFE_CYCLIC_FAN_DEGREE)
96
- .map(([node]) => node);
97
- const fanOutNodes = [...outgoingDegree]
103
+ .map(([node]) => node)
104
+ .toArray();
105
+
106
+ const fanOutNodes = outgoingDegree
107
+ .entries()
98
108
  .filter(([, degree]) => degree >= MIN_UNSAFE_CYCLIC_FAN_DEGREE)
99
- .map(([node]) => node);
109
+ .map(([node]) => node)
110
+ .toArray();
100
111
 
101
112
  return fanInNodes.some((fanIn) =>
102
113
  fanOutNodes.some(
@@ -121,6 +132,7 @@ const exceedsSynchronousRenderBudget = function exceedsSynchronousRenderBudget(
121
132
  }
122
133
 
123
134
  const { edges } = parseMermaid(source);
135
+
124
136
  return edges.length > MAX_FLOWCHART_EDGES || hasUnsafeCyclicFanTopology(edges);
125
137
  };
126
138
 
@@ -134,9 +146,11 @@ const appendStyledChunk = function appendStyledChunk(
134
146
  }
135
147
 
136
148
  const chunk: TextChunk = { __isChunk: true, text };
149
+
137
150
  if (fg !== undefined && fg !== "") {
138
151
  chunk.fg = parseColor(fg);
139
152
  }
153
+
140
154
  chunks.push(chunk);
141
155
  };
142
156
 
@@ -144,6 +158,7 @@ const sgrParams = function sgrParams(rawParams: string): number[] {
144
158
  if (rawParams === "") {
145
159
  return [0];
146
160
  }
161
+
147
162
  return rawParams.split(";").map((param) => (param === "" ? 0 : Number(param)));
148
163
  };
149
164
 
@@ -232,10 +247,12 @@ export const renderMermaidForTerminal = function renderMermaidForTerminal(
232
247
  }
233
248
 
234
249
  const mode = options.mode ?? "plain";
250
+
235
251
  const rendered = renderMermaidASCII(source, {
236
252
  colorMode: mode === "ansi" ? "truecolor" : "none",
237
253
  theme: options.theme,
238
254
  }).trimEnd();
255
+
239
256
  const { text, content } = ansiToStyledText(rendered);
240
257
 
241
258
  if (text.trim().length === 0) {
package/src/parsers.ts CHANGED
@@ -29,6 +29,7 @@ const jsonEntryKeys = function jsonEntryKeys(value: JsonValue): string[] {
29
29
  if (value === null) {
30
30
  throw new TypeError("A JSON table row cannot be null");
31
31
  }
32
+
32
33
  return Object.keys(value);
33
34
  };
34
35
 
@@ -36,12 +37,15 @@ const readJsonEntry = function readJsonEntry(value: JsonValue, key: string): Jso
36
37
  if (isJsonArray(value)) {
37
38
  return value[Number(key)];
38
39
  }
40
+
39
41
  if (value instanceof Object) {
40
42
  return value[key];
41
43
  }
44
+
42
45
  if (Object.prototype.toString.call(value) === "[object String]") {
43
46
  return String.prototype.charAt.call(value, Number(key));
44
47
  }
48
+
45
49
  return undefined;
46
50
  };
47
51
 
@@ -51,6 +55,7 @@ const splitLines = function splitLines(input: string): string[] {
51
55
 
52
56
  const createColumnDefs = function createColumnDefs(rawHeaders: string[]): ColumnDef[] {
53
57
  const seen = new Map<string, number>();
58
+
54
59
  return rawHeaders.map((header, index) => {
55
60
  const trimmed = header.trim();
56
61
  const fallback = `column_${index + 1}`;
@@ -58,6 +63,7 @@ const createColumnDefs = function createColumnDefs(rawHeaders: string[]): Column
58
63
  const count = seen.get(base) ?? 0;
59
64
  seen.set(base, count + 1);
60
65
  const key = count === 0 ? base : `${base}_${count + 1}`;
66
+
61
67
  return {
62
68
  header: trimmed || undefined,
63
69
  key,
@@ -68,9 +74,11 @@ const createColumnDefs = function createColumnDefs(rawHeaders: string[]): Column
68
74
  const buildRows = function buildRows(columns: ColumnDef[], rawRows: string[][]): TableRow[] {
69
75
  return rawRows.map((row) => {
70
76
  const record: TableRow = {};
77
+
71
78
  for (const [index, column] of columns.entries()) {
72
79
  record[column.key] = row[index] ?? "";
73
80
  }
81
+
74
82
  return record;
75
83
  });
76
84
  };
@@ -78,11 +86,13 @@ const buildRows = function buildRows(columns: ColumnDef[], rawRows: string[][]):
78
86
  const parseCSVLine = function parseCSVLine(line: string): string[] {
79
87
  const fields: string[] = [];
80
88
  let i = 0;
89
+
81
90
  while (i < line.length) {
82
91
  if (line[i] === '"') {
83
92
  // Quoted field
84
93
  i += 1;
85
94
  let field = "";
95
+
86
96
  while (i < line.length) {
87
97
  if (line[i] === '"') {
88
98
  if (i + 1 < line.length && line[i + 1] === '"') {
@@ -97,13 +107,16 @@ const parseCSVLine = function parseCSVLine(line: string): string[] {
97
107
  i += 1;
98
108
  }
99
109
  }
110
+
100
111
  fields.push(field);
112
+
101
113
  // Skip the comma after a quoted field.
102
114
  if (i < line.length && line[i] === ",") {
103
115
  i += 1;
104
116
  }
105
117
  } else {
106
118
  const nextComma = line.indexOf(",", i);
119
+
107
120
  if (nextComma === -1) {
108
121
  fields.push(line.slice(i));
109
122
  break;
@@ -113,46 +126,60 @@ const parseCSVLine = function parseCSVLine(line: string): string[] {
113
126
  }
114
127
  }
115
128
  }
129
+
116
130
  return fields;
117
131
  };
118
132
 
119
133
  export const parseCSV = function parseCSV(input: string): TableData {
120
134
  const lines = splitLines(input);
135
+
121
136
  if (lines.length === 0) {
122
137
  return { columns: [], rows: [] };
123
138
  }
139
+
124
140
  const columns = createColumnDefs(parseCSVLine(lines[0]));
125
141
  const rows = buildRows(columns, lines.slice(1).map(parseCSVLine));
142
+
126
143
  return { columns, rows };
127
144
  };
128
145
 
129
146
  export const parseTSV = function parseTSV(input: string): TableData {
130
147
  const lines = splitLines(input);
148
+
131
149
  if (lines.length === 0) {
132
150
  return { columns: [], rows: [] };
133
151
  }
152
+
134
153
  const columns = createColumnDefs(lines[0].split("\t"));
154
+
135
155
  const rows = buildRows(
136
156
  columns,
137
157
  lines.slice(1).map((line) => line.split("\t"))
138
158
  );
159
+
139
160
  return { columns, rows };
140
161
  };
141
162
 
142
163
  export const parseJSON = function parseJSON(input: string): TableData {
143
164
  const data = parseJsonDocument(input);
165
+
144
166
  if (!isJsonArray(data) || data.length === 0) {
145
167
  return { columns: [], rows: [] };
146
168
  }
169
+
147
170
  const keys = [...new Set(data.flatMap(jsonEntryKeys))];
148
171
  const columns: ColumnDef[] = keys.map((key) => ({ header: key, key }));
172
+
149
173
  const rows = data.map((item) => {
150
174
  const row: TableRow = {};
175
+
151
176
  for (const column of columns) {
152
177
  row[column.key] = readJsonEntry(item, column.key) ?? "";
153
178
  }
179
+
154
180
  return row;
155
181
  });
182
+
156
183
  return { columns, rows };
157
184
  };
158
185
 
@@ -160,9 +187,11 @@ export type Format = "csv" | "tsv" | "json" | "unknown";
160
187
 
161
188
  export const detectFormat = function detectFormat(input: string): Format {
162
189
  const trimmed = input.trimStart();
190
+
163
191
  if (trimmed.startsWith("[")) {
164
192
  try {
165
193
  const parsed = parseJsonDocument(trimmed);
194
+
166
195
  if (isJsonArray(parsed)) {
167
196
  return "json";
168
197
  }
@@ -170,13 +199,17 @@ export const detectFormat = function detectFormat(input: string): Format {
170
199
  // Not valid JSON — fall through to the delimiter sniffing below.
171
200
  }
172
201
  }
202
+
173
203
  const firstLine = input.split("\n")[0] ?? "";
204
+
174
205
  if (firstLine.includes("\t")) {
175
206
  return "tsv";
176
207
  }
208
+
177
209
  if (firstLine.includes(",")) {
178
210
  return "csv";
179
211
  }
212
+
180
213
  return "unknown";
181
214
  };
182
215
 
@@ -184,28 +217,34 @@ export const parseAuto = function parseAuto(input: string): ParsedTable {
184
217
  const format = detectFormat(input);
185
218
  let columns: ColumnDef[];
186
219
  let rows: TableRow[];
220
+
187
221
  switch (format) {
188
222
  case "csv": {
189
223
  ({ columns, rows } = parseCSV(input));
190
224
  break;
191
225
  }
226
+
192
227
  case "tsv": {
193
228
  ({ columns, rows } = parseTSV(input));
194
229
  break;
195
230
  }
231
+
196
232
  case "json": {
197
233
  ({ columns, rows } = parseJSON(input));
198
234
  break;
199
235
  }
236
+
200
237
  case "unknown": {
201
238
  // Fall back to CSV
202
239
  ({ columns, rows } = parseCSV(input));
203
240
  break;
204
241
  }
242
+
205
243
  default: {
206
244
  ({ columns, rows } = parseCSV(input));
207
245
  break;
208
246
  }
209
247
  }
248
+
210
249
  return { columns, format, rows };
211
250
  };