|
| 1 | +/** |
| 2 | + * ObjectUI |
| 3 | + * Copyright (c) 2024-present ObjectStack Inc. |
| 4 | + * |
| 5 | + * This source code is licensed under the MIT license found in the |
| 6 | + * LICENSE file in the root directory of this source tree. |
| 7 | + */ |
| 8 | + |
| 9 | +/** |
| 10 | + * The small collect-then-save dialog an in-place change opens when it makes |
| 11 | + * other fields required — objectui#4254 (the kanban drop), made shared by |
| 12 | + * objectstack#35956 so a list cell and the record page's inline edit open the |
| 13 | + * same one. The host decides WHEN to open it (`collectRequiredWhenPromptFields` |
| 14 | + * returned fields) and owns the write; this dialog collects the values. |
| 15 | + * |
| 16 | + * ## What it shows |
| 17 | + * |
| 18 | + * The record's name, then the change that set this off as read-only rows |
| 19 | + * (`changes`, e.g. 「销售阶段:赢单」), then one row per field to fill. Save |
| 20 | + * hands the host the typed values, and the host writes them together with the |
| 21 | + * change in ONE write; Cancel writes nothing. |
| 22 | + * |
| 23 | + * ## Chained requirements |
| 24 | + * |
| 25 | + * A value typed here can make one more field required (`moreFields`): it joins |
| 26 | + * the dialog at once, nothing is saved half-way, and Save waits for it too. |
| 27 | + * |
| 28 | + * ## A refusal stays in the dialog |
| 29 | + * |
| 30 | + * When the host's `onSubmit` rejects (someone else changed the record, a rule |
| 31 | + * the prompt could not foresee), the dialog stays open and says why: a reason |
| 32 | + * naming a field shown here is drawn under that field; one naming another |
| 33 | + * field the reader can fill adds that field (`refusalField`); every other |
| 34 | + * reason is listed at the foot. A host whose `onSubmit` settles its own |
| 35 | + * failures (the kanban board's toast and rollback) simply never rejects. |
| 36 | + * |
| 37 | + * ## Not a mini-form |
| 38 | + * |
| 39 | + * Every control here is {@link FieldEditWidget}, i.e. the SAME widget the |
| 40 | + * record form renders for that field type (its own header: "the SAME dedicated |
| 41 | + * widgets the form renders"), which is also what the data grid's inline editor |
| 42 | + * and the detail page's inline edit compose. So a select edits as a select, a |
| 43 | + * date as a date picker, a boolean as a checkbox — without a second set of |
| 44 | + * field-rendering decisions that could drift from the form's. |
| 45 | + * |
| 46 | + * The validation is the same one definition too: `isMissingForRequired` from |
| 47 | + * `@object-ui/core`, the presence contract the form and the server share, so |
| 48 | + * this dialog cannot decide a value is "empty" in a way the server would |
| 49 | + * disagree with (a `false` boolean and a `0` are values, not absences). |
| 50 | + * |
| 51 | + * ## Copy |
| 52 | + * |
| 53 | + * Through `useSafeTranslate` — the per-call `tt(key, fallback)` channel — so a |
| 54 | + * host with no `I18nProvider` mounted (a standalone board, a package's tests, |
| 55 | + * the preview gallery) reads English instead of a raw key. The host may pass |
| 56 | + * its own `title`, `description` and `submitLabel` (the board keeps its |
| 57 | + * 「移动卡片」). |
| 58 | + */ |
| 59 | + |
| 60 | +import React from 'react'; |
| 61 | +import { |
| 62 | + Button, |
| 63 | + Dialog, |
| 64 | + DialogContent, |
| 65 | + DialogDescription, |
| 66 | + DialogFooter, |
| 67 | + DialogHeader, |
| 68 | + DialogTitle, |
| 69 | +} from '@object-ui/components'; |
| 70 | +import { |
| 71 | + useSafeTranslate, |
| 72 | + declaredUserMessage, |
| 73 | + extractFieldErrors, |
| 74 | + extractWriteErrorMessage, |
| 75 | +} from '@object-ui/react'; |
| 76 | +import { isMissingForRequired } from '@object-ui/core'; |
| 77 | +import { FieldEditWidget } from './FieldEditWidget.js'; |
| 78 | +import type { RequiredWhenPromptField } from './requiredWhenPrompt.js'; |
| 79 | + |
| 80 | +/** A prompt field with its display label already resolved by the host. */ |
| 81 | +export interface RequiredFieldsDialogField extends RequiredWhenPromptField { |
| 82 | + label: string; |
| 83 | +} |
| 84 | + |
| 85 | +/** One read-only row naming a value of the change that opened the dialog. */ |
| 86 | +export interface RequiredFieldsDialogChange { |
| 87 | + name: string; |
| 88 | + label: string; |
| 89 | + /** The value as the reader reads it (an option's label, not its code). */ |
| 90 | + value: string; |
| 91 | +} |
| 92 | + |
| 93 | +export interface RequiredFieldsDialogProps { |
| 94 | + open: boolean; |
| 95 | + /** The required-and-empty fields, in the object's declared order. */ |
| 96 | + fields: RequiredFieldsDialogField[]; |
| 97 | + /** Disables the controls while the host's write is in flight. */ |
| 98 | + submitting?: boolean; |
| 99 | + onCancel: () => void; |
| 100 | + /** |
| 101 | + * Called with the typed values once every field shown has one. The host |
| 102 | + * writes them with its change; a rejection keeps the dialog open and shows |
| 103 | + * the reason (see the file header). |
| 104 | + */ |
| 105 | + onSubmit: (values: Record<string, unknown>) => void | Promise<void>; |
| 106 | + /** The record's display name, drawn first. */ |
| 107 | + recordName?: string; |
| 108 | + /** The change that set this off, drawn read-only above the fields. */ |
| 109 | + changes?: RequiredFieldsDialogChange[]; |
| 110 | + /** |
| 111 | + * The fields the typed values make required in turn (chained requirements), |
| 112 | + * asked on every change of the values; shown after `fields`, de-duplicated. |
| 113 | + */ |
| 114 | + moreFields?: (values: Record<string, unknown>) => RequiredFieldsDialogField[]; |
| 115 | + /** |
| 116 | + * A field a refusal names that is not shown yet: the row to add for it, or |
| 117 | + * `null` when the reader cannot fill it here (its reason is then listed at |
| 118 | + * the foot). |
| 119 | + */ |
| 120 | + refusalField?: (name: string) => RequiredFieldsDialogField | null; |
| 121 | + /** The label of a field a foot line names; `undefined` reads the reason alone. */ |
| 122 | + labelOf?: (name: string) => string | undefined; |
| 123 | + title?: string; |
| 124 | + description?: string; |
| 125 | + submitLabel?: string; |
| 126 | +} |
| 127 | + |
| 128 | +/** The reasons a rejected submit carries: per field, and the rest. */ |
| 129 | +function refusalOf(err: unknown): { entries: Array<{ field: string; message: string }>; fallback: string | null } { |
| 130 | + const entries = (extractFieldErrors(err) ?? []) |
| 131 | + .filter((e) => typeof e.message === 'string' && e.message.length > 0) |
| 132 | + .map((e) => ({ field: e.field, message: e.message as string })); |
| 133 | + return { entries, fallback: entries.length > 0 ? null : declaredUserMessage(err) ?? extractWriteErrorMessage(err) ?? null }; |
| 134 | +} |
| 135 | + |
| 136 | +export function RequiredFieldsDialog({ |
| 137 | + open, |
| 138 | + fields, |
| 139 | + submitting, |
| 140 | + onCancel, |
| 141 | + onSubmit, |
| 142 | + recordName, |
| 143 | + changes, |
| 144 | + moreFields, |
| 145 | + refusalField, |
| 146 | + labelOf, |
| 147 | + title, |
| 148 | + description, |
| 149 | + submitLabel, |
| 150 | +}: RequiredFieldsDialogProps): React.ReactElement { |
| 151 | + const tt = useSafeTranslate(); |
| 152 | + // Each change is its own collection, and that is enforced by MOUNTING rather |
| 153 | + // than by a reset effect: hosts render this component only while a change is |
| 154 | + // pending, so cancelling or saving unmounts it and the next change starts |
| 155 | + // from empty state. A `useEffect` re-seed would be both redundant and a |
| 156 | + // cascading-render hazard the lint rule correctly flags. |
| 157 | + const [values, setValues] = React.useState<Record<string, unknown>>({}); |
| 158 | + // True only after a submit attempt, so the dialog opens clean rather than |
| 159 | + // shouting "Required" at fields the user has not reached yet. |
| 160 | + const [showErrors, setShowErrors] = React.useState(false); |
| 161 | + // The last refusal: per-field reasons, the fields it added, the foot lines. |
| 162 | + const [serverErrors, setServerErrors] = React.useState<Record<string, string>>({}); |
| 163 | + const [addedFields, setAddedFields] = React.useState<RequiredFieldsDialogField[]>([]); |
| 164 | + const [footLines, setFootLines] = React.useState<string[]>([]); |
| 165 | + const [sending, setSending] = React.useState(false); |
| 166 | + const busy = !!submitting || sending; |
| 167 | + |
| 168 | + const shown: RequiredFieldsDialogField[] = []; |
| 169 | + const seen = new Set<string>(); |
| 170 | + for (const f of [...fields, ...(moreFields?.(values) ?? []), ...addedFields]) { |
| 171 | + if (seen.has(f.name)) continue; |
| 172 | + seen.add(f.name); |
| 173 | + shown.push(f); |
| 174 | + } |
| 175 | + const missing = shown.filter((f) => isMissingForRequired(values[f.name])); |
| 176 | + |
| 177 | + const presentRefusal = (err: unknown) => { |
| 178 | + const { entries, fallback } = refusalOf(err); |
| 179 | + const byField: Record<string, string> = {}; |
| 180 | + const added: RequiredFieldsDialogField[] = []; |
| 181 | + const lines: string[] = []; |
| 182 | + for (const { field, message } of entries) { |
| 183 | + if (seen.has(field) || added.some((f) => f.name === field)) { |
| 184 | + if (!(field in byField)) byField[field] = message; |
| 185 | + continue; |
| 186 | + } |
| 187 | + const row = refusalField?.(field) ?? null; |
| 188 | + if (row) { |
| 189 | + added.push(row); |
| 190 | + byField[field] = message; |
| 191 | + continue; |
| 192 | + } |
| 193 | + const label = labelOf?.(field); |
| 194 | + const line = label ? `${label}: ${message}` : message; |
| 195 | + if (!lines.includes(line)) lines.push(line); |
| 196 | + } |
| 197 | + if (fallback) lines.push(fallback); |
| 198 | + if (entries.length === 0 && !fallback) lines.push(tt('table.saveFailed', 'Save failed')); |
| 199 | + setServerErrors(byField); |
| 200 | + setAddedFields((prev) => [...prev, ...added.filter((f) => !prev.some((p) => p.name === f.name))]); |
| 201 | + setFootLines(lines); |
| 202 | + }; |
| 203 | + |
| 204 | + const handleSubmit = async () => { |
| 205 | + if (busy) return; |
| 206 | + if (missing.length > 0) { |
| 207 | + setShowErrors(true); |
| 208 | + return; |
| 209 | + } |
| 210 | + // Only the fields shown are sent: a value typed for a chained field that |
| 211 | + // a later edit made unnecessary again stays out of the write. |
| 212 | + const sent = Object.fromEntries(shown.map((f) => [f.name, values[f.name]])); |
| 213 | + setFootLines([]); |
| 214 | + setSending(true); |
| 215 | + try { |
| 216 | + await onSubmit(sent); |
| 217 | + } catch (err) { |
| 218 | + presentRefusal(err); |
| 219 | + } finally { |
| 220 | + setSending(false); |
| 221 | + } |
| 222 | + }; |
| 223 | + |
| 224 | + return ( |
| 225 | + <Dialog open={open} onOpenChange={(next) => { if (!next && !busy) onCancel(); }}> |
| 226 | + <DialogContent |
| 227 | + className="sm:max-w-md max-h-[90dvh] overflow-y-auto" |
| 228 | + data-testid="required-fields-dialog" |
| 229 | + > |
| 230 | + <DialogHeader> |
| 231 | + <DialogTitle> |
| 232 | + {title ?? tt('fields.requiredPromptTitle', 'Complete required fields')} |
| 233 | + </DialogTitle> |
| 234 | + <DialogDescription> |
| 235 | + {description ?? tt( |
| 236 | + 'fields.requiredPromptDescription', |
| 237 | + 'This change makes the fields below required. Fill them in to save it.', |
| 238 | + )} |
| 239 | + </DialogDescription> |
| 240 | + </DialogHeader> |
| 241 | + |
| 242 | + {(recordName || (changes && changes.length > 0)) && ( |
| 243 | + <div className="flex flex-col gap-2 rounded-md border bg-muted/40 px-3 py-2" data-required-fields-change=""> |
| 244 | + {recordName && ( |
| 245 | + <p className="min-w-0 break-words text-sm font-semibold">{recordName}</p> |
| 246 | + )} |
| 247 | + {changes && changes.length > 0 && ( |
| 248 | + <dl className="flex flex-col gap-1 text-sm"> |
| 249 | + {changes.map((c) => ( |
| 250 | + <div key={c.name} className="flex min-w-0 flex-wrap gap-x-1.5" data-required-fields-change-row={c.name}> |
| 251 | + <dt className="text-muted-foreground">{c.label}:</dt> |
| 252 | + <dd className="min-w-0 break-words font-medium">{c.value}</dd> |
| 253 | + </div> |
| 254 | + ))} |
| 255 | + </dl> |
| 256 | + )} |
| 257 | + </div> |
| 258 | + )} |
| 259 | + |
| 260 | + <div className="flex flex-col gap-4 py-2"> |
| 261 | + {shown.map((f) => { |
| 262 | + const isMissing = isMissingForRequired(values[f.name]); |
| 263 | + const message = serverErrors[f.name] |
| 264 | + ?? (showErrors && isMissing ? tt('common.required', 'Required') : undefined); |
| 265 | + return ( |
| 266 | + // A wrapping `label` gives the control its accessible name |
| 267 | + // implicitly. `FieldEditWidget` does take an `id` (objectui#7009 |
| 268 | + // put it in `DOM_PASS_THROUGH_KEYS`), but this dialog renders |
| 269 | + // whatever field types the change made required, and several of |
| 270 | + // them resolve to COMPOSITE controls with no single labelable |
| 271 | + // element for a `htmlFor` to point at — `RadioField` renders |
| 272 | + // `<div role="radiogroup">`, `CheckboxesField` `<div |
| 273 | + // role="group">`, `AddressField` a set of sibling inputs. One |
| 274 | + // wrapping `label` covers every type uniformly and mints no ids. |
| 275 | + <label key={f.name} className="flex flex-col gap-1.5" data-required-fields-field={f.name}> |
| 276 | + <span className="text-sm font-medium"> |
| 277 | + {f.label} |
| 278 | + <span className="text-destructive ml-0.5" aria-hidden="true">*</span> |
| 279 | + </span> |
| 280 | + <FieldEditWidget |
| 281 | + field={f.def as never} |
| 282 | + value={values[f.name]} |
| 283 | + onChange={(v: unknown) => { |
| 284 | + setValues((prev) => ({ ...prev, [f.name]: v })); |
| 285 | + // A server reason is about the value it was given; a new |
| 286 | + // value retires it. |
| 287 | + setServerErrors((prev) => { |
| 288 | + if (!(f.name in prev)) return prev; |
| 289 | + const next = { ...prev }; |
| 290 | + delete next[f.name]; |
| 291 | + return next; |
| 292 | + }); |
| 293 | + }} |
| 294 | + readonly={busy} |
| 295 | + // A widget reads `error` ONLY to drive `aria-invalid` (the |
| 296 | + // #3222 contract — the message TEXT stays with the host), so |
| 297 | + // the same string as the visible hint below cannot |
| 298 | + // double-display (objectui#7008). |
| 299 | + error={message} |
| 300 | + /> |
| 301 | + {message && ( |
| 302 | + <span className="text-xs text-destructive" data-required-fields-error={f.name}> |
| 303 | + {message} |
| 304 | + </span> |
| 305 | + )} |
| 306 | + </label> |
| 307 | + ); |
| 308 | + })} |
| 309 | + </div> |
| 310 | + |
| 311 | + {footLines.length > 0 && ( |
| 312 | + <div role="alert" className="flex flex-col gap-1 text-sm text-destructive" data-required-fields-refusal=""> |
| 313 | + {footLines.map((line) => <p key={line} className="break-words">{line}</p>)} |
| 314 | + </div> |
| 315 | + )} |
| 316 | + |
| 317 | + <DialogFooter> |
| 318 | + <Button variant="outline" onClick={onCancel} disabled={busy}> |
| 319 | + {tt('common.cancel', 'Cancel')} |
| 320 | + </Button> |
| 321 | + <Button onClick={() => { void handleSubmit(); }} disabled={busy}> |
| 322 | + {submitLabel ?? tt('common.save', 'Save')} |
| 323 | + </Button> |
| 324 | + </DialogFooter> |
| 325 | + </DialogContent> |
| 326 | + </Dialog> |
| 327 | + ); |
| 328 | +} |
0 commit comments