@seed-hypermedia/client 0.0.67 → 0.0.68

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.
@@ -10,6 +10,12 @@
10
10
  * treated as new. Old blocks whose IDs don't appear in the new tree
11
11
  * are deleted. This gives per-block granularity — a mix of known and
12
12
  * unknown IDs is handled correctly.
13
+ *
14
+ * Tables get an extra identity pass (rebindTableIdentities): the markdown
15
+ * dialect only carries table, column, and row ids, so cell block ids are
16
+ * re-derived from (row id, column id) against the old document, and
17
+ * attributes markdown cannot express (column width, header column) are
18
+ * carried over from the old blocks.
13
19
  */
14
20
  import type { DocumentOperation } from './change';
15
21
  import type { HMBlockNode } from './hm-types';
@@ -42,6 +48,25 @@ export declare function createBlocksMap(nodes: APIBlockNode[], parentId?: string
42
48
  * Returns a new tree with IDs reassigned (does not mutate inputs).
43
49
  */
44
50
  export declare function matchBlockIds(oldNodes: APIBlockNode[], newNodes: BlockNode[]): BlockNode[];
51
+ /**
52
+ * Rebind identity inside every Table in the new tree against the old tree.
53
+ *
54
+ * For a new Table whose id matches an old Table:
55
+ * - Columns match by explicit id first, then by header-cell text (unique,
56
+ * non-empty texts only), then by position among the still-unmatched.
57
+ * - Rows match by explicit id first, then by position among the unmatched.
58
+ * - Cells reuse the old cell's block id for (matched row, matched column) —
59
+ * cell ids never travel through markdown.
60
+ * - Attributes markdown cannot express (column width, header column, any
61
+ * future keys) are carried over from the matched old block. A row's
62
+ * isHeader comes from the new tree (the dialect does express it).
63
+ * - Position-0 invariants are enforced: only the first column / first row
64
+ * may carry isHeader.
65
+ *
66
+ * Fresh tables (no old match) are passed through with invariants enforced.
67
+ * Non-table blocks are returned unchanged (children walked recursively).
68
+ */
69
+ export declare function rebindTableIdentities(oldNodes: APIBlockNode[], newNodes: BlockNode[]): BlockNode[];
45
70
  /**
46
71
  * Compare the new block tree against the old blocks map and produce
47
72
  * the minimal set of DocumentOperations:
@@ -49,14 +74,25 @@ export declare function matchBlockIds(oldNodes: APIBlockNode[], newNodes: BlockN
49
74
  * - ReplaceBlock for new or content-changed blocks
50
75
  * - MoveBlocks for positioning (new blocks or position changes)
51
76
  * - DeleteBlocks for blocks removed from the document
77
+ *
78
+ * The delete pass is global: every old block whose id does not appear
79
+ * anywhere in the new tree is deleted, including descendants of deleted
80
+ * blocks (so removing a table row also removes its cells, leaving no
81
+ * orphans), while blocks that moved to a different parent are kept.
52
82
  */
53
83
  export declare function computeReplaceOps(oldMap: BlocksMap, matchedTree: BlockNode[], parentId?: string): DocumentOperation[];
84
+ /**
85
+ * Normalize an HMBlockNode tree (API response shape) into APIBlockNode with
86
+ * all fields defaulted, for use as the "old document" side of the diff.
87
+ */
88
+ export declare function toAPIBlockNode(node: HMBlockNode): APIBlockNode;
54
89
  /**
55
90
  * Convert an HMBlockNode tree (from JSON input or API response) into
56
91
  * a BlockNode tree compatible with the diff pipeline.
57
92
  *
58
93
  * HMBlockNode nests childrenType/language inside `attributes`, while
59
- * SeedBlock/BlockNode has them at the top level.
94
+ * SeedBlock/BlockNode has them at the top level. All other attributes
95
+ * (columnId, isHeader, width, …) are preserved in `block.attributes`.
60
96
  */
61
97
  export declare function hmBlockNodeToBlockNode(node: HMBlockNode): BlockNode;
62
98
  export {};
package/dist/index.d.ts CHANGED
@@ -33,7 +33,7 @@ export type { BlockNode, SeedBlock, Annotation } from './markdown-to-blocks';
33
33
  export { blocksToMarkdown, emitFrontmatter, slugify, draftFilename, parseDraftFilename, documentToResolvedMarkdown, commentToResolvedMarkdown, contentToResolvedMarkdown, } from './blocks-to-markdown';
34
34
  export type { ResolvedMarkdownOptions } from './blocks-to-markdown';
35
35
  export type { BlocksToMarkdownOptions } from './blocks-to-markdown';
36
- export { createBlocksMap, matchBlockIds, computeReplaceOps, hmBlockNodeToBlockNode } from './block-diff';
36
+ export { createBlocksMap, matchBlockIds, computeReplaceOps, hmBlockNodeToBlockNode, rebindTableIdentities, toAPIBlockNode, } from './block-diff';
37
37
  export type { APIBlockNode, APIBlock } from './block-diff';
38
38
  export { autoLinkChildToParent, createAutoLinkOps, documentContainsLinkToChild, documentHasSelfQuery, shouldAutoLinkParent, } from './auto-link';
39
39
  export type { AutoLinkChildToParentOptions } from './auto-link';
package/dist/index.mjs CHANGED
@@ -2841,7 +2841,7 @@ function tokenize(markdown) {
2841
2841
  tableLines.push(lines[i]);
2842
2842
  i++;
2843
2843
  }
2844
- blocks.push({ kind: "table", text: tableLines.join("\n") });
2844
+ blocks.push({ kind: "table", lines: tableLines, containerId: pendingContainerId });
2845
2845
  pendingContainerId = void 0;
2846
2846
  continue;
2847
2847
  }
