@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,58 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { applicableFields, missingRequired, visibleSections } from './connector-form-model'
3
+
4
+ // connector_email: provider picks which API key applies; each provider lives in
5
+ // its own section gated by visible_when.
6
+ const sections = [
7
+ { key: 'provider' },
8
+ { key: 'connection_resend', visible_when: { field: 'provider', equals: 'resend' } },
9
+ { key: 'connection_sendgrid', visible_when: { field: 'provider', equals: 'sendgrid' } },
10
+ { key: 'identity' },
11
+ ]
12
+ const fields = [
13
+ { key: 'provider', type: 'select', required: true, default: 'resend', section: 'provider' },
14
+ { key: 'api_key', type: 'secret', required: true, section: 'connection_resend' },
15
+ { key: 'sendgrid_api_key', type: 'secret', required: true, section: 'connection_sendgrid' },
16
+ { key: 'from_address', type: 'string', required: true, section: 'identity' },
17
+ ]
18
+ const defaults = { provider: 'resend' }
19
+
20
+ describe('conditional credential fields', () => {
21
+ it('provider=resend with sendgrid_api_key empty saves (hidden field is not required)', () => {
22
+ const values = { provider: 'resend', api_key: 're_123', from_address: 'a@b.mx' }
23
+ const active = applicableFields(fields, sections, values, defaults)
24
+ expect(active.map((f) => f.key)).toEqual(['provider', 'api_key', 'from_address'])
25
+ expect(missingRequired(active, values, false)).toEqual([])
26
+ // The old behaviour (every declared field) is what produced the bug.
27
+ expect(missingRequired(fields, values, false)).toContain('sendgrid_api_key')
28
+ })
29
+
30
+ it('the default provider applies when the value is blank', () => {
31
+ const active = applicableFields(fields, sections, { from_address: 'a@b.mx' }, defaults)
32
+ expect(active.map((f) => f.key)).toContain('api_key')
33
+ expect(active.map((f) => f.key)).not.toContain('sendgrid_api_key')
34
+ })
35
+
36
+ it('switching to sendgrid requires ITS key and not the Resend one', () => {
37
+ const values = { provider: 'sendgrid', from_address: 'a@b.mx' }
38
+ const active = applicableFields(fields, sections, values, defaults)
39
+ expect(missingRequired(active, values, false)).toEqual(['sendgrid_api_key'])
40
+ })
41
+
42
+ it('hides sections (wizard steps) of the other providers', () => {
43
+ expect(visibleSections(sections, { provider: 'resend' }, defaults).map((s) => s.key)).toEqual([
44
+ 'provider',
45
+ 'connection_resend',
46
+ 'identity',
47
+ ])
48
+ })
49
+
50
+ it('honours a field-level visible_when (in)', () => {
51
+ const f = [
52
+ { key: 'mode', required: true, default: 'a' },
53
+ { key: 'extra', required: true, visible_when: { field: 'mode', in: ['b', 'c'] } },
54
+ ]
55
+ expect(applicableFields(f, [], { mode: 'a' }, { mode: 'a' }).map((x) => x.key)).toEqual(['mode'])
56
+ expect(applicableFields(f, [], { mode: 'b' }).map((x) => x.key)).toEqual(['mode', 'extra'])
57
+ })
58
+ })
@@ -113,3 +113,72 @@ export function bundleSignature(labels: Record<string, unknown>): string {
113
113
  for (let i = 0; i < s.length; i++) h = ((h << 5) + h + s.charCodeAt(i)) | 0
114
114
  return `${Object.keys(labels).length}:${(h >>> 0).toString(36)}`
115
115
  }
116
+
117
+ // ─── Conditional fields (visible_when) ──────────────────────────────────────
118
+ // Kernel contract (Setting.visible_when / FormSection.visible_when): a hidden
119
+ // credential counts for required checks only while visible. A connector with
120
+ // conditional providers (email: Resend / SendGrid / Mailgun, each with its own
121
+ // key in its own section) must never demand the keys of the providers that were
122
+ // not chosen. These pure helpers decide what is APPLICABLE for the live values.
123
+
124
+ export interface VisibilityPredicate {
125
+ field?: string
126
+ equals?: unknown
127
+ in?: unknown[]
128
+ class?: string
129
+ }
130
+
131
+ interface ConditionalField {
132
+ key: string
133
+ section?: string
134
+ visible_when?: VisibilityPredicate
135
+ visibleWhen?: VisibilityPredicate
136
+ }
137
+ interface ConditionalSection {
138
+ key: string
139
+ visible_when?: VisibilityPredicate
140
+ visibleWhen?: VisibilityPredicate
141
+ }
142
+
143
+ /** Same semantics as `evaluateVisibleWhen` (no field / no comparison => visible). */
144
+ export function predicateHolds(
145
+ cond: VisibilityPredicate | undefined,
146
+ values: Record<string, string>,
147
+ defaults: Record<string, string> = {},
148
+ ): boolean {
149
+ if (!cond || typeof cond.field !== 'string' || cond.field.trim() === '') return true
150
+ const key = cond.field.trim()
151
+ const raw = values[key]
152
+ const current = raw == null || raw === '' ? (defaults[key] ?? '') : String(raw)
153
+ if (Array.isArray(cond.in) && cond.in.length > 0) return cond.in.some((v) => String(v) === current)
154
+ if (cond.equals != null) return String(cond.equals) === current
155
+ return true
156
+ }
157
+
158
+ /** Sections the form shows for these values. */
159
+ export function visibleSections<S extends ConditionalSection>(
160
+ sections: S[],
161
+ values: Record<string, string>,
162
+ defaults: Record<string, string> = {},
163
+ ): S[] {
164
+ return sections.filter((s) => predicateHolds(s.visible_when ?? s.visibleWhen, values, defaults))
165
+ }
166
+
167
+ /**
168
+ * Fields the form shows for these values: the field's own `visible_when` holds
169
+ * AND its section's does. Hidden fields are not validated, not counted in a
170
+ * step's error state and not sent.
171
+ */
172
+ export function applicableFields<F extends ConditionalField>(
173
+ fields: F[],
174
+ sections: ConditionalSection[],
175
+ values: Record<string, string>,
176
+ defaults: Record<string, string> = {},
177
+ ): F[] {
178
+ const hidden = new Set(
179
+ sections.filter((s) => !predicateHolds(s.visible_when ?? s.visibleWhen, values, defaults)).map((s) => s.key),
180
+ )
181
+ return fields.filter(
182
+ (f) => predicateHolds(f.visible_when ?? f.visibleWhen, values, defaults) && !(f.section && hidden.has(f.section)),
183
+ )
184
+ }
@@ -15,12 +15,56 @@ import { useTranslation } from 'react-i18next'
15
15
  import { getUploadConfig } from './dynamic-form-schema'
