docblocks-react-ui 0.21.0 → 0.22.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.
@@ -6,7 +6,7 @@ import { I18nextProvider, initReactI18next, useTranslation } from "react-i18next
6
6
  import { Slot } from "@radix-ui/react-slot";
7
7
  import { cva } from "class-variance-authority";
8
8
  import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
9
- import { ATTRIBUTE_TYPES, BLOCK_REGISTRY, CALLOUT_ICONS, DEFAULT_TABLE_COLUMN_WIDTH, DetachedBlockError, InvalidAttributeError, InvalidAttrsError, InvalidMarkError, InvalidOperationError, createSelection, isHexColor, isSafeEmbedSrc, isSafeLinkHref, linkHrefKindOf, presenceSelectionOf } from "docblocks-core";
9
+ import { ATTRIBUTE_TYPES, BLOCK_REGISTRY, CALLOUT_ICONS, DEFAULT_TABLE_COLUMN_WIDTH, DetachedBlockError, InvalidAttributeError, InvalidAttrsError, InvalidMarkError, InvalidOperationError, createSelection, isHexColor, isMergeableRect, isSafeEmbedSrc, isSafeLinkHref, linkHrefKindOf, presenceSelectionOf, resolveTableGrid } from "docblocks-core";
10
10
  import { createInstance } from "i18next";
11
11
  import { createStore as createStore$1 } from "zustand/vanilla";
12
12
  import { DayPicker, getDefaultClassNames } from "react-day-picker";
@@ -750,7 +750,11 @@ const INIT_OPTIONS = {
750
750
  "column": "Add column",
751
751
  "row": "Add row"
752
752
  },
753
- cell: { "options": "Cell options" }
753
+ cell: {
754
+ "options": "Cell options",
755
+ "merge": "Merge cells",
756
+ "split": "Split cells"
757
+ }
754
758
  }
755
759
  },
756
760
  ru: {
@@ -1289,7 +1293,11 @@ const INIT_OPTIONS = {
1289
1293
  "column": "Добавить столбец",
1290
1294
  "row": "Добавить строку"
1291
1295
  },
1292
- cell: { "options": "Настройки ячейки" }
1296
+ cell: {
1297
+ "options": "Настройки ячейки",
1298
+ "merge": "Объединить ячейки",
1299
+ "split": "Разъединить ячейки"
1300
+ }
1293
1301
  }
1294
1302
  }
1295
1303
  },
@@ -18795,6 +18803,163 @@ function useSlashMenuApi() {
18795
18803
  return useContext(SlashMenuContext);
18796
18804
  }
18797
18805
  //#endregion
18806
+ //#region src/editing/slash/helpers.ts
18807
+ /** The block snapshot's indent: a non-negative integer attr; absent is 0. */
18808
+ function indentOf$1(block) {
18809
+ if (!("attrs" in block)) return 0;
18810
+ const indent = block.attrs?.indent;
18811
+ return typeof indent === "number" && Number.isInteger(indent) && indent >= 0 ? indent : 0;
18812
+ }
18813
+ /**
18814
+ * Hold the editor root's focus across a structural rebuild: the focused
18815
+ * inner editable unmounts during the store-driven re-render, and the
18816
+ * browser drops the focus to <body> until the next-frame caret re-seating
18817
+ * lands. Focusing the (tabIndex -1) root before the rebuild keeps the
18818
+ * focus — and the keyboard scope — inside the editor while the gap lasts
18819
+ * (the root's keydown handler still owns the hotkeys).
18820
+ */
18821
+ function holdFocus(scope) {
18822
+ if (scope instanceof HTMLElement && scope.isConnected) scope.focus({ preventScroll: true });
18823
+ }
18824
+ /** The table's first cell (the caret's seat after the slash Table lands). */
18825
+ function firstCellOf(doc, tableId) {
18826
+ const firstRow = doc.getChildren(tableId)[0];
18827
+ return firstRow === void 0 ? void 0 : doc.getChildren(firstRow)[0];
18828
+ }
18829
+ /** Insert the command's block with its default attrs (type-safe per type), keeping the trigger's attach level (a subtree view's root level may sit deeper than 0 — the same position and indent were valid before, so the sequence's jump rule holds at the landing). */
18830
+ function insertCommand(doc, command, at, indent = 0) {
18831
+ const ind = indent !== 0 ? { indent } : {};
18832
+ switch (command.type) {
18833
+ case "paragraph": return doc.insertBlock("paragraph", ind.indent === void 0 ? void 0 : { ...ind }, at);
18834
+ case "heading": return doc.insertBlock("heading", {
18835
+ level: command.attrs.level,
18836
+ ...ind
18837
+ }, at);
18838
+ case "list-item": return doc.insertBlock("list-item", {
18839
+ list: command.attrs.list,
18840
+ ...ind
18841
+ }, at);
18842
+ case "quote": return doc.insertBlock("quote", ind.indent === void 0 ? void 0 : { ...ind }, at);
18843
+ case "callout": return doc.insertBlock("callout", ind.indent === void 0 ? void 0 : { ...ind }, at);
18844
+ case "code": return doc.insertBlock("code", command.attrs?.language === void 0 ? ind.indent === void 0 ? void 0 : { ...ind } : {
18845
+ language: command.attrs.language,
18846
+ ...ind
18847
+ }, at);
18848
+ case "divider": return doc.insertBlock("divider", ind.indent === void 0 ? void 0 : { ...ind }, at);
18849
+ case "table": {
18850
+ const tableId = doc.insertBlock("table", {
18851
+ cols: 2,
18852
+ columnWidths: [DEFAULT_TABLE_COLUMN_WIDTH, DEFAULT_TABLE_COLUMN_WIDTH],
18853
+ ...ind
18854
+ }, at);
18855
+ for (let row = 0; row < 2; row++) {
18856
+ const rowId = doc.insertBlock("table-row", void 0, { parent: tableId });
18857
+ for (let col = 0; col < 2; col++) doc.insertBlock("table-cell", void 0, { parent: rowId });
18858
+ }
18859
+ return tableId;
18860
+ }
18861
+ default: throw new UnknownSlashCommandError(`Unknown slash command type "${command.type}".`);
18862
+ }
18863
+ }
18864
+ //#endregion
18865
+ //#region src/editing/slash/apply.ts
18866
+ /**
18867
+ * Execute the apply plan (one transaction for the non-replace kinds —
18868
+ * one undo step, one wire update). The validation-first ordering stands:
18869
+ * the type change / the attrs patch validate before the text deletion
18870
+ * runs, so a rejected plan commits nothing.
18871
+ */
18872
+ function applySlashPlan(doc, plan, command, blockId, parentId, indent, scope) {
18873
+ switch (plan.kind) {
18874
+ case "noop": return;
18875
+ case "replace": {
18876
+ let tableId = null;
18877
+ let caretId = null;
18878
+ doc.transact(() => {
18879
+ const siblings = doc.getChildren(parentId);
18880
+ const index = siblings.indexOf(blockId);
18881
+ const after = index > 0 ? siblings[index - 1] : void 0;
18882
+ doc.removeBlock(blockId);
18883
+ const newId = insertCommand(doc, command, after === void 0 ? void 0 : {
18884
+ parent: parentId,
18885
+ after
18886
+ }, indent);
18887
+ if (command.type === "table") {
18888
+ tableId = newId;
18889
+ return;
18890
+ }
18891
+ caretId = newId;
18892
+ if (!BLOCK_REGISTRY[command.type].content && doc.getChildren(parentId).at(-1) === newId) caretId = doc.insertBlock("paragraph", void 0, {
18893
+ parent: parentId,
18894
+ after: newId
18895
+ });
18896
+ });
18897
+ holdFocus(scope);
18898
+ if (tableId !== null) {
18899
+ const firstCell = firstCellOf(doc, tableId);
18900
+ if (firstCell !== void 0) {
18901
+ focusCellActivation(firstCell, scope);
18902
+ return;
18903
+ }
18904
+ }
18905
+ if (caretId !== null) focusCaretIn(caretId, 0, scope);
18906
+ return;
18907
+ }
18908
+ case "update":
18909
+ case "convert": {
18910
+ const attrs = "attrs" in command && command.attrs !== void 0 ? command.attrs : void 0;
18911
+ let tableId = null;
18912
+ try {
18913
+ doc.transact(() => {
18914
+ if (plan.kind === "convert") switch (command.type) {
18915
+ case "paragraph":
18916
+ doc.changeBlockType(blockId, "paragraph");
18917
+ break;
18918
+ case "heading":
18919
+ doc.changeBlockType(blockId, "heading", command.attrs);
18920
+ break;
18921
+ case "list-item":
18922
+ doc.changeBlockType(blockId, "list-item", command.attrs);
18923
+ break;
18924
+ case "quote":
18925
+ doc.changeBlockType(blockId, "quote");
18926
+ break;
18927
+ case "callout":
18928
+ doc.changeBlockType(blockId, "callout");
18929
+ break;
18930
+ case "code": doc.changeBlockType(blockId, "code", command.attrs);
18931
+ }
18932
+ else if (attrs !== void 0) doc.updateBlock(blockId, attrs);
18933
+ doc.deleteText(blockId, plan.deleteFrom, plan.deleteTo);
18934
+ if (command.type === "table") tableId = insertCommand(doc, command, {
18935
+ parent: parentId,
18936
+ after: blockId
18937
+ }, indent);
18938
+ else if (command.type === "divider") insertCommand(doc, command, {
18939
+ parent: parentId,
18940
+ after: blockId
18941
+ }, indent);
18942
+ });
18943
+ } catch (error) {
18944
+ if (error instanceof InvalidAttrsError || error instanceof InvalidOperationError) return;
18945
+ throw error;
18946
+ }
18947
+ if (tableId !== null) {
18948
+ const firstCell = firstCellOf(doc, tableId);
18949
+ if (firstCell !== void 0) {
18950
+ holdFocus(scope);
18951
+ focusCellActivation(firstCell, scope);
18952
+ return;
18953
+ }
18954
+ }
18955
+ if (plan.kind === "convert") holdFocus(scope);
18956
+ focusCaretIn(blockId, plan.deleteFrom, scope);
18957
+ return;
18958
+ }
18959
+ default: return assertNever(plan);
18960
+ }
18961
+ }
18962
+ //#endregion
18798
18963
  //#region src/editing/slash/DatabaseSlashPicker.tsx
