@asteby/metacore-runtime-react 53.9.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 CHANGED
@@ -1,5 +1,17 @@
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
+
9
+ ## 53.10.0
10
+
11
+ ### Minor Changes
12
+
13
+ - fd3b129: `AddonConfigSurface`: Guardar siempre disponible y refresco en el sitio. El pie del modal (fuera del scroll) lleva «Guardar» en TODOS los pasos del asistente (antes solo en el último; «Siguiente» queda como acción secundaria) y un estado «Sin cambios / Cambios sin guardar / Guardando… / Guardado» (aria-live). Tras guardar ya no se cierra: recarga en el sitio las credenciales guardadas (secretos en blanco, campos marcados como guardados), los ajustes y vuelve a listar los selects dependientes (series, entorno, régimen), sin perder paso, scroll ni foco; «Cancelar» pasa a «Cerrar» cuando no hay cambios. «Probar conexión» también refresca los selects dependientes tras persistir.
14
+
3
15
  ## 53.9.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,EAAE,MAAM,gBAAgB,CAAA;AA+B/C,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,EAAE,GAAG,GAAG,KAAK,CAAC,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,CAkB3F;AAYD,MAAM,WAAW,sBAAsB;IACnC,QAAQ,EAAE,MAAM,CAAA;IAChB,IAAI,EAAE,WAAW,CAAA;IACjB,QAAQ,EAAE,MAAM,CAAA;IAChB,MAAM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,MAAM,CAWR;AAuHD;;6EAE6E;AAC7E,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,WAAW,GAAG,IAAI,GAAG,WAAW,GAAG,IAAI,CAe9E;AAgXD,4DAA4D;AAC5D,MAAM,WAAW,mBAAmB;IAChC,gFAAgF;IAChF,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,qBAAqB;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
- if (open && action.fields) {
734
- setFormData(buildFieldDefaults(action.fields, record, model, { timeZone: orgTimeZone }));
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
- }, [open, action.fields, record, model, orgTimeZone]);
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 (!open)
1114
+ if (!seedKey)
1023
1115
  return;
1024
- const allFields = steps.flatMap((s) => s.fields ?? []);
1025
- setFormData(buildFieldDefaults(allFields, record, model, { timeZone: orgTimeZone }));
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
- }, [open, action.steps, record, model, orgTimeZone]);
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;AA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M,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: {}, endpoint: dataEndpoint, onSuccess: () => {
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) => {
@@ -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;AASjC,MAAM,WAAW,eAAe;IAC9B,GAAG,EAAE,MAAM,CAAA;IACX,KAAK,EAAE,MAAM,CAAA;IACb,IAAI,EAAE,MAAM,CAAA;IACZ,aAAa,CAAC,EAAE,OAAO,CAAA;IACvB,OAAO,CAAC,EAAE;QAAE,KAAK,EAAE,OAAO,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,EAAE,CAAA;IAC7C,+EAA+E;IAC/E,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,oEAAoE;IACpE,YAAY,CAAC,EAAE,WAAW,CAAA;IAC1B,WAAW,CAAC,EAAE,WAAW,CAAA;IACzB,8DAA8D;IAC9D,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB,4DAA4D;IAC5D,MAAM,CAAC,EAAE,OAAO,CAAA;CACjB;AAED,MAAM,WAAW,gBAAgB;IAC/B,SAAS,EAAE,MAAM,CAAA;IACjB,QAAQ,EAAE;QACR,IAAI,EAAE,MAAM,CAAA;QACZ,YAAY,CAAC,EAAE,MAAM,CAAA;QACrB,aAAa,C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cAAc,CAAC,EAAE,CAAC,SAAS,EAAE,cAAc,KAAK,IAAI,CAAA;CACrD;AAmQD,6EAA6E;AAC7E,wBAAgB,yBAAyB,SAExC;AA0JD,wBAAgB,kBAAkB,CAAC,EACjC,KAAK,EACL,SAAS,EACT,IAAI,EACJ,YAAY,EACZ,OAAO,EACP,eAAsB,EACtB,gBAAwB,EACxB,YAAmB,EACnB,iBAAiB,EACjB,MAAc,EACd,MAAM,EACN,mBAAqC,EACrC,WAAW,EACX,cAAc,GACf,EAAE,uBAAuB,+BA+kCzB"}
@@ -190,6 +190,14 @@ function DynamicConnectorSelect({ field, value, provider, connected, onChange, }
190
190
  void load();
191
191
  // eslint-disable-next-line react-hooks/exhaustive-deps
192
192
  }, [connected]);
