@asteby/metacore-runtime-react 53.5.0 → 53.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -16,7 +16,7 @@ import { createContext, useContext, useEffect, useId, useRef, useState } from 'r
16
16
  import { useMutation } from '@tanstack/react-query'
17
17
  import { useTranslation } from 'react-i18next'
18
18
  import { toast } from 'sonner'
19
- import { Cable, Check, CheckCircle2, Loader2, Plug, RefreshCw, Settings, XCircle } from 'lucide-react'
19
+ import { AlertCircle, Cable, Check, Eye, EyeOff, Link2, Loader2, Pencil, RefreshCw, Settings, X } from 'lucide-react'
20
20
  import {
21
21
  Badge,
22
22
  Button,
@@ -40,6 +40,17 @@ import { useApi, type ApiClient } from '../api-context'
40
40
  import { evaluateVisibleWhen, getVisibleWhen } from '../dynamic-form-schema'
41
41
  import type { VisibleWhen } from '../types'
42
42
  import { useSetupT } from './messages'
43
+ import { StepStatusBadge } from './step-status-badge'
44
+ import { ConnectorBlocks, HelpText } from './connector-blocks'
45
+ import {
46
+ buildWizardSteps,
47
+ errorMessage,
48
+ hasExplicitTest,
49
+ normalizeBlockResult,
50
+ stepStatus,
51
+ type BlockResult,
52
+ type ConnectorFormBlock,
53
+ } from './connector-blocks-model'
43
54
  import {
44
55
  isSecretCredential,
45
56
  missingRequired,
@@ -91,6 +102,8 @@ export interface ConnectorFormLayoutSection {
91
102
  key: string
92
103
  title?: string // i18n key
93
104
  description?: string // i18n key
105
+ /** Setup blocks (webhook_url / instructions / action), host-filled. */
106
+ blocks?: ConnectorFormBlock[]
94
107
  }
95
108
  export interface ConnectorFormLayout {
96
109
  mode?: 'sections' | 'steps'
@@ -138,6 +151,12 @@ export interface AddonConfigSurfaceProps {
138
151
  * Default true.
139
152
  */
140
153
  canManageIssuer?: boolean
154
+ /**
155
+ * Owner-only: lets the eye on a stored secret fetch its value on demand
156
+ * (GET /integrations/:provider/values/:key/reveal). Default false: the
157
+ * secret stays write-only and the eye is hidden.
158
+ */
159
+ canRevealSecrets?: boolean
141
160
  /** Active branch (for per-branch settings); null/absent hides the branch picker. */
142
161
  activeBranch?: { id: string; name?: string } | null
143
162
  /** Pulls the addon's own i18n bundle when its labels do not resolve yet. */
@@ -154,8 +173,18 @@ export interface AddonConfigSurfaceProps {
154
173
  expectedOptionKinds?: Record<string, string>
155
174
  /** Title name; default `manifest.display_name ?? manifest.name`. */
156
175
  displayName?: string
176
+ /**
177
+ * OAuth connectors (auth != "token") have no credential form: the surface
178
+ * shows the connection state and a "Conectar cuenta" button that calls this
179
+ * (the host starts its OAuth flow). Absent → no button.
180
+ */
181
+ onConnectOAuth?: (connector: ConnectorEntry) => void
157
182
  }
158
183
 
184
+ /** Key of the implicit "Probar conexión" block (connector.test_export). */
185
+ const TEST_BLOCK_KEY = '__test_connection'
186
+ const SYNC_BLOCK_KEY = '__sync'
187
+
159
188
  // ─── Connector credential field (reusable render) ───────────────────────────
160
189
  // One connector credential field: label (i18n) + control (select|password|text)
161
190
  // + optional help. Shared by the unified config dialog for both the essential
@@ -195,12 +224,21 @@ function ConnectorCredentialFieldControl({
195
224
  connected,
196
225
  provider,
197
226
  onChange,
227
+ stored = false,
228
+ onReveal,
229
+ resetKey,
198
230
  }: {
199
231
  field: ConnectorCredentialField
200
232
  value: string
201
233
  connected: boolean
202
234
  provider: string
203
235
  onChange: (value: string) => void
236
+ /** The backend already holds a value for this field (secret or not). */
237
+ stored?: boolean
238
+ /** Fetches a stored secret's value (owner only); absent → no eye while locked. */
239
+ onReveal?: (key: string) => Promise<string>
240
+ /** Changes when the stored values were swapped (environment flipped): relock. */
241
+ resetKey?: string
204
242
  }) {
205
243
  const { t } = useTranslation()
206
244
  const st = useSetupT()
@@ -217,6 +255,55 @@ function ConnectorCredentialFieldControl({
217
255
  : ''
218
256
  const isSecret = isSecretCredential(field)
219
257
  const isDynamic = field.type === 'dynamic_select' || !!field.options_source
258
+ // A stored field opens LOCKED (pencil to edit, eye to view) so a value is
259
+ // never changed by accident; a fresh field is editable straight away.
260
+ const [editing, setEditing] = useState(false)
261
+ const [visible, setVisible] = useState(false)
262
+ const [revealed, setRevealed] = useState<string | null>(null)
263
+ const [revealing, setRevealing] = useState(false)
264
+ const [armed, setArmed] = useState(false)
265
+ const initial = useRef('')
266
+ const locked = stored && !editing
267
+ useEffect(() => {
268
+ setEditing(false)
269
+ setVisible(false)
270
+ setRevealed(null)
271
+ }, [resetKey])
272
+ const canEye = isSecret ? (locked ? !!onReveal : true) : false
273
+ const toggleEye = async () => {
274
+ if (visible) {
275
+ setVisible(false)
276
+ setRevealed(null)
277
+ return
278
+ }
279
+ if (locked && onReveal) {
280
+ setRevealing(true)
281
+ try {
282
+ setRevealed(await onReveal(field.key))
283
+ setVisible(true)
284
+ } catch {
285
+ setRevealed(null)
286
+ } finally {
287
+ setRevealing(false)
288
+ }
289
+ return
290
+ }
291
+ setVisible(true)
292
+ }
293
+ const startEdit = () => {
294
+ initial.current = value
295
+ if (isSecret) onChange('')
296
+ setVisible(false)
297
+ setRevealed(null)
298
+ setArmed(true)
299
+ setEditing(true)
300
+ requestAnimationFrame(() => document.getElementById(`${form.idPrefix}-cred-${field.key}`)?.focus())
301
+ }
302
+ const cancelEdit = () => {
303
+ onChange(initial.current)
304
+ setVisible(false)
305
+ setEditing(false)
306
+ }
220
307
  const error = form.errors[field.key]
221
308
  const mismatch = shapeMismatch(field, value, form.fields)
222
309
  const target = mismatch?.suggestedKey
@@ -259,23 +346,69 @@ function ConnectorCredentialFieldControl({
259
346
  </SelectContent>
260
347
  </Select>
261
348
  ) : (
262
- <Input
263
- id={`${form.idPrefix}-cred-${field.key}`}
264
- type={isSecret ? 'password' : 'text'}
265
- // A secret must never be offered to (or filled by) the browser's
266
- // password manager: "new-password" is the value browsers respect.
267
- autoComplete={isSecret ? 'new-password' : 'off'}
268
- data-1p-ignore={isSecret ? true : undefined}
269
- data-lpignore={isSecret ? 'true' : undefined}
270
- spellCheck={false}
271
- autoCapitalize='off'
272
- aria-invalid={!!error || undefined}
273
- aria-describedby={error ? `${form.idPrefix}-cred-${field.key}-error` : undefined}
274
- className={cn(error && 'border-destructive focus-visible:ring-destructive/40')}
275
- placeholder={connected && isSecret ? '••••••••' : ''}
276
- value={value}
277
- onChange={(e) => onChange(e.target.value)}
278
- />
349
+ <div className='flex items-center gap-1.5'>
350
+ <Input
351
+ id={`${form.idPrefix}-cred-${field.key}`}
352
+ name={`cfg_${field.key}`}
353
+ type={isSecret && !visible ? 'password' : 'text'}
354
+ // Browsers ignore autocomplete=off and fill the text field that
355
+ // precedes a password input; a field stays read-only until the user
356
+ // focuses it (and while locked) so nothing is filled behind their back.
357
+ autoComplete={isSecret ? 'new-password' : 'off'}
358
+ data-1p-ignore
359
+ data-lpignore='true'
360
+ data-form-type='other'
361
+ readOnly={locked || !armed}
362
+ onFocus={() => setArmed(true)}
363
+ spellCheck={false}
364
+ autoCapitalize='off'
365
+ aria-invalid={!!error || undefined}
366
+ aria-describedby={error ? `${form.idPrefix}-cred-${field.key}-error` : undefined}
367
+ className={cn(
368
+ error && 'border-destructive focus-visible:ring-destructive/40',
369
+ locked && 'bg-muted/40 text-muted-foreground',
370
+ )}
371
+ placeholder={(connected || stored) && isSecret ? '••••••••' : ''}
372
+ value={locked && isSecret ? (revealed ?? '') : value}
373
+ onChange={(e) => onChange(e.target.value)}
374
+ />
375
+ {canEye && (
376
+ <Button
377
+ type='button'
378
+ variant='ghost'
379
+ size='icon'
380
+ className='size-9 shrink-0'
381
+ disabled={revealing}
382
+ aria-label={visible ? st('installed_addons.field_hide', { defaultValue: 'Ocultar' }) : st('installed_addons.field_view', { defaultValue: 'Ver' })}
383
+ onClick={() => void toggleEye()}
384
+ >
385
+ {revealing ? <Loader2 className='size-4 animate-spin' /> : visible ? <EyeOff className='size-4' /> : <Eye className='size-4' />}
386
+ </Button>
387
+ )}
388
+ {locked ? (
389
+ <Button
390
+ type='button'
391
+ variant='ghost'
392
+ size='icon'
393
+ className='size-9 shrink-0'
394
+ aria-label={st('installed_addons.field_edit', { defaultValue: 'Editar' })}
395
+ onClick={startEdit}
396
+ >
397
+ <Pencil className='size-4' />
398
+ </Button>
399
+ ) : stored ? (
400
+ <Button
401
+ type='button'
402
+ variant='ghost'
403
+ size='icon'
404
+ className='size-9 shrink-0'
405
+ aria-label={st('installed_addons.field_cancel_edit', { defaultValue: 'Cancelar edición' })}
406
+ onClick={cancelEdit}
407
+ >
408
+ <X className='size-4' />
409
+ </Button>
410
+ ) : null}
411
+ </div>
279
412
  )}
280
413
  {error ? (
281
414
  <p id={`${form.idPrefix}-cred-${field.key}-error`} role='alert' className='text-xs text-destructive'>
@@ -287,7 +420,7 @@ function ConnectorCredentialFieldControl({
287
420
  {warning}
288
421
  </p>
289
422
  ) : null}
290
- {help ? <p className='text-xs text-muted-foreground'>{help}</p> : null}
423
+ {help ? <HelpText text={help} /> : null}
291
424
  </div>
292
425
  )
293
426
  }
@@ -459,12 +592,14 @@ export function AddonConfigSurface({
459
592
  onOpenChange,
460
593
  onSaved,
461
594
  canManageIssuer = true,
595
+ canRevealSecrets = false,
462
596
  activeBranch = null,
463
597
  ensureAddonBundle,
464
598
  notify = toast,
465
599
  client,
466
600
  expectedOptionKinds = NO_OPTION_KINDS,
467
601
  displayName,
602
+ onConnectOAuth,
468
603
  }: AddonConfigSurfaceProps) {
469
604
  const idPrefix = useId()
470
605
  const { t, i18n } = useTranslation()
@@ -498,8 +633,25 @@ export function AddonConfigSurface({
498
633
  const [formError, setFormError] = useState<string | null>(null)
499
634
  const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({})
500
635
  const errorRef = useRef<HTMLDivElement>(null)
636
+ // Results of the step actions (by block key) and whether the operator typed
637
+ // credentials not saved yet (an action tests what is STORED: it saves first).
638
+ const [blockResults, setBlockResults] = useState<Record<string, BlockResult | undefined>>({})
639
+ const [credDirty, setCredDirty] = useState(false)
640
+ // Credential keys the backend already holds (non-secret values + secrets_set).
641
+ const [storedKeys, setStoredKeys] = useState<Set<string>>(new Set())
642
+ // Credentials that differ between sandbox and production (served by /values) and
643
+ // the environment the stored values were loaded for: flipping the selector swaps them.
644
+ const envScoped = useRef<Set<string>>(new Set())
645
+ const loadedEnv = useRef<string | null>(null)
646
+ const envField = credFields.find(
647
+ (f) => f.type === 'select' && ['environment', 'mode', 'env'].includes(f.key),
648
+ )
649
+ const envValue = envField ? (credValues[envField.key] ?? '') : ''
650
+ const stepHeadingRef = useRef<HTMLHeadingElement>(null)
651
+ const stepMoved = useRef(false)
501
652
  const setCred = (key: string, val: string) => {
502
653
  setCredValues((v) => ({ ...v, [key]: val }))
654
+ setCredDirty(true)
503
655
  if (fieldErrors[key]) {
504
656
  setFieldErrors((e) => {
505
657
  const { [key]: _drop, ...rest } = e
@@ -550,8 +702,14 @@ export function AddonConfigSurface({
550
702
  }
551
703
  setCredValues(seed)
552
704
  setCurrentStep(0)
705
+ stepMoved.current = false
553
706
  setFormError(null)
554
707
  setFieldErrors({})
708
+ setBlockResults({})
709
+ setCredDirty(false)
710
+ setStoredKeys(new Set())
711
+ envScoped.current = new Set()
712
+ loadedEnv.current = null
555
713
  if (!canManageIssuer || !connector?.provider || credFields.length === 0) return
556
714
  let cancelled = false
557
715
  api
@@ -559,6 +717,12 @@ export function AddonConfigSurface({
559
717
  .then((res) => {
560
718
  const stored = (res.data?.data?.values ?? {}) as Record<string, string>
561
719
  if (cancelled) return
720
+ const secretsSet = (res.data?.data?.secrets_set ?? []) as string[]
721
+ envScoped.current = new Set((res.data?.data?.env_scoped ?? []) as string[])
722
+ if (envField) loadedEnv.current = stored[envField.key] ?? ''
723
+ setStoredKeys(
724
+ new Set([...Object.keys(stored).filter((k) => stored[k] !== ''), ...secretsSet]),
725
+ )
562
726
  // Only fields the user has not touched yet.
563
727
  setCredValues((prev) => {
564
728
  const next = { ...prev }
@@ -580,6 +744,37 @@ export function AddonConfigSurface({
580
744
  // eslint-disable-next-line react-hooks/exhaustive-deps
581
745
  }, [open, connector?.provider, canManageIssuer])
582
746
 
747
+ // Sandbox and production keep their own credentials: flipping the selector
748
+ // swaps the environment-scoped fields for the ones stored for that environment
749
+ // (locked when it has them, empty when it does not) instead of making the
750
+ // operator paste every key again. Nothing is saved until «Guardar».
751
+ useEffect(() => {
752
+ if (!open || !envField || !envValue || !canManageIssuer || !connector?.provider) return
753
+ if (loadedEnv.current === null || loadedEnv.current === envValue) return
754
+ let cancelled = false
755
+ api
756
+ .get(`/integrations/${connector.provider}/values?environment=${encodeURIComponent(envValue)}`)
757
+ .then((res) => {
758
+ if (cancelled) return
759
+ const stored = (res.data?.data?.values ?? {}) as Record<string, string>
760
+ const secretsSet = (res.data?.data?.secrets_set ?? []) as string[]
761
+ loadedEnv.current = envValue
762
+ setStoredKeys(new Set([...Object.keys(stored).filter((k) => stored[k] !== ''), ...secretsSet]))
763
+ setCredValues((prev) => {
764
+ const next = { ...prev }
765
+ for (const k of envScoped.current) next[k] = stored[k] ?? ''
766
+ return next
767
+ })
768
+ })
769
+ .catch(() => {
770
+ /* keep what is on screen */
771
+ })
772
+ return () => {
773
+ cancelled = true
774
+ }
775
+ // eslint-disable-next-line react-hooks/exhaustive-deps
776
+ }, [open, envValue])
777
+
583
778
  // Load stored settings values + definitions. The backend returns the
584
779
  // manifest's setting definitions alongside the stored values; fall back to
585
780
  // the manifest we already have so custom (declarative) addons whose lifecycle
@@ -617,12 +812,20 @@ export function AddonConfigSurface({
617
812
  const keys = [
618
813
  ...credFields.flatMap((f) => [f.label, f.description]),
619
814
  ...layoutSections.flatMap((sec) => [sec.title, sec.description]),
815
+ ...layoutSections.flatMap((sec) => (sec.blocks ?? []).flatMap((b) => [b.title, b.description, b.label])),
620
816
  ].filter((k): k is string => !!k)
621
817
  if (keys.length === 0 || keys.every((k) => i18n.exists(k))) return
622
818
  void ensureAddonBundle?.(connector.addon_key, i18n)
623
819
  // eslint-disable-next-line react-hooks/exhaustive-deps
624
820
  }, [open, connector?.addon_key, credFields.length])
625
821
 
822
+ // Section/step help: an i18n key or a literal sentence (never a raw key).
823
+ const addonText = (key?: string) => {
824
+ if (!key) return ''
825
+ const out = textOrFallback(t(key, { defaultValue: '' }), key, '')
826
+ return out || (/\s/.test(key) ? key : '')
827
+ }
828
+
626
829
  const credLabel = (f: ConnectorCredentialField) => {
627
830
  const fallback = humanizeKey(f.key)
628
831
  return f.label ? textOrFallback(t(f.label, { defaultValue: fallback }), f.label, fallback) : fallback
@@ -666,6 +869,7 @@ export function AddonConfigSurface({
666
869
  onSuccess: () => {
667
870
  setFormError(null)
668
871
  setFieldErrors({})
872
+ setCredDirty(false)
669
873
  notify.success(st('installed_addons.config_saved'))
670
874
  onOpenChange(false)
671
875
  onSaved?.()
@@ -698,8 +902,9 @@ export function AddonConfigSurface({
698
902
  }
699
903
  const sectionKey = credFields.find((f) => f.key === first)?.section
700
904
  if (sectionKey) {
701
- const idx = layoutSections.findIndex((sec) => sec.key === sectionKey)
702
- if (idx >= 0) setCurrentStep(idx)
905
+ // Index among the WIZARD steps (sections without fields/blocks are not steps).
906
+ const idx = wizardSteps.findIndex((sec) => sec.key === sectionKey)
907
+ if (idx >= 0) goToStep(idx)
703
908
  }
704
909
  window.setTimeout(() => {
705
910
  const el = document.getElementById(`${idPrefix}-cred-${first}`)
@@ -735,68 +940,78 @@ export function AddonConfigSurface({
735
940
  saveMutation.mutate()
736
941
  }
737
942
 
738
- // "Probar conexión": runs the connector's test_export health-check against the
739
- // SAVED credentials (connector_get reads what's stored), so it validates a
740
- // real round-trip to the provider without saving a stamp/order.
741
- const testMutation = useMutation({
742
- mutationFn: async () => {
743
- const res = await api.post(`/integrations/${connector?.provider}/test`, {})
744
- return res.data?.data as { ok?: boolean; message?: string } | undefined
745
- },
746
- onSuccess: (data) => {
747
- if (data?.ok) {
748
- notify.success(
749
- data.message ||
750
- st('installed_addons.test_ok', { defaultValue: 'Conexión válida' }),
751
- )
752
- } else {
753
- notify.error(
754
- data?.message ||
755
- st('installed_addons.test_failed', { defaultValue: 'No se pudo conectar' }),
756
- )
757
- }
758
- },
759
- onError: (err: any) =>
760
- notify.error(err.response?.data?.message || st('installed_addons.settings_error')),
761
- })
943
+ // Saves typed-but-unsaved credentials before an action runs: actions (and
944
+ // the connector test) read the STORED credentials, so testing what is on
945
+ // screen requires persisting it first. Returns an error message, or null.
946
+ const persistCredsIfDirty = async (): Promise<string | null> => {
947
+ if (!credDirty || !connector || !canManageIssuer) return null
948
+ const miss = missingRequired(credFields, credValues, !!connector.connected)
949
+ if (miss.length > 0) {
950
+ const errs: Record<string, string> = {}
951
+ for (const k of miss) errs[k] = st('installed_addons.field_required')
952
+ setFieldErrors(errs)
953
+ return st('installed_addons.missing_fields', {
954
+ fields: miss.map((k) => credLabel(credFields.find((f) => f.key === k)!)).join(', '),
955
+ })
956
+ }
957
+ const payload: Record<string, string> = {}
958
+ for (const [k, v] of Object.entries(credValues)) {
959
+ if (v != null && v !== '') payload[k] = v
960
+ }
961
+ await api.post(`/integrations/${connector.provider}`, payload)
962
+ setCredDirty(false)
963
+ onSaved?.()
964
+ return null
965
+ }
966
+
967
+ // Runs a step action: the implicit connection test (connector.test_export)
968
+ // or a declared action block (host route /blocks/:key/run). The result is
969
+ // shown inline (aria-live) with retry, never as a toast that disappears.
970
+ const runAction = async (block: ConnectorFormBlock): Promise<BlockResult> => {
971
+ const fail = st('blocks.failed')
972
+ try {
973
+ const pre = await persistCredsIfDirty()
974
+ if (pre) return { status: 'error', message: pre, details: [] }
975
+ if (block.key === SYNC_BLOCK_KEY) return await runSync()
976
+ const url =
977
+ block.key === TEST_BLOCK_KEY
978
+ ? `/integrations/${connector?.provider}/test`
979
+ : `/integrations/${connector?.provider}/blocks/${encodeURIComponent(block.key)}/run`
980
+ const res = await api.post(url, {})
981
+ return normalizeBlockResult(res.data, fail)
982
+ } catch (err) {
983
+ return { status: 'error', message: errorMessage(err, fail), details: [] }
984
+ }
985
+ }
986
+ const setResult = (key: string, r: BlockResult) => setBlockResults((prev) => ({ ...prev, [key]: r }))
762
987
 
763
988
  // "Sincronizar ahora": ops-native connectors with a sync worker (hub →
764
989
  // partner read-models) run one sync now and report the run summary.
765
- const syncMutation = useMutation({
766
- mutationFn: async () => {
767
- const res = await api.post(connector?.sync_endpoint ?? '', {})
768
- return res.data?.data as
769
- | {
770
- status?: string
771
- message?: string
772
- licenses?: { fetched?: number }
773
- instances?: { fetched?: number }
774
- accounts?: { fetched?: number }
775
- errors?: string[]
776
- }
777
- | undefined
778
- },
779
- onSuccess: (data) => {
780
- if (data?.status === 'skipped') {
781
- notify.info(data.message || st('installed_addons.sync_skipped'))
782
- return
783
- }
784
- const summary = st('installed_addons.sync_done', {
785
- licenses: data?.licenses?.fetched ?? 0,
786
- instances: data?.instances?.fetched ?? 0,
787
- accounts: data?.accounts?.fetched ?? 0,
788
- })
789
- if (data?.status === 'partial') {
790
- notify.warning(`${summary} · ${(data.errors ?? []).join('; ')}`)
791
- } else {
792
- notify.success(summary)
793
- }
794
- },
795
- onError: (err: unknown) => {
796
- const msg = (err as { response?: { data?: { message?: string } } })?.response?.data?.message
797
- notify.error(msg || st('installed_addons.sync_failed'))
798
- },
799
- })
990
+ const runSync = async (): Promise<BlockResult> => {
991
+ const res = await api.post(connector?.sync_endpoint ?? '', {})
992
+ const data = res.data?.data as
993
+ | {
994
+ status?: string
995
+ message?: string
996
+ licenses?: { fetched?: number }
997
+ instances?: { fetched?: number }
998
+ accounts?: { fetched?: number }
999
+ errors?: string[]
1000
+ }
1001
+ | undefined
1002
+ if (data?.status === 'skipped') {
1003
+ return { status: 'warn', message: data.message || st('installed_addons.sync_skipped'), details: [] }
1004
+ }
1005
+ const summary = st('installed_addons.sync_done', {
1006
+ licenses: data?.licenses?.fetched ?? 0,
1007
+ instances: data?.instances?.fetched ?? 0,
1008
+ accounts: data?.accounts?.fetched ?? 0,
1009
+ })
1010
+ if (data?.status === 'partial') {
1011
+ return { status: 'warn', message: `${summary} · ${(data.errors ?? []).join('; ')}`, details: [] }
1012
+ }
1013
+ return { status: 'ok', message: summary, details: [] }
1014
+ }
800
1015
 
801
1016
  const hasCredentials = credFields.length > 0
802
1017
  const hasSettings = definitions.length > 0
@@ -811,12 +1026,32 @@ export function AddonConfigSurface({
811
1026
  )
812
1027
  const canSync = !!connector?.sync_endpoint && !!connector?.connected
813
1028
 
1029
+ const revealSecret = async (key: string) => {
1030
+ try {
1031
+ const res = await api.get(
1032
+ `/integrations/${connector?.provider}/values/${encodeURIComponent(key)}/reveal${
1033
+ envValue ? `?environment=${encodeURIComponent(envValue)}` : ''
1034
+ }`,
1035
+ )
1036
+ return String(res.data?.data?.value ?? '')
1037
+ } catch (err) {
1038
+ notify.error(st('installed_addons.field_reveal_error', { defaultValue: 'No se pudo mostrar el valor.' }))
1039
+ throw err
1040
+ }
1041
+ }
1042
+ const storedProps = (key: string) => ({
1043
+ stored: storedKeys.has(key),
1044
+ resetKey: envValue,
1045
+ onReveal: canRevealSecrets ? revealSecret : undefined,
1046
+ })
1047
+
814
1048
  const renderCred = (f: ConnectorCredentialField) => (
815
1049
  <ConnectorCredentialFieldControl
816
1050
  key={f.key}
817
1051
  field={f}
818
1052
  connected={!!connector?.connected}
819
1053
  provider={connector?.provider ?? ''}
1054
+ {...storedProps(f.key)}
820
1055
  value={credValues[f.key] ?? ''}
821
1056
  onChange={(val) => setCred(f.key, val)}
822
1057
  />
@@ -949,36 +1184,148 @@ export function AddonConfigSurface({
949
1184
  </div>
950
1185
  )
951
1186
 
952
- // Wizard steps: credential sections that actually have fields, + a final
1187
+ // OAuth connectors have no credential form: the surface shows their state and
1188
+ // hands "Conectar cuenta" to the host (its OAuth redirect flow).
1189
+ const isOAuth = !!connector && !!connector.auth && connector.auth !== 'token'
1190
+ const oauthPanel = isOAuth ? (
1191
+ <section className='flex flex-col gap-3 rounded-lg border border-border/70 p-3'>
1192
+ <div className='flex flex-wrap items-center justify-between gap-2'>
1193
+ <h4 className='flex items-center gap-2 text-sm font-medium'>
1194
+ <Link2 aria-hidden='true' className='h-4 w-4 text-muted-foreground' />
1195
+ {st('oauth.title')}
1196
+ </h4>
1197
+ <StepStatusBadge
1198
+ status={connector!.connected ? 'ok' : 'pending'}
1199
+ label={connector!.connected ? st('oauth.connected') : st('oauth.not_connected')}
1200
+ />
1201
+ </div>
1202
+ <HelpText text={st('oauth.help')} />
1203
+ {onConnectOAuth ? (
1204
+ <Button
1205
+ type='button'
1206
+ variant={connector!.connected ? 'outline' : 'default'}
1207
+ className='h-auto min-h-11 w-full sm:w-fit'
1208
+ onClick={() => onConnectOAuth(connector!)}
1209
+ >
1210
+ {connector!.connected ? st('oauth.reconnect') : st('oauth.connect')}
1211
+ </Button>
1212
+ ) : null}
1213
+ </section>
1214
+ ) : null
1215
+
1216
+ // Wizard steps: form_layout sections with fields OR blocks, + a final
953
1217
  // "Ajustes" step when the addon also ships settings.
954
- const credSteps = stepMode
955
- ? layoutSections.filter((sec) => credFields.some((f) => f.section === sec.key))
1218
+ const wizardSteps = stepMode
1219
+ ? buildWizardSteps(
1220
+ layoutSections,
1221
+ credFields.map((f) => f.section),
1222
+ hasSettings,
1223
+ )
956
1224
  : []
957
- const wizardSteps = [
958
- ...credSteps.map((sec) => ({
959
- key: sec.key,
960
- title: sec.title,
961
- description: sec.description,
962
- kind: 'creds' as const,
963
- })),
964
- ...(stepMode && hasSettings
965
- ? [{ key: '__settings', title: 'installed_addons.section_settings', description: undefined, kind: 'settings' as const }]
966
- : []),
967
- ]
968
1225
  const totalSteps = wizardSteps.length
969
1226
  const useStepper = stepMode && totalSteps > 1
970
1227
  const stepIdx = Math.min(currentStep, Math.max(0, totalSteps - 1))
971
1228
  const activeStep = wizardSteps[stepIdx]
972
1229
  const isLastStep = stepIdx >= totalSteps - 1
973
1230
 
1231
+ // "Probar conexión" (connector.test_export) is a verification INSIDE the
1232
+ // flow (last credentials step / end of the credentials), not a footer
1233
+ // button — unless the addon already declares an action block for it.
1234
+ const implicitTest: ConnectorFormBlock | null =
1235
+ canTest && !hasExplicitTest(layoutSections, connector?.test_export)
1236
+ ? {
1237
+ key: TEST_BLOCK_KEY,
1238
+ kind: 'action',
1239
+ title: st('blocks.test_title'),
1240
+ description: st('blocks.test_help'),
1241
+ label: st('installed_addons.test_connection'),
1242
+ }
1243
+ : null
1244
+ const syncBlock: ConnectorFormBlock | null = canSync
1245
+ ? { key: SYNC_BLOCK_KEY, kind: 'action', title: st('blocks.sync_title'), label: st('installed_addons.sync_now') }
1246
+ : null
1247
+ const lastCredStep = (() => {
1248
+ for (let i = wizardSteps.length - 1; i >= 0; i--) if (wizardSteps[i].kind === 'creds') return wizardSteps[i].key
1249
+ return undefined
1250
+ })()
1251
+ const extraBlocks = [implicitTest, syncBlock].filter((b): b is ConnectorFormBlock => !!b)
1252
+ const blocksFor = (sectionKey: string, declared: ConnectorFormBlock[] = []) =>
1253
+ sectionKey === lastCredStep ? [...declared, ...extraBlocks] : declared
1254
+
1255
+ // Reading order inside a step: what the operator needs BEFORE typing
1256
+ // (instructions, the URL to paste in the provider's panel) goes above the
1257
+ // fields; verifications (actions) go below them.
1258
+ const leadBlocks = (blocks: ConnectorFormBlock[] = []) => blocks.filter((b) => b.kind !== 'action')
1259
+ const trailBlocks = (blocks: ConnectorFormBlock[] = []) => blocks.filter((b) => b.kind === 'action')
1260
+
1261
+ const renderBlocks = (blocks: ConnectorFormBlock[]) => (
1262
+ <ConnectorBlocks
1263
+ blocks={blocks}
1264
+ runAction={runAction}
1265
+ results={blockResults}
1266
+ onResult={setResult}
1267
+ actionsDisabled={!canManageIssuer}
1268
+ actionNote={credDirty ? st('blocks.save_first') : undefined}
1269
+ />
1270
+ )
1271
+
1272
+ const stepState = (i: number) => {
1273
+ const s = wizardSteps[i]
1274
+ return stepStatus({
1275
+ index: i,
1276
+ current: stepIdx,
1277
+ fieldKeys: s.kind === 'creds' ? credFields.filter((f) => f.section === s.key).map((f) => f.key) : [],
1278
+ fieldErrors,
1279
+ blockKeys: blocksFor(s.key, s.blocks).map((b) => b.key),
1280
+ results: blockResults,
1281
+ })
1282
+ }
1283
+
1284
+ // Moving between steps puts focus on the new step's heading (keyboard and
1285
+ // screen-reader users land on the content, not on the footer).
1286
+ const goToStep = (i: number) => {
1287
+ stepMoved.current = true
1288
+ setCurrentStep(i)
1289
+ }
1290
+ useEffect(() => {
1291
+ if (stepMoved.current) stepHeadingRef.current?.focus()
1292
+ }, [stepIdx])
1293
+
1294
+ // "Siguiente" checks the current step's required credentials first, so the
1295
+ // operator learns what is missing where it is, not at the end.
1296
+ const handleNext = () => {
1297
+ if (activeStep?.kind === 'creds' && connector && canManageIssuer) {
1298
+ const stepFields = credFields.filter((f) => f.section === activeStep.key)
1299
+ const miss = missingRequired(stepFields, credValues, !!connector.connected)
1300
+ if (miss.length > 0) {
1301
+ const errs: Record<string, string> = {}
1302
+ for (const k of miss) errs[k] = st('installed_addons.field_required')
1303
+ setFieldErrors(errs)
1304
+ setFormError(
1305
+ st('installed_addons.missing_fields', {
1306
+ fields: miss.map((k) => credLabel(credFields.find((f) => f.key === k)!)).join(', '),
1307
+ }),
1308
+ )
1309
+ focusFirstInvalid(miss)
1310
+ return
1311
+ }
1312
+ }
1313
+ setFormError(null)
1314
+ goToStep(stepIdx + 1)
1315
+ }
1316
+
1317
+ const hasAnyBlocks = layoutSections.some((s) => (s.blocks?.length ?? 0) > 0) || extraBlocks.length > 0
1318
+ const nothingToConfigure = !hasCredentials && !hasSettings && !isOAuth && !hasAnyBlocks
1319
+ const nothingToSave = !hasCredentials && !hasSettings
1320
+
974
1321
  return (
975
1322
  <Dialog open={open} onOpenChange={onOpenChange}>
976
- <DialogContent className='flex max-h-[85vh] flex-col'>
1323
+ <DialogContent className='flex max-h-[85vh] flex-col max-sm:max-h-[calc(100dvh-1rem)] max-sm:gap-3 max-sm:p-4'>
977
1324
  <ConnectorFormStateContext.Provider
978
1325
  value={{ fields: credFields, errors: fieldErrors, idPrefix, client: api, expectedOptionKinds }}
979
1326
  >
980
- <DialogHeader className='shrink-0'>
981
- <DialogTitle>
1327
+ <DialogHeader className='shrink-0 pe-8 text-start'>
1328
+ <DialogTitle className='leading-snug'>
982
1329
  {st('installed_addons.configure_title', { name: displayName ?? addon.manifest.display_name ?? addon.manifest.name })}
983
1330
  </DialogTitle>
984
1331
  <DialogDescription>
@@ -986,7 +1333,7 @@ export function AddonConfigSurface({
986
1333
  </DialogDescription>
987
1334
  </DialogHeader>
988
1335
 
989
- <div className='-mr-2 flex flex-col gap-6 overflow-y-auto py-2 pr-2'>
1336
+ <div className='-mr-2 flex min-h-0 flex-col gap-6 overflow-y-auto py-2 pr-2'>
990
1337
  {loading ? (
991
1338
  <div className='flex justify-center py-8'>
992
1339
  <Loader2 className='h-5 w-5 animate-spin text-muted-foreground' />
@@ -994,42 +1341,60 @@ export function AddonConfigSurface({
994
1341
  ) : useStepper ? (
995
1342
  /* WIZARD por pasos: indicador + un paso a la vez (sin card-in-card). */
996
1343
  <div className='flex flex-col gap-5'>
997
- {/* Pro stepper: filled progress line + check on done + ringed active,
998
- no inline labels (never wraps); the active step title sits below. */}
999
- <div className='flex flex-col gap-2.5'>
1344
+ {/* Stepper: 44px targets, a check on done steps, an alert on a
1345
+ step with errors; the step title wraps (never truncated). */}
1346
+ <nav aria-label={st('wizard.steps')} className='flex flex-col gap-2'>
1000
1347
  <ol className='flex items-center'>
1001
1348
  {wizardSteps.map((s, i) => {
1002
- const done = i < stepIdx
1349
+ const status = stepState(i)
1003
1350
  const active = i === stepIdx
1351
+ const title = t(s.title ?? '', { defaultValue: humanizeKey(s.title) })
1004
1352
  return (
1005
1353
  <li
1006
1354
  key={s.key}
1007
- className={cn(
1008
- 'flex items-center',
1009
- i < wizardSteps.length - 1 && 'flex-1',
1010
- )}
1355
+ className={cn('flex items-center', i < wizardSteps.length - 1 && 'flex-1')}
1011
1356
  >
1012
1357
  <button
1013
1358
  type='button'
1014
- onClick={() => setCurrentStep(i)}
1015
- title={t(s.title ?? '', { defaultValue: humanizeKey(s.title) })}
1359
+ onClick={() => goToStep(i)}
1016
1360
  aria-current={active ? 'step' : undefined}
1017
- className={cn(
1018
- 'flex h-7 w-7 shrink-0 items-center justify-center rounded-full border text-[11px] font-semibold transition-all',
1019
- active
1020
- ? 'border-primary bg-primary text-primary-foreground ring-4 ring-primary/15'
1021
- : done
1022
- ? 'border-primary bg-primary/10 text-primary'
1023
- : 'border-border text-muted-foreground',
1024
- )}
1361
+ aria-label={st('wizard.step_label', {
1362
+ n: i + 1,
1363
+ total: totalSteps,
1364
+ title,
1365
+ status: st(`status.${status}`),
1366
+ })}
1367
+ data-step-status={status}
1368
+ className='flex h-11 w-11 shrink-0 items-center justify-center rounded-full focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring'
1025
1369
  >
1026
- {done ? <Check className='h-3.5 w-3.5' /> : i + 1}
1370
+ <span
1371
+ aria-hidden='true'
1372
+ className={cn(
1373
+ 'flex h-8 w-8 items-center justify-center rounded-full border text-xs font-semibold transition-all',
1374
+ active
1375
+ ? 'border-primary bg-primary text-primary-foreground ring-4 ring-primary/15'
1376
+ : status === 'error'
1377
+ ? 'border-destructive bg-destructive/10 text-destructive'
1378
+ : status === 'ok'
1379
+ ? 'border-primary bg-primary/10 text-primary'
1380
+ : 'border-border text-muted-foreground',
1381
+ )}
1382
+ >
1383
+ {!active && status === 'error' ? (
1384
+ <AlertCircle className='h-4 w-4' />
1385
+ ) : !active && status === 'ok' ? (
1386
+ <Check className='h-4 w-4' />
1387
+ ) : (
1388
+ i + 1
1389
+ )}
1390
+ </span>
1027
1391
  </button>
1028
1392
  {i < wizardSteps.length - 1 && (
1029
1393
  <span
1394
+ aria-hidden='true'
1030
1395
  className={cn(
1031
- 'mx-1.5 h-0.5 flex-1 rounded-full transition-colors',
1032
- done ? 'bg-primary' : 'bg-border',
1396
+ 'mx-1 h-0.5 flex-1 rounded-full transition-colors',
1397
+ i < stepIdx ? 'bg-primary' : 'bg-border',
1033
1398
  )}
1034
1399
  />
1035
1400
  )}
@@ -1037,35 +1402,45 @@ export function AddonConfigSurface({
1037
1402
  )
1038
1403
  })}
1039
1404
  </ol>
1040
- <div className='flex items-baseline justify-between gap-2'>
1041
- <h4 className='truncate text-sm font-semibold'>
1405
+ <div className='flex items-start justify-between gap-3'>
1406
+ <h3
1407
+ ref={stepHeadingRef}
1408
+ tabIndex={-1}
1409
+ className='min-w-0 text-base leading-snug font-semibold break-words outline-none'
1410
+ >
1042
1411
  {t(activeStep?.title ?? '', {
1043
1412
  defaultValue: humanizeKey(activeStep?.title),
1044
1413
  })}
1045
- </h4>
1046
- <span className='shrink-0 text-[11px] font-medium tabular-nums text-muted-foreground'>
1047
- {stepIdx + 1} / {totalSteps}
1414
+ </h3>
1415
+ <span className='mt-0.5 shrink-0 text-xs font-medium tabular-nums text-muted-foreground'>
1416
+ {st('flow.step_of', { n: stepIdx + 1, total: totalSteps })}
1048
1417
  </span>
1049
1418
  </div>
1050
- </div>
1419
+ </nav>
1051
1420
 
1052
- <div className='flex flex-col gap-3'>
1421
+ <div className='flex flex-col gap-4'>
1053
1422
  {activeStep?.description && (
1054
- <p className='text-xs text-muted-foreground'>
1055
- {t(activeStep.description, { defaultValue: '' })}
1056
- </p>
1423
+ <HelpText text={addonText(activeStep.description)} />
1424
+ )}
1425
+ {activeStep?.kind === 'settings' ? (
1426
+ settingsBody
1427
+ ) : !canManageIssuer ? (
1428
+ <>
1429
+ {issuerAdminNote}
1430
+ {renderBlocks(blocksFor(activeStep?.key ?? '', activeStep?.blocks))}
1431
+ </>
1432
+ ) : (
1433
+ <>
1434
+ {renderBlocks(leadBlocks(blocksFor(activeStep?.key ?? '', activeStep?.blocks)))}
1435
+ {credFields.filter((f) => f.section === activeStep?.key).map(renderCred)}
1436
+ {renderBlocks(trailBlocks(blocksFor(activeStep?.key ?? '', activeStep?.blocks)))}
1437
+ </>
1057
1438
  )}
1058
- {activeStep?.kind === 'settings'
1059
- ? settingsBody
1060
- : !canManageIssuer
1061
- ? issuerAdminNote
1062
- : credFields
1063
- .filter((f) => f.section === activeStep?.key)
1064
- .map(renderCred)}
1065
1439
  </div>
1066
1440
  </div>
1067
1441
  ) : (
1068
1442
  <>
1443
+ {oauthPanel}
1069
1444
  {/* Credenciales */}
1070
1445
  {hasCredentials && (
1071
1446
  <section className='flex flex-col gap-3'>
@@ -1081,34 +1456,35 @@ export function AddonConfigSurface({
1081
1456
  // form_layout: one titled group per section, in declared order.
1082
1457
  layoutSections.map((sec) => {
1083
1458
  const fields = credFields.filter((f) => f.section === sec.key)
1084
- if (fields.length === 0) return null
1459
+ if (fields.length === 0 && (sec.blocks?.length ?? 0) === 0) return null
1085
1460
  return (
1086
1461
  <div
1087
1462
  key={sec.key}
1088
1463
  className='flex flex-col gap-3 rounded-md border border-border/60 px-3 py-3'
1089
1464
  >
1090
1465
  {sec.title && (
1091
- <div>
1466
+ <div className='flex flex-col gap-1'>
1092
1467
  <h4 className='text-sm font-medium'>
1093
1468
  {t(sec.title, { defaultValue: sec.title })}
1094
1469
  </h4>
1095
1470
  {sec.description && (
1096
- <p className='text-xs text-muted-foreground'>
1097
- {t(sec.description, { defaultValue: '' })}
1098
- </p>
1471
+ <HelpText text={addonText(sec.description)} />
1099
1472
  )}
1100
1473
  </div>
1101
1474
  )}
1475
+ {renderBlocks(leadBlocks(sec.blocks))}
1102
1476
  {fields.map((f) => (
1103
1477
  <ConnectorCredentialFieldControl
1104
1478
  key={f.key}
1105
1479
  field={f}
1106
1480
  connected={!!connector?.connected}
1107
1481
  provider={connector?.provider ?? ''}
1482
+ {...storedProps(f.key)}
1108
1483
  value={credValues[f.key] ?? ''}
1109
1484
  onChange={(val) => setCred(f.key, val)}
1110
1485
  />
1111
1486
  ))}
1487
+ {renderBlocks(trailBlocks(sec.blocks))}
1112
1488
  </div>
1113
1489
  )
1114
1490
  })
@@ -1120,6 +1496,7 @@ export function AddonConfigSurface({
1120
1496
  field={f}
1121
1497
  connected={!!connector?.connected}
1122
1498
  provider={connector?.provider ?? ''}
1499
+ {...storedProps(f.key)}
1123
1500
  value={credValues[f.key] ?? ''}
1124
1501
  onChange={(val) => setCred(f.key, val)}
1125
1502
  />
@@ -1129,7 +1506,7 @@ export function AddonConfigSurface({
1129
1506
  className='rounded-md border border-border/60 px-3 py-2'
1130
1507
  open={advancedFields.some((f) => !!fieldErrors[f.key]) || undefined}
1131
1508
  >
1132
- <summary className='cursor-pointer select-none text-sm font-medium text-muted-foreground'>
1509
+ <summary className='flex min-h-11 cursor-pointer items-center text-sm font-medium text-muted-foreground select-none sm:min-h-8'>
1133
1510
  {st('installed_addons.advanced')}
1134
1511
  </summary>
1135
1512
  <div className='flex flex-col gap-3 pt-3'>
@@ -1139,6 +1516,7 @@ export function AddonConfigSurface({
1139
1516
  field={f}
1140
1517
  connected={!!connector?.connected}
1141
1518
  provider={connector?.provider ?? ''}
1519
+ {...storedProps(f.key)}
1142
1520
  value={credValues[f.key] ?? ''}
1143
1521
  onChange={(val) => setCred(f.key, val)}
1144
1522
  />
@@ -1151,6 +1529,9 @@ export function AddonConfigSurface({
1151
1529
  </section>
1152
1530
  )}
1153
1531
 
1532
+ {/* Verificación (probar conexión / sincronizar) al final de las credenciales. */}
1533
+ {extraBlocks.length > 0 && renderBlocks(extraBlocks)}
1534
+
1154
1535
  {/* Ajustes */}
1155
1536
  {hasSettings && (
1156
1537
  <section className='flex flex-col gap-3'>
@@ -1165,10 +1546,11 @@ export function AddonConfigSurface({
1165
1546
  </section>
1166
1547
  )}
1167
1548
 
1168
- {!hasCredentials && !hasSettings && (
1169
- <p className='text-sm text-muted-foreground'>
1170
- {st('installed_addons.no_settings')}
1171
- </p>
1549
+ {nothingToConfigure && (
1550
+ <div className='flex flex-col items-start gap-1 rounded-lg border border-dashed p-4'>
1551
+ <p className='text-sm font-medium'>{st('empty.title')}</p>
1552
+ <HelpText text={st('empty.help')} />
1553
+ </div>
1172
1554
  )}
1173
1555
  </>
1174
1556
  )}
@@ -1184,79 +1566,45 @@ export function AddonConfigSurface({
1184
1566
  </div>
1185
1567
  ) : null}
1186
1568
 
1187
- <DialogFooter className='shrink-0 sm:justify-between'>
1188
- {canTest ? (
1189
- <Button
1190
- variant='outline'
1191
- onClick={() => testMutation.mutate()}
1192
- disabled={testMutation.isPending}
1193
- className='gap-2'
1194
- >
1195
- {testMutation.isPending ? (
1196
- <Loader2 className='h-4 w-4 animate-spin' />
1197
- ) : testMutation.data?.ok ? (
1198
- <CheckCircle2 className='h-4 w-4 text-emerald-500' />
1199
- ) : testMutation.isError ||
1200
- (testMutation.data && !testMutation.data.ok) ? (
1201
- <XCircle className='h-4 w-4 text-destructive' />
1202
- ) : (
1203
- <Plug className='h-4 w-4' />
1204
- )}
1205
- {st('installed_addons.test_connection', {
1206
- defaultValue: 'Probar conexión',
1207
- })}
1569
+ {/* Footer: always visible (outside the scroll). ONE primary action
1570
+ (Siguiente / Guardar) full width on phones, Atrás + Cancelar
1571
+ sharing the row below; a single right-aligned row from sm up.
1572
+ Verifications live inside the steps, not here. */}
1573
+ <DialogFooter
1574
+ data-wizard-footer=''
1575
+ 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'
1576
+ >
1577
+ {nothingToSave ? (
1578
+ <Button className='col-span-2 h-11 sm:h-9' onClick={() => onOpenChange(false)}>
1579
+ {st('common.close')}
1208
1580
  </Button>
1209
1581
  ) : (
1210
- <span />
1211
- )}
1212
- {canSync ? (
1213
- <Button
1214
- variant='outline'
1215
- onClick={() => syncMutation.mutate()}
1216
- disabled={syncMutation.isPending}
1217
- className='gap-2'
1218
- >
1219
- {syncMutation.isPending ? (
1220
- <Loader2 className='h-4 w-4 animate-spin' />
1221
- ) : (
1222
- <RefreshCw className='h-4 w-4' />
1223
- )}
1224
- {st('installed_addons.sync_now', { defaultValue: 'Sincronizar ahora' })}
1225
- </Button>
1226
- ) : null}
1227
- <div className='flex gap-2'>
1228
- {useStepper && stepIdx > 0 && (
1582
+ <>
1229
1583
  <Button
1230
- variant='outline'
1231
- onClick={() => setCurrentStep((s) => Math.max(0, s - 1))}
1584
+ className='order-first col-span-2 h-11 sm:order-last sm:h-9'
1585
+ onClick={useStepper && !isLastStep ? handleNext : handleSave}
1586
+ disabled={!(useStepper && !isLastStep) && (saveMutation.isPending || loading)}
1232
1587
  >
1233
- {st('common.back', { defaultValue: 'Atrás' })}
1588
+ {saveMutation.isPending && <Loader2 className='mr-2 h-4 w-4 animate-spin' />}
1589
+ {useStepper && !isLastStep ? st('common.next') : st('common.save')}
1234
1590
  </Button>
1235
- )}
1236
- <Button variant='outline' onClick={() => onOpenChange(false)}>
1237
- {st('common.cancel')}
1238
- </Button>
1239
- {useStepper && !isLastStep ? (
1240
- <Button onClick={() => setCurrentStep((s) => s + 1)}>
1241
- {st('common.next', { defaultValue: 'Siguiente' })}
1242
- </Button>
1243
- ) : (
1591
+ {useStepper && stepIdx > 0 && (
1592
+ <Button variant='outline' className='h-11 sm:h-9' onClick={() => goToStep(Math.max(0, stepIdx - 1))}>
1593
+ {st('common.back')}
1594
+ </Button>
1595
+ )}
1244
1596
  <Button
1245
- onClick={handleSave}
1246
- disabled={
1247
- saveMutation.isPending || loading || (!hasCredentials && !hasSettings)
1248
- }
1597
+ variant='ghost'
1598
+ className={cn('h-11 sm:order-first sm:h-9', !(useStepper && stepIdx > 0) && 'col-span-2')}
1599
+ onClick={() => onOpenChange(false)}
1249
1600
  >
1250
- {saveMutation.isPending && (
1251
- <Loader2 className='mr-2 h-4 w-4 animate-spin' />
1252
- )}
1253
- {st('common.save')}
1601
+ {st('common.cancel')}
1254
1602
  </Button>
1255
- )}
1256
- </div>
1603
+ </>
1604
+ )}
1257
1605
  </DialogFooter>
1258
1606
  </ConnectorFormStateContext.Provider>
1259
1607
  </DialogContent>
1260
1608
  </Dialog>
1261
1609
  )
1262
- }
1610
+ }