@tristan2828/ui-foundation 4.101.0 → 4.102.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.
@@ -26,24 +26,24 @@
26
26
  - [A variant: a pressed icon inside another value's cell](#a-variant-a-pressed-icon-inside-another-values-cell) · lines 631–714
27
27
  - [16. Title linking to the record's view](#16-title-linking-to-the-records-view) · lines 716–751
28
28
  - [17. Quick action on the view](#17-quick-action-on-the-view) · lines 753–826
29
- - [18. Editable value](#18-editable-value) · lines 828–1506
30
- - [Presets: one line per field](#presets-one-line-per-field) · lines 1138–1206
31
- - [Several fields edited as one](#several-fields-edited-as-one) · lines 1208–1244
32
- - [A link and its label](#a-link-and-its-label) · lines 1246–1270
33
- - [A list of sub-items](#a-list-of-sub-items) · lines 1272–1405
34
- - [In a table's rows](#in-a-tables-rows) · lines 1407–1492
35
- - [A table of a few short columns: `width="content"`](#a-table-of-a-few-short-columns-widthcontent) · lines 1494–1506
36
- - [19. Stage circle for an ordered status](#19-stage-circle-for-an-ordered-status) · lines 1508–1574
37
- - [20. Count linking to the related records](#20-count-linking-to-the-related-records) · lines 1576–1640
38
- - [21. Rows grouped under headings, and a pill filter](#21-rows-grouped-under-headings-and-a-pill-filter) · lines 1642–1740
39
- - [22. A highlighted row, and rows that are done](#22-a-highlighted-row-and-rows-that-are-done) · lines 1742–1771
40
- - [24. A list's rows: hover, lines, rows per page](#24-a-lists-rows-hover-lines-rows-per-page) · lines 1773–1811
41
- - [23. A Group menu, and a record read beside the list](#23-a-group-menu-and-a-record-read-beside-the-list) · lines 1813–1889
42
- - [24. A stored colour beside its name](#24-a-stored-colour-beside-its-name) · lines 1891–1914
43
- - [25. A list's tools: views, filters, columns, row actions, a phone's rows](#25-a-lists-tools-views-filters-columns-row-actions-a-phones-rows) · lines 1916–2042
44
- - [The framed look, and sibling lists beside the title](#the-framed-look-and-sibling-lists-beside-the-title) · lines 2004–2042
45
- - [26. A record's related list, capped](#26-a-records-related-list-capped) · lines 2044–2080
46
- - [27. A repeat and its next time](#27-a-repeat-and-its-next-time) · lines 2082–2127
29
+ - [18. Editable value](#18-editable-value) · lines 828–1531
30
+ - [Presets: one line per field](#presets-one-line-per-field) · lines 1163–1231
31
+ - [Several fields edited as one](#several-fields-edited-as-one) · lines 1233–1269
32
+ - [A link and its label](#a-link-and-its-label) · lines 1271–1295
33
+ - [A list of sub-items](#a-list-of-sub-items) · lines 1297–1430
34
+ - [In a table's rows](#in-a-tables-rows) · lines 1432–1517
35
+ - [A table of a few short columns: `width="content"`](#a-table-of-a-few-short-columns-widthcontent) · lines 1519–1531
36
+ - [19. Stage circle for an ordered status](#19-stage-circle-for-an-ordered-status) · lines 1533–1599
37
+ - [20. Count linking to the related records](#20-count-linking-to-the-related-records) · lines 1601–1665
38
+ - [21. Rows grouped under headings, and a pill filter](#21-rows-grouped-under-headings-and-a-pill-filter) · lines 1667–1765
39
+ - [22. A highlighted row, and rows that are done](#22-a-highlighted-row-and-rows-that-are-done) · lines 1767–1796
40
+ - [24. A list's rows: hover, lines, rows per page](#24-a-lists-rows-hover-lines-rows-per-page) · lines 1798–1836
41
+ - [23. A Group menu, and a record read beside the list](#23-a-group-menu-and-a-record-read-beside-the-list) · lines 1838–1914
42
+ - [24. A stored colour beside its name](#24-a-stored-colour-beside-its-name) · lines 1916–1939
43
+ - [25. A list's tools: views, filters, columns, row actions, a phone's rows](#25-a-lists-tools-views-filters-columns-row-actions-a-phones-rows) · lines 1941–2067
44
+ - [The framed look, and sibling lists beside the title](#the-framed-look-and-sibling-lists-beside-the-title) · lines 2029–2067
45
+ - [26. A record's related list, capped](#26-a-records-related-list-capped) · lines 2069–2105
46
+ - [27. A repeat and its next time](#27-a-repeat-and-its-next-time) · lines 2107–2152
47
47
 
48
48
  <!-- /index -->
49
49
 
@@ -867,6 +867,16 @@ on each side without moving it, and never wraps it: a short title or
867
867
  badge edited in place (`layout="inline"`) stays on one line, and a long
868
868
  one wraps between words within its column (4.94; before, a title like
869
869
  "Dr. Example" broke over two lines).
870
+ Inline, the pencil takes no room at rest (4.102): a value in a summary
871
+ line ("Harbor Office · Tuesdays") is followed by its separator a space
872
+ after it, not a pencil's width. The pencil keeps its 24px box out of the
873
+ flow, hidden just past the value over the separator, so it's still a
874
+ target to hover, click and Tab to. Hover or focus makes its room under
875
+ it, eased (at once with reduced motion): what follows moves over by the
876
+ pencil, smoothly, only while it shows, and the pencil stays put. A touch
877
+ screen keeps the room open. `DataTable`'s cells keep the room at rest
878
+ (a column never widens on hover), and so does `EntityView`'s title,
879
+ which ends its line and can fill it. An app needs no override for this.
870
880
 
871
881
  **In a field list, the row is the target** (4.88, `look="row"`, which
872
882
  EntityView's field rows use). The row wears the list's row hover, the
@@ -929,6 +939,21 @@ Larger sets, or ones that grow with the data, keep `MultiReference`
929
939
  - **Keyboard:** opening puts the caret in the filter box; Down goes to
930
940
  the chips, Left/Right (Home/End) move along them, Space or Enter
931
941
  toggles one, Up goes back to the box.
942
+ - **Create "<typed>"** (4.102, `onCreate`): when what's typed names no
943
+ option (ignoring case), a Create "<typed>" button shows under the
944
+ chips; Enter in the box does the same when nothing matches, and Down
945
+ reaches it when there are no chips. It calls `onCreate(name)`, which
946
+ opens the app's small create form (a `FormDialog`, the name filled in)
947
+ or saves at once, and resolves with the new `{ id, label, icon? }`:
948
+ that option joins the chips and is picked (in place, saved like any
949
+ pick, with its spinner). `null` (the form cancelled) changes nothing.
950
+ While it's out the button reads Creating "<typed>"… (`aria-busy`), the
951
+ box is read-only and an edit in place stays open. A rejection shows
952
+ "Couldn't create "<typed>": <reason>" under the chips, the button
953
+ described by it, and keeps the typed name, so Create can be tried
954
+ again; typing clears it. The caret goes back to the box either way,
955
+ and a screen reader hears "<name> created and picked." Never a "New
956
+ <thing>" button beside the picker for this.
932
957
  - Pass the record's value as `value`, not the control's `props.value`
933
958
  (the draft, which never moves here), and keep the field's `save`: the
934
959
  form's whole-set save, never called in place.
@@ -28,9 +28,15 @@ export type EditableFieldProps = EditableValueProps & {
28
28
  trigger?: (start: () => void) => ReactNode;
29
29
  /** Opens again, empty, once a save from the keyboard succeeds: adding one item after another. */
30
30
  reopenAfterKeyboardSave?: boolean;
31
+ /**
32
+ * Inline, the pencil's room is kept at rest, as before 4.102: a table
33
+ * cell (row-edit-cells.tsx), whose column would otherwise widen on
34
+ * hover, and EntityView's title, which ends its line and can fill it.
35
+ */
36
+ keepPencilRoom?: boolean;
31
37
  };
32
38
  export declare function EditableValue(props: EditableValueProps): import("react").JSX.Element;
33
- export declare function EditableField({ label, edit, children, layout, look, className, trigger, reopenAfterKeyboardSave, }: EditableFieldProps): import("react").JSX.Element;
39
+ export declare function EditableField({ label, edit, children, layout, look, className, trigger, reopenAfterKeyboardSave, keepPencilRoom, }: EditableFieldProps): import("react").JSX.Element;
34
40
  /**
35
41
  * While a field holds something unsaved, leaving asks first: an in-app
36
42
  * link or Back (React Router's blocker, so the app needs a data router),
@@ -20,6 +20,8 @@ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-run
20
20
  // value it edits (`inline` among its props).
21
21
  // - Saved (4.88, F16): once a save lands, "✓ Saved" shows beside the value
22
22
  // for two seconds (`role="status"`).
23
+ // - `layout="inline"` (4.102): the pencil takes no room until hover or
24
+ // focus, so nothing gaps before what follows the value on its line.
23
25
  // - `look="row"` (4.88, F15 and F18): in a record's field list the row is
24
26
  // the target (edit-row.ts): it wears the list's row hover and the pencil
25
27
  // sits at its end; under 48rem or on a touch screen there's a chevron
@@ -52,6 +54,13 @@ const LEAVING = 'a[href]:not([target="_blank"]), [data-leave-guard]';
52
54
  // A control holding the field open while something of the app's is in
53
55
  // front of it (ReferenceCombobox's create form): leaving doesn't save.
54
56
  const HOLD = '[data-edit-hold]';
57
+ // An inline value's room for its pencil: none at rest; the pencil's 24px
58
+ // and a 4px gap (w-7) while the value is hovered or its pencil focused.
59
+ function InlinePencilRoom({ inline, children }) {
60
+ if (!inline)
61
+ return children;
62
+ return (_jsx("span", { "data-slot": "editable-value-pencil-room", className: "relative w-0 shrink-0 self-stretch transition-[width] duration-150 ease-out motion-reduce:transition-none group-hover/editable:w-7 group-has-[[data-edit]:focus-visible]/editable:w-7 pointer-coarse:w-7", children: children }));
63
+ }
55
64
  // The field's own control, given what it needs.
56
65
  function Control({ render, ...props }) {
57
66
  return render(props);
@@ -65,7 +74,7 @@ function useStore() {
65
74
  export function EditableValue(props) {
66
75
  return _jsx(EditableField, { ...props });
67
76
  }
68
- export function EditableField({ label, edit, children, layout = 'block', look = 'value', className, trigger, reopenAfterKeyboardSave = false, }) {
77
+ export function EditableField({ label, edit, children, layout = 'block', look = 'value', className, trigger, reopenAfterKeyboardSave = false, keepPencilRoom = false, }) {
69
78
  const store = useStore();
70
79
  const key = useId();
71
80
  const controlId = `${key}-control`;
@@ -235,7 +244,10 @@ export function EditableField({ label, edit, children, layout = 'block', look =
235
244
  if (trigger)
236
245
  return (_jsx("span", { ref: triggerBox, className: "contents", children: trigger(start) }));
237
246
  const row = look === 'row';
238
- return (_jsxs("span", { "data-slot": "editable-value", "data-look": look, onClick: onShownClick, className: cn('group/editable relative cursor-text items-start gap-1',
247
+ const inlineValue = layout === 'inline' && !row && !keepPencilRoom;
248
+ return (_jsxs("span", { "data-slot": "editable-value", "data-look": look, onClick: onShownClick, className: cn(
249
+ // Inline, the gap is the pencil's own margin, there only while it shows.
250
+ 'group/editable relative cursor-text items-start', !inlineValue && 'gap-1',
239
251
  // A row: the row (editRowClass) wears the hover, not the value.
240
252
  !row && '-mx-1.5 rounded-md px-1.5 transition-colors hover:bg-muted has-[[data-edit]:focus-visible]:bg-muted',
241
253
  // Inline, the cap is its column plus the 0.75rem the negative
@@ -243,7 +255,7 @@ export function EditableField({ label, edit, children, layout = 'block', look =
243
255
  // its line) is sized to the margin box, 0.75rem under the box,
244
256
  // and `max-w-full` then wrapped a short value mid-word (4.94).
245
257
  layout === 'block' ? 'flex w-full' : cn('inline-flex align-top', row ? 'max-w-full' : 'max-w-[calc(100%+0.75rem)]'), className), children: [_jsxs("span", { className: cn('min-w-0 flex-1', !row &&
246
- 'group-hover/editable:[&_.text-muted-foreground]:text-foreground group-has-[[data-edit]:focus-visible]/editable:[&_.text-muted-foreground]:text-foreground'), children: [children !== undefined ? children : edit.shown, _jsx("span", { role: "status", "data-slot": "editable-value-saved", className: "ml-2 inline-flex items-center gap-1 align-baseline type-caption text-success-text empty:hidden", children: justSaved && (_jsxs(_Fragment, { children: [_jsx(CheckIcon, { "aria-hidden": "true", className: "size-3.5" }), "Saved"] })) })] }), _jsx(Button, { ref: editButton, "data-edit": "", type: "button", variant: "ghost", size: "icon-xs", "aria-label": `Edit ${label}`, onClick: start, className: cn('shrink-0 text-muted-foreground opacity-0 focus-visible:opacity-100 pointer-coarse:opacity-100', row ? 'group-hover/edit-row:opacity-100 hover:bg-transparent max-md:opacity-100' : 'group-hover/editable:opacity-100'), children: row ? (_jsxs(_Fragment, { children: [_jsx(PencilIcon, { className: "max-md:hidden pointer-coarse:hidden" }), _jsx(ChevronRightIcon, { className: "hidden max-md:block pointer-coarse:block" })] })) : (_jsx(PencilIcon, {})) })] }));
258
+ 'group-hover/editable:[&_.text-muted-foreground]:text-foreground group-has-[[data-edit]:focus-visible]/editable:[&_.text-muted-foreground]:text-foreground'), children: [children !== undefined ? children : edit.shown, _jsx("span", { role: "status", "data-slot": "editable-value-saved", className: "ml-2 inline-flex items-center gap-1 align-baseline type-caption text-success-text empty:hidden", children: justSaved && (_jsxs(_Fragment, { children: [_jsx(CheckIcon, { "aria-hidden": "true", className: "size-3.5" }), "Saved"] })) })] }), _jsx(InlinePencilRoom, { inline: inlineValue, children: _jsx(Button, { ref: editButton, "data-edit": "", type: "button", variant: "ghost", size: "icon-xs", "aria-label": `Edit ${label}`, onClick: start, className: cn('shrink-0 text-muted-foreground opacity-0 focus-visible:opacity-100 pointer-coarse:opacity-100', row ? 'group-hover/edit-row:opacity-100 hover:bg-transparent max-md:opacity-100' : 'group-hover/editable:opacity-100', inlineValue && 'absolute top-0 left-1 z-10'), children: row ? (_jsxs(_Fragment, { children: [_jsx(PencilIcon, { className: "max-md:hidden pointer-coarse:hidden" }), _jsx(ChevronRightIcon, { className: "hidden max-md:block pointer-coarse:block" })] })) : (_jsx(PencilIcon, {})) }) })] }));
247
259
  }
248
260
  // Always editable, before the store has it (the first render): the saved value.
249
261
  const open = state.status === 'closed' ? { status: 'open', draft: edit.value, error: null, autosave: undefined, revision: 0 } : state;
@@ -109,7 +109,7 @@ import { EditInPlaceContext } from './edit-in-place.js';
109
109
  import { EditInPlaceStore } from './edit-in-place-store.js';
110
110
  import { EditableList } from './editable-list.js';
111
111
  import { editRowClass, onEditRowClick } from './edit-row.js';
112
- import { EditableValue, LeaveGuard } from './editable-value.js';
112
+ import { EditableField, EditableValue, LeaveGuard } from './editable-value.js';
113
113
  import { EmptyText } from './empty-value.js';
114
114
  import { EMPTY_DASH, isEmptyValue } from '../../lib/empty-value.js';
115
115
  import { useRecordDialog } from './record-dialog-context.js';
@@ -408,5 +408,5 @@ export function EntityView({ title, documentTitle, titleEdit, leading, subtitle,
408
408
  .filter((section) => !tabbed(section))
409
409
  .map((section) => (_jsx(ViewSection, { section: section }, section.title))), tabList] }));
410
410
  }
411
- return (_jsx(EditInPlaceContext.Provider, { value: store, children: _jsx(EmptyContext.Provider, { value: { text: emptyText, fold: emptyFields === 'fold' }, children: _jsxs("div", { className: layout === 'rail' && !card ? RAIL_LAYOUT.page : cn('flex max-w-4xl flex-col', card ? 'gap-4' : 'gap-6'), "data-state": "success", "data-layout": layout, "data-look": card ? 'card' : undefined, children: [editing && _jsx(LeaveGuard, { store: store }), !dialog && !trail && _jsx(BackLink, { back: back }), !dialog && trail && !inShell && _jsx(PageTrail, { crumbs: trail }), _jsxs("header", { className: card ? 'flex items-start justify-between gap-3' : 'flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between', children: [_jsxs("div", { className: cn('flex min-w-0 flex-1 items-start gap-3', !card && 'sm:min-w-64 sm:gap-4'), children: [leading && (_jsx("div", { "data-slot": "entity-view-leading", className: "flex shrink-0 items-center", children: leading })), _jsxs("div", { className: "flex min-w-0 flex-1 flex-col gap-2", children: [_jsxs("div", { "data-slot": "entity-view-title-line", className: "flex min-w-0 flex-wrap items-center gap-x-3 gap-y-2", children: [_jsx("h1", { id: dialog?.titleId, className: cn('min-w-0 max-w-full break-words text-foreground', card ? 'type-section-title' : 'type-page-title'), children: titleEdit ? (_jsx(EditableValue, { label: titleEdit.label, edit: titleEdit, layout: "inline", children: title })) : (title) }), badges && (_jsx("div", { "data-slot": "entity-view-badges", className: "flex flex-wrap items-center gap-1.5", children: badges }))] }), subtitle && (_jsx("div", { "data-slot": "entity-view-subtitle", className: "type-body break-words text-muted-foreground", children: subtitle }))] })] }), card ? (_jsxs("div", { "data-slot": "entity-view-card-controls", className: "flex shrink-0 items-center gap-1", children: [printButton, actions, dialog?.controls] })) : ((actions || printButton) && (_jsxs("div", { className: "flex min-w-0 flex-wrap items-center gap-2 sm:justify-end", children: [printButton, actions] })))] }), _jsx("div", { role: "status", "data-slot": "entity-view-notice", className: "empty:hidden", children: notice }), strip && _jsx("div", { "data-slot": "entity-view-strip", children: strip }), body, footer && (_jsx("footer", { "data-slot": "entity-view-footer", className: "type-caption text-muted-foreground", children: footer }))] }) }) }));
411
+ return (_jsx(EditInPlaceContext.Provider, { value: store, children: _jsx(EmptyContext.Provider, { value: { text: emptyText, fold: emptyFields === 'fold' }, children: _jsxs("div", { className: layout === 'rail' && !card ? RAIL_LAYOUT.page : cn('flex max-w-4xl flex-col', card ? 'gap-4' : 'gap-6'), "data-state": "success", "data-layout": layout, "data-look": card ? 'card' : undefined, children: [editing && _jsx(LeaveGuard, { store: store }), !dialog && !trail && _jsx(BackLink, { back: back }), !dialog && trail && !inShell && _jsx(PageTrail, { crumbs: trail }), _jsxs("header", { className: card ? 'flex items-start justify-between gap-3' : 'flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between', children: [_jsxs("div", { className: cn('flex min-w-0 flex-1 items-start gap-3', !card && 'sm:min-w-64 sm:gap-4'), children: [leading && (_jsx("div", { "data-slot": "entity-view-leading", className: "flex shrink-0 items-center", children: leading })), _jsxs("div", { className: "flex min-w-0 flex-1 flex-col gap-2", children: [_jsxs("div", { "data-slot": "entity-view-title-line", className: "flex min-w-0 flex-wrap items-center gap-x-3 gap-y-2", children: [_jsx("h1", { id: dialog?.titleId, className: cn('min-w-0 max-w-full break-words text-foreground', card ? 'type-section-title' : 'type-page-title'), children: titleEdit ? (_jsx(EditableField, { label: titleEdit.label, edit: titleEdit, layout: "inline", keepPencilRoom: true, children: title })) : (title) }), badges && (_jsx("div", { "data-slot": "entity-view-badges", className: "flex flex-wrap items-center gap-1.5", children: badges }))] }), subtitle && (_jsx("div", { "data-slot": "entity-view-subtitle", className: "type-body break-words text-muted-foreground", children: subtitle }))] })] }), card ? (_jsxs("div", { "data-slot": "entity-view-card-controls", className: "flex shrink-0 items-center gap-1", children: [printButton, actions, dialog?.controls] })) : ((actions || printButton) && (_jsxs("div", { className: "flex min-w-0 flex-wrap items-center gap-2 sm:justify-end", children: [printButton, actions] })))] }), _jsx("div", { role: "status", "data-slot": "entity-view-notice", className: "empty:hidden", children: notice }), strip && _jsx("div", { "data-slot": "entity-view-strip", children: strip }), body, footer && (_jsx("footer", { "data-slot": "entity-view-footer", className: "type-caption text-muted-foreground", children: footer }))] }) }) }));
412
412
  }
@@ -45,6 +45,16 @@ export type MultiPickProps<Id extends string | number> = {
45
45
  loading?: boolean;
46
46
  /** Shown, not changeable. */
47
47
  readOnly?: boolean;
48
+ /**
49
+ * Offers Create "<typed>" when what's typed names no option (ignoring
50
+ * case and spaces at the ends). Opens the app's create form with the
51
+ * name, or saves it at once, and resolves with the new option, which is
52
+ * then picked (in place, through `onPick`), or `null` when the form was
53
+ * cancelled. Rejecting (with the AppError) shows the reason in the
54
+ * picker, the typed name kept. The new option shows as a chip until the
55
+ * app's `options` have it.
56
+ */
57
+ onCreate?: (name: string) => Promise<MultiPickOption<Id> | null>;
48
58
  className?: string;
49
59
  };
50
- export declare function MultiPick<Id extends string | number>({ options, value, onValueChange, onPick, 'aria-label': label, 'aria-describedby': describedBy, id, placeholder, emptyText, limit, loading, readOnly, className, }: MultiPickProps<Id>): import("react").JSX.Element;
60
+ export declare function MultiPick<Id extends string | number>({ options, value, onValueChange, onPick, 'aria-label': label, 'aria-describedby': describedBy, id, placeholder, emptyText, limit, loading, readOnly, onCreate, className, }: MultiPickProps<Id>): import("react").JSX.Element;
@@ -28,8 +28,19 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
28
28
  // them all. The options can be the app's list of records (its query's
29
29
  // rows as `{ id, label }`, `loading` while it loads), so a link to
30
30
  // several other records uses it too.
31
+ // - `onCreate` (4.102): when what's typed names no option, Create "<typed>"
32
+ // shows under the chips (Enter in the box does the same when nothing
33
+ // matches; Down reaches it when there are no chips). It calls the app's
34
+ // `onCreate(name)`: its small create form with the name filled in, or a
35
+ // save straight away. While that's out the button reads Creating
36
+ // "<typed>"… (`aria-busy`), the box can't change, and an edit in place
37
+ // holding this stays open (`data-edit-hold`). The option it resolves
38
+ // with joins the chips and is picked (in place, saved as any pick is);
39
+ // `null` (the form cancelled) changes nothing. A rejection shows its
40
+ // reason under the chips and keeps what was typed, so Create can be
41
+ // tried again. Either way the caret goes back to the box.
31
42
  import { CheckIcon } from 'lucide-react';
32
- import { useEffect, useId, useRef, useState } from 'react';
43
+ import { useEffect, useId, useLayoutEffect, useRef, useState } from 'react';
33
44
  import { toast } from 'sonner';
34
45
  import { cn } from 'cn';
35
46
  import { Button } from '../ui/button.js';
@@ -37,15 +48,25 @@ import { FieldError } from '../ui/field.js';
37
48
  import { Input } from '../ui/input.js';
38
49
  import { Spinner } from '../ui/spinner.js';
39
50
  import { ToggleGroup, ToggleGroupItem } from '../ui/toggle-group.js';
51
+ import { namesRecord } from '../../lib/names-record.js';
40
52
  import { messageOf } from './edit-in-place-store.js';
41
- export function MultiPick({ options, value, onValueChange, onPick, 'aria-label': label, 'aria-describedby': describedBy, id, placeholder = 'Filter', emptyText = 'No options.', limit = 30, loading = false, readOnly = false, className, }) {
53
+ export function MultiPick({ options, value, onValueChange, onPick, 'aria-label': label, 'aria-describedby': describedBy, id, placeholder = 'Filter', emptyText = 'No options.', limit = 30, loading = false, readOnly = false, onCreate, className, }) {
42
54
  const key = useId();
43
55
  const [filter, setFilter] = useState('');
44
56
  const [showAll, setShowAll] = useState(false);
45
57
  const [pending, setPending] = useState(() => new Map());
46
58
  const [refused, setRefused] = useState(() => new Map());
59
+ // Options made here that the app's `options` don't have yet.
60
+ const [created, setCreated] = useState([]);
61
+ // The name Create is making, while the app's answer is out.
62
+ const [creating, setCreating] = useState(null);
63
+ const [createFailed, setCreateFailed] = useState(null);
64
+ // Said to a screen reader once a created option is picked.
65
+ const [announced, setAnnounced] = useState('');
47
66
  const filterBox = useRef(null);
48
67
  const chips = useRef(null);
68
+ const createButton = useRef(null);
69
+ const root = useRef(null);
49
70
  const mounted = useRef(true);
50
71
  useEffect(() => {
51
72
  mounted.current = true;
@@ -61,8 +82,15 @@ export function MultiPick({ options, value, onValueChange, onPick, 'aria-label':
61
82
  if ([...pending.values()].some((entry) => entry.inFlight === 0))
62
83
  setPending(new Map([...pending].filter(([, entry]) => entry.inFlight > 0)));
63
84
  }
85
+ // The app's options, then any made here that they don't have yet.
86
+ const all = created.length === 0 ? options : [...options, ...created.filter((made) => !options.some((option) => option.id === made.id))];
87
+ // What a create answered later reads: the value and picks by then.
88
+ const latest = useRef({ value, pending });
89
+ useLayoutEffect(() => {
90
+ latest.current = { value, pending };
91
+ });
64
92
  const isPicked = (option) => pending.get(option)?.picked ?? value.includes(option);
65
- const shown = options.filter((option) => isPicked(option.id)).map((option) => option.id);
93
+ const shown = all.filter((option) => isPicked(option.id)).map((option) => option.id);
66
94
  const settle = (option, ok) => setPending((current) => {
67
95
  const entry = current.get(option);
68
96
  if (!entry)
@@ -76,19 +104,11 @@ export function MultiPick({ options, value, onValueChange, onPick, 'aria-label':
76
104
  next.set(option, { ...entry, inFlight });
77
105
  return next;
78
106
  });
79
- const toggle = (option, picked) => {
80
- if (!onPick) {
81
- // In the options' order, keeping any picked id with no option.
82
- const known = new Set(options.map((other) => other.id));
83
- onValueChange?.([
84
- ...options.filter((other) => (other.id === option.id ? picked : isPicked(other.id))).map((other) => other.id),
85
- ...value.filter((other) => !known.has(other)),
86
- ]);
87
- return;
88
- }
107
+ // Edited in place: one pick saved on its own.
108
+ const savePick = (option, picked, save) => {
89
109
  setRefused((current) => without(current, option.id));
90
110
  setPending((current) => new Map(current).set(option.id, { picked, inFlight: (current.get(option.id)?.inFlight ?? 0) + 1 }));
91
- onPick(option.id, picked).then(() => settle(option.id, true), (error) => {
111
+ save(option.id, picked).then(() => settle(option.id, true), (error) => {
92
112
  settle(option.id, false);
93
113
  const reason = `Couldn't ${picked ? 'add' : 'remove'} ${option.label}: ${messageOf(error)}`;
94
114
  // Closed before the answer: the reason has nowhere else to show.
@@ -98,18 +118,90 @@ export function MultiPick({ options, value, onValueChange, onPick, 'aria-label':
98
118
  toast.error(reason);
99
119
  });
100
120
  };
121
+ const toggle = (option, picked) => {
122
+ if (!onPick) {
123
+ // In the options' order, keeping any picked id with no option.
124
+ const known = new Set(all.map((other) => other.id));
125
+ onValueChange?.([
126
+ ...all.filter((other) => (other.id === option.id ? picked : isPicked(other.id))).map((other) => other.id),
127
+ ...value.filter((other) => !known.has(other)),
128
+ ]);
129
+ return;
130
+ }
131
+ savePick(option, picked, onPick);
132
+ };
101
133
  const needle = filter.trim().toLowerCase();
102
- const matching = needle ? options.filter((option) => option.label.toLowerCase().includes(needle)) : options;
134
+ const matching = needle ? all.filter((option) => option.label.toLowerCase().includes(needle)) : all;
103
135
  // A long set: the first `limit`, and any picked one past them, in the options' order.
104
- const capped = !needle && !showAll && options.length > limit;
136
+ const capped = !needle && !showAll && all.length > limit;
105
137
  const visible = capped ? matching.filter((option, index) => index < limit || isPicked(option.id)) : matching;
106
- const hidden = options.length - visible.length;
107
- // Down from the box: into the chips, at the one the group would tab to.
138
+ const hidden = all.length - visible.length;
139
+ const name = filter.trim();
140
+ const offerCreate = Boolean(onCreate) && !readOnly && !loading && (creating !== null || (name !== '' && !namesRecord(all, name)));
141
+ const create = () => {
142
+ if (!onCreate || creating !== null || name === '')
143
+ return;
144
+ setCreating(name);
145
+ setCreateFailed(null);
146
+ setAnnounced('');
147
+ // The caret back in the box once the app's form has closed, so the
148
+ // keyboard keeps its place: the Create button is gone after a create.
149
+ // A form's dialog hands focus back as it closes, a few frames on, so
150
+ // this waits (up to a second) while focus is still in something else.
151
+ // After a refusal the caret stays on Create, to try again.
152
+ const refocus = (created, frames = 60) => requestAnimationFrame(() => {
153
+ if (!mounted.current)
154
+ return;
155
+ const at = document.activeElement;
156
+ if (at === null || at === document.body || (created && at === createButton.current))
157
+ filterBox.current?.focus();
158
+ else if (!root.current?.contains(at) && frames > 0)
159
+ refocus(created, frames - 1);
160
+ });
161
+ onCreate(name).then((option) => {
162
+ if (!mounted.current) {
163
+ // Closed meanwhile: in place, the pick still saves.
164
+ if (option && onPick)
165
+ void onPick(option.id, true).catch((error) => toast.error(`Couldn't add ${option.label}: ${messageOf(error)}`));
166
+ return;
167
+ }
168
+ setCreating(null);
169
+ if (option) {
170
+ setCreated((current) => [...current.filter((made) => made.id !== option.id), option]);
171
+ setFilter('');
172
+ setAnnounced(`${option.label} created and picked.`);
173
+ const { value: now, pending: out } = latest.current;
174
+ if (!(out.get(option.id)?.picked ?? now.includes(option.id))) {
175
+ if (onPick)
176
+ savePick(option, true, onPick);
177
+ else
178
+ onValueChange?.([...now, option.id]);
179
+ }
180
+ }
181
+ refocus(option !== null);
182
+ }, (error) => {
183
+ const reason = `Couldn't create "${name}": ${messageOf(error)}`;
184
+ if (!mounted.current) {
185
+ toast.error(reason);
186
+ return;
187
+ }
188
+ setCreating(null);
189
+ setCreateFailed(reason);
190
+ refocus(false);
191
+ });
192
+ };
193
+ // Down from the box: into the chips, at the one the group would tab to
194
+ // (Create, with no chips). Enter, when nothing matches, creates.
108
195
  const onFilterKeyDown = (event) => {
196
+ if (event.key === 'Enter' && offerCreate && visible.length === 0) {
197
+ event.preventDefault();
198
+ create();
199
+ return;
200
+ }
109
201
  if (event.key !== 'ArrowDown')
110
202
  return;
111
203
  const items = [...(chips.current?.querySelectorAll('[data-slot="toggle-group-item"]') ?? [])];
112
- const target = items.find((item) => item.tabIndex === 0) ?? items[0];
204
+ const target = items.find((item) => item.tabIndex === 0) ?? items[0] ?? createButton.current;
113
205
  if (!target)
114
206
  return;
115
207
  event.preventDefault();
@@ -122,13 +214,17 @@ export function MultiPick({ options, value, onValueChange, onPick, 'aria-label':
122
214
  filterBox.current?.focus();
123
215
  };
124
216
  const errorId = (option) => `${key}-refused-${String(option)}`;
125
- return (_jsxs("div", { "data-slot": "multi-pick", className: cn('flex w-full min-w-0 flex-col gap-2', className), children: [_jsx(Input, { ref: filterBox, id: id, type: "search", value: filter, onChange: (event) => setFilter(event.target.value), onKeyDown: onFilterKeyDown, placeholder: placeholder, "aria-label": `Filter ${label}`, "aria-describedby": describedBy, autoComplete: "off", readOnly: readOnly, className: "max-w-xs" }), loading ? (_jsx("p", { role: "status", className: "type-caption text-muted-foreground", children: "Loading\u2026" })) : visible.length === 0 ? (_jsx("p", { className: "type-caption text-muted-foreground", children: options.length === 0 ? emptyText : 'No matches.' })) : (_jsx(ToggleGroup, { ref: chips, multiple: true, variant: "outline", size: "sm", spacing: 1.5, value: shown.map(String), disabled: readOnly, onKeyDown: onChipsKeyDown, "aria-label": label, "aria-describedby": describedBy,
217
+ const createErrorId = `${key}-create-failed`;
218
+ return (_jsxs("div", { ref: root, "data-slot": "multi-pick", "data-edit-hold": creating !== null ? '' : undefined, className: cn('flex w-full min-w-0 flex-col gap-2', className), children: [_jsx(Input, { ref: filterBox, id: id, type: "search", value: filter, onChange: (event) => {
219
+ setFilter(event.target.value);
220
+ setCreateFailed(null);
221
+ }, onKeyDown: onFilterKeyDown, placeholder: placeholder, "aria-label": `Filter ${label}`, "aria-describedby": describedBy, autoComplete: "off", readOnly: readOnly || creating !== null, className: "max-w-xs" }), loading ? (_jsx("p", { role: "status", className: "type-caption text-muted-foreground", children: "Loading\u2026" })) : visible.length === 0 ? (_jsx("p", { className: "type-caption text-muted-foreground", children: all.length === 0 && !needle ? emptyText : 'No matches.' })) : (_jsx(ToggleGroup, { ref: chips, multiple: true, variant: "outline", size: "sm", spacing: 1.5, value: shown.map(String), disabled: readOnly, onKeyDown: onChipsKeyDown, "aria-label": label, "aria-describedby": describedBy,
126
222
  // Wraps at every width; a chip longer than the row ends in "…".
127
223
  className: "w-full max-w-full min-w-0 flex-wrap", children: visible.map((option) => {
128
224
  const picked = isPicked(option.id);
129
225
  const saving = (pending.get(option.id)?.inFlight ?? 0) > 0;
130
226
  return (_jsxs(ToggleGroupItem, { value: String(option.id), onPressedChange: (next) => toggle(option, next), "aria-busy": saving || undefined, "aria-describedby": refused.has(option.id) ? errorId(option.id) : undefined, title: option.label, className: "max-w-full min-w-0", children: [option.icon && (_jsx("span", { "aria-hidden": "true", className: "inline-flex shrink-0", children: option.icon })), _jsx("span", { className: "min-w-0 truncate", children: option.label }), _jsx("span", { "aria-hidden": "true", className: "inline-flex size-3.5 shrink-0 items-center justify-center", children: saving ? (_jsx(Spinner, { className: "size-3.5 text-muted-foreground" })) : (picked && _jsx(CheckIcon, { className: "size-3.5" })) })] }, option.id));
131
- }) })), !loading && capped && hidden > 0 && (_jsxs(Button, { type: "button", variant: "link", size: "sm", className: "h-auto w-fit p-0", "aria-label": `Show All ${options.length} ${label}`, onClick: () => setShowAll(true), children: ["Show All ", options.length] })), refused.size > 0 && (_jsx(FieldError, { className: "type-caption flex flex-col gap-0.5", children: [...refused].map(([option, reason]) => (_jsx("span", { id: errorId(option), children: reason }, String(option)))) }))] }));
227
+ }) })), !loading && capped && hidden > 0 && (_jsxs(Button, { type: "button", variant: "link", size: "sm", className: "h-auto w-fit p-0", "aria-label": `Show All ${all.length} ${label}`, onClick: () => setShowAll(true), children: ["Show All ", all.length] })), offerCreate && (_jsxs(Button, { ref: createButton, type: "button", variant: "outline", size: "sm", "data-create": "", "aria-disabled": creating !== null || undefined, "aria-busy": creating !== null || undefined, "aria-describedby": createFailed ? createErrorId : undefined, onClick: create, className: "w-fit max-w-full min-w-0", children: [creating !== null && _jsx(Spinner, { "aria-hidden": "true", className: "size-3.5" }), _jsx("span", { className: "min-w-0 truncate", children: creating !== null ? `Creating "${creating}"…` : `Create "${name}"` })] })), _jsx("span", { role: "status", className: "sr-only", children: announced }), (refused.size > 0 || createFailed) && (_jsxs(FieldError, { className: "type-caption flex flex-col gap-0.5", children: [[...refused].map(([option, reason]) => (_jsx("span", { id: errorId(option), children: reason }, String(option)))), createFailed && _jsx("span", { id: createErrorId, children: createFailed })] }))] }));
132
228
  }
133
229
  function without(map, key) {
134
230
  if (!map.has(key))
@@ -4,10 +4,10 @@ import { Input } from '../ui/input.js';
4
4
  import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select.js';
5
5
  import { linkHref, linkRule } from '../../lib/link-href.js';
6
6
  import { editInPlace } from './edit-in-place.js';
7
- import { EditableValue } from './editable-value.js';
7
+ import { EditableField } from './editable-value.js';
8
8
  /** A name in one line: Enter saves, the form's rule runs first, a taken name's 422 shows in the cell. */
9
9
  export function NameCell({ label, value, save, schema, children, inputClassName = 'w-48' }) {
10
- return (_jsx(EditableValue, { label: label, layout: "inline", edit: editInPlace({
10
+ return (_jsx(EditableField, { keepPencilRoom: true, label: label, layout: "inline", edit: editInPlace({
11
11
  kind: 'text',
12
12
  value,
13
13
  schema,
@@ -17,7 +17,7 @@ export function NameCell({ label, value, save, schema, children, inputClassName
17
17
  }
18
18
  /** A single choice: its list opens with the cell, a pick saves, closing it with no pick gives up. */
19
19
  export function ChoiceCell({ label, value, options, render, save, triggerClassName = 'w-40', }) {
20
- return (_jsx(EditableValue, { label: label, layout: "inline", edit: editInPlace({
20
+ return (_jsx(EditableField, { keepPencilRoom: true, label: label, layout: "inline", edit: editInPlace({
21
21
  kind: 'choice',
22
22
  value,
23
23
  save,
@@ -52,7 +52,7 @@ export function LinkCell({ label, value, save, linkText, emptyLabel = 'Not set',
52
52
  // Only an address the editor would have saved is shown as a link: a
53
53
  // stored `javascript:` reads as text, never as something to click.
54
54
  const href = value ? linkHref(value) : null;
55
- return (_jsx(EditableValue, { label: label, layout: "inline", edit: editInPlace({
55
+ return (_jsx(EditableField, { keepPencilRoom: true, label: label, layout: "inline", edit: editInPlace({
56
56
  kind: 'text',
57
57
  value: value ?? '',
58
58
  schema: LINK_RULE,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tristan2828/ui-foundation",
3
- "version": "4.101.0",
3
+ "version": "4.102.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": {