@asteby/metacore-runtime-react 53.10.0 → 53.10.2
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 +12 -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/dist/setup/addon-config-surface.d.ts +6 -0
- package/dist/setup/addon-config-surface.d.ts.map +1 -1
- package/dist/setup/addon-config-surface.js +24 -14
- package/dist/setup/connector-form-model.d.ts +28 -0
- package/dist/setup/connector-form-model.d.ts.map +1 -1
- package/dist/setup/connector-form-model.js +26 -0
- 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/src/setup/addon-config-surface.tsx +33 -17
- package/src/setup/connector-conditional-fields.test.ts +58 -0
- package/src/setup/connector-form-model.ts +69 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# @asteby/metacore-runtime-react
|
|
2
2
|
|
|
3
|
+
## 53.10.2
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 8836f74: `AddonConfigSurface`: un campo de credencial oculto por `visible_when` (propio o de su sección de `form_layout`) ya nunca es obligatorio, no se valida, no cuenta en el estado de error del paso y no se envía. Antes se validaban TODOS los campos declarados: un conector con proveedores condicionales (connector_email con Resend/SendGrid/Mailgun) pedía la API key de SendGrid al guardar con Resend. Las secciones con `visible_when` también desaparecen como pasos del asistente, y el mensaje de error nombra solo campos aplicables. Helpers puros nuevos: `applicableFields`, `visibleSections`, `predicateHolds`.
|
|
8
|
+
|
|
9
|
+
## 53.10.1
|
|
10
|
+
|
|
11
|
+
### Patch Changes
|
|
12
|
+
|
|
13
|
+
- 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`.
|
|
14
|
+
|
|
3
15
|
## 53.10.0
|
|
4
16
|
|
|
5
17
|
### 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,gBA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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,CAAA;IACrB,iDAAiD;IACjD,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB;;;;OAIG;IACH,cAAc,CAAC,EAAE,CAAC,MAAM,EAAE,gBAAgB,KAAK,IAAI,CAAA;IACnD;;;;OAIG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAA;CAC5B;
|
|
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,CAAA;IACrB,iDAAiD;IACjD,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB;;;;OAIG;IACH,cAAc,CAAC,EAAE,CAAC,MAAM,EAAE,gBAAgB,KAAK,IAAI,CAAA;IACnD;;;;OAIG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAA;CAC5B;AAQD;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAgBzD;AAQD;;;GAGG;AACH,wBAAgB,eAAe,CAC3B,KAAK,EAAE,MAAM,EACb,UAAU,GAAE,eAAe,EAAuB,EAClD,QAAQ,CAAC,EAAE,gBAAgB,EAAE,GAC9B,gBAAgB,EAAE,CA2BpB;AAED,wBAAgB,kBAAkB,CAAC,EAC/B,KAAK,EACL,QAAQ,EACR,OAAO,EACP,UAA+B,EAC/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) => {
|
|
@@ -42,9 +42,15 @@ export interface ConnectorCredentialField {
|
|
|
42
42
|
}[];
|
|
43
43
|
options_source?: string;
|
|
44
44
|
section?: string;
|
|
45
|
+
/** Shown only while a sibling credential has this value (kernel Setting.visible_when). */
|
|
46
|
+
visible_when?: VisibleWhen;
|
|
47
|
+
visibleWhen?: VisibleWhen;
|
|
45
48
|
}
|
|
46
49
|
export interface ConnectorFormLayoutSection {
|
|
47
50
|
key: string;
|
|
51
|
+
/** Hides the whole section (and its fields) while false. */
|
|
52
|
+
visible_when?: VisibleWhen;
|
|
53
|
+
visibleWhen?: VisibleWhen;
|
|
48
54
|
title?: string;
|
|
49
55
|
description?: string;
|
|
50
56
|
/** Setup blocks (webhook_url / instructions / action), host-filled. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"addon-config-surface.d.ts","sourceRoot":"","sources":["../../src/setup/addon-config-surface.tsx"],"names":[],"mappings":"AAsCA,OAAO,EAAU,KAAK,SAAS,EAAE,MAAM,gBAAgB,CAAA;AAEvD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,UAAU,CAAA;AAI3C,OAAO,EAOL,KAAK,kBAAkB,EACxB,MAAM,0BAA0B,CAAA;
|
|
1
|
+
{"version":3,"file":"addon-config-surface.d.ts","sourceRoot":"","sources":["../../src/setup/addon-config-surface.tsx"],"names":[],"mappings":"AAsCA,OAAO,EAAU,KAAK,SAAS,EAAE,MAAM,gBAAgB,CAAA;AAEvD,OAAO,KAA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,GACf,EAAE,uBAAuB,+BAulCzB"}
|
|
@@ -26,7 +26,7 @@ import { useSetupT } from './messages';
|
|
|
26
26
|
import { StepStatusBadge } from './step-status-badge';
|
|
27
27
|
import { ConnectorBlocks, HelpText } from './connector-blocks';
|
|
28
28
|
import { buildWizardSteps, errorMessage, hasExplicitTest, normalizeBlockResult, stepStatus, } from './connector-blocks-model';
|
|
29
|
-
import { isSecretCredential, missingRequired, parseSaveError, shapeMismatch, textOrFallback, } from './connector-form-model';
|
|
29
|
+
import { isSecretCredential, missingRequired, applicableFields, visibleSections, parseSaveError, shapeMismatch, textOrFallback, } from './connector-form-model';
|
|
30
30
|
// Empty write_only value (typed then erased) must not overwrite the stored secret.
|
|
31
31
|
const isBlank = (v) => v == null || (typeof v === 'string' && v.trim() === '');
|
|
32
32
|
const NO_OPTION_KINDS = {};
|
|
@@ -236,8 +236,6 @@ export function AddonConfigSurface({ addon, connector, open, onOpenChange, onSav
|
|
|
236
236
|
clearConnectorLookupCache();
|
|
237
237
|
}, [open]);
|
|
238
238
|
const credFields = connector?.credentials ?? [];
|
|
239
|
-
const requiredFields = credFields.filter((f) => f.required);
|
|
240
|
-
const advancedFields = credFields.filter((f) => !f.required);
|
|
241
239
|
// A connector with a form_layout groups its credentials into titled sections
|
|
242
240
|
// (a light wizard). Fall back to the required/advanced split when absent.
|
|
243
241
|
const layoutSections = connector?.form_layout?.sections ?? [];
|
|
@@ -270,6 +268,18 @@ export function AddonConfigSurface({ addon, connector, open, onOpenChange, onSav
|
|
|
270
268
|
const loadedEnv = useRef(null);
|
|
271
269
|
const envField = credFields.find((f) => f.type === 'select' && ['environment', 'mode', 'env'].includes(f.key));
|
|
272
270
|
const envValue = envField ? (credValues[envField.key] ?? '') : '';
|
|
271
|
+
// What the form SHOWS for the live values: a credential whose own visible_when
|
|
272
|
+
// (or whose section's) is false is not applicable — never required, never
|
|
273
|
+
// validated, never counted in a step's error, never sent (connector_email:
|
|
274
|
+
// choosing Resend must not demand the SendGrid key).
|
|
275
|
+
const credDefaults = {};
|
|
276
|
+
for (const f of credFields)
|
|
277
|
+
if (f.default != null && f.default !== '')
|
|
278
|
+
credDefaults[f.key] = String(f.default);
|
|
279
|
+
const activeSections = visibleSections(layoutSections, credValues, credDefaults);
|
|
280
|
+
const activeFields = applicableFields(credFields, layoutSections, credValues, credDefaults);
|
|
281
|
+
// Only what applies is sent: a hidden provider's field is left out.
|
|
282
|
+
const isSendable = (key) => !credFields.some((f) => f.key === key) || activeFields.some((f) => f.key === key);
|
|
273
283
|
const stepHeadingRef = useRef(null);
|
|
274
284
|
const stepMoved = useRef(false);
|
|
275
285
|
const setCred = (key, val) => {
|
|
@@ -507,7 +517,7 @@ export function AddonConfigSurface({ addon, connector, open, onOpenChange, onSav
|
|
|
507
517
|
// secret leaves it untouched (server merges).
|
|
508
518
|
const payload = {};
|
|
509
519
|
for (const [k, v] of Object.entries(credValues)) {
|
|
510
|
-
if (v != null && v !== '')
|
|
520
|
+
if (v != null && v !== '' && isSendable(k))
|
|
511
521
|
payload[k] = v;
|
|
512
522
|
}
|
|
513
523
|
await api.post(`/integrations/${connector.provider}`, payload);
|
|
@@ -590,7 +600,7 @@ export function AddonConfigSurface({ addon, connector, open, onOpenChange, onSav
|
|
|
590
600
|
const handleSave = () => {
|
|
591
601
|
setFormError(null);
|
|
592
602
|
if (connector && canManageIssuer) {
|
|
593
|
-
const miss = missingRequired(
|
|
603
|
+
const miss = missingRequired(activeFields, credValues, !!connector.connected);
|
|
594
604
|
if (miss.length > 0) {
|
|
595
605
|
const errs = {};
|
|
596
606
|
for (const k of miss) {
|
|
@@ -614,7 +624,7 @@ export function AddonConfigSurface({ addon, connector, open, onOpenChange, onSav
|
|
|
614
624
|
const persistCredsIfDirty = async () => {
|
|
615
625
|
if (!credDirty || !connector || !canManageIssuer)
|
|
616
626
|
return null;
|
|
617
|
-
const miss = missingRequired(
|
|
627
|
+
const miss = missingRequired(activeFields, credValues, !!connector.connected);
|
|
618
628
|
if (miss.length > 0) {
|
|
619
629
|
const errs = {};
|
|
620
630
|
for (const k of miss)
|
|
@@ -626,7 +636,7 @@ export function AddonConfigSurface({ addon, connector, open, onOpenChange, onSav
|
|
|
626
636
|
}
|
|
627
637
|
const payload = {};
|
|
628
638
|
for (const [k, v] of Object.entries(credValues)) {
|
|
629
|
-
if (v != null && v !== '')
|
|
639
|
+
if (v != null && v !== '' && isSendable(k))
|
|
630
640
|
payload[k] = v;
|
|
631
641
|
}
|
|
632
642
|
await api.post(`/integrations/${connector.provider}`, payload);
|
|
@@ -737,7 +747,7 @@ export function AddonConfigSurface({ addon, connector, open, onOpenChange, onSav
|
|
|
737
747
|
// Wizard steps: form_layout sections with fields OR blocks, + a final
|
|
738
748
|
// "Ajustes" step when the addon also ships settings.
|
|
739
749
|
const wizardSteps = stepMode
|
|
740
|
-
? buildWizardSteps(
|
|
750
|
+
? buildWizardSteps(activeSections, activeFields.map((f) => f.section), hasSettings)
|
|
741
751
|
: [];
|
|
742
752
|
const totalSteps = wizardSteps.length;
|
|
743
753
|
const useStepper = stepMode && totalSteps > 1;
|
|
@@ -778,7 +788,7 @@ export function AddonConfigSurface({ addon, connector, open, onOpenChange, onSav
|
|
|
778
788
|
return stepStatus({
|
|
779
789
|
index: i,
|
|
780
790
|
current: stepIdx,
|
|
781
|
-
fieldKeys: s.kind === 'creds' ?
|
|
791
|
+
fieldKeys: s.kind === 'creds' ? activeFields.filter((f) => f.section === s.key).map((f) => f.key) : [],
|
|
782
792
|
fieldErrors,
|
|
783
793
|
blockKeys: blocksFor(s.key, s.blocks).map((b) => b.key),
|
|
784
794
|
results: blockResults,
|
|
@@ -798,7 +808,7 @@ export function AddonConfigSurface({ addon, connector, open, onOpenChange, onSav
|
|
|
798
808
|
// operator learns what is missing where it is, not at the end.
|
|
799
809
|
const handleNext = () => {
|
|
800
810
|
if (activeStep?.kind === 'creds' && connector && canManageIssuer) {
|
|
801
|
-
const stepFields =
|
|
811
|
+
const stepFields = activeFields.filter((f) => f.section === activeStep.key);
|
|
802
812
|
const miss = missingRequired(stepFields, credValues, !!connector.connected);
|
|
803
813
|
if (miss.length > 0) {
|
|
804
814
|
const errs = {};
|
|
@@ -852,12 +862,12 @@ export function AddonConfigSurface({ addon, connector, open, onOpenChange, onSav
|
|
|
852
862
|
: 'border-border text-muted-foreground'), children: !active && status === 'error' ? (_jsx(AlertCircle, { className: 'h-4 w-4' })) : !active && status === 'ok' ? (_jsx(Check, { className: 'h-4 w-4' })) : (i + 1) }) }), i < wizardSteps.length - 1 && (_jsx("span", { "aria-hidden": 'true', className: cn('mx-1 h-0.5 flex-1 rounded-full transition-colors', i < stepIdx ? 'bg-primary' : 'bg-border') }))] }, s.key));
|
|
853
863
|
}) }), _jsxs("div", { className: 'flex items-start justify-between gap-3', children: [_jsx("h3", { ref: stepHeadingRef, tabIndex: -1, className: 'min-w-0 text-base leading-snug font-semibold break-words outline-none', children: t(activeStep?.title ?? '', {
|
|
854
864
|
defaultValue: humanizeKey(activeStep?.title),
|
|
855
|
-
}) }), _jsx("span", { className: 'mt-0.5 shrink-0 text-xs font-medium tabular-nums text-muted-foreground', children: st('flow.step_of', { n: stepIdx + 1, total: totalSteps }) })] })] }), _jsxs("div", { className: 'flex flex-col gap-4', children: [activeStep?.description && (_jsx(HelpText, { text: addonText(activeStep.description) })), activeStep?.kind === 'settings' ? (settingsBody) : !canManageIssuer ? (_jsxs(_Fragment, { children: [issuerAdminNote, renderBlocks(blocksFor(activeStep?.key ?? '', activeStep?.blocks))] })) : (_jsxs(_Fragment, { children: [renderBlocks(leadBlocks(blocksFor(activeStep?.key ?? '', activeStep?.blocks))),
|
|
865
|
+
}) }), _jsx("span", { className: 'mt-0.5 shrink-0 text-xs font-medium tabular-nums text-muted-foreground', children: st('flow.step_of', { n: stepIdx + 1, total: totalSteps }) })] })] }), _jsxs("div", { className: 'flex flex-col gap-4', children: [activeStep?.description && (_jsx(HelpText, { text: addonText(activeStep.description) })), activeStep?.kind === 'settings' ? (settingsBody) : !canManageIssuer ? (_jsxs(_Fragment, { children: [issuerAdminNote, renderBlocks(blocksFor(activeStep?.key ?? '', activeStep?.blocks))] })) : (_jsxs(_Fragment, { children: [renderBlocks(leadBlocks(blocksFor(activeStep?.key ?? '', activeStep?.blocks))), activeFields.filter((f) => f.section === activeStep?.key).map(renderCred), renderBlocks(trailBlocks(blocksFor(activeStep?.key ?? '', activeStep?.blocks)))] }))] })] })) : (_jsxs(_Fragment, { children: [oauthPanel, hasCredentials && (_jsxs("section", { className: 'flex flex-col gap-3', children: [_jsxs("div", { className: 'flex items-center gap-2', children: [_jsx(Cable, { className: 'h-4 w-4 text-muted-foreground' }), _jsx("h3", { className: 'text-sm font-semibold', children: st('installed_addons.section_credentials') })] }), !canManageIssuer ? (issuerAdminNote) : useLayout ? (
|
|
856
866
|
// form_layout: one titled group per section, in declared order.
|
|
857
|
-
|
|
858
|
-
const fields =
|
|
867
|
+
activeSections.map((sec) => {
|
|
868
|
+
const fields = activeFields.filter((f) => f.section === sec.key);
|
|
859
869
|
if (fields.length === 0 && (sec.blocks?.length ?? 0) === 0)
|
|
860
870
|
return null;
|
|
861
871
|
return (_jsxs("div", { className: 'flex flex-col gap-3 rounded-md border border-border/60 px-3 py-3', children: [sec.title && (_jsxs("div", { className: 'flex flex-col gap-1', children: [_jsx("h4", { className: 'text-sm font-medium', children: t(sec.title, { defaultValue: sec.title }) }), sec.description && (_jsx(HelpText, { text: addonText(sec.description) }))] })), renderBlocks(leadBlocks(sec.blocks)), fields.map((f) => (_jsx(ConnectorCredentialFieldControl, { field: f, connected: !!connector?.connected, provider: connector?.provider ?? '', ...storedProps(f.key), value: credValues[f.key] ?? '', onChange: (val) => setCred(f.key, val) }, f.key))), renderBlocks(trailBlocks(sec.blocks))] }, sec.key));
|
|
862
|
-
})) : (_jsxs(_Fragment, { children: [
|
|
872
|
+
})) : (_jsxs(_Fragment, { children: [activeFields.filter((f) => f.required).map((f) => (_jsx(ConnectorCredentialFieldControl, { field: f, connected: !!connector?.connected, provider: connector?.provider ?? '', ...storedProps(f.key), value: credValues[f.key] ?? '', onChange: (val) => setCred(f.key, val) }, f.key))), activeFields.some((f) => !f.required) && (_jsxs("details", { className: 'rounded-md border border-border/60 px-3 py-2', open: activeFields.filter((f) => !f.required).some((f) => !!fieldErrors[f.key]) || undefined, children: [_jsx("summary", { className: 'flex min-h-11 cursor-pointer items-center text-sm font-medium text-muted-foreground select-none sm:min-h-8', children: st('installed_addons.advanced') }), _jsx("div", { className: 'flex flex-col gap-3 pt-3', children: activeFields.filter((f) => !f.required).map((f) => (_jsx(ConnectorCredentialFieldControl, { field: f, connected: !!connector?.connected, provider: connector?.provider ?? '', ...storedProps(f.key), value: credValues[f.key] ?? '', onChange: (val) => setCred(f.key, val) }, f.key))) })] }))] }))] })), extraBlocks.length > 0 && renderBlocks(extraBlocks), hasSettings && (_jsxs("section", { className: 'flex flex-col gap-3', children: [_jsxs("div", { className: 'flex items-center gap-2', children: [_jsx(Settings, { className: 'h-4 w-4 text-muted-foreground' }), _jsx("h3", { className: 'text-sm font-semibold', children: st('installed_addons.section_settings') })] }), targetPicker, shownDefs.map(renderSetting)] })), nothingToConfigure && (_jsxs("div", { className: 'flex flex-col items-start gap-1 rounded-lg border border-dashed p-4', children: [_jsx("p", { className: 'text-sm font-medium', children: st('empty.title') }), _jsx(HelpText, { text: st('empty.help') })] }))] })) }), formError ? (_jsx("div", { ref: errorRef, role: 'alert', className: 'max-h-40 shrink-0 overflow-y-auto whitespace-pre-wrap break-words rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive', children: formError })) : null, _jsx(DialogFooter, { "data-wizard-footer": '', className: 'flex shrink-0 flex-col gap-2 border-t pt-3 sm:flex-row sm:flex-wrap sm:items-center sm:justify-between sm:space-x-0', children: nothingToSave ? (_jsx(Button, { className: 'h-11 w-full sm:ml-auto sm:h-9 sm:w-auto', onClick: () => onOpenChange(false), children: st('common.close') })) : (_jsxs(_Fragment, { children: [_jsxs("p", { role: 'status', "aria-live": 'polite', "data-save-status": saveStatus, className: cn('flex shrink-0 items-center gap-1.5 whitespace-nowrap text-xs', saveStatus === 'dirty' ? 'font-medium text-amber-600 dark:text-amber-400' : 'text-muted-foreground', saveStatus === 'saved' && 'text-emerald-600 dark:text-emerald-400'), children: [saveStatus === 'saving' ? (_jsx(Loader2, { className: 'h-3.5 w-3.5 animate-spin' })) : saveStatus === 'saved' ? (_jsx(Check, { className: 'h-3.5 w-3.5' })) : (_jsx("span", { "aria-hidden": true, className: cn('h-2 w-2 rounded-full', saveStatus === 'dirty' ? 'bg-amber-500' : 'bg-muted-foreground/40') })), st(`form.status_${saveStatus}`)] }), _jsxs("div", { className: 'flex flex-wrap items-center gap-2 sm:ml-auto sm:flex-nowrap sm:justify-end', children: [_jsx(Button, { variant: 'ghost', className: 'h-11 px-3 sm:h-9', onClick: () => onOpenChange(false), children: dirty ? st('common.cancel') : st('common.close') }), useStepper && stepIdx > 0 && (_jsx(Button, { variant: 'outline', className: 'h-11 sm:h-9', onClick: () => goToStep(Math.max(0, stepIdx - 1)), children: st('common.back') })), useStepper && !isLastStep && (_jsx(Button, { variant: 'outline', className: 'h-11 sm:h-9', onClick: handleNext, children: st('common.next') })), _jsxs(Button, { className: 'h-11 flex-1 sm:h-9 sm:flex-none', onClick: handleSave, disabled: saveMutation.isPending || loading, "data-testid": 'config-save', children: [saveMutation.isPending && _jsx(Loader2, { className: 'mr-2 h-4 w-4 animate-spin' }), st('common.save')] })] })] })) })] }) }) }));
|
|
863
873
|
}
|
|
@@ -37,4 +37,32 @@ export declare function parseSaveError(err: unknown, fallback: string): SaveErro
|
|
|
37
37
|
export declare function textOrFallback(text: string | undefined, key: string, fallback: string): string;
|
|
38
38
|
/** Cheap content hash so a re-published bundle with the same key count re-merges. */
|
|
39
39
|
export declare function bundleSignature(labels: Record<string, unknown>): string;
|
|
40
|
+
export interface VisibilityPredicate {
|
|
41
|
+
field?: string;
|
|
42
|
+
equals?: unknown;
|
|
43
|
+
in?: unknown[];
|
|
44
|
+
class?: string;
|
|
45
|
+
}
|
|
46
|
+
interface ConditionalField {
|
|
47
|
+
key: string;
|
|
48
|
+
section?: string;
|
|
49
|
+
visible_when?: VisibilityPredicate;
|
|
50
|
+
visibleWhen?: VisibilityPredicate;
|
|
51
|
+
}
|
|
52
|
+
interface ConditionalSection {
|
|
53
|
+
key: string;
|
|
54
|
+
visible_when?: VisibilityPredicate;
|
|
55
|
+
visibleWhen?: VisibilityPredicate;
|
|
56
|
+
}
|
|
57
|
+
/** Same semantics as `evaluateVisibleWhen` (no field / no comparison => visible). */
|
|
58
|
+
export declare function predicateHolds(cond: VisibilityPredicate | undefined, values: Record<string, string>, defaults?: Record<string, string>): boolean;
|
|
59
|
+
/** Sections the form shows for these values. */
|
|
60
|
+
export declare function visibleSections<S extends ConditionalSection>(sections: S[], values: Record<string, string>, defaults?: Record<string, string>): S[];
|
|
61
|
+
/**
|
|
62
|
+
* Fields the form shows for these values: the field's own `visible_when` holds
|
|
63
|
+
* AND its section's does. Hidden fields are not validated, not counted in a
|
|
64
|
+
* step's error state and not sent.
|
|
65
|
+
*/
|
|
66
|
+
export declare function applicableFields<F extends ConditionalField>(fields: F[], sections: ConditionalSection[], values: Record<string, string>, defaults?: Record<string, string>): F[];
|
|
67
|
+
export {};
|
|
40
68
|
//# sourceMappingURL=connector-form-model.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connector-form-model.d.ts","sourceRoot":"","sources":["../../src/setup/connector-form-model.ts"],"names":[],"mappings":"AAMA,mEAAmE;AACnE,MAAM,WAAW,cAAc;IAC7B,GAAG,EAAE,MAAM,CAAA;IACX,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB,MAAM,CAAC,EAAE,OAAO,CAAA;IAChB,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,OAAO,CAAC,EAAE,MAAM,CAAA;CACjB;AAED,MAAM,MAAM,eAAe,GAAG,YAAY,GAAG,YAAY,CAAA;AASzD,2EAA2E;AAC3E,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,GAAG,eAAe,GAAG,IAAI,CAMnE;AAED,eAAO,MAAM,kBAAkB,GAAI,GAAG,cAAc,YAAsC,CAAA;AAI1F,MAAM,WAAW,aAAa;IAC5B,iCAAiC;IACjC,KAAK,EAAE,eAAe,CAAA;IACtB,8EAA8E;IAC9E,YAAY,CAAC,EAAE,MAAM,CAAA;CACtB;AAED;;;;GAIG;AACH,wBAAgB,aAAa,CAC3B,KAAK,EAAE,cAAc,EACrB,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,cAAc,EAAE,GACvB,aAAa,GAAG,IAAI,CAatB;AAED,iFAAiF;AACjF,wBAAgB,eAAe,CAC7B,MAAM,EAAE,cAAc,EAAE,EACxB,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAC9B,SAAS,EAAE,OAAO,GACjB,MAAM,EAAE,CAOV;AAED,MAAM,WAAW,SAAS;IACxB,oDAAoD;IACpD,OAAO,EAAE,MAAM,CAAA;IACf,mEAAmE;IACnE,SAAS,EAAE,MAAM,EAAE,CAAA;CACpB;AAED,iFAAiF;AACjF,wBAAgB,cAAc,CAAC,GAAG,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,GAAG,SAAS,CASxE;AAED,qFAAqF;AACrF,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAG9F;AAED,qFAAqF;AACrF,wBAAgB,eAAe,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAKvE"}
|
|
1
|
+
{"version":3,"file":"connector-form-model.d.ts","sourceRoot":"","sources":["../../src/setup/connector-form-model.ts"],"names":[],"mappings":"AAMA,mEAAmE;AACnE,MAAM,WAAW,cAAc;IAC7B,GAAG,EAAE,MAAM,CAAA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|
|
@@ -74,3 +74,29 @@ export function bundleSignature(labels) {
|
|
|
74
74
|
h = ((h << 5) + h + s.charCodeAt(i)) | 0;
|
|
75
75
|
return `${Object.keys(labels).length}:${(h >>> 0).toString(36)}`;
|
|
76
76
|
}
|
|
77
|
+
/** Same semantics as `evaluateVisibleWhen` (no field / no comparison => visible). */
|
|
78
|
+
export function predicateHolds(cond, values, defaults = {}) {
|
|
79
|
+
if (!cond || typeof cond.field !== 'string' || cond.field.trim() === '')
|
|
80
|
+
return true;
|
|
81
|
+
const key = cond.field.trim();
|
|
82
|
+
const raw = values[key];
|
|
83
|
+
const current = raw == null || raw === '' ? (defaults[key] ?? '') : String(raw);
|
|
84
|
+
if (Array.isArray(cond.in) && cond.in.length > 0)
|
|
85
|
+
return cond.in.some((v) => String(v) === current);
|
|
86
|
+
if (cond.equals != null)
|
|
87
|
+
return String(cond.equals) === current;
|
|
88
|
+
return true;
|
|
89
|
+
}
|
|
90
|
+
/** Sections the form shows for these values. */
|
|
91
|
+
export function visibleSections(sections, values, defaults = {}) {
|
|
92
|
+
return sections.filter((s) => predicateHolds(s.visible_when ?? s.visibleWhen, values, defaults));
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Fields the form shows for these values: the field's own `visible_when` holds
|
|
96
|
+
* AND its section's does. Hidden fields are not validated, not counted in a
|
|
97
|
+
* step's error state and not sent.
|
|
98
|
+
*/
|
|
99
|
+
export function applicableFields(fields, sections, values, defaults = {}) {
|
|
100
|
+
const hidden = new Set(sections.filter((s) => !predicateHolds(s.visible_when ?? s.visibleWhen, values, defaults)).map((s) => s.key));
|
|
101
|
+
return fields.filter((f) => predicateHolds(f.visible_when ?? f.visibleWhen, values, defaults) && !(f.section && hidden.has(f.section)));
|
|
102
|
+
}
|
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)
|
|
@@ -54,6 +54,8 @@ import {
|
|
|
54
54
|
import {
|
|
55
55
|
isSecretCredential,
|
|
56
56
|
missingRequired,
|
|
57
|
+
applicableFields,
|
|
58
|
+
visibleSections,
|
|
57
59
|
parseSaveError,
|
|
58
60
|
shapeMismatch,
|
|
59
61
|
textOrFallback,
|
|
@@ -96,10 +98,16 @@ export interface ConnectorCredentialField {
|
|
|
96
98
|
options?: { value: string; label: string }[]
|
|
97
99
|
options_source?: string // dynamic_select: export the host runs to list options
|
|
98
100
|
section?: string // binds to a form_layout section
|
|
101
|
+
/** Shown only while a sibling credential has this value (kernel Setting.visible_when). */
|
|
102
|
+
visible_when?: VisibleWhen
|
|
103
|
+
visibleWhen?: VisibleWhen
|
|
99
104
|
}
|
|
100
105
|
|
|
101
106
|
export interface ConnectorFormLayoutSection {
|
|
102
107
|
key: string
|
|
108
|
+
/** Hides the whole section (and its fields) while false. */
|
|
109
|
+
visible_when?: VisibleWhen
|
|
110
|
+
visibleWhen?: VisibleWhen
|
|
103
111
|
title?: string // i18n key
|
|
104
112
|
description?: string // i18n key
|
|
105
113
|
/** Setup blocks (webhook_url / instructions / action), host-filled. */
|
|
@@ -622,8 +630,6 @@ export function AddonConfigSurface({
|
|
|
622
630
|
}, [open])
|
|
623
631
|
|
|
624
632
|
const credFields = connector?.credentials ?? []
|
|
625
|
-
const requiredFields = credFields.filter((f) => f.required)
|
|
626
|
-
const advancedFields = credFields.filter((f) => !f.required)
|
|
627
633
|
// A connector with a form_layout groups its credentials into titled sections
|
|
628
634
|
// (a light wizard). Fall back to the required/advanced split when absent.
|
|
629
635
|
const layoutSections = connector?.form_layout?.sections ?? []
|
|
@@ -660,6 +666,16 @@ export function AddonConfigSurface({
|
|
|
660
666
|
(f) => f.type === 'select' && ['environment', 'mode', 'env'].includes(f.key),
|
|
661
667
|
)
|
|
662
668
|
const envValue = envField ? (credValues[envField.key] ?? '') : ''
|
|
669
|
+
// What the form SHOWS for the live values: a credential whose own visible_when
|
|
670
|
+
// (or whose section's) is false is not applicable — never required, never
|
|
671
|
+
// validated, never counted in a step's error, never sent (connector_email:
|
|
672
|
+
// choosing Resend must not demand the SendGrid key).
|
|
673
|
+
const credDefaults: Record<string, string> = {}
|
|
674
|
+
for (const f of credFields) if (f.default != null && f.default !== '') credDefaults[f.key] = String(f.default)
|
|
675
|
+
const activeSections = visibleSections(layoutSections, credValues, credDefaults)
|
|
676
|
+
const activeFields = applicableFields(credFields, layoutSections, credValues, credDefaults)
|
|
677
|
+
// Only what applies is sent: a hidden provider's field is left out.
|
|
678
|
+
const isSendable = (key: string) => !credFields.some((f) => f.key === key) || activeFields.some((f) => f.key === key)
|
|
663
679
|
const stepHeadingRef = useRef<HTMLHeadingElement>(null)
|
|
664
680
|
const stepMoved = useRef(false)
|
|
665
681
|
const setCred = (key: string, val: string) => {
|
|
@@ -891,7 +907,7 @@ export function AddonConfigSurface({
|
|
|
891
907
|
// secret leaves it untouched (server merges).
|
|
892
908
|
const payload: Record<string, string> = {}
|
|
893
909
|
for (const [k, v] of Object.entries(credValues)) {
|
|
894
|
-
if (v != null && v !== '') payload[k] = v
|
|
910
|
+
if (v != null && v !== '' && isSendable(k)) payload[k] = v
|
|
895
911
|
}
|
|
896
912
|
await api.post(`/integrations/${connector.provider}`, payload)
|
|
897
913
|
}
|
|
@@ -973,7 +989,7 @@ export function AddonConfigSurface({
|
|
|
973
989
|
const handleSave = () => {
|
|
974
990
|
setFormError(null)
|
|
975
991
|
if (connector && canManageIssuer) {
|
|
976
|
-
const miss = missingRequired(
|
|
992
|
+
const miss = missingRequired(activeFields, credValues, !!connector.connected)
|
|
977
993
|
if (miss.length > 0) {
|
|
978
994
|
const errs: Record<string, string> = {}
|
|
979
995
|
for (const k of miss) {
|
|
@@ -999,7 +1015,7 @@ export function AddonConfigSurface({
|
|
|
999
1015
|
// screen requires persisting it first. Returns an error message, or null.
|
|
1000
1016
|
const persistCredsIfDirty = async (): Promise<string | null> => {
|
|
1001
1017
|
if (!credDirty || !connector || !canManageIssuer) return null
|
|
1002
|
-
const miss = missingRequired(
|
|
1018
|
+
const miss = missingRequired(activeFields, credValues, !!connector.connected)
|
|
1003
1019
|
if (miss.length > 0) {
|
|
1004
1020
|
const errs: Record<string, string> = {}
|
|
1005
1021
|
for (const k of miss) errs[k] = st('installed_addons.field_required')
|
|
@@ -1010,7 +1026,7 @@ export function AddonConfigSurface({
|
|
|
1010
1026
|
}
|
|
1011
1027
|
const payload: Record<string, string> = {}
|
|
1012
1028
|
for (const [k, v] of Object.entries(credValues)) {
|
|
1013
|
-
if (v != null && v !== '') payload[k] = v
|
|
1029
|
+
if (v != null && v !== '' && isSendable(k)) payload[k] = v
|
|
1014
1030
|
}
|
|
1015
1031
|
await api.post(`/integrations/${connector.provider}`, payload)
|
|
1016
1032
|
setCredDirty(false)
|
|
@@ -1282,8 +1298,8 @@ export function AddonConfigSurface({
|
|
|
1282
1298
|
// "Ajustes" step when the addon also ships settings.
|
|
1283
1299
|
const wizardSteps = stepMode
|
|
1284
1300
|
? buildWizardSteps(
|
|
1285
|
-
|
|
1286
|
-
|
|
1301
|
+
activeSections,
|
|
1302
|
+
activeFields.map((f) => f.section),
|
|
1287
1303
|
hasSettings,
|
|
1288
1304
|
)
|
|
1289
1305
|
: []
|
|
@@ -1339,7 +1355,7 @@ export function AddonConfigSurface({
|
|
|
1339
1355
|
return stepStatus({
|
|
1340
1356
|
index: i,
|
|
1341
1357
|
current: stepIdx,
|
|
1342
|
-
fieldKeys: s.kind === 'creds' ?
|
|
1358
|
+
fieldKeys: s.kind === 'creds' ? activeFields.filter((f) => f.section === s.key).map((f) => f.key) : [],
|
|
1343
1359
|
fieldErrors,
|
|
1344
1360
|
blockKeys: blocksFor(s.key, s.blocks).map((b) => b.key),
|
|
1345
1361
|
results: blockResults,
|
|
@@ -1360,7 +1376,7 @@ export function AddonConfigSurface({
|
|
|
1360
1376
|
// operator learns what is missing where it is, not at the end.
|
|
1361
1377
|
const handleNext = () => {
|
|
1362
1378
|
if (activeStep?.kind === 'creds' && connector && canManageIssuer) {
|
|
1363
|
-
const stepFields =
|
|
1379
|
+
const stepFields = activeFields.filter((f) => f.section === activeStep.key)
|
|
1364
1380
|
const miss = missingRequired(stepFields, credValues, !!connector.connected)
|
|
1365
1381
|
if (miss.length > 0) {
|
|
1366
1382
|
const errs: Record<string, string> = {}
|
|
@@ -1512,7 +1528,7 @@ export function AddonConfigSurface({
|
|
|
1512
1528
|
) : (
|
|
1513
1529
|
<>
|
|
1514
1530
|
{renderBlocks(leadBlocks(blocksFor(activeStep?.key ?? '', activeStep?.blocks)))}
|
|
1515
|
-
{
|
|
1531
|
+
{activeFields.filter((f) => f.section === activeStep?.key).map(renderCred)}
|
|
1516
1532
|
{renderBlocks(trailBlocks(blocksFor(activeStep?.key ?? '', activeStep?.blocks)))}
|
|
1517
1533
|
</>
|
|
1518
1534
|
)}
|
|
@@ -1534,8 +1550,8 @@ export function AddonConfigSurface({
|
|
|
1534
1550
|
issuerAdminNote
|
|
1535
1551
|
) : useLayout ? (
|
|
1536
1552
|
// form_layout: one titled group per section, in declared order.
|
|
1537
|
-
|
|
1538
|
-
const fields =
|
|
1553
|
+
activeSections.map((sec) => {
|
|
1554
|
+
const fields = activeFields.filter((f) => f.section === sec.key)
|
|
1539
1555
|
if (fields.length === 0 && (sec.blocks?.length ?? 0) === 0) return null
|
|
1540
1556
|
return (
|
|
1541
1557
|
<div
|
|
@@ -1570,7 +1586,7 @@ export function AddonConfigSurface({
|
|
|
1570
1586
|
})
|
|
1571
1587
|
) : (
|
|
1572
1588
|
<>
|
|
1573
|
-
{
|
|
1589
|
+
{activeFields.filter((f) => f.required).map((f) => (
|
|
1574
1590
|
<ConnectorCredentialFieldControl
|
|
1575
1591
|
key={f.key}
|
|
1576
1592
|
field={f}
|
|
@@ -1581,16 +1597,16 @@ export function AddonConfigSurface({
|
|
|
1581
1597
|
onChange={(val) => setCred(f.key, val)}
|
|
1582
1598
|
/>
|
|
1583
1599
|
))}
|
|
1584
|
-
{
|
|
1600
|
+
{activeFields.some((f) => !f.required) && (
|
|
1585
1601
|
<details
|
|
1586
1602
|
className='rounded-md border border-border/60 px-3 py-2'
|
|
1587
|
-
open={
|
|
1603
|
+
open={activeFields.filter((f) => !f.required).some((f) => !!fieldErrors[f.key]) || undefined}
|
|
1588
1604
|
>
|
|
1589
1605
|
<summary className='flex min-h-11 cursor-pointer items-center text-sm font-medium text-muted-foreground select-none sm:min-h-8'>
|
|
1590
1606
|
{st('installed_addons.advanced')}
|
|
1591
1607
|
</summary>
|
|
1592
1608
|
<div className='flex flex-col gap-3 pt-3'>
|
|
1593
|
-
{
|
|
1609
|
+
{activeFields.filter((f) => !f.required).map((f) => (
|
|
1594
1610
|
<ConnectorCredentialFieldControl
|
|
1595
1611
|
key={f.key}
|
|
1596
1612
|
field={f}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { applicableFields, missingRequired, visibleSections } from './connector-form-model'
|
|
3
|
+
|
|
4
|
+
// connector_email: provider picks which API key applies; each provider lives in
|
|
5
|
+
// its own section gated by visible_when.
|
|
6
|
+
const sections = [
|
|
7
|
+
{ key: 'provider' },
|
|
8
|
+
{ key: 'connection_resend', visible_when: { field: 'provider', equals: 'resend' } },
|
|
9
|
+
{ key: 'connection_sendgrid', visible_when: { field: 'provider', equals: 'sendgrid' } },
|
|
10
|
+
{ key: 'identity' },
|
|
11
|
+
]
|
|
12
|
+
const fields = [
|
|
13
|
+
{ key: 'provider', type: 'select', required: true, default: 'resend', section: 'provider' },
|
|
14
|
+
{ key: 'api_key', type: 'secret', required: true, section: 'connection_resend' },
|
|
15
|
+
{ key: 'sendgrid_api_key', type: 'secret', required: true, section: 'connection_sendgrid' },
|
|
16
|
+
{ key: 'from_address', type: 'string', required: true, section: 'identity' },
|
|
17
|
+
]
|
|
18
|
+
const defaults = { provider: 'resend' }
|
|
19
|
+
|
|
20
|
+
describe('conditional credential fields', () => {
|
|
21
|
+
it('provider=resend with sendgrid_api_key empty saves (hidden field is not required)', () => {
|
|
22
|
+
const values = { provider: 'resend', api_key: 're_123', from_address: 'a@b.mx' }
|
|
23
|
+
const active = applicableFields(fields, sections, values, defaults)
|
|
24
|
+
expect(active.map((f) => f.key)).toEqual(['provider', 'api_key', 'from_address'])
|
|
25
|
+
expect(missingRequired(active, values, false)).toEqual([])
|
|
26
|
+
// The old behaviour (every declared field) is what produced the bug.
|
|
27
|
+
expect(missingRequired(fields, values, false)).toContain('sendgrid_api_key')
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
it('the default provider applies when the value is blank', () => {
|
|
31
|
+
const active = applicableFields(fields, sections, { from_address: 'a@b.mx' }, defaults)
|
|
32
|
+
expect(active.map((f) => f.key)).toContain('api_key')
|
|
33
|
+
expect(active.map((f) => f.key)).not.toContain('sendgrid_api_key')
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
it('switching to sendgrid requires ITS key and not the Resend one', () => {
|
|
37
|
+
const values = { provider: 'sendgrid', from_address: 'a@b.mx' }
|
|
38
|
+
const active = applicableFields(fields, sections, values, defaults)
|
|
39
|
+
expect(missingRequired(active, values, false)).toEqual(['sendgrid_api_key'])
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
it('hides sections (wizard steps) of the other providers', () => {
|
|
43
|
+
expect(visibleSections(sections, { provider: 'resend' }, defaults).map((s) => s.key)).toEqual([
|
|
44
|
+
'provider',
|
|
45
|
+
'connection_resend',
|
|
46
|
+
'identity',
|
|
47
|
+
])
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
it('honours a field-level visible_when (in)', () => {
|
|
51
|
+
const f = [
|
|
52
|
+
{ key: 'mode', required: true, default: 'a' },
|
|
53
|
+
{ key: 'extra', required: true, visible_when: { field: 'mode', in: ['b', 'c'] } },
|
|
54
|
+
]
|
|
55
|
+
expect(applicableFields(f, [], { mode: 'a' }, { mode: 'a' }).map((x) => x.key)).toEqual(['mode'])
|
|
56
|
+
expect(applicableFields(f, [], { mode: 'b' }).map((x) => x.key)).toEqual(['mode', 'extra'])
|
|
57
|
+
})
|
|
58
|
+
})
|
|
@@ -113,3 +113,72 @@ export function bundleSignature(labels: Record<string, unknown>): string {
|
|
|
113
113
|
for (let i = 0; i < s.length; i++) h = ((h << 5) + h + s.charCodeAt(i)) | 0
|
|
114
114
|
return `${Object.keys(labels).length}:${(h >>> 0).toString(36)}`
|
|
115
115
|
}
|
|
116
|
+
|
|
117
|
+
// ─── Conditional fields (visible_when) ──────────────────────────────────────
|
|
118
|
+
// Kernel contract (Setting.visible_when / FormSection.visible_when): a hidden
|
|
119
|
+
// credential counts for required checks only while visible. A connector with
|
|
120
|
+
// conditional providers (email: Resend / SendGrid / Mailgun, each with its own
|
|
121
|
+
// key in its own section) must never demand the keys of the providers that were
|
|
122
|
+
// not chosen. These pure helpers decide what is APPLICABLE for the live values.
|
|
123
|
+
|
|
124
|
+
export interface VisibilityPredicate {
|
|
125
|
+
field?: string
|
|
126
|
+
equals?: unknown
|
|
127
|
+
in?: unknown[]
|
|
128
|
+
class?: string
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
interface ConditionalField {
|
|
132
|
+
key: string
|
|
133
|
+
section?: string
|
|
134
|
+
visible_when?: VisibilityPredicate
|
|
135
|
+
visibleWhen?: VisibilityPredicate
|
|
136
|
+
}
|
|
137
|
+
interface ConditionalSection {
|
|
138
|
+
key: string
|
|
139
|
+
visible_when?: VisibilityPredicate
|
|
140
|
+
visibleWhen?: VisibilityPredicate
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Same semantics as `evaluateVisibleWhen` (no field / no comparison => visible). */
|
|
144
|
+
export function predicateHolds(
|
|
145
|
+
cond: VisibilityPredicate | undefined,
|
|
146
|
+
values: Record<string, string>,
|
|
147
|
+
defaults: Record<string, string> = {},
|
|
148
|
+
): boolean {
|
|
149
|
+
if (!cond || typeof cond.field !== 'string' || cond.field.trim() === '') return true
|
|
150
|
+
const key = cond.field.trim()
|
|
151
|
+
const raw = values[key]
|
|
152
|
+
const current = raw == null || raw === '' ? (defaults[key] ?? '') : String(raw)
|
|
153
|
+
if (Array.isArray(cond.in) && cond.in.length > 0) return cond.in.some((v) => String(v) === current)
|
|
154
|
+
if (cond.equals != null) return String(cond.equals) === current
|
|
155
|
+
return true
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Sections the form shows for these values. */
|
|
159
|
+
export function visibleSections<S extends ConditionalSection>(
|
|
160
|
+
sections: S[],
|
|
161
|
+
values: Record<string, string>,
|
|
162
|
+
defaults: Record<string, string> = {},
|
|
163
|
+
): S[] {
|
|
164
|
+
return sections.filter((s) => predicateHolds(s.visible_when ?? s.visibleWhen, values, defaults))
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Fields the form shows for these values: the field's own `visible_when` holds
|
|
169
|
+
* AND its section's does. Hidden fields are not validated, not counted in a
|
|
170
|
+
* step's error state and not sent.
|
|
171
|
+
*/
|
|
172
|
+
export function applicableFields<F extends ConditionalField>(
|
|
173
|
+
fields: F[],
|
|
174
|
+
sections: ConditionalSection[],
|
|
175
|
+
values: Record<string, string>,
|
|
176
|
+
defaults: Record<string, string> = {},
|
|
177
|
+
): F[] {
|
|
178
|
+
const hidden = new Set(
|
|
179
|
+
sections.filter((s) => !predicateHolds(s.visible_when ?? s.visibleWhen, values, defaults)).map((s) => s.key),
|
|
180
|
+
)
|
|
181
|
+
return fields.filter(
|
|
182
|
+
(f) => predicateHolds(f.visible_when ?? f.visibleWhen, values, defaults) && !(f.section && hidden.has(f.section)),
|
|
183
|
+
)
|
|
184
|
+
}
|