@tristan2828/ui-foundation 4.71.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.
@@ -11,6 +11,11 @@ export function messageOf(error) {
11
11
  return error.message;
12
12
  return 'The save failed. Try again.';
13
13
  }
14
+ // The refusal's messages for the value's own fields, or null for none.
15
+ function fieldErrorsOf(config, cause) {
16
+ const found = config?.fieldErrors?.(cause);
17
+ return found && Object.keys(found).length > 0 ? found : undefined;
18
+ }
14
19
  export class EditInPlaceStore {
15
20
  configs = new Map();
16
21
  states = new Map();
@@ -210,17 +215,18 @@ export class EditInPlaceStore {
210
215
  }
211
216
  const parsed = config.schema ? config.schema.safeParse(open.draft) : { success: true, data: open.draft };
212
217
  if (!parsed.success) {
213
- this.set(key, { ...open, error: parsed.error.issues[0]?.message ?? 'Check this value.' });
218
+ const fieldErrors = fieldErrorsOf(config, parsed.error);
219
+ this.set(key, { ...open, error: parsed.error.issues[0]?.message ?? 'Check this value.', fieldErrors });
214
220
  return Promise.resolve(false);
215
221
  }
216
- this.set(key, { ...open, status: 'saving', error: null });
222
+ this.set(key, { ...open, status: 'saving', error: null, fieldErrors: undefined });
217
223
  const save = config
218
224
  .save(parsed.data)
219
225
  .then(() => {
220
226
  this.set(key, CLOSED);
221
227
  return true;
222
228
  }, (error) => {
223
- this.set(key, { ...open, status: 'open', error: messageOf(error) });
229
+ this.set(key, { ...open, status: 'open', error: messageOf(error), fieldErrors: fieldErrorsOf(config, error) });
224
230
  return false;
225
231
  })
226
232
  .finally(() => this.saving.delete(key));
@@ -296,24 +302,25 @@ export class EditInPlaceStore {
296
302
  }
297
303
  const parsed = config.schema ? config.schema.safeParse(state.draft) : { success: true, data: state.draft };
298
304
  if (!parsed.success) {
299
- this.set(key, { ...state, error: parsed.error.issues[0]?.message ?? 'Check this value.' });
305
+ const fieldErrors = fieldErrorsOf(config, parsed.error);
306
+ this.set(key, { ...state, error: parsed.error.issues[0]?.message ?? 'Check this value.', fieldErrors });
300
307
  return Promise.resolve(false);
301
308
  }
302
309
  const sent = state.draft;
303
- this.set(key, { ...state, error: null, autosave: 'saving' });
310
+ this.set(key, { ...state, error: null, fieldErrors: undefined, autosave: 'saving' });
304
311
  const promise = config
305
312
  .save(parsed.data)
306
313
  .then(() => {
307
314
  const now = this.state(key);
308
315
  if (now.status === 'open') {
309
316
  const status = isEqual(now.draft, sent) ? 'saved' : this.queued.has(key) ? 'saving' : undefined;
310
- this.set(key, { ...now, initial: sent, error: null, autosave: status });
317
+ this.set(key, { ...now, initial: sent, error: null, fieldErrors: undefined, autosave: status });
311
318
  }
312
319
  return true;
313
320
  }, (error) => {
314
321
  const now = this.state(key);
315
322
  if (now.status === 'open')
316
- this.set(key, { ...now, error: messageOf(error), autosave: undefined });
323
+ this.set(key, { ...now, error: messageOf(error), fieldErrors: fieldErrorsOf(config, error), autosave: undefined });
317
324
  return false;
318
325
  })
319
326
  .finally(() => this.autosaving.delete(key));
@@ -1,4 +1,5 @@
1
1
  import { type ReactNode } from 'react';
2
+ import type { FieldValues, UseFormReturn } from 'react-hook-form';
2
3
  import type { EditInPlaceStore } from './edit-in-place-store.js';
3
4
  /** What an editable value's control is given. Spread what applies onto the form's own control. */
4
5
  export type EditControlProps<TDraft> = {
@@ -29,6 +30,12 @@ export type EditControlProps<TDraft> = {
29
30
  * Give it to RichTextEditor's `inline` (with `toolbar="floating"`).
30
31
  */
31
32
  inline?: boolean;
33
+ /**
34
+ * A refusal's messages about the value's own fields (`fieldErrors`),
35
+ * keyed by each field's path inside the value (`text`, `effort`). Show
36
+ * each on its field (`aria-invalid`, the message under it).
37
+ */
38
+ errors?: Readonly<Record<string, string>>;
32
39
  };
33
40
  /**
34
41
  * How the value saves, which follows from its control:
@@ -53,7 +60,7 @@ type SafeParseResult<TValue> = {
53
60
  }[];
54
61
  };
55
62
  };
56
- /** A field marked editable. Make one with `editInPlace({...})`. */
63
+ /** A field marked editable. Make one with `editInPlace({...})`, or a ready-made one with `inPlace`. */
57
64
  export type EditInPlace = {
58
65
  kind: EditKind;
59
66
  value: unknown;
@@ -66,6 +73,9 @@ export type EditInPlace = {
66
73
  autosave?: boolean;
67
74
  alwaysEditable?: boolean;
68
75
  inline?: boolean;
76
+ shown?: ReactNode;
77
+ fieldErrors?: (cause: unknown) => Record<string, string> | null;
78
+ errorsOnFields?: boolean;
69
79
  };
70
80
  export type EditInPlaceOptions<TDraft, TValue> = {
71
81
  kind: EditKind;
@@ -115,6 +125,24 @@ export type EditInPlaceOptions<TDraft, TValue> = {
115
125
  * shows the editor's `placeholder`, not the view's "Not set".
116
126
  */
117
127
  inline?: boolean;
128
+ /**
129
+ * How the value reads at rest, for a field that gives no `value` of its
130
+ * own (EntityView's field, EditableValue's children). The `inPlace`
131
+ * presets set it. `null` reads as the field's "Not set".
132
+ */
133
+ shown?: ReactNode;
134
+ /**
135
+ * Which of the value's own fields a refusal is about, for a value made of
136
+ * several (a pair saved as one): given the schema's error (`{ issues }`)
137
+ * or the save's rejection (the AppError), each field's message keyed by
138
+ * its path inside the value. The control gets them as `errors`.
139
+ */
140
+ fieldErrors?: (cause: unknown) => Record<string, string> | null;
141
+ /**
142
+ * The control shows `errors` on its own fields, so a refusal about one
143
+ * of them isn't repeated under the control; one about none still shows there.
144
+ */
145
+ errorsOnFields?: boolean;
118
146
  };
119
147
  /** What a list item's fields are given while it's edited: a control's props, plus where the item is. */
120
148
  export type EditListItemProps<TItem> = EditControlProps<TItem> & {
@@ -122,6 +150,16 @@ export type EditListItemProps<TItem> = EditControlProps<TItem> & {
122
150
  index: number;
123
151
  /** The item being added at the end, not one already in the list. */
124
152
  isNew: boolean;
153
+ /**
154
+ * With the list's `itemForm`: a react-hook-form form holding the list
155
+ * under its `name`, the draft at `index`, so the form's own row works
156
+ * here unchanged (`form.register('checklist.2.text')` for item 2, a
157
+ * `Controller` on `form.control`, its errors in `form.formState.errors`).
158
+ * Every change to it is the item's draft.
159
+ */
160
+ form?: UseFormReturn<FieldValues>;
161
+ /** With `groupBy`: the group the item being added goes in (what its "Add" was under). */
162
+ group?: string;
125
163
  };
126
164
  /** What a list's own `add` is given: how to put new items at the end, saved as the list's other changes are. */
127
165
  export type EditListAddProps<TItem> = {
@@ -162,8 +200,12 @@ export type EditInPlaceListOptions<TItem> = {
162
200
  renderItem: (props: EditListItemProps<TItem>) => ReactNode;
163
201
  /** How the item reads when it isn't being edited. Its own controls (a done box) keep working. */
164
202
  renderShown: (item: TItem, index: number) => ReactNode;
165
- /** A blank item, what "Add" starts from. Not needed with `add`; one or the other is. */
166
- newItem?: () => TItem;
203
+ /**
204
+ * A blank item, what "Add" starts from. Not needed with `add`; one or
205
+ * the other is. With `groupBy`, each group has its own Add, given that
206
+ * group's key (`(room) => ({ text: '', room })`).
207
+ */
208
+ newItem?: (group?: string) => TItem;
167
209
  /**
168
210
  * In place of "Add" and its blank item: what adds items, such as a file
169
211
  * upload or a picker, e.g. a button that uploads, then calls
@@ -191,9 +233,57 @@ export type EditInPlaceListOptions<TItem> = {
191
233
  * Rejects with the AppError; a 422's message shows where the change was made.
192
234
  */
193
235
  save: (change: (current: TItem[]) => TItem[]) => Promise<unknown>;
236
+ /**
237
+ * Shows the items under headings, by one of their fields (a room, a
238
+ * day): each group its own list with its own move buttons (an item moves
239
+ * past the group's next item, never into another group) and its own Add.
240
+ * The list still saves as one, in its own order.
241
+ */
242
+ groupBy?: {
243
+ /** The item's group. */
244
+ key: (item: TItem) => string;
245
+ /** The group's heading. Defaults to its key. */
246
+ label?: (key: string) => string;
247
+ /**
248
+ * The groups in this order, each shown even with no items (so its Add
249
+ * is there). Groups not named follow, in the order their first item comes.
250
+ */
251
+ order?: readonly string[];
252
+ };
253
+ /**
254
+ * Shows only the items this keeps (the view's filter, a pill's value).
255
+ * The others stay in the list as they are: a move passes over them, a
256
+ * save keeps them. A new item that this drops goes out of sight once saved.
257
+ */
258
+ filter?: (item: TItem, index: number) => boolean;
259
+ /**
260
+ * Puts a Duplicate button beside Remove ("Duplicate item 2"), as on the
261
+ * form's ListEditor: the copy this makes of an item goes right after it,
262
+ * saved as a move is. Leave out what a copy mustn't share (a saved id).
263
+ */
264
+ duplicate?: (item: TItem) => TItem;
265
+ /**
266
+ * The list's field name on the record (`checklist`). A refusal from the
267
+ * server about an item's field (a 422 at `checklist.2.text`) is then
268
+ * given to that item's row as `errors.text`. Needed by `itemForm`.
269
+ */
270
+ name?: string;
271
+ /**
272
+ * The row shows `props.errors` on its own fields (the schema's and the
273
+ * server's), so they aren't repeated under the row; a message about no
274
+ * one field still shows there. Implied by `itemForm`.
275
+ */
276
+ errorsOnFields?: boolean;
277
+ /**
278
+ * The row is the form's react-hook-form row: `renderItem` gets `form`, a
279
+ * form of the list under `name`, so the row registers its fields as on
280
+ * the form and shows their errors (the schema's and a 422's, set on it
281
+ * with `setError`) as the form does. No form of the app's own per item.
282
+ */
283
+ itemForm?: boolean;
194
284
  };
195
285
  /** A list marked editable in place. Make one with `editInPlace({ kind: 'list', ... })`. */
196
- export type EditInPlaceList = Omit<EditInPlaceListOptions<unknown>, 'renderItem' | 'renderShown' | 'schema' | 'save' | 'add'> & {
286
+ export type EditInPlaceList = Omit<EditInPlaceListOptions<unknown>, 'renderItem' | 'renderShown' | 'schema' | 'save' | 'add' | 'groupBy' | 'filter' | 'duplicate'> & {
197
287
  add?: (props: EditListAddProps<unknown>) => ReactNode;
198
288
  renderItem: (props: EditListItemProps<unknown>) => ReactNode;
199
289
  renderShown: (item: unknown, index: number) => ReactNode;
@@ -201,6 +291,13 @@ export type EditInPlaceList = Omit<EditInPlaceListOptions<unknown>, 'renderItem'
201
291
  safeParse: (value: unknown) => SafeParseResult<unknown[]>;
202
292
  };
203
293
  save: (change: (current: unknown[]) => unknown[]) => Promise<unknown>;
294
+ groupBy?: {
295
+ key: (item: unknown) => string;
296
+ label?: (key: string) => string;
297
+ order?: readonly string[];
298
+ };
299
+ filter?: (item: unknown, index: number) => boolean;
300
+ duplicate?: (item: unknown) => unknown;
204
301
  };
205
302
  /** Marks a list editable in place: its items added, edited, removed and moved on the view. */
206
303
  export declare function editInPlace<TItem>(options: EditInPlaceListOptions<TItem>): EditInPlaceList;
@@ -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 }));
@@ -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 {};