@tooee/renderers 0.13.0 → 0.14.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 (62) hide show
  1. package/dist/index.d.ts +1 -1
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js.map +1 -1
  4. package/dist/markdown/blocks/flat-block.d.ts.map +1 -1
  5. package/dist/markdown/blocks/flat-block.js +38 -33
  6. package/dist/markdown/blocks/flat-block.js.map +1 -1
  7. package/dist/markdown/blocks/list-line.d.ts +2 -2
  8. package/dist/markdown/blocks/list-line.d.ts.map +1 -1
  9. package/dist/markdown/blocks/list-line.js +2 -3
  10. package/dist/markdown/blocks/list-line.js.map +1 -1
  11. package/dist/markdown/blocks/table.d.ts +17 -3
  12. package/dist/markdown/blocks/table.d.ts.map +1 -1
  13. package/dist/markdown/blocks/table.js +29 -29
  14. package/dist/markdown/blocks/table.js.map +1 -1
  15. package/dist/markdown/links.d.ts +10 -0
  16. package/dist/markdown/links.d.ts.map +1 -1
  17. package/dist/markdown/links.js +30 -18
  18. package/dist/markdown/links.js.map +1 -1
  19. package/dist/markdown/table-layout.d.ts +28 -0
  20. package/dist/markdown/table-layout.d.ts.map +1 -0
  21. package/dist/markdown/table-layout.js +100 -0
  22. package/dist/markdown/table-layout.js.map +1 -0
  23. package/dist/markdown/table-links.d.ts +5 -4
  24. package/dist/markdown/table-links.d.ts.map +1 -1
  25. package/dist/markdown/table-links.js +6 -23
  26. package/dist/markdown/table-links.js.map +1 -1
  27. package/dist/markdown/tokens.d.ts +2 -0
  28. package/dist/markdown/tokens.d.ts.map +1 -1
  29. package/dist/markdown/tokens.js.map +1 -1
  30. package/dist/markdown-blocks.d.ts +72 -14
  31. package/dist/markdown-blocks.d.ts.map +1 -1
  32. package/dist/markdown-blocks.js +137 -77
  33. package/dist/markdown-blocks.js.map +1 -1
  34. package/dist/markdown-images.d.ts.map +1 -1
  35. package/dist/markdown-images.js +5 -8
  36. package/dist/markdown-images.js.map +1 -1
  37. package/dist/markdown-view.d.ts +0 -1
  38. package/dist/markdown-view.d.ts.map +1 -1
  39. package/dist/markdown-view.js +0 -1
  40. package/dist/markdown-view.js.map +1 -1
  41. package/package.json +6 -6
  42. package/src/index.ts +14 -1
  43. package/src/markdown/blocks/flat-block.tsx +115 -95
  44. package/src/markdown/blocks/list-line.tsx +4 -7
  45. package/src/markdown/blocks/table.tsx +81 -53
  46. package/src/markdown/links.ts +47 -29
  47. package/src/markdown/table-layout.ts +156 -0
  48. package/src/markdown/table-links.ts +11 -31
  49. package/src/markdown/tokens.ts +2 -0
  50. package/src/markdown-blocks.ts +267 -100
  51. package/src/markdown-images.ts +9 -9
  52. package/src/markdown-view.tsx +0 -1
  53. package/dist/text-table-internals.d.ts +0 -34
  54. package/dist/text-table-internals.d.ts.map +0 -1
  55. package/dist/text-table-internals.js +0 -68
  56. package/dist/text-table-internals.js.map +0 -1
  57. package/dist/text-table.d.ts +0 -7
  58. package/dist/text-table.d.ts.map +0 -1
  59. package/dist/text-table.js +0 -4
  60. package/dist/text-table.js.map +0 -1
  61. package/src/text-table-internals.ts +0 -136
  62. package/src/text-table.ts +0 -10