18799
18964
  /**
18800
18965
  * The slash `Database` picker: the create-new form (a `New table` button that stands the
@@ -19315,12 +19480,13 @@ function sameAttrs(block, command) {
19315
19480
  function planSlashApply(command, block, text, slashOffset, hasFollowers) {
19316
19481
  if (sameAttrs(block, command)) return { kind: "noop" };
19317
19482
  const queryEnd = deriveSlash(text, slashOffset, text.length).queryEnd;
19318
- if (command.type === "table") return {
19483
+ const stripped = text.slice(0, slashOffset) + text.slice(queryEnd);
19484
+ if (command.type === "table") return stripped === "" && !hasFollowers ? { kind: "replace" } : {
19319
19485
  kind: "update",
19320
19486
  deleteFrom: slashOffset,
19321
19487
  deleteTo: queryEnd
19322
19488
  };
19323
- if (text.slice(0, slashOffset) + text.slice(queryEnd) === "" && !hasFollowers && command.type !== block.type) return { kind: "replace" };
19489
+ if (stripped === "" && !hasFollowers && command.type !== block.type) return { kind: "replace" };
19324
19490
  if (command.type === "divider") return {
19325
19491
  kind: "update",
19326
19492
  deleteFrom: slashOffset,
@@ -19337,144 +19503,6 @@ function planSlashApply(command, block, text, slashOffset, hasFollowers) {
19337
19503
  deleteTo: queryEnd
19338
19504
  };
19339
19505
  }
19340
- /** Insert the command's block with its default attrs (type-safe per type), keeping the trigger's attach level (a subtree view's root level may sit deeper than 0 — the same position and indent were valid before, so the sequence's jump rule holds at the landing). */
19341
- function insertCommand(doc, command, at, indent = 0) {
19342
- const ind = indent !== 0 ? { indent } : {};
19343
- switch (command.type) {
19344
- case "paragraph": return doc.insertBlock("paragraph", ind.indent === void 0 ? void 0 : { ...ind }, at);
19345
- case "heading": return doc.insertBlock("heading", {
19346
- level: command.attrs.level,
19347
- ...ind
19348
- }, at);
19349
- case "list-item": return doc.insertBlock("list-item", {
19350
- list: command.attrs.list,
19351
- ...ind
19352
- }, at);
19353
- case "quote": return doc.insertBlock("quote", ind.indent === void 0 ? void 0 : { ...ind }, at);
19354
- case "callout": return doc.insertBlock("callout", ind.indent === void 0 ? void 0 : { ...ind }, at);
19355
- case "code": return doc.insertBlock("code", command.attrs?.language === void 0 ? ind.indent === void 0 ? void 0 : { ...ind } : {
19356
- language: command.attrs.language,
19357
- ...ind
19358
- }, at);
19359
- case "divider": return doc.insertBlock("divider", ind.indent === void 0 ? void 0 : { ...ind }, at);
19360
- case "table": {
19361
- const tableId = doc.insertBlock("table", {
19362
- cols: 2,
19363
- columnWidths: [DEFAULT_TABLE_COLUMN_WIDTH, DEFAULT_TABLE_COLUMN_WIDTH],
19364
- ...ind
19365
- }, at);
19366
- for (let row = 0; row < 2; row++) {
19367
- const rowId = doc.insertBlock("table-row", void 0, { parent: tableId });
19368
- for (let col = 0; col < 2; col++) doc.insertBlock("table-cell", void 0, { parent: rowId });
19369
- }
19370
- return tableId;
19371
- }
19372
- default: throw new UnknownSlashCommandError(`Unknown slash command type "${command.type}".`);
19373
- }
19374
- }
19375
- /** The block snapshot's indent: a non-negative integer attr; absent is 0. */
19376
- function indentOf$1(block) {
19377
- if (!("attrs" in block)) return 0;
19378
- const indent = block.attrs?.indent;
19379
- return typeof indent === "number" && Number.isInteger(indent) && indent >= 0 ? indent : 0;
19380
- }
19381
- /**
19382
- * Hold the editor root's focus across a structural rebuild: the focused
19383
- * inner editable unmounts during the store-driven re-render, and the
19384
- * browser drops the focus to <body> until the next-frame caret re-seating
19385
- * lands. Focusing the (tabIndex -1) root before the rebuild keeps the
19386
- * focus — and the keyboard scope — inside the editor while the gap lasts
19387
- * (the root's keydown handler still owns the hotkeys).
19388
- */
19389
- function holdFocus(scope) {
19390
- if (scope instanceof HTMLElement && scope.isConnected) scope.focus({ preventScroll: true });
19391
- }
19392
- /**
19393
- * Execute the apply plan (one transaction for the non-replace kinds —
19394
- * one undo step, one wire update). The validation-first ordering stands:
19395
- * the type change / the attrs patch validate before the text deletion
19396
- * runs, so a rejected plan commits nothing.
19397
- */
19398
- function applySlashPlan(doc, plan, command, blockId, parentId, indent, scope) {
19399
- switch (plan.kind) {
19400
- case "noop": return;
19401
- case "replace":
19402
- doc.transact(() => {
19403
- const siblings = doc.getChildren(parentId);
19404
- const index = siblings.indexOf(blockId);
19405
- const after = index > 0 ? siblings[index - 1] : void 0;
19406
- doc.removeBlock(blockId);
19407
- const newId = insertCommand(doc, command, after === void 0 ? void 0 : {
19408
- parent: parentId,
19409
- after
19410
- }, indent);
19411
- let caretId = newId;
19412
- if (!BLOCK_REGISTRY[command.type].content) {
19413
- const sequence = doc.getChildren(parentId);
19414
- if (sequence[sequence.length - 1] === newId) caretId = doc.insertBlock("paragraph", void 0, {
19415
- parent: parentId,
19416
- after: newId
19417
- });
19418
- }
19419
- focusCaretIn(caretId, 0, scope);
19420
- });
19421
- holdFocus(scope);
19422
- return;
19423
- case "update":
19424
- case "convert": {
19425
- const attrs = "attrs" in command && command.attrs !== void 0 ? command.attrs : void 0;
19426
- let tableId = null;
19427
- try {
19428
- doc.transact(() => {
19429
- if (plan.kind === "convert") switch (command.type) {
19430
- case "paragraph":
19431
- doc.changeBlockType(blockId, "paragraph");
19432
- break;
19433
- case "heading":
19434
- doc.changeBlockType(blockId, "heading", command.attrs);
19435
- break;
19436
- case "list-item":
19437
- doc.changeBlockType(blockId, "list-item", command.attrs);
19438
- break;
19439
- case "quote":
19440
- doc.changeBlockType(blockId, "quote");
19441
- break;
19442
- case "callout":
19443
- doc.changeBlockType(blockId, "callout");
19444
- break;
19445
- case "code": doc.changeBlockType(blockId, "code", command.attrs);
19446
- }
19447
- else if (attrs !== void 0) doc.updateBlock(blockId, attrs);
19448
- doc.deleteText(blockId, plan.deleteFrom, plan.deleteTo);
19449
- if (command.type === "table") tableId = insertCommand(doc, command, {
19450
- parent: parentId,
19451
- after: blockId
19452
- }, indent);
19453
- else if (command.type === "divider") insertCommand(doc, command, {
19454
- parent: parentId,
19455
- after: blockId
19456
- }, indent);
19457
- });
19458
- } catch (error) {
19459
- if (error instanceof InvalidAttrsError || error instanceof InvalidOperationError) return;
19460
- throw error;
19461
- }
19462
- if (tableId !== null) {
19463
- const firstRow = doc.getChildren(tableId)[0];
19464
- const firstCell = firstRow === void 0 ? void 0 : doc.getChildren(firstRow)[0];
19465
- if (firstCell !== void 0) {
19466
- holdFocus(scope);
19467
- focusCellActivation(firstCell, scope);
19468
- return;
19469
- }
19470
- }
19471
- if (plan.kind === "convert") holdFocus(scope);
19472
- focusCaretIn(blockId, plan.deleteFrom, scope);
19473
- return;
19474
- }
19475
- default: return assertNever(plan);
19476
- }
19477
- }
19478
19506
  //#endregion
