@folijs/core 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/dist/model/schema.d.ts +9 -1
  3. package/dist/model/schema.d.ts.map +1 -1
  4. package/dist/model/schema.js +13 -3
  5. package/dist/model/schema.js.map +1 -1
  6. package/dist/state/commands.d.ts +8 -1
  7. package/dist/state/commands.d.ts.map +1 -1
  8. package/dist/state/commands.js +119 -38
  9. package/dist/state/commands.js.map +1 -1
  10. package/dist/state/comments.d.ts +47 -0
  11. package/dist/state/comments.d.ts.map +1 -0
  12. package/dist/state/comments.js +304 -0
  13. package/dist/state/comments.js.map +1 -0
  14. package/dist/state/editor.d.ts +42 -1
  15. package/dist/state/editor.d.ts.map +1 -1
  16. package/dist/state/editor.js +32 -2
  17. package/dist/state/editor.js.map +1 -1
  18. package/dist/state/history.d.ts +1 -1
  19. package/dist/state/history.d.ts.map +1 -1
  20. package/dist/state/history.js +3 -2
  21. package/dist/state/history.js.map +1 -1
  22. package/dist/state/index.d.ts +8 -2
  23. package/dist/state/index.d.ts.map +1 -1
  24. package/dist/state/index.js +8 -2
  25. package/dist/state/index.js.map +1 -1
  26. package/dist/state/links.d.ts.map +1 -1
  27. package/dist/state/links.js +30 -19
  28. package/dist/state/links.js.map +1 -1
  29. package/dist/state/mark.d.ts +5 -2
  30. package/dist/state/mark.d.ts.map +1 -1
  31. package/dist/state/mark.js +20 -3
  32. package/dist/state/mark.js.map +1 -1
  33. package/dist/state/pictures.d.ts +51 -0
  34. package/dist/state/pictures.d.ts.map +1 -0
  35. package/dist/state/pictures.js +140 -0
  36. package/dist/state/pictures.js.map +1 -0
  37. package/dist/state/review.d.ts +43 -0
  38. package/dist/state/review.d.ts.map +1 -0
  39. package/dist/state/review.js +361 -0
  40. package/dist/state/review.js.map +1 -0
  41. package/dist/state/selection.d.ts +12 -1
  42. package/dist/state/selection.d.ts.map +1 -1
  43. package/dist/state/selection.js +12 -0
  44. package/dist/state/selection.js.map +1 -1
  45. package/dist/state/state.d.ts +2 -0
  46. package/dist/state/state.d.ts.map +1 -1
  47. package/dist/state/state.js +8 -1
  48. package/dist/state/state.js.map +1 -1
  49. package/dist/state/tablecommands.d.ts +77 -0
  50. package/dist/state/tablecommands.d.ts.map +1 -0
  51. package/dist/state/tablecommands.js +675 -0
  52. package/dist/state/tablecommands.js.map +1 -0
  53. package/dist/state/tables.d.ts +110 -0
  54. package/dist/state/tables.d.ts.map +1 -0
  55. package/dist/state/tables.js +729 -0
  56. package/dist/state/tables.js.map +1 -0
  57. package/dist/state/track.d.ts +47 -0
  58. package/dist/state/track.d.ts.map +1 -0
  59. package/dist/state/track.js +583 -0
  60. package/dist/state/track.js.map +1 -0
  61. package/dist/state/word.d.ts +30 -2
  62. package/dist/state/word.d.ts.map +1 -1
  63. package/dist/state/word.js +83 -3
  64. package/dist/state/word.js.map +1 -1
  65. package/dist/state/wordclip.d.ts.map +1 -1
  66. package/dist/state/wordclip.js +26 -9
  67. package/dist/state/wordclip.js.map +1 -1
  68. package/dist/state/wordformat.d.ts +9 -1
  69. package/dist/state/wordformat.d.ts.map +1 -1
  70. package/dist/state/wordformat.js +38 -16
  71. package/dist/state/wordformat.js.map +1 -1
  72. package/dist/v3/document.d.ts +114 -7
  73. package/dist/v3/document.d.ts.map +1 -1
  74. package/dist/v3/document.js +170 -13
  75. package/dist/v3/document.js.map +1 -1
  76. package/dist/v3/index.d.ts +2 -2
  77. package/dist/v3/index.d.ts.map +1 -1
  78. package/dist/v3/index.js +2 -2
  79. package/dist/v3/index.js.map +1 -1
  80. package/dist/v3/migrate.d.ts +2 -2
  81. package/dist/v3/migrate.d.ts.map +1 -1
  82. package/dist/v3/resolve.d.ts +50 -4
  83. package/dist/v3/resolve.d.ts.map +1 -1
  84. package/dist/v3/resolve.js +205 -15
  85. package/dist/v3/resolve.js.map +1 -1
  86. package/dist/v3/schema.d.ts +6 -0
  87. package/dist/v3/schema.d.ts.map +1 -1
  88. package/dist/v3/schema.js +168 -6
  89. package/dist/v3/schema.js.map +1 -1
  90. package/package.json +1 -1
  91. package/src/model/schema.ts +18 -2
  92. package/src/state/commands.ts +110 -32
  93. package/src/state/comments.ts +342 -0
  94. package/src/state/editor.ts +97 -1
  95. package/src/state/history.ts +3 -2
  96. package/src/state/index.ts +74 -1
  97. package/src/state/links.ts +27 -17
  98. package/src/state/mark.ts +20 -3
  99. package/src/state/pictures.ts +168 -0
  100. package/src/state/review.ts +412 -0
  101. package/src/state/selection.ts +15 -1
  102. package/src/state/state.ts +8 -1
  103. package/src/state/tablecommands.ts +741 -0
  104. package/src/state/tables.ts +760 -0
  105. package/src/state/track.ts +659 -0
  106. package/src/state/word.ts +89 -4
  107. package/src/state/wordclip.ts +28 -11
  108. package/src/state/wordformat.ts +35 -13
  109. package/src/v3/document.ts +285 -14
  110. package/src/v3/index.ts +14 -0
  111. package/src/v3/migrate.ts +2 -2
  112. package/src/v3/resolve.ts +259 -15
  113. package/src/v3/schema.ts +190 -7