@@ -2871,11 +2871,11 @@ function tokenize(markdown) {
2871
2871
  }
2872
2872
  const paraLines = [];
2873
2873
  while (i < lines.length && lines[i].trim() !== "" && !lines[i].trim().startsWith("```") && !lines[i].trim().startsWith("$$") && !lines[i].trim().startsWith("#") && !lines[i].trim().startsWith("|") && !lines[i].match(STANDALONE_ID_RE) && !/^!\[([^\]]*)\]\(([^)]+)\)/.test(lines[i].trim()) && !/^[-*+]\s+/.test(lines[i].trim()) && !/^\d+\.\s+/.test(lines[i].trim())) {
2874
- paraLines.push(lines[i]);
2874
+ paraLines.push(lines[i].trimStart());
2875
2875
  i++;
2876
2876
  }
2877
2877
  if (paraLines.length === 0) {
2878
- paraLines.push(line);
2878
+ paraLines.push(line.trimStart());
2879
2879
  i++;
2880
2880
  }
2881
2881
  const firstLine = paraLines[0];
@@ -2937,9 +2937,8 @@ function createImageNode(alt, url, id) {
2937
2937
  link: url
2938
2938
  });
2939
2939
  }
2940
- function createListNode(items, listType, containerId) {
2941
- const children = items.map((item) => createParagraphNode(item.text, item.id));
2942
- const container = makeBlockNode(
2940
+ function createListContainerNode(items, listType, containerId) {
2941
+ return makeBlockNode(
2943
2942
  {
2944
2943
  type: "Paragraph",
2945
2944
  id: containerId || generateBlockId4(),
@@ -2947,9 +2946,127 @@ function createListNode(items, listType, containerId) {
2947
2946
  annotations: [],
2948
2947
  childrenType: listType
2949
2948
  },
2950
- children
2949
+ items
2950
+ );
2951
+ }
2952
+ var COL_ID_RE = /<!--\s*col:([A-Za-z0-9_-]+)\s*-->/;
2953
+ var CELL_ID_RE = /<!--\s*id:([A-Za-z0-9_-]+)\s*-->/;
2954
+ function splitTableRow(line) {
2955
+ const { text, id: afterPipeId } = stripBlockId(line.trim());
2956
+ let s = text.trim();
2957
+ if (s.startsWith("|")) s = s.slice(1);
2958
+ const rawCells = [];
2959
+ let cur = "";
2960
+ for (let i = 0; i < s.length; i++) {
2961
+ if (s[i] === "\\" && s[i + 1] === "|") {
2962
+ cur += "|";
2963
+ i++;
2964
+ } else if (s[i] === "|") {
2965
+ rawCells.push(cur.trim());
2966
+ cur = "";
2967
+ } else {
2968
+ cur += s[i];
2969
+ }
2970
+ }
2971
+ const last = cur.trim();
2972
+ if (last !== "" || rawCells.length === 0) rawCells.push(last);
2973
+ let rowId = afterPipeId;
2974
+ const cells = rawCells.map((raw) => {
2975
+ let cellText = raw;
2976
+ const idMatch = cellText.match(CELL_ID_RE);
2977
+ if (idMatch) {
2978
+ rowId = idMatch[1];
2979
+ cellText = cellText.replace(idMatch[0], "");
2980
+ }
2981
+ let colId;
2982
+ const colMatch = cellText.match(COL_ID_RE);
2983
+ if (colMatch) {
2984
+ colId = colMatch[1];
2985
+ cellText = cellText.replace(colMatch[0], "");
2986
+ }
2987
+ return { text: cellText.trim(), colId };
2988
+ });
2989
+ return { cells, id: rowId };
2990
+ }
2991
+ function isSeparatorRow(cells) {
2992
+ return cells.length > 0 && cells.every((c) => /^:?-+:?$/.test(c.text));
2993
+ }
2994
+ function createTableCellNode(rawText, columnId) {
2995
+ const { text, annotations } = parseInlineFormatting(rawText.replace(/<br\s*\/?>/gi, "\n"));
2996
+ return makeBlockNode({
2997
+ type: "Paragraph",
2998
+ id: generateBlockId4(),
2999
+ text,
3000
+ annotations,
3001
+ attributes: { columnId }
3002
+ });
3003
+ }
3004
+ function createTableNode(lines, containerId) {
3005
+ var _a;
3006
+ const rawRows = lines.map(splitTableRow);
3007
+ let headerRow;
3008
+ let bodyRows;
3009
+ if (rawRows.length >= 2 && isSeparatorRow(rawRows[1].cells)) {
3010
+ headerRow = rawRows[0];
3011
+ bodyRows = rawRows.slice(2).filter((r) => !isSeparatorRow(r.cells));
3012
+ } else {
3013
+ bodyRows = rawRows.filter((r) => !isSeparatorRow(r.cells));
3014
+ }
3015
+ const headerCells = (headerRow == null ? void 0 : headerRow.cells) ?? [];
3016
+ const colCount = Math.max(headerCells.length, ...bodyRows.map((r) => r.cells.length), 0);
3017
+ const columnIds = [];
3018
+ for (let idx = 0; idx < colCount; idx++) {
3019
+ columnIds.push(((_a = headerCells[idx]) == null ? void 0 : _a.colId) || generateBlockId4());
3020
+ }
3021
+ const columnNodes = columnIds.map(
3022
+ (id) => makeBlockNode({ type: "TableColumn", id, text: "", annotations: [] })
3023
+ );
3024
+ const rowNodes = [];
3025
+ const hasHeaderRow = headerCells.some((c) => c.text !== "");
3026
+ if (headerRow && hasHeaderRow) {
3027
+ const cells = columnIds.map((columnId, idx) => {
3028
+ var _a2;
3029
+ return createTableCellNode(((_a2 = headerCells[idx]) == null ? void 0 : _a2.text) ?? "", columnId);
3030
+ });
3031
+ rowNodes.push(
3032
+ makeBlockNode(
3033
+ {
3034
+ type: "TableRow",
3035
+ id: headerRow.id || generateBlockId4(),
3036
+ text: "",
3037
+ annotations: [],
3038
+ attributes: { isHeader: true }
3039
+ },
3040
+ cells
3041
+ )
3042
+ );
3043
+ }
3044
+ for (const row of bodyRows) {
3045
+ const cells = columnIds.map((columnId, idx) => {
3046
+ var _a2;
3047
+ return createTableCellNode(((_a2 = row.cells[idx]) == null ? void 0 : _a2.text) ?? "", columnId);
3048
+ });
3049
+ rowNodes.push(
3050
+ makeBlockNode(
3051
+ {
3052
+ type: "TableRow",
3053
+ id: row.id || generateBlockId4(),
3054
+ text: "",
3055
+ annotations: []
3056
+ },
3057
+ cells
3058
+ )
3059
+ );
3060
+ }
3061
+ return makeBlockNode(
3062
+ {
3063
+ type: "Table",
3064
+ id: containerId || generateBlockId4(),
3065
+ text: "",
3066
+ annotations: []
3067
+ },
3068
+ [...columnNodes, ...rowNodes]
2951
3069
  );
2952
- return [container];
2953
3070
  }
2954
3071
  function coerceString(value) {
2955
3072
  if (value == null) return void 0;
@@ -3023,14 +3140,49 @@ function parseMarkdown(markdown) {
3023
3140
  const tokens = tokenize(content);
3024
3141
  const rootNodes = [];
3025
3142
  const headingStack = [];
3143
+ function currentParent() {
3144
+ return headingStack.length > 0 ? headingStack[headingStack.length - 1].node : void 0;
3145
+ }
3146
+ function currentSiblings() {
3147
+ var _a;
3148
+ return ((_a = currentParent()) == null ? void 0 : _a.children) ?? rootNodes;
3149
+ }
3150
+ function unmergeHeadingList() {
3151
+ const parent = currentParent();
3152
+ if (!parent || parent.block.type !== "Heading") return;
3153
+ const ct = parent.block.childrenType;
3154
+ if (ct !== "Unordered" && ct !== "Ordered") return;
3155
+ parent.children = [createListContainerNode(parent.children, ct)];
3156
+ parent.block.childrenType = "Group";
3157
+ }
3026
3158
  function addToCurrentParent(node) {
3159
+ unmergeHeadingList();
3027
3160
  const nodes = Array.isArray(node) ? node : [node];
3028
- if (headingStack.length === 0) {
3029
- rootNodes.push(...nodes);
3030
- } else {
3031
- const parent = headingStack[headingStack.length - 1].node;
3032
- parent.children.push(...nodes);
3161
+ currentSiblings().push(...nodes);
3162
+ }
3163
+ function findListTarget() {
3164
+ const parent = currentParent();
3165
+ const parentType = parent == null ? void 0 : parent.block.childrenType;
3166
+ if (parentType === "Unordered" || parentType === "Ordered") return void 0;
3167
+ const siblings = currentSiblings();
3168
+ const prev = siblings[siblings.length - 1];
3169
+ if (prev) {
3170
+ const canNest = prev.block.type === "Paragraph" && prev.block.text !== "" && prev.children.length === 0 && !prev.block.childrenType;
3171
+ return canNest ? prev : void 0;
3172
+ }
3173
+ return parent;
3174
+ }
3175
+ function addList(items, listType, containerId) {
3176
+ const itemNodes = items.map((item) => createParagraphNode(item.text, item.id));
3177
+ if (!containerId) {
3178
+ const target = findListTarget();
3179
+ if (target) {
3180
+ target.block.childrenType = listType;
3181
+ target.children.push(...itemNodes);
3182
+ return;
3183
+ }
3033
3184
  }
3185
+ addToCurrentParent(createListContainerNode(itemNodes, listType, containerId));
3034
3186
  }
3035
3187
  for (const token of tokens) {
3036
3188
  switch (token.kind) {
@@ -3056,13 +3208,13 @@ function parseMarkdown(markdown) {
3056
3208
  addToCurrentParent(createImageNode(token.alt, token.url, token.id));
3057
3209
  break;
3058
3210
  case "table":
3059
- addToCurrentParent(createCodeNode(token.text, "", token.id));
3211
+ addToCurrentParent(createTableNode(token.lines, token.containerId));
3060
3212
  break;
3061
3213
  case "ul":
3062
- addToCurrentParent(createListNode(token.items, "Unordered", token.containerId));
3214
+ addList(token.items, "Unordered", token.containerId);
3063
3215
  break;
3064
3216
  case "ol":
3065
- addToCurrentParent(createListNode(token.items, "Ordered", token.containerId));
3217
+ addList(token.items, "Ordered", token.containerId);
3066
3218
  break;
3067
3219
  }
3068
3220
  }
@@ -3071,7 +3223,7 @@ function parseMarkdown(markdown) {
3071
3223
  function markdownBlockNodesToHMBlockNodes(nodes) {
3072
3224
  return nodes.map((node) => {
3073
3225
  const { block } = node;
3074
- const attributes = {};
3226
+ const attributes = { ...block.attributes };
3075
3227
  if (block.childrenType !== void 0) {
3076
3228
  attributes.childrenType = block.childrenType;
3077
3229
  }
@@ -3104,6 +3256,7 @@ function flattenToOperations(tree, parentId = "") {
3104
3256
  const blockIds = [];
3105
3257
  for (const node of tree) {
3106
3258
  const block = {
3259
+ ...node.block.attributes,
3107
3260
  type: node.block.type,
3108
3261
  id: node.block.id,
3109
3262
  text: node.block.text,
@@ -3201,6 +3354,9 @@ function blockNodeToMarkdown(node, depth, opts) {
3201
3354
  var _a;
3202
3355
  const block = node.block;
3203
3356
  const children = node.children || [];
3357
+ if (block.type === "Table") {
3358
+ return tableToMarkdown(node, depth, (text, annotations) => applyAnnotations(text, annotations));
3359
+ }
3204
3360
  const childrenType = (_a = block.attributes) == null ? void 0 : _a.childrenType;
3205
3361
  const isListContainer = block.type === "Paragraph" && !block.text && (childrenType === "Ordered" || childrenType === "Unordered" || childrenType === "Blockquote");
3206
3362
  let result;
@@ -3289,6 +3445,102 @@ function blockToMarkdown(block, depth, opts) {
3289
3445
  }
3290
3446
  }
3291
3447
  }
3448
+ function normalizeTableNode(node) {
3449
+ var _a, _b;
3450
+ const columns = [];
3451
+ const rows = [];
3452
+ for (const child of node.children || []) {
3453
+ const block = child.block;
3454
+ if ((block == null ? void 0 : block.type) === "TableColumn") {
3455
+ columns.push({ id: block.id });
3456
+ } else if ((block == null ? void 0 : block.type) === "TableRow") {
3457
+ const cells = /* @__PURE__ */ new Map();
3458
+ for (const cellNode of child.children || []) {
3459
+ const cell = cellNode.block;
3460
+ const columnId = (_a = cell == null ? void 0 : cell.attributes) == null ? void 0 : _a.columnId;
3461
+ if (typeof columnId === "string" && columnId && !cells.has(columnId)) {
3462
+ cells.set(columnId, { text: cell.text || "", annotations: cell.annotations });
3463
+ }
3464
+ }
3465
+ rows.push({
3466
+ id: block.id,
3467
+ // Position-0 invariant: only the first row may be the header row.
3468
+ isHeader: rows.length === 0 && ((_b = block.attributes) == null ? void 0 : _b.isHeader) === true,
3469
+ cells
3470
+ });
3471
+ }
3472
+ }
3473
+ return { columns, rows };
3474
+ }
3475
+ function escapeCellText(s) {
3476
+ return s.replace(/\|/g, "\\|").replace(/\n/g, "<br>");
3477
+ }
3478
+ function assembleTableMarkdown(tableId, columns, header, bodyRows, ind) {
3479
+ const lines = [];
3480
+ lines.push(ind + idComment(tableId));
3481
+ const headerCells = columns.map((col, idx) => {
3482
+ const text = header.cellTexts[idx] || "";
3483
+ return (text ? text + " " : "") + `<!-- col:${col.id} -->`;
3484
+ });
3485
+ if (header.rowId) {
3486
+ headerCells[headerCells.length - 1] += " " + idComment(header.rowId);
3487
+ }
3488
+ lines.push(ind + "| " + headerCells.join(" | ") + " |");
3489
+ lines.push(ind + "|" + columns.map(() => " --- ").join("|") + "|");
3490
+ for (const row of bodyRows) {
3491
+ const cells = [...row.cellTexts];
3492
+ const last = cells.length - 1;
3493
+ cells[last] = (cells[last] ? cells[last] + " " : "") + idComment(row.rowId);
3494
+ lines.push(ind + "| " + cells.join(" | ") + " |");
3495
+ }
3496
+ return lines.join("\n");
3497
+ }
3498
+ function tableToMarkdown(node, depth, renderCell) {
3499
+ var _a;
3500
+ const { columns, rows } = normalizeTableNode(node);
3501
+ if (columns.length === 0) return "";
3502
+ const renderRowCells = (row) => columns.map((col) => {
3503
+ const cell = row == null ? void 0 : row.cells.get(col.id);
3504
+ return cell ? escapeCellText(renderCell(cell.text, cell.annotations)) : "";
3505
+ });
3506
+ const headerRow = ((_a = rows[0]) == null ? void 0 : _a.isHeader) ? rows[0] : void 0;
3507
+ const bodyRows = (headerRow ? rows.slice(1) : rows).map((row) => ({
3508
+ rowId: row.id,
3509
+ cellTexts: renderRowCells(row)
3510
+ }));
3511
+ return assembleTableMarkdown(
3512
+ node.block.id,
3513
+ columns,
3514
+ { rowId: headerRow == null ? void 0 : headerRow.id, cellTexts: renderRowCells(headerRow) },
3515
+ bodyRows,
3516
+ indent(depth)
3517
+ );
3518
+ }
3519
+ async function tableToResolvedMarkdown(node, depth, renderCell) {
3520
+ var _a;
3521
+ const { columns, rows } = normalizeTableNode(node);
3522
+ if (columns.length === 0) return "";
3523
+ const renderRowCells = (row) => Promise.all(
3524
+ columns.map(async (col) => {
3525
+ const cell = row == null ? void 0 : row.cells.get(col.id);
3526
+ return cell ? escapeCellText(await renderCell(cell.text, cell.annotations)) : "";
3527
+ })
3528
+ );
3529
+ const headerRow = ((_a = rows[0]) == null ? void 0 : _a.isHeader) ? rows[0] : void 0;
3530
+ const bodyRows = await Promise.all(
3531
+ (headerRow ? rows.slice(1) : rows).map(async (row) => ({
3532
+ rowId: row.id,
3533
+ cellTexts: await renderRowCells(row)
3534
+ }))
3535
+ );
3536
+ return assembleTableMarkdown(
3537
+ node.block.id,
3538
+ columns,
3539
+ { rowId: headerRow == null ? void 0 : headerRow.id, cellTexts: await renderRowCells(headerRow) },
3540
+ bodyRows,
3541
+ indent(depth)
3542
+ );
3543
+ }
3292
3544
  function applyAnnotations(text, annotations) {
3293
3545
  if (!annotations || annotations.length === 0) {
3294
3546
  return text;
@@ -3411,6 +3663,9 @@ async function resolvedBlockNodeToMarkdown(node, depth, ctx) {
3411
3663
  var _a;
3412
3664
  const block = node.block;
3413
3665
  const children = node.children || [];
3666
+ if (block.type === "Table") {
3667
+ return tableToResolvedMarkdown(node, depth, (text, annotations) => applyResolvedAnnotations(text, annotations, ctx));
3668
+ }
3414
3669
  const childrenType = (_a = block.attributes) == null ? void 0 : _a.childrenType;
3415
3670
  const isListContainer = block.type === "Paragraph" && !block.text && (childrenType === "Ordered" || childrenType === "Unordered" || childrenType === "Blockquote");
3416
3671
  let result = isListContainer ? resolvedIdComment(block.id) : await resolvedBlockToMarkdown(block, depth, ctx);
@@ -3772,17 +4027,203 @@ function matchBlockIds(oldNodes, newNodes) {
3772
4027
  };
3773
4028
  });
3774
4029
  }
4030
+ function extraAttributes(attrs) {
4031
+ if (!attrs) return {};
4032
+ const { childrenType: _c, language: _l, ...rest } = attrs;
4033
+ return rest;
4034
+ }
4035
+ function oldHeaderCellText(row, columnId) {
4036
+ var _a, _b;
4037
+ if (!row) return void 0;
4038
+ for (const cell of row.children || []) {
4039
+ if (((_b = (_a = cell.block) == null ? void 0 : _a.attributes) == null ? void 0 : _b.columnId) === columnId) return cell.block.text || "";
4040
+ }
4041
+ return void 0;
4042
+ }
4043
+ function rebindTableIdentities(oldNodes, newNodes) {
4044
+ const oldTables = /* @__PURE__ */ new Map();
4045
+ const indexTables = (nodes) => {
4046
+ var _a, _b;
4047
+ for (const node of nodes) {
4048
+ if (((_a = node.block) == null ? void 0 : _a.type) === "Table") oldTables.set(node.block.id, node);
4049
+ if ((_b = node.children) == null ? void 0 : _b.length) indexTables(node.children);
4050
+ }
4051
+ };
4052
+ indexTables(oldNodes);
4053
+ const walk = (nodes) => nodes.map((node) => {
4054
+ if (node.block.type === "Table") {
4055
+ return rebindTable(oldTables.get(node.block.id), node);
4056
+ }
4057
+ return { ...node, children: walk(node.children) };
4058
+ });
4059
+ return walk(newNodes);
4060
+ }
4061
+ function rebindTable(oldTable, newTable) {
4062
+ const newCols = newTable.children.filter((c) => c.block.type === "TableColumn");
4063
+ const newRows = newTable.children.filter((c) => c.block.type === "TableRow");
4064
+ const otherChildren = newTable.children.filter((c) => c.block.type !== "TableColumn" && c.block.type !== "TableRow");
4065
+ const oldCols = ((oldTable == null ? void 0 : oldTable.children) || []).filter((c) => {
4066
+ var _a;
4067
+ return ((_a = c.block) == null ? void 0 : _a.type) === "TableColumn";
4068
+ });
4069
+ const oldRows = ((oldTable == null ? void 0 : oldTable.children) || []).filter((c) => {
4070
+ var _a;
4071
+ return ((_a = c.block) == null ? void 0 : _a.type) === "TableRow";
4072
+ });
4073
+ const oldColById = new Map(oldCols.map((c) => [c.block.id, c]));
4074
+ const oldRowById = new Map(oldRows.map((r) => [r.block.id, r]));
4075
+ const usedOldCols = /* @__PURE__ */ new Set();
4076
+ const matchedOldCol = new Array(newCols.length).fill(void 0);
4077
+ newCols.forEach((col, idx) => {
4078
+ const old = oldColById.get(col.block.id);
4079
+ if (old && !usedOldCols.has(old.block.id)) {
4080
+ matchedOldCol[idx] = old;
4081
+ usedOldCols.add(old.block.id);
4082
+ }
4083
+ });
4084
+ const oldHeaderRow = oldRows.find((r) => {
4085
+ var _a;
4086
+ return ((_a = r.block.attributes) == null ? void 0 : _a.isHeader) === true;
4087
+ });
4088
+ const newHeaderRow = newRows.find((r) => {
4089
+ var _a;
4090
+ return ((_a = r.block.attributes) == null ? void 0 : _a.isHeader) === true;
4091
+ });
4092
+ if (oldHeaderRow && newHeaderRow) {
4093
+ const textToOldCol = /* @__PURE__ */ new Map();
4094
+ for (const old of oldCols) {
4095
+ if (usedOldCols.has(old.block.id)) continue;
4096
+ const text = oldHeaderCellText(oldHeaderRow, old.block.id);
4097
+ if (!text) continue;
4098
+ textToOldCol.set(text, textToOldCol.has(text) ? null : old);
4099
+ }
4100
+ newCols.forEach((col, idx) => {
4101
+ if (matchedOldCol[idx]) return;
4102
+ const cell = newHeaderRow.children.find((c) => {
4103
+ var _a;
4104
+ return ((_a = c.block.attributes) == null ? void 0 : _a.columnId) === col.block.id;
4105
+ });
4106
+ const text = (cell == null ? void 0 : cell.block.text) || "";
4107
+ const old = text ? textToOldCol.get(text) : void 0;
4108
+ if (old && !usedOldCols.has(old.block.id)) {
4109
+ matchedOldCol[idx] = old;
4110
+ usedOldCols.add(old.block.id);
4111
+ }
4112
+ });
4113
+ }
4114
+ const remainingOldCols = oldCols.filter((c) => !usedOldCols.has(c.block.id));
4115
+ let remainingIdx = 0;
4116
+ newCols.forEach((_, idx) => {
4117
+ if (matchedOldCol[idx]) return;
4118
+ const old = remainingOldCols[remainingIdx];
4119
+ if (old) {
4120
+ matchedOldCol[idx] = old;
4121
+ usedOldCols.add(old.block.id);
4122
+ remainingIdx++;
4123
+ }
4124
+ });
4125
+ const colIdMap = /* @__PURE__ */ new Map();
4126
+ const finalCols = newCols.map((col, idx) => {
4127
+ const old = matchedOldCol[idx];
4128
+ const finalId = old ? old.block.id : col.block.id;
4129
+ colIdMap.set(col.block.id, finalId);
4130
+ const carried = { ...extraAttributes(old == null ? void 0 : old.block.attributes), ...col.block.attributes };
4131
+ const block = {
4132
+ ...col.block,
4133
+ id: finalId,
4134
+ ...Object.keys(carried).length > 0 ? { attributes: carried } : {}
4135
+ };
4136
+ return { block, children: [] };
4137
+ });
4138
+ const usedOldRows = /* @__PURE__ */ new Set();
4139
+ const matchedOldRow = new Array(newRows.length).fill(void 0);
4140
+ newRows.forEach((row, idx) => {
4141
+ const old = oldRowById.get(row.block.id);
4142
+ if (old && !usedOldRows.has(old.block.id)) {
4143
+ matchedOldRow[idx] = old;
4144
+ usedOldRows.add(old.block.id);
4145
+ }
4146
+ });
4147
+ const remainingOldRows = oldRows.filter((r) => !usedOldRows.has(r.block.id));
4148
+ let remainingRowIdx = 0;
4149
+ newRows.forEach((_, idx) => {
4150
+ if (matchedOldRow[idx]) return;
4151
+ const old = remainingOldRows[remainingRowIdx];
4152
+ if (old) {
4153
+ matchedOldRow[idx] = old;
4154
+ usedOldRows.add(old.block.id);
4155
+ remainingRowIdx++;
4156
+ }
4157
+ });
4158
+ const finalRows = newRows.map((row, idx) => {
4159
+ const old = matchedOldRow[idx];
4160
+ const rowId = old ? old.block.id : row.block.id;
4161
+ const { isHeader: _oldIsHeader, ...oldRowExtras } = extraAttributes(old == null ? void 0 : old.block.attributes);
4162
+ const rowAttrs = { ...oldRowExtras, ...row.block.attributes };
4163
+ const cells = row.children.map((cell) => {
4164
+ var _a;
4165
+ const newColumnId = (_a = cell.block.attributes) == null ? void 0 : _a.columnId;
4166
+ const finalColumnId = typeof newColumnId === "string" ? colIdMap.get(newColumnId) ?? newColumnId : newColumnId;
4167
+ const oldCell = old == null ? void 0 : old.children.find((c) => {
4168
+ var _a2, _b;
4169
+ return ((_b = (_a2 = c.block) == null ? void 0 : _a2.attributes) == null ? void 0 : _b.columnId) === finalColumnId;
4170
+ });
4171
+ const cellAttrs = {
4172
+ ...extraAttributes(oldCell == null ? void 0 : oldCell.block.attributes),
4173
+ ...cell.block.attributes,
4174
+ columnId: finalColumnId
4175
+ };
4176
+ const block2 = {
4177
+ ...cell.block,
4178
+ id: oldCell ? oldCell.block.id : cell.block.id,
4179
+ attributes: cellAttrs
4180
+ };
4181
+ return { block: block2, children: cell.children };
4182
+ });
4183
+ const block = {
4184
+ ...row.block,
4185
+ id: rowId,
4186
+ ...Object.keys(rowAttrs).length > 0 ? { attributes: rowAttrs } : {}
4187
+ };
4188
+ return { block, children: cells };
4189
+ });
4190
+ const stripLateHeader = (nodes) => {
4191
+ nodes.forEach((node, idx) => {
4192
+ var _a;
4193
+ if (idx === 0 || ((_a = node.block.attributes) == null ? void 0 : _a.isHeader) !== true) return;
4194
+ const { isHeader: _h, ...rest } = node.block.attributes;
4195
+ node.block = { ...node.block, attributes: rest };
4196
+ });
4197
+ };
4198
+ stripLateHeader(finalCols);
4199
+ stripLateHeader(finalRows);
4200
+ const tableAttrs = { ...extraAttributes(oldTable == null ? void 0 : oldTable.block.attributes), ...newTable.block.attributes };
4201
+ const tableBlock = {
4202
+ ...newTable.block,
4203
+ ...Object.keys(tableAttrs).length > 0 ? { attributes: tableAttrs } : {}
4204
+ };
4205
+ return { block: tableBlock, children: [...finalCols, ...finalRows, ...otherChildren] };
4206
+ }
3775
4207
  function computeReplaceOps(oldMap, matchedTree, parentId = "") {
3776
- const ops = [];
3777
4208
  const touchedIds = /* @__PURE__ */ new Set();
4209
+ const ops = computeReplaceOpsInner(oldMap, matchedTree, parentId, touchedIds);
4210
+ const deletedIds = Object.keys(oldMap).filter((id) => !touchedIds.has(id));
4211
+ if (deletedIds.length > 0) {
4212
+ ops.push({ type: "DeleteBlocks", blocks: deletedIds });
4213
+ }
4214
+ return ops;
4215
+ }
4216
+ function computeReplaceOpsInner(oldMap, matchedTree, parentId, touchedIds) {
4217
+ const ops = [];
3778
4218
  const blockIdsAtLevel = [];
3779
- matchedTree.forEach((node, idx) => {
4219
+ matchedTree.forEach((node) => {
3780
4220
  const blockId = node.block.id;
3781
4221
  touchedIds.add(blockId);
3782
4222
  blockIdsAtLevel.push(blockId);
3783
4223
  const oldEntry = oldMap[blockId];
3784
4224
  const isNew = !oldEntry;
3785
4225
  const block = {
4226
+ ...node.block.attributes,
3786
4227
  type: node.block.type,
3787
4228
  id: blockId,
3788
4229
  text: node.block.text,
@@ -3803,15 +4244,9 @@ function computeReplaceOps(oldMap, matchedTree, parentId = "") {
3803
4244
  if (!isBlockContentEqual(oldEntry.block, node.block)) {
3804
4245
  ops.push({ type: "ReplaceBlock", block });
3805
4246
  }
3806
- const prevNode = idx > 0 ? matchedTree[idx - 1] : void 0;
3807
- const expectedLeft = (prevNode == null ? void 0 : prevNode.block.id) ?? "";
3808
- if (oldEntry.parent !== parentId || oldEntry.left !== expectedLeft) {
3809
- }
3810
4247
  }
3811
4248
  if (node.children.length > 0) {
3812
- const childOps = computeReplaceOps(oldMap, node.children, blockId);
3813
- ops.push(...childOps);
3814
- collectIds(node.children, touchedIds);
4249
+ ops.push(...computeReplaceOpsInner(oldMap, node.children, blockId, touchedIds));
3815
4250
  }
3816
4251
  });
3817
4252
  if (blockIdsAtLevel.length > 0) {
@@ -3821,22 +4256,17 @@ function computeReplaceOps(oldMap, matchedTree, parentId = "") {
3821
4256
  parent: parentId
3822
4257
  });
3823
4258
  }
3824
- const deletedIds = [];
3825
- for (const [id, entry] of Object.entries(oldMap)) {
3826
- if (entry.parent === parentId && !touchedIds.has(id)) {
3827
- deletedIds.push(id);
3828
- }
3829
- }
3830
- if (deletedIds.length > 0) {
3831
- ops.push({ type: "DeleteBlocks", blocks: deletedIds });
3832
- }
3833
4259
  return ops;
3834
4260
  }
3835
- function collectIds(nodes, set) {
3836
- for (const node of nodes) {
3837
- set.add(node.block.id);
3838
- collectIds(node.children, set);
4261
+ function attrsEqual(a, b) {
4262
+ const keys = Object.keys({ ...a, ...b });
4263
+ for (const key of keys) {
4264
+ const av = a[key];
4265
+ const bv = b[key];
4266
+ if (av === bv) continue;
4267
+ if (JSON.stringify(av) !== JSON.stringify(bv)) return false;
3839
4268
  }
4269
+ return true;
3840
4270
  }
3841
4271
  function isBlockContentEqual(old, newBlock) {
3842
4272
  if (old.type !== newBlock.type) return false;
@@ -3853,11 +4283,27 @@ function isBlockContentEqual(old, newBlock) {
3853
4283
  return false;
3854
4284
  }
3855
4285
  if ((oldAttrs.language || "") !== (newBlock.language || "")) return false;
4286
+ if (!attrsEqual(extraAttributes(oldAttrs), newBlock.attributes || {})) return false;
3856
4287
  return true;
3857
4288
  }
4289
+ function toAPIBlockNode(node) {
4290
+ const block = node.block;
4291
+ return {
4292
+ block: {
4293
+ id: block.id,
4294
+ type: block.type,
4295
+ text: block.text || "",
4296
+ link: block.link || "",
4297
+ annotations: block.annotations || [],
4298
+ attributes: block.attributes || {}
4299
+ },
4300
+ children: (node.children || []).map(toAPIBlockNode)
4301
+ };
4302
+ }
3858
4303
  function hmBlockNodeToBlockNode(node) {
3859
4304
  const b = node.block;
3860
4305
  const attrs = b.attributes || {};
4306
+ const extra = extraAttributes(attrs);
3861
4307
  const block = {
3862
4308
  type: b.type || "",
3863
4309
  id: b.id || "",
@@ -3865,7 +4311,8 @@ function hmBlockNodeToBlockNode(node) {
3865
4311
  annotations: b.annotations || [],
3866
4312
  ...attrs.childrenType ? { childrenType: attrs.childrenType } : {},
3867
4313
  ...attrs.language ? { language: attrs.language } : {},
3868
- ...b.link ? { link: b.link } : {}
4314
+ ...b.link ? { link: b.link } : {},
4315
+ ...Object.keys(extra).length > 0 ? { attributes: extra } : {}
3869
4316
  };
3870
4317
  return {
3871
4318
  block,
@@ -5086,6 +5533,7 @@ export {
5086
5533
  pdfToBlocks,
5087
5534
  processFulltextDocument,
5088
5535
  pushSpanToAnnotation,
5536
+ rebindTableIdentities,
5089
5537
  resolveCapability,
5090
5538
  resolveDocumentState,
5091
5539
  resolveFileLinksInBlocks,
@@ -5098,6 +5546,7 @@ export {
5098
5546
  signPreparedChange,
5099
5547
  slugify,
5100
5548
  teiToBlocks,
5549
+ toAPIBlockNode,
5101
5550
  trimTrailingEmptyBlocks,
5102
5551
  unpackHmId,
5103
5552
  updateComment,
@@ -29,6 +29,13 @@ export type SeedBlock = {
29
29
  childrenType?: string;
30
30
  language?: string;
31
31
  link?: string;
32
+ /**
33
+ * Additional block attributes beyond the legacy top-level ones above
34
+ * (e.g. `columnId` on table cell Paragraphs, `isHeader` on TableRow /
35
+ * TableColumn, `width` on TableColumn). Inlined at the top level of the
36
+ * wire block, nested under `attributes` in HMBlockNode.
37
+ */
38
+ attributes?: Record<string, unknown>;
32
39
  };
33
40
  export type BlockNode = {
34
41
  block: SeedBlock;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seed-hypermedia/client",
3
- "version": "0.0.67",
3
+ "version": "0.0.68",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/seed-hypermedia/seed",
package/src/index.ts CHANGED
@@ -86,7 +86,14 @@ export {
86
86
  export type {ResolvedMarkdownOptions} from './blocks-to-markdown'
87
87
  export type {BlocksToMarkdownOptions} from './blocks-to-markdown'
88
88
 
89
- export {createBlocksMap, matchBlockIds, computeReplaceOps, hmBlockNodeToBlockNode} from './block-diff'
89
+ export {
90
+ createBlocksMap,
91
+ matchBlockIds,
92
+ computeReplaceOps,
93
+ hmBlockNodeToBlockNode,
94
+ rebindTableIdentities,
95
+ toAPIBlockNode,
96
+ } from './block-diff'
90
97
  export type {APIBlockNode, APIBlock} from './block-diff'
91
98
 
92
99
  export {