@asteby/metacore-runtime-react 53.10.1 → 53.11.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.
Files changed (36) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/dist/dynamic-form.d.ts +10 -1
  3. package/dist/dynamic-form.d.ts.map +1 -1
  4. package/dist/dynamic-form.js +6 -6
  5. package/dist/dynamic-relation-helpers.d.ts +51 -0
  6. package/dist/dynamic-relation-helpers.d.ts.map +1 -1
  7. package/dist/dynamic-relation-helpers.js +139 -2
  8. package/dist/dynamic-relation.d.ts +16 -0
  9. package/dist/dynamic-relation.d.ts.map +1 -1
  10. package/dist/dynamic-relation.js +205 -12
  11. package/dist/dynamic-relations.d.ts.map +1 -1
  12. package/dist/dynamic-relations.js +1 -1
  13. package/dist/relation-gallery.d.ts +31 -0
  14. package/dist/relation-gallery.d.ts.map +1 -0
  15. package/dist/relation-gallery.js +154 -0
  16. package/dist/setup/addon-config-surface.d.ts +6 -0
  17. package/dist/setup/addon-config-surface.d.ts.map +1 -1
  18. package/dist/setup/addon-config-surface.js +24 -14
  19. package/dist/setup/connector-form-model.d.ts +28 -0
  20. package/dist/setup/connector-form-model.d.ts.map +1 -1
  21. package/dist/setup/connector-form-model.js +26 -0
  22. package/dist/upload-field.d.ts +19 -1
  23. package/dist/upload-field.d.ts.map +1 -1
  24. package/dist/upload-field.js +50 -3
  25. package/package.json +1 -1
  26. package/src/__tests__/relation-gallery-helpers.test.ts +125 -0
  27. package/src/__tests__/relation-gallery.test.tsx +170 -0
  28. package/src/dynamic-form.tsx +20 -2
  29. package/src/dynamic-relation-helpers.ts +171 -2
  30. package/src/dynamic-relation.tsx +257 -14
  31. package/src/dynamic-relations.tsx +1 -0
  32. package/src/relation-gallery.tsx +488 -0
  33. package/src/setup/addon-config-surface.tsx +33 -17
  34. package/src/setup/connector-conditional-fields.test.ts +58 -0
  35. package/src/setup/connector-form-model.ts +69 -0
  36. package/src/upload-field.tsx +60 -2
