@tristan2828/ui-foundation 4.77.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.
@@ -0,0 +1,134 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ // A month and day with no year: something that comes round every year (a
3
+ // season's start, a yearly deadline). The value is `'MM-DD'`, or `''` for
4
+ // not set (`lib/month-day.ts`).
5
+ //
6
+ // A button showing the day ("Mar 14"), opening a picker in a Popover like
7
+ // DateField's: twelve months, then the chosen month's days. A calendar
8
+ // grid would need a year (its weekdays and leading blanks are a year's),
9
+ // so the days are 1 to the month's last in rows of seven, February
10
+ // running to the 29th. Only real days are offered, so the field can't
11
+ // make February 30; a stored value that isn't one (`'02-30'`, old text)
12
+ // shows as written, nothing selected. The arrow keys move through either
13
+ // grid (Home and End to its ends), Page Up and Page Down change the month,
14
+ // and every button is 36px or larger for a finger.
15
+ //
16
+ // One control for the form (a react-hook-form `Controller`) and for
17
+ // editing in place (`inPlace.monthDay`: picking a day saves, and the
18
+ // picker opens with the field). `clearable` adds Clear for an optional field.
19
+ import { useEffect, useId, useRef, useState } from 'react';
20
+ import { CalendarIcon, ChevronLeftIcon, ChevronRightIcon } from 'lucide-react';
21
+ import { cn } from 'cn';
22
+ import { Button } from '../ui/button.js';
23
+ import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover.js';
24
+ import { daysInMonth, formatMonthDay, monthDayParts, monthName, toMonthDay } from '../../lib/month-day.js';
25
+ const MONTH_COLUMNS = 3;
26
+ const DAY_COLUMNS = 7;
27
+ // Where an arrow key moves in a grid of `count` cells, `columns` wide, or
28
+ // null for a key the grid doesn't use. Left and Right run on across rows.
29
+ function moveInGrid(key, at, count, columns) {
30
+ const next = key === 'ArrowLeft'
31
+ ? at - 1
32
+ : key === 'ArrowRight'
33
+ ? at + 1
34
+ : key === 'ArrowUp'
35
+ ? at - columns
36
+ : key === 'ArrowDown'
37
+ ? at + columns
38
+ : key === 'Home'
39
+ ? 0
40
+ : key === 'End'
41
+ ? count - 1
42
+ : null;
43
+ if (next === null)
44
+ return null;
45
+ return Math.min(Math.max(next, 0), count - 1);
46
+ }
47
+ // The month after (or before) one, round the year.
48
+ const nextMonth = (month, by) => ((month - 1 + by + 12) % 12) + 1;
49
+ export function MonthDayField({ id, value, onChange, placeholder = 'Pick a day', clearable = false, invalid = false, readOnly = false, defaultOpen = false, modal, onOpenChange, format, locale, className, ...aria }) {
50
+ const [open, setOpen] = useState(defaultOpen && !readOnly);
51
+ const popup = useRef(null);
52
+ const selected = monthDayParts(value);
53
+ // A value that isn't a day of the year reads as written, so nothing typed before is hidden.
54
+ const shown = formatMonthDay(value, format, locale) || value;
55
+ const changeOpen = (next) => {
56
+ if (next && readOnly)
57
+ return;
58
+ setOpen(next);
59
+ onOpenChange?.(next);
60
+ };
61
+ const pick = (next) => {
62
+ onChange(next);
63
+ changeOpen(false);
64
+ };
65
+ return (_jsxs(Popover, { open: open, onOpenChange: changeOpen, modal: modal, children: [_jsxs(PopoverTrigger, { render: _jsx(Button, { id: id, type: "button", variant: "outline", "aria-invalid": invalid || undefined, "aria-readonly": readOnly || undefined, className: cn('w-full justify-start font-normal', !shown && 'text-muted-foreground', className), ...aria }), children: [_jsx(CalendarIcon, { "aria-hidden": "true", className: "size-4" }), shown || placeholder] }), _jsxs(PopoverContent, { ref: popup, className: "w-auto p-0", "data-slot": "month-day-field-picker", "aria-label": "Month and day",
66
+ // The button the keyboard starts from (the chosen day, else this
67
+ // month): the one the grid makes tabbable. The popup would
68
+ // otherwise take focus itself.
69
+ initialFocus: () => popup.current?.querySelector('[data-cell][tabindex="0"]') ?? true, children: [open && (_jsx(Picker, { selected: selected, locale: locale, onPick: (month, day) => pick(toMonthDay(month, day)) })), clearable && value && (_jsx("div", { className: "border-t border-border p-2", children: _jsx(Button, { type: "button", variant: "ghost", size: "sm", className: "w-full", onClick: () => pick(''), children: "Clear" }) }))] })] }));
70
+ }
71
+ // The two steps: a month (when nothing is chosen yet, or from the day
72
+ // step's month button), then its days. It opens on the chosen day's month,
73
+ // else on the months with this one to start from.
74
+ function Picker({ selected, locale, onPick }) {
75
+ const today = new Date();
76
+ const [step, setStep] = useState(selected ? 'day' : 'month');
77
+ const [month, setMonth] = useState(selected?.month ?? today.getMonth() + 1);
78
+ // The cell the keyboard is on in the grid shown: a month (1–12) or a day.
79
+ const [active, setActive] = useState(selected ? selected.day : today.getMonth() + 1);
80
+ const grid = useRef(null);
81
+ // Focus follows `active` once the grid is drawn (a step or a month
82
+ // changed, an arrow key), never on a click elsewhere in the popup. On
83
+ // opening, the popup's own initial focus puts it there.
84
+ const focusWanted = useRef(false);
85
+ const monthsLabel = useId();
86
+ useEffect(() => {
87
+ if (!focusWanted.current)
88
+ return;
89
+ focusWanted.current = false;
90
+ grid.current?.querySelector(`[data-cell="${active}"]`)?.focus();
91
+ });
92
+ const days = daysInMonth(month);
93
+ const showMonth = (next, day) => {
94
+ setMonth(next);
95
+ setActive(Math.min(day, daysInMonth(next)));
96
+ focusWanted.current = true;
97
+ };
98
+ const onGridKeyDown = (event) => {
99
+ if (step === 'day' && (event.key === 'PageUp' || event.key === 'PageDown')) {
100
+ event.preventDefault();
101
+ showMonth(nextMonth(month, event.key === 'PageUp' ? -1 : 1), active);
102
+ return;
103
+ }
104
+ const [count, columns] = step === 'month' ? [12, MONTH_COLUMNS] : [days, DAY_COLUMNS];
105
+ const at = moveInGrid(event.key, active - 1, count, columns);
106
+ if (at === null)
107
+ return;
108
+ event.preventDefault();
109
+ if (at + 1 === active)
110
+ return;
111
+ setActive(at + 1);
112
+ focusWanted.current = true;
113
+ };
114
+ const name = monthName(month, 'long', locale);
115
+ if (step === 'month') {
116
+ return (_jsxs("div", { className: "p-3", children: [_jsx("p", { className: "mb-2 px-1 text-sm font-medium", id: monthsLabel, children: "Month" }), _jsx("div", { ref: grid, role: "group", "aria-labelledby": monthsLabel, className: "grid grid-cols-3 gap-1", onKeyDown: onGridKeyDown, children: Array.from({ length: 12 }, (_, index) => {
117
+ const each = index + 1;
118
+ const chosen = selected?.month === each;
119
+ return (_jsxs(Button, { type: "button", variant: chosen ? 'default' : 'ghost', className: "h-10 w-20 font-normal", "data-cell": each, tabIndex: each === active ? 0 : -1, "aria-pressed": chosen, onClick: () => {
120
+ setStep('day');
121
+ showMonth(each, selected?.month === each ? selected.day : 1);
122
+ }, children: [_jsx("span", { "aria-hidden": "true", children: monthName(each, 'short', locale) }), _jsx("span", { className: "sr-only", children: monthName(each, 'long', locale) })] }, each));
123
+ }) })] }));
124
+ }
125
+ return (_jsxs("div", { className: "p-3", children: [_jsxs("div", { className: "mb-2 flex items-center justify-between gap-1", children: [_jsx(Button, { type: "button", variant: "ghost", size: "icon", "aria-label": "Previous month", onClick: () => showMonth(nextMonth(month, -1), active), children: _jsx(ChevronLeftIcon, { "aria-hidden": "true" }) }), _jsx(Button, { type: "button", variant: "ghost", className: "font-medium", "aria-label": `${name}, pick another month`, onClick: () => {
126
+ setStep('month');
127
+ setActive(month);
128
+ focusWanted.current = true;
129
+ }, children: name }), _jsx(Button, { type: "button", variant: "ghost", size: "icon", "aria-label": "Next month", onClick: () => showMonth(nextMonth(month, 1), active), children: _jsx(ChevronRightIcon, { "aria-hidden": "true" }) })] }), _jsx("div", { ref: grid, role: "group", "aria-label": name, className: "grid grid-cols-7 gap-1", onKeyDown: onGridKeyDown, children: Array.from({ length: days }, (_, index) => {
130
+ const day = index + 1;
131
+ const chosen = selected?.month === month && selected.day === day;
132
+ return (_jsx(Button, { type: "button", variant: chosen ? 'default' : 'ghost', size: "icon", className: "font-normal tabular-nums", "data-cell": day, tabIndex: day === active ? 0 : -1, "aria-label": formatMonthDay(toMonthDay(month, day), { month: 'long', day: 'numeric' }, locale), "aria-pressed": chosen, onClick: () => onPick(month, day), children: day }, day));
133
+ }) })] }));
134
+ }
@@ -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
package/dist/index.d.ts CHANGED
@@ -20,7 +20,7 @@ export { usePrinting } from './components/app/print-context.js';
20
20
  export { RecordDialogRoute, RecordLink, type RecordDialogRouteProps, type RecordLinkProps, } from './components/app/record-dialog.js';
