@tristan2828/ui-foundation 4.70.0 → 4.72.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.
@@ -1,4 +1,4 @@
1
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
1
+ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  // A list of sub-items edited in place on a record's view (cell-patterns.md
3
3
  // "Editable list"): editInPlace's `list` kind, on a `content` section of
4
4
  // EntityView. Built on ListEditor, so the rows and their buttons are the
@@ -17,12 +17,20 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
17
17
  // - Every change is one save of the whole list, built from the record's
18
18
  // latest list when it's sent (`save` takes a change, not a list), so it
19
19
  // never undoes a tick or another change still saving.
20
+ // - `groupBy` shows the items under headings, each group its own rows and
21
+ // Add; `filter` shows only some. Both only change what's shown: the
22
+ // list saves as one, in its own order, and a move swaps an item with the
23
+ // next one shown. `duplicate` adds ListEditor's Duplicate button.
24
+ // - A refusal about an item's own field (the schema's, or a 422 at
25
+ // `<name>.2.text`) goes to the row as `errors`; `itemForm` hands the row
26
+ // a react-hook-form form of the list instead, with those errors set on it.
20
27
  import { PlusIcon } from 'lucide-react';
21
28
  import { useContext, useEffect, useId, useRef, useState } from 'react';
29
+ import { FormProvider, useForm } from 'react-hook-form';
22
30
  import { Button } from '../ui/button.js';
23
31
  import { FieldError } from '../ui/field.js';
24
32
  import { Spinner } from '../ui/spinner.js';
25
- import { EditInPlaceContext } from './edit-in-place.js';
33
+ import { EditInPlaceContext, } from './edit-in-place.js';
26
34
  import { messageOf } from './edit-in-place-store.js';
27
35
  import { EditableField } from './editable-value.js';
28
36
  import { ListEditor } from './list-editor.js';