@@ -0,0 +1,488 @@
1
+ // RelationGallery — the thumbnail-grid view of a one_to_many relation whose
2
+ // image column declares `display_config.gallery: true` (e.g. a product's
3
+ // ProductImage rows). Opt-in: DynamicRelation keeps its table for every other
4
+ // relation. Pure UI over callbacks — DynamicRelation owns the API calls, so the
5
+ // `/upload` and `/data` contracts are the ones the table already uses.
6
+ //
7
+ // - Add several photos at once (picker or drag & drop), one progress bar,
8
+ // preview, error and retry per file; type/size limits with clear messages.
9
+ // - Reorder by dragging (pointer or keyboard: Space to lift, arrows to move)
10
+ // or with the explicit move buttons; the first image is the main one.
11
+ // - Delete asks for confirmation, then offers «Deshacer» for a few seconds.
12
+ // - Theme tokens only (bg-card, border, muted…) so it follows dark mode.
13
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
14
+ import { useTranslation } from 'react-i18next'
15
+ import {
16
+ DndContext,
17
+ KeyboardSensor,
18
+ PointerSensor,
19
+ closestCenter,
20
+ useSensor,
21
+ useSensors,
22
+ type DragEndEvent,
23
+ } from '@dnd-kit/core'
24
+ import {
25
+ SortableContext,
26
+ arrayMove,
27
+ rectSortingStrategy,
28
+ sortableKeyboardCoordinates,
29
+ useSortable,
30
+ } from '@dnd-kit/sortable'
31
+ import { CSS } from '@dnd-kit/utilities'
32
+ import { cn } from '@asteby/metacore-ui/lib'
33
+ import { Button } from '@asteby/metacore-ui/primitives'
34
+ import { ArrowLeft, ArrowRight, ImagePlus, Loader2, Pencil, RotateCcw, Star, Trash2, X } from 'lucide-react'
35
+ import { validateUploadFile } from './upload-field'
36
+
37
+ export interface GalleryUploadProgress {
38
+ (fraction: number): void
39
+ }
40
+
41
+ export interface RelationGalleryProps {
42
+ rows: Record<string, any>[]
43
+ rowKey: (row: Record<string, any>, index: number) => string
44
+ imageKey: string
45
+ /** Optional caption column (alt text). */
46
+ captionKey?: string
47
+ getImageUrl: (path: string) => string
48
+ accept?: string
49
+ maxSize?: number
50
+ canCreate?: boolean
51
+ canEdit?: boolean
52
+ /** Reorder / «Hacer principal» (needs a position column). Default = canEdit. */
53
+ canReorder?: boolean
54
+ canDelete?: boolean
55
+ /** Uploads one file and creates its row at gallery index `offset` past the end. */
56
+ onUpload: (file: File, offset: number, onProgress: GalleryUploadProgress, reuseUrl?: string) => Promise<void>
57
+ /** All uploads of one batch finished (refresh the list). */
58
+ onUploadsSettled?: () => void
59
+ /** New order of the rows (persist positions). */
60
+ onReorder: (ordered: Record<string, any>[]) => Promise<void> | void
61
+ onEdit?: (row: Record<string, any>) => void
62
+ /** Asks for confirmation and deletes (with undo) — owned by the host. */
63
+ onDelete?: (row: Record<string, any>) => void
64
+ /** Keys of rows pending deletion (hidden while «Deshacer» is offered). */
65
+ hiddenKeys?: Set<string>
66
+ }
67
+
68
+ interface UploadItem {
69
+ id: string
70
+ file: File
71
+ preview: string
72
+ progress: number
73
+ status: 'uploading' | 'error' | 'done'
74
+ error?: string
75
+ offset: number
76
+ /** Stored file of a failed row create — a retry reuses it. */
77
+ uploadedUrl?: string
78
+ }
79
+
80
+ let uploadSeq = 0
81
+
82
+ export function RelationGallery({
83
+ rows,
84
+ rowKey,
85
+ imageKey,
86
+ captionKey,
87
+ getImageUrl,
88
+ accept = 'image/*',
89
+ maxSize,
90
+ canCreate = true,
91
+ canEdit = true,
92
+ canReorder,
93
+ canDelete = true,
94
+ onUpload,
95
+ onUploadsSettled,
96
+ onReorder,
97
+ onEdit,
98
+ onDelete,
99
+ hiddenKeys,
100
+ }: RelationGalleryProps) {
101
+ const { t } = useTranslation()
102
+ const inputRef = useRef<HTMLInputElement>(null)
103
+ const [dragOver, setDragOver] = useState(false)
104
+ const [uploads, setUploads] = useState<UploadItem[]>([])
105
+ const reorderable = canReorder ?? canEdit
106
+ // Every local preview is released when its item goes away or on unmount.
107
+ const uploadsRef = useRef<UploadItem[]>([])
108
+ uploadsRef.current = uploads
109
+ const releasePreview = (u: UploadItem) => {
110
+ if (u.preview) URL.revokeObjectURL?.(u.preview)
111
+ }
112
+
113
+ const keyed = useMemo(
114
+ () =>
115
+ rows
116
+ .map((row, i) => ({ row, key: rowKey(row, i) }))
117
+ .filter((r) => !hiddenKeys?.has(r.key)),
118
+ [rows, rowKey, hiddenKeys],
119
+ )
120
+ const ids = useMemo(() => keyed.map((k) => k.key), [keyed])
121
+
122
+ useEffect(() => () => uploadsRef.current.forEach(releasePreview), [])
123
+
124
+ const sensors = useSensors(
125
+ useSensor(PointerSensor, { activationConstraint: { distance: 6 } }),
126
+ useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
127
+ )
128
+
129
+ const move = useCallback(
130
+ (from: number, to: number) => {
131
+ if (from === to || to < 0 || to >= keyed.length) return
132
+ void onReorder(arrayMove(keyed, from, to).map((k) => k.row))
133
+ },
134
+ [keyed, onReorder],
135
+ )
136
+
137
+ const handleDragEnd = useCallback(
138
+ (e: DragEndEvent) => {
139
+ if (!e.over || e.active.id === e.over.id) return
140
+ move(ids.indexOf(String(e.active.id)), ids.indexOf(String(e.over.id)))
141
+ },
142
+ [ids, move],
143
+ )
144
+
145
+ const runUpload = useCallback(
146
+ async (item: UploadItem) => {
147
+ setUploads((list) => list.map((u) => (u.id === item.id ? { ...u, status: 'uploading', progress: 0, error: undefined } : u)))
148
+ try {
149
+ await onUpload(
150
+ item.file,
151
+ item.offset,
152
+ (fraction) =>
153
+ setUploads((list) => list.map((u) => (u.id === item.id ? { ...u, progress: Math.max(0, Math.min(1, fraction)) } : u))),
154
+ item.uploadedUrl,
155
+ )
156
+ setUploads((list) => list.map((u) => (u.id === item.id ? { ...u, status: 'done', progress: 1 } : u)))
157
+ return true
158
+ } catch (err: any) {
159
+ const msg =
160
+ err?.response?.data?.message ||
161
+ err?.message ||
162
+ t('dynamic.gallery.upload_failed', { defaultValue: 'No se pudo subir la foto.' })
163
+ const stored = typeof err?.uploadedUrl === 'string' ? err.uploadedUrl : item.uploadedUrl
164
+ setUploads((list) => list.map((u) => (u.id === item.id ? { ...u, status: 'error', error: String(msg), uploadedUrl: stored } : u)))
165
+ return false
166
+ }
167
+ },
168
+ [onUpload, t],
169
+ )
170
+
171
+ const addFiles = useCallback(
172
+ async (files: FileList | File[] | null | undefined) => {
173
+ const picked = Array.from(files ?? [])
174
+ if (picked.length === 0) return
175
+ const accepted: UploadItem[] = []
176
+ const rejected: UploadItem[] = []
177
+ for (const file of picked) {
178
+ const item: UploadItem = {
179
+ id: `up-${++uploadSeq}`,
180
+ file,
181
+ preview: typeof URL !== 'undefined' && URL.createObjectURL ? URL.createObjectURL(file) : '',
182
+ progress: 0,
183
+ status: 'uploading',
184
+ offset: accepted.length,
185
+ }
186
+ const bad = validateUploadFile(file, { accept, maxSize })
187
+ if (bad === 'type') {
188
+ rejected.push({ ...item, status: 'error', error: t('dynamic.gallery.invalid_type', { defaultValue: 'Formato no permitido. Usa JPG, PNG o WebP.' }) })
189
+ } else if (bad === 'size') {
190
+ const mb = ((maxSize ?? 0) / (1024 * 1024)).toFixed(1)
191
+ rejected.push({ ...item, status: 'error', error: t('dynamic.gallery.too_large', { mb, defaultValue: `La foto pesa más de ${mb} MB.` }) })
192
+ } else {
193
+ accepted.push(item)
194
+ }
195
+ }
196
+ setUploads((list) => {
197
+ list.filter((u) => u.status === 'done').forEach(releasePreview)
198
+ return [...list.filter((u) => u.status !== 'done'), ...accepted, ...rejected]
199
+ })
200
+ // Sequential: keeps positions in pick order and spares the server.
201
+ let any = false
202
+ for (const item of accepted) {
203
+ if (await runUpload(item)) any = true
204
+ }
205
+ if (any) onUploadsSettled?.()
206
+ },
207
+ [accept, maxSize, runUpload, onUploadsSettled, t],
208
+ )
209
+
210
+ const retry = useCallback(
211
+ async (item: UploadItem) => {
212
+ if (await runUpload({ ...item, offset: 0 })) onUploadsSettled?.()
213
+ },
214
+ [runUpload, onUploadsSettled],
215
+ )
216
+
217
+ const dismiss = useCallback((id: string) => {
218
+ setUploads((list) => {
219
+ const gone = list.find((u) => u.id === id)
220
+ if (gone) releasePreview(gone)
221
+ return list.filter((u) => u.id !== id)
222
+ })
223
+ }, [])
224
+
225
+ const pending = uploads.filter((u) => u.status !== 'done')
226
+ // A retry numbers its photo past the rows already refreshed; while a batch
227
+ // is still uploading that list is stale, so retry waits for it.
228
+ const busy = uploads.some((u) => u.status === 'uploading')
229
+ const hintId = useMemo(() => `gallery-hint-${++uploadSeq}`, [])
230
+ const mainLabel = t('dynamic.gallery.main', { defaultValue: 'Principal' })
231
+
232
+ return (
233
+ <div className="grid gap-3" data-relation-view="gallery">
234
+ {canCreate && (
235
+ <div
236
+ role="button"
237
+ tabIndex={0}
238
+ aria-label={t('dynamic.gallery.add', { defaultValue: 'Agregar fotos' })}
239
+ aria-describedby={hintId}
240
+ onClick={() => inputRef.current?.click()}
241
+ onKeyDown={(e) => {
242
+ if (e.key === 'Enter' || e.key === ' ') {
243
+ e.preventDefault()
244
+ inputRef.current?.click()
245
+ }
246
+ }}
247
+ onDragOver={(e) => {
248
+ e.preventDefault()
249
+ setDragOver(true)
250
+ }}
251
+ onDragLeave={() => setDragOver(false)}
252
+ onDrop={(e) => {
253
+ e.preventDefault()
254
+ setDragOver(false)
255
+ void addFiles(e.dataTransfer?.files)
256
+ }}
257
+ className={cn(
258
+ 'flex cursor-pointer flex-col items-center justify-center gap-1 rounded-lg border-2 border-dashed border-muted-foreground/30 px-4 py-6 text-center text-sm text-muted-foreground transition-colors hover:border-primary/50 hover:bg-muted/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
259
+ dragOver && 'border-primary/60 bg-muted/50',
260
+ )}
261
+ data-testid="gallery-dropzone"
262
+ >
263
+ <ImagePlus className="h-6 w-6" aria-hidden />
264
+ <span className="font-medium text-foreground">
265
+ {t('dynamic.gallery.add', { defaultValue: 'Agregar fotos' })}
266
+ </span>
267
+ <span className="text-xs" id={hintId}>
268
+ {maxSize
269
+ ? t('dynamic.gallery.hint_size', {
270
+ mb: (maxSize / (1024 * 1024)).toFixed(0),
271
+ defaultValue: `Arrastra aquí o elige varias a la vez · JPG, PNG o WebP · hasta ${(maxSize / (1024 * 1024)).toFixed(0)} MB`,
272
+ })
273
+ : t('dynamic.gallery.hint', { defaultValue: 'Arrastra aquí o elige varias a la vez · JPG, PNG o WebP' })}
274
+ </span>
275
+ <input
276
+ ref={inputRef}
277
+ type="file"
278
+ accept={accept}
279
+ multiple
280
+ className="hidden"
281
+ data-testid="gallery-input"
282
+ onChange={(e) => {
283
+ void addFiles(e.target.files)
284
+ e.target.value = ''
285
+ }}
286
+ />
287
+ </div>
288
+ )}
289
+
290
+ {pending.length > 0 && (
291
+ <ul className="grid gap-2" aria-live="polite" data-testid="gallery-uploads">
292
+ {pending.map((u) => (
293
+ <li key={u.id} className="flex items-center gap-3 rounded-md border bg-card p-2">
294
+ {u.preview ? (
295
+ <img src={u.preview} alt="" className="h-12 w-12 shrink-0 rounded object-cover" />
296
+ ) : (
297
+ <div className="h-12 w-12 shrink-0 rounded bg-muted" />
298
+ )}
299
+ <div className="min-w-0 flex-1">
300
+ <div className="truncate text-sm">{u.file.name}</div>
301
+ {u.status === 'error' ? (
302
+ <div className="text-xs text-destructive" role="alert">
303
+ {u.error}
304
+ </div>
305
+ ) : (
306
+ <div
307
+ className="mt-1 h-1.5 w-full overflow-hidden rounded bg-muted"
308
+ role="progressbar"
309
+ aria-label={u.file.name}
310
+ aria-valuemin={0}
311
+ aria-valuemax={100}
312
+ aria-valuenow={Math.round(u.progress * 100)}
313
+ >
314
+ <div className="h-full bg-primary transition-all" style={{ width: `${Math.round(u.progress * 100)}%` }} />
315
+ </div>
316
+ )}
317
+ </div>
318
+ {u.status === 'uploading' && <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" aria-hidden />}
319
+ {u.status === 'error' && !validateUploadFile(u.file, { accept, maxSize }) && (
320
+ <Button type="button" size="sm" variant="ghost" disabled={busy} onClick={() => void retry(u)} aria-label={t('dynamic.gallery.retry', { defaultValue: 'Reintentar' })}>
321
+ <RotateCcw className="h-4 w-4" />
322
+ </Button>
323
+ )}
324
+ {u.status === 'error' && (
325
+ <Button type="button" size="sm" variant="ghost" onClick={() => dismiss(u.id)} aria-label={t('dynamic.gallery.dismiss', { defaultValue: 'Quitar' })}>
326
+ <X className="h-4 w-4" />
327
+ </Button>
328
+ )}
329
+ </li>
330
+ ))}
331
+ </ul>
332
+ )}
333
+
334
+ {keyed.length === 0 && !canCreate && pending.length === 0 && (
335
+ <div className="rounded-md border bg-muted/30 py-8 text-center text-sm text-muted-foreground">
336
+ {t('dynamic.gallery.empty', { defaultValue: 'Sin fotos.' })}
337
+ </div>
338
+ )}
339
+
340
+ {keyed.length > 0 && (
341
+ <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
342
+ <SortableContext items={ids} strategy={rectSortingStrategy}>
343
+ <ul className="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4" data-testid="gallery-grid">
344
+ {keyed.map(({ row, key }, index) => (
345
+ <GalleryTile
346
+ key={key}
347
+ id={key}
348
+ src={row[imageKey] ? getImageUrl(String(row[imageKey])) : ''}
349
+ caption={captionKey ? String(row[captionKey] ?? '') : ''}
350
+ index={index}
351
+ total={keyed.length}
352
+ isMain={index === 0}
353
+ mainLabel={mainLabel}
354
+ canEdit={canEdit}
355
+ canReorder={reorderable}
356
+ canDelete={canDelete}
357
+ onMove={(to) => move(index, to)}
358
+ onEdit={onEdit ? () => onEdit(row) : undefined}
359
+ onDelete={onDelete ? () => onDelete(row) : undefined}
360
+ />
361
+ ))}
362
+ </ul>
363
+ </SortableContext>
364
+ </DndContext>
365
+ )}
366
+ </div>
367
+ )
368
+ }
369
+
370
+ function GalleryTile({
371
+ id,
372
+ src,
373
+ caption,
374
+ index,
375
+ total,
376
+ isMain,
377
+ mainLabel,
378
+ canEdit,
379
+ canReorder,
380
+ canDelete,
381
+ onMove,
382
+ onEdit,
383
+ onDelete,
384
+ }: {
385
+ id: string
386
+ src: string
387
+ caption: string
388
+ index: number
389
+ total: number
390
+ isMain: boolean
391
+ mainLabel: string
392
+ canEdit: boolean
393
+ canReorder: boolean
394
+ canDelete: boolean
395
+ onMove: (to: number) => void
396
+ onEdit?: () => void
397
+ onDelete?: () => void
398
+ }) {
399
+ const { t } = useTranslation()
400
+ const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id, disabled: !canReorder })
401
+ const label = caption || t('dynamic.gallery.photo', { n: index + 1, defaultValue: `Foto ${index + 1}` })
402
+ return (
403
+ <li
404
+ ref={setNodeRef}
405
+ style={{ transform: CSS.Transform.toString(transform), transition }}
406
+ className={cn(
407
+ 'group relative overflow-hidden rounded-lg border bg-card',
408
+ isMain && 'ring-2 ring-primary',
409
+ isDragging && 'z-10 opacity-80 shadow-lg',
410
+ )}
411
+ data-testid="gallery-tile"
412
+ data-main={isMain ? 'true' : undefined}
413
+ >
414
+ <div
415
+ className="aspect-square w-full touch-none bg-muted outline-none focus-visible:ring-2 focus-visible:ring-ring"
416
+ {...attributes}
417
+ {...listeners}
418
+ aria-roledescription={t('dynamic.gallery.sortable', { defaultValue: 'foto reordenable' })}
419
+ aria-label={`${label}${isMain ? ` · ${mainLabel}` : ''}`}
420
+ >
421
+ {src ? (
422
+ <img src={src} alt={caption} className="h-full w-full min-h-24 object-cover" draggable={false} />
423
+ ) : null}
424
+ </div>
425
+ {isMain && (
426
+ <span className="absolute start-2 top-2 inline-flex items-center gap-1 rounded-full bg-primary px-2 py-0.5 text-xs font-medium text-primary-foreground">
427
+ <Star className="h-3 w-3" aria-hidden />
428
+ {mainLabel}
429
+ </span>
430
+ )}
431
+ <div className="flex items-center justify-between gap-1 border-t bg-card px-1 py-1">
432
+ <div className="flex items-center">
433
+ {canReorder && (
434
+ <>
435
+ <Button
436
+ type="button"
437
+ size="sm"
438
+ variant="ghost"
439
+ className="h-8 w-8 p-0"
440
+ disabled={index === 0}
441
+ onClick={() => onMove(index - 1)}
442
+ aria-label={t('dynamic.gallery.move_before', { defaultValue: 'Mover antes' })}
443
+ >
444
+ <ArrowLeft className="h-4 w-4 rtl:rotate-180" />
445
+ </Button>
446
+ <Button
447
+ type="button"
448
+ size="sm"
449
+ variant="ghost"
450
+ className="h-8 w-8 p-0"
451
+ disabled={index === total - 1}
452
+ onClick={() => onMove(index + 1)}
453
+ aria-label={t('dynamic.gallery.move_after', { defaultValue: 'Mover después' })}
454
+ >
455
+ <ArrowRight className="h-4 w-4 rtl:rotate-180" />
456
+ </Button>
457
+ {!isMain && (
458
+ <Button
459
+ type="button"
460
+ size="sm"
461
+ variant="ghost"
462
+ className="h-8 w-8 p-0"
463
+ onClick={() => onMove(0)}
464
+ aria-label={t('dynamic.gallery.make_main', { defaultValue: 'Hacer principal' })}
465
+ title={t('dynamic.gallery.make_main', { defaultValue: 'Hacer principal' })}
466
+ >
467
+ <Star className="h-4 w-4" />
468
+ </Button>
469
+ )}
470
+ </>
471
+ )}
472
+ </div>
473
+ <div className="flex items-center">
474
+ {canEdit && onEdit && (
475
+ <Button type="button" size="sm" variant="ghost" className="h-8 w-8 p-0" onClick={onEdit} aria-label={t('dynamic.gallery.edit', { defaultValue: 'Editar foto' })}>
476
+ <Pencil className="h-4 w-4" />
477
+ </Button>
478
+ )}
479
+ {canDelete && onDelete && (
480
+ <Button type="button" size="sm" variant="ghost" className="h-8 w-8 p-0 text-destructive" onClick={onDelete} aria-label={t('dynamic.gallery.delete', { defaultValue: 'Eliminar foto' })}>
481
+ <Trash2 className="h-4 w-4" />
482
+ </Button>
483
+ )}
484
+ </div>
485
+ </div>
486
+ </li>
487
+ )
488
+ }
@@ -54,6 +54,8 @@ import {
54
54
  import {
55
55
  isSecretCredential,
56
56
  missingRequired,
57
+ applicableFields,
58
+ visibleSections,
57
59
  parseSaveError,
58
60
  shapeMismatch,
59
61
  textOrFallback,
@@ -96,10 +98,16 @@ export interface ConnectorCredentialField {
96
98
  options?: { value: string; label: string }[]
97
99
  options_source?: string // dynamic_select: export the host runs to list options
98
100
  section?: string // binds to a form_layout section
101
+ /** Shown only while a sibling credential has this value (kernel Setting.visible_when). */
102
+ visible_when?: VisibleWhen
103
+ visibleWhen?: VisibleWhen
99
104
  }
100
105
 
101
106
  export interface ConnectorFormLayoutSection {
102
107
  key: string
108
+ /** Hides the whole section (and its fields) while false. */
109
+ visible_when?: VisibleWhen
110
+ visibleWhen?: VisibleWhen
103
111
  title?: string // i18n key
104
112
  description?: string // i18n key
105
113
  /** Setup blocks (webhook_url / instructions / action), host-filled. */
@@ -622,8 +630,6 @@ export function AddonConfigSurface({
622
630
  }, [open])
623
631
 
624
632
  const credFields = connector?.credentials ?? []
625
- const requiredFields = credFields.filter((f) => f.required)
626
- const advancedFields = credFields.filter((f) => !f.required)
627
633
  // A connector with a form_layout groups its credentials into titled sections
628
634
  // (a light wizard). Fall back to the required/advanced split when absent.
629
635
  const layoutSections = connector?.form_layout?.sections ?? []
@@ -660,6 +666,16 @@ export function AddonConfigSurface({
660
666
  (f) => f.type === 'select' && ['environment', 'mode', 'env'].includes(f.key),
661
667
  )
662
668
  const envValue = envField ? (credValues[envField.key] ?? '') : ''
669
+ // What the form SHOWS for the live values: a credential whose own visible_when
670
+ // (or whose section's) is false is not applicable — never required, never
671
+ // validated, never counted in a step's error, never sent (connector_email:
672
+ // choosing Resend must not demand the SendGrid key).
673
+ const credDefaults: Record<string, string> = {}
674
+ for (const f of credFields) if (f.default != null && f.default !== '') credDefaults[f.key] = String(f.default)
675
+ const activeSections = visibleSections(layoutSections, credValues, credDefaults)
676
+ const activeFields = applicableFields(credFields, layoutSections, credValues, credDefaults)
677
+ // Only what applies is sent: a hidden provider's field is left out.
678
+ const isSendable = (key: string) => !credFields.some((f) => f.key === key) || activeFields.some((f) => f.key === key)
663
679
  const stepHeadingRef = useRef<HTMLHeadingElement>(null)
664
680
  const stepMoved = useRef(false)
665
681
  const setCred = (key: string, val: string) => {
@@ -891,7 +907,7 @@ export function AddonConfigSurface({
891
907
  // secret leaves it untouched (server merges).
892
908
  const payload: Record<string, string> = {}
893
909
  for (const [k, v] of Object.entries(credValues)) {
894
- if (v != null && v !== '') payload[k] = v
910
+ if (v != null && v !== '' && isSendable(k)) payload[k] = v
895
911
  }
896
912
  await api.post(`/integrations/${connector.provider}`, payload)
897
913
  }
@@ -973,7 +989,7 @@ export function AddonConfigSurface({
973
989
  const handleSave = () => {
974
990
  setFormError(null)
975
991
  if (connector && canManageIssuer) {
976
- const miss = missingRequired(credFields, credValues, !!connector.connected)
992
+ const miss = missingRequired(activeFields, credValues, !!connector.connected)
977
993
  if (miss.length > 0) {
978
994
  const errs: Record<string, string> = {}
979
995
  for (const k of miss) {
@@ -999,7 +1015,7 @@ export function AddonConfigSurface({
999
1015
  // screen requires persisting it first. Returns an error message, or null.
1000
1016
  const persistCredsIfDirty = async (): Promise<string | null> => {
1001
1017
  if (!credDirty || !connector || !canManageIssuer) return null
1002
- const miss = missingRequired(credFields, credValues, !!connector.connected)
1018
+ const miss = missingRequired(activeFields, credValues, !!connector.connected)
1003
1019
  if (miss.length > 0) {
1004
1020
  const errs: Record<string, string> = {}
1005
1021
  for (const k of miss) errs[k] = st('installed_addons.field_required')
@@ -1010,7 +1026,7 @@ export function AddonConfigSurface({
1010
1026
  }
1011
1027
  const payload: Record<string, string> = {}
1012
1028
  for (const [k, v] of Object.entries(credValues)) {
1013
- if (v != null && v !== '') payload[k] = v
1029
+ if (v != null && v !== '' && isSendable(k)) payload[k] = v
1014
1030
  }
1015
1031
  await api.post(`/integrations/${connector.provider}`, payload)
1016
1032
  setCredDirty(false)
@@ -1282,8 +1298,8 @@ export function AddonConfigSurface({
1282
1298
  // "Ajustes" step when the addon also ships settings.
1283
1299
  const wizardSteps = stepMode
1284
1300
  ? buildWizardSteps(
1285
- layoutSections,
1286
- credFields.map((f) => f.section),
1301
+ activeSections,
1302
+ activeFields.map((f) => f.section),
1287
1303
  hasSettings,
1288
1304
  )
1289
1305
  : []
@@ -1339,7 +1355,7 @@ export function AddonConfigSurface({
1339
1355
  return stepStatus({
1340
1356
  index: i,
1341
1357
  current: stepIdx,
1342
- fieldKeys: s.kind === 'creds' ? credFields.filter((f) => f.section === s.key).map((f) => f.key) : [],
1358
+ fieldKeys: s.kind === 'creds' ? activeFields.filter((f) => f.section === s.key).map((f) => f.key) : [],
1343
1359
  fieldErrors,
1344
1360
  blockKeys: blocksFor(s.key, s.blocks).map((b) => b.key),
1345
1361
  results: blockResults,
@@ -1360,7 +1376,7 @@ export function AddonConfigSurface({
1360
1376
  // operator learns what is missing where it is, not at the end.
1361
1377
  const handleNext = () => {
1362
1378
  if (activeStep?.kind === 'creds' && connector && canManageIssuer) {
1363
- const stepFields = credFields.filter((f) => f.section === activeStep.key)
1379
+ const stepFields = activeFields.filter((f) => f.section === activeStep.key)
1364
1380
  const miss = missingRequired(stepFields, credValues, !!connector.connected)
1365
1381
  if (miss.length > 0) {
1366
1382
  const errs: Record<string, string> = {}
@@ -1512,7 +1528,7 @@ export function AddonConfigSurface({
1512
1528
  ) : (
1513
1529
  <>
1514
1530
  {renderBlocks(leadBlocks(blocksFor(activeStep?.key ?? '', activeStep?.blocks)))}
1515
- {credFields.filter((f) => f.section === activeStep?.key).map(renderCred)}
1531
+ {activeFields.filter((f) => f.section === activeStep?.key).map(renderCred)}
1516
1532
  {renderBlocks(trailBlocks(blocksFor(activeStep?.key ?? '', activeStep?.blocks)))}
1517
1533
  </>
1518
1534
  )}
@@ -1534,8 +1550,8 @@ export function AddonConfigSurface({
1534
1550
  issuerAdminNote
1535
1551
  ) : useLayout ? (
1536
1552
  // form_layout: one titled group per section, in declared order.
1537
- layoutSections.map((sec) => {
1538
- const fields = credFields.filter((f) => f.section === sec.key)
1553
+ activeSections.map((sec) => {
1554
+ const fields = activeFields.filter((f) => f.section === sec.key)
1539
1555
  if (fields.length === 0 && (sec.blocks?.length ?? 0) === 0) return null
1540
1556
  return (
1541
1557
  <div
@@ -1570,7 +1586,7 @@ export function AddonConfigSurface({
1570
1586
  })
1571
1587
  ) : (
1572
1588
  <>
1573
- {requiredFields.map((f) => (
1589
+ {activeFields.filter((f) => f.required).map((f) => (
1574
1590
  <ConnectorCredentialFieldControl
1575
1591
  key={f.key}
1576
1592
  field={f}
@@ -1581,16 +1597,16 @@ export function AddonConfigSurface({
1581
1597
  onChange={(val) => setCred(f.key, val)}
1582
1598
  />
1583
1599
  ))}
1584
- {advancedFields.length > 0 && (
1600
+ {activeFields.some((f) => !f.required) && (
1585
1601
  <details
1586
1602
  className='rounded-md border border-border/60 px-3 py-2'
1587
- open={advancedFields.some((f) => !!fieldErrors[f.key]) || undefined}
1603
+ open={activeFields.filter((f) => !f.required).some((f) => !!fieldErrors[f.key]) || undefined}
1588
1604
  >
1589
1605
  <summary className='flex min-h-11 cursor-pointer items-center text-sm font-medium text-muted-foreground select-none sm:min-h-8'>
1590
1606
  {st('installed_addons.advanced')}
1591
1607
  </summary>
1592
1608
  <div className='flex flex-col gap-3 pt-3'>
1593
- {advancedFields.map((f) => (
1609
+ {activeFields.filter((f) => !f.required).map((f) => (
1594
1610
  <ConnectorCredentialFieldControl
1595
1611
  key={f.key}
1596
1612
  field={f}