19479
19507
  //#region src/editing/slash/SlashMenu.tsx
19480
19508
  /** The slash menu's floating command list: a plain absolutely-positioned
@@ -29545,10 +29573,7 @@ function CodeHeader({ id, block, center }) {
29545
29573
  }
29546
29574
  //#endregion
29547
29575
  //#region src/blocks/table/constants.ts
29548
- /** The table block's constants (the handle / add-chip geometry, the drag
29549
- * thresholds and steps, the column-width floor). */
29550
29576
  const EMPTY_IDS = [];
29551
- const ADD_COLUMN_DRAG_STEP_PX = DEFAULT_TABLE_COLUMN_WIDTH;
29552
29577
  const ADD_BUTTON_CLASSES = "pointer-events-none opacity-0 transition-opacity group-hover:pointer-events-auto group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100";
29553
29578
  /** The table element's selector (the live DOM read — the commit and the
29554
29579
  * hover math, the row metrics' measurement). */
@@ -29565,7 +29590,7 @@ const HANDLE_DRAG_TRANSITION = "left 120ms ease-out, top 120ms ease-out";
29565
29590
  * the content anchors to the cursor, like a native context menu). The
29566
29591
  * gesture + the doc's commands stand over `use-table-cell-menu` +
29567
29592
  * `use-table-add-chips`. */
