@asteby/metacore-runtime-react 53.10.2 → 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.
- package/CHANGELOG.md +22 -0
- package/dist/dynamic-form.d.ts +10 -1
- package/dist/dynamic-form.d.ts.map +1 -1
- package/dist/dynamic-form.js +6 -6
- package/dist/dynamic-relation-helpers.d.ts +51 -0
- package/dist/dynamic-relation-helpers.d.ts.map +1 -1
- package/dist/dynamic-relation-helpers.js +139 -2
- package/dist/dynamic-relation.d.ts +16 -0
- package/dist/dynamic-relation.d.ts.map +1 -1
- package/dist/dynamic-relation.js +205 -12
- package/dist/dynamic-relations.d.ts.map +1 -1
- package/dist/dynamic-relations.js +1 -1
- package/dist/relation-gallery.d.ts +31 -0
- package/dist/relation-gallery.d.ts.map +1 -0
- package/dist/relation-gallery.js +154 -0
- package/dist/upload-field.d.ts +19 -1
- package/dist/upload-field.d.ts.map +1 -1
- package/dist/upload-field.js +50 -3
- package/package.json +1 -1
- package/src/__tests__/relation-gallery-helpers.test.ts +125 -0
- package/src/__tests__/relation-gallery.test.tsx +170 -0
- package/src/dynamic-form.tsx +20 -2
- package/src/dynamic-relation-helpers.ts +171 -2
- package/src/dynamic-relation.tsx +257 -14
- package/src/dynamic-relations.tsx +1 -0
- package/src/relation-gallery.tsx +488 -0
- package/src/upload-field.tsx +60 -2
package/dist/upload-field.js
CHANGED
|
@@ -16,6 +16,46 @@ import { useTranslation } from 'react-i18next';
|
|
|
16
16
|
import { getUploadConfig } from './dynamic-form-schema';
|
|
17
17
|
import { FilePickButton } from './file-pick-button';
|
|
18
18
|
import { useApi } from './api-context';
|
|
19
|
+
import { useImageUrl } from './image-url-context';
|
|
20
|
+
/**
|
|
21
|
+
* Natural pixel size of an image file, measured client-side. Resolves `{}` for
|
|
22
|
+
* a non-image or when the browser cannot decode it — never throws, never
|
|
23
|
+
* guesses.
|
|
24
|
+
*/
|
|
25
|
+
export async function readImageSize(file) {
|
|
26
|
+
if (!file || !String(file.type || '').startsWith('image/'))
|
|
27
|
+
return {};
|
|
28
|
+
try {
|
|
29
|
+
if (typeof createImageBitmap === 'function') {
|
|
30
|
+
const bmp = await createImageBitmap(file);
|
|
31
|
+
const out = { width: bmp.width, height: bmp.height };
|
|
32
|
+
bmp.close?.();
|
|
33
|
+
if (out.width > 0 && out.height > 0)
|
|
34
|
+
return out;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
// fall through to <img>
|
|
39
|
+
}
|
|
40
|
+
if (typeof Image === 'undefined' || typeof URL === 'undefined' || !URL.createObjectURL)
|
|
41
|
+
return {};
|
|
42
|
+
return new Promise((resolve) => {
|
|
43
|
+
const url = URL.createObjectURL(file);
|
|
44
|
+
const img = new Image();
|
|
45
|
+
img.onload = () => {
|
|
46
|
+
URL.revokeObjectURL(url);
|
|
47
|
+
resolve(img.naturalWidth > 0 ? { width: img.naturalWidth, height: img.naturalHeight } : {});
|
|
48
|
+
};
|
|
49
|
+
img.onerror = () => {
|
|
50
|
+
URL.revokeObjectURL(url);
|
|
51
|
+
resolve({});
|
|
52
|
+
};
|
|
53
|
+
img.src = url;
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
function isImageField(field, accept) {
|
|
57
|
+
return field.type === 'image' || (accept ?? '').toLowerCase().split(',').some((t) => t.trim().startsWith('image/'));
|
|
58
|
+
}
|
|
19
59
|
/** Default host upload endpoint. Overridable per-field via `searchEndpoint`. */
|
|
20
60
|
const DEFAULT_UPLOAD_ENDPOINT = '/upload';
|
|
21
61
|
/**
|
|
@@ -78,9 +118,10 @@ export function validateUploadFile(file, opts) {
|
|
|
78
118
|
return 'size';
|
|
79
119
|
return null;
|
|
80
120
|
}
|
|
81
|
-
export function UploadField({ field, value, onChange }) {
|
|
121
|
+
export function UploadField({ field, value, onChange, onFileMeta }) {
|
|
82
122
|
const { t } = useTranslation();
|
|
83
123
|
const api = useApi();
|
|
124
|
+
const getImageUrl = useImageUrl();
|
|
84
125
|
const [uploading, setUploading] = useState(false);
|
|
85
126
|
const [error, setError] = useState(null);
|
|
86
127
|
const { accept, maxSize, storagePath } = getUploadConfig(field);
|
|
@@ -137,6 +178,12 @@ export function UploadField({ field, value, onChange }) {
|
|
|
137
178
|
return;
|
|
138
179
|
}
|
|
139
180
|
onChange(stored);
|
|
181
|
+
if (onFileMeta && isImageField(field, accept)) {
|
|
182
|
+
void readImageSize(file).then((meta) => {
|
|
183
|
+
if (meta.width && meta.height)
|
|
184
|
+
onFileMeta(meta);
|
|
185
|
+
});
|
|
186
|
+
}
|
|
140
187
|
}
|
|
141
188
|
catch (err) {
|
|
142
189
|
setError(err?.response?.data?.message ||
|
|
@@ -145,7 +192,7 @@ export function UploadField({ field, value, onChange }) {
|
|
|
145
192
|
finally {
|
|
146
193
|
setUploading(false);
|
|
147
194
|
}
|
|
148
|
-
}, [api, endpoint, accept, maxSize, storagePath, onChange, t]);
|
|
195
|
+
}, [api, endpoint, accept, maxSize, storagePath, onChange, onFileMeta, field, t]);
|
|
149
196
|
return (_jsxs("div", { className: "grid gap-1.5", "data-widget": "upload", onDragOver: (e) => {
|
|
150
197
|
e.preventDefault();
|
|
151
198
|
}, onDrop: (e) => {
|
|
@@ -154,5 +201,5 @@ export function UploadField({ field, value, onChange }) {
|
|
|
154
201
|
if (!dropped || uploading)
|
|
155
202
|
return;
|
|
156
203
|
void handleFile(dropped);
|
|
157
|
-
}, children: [_jsx(FilePickButton, { id: field.key, accept: accept, loading: uploading, hasFile: hasValue, fileName: hasValue ? uploadedDisplayName(value) : undefined, onFile: (f) => void handleFile(f), pickLabel: field.placeholder || undefined }), error && (_jsx("span", { className: "text-sm text-destructive", role: "alert", children: error }))] }));
|
|
204
|
+
}, children: [hasValue && isImageField(field, accept) && (_jsx("img", { src: getImageUrl(String(value)), alt: "", className: "h-24 w-24 rounded-md border bg-muted object-cover", "data-testid": "upload-preview" })), _jsx(FilePickButton, { id: field.key, accept: accept, loading: uploading, hasFile: hasValue, fileName: hasValue ? uploadedDisplayName(value) : undefined, onFile: (f) => void handleFile(f), pickLabel: field.placeholder || undefined }), error && (_jsx("span", { className: "text-sm text-destructive", role: "alert", children: error }))] }));
|
|
158
205
|
}
|
package/package.json
CHANGED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import {
|
|
3
|
+
deriveRelationFormFields,
|
|
4
|
+
isManagedRelationColumn,
|
|
5
|
+
nextRelationPosition,
|
|
6
|
+
relationColumnUi,
|
|
7
|
+
relationDerivedValues,
|
|
8
|
+
relationGalleryColumn,
|
|
9
|
+
relationInitialValues,
|
|
10
|
+
relationMediaKind,
|
|
11
|
+
relationPositionKey,
|
|
12
|
+
relationPositionSortable,
|
|
13
|
+
sortRelationRows,
|
|
14
|
+
} from '../dynamic-relation-helpers'
|
|
15
|
+
import { resolveWidget } from '../dynamic-form-schema'
|
|
16
|
+
import type { ColumnDefinition, TableMetadata } from '../types'
|
|
17
|
+
|
|
18
|
+
const col = (c: Partial<ColumnDefinition> & { key: string }): ColumnDefinition =>
|
|
19
|
+
({ label: c.key, type: 'text', sortable: false, filterable: false, ...c }) as ColumnDefinition
|
|
20
|
+
|
|
21
|
+
// What /metadata/table serves for ProductImage (products 0.23.2) — the manifest
|
|
22
|
+
// `widget: image` does not travel to the table endpoint, `display: image_stack`
|
|
23
|
+
// does (as cellStyle), plus the creator avatar column every table gets.
|
|
24
|
+
const productImagesToday: Pick<TableMetadata, 'columns'> = {
|
|
25
|
+
columns: [
|
|
26
|
+
col({ key: 'product_id', ref: 'products' }),
|
|
27
|
+
col({ key: 'variant_id', ref: 'product_variants' }),
|
|
28
|
+
col({ key: 'url', cellStyle: 'image_stack' }),
|
|
29
|
+
col({ key: 'alt' }),
|
|
30
|
+
col({ key: 'width', type: 'number' }),
|
|
31
|
+
col({ key: 'height', type: 'number' }),
|
|
32
|
+
col({ key: 'position', type: 'number' }),
|
|
33
|
+
col({ key: 'created_by.avatar', type: 'avatar', cellStyle: 'creator' }),
|
|
34
|
+
],
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const productImagesDeclared: Pick<TableMetadata, 'columns'> = {
|
|
38
|
+
columns: [
|
|
39
|
+
col({ key: 'product_id', ref: 'products' }),
|
|
40
|
+
col({ key: 'variant_id', ref: 'product_variants', styleConfig: { empty_label: 'Para todas las variantes' } }),
|
|
41
|
+
col({ key: 'url', cellStyle: 'image_stack', styleConfig: { gallery: true, max_size: 5242880 } }),
|
|
42
|
+
col({ key: 'alt', styleConfig: { default_from_parent: 'name' } }),
|
|
43
|
+
col({ key: 'width', type: 'number', styleConfig: { derive: 'image_width' } }),
|
|
44
|
+
col({ key: 'height', type: 'number', styleConfig: { derive: 'image_height' } }),
|
|
45
|
+
col({ key: 'position', type: 'number', styleConfig: { derive: 'next_position' } }),
|
|
46
|
+
col({ key: 'created_by.avatar', type: 'avatar', cellStyle: 'creator' }),
|
|
47
|
+
],
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
describe('deriveRelationFormFields: galería de producto', () => {
|
|
51
|
+
// Protek 01/11: «Imagen» salía como input de texto y «Creado por» editable.
|
|
52
|
+
it('la columna de imagen es el widget de subida y la auditoría no aparece', () => {
|
|
53
|
+
const fields = deriveRelationFormFields(productImagesToday, 'product_id')
|
|
54
|
+
const byKey = Object.fromEntries(fields.map((f) => [f.key, f]))
|
|
55
|
+
expect(byKey.url?.type).toBe('image')
|
|
56
|
+
expect(byKey.url?.accept).toBe('image/*')
|
|
57
|
+
expect(resolveWidget(byKey.url!)).toBe('upload')
|
|
58
|
+
expect(byKey['created_by.avatar']).toBeUndefined()
|
|
59
|
+
expect(byKey.variant_id && resolveWidget(byKey.variant_id)).toBe('dynamic_select')
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
it('sin display_config los campos numéricos siguen visibles (retrocompat)', () => {
|
|
63
|
+
const keys = deriveRelationFormFields(productImagesToday, 'product_id').map((f) => f.key)
|
|
64
|
+
expect(keys).toEqual(['variant_id', 'url', 'alt', 'width', 'height', 'position'])
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
it('derived/hidden fuera del formulario; empty_label como placeholder', () => {
|
|
68
|
+
const fields = deriveRelationFormFields(productImagesDeclared, 'product_id')
|
|
69
|
+
expect(fields.map((f) => f.key)).toEqual(['variant_id', 'url', 'alt'])
|
|
70
|
+
expect(fields[0].placeholder).toBe('Para todas las variantes')
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
it('una FK con display image_stack (logo de marca) sigue siendo picker, no subida', () => {
|
|
74
|
+
expect(relationMediaKind(col({ key: 'brand_id', ref: 'brands', cellStyle: 'image_stack' }))).toBeUndefined()
|
|
75
|
+
expect(relationMediaKind(col({ key: 'doc', widget: 'file' } as any))).toBe('file')
|
|
76
|
+
expect(relationMediaKind(col({ key: 'photo', type: 'image' }))).toBe('image')
|
|
77
|
+
expect(relationMediaKind(col({ key: 'sku' }))).toBeUndefined()
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
it('auditoría y proyecciones con punto nunca son editables', () => {
|
|
81
|
+
for (const k of ['created_by', 'created_by.avatar', 'updated_by_id', 'deleted_by', 'organization_id', 'product.name']) {
|
|
82
|
+
expect(isManagedRelationColumn(k)).toBe(true)
|
|
83
|
+
}
|
|
84
|
+
expect(isManagedRelationColumn('alt')).toBe(false)
|
|
85
|
+
})
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
describe('valores derivados de la fila', () => {
|
|
89
|
+
const rows = [{ position: 0 }, { position: 3 }, { position: null }]
|
|
90
|
+
|
|
91
|
+
it('posición siguiente solo al crear; tamaño solo si se midió', () => {
|
|
92
|
+
expect(relationDerivedValues(productImagesDeclared, { isCreate: true, rows, image: { width: 1200.4, height: 800 } }))
|
|
93
|
+
.toEqual({ width: 1200, height: 800, position: 4 })
|
|
94
|
+
expect(relationDerivedValues(productImagesDeclared, { isCreate: false, rows, image: null })).toEqual({})
|
|
95
|
+
expect(relationDerivedValues(productImagesToday, { isCreate: true, rows, image: { width: 1, height: 1 } })).toEqual({})
|
|
96
|
+
})
|
|
97
|
+
|
|
98
|
+
it('nextRelationPosition: 0 sin filas', () => {
|
|
99
|
+
expect(nextRelationPosition([])).toBe(0)
|
|
100
|
+
expect(nextRelationPosition([{ position: '2' }, { position: 'x' }])).toBe(3)
|
|
101
|
+
})
|
|
102
|
+
|
|
103
|
+
it('texto alternativo sugerido con el nombre del padre', () => {
|
|
104
|
+
expect(relationInitialValues(productImagesDeclared, { name: 'BALATA DISCO' })).toEqual({ alt: 'BALATA DISCO' })
|
|
105
|
+
expect(relationInitialValues(productImagesDeclared, null)).toEqual({})
|
|
106
|
+
expect(relationInitialValues(productImagesToday, { name: 'X' })).toEqual({})
|
|
107
|
+
})
|
|
108
|
+
})
|
|
109
|
+
|
|
110
|
+
describe('orden y modo galería', () => {
|
|
111
|
+
it('ordena por position, estable, sin posición al final', () => {
|
|
112
|
+
const rows = [{ id: 'a', position: 2 }, { id: 'b' }, { id: 'c', position: 0 }, { id: 'd', position: 2 }]
|
|
113
|
+
expect(sortRelationRows(rows, 'position').map((r) => r.id)).toEqual(['c', 'a', 'd', 'b'])
|
|
114
|
+
expect(sortRelationRows(rows, undefined)).toBe(rows)
|
|
115
|
+
expect(relationPositionKey(productImagesToday)).toBe('position')
|
|
116
|
+
expect(relationPositionSortable(productImagesToday)).toBe(false)
|
|
117
|
+
expect(relationPositionSortable({ columns: [col({ key: 'position', sortable: true })] })).toBe(true)
|
|
118
|
+
})
|
|
119
|
+
|
|
120
|
+
it('la galería es opt-in por display_config.gallery', () => {
|
|
121
|
+
expect(relationGalleryColumn(productImagesToday)).toBeUndefined()
|
|
122
|
+
expect(relationGalleryColumn(productImagesDeclared)?.key).toBe('url')
|
|
123
|
+
expect(relationColumnUi(col({ key: 'x', styleConfig: { derive: 'otra' } }))).toEqual({})
|
|
124
|
+
})
|
|
125
|
+
})
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
// @vitest-environment happy-dom
|
|
2
|
+
//
|
|
3
|
+
// Galería de producto (display_config.gallery en la columna de imagen): la
|
|
4
|
+
// relación se ve como cuadrícula ordenada por position con la principal
|
|
5
|
+
// marcada, sube varias fotos de una vez (una fila por foto, posiciones en
|
|
6
|
+
// orden, tamaño medido, alt sugerido con el nombre del padre) y reordena
|
|
7
|
+
// persistiendo solo las posiciones que cambiaron. Sin display_config la
|
|
8
|
+
// relación sigue siendo la tabla de siempre.
|
|
9
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
|
10
|
+
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
|
11
|
+
import { DynamicRelation } from '../dynamic-relation'
|
|
12
|
+
import { ApiProvider, type ApiClient } from '../api-context'
|
|
13
|
+
|
|
14
|
+
vi.mock('../upload-field', async (orig) => {
|
|
15
|
+
const real: any = await orig()
|
|
16
|
+
return { ...real, readImageSize: vi.fn(async () => ({ width: 1200, height: 900 })) }
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
afterEach(cleanup)
|
|
20
|
+
beforeEach(() => {
|
|
21
|
+
ROWS = BASE_ROWS.map((r) => ({ ...r }))
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
const col = (c: Record<string, unknown>) => ({ label: c.key, type: 'text', sortable: false, filterable: false, ...c })
|
|
25
|
+
|
|
26
|
+
function meta(gallery: boolean) {
|
|
27
|
+
return {
|
|
28
|
+
name: 'product_images',
|
|
29
|
+
columns: [
|
|
30
|
+
col({ key: 'id', hidden: true }),
|
|
31
|
+
col({ key: 'product_id', ref: 'products' }),
|
|
32
|
+
col({ key: 'url', label: 'Imagen', cellStyle: 'image_stack', ...(gallery ? { styleConfig: { gallery: true, max_size: 1024 } } : {}) }),
|
|
33
|
+
col({ key: 'alt', label: 'Texto alternativo', ...(gallery ? { styleConfig: { default_from_parent: 'name' } } : {}) }),
|
|
34
|
+
col({ key: 'width', type: 'number', ...(gallery ? { styleConfig: { derive: 'image_width' } } : {}) }),
|
|
35
|
+
col({ key: 'height', type: 'number', ...(gallery ? { styleConfig: { derive: 'image_height' } } : {}) }),
|
|
36
|
+
col({ key: 'position', type: 'number', sortable: true, ...(gallery ? { styleConfig: { derive: 'next_position' } } : {}) }),
|
|
37
|
+
],
|
|
38
|
+
actions: [],
|
|
39
|
+
hasActions: false,
|
|
40
|
+
enableCRUDActions: false,
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
let ROWS: Record<string, unknown>[] = []
|
|
45
|
+
const BASE_ROWS = [
|
|
46
|
+
{ id: 'img_b', product_id: 'p1', url: '/storage/b.png', alt: 'Trasera', position: 1 },
|
|
47
|
+
{ id: 'img_a', product_id: 'p1', url: '/storage/a.png', alt: 'Frente', position: 0 },
|
|
48
|
+
]
|
|
49
|
+
|
|
50
|
+
function mockApi(gallery: boolean) {
|
|
51
|
+
let n = 0
|
|
52
|
+
const api = {
|
|
53
|
+
get: vi.fn((url: string) =>
|
|
54
|
+
Promise.resolve({ data: url.startsWith('/metadata/table/') ? { success: true, data: meta(gallery) } : { success: true, data: ROWS } }),
|
|
55
|
+
),
|
|
56
|
+
post: vi.fn((url: string, _body?: any, cfg?: any) => {
|
|
57
|
+
if (url === '/upload') {
|
|
58
|
+
cfg?.onUploadProgress?.({ loaded: 5, total: 10 })
|
|
59
|
+
return Promise.resolve({ data: { success: true, data: { url: `/storage/new-${++n}.webp` } } })
|
|
60
|
+
}
|
|
61
|
+
return Promise.resolve({ data: { success: true, data: {} } })
|
|
62
|
+
}),
|
|
63
|
+
put: vi.fn(() => Promise.resolve({ data: { success: true, data: {} } })),
|
|
64
|
+
delete: vi.fn(() => Promise.resolve({ data: { success: true, data: {} } })),
|
|
65
|
+
}
|
|
66
|
+
return api as unknown as ApiClient & typeof api
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function renderPanel(api: ApiClient, model = 'product_images') {
|
|
70
|
+
return render(
|
|
71
|
+
<ApiProvider client={api}>
|
|
72
|
+
<DynamicRelation
|
|
73
|
+
kind="one_to_many"
|
|
74
|
+
model={model}
|
|
75
|
+
foreignKey="product_id"
|
|
76
|
+
parentId="p1"
|
|
77
|
+
parentRecord={{ id: 'p1', name: 'BALATA DISCO' }}
|
|
78
|
+
/>
|
|
79
|
+
</ApiProvider>,
|
|
80
|
+
)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const png = (name: string, size = 10) => new File([new Uint8Array(size)], name, { type: 'image/png' })
|
|
84
|
+
|
|
85
|
+
describe('DynamicRelation — galería', () => {
|
|
86
|
+
it('cuadrícula ordenada por position, la primera es la principal', async () => {
|
|
87
|
+
renderPanel(mockApi(true))
|
|
88
|
+
await waitFor(() => expect(screen.getAllByTestId('gallery-tile')).toHaveLength(2))
|
|
89
|
+
const tiles = screen.getAllByTestId('gallery-tile')
|
|
90
|
+
expect(tiles[0].querySelector('img')?.getAttribute('alt')).toBe('Frente')
|
|
91
|
+
expect(tiles[0].getAttribute('data-main')).toBe('true')
|
|
92
|
+
expect(tiles[1].getAttribute('data-main')).toBeNull()
|
|
93
|
+
expect(screen.getByText('Principal')).toBeTruthy()
|
|
94
|
+
expect(screen.queryByRole('table')).toBeNull()
|
|
95
|
+
})
|
|
96
|
+
|
|
97
|
+
it('sube varias fotos: una fila por foto con posición siguiente, tamaño y alt sugerido; rechaza la pesada', async () => {
|
|
98
|
+
const api = mockApi(true)
|
|
99
|
+
renderPanel(api)
|
|
100
|
+
await waitFor(() => expect(screen.getAllByTestId('gallery-tile')).toHaveLength(2))
|
|
101
|
+
const input = screen.getByTestId('gallery-input') as HTMLInputElement
|
|
102
|
+
fireEvent.change(input, { target: { files: [png('uno.png'), png('dos.png'), png('pesada.png', 4096)] } })
|
|
103
|
+
|
|
104
|
+
await waitFor(() => {
|
|
105
|
+
const creates = api.post.mock.calls.filter((c: any[]) => c[0] === '/data/product_images')
|
|
106
|
+
expect(creates).toHaveLength(2)
|
|
107
|
+
})
|
|
108
|
+
const creates = api.post.mock.calls.filter((c: any[]) => c[0] === '/data/product_images').map((c: any[]) => c[1])
|
|
109
|
+
expect(creates[0]).toMatchObject({ product_id: 'p1', url: '/storage/new-1.webp', alt: 'BALATA DISCO', width: 1200, height: 900, position: 2 })
|
|
110
|
+
expect(creates[1]).toMatchObject({ url: '/storage/new-2.webp', position: 3 })
|
|
111
|
+
expect(api.post.mock.calls.filter((c: any[]) => c[0] === '/upload')).toHaveLength(2)
|
|
112
|
+
expect(await screen.findByText(/pesa más de/)).toBeTruthy()
|
|
113
|
+
})
|
|
114
|
+
|
|
115
|
+
it('hacer principal persiste solo las posiciones que cambian', async () => {
|
|
116
|
+
const api = mockApi(true)
|
|
117
|
+
renderPanel(api)
|
|
118
|
+
await waitFor(() => expect(screen.getAllByTestId('gallery-tile')).toHaveLength(2))
|
|
119
|
+
fireEvent.click(screen.getByLabelText('Hacer principal'))
|
|
120
|
+
await waitFor(() => expect(api.put).toHaveBeenCalledTimes(2))
|
|
121
|
+
expect(api.put).toHaveBeenCalledWith('/data/product_images/img_b', { position: 0 })
|
|
122
|
+
expect(api.put).toHaveBeenCalledWith('/data/product_images/img_a', { position: 1 })
|
|
123
|
+
})
|
|
124
|
+
|
|
125
|
+
it('una foto sin posición que pasa a principal sí se guarda (null no es 0)', async () => {
|
|
126
|
+
ROWS = [
|
|
127
|
+
{ id: 'img_a', product_id: 'p1', url: '/storage/a.png', alt: 'Frente', position: 0 },
|
|
128
|
+
{ id: 'img_n', product_id: 'p1', url: '/storage/n.png', alt: 'Vieja', position: null },
|
|
129
|
+
]
|
|
130
|
+
const api = mockApi(true)
|
|
131
|
+
renderPanel(api)
|
|
132
|
+
await waitFor(() => expect(screen.getAllByTestId('gallery-tile')).toHaveLength(2))
|
|
133
|
+
fireEvent.click(screen.getByLabelText('Hacer principal'))
|
|
134
|
+
await waitFor(() => expect(api.put).toHaveBeenCalledTimes(2))
|
|
135
|
+
expect(api.put).toHaveBeenCalledWith('/data/product_images/img_n', { position: 0 })
|
|
136
|
+
expect(api.put).toHaveBeenCalledWith('/data/product_images/img_a', { position: 1 })
|
|
137
|
+
})
|
|
138
|
+
|
|
139
|
+
it('en frío, tras conocer la metadata, vuelve a pedir ordenado y completo', async () => {
|
|
140
|
+
const api = mockApi(true)
|
|
141
|
+
renderPanel(api, 'product_images_cold')
|
|
142
|
+
await waitFor(() => {
|
|
143
|
+
const lists = api.get.mock.calls.filter((c: any[]) => c[0] === '/data/product_images_cold')
|
|
144
|
+
expect(lists.length).toBe(2)
|
|
145
|
+
expect(lists[1][1].params).toMatchObject({ sortBy: 'position', per_page: 200 })
|
|
146
|
+
})
|
|
147
|
+
})
|
|
148
|
+
|
|
149
|
+
it('lista ordenada por position en el servidor una vez conocida la metadata', async () => {
|
|
150
|
+
const api = mockApi(true)
|
|
151
|
+
renderPanel(api)
|
|
152
|
+
await waitFor(() => expect(screen.getAllByTestId('gallery-tile')).toHaveLength(2))
|
|
153
|
+
fireEvent.click(screen.getByLabelText('Hacer principal'))
|
|
154
|
+
await waitFor(() => {
|
|
155
|
+
const lists = api.get.mock.calls.filter((c: any[]) => c[0] === '/data/product_images')
|
|
156
|
+
expect(lists.length).toBeGreaterThan(1)
|
|
157
|
+
expect(lists[lists.length - 1][1].params).toMatchObject({ sortBy: 'position', order: 'asc', per_page: 200 })
|
|
158
|
+
})
|
|
159
|
+
})
|
|
160
|
+
|
|
161
|
+
it('sin display_config sigue siendo tabla, «Imagen» es subida y sin «Creado por»', async () => {
|
|
162
|
+
renderPanel(mockApi(false), 'product_images_plain')
|
|
163
|
+
await waitFor(() => expect(screen.getByRole('table')).toBeTruthy())
|
|
164
|
+
expect(screen.queryByTestId('gallery-grid')).toBeNull()
|
|
165
|
+
fireEvent.click(screen.getByText('Agregar'))
|
|
166
|
+
await waitFor(() => expect(screen.getByRole('dialog')).toBeTruthy())
|
|
167
|
+
expect(document.querySelector('[data-widget="upload"]')).toBeTruthy()
|
|
168
|
+
expect(screen.queryByText('Creado por')).toBeNull()
|
|
169
|
+
})
|
|
170
|
+
})
|
package/src/dynamic-form.tsx
CHANGED
|
@@ -73,6 +73,12 @@ export interface DynamicFormProps {
|
|
|
73
73
|
* debe ser flex-col con alto máximo (p.ej. `max-h-[90dvh]`).
|
|
74
74
|
*/
|
|
75
75
|
scrollableBody?: boolean
|
|
76
|
+
/**
|
|
77
|
+
* Side data an upload widget learned about the file it stored (an image's
|
|
78
|
+
* natural width/height). Lets the host fill derived columns that are not
|
|
79
|
+
* form inputs. Optional; forms without it behave as before.
|
|
80
|
+
*/
|
|
81
|
+
onFieldMeta?: (key: string, meta: { width?: number; height?: number }) => void
|
|
76
82
|
}
|
|
77
83
|
|
|
78
84
|
// Valores iniciales del formulario: el registro (edición) gana sobre el default
|
|
@@ -105,6 +111,7 @@ export function DynamicForm({
|
|
|
105
111
|
disabled = false,
|
|
106
112
|
formLayout,
|
|
107
113
|
scrollableBody = false,
|
|
114
|
+
onFieldMeta,
|
|
108
115
|
}: DynamicFormProps) {
|
|
109
116
|
const [errors, setErrors] = useState<Record<string, string>>({})
|
|
110
117
|
const [submitting, setSubmitting] = useState(false)
|
|
@@ -226,6 +233,7 @@ export function DynamicForm({
|
|
|
226
233
|
values={values}
|
|
227
234
|
error={errors[field.key]}
|
|
228
235
|
initialValues={initialValues}
|
|
236
|
+
onFieldMeta={onFieldMeta}
|
|
229
237
|
/>
|
|
230
238
|
))}
|
|
231
239
|
</div>
|
|
@@ -343,6 +351,7 @@ interface FieldRendererProps {
|
|
|
343
351
|
* gate its options by a sibling field's value (`applyOptionWhen`).
|
|
344
352
|
*/
|
|
345
353
|
values?: Record<string, any>
|
|
354
|
+
onFieldMeta?: (key: string, meta: { width?: number; height?: number }) => void
|
|
346
355
|
}
|
|
347
356
|
|
|
348
357
|
interface FieldRowProps extends FieldRendererProps {
|
|
@@ -353,7 +362,7 @@ interface FieldRowProps extends FieldRendererProps {
|
|
|
353
362
|
// component so a STATIC enum select whose options are all gated out by a sibling
|
|
354
363
|
// value (`when`) can hide the ENTIRE row (label included) and run its reset
|
|
355
364
|
// effect with valid hook ordering.
|
|
356
|
-
function FieldRow({ field, value, onChange, values, error, initialValues }: FieldRowProps) {
|
|
365
|
+
function FieldRow({ field, value, onChange, values, error, initialValues, onFieldMeta }: FieldRowProps) {
|
|
357
366
|
const isStaticSelect =
|
|
358
367
|
resolveWidget(field) === 'select' && !field.ref && Array.isArray(field.options)
|
|
359
368
|
const effectiveOptions = isStaticSelect
|
|
@@ -390,6 +399,7 @@ function FieldRow({ field, value, onChange, values, error, initialValues }: Fiel
|
|
|
390
399
|
values={values}
|
|
391
400
|
effectiveOptions={effectiveOptions}
|
|
392
401
|
error={error}
|
|
402
|
+
onFieldMeta={onFieldMeta}
|
|
393
403
|
/>
|
|
394
404
|
{error && <span className="text-red-500 text-sm" role="alert">{error}</span>}
|
|
395
405
|
</div>
|
|
@@ -431,6 +441,7 @@ function FieldRenderer({
|
|
|
431
441
|
values,
|
|
432
442
|
effectiveOptions,
|
|
433
443
|
error,
|
|
444
|
+
onFieldMeta,
|
|
434
445
|
}: FieldRendererProps & { effectiveOptions?: import('./types').OptionDef[]; error?: string }) {
|
|
435
446
|
// Host-registered widget (`widget: "<name>"`) wins over every built-in and
|
|
436
447
|
// type-based branch. Unregistered names fall through untouched.
|
|
@@ -461,7 +472,14 @@ function FieldRenderer({
|
|
|
461
472
|
// File upload → themed picker that POSTs to the host upload endpoint and
|
|
462
473
|
// stores the returned file url/path as the field value.
|
|
463
474
|
if (widget === 'upload') {
|
|
464
|
-
return
|
|
475
|
+
return (
|
|
476
|
+
<UploadField
|
|
477
|
+
field={field}
|
|
478
|
+
value={value}
|
|
479
|
+
onChange={onChange}
|
|
480
|
+
onFileMeta={onFieldMeta ? (meta) => onFieldMeta(field.key, meta) : undefined}
|
|
481
|
+
/>
|
|
482
|
+
)
|
|
465
483
|
}
|
|
466
484
|
// Icon picker → lucide glyph search grid, with an "Imagen" mode that
|
|
467
485
|
// delegates to the same UploadField as `upload`. Stores a plain string:
|
|
@@ -32,8 +32,167 @@ const MANAGED_RELATION_COLUMNS = new Set([
|
|
|
32
32
|
'created_by_id',
|
|
33
33
|
'updated_by',
|
|
34
34
|
'updated_by_id',
|
|
35
|
+
'deleted_by',
|
|
36
|
+
'deleted_by_id',
|
|
37
|
+
'organization_id',
|
|
35
38
|
])
|
|
36
39
|
|
|
40
|
+
// isManagedRelationColumn: an audit/server column, including the dotted
|
|
41
|
+
// projections the backend serves for them (`created_by.avatar`, the creator
|
|
42
|
+
// avatar column every table gets). Any dotted key is a projection of another
|
|
43
|
+
// column, never an editable value of the row.
|
|
44
|
+
export function isManagedRelationColumn(key: string): boolean {
|
|
45
|
+
const k = key.toLowerCase()
|
|
46
|
+
if (k.includes('.')) return true
|
|
47
|
+
return MANAGED_RELATION_COLUMNS.has(k)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const MEDIA_WIDGETS = new Set(['image', 'upload', 'photo', 'file', 'media'])
|
|
51
|
+
const IMAGE_CELL_STYLES = new Set(['image', 'image_stack'])
|
|
52
|
+
|
|
53
|
+
// relationMediaKind: 'image' / 'file' when a child column holds an uploaded
|
|
54
|
+
// file path (manifest `widget: image|upload|file`, `type: image`, or a ref-less
|
|
55
|
+
// column the backend renders as an image — `/metadata/table` carries the
|
|
56
|
+
// manifest `display: image_stack` as `cellStyle`, not the widget). A `ref`
|
|
57
|
+
// column is an FK picker (brand logo chip), never an upload.
|
|
58
|
+
export function relationMediaKind(col: ColumnDefinition): 'image' | 'file' | undefined {
|
|
59
|
+
if (col.ref) return undefined
|
|
60
|
+
const widget = String((col as ColumnDefinition & { widget?: string }).widget ?? '').toLowerCase()
|
|
61
|
+
if (widget === 'file') return 'file'
|
|
62
|
+
if (MEDIA_WIDGETS.has(widget)) return 'image'
|
|
63
|
+
if (col.type === 'image') return 'image'
|
|
64
|
+
if (IMAGE_CELL_STYLES.has(String(col.cellStyle ?? '').toLowerCase())) return 'image'
|
|
65
|
+
return undefined
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export type RelationDerive = 'image_width' | 'image_height' | 'next_position'
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Declarative form hints a child column carries in its manifest
|
|
72
|
+
* `display_config` (served as `styleConfig`, no kernel field needed):
|
|
73
|
+
* - `form: "hidden"` → never an input in the row form.
|
|
74
|
+
* - `derive: <RelationDerive>` → not an input; filled by the SDK (image
|
|
75
|
+
* size measured in the browser on upload, next gallery position on create).
|
|
76
|
+
* - `default_from_parent: <k>` → create-form initial value from the parent
|
|
77
|
+
* record's `<k>` (e.g. the product name as the image alt text), editable.
|
|
78
|
+
* - `empty_label: <text>` → placeholder of an optional picker
|
|
79
|
+
* ("Para todas las variantes").
|
|
80
|
+
* - `gallery: true` (on the image column) → the relation renders as a
|
|
81
|
+
* thumbnail gallery instead of a table.
|
|
82
|
+
* A column with none of them behaves exactly as before.
|
|
83
|
+
*/
|
|
84
|
+
export interface RelationColumnUi {
|
|
85
|
+
form?: 'hidden' | 'advanced'
|
|
86
|
+
derive?: RelationDerive
|
|
87
|
+
defaultFromParent?: string
|
|
88
|
+
emptyLabel?: string
|
|
89
|
+
gallery?: boolean
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const DERIVES = new Set<RelationDerive>(['image_width', 'image_height', 'next_position'])
|
|
93
|
+
|
|
94
|
+
export function relationColumnUi(col: ColumnDefinition): RelationColumnUi {
|
|
95
|
+
const sc = (col.styleConfig ?? {}) as Record<string, unknown>
|
|
96
|
+
const out: RelationColumnUi = {}
|
|
97
|
+
const form = sc.form
|
|
98
|
+
if (form === 'hidden' || form === 'advanced') out.form = form
|
|
99
|
+
const derive = sc.derive
|
|
100
|
+
if (typeof derive === 'string' && DERIVES.has(derive as RelationDerive)) out.derive = derive as RelationDerive
|
|
101
|
+
const dfp = sc.default_from_parent ?? sc.defaultFromParent
|
|
102
|
+
if (typeof dfp === 'string' && dfp.trim() !== '') out.defaultFromParent = dfp.trim()
|
|
103
|
+
const empty = sc.empty_label ?? sc.emptyLabel
|
|
104
|
+
if (typeof empty === 'string' && empty.trim() !== '') out.emptyLabel = empty
|
|
105
|
+
if (sc.gallery === true) out.gallery = true
|
|
106
|
+
return out
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** The gallery image column (media + `display_config.gallery: true`), if any. */
|
|
110
|
+
export function relationGalleryColumn(
|
|
111
|
+
metadata: Pick<TableMetadata, 'columns'> | null | undefined,
|
|
112
|
+
): ColumnDefinition | undefined {
|
|
113
|
+
return metadata?.columns?.find((c) => relationMediaKind(c) === 'image' && relationColumnUi(c).gallery === true)
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export interface ImageMeta {
|
|
117
|
+
width?: number
|
|
118
|
+
height?: number
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Values the SDK fills for derived columns of a child row. `next_position`
|
|
123
|
+
* only on create (an edit keeps the stored order); image size only when the
|
|
124
|
+
* upload measured one. Never invents a value it does not know.
|
|
125
|
+
*/
|
|
126
|
+
export function relationDerivedValues(
|
|
127
|
+
metadata: Pick<TableMetadata, 'columns'> | null | undefined,
|
|
128
|
+
ctx: { isCreate: boolean; rows: Record<string, any>[]; image?: ImageMeta | null },
|
|
129
|
+
): Record<string, number> {
|
|
130
|
+
const out: Record<string, number> = {}
|
|
131
|
+
for (const col of metadata?.columns ?? []) {
|
|
132
|
+
const d = relationColumnUi(col).derive
|
|
133
|
+
if (d === 'next_position' && ctx.isCreate) out[col.key] = nextRelationPosition(ctx.rows, col.key)
|
|
134
|
+
if (d === 'image_width' && ctx.image?.width) out[col.key] = Math.round(ctx.image.width)
|
|
135
|
+
if (d === 'image_height' && ctx.image?.height) out[col.key] = Math.round(ctx.image.height)
|
|
136
|
+
}
|
|
137
|
+
return out
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Create-form initial values copied from the parent (`default_from_parent`). */
|
|
141
|
+
export function relationInitialValues(
|
|
142
|
+
metadata: Pick<TableMetadata, 'columns'> | null | undefined,
|
|
143
|
+
parent: Record<string, unknown> | null | undefined,
|
|
144
|
+
): Record<string, any> {
|
|
145
|
+
const out: Record<string, any> = {}
|
|
146
|
+
if (!parent) return out
|
|
147
|
+
for (const col of metadata?.columns ?? []) {
|
|
148
|
+
const k = relationColumnUi(col).defaultFromParent
|
|
149
|
+
if (!k) continue
|
|
150
|
+
const v = parent[k]
|
|
151
|
+
if (typeof v === 'string' && v !== '') out[col.key] = v
|
|
152
|
+
else if (typeof v === 'number') out[col.key] = String(v)
|
|
153
|
+
}
|
|
154
|
+
return out
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Key of the child model's ordering column (`position`), if it declares one. */
|
|
158
|
+
export function relationPositionKey(
|
|
159
|
+
metadata: Pick<TableMetadata, 'columns'> | null | undefined,
|
|
160
|
+
): string | undefined {
|
|
161
|
+
return metadata?.columns?.some((c) => c.key === 'position') ? 'position' : undefined
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** True when the list endpoint can sort by the position column (declared sortable). */
|
|
165
|
+
export function relationPositionSortable(
|
|
166
|
+
metadata: Pick<TableMetadata, 'columns'> | null | undefined,
|
|
167
|
+
): boolean {
|
|
168
|
+
return metadata?.columns?.some((c) => c.key === 'position' && c.sortable === true) ?? false
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Rows sorted ascending by their position column; rows without one go last, stable. */
|
|
172
|
+
export function sortRelationRows<T extends Record<string, any>>(rows: T[], positionKey?: string): T[] {
|
|
173
|
+
if (!positionKey) return rows
|
|
174
|
+
const num = (r: T) => {
|
|
175
|
+
const n = Number(r?.[positionKey])
|
|
176
|
+
return r?.[positionKey] === null || r?.[positionKey] === undefined || r?.[positionKey] === '' || !Number.isFinite(n)
|
|
177
|
+
? Number.POSITIVE_INFINITY
|
|
178
|
+
: n
|
|
179
|
+
}
|
|
180
|
+
return rows
|
|
181
|
+
.map((r, i) => [r, i] as const)
|
|
182
|
+
.sort((a, b) => num(a[0]) - num(b[0]) || a[1] - b[1])
|
|
183
|
+
.map(([r]) => r)
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** Default position for a new child row: one past the highest loaded, 0 when empty. */
|
|
187
|
+
export function nextRelationPosition(rows: Record<string, any>[], positionKey = 'position'): number {
|
|
188
|
+
let max = -1
|
|
189
|
+
for (const r of rows) {
|
|
190
|
+
const n = Number(r?.[positionKey])
|
|
191
|
+
if (r?.[positionKey] !== null && r?.[positionKey] !== '' && Number.isFinite(n) && n > max) max = n
|
|
192
|
+
}
|
|
193
|
+
return max + 1
|
|
194
|
+
}
|
|
195
|
+
|
|
37
196
|
// Pulls a human label off a resolved relation/user object a backend serves:
|
|
38
197
|
// `{ value, label }` (FK sibling), `{ name, … }` (user object such as
|
|
39
198
|
// created_by) or `{ title }`. Returns undefined for plain/empty objects so the
|
|
@@ -163,11 +322,21 @@ export function deriveRelationFormFields(
|
|
|
163
322
|
// Managed/audit columns are server-owned and ship resolved objects
|
|
164
323
|
// (`created_by = { name, avatar, … }`); making them editable inputs
|
|
165
324
|
// renders `[object Object]`. Never surface them in the inline form.
|
|
166
|
-
if (
|
|
325
|
+
if (isManagedRelationColumn(col.key)) continue
|
|
326
|
+
// Derived / hidden columns are filled by the SDK or the server, never
|
|
327
|
+
// typed by whoever uploads a photo (width, height, position…).
|
|
328
|
+
const ui = relationColumnUi(col)
|
|
329
|
+
if (ui.form || ui.derive) continue
|
|
330
|
+
const media = relationMediaKind(col)
|
|
331
|
+
const accept = (col as ColumnDefinition & { accept?: string }).accept
|
|
167
332
|
out.push({
|
|
168
333
|
key: col.key,
|
|
169
334
|
label: col.label,
|
|
170
|
-
|
|
335
|
+
// A file/image column gets the same upload widget (with preview) as
|
|
336
|
+
// the parent form, not a free-text path input.
|
|
337
|
+
type: media ?? columnTypeToFieldType(col),
|
|
338
|
+
...(media === 'image' ? { accept: accept || 'image/*' } : accept ? { accept } : {}),
|
|
339
|
+
...(ui.emptyLabel ? { placeholder: ui.emptyLabel } : {}),
|
|
171
340
|
required: false,
|
|
172
341
|
options: col.options?.map(o => ({ value: String(o.value), label: o.label })),
|
|
173
342
|
// Carry the FK target through so a belongs_to column renders the
|