21
21
  export { recordDialogState, useOpenRecord, useRecordDialog, type RecordDialogBackground, type RecordDialogContextValue, type RecordDialogState, } from './components/app/record-dialog-context.js';
22
22
  export { editInPlace, type EditControlProps, type EditInPlace, type EditInPlaceList, type EditInPlaceListOptions, type EditInPlaceOptions, type EditKind, type EditListAddProps, type EditListItemProps, } from './components/app/edit-in-place.js';
23
- export { inPlace, type InPlaceDateConfig, type InPlaceFieldsOptions, type InPlaceLinkConfig, type InPlaceLinkValue, type InPlaceMoneyConfig, type InPlaceNumberConfig, type InPlaceOption, type InPlacePart, type InPlaceRecord, type InPlaceReferenceConfig, type InPlaceSaved, type InPlaceSelectConfig, type InPlaceTextConfig, } from './components/app/edit-in-place-presets.js';
23
+ export { inPlace, type InPlaceDateConfig, type InPlaceFieldsOptions, type InPlaceLinkConfig, type InPlaceLinkValue, type InPlaceMoneyConfig, type InPlaceMonthDayConfig, type InPlaceNumberConfig, type InPlaceOption, type InPlacePart, type InPlaceRecord, type InPlaceReferenceConfig, type InPlaceSaved, type InPlaceSelectConfig, type InPlaceTextConfig, } from './components/app/edit-in-place-presets.js';
24
24
  export { linkHost, linkHref, linkRule } from './lib/link-href.js';