16
16
  import { FilePickButton } from './file-pick-button'
17
17
  import { useApi } from './api-context'
18
+ import { useImageUrl } from './image-url-context'
18
19
  import type { ActionFieldDef } from './types'
19
20
 
20
21
  export interface UploadFieldProps {
21
22
  field: ActionFieldDef
22
23
  value: any
23
24
  onChange: (v: any) => void
25
+ /**
26
+ * Called after a successful upload of an image with its natural size,
27
+ * measured in the browser (no server round-trip, `/upload` contract
28
+ * unchanged). Lets a form fill derived width/height columns.
29
+ */
30
+ onFileMeta?: (meta: { width?: number; height?: number }) => void
31
+ }
32
+
33
+ /**
34
+ * Natural pixel size of an image file, measured client-side. Resolves `{}` for
35
+ * a non-image or when the browser cannot decode it — never throws, never
36
+ * guesses.
37
+ */
38
+ export async function readImageSize(file: Blob): Promise<{ width?: number; height?: number }> {
39
+ if (!file || !String((file as File).type || '').startsWith('image/')) return {}
40
+ try {
41
+ if (typeof createImageBitmap === 'function') {
42
+ const bmp = await createImageBitmap(file)
43
+ const out = { width: bmp.width, height: bmp.height }
44
+ bmp.close?.()
45
+ if (out.width > 0 && out.height > 0) return out
46
+ }
47
+ } catch {
48
+ // fall through to <img>
49
+ }
50
+ if (typeof Image === 'undefined' || typeof URL === 'undefined' || !URL.createObjectURL) return {}
51
+ return new Promise((resolve) => {
52
+ const url = URL.createObjectURL(file)
53
+ const img = new Image()
54
+ img.onload = () => {
55
+ URL.revokeObjectURL(url)
56
+ resolve(img.naturalWidth > 0 ? { width: img.naturalWidth, height: img.naturalHeight } : {})
57
+ }
58
+ img.onerror = () => {
59
+ URL.revokeObjectURL(url)
60
+ resolve({})
61
+ }
62
+ img.src = url
63
+ })
64
+ }
65
+
66
+ function isImageField(field: ActionFieldDef, accept?: string): boolean {
67
+ return field.type === 'image' || (accept ?? '').toLowerCase().split(',').some((t) => t.trim().startsWith('image/'))
24
68
  }
25
69
 
26
70
  /** Default host upload endpoint. Overridable per-field via `searchEndpoint`. */
@@ -84,9 +128,10 @@ export function validateUploadFile(
84
128
  return null
85
129
  }
86
130
 
87
- export function UploadField({ field, value, onChange }: UploadFieldProps) {
131
+ export function UploadField({ field, value, onChange, onFileMeta }: UploadFieldProps) {
88
132
  const { t } = useTranslation()
89
133
  const api = useApi()
134
+ const getImageUrl = useImageUrl()
90
135
  const [uploading, setUploading] = useState(false)
91
136
  const [error, setError] = useState<string | null>(null)
92
137
 
@@ -154,6 +199,11 @@ export function UploadField({ field, value, onChange }: UploadFieldProps) {
154
199
  return
155
200
  }
156
201
  onChange(stored)
202
+ if (onFileMeta && isImageField(field, accept)) {
203
+ void readImageSize(file).then((meta) => {
204
+ if (meta.width && meta.height) onFileMeta(meta)
205
+ })
206
+ }
157
207
  } catch (err: any) {
158
208
  setError(
159
209
  err?.response?.data?.message ||
@@ -163,7 +213,7 @@ export function UploadField({ field, value, onChange }: UploadFieldProps) {
163
213
  setUploading(false)
164
214
  }
165
215
  },
166
- [api, endpoint, accept, maxSize, storagePath, onChange, t],
216
+ [api, endpoint, accept, maxSize, storagePath, onChange, onFileMeta, field, t],
167
217
  )
168
218
 
169
219
  return (
@@ -180,6 +230,14 @@ export function UploadField({ field, value, onChange }: UploadFieldProps) {
180
230
  void handleFile(dropped)
181
231
  }}
182
232
  >
233
+ {hasValue && isImageField(field, accept) && (
234
+ <img
235
+ src={getImageUrl(String(value))}
236
+ alt=""
237
+ className="h-24 w-24 rounded-md border bg-muted object-cover"
238
+ data-testid="upload-preview"
239
+ />
240
+ )}
183
241
  <FilePickButton
184
242
  id={field.key}
185
243
  accept={accept}