@@ -43,8 +51,8 @@ function locate(current, item, index) {
43
51
  function ItemRow({ children }) {
44
52
  return _jsx("span", { className: "flex min-w-0 items-start gap-2 [&>:only-child]:flex-1", children: children });
45
53
  }
46
- // The list's schema, run on the list this draft would make. A message
47
- // about this item comes first, then one about the list as a whole (too
54
+ // The list's schema, run on the list this draft would make. Messages
55
+ // about this item come first, then one about the list as a whole (too
48
56
  // many items).
49
57
  function checkItem(edit, items, index, draft) {
50
58
  if (!edit.schema)
@@ -54,20 +62,82 @@ function checkItem(edit, items, index, draft) {
54
62
  if (result.success)
55
63
  return { success: true, data: result.data[index] };
56
64
  const { issues } = result.error;
57
- const issue = issues.find(({ path }) => path?.[0] === index) ?? issues.find(({ path }) => !path?.length) ?? issues[0];
58
- return { success: false, error: { issues: issue ? [issue] : [] } };
65
+ const own = issues.filter(({ path }) => path?.[0] === index);
66
+ const issue = own[0] ?? issues.find(({ path }) => !path?.length) ?? issues[0];
67
+ return { success: false, error: { issues: own.length > 0 ? own : issue ? [issue] : [] } };
68
+ }
69
+ // What a refusal says about the item's own fields, keyed by the field's
70
+ // path inside the item (`text`, `links.0.url`): the schema's issues at
71
+ // [index, ...], or a 422's field errors at `<name>.<index>.…`.
72
+ function itemFieldErrors(edit, index, cause) {
73
+ const errors = {};
74
+ if (cause && typeof cause === 'object' && 'issues' in cause) {
75
+ for (const { message, path } of cause.issues) {
76
+ if (path?.[0] !== index || path.length < 2)
77
+ continue;
78
+ errors[path.slice(1).map(String).join('.')] ??= message;
79
+ }
80
+ }
81
+ else if (edit.name && cause && typeof cause === 'object' && 'kind' in cause) {
82
+ const prefix = `${edit.name}.${index}.`;
83
+ for (const [field, messages] of Object.entries(cause.fieldErrors ?? {})) {
84
+ if (field.startsWith(prefix) && messages[0])
85
+ errors[field.slice(prefix.length)] ??= messages[0];
86
+ }
87
+ }
88
+ return Object.keys(errors).length > 0 ? errors : null;
89
+ }
90
+ // A form of the whole list, for the one open item: the form's own row
91
+ // registers its fields here as it does on the form, and every change to
92
+ // it is the item's draft. A refusal's field errors are set on it, so the
93
+ // row shows them where the form would.
94
+ function ItemForm({ name, index, list, props, render }) {
95
+ const [defaultValues] = useState(() => ({ [name]: structuredClone(list) }));
96
+ const form = useForm({ defaultValues });
97
+ const onChange = useRef(props.onChange);
98
+ useEffect(() => {
99
+ onChange.current = props.onChange;
100
+ });
101
+ const { subscribe } = form;
102
+ useEffect(() => subscribe({
103
+ formState: { values: true },
104
+ callback: ({ values }) => {
105
+ const item = values[name]?.[index];
106
+ onChange.current(structuredClone(item));
107
+ },
108
+ }), [subscribe, name, index]);
109
+ const { errors } = props;
110
+ useEffect(() => {
111
+ form.clearErrors();
112
+ for (const [path, message] of Object.entries(errors ?? {}))
113
+ form.setError(`${name}.${index}.${path}`, { type: 'refused', message });
114
+ }, [form, name, index, errors]);
115
+ return _jsx(FormProvider, { ...form, children: render({ ...props, form }) });
59
116
  }
60
117
  // The app's own add, as a component of its own: it renders the app's
61
118
  // control with what it's given, and holds nothing.
62
119
  function ListAdd({ render, ...props }) {
63
120
  return _jsx("div", { "data-list-add-slot": "", children: render(props) });
64
121
  }
122
+ function runsOf(edit, items) {
123
+ const shown = items.map((_, index) => index).filter((index) => !edit.filter || edit.filter(items[index], index));
124
+ const groupBy = edit.groupBy;
125
+ if (!groupBy)
126
+ return [{ key: null, heading: null, indices: shown }];
127
+ const groups = new Map((groupBy.order ?? []).map((key) => [key, []]));
128
+ for (const index of shown) {
129
+ const key = groupBy.key(items[index]);
130
+ groups.set(key, [...(groups.get(key) ?? []), index]);
131
+ }
132
+ return [...groups].map(([key, indices]) => ({ key, heading: groupBy.label?.(key) ?? key, indices }));
133
+ }
65
134
  export function EditableList({ label, edit, emptyLabel }) {
66
135
  const store = useContext(EditInPlaceContext);
67
136
  if (!store)
68
137
  throw new Error('A list edited in place works inside an <EntityView>, which runs editing in place.');
69
138
  const items = edit.value;
70
139
  const statusId = useId();
140
+ const headingId = useId();
71
141
  const [status, setStatus] = useState({ saving: false, inFlight: 0, error: null });
72
142
  // The buttons are disabled while a change saves, which drops the caret.
73
143
  // Once the list shows the outcome it goes to the first of these buttons
@@ -84,10 +154,11 @@ export function EditableList({ label, edit, emptyLabel }) {
84
154
  const target = names.map((name) => buttons.find((button) => button.getAttribute('aria-label') === name)).find(Boolean);
85
155
  (target ?? root.current?.querySelector('[data-list-add]:not(:disabled), [data-list-add-slot] button:not(:disabled)'))?.focus();
86
156
  }, [items, status.saving]);
87
- // Move, remove and the app's own add: save the open field first (if it
88
- // can't save, it stays and nothing else happens), then the change. An
89
- // add that lands while a change saves (an upload finishing) still goes:
90
- // `save` builds on the latest list, and "Saving…" stays until both are done.
157
+ // Move, remove, duplicate and the app's own add: save the open field
158
+ // first (if it can't save, it stays and nothing else happens), then the
159
+ // change. An add that lands while a change saves (an upload finishing)
160
+ // still goes: `save` builds on the latest list, and "Saving…" stays
161
+ // until both are done.
91
162
  const act = async (change, focusAfter, focusIfRefused, waits = true) => {
92
163
  if (waits && status.saving)
93
164
  return false;
@@ -107,47 +178,111 @@ export function EditableList({ label, edit, emptyLabel }) {
107
178
  setStatus((now) => ({ saving: now.inFlight > 1, inFlight: now.inFlight - 1, error: error ?? now.error }));
108
179
  return error === null;
109
180
  };
181
+ // Grouped or filtered, the rows a ListEditor shows aren't the whole
182
+ // list: a move swaps the item with the next one shown, wherever that is.
183
+ const partial = Boolean(edit.groupBy || edit.filter);
110
184
  const move = (from, to) => {
111
185
  const direction = to < from ? 'up' : 'down';
112
186
  const other = direction === 'up' ? 'down' : 'up';
113
187
  void act((current) => {
114
188
  const at = locate(current, items[from], from);
115
- const target = at + (to - from);
116
- if (target < 0 || target >= current.length)
189
+ const target = partial ? locate(current, items[to], to) : at + (to - from);
190
+ if (target < 0 || target >= current.length || target === at)
117
191
  return current;
118
192
  const next = [...current];
119
- next.splice(target, 0, ...next.splice(at, 1));
193
+ if (partial)
194
+ [next[at], next[target]] = [next[target], next[at]];
195
+ else
196
+ next.splice(target, 0, ...next.splice(at, 1));
120
197
  return next;
121
198
  }, [`Move ${edit.itemName(to)} ${direction}`, `Move ${edit.itemName(to)} ${other}`], [`Move ${edit.itemName(from)} ${direction}`]);
122
199
  };
123
- const remove = (index) => void act((current) => {
124
- const at = locate(current, items[index], index);
125
- return current.filter((_, i) => i !== at);
126
- }, [`Remove ${edit.itemName(index)}`, `Remove ${edit.itemName(index - 1)}`], [`Remove ${edit.itemName(index)}`]);
200
+ // `shown` is the run the item was removed from: the caret goes to the
201
+ // next one there (one place earlier once this one's gone), else the one before.
202
+ const remove = (index, shown) => {
203
+ const at = shown.indexOf(index);
204
+ const after = shown[at + 1];
205
+ const before = shown[at - 1];
206
+ void act((current) => {
207
+ const found = locate(current, items[index], index);
208
+ return current.filter((_, i) => i !== found);
209
+ }, [
210
+ ...(after !== undefined ? [`Remove ${edit.itemName(after - 1)}`] : []),
211
+ ...(before !== undefined ? [`Remove ${edit.itemName(before)}`] : []),
212
+ ], [`Remove ${edit.itemName(index)}`]);
213
+ };
214
+ const duplicate = edit.duplicate;
215
+ const copy = (index) => {
216
+ if (!duplicate)
217
+ return;
218
+ void act((current) => {
219
+ const at = locate(current, items[index], index);
220
+ const next = [...current];
221
+ next.splice(at + 1, 0, duplicate(current[at]));
222
+ return next;
223
+ }, [`Duplicate ${edit.itemName(index)}`], [`Duplicate ${edit.itemName(index)}`]);
224
+ };
225
+ const itemForm = Boolean(edit.itemForm);
226
+ if (itemForm && !edit.name)
227
+ throw new Error('A list edited in place with `itemForm` needs `name`: the list field the form holds.');
228
+ const errorsOnFields = itemForm || Boolean(edit.errorsOnFields);
229
+ // The row, as the app's renderItem draws it: given a form of the list
230
+ // with the draft in it, with `itemForm`.
231
+ const row = (props, index, isNew, group) => {
232
+ const itemProps = { ...props, index, isNew, ...(group !== undefined ? { group } : {}) };
233
+ if (!itemForm)
234
+ return _jsx(ItemRow, { children: edit.renderItem(itemProps) });
235
+ const list = isNew ? [...items, props.value] : items.map((item, i) => (i === index ? props.value : item));
236
+ return (_jsx(ItemRow, { children: _jsx(ItemForm, { name: edit.name, index: index, list: list, props: itemProps, render: edit.renderItem }) }));
237
+ };
127
238
  // An item, edited as the form's row.
128
239
  const itemEdit = (index) => ({
129
240
  kind: 'text',
130
241
  value: items[index],
131
- control: (props) => _jsx(ItemRow, { children: edit.renderItem({ ...props, index, isNew: false }) }),
242
+ control: (props) => row(props, index, false),
132
243
  schema: { safeParse: (draft) => checkItem(edit, items, index, draft) },
133
244
  save: (item) => edit.save((current) => {
134
245
  const at = locate(current, items[index], index);
135
246
  return current.map((other, i) => (i === at ? item : other));
136
247
  }),
248
+ fieldErrors: (cause) => itemFieldErrors(edit, index, cause),
249
+ errorsOnFields,
137
250
  });
138
251
  // The app's own add: its items saved at the end, the caret back on it.
139
252
  const addItems = (added) => added.length === 0 ? Promise.resolve(true) : act((current) => [...current, ...added], [], [], false);
140
253
  const onProblem = (message) => setStatus((now) => ({ ...now, error: message }));
141
- // The item being added, at the end.
254
+ // The item being added, at the end of the list (a group's Add puts it
255
+ // in that group: its blank item says which).
142
256
  const newItem = edit.newItem;
143
257
  if (!newItem && !edit.add)
144
258
  throw new Error('A list edited in place needs `newItem` (a blank item to add) or `add` (its own control).');
145
- const addEdit = {
259
+ const addEdit = (group) => ({
146
260
  kind: 'text',
147
- value: newItem?.(),
148
- control: (props) => _jsx(ItemRow, { children: edit.renderItem({ ...props, index: items.length, isNew: true }) }),
261
+ value: newItem?.(group),
262
+ control: (props) => row(props, items.length, true, group),
149
263
  schema: { safeParse: (draft) => checkItem(edit, items, items.length, draft) },
150
264
  save: (item) => edit.save((current) => [...current, item]),
265
+ fieldErrors: (cause) => itemFieldErrors(edit, items.length, cause),
266
+ errorsOnFields,
267
+ });
268
+ const addBox = (run, last) => {
269
+ if (edit.add) {
270
+ // The app's own add is the list's, once, at the end.
271
+ return last ? _jsx(ListAdd, { render: edit.add, add: addItems, items: items, disabled: status.saving, onProblem: onProblem }) : _jsx(_Fragment, {});
272
+ }
273
+ const group = run.key ?? undefined;
274
+ return (_jsx(EditableField, { label: edit.itemName(items.length), edit: addEdit(group), reopenAfterKeyboardSave: true, children: null, trigger: (start) => (_jsx("div", { children: _jsxs(Button, { "data-list-add": "", type: "button", variant: "outline", size: "sm", disabled: status.saving, onClick: start, "aria-label": run.heading !== null && edit.addLabel ? `${edit.addLabel} to ${run.heading}` : undefined, children: [_jsx(PlusIcon, {}), edit.addLabel] }) })) }));
151
275
  };
152
- return (_jsxs("div", { ref: root, className: "flex flex-col gap-2", "data-slot": "editable-list", children: [_jsx(ListEditor, { "aria-label": label, items: items.map((_, index) => ({ id: String(index) })), itemName: edit.itemName, addLabel: edit.addLabel ?? '', emptyText: emptyLabel, disabled: status.saving, onRemove: remove, onMove: move, renderItem: (index) => (_jsx(EditableField, { label: edit.itemName(index), edit: itemEdit(index), children: edit.renderShown(items[index], index) })), add: edit.add ? (_jsx(ListAdd, { render: edit.add, add: addItems, items: items, disabled: status.saving, onProblem: onProblem })) : (_jsx(EditableField, { label: edit.itemName(items.length), edit: addEdit, reopenAfterKeyboardSave: true, children: null, trigger: (start) => (_jsx("div", { children: _jsxs(Button, { "data-list-add": "", type: "button", variant: "outline", size: "sm", disabled: status.saving, onClick: start, children: [_jsx(PlusIcon, {}), edit.addLabel] }) })) })) }), _jsx("span", { id: statusId, className: "type-body", children: status.saving ? (_jsxs("span", { role: "status", className: "inline-flex items-center gap-1.5 type-caption text-muted-foreground", children: [_jsx(Spinner, { "aria-hidden": "true", className: "size-3.5" }), "Saving\u2026"] })) : (status.error && _jsx(FieldError, { className: "type-caption", children: status.error })) })] }));
276
+ const runs = runsOf(edit, items);
277
+ const grouped = Boolean(edit.groupBy) && runs.length > 0;
278
+ const shownRuns = grouped ? runs : [runs[0] ?? { key: null, heading: null, indices: [] }];
279
+ return (_jsxs("div", { ref: root, className: "flex flex-col gap-2", "data-slot": "editable-list", children: [_jsx("div", { className: grouped ? 'flex flex-col gap-4' : 'contents', children: shownRuns.map((run, at) => {
280
+ const list = (_jsx(ListEditor, { "aria-label": run.heading === null ? label : `${label}: ${run.heading}`, items: run.indices.map((index) => ({ id: String(index) })), itemName: (position) => edit.itemName(run.indices[position] ?? items.length), addLabel: edit.addLabel ?? '', emptyText: emptyLabel, disabled: status.saving, onRemove: (position) => remove(run.indices[position], run.indices), onMove: (from, to) => move(run.indices[from], run.indices[to]), onDuplicate: duplicate ? (position) => copy(run.indices[position]) : undefined, renderItem: (position) => {
281
+ const index = run.indices[position];
282
+ return (_jsx(EditableField, { label: edit.itemName(index), edit: itemEdit(index), children: edit.renderShown(items[index], index) }));
283
+ }, add: addBox(run, at === shownRuns.length - 1) }));
284
+ if (!grouped)
285
+ return _jsx("div", { className: "contents", children: list }, "list");
286
+ return (_jsxs("div", { role: "group", "aria-labelledby": `${headingId}-${at}`, className: "flex flex-col gap-2", children: [_jsx("h3", { id: `${headingId}-${at}`, className: "type-label text-muted-foreground", children: run.heading }), list] }, run.key));
287
+ }) }), _jsx("span", { id: statusId, className: "type-body", children: status.saving ? (_jsxs("span", { role: "status", className: "inline-flex items-center gap-1.5 type-caption text-muted-foreground", children: [_jsx(Spinner, { "aria-hidden": "true", className: "size-3.5" }), "Saving\u2026"] })) : (status.error && _jsx(FieldError, { className: "type-caption", children: status.error })) })] }));
153
288
  }
@@ -5,8 +5,8 @@ export type EditableValueProps = {
5
5
  /** The field's label: the control's accessible name, and the edit button's ("Edit Name"). */
6
6
  label: string;
7
7
  edit: EditInPlace;
8
- /** The value as the view shows it. */
9
- children: ReactNode;
8
+ /** The value as the view shows it. Defaults to the edit's `shown` (an `inPlace` preset's). */
9
+ children?: ReactNode;
10
10
  /** `inline` in a heading or beside badges, `block` in a field row (default). */
11
11
  layout?: 'inline' | 'block';
12
12
  className?: string;
@@ -206,14 +206,18 @@ export function EditableField({ label, edit, children, layout = 'block', classNa
206
206
  if (state.status === 'closed' && !always) {
207
207
  if (trigger)
208
208
  return (_jsx("span", { ref: triggerBox, className: "contents", children: trigger(start) }));
209
- return (_jsxs("span", { "data-slot": "editable-value", onClick: onShownClick, className: cn('group/editable relative -mx-1.5 cursor-text items-start gap-1 rounded-md px-1.5 transition-colors hover:bg-muted has-[[data-edit]:focus-visible]:bg-muted', layout === 'block' ? 'flex w-full' : 'inline-flex max-w-full align-top', className), children: [_jsx("span", { className: "min-w-0 flex-1 group-hover/editable:[&_.text-muted-foreground]:text-foreground group-has-[[data-edit]:focus-visible]/editable:[&_.text-muted-foreground]:text-foreground", children: children }), _jsx(Button, { ref: editButton, "data-edit": "", type: "button", variant: "ghost", size: "icon-xs", "aria-label": `Edit ${label}`, onClick: start, className: "shrink-0 text-muted-foreground opacity-0 group-hover/editable:opacity-100 focus-visible:opacity-100 pointer-coarse:opacity-100", children: _jsx(PencilIcon, {}) })] }));
209
+ return (_jsxs("span", { "data-slot": "editable-value", onClick: onShownClick, className: cn('group/editable relative -mx-1.5 cursor-text items-start gap-1 rounded-md px-1.5 transition-colors hover:bg-muted has-[[data-edit]:focus-visible]:bg-muted', layout === 'block' ? 'flex w-full' : 'inline-flex max-w-full align-top', className), children: [_jsx("span", { className: "min-w-0 flex-1 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(Button, { ref: editButton, "data-edit": "", type: "button", variant: "ghost", size: "icon-xs", "aria-label": `Edit ${label}`, onClick: start, className: "shrink-0 text-muted-foreground opacity-0 group-hover/editable:opacity-100 focus-visible:opacity-100 pointer-coarse:opacity-100", children: _jsx(PencilIcon, {}) })] }));
210
210
  }
211
211
  // Always editable, before the store has it (the first render): the saved value.
212
212
  const open = state.status === 'closed' ? { status: 'open', draft: edit.value, error: null, autosave: undefined, revision: 0 } : state;
213
213
  const saving = open.status === 'saving';
214
214
  const autosaving = open.autosave === 'saving';
215
- return (_jsxs("span", { ref: container, "data-slot": "editable-value", "data-state": saving || autosaving ? 'saving' : open.error ? 'failed' : 'editing', onKeyDown: onKeyDown, onBlur: onBlur, onFocus: onFocus, className: cn('flex min-w-0 flex-col gap-1.5', layout === 'block' ? 'w-full' : 'w-fit max-w-full', className), children: [_jsx(Control, { render: edit.control, id: controlId, value: open.draft, onChange: (value) => store.change(key, value), commit: commit, cancel: cancel, disabled: saving, invalid: !saving && open.error !== null, label: label, describedBy: describedBy, onProblem: (problem) => store.report(key, problem), inline: Boolean(edit.inline) }, open.revision ?? 0), _jsx("span", { id: describedBy, className: "type-body", children: autosave ? (_jsxs(_Fragment, { children: [open.error && _jsx(FieldError, { className: "type-caption", children: open.error }), _jsx("span", { role: "status", className: "inline-flex items-center gap-1.5 type-caption text-muted-foreground", children: autosaving ? (_jsxs(_Fragment, { children: [_jsx(Spinner, { "aria-hidden": "true", className: "size-3.5" }), "Saving\u2026"] })) : (open.autosave === 'saved' &&
216
- !open.error && (_jsxs(_Fragment, { children: [_jsx(CheckIcon, { "aria-hidden": "true", className: "size-3.5" }), "Saved"] }))) })] })) : saving ? (_jsxs("span", { role: "status", className: "inline-flex items-center gap-1.5 type-caption text-muted-foreground", children: [_jsx(Spinner, { "aria-hidden": "true", className: "size-3.5" }), "Saving\u2026"] })) : (open.error && _jsx(FieldError, { className: "type-caption", children: open.error })) })] }));
215
+ const fieldErrors = 'fieldErrors' in open ? (open.fieldErrors ?? undefined) : undefined;
216
+ // A refusal about one of the value's own fields shows on that field when
217
+ // the control says it shows them; anything else shows under the control.
218
+ const lineError = edit.errorsOnFields && fieldErrors ? null : open.error;
219
+ return (_jsxs("span", { ref: container, "data-slot": "editable-value", "data-state": saving || autosaving ? 'saving' : open.error ? 'failed' : 'editing', onKeyDown: onKeyDown, onBlur: onBlur, onFocus: onFocus, className: cn('flex min-w-0 flex-col gap-1.5', layout === 'block' ? 'w-full' : 'w-fit max-w-full', className), children: [_jsx(Control, { render: edit.control, id: controlId, value: open.draft, onChange: (value) => store.change(key, value), commit: commit, cancel: cancel, disabled: saving, invalid: !saving && open.error !== null, label: label, describedBy: describedBy, onProblem: (problem) => store.report(key, problem), inline: Boolean(edit.inline), errors: saving ? undefined : fieldErrors }, open.revision ?? 0), _jsx("span", { id: describedBy, className: "type-body", children: autosave ? (_jsxs(_Fragment, { children: [lineError && _jsx(FieldError, { className: "type-caption", children: lineError }), _jsx("span", { role: "status", className: "inline-flex items-center gap-1.5 type-caption text-muted-foreground", children: autosaving ? (_jsxs(_Fragment, { children: [_jsx(Spinner, { "aria-hidden": "true", className: "size-3.5" }), "Saving\u2026"] })) : (open.autosave === 'saved' &&
220
+ !open.error && (_jsxs(_Fragment, { children: [_jsx(CheckIcon, { "aria-hidden": "true", className: "size-3.5" }), "Saved"] }))) })] })) : saving ? (_jsxs("span", { role: "status", className: "inline-flex items-center gap-1.5 type-caption text-muted-foreground", children: [_jsx(Spinner, { "aria-hidden": "true", className: "size-3.5" }), "Saving\u2026"] })) : (lineError && _jsx(FieldError, { className: "type-caption", children: lineError })) })] }));
217
221
  }
218
222
  /**
219
223
  * While a field holds something unsaved, leaving asks first: an in-app
@@ -8,10 +8,14 @@ export type EntityViewField = {
8
8
  * and an empty array all count as empty and show `emptyLabel` instead,
9
9
  * so `{tags.map(...)}` or `{email}` can be passed as they are.
10
10
  */
11
- value: ReactNode;
11
+ value?: ReactNode;
12
12
  /** What an empty value reads as: the plan's "not set" label. Defaults to "Not set". */
13
13
  emptyLabel?: string;
14
- /** Editable in place: `editInPlace({...})`. Unmarked, the value is read-only. */
14
+ /**
15
+ * Editable in place: `editInPlace({...})`, or a ready-made `inPlace`
16
+ * preset, whose `shown` is the value when `value` is left out.
17
+ * Unmarked, the value is read-only.
18
+ */
15
19
  edit?: EditInPlace;
16
20
  };
17
21
  /**
@@ -95,7 +95,9 @@ const FIELD_ROW = {
95
95
  rail: '@lg/fields:grid @lg/fields:grid-cols-[minmax(--spacing(32),--spacing(48))_1fr] @lg/fields:gap-6',
96
96
  };
97
97
  function FieldRow({ field, inRail }) {
98
- return (_jsxs("div", { className: cn('flex flex-col gap-1 py-3 first:pt-0 last:pb-0', FIELD_ROW[inRail ? 'rail' : 'page']), children: [_jsx("dt", { className: "type-label text-muted-foreground", children: field.label }), _jsx("dd", { className: "min-w-0 type-body break-words text-foreground", children: field.edit ? (_jsx(EditableValue, { label: field.label, edit: field.edit, children: orEmptyLabel(field.value, field.emptyLabel) })) : (orEmptyLabel(field.value, field.emptyLabel)) })] }));
98
+ // A preset shows its own value unless the screen gives one.
99
+ const value = field.value !== undefined ? field.value : field.edit?.shown;
100
+ return (_jsxs("div", { className: cn('flex flex-col gap-1 py-3 first:pt-0 last:pb-0', FIELD_ROW[inRail ? 'rail' : 'page']), children: [_jsx("dt", { className: "type-label text-muted-foreground", children: field.label }), _jsx("dd", { className: "min-w-0 type-body break-words text-foreground", children: field.edit ? (_jsx(EditableValue, { label: field.label, edit: field.edit, children: orEmptyLabel(value, field.emptyLabel) })) : (orEmptyLabel(value, field.emptyLabel)) })] }));
99
101
  }
100
102
  function ViewSection({ section, inRail = false }) {
101
103
  const headingId = useId();
@@ -181,7 +183,14 @@ export function EntityView({ title, documentTitle, titleEdit, subtitle, badges,
181
183
  .filter((section) => section.print)
182
184
  .map((section) => ({
183
185
  title: section.title,
184
- ...('fields' in section ? { fields: section.fields } : { content: section.content, emptyLabel: section.emptyLabel }),
186
+ ...('fields' in section
187
+ ? {
188
+ fields: section.fields.map((field) => ({
189
+ label: field.label,
190
+ value: field.value !== undefined ? field.value : field.edit?.shown,
191
+ })),
192
+ }
193
+ : { content: section.content, emptyLabel: section.emptyLabel }),
185
194
  answerSpace: typeof section.print === 'object' && section.print.answerSpace === true,
186
195
  }));
187
196
  const printButton = printSections.length > 0 && (_jsx(PrintNotes, { label: printLabel, title: title, subtitle: subtitle, sections: printSections }));
@@ -17,8 +17,17 @@ export type RecordDialogRouteProps = {
17
17
  * over the list. True by default.
18
18
  */
19
19
  fullPage?: boolean;
20
+ /**
21
+ * Where the list lives when it isn't this route's own address: a child
22
+ * route of this one with no element (`'list'` for `/things/list`), or
23
+ * an absolute path under it. This route's other children are its
24
+ * records (`/things/12`), drawn over the list when opened from it. Left
25
+ * out, the list is this route's own address and its children are the
26
+ * records (the nested pattern).
27
+ */
28
+ listPath?: string;
20
29
  };
21
- export declare function RecordDialogRoute({ list, label, className, fullPage }: RecordDialogRouteProps): import("react").JSX.Element;
30
+ export declare function RecordDialogRoute({ list, label, className, fullPage, listPath: listAt }: RecordDialogRouteProps): import("react").JSX.Element | null;
22
31
  export type RecordLinkProps = Omit<ComponentProps<typeof Link>, 'state'>;
23
32
  /**
24
33
  * A link to a record that opens it over the current list (a board's card,
@@ -28,6 +28,25 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
28
28
  // another page opens the dialog over its own list, at the list's plain
29
29
  // address.
30
30
  //
31
+ // A list that isn't the record's parent route (`listPath`, 4.71): the
32
+ // list at /things/list, the record at /things/12, siblings. The route the
33
+ // two share wraps them, its `list` drawn at `listPath` (whose own route
34
+ // has no element) and every other child the record:
35
+ //
36
+ // { path: 'things', element: <RecordDialogRoute list={<ThingsList />} listPath="list" label="Thing" />,
37
+ // children: [{ path: 'list' }, { path: ':id', element: <ThingView /> }] }
38
+ //
39
+ // Opened from the list, /things/12 is the dialog over /things/list, and
40
+ // closing goes back to it; a deep link is the full page, as above.
41
+ //
42
+ // A sub-record over its parent's page (4.71) is the same route one level
43
+ // down: the parent's page is the `list`, the sub-record its child, and
44
+ // `fullPage={false}`, so a reload of /parents/7/children/31 is the dialog
45
+ // over the parent again:
46
+ //
47
+ // { path: 'parents/:id', element: <RecordDialogRoute list={<ParentView />} label="Document" fullPage={false} />,
48
+ // children: [{ path: 'children/:childId', element: <ChildView /> }] }
49
+ //
31
50
  // Inside, the record's route renders as it always does. EntityView sees
32
51
  // the dialog (useRecordDialog): its heading names the dialog, its back link
33
52
  // gives way to the dialog's own bar, and not found's way out closes the
@@ -40,19 +59,24 @@ import { Button, buttonVariants } from '../ui/button.js';
40
59
  import { Dialog, DialogClose, DialogContent } from '../ui/dialog.js';
41
60
  import { escapePassedThrough } from './escape-passthrough.js';
42
61
  import { backgroundOf, recordDialogState, RecordDialogContext } from './record-dialog-context.js';
43
- export function RecordDialogRoute({ list, label, className, fullPage = true }) {
62
+ // Two paths are the same address, give or take a trailing slash.
63
+ const samePath = (a, b) => a.replace(/\/+$/, '') === b.replace(/\/+$/, '');
64
+ export function RecordDialogRoute({ list, label, className, fullPage = true, listPath: listAt }) {
44
65
  const location = useLocation();
45
66
  const navigationType = useNavigationType();
46
67
  const navigate = useNavigate();
47
- const outlet = useOutlet();
68
+ const childOutlet = useOutlet();
48
69
  const titleId = useId();
49
- const listPath = useResolvedPath('.').pathname;
70
+ const listPath = useResolvedPath(listAt ?? '.').pathname;
71
+ // With `listPath`, its own (element-less) child is the list, not a record.
72
+ const atList = listAt !== undefined && samePath(location.pathname, listPath);
73
+ const outlet = atList ? null : childOutlet;
50
74
  const opened = backgroundOf(location.state);
51
75
  // Over its own list only: opened from anywhere else, the list under it
52
76
  // would be a page the user wasn't on.
53
77
  // With no full page, a record opened any other way is the dialog over
54
78
  // the list's plain address, with nothing to go back over.
55
- const background = opened && opened.pathname === listPath
79
+ const background = opened && samePath(opened.pathname, listPath)
56
80
  ? opened
57
81
  : !fullPage && outlet !== null
58
82
  ? { pathname: listPath, search: '', hash: '', depth: 0 }
@@ -77,6 +101,10 @@ export function RecordDialogRoute({ list, label, className, fullPage = true }) {
77
101
  // The record's full page: a deep link, or "Open full page".
78
102
  if (outlet !== null && !open)
79
103
  return outlet;
104
+ // `listPath` given and this route's own address (no index route): there
105
+ // is no list here to draw.
106
+ if (listAt !== undefined && outlet === null && !atList)
107
+ return null;
80
108
  return (_jsxs(_Fragment, { children: [_jsx(LocationContext.Provider, { value: listContext, children: list }), _jsx(Dialog, { open: open, onOpenChange: (next, details) => {
81
109
  if (next)
82
110
  return;
@@ -47,6 +47,15 @@ export type LinkCellProps = {
47
47
  /** The input's width class. Defaults to `w-64`. */
48
48
  inputClassName?: string;
49
49
  };
50
+ /**
51
+ * A link out of the app as LinkCell shows one at rest: the link tone,
52
+ * underlined, an external-link mark, opening in a new tab (said to a
53
+ * screen reader). `href` must be one `linkHref` returned.
54
+ */
55
+ export declare function LinkOut({ href, children }: {
56
+ href: string;
57
+ children: ReactNode;
58
+ }): import("react").JSX.Element;
50
59
  /** An optional link: shown as a link out (or the not-set label), edited as one line; blank clears it. */
51
60
  export declare function LinkCell({ label, value, save, linkText, emptyLabel, inputClassName }: LinkCellProps): import("react").JSX.Element;
52
61
  export {};
@@ -2,7 +2,7 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { ExternalLinkIcon } from 'lucide-react';
3
3
  import { Input } from '../ui/input.js';
4
4
  import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select.js';
5
- import { linkHref, linkRefusal } from '../../lib/link-href.js';
5
+ import { linkHref, linkRule } from '../../lib/link-href.js';
6
6
  import { editInPlace } from './edit-in-place.js';
7
7
  import { EditableValue } 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. */
@@ -32,20 +32,16 @@ export function ChoiceCell({ label, value, options, render, save, triggerClassNa
32
32
  }
33
33
  // A web or email address (`example.com` gains https://), blank for none.
34
34
  // Another scheme (`javascript:`) or a space inside the address is refused
35
- // before anything is sent.
36
- const LINK_RULE = {
37
- safeParse: (value) => {
38
- const typed = String(value ?? '');
39
- const href = linkHref(typed);
40
- if (href === '')
41
- return { success: true, data: null };
42
- if (href === null) {
43
- const message = linkRefusal(typed) === 'whitespace' ? 'An address has no spaces' : 'Use a web or email address';
44
- return { success: false, error: { issues: [{ message }] } };
45
- }
46
- return { success: true, data: href };
47
- },
48
- };
35
+ // before anything is sent: `linkRule`, shared with `inPlace.link`.
36
+ const LINK_RULE = linkRule;
37
+ /**
38
+ * A link out of the app as LinkCell shows one at rest: the link tone,
39
+ * underlined, an external-link mark, opening in a new tab (said to a
40
+ * screen reader). `href` must be one `linkHref` returned.
41
+ */
42
+ export function LinkOut({ href, children }) {
43
+ return (_jsxs("a", { href: href, target: "_blank", rel: "noopener noreferrer", className: "rounded-sm text-link underline underline-offset-4 outline-none focus-visible:ring-3 focus-visible:ring-ring/50", children: [children, _jsx(ExternalLinkIcon, { "aria-hidden": "true", className: "ml-0.5 inline size-3 align-baseline" }), _jsx("span", { className: "sr-only", children: " (opens in a new tab)" })] }));
44
+ }
49
45
  function shownLinkText(href, linkText) {
50
46
  if (typeof linkText === 'function')
51
47
  return linkText(href);
@@ -62,5 +58,5 @@ export function LinkCell({ label, value, save, linkText, emptyLabel = 'Not set',
62
58
  schema: LINK_RULE,
63
59
  save,
64
60
  control: (props) => (_jsx(Input, { id: props.id, type: "url", inputMode: "url", className: inputClassName, value: props.value, placeholder: "https://", readOnly: props.disabled, "aria-invalid": props.invalid || undefined, "aria-label": props.label, "aria-describedby": props.describedBy, onChange: (event) => props.onChange(event.target.value) })),
65
- }), children: !value ? (_jsx("span", { className: "text-muted-foreground", children: emptyLabel })) : href ? (_jsxs("a", { href: href, target: "_blank", rel: "noreferrer", className: "rounded-sm text-link underline underline-offset-4 outline-none focus-visible:ring-3 focus-visible:ring-ring/50", children: [shownLinkText(href, linkText), _jsx(ExternalLinkIcon, { "aria-hidden": "true", className: "ml-0.5 inline size-3 align-baseline" }), _jsx("span", { className: "sr-only", children: " (opens in a new tab)" })] })) : (value) }));
61
+ }), children: !value ? (_jsx("span", { className: "text-muted-foreground", children: emptyLabel })) : href ? (_jsx(LinkOut, { href: href, children: shownLinkText(href, linkText) })) : (value) }));
66
62
  }
package/dist/index.d.ts CHANGED
@@ -19,6 +19,8 @@ export { usePrinting } from './components/app/print-context.js';
19
19
  export { RecordDialogRoute, RecordLink, type RecordDialogRouteProps, type RecordLinkProps, } from './components/app/record-dialog.js';
20
20
  export { recordDialogState, useOpenRecord, useRecordDialog, type RecordDialogBackground, type RecordDialogContextValue, type RecordDialogState, } from './components/app/record-dialog-context.js';
21
21
  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';
22
+ 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 { linkHost, linkHref, linkRule } from './lib/link-href.js';
22
24
  export { DataEnvironmentBanner } from './components/app/data-environment-banner.js';
23
25
  export { EditableValue, type EditableValueProps } from './components/app/editable-value.js';
24
26
  export { ErrorState } from './components/app/error-state.js';
@@ -53,7 +55,7 @@ export { EmojiField, type EmojiFieldProps } from './components/app/emoji-field.j
53
55
  export { ImageField, type ImageFieldProps } from './components/app/image-field.js';
54
56
  export { DEFAULT_IMAGE_TYPES, type ImageUpload, type ImageUploadResult } from './lib/image-file.js';
55
57
  export { formatPlainDate, type PlainDate } from './lib/plain-date.js';
56
- export { ChoiceCell, LinkCell, NameCell, type ChoiceCellProps, type LinkCellProps, type NameCellProps, } from './components/app/row-edit-cells.js';
58
+ export { ChoiceCell, LinkCell, LinkOut, NameCell, type ChoiceCellProps, type LinkCellProps, type NameCellProps, } from './components/app/row-edit-cells.js';
57
59
  export { ModuleCard, ModuleStrip, type CategorySlot, type ModuleCardLink, type ModuleCardPlace, type ModuleCardProps, type ModuleStripMobile, type ModuleStripProps, } from './components/app/module-card.js';
58
60
  export { WidgetCard, WidgetCardGroup, WidgetList, WidgetListItem, type WidgetCardGroupProps, type WidgetCardLink, type WidgetCardProps, type WidgetListItemProps, } from './components/app/widget-card.js';
59
61
  export { WidgetLayoutSheet, type WidgetLayoutSheetProps } from './components/app/widget-layout-sheet.js';
package/dist/index.js CHANGED
@@ -23,6 +23,8 @@ export { usePrinting } from './components/app/print-context.js';
23
23
  export { RecordDialogRoute, RecordLink, } from './components/app/record-dialog.js';
24
24
  export { recordDialogState, useOpenRecord, useRecordDialog, } from './components/app/record-dialog-context.js';
25
25
  export { editInPlace, } from './components/app/edit-in-place.js';
26
+ export { inPlace, } from './components/app/edit-in-place-presets.js';
27
+ export { linkHost, linkHref, linkRule } from './lib/link-href.js';
26
28
  export { DataEnvironmentBanner } from './components/app/data-environment-banner.js';
27
29
  export { EditableValue } from './components/app/editable-value.js';
28
30
  export { ErrorState } from './components/app/error-state.js';
@@ -56,7 +58,7 @@ export { EmojiField } from './components/app/emoji-field.js';
56
58
  export { ImageField } from './components/app/image-field.js';
57
59
  export { DEFAULT_IMAGE_TYPES } from './lib/image-file.js';
58
60
  export { formatPlainDate } from './lib/plain-date.js';
59
- export { ChoiceCell, LinkCell, NameCell, } from './components/app/row-edit-cells.js';
61
+ export { ChoiceCell, LinkCell, LinkOut, NameCell, } from './components/app/row-edit-cells.js';
60
62
  export { ModuleCard, ModuleStrip, } from './components/app/module-card.js';
61
63
  export { WidgetCard, WidgetCardGroup, WidgetList, WidgetListItem, } from './components/app/widget-card.js';
62
64
  export { WidgetLayoutSheet } from './components/app/widget-layout-sheet.js';
@@ -2,3 +2,31 @@
2
2
  export declare function linkHref(typed: string): string | null;
3
3
  /** Why `linkHref` refused what was typed, for the message shown with it. */
4
4
  export declare function linkRefusal(typed: string): 'whitespace' | 'scheme';
5
+ type LinkRuleResult = {
6
+ success: true;
7
+ data: string | null;
8
+ } | {
9
+ success: false;
10
+ error: {
11
+ issues: {
12
+ message: string;
13
+ }[];
14
+ };
15
+ };
16
+ /**
17
+ * The rule for a link field, shaped as a schema (`safeParse`): what was
18
+ * typed becomes the address to save (`linkHref`: `example.com` gains
19
+ * https://), or `null` for a blank box; another scheme (`javascript:`) or
20
+ * a space inside the address is refused with the words to show. LinkCell
21
+ * and the `inPlace.link` preset check with it.
22
+ */
23
+ export declare const linkRule: {
24
+ safeParse(value: unknown): LinkRuleResult;
25
+ };
26
+ /**
27
+ * A link's text when it has no label of its own: the host of a web
28
+ * address (`docs.example.com`), the address of an email link, the path
29
+ * of a link on this site. `href` is one `linkHref` returned.
30
+ */
31
+ export declare function linkHost(href: string): string;
32
+ export {};