@@ -0,0 +1,675 @@
1
+ /**
2
+ * Table commands (10.7, ADR-0006): inserting a table, inserting and deleting rows and columns,
3
+ * deleting a table. They act on the table around the selection: the rectangle of a cell
4
+ * selection, or the cell holding the caret. Rows are inserted and deleted as tracked changes
5
+ * while tracking (the rebuild records them, 10.6a); column changes are not tracked by Foli yet,
6
+ * so they do not apply while tracking.
7
+ */
8
+ import { FoliDocumentError, Fragment, Slice } from "../model/index.js";
9
+ import { attempt } from "./attempt.js";
10
+ import { deleteSelectionKeepingTables } from "./commands.js";
11
+ import { closeHistory } from "./history.js";
12
+ import { MARK_ATTRS } from "./mark.js";
13
+ import { Selection } from "./selection.js";
14
+ import { CellSelection, cellDepth, coveringAt, coveringCell, emptyRowLike, gridOf, keepTablesApart, } from "./tables.js";
15
+ import { trackState } from "./track.js";
16
+ import { splitAttrs, withEnvelope, wordContext } from "./word.js";
17
+ import { ensureStyle } from "./wordformat.js";
18
+ /** Word's limits: 63 columns; rows are bounded here to keep a table insert reasonable. */
19
+ const MAX_COLUMNS = 63;
20
+ const MAX_ROWS = 1000;
21
+ /** Word's default page (Letter) and margins, in twips, when the section does not say. */
22
+ const PAGE_WIDTH = 12_240;
23
+ const MARGIN = 1_440;
24
+ const tracking = (state) => trackState(state)?.on === true;
25
+ /** Word's largest measure in twips (22 inches). */
26
+ const MAX_TWIPS = 31_680;
27
+ /** `attempt`, as its own undo step (never joined with the typing or command before it). */
28
+ const apply = (state, dispatch, build) => attempt(state, dispatch, (tr) => {
29
+ tr.setMeta(closeHistory, true);
30
+ build(tr);
31
+ });
32
+ /**
33
+ * An empty paragraph like a cell's last one (a cell always ends with a paragraph): its
34
+ * properties, not what only that paragraph has (its identity, revisions, section).
35
+ */
36
+ function emptyLike(cell, paragraph) {
37
+ const last = cell.lastChild;
38
+ if (last?.type !== paragraph)
39
+ return paragraph.create();
40
+ const own = Object.fromEntries(MARK_ATTRS.map((key) => [key, null]));
41
+ return paragraph.create({ ...last.attrs, ...own, attributes: null });
42
+ }
43
+ function around(state) {
44
+ const { selection } = state;
45
+ let cells;
46
+ let $cell;
47
+ if (selection instanceof CellSelection) {
48
+ cells = [...selection.cells];
49
+ $cell = selection.$anchor;
50
+ }
51
+ else {
52
+ const depth = cellDepth(selection.$from);
53
+ if (depth < 0)
54
+ return null;
55
+ const pos = selection.$from.before(depth);
56
+ cells = [pos];
57
+ $cell = state.doc.resolve(pos);
58
+ }
59
+ const tableDepth = $cell.depth - 1;
60
+ const table = $cell.node(tableDepth);
61
+ const pos = $cell.before(tableDepth);
62
+ const grid = gridOf(table, pos);
63
+ const chosen = grid.filter((c) => cells.includes(c.pos));
64
+ // A caret in a cell a merge covers: the merge's cell.
65
+ const covering = chosen.length ? undefined : coveringCell(table, pos, grid, cells[0]);
66
+ if (covering)
67
+ chosen.push(covering);
68
+ if (!chosen.length)
69
+ return null;
70
+ return {
71
+ table,
72
+ pos,
73
+ grid,
74
+ top: Math.min(...chosen.map((c) => c.row)),
75
+ bottom: Math.max(...chosen.map((c) => c.row + c.rowSpan - 1)),
76
+ left: Math.min(...chosen.map((c) => c.column)),
77
+ right: Math.max(...chosen.map((c) => c.column + c.span - 1)),
78
+ };
79
+ }
80
+ /** A row's cells with the grid column each starts at. */
81
+ function placed(row) {
82
+ const out = [];
83
+ let column = row.attrs.gridBefore ?? 0;
84
+ row.forEach((cell) => {
85
+ const span = cell.attrs.gridSpan ?? 1;
86
+ out.push({ cell, column, span });
87
+ column += span;
88
+ });
89
+ return out;
90
+ }
91
+ /** The position before row `index` of the table at `pos`. */
92
+ function rowPos(table, pos, index) {
93
+ let at = pos + 1;
94
+ for (let i = 0; i < index; i++)
95
+ at += table.child(i).nodeSize;
96
+ return at;
97
+ }
98
+ /** The caret at the start of the first paragraph of the cell at `cellPos`. */
99
+ const caretIn = (tr, cellPos) => tr.setSelection(Selection.near(tr.doc.resolve(cellPos + 1), 1));
100
+ /** The text width of the document's (last) section, in twips. */
101
+ function textWidth(state) {
102
+ const section = wordContext(state)?.envelope.section;
103
+ const width = section?.pageSize?.width ?? PAGE_WIDTH;
104
+ const { left = MARGIN, right = MARGIN, gutter = 0 } = section?.margins ?? {};
105
+ return Math.max(width - left - right - gutter, 1);
106
+ }
107
+ /**
108
+ * Inserts a table of `rows` × `columns` empty cells at the caret, as Word does: before the
109
+ * paragraph at its start, after it at its end, else between its two halves; a paragraph
110
+ * follows it where nothing would. Its columns share the text width; it has Word's "Table Grid"
111
+ * style (added to the document when missing). The caret goes into its first cell.
112
+ */
113
+ export function insertTable(rows, columns) {
114
+ return (state, dispatch) => {
115
+ const { table, tableRow, tableCell, paragraph } = state.schema.nodes;
116
+ const context = wordContext(state);
117
+ if (!table || !tableRow || !tableCell || !paragraph || !context)
118
+ return false;
119
+ const valid = (n, max) => Number.isInteger(n) && n >= 1 && n <= max;
120
+ if (!valid(rows, MAX_ROWS) || !valid(columns, MAX_COLUMNS))
121
+ return false;
122
+ if (!state.selection.$from.parent.isTextblock)
123
+ return false;
124
+ const each = Math.max(Math.floor(textWidth(state) / columns), 1);
125
+ const style = ensureStyle(context, "Table Grid", "table");
126
+ const cell = tableCell.create({ width: { value: each, type: "dxa" } }, paragraph.create());
127
+ const row = tableRow.create(null, Array.from({ length: columns }, () => cell));
128
+ const node = table.create({ style: style?.id ?? null, grid: Array.from({ length: columns }, () => each) }, Array.from({ length: rows }, () => row));
129
+ return apply(state, dispatch, (tr) => {
130
+ if (!tr.selection.empty)
131
+ deleteSelectionKeepingTables(tr);
132
+ const $pos = tr.selection.$from;
133
+ if (!$pos.parent.isTextblock)
134
+ throw new RangeError("No paragraph at the caret");
135
+ let at;
136
+ if ($pos.parentOffset === 0)
137
+ at = $pos.before();
138
+ // While tracking, after the paragraph: a tracked split would stay when the table is
139
+ // rejected.
140
+ else if ($pos.parentOffset === $pos.parent.content.size || tracking(state))
141
+ at = $pos.after();
142
+ else {
143
+ // As Enter splits: the first half gets a new paragraph mark, the second keeps it.
144
+ const { before, after } = splitAttrs(context, $pos.parent, false);
145
+ tr.split($pos.pos, 1, [{ type: $pos.parent.type, attrs: after }]);
146
+ if (before)
147
+ tr.setNodeMarkup($pos.before(), $pos.parent.type, before);
148
+ at = $pos.pos + 1;
149
+ }
150
+ // A paragraph after it where nothing follows (a cell's last block, the body's end).
151
+ const $at = tr.doc.resolve(at);
152
+ const last = $at.index() === $at.parent.childCount;
153
+ tr.insert(at, last ? Fragment.from([node, paragraph.create()]) : node);
154
+ keepTablesApart(tr);
155
+ if (style && style.envelope !== context.envelope)
156
+ withEnvelope(tr, style.envelope);
157
+ caretIn(tr, at + 2);
158
+ });
159
+ };
160
+ }
161
+ /**
162
+ * Inserts an empty row above the selection's first row (`dir` -1) or below its last (1), like
163
+ * that row (its cells' properties, no content); a vertical merge running across it goes on
164
+ * through the new row. While tracking, the row is a tracked insertion.
165
+ */
166
+ export function insertRow(dir) {
167
+ return (state, dispatch) => {
168
+ const found = around(state);
169
+ if (!found)
170
+ return false;
171
+ const { table, pos } = found;
172
+ const index = dir < 0 ? found.top : found.bottom;
173
+ const reference = table.child(index);
174
+ const plain = emptyRowLike(reference);
175
+ if (!plain)
176
+ return false;
177
+ // A merge goes on through the new row where the row past it continues it (below) or the
178
+ // reference row is itself continued (above).
179
+ const beyond = dir > 0 ? table.maybeChild(index + 1) : null;
180
+ const continued = new Set((dir > 0 ? (beyond ? placed(beyond) : []) : placed(reference))
181
+ .filter((p) => p.cell.attrs.vMerge === "continue")
182
+ .map((p) => p.column));
183
+ const cells = [];
184
+ const refPlaced = placed(reference);
185
+ plain.forEach((cell, _o, i) => {
186
+ const { column, cell: ref } = refPlaced[i];
187
+ const merged = continued.has(column) && ref.attrs.vMerge !== null;
188
+ cells.push(merged ? cell.type.create({ ...cell.attrs, vMerge: "continue" }, cell.content) : cell);
189
+ });
190
+ const row = plain.type.create(plain.attrs, cells);
191
+ const at = dir < 0 ? rowPos(table, pos, index) : rowPos(table, pos, index + 1);
192
+ return apply(state, dispatch, (tr) => {
193
+ tr.insert(at, row);
194
+ caretIn(tr, at + 1);
195
+ });
196
+ };
197
+ }
198
+ /**
199
+ * Deletes the selection's rows (the whole table when they are all its rows). A vertical merge
200
+ * starting in a deleted row goes on from the first row kept, with its content. While tracking,
201
+ * the rows are tracked deletions instead.
202
+ */
203
+ export const deleteRows = (state, dispatch) => {
204
+ const found = around(state);
205
+ if (!found)
206
+ return false;
207
+ const { table, pos, grid, top, bottom } = found;
208
+ if (top === 0 && bottom === table.childCount - 1)
209
+ return deleteTable(state, dispatch);
210
+ const from = rowPos(table, pos, top);
211
+ const to = rowPos(table, pos, bottom + 1);
212
+ return apply(state, dispatch, (tr) => {
213
+ const next = table.maybeChild(bottom + 1);
214
+ if (next && !tracking(state)) {
215
+ // Merges cut at their start: the first kept row's covered cell starts them again.
216
+ let cellPos = to + 1;
217
+ const starts = [];
218
+ for (const { cell, column } of placed(next)) {
219
+ if (cell.attrs.vMerge === "continue") {
220
+ const start = grid.find((c) => c.column === column &&
221
+ c.row >= top &&
222
+ c.row <= bottom &&
223
+ c.row + c.rowSpan > bottom + 1);
224
+ if (start)
225
+ starts.push({ pos: cellPos, from: start });
226
+ }
227
+ cellPos += cell.nodeSize;
228
+ }
229
+ for (const { pos: at, from: start } of starts.reverse()) {
230
+ const cell = tr.doc.nodeAt(at);
231
+ const first = state.doc.nodeAt(start.pos);
232
+ // The merge's cell as it was (its properties, its text, then any text the covered
233
+ // cell held, which Word does not show).
234
+ const content = cell.textContent ? first.content.append(cell.content) : first.content;
235
+ tr.setNodeMarkup(at, cell.type, { ...first.attrs, vMerge: "restart" });
236
+ tr.replace(at + 1, at + cell.nodeSize - 1, new Slice(content, 0, 0));
237
+ }
238
+ }
239
+ tr.delete(from, to);
240
+ // The row after the deleted ones, or the one before when they were the last.
241
+ const last = bottom === table.childCount - 1;
242
+ caretIn(tr, last ? rowPos(table, pos, top - 1) + 1 : tr.mapping.map(from) + 1);
243
+ });
244
+ };
245
+ /** Deletes the table around the selection (while tracking, its rows are tracked deletions). */
246
+ export const deleteTable = (state, dispatch) => {
247
+ const found = around(state);
248
+ if (!found)
249
+ return false;
250
+ const { table, pos } = found;
251
+ return apply(state, dispatch, (tr) => {
252
+ tr.delete(pos, pos + table.nodeSize);
253
+ keepTablesApart(tr);
254
+ tr.setSelection(Selection.near(tr.doc.resolve(tr.mapping.map(pos)), 1));
255
+ });
256
+ };
257
+ /** The table at `pos` rebuilt with each row passed through `row` (null: the row goes). */
258
+ function rebuild(table, attrs, row) {
259
+ const rows = [];
260
+ table.forEach((r, _o, i) => {
261
+ const next = row(r, i);
262
+ if (next)
263
+ rows.push(next);
264
+ });
265
+ return rows.length ? table.type.create(attrs, rows) : null;
266
+ }
267
+ /** A cell's `width` in twips set to the grid columns it spans, when it gives one in twips. */
268
+ function widthFor(attrs, grid, column, span) {
269
+ const width = attrs.width;
270
+ if (width?.type !== "dxa" || grid.length < column + span)
271
+ return attrs;
272
+ const value = grid.slice(column, column + span).reduce((a, b) => a + b, 0);
273
+ return { ...attrs, width: { value: Math.min(Math.max(value, 0), MAX_TWIPS), type: "dxa" } };
274
+ }
275
+ /** Replaces the table at `pos` with `next` and puts the caret in its cell at `row`, `column`. */
276
+ function replaceTable(tr, pos, old, next, row, column) {
277
+ tr.replace(pos, pos + old.nodeSize, new Slice(Fragment.from(next), 0, 0));
278
+ const grid = gridOf(next, pos);
279
+ const at = grid.find((c) => c.row <= row && row < c.row + c.rowSpan && c.column <= column && column < c.column + c.span) ?? grid[0];
280
+ if (at)
281
+ caretIn(tr, at.pos);
282
+ }
283
+ /**
284
+ * Inserts an empty column left of the selection's first column (`dir` -1) or right of its last
285
+ * (1), as wide as that column: a cell spanning the boundary grows by it; the new cells take
286
+ * their neighbour's properties (a vertical merge too). Not while tracking (Foli does not
287
+ * record column changes yet).
288
+ */
289
+ export function insertColumn(dir) {
290
+ return (state, dispatch) => {
291
+ if (tracking(state))
292
+ return false;
293
+ const found = around(state);
294
+ const paragraph = state.schema.nodes.paragraph;
295
+ if (!found || !paragraph)
296
+ return false;
297
+ const { table, pos, top } = found;
298
+ const at = dir < 0 ? found.left : found.right + 1;
299
+ const oldGrid = table.attrs.grid;
300
+ const columns = Math.max(oldGrid.length, ...found.grid.map((c) => c.column + c.span));
301
+ if (columns >= MAX_COLUMNS)
302
+ return false;
303
+ // A table without a grid (widths left to Word) keeps none.
304
+ const width = oldGrid[dir < 0 ? found.left : found.right] ?? 0;
305
+ const grid = oldGrid.length >= columns ? [...oldGrid.slice(0, at), width, ...oldGrid.slice(at)] : oldGrid;
306
+ const next = rebuild(table, { ...table.attrs, grid, gridExt: null }, (row) => {
307
+ const cells = placed(row);
308
+ const before = row.attrs.gridBefore ?? 0;
309
+ const end = cells.length
310
+ ? cells[cells.length - 1].column +
311
+ cells[cells.length - 1].span
312
+ : before;
313
+ if (at < before)
314
+ return row.type.create({ ...row.attrs, gridBefore: before + 1 }, row.content);
315
+ // Past the row's cells: its empty columns after them widen where they reach the new
316
+ // column's place; a row ending before it stays short (as Word leaves it).
317
+ if (at > end) {
318
+ const after = row.attrs.gridAfter ?? 0;
319
+ return at > end + after
320
+ ? row
321
+ : row.type.create({ ...row.attrs, gridAfter: after + 1 }, row.content);
322
+ }
323
+ const out = [];
324
+ // The neighbour on the selection's side: the cell starting at the boundary (left) or
325
+ // ending at it (right).
326
+ const neighbour = cells.find((c) => (dir < 0 ? c.column === at : c.column + c.span === at)) ??
327
+ cells.find((c) => c.column === at) ??
328
+ cells[cells.length - 1];
329
+ const fresh = (ref) => {
330
+ const first = ref.firstChild;
331
+ const own = first?.type === paragraph ? { ...first.attrs, attributes: null, revision: null } : null;
332
+ const attrs = widthFor({ ...ref.attrs, gridSpan: null }, grid, at, 1);
333
+ return ref.type.create(attrs, paragraph.create(own));
334
+ };
335
+ for (const c of cells) {
336
+ if (c.column < at && at < c.column + c.span) {
337
+ // Spans the boundary: one column wider.
338
+ out.push(c.cell.type.create(widthFor({ ...c.cell.attrs, gridSpan: c.span + 1 }, grid, c.column, c.span + 1), c.cell.content));
339
+ continue;
340
+ }
341
+ if (c.column === at && neighbour)
342
+ out.push(fresh(neighbour.cell));
343
+ out.push(c.cell);
344
+ }
345
+ if (at === end && neighbour)
346
+ out.push(fresh(neighbour.cell));
347
+ return row.type.create(row.attrs, out);
348
+ });
349
+ if (!next)
350
+ return false;
351
+ return apply(state, dispatch, (tr) => replaceTable(tr, pos, table, next, top, at));
352
+ };
353
+ }
354
+ /**
355
+ * Deletes the selection's columns (the whole table when they are all its columns): cells in
356
+ * them go, cells spanning into them narrow, a row left with no cell goes. Not while tracking.
357
+ */
358
+ export const deleteColumns = (state, dispatch) => {
359
+ if (tracking(state))
360
+ return false;
361
+ const found = around(state);
362
+ if (!found)
363
+ return false;
364
+ const { table, pos, top, left, right } = found;
365
+ const oldGrid = table.attrs.grid;
366
+ const width = Math.max(oldGrid.length, ...found.grid.map((c) => c.column + c.span));
367
+ if (left === 0 && right >= width - 1)
368
+ return deleteTable(state, dispatch);
369
+ const removed = right - left + 1;
370
+ const grid = [...oldGrid.slice(0, left), ...oldGrid.slice(right + 1)];
371
+ const overlap = (from, span) => Math.max(0, Math.min(from + span - 1, right) - Math.max(from, left) + 1);
372
+ const next = rebuild(table, { ...table.attrs, grid, gridExt: null }, (row) => {
373
+ const before = row.attrs.gridBefore ?? 0;
374
+ const cells = [];
375
+ let column = before - overlap(0, before);
376
+ for (const c of placed(row)) {
377
+ const span = c.span - overlap(c.column, c.span);
378
+ if (span <= 0)
379
+ continue;
380
+ cells.push(c.cell.type.create(widthFor({ ...c.cell.attrs, gridSpan: span > 1 ? span : null }, grid, column, span), c.cell.content));
381
+ column += span;
382
+ }
383
+ if (!cells.length)
384
+ return null;
385
+ const cellsEnd = placed(row).reduce((end, c) => Math.max(end, c.column + c.span), before);
386
+ const after = row.attrs.gridAfter ?? 0;
387
+ const afterLeft = after - overlap(cellsEnd, after);
388
+ return row.type.create({
389
+ ...row.attrs,
390
+ gridBefore: before - overlap(0, before) || null,
391
+ gridAfter: afterLeft || null,
392
+ }, cells);
393
+ });
394
+ if (!next)
395
+ return deleteTable(state, dispatch);
396
+ return apply(state, dispatch, (tr) => replaceTable(tr, pos, table, next, top, Math.min(left, width - removed - 1)));
397
+ };
398
+ // ---- Cells and properties (10.7b) --------------------------------------------------------------
399
+ /** A cell holding only one empty paragraph. */
400
+ const blank = (cell) => cell.childCount === 1 && !!cell.firstChild?.isTextblock && !cell.firstChild.content.size;
401
+ /**
402
+ * Merges the selected cells into one, as Word does: the rectangle's first cell spans its columns
403
+ * (`gridSpan`) and, over several rows, starts a vertical merge the rows below continue; it holds
404
+ * the text of every selected cell in order. Applies to a cell selection whose rectangle cells
405
+ * fill. Not while tracking.
406
+ */
407
+ export const mergeCells = (state, dispatch) => {
408
+ if (tracking(state) || !(state.selection instanceof CellSelection))
409
+ return false;
410
+ const found = around(state);
411
+ const paragraph = state.schema.nodes.paragraph;
412
+ if (!found || !paragraph)
413
+ return false;
414
+ const { table, pos, grid, top, bottom, left, right } = found;
415
+ const width = right - left + 1;
416
+ const inside = grid.filter((c) => c.row >= top && c.row <= bottom && c.column >= left && c.column <= right);
417
+ if (inside.length < 2)
418
+ return false;
419
+ // Every grid place of the rectangle has a cell (no row starts or ends inside it).
420
+ const area = inside.reduce((sum, c) => sum + c.span * c.rowSpan, 0);
421
+ if (area !== width * (bottom - top + 1))
422
+ return false;
423
+ // Every cell's blocks, row by row (a covered cell's own text too: nothing is dropped).
424
+ const content = [];
425
+ for (let r = top; r <= bottom; r++)
426
+ for (const c of placed(table.child(r)))
427
+ if (c.column >= left && c.column <= right && !blank(c.cell))
428
+ c.cell.forEach((block) => {
429
+ content.push(block);
430
+ });
431
+ if (!content.length || !content[content.length - 1]?.isTextblock)
432
+ content.push(paragraph.create());
433
+ const tableGrid = table.attrs.grid;
434
+ const next = rebuild(table, table.attrs, (row, r) => {
435
+ if (r < top || r > bottom)
436
+ return row;
437
+ const cells = [];
438
+ let merged = false;
439
+ for (const c of placed(row)) {
440
+ if (c.column < left || c.column > right) {
441
+ cells.push(c.cell);
442
+ continue;
443
+ }
444
+ if (merged)
445
+ continue;
446
+ merged = true;
447
+ const attrs = widthFor({
448
+ ...c.cell.attrs,
449
+ gridSpan: width > 1 ? width : null,
450
+ vMerge: bottom > top ? (r === top ? "restart" : "continue") : null,
451
+ }, tableGrid, left, width);
452
+ cells.push(c.cell.type.create(attrs, r === top ? Fragment.from(content) : emptyLike(c.cell, paragraph)));
453
+ }
454
+ return row.type.create(row.attrs, cells);
455
+ });
456
+ if (!next)
457
+ return false;
458
+ return apply(state, dispatch, (tr) => replaceTable(tr, pos, table, next, top, left));
459
+ };
460
+ /**
461
+ * Splits the selected merged cells back into their grid's cells (a horizontal span into one
462
+ * cell per column, a vertical merge into one cell per row); the text stays in the first.
463
+ * Applies where a selected cell is merged. Not while tracking.
464
+ */
465
+ export const splitCell = (state, dispatch) => {
466
+ if (tracking(state))
467
+ return false;
468
+ const found = around(state);
469
+ const paragraph = state.schema.nodes.paragraph;
470
+ if (!found || !paragraph)
471
+ return false;
472
+ const { table, pos, grid, top, bottom, left, right } = found;
473
+ const split = new Set(grid
474
+ .filter((c) => (c.span > 1 || c.rowSpan > 1) &&
475
+ c.row >= top &&
476
+ c.row <= bottom &&
477
+ c.column >= left &&
478
+ c.column <= right)
479
+ .map((c) => c.pos));
480
+ if (!split.size)
481
+ return false;
482
+ const tableGrid = table.attrs.grid;
483
+ const next = rebuild(table, table.attrs, (row, r) => {
484
+ const cells = [];
485
+ for (const c of placed(row)) {
486
+ const owner = coveringAt(grid, r, c.column);
487
+ if (!owner || !split.has(owner.pos)) {
488
+ cells.push(c.cell);
489
+ continue;
490
+ }
491
+ for (let i = 0; i < c.span; i++) {
492
+ const attrs = widthFor({ ...c.cell.attrs, gridSpan: null, vMerge: null }, tableGrid, c.column + i, 1);
493
+ // The merge's text stays in its first cell; a covered cell's own text (which Word does
494
+ // not show) stays in its cell.
495
+ const keep = i === 0 && (r === owner.row || !blank(c.cell));
496
+ cells.push(c.cell.type.create(attrs, keep ? c.cell.content : emptyLike(c.cell, paragraph)));
497
+ }
498
+ }
499
+ return row.type.create(row.attrs, cells);
500
+ });
501
+ if (!next)
502
+ return false;
503
+ return apply(state, dispatch, (tr) => replaceTable(tr, pos, table, next, top, left));
504
+ };
505
+ /** Whether the selection's rows are all header rows (repeated on each page). */
506
+ export function isHeaderRow(state) {
507
+ const found = around(state);
508
+ if (!found)
509
+ return false;
510
+ for (let r = found.top; r <= found.bottom; r++)
511
+ if (found.table.child(r).attrs.header !== true)
512
+ return false;
513
+ return true;
514
+ }
515
+ /**
516
+ * Makes the selection's rows header rows, with every row above them (Word repeats only a run of
517
+ * rows from the table's top), or, when they all are, makes them and the header rows below them
518
+ * ordinary rows. Not while tracking.
519
+ */
520
+ export const toggleHeaderRow = (state, dispatch) => {
521
+ if (tracking(state))
522
+ return false;
523
+ const found = around(state);
524
+ if (!found)
525
+ return false;
526
+ const { table, pos, top, bottom } = found;
527
+ const on = !isHeaderRow(state);
528
+ return apply(state, dispatch, (tr) => {
529
+ for (let r = 0; r < table.childCount; r++) {
530
+ const row = table.child(r);
531
+ const header = row.attrs.header === true;
532
+ const value = on ? (r <= bottom ? true : header) : r >= top ? false : header;
533
+ if (value !== header)
534
+ tr.setNodeMarkup(rowPos(table, pos, r), row.type, {
535
+ ...row.attrs,
536
+ header: value || null,
537
+ });
538
+ }
539
+ });
540
+ };
541
+ /** The table styles one can pick: the document's, with Word's Table Grid where it lacks it. */
542
+ export function tableStyles(state) {
543
+ const styles = wordContext(state)?.envelope.styles ?? [];
544
+ const names = styles.filter((s) => s.type === "table" && s.name).map((s) => s.name);
545
+ return names.some((n) => n.toLowerCase() === "table grid") ? names : [...names, "Table Grid"];
546
+ }
547
+ /** The name of the style of the table around the selection (null: none, or no table). */
548
+ export function tableStyleAt(state) {
549
+ // O(depth): the table above the selection's cell, not its grid (runs after every transaction).
550
+ const { selection } = state;
551
+ let table;
552
+ if (selection instanceof CellSelection)
553
+ table = selection.$anchor.node(selection.$anchor.depth - 1);
554
+ else {
555
+ const depth = cellDepth(selection.$from);
556
+ if (depth >= 0)
557
+ table = selection.$from.node(depth - 2);
558
+ }
559
+ const id = table?.attrs.style;
560
+ if (!id)
561
+ return null;
562
+ return wordContext(state)?.envelope.styles.find((s) => s.id === id)?.name ?? null;
563
+ }
564
+ /**
565
+ * Gives the table around the selection the table style named `name` (Word's Table Grid is
566
+ * added when missing; any other must exist), or none. Not while tracking.
567
+ */
568
+ export function setTableStyle(name) {
569
+ return (state, dispatch) => {
570
+ if (tracking(state))
571
+ return false;
572
+ const found = around(state);
573
+ const context = wordContext(state);
574
+ if (!found || !context)
575
+ return false;
576
+ const style = name === null ? null : ensureStyle(context, name, "table");
577
+ if (name !== null && !style)
578
+ return false;
579
+ // A built-in of another type (a heading's) is not a table style.
580
+ if (style && style.envelope.styles.find((s) => s.id === style.id)?.type !== "table")
581
+ return false;
582
+ const { table, pos } = found;
583
+ return apply(state, dispatch, (tr) => {
584
+ tr.setNodeMarkup(pos, table.type, { ...table.attrs, style: style?.id ?? null });
585
+ if (style && style.envelope !== context.envelope)
586
+ withEnvelope(tr, style.envelope);
587
+ });
588
+ };
589
+ }
590
+ /**
591
+ * Shades the selected cells with `fill` (`RRGGBB`), or takes their shading off (null). Not
592
+ * while tracking.
593
+ */
594
+ export function setCellShading(fill) {
595
+ return (state, dispatch) => {
596
+ if (tracking(state))
597
+ return false;
598
+ if (fill !== null && !/^[0-9A-Fa-f]{6}$/.test(fill))
599
+ return false;
600
+ const found = around(state);
601
+ if (!found)
602
+ return false;
603
+ const { table, pos, top, bottom, left, right } = found;
604
+ const shading = fill === null ? null : { pattern: "clear", color: "auto", fill: fill.toUpperCase() };
605
+ return apply(state, dispatch, (tr) => {
606
+ // Every cell of the rectangle, the ones a merge covers too: Word paints each row's part of
607
+ // a merged cell from its own properties.
608
+ for (let r = top; r <= bottom; r++) {
609
+ let at = rowPos(table, pos, r) + 1;
610
+ for (const c of placed(table.child(r))) {
611
+ if (c.column >= left && c.column <= right)
612
+ tr.setNodeMarkup(at, c.cell.type, { ...c.cell.attrs, shading });
613
+ at += c.cell.nodeSize;
614
+ }
615
+ }
616
+ });
617
+ };
618
+ }
619
+ /** The narrowest a column gets by dragging its border, in twips (0.1 inch). */
620
+ const MIN_COLUMN = 144;
621
+ /**
622
+ * Sets grid column `column` of the table at `pos` to `width` twips, as dragging its right border
623
+ * does in Word: the column after it gives or takes the difference (the table keeps its width),
624
+ * neither narrower than 0.1 inch; the last column's border widens or narrows the table. The
625
+ * widths in twips of the cells over those columns follow. Not while tracking.
626
+ */
627
+ export function setColumnWidth(pos, column, width) {
628
+ return (state, dispatch) => {
629
+ if (tracking(state))
630
+ return false;
631
+ const table = state.doc.nodeAt(pos);
632
+ if (table?.type.name !== "table" || !Number.isFinite(width))
633
+ return false;
634
+ const grid = [...table.attrs.grid];
635
+ const old = grid[column];
636
+ if (old === undefined)
637
+ return false;
638
+ const after = grid[column + 1];
639
+ // Two columns too narrow to give each other anything.
640
+ if (after !== undefined && old + after < 2 * MIN_COLUMN)
641
+ return false;
642
+ let next = Math.min(Math.max(Math.round(width), MIN_COLUMN), MAX_TWIPS);
643
+ if (after !== undefined)
644
+ next = Math.min(next, old + after - MIN_COLUMN);
645
+ if (next === old)
646
+ return false;
647
+ if (after !== undefined)
648
+ grid[column + 1] = after - (next - old);
649
+ grid[column] = next;
650
+ // The last column's border: a table width in twips grows or shrinks with it.
651
+ const tableWidth = table.attrs.width;
652
+ const widthAttr = after === undefined && tableWidth?.type === "dxa"
653
+ ? { value: Math.min(Math.max(tableWidth.value + next - old, 0), MAX_TWIPS), type: "dxa" }
654
+ : tableWidth;
655
+ let rebuilt;
656
+ try {
657
+ rebuilt = rebuild(table, { ...table.attrs, grid, gridExt: null, width: widthAttr }, (row) => row.type.create(row.attrs, placed(row).map((c) => c.cell.type.create(widthFor(c.cell.attrs, grid, c.column, c.span), c.cell.content))));
658
+ }
659
+ catch (error) {
660
+ // A grid the schema does not take (a width out of its range): the drag does not apply.
661
+ if (error instanceof FoliDocumentError)
662
+ return false;
663
+ throw error;
664
+ }
665
+ if (!rebuilt)
666
+ return false;
667
+ return apply(state, dispatch, (tr) => {
668
+ const selection = tr.selection.toJSON();
669
+ tr.replace(pos, pos + table.nodeSize, new Slice(Fragment.from(rebuilt), 0, 0));
670
+ // The same shape: the selection stays where it was.
671
+ tr.setSelection(Selection.fromJSON(tr.doc, selection));
672
+ });
673
+ };
674
+ }
675
+ //# sourceMappingURL=tablecommands.js.map