@@ -0,0 +1,156 @@
1
+ import { bold as boldChunk } from "@opentui/core";
2
+ import type { TextChunk } from "@opentui/core";
3
+ import type { ResolvedTheme } from "@tooee/themes";
4
+ import type { Tokens } from "marked";
5
+
6
+ import { inlineTokensToChunks } from "./chunks.js";
7
+ import { getPlainText } from "./plain-text.js";
8
+
9
+ /** Border columns around a table row: one before each cell and one after the last. */
10
+ export const tableBorderColumns = function tableBorderColumns(columnCount: number): number {
11
+ return columnCount + 1;
12
+ };
13
+
14
+ /**
15
+ * Styled chunks for one table cell. Header cells are bold. A cell with no
16
+ * inline chunks falls back to its plain text.
17
+ */
18
+ export const tableCellChunks = function tableCellChunks(
19
+ cell: Tokens.TableCell,
20
+ theme: ResolvedTheme,
21
+ header: boolean
22
+ ): TextChunk[] {
23
+ const chunks = inlineTokensToChunks(cell.tokens, theme);
24
+
25
+ if (header) {
26
+ return chunks.length > 0
27
+ ? chunks.map((item) => boldChunk(item))
28
+ : [boldChunk(getPlainText(cell.tokens).trim())];
29
+ }
30
+
31
+ return chunks.length > 0 ? chunks : [{ __isChunk: true, text: getPlainText(cell.tokens) }];
32
+ };
33
+
34
+ /** Cells of row `index` of a table. Row `0` is the header. */
35
+ export const tableRowCells = function tableRowCells(
36
+ table: Tokens.Table,
37
+ index: number
38
+ ): readonly Tokens.TableCell[] {
39
+ return index === 0 ? table.header : (table.rows[index - 1] ?? []);
40
+ };
41
+
42
+ /** Display width of the widest line of a cell's chunks. Never less than 1. */
43
+ export const chunksDisplayWidth = function chunksDisplayWidth(
44
+ chunks: readonly TextChunk[]
45
+ ): number {
46
+ const lines = chunks
47
+ .map((item) => item.text)
48
+ .join("")
49
+ .split("\n");
50
+
51
+ return Math.max(1, ...lines.map((line) => Bun.stringWidth(line)));
52
+ };
53
+
54
+ /**
55
+ * Fit natural column widths into `available` cells. When they do not fit,
56
+ * narrow columns keep their width and the widest columns share what is left,
57
+ * so the widest ones wrap first. Every column keeps at least one cell.
58
+ */
59
+ export const fitTableColumnWidths = function fitTableColumnWidths(
60
+ natural: readonly number[],
61
+ available: number
62
+ ): number[] {
63
+ const total = natural.reduce((sum, width) => sum + width, 0);
64
+
65
+ if (total <= available) {
66
+ return [...natural];
67
+ }
68
+
69
+ const budget = Math.max(available, natural.length);
70
+ const ascending = natural.toSorted((a, b) => a - b);
71
+ let remaining = budget;
72
+ let cap = 1;
73
+
74
+ for (const [position, width] of ascending.entries()) {
75
+ const share = Math.floor(remaining / (ascending.length - position));
76
+
77
+ if (width > share) {
78
+ cap = Math.max(1, share);
79
+ break;
80
+ }
81
+
82
+ remaining -= width;
83
+ }
84
+
85
+ const widths = natural.map((width) => Math.min(width, cap));
86
+ let spare = budget - widths.reduce((sum, width) => sum + width, 0);
87
+
88
+ for (const [column, width] of natural.entries()) {
89
+ if (spare <= 0) {
90
+ break;
91
+ }
92
+
93
+ if (width > cap) {
94
+ widths[column] = cap + 1;
95
+ spare -= 1;
96
+ }
97
+ }
98
+
99
+ return widths;
100
+ };
101
+
102
+ interface CachedWidths {
103
+ available: number;
104
+ widths: number[];
105
+ }
106
+
107
+ /**
108
+ * Column widths per table token. Every row of a table renders on its own, so
109
+ * the cache makes all rows share one result and measures each cell once.
110
+ */
111
+ const widthCache = new WeakMap<Tokens.Table, CachedWidths>();
112
+
113
+ /**
114
+ * Column widths, without borders, for every row of `table`. The widths depend
115
+ * only on the cell text and `available`, so theme changes reuse the cache.
116
+ */
117
+ export const tableColumnWidths = function tableColumnWidths(
118
+ table: Tokens.Table,
119
+ available: number,
120
+ theme: ResolvedTheme
121
+ ): number[] {
122
+ const cached = widthCache.get(table);
123
+
124
+ if (cached?.available === available) {
125
+ return cached.widths;
126
+ }
127
+
128
+ const natural = table.header.map((_cell, column) => {
129
+ let widest = 1;
130
+
131
+ for (let index = 0; index <= table.rows.length; index += 1) {
132
+ const cell = tableRowCells(table, index)[column];
133
+
134
+ if (cell !== undefined) {
135
+ widest = Math.max(widest, chunksDisplayWidth(tableCellChunks(cell, theme, index === 0)));
136
+ }
137
+ }
138
+
139
+ return widest;
140
+ });
141
+
142
+ const widths = fitTableColumnWidths(natural, available);
143
+ widthCache.set(table, { available, widths });
144
+
145
+ return widths;
146
+ };
147
+
148
+ /** A horizontal border line such as `┌──┬──┐` for the given column widths. */
149
+ export const tableBorderLine = function tableBorderLine(
150
+ widths: readonly number[],
151
+ left: string,
152
+ middle: string,
153
+ right: string
154
+ ): string {
155
+ return left + widths.map((width) => "─".repeat(width)).join(middle) + right;
156
+ };
@@ -1,6 +1,6 @@
1
- import type { MouseEvent, TextChunk, TextTableContent } from "@opentui/core";
1
+ import type { MouseEvent, TextChunk } from "@opentui/core";
2
2
 
