@tristan2828/ui-foundation 4.78.0 → 4.80.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.
@@ -11,7 +11,9 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
11
11
  // - No HTML in, ever. The preset's "preserve empty line" plugin is left
12
12
  // out: it writes an empty paragraph as a raw `<br />`. Raw HTML already
13
13
  // in the text shows as its characters (an uneditable chip, Milkdown's
14
- // html node), and HTML pasted as such a chip becomes plain text.
14
+ // html node), and HTML pasted as such a chip becomes plain text. The
15
+ // one thing it writes is the comment after a table that keeps its column
16
+ // widths (src/lib/markdown-table-widths.ts).
15
17
  // - Headings render from <h3>, like <Markdown>: the page owns <h1> and
16
18
  // <h2>. `headingLevel` moves them to where the field sits in the page's
17
19
  // outline, as it does <Markdown>'s; only the element moves, never the
@@ -27,7 +29,10 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
27
29
  // on the column and one on the row the pointer or the caret is in, each
28
30
  // a menu to insert, move, delete, align, sort and colour
29
31
  // (rich-text-table-grips.tsx); right-click or Shift+F10 in a cell opens
30
- // the cell's. Tab in the last cell adds a row and Enter goes down a
32
+ // the cell's. A column's right edge drags to a width (double-click:
33
+ // back to fit its words), and the menus hold Narrower, Wider and Fit to
34
+ // content; none of that on a phone, which fits columns to their words.
35
+ // Tab in the last cell adds a row and Enter goes down a
31
36
  // column (rich-text-table.ts). Colours and a header column are kept as
32
37
  // Markdown writes them (src/lib/markdown-table.ts).
33
38
  // - Edited blocks are written in the document's own bullet and rule marks.
@@ -72,7 +77,7 @@ import { useInRouterContext, useNavigate } from 'react-router';
72
77
  import { defaultValueCtx, Editor, editorViewCtx, editorViewOptionsCtx, parserCtx, remarkStringifyOptionsCtx, rootCtx, schemaCtx, serializerCtx, } from '@milkdown/kit/core';
73
78
  import { history } from '@milkdown/kit/plugin/history';
74
79
  import { commands, headingSchema, inputRules, keymap, markInputRules, plugins, remarkPreserveEmptyLinePlugin, schema, } from '@milkdown/kit/preset/commonmark';
75
- import { gfm } from '@milkdown/kit/preset/gfm';
80
+ import { gfm, tableCellSchema, tableHeaderSchema, tableSchema } from '@milkdown/kit/preset/gfm';
76
81
  import { Fragment, Slice } from '@milkdown/kit/prose/model';
77
82
  import { NodeSelection, Plugin, TextSelection } from '@milkdown/kit/prose/state';
78
83
  import { isInTable, TableMap } from '@milkdown/kit/prose/tables';
@@ -91,6 +96,7 @@ import { restorePage } from './page-restore.js';
91
96
  import { insertPageLink, pageLinkInfo, pageLinksPlugin, pendingPagePlugin, refreshPageLinks, setPendingPage, } from './rich-text-page-links.js';
92
97
  import { passEscapeThrough } from './escape-passthrough.js';
93
98
  import { calloutHandler, remarkCalloutNodes } from '../../lib/markdown-callout.js';
99
+ import { formatTableWidths, remarkTableWidths } from '../../lib/markdown-table-widths.js';
94
100
  import { DEFAULT_HIGHLIGHT, highlightHandler, isHighlightColor, remarkHighlightNodes } from '../../lib/markdown-highlight.js';
95
101
  import { textTopHeading } from '../../lib/markdown-top-heading.js';
96
102
  import { MarkdownMergeError, markdownStyle, mergeMarkdown } from '../../lib/markdown-merge.js';