193
+ // After a save the stored connection changed (series, environment, issuer…):
194
+ // re-list in place so the options are current without leaving the dialog.
195
+ const reloadNonce = form.reloadNonce ?? 0;
196
+ useEffect(() => {
197
+ if (reloadNonce > 0)
198
+ void load(true);
199
+ // eslint-disable-next-line react-hooks/exhaustive-deps
200
+ }, [reloadNonce]);
193
201
  // Scope the options to the kind (`tipo`) the host expects for this field,
194
202
  // when the source reports one. The mapping is injected by the host
195
203
  // (`expectedOptionKinds`); empty by default, so the SDK stays domain-agnostic.
@@ -251,6 +259,9 @@ export function AddonConfigSurface({ addon, connector, open, onOpenChange, onSav
251
259
  // credentials not saved yet (an action tests what is STORED: it saves first).
252
260
  const [blockResults, setBlockResults] = useState({});
253
261
  const [credDirty, setCredDirty] = useState(false);
262
+ // Bumped after a save (selects re-list) and the «Guardado» footer state.
263
+ const [reloadNonce, setReloadNonce] = useState(0);
264
+ const [justSaved, setJustSaved] = useState(false);
254
265
  // Credential keys the backend already holds (non-secret values + secrets_set).
255
266
  const [storedKeys, setStoredKeys] = useState(new Set());
256
267
  // Credentials that differ between sandbox and production (served by /values) and
@@ -446,6 +457,49 @@ export function AddonConfigSurface({ addon, connector, open, onOpenChange, onSav
446
457
  const fallback = humanizeKey(f.key);
447
458
  return f.label ? textOrFallback(t(f.label, { defaultValue: fallback }), f.label, fallback) : fallback;
448
459
  };
460
+ // Re-reads what the backend now holds after «Guardar» WITHOUT resetting the
461
+ // step, the scroll or the focus: stored credentials (secrets blank again, the
462
+ // fields marked as stored), settings, and the dependent selects.
463
+ const refreshInPlace = async () => {
464
+ try {
465
+ if (canManageIssuer && connector?.provider && credFields.length > 0) {
466
+ const envQuery = envField && envValue ? `?environment=${encodeURIComponent(envValue)}` : '';
467
+ const res = await api.get(`/integrations/${connector.provider}/values${envQuery}`);
468
+ const stored = (res.data?.data?.values ?? {});
469
+ const secretsSet = (res.data?.data?.secrets_set ?? []);
470
+ envScoped.current = new Set((res.data?.data?.env_scoped ?? []));
471
+ if (envField)
472
+ loadedEnv.current = envValue || (stored[envField.key] ?? '');
473
+ setStoredKeys(new Set([...Object.keys(stored).filter((k) => stored[k] !== ''), ...secretsSet]));
474
+ setCredValues((prev) => {
475
+ const next = { ...prev };
476
+ for (const f of credFields) {
477
+ if (isSecretCredential(f))
478
+ next[f.key] = '';
479
+ else if (stored[f.key] != null && stored[f.key] !== '')
480
+ next[f.key] = stored[f.key];
481
+ }
482
+ return next;
483
+ });
484
+ }
485
+ }
486
+ catch {
487
+ /* keep what is on screen */
488
+ }
489
+ try {
490
+ const branchQuery = target === 'branch' && activeBranch ? `?branch_id=${encodeURIComponent(activeBranchId)}` : '';
491
+ const res = await api.get(`/addons/${addon.addon_key}/settings${branchQuery}`);
492
+ setSettingsValues(res.data?.data || {});
493
+ setOverrides(res.data?.overrides || {});
494
+ }
495
+ catch {
496
+ /* keep what is on screen */
497
+ }
498
+ setCredDirty(false);
499
+ setTouched(new Set());
500
+ setCleared(new Set());
501
+ setReloadNonce((n) => n + 1);
502
+ };
449
503
  const saveMutation = useMutation({
450
504
  mutationFn: async () => {
451
505
  if (connector && canManageIssuer) {
@@ -486,9 +540,10 @@ export function AddonConfigSurface({ addon, connector, open, onOpenChange, onSav
486
540
  onSuccess: () => {
487
541
  setFormError(null);
488
542
  setFieldErrors({});
489
- setCredDirty(false);
490
543
  notify.success(st('installed_addons.config_saved'));
491
- onOpenChange(false);
544
+ // Stay open: reload what was saved in place (no scroll/focus loss) so the
545
+ // operator sees the stored state and the dependent selects are current.
546
+ void refreshInPlace().finally(() => setJustSaved(true));
492
547
  onSaved?.();
493
548
  },
494
549
  onError: (err) => {
@@ -576,6 +631,7 @@ export function AddonConfigSurface({ addon, connector, open, onOpenChange, onSav
576
631
  }
577
632
  await api.post(`/integrations/${connector.provider}`, payload);
578
633
  setCredDirty(false);
634
+ setReloadNonce((n) => n + 1);
579
635
  onSaved?.();
580
636
  return null;
581
637
  };
@@ -759,10 +815,26 @@ export function AddonConfigSurface({ addon, connector, open, onOpenChange, onSav
759
815
  setFormError(null);
760
816
  goToStep(stepIdx + 1);
761
817
  };
818
+ const dirty = credDirty || touched.size > 0 || cleared.size > 0;
819
+ useEffect(() => {
820
+ if (dirty)
821
+ setJustSaved(false);
822
+ }, [dirty]);
823
+ useEffect(() => {
824
+ if (open)
825
+ setJustSaved(false);
826
+ }, [open]);
827
+ const saveStatus = saveMutation.isPending
828
+ ? 'saving'
829
+ : dirty
830
+ ? 'dirty'
831
+ : justSaved
832
+ ? 'saved'
833
+ : 'clean';
762
834
  const hasAnyBlocks = layoutSections.some((s) => (s.blocks?.length ?? 0) > 0) || extraBlocks.length > 0;
763
835
  const nothingToConfigure = !hasCredentials && !hasSettings && !isOAuth && !hasAnyBlocks;
764
836
  const nothingToSave = !hasCredentials && !hasSettings;
765
- return (_jsx(Dialog, { open: open, onOpenChange: onOpenChange, children: _jsx(DialogContent, { className: 'flex max-h-[85vh] flex-col max-sm:max-h-[calc(100dvh-1rem)] max-sm:gap-3 max-sm:p-4', children: _jsxs(ConnectorFormStateContext.Provider, { value: { fields: credFields, errors: fieldErrors, idPrefix, client: api, expectedOptionKinds }, children: [_jsxs(DialogHeader, { className: 'shrink-0 pe-8 text-start', children: [_jsx(DialogTitle, { className: 'leading-snug', children: st('installed_addons.configure_title', { name: displayName ?? addon.manifest.display_name ?? addon.manifest.name }) }), _jsx(DialogDescription, { children: st('installed_addons.configure_description') })] }), _jsx("div", { className: '-mr-2 flex min-h-0 flex-col gap-6 overflow-y-auto py-2 pr-2', children: loading ? (_jsx("div", { className: 'flex justify-center py-8', children: _jsx(Loader2, { className: 'h-5 w-5 animate-spin text-muted-foreground' }) })) : useStepper ? (_jsxs("div", { className: 'flex flex-col gap-5', children: [_jsxs("nav", { "aria-label": st('wizard.steps'), className: 'flex flex-col gap-2', children: [_jsx("ol", { className: 'flex items-center', children: wizardSteps.map((s, i) => {
837
+ return (_jsx(Dialog, { open: open, onOpenChange: onOpenChange, children: _jsx(DialogContent, { className: 'flex max-h-[85vh] flex-col max-sm:max-h-[calc(100dvh-1rem)] max-sm:gap-3 max-sm:p-4', children: _jsxs(ConnectorFormStateContext.Provider, { value: { fields: credFields, errors: fieldErrors, idPrefix, client: api, expectedOptionKinds, reloadNonce }, children: [_jsxs(DialogHeader, { className: 'shrink-0 pe-8 text-start', children: [_jsx(DialogTitle, { className: 'leading-snug', children: st('installed_addons.configure_title', { name: displayName ?? addon.manifest.display_name ?? addon.manifest.name }) }), _jsx(DialogDescription, { children: st('installed_addons.configure_description') })] }), _jsx("div", { className: '-mr-2 flex min-h-0 flex-col gap-6 overflow-y-auto py-2 pr-2', children: loading ? (_jsx("div", { className: 'flex justify-center py-8', children: _jsx(Loader2, { className: 'h-5 w-5 animate-spin text-muted-foreground' }) })) : useStepper ? (_jsxs("div", { className: 'flex flex-col gap-5', children: [_jsxs("nav", { "aria-label": st('wizard.steps'), className: 'flex flex-col gap-2', children: [_jsx("ol", { className: 'flex items-center', children: wizardSteps.map((s, i) => {
766
838
  const status = stepState(i);
767
839
  const active = i === stepIdx;
768
840
  const title = t(s.title ?? '', { defaultValue: humanizeKey(s.title) });
@@ -787,5 +859,5 @@ export function AddonConfigSurface({ addon, connector, open, onOpenChange, onSav
787
859
  if (fields.length === 0 && (sec.blocks?.length ?? 0) === 0)
788
860
  return null;
789
861
  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));
790
- })) : (_jsxs(_Fragment, { children: [requiredFields.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))), advancedFields.length > 0 && (_jsxs("details", { className: 'rounded-md border border-border/60 px-3 py-2', open: advancedFields.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: advancedFields.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: 'grid shrink-0 grid-cols-2 gap-2 border-t pt-3 sm:flex sm:flex-row sm:justify-end sm:border-t-0 sm:pt-0', children: nothingToSave ? (_jsx(Button, { className: 'col-span-2 h-11 sm:h-9', onClick: () => onOpenChange(false), children: st('common.close') })) : (_jsxs(_Fragment, { children: [_jsxs(Button, { className: 'order-first col-span-2 h-11 sm:order-last sm:h-9', onClick: useStepper && !isLastStep ? handleNext : handleSave, disabled: !(useStepper && !isLastStep) && (saveMutation.isPending || loading), children: [saveMutation.isPending && _jsx(Loader2, { className: 'mr-2 h-4 w-4 animate-spin' }), useStepper && !isLastStep ? st('common.next') : st('common.save')] }), useStepper && stepIdx > 0 && (_jsx(Button, { variant: 'outline', className: 'h-11 sm:h-9', onClick: () => goToStep(Math.max(0, stepIdx - 1)), children: st('common.back') })), _jsx(Button, { variant: 'ghost', className: cn('h-11 sm:order-first sm:h-9', !(useStepper && stepIdx > 0) && 'col-span-2'), onClick: () => onOpenChange(false), children: st('common.cancel') })] })) })] }) }) }));
862
+ })) : (_jsxs(_Fragment, { children: [requiredFields.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))), advancedFields.length > 0 && (_jsxs("details", { className: 'rounded-md border border-border/60 px-3 py-2', open: advancedFields.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: advancedFields.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')] })] })] })) })] }) }) }));
791
863
  }
@@ -1 +1 @@
1
- {"version":3,"file":"messages.d.ts","sourceRoot":"","sources":["../../src/setup/messages.ts"],"names":[],"mappings":"AAMA,KAAK,IAAI,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;AAElC,eAAO,MAAM,iBAAiB,EAAE,IAuJ/B,CAAA;AAED,eAAO,MAAM,iBAAiB,EAAE,IAoJ/B,CAAA;AAED,MAAM,MAAM,GAAG,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,MAAM,CAAA;AAOzE,8EAA8E;AAC9E,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM,CAGjE;AAED;;;;;GAKG;AACH,wBAAgB,SAAS,IAAI,GAAG,CAa/B"}
1
+ {"version":3,"file":"messages.d.ts","sourceRoot":"","sources":["../../src/setup/messages.ts"],"names":[],"mappings":"AAMA,KAAK,IAAI,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;AAElC,eAAO,MAAM,iBAAiB,EAAE,IA2J/B,CAAA;AAED,eAAO,MAAM,iBAAiB,EAAE,IAwJ/B,CAAA;AAED,MAAM,MAAM,GAAG,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,MAAM,CAAA;AAOzE,8EAA8E;AAC9E,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM,CAGjE;AAED;;;;;GAKG;AACH,wBAAgB,SAAS,IAAI,GAAG,CAa/B"}
@@ -152,6 +152,10 @@ export const SETUP_MESSAGES_ES = {
152
152
  'common.cancel': 'Cancelar',
153
153
  'common.save': 'Guardar',
154
154
  'common.close': 'Cerrar',
155
+ 'form.status_clean': 'Sin cambios',
156
+ 'form.status_dirty': 'Cambios sin guardar',
157
+ 'form.status_saved': 'Guardado',
158
+ 'form.status_saving': 'Guardando…',
155
159
  };
156
160
  export const SETUP_MESSAGES_EN = {
157
161
  'status.pending': 'Pending',
@@ -300,6 +304,10 @@ export const SETUP_MESSAGES_EN = {
300
304
  'common.cancel': 'Cancel',
301
305
  'common.save': 'Save',
302
306
  'common.close': 'Close',
307
+ 'form.status_clean': 'No changes',
308
+ 'form.status_dirty': 'Unsaved changes',
309
+ 'form.status_saved': 'Saved',
310
+ 'form.status_saving': 'Saving…',
303
311
  };
304
312
  function interpolate(s, vars) {
305
313
  if (!vars)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@asteby/metacore-runtime-react",
3
- "version": "53.9.0",
3
+ "version": "53.10.1",
4
4
  "description": "React runtime for metacore hosts — renders addon contributions dynamically",
5
5
  "repository": {
6
6
  "type": "git",
@@ -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
- it('footer: one primary, full width on phones; Atrás + Cancelar share a row', async () => {
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(['Guardar', 'Atrás', 'Cancelar'])
247
- expect(buttons[0].className).toContain('col-span-2')
248
- expect(buttons[0].className).toContain('h-11')
249
- expect(buttons[1].className).not.toContain('col-span-2')
250
- expect(buttons[2].className).not.toContain('col-span-2')
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
- if (open && action.fields) {
1068
- setFormData(buildFieldDefaults(action.fields, record, model, { timeZone: orgTimeZone }))
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
- }, [open, action.fields, record, model, orgTimeZone])
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">{fieldErrors[field.key]}</p>
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 (!open) return
1460
- const allFields = steps.flatMap((s) => s.fields ?? [])
1461
- setFormData(buildFieldDefaults(allFields, record, model, { timeZone: orgTimeZone }))
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
- }, [open, action.steps, record, model, orgTimeZone])
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)
@@ -210,6 +210,8 @@ interface ConnectorFormState {
210
210
  client?: ApiClient
211
211
  /** Host-injected: credential key -> expected option `tipo`. */
212
212
  expectedOptionKinds: Record<string, string>
213
+ /** Bumped after a save: dependent selects re-list their options in place. */
214
+ reloadNonce?: number
213
215
  }
214
216
  const ConnectorFormStateContext = createContext<ConnectorFormState>({
215
217
  fields: [],
@@ -513,6 +515,14 @@ function DynamicConnectorSelect({
513
515
  // eslint-disable-next-line react-hooks/exhaustive-deps
514
516
  }, [connected])
515
517
 
518
+ // After a save the stored connection changed (series, environment, issuer…):
519
+ // re-list in place so the options are current without leaving the dialog.
520
+ const reloadNonce = form.reloadNonce ?? 0
521
+ useEffect(() => {
522
+ if (reloadNonce > 0) void load(true)
523
+ // eslint-disable-next-line react-hooks/exhaustive-deps
524
+ }, [reloadNonce])
525
+
516
526
  // Scope the options to the kind (`tipo`) the host expects for this field,
517
527
  // when the source reports one. The mapping is injected by the host
518
528
  // (`expectedOptionKinds`); empty by default, so the SDK stays domain-agnostic.
@@ -637,6 +647,9 @@ export function AddonConfigSurface({
637
647
  // credentials not saved yet (an action tests what is STORED: it saves first).
638
648
  const [blockResults, setBlockResults] = useState<Record<string, BlockResult | undefined>>({})
639
649
  const [credDirty, setCredDirty] = useState(false)
650
+ // Bumped after a save (selects re-list) and the «Guardado» footer state.
651
+ const [reloadNonce, setReloadNonce] = useState(0)
652
+ const [justSaved, setJustSaved] = useState(false)
640
653
  // Credential keys the backend already holds (non-secret values + secrets_set).
641
654
  const [storedKeys, setStoredKeys] = useState<Set<string>>(new Set())
642
655
  // Credentials that differ between sandbox and production (served by /values) and
@@ -831,6 +844,46 @@ export function AddonConfigSurface({
831
844
  return f.label ? textOrFallback(t(f.label, { defaultValue: fallback }), f.label, fallback) : fallback
832
845
  }
833
846
 
847
+ // Re-reads what the backend now holds after «Guardar» WITHOUT resetting the
848
+ // step, the scroll or the focus: stored credentials (secrets blank again, the
849
+ // fields marked as stored), settings, and the dependent selects.
850
+ const refreshInPlace = async () => {
851
+ try {
852
+ if (canManageIssuer && connector?.provider && credFields.length > 0) {
853
+ const envQuery = envField && envValue ? `?environment=${encodeURIComponent(envValue)}` : ''
854
+ const res = await api.get(`/integrations/${connector.provider}/values${envQuery}`)
855
+ const stored = (res.data?.data?.values ?? {}) as Record<string, string>
856
+ const secretsSet = (res.data?.data?.secrets_set ?? []) as string[]
857
+ envScoped.current = new Set((res.data?.data?.env_scoped ?? []) as string[])
858
+ if (envField) loadedEnv.current = envValue || (stored[envField.key] ?? '')
859
+ setStoredKeys(new Set([...Object.keys(stored).filter((k) => stored[k] !== ''), ...secretsSet]))
860
+ setCredValues((prev) => {
861
+ const next = { ...prev }
862
+ for (const f of credFields) {
863
+ if (isSecretCredential(f)) next[f.key] = ''
864
+ else if (stored[f.key] != null && stored[f.key] !== '') next[f.key] = stored[f.key]
865
+ }
866
+ return next
867
+ })
868
+ }
869
+ } catch {
870
+ /* keep what is on screen */
871
+ }
872
+ try {
873
+ const branchQuery =
874
+ target === 'branch' && activeBranch ? `?branch_id=${encodeURIComponent(activeBranchId)}` : ''
875
+ const res = await api.get(`/addons/${addon.addon_key}/settings${branchQuery}`)
876
+ setSettingsValues(res.data?.data || {})
877
+ setOverrides(res.data?.overrides || {})
878
+ } catch {
879
+ /* keep what is on screen */
880
+ }
881
+ setCredDirty(false)
882
+ setTouched(new Set())
883
+ setCleared(new Set())
884
+ setReloadNonce((n) => n + 1)
885
+ }
886
+
834
887
  const saveMutation = useMutation({
835
888
  mutationFn: async () => {
836
889
  if (connector && canManageIssuer) {
@@ -869,9 +922,10 @@ export function AddonConfigSurface({
869
922
  onSuccess: () => {
870
923
  setFormError(null)
871
924
  setFieldErrors({})
872
- setCredDirty(false)
873
925
  notify.success(st('installed_addons.config_saved'))
874
- onOpenChange(false)
926
+ // Stay open: reload what was saved in place (no scroll/focus loss) so the
927
+ // operator sees the stored state and the dependent selects are current.
928
+ void refreshInPlace().finally(() => setJustSaved(true))
875
929
  onSaved?.()
876
930
  },
877
931
  onError: (err: unknown) => {
@@ -960,6 +1014,7 @@ export function AddonConfigSurface({
960
1014
  }
961
1015
  await api.post(`/integrations/${connector.provider}`, payload)
962
1016
  setCredDirty(false)
1017
+ setReloadNonce((n) => n + 1)
963
1018
  onSaved?.()
964
1019
  return null
965
1020
  }
@@ -1324,6 +1379,21 @@ export function AddonConfigSurface({
1324
1379
  goToStep(stepIdx + 1)
1325
1380
  }
1326
1381
 
1382
+ const dirty = credDirty || touched.size > 0 || cleared.size > 0
1383
+ useEffect(() => {
1384
+ if (dirty) setJustSaved(false)
1385
+ }, [dirty])
1386
+ useEffect(() => {
1387
+ if (open) setJustSaved(false)
1388
+ }, [open])
1389
+ const saveStatus: 'saving' | 'dirty' | 'saved' | 'clean' = saveMutation.isPending
1390
+ ? 'saving'
1391
+ : dirty
1392
+ ? 'dirty'
1393
+ : justSaved
1394
+ ? 'saved'
1395
+ : 'clean'
1396
+
1327
1397
  const hasAnyBlocks = layoutSections.some((s) => (s.blocks?.length ?? 0) > 0) || extraBlocks.length > 0
1328
1398
  const nothingToConfigure = !hasCredentials && !hasSettings && !isOAuth && !hasAnyBlocks
1329
1399
  const nothingToSave = !hasCredentials && !hasSettings
@@ -1332,7 +1402,7 @@ export function AddonConfigSurface({
1332
1402
  <Dialog open={open} onOpenChange={onOpenChange}>
1333
1403
  <DialogContent className='flex max-h-[85vh] flex-col max-sm:max-h-[calc(100dvh-1rem)] max-sm:gap-3 max-sm:p-4'>
1334
1404
  <ConnectorFormStateContext.Provider
1335
- value={{ fields: credFields, errors: fieldErrors, idPrefix, client: api, expectedOptionKinds }}
1405
+ value={{ fields: credFields, errors: fieldErrors, idPrefix, client: api, expectedOptionKinds, reloadNonce }}
1336
1406
  >
1337
1407
  <DialogHeader className='shrink-0 pe-8 text-start'>
1338
1408
  <DialogTitle className='leading-snug'>
@@ -1576,40 +1646,66 @@ export function AddonConfigSurface({
1576
1646
  </div>
1577
1647
  ) : null}
1578
1648
 
1579
- {/* Footer: always visible (outside the scroll). ONE primary action
1580
- (Siguiente / Guardar) full width on phones, Atrás + Cancelar
1581
- sharing the row below; a single right-aligned row from sm up.
1582
- Verifications live inside the steps, not here. */}
1649
+ {/* Footer: ALWAYS visible (outside the scroll) and Guardar is ALWAYS in
1650
+ it, on every step and at any scroll position. Left: the save state
1651
+ (aria-live). Right: Cancelar/Cerrar, Atrás, Siguiente (steps) and the
1652
+ primary Guardar. Verifications live inside the steps, not here. */}
1583
1653
  <DialogFooter
1584
1654
  data-wizard-footer=''
1585
- className='grid shrink-0 grid-cols-2 gap-2 border-t pt-3 sm:flex sm:flex-row sm:justify-end sm:border-t-0 sm:pt-0'
1655
+ 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'
1586
1656
  >
1587
1657
  {nothingToSave ? (
1588
- <Button className='col-span-2 h-11 sm:h-9' onClick={() => onOpenChange(false)}>
1658
+ <Button className='h-11 w-full sm:ml-auto sm:h-9 sm:w-auto' onClick={() => onOpenChange(false)}>
1589
1659
  {st('common.close')}
1590
1660
  </Button>
1591
1661
  ) : (
1592
1662
  <>
1593
- <Button
1594
- className='order-first col-span-2 h-11 sm:order-last sm:h-9'
1595
- onClick={useStepper && !isLastStep ? handleNext : handleSave}
1596
- disabled={!(useStepper && !isLastStep) && (saveMutation.isPending || loading)}
1663
+ <p
1664
+ role='status'
1665
+ aria-live='polite'
1666
+ data-save-status={saveStatus}
1667
+ className={cn(
1668
+ 'flex shrink-0 items-center gap-1.5 whitespace-nowrap text-xs',
1669
+ saveStatus === 'dirty' ? 'font-medium text-amber-600 dark:text-amber-400' : 'text-muted-foreground',
1670
+ saveStatus === 'saved' && 'text-emerald-600 dark:text-emerald-400',
1671
+ )}
1597
1672
  >
1598
- {saveMutation.isPending && <Loader2 className='mr-2 h-4 w-4 animate-spin' />}
1599
- {useStepper && !isLastStep ? st('common.next') : st('common.save')}
1600
- </Button>
1601
- {useStepper && stepIdx > 0 && (
1602
- <Button variant='outline' className='h-11 sm:h-9' onClick={() => goToStep(Math.max(0, stepIdx - 1))}>
1603
- {st('common.back')}
1673
+ {saveStatus === 'saving' ? (
1674
+ <Loader2 className='h-3.5 w-3.5 animate-spin' />
1675
+ ) : saveStatus === 'saved' ? (
1676
+ <Check className='h-3.5 w-3.5' />
1677
+ ) : (
1678
+ <span
1679
+ aria-hidden
1680
+ className={cn('h-2 w-2 rounded-full', saveStatus === 'dirty' ? 'bg-amber-500' : 'bg-muted-foreground/40')}
1681
+ />
1682
+ )}
1683
+ {st(`form.status_${saveStatus}`)}
1684
+ </p>
1685
+ <div className='flex flex-wrap items-center gap-2 sm:ml-auto sm:flex-nowrap sm:justify-end'>
1686
+ <Button variant='ghost' className='h-11 px-3 sm:h-9' onClick={() => onOpenChange(false)}>
1687
+ {dirty ? st('common.cancel') : st('common.close')}
1604
1688
  </Button>
1605
- )}
1606
- <Button
1607
- variant='ghost'
1608
- className={cn('h-11 sm:order-first sm:h-9', !(useStepper && stepIdx > 0) && 'col-span-2')}
1609
- onClick={() => onOpenChange(false)}
1610
- >
1611
- {st('common.cancel')}
1612
- </Button>
1689
+ {useStepper && stepIdx > 0 && (
1690
+ <Button variant='outline' className='h-11 sm:h-9' onClick={() => goToStep(Math.max(0, stepIdx - 1))}>
1691
+ {st('common.back')}
1692
+ </Button>
1693
+ )}
1694
+ {useStepper && !isLastStep && (
1695
+ <Button variant='outline' className='h-11 sm:h-9' onClick={handleNext}>
1696
+ {st('common.next')}
1697
+ </Button>
1698
+ )}
1699
+ <Button
1700
+ className='h-11 flex-1 sm:h-9 sm:flex-none'
1701
+ onClick={handleSave}
1702
+ disabled={saveMutation.isPending || loading}
1703
+ data-testid='config-save'
1704
+ >
1705
+ {saveMutation.isPending && <Loader2 className='mr-2 h-4 w-4 animate-spin' />}
1706
+ {st('common.save')}
1707
+ </Button>
1708
+ </div>
1613
1709
  </>
1614
1710
  )}
1615
1711
  </DialogFooter>
@@ -157,6 +157,10 @@ export const SETUP_MESSAGES_ES: Dict = {
157
157
  'common.cancel': 'Cancelar',
158
158
  'common.save': 'Guardar',
159
159
  'common.close': 'Cerrar',
160
+ 'form.status_clean': 'Sin cambios',
161
+ 'form.status_dirty': 'Cambios sin guardar',
162
+ 'form.status_saved': 'Guardado',
163
+ 'form.status_saving': 'Guardando…',
160
164
  }
161
165
 
162
166
  export const SETUP_MESSAGES_EN: Dict = {
@@ -307,6 +311,10 @@ export const SETUP_MESSAGES_EN: Dict = {
307
311
  'common.cancel': 'Cancel',
308
312
  'common.save': 'Save',
309
313
  'common.close': 'Close',
314
+ 'form.status_clean': 'No changes',
315
+ 'form.status_dirty': 'Unsaved changes',
316
+ 'form.status_saved': 'Saved',
317
+ 'form.status_saving': 'Saving…',
310
318
  }
311
319
 
312
320
  export type TFn = (key: string, vars?: Record<string, unknown>) => string