29568
- function TableFrameChrome({ viewMode, insertTableRow, onAddChipPointerDown, onAddChipPointerMove, onAddChipPointerUp, onAddChipPointerCancel, rowButtonLeft, addPreview, columnCount, rowCount, cellMenu }) {
29593
+ function TableFrameChrome({ tableWidth, rowMetrics, viewMode, insertTableRow, onAddChipPointerDown, onAddChipPointerMove, onAddChipPointerUp, onAddChipPointerCancel, rowButtonLeft, addPreview, columnCount, rowCount, cellMenu }) {
29569
29594
  const { t } = useTranslation("table");
29570
29595
  return /* @__PURE__ */ jsxs(Fragment$1, { children: [
29571
29596
  !viewMode && /* @__PURE__ */ jsx(Button, {
@@ -29583,11 +29608,26 @@ function TableFrameChrome({ viewMode, insertTableRow, onAddChipPointerDown, onAd
29583
29608
  style: { left: rowButtonLeft },
29584
29609
  children: /* @__PURE__ */ jsx(Plus, {})
29585
29610
  }),
29611
+ addPreview !== null && addPreview.kind === "row" && addPreview.count < 0 ? Array.from({ length: -addPreview.count }, (_, offset) => {
29612
+ const metrics = rowMetrics[rowCount - 1 - offset];
29613
+ if (metrics === void 0) return null;
29614
+ return /* @__PURE__ */ jsx("div", {
29615
+ "data-slot": "docblocks/table-row-remove",
29616
+ "aria-hidden": true,
29617
+ className: "pointer-events-none absolute bg-(--muted-foreground)/30",
29618
+ style: {
29619
+ left: 20,
29620
+ top: 20 + metrics.top,
29621
+ width: tableWidth,
29622
+ height: metrics.height
29623
+ }
29624
+ }, `remove-row-${offset}`);
29625
+ }) : null,
29586
29626
  addPreview !== null && addPreview.count !== 0 ? /* @__PURE__ */ jsx("div", {
29587
29627
  "data-slot": "docblocks/table-size",
29588
29628
  "aria-hidden": true,
29589
29629
  className: "pointer-events-none absolute top-0.5 left-1.5 text-xs text-(--muted-foreground) select-none",
29590
- children: `${addPreview.kind === "column" ? columnCount + addPreview.count : columnCount} × ${addPreview.kind === "row" ? rowCount + addPreview.count : rowCount}`
29630
+ children: `${addPreview.kind === "column" ? columnCount + addPreview.count : columnCount} × ${addPreview.kind === "row" ? rowCount + addPreview.count : rowCount} ${addPreview.count > 0 ? `+ ${addPreview.count}` : `− ${-addPreview.count}`}`
29591
29631
  }) : null,
29592
29632
  /* @__PURE__ */ jsxs(DropdownMenu, {
29593
29633
  modal: false,
@@ -29609,6 +29649,16 @@ function TableFrameChrome({ viewMode, insertTableRow, onAddChipPointerDown, onAd
29609
29649
  sideOffset: 4,
29610
29650
  onFocusOutside: preventDefault,
29611
29651
  children: [
29652
+ /* @__PURE__ */ jsx(DropdownMenuItem, {
29653
+ disabled: !cellMenu.canMerge,
29654
+ onSelect: cellMenu.onMergeCells,
29655
+ children: t("cell.merge")
29656
+ }),
29657
+ /* @__PURE__ */ jsx(DropdownMenuItem, {
29658
+ disabled: !cellMenu.canSplit,
29659
+ onSelect: cellMenu.onSplitCells,
29660
+ children: t("cell.split")
29661
+ }),
29612
29662
  /* @__PURE__ */ jsx(DropdownMenuItem, {
29613
29663
  onSelect: cellMenu.onCopy,
29614
29664
  children: t("common:copy")
@@ -29760,17 +29810,33 @@ function clampColumnWidth(width) {
29760
29810
  return Math.max(Math.round(width), 50);
29761
29811
  }
29762
29812
  /**
29763
- * The add chip's drag delta -> the count (positive = the add, negative =
29764
- * the remove): the nearest step's count (the rows' step 24 px, the
29765
- * columns' the base width 100 px); the floor clamps the removal to keep
29766
- * at least one row / column (the full removal is the handle's menu
29767
- * delete only — the paragraph conversion), the add stands unclamped (the
29768
- * travel's count is the intent).
29813
+ * The add chip's drag delta -> the count (positive = the add, negative = the
29814
+ * remove). The travel is measured in the ITEMS the reader sees: an add step
29815
+ * is one expected item's size, and a removal counts the items whose midpoint
29816
+ * the travel passed (so one row's worth of drag removes exactly one row,
29817
+ * whatever the rows' heights are). The removal keeps at least one row /
29818
+ * column (the full removal is the handle's menu delete only — the paragraph
29819
+ * conversion); the add stands unclamped (the travel's count is the intent).
29769
29820
  */
29770
- function addDragCount(kind, total, delta) {
29771
- const raw = Math.round(delta / (kind === "row" ? 24 : ADD_COLUMN_DRAG_STEP_PX));
29772
- if (raw >= 0) return raw;
29773
- return Math.max(1 - total, raw);
29821
+ function addDragCount(total, delta, steps) {
29822
+ const sizeOf = (index) => {
29823
+ const size = steps.sizes[index];
29824
+ return size !== void 0 && size > 0 ? size : steps.fallback;
29825
+ };
29826
+ if (delta >= 0) {
29827
+ const step = sizeOf(total - 1) > 0 ? sizeOf(total - 1) : steps.fallback;
29828
+ return step > 0 ? Math.round(delta / step) : 0;
29829
+ }
29830
+ const travelled = -delta;
29831
+ let passed = 0;
29832
+ let count = 0;
29833
+ for (let index = total - 1; index >= 0 && total - count > 1; index -= 1) {
29834
+ const size = sizeOf(index);
29835
+ if (travelled <= passed + size / 2) break;
29836
+ passed += size;
29837
+ count += 1;
29838
+ }
29839
+ return count === 0 ? 0 : -count;
29774
29840
  }
29775
29841
  //#endregion
29776
29842
  //#region src/blocks/table/HandleMenu.tsx
@@ -29984,8 +30050,8 @@ function seamXsOf(widths) {
29984
30050
  }
29985
30051
  //#endregion
29986
30052
  //#region src/blocks/table/TableHandles.tsx
29987
- function TableHandles({ tableId, widths, rows, rowMetrics, hover, menu, preview, columnCenters, onHandlePointerDown, onHandlePointerMove, onHandlePointerUp, onHandlePointerCancel, openHandleMenu, onMenuOpenChange, onColumnHandleAction, onRowHandleAction, onColumnHandleColor, onRowHandleColor, palette }) {
29988
- return /* @__PURE__ */ jsxs(Fragment$1, { children: [widths.map((_, index) => /* @__PURE__ */ jsx(HandleMenu, {
30053
+ function TableHandles({ lockedColumns, lockedRows, tableId, widths, rows, rowMetrics, hover, menu, preview, columnCenters, onHandlePointerDown, onHandlePointerMove, onHandlePointerUp, onHandlePointerCancel, openHandleMenu, onMenuOpenChange, onColumnHandleAction, onRowHandleAction, onColumnHandleColor, onRowHandleColor, palette }) {
30054
+ return /* @__PURE__ */ jsxs(Fragment$1, { children: [widths.map((_, index) => lockedColumns.has(index) ? null : /* @__PURE__ */ jsx(HandleMenu, {
29989
30055
  kind: "column",
29990
30056
  index,
29991
30057
  visible: isTablePreview(preview, "column", index) || hover?.col === index || menu !== null && menu.kind === "column" && menu.index === index,
@@ -30012,7 +30078,7 @@ function TableHandles({ tableId, widths, rows, rowMetrics, hover, menu, preview,
30012
30078
  onAction: onColumnHandleAction(index),
30013
30079
  onColor: onColumnHandleColor(index)
30014
30080
  })
30015
- }, `col-${index}`)), rows.map((rowId, rowIndex) => /* @__PURE__ */ jsx(HandleMenu, {
30081
+ }, `col-${index}`)), rows.map((rowId, rowIndex) => lockedRows.has(rowIndex) ? null : /* @__PURE__ */ jsx(HandleMenu, {
30016
30082
  kind: "row",
30017
30083
  index: rowIndex,
30018
30084
  visible: isTablePreview(preview, "row", rowIndex) || hover?.row === rowIndex || menu !== null && menu.kind === "row" && menu.index === rowIndex,
@@ -30150,6 +30216,247 @@ function CellActivation({ cellId }) {
30150
30216
  });
30151
30217
  }
30152
30218
  //#endregion
30219
+ //#region src/blocks/table/table-range-context.tsx
30220
+ /**
30221
+ * The table cell range's handlers over the table's subtree: the cells render
30222
+ * the corner grip and hand its pointer events to the table-level session
30223
+ * (`useTableCellRange`), so a cell needs no session state of its own.
30224
+ */
30225
+ const TableCellRangeContext = createContext(null);
30226
+ /** The table's range handlers; null outside a table (the grip never renders). */
30227
+ function useTableCellRangeHandlers() {
30228
+ return useContext(TableCellRangeContext);
30229
+ }
30230
+ //#endregion
30231
+ //#region src/blocks/table/use-table-cell-range.ts
30232
+ /**
30233
+ * The table cell range's session: the grip drag that selects a rectangle of
30234
+ * cells (the merge / split gesture's stand, the cell's text selection is
30235
+ * untouched). The range is view state — the store's `tableRange` slice — not
30236
+ * document data: it never travels the wire and the doc commands read it, not
30237
+ * the other way round.
30238
+ *
30239
+ * The gesture: a press on the hovered cell's corner grip starts the range at
30240
+ * that cell, the drag extends it over the cells under the pointer, the
30241
+ * release keeps it. Escape clears it. Every coordinate comes from the grid
30242
+ * resolver (a merged region stands one cell over several coordinates).
30243
+ */
30244
+ /** The anchor of the cell in the resolved grid (null for an unknown id). */
30245
+ function anchorOfId(doc, tableId, cellId) {
30246
+ const grid = resolveTableGrid(doc.raw, tableId);
30247
+ if (grid === null) return null;
30248
+ for (const line of grid.rows) for (const anchor of line) if (anchor.id === cellId) return anchor;
30249
+ return null;
30250
+ }
30251
+ /**
30252
+ * The range between two anchor cells: their rectangles' union. A region the
30253
+ * union touches joins it WHOLE (a selection never cuts a merged cell — a
30254
+ * cut rectangle would show a frame in the middle of a region and a merge
30255
+ * over it would take cells the reader did not select).
30256
+ */
30257
+ function rangeOfAnchors(doc, tableId, from, to) {
30258
+ const grid = resolveTableGrid(doc.raw, tableId);
30259
+ if (grid === null) return null;
30260
+ let top = Math.min(from.row, to.row);
30261
+ let left = Math.min(from.col, to.col);
30262
+ let bottom = Math.max(from.row + from.rowspan - 1, to.row + to.rowspan - 1);
30263
+ let right = Math.max(from.col + from.colspan - 1, to.col + to.colspan - 1);
30264
+ for (let guard = 0; guard < 8; guard += 1) {
30265
+ let grew = false;
30266
+ for (const anchor of grid.anchorsIn(top, left, bottom, right)) {
30267
+ if (anchor.row < top) {
30268
+ top = anchor.row;
30269
+ grew = true;
30270
+ }
30271
+ if (anchor.col < left) {
30272
+ left = anchor.col;
30273
+ grew = true;
30274
+ }
30275
+ if (anchor.row + anchor.rowspan - 1 > bottom) {
30276
+ bottom = anchor.row + anchor.rowspan - 1;
30277
+ grew = true;
30278
+ }
30279
+ if (anchor.col + anchor.colspan - 1 > right) {
30280
+ right = anchor.col + anchor.colspan - 1;
30281
+ grew = true;
30282
+ }
30283
+ }
30284
+ if (!grew) break;
30285
+ }
30286
+ const anchors = grid.anchorsIn(top, left, bottom, right);
30287
+ if (anchors.length === 0) return null;
30288
+ const cells = {};
30289
+ for (const anchor of anchors) cells[anchor.id] = {
30290
+ row: anchor.row,
30291
+ col: anchor.col,
30292
+ colspan: anchor.colspan,
30293
+ rowspan: anchor.rowspan
30294
+ };
30295
+ return {
30296
+ tableId,
30297
+ top,
30298
+ left,
30299
+ bottom,
30300
+ right,
30301
+ cellIds: anchors.map((anchor) => anchor.id),
30302
+ cells
30303
+ };
30304
+ }
30305
+ /**
30306
+ * The cell whose BOX holds the point: the geometry's stand, never the
30307
+ * top-most element — the table's chrome (the seams, the handles, the chips)
30308
+ * overlays the grid, and a covered region's interior boundary stands no cell
30309
+ * to hit. `null` when the point stands outside the cells.
30310
+ */
30311
+ function cellAtPoint(table, clientX, clientY) {
30312
+ if (table === null) return null;
30313
+ for (const td of table.querySelectorAll("td[data-block-id]")) {
30314
+ const box = td.getBoundingClientRect();
30315
+ if (box.width === 0 || box.height === 0) continue;
30316
+ if (clientX >= box.left && clientX <= box.right && clientY >= box.top && clientY <= box.bottom) return td.dataset.blockId ?? null;
30317
+ }
30318
+ return null;
30319
+ }
30320
+ /** The table cell range's slice for one table (null when the range stands elsewhere / nowhere). */
30321
+ function useTableRangeOf(tableId) {
30322
+ const { store } = useEditorContext();
30323
+ return useStore(store, (state) => state.tableRange?.tableId === tableId ? state.tableRange : null);
30324
+ }
30325
+ /**
30326
+ * The cell's range stand as a bitmask (a primitive — the selector keeps the
30327
+ * cells' re-render scope to their own membership / edges): the membership bit
30328
+ * and the frame's edges the cell stands on the rectangle's boundary.
30329
+ */
30330
+ function useTableCellRangeMask(cellId) {
30331
+ const { store } = useEditorContext();
30332
+ return useStore(store, (state) => {
30333
+ const range = state.tableRange;
30334
+ if (range === null) return 0;
30335
+ const rect = range.cells[cellId];
30336
+ if (rect === void 0) return 0;
30337
+ let mask = 1;
30338
+ if (rect.row === range.top) mask |= 2;
30339
+ if (rect.col === range.left) mask |= 16;
30340
+ if (rect.row + rect.rowspan - 1 === range.bottom) mask |= 8;
30341
+ if (rect.col + rect.colspan - 1 === range.right) mask |= 4;
30342
+ return mask;
30343
+ });
30344
+ }
30345
+ /** The range's setter (the clear stands `null`). */
30346
+ function useSetTableCellRange() {
30347
+ const { store } = useEditorContext();
30348
+ return useStore(store, (state) => state.setTableCellRange);
30349
+ }
30350
+ /** The grip's drag session over one table. */
30351
+ function useTableCellRange({ doc, tableId, tableEl }) {
30352
+ const setRange = useSetTableCellRange();
30353
+ const sessionRef = useRef(null);
30354
+ return {
30355
+ onGripPointerDown: useCallback((cellId) => (event) => {
30356
+ const anchor = anchorOfId(doc, tableId, cellId);
30357
+ if (anchor === null) return;
30358
+ event.preventDefault();
30359
+ event.stopPropagation();
30360
+ event.currentTarget.setPointerCapture(event.pointerId);
30361
+ sessionRef.current = {
30362
+ pointerId: event.pointerId,
30363
+ origin: anchor
30364
+ };
30365
+ setRange(rangeOfAnchors(doc, tableId, anchor, anchor));
30366
+ }, [
30367
+ doc,
30368
+ tableId,
30369
+ setRange
30370
+ ]),
30371
+ onGripPointerMove: useCallback((event) => {
30372
+ const session = sessionRef.current;
30373
+ if (session === null || session.pointerId !== event.pointerId) return;
30374
+ const cellId = cellAtPoint(tableEl(), event.clientX, event.clientY);
30375
+ if (cellId === null) return;
30376
+ const anchor = anchorOfId(doc, tableId, cellId);
30377
+ if (anchor === null) return;
30378
+ setRange(rangeOfAnchors(doc, tableId, session.origin, anchor));
30379
+ }, [
30380
+ doc,
30381
+ tableId,
30382
+ setRange,
30383
+ tableEl
30384
+ ]),
30385
+ onGripPointerUp: useCallback((event) => {
30386
+ const session = sessionRef.current;
30387
+ if (session === null || session.pointerId !== event.pointerId) return;
30388
+ sessionRef.current = null;
30389
+ if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId);
30390
+ }, []),
30391
+ clearRange: useCallback(() => setRange(null), [setRange])
30392
+ };
30393
+ }
30394
+ /**
30395
+ * The table's range wiring: the grip's handlers (the context value) and the
30396
+ * Escape cancel. The table component hands the handlers to the cells and
30397
+ * keeps the range's own read for the menu's stand.
30398
+ */
30399
+ function useTableCellRangeWiring({ doc, tableId, tableEl }) {
30400
+ const session = useTableCellRange({
30401
+ doc,
30402
+ tableId,
30403
+ tableEl
30404
+ });
30405
+ const rangeHandlers = useMemo(() => ({
30406
+ onGripPointerDown: session.onGripPointerDown,
30407
+ onGripPointerMove: session.onGripPointerMove,
30408
+ onGripPointerUp: session.onGripPointerUp
30409
+ }), [
30410
+ session.onGripPointerDown,
30411
+ session.onGripPointerMove,
30412
+ session.onGripPointerUp
30413
+ ]);
30414
+ const range = useTableRangeOf(tableId);
30415
+ const { clearRange } = session;
30416
+ const { store } = useEditorContext();
30417
+ const chromeStamp = useStore(store, (state) => state.chromeStamp);
30418
+ const stampRef = useRef(chromeStamp);
30419
+ useEffect(() => {
30420
+ if (stampRef.current === chromeStamp) return;
30421
+ stampRef.current = chromeStamp;
30422
+ if (range !== null && range.tableId === tableId) clearRange();
30423
+ }, [
30424
+ chromeStamp,
30425
+ range,
30426
+ tableId,
30427
+ clearRange
30428
+ ]);
30429
+ useEffect(() => {
30430
+ if (range === null) return;
30431
+ const onKeyDown = (event) => {
30432
+ if (event.key === "Escape") clearRange();
30433
+ };
30434
+ const onPointerDown = (event) => {
30435
+ const target = event.target;
30436
+ if (!(target instanceof Element)) return;
30437
+ const cell = target.closest("td[data-block-id]");
30438
+ if (cell !== null && cell.closest(`[data-block-id="${tableId}"]`) !== null) return;
30439
+ if (target.closest("[data-slot=\"docblocks/editor\"]") === null) return;
30440
+ if (cell === null && target.closest(`[data-block-id="${tableId}"]`) !== null) return;
30441
+ clearRange();
30442
+ };
30443
+ window.addEventListener("keydown", onKeyDown);
30444
+ document.addEventListener("pointerdown", onPointerDown);
30445
+ return () => {
30446
+ window.removeEventListener("keydown", onKeyDown);
30447
+ document.removeEventListener("pointerdown", onPointerDown);
30448
+ };
30449
+ }, [
30450
+ range,
30451
+ tableId,
30452
+ clearRange
30453
+ ]);
30454
+ return {
30455
+ rangeHandlers,
30456
+ range
30457
+ };
30458
+ }
30459
+ //#endregion
30153
30460
  //#region src/blocks/table/TableCell.tsx
30154
30461
  /** The table's cell renderer (the row / column drag's transform — the cell
30155
30462
  * is the transform's element: the `<tr>` is not a CSS transformable
@@ -30160,6 +30467,9 @@ function CellActivation({ cellId }) {
30160
30467
  const TableCell = memo(function TableCell({ id, dragX, dragShifted, rowDy, rowShifted }) {
30161
30468
  const cell = useBlock(id);
30162
30469
  const { viewMode } = useEditorContext();
30470
+ const rangeHandlers = useTableCellRangeHandlers();
30471
+ const rangeMask = useTableCellRangeMask(id);
30472
+ const selected = (rangeMask & 1) !== 0;
30163
30473
  const children = cell !== void 0 && cell.type === "table-cell" ? cell.children ?? EMPTY_IDS : EMPTY_IDS;
30164
30474
  const contextValue = useBlockContextValue(id, children, "table-cell");
30165
30475
  if (cell === void 0 || cell.type !== "table-cell") return null;
@@ -30168,6 +30478,7 @@ const TableCell = memo(function TableCell({ id, dragX, dragShifted, rowDy, rowSh
30168
30478
  const dragged = hasDrag && !dragShifted && !rowShifted;
30169
30479
  const style = {
30170
30480
  ...background !== void 0 ? { background } : {},
30481
+ ...selected && !dragged ? { background: "var(--docblocks-table-range-background)" } : {},
30171
30482
  ...dragged && background === void 0 ? { background: "var(--docblocks-table-drag-background, transparent)" } : {},
30172
30483
  ...dragged ? { boxShadow: "var(--docblocks-table-drag-shadow, none), inset 0 0 0 var(--docblocks-table-border-width) var(--docblocks-table-border-color)" } : {},
30173
30484
  ...hasDrag ? {
@@ -30177,23 +30488,47 @@ const TableCell = memo(function TableCell({ id, dragX, dragShifted, rowDy, rowSh
30177
30488
  transition: dragged ? void 0 : DRAG_TRANSITION
30178
30489
  } : {}
30179
30490
  };
30491
+ const frameEdges = [
30492
+ ...(rangeMask & 2) !== 0 ? [`inset 0 var(--docblocks-table-range-border-width) 0 0 var(--docblocks-table-range-border-color)`] : [],
30493
+ ...(rangeMask & 8) !== 0 ? [`inset 0 calc(-1 * var(--docblocks-table-range-border-width)) 0 0 var(--docblocks-table-range-border-color)`] : [],
30494
+ ...(rangeMask & 16) !== 0 ? [`inset var(--docblocks-table-range-border-width) 0 0 0 var(--docblocks-table-range-border-color)`] : [],
30495
+ ...(rangeMask & 4) !== 0 ? [`inset calc(-1 * var(--docblocks-table-range-border-width)) 0 0 0 var(--docblocks-table-range-border-color)`] : []
30496
+ ];
30497
+ if (frameEdges.length > 0) style.boxShadow = [style.boxShadow, ...frameEdges].filter((part) => part !== void 0 && part !== "").join(", ");
30180
30498
  const hasOwnText = (cell.content ?? []).some((run) => run.text !== "");
30499
+ const colspan = cell.attrs?.colspan;
30500
+ const rowspan = cell.attrs?.rowspan;
30181
30501
  return /* @__PURE__ */ jsx("td", {
30182
30502
  "data-slot": "docblocks/table-cell",
30183
30503
  "data-block-id": id,
30184
- className: "\n border-(length:--docblocks-table-border-width) border-(--docblocks-table-border-color)\n p-(--docblocks-table-cell-padding) align-top\n ",
30504
+ colSpan: colspan !== void 0 && colspan > 1 ? colspan : void 0,
30505
+ rowSpan: rowspan !== void 0 && rowspan > 1 ? rowspan : void 0,
30506
+ "data-range": selected ? "true" : void 0,
30507
+ className: "\n group/cell relative border-(length:--docblocks-table-border-width) border-(--docblocks-table-border-color)\n p-(--docblocks-table-cell-padding) align-top\n ",
30185
30508
  style,
30186
30509
  children: /* @__PURE__ */ jsxs(BlockContext.Provider, {
30187
30510
  value: contextValue,
30188
- children: [hasOwnText ? /* @__PURE__ */ jsx(CellContent, {
30189
- id,
30190
- block: cell
30191
- }) : null, children.length === 0 && !hasOwnText ? viewMode ? /* @__PURE__ */ jsx("span", {
30192
- "aria-hidden": true,
30193
- "data-slot": "docblocks/cell-empty",
30194
- className: "my-(--docblocks-block-spacing) block whitespace-pre-wrap",
30195
- children: "​"
30196
- }) : /* @__PURE__ */ jsx(CellActivation, { cellId: id }) : /* @__PURE__ */ jsx(BlockGroups, { ids: children })]
30511
+ children: [
30512
+ hasOwnText ? /* @__PURE__ */ jsx(CellContent, {
30513
+ id,
30514
+ block: cell
30515
+ }) : null,
30516
+ children.length === 0 && !hasOwnText ? viewMode ? /* @__PURE__ */ jsx("span", {
30517
+ "aria-hidden": true,
30518
+ "data-slot": "docblocks/cell-empty",
30519
+ className: "my-(--docblocks-block-spacing) block whitespace-pre-wrap",
30520
+ children: "​"
30521
+ }) : /* @__PURE__ */ jsx(CellActivation, { cellId: id }) : /* @__PURE__ */ jsx(BlockGroups, { ids: children }),
30522
+ rangeHandlers !== null && !viewMode ? /* @__PURE__ */ jsx("span", {
30523
+ "aria-hidden": true,
30524
+ "data-slot": "docblocks/table-cell-range-grip",
30525
+ className: "\n absolute top-1 right-1 size-2 cursor-crosshair rounded-full bg-(--docblocks-table-border-color) opacity-0\n transition-opacity\n group-hover/cell:opacity-100\n ",
30526
+ onPointerDown: rangeHandlers.onGripPointerDown(id),
30527
+ onPointerMove: rangeHandlers.onGripPointerMove,
30528
+ onPointerUp: rangeHandlers.onGripPointerUp,
30529
+ onPointerCancel: rangeHandlers.onGripPointerUp
30530
+ }) : null
30531
+ ]
30197
30532
  })
30198
30533
  });
30199
30534
  });
@@ -30288,11 +30623,12 @@ const TableRow = memo(function TableRow({ id, rowTransform, columnTransforms, di
30288
30623
  * and the add-column chip (the table's right edge). The add-row chip and
30289
30624
  * the size's stand stand at the frame's level (they stay pinned while the
30290
30625
  * content scrolls) — over the entry. */
30291
- function TableSeams({ widths, tableWidth, tableHeight, seamXs, resizePreview, addPreview, onSeamPointerDown, onSeamPointerMove, onSeamPointerUp, onSeamPointerCancel, onSeamKeyDown, onAddChipPointerDown, onAddChipPointerMove, onAddChipPointerUp, onAddChipPointerCancel, insertTableColumn }) {
30626
+ function TableSeams({ blockedSeams, widths, tableWidth, tableHeight, seamXs, resizePreview, addPreview, onSeamPointerDown, onSeamPointerMove, onSeamPointerUp, onSeamPointerCancel, onSeamKeyDown, onAddChipPointerDown, onAddChipPointerMove, onAddChipPointerUp, onAddChipPointerCancel, insertTableColumn }) {
30292
30627
  const { t } = useTranslation("table");
30293
30628
  return /* @__PURE__ */ jsxs(Fragment$1, { children: [
30294
30629
  widths.map((_, col) => {
30295
30630
  const seamIndex = col + 1;
30631
+ if (blockedSeams.has(seamIndex)) return null;
30296
30632
  const x = col + 1 < widths.length ? seamXs[seamIndex] ?? 20 + tableWidth : 20 + tableWidth;
30297
30633
  return /* @__PURE__ */ jsx("div", {
30298
30634
  "data-slot": "docblocks/table-col-resize",
@@ -30371,7 +30707,19 @@ function TableSeams({ widths, tableWidth, tableHeight, seamXs, resizePreview, ad
30371
30707
  }
30372
30708
  //#endregion
30373
30709
  //#region src/blocks/table/use-table-add-chips.ts
30374
- function useTableAddChips({ addSessionRef, sessionRef, resizeSessionRef, addDragClickRef, setAddPreview, doc, rows, block, id }) {
30710
+ function useTableAddChips({ rowHeights, columnWidths, addSessionRef, sessionRef, resizeSessionRef, addDragClickRef, setAddPreview, doc, rows, block, id }) {
30711
+ /** The drag's count over the session's kind: the rows' heights / the columns' widths drive the steps. */
30712
+ const dragCount = (session, dy, dx) => {
30713
+ const total = session.kind === "row" ? session.rows.length : session.cols;
30714
+ const steps = session.kind === "row" ? {
30715
+ sizes: rowHeights,
30716
+ fallback: 28
30717
+ } : {
30718
+ sizes: columnWidths,
30719
+ fallback: DEFAULT_TABLE_COLUMN_WIDTH
30720
+ };
30721
+ return addDragCount(total, session.kind === "row" ? dy : dx, steps);
30722
+ };
30375
30723
  const onAddChipPointerDown = (kind) => (event) => {
30376
30724
  if (event.button !== 0 || addSessionRef.current !== null || sessionRef.current !== null || resizeSessionRef.current !== null) return;
30377
30725
  event.currentTarget.setPointerCapture?.(event.pointerId);
@@ -30392,11 +30740,9 @@ function useTableAddChips({ addSessionRef, sessionRef, resizeSessionRef, addDrag
30392
30740
  const dy = event.clientY - session.startY;
30393
30741
  if (!session.dragging && (Math.abs(dx) > 4 || Math.abs(dy) > 4)) session.dragging = true;
30394
30742
  if (!session.dragging) return;
30395
- const total = session.kind === "row" ? session.rows.length : session.cols;
30396
- const delta = session.kind === "row" ? dy : dx;
30397
30743
  setAddPreview({
30398
30744
  kind: session.kind,
30399
- count: addDragCount(session.kind, total, delta)
30745
+ count: dragCount(session, dy, dx)
30400
30746
  });
30401
30747
  };
30402
30748
  const onAddChipPointerUp = (event) => {
@@ -30420,9 +30766,7 @@ function useTableAddChips({ addSessionRef, sessionRef, resizeSessionRef, addDrag
30420
30766
  * stale guard, the handle's contract) — no command, the rows resync.
30421
30767
  */
30422
30768
  const commitAddDrag = (session, clientX, clientY) => {
30423
- const total = session.kind === "row" ? session.rows.length : session.cols;
30424
- const delta = session.kind === "row" ? clientY - session.startY : clientX - session.startX;
30425
- const count = addDragCount(session.kind, total, delta);
30769
+ const count = dragCount(session, clientY - session.startY, clientX - session.startX);
30426
30770
  if (count === 0) return;
30427
30771
  const live = doc.getBlock(id);
30428
30772
  if (live === null || live.type !== "table") return;
@@ -30472,7 +30816,7 @@ function useTableAddChips({ addSessionRef, sessionRef, resizeSessionRef, addDrag
30472
30816
  * pointerup) and the menu's doc commands (the copy over the cell's plain
30473
30817
  * text, the paste over the clipboard's plain text, the clear over the
30474
30818
  * cell's own content + the children cascade). */
30475
- function useTableCellMenu({ doc, viewMode, frameRef }) {
30819
+ function useTableCellMenu({ doc, tableId, viewMode, frameRef }) {
30476
30820
  const [ctx, setCtx] = useState(null);
30477
30821
  const pendingCtxRef = useRef(null);
30478
30822
  /**
@@ -30525,6 +30869,47 @@ function useTableCellMenu({ doc, viewMode, frameRef }) {
30525
30869
  };
30526
30870
  };
30527
30871
  const cellScope = () => frameRef.current?.closest("[data-slot=\"docblocks/editor\"]") ?? document;
30872
+ const range = useTableRangeOf(tableId);
30873
+ const setRange = useSetTableCellRange();
30874
+ /** The clicked cell's merged region stand (`colspan`/`rowspan` over 1). */
30875
+ const clicked = ctx === null ? null : doc.getBlock(ctx.cellId);
30876
+ const clickedSpan = clicked !== null && clicked.type === "table-cell" ? Math.max(clicked.attrs?.colspan ?? 1, clicked.attrs?.rowspan ?? 1) : 1;
30877
+ /**
30878
+ * The merge stands over a rectangle the command accepts — the same
30879
+ * predicate the core reads, so the menu never offers a merge that would be
30880
+ * rejected (or, worse, would take cells outside the selection).
30881
+ */
30882
+ const canMerge = (() => {
30883
+ if (range === null || range.tableId !== tableId) return false;
30884
+ const grid = resolveTableGrid(doc.raw, tableId);
30885
+ return grid !== null && isMergeableRect(grid, range);
30886
+ })();
30887
+ /** The split stands over a merged cell (the clicked one or the range's). */
30888
+ const canSplit = clickedSpan > 1 || range !== null && range.cellIds.length === 1 && clickedSpan > 1;
30889
+ /** The merge: the selected rectangle folds into its top-left cell (one undo step); the range clears. */
30890
+ const onMergeCells = () => {
30891
+ if (!canMerge || range === null) return;
30892
+ try {
30893
+ doc.mergeTableCells(range.tableId, {
30894
+ row: range.top,
30895
+ col: range.left
30896
+ }, {
30897
+ row: range.bottom,
30898
+ col: range.right
30899
+ });
30900
+ } catch {}
30901
+ setRange(null);
30902
+ };
30903
+ /** The split: the merged region containing the clicked cell (or the range's cell) expands. */
30904
+ const onSplitCells = () => {
30905
+ if (ctx === null) return;
30906
+ const anchor = anchorOfId(doc, tableId, ctx.cellId);
30907
+ if (anchor === null) return;
30908
+ try {
30909
+ doc.splitTableCells(tableId, anchor.row, anchor.col);
30910
+ } catch {}
30911
+ setRange(null);
30912
+ };
30528
30913
  /** The copy: the cell's plain text to the clipboard (the blocks joined
30529
30914
  * with the line break); an unreadable clipboard stands a no-op (v1). */
30530
30915
  const onCellCopy = async () => {
@@ -30569,10 +30954,14 @@ function useTableCellMenu({ doc, viewMode, frameRef }) {
30569
30954
  }, []);
30570
30955
  return {
30571
30956
  ctx,
30572
- closeCtx,
30573
- onCellClear,
30574
- onCellCopy,
30575
- onCellPaste,
30957
+ canMerge,
30958
+ canSplit,
30959
+ onMergeCells,
30960
+ onSplitCells,
30961
+ onOpenChange: closeCtx,
30962
+ onCopy: onCellCopy,
30963
+ onPaste: onCellPaste,
30964
+ onClear: onCellClear,
30576
30965
  onTableContextMenu
30577
30966
  };
30578
30967
  }
@@ -30775,6 +31164,39 @@ function useTableHandleDrag({ sessionRef, setHover, setMenu, tableEl, doc, rows,
30775
31164
  };
30776
31165
  }
30777
31166
  //#endregion
31167
+ //#region src/blocks/table/use-table-hover.ts
31168
+ /**
31169
+ * The table's pointer hover: the grid coordinate of the cell under the
31170
+ * pointer (the handle zones read it — the row / column highlight and the
31171
+ * hover-revealed affordances). The coordinate comes from the grid resolver,
31172
+ * not the DOM: a merged cell stands one `<td>` over several columns, so
31173
+ * `cellIndex` would count the drawn cells instead of the grid's columns.
31174
+ */
31175
+ function useTableHover({ doc, tableId }) {
31176
+ const [hover, setHover] = useState(null);
31177
+ return {
31178
+ hover,
31179
+ onContentPointerMove: useCallback((event) => {
31180
+ const cell = event.target.closest("td[data-block-id]");
31181
+ if (cell === null) return;
31182
+ const row = cell.closest("tr[data-block-id]");
31183
+ if (row === null) return;
31184
+ const cellId = cell.dataset.blockId;
31185
+ const grid = cellId === void 0 ? null : resolveTableGrid(doc.raw, tableId);
31186
+ const anchor = grid === null || cellId === void 0 ? null : grid.rows.flat().find((candidate) => candidate.id === cellId) ?? null;
31187
+ const next = anchor !== null ? {
31188
+ row: anchor.row,
31189
+ col: anchor.col
31190
+ } : {
31191
+ row: row.rowIndex,
31192
+ col: cell.cellIndex
31193
+ };
31194
+ setHover((prev) => prev !== null && prev.row === next.row && prev.col === next.col ? prev : next);
31195
+ }, [doc, tableId]),
31196
+ setHover
31197
+ };
31198
+ }
31199
+ //#endregion
30778
31200
  //#region src/blocks/table/use-table-metrics.ts
30779
31201
  /** The table's live DOM metrics: the add-row chip's left offset (the
30780
31202
  * center of the visible part of the table) and the row handles' vertical
@@ -30788,7 +31210,10 @@ function useTableMetrics({ scrollRef, tableWidth, rows }) {
30788
31210
  useLayoutEffect(() => {
30789
31211
  const el = scrollRef.current;
30790
31212
  if (el === null) return;
30791
- const update = () => setRowButtonLeft(Math.max(0, Math.min(tableWidth, el.clientWidth) / 2 - 12));
31213
+ const update = () => {
31214
+ const visible = Math.max(0, Math.min(tableWidth, el.clientWidth - 20));
31215
+ setRowButtonLeft(20 + visible / 2 - 12);
31216
+ };
30792
31217
  update();
30793
31218
  if (typeof ResizeObserver === "function") {
30794
31219
  const observer = new ResizeObserver(update);
@@ -30817,10 +31242,53 @@ function useTableMetrics({ scrollRef, tableWidth, rows }) {
30817
31242
  ]);
30818
31243
  return {
30819
31244
  rowButtonLeft,
30820
- rowMetrics
31245
+ rowMetrics,
31246
+ tableHeight: rowMetrics.length > 0 ? rowMetrics[rowMetrics.length - 1].top + rowMetrics[rowMetrics.length - 1].height : 0,
31247
+ ghostRowHeight: rowMetrics[rowMetrics.length - 1]?.height ?? 28
30821
31248
  };
30822
31249
  }
30823
31250
  //#endregion
31251
+ //#region src/blocks/table/use-table-regions.ts
31252
+ /**
31253
+ * The table's merged regions over the renderer's chrome: the stands the chrome
31254
+ * must honour — no resize seam and no reorder handle on a region's interior,
31255
+ * and no handle to drag at all for a column / row the region spans (a reorder
31256
+ * through a region would shift its rectangle; the core rejects it, and the
31257
+ * chrome simply offers nothing).
31258
+ */
31259
+ /**
31260
+ * The region-derived chrome stands. The chrome stamp re-reads the grid over
31261
+ * any structural change: a merge moves the cells' attrs and the rows'
31262
+ * children, not the table's own block, so the table's snapshot alone would
31263
+ * not re-render this.
31264
+ */
31265
+ function useTableRegions({ doc, tableId }) {
31266
+ const { store } = useEditorContext();
31267
+ const chromeStamp = useStore(store, (state) => state.chromeStamp);
31268
+ return useMemo(() => {
31269
+ const grid = resolveTableGrid(doc.raw, tableId);
31270
+ const blockedSeams = /* @__PURE__ */ new Set();
31271
+ const lockedColumns = /* @__PURE__ */ new Set();
31272
+ const lockedRows = /* @__PURE__ */ new Set();
31273
+ for (const anchor of grid?.rows.flat() ?? []) {
31274
+ if (anchor.colspan > 1) {
31275
+ for (let col = anchor.col + 1; col < anchor.col + anchor.colspan; col += 1) blockedSeams.add(col);
31276
+ for (let col = anchor.col; col < anchor.col + anchor.colspan; col += 1) lockedColumns.add(col);
31277
+ }
31278
+ if (anchor.rowspan > 1) for (let row = anchor.row; row < anchor.row + anchor.rowspan; row += 1) lockedRows.add(row);
31279
+ }
31280
+ return {
31281
+ blockedSeams,
31282
+ lockedColumns,
31283
+ lockedRows
31284
+ };
31285
+ }, [
31286
+ doc,
31287
+ tableId,
31288
+ chromeStamp
31289
+ ]);
31290
+ }
31291
+ //#endregion
30824
31292
  //#region src/blocks/table/use-table-seam-resize.ts
30825
31293
  /** The table's column-seam resize: the seam's press + drag (the live
30826
31294
  * preview overrides the dragged column's width — no wire traffic until the
@@ -30901,6 +31369,26 @@ function useTableSeamResize({ docWidths, doc, id, resizeSessionRef }) {
30901
31369
  };
30902
31370
  }
30903
31371
  //#endregion
31372
+ //#region src/blocks/table/use-table-structure-guard.ts
31373
+ /**
31374
+ * The open menu's structural guard: a concurrent structural change (a peer's
31375
+ * insert / remove / move) invalidates the menu's index-based anchor, so the
31376
+ * menu closes (a re-anchored chip would act on the wrong target; a local
31377
+ * action closes the menu before the doc changes, so this fires on concurrent
31378
+ * changes only).
31379
+ */
31380
+ function useTableStructureGuard(structureKey, open, close) {
31381
+ const previous = useRef(structureKey);
31382
+ useLayoutEffect(() => {
31383
+ if (open && previous.current !== structureKey) close();
31384
+ previous.current = structureKey;
31385
+ }, [
31386
+ structureKey,
31387
+ open,
31388
+ close
31389
+ ]);
31390
+ }
31391
+ //#endregion
30904
31392
  //#region src/blocks/table/TableBlock.tsx
30905
31393
  /**
30906
31394
  * A table: one <tr> per row block, one <td> per cell; each cell renders
@@ -30941,29 +31429,35 @@ function TableBlock({ id, block }) {
30941
31429
  const widths = resizePreview !== null ? docWidths.map((width, i) => i === resizePreview.col - 1 ? resizePreview.width : width) : docWidths;
30942
31430
  const tableWidth = widths.reduce((sum, width) => sum + width, 0);
30943
31431
  const scrollRef = useRef(null);
30944
- const [hover, setHover] = useState(null);
30945
31432
  const [menu, setMenu] = useState(null);
30946
31433
  const sessionRef = useRef(null);
30947
31434
  const frameRef = useRef(null);
30948
31435
  const addSessionRef = useRef(null);
30949
31436
  const [addPreview, setAddPreview] = useState(null);
31437
+ const addDragClickRef = useRef(false);
31438
+ const { rowButtonLeft, rowMetrics, tableHeight, ghostRowHeight } = useTableMetrics({
31439
+ scrollRef,
31440
+ tableWidth,
31441
+ rows
31442
+ });
30950
31443
  const { insertTableColumn, insertTableRow, onAddChipPointerDown, onAddChipPointerMove, onAddChipPointerUp, onAddChipPointerCancel } = useTableAddChips({
31444
+ rowHeights: rowMetrics.map((row) => row.height),
31445
+ columnWidths: widths,
30951
31446
  addSessionRef,
30952
31447
  sessionRef,
30953
31448
  resizeSessionRef,
30954
- addDragClickRef: useRef(false),
31449
+ addDragClickRef,
30955
31450
  setAddPreview,
30956
31451
  doc,
30957
31452
  rows,
30958
31453
  block,
30959
31454
  id
30960
31455
  });
30961
- const { rowButtonLeft, rowMetrics } = useTableMetrics({
30962
- scrollRef,
30963
- tableWidth,
30964
- rows
30965
- });
30966
31456
  const tableEl = () => scrollRef.current?.querySelector("table[data-slot=\"docblocks/table\"]") ?? null;
31457
+ const { hover, onContentPointerMove, setHover } = useTableHover({
31458
+ doc,
31459
+ tableId: id
31460
+ });
30967
31461
  const { preview, onHandlePointerDown, onHandlePointerMove, onHandlePointerUp, onHandlePointerCancel } = useTableHandleDrag({
30968
31462
  sessionRef,
30969
31463
  setHover,
@@ -30974,19 +31468,14 @@ function TableBlock({ id, block }) {
30974
31468
  block,
30975
31469
  id
30976
31470
  });
30977
- const onContentPointerMove = (event) => {
30978
- const cell = event.target.closest("td[data-block-id]");
30979
- if (cell === null) return;
30980
- const row = cell.closest("tr[data-block-id]");
30981
- if (row === null) return;
30982
- const next = {
30983
- row: row.rowIndex,
30984
- col: cell.cellIndex
30985
- };
30986
- setHover((prev) => prev !== null && prev.row === next.row && prev.col === next.col ? prev : next);
30987
- };
30988
- const { ctx, closeCtx, onCellClear, onCellCopy, onCellPaste, onTableContextMenu } = useTableCellMenu({
31471
+ const { rangeHandlers } = useTableCellRangeWiring({
31472
+ doc,
31473
+ tableId: id,
31474
+ tableEl
31475
+ });
31476
+ const cellMenu = useTableCellMenu({
30989
31477
  doc,
31478
+ tableId: id,
30990
31479
  viewMode,
30991
31480
  frameRef
30992
31481
  });
@@ -30999,13 +31488,12 @@ function TableBlock({ id, block }) {
30999
31488
  });
31000
31489
  const columnCenters = columnCentersOf(widths);
31001
31490
  const seamXs = seamXsOf(widths);
31002
- const structureKey = `${block.columnOrder.length}:${rows.join(",")}`;
31003
- const prevStructureKey = useRef(structureKey);
31004
- useLayoutEffect(() => {
31005
- if (menu !== null && prevStructureKey.current !== structureKey) setMenu(null);
31006
- prevStructureKey.current = structureKey;
31007
- }, [structureKey, menu]);
31008
- const tableHeight = rowMetrics.length > 0 ? rowMetrics[rowMetrics.length - 1].top + rowMetrics[rowMetrics.length - 1].height : 0;
31491
+ const { blockedSeams, lockedColumns, lockedRows } = useTableRegions({
31492
+ doc,
31493
+ tableId: id
31494
+ });
31495
+ const closeMenuRef = () => setMenu(null);
31496
+ useTableStructureGuard(`${block.columnOrder.length}:${rows.join(",")}`, menu !== null, closeMenuRef);
31009
31497
  const columnTransforms = widths.map((_, index) => columnDragTransformOf(preview, index));
31010
31498
  const clearHover = () => setHover(null);
31011
31499
  const closeMenu = (open) => {
@@ -31033,25 +31521,30 @@ function TableBlock({ id, block }) {
31033
31521
  "data-block-id": id,
31034
31522
  className: "relative m-0 table-fixed border-collapse",
31035
31523
  style: { width: tableWidth },
31036
- onContextMenu: onTableContextMenu,
31037
- children: [/* @__PURE__ */ jsx("colgroup", { children: widths.map((width, index) => /* @__PURE__ */ jsx("col", { style: { width } }, index)) }), /* @__PURE__ */ jsx("tbody", { children: /* @__PURE__ */ jsxs(BlockContext.Provider, {
31038
- value: contextValue,
31039
- children: [rows.map((rowId, rowIndex) => /* @__PURE__ */ jsx(TableRow, {
31040
- id: rowId,
31041
- rowTransform: rowDragTransformOf(preview, rowIndex),
31042
- columnTransforms,
31043
- dimmed: addPreview !== null && addPreview.kind === "row" && addPreview.count < 0 && rowIndex >= rows.length + addPreview.count
31044
- }, rowId)), addPreview !== null && addPreview.kind === "row" && addPreview.count > 0 ? Array.from({ length: addPreview.count }, (_, i) => /* @__PURE__ */ jsx("tr", {
31045
- "aria-hidden": true,
31046
- "data-slot": "docblocks/table-ghost-row",
31047
- children: /* @__PURE__ */ jsx("td", {
31048
- colSpan: block.columnOrder.length,
31049
- className: "\n border-(length:--docblocks-table-border-width) border-dashed\n border-(--docblocks-table-border-color) bg-muted/40\n ",
31050
- style: { height: 28 }
31051
- })
31052
- }, `ghost-row-${i}`)) : null]
31524
+ onContextMenu: cellMenu.onTableContextMenu,
31525
+ children: [/* @__PURE__ */ jsx("colgroup", { children: widths.map((width, index) => /* @__PURE__ */ jsx("col", { style: { width } }, index)) }), /* @__PURE__ */ jsx("tbody", { children: /* @__PURE__ */ jsx(TableCellRangeContext.Provider, {
31526
+ value: rangeHandlers,
31527
+ children: /* @__PURE__ */ jsxs(BlockContext.Provider, {
31528
+ value: contextValue,
31529
+ children: [rows.map((rowId, rowIndex) => /* @__PURE__ */ jsx(TableRow, {
31530
+ id: rowId,
31531
+ rowTransform: rowDragTransformOf(preview, rowIndex),
31532
+ columnTransforms,
31533
+ dimmed: addPreview !== null && addPreview.kind === "row" && addPreview.count < 0 && rowIndex >= rows.length + addPreview.count
31534
+ }, rowId)), addPreview !== null && addPreview.kind === "row" && addPreview.count > 0 ? Array.from({ length: addPreview.count }, (_, i) => /* @__PURE__ */ jsx("tr", {
31535
+ "aria-hidden": true,
31536
+ "data-slot": "docblocks/table-ghost-row",
31537
+ children: /* @__PURE__ */ jsx("td", {
31538
+ colSpan: block.columnOrder.length,
31539
+ className: "\n border-(length:--docblocks-table-border-width) border-dashed\n border-(--docblocks-table-border-color) bg-muted/40\n ",
31540
+ style: { height: ghostRowHeight }
31541
+ })
31542
+ }, `ghost-row-${i}`)) : null]
31543
+ })
31053
31544
  }) })]
31054
31545
  }), !viewMode && /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx(TableHandles, {
31546
+ lockedColumns,
31547
+ lockedRows,
31055
31548
  tableId: id,
31056
31549
  widths,
31057
31550
  rows,
@@ -31072,6 +31565,7 @@ function TableBlock({ id, block }) {
31072
31565
  onRowHandleColor,
31073
31566
  palette
31074
31567
  }), /* @__PURE__ */ jsx(TableSeams, {
31568
+ blockedSeams,
31075
31569
  widths,
31076
31570
  tableWidth,
31077
31571
  tableHeight,
@@ -31099,15 +31593,11 @@ function TableBlock({ id, block }) {
31099
31593
  onAddChipPointerCancel,
31100
31594
  rowButtonLeft,
31101
31595
  addPreview,
31596
+ tableWidth,
31597
+ rowMetrics,
31102
31598
  columnCount: block.columnOrder.length,
31103
31599
  rowCount: rows.length,
31104
- cellMenu: {
31105
- ctx,
31106
- onOpenChange: closeCtx,
31107
- onCopy: onCellCopy,
31108
- onPaste: onCellPaste,
31109
- onClear: onCellClear
31110
- }
31600
+ cellMenu
31111
31601
  })]
31112
31602
  });
31113
31603
  }
@@ -34571,6 +35061,7 @@ function createEditorStore(doc, rootId) {
34571
35061
  presence: [],
34572
35062
  sharing: "off",
34573
35063
  canvasClipboard: null,
35064
+ tableRange: null,
34574
35065
  fileUpload: null,
34575
35066
  changeStamp: 0,
34576
35067
  chromeStamp: 0,
@@ -34583,6 +35074,7 @@ function createEditorStore(doc, rootId) {
34583
35074
  store.setState({ collapsedIds: collapsed ? [...ids.includes(id) ? ids : [...ids, id]] : ids.filter((x) => x !== id) });
34584
35075
  },
34585
35076
  setCanvasClipboard: (clipboard) => store.setState({ canvasClipboard: clipboard }),
35077
+ setTableCellRange: (range) => store.setState({ tableRange: range }),
34586
35078
  setFileUpload: (stand) => store.setState({ fileUpload: stand })
34587
35079
  }));
34588
35080
  return store;