@tristan2828/ui-foundation 4.78.0 → 4.79.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.
@@ -15,22 +15,22 @@
15
15
  - [Depth ramps](#depth-ramps) · lines 408–486
16
16
  - [A stored colour](#a-stored-colour) · lines 488–536
17
17
  - [Shapes and sizes](#shapes-and-sizes) · lines 538–559
18
- - [Typography](#typography) · lines 561–671
19
- - [Written text (notes)](#written-text-notes) · lines 595–671
20
- - [Density](#density) · lines 673–759
21
- - [Rows on this device](#rows-on-this-device) · lines 732–759
22
- - [Widget cards (hub pages)](#widget-cards-hub-pages) · lines 761–875
23
- - [Module cards (a hub's places)](#module-cards-a-hubs-places) · lines 877–954
24
- - [Notices](#notices) · lines 956–984
25
- - [A value over time](#a-value-over-time) · lines 986–1072
26
- - [Several values over time](#several-values-over-time) · lines 1035–1072
27
- - [A list as a board](#a-list-as-a-board) · lines 1074–1125
28
- - [A list as cards](#a-list-as-cards) · lines 1127–1173
29
- - [Key numbers on a record](#key-numbers-on-a-record) · lines 1175–1197
30
- - [A record's tabs, mark and rail](#a-records-tabs-mark-and-rail) · lines 1199–1243
31
- - [Picking at random](#picking-at-random) · lines 1245–1276
32
- - [Filling in what's missing](#filling-in-whats-missing) · lines 1278–1345
33
- - [Values edited in place: the presets' looks](#values-edited-in-place-the-presets-looks) · lines 1347–1372
18
+ - [Typography](#typography) · lines 561–681
19
+ - [Written text (notes)](#written-text-notes) · lines 595–681
20
+ - [Density](#density) · lines 683–769
21
+ - [Rows on this device](#rows-on-this-device) · lines 742–769
22
+ - [Widget cards (hub pages)](#widget-cards-hub-pages) · lines 771–885
23
+ - [Module cards (a hub's places)](#module-cards-a-hubs-places) · lines 887–964
24
+ - [Notices](#notices) · lines 966–994
25
+ - [A value over time](#a-value-over-time) · lines 996–1082
26
+ - [Several values over time](#several-values-over-time) · lines 1045–1082
27
+ - [A list as a board](#a-list-as-a-board) · lines 1084–1135
28
+ - [A list as cards](#a-list-as-cards) · lines 1137–1183
29
+ - [Key numbers on a record](#key-numbers-on-a-record) · lines 1185–1207
30
+ - [A record's tabs, mark and rail](#a-records-tabs-mark-and-rail) · lines 1209–1253
31
+ - [Picking at random](#picking-at-random) · lines 1255–1286
32
+ - [Filling in what's missing](#filling-in-whats-missing) · lines 1288–1355
33
+ - [Values edited in place: the presets' looks](#values-edited-in-place-the-presets-looks) · lines 1357–1382
34
34
 
35
35
  <!-- /index -->
36
36
 
@@ -627,6 +627,16 @@ puts the text's own highest heading at `headingLevel` instead, the rest
627
627
  keeping their distance from it (the editor reads it from the text it
628
628
  opens with). The text isn't rewritten.
629
629
 
630
+ A column in a written table can have a width: dragged at its right edge
631
+ in `RichTextEditor` (the edge catches on 96, 160, 256 and 384px, 56px at
632
+ least), a column's menu has Narrower, Wider, Fit to content and Fit all
633
+ columns, and a double-click on the edge fits it again. The width is kept
634
+ in the Markdown as a comment after the table, naming its columns
635
+ (`<!-- table widths: Item=140, Cost=72 -->`), which `<Markdown>` and the
636
+ editor read and never show. A column named nowhere fits its words. A
637
+ phone ignores the widths and can't set them; on paper they scale to the
638
+ page.
639
+
630
640
  A table wider than the text scrolls sideways. While it does, its box is a
631
641
  tab stop and a region named "Table, scrolls sideways: " and its first
632
642
  columns ("Item, Size, Colour, …"), so two such tables keep distinct
@@ -7,7 +7,8 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
7
7
  // Safe by default, and kept that way on purpose:
8
8
  // - Raw HTML is never rendered. react-markdown escapes it, so `<b>` in the
9
9
  // text shows as the characters `<b>`, never as markup, and nothing the
10
- // author typed silently disappears. Never add rehype-raw.
10
+ // author typed silently disappears. Never add rehype-raw. The one thing
11
+ // taken out is a table's widths comment, read as its column widths.
11
12
  // - URLs go through react-markdown's default urlTransform, which drops
12
13
  // `javascript:` and other unsafe protocols. A link left with no URL
13
14
  // renders as its text.
@@ -28,6 +29,9 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
28
29
  // (`tableLook`, as on RichTextEditor: styles/index.css "Tables in written
29
30
  // text"). A cell whose whole text is one highlight is painted in it, and
30
31
  // a first column of bold cells is row headers (src/lib/markdown-table.ts).
32
+ // A column the rich-text editor set a width for keeps it, from the comment
33
+ // after the table (src/lib/markdown-table-widths.ts); on a phone columns
34
+ // still fit their words, and on paper the widths scale to the page.
31
35
  // A table wider than the text scrolls sideways, and while it does, its
32
36
  // box is a tab stop, named for its columns, that the arrow keys scroll
33
37
  // (prose-table-scroll.ts). Its cells wrap first, so that's only a table
@@ -88,6 +92,7 @@ import { rehypeFold, toggleFold } from '../../lib/markdown-fold.js';
88
92
  import { rehypeInline } from '../../lib/markdown-inline.js';
89
93
  import { isHighlightColor, remarkHighlights } from '../../lib/markdown-highlight.js';
90
94
  import { rehypeTables } from '../../lib/markdown-table.js';
95
+ import { remarkTableWidths } from '../../lib/markdown-table-widths.js';
91
96
  import { remarkToggleHeadings } from '../../lib/markdown-toggle.js';
92
97
  import { toggleTaskAt } from '../../lib/markdown-tasks.js';
93
98
  import { textTopHeading } from '../../lib/markdown-top-heading.js';
@@ -95,7 +100,7 @@ import { CALLOUT_BOX, CALLOUT_LOOK, DEFAULT_HEADING_LEVEL, FOLD_BUTTON, FOLD_HEA
95
100
  import { PageLinkView } from './page-link.js';
96
101
  import { usePrinting } from './print-context.js';
97
102
  import { headerTexts, TABLE_SCROLL_FOCUS, watchTableScroll } from './prose-table-scroll.js';
98
- const REMARK_PLUGINS = [remarkGfm, remarkCallouts, remarkHighlights, remarkToggleHeadings];
103
+ const REMARK_PLUGINS = [remarkGfm, remarkCallouts, remarkHighlights, remarkToggleHeadings, remarkTableWidths];
99
104
  const HIGHLIGHT_WASH = {
100
105
  amber: 'bg-highlight-amber',
101
106
  yellow: 'bg-highlight-yellow',
@@ -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 {};
@@ -0,0 +1,179 @@
1
+ // A table's column widths, kept in the Markdown as one comment after the
2
+ // table, naming its columns (the developer's choice, 2026-11-09):
3
+ //
4
+ // | Item | Room | Cost |
5
+ // | ---- | ---- | ---: |
6
+ // | Paint | Hall | $42 |
7
+ //
8
+ // <!-- table widths: Item=140, Cost=72 -->
9
+ //
10
+ // GFM has nowhere to put a width, and the table has to stay a table to
11
+ // everything else that reads it. A comment hides itself on GitHub and in
12
+ // other renderers, and a chat or the connector can read or change it.
13
+ // By name, so a column moved outside the editor keeps its width: a
14
+ // column named nowhere is automatic (fit to its words), a name no column
15
+ // has is ignored. A blank or repeated header can't be named, and is its
16
+ // place instead (`#3=72`). A header that isn't plain words is quoted, as
17
+ // JSON (`"Cost, each"=72`).
18
+ //
19
+ // It's the one piece of HTML the rich-text editor writes, and neither
20
+ // renderer shows it: `remarkTableWidths` takes it off the tree and puts
21
+ // each width on its column's cells. A comment that isn't this one, or
22
+ // isn't straight after a table, is any other raw HTML: shown as its
23
+ // characters, never lost.
24
+ //
25
+ // Widths are pixels. In the editor they sit on the cells (ProseMirror's
26
+ // `colwidth`), so a column moved, added or deleted there, and a row added
27
+ // or sorted there, keeps them right; the comment is written from the
28
+ // cells on each save. Styled in styles/index.css ("Tables in written
29
+ // text"): a phone keeps fitting columns to their words.
30
+ export const MIN_COLUMN_WIDTH = 56;
31
+ export const MAX_COLUMN_WIDTH = 1200;
32
+ /** The sizes a dragged edge catches on, within `COLUMN_CATCH` pixels. */
33
+ export const COLUMN_SIZES = [
34
+ { label: 'S', width: 96 },
35
+ { label: 'M', width: 160 },
36
+ { label: 'L', width: 256 },
37
+ { label: 'XL', width: 384 },
38
+ ];
39
+ export const COLUMN_CATCH = 10;
40
+ /** A width within the limits, whole pixels. */
41
+ export function clampColumnWidth(width) {
42
+ return Math.min(MAX_COLUMN_WIDTH, Math.max(MIN_COLUMN_WIDTH, Math.round(width)));
43
+ }
44
+ /** A dragged width: within the limits, and on a size when it's that close to one. */
45
+ export function catchColumnWidth(width) {
46
+ const clamped = clampColumnWidth(width);
47
+ const size = COLUMN_SIZES.find((one) => Math.abs(one.width - clamped) <= COLUMN_CATCH);
48
+ return size ? { width: size.width, size: size.label } : { width: clamped, size: null };
49
+ }
50
+ const COMMENT = /^<!--\s*table widths:\s*(.*?)\s*-->\s*$/s;
51
+ // One `key=width`: a quoted name, a place (`#3`), or bare words.
52
+ const ENTRY = /\s*(?:("(?:[^"\\]|\\.)*")|#(\d+)|([^,="]+?))\s*=\s*(\d+)\s*(,|$)/y;
53
+ /** The entries of a widths comment, or null when it isn't one. */
54
+ export function parseTableWidths(comment) {
55
+ const body = COMMENT.exec(comment.trim())?.[1];
56
+ if (!body)
57
+ return null;
58
+ const entries = [];
59
+ ENTRY.lastIndex = 0;
60
+ for (;;) {
61
+ const at = ENTRY.lastIndex;
62
+ const found = ENTRY.exec(body);
63
+ if (!found)
64
+ return null;
65
+ const [, quoted, position, bare, width, separator] = found;
66
+ let name = bare;
67
+ if (quoted !== undefined) {
68
+ try {
69
+ name = JSON.parse(quoted);
70
+ }
71
+ catch {
72
+ return null;
73
+ }
74
+ }
75
+ if (position !== undefined)
76
+ entries.push({ position: Number(position), width: Number(width) });
77
+ else
78
+ entries.push({ name: cleanHeader(name), width: Number(width) });
79
+ if (!separator)
80
+ break;
81
+ // A `,` with nothing after it isn't one of ours.
82
+ if (ENTRY.lastIndex === at || ENTRY.lastIndex >= body.length)
83
+ return null;
84
+ }
85
+ return entries;
86
+ }
87
+ const cleanHeader = (text) => text.replace(/\s+/g, ' ').trim();
88
+ /** Each column's width, in order: null is automatic. */
89
+ export function resolveTableWidths(entries, headers) {
90
+ const names = headers.map(cleanHeader);
91
+ const widths = headers.map(() => null);
92
+ const used = new Set();
93
+ for (const entry of entries) {
94
+ const index = 'position' in entry
95
+ ? entry.position - 1
96
+ : names.findIndex((name, column) => name === entry.name && name !== '' && !used.has(column));
97
+ if (index < 0 || index >= headers.length)
98
+ continue;
99
+ used.add(index);
100
+ widths[index] = clampColumnWidth(entry.width);
101
+ }
102
+ return widths;
103
+ }
104
+ // A name that can sit bare in the comment. `--` could end the comment, and
105
+ // `#3` would read as a place.
106
+ const isBare = (name) => /^[^,="\\<>\r\n]+$/.test(name) && !name.includes('--') && !/^#\d+$/.test(name);
107
+ // Quoted as JSON, with what could end the comment as an escape.
108
+ const quoted = (name) => JSON.stringify(name).replace(/-/g, '\\u002d').replace(/>/g, '\\u003e');
109
+ /** The comment for these columns' widths, or null when they're all automatic. */
110
+ export function formatTableWidths(headers, widths) {
111
+ const names = headers.map(cleanHeader);
112
+ const entries = [];
113
+ names.forEach((name, column) => {
114
+ const width = widths[column];
115
+ if (width === null || width === undefined)
116
+ return;
117
+ const nameable = name !== '' && names.indexOf(name) === names.lastIndexOf(name);
118
+ entries.push(`${nameable ? (isBare(name) ? name : quoted(name)) : `#${column + 1}`}=${width}`);
119
+ });
120
+ return entries.length ? `<!-- table widths: ${entries.join(', ')} -->` : null;
121
+ }
122
+ // `==words==` and `=={green}words==`: text to a tree the highlights
123
+ // haven't been read from (the merge's), so a header's name is the same
124
+ // in every tree.
125
+ const HIGHLIGHT = /==(?:\{(?:amber|yellow|green|red)\})?(\S(?:.*?\S)?)==/g;
126
+ function textOf(node) {
127
+ if (typeof node.value === 'string')
128
+ return node.value;
129
+ return (node.children ?? []).map(textOf).join('');
130
+ }
131
+ /** A table node's header texts, as a reader sees them. */
132
+ export function tableHeaders(table) {
133
+ return (table.children?.[0]?.children ?? []).map((cell) => cleanHeader(textOf(cell).replace(HIGHLIGHT, '$1')));
134
+ }
135
+ /** The widths the block after a table gives it, or null when it gives none. */
136
+ export function widthsAfterTable(table, next) {
137
+ // The rich-text editor's commonmark preset wraps a block of HTML in a
138
+ // paragraph before this reads it.
139
+ const block = next?.type === 'paragraph' && next.children?.length === 1 ? next.children[0] : next;
140
+ if (block?.type !== 'html' || typeof block.value !== 'string')
141
+ return null;
142
+ const entries = parseTableWidths(block.value);
143
+ return entries && resolveTableWidths(entries, tableHeaders(table));
144
+ }
145
+ function putOnCells(table, widths) {
146
+ for (const row of table.children ?? []) {
147
+ ;
148
+ (row.children ?? []).forEach((cell, column) => {
149
+ const width = widths[column];
150
+ if (width === null || width === undefined)
151
+ return;
152
+ // The editor's parser reads `columnWidth`; the read view's HTML
153
+ // takes `hProperties`.
154
+ cell.columnWidth = width;
155
+ cell.data = { ...cell.data, hProperties: { dataColumnWidth: String(width), style: `--column-width: ${width}px` } };
156
+ });
157
+ }
158
+ }
159
+ function walk(parent) {
160
+ const children = parent.children;
161
+ if (!children)
162
+ return;
163
+ for (let index = 0; index < children.length; index++) {
164
+ const node = children[index];
165
+ if (node.type !== 'table') {
166
+ walk(node);
167
+ continue;
168
+ }
169
+ const widths = widthsAfterTable(node, children[index + 1]);
170
+ if (!widths)
171
+ continue;
172
+ putOnCells(node, widths);
173
+ children.splice(index + 1, 1);
174
+ }
175
+ }
176
+ /** Takes each widths comment off the tree and puts its widths on its table's cells. */
177
+ export function remarkTableWidths() {
178
+ return (tree) => walk(tree);
179
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tristan2828/ui-foundation",
3
- "version": "4.78.0",
3
+ "version": "4.79.0",
4
4
  "description": "Shared UI foundation for contract-first, database-backed React apps: shadcn primitives, DataTable/EntityForm composites, auth, the gateway error seam, design tokens, lint rules and the AI playbook.",
5
5
  "license": "MIT",
6
6
  "repository": {
package/styles/index.css CHANGED
@@ -360,6 +360,10 @@
360
360
  - boxed: a rounded box, roomier cells, the header row on the muted
361
361
  fill.
362
362
  Both stripe their body rows (zebra, as DataTable's).
363
+ A column with a set width (src/lib/markdown-table-widths.ts) is exactly
364
+ that wide, its words wrapping inside it, from a phone's width up; on a
365
+ phone columns still fit their words. On paper the widths are only
366
+ preferences, so the table shrinks to the page rather than run off it.
363
367
  Row headers (a header column: src/lib/markdown-table.ts) sit on the
364
368
  muted fill, semibold. A coloured cell (its whole text one highlight)
365
369
  is painted in that wash, its words' own wash dropped. Unlayered, so a
@@ -397,6 +401,16 @@
397
401
  white-space: nowrap;
398
402
  font-variant-numeric: tabular-nums;
399
403
  }
404
+ @media (min-width: 768px) {
405
+ .prose-table :is(td, th)[data-column-width] {
406
+ box-sizing: border-box;
407
+ width: var(--column-width);
408
+ min-width: var(--column-width);
409
+ max-width: var(--column-width);
410
+ white-space: normal;
411
+ overflow-wrap: anywhere;
412
+ }
413
+ }
400
414
  .prose-table th:not([scope="row"], [data-row-header]) {
401
415
  background: var(--heading-band);
402
416
  font-weight: 600;
@@ -507,6 +521,19 @@
507
521
  [data-print-notes] table {
508
522
  border-collapse: collapse;
509
523
  }
524
+ /* Paper can't scroll: the widths are what the columns would like, and
525
+ the table takes the page's width when they add up to more. */
526
+ [data-print-notes] [data-slot="table-container"] > table {
527
+ max-width: 100%;
528
+ }
529
+ [data-print-notes] [data-slot="table-container"] :is(td, th)[data-column-width] {
530
+ box-sizing: border-box;
531
+ width: var(--column-width);
532
+ min-width: 0;
533
+ max-width: none;
534
+ white-space: normal;
535
+ overflow-wrap: anywhere;
536
+ }
510
537
  [data-print-notes] tr {
511
538
  break-inside: avoid;
512
539
  }