25
25
  export { DataEnvironmentBanner } from './components/app/data-environment-banner.js';
26
26
  export { EditableValue, type EditableValueProps } from './components/app/editable-value.js';
@@ -55,9 +55,11 @@ export { StepBar, type StepBarProps } from './components/app/step-bar.js';
55
55
  export { RatingStar, type RatingStarProps, type RatingStarValue } from './components/app/rating-star.js';
56
56
  export { DateField, type DateFieldProps } from './components/app/date-field.js';
57
57
  export { EmojiField, type EmojiFieldProps } from './components/app/emoji-field.js';
58
+ export { MonthDayField, type MonthDayFieldProps } from './components/app/month-day-field.js';
58
59
  export { ImageField, type ImageFieldProps } from './components/app/image-field.js';
59
60
  export { DEFAULT_IMAGE_TYPES, type ImageUpload, type ImageUploadResult } from './lib/image-file.js';
60
61
  export { formatPlainDate, type PlainDate } from './lib/plain-date.js';
62
+ export { formatMonthDay, isMonthDay, monthDayProblem, type MonthDay } from './lib/month-day.js';
61
63
  export { ChoiceCell, LinkCell, LinkOut, NameCell, type ChoiceCellProps, type LinkCellProps, type NameCellProps, } from './components/app/row-edit-cells.js';
62
64
  export { ModuleCard, ModuleStrip, type CategorySlot, type ModuleCardLink, type ModuleCardPlace, type ModuleCardProps, type ModuleStripMobile, type ModuleStripProps, } from './components/app/module-card.js';
63
65
  export { WidgetCard, WidgetCardGroup, WidgetList, WidgetListItem, type WidgetCardGroupProps, type WidgetCardLink, type WidgetCardProps, type WidgetListItemProps, } from './components/app/widget-card.js';
package/dist/index.js CHANGED
@@ -57,9 +57,11 @@ export { StepBar } from './components/app/step-bar.js';
57
57
  export { RatingStar } from './components/app/rating-star.js';
58
58
  export { DateField } from './components/app/date-field.js';
59
59
  export { EmojiField } from './components/app/emoji-field.js';
60
+ export { MonthDayField } from './components/app/month-day-field.js';
60
61
  export { ImageField } from './components/app/image-field.js';
61
62
  export { DEFAULT_IMAGE_TYPES } from './lib/image-file.js';
62
63
  export { formatPlainDate } from './lib/plain-date.js';
64
+ export { formatMonthDay, isMonthDay, monthDayProblem } from './lib/month-day.js';
63
65
  export { ChoiceCell, LinkCell, LinkOut, NameCell, } from './components/app/row-edit-cells.js';
64
66
  export { ModuleCard, ModuleStrip, } from './components/app/module-card.js';
65
67
  export { WidgetCard, WidgetCardGroup, WidgetList, WidgetListItem, } from './components/app/widget-card.js';
@@ -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.