@mdbase-dev/ui 0.1.0-beta.164 → 0.1.0-beta.166

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.
@@ -0,0 +1,832 @@
1
+ import { syntaxTree } from "@codemirror/language";
2
+ import { EditorSelection, EditorState, Prec, RangeSet, Transaction } from "@codemirror/state";
3
+ import { BlockWrapper, Decoration, EditorView, ViewPlugin, WidgetType, keymap } from "@codemirror/view";
4
+ import { isRevealed, revealChanged } from "./reveal.js";
5
+ import { cellAt, cellClipboard, cellCorners, cellRange, clearBlock, clearCells, dispatchTableEdit, escapeCell, headerCells, insertRow, moveRow, parseGrid, pasteGrid, rangeCells, selectCells, tableAt, tableContext, tableEdit, tableModel, wholeTable } from "./table-model.js";
6
+ import { cellTarget, tableControls } from "./table-controls.js";
7
+ class EmptyCell extends WidgetType {
8
+ filler;
9
+ className;
10
+ constructor(filler, className) {
11
+ super();
12
+ this.filler = filler;
13
+ this.className = className;
14
+ }
15
+ eq(other) {
16
+ return other.filler === this.filler && other.className === this.className;
17
+ }
18
+ toDOM() {
19
+ const cell = document.createElement("span");
20
+ cell.className = this.className;
21
+ // A row shorter than its header is padded; a click there materializes the cell.
22
+ if (this.filler) cell.dataset.lpFill = "";else cell.dataset.lpEmpty = "";
23
+ return cell;
24
+ }
25
+ ignoreEvent() {
26
+ return false;
27
+ }
28
+ }
29
+ class LineBreak extends WidgetType {
30
+ eq() {
31
+ return true;
32
+ }
33
+ toDOM() {
34
+ return document.createElement("br");
35
+ }
36
+ }
37
+ const hide = Decoration.replace({});
38
+ const lineBreak = Decoration.replace({
39
+ widget: new LineBreak()
40
+ });
41
+ const grid = BlockWrapper.create({
42
+ tagName: "div",
43
+ attributes: {
44
+ class: "cm-lp-table"
45
+ },
46
+ rank: 0
47
+ });
48
+ // While a block of cells is selected, the text selection under it is not drawn.
49
+ const gridWithCells = BlockWrapper.create({
50
+ tagName: "div",
51
+ attributes: {
52
+ class: "cm-lp-table cm-lp-table-cells"
53
+ },
54
+ rank: 0
55
+ });
56
+ /** The frame carries what the rows' lines would have: a list's indent or a quote's fill. */
57
+ function frame(state, table, last) {
58
+ const quotes = (table.prefix.match(/>/g) ?? []).length;
59
+ const indent = table.prefix.replace(/>\s?/g, "").replace(/\t/g, " ").length;
60
+ let className = "cm-lp-table-frame";
61
+ if (quotes) {
62
+ className += " cm-lp-table-quote";
63
+ // The quote's last line may be the table's: then the frame closes the fill.
64
+ const next = last < state.doc.lines ? state.doc.line(last + 1).text : "";
65
+ if (!/^\s*>/.test(next)) className += " cm-lp-table-quote-last";
66
+ }
67
+ return BlockWrapper.create({
68
+ tagName: "div",
69
+ rank: 1,
70
+ attributes: {
71
+ class: className,
72
+ style: `--lp-table-indent: ${indent}ch; --lp-quote-depth: ${quotes}`
73
+ }
74
+ });
75
+ }
76
+ function cellClass(table, row, column, active, selected) {
77
+ const alignment = table.alignments[column];
78
+ return `cm-lp-td${table.rows[row].kind === "header" ? " cm-lp-th" : ""}${alignment && alignment !== "left" ? ` cm-lp-align-${alignment}` : ""}${active ? " cm-lp-td-active" : ""}${selected ? " cm-lp-td-selected" : ""}`;
79
+ }
80
+ function build(view) {
81
+ const {
82
+ state
83
+ } = view;
84
+ const decorations = [];
85
+ const cells = [];
86
+ const atomic = [];
87
+ const stops = new Set();
88
+ const wrappers = [];
89
+ const head = state.selection.main.head;
90
+ const range = cellRange(state);
91
+ const block = range && rangeCells(range);
92
+ let seen = -1;
93
+ for (const visible of view.visibleRanges) {
94
+ syntaxTree(state).iterate({
95
+ from: visible.from,
96
+ to: visible.to,
97
+ enter(node) {
98
+ if (node.name !== "Table") return;
99
+ if (node.from <= seen) return false;
100
+ seen = node.from;
101
+ const table = tableModel(state, node.node);
102
+ const selecting = range?.table.from === table.from ? block : null;
103
+ // Typing over a block of cells starts in its anchor, so that is the active cell.
104
+ const active = !view.hasFocus ? null : selecting ? range.anchor : head >= table.rows[0].lineFrom && head <= table.to ? cellAt(table, head) : null;
105
+ wrappers.push(frame(state, table, state.doc.lineAt(table.to).number).range(table.rows[0].lineFrom, table.to));
106
+ wrappers.push((selecting ? gridWithCells : grid).range(table.rows[0].lineFrom, table.to));
107
+ table.rows.forEach((row, rowIndex) => {
108
+ const kinds = `cm-lp-tr cm-lp-tr-${row.kind}${rowIndex === table.rows.length - 1 ? " cm-lp-tr-last" : ""}`;
109
+ decorations.push(Decoration.line({
110
+ class: kinds
111
+ }).range(row.lineFrom));
112
+ if (rowIndex > 0) atomic.push([table.rows[rowIndex - 1].to, row.from]);
113
+ if (row.kind === "delimiter") {
114
+ if (row.to > row.from) decorations.push(hide.range(row.from, row.to));
115
+ atomic.push([row.from, row.to]);
116
+ return;
117
+ }
118
+ let hiddenFrom = row.from;
119
+ const hideTo = to => {
120
+ if (to > hiddenFrom) decorations.push(hide.range(hiddenFrom, to));
121
+ if (to >= hiddenFrom) atomic.push([hiddenFrom, to]);
122
+ };
123
+ for (let column = 0; column < table.columns; column++) {
124
+ const cell = row.cells[column];
125
+ const className = cellClass(table, rowIndex, column, active?.row === rowIndex && active.column === column, !!selecting && selecting.rows.includes(rowIndex) && selecting.columns.includes(column));
126
+ if (!cell) {
127
+ cells.push(Decoration.widget({
128
+ widget: new EmptyCell(true, className),
129
+ side: 1
130
+ }).range(row.to));
131
+ continue;
132
+ }
133
+ // A space typed at the end of a cell is padding until text follows it. While the caret
134
+ // sits after it, it shows: hidden, the caret would land in the next cell.
135
+ const editing = !range && active?.row === rowIndex && active.column === column && head > cell.contentTo && head <= cell.to;
136
+ const end = editing ? head : cell.contentTo;
137
+ hideTo(cell.contentFrom);
138
+ if (cell.contentFrom === end) {
139
+ stops.add(cell.contentFrom);
140
+ cells.push(Decoration.widget({
141
+ widget: new EmptyCell(false, className),
142
+ side: 1
143
+ }).range(cell.contentFrom));
144
+ } else {
145
+ cells.push(Decoration.mark({
146
+ class: className,
147
+ inclusive: true
148
+ }).range(cell.contentFrom, end));
149
+ const revealed = active?.row === rowIndex && active.column === column && view.hasFocus;
150
+ const text = state.sliceDoc(cell.contentFrom, cell.contentTo);
151
+ for (const match of text.matchAll(/<br\s*\/?>/gi)) {
152
+ const from = cell.contentFrom + match.index;
153
+ if (!revealed || !isRevealed(state, from, from + match[0].length)) decorations.push(lineBreak.range(from, from + match[0].length));
154
+ }
155
+ }
156
+ hiddenFrom = end;
157
+ }
158
+ // Cells past the header's width are not part of the table.
159
+ hideTo(row.to);
160
+ });
161
+ }
162
+ });
163
+ }
164
+ atomic.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
165
+ const merged = [];
166
+ for (const [from, to] of atomic) {
167
+ const last = merged.at(-1);
168
+ // Touching ranges merge, except at an empty cell's only caret stop.
169
+ if (last && (from < last[1] || from === last[1] && !stops.has(from))) last[1] = Math.max(last[1], to);else if (to > from) merged.push([from, to]);
170
+ }
171
+ return {
172
+ decorations: Decoration.set(decorations, true),
173
+ cells: Decoration.set(cells, true),
174
+ atomic: RangeSet.of(merged.map(([from, to]) => hide.range(from, to))),
175
+ wrappers: BlockWrapper.set(wrappers, true)
176
+ };
177
+ }
178
+ const tableView = ViewPlugin.fromClass(class {
179
+ built;
180
+ constructor(view) {
181
+ this.built = build(view);
182
+ }
183
+ update(update) {
184
+ if (update.docChanged || update.viewportChanged || update.selectionSet || update.focusChanged || revealChanged(update) || syntaxTree(update.startState) !== syntaxTree(update.state)) this.built = build(update.view);
185
+ }
186
+ }, {
187
+ provide: plugin => [EditorView.decorations.of(view => view.plugin(plugin)?.built.decorations ?? Decoration.none),
188
+ // Cells must be the line's direct children for table layout, outside every inline mark.
189
+ EditorView.outerDecorations.of(view => view.plugin(plugin)?.built.cells ?? Decoration.none), EditorView.atomicRanges.of(view => view.plugin(plugin)?.built.atomic ?? RangeSet.empty), EditorView.blockWrappers.of(view => view.plugin(plugin)?.built.wrappers ?? RangeSet.empty)]
190
+ });
191
+ function cellSelection(view, table, row, column, select) {
192
+ const cell = table.rows[row].cells[column];
193
+ if (!cell) {
194
+ // GFM pads short rows. Materialize only the missing cells someone edits.
195
+ const target = table.rows[row];
196
+ const missing = column - target.cells.length + 1;
197
+ const insert = `${target.trailingPipe ? "" : " |"}${" |".repeat(missing)}`;
198
+ return dispatchTableEdit(view, {
199
+ changes: {
200
+ from: target.to,
201
+ insert
202
+ },
203
+ anchor: target.to + insert.length - 2
204
+ }, "input.table");
205
+ }
206
+ view.dispatch({
207
+ selection: EditorSelection.single(select ? cell.contentFrom : cell.contentTo, cell.contentTo),
208
+ scrollIntoView: true,
209
+ userEvent: "select"
210
+ });
211
+ return true;
212
+ }
213
+ function nextCell(view, direction) {
214
+ const context = tableContext(view.state);
215
+ if (!context) return false;
216
+ const {
217
+ table,
218
+ at
219
+ } = context;
220
+ const order = table.rows.flatMap((row, index) => row.kind === "delimiter" ? [] : [index]);
221
+ let position = order.indexOf(at.row) * table.columns + at.column + direction;
222
+ if (position < 0) return true;
223
+ if (position >= order.length * table.columns) {
224
+ // Tab past the last cell adds a row, as in a spreadsheet.
225
+ return dispatchTableEdit(view, insertRow(table, table.rows.length - 1));
226
+ }
227
+ return cellSelection(view, table, order[Math.floor(position / table.columns)], position % table.columns, true);
228
+ }
229
+ function isEmptyRow(state, table, row) {
230
+ return table.rows[row].cells.every(cell => cell.contentFrom === cell.contentTo || !state.sliceDoc(cell.contentFrom, cell.contentTo).trim());
231
+ }
232
+ function enter(view) {
233
+ const context = tableContext(view.state);
234
+ if (!context) return startTable(view);
235
+ const {
236
+ table,
237
+ at
238
+ } = context;
239
+ const first = table.rows[0];
240
+ if (at.row === 0 && at.column === 0 && view.state.selection.main.empty && view.state.selection.main.head <= (first.cells[0]?.contentFrom ?? first.from)) {
241
+ // At the table's very start, Enter opens a line above it, as in a word processor: otherwise
242
+ // a table at the top of a note, or straight after another block, has nothing in front of it.
243
+ const prefix = view.state.sliceDoc(first.lineFrom, first.from).trimEnd();
244
+ return dispatchTableEdit(view, {
245
+ changes: {
246
+ from: first.lineFrom,
247
+ insert: `${prefix}\n`
248
+ },
249
+ anchor: first.lineFrom + prefix.length
250
+ });
251
+ }
252
+ const last = table.rows.length - 1;
253
+ if (at.row === last && table.rows[last].kind === "body" && isEmptyRow(view.state, table, last)) {
254
+ // Enter on an empty last row leaves the table, like an empty list item.
255
+ // In GFM a line straight after a table joins it, so the caret lands past a blank line.
256
+ const {
257
+ doc
258
+ } = view.state;
259
+ const row = doc.lineAt(table.to);
260
+ const next = row.number < doc.lines ? doc.line(row.number + 1) : null;
261
+ const insert = next && next.text.trim() ? "\n\n\n" : "\n\n";
262
+ const previous = table.rows[last - 1];
263
+ return dispatchTableEdit(view, {
264
+ changes: {
265
+ from: previous.to,
266
+ to: row.to,
267
+ insert
268
+ },
269
+ anchor: previous.to + 2
270
+ });
271
+ }
272
+ if (at.row < last) {
273
+ const row = at.row === 0 ? 2 : at.row + 1;
274
+ if (row <= last) return cellSelection(view, table, row, at.column, false);
275
+ }
276
+ const edit = insertRow(table, at.row);
277
+ return dispatchTableEdit(view, {
278
+ ...edit,
279
+ anchor: edit.anchor + 3 * at.column
280
+ });
281
+ }
282
+ function insertBelow(view) {
283
+ const context = tableContext(view.state);
284
+ if (!context) return false;
285
+ const edit = insertRow(context.table, context.at.row);
286
+ return dispatchTableEdit(view, {
287
+ ...edit,
288
+ anchor: edit.anchor + 3 * context.at.column
289
+ });
290
+ }
291
+ /** `| a | b |` then Enter writes the delimiter and a first row. */
292
+ function startTable(view) {
293
+ const {
294
+ state
295
+ } = view;
296
+ const selection = state.selection.main;
297
+ if (!selection.empty || state.selection.ranges.length !== 1) return false;
298
+ const line = state.doc.lineAt(selection.head);
299
+ if (selection.head !== line.to) return false;
300
+ const pipe = line.text.indexOf("|");
301
+ if (pipe < 0) return false;
302
+ const before = line.text.slice(0, pipe);
303
+ if (!/^[\s>]*$/.test(before)) return false;
304
+ const cells = headerCells(line.text.slice(pipe));
305
+ const node = syntaxTree(state).resolveInner(line.from, 1);
306
+ if (!cells || node.name !== "Paragraph" && node.name !== "Document" && node.name !== "Blockquote") return false;
307
+ if (line.number > 1 && state.doc.line(line.number - 1).text.trim() && !/^[\s>]*$/.test(state.doc.line(line.number - 1).text)) return false;
308
+ const delimiter = `${before}| ${cells.map(() => "---").join(" | ")} |`;
309
+ const row = `${before}| ${cells.map(() => "").join(" | ")} |`;
310
+ const anchor = line.to + 1 + delimiter.length + 1 + before.length + 2;
311
+ return dispatchTableEdit(view, {
312
+ changes: {
313
+ from: line.to,
314
+ insert: `\n${delimiter}\n${row}`
315
+ },
316
+ anchor
317
+ });
318
+ }
319
+ function cellBoundary(view, side, extend) {
320
+ const context = tableContext(view.state);
321
+ if (!context) return false;
322
+ const cell = context.table.rows[context.at.row].cells[context.at.column];
323
+ if (!cell) return false;
324
+ const target = side < 0 ? cell.contentFrom : cell.contentTo;
325
+ const {
326
+ anchor,
327
+ head
328
+ } = view.state.selection.main;
329
+ if (head === target && !extend) return false;
330
+ view.dispatch({
331
+ selection: EditorSelection.single(extend ? anchor : target, target),
332
+ scrollIntoView: true,
333
+ userEvent: "select"
334
+ });
335
+ return true;
336
+ }
337
+ function backspaceRow(view) {
338
+ const context = tableContext(view.state);
339
+ if (!context || !view.state.selection.main.empty) return false;
340
+ const {
341
+ table,
342
+ at
343
+ } = context;
344
+ const cell = table.rows[at.row].cells[at.column];
345
+ if (at.column !== 0 || !cell || view.state.selection.main.head !== cell.contentFrom) return false;
346
+ // An empty row goes away from its first cell, like an empty list item.
347
+ if (table.rows[at.row].kind === "body" && isEmptyRow(view.state, table, at.row)) {
348
+ const previous = table.rows[at.row - 1];
349
+ const target = previous.kind === "delimiter" ? table.rows[0] : previous;
350
+ const last = target.cells[Math.min(target.cells.length, table.columns) - 1];
351
+ return dispatchTableEdit(view, {
352
+ changes: {
353
+ from: previous.to,
354
+ to: table.rows[at.row].to
355
+ },
356
+ anchor: last?.contentTo ?? target.to
357
+ }, "delete.table");
358
+ }
359
+ return true;
360
+ }
361
+ function shiftRow(view, direction) {
362
+ const context = tableContext(view.state);
363
+ if (!context) return false;
364
+ return dispatchTableEdit(view, moveRow(view.state, context.table, context.at.row, context.at.row + direction), "move.table") || true;
365
+ }
366
+ const segments = table => table.rows.flatMap(row => row.kind === "delimiter" ? [] : row.cells.slice(0, table.columns));
367
+ /** Keeps typing, deleting, cutting and dropping inside cells, so no edit breaks a row apart. */
368
+ function protectRows(transaction) {
369
+ if (!transaction.docChanged || transaction.annotation(tableEdit) || !(transaction.isUserEvent("input") || transaction.isUserEvent("delete") || transaction.isUserEvent("move"))) return transaction;
370
+ const state = transaction.startState;
371
+ const range = cellRange(state);
372
+ if (range && !wholeRows(state, range.table)) return replaceCells(transaction, range);
373
+ const changes = [];
374
+ let rewritten = false;
375
+ let caret = null;
376
+ let caretText = 0;
377
+ transaction.changes.iterChanges((fromA, toA, _fromB, _toB, inserted) => {
378
+ const text = inserted.toString();
379
+ const table = tableAt(state, fromA) ?? (toA > fromA ? tableAt(state, toA) : null);
380
+ const start = table?.rows[0].lineFrom ?? 0;
381
+ if (!table || toA < start || fromA > table.to) {
382
+ changes.push({
383
+ from: fromA,
384
+ to: toA,
385
+ insert: text
386
+ });
387
+ return;
388
+ }
389
+ const rowStarts = new Set(table.rows.map(row => row.lineFrom));
390
+ const rowEnds = new Set(table.rows.map(row => row.to));
391
+ // Whole rows, or the whole table, go as people selected them.
392
+ const whole = (rowStarts.has(fromA) || fromA === start) && (rowStarts.has(toA) || toA === table.to + 1 || toA === table.to && fromA === start) || rowEnds.has(fromA) && (rowEnds.has(toA) || toA === table.to) && toA > fromA && !text;
393
+ if (whole) {
394
+ changes.push({
395
+ from: fromA,
396
+ to: toA,
397
+ insert: text
398
+ });
399
+ return;
400
+ }
401
+ const cells = segments(table);
402
+ const inside = cells.find(cell => fromA >= cell.from && toA <= cell.to);
403
+ const escaped = escapeCell(text);
404
+ if (inside && escaped === text) {
405
+ changes.push({
406
+ from: fromA,
407
+ to: toA,
408
+ insert: text
409
+ });
410
+ return;
411
+ }
412
+ rewritten = true;
413
+ const touched = cells.filter(cell => cell.to >= fromA && cell.from <= toA);
414
+ // Across cells, only text goes: padding and pipes stay, so a row never loses a column.
415
+ for (const cell of touched) {
416
+ const from = inside ? fromA : Math.max(cell.contentFrom, fromA),
417
+ to = inside ? toA : Math.min(cell.contentTo, toA);
418
+ if (to > from) changes.push({
419
+ from,
420
+ to
421
+ });
422
+ }
423
+ if (escaped) {
424
+ // Text typed on structure lands in the nearest cell's content.
425
+ const target = inside ?? touched[0] ?? cells.find(cell => cell.from >= fromA) ?? cells.at(-1);
426
+ const at = inside ? fromA : Math.max(target.contentFrom, Math.min(fromA, target.contentTo));
427
+ changes.push({
428
+ from: at,
429
+ insert: escaped
430
+ });
431
+ caret = at;
432
+ caretText = escaped.length;
433
+ } else caret = touched[0] ? Math.max(touched[0].contentFrom, fromA) : fromA;
434
+ });
435
+ if (!rewritten) return transaction;
436
+ const set = state.changes(changes);
437
+ // Deleting only structure, such as Backspace at a cell's start, does nothing.
438
+ if (set.empty) return {};
439
+ const anchor = caret === null ? set.mapPos(state.selection.main.head) : set.mapPos(caret, -1) + caretText;
440
+ return {
441
+ changes: set,
442
+ selection: EditorSelection.cursor(Math.min(anchor, set.newLength)),
443
+ annotations: tableEdit.of(true),
444
+ userEvent: transaction.annotation(Transaction.userEvent),
445
+ scrollIntoView: true
446
+ };
447
+ }
448
+ /** Whether the selection is whole rows, from a row's start to another's: those go as rows, not cell by cell. */
449
+ function wholeRows(state, table) {
450
+ const {
451
+ from,
452
+ to
453
+ } = state.selection.main;
454
+ const starts = table.rows.map(row => row.lineFrom);
455
+ return (starts.includes(from) || from === table.rows[0].lineFrom) && (starts.includes(to) || to === table.to + 1 || to === table.to && from === table.rows[0].lineFrom);
456
+ }
457
+ /** Typing or deleting over a block of cells empties them; typed text goes in the anchor cell, as in a spreadsheet. */
458
+ function replaceCells(transaction, range) {
459
+ const state = transaction.startState;
460
+ const start = range.table.rows[0].lineFrom;
461
+ let inserted = "",
462
+ outside = false;
463
+ transaction.changes.iterChanges((fromA, toA, _fromB, _toB, text) => {
464
+ if (fromA < start || toA > range.table.to) outside = true;
465
+ inserted += text.toString();
466
+ });
467
+ // A change past the table, such as dropped text, is not an edit of these cells.
468
+ if (outside) return transaction;
469
+ const text = escapeCell(inserted);
470
+ const anchor = range.table.rows[range.anchor.row].cells[range.anchor.column];
471
+ const userEvent = transaction.annotation(Transaction.userEvent);
472
+ // After deleting, the emptied block stays selected; after typing, the caret follows the text.
473
+ if (!text || !anchor) return clearBlock(state, range, userEvent) ?? {};
474
+ const set = state.changes([...clearCells(state, range), {
475
+ from: anchor.contentFrom,
476
+ insert: text
477
+ }]);
478
+ return {
479
+ changes: set,
480
+ selection: EditorSelection.cursor(set.mapPos(anchor.contentFrom, -1) + text.length),
481
+ annotations: tableEdit.of(true),
482
+ userEvent,
483
+ scrollIntoView: true
484
+ };
485
+ }
486
+ /** Steps a block of cells' head; from inside a single cell, only leaving it by an edge starts a block. */
487
+ function extendCells(view, rows, columns) {
488
+ const range = cellRange(view.state);
489
+ let table, anchor, head;
490
+ if (range) ({
491
+ table,
492
+ anchor,
493
+ head
494
+ } = range);else {
495
+ const context = tableContext(view.state);
496
+ if (!context) return false;
497
+ const cell = context.table.rows[context.at.row].cells[context.at.column];
498
+ const position = view.state.selection.main.head;
499
+ if (cell && (columns > 0 && position < cell.contentTo || columns < 0 && position > cell.contentFrom)) return false;
500
+ ({
501
+ table
502
+ } = context);
503
+ anchor = head = context.at;
504
+ }
505
+ const order = table.rows.flatMap((row, index) => row.kind === "delimiter" ? [] : [index]);
506
+ const row = order[order.indexOf(head.row) + rows];
507
+ const column = head.column + columns;
508
+ if (row === undefined || column < 0 || column >= table.columns) return !!range;
509
+ view.dispatch({
510
+ ...selectCells(table, anchor, {
511
+ row,
512
+ column
513
+ }),
514
+ scrollIntoView: true,
515
+ userEvent: "select"
516
+ });
517
+ return true;
518
+ }
519
+ /** Select-all inside a table takes the table first, then the note. */
520
+ function selectTable(view) {
521
+ const context = tableContext(view.state);
522
+ if (!context) return false;
523
+ const all = wholeTable(context.table);
524
+ const block = selectCells(context.table, all.anchor, all.head);
525
+ if (block.selection.eq(view.state.selection)) return false;
526
+ view.dispatch({
527
+ ...block,
528
+ userEvent: "select"
529
+ });
530
+ return true;
531
+ }
532
+ function copyCells(event, view) {
533
+ const range = cellRange(view.state);
534
+ if (!range || !event.clipboardData) return false;
535
+ const {
536
+ markdown,
537
+ html
538
+ } = cellClipboard(view.state, range);
539
+ event.preventDefault();
540
+ event.clipboardData.setData("text/plain", markdown);
541
+ event.clipboardData.setData("text/html", html);
542
+ if (event.type === "cut" && !view.state.readOnly) {
543
+ const {
544
+ from,
545
+ to
546
+ } = view.state.selection.main;
547
+ view.dispatch({
548
+ changes: {
549
+ from,
550
+ to
551
+ },
552
+ userEvent: "delete.cut"
553
+ });
554
+ }
555
+ return true;
556
+ }
557
+ /** Text in a pasted HTML cell, keeping its line breaks as `<br>`. */
558
+ function htmlCellText(cell) {
559
+ const breakMark = "\uE000";
560
+ for (const element of cell.querySelectorAll("br")) element.replaceWith(breakMark);
561
+ for (const element of cell.querySelectorAll("p, div, li")) element.append(breakMark);
562
+ return escapeCell((cell.textContent ?? "").split(breakMark).map(line => line.replace(/\s+/g, " ").trim()).filter(Boolean).join("\n"));
563
+ }
564
+ /** A clipboard holding just one HTML table, as browsers, spreadsheets and documents copy them. */
565
+ function htmlGrid(html) {
566
+ if (!/<table[\s>]/i.test(html)) return null;
567
+ const document_ = new DOMParser().parseFromString(html, "text/html");
568
+ // Spreadsheets put their styles in the clipboard's body.
569
+ for (const element of document_.querySelectorAll("style, script, template")) element.remove();
570
+ const tables = document_.querySelectorAll("table");
571
+ const visible = node => (node.textContent ?? "").replace(/\s+/g, "").length;
572
+ if (tables.length !== 1 || visible(document_.body) > visible(tables[0])) return null;
573
+ const grid = [...tables[0].rows].map(row => [...row.cells].map(htmlCellText)).filter(row => row.length);
574
+ return grid.length ? grid : null;
575
+ }
576
+ /** A new Markdown table from a grid, on its own lines so nothing around it joins it. */
577
+ function insertTable(view, grid) {
578
+ const {
579
+ state
580
+ } = view;
581
+ const {
582
+ from,
583
+ to
584
+ } = state.selection.main;
585
+ const width = Math.max(...grid.map(row => row.length));
586
+ const line = cells => `| ${Array.from({
587
+ length: width
588
+ }, (_, index) => cells[index] ?? "").join(" | ")} |`;
589
+ const table = [line(grid[0]), line(Array(width).fill("---")), ...grid.slice(1).map(line)].join("\n");
590
+ const first = state.doc.lineAt(from),
591
+ last = state.doc.lineAt(to);
592
+ const textBefore = !!state.sliceDoc(first.from, from).trim(),
593
+ textAfter = !!state.sliceDoc(to, last.to).trim();
594
+ const lineBefore = first.number > 1 && !!state.doc.line(first.number - 1).text.trim();
595
+ const lineAfter = last.number < state.doc.lines && !!state.doc.line(last.number + 1).text.trim();
596
+ const before = textBefore ? "\n\n" : lineBefore ? "\n" : "";
597
+ const after = textAfter ? "\n\n" : lineAfter ? "\n" : "";
598
+ view.dispatch({
599
+ changes: {
600
+ from,
601
+ to,
602
+ insert: before + table + after
603
+ },
604
+ selection: {
605
+ anchor: from + before.length + table.length
606
+ },
607
+ scrollIntoView: true,
608
+ userEvent: "input.paste"
609
+ });
610
+ return true;
611
+ }
612
+ /**
613
+ * A caret at a cell's edge borders a hidden pipe, which has no box: measured on that side, the
614
+ * caret sits at the top of the window and scrolling into view jumps there. Bind it to the cell's side.
615
+ */
616
+ function caretSide(transaction) {
617
+ if (!transaction.selection && !transaction.docChanged) return transaction;
618
+ const {
619
+ state
620
+ } = transaction;
621
+ const {
622
+ main
623
+ } = state.selection;
624
+ if (!main.empty || state.selection.ranges.length !== 1) return transaction;
625
+ const table = tableAt(state, main.head);
626
+ const at = table && main.head >= table.rows[0].lineFrom && main.head <= table.to ? cellAt(table, main.head) : null;
627
+ const cell = at && table.rows[at.row].cells[at.column];
628
+ if (!cell) return transaction;
629
+ // An empty cell's caret stop is the widget after it; text ends before the caret.
630
+ const side = cell.contentFrom === cell.contentTo && main.head === cell.contentFrom ? 1 : main.head >= cell.contentTo ? -1 : main.head <= cell.contentFrom ? 1 : 0;
631
+ if (!side || main.assoc === side) return transaction;
632
+ return [transaction, {
633
+ selection: EditorSelection.create([EditorSelection.cursor(main.head, side)]),
634
+ sequential: true
635
+ }];
636
+ }
637
+ function paste(event, view) {
638
+ if (view.state.readOnly || !event.clipboardData) return false;
639
+ const text = event.clipboardData.getData("text/plain");
640
+ const html = event.clipboardData.getData("text/html");
641
+ const range = cellRange(view.state);
642
+ const context = range ? null : tableContext(view.state);
643
+ if (range || context) {
644
+ const grid = parseGrid(text) ?? htmlGrid(html);
645
+ // One value into one cell is plain typing; over a block, protectRows puts it in the anchor cell.
646
+ if (!grid || grid.length === 1 && grid[0].length < 2) return false;
647
+ event.preventDefault();
648
+ const at = range ? {
649
+ row: rangeCells(range).rows[0],
650
+ column: rangeCells(range).columns[0]
651
+ } : context.at;
652
+ return dispatchTableEdit(view, pasteGrid(view.state, range?.table ?? context.table, at, grid), "input.paste.table");
653
+ }
654
+ // Outside a table, an HTML table becomes a Markdown table, unless the text already is one.
655
+ if (parseGrid(text) && /^\s*\|/.test(text)) return false;
656
+ const grid = htmlGrid(html);
657
+ if (!grid) return false;
658
+ event.preventDefault();
659
+ return insertTable(view, grid);
660
+ }
661
+ /** Typing over a block of cells goes through protectRows, not the browser's edit of the text under it. */
662
+ function typeOverCells(event, view) {
663
+ if (!cellRange(view.state) || view.state.readOnly) return false;
664
+ const typing = event.inputType === "insertText" && event.data;
665
+ const deleting = event.inputType.startsWith("delete");
666
+ if (!typing && !deleting) return false;
667
+ event.preventDefault();
668
+ const {
669
+ from,
670
+ to
671
+ } = view.state.selection.main;
672
+ view.dispatch({
673
+ changes: {
674
+ from,
675
+ to,
676
+ insert: typing ? event.data : ""
677
+ },
678
+ userEvent: typing ? "input.type" : "delete"
679
+ });
680
+ return true;
681
+ }
682
+ /** Empty cells hold no text to hit, so a click there places the caret explicitly. */
683
+ /** A press on a missing cell materializes it; the drag that follows is `cellDrag`'s. */
684
+ function clickCell(event, view) {
685
+ if (event.button !== 0 || event.shiftKey || !(event.target instanceof Element) || view.state.readOnly) return false;
686
+ const filler = event.target.closest("[data-lp-fill]");
687
+ const target = filler && cellTarget(view, filler);
688
+ const table = target && tableAt(view.state, target.tableFrom);
689
+ if (table) cellSelection(view, table, target.at.row, target.at.column, false);
690
+ return false;
691
+ }
692
+ /** The block a pointer drag last selected, so its transaction can carry the block's corners. */
693
+ let pointerBlock = null;
694
+ /**
695
+ * A drag from a cell selects by the cells under the pointer, so empty and missing cells, which
696
+ * have no text to hit, can be a block's corners. Within one cell it selects that cell's text.
697
+ */
698
+ function cellDrag(view, start) {
699
+ if (start.button !== 0 || start.detail !== 1 || start.shiftKey || start.altKey || start.ctrlKey || start.metaKey) return null;
700
+ let origin = cellTarget(view, start.target instanceof Element ? start.target : null);
701
+ if (!origin) return null;
702
+ const textAt = (table, at, x, y) => {
703
+ const cell = table.rows[at.row].cells[at.column];
704
+ return cell ? Math.max(cell.contentFrom, Math.min(view.posAtCoords({
705
+ x,
706
+ y
707
+ }, false), cell.contentTo)) : table.rows[at.row].to;
708
+ };
709
+ let table = tableAt(view.state, origin.tableFrom);
710
+ let anchor = textAt(table, origin.at, start.clientX, start.clientY);
711
+ let last = origin.at;
712
+ return {
713
+ get(event) {
714
+ pointerBlock = null;
715
+ const {
716
+ clientX: x,
717
+ clientY: y
718
+ } = event;
719
+ const element = view.root.elementFromPoint(x, y);
720
+ const here = cellTarget(view, element);
721
+ if (here?.tableFrom === origin.tableFrom) last = here.at;
722
+ // Between cells, the block holds; past the table, the selection is text again.
723
+ else if (here || !element?.closest(".cm-lp-table")) return EditorSelection.single(anchor, view.posAtCoords({
724
+ x,
725
+ y
726
+ }, false));
727
+ if (last.row === origin.at.row && last.column === origin.at.column) return EditorSelection.single(anchor, textAt(table, last, x, y));
728
+ pointerBlock = selectCells(table, origin.at, last);
729
+ return pointerBlock.selection;
730
+ },
731
+ update(update) {
732
+ if (!update.docChanged) return false;
733
+ anchor = update.changes.mapPos(anchor);
734
+ origin = {
735
+ ...origin,
736
+ tableFrom: update.changes.mapPos(origin.tableFrom)
737
+ };
738
+ const next = tableAt(update.state, origin.tableFrom);
739
+ if (next) table = next;
740
+ return false;
741
+ }
742
+ };
743
+ }
744
+ /** Tables edit in place: the Markdown rows are laid out as the grid, so the caret, undo, IME and search are the editor's own. */
745
+ /**
746
+ * At a cell's end the view puts the DOM caret after the cell, among the hidden pipe
747
+ * spans, and the browser then types into the next visible cell. Keep it in the text.
748
+ */
749
+ function keepCaretInCell(update) {
750
+ const {
751
+ view
752
+ } = update;
753
+ if (!(update.selectionSet || update.docChanged) || !view.hasFocus) return;
754
+ const selection = view.root.getSelection?.();
755
+ const line = selection?.isCollapsed ? selection.anchorNode : null;
756
+ if (!(line instanceof HTMLElement) || !line.classList.contains("cm-lp-tr")) return;
757
+ let cell = line.childNodes[selection.anchorOffset - 1] ?? null;
758
+ while (cell && !(cell instanceof HTMLElement && cell.classList.contains("cm-lp-td"))) {
759
+ if (cell instanceof HTMLElement && cell.offsetParent !== null) return;
760
+ cell = cell.previousSibling;
761
+ }
762
+ if (!cell || view.posAtDOM(cell, cell.childNodes.length) !== view.state.selection.main.head) return;
763
+ const walker = document.createTreeWalker(cell, NodeFilter.SHOW_TEXT);
764
+ let text = null;
765
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) text = node;
766
+ if (text) selection.collapse(text, text.textContent.length);
767
+ }
768
+ export function tablePreview() {
769
+ return [tableView, EditorView.updateListener.of(keepCaretInCell), EditorState.transactionFilter.of(protectRows), EditorState.transactionFilter.of(caretSide), cellCorners, EditorState.transactionExtender.of(transaction => pointerBlock && transaction.isUserEvent("select.pointer") && transaction.selection?.eq(pointerBlock.selection) ? {
770
+ effects: pointerBlock.effects
771
+ } : null), EditorView.mouseSelectionStyle.of(cellDrag), Prec.highest(keymap.of([{
772
+ key: "Tab",
773
+ run: view => nextCell(view, 1)
774
+ }, {
775
+ key: "Shift-Tab",
776
+ run: view => nextCell(view, -1)
777
+ }, {
778
+ key: "Enter",
779
+ run: enter
780
+ }, {
781
+ key: "Mod-Enter",
782
+ run: insertBelow
783
+ }, {
784
+ key: "Shift-Enter",
785
+ run: view => tableContext(view.state) ? dispatchTableEdit(view, {
786
+ changes: {
787
+ from: view.state.selection.main.from,
788
+ to: view.state.selection.main.to,
789
+ insert: "<br>"
790
+ },
791
+ anchor: view.state.selection.main.from + 4
792
+ }) : false
793
+ }, {
794
+ key: "Backspace",
795
+ run: backspaceRow
796
+ }, {
797
+ key: "Home",
798
+ run: view => cellBoundary(view, -1, false),
799
+ shift: view => cellBoundary(view, -1, true)
800
+ }, {
801
+ key: "End",
802
+ run: view => cellBoundary(view, 1, false),
803
+ shift: view => cellBoundary(view, 1, true)
804
+ }, {
805
+ key: "Alt-ArrowUp",
806
+ run: view => shiftRow(view, -1)
807
+ }, {
808
+ key: "Alt-ArrowDown",
809
+ run: view => shiftRow(view, 1)
810
+ }, {
811
+ key: "Shift-ArrowLeft",
812
+ run: view => extendCells(view, 0, -1)
813
+ }, {
814
+ key: "Shift-ArrowRight",
815
+ run: view => extendCells(view, 0, 1)
816
+ }, {
817
+ key: "Shift-ArrowUp",
818
+ run: view => extendCells(view, -1, 0)
819
+ }, {
820
+ key: "Shift-ArrowDown",
821
+ run: view => extendCells(view, 1, 0)
822
+ }, {
823
+ key: "Mod-a",
824
+ run: selectTable
825
+ }])), EditorView.domEventHandlers({
826
+ paste,
827
+ copy: copyCells,
828
+ cut: copyCells,
829
+ beforeinput: typeOverCells,
830
+ mousedown: clickCell
831
+ }), tableControls()];
832
+ }