@mdbase-dev/ui 0.1.0-beta.163 → 0.1.0-beta.165

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,113 @@
1
+ import { EditorSelection, StateEffect, StateField, type ChangeSpec, type EditorState, type TransactionSpec } from "@codemirror/state";
2
+ import type { EditorView } from "@codemirror/view";
3
+ import type { SyntaxNode } from "@lezer/common";
4
+ export type TableAlignment = "left" | "center" | "right" | null;
5
+ interface TableCell {
6
+ /** Source between two delimiters, including padding. */
7
+ from: number;
8
+ to: number;
9
+ /** The cell's text without its padding; empty cells collapse to one caret stop. */
10
+ contentFrom: number;
11
+ contentTo: number;
12
+ }
13
+ interface TableRow {
14
+ kind: "header" | "delimiter" | "body";
15
+ /** The row's own source, after any list or quote prefix on its line. */
16
+ from: number;
17
+ to: number;
18
+ lineFrom: number;
19
+ cells: TableCell[];
20
+ trailingPipe: boolean;
21
+ }
22
+ export interface TableModel {
23
+ from: number;
24
+ to: number;
25
+ /** Header, delimiter, then body rows, in source order. */
26
+ rows: TableRow[];
27
+ columns: number;
28
+ alignments: TableAlignment[];
29
+ /** What a new row's line starts with, so tables in lists and quotes stay there. */
30
+ prefix: string;
31
+ }
32
+ export interface TablePosition {
33
+ row: number;
34
+ column: number;
35
+ }
36
+ export interface TableEdit {
37
+ changes: ChangeSpec;
38
+ /** Caret after the edit, in the new document. */
39
+ anchor: number;
40
+ head?: number;
41
+ }
42
+ export declare function tableModel(state: EditorState, node: SyntaxNode): TableModel;
43
+ export declare function tableAt(state: EditorState, position: number): TableModel | null;
44
+ /** The cell holding a position; padding belongs to the nearest cell. Null on the delimiter row. */
45
+ export declare function cellAt(table: TableModel, position: number): TablePosition | null;
46
+ /** Writes a row's text as it is, without escaping: callers own their cells' Markdown. */
47
+ export declare function insertRow(table: TableModel, after: number, cells?: string[]): TableEdit;
48
+ /** Deletes body rows; the header and delimiter stay. */
49
+ export declare function deleteRows(table: TableModel, rows: readonly number[]): TableEdit | null;
50
+ export declare function insertColumn(state: EditorState, table: TableModel, at: TablePosition, index: number): TableEdit;
51
+ /** Deletes columns, keeping at least one. */
52
+ export declare function deleteColumns(state: EditorState, table: TableModel, at: TablePosition, columns: readonly number[]): TableEdit | null;
53
+ /** Moves a column to another index; every row is rewritten so short rows keep their place. */
54
+ export declare function moveColumn(state: EditorState, table: TableModel, at: TablePosition, target: number): TableEdit | null;
55
+ export declare function alignColumn(state: EditorState, table: TableModel, at: TablePosition, alignment: TableAlignment): TableEdit;
56
+ /** Moves a body row to another body row's index. */
57
+ export declare function moveRow(state: EditorState, table: TableModel, row: number, target: number): TableEdit | null;
58
+ /** Sorts body rows by one column; blank cells stay last. */
59
+ export declare function sortRows(state: EditorState, table: TableModel, column: number, direction: 1 | -1): TableEdit | null;
60
+ /** Text typed or pasted into one cell cannot end the cell or the row. */
61
+ export declare function escapeCell(text: string): string;
62
+ /** Clipboard grids: spreadsheet tab-separated text, or rows of a Markdown table. */
63
+ export declare function parseGrid(text: string): string[][] | null;
64
+ /** Fills cells from a position, adding rows and columns the grid needs. */
65
+ export declare function pasteGrid(state: EditorState, table: TableModel, at: TablePosition, grid: string[][]): TableEdit;
66
+ /** A pipe-delimited line that is about to become a table header. */
67
+ export declare function headerCells(text: string): string[] | null;
68
+ /** Marks a table edit that already keeps every row well formed. */
69
+ export declare const tableEdit: import("@codemirror/state").AnnotationType<boolean>;
70
+ export declare function dispatchTableEdit(view: EditorView, edit: TableEdit | null, userEvent?: string): boolean;
71
+ /** A block of cells: a selection running from one cell into another of the same table. */
72
+ export interface CellRange {
73
+ table: TableModel;
74
+ anchor: TablePosition;
75
+ head: TablePosition;
76
+ }
77
+ type Corners = Pick<CellRange, "anchor" | "head">;
78
+ /**
79
+ * A block's corners, set with the selection that spans it. A row shorter than its header
80
+ * has no text in its missing cells, so the selection alone cannot end a block there.
81
+ */
82
+ export declare const cellCorners: StateField<Corners | null>;
83
+ export declare function cellRange(state: EditorState): CellRange | null;
84
+ /** Row indexes and columns a range covers, top-left first; the delimiter row is never one of them. */
85
+ export declare function rangeCells(range: CellRange): {
86
+ rows: number[];
87
+ columns: number[];
88
+ };
89
+ /** The selection for a block of cells, spanning from the anchor cell's text to the head cell's. */
90
+ export declare function selectCells(table: TableModel, anchor: TablePosition, head: TablePosition): {
91
+ selection: EditorSelection;
92
+ effects: StateEffect<Corners>;
93
+ };
94
+ /** Empties every cell in a range; the pipes and padding stay. */
95
+ export declare function clearCells(state: EditorState, range: CellRange): ChangeSpec[];
96
+ /** Empties a block's cells, leaving it selected. */
97
+ export declare function clearBlock(state: EditorState, range: CellRange, userEvent?: string): TransactionSpec | null;
98
+ /**
99
+ * A range as the clipboard carries it: Markdown rows for text editors and our own tables,
100
+ * an HTML table for spreadsheets and documents. With the header included, the Markdown is a whole table.
101
+ */
102
+ export declare function cellClipboard(state: EditorState, range: CellRange): {
103
+ markdown: string;
104
+ html: string;
105
+ };
106
+ /** The whole table as a range. */
107
+ export declare function wholeTable(table: TableModel): CellRange;
108
+ interface TableContext {
109
+ table: TableModel;
110
+ at: TablePosition;
111
+ }
112
+ export declare function tableContext(state: EditorState): TableContext | null;
113
+ export {};
@@ -0,0 +1,510 @@
1
+ import { syntaxTree } from "@codemirror/language";
2
+ import { Annotation, EditorSelection, StateEffect, StateField } from "@codemirror/state";
3
+ /** GFM splits cells on every unescaped pipe, inside code spans too. */
4
+ function parseRow(state, kind, from, to) {
5
+ const text = state.sliceDoc(from, to);
6
+ const pipes = [];
7
+ for (let index = 0; index < text.length; index++) {
8
+ if (text[index] === "\\") index++;else if (text[index] === "|") pipes.push(index);
9
+ }
10
+ const leading = text.trimStart().startsWith("|");
11
+ const trailingPipe = pipes.length > 0 && pipes.at(-1) === text.trimEnd().length - 1 && !(pipes.length === 1 && leading);
12
+ const bounds = [];
13
+ let start = leading ? pipes[0] + 1 : 0;
14
+ for (const pipe of pipes.slice(leading ? 1 : 0)) {
15
+ bounds.push([start, pipe]);
16
+ start = pipe + 1;
17
+ }
18
+ if (!trailingPipe) bounds.push([start, text.trimEnd().length]);
19
+ const cells = bounds.map(([cellFrom, cellTo]) => {
20
+ const source = text.slice(cellFrom, cellTo);
21
+ const trimmed = source.trim();
22
+ let contentFrom = from + cellFrom + (source.length - source.trimStart().length);
23
+ let contentTo = contentFrom + trimmed.length;
24
+ if (!trimmed) contentFrom = contentTo = from + Math.min(cellFrom + 1, cellTo);
25
+ return {
26
+ from: from + cellFrom,
27
+ to: from + cellTo,
28
+ contentFrom,
29
+ contentTo
30
+ };
31
+ });
32
+ return {
33
+ kind,
34
+ from,
35
+ to,
36
+ lineFrom: state.doc.lineAt(from).from,
37
+ cells,
38
+ trailingPipe
39
+ };
40
+ }
41
+ export function tableModel(state, node) {
42
+ const rows = [];
43
+ for (let child = node.firstChild; child; child = child.nextSibling) {
44
+ const kind = child.name === "TableHeader" ? "header" : child.name === "TableDelimiter" ? "delimiter" : child.name === "TableRow" ? "body" : null;
45
+ if (kind) rows.push(parseRow(state, kind, child.from, child.to));
46
+ }
47
+ const delimiter = rows.find(row => row.kind === "delimiter");
48
+ const alignments = delimiter.cells.map(cell => {
49
+ const value = state.sliceDoc(cell.contentFrom, cell.contentTo);
50
+ const left = value.startsWith(":"),
51
+ right = value.endsWith(":");
52
+ return left && right ? "center" : right ? "right" : left ? "left" : null;
53
+ });
54
+ return {
55
+ from: node.from,
56
+ to: node.to,
57
+ rows,
58
+ columns: rows[0].cells.length,
59
+ alignments,
60
+ prefix: state.sliceDoc(delimiter.lineFrom, delimiter.from)
61
+ };
62
+ }
63
+ export function tableAt(state, position) {
64
+ for (const side of [1, -1]) {
65
+ for (let node = syntaxTree(state).resolveInner(position, side); node; node = node.parent) {
66
+ if (node.name === "Table") return tableModel(state, node);
67
+ }
68
+ }
69
+ return null;
70
+ }
71
+ /** The cell holding a position; padding belongs to the nearest cell. Null on the delimiter row. */
72
+ export function cellAt(table, position) {
73
+ const row = table.rows.findIndex(row => position >= row.lineFrom && position <= row.to);
74
+ if (row < 0 || table.rows[row].kind === "delimiter") return null;
75
+ const cells = table.rows[row].cells;
76
+ let column = cells.findIndex(cell => position <= cell.to);
77
+ if (column < 0) column = cells.length - 1;
78
+ return {
79
+ row,
80
+ column: Math.max(0, column)
81
+ };
82
+ }
83
+ function bodyRows(table) {
84
+ return table.rows.flatMap((row, index) => row.kind === "body" ? [index] : []);
85
+ }
86
+ function rowLine(table, cells) {
87
+ return `${table.prefix}| ${cells.join(" | ")} |`;
88
+ }
89
+ /** The first content position of a freshly written row starting at `lineFrom`. */
90
+ function firstCell(table, lineFrom) {
91
+ return lineFrom + table.prefix.length + 2;
92
+ }
93
+ function emptyCells(table) {
94
+ return Array(table.columns).fill("");
95
+ }
96
+ /** Writes a row's text as it is, without escaping: callers own their cells' Markdown. */
97
+ export function insertRow(table, after, cells = emptyCells(table)) {
98
+ // Rows are never added above the header or between it and the delimiter.
99
+ const anchorRow = table.rows[Math.max(after, 1)];
100
+ const at = anchorRow.to;
101
+ const lineFrom = at + 1;
102
+ return {
103
+ changes: {
104
+ from: at,
105
+ insert: `\n${rowLine(table, cells)}`
106
+ },
107
+ anchor: firstCell(table, lineFrom) + (cells[0]?.length ?? 0)
108
+ };
109
+ }
110
+ /** Deletes body rows; the header and delimiter stay. */
111
+ export function deleteRows(table, rows) {
112
+ const targets = rows.filter(row => table.rows[row]?.kind === "body").sort((a, b) => a - b);
113
+ if (!targets.length) return null;
114
+ const changes = targets.map(row => ({
115
+ from: table.rows[row - 1].to,
116
+ to: table.rows[row].to
117
+ }));
118
+ // The caret goes to the first cell of the row that takes their place.
119
+ const before = table.rows[targets[0] - 1];
120
+ const destination = table.rows[targets.at(-1) + 1] ?? (before.kind === "body" ? before : table.rows[0]);
121
+ const position = destination.cells[0]?.contentTo ?? destination.to;
122
+ return {
123
+ changes,
124
+ anchor: position - changes.reduce((removed, change) => removed + (change.to <= position ? change.to - change.from : 0), 0)
125
+ };
126
+ }
127
+ function cellText(state, cell) {
128
+ return cell ? state.sliceDoc(cell.contentFrom, cell.contentTo) : "";
129
+ }
130
+ /** Rewrites each row's cells, keeping its prefix; used by column edits so every row agrees. */
131
+ function rewriteRows(state, table, map) {
132
+ return table.rows.map(row => {
133
+ const cells = Array.from({
134
+ length: Math.max(row.cells.length, row.kind === "body" ? 0 : table.columns)
135
+ }, (_, index) => cellText(state, row.cells[index]));
136
+ return {
137
+ from: row.from,
138
+ to: row.to,
139
+ insert: `| ${map(cells, row).join(" | ")} |`
140
+ };
141
+ });
142
+ }
143
+ function delimiterCell(alignment) {
144
+ return alignment === "center" ? ":---:" : alignment === "right" ? "---:" : alignment === "left" ? ":---" : "---";
145
+ }
146
+ /** Position of a column's content after a column edit rewrote every row. */
147
+ function rewrittenCell(state, table, rowIndex, column, map) {
148
+ let offset = 0;
149
+ for (let index = 0; index < rowIndex; index++) {
150
+ const row = table.rows[index];
151
+ const cells = Array.from({
152
+ length: Math.max(row.cells.length, row.kind === "body" ? 0 : table.columns)
153
+ }, (_, cell) => cellText(state, row.cells[cell]));
154
+ offset += `| ${map(cells, row).join(" | ")} |`.length - (row.to - row.from);
155
+ }
156
+ const row = table.rows[rowIndex];
157
+ const cells = map(Array.from({
158
+ length: Math.max(row.cells.length, row.kind === "body" ? 0 : table.columns)
159
+ }, (_, cell) => cellText(state, row.cells[cell])), row);
160
+ let position = row.from + offset + 2;
161
+ for (let index = 0; index < Math.min(column, cells.length); index++) position += cells[index].length + 3;
162
+ return position + (cells[column]?.length ?? 0);
163
+ }
164
+ function columnEdit(state, table, at, column, map) {
165
+ return {
166
+ changes: rewriteRows(state, table, map),
167
+ anchor: rewrittenCell(state, table, at.row, column, map)
168
+ };
169
+ }
170
+ export function insertColumn(state, table, at, index) {
171
+ return columnEdit(state, table, at, index, (cells, row) => {
172
+ if (row.kind === "body" && cells.length < index) return cells;
173
+ const next = cells.slice();
174
+ next.splice(index, 0, row.kind === "delimiter" ? "---" : "");
175
+ return next;
176
+ });
177
+ }
178
+ /** Deletes columns, keeping at least one. */
179
+ export function deleteColumns(state, table, at, columns) {
180
+ if (columns.length >= table.columns) return null;
181
+ return columnEdit(state, table, at, Math.min(Math.min(...columns), table.columns - columns.length - 1), cells => cells.filter((_, index) => !columns.includes(index)));
182
+ }
183
+ /** Moves a column to another index; every row is rewritten so short rows keep their place. */
184
+ export function moveColumn(state, table, at, target) {
185
+ if (target < 0 || target >= table.columns || target === at.column) return null;
186
+ return columnEdit(state, table, at, target, cells => {
187
+ const next = cells.slice();
188
+ while (next.length <= Math.max(at.column, target)) next.push("");
189
+ next.splice(target, 0, ...next.splice(at.column, 1));
190
+ return next;
191
+ });
192
+ }
193
+ export function alignColumn(state, table, at, alignment) {
194
+ const cell = table.rows[1].cells[at.column];
195
+ const insert = delimiterCell(alignment);
196
+ const delta = insert.length - (cell.contentTo - cell.contentFrom);
197
+ const head = state.selection.main.head;
198
+ // Only the delimiter row changes, so the caret stays where it was.
199
+ return {
200
+ changes: {
201
+ from: cell.contentFrom,
202
+ to: cell.contentTo,
203
+ insert
204
+ },
205
+ anchor: head > cell.contentTo ? head + delta : head
206
+ };
207
+ }
208
+ /** Writes body rows in a new order; the caret stays on the row it was in. */
209
+ function reorderRows(state, table, order) {
210
+ const rows = bodyRows(table).map(index => table.rows[index]);
211
+ const first = rows[0],
212
+ last = rows.at(-1);
213
+ const separator = `\n${state.sliceDoc(first.lineFrom, first.from)}`;
214
+ const head = state.selection.main.head;
215
+ let anchor = head,
216
+ at = first.from;
217
+ for (const row of order) {
218
+ if (head >= row.from && head <= row.to) anchor = at + head - row.from;
219
+ at += row.to - row.from + separator.length;
220
+ }
221
+ return {
222
+ changes: {
223
+ from: first.from,
224
+ to: last.to,
225
+ insert: order.map(row => state.sliceDoc(row.from, row.to)).join(separator)
226
+ },
227
+ anchor
228
+ };
229
+ }
230
+ /** Moves a body row to another body row's index. */
231
+ export function moveRow(state, table, row, target) {
232
+ if (table.rows[row]?.kind !== "body" || table.rows[target]?.kind !== "body" || row === target) return null;
233
+ const order = bodyRows(table).map(index => table.rows[index]);
234
+ const first = bodyRows(table)[0];
235
+ order.splice(target - first, 0, ...order.splice(row - first, 1));
236
+ return reorderRows(state, table, order);
237
+ }
238
+ /** Sorts body rows by one column; blank cells stay last. */
239
+ export function sortRows(state, table, column, direction) {
240
+ const rows = bodyRows(table).map(index => table.rows[index]);
241
+ if (rows.length < 2) return null;
242
+ const collator = new Intl.Collator(undefined, {
243
+ numeric: true,
244
+ sensitivity: "base"
245
+ });
246
+ const keyed = rows.map(row => ({
247
+ row,
248
+ key: cellText(state, row.cells[column]).trim()
249
+ }));
250
+ keyed.sort((a, b) => !a.key || !b.key ? Number(!a.key) - Number(!b.key) : direction * collator.compare(a.key, b.key));
251
+ return reorderRows(state, table, keyed.map(({
252
+ row
253
+ }) => row));
254
+ }
255
+ /** Text typed or pasted into one cell cannot end the cell or the row. */
256
+ export function escapeCell(text) {
257
+ return text.replace(/\r\n?/g, "\n").replace(/\\?\|/g, pipe => pipe.length === 2 ? pipe : "\\|").replace(/\n/g, "<br>");
258
+ }
259
+ /** Clipboard grids: spreadsheet tab-separated text, or rows of a Markdown table. */
260
+ export function parseGrid(text) {
261
+ const lines = text.replace(/\r\n?/g, "\n").replace(/\n$/, "").split("\n");
262
+ if (lines.every(line => /^\s*\|.*\|\s*$/.test(line))) {
263
+ return lines.filter(line => !/^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/.test(line)).map(line => {
264
+ const cells = [];
265
+ let current = "";
266
+ const body = line.trim().replace(/^\|/, "");
267
+ for (let index = 0; index < body.length; index++) {
268
+ if (body[index] === "\\" && index + 1 < body.length) {
269
+ current += body.slice(index, index + 2);
270
+ index++;
271
+ } else if (body[index] === "|") {
272
+ cells.push(current.trim());
273
+ current = "";
274
+ } else current += body[index];
275
+ }
276
+ if (current.trim()) cells.push(current.trim());
277
+ return cells;
278
+ });
279
+ }
280
+ if (!text.includes("\t")) return null;
281
+ return lines.map(line => line.split("\t").map(cell => escapeCell(cell.trim())));
282
+ }
283
+ /** Fills cells from a position, adding rows and columns the grid needs. */
284
+ export function pasteGrid(state, table, at, grid) {
285
+ const width = Math.max(table.columns, at.column + Math.max(...grid.map(row => row.length)));
286
+ const startRow = Math.max(at.row, 0);
287
+ const rows = table.rows.map(row => Array.from({
288
+ length: row.kind === "body" ? row.cells.length : table.columns
289
+ }, (_, index) => cellText(state, row.cells[index])));
290
+ for (let index = rows.length; index < startRow + grid.length + (startRow === 0 ? 1 : 0); index++) rows.push(Array(width).fill(""));
291
+ grid.forEach((values, offset) => {
292
+ // The delimiter row is never a paste target.
293
+ const target = startRow + offset + (startRow === 0 && offset > 0 ? 1 : 0);
294
+ values.forEach((value, column) => {
295
+ const cells = rows[target];
296
+ while (cells.length < at.column + column) cells.push("");
297
+ cells[at.column + column] = value;
298
+ });
299
+ });
300
+ rows[1] = Array.from({
301
+ length: width
302
+ }, (_, index) => table.rows[1].cells[index] ? cellText(state, table.rows[1].cells[index]) : "---");
303
+ rows[0] = Array.from({
304
+ length: width
305
+ }, (_, index) => rows[0][index] ?? "");
306
+ const lines = rows.map((cells, index) => index < table.rows.length ? `${state.sliceDoc(table.rows[index].lineFrom, table.rows[index].from)}| ${cells.join(" | ")} |` : `${table.prefix}| ${cells.join(" | ")} |`);
307
+ const first = table.rows[0];
308
+ const last = grid.at(-1);
309
+ const lastRow = startRow + grid.length - 1 + (startRow === 0 && grid.length > 1 ? 1 : 0);
310
+ let anchor = first.lineFrom;
311
+ for (let index = 0; index < lastRow; index++) anchor += lines[index].length + 1;
312
+ const lastColumn = at.column + last.length - 1;
313
+ anchor += (index => {
314
+ const prefix = index < table.rows.length ? table.rows[index].from - table.rows[index].lineFrom : table.prefix.length;
315
+ return prefix + 2 + rows[index].slice(0, lastColumn + 1).reduce((sum, cell) => sum + cell.length + 3, 0) - 3;
316
+ })(lastRow);
317
+ return {
318
+ changes: {
319
+ from: first.lineFrom,
320
+ to: table.rows.at(-1).to,
321
+ insert: lines.join("\n")
322
+ },
323
+ anchor
324
+ };
325
+ }
326
+ /** A pipe-delimited line that is about to become a table header. */
327
+ export function headerCells(text) {
328
+ const trimmed = text.trim();
329
+ if (!/^\|.*\|$/.test(trimmed) || trimmed.length < 3) return null;
330
+ const cells = trimmed.slice(1, -1).split(/(?<!\\)\|/).map(cell => cell.trim());
331
+ return cells.length && cells.some(Boolean) ? cells : null;
332
+ }
333
+ /** Marks a table edit that already keeps every row well formed. */
334
+ export const tableEdit = Annotation.define();
335
+ export function dispatchTableEdit(view, edit, userEvent = "input.table") {
336
+ if (!edit) return false;
337
+ if (view.state.readOnly) return true;
338
+ view.dispatch({
339
+ changes: edit.changes,
340
+ selection: EditorSelection.single(edit.anchor, edit.head ?? edit.anchor),
341
+ annotations: tableEdit.of(true),
342
+ scrollIntoView: true,
343
+ userEvent
344
+ });
345
+ return true;
346
+ }
347
+ const setCorners = StateEffect.define();
348
+ /**
349
+ * A block's corners, set with the selection that spans it. A row shorter than its header
350
+ * has no text in its missing cells, so the selection alone cannot end a block there.
351
+ */
352
+ export const cellCorners = StateField.define({
353
+ create: () => null,
354
+ update(value, transaction) {
355
+ for (const effect of transaction.effects) if (effect.is(setCorners)) return effect.value;
356
+ return transaction.selection || transaction.docChanged ? null : value;
357
+ }
358
+ });
359
+ /** The cell a position belongs to; the delimiter row counts as the header, and hidden overflow as the last column. */
360
+ function cellOf(table, position) {
361
+ let row = 0;
362
+ table.rows.forEach((candidate, index) => {
363
+ if (candidate.lineFrom <= position) row = index;
364
+ });
365
+ const cells = table.rows[row].cells;
366
+ const column = cells.findIndex(cell => position <= cell.to);
367
+ return {
368
+ row: table.rows[row].kind === "delimiter" ? 0 : row,
369
+ column: Math.max(0, Math.min(column < 0 ? cells.length - 1 : column, table.columns - 1))
370
+ };
371
+ }
372
+ export function cellRange(state) {
373
+ if (state.selection.ranges.length !== 1 || state.selection.main.empty) return null;
374
+ const {
375
+ anchor,
376
+ head,
377
+ from,
378
+ to
379
+ } = state.selection.main;
380
+ const table = tableAt(state, head);
381
+ if (!table || from < table.rows[0].lineFrom || to > table.to) return null;
382
+ // A selection ending at a row's start ends with the row before, as whole rows do.
383
+ const corners = state.field(cellCorners, false);
384
+ if (corners && corners.anchor.row < table.rows.length && corners.head.row < table.rows.length) return {
385
+ table,
386
+ ...corners
387
+ };
388
+ const end = position => position === to && table.rows.some(row => row.lineFrom === position) ? position - 1 : position;
389
+ const range = {
390
+ table,
391
+ anchor: cellOf(table, end(anchor)),
392
+ head: cellOf(table, end(head))
393
+ };
394
+ return range.anchor.row === range.head.row && range.anchor.column === range.head.column ? null : range;
395
+ }
396
+ /** Row indexes and columns a range covers, top-left first; the delimiter row is never one of them. */
397
+ export function rangeCells(range) {
398
+ const rows = range.table.rows.flatMap((row, index) => row.kind !== "delimiter" && index >= Math.min(range.anchor.row, range.head.row) && index <= Math.max(range.anchor.row, range.head.row) ? [index] : []);
399
+ const left = Math.min(range.anchor.column, range.head.column),
400
+ right = Math.max(range.anchor.column, range.head.column);
401
+ return {
402
+ rows,
403
+ columns: Array.from({
404
+ length: right - left + 1
405
+ }, (_, index) => left + index)
406
+ };
407
+ }
408
+ /** The selection for a block of cells, spanning from the anchor cell's text to the head cell's. */
409
+ export function selectCells(table, anchor, head) {
410
+ const forward = head.row > anchor.row || head.row === anchor.row && head.column >= anchor.column;
411
+ const edge = (at, end) => {
412
+ const cell = table.rows[at.row].cells[at.column];
413
+ return cell ? end ? cell.contentTo : cell.contentFrom : table.rows[at.row].to;
414
+ };
415
+ return {
416
+ selection: EditorSelection.single(edge(anchor, !forward), edge(head, forward)),
417
+ effects: setCorners.of({
418
+ anchor,
419
+ head
420
+ })
421
+ };
422
+ }
423
+ /** Empties every cell in a range; the pipes and padding stay. */
424
+ export function clearCells(state, range) {
425
+ const {
426
+ rows,
427
+ columns
428
+ } = rangeCells(range);
429
+ return rows.flatMap(row => columns.flatMap(column => {
430
+ const cell = range.table.rows[row].cells[column];
431
+ return cell && cell.contentTo > cell.contentFrom && state.sliceDoc(cell.contentFrom, cell.contentTo).trim() ? [{
432
+ from: cell.contentFrom,
433
+ to: cell.contentTo
434
+ }] : [];
435
+ }));
436
+ }
437
+ /** Empties a block's cells, leaving it selected. */
438
+ export function clearBlock(state, range, userEvent) {
439
+ const changes = state.changes(clearCells(state, range));
440
+ if (changes.empty) return null;
441
+ const {
442
+ main
443
+ } = state.selection;
444
+ return {
445
+ changes,
446
+ selection: EditorSelection.single(changes.mapPos(main.anchor), changes.mapPos(main.head)),
447
+ effects: setCorners.of({
448
+ anchor: range.anchor,
449
+ head: range.head
450
+ }),
451
+ annotations: tableEdit.of(true),
452
+ userEvent,
453
+ scrollIntoView: true
454
+ };
455
+ }
456
+ const escapeHtml = text => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
457
+ /** A cell's common inline Markdown as HTML, so spreadsheets and documents get formatting, not markers. */
458
+ function cellHtml(markdown) {
459
+ return markdown.split(/<br\s*\/?>/i).map(part => escapeHtml(part.replace(/\\\|/g, "|")).replace(/`([^`]+)`/g, "<code>$1</code>").replace(/\*\*([^*]+)\*\*|__([^_]+)__/g, (_, star, line) => `<strong>${star ?? line}</strong>`).replace(/(?<![*\w])\*([^*]+)\*(?!\*)|(?<![_\w])_([^_]+)_(?![_\w])/g, (_, star, line) => `<em>${star ?? line}</em>`).replace(/~~([^~]+)~~/g, "<del>$1</del>").replace(/\[\[([^\]|]+)(?:\|([^\]]+))?\]\]/g, (_, target, label) => label ?? target).replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, '<a href="$2">$1</a>')).join("<br>");
460
+ }
461
+ /**
462
+ * A range as the clipboard carries it: Markdown rows for text editors and our own tables,
463
+ * an HTML table for spreadsheets and documents. With the header included, the Markdown is a whole table.
464
+ */
465
+ export function cellClipboard(state, range) {
466
+ const {
467
+ rows,
468
+ columns
469
+ } = rangeCells(range);
470
+ const values = rows.map(row => columns.map(column => cellText(state, range.table.rows[row].cells[column])));
471
+ const lines = values.map(cells => `| ${cells.join(" | ")} |`);
472
+ if (rows[0] === 0) lines.splice(1, 0, `| ${columns.map(column => delimiterCell(range.table.alignments[column])).join(" | ")} |`);
473
+ const html = values.map((cells, index) => {
474
+ const tag = rows[index] === 0 ? "th" : "td";
475
+ return `<tr>${cells.map(cell => `<${tag}>${cellHtml(cell)}</${tag}>`).join("")}</tr>`;
476
+ });
477
+ const head = rows[0] === 0 ? `<thead>${html.shift()}</thead>` : "";
478
+ return {
479
+ markdown: lines.join("\n"),
480
+ html: `<table>${head}<tbody>${html.join("")}</tbody></table>`
481
+ };
482
+ }
483
+ /** The whole table as a range. */
484
+ export function wholeTable(table) {
485
+ return {
486
+ table,
487
+ anchor: {
488
+ row: 0,
489
+ column: 0
490
+ },
491
+ head: {
492
+ row: table.rows.length - 1,
493
+ column: table.columns - 1
494
+ }
495
+ };
496
+ }
497
+ export function tableContext(state) {
498
+ if (state.selection.ranges.length !== 1) return null;
499
+ const {
500
+ head,
501
+ anchor
502
+ } = state.selection.main;
503
+ const table = tableAt(state, head);
504
+ if (!table || Math.min(head, anchor) < table.rows[0].lineFrom || Math.max(head, anchor) > table.to) return null;
505
+ const at = cellAt(table, head);
506
+ return at ? {
507
+ table,
508
+ at
509
+ } : null;
510
+ }
@@ -0,0 +1,2 @@
1
+ import { type Extension } from "@codemirror/state";
2
+ export declare function tablePreview(): Extension;