@asteby/metacore-runtime-react 53.10.0 → 53.10.1
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.
- package/CHANGELOG.md +6 -0
- package/dist/action-modal-dispatcher.d.ts +4 -0
- package/dist/action-modal-dispatcher.d.ts.map +1 -1
- package/dist/action-modal-dispatcher.js +103 -10
- package/dist/model-action-toolbar.d.ts.map +1 -1
- package/dist/model-action-toolbar.js +4 -1
- package/package.json +1 -1
- package/src/__tests__/action-modal-field-errors.test.tsx +142 -0
- package/src/__tests__/connector-blocks.test.tsx +12 -7
- package/src/action-modal-dispatcher.tsx +109 -11
- package/src/model-action-toolbar.tsx +5 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# @asteby/metacore-runtime-react
|
|
2
2
|
|
|
3
|
+
## 53.10.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 4139fa3: Diálogo de acciones con `fields`: un envío fallido ya no borra lo escrito (el formulario se siembra una vez por apertura, no cuando la lista vuelve a pintar con otro `record={{}}`/`action`), y el campo que nombra el servidor (`errors` o `error.field`) queda en rojo con `aria-invalid`, mensaje debajo, foco y scroll al primero. Contrato en `docs/action-errors.md`.
|
|
8
|
+
|
|
3
9
|
## 53.10.0
|
|
4
10
|
|
|
5
11
|
### Minor Changes
|
|
@@ -89,6 +89,10 @@ export declare const FEDERATED_ACTION_MODAL_TIMEOUT_MS = 20000;
|
|
|
89
89
|
* other failure (500, network) -> the server's own message and cause. Unlike
|
|
90
90
|
* the toast it stays on screen until the next attempt. */
|
|
91
91
|
export declare function actionErrorBannerMessage(err: unknown, fields: readonly ActionFieldDef[] | undefined, t: Translate, language?: string): string;
|
|
92
|
+
/** Focus and scroll into view the first invalid control inside `root` (DOM
|
|
93
|
+
* order = field order): the input/select trigger flagged `aria-invalid`, else
|
|
94
|
+
* the first focusable element of the cell holding a field error message. */
|
|
95
|
+
export declare function focusFirstInvalid(root: HTMLElement | null): HTMLElement | null;
|
|
92
96
|
/** Context a declared field default is resolved against. */
|
|
93
97
|
export interface FieldDefaultContext {
|
|
94
98
|
/** Org IANA timezone: `$today` is the org's day, not the browser's or UTC's. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"action-modal-dispatcher.d.ts","sourceRoot":"","sources":["../src/action-modal-dispatcher.tsx"],"names":[],"mappings":"AAmDA,OAAO,KAAK,EAAE,SAAS,
|
|
1
|
+
{"version":3,"file":"action-modal-dispatcher.d.ts","sourceRoot":"","sources":["../src/action-modal-dispatcher.tsx"],"names":[],"mappings":"AAmDA,OAAO,KAAK,EAAE,SAAS,EAAc,MAAM,gBAAgB,CAAA;AA+B3D,OAAO,KAAK,EAAE,cAAc,EAAmC,MAAM,SAAS,CAAA;AAE9E,OAAO,EACH,KAAK,cAAc,EACnB,KAAK,gBAAgB,EAKxB,MAAM,sBAAsB,CAAA;AAQ7B,YAAY,EAAE,cAAc,EAAE,gBAAgB,EAAE,CAAA;AAiBhD,MAAM,WAAW,WAAW;IACxB,kBAAkB,EAAE,MAAM,CAAA;IAC1B,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IAC5B,SAAS,CAAC,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,EAAE,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAA;IAC1D;;;;;OAKG;IACH,IAAI,CAAC,EAAE,MAAM,EAAE,CAAA;IACf;;;;;;;;OAQG;IACH,SAAS,CAAC,EAAE,MAAM,CAAA;CACrB;AAED,wBAAgB,aAAa,CAAC,CAAC,EAAE,OAAO,GAAG,CAAC,IAAI,WAAW,CAM1D;AAsBD,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,cAAc,GAAG,cAAc,CAStE;AAGD,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,WAAW,EAAE,MAAM,EAA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AAqB;IACrB,GAAG,CAAC,EAAE,IAAI,CAAA;CACb;AAID;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,cAAc,EAAE,GAAG,GAAE,mBAAwB,GAAG,OAAO,CASjG;AAKD,wBAAgB,kBAAkB,CAC9B,MAAM,EAAE,cAAc,EAAE,EACxB,MAAM,EAAE,GAAG,EACX,KAAK,CAAC,EAAE,MAAM,EACd,GAAG,GAAE,mBAAwB,GAC9B,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAoBrB;AA8PD,wBAAgB,oBAAoB,CAChC,KAAK,EAAE,cAAc,EACrB,KAAK,EAAE,GAAG,EACV,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAC7B,OAAO,wBAAwB,EAAE,cAAc,GAAG,SAAS,CAuB7D;AAED,oGAAoG;AACpG,wBAAgB,WAAW,CACvB,KAAK,EAAE,cAAc,EACrB,KAAK,EAAE,GAAG,EACV,QAAQ,EAAE,CAAC,KAAK,EAAE,GAAG,KAAK,IAAI,EAK9B,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAChC,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAC5B,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,+BAiFvC"}
|
|
@@ -575,11 +575,38 @@ function RecordPreview({ model, record }) {
|
|
|
575
575
|
function humanizeKey(k) {
|
|
576
576
|
return k.replace(/[._-]+/g, ' ').replace(/\b\w/g, c => c.toUpperCase());
|
|
577
577
|
}
|
|
578
|
+
/**
|
|
579
|
+
* A failed action that names ONE input without an `errors` map — the error
|
|
580
|
+
* contract a handler may answer with (documented in docs/action-errors.md):
|
|
581
|
+
* { success:false, error:{ code, message, message_key, params, field: "<field key>" } }
|
|
582
|
+
* (also `field` at the top level, as hosts that flatten the guest error send
|
|
583
|
+
* it). The field must be one of the dialog's own field keys — a human label in
|
|
584
|
+
* `params.field` never matches — and its message is the server's own (already
|
|
585
|
+
* localized by the host) message.
|
|
586
|
+
*/
|
|
587
|
+
function singleFieldError(err, fields, t) {
|
|
588
|
+
if (!fields?.length)
|
|
589
|
+
return undefined;
|
|
590
|
+
const data = (err?.response?.data ?? err);
|
|
591
|
+
if (!data || typeof data !== 'object')
|
|
592
|
+
return undefined;
|
|
593
|
+
const inner = data.error && typeof data.error === 'object' ? data.error : undefined;
|
|
594
|
+
const candidates = [data.field, inner?.field, data.params?.field_key, inner?.params?.field_key];
|
|
595
|
+
const keys = new Set(fields.map((f) => f.key));
|
|
596
|
+
const key = candidates.find((c) => typeof c === 'string' && keys.has(c));
|
|
597
|
+
if (!key)
|
|
598
|
+
return undefined;
|
|
599
|
+
const raw = (typeof data.message === 'string' && data.message.trim()) ||
|
|
600
|
+
(typeof inner?.message === 'string' && inner.message.trim()) ||
|
|
601
|
+
'';
|
|
602
|
+
const message = raw ? t(raw, { defaultValue: raw, ...(data.params ?? inner?.params ?? {}) }) : '';
|
|
603
|
+
return { [key]: [message ? { message } : { code: 'invalid' }] };
|
|
604
|
+
}
|
|
578
605
|
/** Localize a failed action submit's per-field `errors` (422 map or `{errors}`
|
|
579
606
|
* body) into `{ [fieldKey]: localizedMessage }`, using each field's label.
|
|
580
607
|
* Returns undefined when there is no usable per-field map. */
|
|
581
608
|
function localizeActionFieldErrors(err, fields, t, language) {
|
|
582
|
-
const map = extractFieldErrors(err);
|
|
609
|
+
const map = extractFieldErrors(err) ?? singleFieldError(err, fields, t);
|
|
583
610
|
if (!map)
|
|
584
611
|
return undefined;
|
|
585
612
|
const labels = {};
|
|
@@ -682,6 +709,45 @@ function ConfirmActionDialog({ open, onOpenChange, action, model, record, endpoi
|
|
|
682
709
|
}
|
|
683
710
|
return (_jsxs(_Fragment, { children: [reasonPrompt.dialog, _jsx(AlertDialog, { open: open, onOpenChange: onOpenChange, children: _jsxs(AlertDialogContent, { children: [_jsxs(AlertDialogHeader, { children: [_jsxs(AlertDialogTitle, { className: "flex items-center gap-2", children: [_jsx(DynamicIcon, { name: action.icon, className: "h-5 w-5" }), label] }), _jsx(AlertDialogDescription, { children: action.confirmMessage || `${label}?` })] }), record ? _jsx(RecordPreview, { model: model, record: record }) : null, _jsx(FormErrorBanner, { message: formError }), _jsxs(AlertDialogFooter, { children: [_jsx(AlertDialogCancel, { disabled: executing, children: t('common.cancel') }), _jsxs(AlertDialogAction, { onClick: (e) => { e.preventDefault(); execute(); }, disabled: executing, style: action.color ? { backgroundColor: action.color } : undefined, children: [executing ? _jsx(Loader2, { className: "mr-2 h-4 w-4 animate-spin" }) : _jsx(DynamicIcon, { name: action.icon, className: "mr-2 h-4 w-4" }), label] })] })] }) })] }));
|
|
684
711
|
}
|
|
712
|
+
/**
|
|
713
|
+
* Identity of one "opening" of an action dialog: open + action + record id +
|
|
714
|
+
* model, plus a counter bumped on every closed→open transition. Re-renders that
|
|
715
|
+
* only hand a NEW OBJECT for the same record (`record={{}}`, a refetched row)
|
|
716
|
+
* keep the same key, so the form is not re-seeded under the person's hands.
|
|
717
|
+
* Empty string while closed.
|
|
718
|
+
*/
|
|
719
|
+
function useSeedKey(open, actionKey, record, model) {
|
|
720
|
+
const opening = useRef(0);
|
|
721
|
+
const wasOpen = useRef(false);
|
|
722
|
+
if (open && !wasOpen.current)
|
|
723
|
+
opening.current += 1;
|
|
724
|
+
wasOpen.current = open;
|
|
725
|
+
if (!open)
|
|
726
|
+
return '';
|
|
727
|
+
const rid = record?.id == null ? '' : String(record.id);
|
|
728
|
+
return `${opening.current}|${model}|${actionKey ?? ''}|${rid}`;
|
|
729
|
+
}
|
|
730
|
+
/** Focus and scroll into view the first invalid control inside `root` (DOM
|
|
731
|
+
* order = field order): the input/select trigger flagged `aria-invalid`, else
|
|
732
|
+
* the first focusable element of the cell holding a field error message. */
|
|
733
|
+
export function focusFirstInvalid(root) {
|
|
734
|
+
if (!root)
|
|
735
|
+
return null;
|
|
736
|
+
const msg = root.querySelector('[data-field-error]');
|
|
737
|
+
const target = root.querySelector('[aria-invalid="true"]') ??
|
|
738
|
+
msg?.parentElement?.querySelector('input, textarea, button, [tabindex]') ??
|
|
739
|
+
null;
|
|
740
|
+
if (!target)
|
|
741
|
+
return null;
|
|
742
|
+
try {
|
|
743
|
+
target.scrollIntoView?.({ block: 'center', behavior: 'smooth' });
|
|
744
|
+
}
|
|
745
|
+
catch {
|
|
746
|
+
/* older engines: scrollIntoView without options */
|
|
747
|
+
}
|
|
748
|
+
target.focus?.({ preventScroll: true });
|
|
749
|
+
return target;
|
|
750
|
+
}
|
|
685
751
|
function GenericActionModal({ open, onOpenChange, action, model, record, endpoint, onSuccess }) {
|
|
686
752
|
const { t, i18n } = useTranslation();
|
|
687
753
|
// Addon-contributed labels (action + fields) are i18n keys whose locale
|
|
@@ -729,13 +795,24 @@ function GenericActionModal({ open, onOpenChange, action, model, record, endpoin
|
|
|
729
795
|
cancelled = true;
|
|
730
796
|
};
|
|
731
797
|
}, [open, model, recordId, api]);
|
|
798
|
+
// Seed the form ONCE per opening (and again only when the dialog switches to
|
|
799
|
+
// another action or record). Never on a mere re-render: callers pass
|
|
800
|
+
// `record={{}}` / a refetched row / a re-derived `action` with a new identity
|
|
801
|
+
// on every render of the list, and re-seeding on identity wiped what the
|
|
802
|
+
// person typed right after a failed submit (ProtekAuto: «Configurar origen de
|
|
803
|
+
// envío» lost contact, company, phone… on the second attempt). What was
|
|
804
|
+
// typed survives a failure; it is cleared only by closing or by success.
|
|
805
|
+
const seedKey = useSeedKey(open, action.key, record, model);
|
|
806
|
+
const seedRef = useRef({ fields: action.fields, record, model, orgTimeZone });
|
|
807
|
+
seedRef.current = { fields: action.fields, record, model, orgTimeZone };
|
|
732
808
|
useEffect(() => {
|
|
733
|
-
|
|
734
|
-
|
|
809
|
+
const cur = seedRef.current;
|
|
810
|
+
if (seedKey && cur.fields) {
|
|
811
|
+
setFormData(buildFieldDefaults(cur.fields, cur.record, cur.model, { timeZone: cur.orgTimeZone }));
|
|
735
812
|
setFieldErrors({});
|
|
736
813
|
setFormError(undefined);
|
|
737
814
|
}
|
|
738
|
-
}, [
|
|
815
|
+
}, [seedKey]);
|
|
739
816
|
// Lines the list row does not carry: load them from the declared relation
|
|
740
817
|
// (see prefillRelationRequests) and seed the line-items grid.
|
|
741
818
|
useEffect(() => {
|
|
@@ -818,6 +895,14 @@ function GenericActionModal({ open, onOpenChange, action, model, record, endpoin
|
|
|
818
895
|
setFormData((prev) => ({ ...prev, [key]: value }));
|
|
819
896
|
setFieldErrors((prev) => clearFieldErrorTree(prev, key));
|
|
820
897
|
};
|
|
898
|
+
// Focus + scroll to the first invalid input after a failed submit (client
|
|
899
|
+
// validation or server `errors`), so the person lands on what to fix.
|
|
900
|
+
const bodyRef = useRef(null);
|
|
901
|
+
const [focusTick, setFocusTick] = useState(0);
|
|
902
|
+
useEffect(() => {
|
|
903
|
+
if (focusTick > 0)
|
|
904
|
+
focusFirstInvalid(bodyRef.current);
|
|
905
|
+
}, [focusTick]);
|
|
821
906
|
const lang = i18n.language;
|
|
822
907
|
const handleActionError = (err) => {
|
|
823
908
|
setFormError(actionErrorBannerMessage(err, action.fields, t, lang));
|
|
@@ -832,6 +917,7 @@ function GenericActionModal({ open, onOpenChange, action, model, record, endpoin
|
|
|
832
917
|
labels[path] = labelForValidationPath(path, action.fields, t);
|
|
833
918
|
}
|
|
834
919
|
setFieldErrors(withPathLabels);
|
|
920
|
+
setFocusTick((n) => n + 1);
|
|
835
921
|
toast.error(t('validation.failed', { defaultValue: validationCatalog(lang).failed }), {
|
|
836
922
|
description: formatFieldErrorsDescription(withPathLabels, action.fields, t),
|
|
837
923
|
});
|
|
@@ -851,6 +937,7 @@ function GenericActionModal({ open, onOpenChange, action, model, record, endpoin
|
|
|
851
937
|
}
|
|
852
938
|
const next = localizeFieldErrorMap(bag, t, { labels, language: lang });
|
|
853
939
|
setFieldErrors(next);
|
|
940
|
+
setFocusTick((n) => n + 1);
|
|
854
941
|
toast.error(t('validation.failed', { defaultValue: validationCatalog(lang).failed }), {
|
|
855
942
|
description: formatFieldErrorsDescription(next, action.fields, t),
|
|
856
943
|
});
|
|
@@ -934,11 +1021,11 @@ function GenericActionModal({ open, onOpenChange, action, model, record, endpoin
|
|
|
934
1021
|
onSuccess();
|
|
935
1022
|
} }));
|
|
936
1023
|
}
|
|
937
|
-
return (_jsx(Dialog, { open: open, onOpenChange: onOpenChange, children: _jsxs(DialogContent, { className: 'flex max-h-[90dvh] flex-col overflow-hidden ' + (widthPx ? '' : 'sm:max-w-xl'), style: { maxHeight: '90dvh', ...(widthPx ? { maxWidth: widthPx, width: '95vw' } : {}) }, children: [_jsxs(DialogHeader, { className: "shrink-0", children: [_jsxs(DialogTitle, { className: "flex items-center gap-2", children: [_jsx(DynamicIcon, { name: action.icon, className: "h-5 w-5" }), tl(action.label)] }), action.confirmMessage && _jsx(DialogDescription, { children: tl(action.confirmMessage) })] }), _jsxs("div", { className: "-mx-1 min-h-0 flex-1 overflow-y-auto px-1 py-4", children: [_jsx(FormErrorBanner, { message: formError, className: "mb-3" }), _jsxs(FieldGrid, { children: [action.fields?.map((field) => {
|
|
1024
|
+
return (_jsx(Dialog, { open: open, onOpenChange: onOpenChange, children: _jsxs(DialogContent, { className: 'flex max-h-[90dvh] flex-col overflow-hidden ' + (widthPx ? '' : 'sm:max-w-xl'), style: { maxHeight: '90dvh', ...(widthPx ? { maxWidth: widthPx, width: '95vw' } : {}) }, children: [_jsxs(DialogHeader, { className: "shrink-0", children: [_jsxs(DialogTitle, { className: "flex items-center gap-2", children: [_jsx(DynamicIcon, { name: action.icon, className: "h-5 w-5" }), tl(action.label)] }), action.confirmMessage && _jsx(DialogDescription, { children: tl(action.confirmMessage) })] }), _jsxs("div", { ref: bodyRef, className: "-mx-1 min-h-0 flex-1 overflow-y-auto px-1 py-4", children: [_jsx(FormErrorBanner, { message: formError, className: "mb-3" }), _jsxs(FieldGrid, { children: [action.fields?.map((field) => {
|
|
938
1025
|
const fullWidth = isLineItemsField(field) ||
|
|
939
1026
|
resolveWidget(field) === 'textarea' ||
|
|
940
1027
|
resolveWidget(field) === 'richtext';
|
|
941
|
-
return (_jsxs(FieldCell, { fullWidth: fullWidth, children: [_jsx(FieldLabel, { htmlFor: field.key, required: field.required, children: tl(field.label) }), renderField(field, formData[field.key], (v) => updateField(field.key, v), formData, record, fieldErrors), fieldErrors[field.key] && (_jsx("p", { className: "text-destructive text-xs mt-1", children: fieldErrors[field.key] }))] }, field.key));
|
|
1028
|
+
return (_jsxs(FieldCell, { fullWidth: fullWidth, children: [_jsx(FieldLabel, { htmlFor: field.key, required: field.required, children: tl(field.label) }), renderField(field, formData[field.key], (v) => updateField(field.key, v), formData, record, fieldErrors), fieldErrors[field.key] && (_jsx("p", { id: `${field.key}-error`, className: "text-destructive text-xs mt-1", "data-field-error": field.key, children: fieldErrors[field.key] }))] }, field.key));
|
|
942
1029
|
}), embedRelations && relations.length > 0 && (_jsx(FieldCell, { fullWidth: true, children: _jsx(DynamicRelations, { record: record, relations: relations, lineSubtable: true, embedOnly: true }) }))] })] }), _jsxs(DialogFooter, { className: "shrink-0", children: [_jsx(Button, { variant: "outline", onClick: () => onOpenChange(false), disabled: executing, children: t('common.cancel') }), _jsxs(Button, { onClick: execute, disabled: executing, style: action.color ? { backgroundColor: action.color, color: 'white' } : undefined, children: [executing ? _jsx(Loader2, { className: "mr-2 h-4 w-4 animate-spin" }) : _jsx(DynamicIcon, { name: action.icon, className: "mr-2 h-4 w-4" }), tl(action.label)] })] }), reasonPrompt.dialog] }) }));
|
|
943
1030
|
}
|
|
944
1031
|
const DATE_FIELD_TYPES = new Set(['date', 'datetime', 'timestamp', 'timestamptz']);
|
|
@@ -1018,14 +1105,20 @@ function WizardActionModal({ open, onOpenChange, action, model, record, endpoint
|
|
|
1018
1105
|
const [stamp, setStamp] = useState();
|
|
1019
1106
|
// Reset to the first step and seed defaults for EVERY step's fields whenever
|
|
1020
1107
|
// the modal (re)opens, so accumulated values from a prior run don't leak.
|
|
1108
|
+
// Keyed like GenericActionModal: a re-render with a new `record`/`action`
|
|
1109
|
+
// identity must not wipe what was typed (only a new opening does).
|
|
1110
|
+
const seedKey = useSeedKey(open, action.key, record, model);
|
|
1111
|
+
const seedRef = useRef({ steps, record, model, orgTimeZone });
|
|
1112
|
+
seedRef.current = { steps, record, model, orgTimeZone };
|
|
1021
1113
|
useEffect(() => {
|
|
1022
|
-
if (!
|
|
1114
|
+
if (!seedKey)
|
|
1023
1115
|
return;
|
|
1024
|
-
const
|
|
1025
|
-
|
|
1116
|
+
const cur = seedRef.current;
|
|
1117
|
+
const allFields = cur.steps.flatMap((s) => s.fields ?? []);
|
|
1118
|
+
setFormData(buildFieldDefaults(allFields, cur.record, cur.model, { timeZone: cur.orgTimeZone }));
|
|
1026
1119
|
setStepIndex(0);
|
|
1027
1120
|
setFormError(undefined);
|
|
1028
|
-
}, [
|
|
1121
|
+
}, [seedKey]);
|
|
1029
1122
|
const updateField = (key, value) => setFormData((prev) => ({ ...prev, [key]: value }));
|
|
1030
1123
|
const step = steps[stepIndex];
|
|
1031
1124
|
const isLast = stepIndex === steps.length - 1;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model-action-toolbar.d.ts","sourceRoot":"","sources":["../src/model-action-toolbar.tsx"],"names":[],"mappings":"AAiCA,OAAO,KAAK,EAAE,gBAAgB,EAAgD,MAAM,SAAS,CAAA;AAG7F,MAAM,MAAM,eAAe,GAAG,KAAK,GAAG,OAAO,GAAG,QAAQ,CAAA;AAExD,MAAM,WAAW,uBAAuB;IACpC,oEAAoE;IACpE,KAAK,EAAE,MAAM,CAAA;IACb,8EAA8E;IAC9E,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB;;;;OAIG;IACH,OAAO,CAAC,EAAE,gBAAgB,EAAE,CAAA;IAC5B,qEAAqE;IACrE,UAAU,CAAC,EAAE,eAAe,EAAE,CAAA;IAC9B,qDAAqD;IACrD,QAAQ,CAAC,EAAE,MAAM,IAAI,CAA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B,QAAQ,EACR,SAAS,EACT,cAAc,EACd,gBAAgB,GACnB,EAAE,uBAAuB,sCA+FzB"}
|
|
@@ -29,6 +29,9 @@ import { useCan, modelCapability } from './permissions-context';
|
|
|
29
29
|
import { RequiresAddonDialog, RequiresAddonLock, resolveRequiresAddon, useRequiresAddonLabel, } from './requires-addon';
|
|
30
30
|
import { resolveListPrimaryAction } from './list-primary-action';
|
|
31
31
|
const DEFAULT_PLACEMENTS = ['table', 'create'];
|
|
32
|
+
/** Table/create actions act on no record: one stable empty object, not a new
|
|
33
|
+
* `{}` per render (the dialog keys its form on the opening, not on identity). */
|
|
34
|
+
const NO_RECORD = {};
|
|
32
35
|
/**
|
|
33
36
|
* Last-resort label when `t(key)` has no translation yet: never flash the full
|
|
34
37
|
* dotted key in a primary CTA. Prefers the action/field segment over a trailing
|
|
@@ -126,7 +129,7 @@ export function ModelActionToolbar({ model, endpoint, actions, placements = DEFA
|
|
|
126
129
|
}) }), active && (_jsx(ActionModalDispatcher, { open: !!active, onOpenChange: (open) => {
|
|
127
130
|
if (!open)
|
|
128
131
|
setActive(null);
|
|
129
|
-
}, action: active, model: model, record:
|
|
132
|
+
}, action: active, model: model, record: NO_RECORD, endpoint: dataEndpoint, onSuccess: () => {
|
|
130
133
|
setActive(null);
|
|
131
134
|
onChange?.();
|
|
132
135
|
} })), _jsx(RequiresAddonDialog, { requirement: missingAddon, onOpenChange: (open) => {
|
package/package.json
CHANGED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
// @vitest-environment happy-dom
|
|
2
|
+
//
|
|
3
|
+
// ProtekAuto, «Configurar origen de envío» (warehouse 0.18.0): a failed submit
|
|
4
|
+
// - must NOT wipe what was typed, even when the list re-renders the dialog with
|
|
5
|
+
// a new `record={{}}` / `action` identity (it did: contact, company, phone…
|
|
6
|
+
// came back empty on the second attempt);
|
|
7
|
+
// - must light up the input the server named — through the `errors` map
|
|
8
|
+
// (host contract, OPS WasmActionError.Fields) or a single `error.field` —
|
|
9
|
+
// with aria-invalid, the message under the input, and focus on it.
|
|
10
|
+
import { afterEach, describe, expect, it, vi } from 'vitest'
|
|
11
|
+
import { cleanup, render, screen, fireEvent, waitFor } from '@testing-library/react'
|
|
12
|
+
|
|
13
|
+
vi.mock('react-i18next', () => ({
|
|
14
|
+
useTranslation: () => ({
|
|
15
|
+
t: (k: string, o?: any) => o?.defaultValue ?? k,
|
|
16
|
+
i18n: { language: 'es' },
|
|
17
|
+
}),
|
|
18
|
+
}))
|
|
19
|
+
|
|
20
|
+
import { ActionModalDispatcher } from '../action-modal-dispatcher'
|
|
21
|
+
import { ApiProvider, type ApiClient } from '../api-context'
|
|
22
|
+
import type { ActionMetadata } from '@asteby/metacore-sdk'
|
|
23
|
+
|
|
24
|
+
afterEach(cleanup)
|
|
25
|
+
|
|
26
|
+
const fields = [
|
|
27
|
+
{ key: 'contact_name', label: 'Contacto', type: 'text' },
|
|
28
|
+
{ key: 'street', label: 'Calle', type: 'text', required: true },
|
|
29
|
+
{ key: 'neighborhood', label: 'Colonia', type: 'text' },
|
|
30
|
+
{ key: 'postal_code', label: 'Código postal', type: 'text', required: true },
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
const makeAction = () =>
|
|
34
|
+
({ key: 'save_shipping_origin', label: 'Guardar origen', icon: 'map-pin', placement: 'table', fields: fields.map((f) => ({ ...f })) }) as unknown as ActionMetadata
|
|
35
|
+
|
|
36
|
+
function Harness({ api, tick }: { api: ApiClient; tick: number }) {
|
|
37
|
+
// Every render hands a NEW record object and a NEW action object, like the
|
|
38
|
+
// list toolbar / a refetched metadata cache do.
|
|
39
|
+
return (
|
|
40
|
+
<ApiProvider client={api}>
|
|
41
|
+
<span data-tick={tick} />
|
|
42
|
+
<ActionModalDispatcher
|
|
43
|
+
open
|
|
44
|
+
onOpenChange={() => {}}
|
|
45
|
+
action={makeAction()}
|
|
46
|
+
model="ShippingOrigin"
|
|
47
|
+
record={{}}
|
|
48
|
+
endpoint="/data/ShippingOrigin/me"
|
|
49
|
+
onSuccess={() => {}}
|
|
50
|
+
/>
|
|
51
|
+
</ApiProvider>
|
|
52
|
+
)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function setup(postImpl: () => Promise<any>) {
|
|
56
|
+
const post = vi.fn(postImpl)
|
|
57
|
+
const api = { get: vi.fn().mockResolvedValue({ data: {} }), post } as unknown as ApiClient
|
|
58
|
+
const view = render(<Harness api={api} tick={0} />)
|
|
59
|
+
return { post, api, view }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const input = (id: string) => document.getElementById(id) as HTMLInputElement
|
|
63
|
+
const type = (id: string, v: string) => fireEvent.change(input(id), { target: { value: v } })
|
|
64
|
+
const submit = () => fireEvent.click(screen.getByRole('button', { name: 'Guardar origen' }))
|
|
65
|
+
|
|
66
|
+
describe('action dialog keeps the values and lights up the field', () => {
|
|
67
|
+
it('server `errors` map: values survive a failure and a parent re-render; the field is invalid and focused', async () => {
|
|
68
|
+
const { post, api, view } = setup(() =>
|
|
69
|
+
Promise.reject({
|
|
70
|
+
response: {
|
|
71
|
+
status: 422,
|
|
72
|
+
data: {
|
|
73
|
+
success: false,
|
|
74
|
+
code: 'invalid_input',
|
|
75
|
+
message: 'Falta un dato del origen de envío: Colonia.',
|
|
76
|
+
errors: { neighborhood: 'Falta un dato del origen de envío: Colonia.' },
|
|
77
|
+
},
|
|
78
|
+
},
|
|
79
|
+
}),
|
|
80
|
+
)
|
|
81
|
+
type('contact_name', 'Ana')
|
|
82
|
+
type('street', 'Calle Huitzilopochtli')
|
|
83
|
+
type('postal_code', '16030')
|
|
84
|
+
submit()
|
|
85
|
+
await waitFor(() => expect(post).toHaveBeenCalledTimes(1))
|
|
86
|
+
await waitFor(() => expect(input('neighborhood').getAttribute('aria-invalid')).toBe('true'))
|
|
87
|
+
expect(document.querySelector('[data-field-error="neighborhood"]')?.textContent).toContain('Colonia')
|
|
88
|
+
await waitFor(() => expect(document.activeElement).toBe(input('neighborhood')))
|
|
89
|
+
|
|
90
|
+
// The list re-renders (new record / action identity): nothing is wiped.
|
|
91
|
+
view.rerender(<Harness api={api} tick={1} />)
|
|
92
|
+
expect(input('contact_name').value).toBe('Ana')
|
|
93
|
+
expect(input('street').value).toBe('Calle Huitzilopochtli')
|
|
94
|
+
expect(input('postal_code').value).toBe('16030')
|
|
95
|
+
expect(input('neighborhood').getAttribute('aria-invalid')).toBe('true')
|
|
96
|
+
|
|
97
|
+
// Typing in the field clears its error.
|
|
98
|
+
type('neighborhood', 'Barrio 18')
|
|
99
|
+
expect(input('neighborhood').getAttribute('aria-invalid')).toBeNull()
|
|
100
|
+
})
|
|
101
|
+
|
|
102
|
+
it('single `error.field` naming a dialog field lights it up', async () => {
|
|
103
|
+
setup(() =>
|
|
104
|
+
Promise.resolve({
|
|
105
|
+
data: {
|
|
106
|
+
success: false,
|
|
107
|
+
error: { code: 'invalid_input', message: 'El código postal no es válido.', field: 'postal_code' },
|
|
108
|
+
},
|
|
109
|
+
}),
|
|
110
|
+
)
|
|
111
|
+
type('street', 'Calle 1')
|
|
112
|
+
type('postal_code', '1')
|
|
113
|
+
submit()
|
|
114
|
+
await waitFor(() => expect(input('postal_code').getAttribute('aria-invalid')).toBe('true'))
|
|
115
|
+
expect(document.querySelector('[data-field-error="postal_code"]')?.textContent).toContain('código postal')
|
|
116
|
+
expect(input('street').value).toBe('Calle 1')
|
|
117
|
+
})
|
|
118
|
+
|
|
119
|
+
it('a human label in params.field is not taken for a field key', async () => {
|
|
120
|
+
setup(() =>
|
|
121
|
+
Promise.resolve({
|
|
122
|
+
data: { success: false, error: { code: 'invalid_input', message: 'x', params: { field: 'Colonia / Neighborhood' } } },
|
|
123
|
+
}),
|
|
124
|
+
)
|
|
125
|
+
type('street', 'Calle 1')
|
|
126
|
+
type('postal_code', '16030')
|
|
127
|
+
submit()
|
|
128
|
+
await screen.findByRole('alert')
|
|
129
|
+
expect(document.querySelector('[aria-invalid="true"]')).toBeNull()
|
|
130
|
+
expect(input('street').value).toBe('Calle 1')
|
|
131
|
+
})
|
|
132
|
+
|
|
133
|
+
it('client-side required check focuses the first missing field', async () => {
|
|
134
|
+
const { post } = setup(() => Promise.resolve({ data: { success: true } }))
|
|
135
|
+
type('contact_name', 'Ana')
|
|
136
|
+
submit()
|
|
137
|
+
await waitFor(() => expect(input('street').getAttribute('aria-invalid')).toBe('true'))
|
|
138
|
+
await waitFor(() => expect(document.activeElement).toBe(input('street')))
|
|
139
|
+
expect(post).not.toHaveBeenCalled()
|
|
140
|
+
expect(input('contact_name').value).toBe('Ana')
|
|
141
|
+
})
|
|
142
|
+
})
|
|
@@ -237,19 +237,24 @@ describe('AddonConfigSurface with setup blocks', () => {
|
|
|
237
237
|
expect(screen.queryByText(WEBHOOK)).toBeNull()
|
|
238
238
|
})
|
|
239
239
|
|
|
240
|
-
|
|
240
|
+
// Footer since #1287 (Guardar siempre visible): save state on the left;
|
|
241
|
+
// Cerrar/Cancelar, Atrás and the ONE primary Guardar on the right, Guardar
|
|
242
|
+
// stretching to the full row on phones. Verifications live in the steps.
|
|
243
|
+
it('footer: Guardar is the one primary, always there, full width on phones; Cerrar + Atrás beside it', async () => {
|
|
241
244
|
setup(mp)
|
|
242
245
|
await screen.findByText('Access token')
|
|
243
246
|
fireEvent.click(within(footer()).getByText('Siguiente'))
|
|
244
247
|
await screen.findByText(WEBHOOK)
|
|
245
248
|
const buttons = within(footer()).getAllByRole('button')
|
|
246
|
-
expect(buttons.map((b) => b.textContent)).toEqual(['
|
|
247
|
-
|
|
248
|
-
expect(buttons[
|
|
249
|
-
expect(
|
|
250
|
-
expect(
|
|
249
|
+
expect(buttons.map((b) => b.textContent)).toEqual(['Cerrar', 'Atrás', 'Guardar'])
|
|
250
|
+
const save = within(footer()).getByTestId('config-save')
|
|
251
|
+
expect(save).toBe(buttons[2])
|
|
252
|
+
expect(save.className).toContain('flex-1')
|
|
253
|
+
expect(save.className).toContain('h-11')
|
|
254
|
+
expect(buttons[0].className).not.toContain('flex-1')
|
|
255
|
+
expect(buttons[1].className).not.toContain('flex-1')
|
|
256
|
+
expect(within(footer()).getByRole('status')).toBeTruthy()
|
|
251
257
|
expect(within(footer()).queryByText('Probar conexión')).toBeNull()
|
|
252
|
-
expect(footer().className).toContain('grid-cols-2')
|
|
253
258
|
})
|
|
254
259
|
|
|
255
260
|
it('an explicit action bound to test_export replaces the implicit test', async () => {
|
|
@@ -49,7 +49,7 @@ import { toastServerError, toastServerSuccess, extractFieldErrors, extractServer
|
|
|
49
49
|
import { FormErrorBanner } from './business/feedback'
|
|
50
50
|
import { CfdiStampResultDialog, extractStampResult, type CfdiStampResult } from './cfdi-stamp-panel'
|
|
51
51
|
import { useBranchCreateGate } from './branch-create-gate'
|
|
52
|
-
import type { Translate } from './server-error'
|
|
52
|
+
import type { Translate, FieldIssue } from './server-error'
|
|
53
53
|
import { validateValues, bagHasErrors } from './validator'
|
|
54
54
|
import {
|
|
55
55
|
clearFieldErrorTree,
|
|
@@ -858,6 +858,38 @@ function humanizeKey(k: string): string {
|
|
|
858
858
|
return k.replace(/[._-]+/g, ' ').replace(/\b\w/g, c => c.toUpperCase())
|
|
859
859
|
}
|
|
860
860
|
|
|
861
|
+
/**
|
|
862
|
+
* A failed action that names ONE input without an `errors` map — the error
|
|
863
|
+
* contract a handler may answer with (documented in docs/action-errors.md):
|
|
864
|
+
* { success:false, error:{ code, message, message_key, params, field: "<field key>" } }
|
|
865
|
+
* (also `field` at the top level, as hosts that flatten the guest error send
|
|
866
|
+
* it). The field must be one of the dialog's own field keys — a human label in
|
|
867
|
+
* `params.field` never matches — and its message is the server's own (already
|
|
868
|
+
* localized by the host) message.
|
|
869
|
+
*/
|
|
870
|
+
function singleFieldError(
|
|
871
|
+
err: unknown,
|
|
872
|
+
fields: readonly ActionFieldDef[] | undefined,
|
|
873
|
+
t: Translate,
|
|
874
|
+
): Record<string, FieldIssue[]> | undefined {
|
|
875
|
+
if (!fields?.length) return undefined
|
|
876
|
+
const data = ((err as { response?: { data?: unknown } } | undefined)?.response?.data ?? err) as
|
|
877
|
+
| Record<string, any>
|
|
878
|
+
| undefined
|
|
879
|
+
if (!data || typeof data !== 'object') return undefined
|
|
880
|
+
const inner = data.error && typeof data.error === 'object' ? (data.error as Record<string, any>) : undefined
|
|
881
|
+
const candidates = [data.field, inner?.field, data.params?.field_key, inner?.params?.field_key]
|
|
882
|
+
const keys = new Set(fields.map((f) => f.key))
|
|
883
|
+
const key = candidates.find((c): c is string => typeof c === 'string' && keys.has(c))
|
|
884
|
+
if (!key) return undefined
|
|
885
|
+
const raw =
|
|
886
|
+
(typeof data.message === 'string' && data.message.trim()) ||
|
|
887
|
+
(typeof inner?.message === 'string' && inner.message.trim()) ||
|
|
888
|
+
''
|
|
889
|
+
const message = raw ? t(raw, { defaultValue: raw, ...(data.params ?? inner?.params ?? {}) }) : ''
|
|
890
|
+
return { [key]: [message ? { message } : { code: 'invalid' }] }
|
|
891
|
+
}
|
|
892
|
+
|
|
861
893
|
/** Localize a failed action submit's per-field `errors` (422 map or `{errors}`
|
|
862
894
|
* body) into `{ [fieldKey]: localizedMessage }`, using each field's label.
|
|
863
895
|
* Returns undefined when there is no usable per-field map. */
|
|
@@ -867,7 +899,7 @@ function localizeActionFieldErrors(
|
|
|
867
899
|
t: Translate,
|
|
868
900
|
language?: string,
|
|
869
901
|
): Record<string, string> | undefined {
|
|
870
|
-
const map = extractFieldErrors(err)
|
|
902
|
+
const map = extractFieldErrors(err) ?? singleFieldError(err, fields, t)
|
|
871
903
|
if (!map) return undefined
|
|
872
904
|
const labels: Record<string, string> = {}
|
|
873
905
|
for (const f of fields ?? []) {
|
|
@@ -1017,6 +1049,43 @@ function ConfirmActionDialog({ open, onOpenChange, action, model, record, endpoi
|
|
|
1017
1049
|
)
|
|
1018
1050
|
}
|
|
1019
1051
|
|
|
1052
|
+
/**
|
|
1053
|
+
* Identity of one "opening" of an action dialog: open + action + record id +
|
|
1054
|
+
* model, plus a counter bumped on every closed→open transition. Re-renders that
|
|
1055
|
+
* only hand a NEW OBJECT for the same record (`record={{}}`, a refetched row)
|
|
1056
|
+
* keep the same key, so the form is not re-seeded under the person's hands.
|
|
1057
|
+
* Empty string while closed.
|
|
1058
|
+
*/
|
|
1059
|
+
function useSeedKey(open: boolean, actionKey: string | undefined, record: Record<string, any> | undefined, model: string): string {
|
|
1060
|
+
const opening = useRef(0)
|
|
1061
|
+
const wasOpen = useRef(false)
|
|
1062
|
+
if (open && !wasOpen.current) opening.current += 1
|
|
1063
|
+
wasOpen.current = open
|
|
1064
|
+
if (!open) return ''
|
|
1065
|
+
const rid = record?.id == null ? '' : String(record.id)
|
|
1066
|
+
return `${opening.current}|${model}|${actionKey ?? ''}|${rid}`
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
/** Focus and scroll into view the first invalid control inside `root` (DOM
|
|
1070
|
+
* order = field order): the input/select trigger flagged `aria-invalid`, else
|
|
1071
|
+
* the first focusable element of the cell holding a field error message. */
|
|
1072
|
+
export function focusFirstInvalid(root: HTMLElement | null): HTMLElement | null {
|
|
1073
|
+
if (!root) return null
|
|
1074
|
+
const msg = root.querySelector<HTMLElement>('[data-field-error]')
|
|
1075
|
+
const target =
|
|
1076
|
+
root.querySelector<HTMLElement>('[aria-invalid="true"]') ??
|
|
1077
|
+
msg?.parentElement?.querySelector<HTMLElement>('input, textarea, button, [tabindex]') ??
|
|
1078
|
+
null
|
|
1079
|
+
if (!target) return null
|
|
1080
|
+
try {
|
|
1081
|
+
target.scrollIntoView?.({ block: 'center', behavior: 'smooth' })
|
|
1082
|
+
} catch {
|
|
1083
|
+
/* older engines: scrollIntoView without options */
|
|
1084
|
+
}
|
|
1085
|
+
target.focus?.({ preventScroll: true })
|
|
1086
|
+
return target
|
|
1087
|
+
}
|
|
1088
|
+
|
|
1020
1089
|
function GenericActionModal({ open, onOpenChange, action, model, record, endpoint, onSuccess }: ActionModalProps) {
|
|
1021
1090
|
const { t, i18n } = useTranslation()
|
|
1022
1091
|
// Addon-contributed labels (action + fields) are i18n keys whose locale
|
|
@@ -1063,13 +1132,24 @@ function GenericActionModal({ open, onOpenChange, action, model, record, endpoin
|
|
|
1063
1132
|
}
|
|
1064
1133
|
}, [open, model, recordId, api])
|
|
1065
1134
|
|
|
1135
|
+
// Seed the form ONCE per opening (and again only when the dialog switches to
|
|
1136
|
+
// another action or record). Never on a mere re-render: callers pass
|
|
1137
|
+
// `record={{}}` / a refetched row / a re-derived `action` with a new identity
|
|
1138
|
+
// on every render of the list, and re-seeding on identity wiped what the
|
|
1139
|
+
// person typed right after a failed submit (ProtekAuto: «Configurar origen de
|
|
1140
|
+
// envío» lost contact, company, phone… on the second attempt). What was
|
|
1141
|
+
// typed survives a failure; it is cleared only by closing or by success.
|
|
1142
|
+
const seedKey = useSeedKey(open, action.key, record, model)
|
|
1143
|
+
const seedRef = useRef({ fields: action.fields, record, model, orgTimeZone })
|
|
1144
|
+
seedRef.current = { fields: action.fields, record, model, orgTimeZone }
|
|
1066
1145
|
useEffect(() => {
|
|
1067
|
-
|
|
1068
|
-
|
|
1146
|
+
const cur = seedRef.current
|
|
1147
|
+
if (seedKey && cur.fields) {
|
|
1148
|
+
setFormData(buildFieldDefaults(cur.fields, cur.record, cur.model, { timeZone: cur.orgTimeZone }))
|
|
1069
1149
|
setFieldErrors({})
|
|
1070
1150
|
setFormError(undefined)
|
|
1071
1151
|
}
|
|
1072
|
-
}, [
|
|
1152
|
+
}, [seedKey])
|
|
1073
1153
|
|
|
1074
1154
|
// Lines the list row does not carry: load them from the declared relation
|
|
1075
1155
|
// (see prefillRelationRequests) and seed the line-items grid.
|
|
@@ -1153,6 +1233,14 @@ function GenericActionModal({ open, onOpenChange, action, model, record, endpoin
|
|
|
1153
1233
|
setFieldErrors((prev) => clearFieldErrorTree(prev, key))
|
|
1154
1234
|
}
|
|
1155
1235
|
|
|
1236
|
+
// Focus + scroll to the first invalid input after a failed submit (client
|
|
1237
|
+
// validation or server `errors`), so the person lands on what to fix.
|
|
1238
|
+
const bodyRef = useRef<HTMLDivElement>(null)
|
|
1239
|
+
const [focusTick, setFocusTick] = useState(0)
|
|
1240
|
+
useEffect(() => {
|
|
1241
|
+
if (focusTick > 0) focusFirstInvalid(bodyRef.current)
|
|
1242
|
+
}, [focusTick])
|
|
1243
|
+
|
|
1156
1244
|
const lang = i18n.language
|
|
1157
1245
|
const handleActionError = (err: unknown) => {
|
|
1158
1246
|
setFormError(actionErrorBannerMessage(err, action.fields, t, lang))
|
|
@@ -1166,6 +1254,7 @@ function GenericActionModal({ open, onOpenChange, action, model, record, endpoin
|
|
|
1166
1254
|
if (!labels[path]) labels[path] = labelForValidationPath(path, action.fields, t)
|
|
1167
1255
|
}
|
|
1168
1256
|
setFieldErrors(withPathLabels)
|
|
1257
|
+
setFocusTick((n) => n + 1)
|
|
1169
1258
|
toast.error(t('validation.failed', { defaultValue: validationCatalog(lang).failed }), {
|
|
1170
1259
|
description: formatFieldErrorsDescription(withPathLabels, action.fields, t),
|
|
1171
1260
|
})
|
|
@@ -1185,6 +1274,7 @@ function GenericActionModal({ open, onOpenChange, action, model, record, endpoin
|
|
|
1185
1274
|
}
|
|
1186
1275
|
const next = localizeFieldErrorMap(bag, t, { labels, language: lang })
|
|
1187
1276
|
setFieldErrors(next)
|
|
1277
|
+
setFocusTick((n) => n + 1)
|
|
1188
1278
|
toast.error(t('validation.failed', { defaultValue: validationCatalog(lang).failed }), {
|
|
1189
1279
|
description: formatFieldErrorsDescription(next, action.fields, t),
|
|
1190
1280
|
})
|
|
@@ -1305,7 +1395,7 @@ function GenericActionModal({ open, onOpenChange, action, model, record, endpoin
|
|
|
1305
1395
|
grids and textareas span the full width. `min-w-0` on each cell
|
|
1306
1396
|
(in FieldCell) keeps a long select/input value from blowing the
|
|
1307
1397
|
grid past the dialog and spawning a horizontal scrollbar. */}
|
|
1308
|
-
<div className="-mx-1 min-h-0 flex-1 overflow-y-auto px-1 py-4">
|
|
1398
|
+
<div ref={bodyRef} className="-mx-1 min-h-0 flex-1 overflow-y-auto px-1 py-4">
|
|
1309
1399
|
<FormErrorBanner message={formError} className="mb-3" />
|
|
1310
1400
|
<FieldGrid>
|
|
1311
1401
|
{action.fields?.map((field) => {
|
|
@@ -1327,7 +1417,9 @@ function GenericActionModal({ open, onOpenChange, action, model, record, endpoin
|
|
|
1327
1417
|
fieldErrors,
|
|
1328
1418
|
)}
|
|
1329
1419
|
{fieldErrors[field.key] && (
|
|
1330
|
-
<p className="text-destructive text-xs mt-1"
|
|
1420
|
+
<p id={`${field.key}-error`} className="text-destructive text-xs mt-1" data-field-error={field.key}>
|
|
1421
|
+
{fieldErrors[field.key]}
|
|
1422
|
+
</p>
|
|
1331
1423
|
)}
|
|
1332
1424
|
</FieldCell>
|
|
1333
1425
|
)
|
|
@@ -1455,13 +1547,19 @@ function WizardActionModal({ open, onOpenChange, action, model, record, endpoint
|
|
|
1455
1547
|
|
|
1456
1548
|
// Reset to the first step and seed defaults for EVERY step's fields whenever
|
|
1457
1549
|
// the modal (re)opens, so accumulated values from a prior run don't leak.
|
|
1550
|
+
// Keyed like GenericActionModal: a re-render with a new `record`/`action`
|
|
1551
|
+
// identity must not wipe what was typed (only a new opening does).
|
|
1552
|
+
const seedKey = useSeedKey(open, action.key, record, model)
|
|
1553
|
+
const seedRef = useRef({ steps, record, model, orgTimeZone })
|
|
1554
|
+
seedRef.current = { steps, record, model, orgTimeZone }
|
|
1458
1555
|
useEffect(() => {
|
|
1459
|
-
if (!
|
|
1460
|
-
const
|
|
1461
|
-
|
|
1556
|
+
if (!seedKey) return
|
|
1557
|
+
const cur = seedRef.current
|
|
1558
|
+
const allFields = cur.steps.flatMap((s) => s.fields ?? [])
|
|
1559
|
+
setFormData(buildFieldDefaults(allFields, cur.record, cur.model, { timeZone: cur.orgTimeZone }))
|
|
1462
1560
|
setStepIndex(0)
|
|
1463
1561
|
setFormError(undefined)
|
|
1464
|
-
}, [
|
|
1562
|
+
}, [seedKey])
|
|
1465
1563
|
|
|
1466
1564
|
const updateField = (key: string, value: any) =>
|
|
1467
1565
|
setFormData((prev: Record<string, any>) => ({ ...prev, [key]: value }))
|
|
@@ -69,6 +69,10 @@ export interface ModelActionToolbarProps {
|
|
|
69
69
|
|
|
70
70
|
const DEFAULT_PLACEMENTS: ActionPlacement[] = ['table', 'create']
|
|
71
71
|
|
|
72
|
+
/** Table/create actions act on no record: one stable empty object, not a new
|
|
73
|
+
* `{}` per render (the dialog keys its form on the opening, not on identity). */
|
|
74
|
+
const NO_RECORD: Record<string, any> = {}
|
|
75
|
+
|
|
72
76
|
/**
|
|
73
77
|
* Last-resort label when `t(key)` has no translation yet: never flash the full
|
|
74
78
|
* dotted key in a primary CTA. Prefers the action/field segment over a trailing
|
|
@@ -225,7 +229,7 @@ export function ModelActionToolbar({
|
|
|
225
229
|
}}
|
|
226
230
|
action={active}
|
|
227
231
|
model={model}
|
|
228
|
-
record={
|
|
232
|
+
record={NO_RECORD}
|
|
229
233
|
endpoint={dataEndpoint}
|
|
230
234
|
onSuccess={() => {
|
|
231
235
|
setActive(null)
|