3
- import { textTableCellAt } from "../text-table-internals.js";
3
+ import { positionLinkMouseHandler } from "./links.js";
4
4
  import type { MarkdownLinkHandler } from "./links.js";
5
5
 
6
6
  /** The OSC 8 link URL of the chunk at a text position in one table cell. */
@@ -35,36 +35,16 @@ export const chunkLinkAt = function chunkLinkAt(
35
35
  };
36
36
 
37
37
  /**
38
- * Primary-click handler for a Markdown table. It activates the link under the pointer and
39
- * consumes the event only when the host handler returns literal true.
38
+ * Primary-click handler for one Markdown table cell. It activates the link
39
+ * under the pointer and consumes the event only when the host handler returns
40
+ * literal true.
40
41
  */
41
- export const tableLinkMouseHandler = function tableLinkMouseHandler(
42
- content: TextTableContent,
42
+ export const tableCellLinkMouseHandler = function tableCellLinkMouseHandler(
43
+ chunks: readonly TextChunk[],
43
44
  onLinkActivate?: MarkdownLinkHandler
44
45
  ): ((event: MouseEvent) => void) | undefined {
45
- if (onLinkActivate === undefined) {
46
- return undefined;
47
- }
48
-
49
- return (event: MouseEvent): void => {
50
- if (event.button !== 0 || event.target === null) {
51
- return;
52
- }
53
-
54
- const hit = textTableCellAt(event.target, event.x, event.y);
55
- const chunks = hit === null ? null : content[hit.row]?.[hit.column];
56
-
57
- if (hit === null || chunks === null || chunks === undefined) {
58
- return;
59
- }
60
-
61
- const href = chunkLinkAt(chunks, hit.line, hit.offset);
62
-
63
- if (href === null || onLinkActivate(href) !== true) {
64
- return;
65
- }
66
-
67
- event.preventDefault();
68
- event.stopPropagation();
69
- };
46
+ return positionLinkMouseHandler(
47
+ (position) => chunkLinkAt(chunks, position.line, position.column),
48
+ onLinkActivate
49
+ );
70
50
  };
@@ -9,8 +9,10 @@ interface KnownTokenByType {
9
9
  em: Tokens.Em;
10
10
  escape: Tokens.Escape;
11
11
  heading: Tokens.Heading;
12
+ hr: Tokens.Hr;
12
13
  image: Tokens.Image;
13
14
  link: Tokens.Link;
15
+ list: Tokens.List;
14
16
  paragraph: Tokens.Paragraph;
15
17
  space: Tokens.Space;
16
18
  strong: Tokens.Strong;
@@ -1,6 +1,7 @@
1
1
  import { marked } from "marked";
2
2
  import type { Token, Tokens } from "marked";
3
3
 
4
+ import { narrowToken } from "./markdown/tokens.js";
4
5
  import { SourceIndex } from "./source.js";
5
6
  import type { DocumentRowSource } from "./source.js";
6
7
 
@@ -13,19 +14,94 @@ const LIST_MARKER = /^(?<indent>\s*)(?:[-*+]|\d+[.)])[ \t]*(?:\[[ xX]\])?/u;
13
14
  // Flat block model
14
15
  // ---------------------------------------------------------------------------
15
16
 
17
+ /** Fields that every flattened block has, whatever its kind. */
18
+ interface FlatBlockBase {
19
+ /** Columns of nesting, such as the bullet width of each parent list item. */
20
+ indent: number;
21
+ /** Provenance in the Markdown input; `null` only if resolution genuinely failed. */
22
+ source: DocumentRowSource | null;
23
+ }
24
+
25
+ export interface FlatHeadingBlock extends FlatBlockBase {
26
+ kind: "heading";
27
+ token: Tokens.Heading;
28
+ }
29
+
30
+ export interface FlatParagraphBlock extends FlatBlockBase {
31
+ kind: "paragraph";
32
+ token: Tokens.Paragraph;
33
+ }
34
+
35
+ export interface FlatCodeBlock extends FlatBlockBase {
36
+ kind: "code";
37
+ token: Tokens.Code;
38
+ }
39
+
40
+ export interface FlatBlockquoteBlock extends FlatBlockBase {
41
+ kind: "blockquote";
42
+ token: Tokens.Blockquote;
43
+ }
44
+
45
+ export interface FlatRuleBlock extends FlatBlockBase {
46
+ kind: "hr";
47
+ token: Tokens.Hr;
48
+ }
49
+
50
+ /**
51
+ * The first line of a list item: the bullet, an optional checkbox and the
52
+ * item's first inline content. An item that starts with block content, or
53
+ * has no content, gets an empty `text` token.
54
+ */
55
+ export interface FlatListLineBlock extends FlatBlockBase {
56
+ kind: "list-line";
57
+ token: Tokens.Text | Tokens.Paragraph;
58
+ bullet: string;
59
+ /** Set on task-list items only. */
60
+ checked?: boolean;
61
+ }
62
+
63
+ /** One header or body row of a Markdown table. A table is one block per row. */
64
+ export interface FlatTableRowBlock extends FlatBlockBase {
65
+ kind: "table-row";
66
+ row: FlatTableRow;
67
+ }
68
+
69
+ /** Any other block token, such as a `text` token inside a list item. */
70
+ export interface FlatOtherBlock extends FlatBlockBase {
71
+ kind: "other";
72
+ token: Token;
73
+ }
74
+
16
75
  /**
17
76
  * A flattened block — all blocks exist at the top level with an indent.
18
77
  * Nested structures (lists containing code blocks, etc.) are flattened into
19
- * sibling blocks with appropriate indentation.
78
+ * sibling blocks with appropriate indentation. `kind` tells readers which
79
+ * fields the block has, so they do not need to inspect the Marked token.
20
80
  */
21
- export interface FlatBlock {
22
- token: Token;
23
- indent: number;
24
- bullet?: string;
25
- checked?: boolean;
81
+ export type FlatBlock =
82
+ | FlatHeadingBlock
83
+ | FlatParagraphBlock
84
+ | FlatCodeBlock
85
+ | FlatBlockquoteBlock
86
+ | FlatRuleBlock
87
+ | FlatListLineBlock
88
+ | FlatTableRowBlock
89
+ | FlatOtherBlock;
90
+
91
+ export type FlatBlockKind = FlatBlock["kind"];
26
92
 
27
- /** Provenance in the Markdown input; `null` only if resolution genuinely failed. */
28
- source: DocumentRowSource | null;
93
+ /**
94
+ * One row of a Markdown table. The delimiter line (`| --- |`) is not a row.
95
+ * Rows of the same table share `table`, so a renderer can give every row the
96
+ * same column widths.
97
+ */
98
+ export interface FlatTableRow {
99
+ /** The parent table token, the same object for every row of the table. */
100
+ table: Tokens.Table;
101
+ /** `0` is the header row. Body rows start at `1`. */
102
+ index: number;
103
+ /** This row's Markdown line, without indent or line ending. */
104
+ raw: string;
29
105
  }
30
106
 
31
107
  export interface FlattenMarkdownOptions {
@@ -33,7 +109,7 @@ export interface FlattenMarkdownOptions {
33
109
  }
34
110
 
35
111
  /** Empty synthetic token stamped onto bullet-only rows (nested-list/block/empty items). */
36
- const syntheticTextToken = function syntheticTextToken(): Token {
112
+ const syntheticTextToken = function syntheticTextToken(): Tokens.Text {
37
113
  return { raw: "", text: "", tokens: [], type: "text" };
38
114
  };
39
115
 
@@ -50,19 +126,23 @@ export const checkboxMarker = function checkboxMarker(checked: boolean | undefin
50
126
  };
51
127
 
52
128
  /**
53
- * The visible/searchable text for a block. Non-synthetic blocks use the token's
54
- * `raw`; synthetic bullet rows (empty raw) fall back to the visible
129
+ * The visible/searchable text for a block. A table row uses its own Markdown
130
+ * line. Other non-synthetic blocks use the token's `raw`; synthetic bullet rows (empty raw) fall back to the visible
55
131
  * bullet/checkbox text, then to the resolved source text. This keeps default
56
132
  * search and copy in agreement with the source mapping on synthetic rows.
57
133
  */
58
134
  export const getFlatBlockText = function getFlatBlockText(block: FlatBlock): string {
135
+ if (block.kind === "table-row") {
136
+ return block.row.raw;
137
+ }
138
+
59
139
  const { raw } = block.token;
60
140
 
61
141
  if (raw.length > 0) {
62
142
  return raw;
63
143
  }
64
144
 
65
- if (block.bullet !== undefined) {
145
+ if (block.kind === "list-line") {
66
146
  return block.bullet + checkboxMarker(block.checked);
67
147
  }
68
148
 
@@ -227,98 +307,173 @@ const bulletFor = function bulletFor(list: Tokens.List, itemIndex: number): stri
227
307
  : "- ";
228
308
  };
229
309
 
230
- const flattenList = function flattenList(
231
- list: Tokens.List,
232
- indent: number,
233
- out: FlatBlock[],
234
- res: MarkdownResolver | null,
235
- bound: number
236
- ): void {
237
- for (let i = 0; i < list.items.length; i += 1) {
238
- const item = list.items[i];
239
- const bullet = bulletFor(list, i);
310
+ /** Where flattened blocks go, and the limits for source resolution. */
311
+ interface FlattenContext {
312
+ /** Source offset that resolution must not pass, such as the end of the parent list item. */
313
+ bound: number;
314
+ indent: number;
315
+ out: FlatBlock[];
316
+ res: MarkdownResolver | null;
317
+ }
240
318
 
241
- let itemStart: number | null = null;
242
- let itemEnd = bound;
319
+ const resolveSource = function resolveSource(
320
+ raw: string,
321
+ ctx: FlattenContext
322
+ ): DocumentRowSource | null {
323
+ return ctx.res ? ctx.res.resolveRaw(raw, ctx.bound) : null;
324
+ };
325
+
326
+ /**
327
+ * The typed block for a token that is not a list, a table or HTML. This is the
328
+ * one place that maps a Marked token type to a block `kind`.
329
+ */
330
+ const leafBlock = function leafBlock(token: Token, base: FlatBlockBase): FlatBlock {
331
+ const heading = narrowToken(token, "heading");
243
332
 
244
- if (res) {
245
- const loc = res.locate(item.raw, bound);
333
+ if (heading !== null) {
334
+ return { ...base, kind: "heading", token: heading };
335
+ }
246
336
 
247
- if (loc) {
248
- itemStart = loc.start;
249
- itemEnd = loc.end;
250
- res.cursor = loc.start;
251
- }
252
- }
337
+ const paragraph = narrowToken(token, "paragraph");
253
338
 
254
- // oxlint-disable-next-line no-use-before-define -- preserve deliberate top-down list flattening organization
255
- flattenListItem(item, indent, bullet, out, res, itemStart, itemEnd);
339
+ if (paragraph !== null) {
340
+ return { ...base, kind: "paragraph", token: paragraph };
341
+ }
256
342
 
257
- if (res && itemStart !== null) {
258
- res.cursor = itemEnd;
259
- }
343
+ const code = narrowToken(token, "code");
344
+
345
+ if (code !== null) {
346
+ return { ...base, kind: "code", token: code };
260
347
  }
348
+
349
+ const blockquote = narrowToken(token, "blockquote");
350
+
351
+ if (blockquote !== null) {
352
+ return { ...base, kind: "blockquote", token: blockquote };
353
+ }
354
+
355
+ const hr = narrowToken(token, "hr");
356
+
357
+ if (hr !== null) {
358
+ return { ...base, kind: "hr", token: hr };
359
+ }
360
+
361
+ return { ...base, kind: "other", token };
362
+ };
363
+
364
+ /**
365
+ * Emit one block per table row: the header, then each body row. Each row
366
+ * resolves its own source line, so the delimiter line between the header and
367
+ * the body stays unmapped. Lines are trimmed, because marked strips the list
368
+ * indent from a table inside a list item but the source keeps it.
369
+ */
370
+ const flattenTable = function flattenTable(table: Tokens.Table, ctx: FlattenContext): void {
371
+ const lines = table.raw
372
+ .split("\n")
373
+ .map((line) => line.trim())
374
+ .filter((line) => line.length > 0);
375
+
376
+ for (let index = 0; index <= table.rows.length; index += 1) {
377
+ // Line 1 is the delimiter, so body row `index` is on line `index + 1`.
378
+ const raw = lines[index === 0 ? 0 : index + 1] ?? "";
379
+
380
+ ctx.out.push({
381
+ indent: ctx.indent,
382
+ kind: "table-row",
383
+ row: { index, raw, table },
384
+ source: resolveSource(raw, ctx),
385
+ });
386
+ }
387
+ };
388
+
389
+ /**
390
+ * Flatten one block token at the context's indent. The top level and list
391
+ * items share this step, so lists and tables nest the same way everywhere.
392
+ * Block HTML is not rendered, so it gets no block. It is still resolved, so
393
+ * later blocks keep their sequential source anchors.
394
+ */
395
+ const flattenBlockToken = function flattenBlockToken(token: Token, ctx: FlattenContext): void {
396
+ const list = narrowToken(token, "list");
397
+
398
+ if (list !== null) {
399
+ // oxlint-disable-next-line no-use-before-define -- lists and list items recurse through this step
400
+ flattenList(list, ctx);
401
+
402
+ return;
403
+ }
404
+
405
+ const table = narrowToken(token, "table");
406
+
407
+ if (table !== null) {
408
+ flattenTable(table, ctx);
409
+
410
+ return;
411
+ }
412
+
413
+ const source = resolveSource(token.raw ?? "", ctx);
414
+
415
+ if (token.type === "html") {
416
+ return;
417
+ }
418
+
419
+ ctx.out.push(leafBlock(token, { indent: ctx.indent, source }));
261
420
  };
262
421
 
422
+ /**
423
+ * Flatten one list item. `ctx.bound` is the end of the item. `itemStart` is
424
+ * its start offset, or `null` when the item was not found in the source.
425
+ */
263
426
  const flattenListItem = function flattenListItem(
264
427
  item: Tokens.ListItem,
265
- indent: number,
266
428
  bullet: string,
267
- out: FlatBlock[],
268
- res: MarkdownResolver | null,
269
- itemStart: number | null,
270
- itemEnd: number
429
+ ctx: FlattenContext,
430
+ itemStart: number | null
271
431
  ): void {
272
432
  const checked = item.checked === null ? undefined : item.checked;
273
- const childTokens = item.tokens;
433
+ const childCtx: FlattenContext = { ...ctx, indent: ctx.indent + bullet.length };
274
434
  let bulletUsed = false;
275
435
 
276
- const emitBulletMarker = () => {
277
- out.push({
278
- bullet,
279
- checked,
280
- indent,
281
- source: res && itemStart !== null ? res.markerSource(itemStart, itemEnd) : null,
282
- token: syntheticTextToken(),
283
- });
436
+ const pushListLine = (
437
+ token: Tokens.Text | Tokens.Paragraph,
438
+ source: DocumentRowSource | null
439
+ ) => {
440
+ ctx.out.push({ bullet, checked, indent: ctx.indent, kind: "list-line", source, token });
284
441
  bulletUsed = true;
285
442
  };
286
443
 
287
- for (const token of childTokens) {
444
+ const emitBulletMarker = () => {
445
+ const source =
446
+ ctx.res && itemStart !== null ? ctx.res.markerSource(itemStart, ctx.bound) : null;
447
+
448
+ pushListLine(syntheticTextToken(), source);
449
+ };
450
+
451
+ for (const token of item.tokens) {
288
452
  if (token.type === "space" || token.type === "checkbox") {
289
453
  continue;
290
454
  }
291
455
 
292
- if (token.type === "text" || token.type === "paragraph") {
456
+ const inline = narrowToken(token, "text") ?? narrowToken(token, "paragraph");
457
+
458
+ if (inline !== null) {
293
459
  // Inline content — attach the bullet to the first one.
294
- out.push({
295
- bullet: bulletUsed ? undefined : bullet,
296
- checked: bulletUsed ? undefined : checked,
297
- indent,
298
- source: res ? res.resolveRaw(token.raw ?? "", itemEnd) : null,
299
- token,
300
- });
301
- bulletUsed = true;
302
- } else if (token.type === "list") {
303
- if (!bulletUsed) {
304
- emitBulletMarker();
305
- }
460
+ const source = resolveSource(inline.raw, ctx);
306
461
 
307
- // SAFETY: Marked creates a List token for the adjacent token.type branch.
308
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Marked's broad Token fallback prevents discriminator narrowing
309
- flattenList(token as Tokens.List, indent + bullet.length, out, res, itemEnd);
310
- } else {
311
- // Block content (code, table, blockquote, hr, etc.).
312
- if (!bulletUsed) {
313
- emitBulletMarker();
462
+ if (bulletUsed) {
463
+ ctx.out.push(leafBlock(inline, { indent: ctx.indent, source }));
464
+ } else {
465
+ pushListLine(inline, source);
314
466
  }
315
467
 
316
- out.push({
317
- indent: indent + bullet.length,
318
- source: res ? res.resolveRaw(token.raw ?? "", itemEnd) : null,
319
- token,
320
- });
468
+ continue;
469
+ }
470
+
471
+ // Block content (list, table, code, blockquote, hr, etc.) sits under the bullet.
472
+ if (!bulletUsed) {
473
+ emitBulletMarker();
321
474
  }
475
+
476
+ flattenBlockToken(token, childCtx);
322
477
  }
323
478
 
324
479
  // List item had no content tokens — still emit the bullet.
@@ -327,24 +482,27 @@ const flattenListItem = function flattenListItem(
327
482
  }
328
483
  };
329
484
 
330
- const flattenWalk = function flattenWalk(
331
- tokens: Token[],
332
- indent: number,
333
- out: FlatBlock[],
334
- res: MarkdownResolver | null,
335
- bound: number
336
- ): void {
337
- for (const token of tokens) {
338
- if (token.type === "space") {
339
- continue;
485
+ const flattenList = function flattenList(list: Tokens.List, ctx: FlattenContext): void {
486
+ for (let i = 0; i < list.items.length; i += 1) {
487
+ const item = list.items[i];
488
+
489
+ let itemStart: number | null = null;
490
+ let itemEnd = ctx.bound;
491
+
492
+ if (ctx.res) {
493
+ const loc = ctx.res.locate(item.raw, ctx.bound);
494
+
495
+ if (loc) {
496
+ itemStart = loc.start;
497
+ itemEnd = loc.end;
498
+ ctx.res.cursor = loc.start;
499
+ }
340
500
  }
341
501
 
342
- if (token.type === "list") {
343
- // SAFETY: Marked creates a List token for the adjacent token.type branch.
344
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Marked's broad Token fallback prevents discriminator narrowing
345
- flattenList(token as Tokens.List, indent, out, res, bound);
346
- } else {
347
- out.push({ indent, source: res ? res.resolveRaw(token.raw ?? "", bound) : null, token });
502
+ flattenListItem(item, bulletFor(list, i), { ...ctx, bound: itemEnd }, itemStart);
503
+
504
+ if (ctx.res && itemStart !== null) {
505
+ ctx.res.cursor = itemEnd;
348
506
  }
349
507
  }
350
508
  };
@@ -354,19 +512,28 @@ const flattenWalk = function flattenWalk(
354
512
  // ---------------------------------------------------------------------------
355
513
 
356
514
  /**
357
- * Lex, flatten, and source-map Markdown in one operation. Every returned block
515
+ * Lex, flatten, and source-map Markdown in one operation. A table becomes one
516
+ * `table-row` block per header or body row. Every returned block
358
517
  * carries a `source` anchor (or `null` when a marked edge case leaves a token
359
518
  * genuinely unresolvable), in the exact order used for navigation/rendering.
360
- * Block HTML is not rendered, so it does not occupy a navigation row. Resolve
361
- * it before filtering so later blocks retain their sequential source anchors.
519
+ * Block HTML is not rendered, so it does not occupy a navigation row.
362
520
  */
363
521
  export const flattenMarkdown = function flattenMarkdown(
364
522
  markdown: string,
365
523
  options?: FlattenMarkdownOptions
366
524
  ): FlatBlock[] {
367
- const res = new MarkdownResolver(markdown, options?.sourceId);
368
- const out: FlatBlock[] = [];
369
- flattenWalk(marked.lexer(markdown), 0, out, res, markdown.length);
525
+ const ctx: FlattenContext = {
526
+ bound: markdown.length,
527
+ indent: 0,
528
+ out: [],
529
+ res: new MarkdownResolver(markdown, options?.sourceId),
530
+ };
531
+
532
+ for (const token of marked.lexer(markdown)) {
533
+ if (token.type !== "space") {
534
+ flattenBlockToken(token, ctx);
535
+ }
536
+ }
370
537
 
371
- return out.filter((block) => block.token.type !== "html");
538
+ return ctx.out;
372
539
  };