@@ -105,7 +111,7 @@ import { droppedFiles, imageUploadPlugin, pastedImages, uploadImages, uploadPlac
105
111
  import { handleShortcut } from './rich-text-shortcuts.js';
106
112
  import { splitTaskItem, taskInputRule } from './rich-text-tasks.js';
107
113
  import { toggleHeadingInputRule, toggleHeadingRemark, withToggle } from './rich-text-toggle-heading.js';
108
- import { addRowAtEnd, colorTableCells, handleTableKey, runTableAction, tableLook as tableLookPlugin } from './rich-text-table.js';
114
+ import { addRowAtEnd, colorTableCells, fitAllColumns, handleTableKey, previewColumnWidth, runTableAction, setColumnWidth, tableLook as tableLookPlugin, tableWidthsOf } from './rich-text-table.js';
109
115
  import { TABLE_MENU_EVENT, TableGrips } from './rich-text-table-grips.js';
110
116
  import { applySlash, closeSlash, slashItems, slashOptionId, slashPlugin, slashQuery, } from './rich-text-slash.js';
111
117
  import { RichTextSlashMenu } from './rich-text-slash-menu.js';
@@ -184,6 +190,39 @@ const highlightSchema = $markSchema('highlight', () => ({
184
190
  // A table's cell colours and header column, drawn from the Markdown that
185
191
  // keeps them (rich-text-table.ts tableLook).
186
192
  const tableDecorations = $prose(() => tableLookPlugin());
193
+ // A table's column widths: read from the comment after it onto its cells
194
+ // (remarkTableWidths), and written back as that comment after the table,
195
+ // the one piece of HTML the editor writes (src/lib/markdown-table-widths.ts).
196
+ const tableWidthsRemark = $remark('remarkTableWidths', () => remarkTableWidths);
197
+ const tableWithWidths = tableSchema.extendSchema((previous) => (ctx) => {
198
+ const base = previous(ctx);
199
+ return {
200
+ ...base,
201
+ toMarkdown: {
202
+ match: base.toMarkdown.match,
203
+ runner: (state, node) => {
204
+ base.toMarkdown.runner(state, node);
205
+ const { headers, widths } = tableWidthsOf(node);
206
+ const comment = formatTableWidths(headers, widths);
207
+ if (comment)
208
+ state.addNode('html', undefined, comment);
209
+ },
210
+ },
211
+ };
212
+ });
213
+ // Milkdown's own cell reader, with the width the comment put on the cell.
214
+ const readCell = (state, node, type) => {
215
+ const attrs = { alignment: node.align, colwidth: typeof node.columnWidth === 'number' ? [node.columnWidth] : null };
216
+ state.openNode(type, attrs).openNode(state.schema.nodes.paragraph).next(node.children).closeNode().closeNode();
217
+ };
218
+ const cellWithWidth = tableCellSchema.extendSchema((previous) => (ctx) => {
219
+ const base = previous(ctx);
220
+ return { ...base, parseMarkdown: { match: base.parseMarkdown.match, runner: readCell } };
221
+ });
222
+ const headerWithWidth = tableHeaderSchema.extendSchema((previous) => (ctx) => {
223
+ const base = previous(ctx);
224
+ return { ...base, parseMarkdown: { match: base.parseMarkdown.match, runner: readCell } };
225
+ });
187
226
  function emptyImageTitles(node) {
188
227
  if (node.type === 'image' && node.title == null)
189
228
  node.title = '';
@@ -912,6 +951,10 @@ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem,
912
951
  .use(highlightRemark)
913
952
  .use(highlightSchema)
914
953
  .use(tableDecorations)
954
+ .use(tableWidthsRemark)
955
+ .use(tableWithWidths)
956
+ .use(cellWithWidth)
957
+ .use(headerWithWidth)
915
958
  .use(imageTitles)
916
959
  .use(history)
917
960
  .use(changes)
@@ -1031,6 +1074,23 @@ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem,
1031
1074
  colorTableCells(editorView.state, editorView.dispatch, scope, color);
1032
1075
  editorView.focus();
1033
1076
  };
1077
+ // A column's width from its edge or menu (`null`: automatic), `'all'`
1078
+ // every column automatic.
1079
+ const widthTableAt = (getPos, column, width) => {
1080
+ const pos = getPos();
1081
+ if (!editorView || pos === undefined)
1082
+ return;
1083
+ if (width === 'all')
1084
+ fitAllColumns(editorView.state, editorView.dispatch, pos);
1085
+ else
1086
+ setColumnWidth(editorView.state, editorView.dispatch, pos, column, width);
1087
+ };
1088
+ const previewTableWidth = (getPos, column, width) => {
1089
+ const tablePos = getPos();
1090
+ if (!editorView || tablePos === undefined)
1091
+ return;
1092
+ previewColumnWidth(editorView.state, editorView.dispatch, width === null ? null : { tablePos, column, width });
1093
+ };
1034
1094
  // A callout's menu: its kind changed, or the callout taken away (its
1035
1095
  // blocks kept). The menu gives focus back to the text.
1036
1096
  const changeCallout = (getPos, kind) => {
@@ -1219,7 +1279,7 @@ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem,
1219
1279
  createPortal(_jsx(TableBar, { side: "row", active: active, readOnly: readOnly, onAdd: () => addToTable(widget.getPos, 'row') }), widget.slot, `${widget.key}-row`),
1220
1280
  createPortal(_jsx(TableBar, { side: "column", active: active, readOnly: readOnly, onAdd: () => addToTable(widget.getPos, 'column') }), widget.column, `${widget.key}-column`),
1221
1281
  editorView &&
1222
- createPortal(_jsx(TableGrips, { view: editorView, state: editorState, getPos: widget.getPos, frame: widget.frame, box: widget.box, table: widget.table, readOnly: readOnly, focused: focused, onAction: (cell, action) => runTableAt(widget.getPos, cell, action), onColor: (cell, scope, color) => colorTableAt(widget.getPos, cell, scope, color), text: textElement }), widget.grips, `${widget.key}-grips`),
1282
+ createPortal(_jsx(TableGrips, { view: editorView, state: editorState, getPos: widget.getPos, frame: widget.frame, box: widget.box, table: widget.table, readOnly: readOnly, focused: focused, onAction: (cell, action) => runTableAt(widget.getPos, cell, action), onColor: (cell, scope, color) => colorTableAt(widget.getPos, cell, scope, color), onWidth: (column, width) => widthTableAt(widget.getPos, column, width), onPreviewWidth: (column, width) => previewTableWidth(widget.getPos, column, width), text: textElement }), widget.grips, `${widget.key}-grips`),
1223
1283
  ];
1224
1284
  }), slashOpen && slash && editorView && (_jsx(RichTextSlashMenu, { id: slashListId, view: editorView, at: slash.to, field: field, items: slashMatches, active: slashIndex, onHighlight: (index) => setSlashActive({ key: slashMenuKey, index }), onPick: (item) => (item === 'page' ? startPage(editorView, slash, '') : applySlash(editorView, slash, item)) })), toolsOpen && (_jsx(RichTextToolsBar, { ref: toolsRef, state: editorState, readOnly: readOnly, fullScreen: fullScreen, controls: editableId, onFormat: runFormat, onFullScreen: toggleFullScreen, onReturn: returnToText, onBlur: (event) => {
1225
1285
  const next = event.relatedTarget;
@@ -25,7 +25,11 @@ export interface TableGripsProps {
25
25
  onAction: (cell: TableCell, action: TableAction) => void;
26
26
  /** Colours a cell, its row or its column (null: no colour). */
27
27
  onColor: (cell: TableCell, scope: TableColorScope, color: HighlightColor | null) => void;
28
+ /** Sets a column's width (null: automatic), or every column automatic (`'all'`). */
29
+ onWidth: (column: number, width: number | null | 'all') => void;
30
+ /** Shows a column at a width while it's dragged, changing nothing (null: stop). */
31
+ onPreviewWidth: (column: number, width: number | null) => void;
28
32
  /** The editable element, where focus goes when a menu closes. */
29
33
  text: () => HTMLElement | null;
30
34
  }
31
- export declare function TableGrips({ view, state, getPos, frame, box, table, readOnly, focused, onAction, onColor, text }: TableGripsProps): import("react").JSX.Element | null;
35
+ export declare function TableGrips({ view, state, getPos, frame, box, table, readOnly, focused, onAction, onColor, onWidth, onPreviewWidth, text }: TableGripsProps): import("react").JSX.Element | null;
@@ -9,18 +9,28 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
9
9
  // column's items. The grips are mouse shortcuts, out of the tab order;
10
10
  // the keyboard has the cell's menu.
11
11
  //
12
+ // A column's width: its right edge, within a few pixels of the pointer,
13
+ // shows a line to drag (the width in a label beside it; the edge catches
14
+ // on the four sizes, markdown-table-widths.ts). Only that column changes,
15
+ // so the table grows or shrinks. A double-click puts it back to fitting
16
+ // its words. The menus have Narrower, Wider, Fit to content and Fit all
17
+ // columns. On a phone there's none of it: a phone fits columns to their
18
+ // words, so a width set there couldn't be seen.
19
+ //
12
20
  // Rendered into the table node view's grip layer (rich-text-node-views.ts)
13
21
  // through a portal. A menu acts on the cell it was opened for, then gives
14
22
  // focus back to the text with the caret in that cell.
15
23
  import { useEffect, useLayoutEffect, useRef, useState } from 'react';
16
24
  import { TextSelection } from '@milkdown/kit/prose/state';
17
25
  import { selectedRect, TableMap } from '@milkdown/kit/prose/tables';
18
- import { AlignCenterIcon, AlignLeftIcon, AlignRightIcon, ArrowDownAZIcon, ArrowDownIcon, ArrowLeftIcon, ArrowRightIcon, ArrowUpIcon, ArrowUpZAIcon, BetweenHorizontalEndIcon, BetweenHorizontalStartIcon, BetweenVerticalEndIcon, BetweenVerticalStartIcon, GripHorizontalIcon, GripVerticalIcon, PanelLeftIcon, Trash2Icon, } from 'lucide-react';
26
+ import { AlignCenterIcon, AlignLeftIcon, AlignRightIcon, ArrowDownAZIcon, ArrowDownIcon, ArrowLeftIcon, ArrowRightIcon, ArrowUpIcon, ArrowUpZAIcon, BetweenHorizontalEndIcon, BetweenHorizontalStartIcon, BetweenVerticalEndIcon, BetweenVerticalStartIcon, ChevronsLeftRightIcon, ChevronsRightLeftIcon, Columns3Icon, GripHorizontalIcon, GripVerticalIcon, MoveHorizontalIcon, PanelLeftIcon, Trash2Icon, } from 'lucide-react';
19
27
  import { cn } from 'cn';
20
28
  import { DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuSeparator, DropdownMenuTrigger, } from '../ui/dropdown-menu.js';
29
+ import { useIsMobile } from '../../hooks/use-mobile.js';
21
30
  import { HIGHLIGHT_COLORS } from '../../lib/markdown-highlight.js';
31
+ import { catchColumnWidth, clampColumnWidth, MAX_COLUMN_WIDTH, MIN_COLUMN_WIDTH } from '../../lib/markdown-table-widths.js';
22
32
  import { tableAt } from './rich-text-formats.js';
23
- import { cellColorAt, columnAlignment, headerColumnOn, tableActionEnabled, tableColorEnabled, } from './rich-text-table.js';
33
+ import { cellColorAt, columnAlignment, columnWidthAt, headerColumnOn, tableHasWidths, tableActionEnabled, tableColorEnabled, } from './rich-text-table.js';
24
34
  /** The event the editor sends a table's frame to open the caret's cell menu (Shift+F10). */
25
35
  export const TABLE_MENU_EVENT = 'rich-text-table-menu';
26
36
  const SWATCH = {
@@ -70,7 +80,29 @@ function stateAt(state, tablePos, cell) {
70
80
  const at = tablePos + 1 + map.map[cell.row * map.width + cell.column] + 1;
71
81
  return state.apply(state.tr.setSelection(TextSelection.near(state.doc.resolve(at))));
72
82
  }
73
- export function TableGrips({ view, state, getPos, frame, box, table, readOnly, focused, onAction, onColor, text }) {
83
+ // How far either side of a column's right edge the pointer can be to take it.
84
+ const EDGE_REACH = 6;
85
+ // How much Narrower and Wider change a column.
86
+ const WIDTH_STEP = 16;
87
+ // The column whose right edge is nearest a point within the table, if one's in reach.
88
+ function edgeAt(table, box, x, y) {
89
+ const area = table.getBoundingClientRect();
90
+ const scroll = box.getBoundingClientRect();
91
+ if (y < area.top || y > area.bottom || x > scroll.right + EDGE_REACH)
92
+ return null;
93
+ const cells = Array.from(table.rows[0]?.cells ?? []);
94
+ let best = null;
95
+ let nearest = EDGE_REACH + 1;
96
+ cells.forEach((cell, column) => {
97
+ const off = Math.abs(cell.getBoundingClientRect().right - x);
98
+ if (off < nearest) {
99
+ nearest = off;
100
+ best = column;
101
+ }
102
+ });
103
+ return best;
104
+ }
105
+ export function TableGrips({ view, state, getPos, frame, box, table, readOnly, focused, onAction, onColor, onWidth, onPreviewWidth, text }) {
74
106
  const [hover, setHover] = useState(null);
75
107
  const [open, setOpen] = useState(null);
76
108
  const [target, setTarget] = useState(null);
@@ -78,6 +110,12 @@ export function TableGrips({ view, state, getPos, frame, box, table, readOnly, f
78
110
  const [, setLayout] = useState(0);
79
111
  const columnGrip = useRef(null);
80
112
  const rowGrip = useRef(null);
113
+ // A column's right edge: the one under the pointer, or the one being dragged.
114
+ const [edge, setEdge] = useState(null);
115
+ const [drag, setDrag] = useState(null);
116
+ const dragging = useRef(false);
117
+ const edgeHandle = useRef(null);
118
+ const phone = useIsMobile();
81
119
  const tablePos = getPos();
82
120
  // The caret's cell, when it's in this table.
83
121
  let caret = null;
@@ -97,8 +135,14 @@ export function TableGrips({ view, state, getPos, frame, box, table, readOnly, f
97
135
  const cell = cellOf(table, event.target);
98
136
  if (cell)
99
137
  setHover((now) => (now && now.row === cell.row && now.column === cell.column ? now : cell));
138
+ if (!dragging.current && event.pointerType === 'mouse')
139
+ setEdge(edgeAt(table, box, event.clientX, event.clientY));
140
+ };
141
+ const onLeave = () => {
142
+ setHover(null);
143
+ if (!dragging.current)
144
+ setEdge(null);
100
145
  };
101
- const onLeave = () => setHover(null);
102
146
  const onLayout = () => setLayout((n) => n + 1);
103
147
  const onMenu = () => {
104
148
  const now = caretRef.current;
@@ -161,6 +205,27 @@ export function TableGrips({ view, state, getPos, frame, box, table, readOnly, f
161
205
  rowButton.style.left = `${scroll.left - origin.left}px`;
162
206
  rowButton.style.top = `${line.top - origin.top + line.height / 2}px`;
163
207
  });
208
+ // The edge's handle, on the column's right edge and as tall as the table
209
+ // (or the box's width of it). While dragged it stays with the pointer's
210
+ // column, even past the box's side.
211
+ useLayoutEffect(() => {
212
+ const handle = edgeHandle.current;
213
+ if (!handle)
214
+ return;
215
+ const cell = edge === null ? undefined : table.rows[0]?.cells[edge];
216
+ if (!cell) {
217
+ handle.hidden = true;
218
+ return;
219
+ }
220
+ const origin = frame.getBoundingClientRect();
221
+ const scroll = box.getBoundingClientRect();
222
+ const area = table.getBoundingClientRect();
223
+ const right = cell.getBoundingClientRect().right;
224
+ handle.hidden = !dragging.current && right > scroll.right + 1;
225
+ handle.style.left = `${Math.min(right, scroll.right) - origin.left}px`;
226
+ handle.style.top = `${area.top - origin.top}px`;
227
+ handle.style.height = `${area.height}px`;
228
+ });
164
229
  if (readOnly || tablePos === undefined || !state)
165
230
  return null;
166
231
  const at = (cell) => (cell ? stateAt(state, tablePos, cell) : null);
@@ -193,6 +258,48 @@ export function TableGrips({ view, state, getPos, frame, box, table, readOnly, f
193
258
  if (cell)
194
259
  later(() => onColor(cell, scope, value));
195
260
  };
261
+ const widthOf = (column) => table.rows[0]?.cells[column]?.getBoundingClientRect().width ?? MIN_COLUMN_WIDTH;
262
+ // Dragging a column's right edge: a preview until the button comes up,
263
+ // then one edit (one undo step). A press that doesn't move changes nothing.
264
+ const startDrag = (event) => {
265
+ if (edge === null || event.button !== 0)
266
+ return;
267
+ event.preventDefault();
268
+ const handle = event.currentTarget;
269
+ const column = edge;
270
+ const startX = event.clientX;
271
+ const startWidth = widthOf(column);
272
+ let width = null;
273
+ handle.setPointerCapture(event.pointerId);
274
+ dragging.current = true;
275
+ const stop = () => {
276
+ dragging.current = false;
277
+ handle.removeEventListener('pointermove', move);
278
+ handle.removeEventListener('pointerup', up);
279
+ handle.removeEventListener('pointercancel', cancel);
280
+ setDrag(null);
281
+ };
282
+ const move = (next) => {
283
+ const caught = catchColumnWidth(startWidth + next.clientX - startX);
284
+ width = caught.width;
285
+ onPreviewWidth(column, width);
286
+ setDrag({ column, label: caught.size ? `${caught.size} · ${width} px` : `${width} px` });
287
+ };
288
+ const up = () => {
289
+ stop();
290
+ if (width === null)
291
+ onPreviewWidth(column, null);
292
+ else
293
+ onWidth(column, width);
294
+ };
295
+ const cancel = () => {
296
+ stop();
297
+ onPreviewWidth(column, null);
298
+ };
299
+ handle.addEventListener('pointermove', move);
300
+ handle.addEventListener('pointerup', up);
301
+ handle.addEventListener('pointercancel', cancel);
302
+ };
196
303
  const items = (list) => list.map(({ action, label, icon: Icon }) => (_jsxs(DropdownMenuItem, { disabled: !enabled(action), onClick: () => run(action), children: [_jsx(Icon, { "aria-hidden": "true" }), label] }, action)));
197
304
  const colorGroup = (scope, label) => {
198
305
  if (!there || !tableColorEnabled(there, scope))
@@ -204,7 +311,14 @@ export function TableGrips({ view, state, getPos, frame, box, table, readOnly, f
204
311
  // A cell says its colour; a row's or a column's cells may differ.
205
312
  value: scope === 'cell' ? (current ?? '') : null, onValueChange: (value) => color(scope, HIGHLIGHT_COLORS.includes(value) ? value : null), children: [HIGHLIGHT_COLORS.map((one) => (_jsxs(DropdownMenuRadioItem, { value: one, closeOnClick: true, children: [_jsx("span", { "aria-hidden": "true", className: cn('size-4 shrink-0 rounded-sm border border-foreground/30', SWATCH[one]) }), one[0].toUpperCase() + one.slice(1)] }, one))), _jsxs(DropdownMenuRadioItem, { value: "", closeOnClick: true, children: [_jsx("span", { "aria-hidden": "true", className: "size-4 shrink-0 rounded-sm border border-foreground/30" }), "No colour"] })] })] }));
206
313
  };
207
- const columnItems = (withColor, label) => (_jsxs(_Fragment, { children: [_jsxs(DropdownMenuGroup, { children: [label && _jsx(DropdownMenuLabel, { children: label }), items(COLUMN_ITEMS)] }), _jsx(DropdownMenuSeparator, {}), _jsxs(DropdownMenuGroup, { children: [_jsx(DropdownMenuLabel, { children: "Align column" }), _jsx(DropdownMenuRadioGroup, { value: there ? columnAlignment(there) : 'left', onValueChange: (value) => {
314
+ const setWidth = there ? columnWidthAt(there) : null;
315
+ const anyWidth = there ? tableHasWidths(there) : false;
316
+ const shownWidth = (column) => setWidth ?? Math.round(widthOf(column));
317
+ const resize = (column, by) => {
318
+ const width = clampColumnWidth(shownWidth(column) + by);
319
+ later(() => onWidth(column, width));
320
+ };
321
+ const columnItems = (withColor, label) => (_jsxs(_Fragment, { children: [_jsxs(DropdownMenuGroup, { children: [label && _jsx(DropdownMenuLabel, { children: label }), items(COLUMN_ITEMS)] }), _jsx(DropdownMenuSeparator, {}), !phone && menuCell && (_jsxs(_Fragment, { children: [_jsxs(DropdownMenuGroup, { children: [_jsxs(DropdownMenuLabel, { children: ["Width: ", setWidth === null ? 'fit to content' : `${setWidth} px`] }), _jsxs(DropdownMenuItem, { disabled: shownWidth(menuCell.column) <= MIN_COLUMN_WIDTH, onClick: () => resize(menuCell.column, -WIDTH_STEP), children: [_jsx(ChevronsRightLeftIcon, { "aria-hidden": "true" }), "Narrower"] }), _jsxs(DropdownMenuItem, { disabled: shownWidth(menuCell.column) >= MAX_COLUMN_WIDTH, onClick: () => resize(menuCell.column, WIDTH_STEP), children: [_jsx(ChevronsLeftRightIcon, { "aria-hidden": "true" }), "Wider"] }), _jsxs(DropdownMenuItem, { disabled: setWidth === null, onClick: () => later(() => onWidth(menuCell.column, null)), children: [_jsx(MoveHorizontalIcon, { "aria-hidden": "true" }), "Fit to content"] }), _jsxs(DropdownMenuItem, { disabled: !anyWidth, onClick: () => later(() => onWidth(menuCell.column, 'all')), children: [_jsx(Columns3Icon, { "aria-hidden": "true" }), "Fit all columns"] })] }), _jsx(DropdownMenuSeparator, {})] })), _jsxs(DropdownMenuGroup, { children: [_jsx(DropdownMenuLabel, { children: "Align column" }), _jsx(DropdownMenuRadioGroup, { value: there ? columnAlignment(there) : 'left', onValueChange: (value) => {
208
322
  const one = ALIGNMENTS.find((alignment) => alignment.value === value);
209
323
  if (one)
210
324
  run(one.action);
@@ -212,5 +326,5 @@ export function TableGrips({ view, state, getPos, frame, box, table, readOnly, f
212
326
  const rowColor = there && tableColorEnabled(there, 'row');
213
327
  const finalFocus = () => text() ?? true;
214
328
  const grip = 'pointer-events-auto absolute flex items-center justify-center rounded-sm border border-border bg-muted text-muted-foreground shadow-xs outline-none hover:bg-primary hover:text-primary-foreground data-popup-open:bg-primary data-popup-open:text-primary-foreground';
215
- return (_jsxs(_Fragment, { children: [_jsxs(DropdownMenu, { open: open === 'column' || open === 'cell', onOpenChange: openMenu('column'), children: [_jsx(DropdownMenuTrigger, { tabIndex: -1, "aria-label": menuCell ? `Column: ${columnName(menuCell.column)}` : 'Column', ref: columnGrip, "data-slot": "rich-text-table-column-grip", className: cn(grip, 'h-3.5 w-6 -translate-x-1/2 -translate-y-1/2'), children: _jsx(GripHorizontalIcon, { "aria-hidden": "true", className: "size-3" }) }), _jsx(DropdownMenuContent, { className: "w-56", "data-rich-text-menu": "", finalFocus: finalFocus, children: open === 'cell' ? (_jsxs(_Fragment, { children: [menuCell && menuCell.row > 0 && (_jsxs(_Fragment, { children: [colorGroup('cell', 'Cell colour'), _jsx(DropdownMenuSeparator, {})] })), _jsxs(DropdownMenuGroup, { children: [_jsx(DropdownMenuLabel, { children: "Row" }), items(ROW_ITEMS)] }), _jsx(DropdownMenuSeparator, {}), columnItems(false, menuCell ? `Column: ${columnName(menuCell.column)}` : 'Column')] })) : (columnItems(true)) })] }), _jsxs(DropdownMenu, { open: open === 'row', onOpenChange: openMenu('row'), children: [_jsx(DropdownMenuTrigger, { tabIndex: -1, "aria-label": menuCell ? (menuCell.row === 0 ? 'Header row' : `Row ${menuCell.row}`) : 'Row', ref: rowGrip, "data-slot": "rich-text-table-row-grip", className: cn(grip, 'h-6 w-3.5 -translate-x-1/2 -translate-y-1/2'), children: _jsx(GripVerticalIcon, { "aria-hidden": "true", className: "size-3" }) }), _jsxs(DropdownMenuContent, { className: "w-56", "data-rich-text-menu": "", finalFocus: finalFocus, children: [_jsx(DropdownMenuGroup, { children: items(ROW_ITEMS) }), rowColor && (_jsxs(_Fragment, { children: [_jsx(DropdownMenuSeparator, {}), colorGroup('row', 'Colour row')] }))] })] })] }));
329
+ return (_jsxs(_Fragment, { children: [!phone && (_jsxs("div", { ref: edgeHandle, hidden: true, "aria-hidden": "true", "data-slot": "rich-text-table-column-edge", className: "pointer-events-auto absolute z-10 flex w-3 -translate-x-1/2 cursor-col-resize touch-none justify-center", onPointerDown: startDrag, onDoubleClick: () => edge !== null && onWidth(edge, null), children: [_jsx("span", { className: "h-full w-0.5 bg-primary" }), drag && (_jsx("span", { "data-slot": "rich-text-table-column-size", className: "absolute bottom-full mb-1 rounded-sm bg-primary px-1.5 font-mono text-xs whitespace-nowrap text-primary-foreground tabular-nums", children: drag.label }))] })), _jsxs(DropdownMenu, { open: open === 'column' || open === 'cell', onOpenChange: openMenu('column'), children: [_jsx(DropdownMenuTrigger, { tabIndex: -1, "aria-label": menuCell ? `Column: ${columnName(menuCell.column)}` : 'Column', ref: columnGrip, "data-slot": "rich-text-table-column-grip", className: cn(grip, 'h-3.5 w-6 -translate-x-1/2 -translate-y-1/2'), children: _jsx(GripHorizontalIcon, { "aria-hidden": "true", className: "size-3" }) }), _jsx(DropdownMenuContent, { className: "w-56", "data-rich-text-menu": "", finalFocus: finalFocus, children: open === 'cell' ? (_jsxs(_Fragment, { children: [menuCell && menuCell.row > 0 && (_jsxs(_Fragment, { children: [colorGroup('cell', 'Cell colour'), _jsx(DropdownMenuSeparator, {})] })), _jsxs(DropdownMenuGroup, { children: [_jsx(DropdownMenuLabel, { children: "Row" }), items(ROW_ITEMS)] }), _jsx(DropdownMenuSeparator, {}), columnItems(false, menuCell ? `Column: ${columnName(menuCell.column)}` : 'Column')] })) : (columnItems(true)) })] }), _jsxs(DropdownMenu, { open: open === 'row', onOpenChange: openMenu('row'), children: [_jsx(DropdownMenuTrigger, { tabIndex: -1, "aria-label": menuCell ? (menuCell.row === 0 ? 'Header row' : `Row ${menuCell.row}`) : 'Row', ref: rowGrip, "data-slot": "rich-text-table-row-grip", className: cn(grip, 'h-6 w-3.5 -translate-x-1/2 -translate-y-1/2'), children: _jsx(GripVerticalIcon, { "aria-hidden": "true", className: "size-3" }) }), _jsxs(DropdownMenuContent, { className: "w-56", "data-rich-text-menu": "", finalFocus: finalFocus, children: [_jsx(DropdownMenuGroup, { children: items(ROW_ITEMS) }), rowColor && (_jsxs(_Fragment, { children: [_jsx(DropdownMenuSeparator, {}), colorGroup('row', 'Colour row')] }))] })] })] }));
216
330
  }
@@ -1,8 +1,15 @@
1
+ import { type Node as ProseNode } from '@milkdown/kit/prose/model';
1
2
  import { Plugin, type EditorState, type Transaction } from '@milkdown/kit/prose/state';
2
3
  import { type HighlightColor } from '../../lib/markdown-highlight.js';
3
4
  type Dispatch = (tr: Transaction) => void;
4
5
  export type TableAction = 'rowAbove' | 'rowBelow' | 'columnLeft' | 'columnRight' | 'alignLeft' | 'alignCenter' | 'alignRight' | 'deleteRow' | 'deleteColumn' | 'deleteTable' | 'moveRowUp' | 'moveRowDown' | 'moveColumnLeft' | 'moveColumnRight' | 'sortAscending' | 'sortDescending' | 'headerColumn';
5
6
  export type ColumnAlignment = 'left' | 'center' | 'right';
7
+ /** A column being dragged to a width: the table's position, the column and the width so far. */
8
+ export type ColumnDrag = {
9
+ tablePos: number;
10
+ column: number;
11
+ width: number;
12
+ };
6
13
  /** The caret's column's alignment, as the header cell has it (GFM's default is left). */
7
14
  export declare function columnAlignment(state: EditorState): ColumnAlignment;
8
15
  /** Whether an action can apply where the caret is. */
@@ -23,8 +30,23 @@ export declare function cellColorAt(state: EditorState): HighlightColor | null;
23
30
  * needs words.
24
31
  */
25
32
  export declare function colorTableCells(state: EditorState, dispatch: Dispatch, scope: TableColorScope, color: HighlightColor | null): boolean;
26
- /** The plugin that draws cell colours and a header column (tableDecorations). */
33
+ /** The plugin that draws cell colours, a header column and column widths (tableDecorations). */
27
34
  export declare function tableLook(): Plugin;
35
+ /** Shows a column at a width while it's dragged, changing nothing; `null` ends it. */
36
+ export declare function previewColumnWidth(state: EditorState, dispatch: Dispatch, drag: ColumnDrag | null): void;
37
+ /** A column's width (`null`: automatic), set on its cells. One undo step. */
38
+ export declare function setColumnWidth(state: EditorState, dispatch: Dispatch, tablePos: number, column: number, width: number | null): boolean;
39
+ /** Every column back to automatic. One undo step. */
40
+ export declare function fitAllColumns(state: EditorState, dispatch: Dispatch, tablePos: number): boolean;
41
+ /** The caret's column's width, or null when it's automatic. */
42
+ export declare function columnWidthAt(state: EditorState): number | null;
43
+ /** Whether the caret's table has a column with a width set. */
44
+ export declare function tableHasWidths(state: EditorState): boolean;
45
+ /** A table node's header texts and their widths, for its comment. */
46
+ export declare function tableWidthsOf(table: ProseNode): {
47
+ headers: string[];
48
+ widths: (number | null)[];
49
+ };
28
50
  /**
29
51
  * The editor's table keys, before Milkdown's own (which go to the next
30
52
  * cell on Tab, and out of the table on any Enter). True when it handled
@@ -17,6 +17,12 @@
17
17
  // deleted or have a row put above it). Alignment is per column, as the
18
18
  // Markdown writes it (`:---:`).
19
19
  //
20
+ // A column's width is on its cells (`colwidth`), kept in the Markdown as a
21
+ // comment after the table (src/lib/markdown-table-widths.ts). Moves and
22
+ // sorts carry it with the cells, and prosemirror-tables' fixTables gives a
23
+ // new row's cells their column's width. One drag is one undo step: while
24
+ // it runs the width is a decoration only (previewColumnWidth).
25
+ //
20
26
  // Keys (handleTableKey), on top of Milkdown's Tab/Shift+Tab between cells:
21
27
  // Tab in the last cell adds a row; Enter goes to the cell below, and out
22
28
  // of the table from its last row; Shift+Enter does nothing (a line break
@@ -251,20 +257,25 @@ export function colorTableCells(state, dispatch, scope, color) {
251
257
  return true;
252
258
  }
253
259
  // The decorations that draw what the Markdown keeps: a coloured cell's
254
- // wash (`data-color`) and a header column's first cells (`data-row-header`),
255
- // styled in styles/index.css ("Tables in written text").
256
- function tableDecorations(doc) {
260
+ // wash (`data-color`), a header column's first cells (`data-row-header`)
261
+ // and a column's width (`data-column-width`, or the width it's being
262
+ // dragged to), styled in styles/index.css ("Tables in written text").
263
+ function tableDecorations(doc, drag) {
257
264
  const decorations = [];
258
265
  doc.descendants((node, pos) => {
259
266
  if (node.type.name !== 'table')
260
267
  return node.isBlock && !node.isTextblock;
261
268
  const tableStart = pos + 1;
262
269
  node.forEach((row, rowOffset) => {
263
- row.forEach((cell, cellOffset) => {
270
+ row.forEach((cell, cellOffset, column) => {
264
271
  const color = cellColor(runsOf(cell));
265
272
  const at = tableStart + rowOffset + 1 + cellOffset;
266
273
  if (color)
267
274
  decorations.push(Decoration.node(at, at + cell.nodeSize, { 'data-color': color }));
275
+ const width = drag && drag.tablePos === pos && drag.column === column ? drag.width : widthOf(cell);
276
+ if (width !== null) {
277
+ decorations.push(Decoration.node(at, at + cell.nodeSize, { 'data-column-width': String(width), style: `--column-width: ${width}px` }));
278
+ }
268
279
  });
269
280
  });
270
281
  const firsts = firstCells(node, tableStart);
@@ -276,16 +287,95 @@ function tableDecorations(doc) {
276
287
  return DecorationSet.create(doc, decorations);
277
288
  }
278
289
  const tableLookKey = new PluginKey('tableLook');
279
- /** The plugin that draws cell colours and a header column (tableDecorations). */
290
+ /** The plugin that draws cell colours, a header column and column widths (tableDecorations). */
280
291
  export function tableLook() {
281
292
  return new Plugin({
282
293
  key: tableLookKey,
283
294
  state: {
284
- init: (_config, state) => tableDecorations(state.doc),
285
- apply: (tr, previous) => (tr.docChanged ? tableDecorations(tr.doc) : previous),
295
+ init: (_config, state) => ({ set: tableDecorations(state.doc, null), drag: null }),
296
+ apply: (tr, previous) => {
297
+ const meta = tr.getMeta(tableLookKey);
298
+ if (meta === undefined && !tr.docChanged)
299
+ return previous;
300
+ // A change to the text ends a drag's preview (its table may have moved).
301
+ const drag = meta === undefined ? null : meta;
302
+ return { set: tableDecorations(tr.doc, drag), drag };
303
+ },
286
304
  },
287
- props: { decorations: (state) => tableLookKey.getState(state) },
305
+ props: { decorations: (state) => tableLookKey.getState(state)?.set },
306
+ });
307
+ }
308
+ /** Shows a column at a width while it's dragged, changing nothing; `null` ends it. */
309
+ export function previewColumnWidth(state, dispatch, drag) {
310
+ dispatch(state.tr.setMeta(tableLookKey, drag).setMeta('addToHistory', false));
311
+ }
312
+ /** A column's width (`null`: automatic), set on its cells. One undo step. */
313
+ export function setColumnWidth(state, dispatch, tablePos, column, width) {
314
+ const table = state.doc.nodeAt(tablePos);
315
+ if (table?.type.name !== 'table')
316
+ return false;
317
+ const map = TableMap.get(table);
318
+ if (column >= map.width)
319
+ return false;
320
+ const tr = state.tr;
321
+ writeColumnWidth(tr, table, tablePos, map, column, width);
322
+ if (tr.docChanged)
323
+ dispatch(closeHistory(tr));
324
+ else
325
+ previewColumnWidth(state, dispatch, null);
326
+ return true;
327
+ }
328
+ /** Every column back to automatic. One undo step. */
329
+ export function fitAllColumns(state, dispatch, tablePos) {
330
+ const table = state.doc.nodeAt(tablePos);
331
+ if (table?.type.name !== 'table')
332
+ return false;
333
+ const map = TableMap.get(table);
334
+ const tr = state.tr;
335
+ for (let column = 0; column < map.width; column++)
336
+ writeColumnWidth(tr, table, tablePos, map, column, null);
337
+ if (tr.docChanged)
338
+ dispatch(closeHistory(tr));
339
+ return true;
340
+ }
341
+ function writeColumnWidth(tr, table, tablePos, map, column, width) {
342
+ const colwidth = width === null ? null : [width];
343
+ for (let row = 0; row < map.height; row++) {
344
+ const at = map.map[row * map.width + column];
345
+ const cell = table.nodeAt(at);
346
+ if (widthOf(cell) !== width)
347
+ tr.setNodeMarkup(tablePos + 1 + at, undefined, { ...cell.attrs, colwidth });
348
+ }
349
+ }
350
+ const widthOf = (cell) => cell?.attrs.colwidth?.[0] ?? null;
351
+ /** The caret's column's width, or null when it's automatic. */
352
+ export function columnWidthAt(state) {
353
+ if (!isInTable(state))
354
+ return null;
355
+ const { map, table, left } = selectedRect(state);
356
+ return widthOf(table.nodeAt(map.map[left]));
357
+ }
358
+ /** Whether the caret's table has a column with a width set. */
359
+ export function tableHasWidths(state) {
360
+ if (!isInTable(state))
361
+ return false;
362
+ const header = selectedRect(state).table.firstChild;
363
+ let found = false;
364
+ header?.forEach((cell) => {
365
+ if (widthOf(cell) !== null)
366
+ found = true;
367
+ });
368
+ return found;
369
+ }
370
+ /** A table node's header texts and their widths, for its comment. */
371
+ export function tableWidthsOf(table) {
372
+ const headers = [];
373
+ const widths = [];
374
+ table.firstChild?.forEach((cell) => {
375
+ headers.push(cell.textContent);
376
+ widths.push(widthOf(cell));
288
377
  });
378
+ return { headers, widths };
289
379
  }
290
380
  // A row of empty cells, each aligned as its column is, above or below the
291
381
  // caret's rows (or at the end: `'end'`), and the caret into it in the
@@ -5,7 +5,8 @@
5
5
  // ==amber, the default== =={yellow}yellow== =={green}green== =={red}red==
6
6
  //
7
7
  // It's plain text where nothing reads it (the marks show), and no HTML:
8
- // <Markdown> never renders raw HTML, and the editor never writes any.
8
+ // <Markdown> never renders raw HTML, and the editor writes none but a
9
+ // table's widths comment (markdown-table-widths.ts).
9
10
  // remark has no highlight, so these plugins read the marks from the text
10
11
  // nodes of a parsed document: `remarkHighlights` for <Markdown> (a `mark`
11
12
  // element with `data-color`) and `remarkHighlightNodes` for the rich-text
@@ -25,9 +25,13 @@
25
25
  // - Guard: the result must mean exactly what the editor shows. If it
26
26
  // wouldn't (two blocks fusing, say), the merge throws instead of saving
27
27
  // something else; the draft stays on screen.
28
+ // - A table and the comment after it that keeps its column widths
29
+ // (markdown-table-widths.ts) are one block: a width changed in the editor
30
+ // is an edit to the table, and an unchanged one keeps the comment as written.
28
31
  import remarkGfm from 'remark-gfm';
29
32
  import remarkParse from 'remark-parse';
30
33
  import { unified } from 'unified';
34
+ import { widthsAfterTable } from './markdown-table-widths.js';
31
35
  const processor = unified().use(remarkParse).use(remarkGfm);
32
36
  function parse(markdown) {
33
37
  return processor.runSync(processor.parse(markdown));
@@ -140,18 +144,26 @@ function blocks(markdown) {
140
144
  for (const child of children)
141
145
  if (child.type === 'definition')
142
146
  definitions.set(String(child.identifier), child);
143
- return children.map((child) => {
147
+ const out = [];
148
+ for (let index = 0; index < children.length; index++) {
149
+ const child = children[index];
150
+ // A table's widths are part of it: the comment is taken with the table.
151
+ const widths = child.type === 'table' ? widthsAfterTable(child, children[index + 1]) : null;
152
+ const last = widths ? children[++index] : child;
144
153
  const start = child.position?.start.offset ?? 0;
145
- const end = child.position?.end.offset ?? 0;
146
- return {
154
+ const end = last.position?.end.offset ?? 0;
155
+ const key = meaning(child, definitions);
156
+ out.push({
147
157
  type: child.type,
148
158
  start,
149
159
  end,
150
160
  source: markdown.slice(start, end),
151
- key: JSON.stringify(meaning(child, definitions)),
161
+ // Tables with no width set read as they always have.
162
+ key: JSON.stringify(widths?.some((width) => width !== null) ? [key, widths] : key),
152
163
  content: content(child, definitions),
153
- };
154
- });
164
+ });
165
+ }
166
+ return out;
155
167
  }
156
168
  // Longest common subsequence by meaning: which `to` block is which `from`
157
169
  // block, as a map from `to` index to `from` index.
@@ -0,0 +1,51 @@
1
+ export declare const MIN_COLUMN_WIDTH = 56;
2
+ export declare const MAX_COLUMN_WIDTH = 1200;
3
+ /** The sizes a dragged edge catches on, within `COLUMN_CATCH` pixels. */
4
+ export declare const COLUMN_SIZES: readonly [{
5
+ readonly label: "S";
6
+ readonly width: 96;
7
+ }, {
8
+ readonly label: "M";
9
+ readonly width: 160;
10
+ }, {
11
+ readonly label: "L";
12
+ readonly width: 256;
13
+ }, {
14
+ readonly label: "XL";
15
+ readonly width: 384;
16
+ }];
17
+ export declare const COLUMN_CATCH = 10;
18
+ /** A width within the limits, whole pixels. */
19
+ export declare function clampColumnWidth(width: number): number;
20
+ /** A dragged width: within the limits, and on a size when it's that close to one. */
21
+ export declare function catchColumnWidth(width: number): {
22
+ width: number;
23
+ size: string | null;
24
+ };
25
+ type Entry = {
26
+ name: string;
27
+ width: number;
28
+ } | {
29
+ position: number;
30
+ width: number;
31
+ };
32
+ /** The entries of a widths comment, or null when it isn't one. */
33
+ export declare function parseTableWidths(comment: string): Entry[] | null;
34
+ /** Each column's width, in order: null is automatic. */
35
+ export declare function resolveTableWidths(entries: readonly Entry[], headers: readonly string[]): (number | null)[];
36
+ /** The comment for these columns' widths, or null when they're all automatic. */
37
+ export declare function formatTableWidths(headers: readonly string[], widths: readonly (number | null | undefined)[]): string | null;
38
+ type MdNode = {
39
+ type: string;
40
+ value?: string;
41
+ children?: MdNode[];
42
+ data?: Record<string, unknown>;
43
+ [key: string]: unknown;
44
+ };
45
+ /** A table node's header texts, as a reader sees them. */
46
+ export declare function tableHeaders(table: MdNode): string[];
47
+ /** The widths the block after a table gives it, or null when it gives none. */
48
+ export declare function widthsAfterTable(table: MdNode, next: MdNode | undefined): (number | null)[] | null;
49
+ /** Takes each widths comment off the tree and puts its widths on its table's cells. */
50
+ export declare function remarkTableWidths(): (tree: unknown) => void;
51
+ export {};