@asteby/metacore-runtime-react 53.11.0 → 53.13.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 +26 -0
- package/dist/bulk-image-dialog.d.ts +31 -0
- package/dist/bulk-image-dialog.d.ts.map +1 -0
- package/dist/bulk-image-dialog.js +339 -0
- package/dist/bulk-image-import.d.ts +158 -0
- package/dist/bulk-image-import.d.ts.map +1 -0
- package/dist/bulk-image-import.js +310 -0
- package/dist/dynamic-crud-page.d.ts.map +1 -1
- package/dist/dynamic-crud-page.js +2 -1
- package/dist/dynamic-relation-helpers.d.ts +27 -0
- package/dist/dynamic-relation-helpers.d.ts.map +1 -1
- package/dist/dynamic-relation-helpers.js +59 -0
- package/dist/dynamic-relation.d.ts.map +1 -1
- package/dist/dynamic-relation.js +95 -23
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/relation-gallery.d.ts +9 -1
- package/dist/relation-gallery.d.ts.map +1 -1
- package/dist/relation-gallery.js +4 -4
- package/package.json +2 -1
- package/src/__tests__/bulk-image-dialog.test.tsx +127 -0
- package/src/__tests__/bulk-image-import.test.ts +129 -0
- package/src/__tests__/relation-gallery-helpers.test.ts +29 -0
- package/src/__tests__/relation-gallery.test.tsx +91 -7
- package/src/bulk-image-dialog.tsx +594 -0
- package/src/bulk-image-import.ts +456 -0
- package/src/dynamic-crud-page.tsx +2 -0
- package/src/dynamic-relation-helpers.ts +66 -0
- package/src/dynamic-relation.tsx +98 -21
- package/src/index.ts +12 -0
- package/src/relation-gallery.tsx +36 -7
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
import { relationColumnUi, relationGalleryColumn } from './dynamic-relation-helpers';
|
|
2
|
+
export const BULK_IMAGE_EXTENSIONS = ['jpg', 'jpeg', 'png', 'webp', 'gif', 'avif'];
|
|
3
|
+
/** Lado largo por debajo del cual la foto se avisa como «baja resolución». */
|
|
4
|
+
export const DEFAULT_MIN_LONG_SIDE = 600;
|
|
5
|
+
/** Máximo de archivos por lote (la vista previa y la subida viven en memoria). */
|
|
6
|
+
export const MAX_BULK_FILES = 500;
|
|
7
|
+
// ---------------------------------------------------------------------------
|
|
8
|
+
// Nombres de archivo
|
|
9
|
+
// ---------------------------------------------------------------------------
|
|
10
|
+
/** Último segmento de una ruta (acepta `/` y `\`). */
|
|
11
|
+
export function baseName(path) {
|
|
12
|
+
const parts = path.split(/[\\/]/);
|
|
13
|
+
return parts[parts.length - 1] ?? '';
|
|
14
|
+
}
|
|
15
|
+
/** ¿Es una entrada ignorable (carpetas de macOS, archivos ocultos, no-imagen)? */
|
|
16
|
+
export function isIgnoredEntry(path) {
|
|
17
|
+
if (path.endsWith('/') || path.endsWith('\\'))
|
|
18
|
+
return true;
|
|
19
|
+
if (/(^|[\\/])__MACOSX([\\/]|$)/.test(path))
|
|
20
|
+
return true;
|
|
21
|
+
const name = baseName(path);
|
|
22
|
+
if (name === '' || name.startsWith('.'))
|
|
23
|
+
return true;
|
|
24
|
+
return !isImageName(name);
|
|
25
|
+
}
|
|
26
|
+
export function isImageName(name) {
|
|
27
|
+
const ext = name.split('.').pop()?.toLowerCase() ?? '';
|
|
28
|
+
return BULK_IMAGE_EXTENSIONS.includes(ext);
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* `SKU.ext` → orden 1; `SKU_2.ext` → orden 2. Como un SKU real puede terminar
|
|
32
|
+
* en `_N`, se ofrecen los dos candidatos y gana el que exista en el catálogo
|
|
33
|
+
* (primero el nombre completo).
|
|
34
|
+
*/
|
|
35
|
+
export function parseImageName(path) {
|
|
36
|
+
const name = baseName(path);
|
|
37
|
+
const dot = name.lastIndexOf('.');
|
|
38
|
+
const stem = (dot > 0 ? name.slice(0, dot) : name).trim();
|
|
39
|
+
const candidates = [];
|
|
40
|
+
if (stem)
|
|
41
|
+
candidates.push({ sku: stem, order: 1 });
|
|
42
|
+
const m = /^(.+?)_(\d{1,3})$/.exec(stem);
|
|
43
|
+
if (m)
|
|
44
|
+
candidates.push({ sku: m[1].trim(), order: Math.max(1, parseInt(m[2], 10)) });
|
|
45
|
+
return { stem, candidates };
|
|
46
|
+
}
|
|
47
|
+
export const normalizeSku = (s) => s.trim().toLowerCase();
|
|
48
|
+
/**
|
|
49
|
+
* SKUs a consultar (todos los candidatos, sin repetir), para pedirlos por
|
|
50
|
+
* lotes. El `IN` del servidor distingue mayúsculas, así que se piden también
|
|
51
|
+
* las variantes en MAYÚSCULAS y minúsculas; el cruce local no distingue.
|
|
52
|
+
*/
|
|
53
|
+
export function collectCandidateSkus(names) {
|
|
54
|
+
const seen = new Set();
|
|
55
|
+
for (const n of names) {
|
|
56
|
+
for (const c of parseImageName(n).candidates) {
|
|
57
|
+
for (const v of [c.sku, c.sku.toUpperCase(), c.sku.toLowerCase()])
|
|
58
|
+
seen.add(v);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return [...seen];
|
|
62
|
+
}
|
|
63
|
+
export function chunk(arr, size) {
|
|
64
|
+
const out = [];
|
|
65
|
+
for (let i = 0; i < arr.length; i += size)
|
|
66
|
+
out.push(arr.slice(i, i + size));
|
|
67
|
+
return out;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Busca la relación 1:N con galería. Necesita la metadata del hijo (para saber
|
|
71
|
+
* cuál es su columna de imagen); `childMetadata` la resuelve el llamador.
|
|
72
|
+
*/
|
|
73
|
+
export function deriveBulkImageTarget(relation, childMetadata) {
|
|
74
|
+
if (relation.kind !== 'one_to_many')
|
|
75
|
+
return null;
|
|
76
|
+
const img = relationGalleryColumn(childMetadata);
|
|
77
|
+
if (!img)
|
|
78
|
+
return null;
|
|
79
|
+
// Sin la FK declarada el listado ignoraría `f_<fk>=in:` en silencio y devolvería todo.
|
|
80
|
+
if (!(childMetadata?.columns ?? []).some((c) => c.key === relation.foreign_key))
|
|
81
|
+
return null;
|
|
82
|
+
const sc = (img.styleConfig ?? {});
|
|
83
|
+
const keyOf = (derive) => (childMetadata?.columns ?? []).find((c) => relationColumnUi(c).derive === derive)?.key;
|
|
84
|
+
const storagePath = (sc.storage_path ?? sc.storagePath);
|
|
85
|
+
return {
|
|
86
|
+
childModel: relation.through,
|
|
87
|
+
foreignKey: relation.foreign_key,
|
|
88
|
+
imageKey: img.key,
|
|
89
|
+
widthKey: keyOf('image_width'),
|
|
90
|
+
heightKey: keyOf('image_height'),
|
|
91
|
+
positionKey: keyOf('next_position') ?? (childMetadata?.columns ?? []).find((c) => c.key === 'position')?.key,
|
|
92
|
+
storagePath: typeof storagePath === 'string' && storagePath ? storagePath : undefined,
|
|
93
|
+
accept: img.accept || 'image/*',
|
|
94
|
+
maxSize: img.maxSize ?? img.max_size,
|
|
95
|
+
scope: relation.scope,
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
/** ¿La fila se importa por defecto? (`low_res` sí, con aviso; el usuario puede excluirla). */
|
|
99
|
+
export const isImportable = (r) => r.status === 'ok' || r.status === 'low_res';
|
|
100
|
+
/**
|
|
101
|
+
* Cruza los archivos con el catálogo. Reglas:
|
|
102
|
+
* - gana el nombre completo; si no existe como SKU, se prueba quitando `_N`;
|
|
103
|
+
* - dos archivos para el mismo SKU y el mismo orden son duplicados (se
|
|
104
|
+
* conserva el primero por ruta; el resto se marca y no se importa);
|
|
105
|
+
* - las fotos de un producto se numeran a continuación de las que ya tiene,
|
|
106
|
+
* en orden de `_N` (y de ruta a igualdad).
|
|
107
|
+
*/
|
|
108
|
+
export function buildPreview(inputs, parentsBySku, opts = {}) {
|
|
109
|
+
const minLong = opts.minLongSide ?? DEFAULT_MIN_LONG_SIDE;
|
|
110
|
+
const rows = inputs
|
|
111
|
+
.slice()
|
|
112
|
+
.sort((a, b) => a.path.localeCompare(b.path, undefined, { numeric: true }))
|
|
113
|
+
.map((inp, i) => {
|
|
114
|
+
const base = { ...inp, key: `${i}:${inp.path}`, status: 'ok' };
|
|
115
|
+
if (inp.decodable === false)
|
|
116
|
+
return { ...base, status: 'invalid_image', note: 'No es una imagen válida' };
|
|
117
|
+
if (opts.maxSize && inp.size > opts.maxSize)
|
|
118
|
+
return { ...base, status: 'too_large', note: 'Excede el tamaño máximo' };
|
|
119
|
+
const parsed = parseImageName(inp.path);
|
|
120
|
+
for (const c of parsed.candidates) {
|
|
121
|
+
const parent = parentsBySku.get(normalizeSku(c.sku));
|
|
122
|
+
if (parent) {
|
|
123
|
+
const long = Math.max(inp.width ?? 0, inp.height ?? 0);
|
|
124
|
+
const lowRes = long > 0 && long < minLong;
|
|
125
|
+
return {
|
|
126
|
+
...base,
|
|
127
|
+
sku: parent.sku,
|
|
128
|
+
order: c.order,
|
|
129
|
+
parent,
|
|
130
|
+
status: lowRes ? 'low_res' : 'ok',
|
|
131
|
+
note: lowRes ? `Baja resolución (${inp.width}×${inp.height})` : undefined,
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return { ...base, sku: parsed.stem, status: 'sku_not_found', note: 'SKU no encontrado' };
|
|
136
|
+
});
|
|
137
|
+
// Duplicados: mismo producto + mismo orden.
|
|
138
|
+
const seen = new Set();
|
|
139
|
+
for (const r of rows) {
|
|
140
|
+
if (!r.parent)
|
|
141
|
+
continue;
|
|
142
|
+
const k = `${r.parent.id}#${r.order}`;
|
|
143
|
+
if (seen.has(k)) {
|
|
144
|
+
r.status = 'duplicate';
|
|
145
|
+
r.note = `Duplicado: ya hay otra foto ${r.order === 1 ? 'principal' : `_${r.order}`} para ${r.parent.sku}`;
|
|
146
|
+
}
|
|
147
|
+
else {
|
|
148
|
+
seen.add(k);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
// Posiciones consecutivas por producto, a continuación de las existentes.
|
|
152
|
+
const byParent = new Map();
|
|
153
|
+
for (const r of rows) {
|
|
154
|
+
if (!r.parent || !isImportable(r))
|
|
155
|
+
continue;
|
|
156
|
+
const list = byParent.get(r.parent.id) ?? [];
|
|
157
|
+
list.push(r);
|
|
158
|
+
byParent.set(r.parent.id, list);
|
|
159
|
+
}
|
|
160
|
+
for (const list of byParent.values()) {
|
|
161
|
+
list.sort((a, b) => (a.order ?? 1) - (b.order ?? 1) || a.path.localeCompare(b.path, undefined, { numeric: true }));
|
|
162
|
+
list.forEach((r, i) => {
|
|
163
|
+
r.position = (r.parent?.existingMaxPosition ?? -1) + i + 1;
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
return rows;
|
|
167
|
+
}
|
|
168
|
+
export function summarizePreview(rows, excluded) {
|
|
169
|
+
const s = {
|
|
170
|
+
total: rows.length, importable: 0, products: 0, ok: 0, low_res: 0,
|
|
171
|
+
sku_not_found: 0, duplicate: 0, invalid_image: 0, too_large: 0,
|
|
172
|
+
};
|
|
173
|
+
const parents = new Set();
|
|
174
|
+
for (const r of rows) {
|
|
175
|
+
s[r.status] += 1;
|
|
176
|
+
if (isImportable(r) && !excluded?.has(r.key)) {
|
|
177
|
+
s.importable += 1;
|
|
178
|
+
if (r.parent)
|
|
179
|
+
parents.add(r.parent.id);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
s.products = parents.size;
|
|
183
|
+
return s;
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Tras excluir filas a mano, las posiciones se recalculan para no dejar
|
|
187
|
+
* huecos (la 2.ª foto de un producto cuya 1.ª se excluyó pasa a ser la 1.ª).
|
|
188
|
+
*/
|
|
189
|
+
export function selectForImport(rows, excluded) {
|
|
190
|
+
const byOrder = (a, b) => (a.order ?? 1) - (b.order ?? 1) || a.path.localeCompare(b.path, undefined, { numeric: true });
|
|
191
|
+
// Mismo criterio que buildPreview: dentro de cada producto manda `_N`, no la ruta.
|
|
192
|
+
const picked = rows.filter((r) => isImportable(r) && !excluded.has(r.key)).sort(byOrder);
|
|
193
|
+
const counter = new Map();
|
|
194
|
+
return picked.map((r) => {
|
|
195
|
+
const n = (counter.get(r.parent.id) ?? 0) + 1;
|
|
196
|
+
counter.set(r.parent.id, n);
|
|
197
|
+
return { ...r, position: r.parent.existingMaxPosition + n };
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
// ---------------------------------------------------------------------------
|
|
201
|
+
// Cuerpo de la fila hija
|
|
202
|
+
// ---------------------------------------------------------------------------
|
|
203
|
+
export function buildChildPayload(target, row, url) {
|
|
204
|
+
const out = {
|
|
205
|
+
...(target.scope || {}),
|
|
206
|
+
[target.imageKey]: url,
|
|
207
|
+
[target.foreignKey]: row.parent.id,
|
|
208
|
+
};
|
|
209
|
+
if (target.positionKey && typeof row.position === 'number')
|
|
210
|
+
out[target.positionKey] = row.position;
|
|
211
|
+
if (target.widthKey && row.width)
|
|
212
|
+
out[target.widthKey] = Math.round(row.width);
|
|
213
|
+
if (target.heightKey && row.height)
|
|
214
|
+
out[target.heightKey] = Math.round(row.height);
|
|
215
|
+
return out;
|
|
216
|
+
}
|
|
217
|
+
const LOG_KEY = 'metacore.bulk-image-batches.v1';
|
|
218
|
+
const MAX_LOGS = 10;
|
|
219
|
+
export function newBatchId(now = new Date()) {
|
|
220
|
+
return `bulk-${now.toISOString().replace(/[-:.TZ]/g, '').slice(0, 14)}-${Math.random().toString(36).slice(2, 6)}`;
|
|
221
|
+
}
|
|
222
|
+
export function loadBatchLogs(storage = safeStorage(), scope) {
|
|
223
|
+
try {
|
|
224
|
+
const raw = storage?.getItem(LOG_KEY);
|
|
225
|
+
const parsed = raw ? JSON.parse(raw) : [];
|
|
226
|
+
if (!Array.isArray(parsed))
|
|
227
|
+
return [];
|
|
228
|
+
// Con `scope`, solo los lotes de esa organización/usuario.
|
|
229
|
+
return scope === undefined ? parsed : parsed.filter((l) => !!l.scope && l.scope === scope);
|
|
230
|
+
}
|
|
231
|
+
catch {
|
|
232
|
+
return [];
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
export function saveBatchLog(log, storage = safeStorage()) {
|
|
236
|
+
try {
|
|
237
|
+
const all = loadBatchLogs(storage).filter((l) => l.batchId !== log.batchId);
|
|
238
|
+
all.unshift(log);
|
|
239
|
+
storage?.setItem(LOG_KEY, JSON.stringify(all.slice(0, MAX_LOGS)));
|
|
240
|
+
}
|
|
241
|
+
catch {
|
|
242
|
+
/* almacenamiento no disponible: el registro descargable sigue siendo válido */
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
function safeStorage() {
|
|
246
|
+
try {
|
|
247
|
+
return typeof localStorage !== 'undefined' ? localStorage : undefined;
|
|
248
|
+
}
|
|
249
|
+
catch {
|
|
250
|
+
return undefined;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
/** Filas del lote que aún se pueden deshacer. */
|
|
254
|
+
export const pendingUndo = (log) => log.items.filter((i) => !i.undone);
|
|
255
|
+
const MIME_BY_EXT = {
|
|
256
|
+
jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png', webp: 'image/webp', gif: 'image/gif', avif: 'image/avif',
|
|
257
|
+
};
|
|
258
|
+
/** Máximo descomprimido aceptado por archivo de un ZIP (defensa ante zip-bombs). */
|
|
259
|
+
export const MAX_ENTRY_BYTES = 25 * 1024 * 1024;
|
|
260
|
+
export const MAX_TOTAL_BYTES = 400 * 1024 * 1024;
|
|
261
|
+
/** Descomprime un ZIP en el navegador y devuelve solo las imágenes. */
|
|
262
|
+
export async function readZipImages(zip) {
|
|
263
|
+
const { unzipSync } = await import('fflate');
|
|
264
|
+
const data = new Uint8Array(await zip.arrayBuffer());
|
|
265
|
+
let total = 0;
|
|
266
|
+
let skipped = 0;
|
|
267
|
+
const files = [];
|
|
268
|
+
const entries = unzipSync(data, {
|
|
269
|
+
filter: (f) => {
|
|
270
|
+
if (f.name.endsWith('/'))
|
|
271
|
+
return false;
|
|
272
|
+
// Solo almacenado (0) o deflate (8): deflate64/cifrado abortarían todo el ZIP.
|
|
273
|
+
if (isIgnoredEntry(f.name) || (f.compression !== 0 && f.compression !== 8)) {
|
|
274
|
+
skipped += 1;
|
|
275
|
+
return false;
|
|
276
|
+
}
|
|
277
|
+
total += f.originalSize;
|
|
278
|
+
if (f.originalSize > MAX_ENTRY_BYTES || total > MAX_TOTAL_BYTES) {
|
|
279
|
+
skipped += 1;
|
|
280
|
+
return false;
|
|
281
|
+
}
|
|
282
|
+
return true;
|
|
283
|
+
},
|
|
284
|
+
});
|
|
285
|
+
for (const [path, bytes] of Object.entries(entries)) {
|
|
286
|
+
const ext = path.split('.').pop()?.toLowerCase() ?? '';
|
|
287
|
+
files.push({ path, file: new File([bytes], baseName(path), { type: MIME_BY_EXT[ext] ?? '' }) });
|
|
288
|
+
}
|
|
289
|
+
return { files, skipped };
|
|
290
|
+
}
|
|
291
|
+
/** Normaliza lo que entrega un `<input>` / drop: ZIP o imágenes sueltas/carpeta. */
|
|
292
|
+
export async function collectBulkFiles(list) {
|
|
293
|
+
const files = [];
|
|
294
|
+
let skipped = 0;
|
|
295
|
+
for (const f of list) {
|
|
296
|
+
if (/\.zip$/i.test(f.name) || f.type === 'application/zip' || f.type === 'application/x-zip-compressed') {
|
|
297
|
+
const z = await readZipImages(f);
|
|
298
|
+
files.push(...z.files);
|
|
299
|
+
skipped += z.skipped;
|
|
300
|
+
continue;
|
|
301
|
+
}
|
|
302
|
+
const rel = f.webkitRelativePath || f.name;
|
|
303
|
+
if (isIgnoredEntry(rel)) {
|
|
304
|
+
skipped += 1;
|
|
305
|
+
continue;
|
|
306
|
+
}
|
|
307
|
+
files.push({ path: rel, file: f });
|
|
308
|
+
}
|
|
309
|
+
return { files, skipped };
|
|
310
|
+
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dynamic-crud-page.d.ts","sourceRoot":"","sources":["../src/dynamic-crud-page.tsx"],"names":[],"mappings":"AAwBA,OAAO,KAKN,MAAM,OAAO,CAAA;AAMd,OAAO,EAKH,KAAK,eAAe,EACvB,MAAM,wBAAwB,CAAA;
|
|
1
|
+
{"version":3,"file":"dynamic-crud-page.d.ts","sourceRoot":"","sources":["../src/dynamic-crud-page.tsx"],"names":[],"mappings":"A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AAQ,CAAC,EAAE,MAAM,IAAI,CAAA;IACrB;;;OAGG;IACH,aAAa,CAAC,EAAE,qBAAqB,CAAA;IACrC;;;;OAIG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IAC/B;;;;OAIG;IACH,aAAa,CAAC,EAAE;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE;YAAE,GAAG,EAAE,MAAM,CAAC;YAAC,EAAE,EAAE,MAAM,CAAA;SAAE,CAAA;KAAE,CAAA;IACvE;;;;OAIG;IACH,gBAAgB,CAAC,EAAE,CAAC,MAAM,EAAE,eAAe,KAAK,IAAI,CAAA;CACvD;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,oBAAoB,qBAoP1D"}
|
|
@@ -34,6 +34,7 @@ import { ExportDialog } from './dialogs/export';
|
|
|
34
34
|
import { ImportDialog } from './dialogs/import';
|
|
35
35
|
import { getModelExtension } from './model-extension-registry';
|
|
36
36
|
import { ModelActionToolbar } from './model-action-toolbar';
|
|
37
|
+
import { BulkImageImportButton } from './bulk-image-dialog';
|
|
37
38
|
import { resolveListPrimaryAction } from './list-primary-action';
|
|
38
39
|
import { useCan, modelCapability } from './permissions-context';
|
|
39
40
|
const defaultStrings = {
|
|
@@ -139,5 +140,5 @@ export function DynamicCRUDPage(props) {
|
|
|
139
140
|
const titleCls = classes?.title ?? 'text-2xl font-bold tracking-tight';
|
|
140
141
|
const toolbarCls = classes?.toolbar ?? 'flex items-center gap-2';
|
|
141
142
|
const tableWrapperCls = classes?.tableWrapper ?? 'flex-1 min-h-0';
|
|
142
|
-
return (_jsxs("div", { className: rootCls, children: [_jsxs("div", { className: containerCls, children: [ext?.headerExtras && _jsx(ext.headerExtras, { model: model, onRefresh: handleRefresh }), headerExtras, _jsxs("div", { className: headerCls, children: [metadata ? (_jsx("h1", { className: titleCls, children: title })) : (_jsx("div", { className: 'h-8 w-48 bg-muted rounded animate-pulse' })), _jsxs("div", { className: toolbarCls, children: [showRefresh && (_jsx("button", { type: 'button', onClick: handleRefresh, "aria-label": strings.refresh, className: 'inline-flex items-center justify-center size-9 rounded-md border border-border bg-background hover:bg-accent text-foreground', children: _jsx(RefreshCw, { className: 'size-4' }) })), metadata && showExport && (_jsxs("button", { type: 'button', onClick: () => setOpenExport(true), className: 'inline-flex items-center gap-2 h-9 px-3 rounded-md border border-border bg-background hover:bg-accent text-sm font-medium text-foreground', children: [_jsx(Download, { className: 'size-4' }), strings.export] })), metadata && showImport && (_jsxs("button", { type: 'button', onClick: () => setOpenImport(true), className: 'inline-flex items-center gap-2 h-9 px-3 rounded-md border border-border bg-background hover:bg-accent text-sm font-medium text-foreground', children: [_jsx(Upload, { className: 'size-4' }), strings.import] })), ext?.toolbarExtras && _jsx(ext.toolbarExtras, { model: model, onRefresh: handleRefresh }), toolbarExtras, _jsx(ModelActionToolbar, { model: model, endpoint: dataEndpoint, actions: metadata?.actions, primaryActionKey: ext?.primaryActionKey, onChange: handleRefresh }), showCreate && (_jsxs("button", { type: 'button', "data-primary": 'true', onClick: () => setOpenCreate(true), className: 'inline-flex items-center gap-2 h-9 px-3 rounded-md bg-primary text-primary-foreground hover:opacity-90 text-sm font-medium', children: [_jsx(Plus, { className: 'size-4' }), resolvedNewLabel ?? `${strings.newPrefix} ${singular}`] }))] })] }), _jsx("div", { className: tableWrapperCls, children: _jsx(DynamicTable, { model: model, endpoint: dataEndpoint, refreshTrigger: refreshKey, defaultFilters: tableFilters }, model) })] }), showCreate && guidedForms && (_jsx(DocumentFormDialog, { open: openCreate, onOpenChange: setOpenCreate, model: model, endpoint: dataEndpoint, forms: guidedForms, initialType: initialCreate?.type, initialSource: initialCreate?.source, onSaved: handleRefresh, onDelegateCreate: onDelegateCreate })), showCreate && !guidedForms && (_jsx(DynamicRecordDialog, { open: openCreate && !initialCreate?.source, onOpenChange: setOpenCreate, mode: 'create', model: model, endpoint: dataEndpoint, onSaved: handleRefresh })), metadata && showExport && (_jsx(ExportDialog, { open: openExport, onOpenChange: setOpenExport, model: model, metadata: metadata })), metadata && showImport && (_jsx(ImportDialog, { open: openImport, onOpenChange: setOpenImport, model: model, metadata: metadata, onImported: handleRefresh }))] }));
|
|
143
|
+
return (_jsxs("div", { className: rootCls, children: [_jsxs("div", { className: containerCls, children: [ext?.headerExtras && _jsx(ext.headerExtras, { model: model, onRefresh: handleRefresh }), headerExtras, _jsxs("div", { className: headerCls, children: [metadata ? (_jsx("h1", { className: titleCls, children: title })) : (_jsx("div", { className: 'h-8 w-48 bg-muted rounded animate-pulse' })), _jsxs("div", { className: toolbarCls, children: [showRefresh && (_jsx("button", { type: 'button', onClick: handleRefresh, "aria-label": strings.refresh, className: 'inline-flex items-center justify-center size-9 rounded-md border border-border bg-background hover:bg-accent text-foreground', children: _jsx(RefreshCw, { className: 'size-4' }) })), metadata && showExport && (_jsxs("button", { type: 'button', onClick: () => setOpenExport(true), className: 'inline-flex items-center gap-2 h-9 px-3 rounded-md border border-border bg-background hover:bg-accent text-sm font-medium text-foreground', children: [_jsx(Download, { className: 'size-4' }), strings.export] })), metadata && showImport && (_jsxs("button", { type: 'button', onClick: () => setOpenImport(true), className: 'inline-flex items-center gap-2 h-9 px-3 rounded-md border border-border bg-background hover:bg-accent text-sm font-medium text-foreground', children: [_jsx(Upload, { className: 'size-4' }), strings.import] })), metadata && !scoped.hideCreate && can(modelCapability(model, 'create')) && _jsx(BulkImageImportButton, { model: model, metadata: metadata, onChange: handleRefresh }), ext?.toolbarExtras && _jsx(ext.toolbarExtras, { model: model, onRefresh: handleRefresh }), toolbarExtras, _jsx(ModelActionToolbar, { model: model, endpoint: dataEndpoint, actions: metadata?.actions, primaryActionKey: ext?.primaryActionKey, onChange: handleRefresh }), showCreate && (_jsxs("button", { type: 'button', "data-primary": 'true', onClick: () => setOpenCreate(true), className: 'inline-flex items-center gap-2 h-9 px-3 rounded-md bg-primary text-primary-foreground hover:opacity-90 text-sm font-medium', children: [_jsx(Plus, { className: 'size-4' }), resolvedNewLabel ?? `${strings.newPrefix} ${singular}`] }))] })] }), _jsx("div", { className: tableWrapperCls, children: _jsx(DynamicTable, { model: model, endpoint: dataEndpoint, refreshTrigger: refreshKey, defaultFilters: tableFilters }, model) })] }), showCreate && guidedForms && (_jsx(DocumentFormDialog, { open: openCreate, onOpenChange: setOpenCreate, model: model, endpoint: dataEndpoint, forms: guidedForms, initialType: initialCreate?.type, initialSource: initialCreate?.source, onSaved: handleRefresh, onDelegateCreate: onDelegateCreate })), showCreate && !guidedForms && (_jsx(DynamicRecordDialog, { open: openCreate && !initialCreate?.source, onOpenChange: setOpenCreate, mode: 'create', model: model, endpoint: dataEndpoint, onSaved: handleRefresh })), metadata && showExport && (_jsx(ExportDialog, { open: openExport, onOpenChange: setOpenExport, model: model, metadata: metadata })), metadata && showImport && (_jsx(ImportDialog, { open: openImport, onOpenChange: setOpenImport, model: model, metadata: metadata, onImported: handleRefresh }))] }));
|
|
143
144
|
}
|
|
@@ -15,6 +15,9 @@ export type RelationDerive = 'image_width' | 'image_height' | 'next_position';
|
|
|
15
15
|
* ("Para todas las variantes").
|
|
16
16
|
* - `gallery: true` (on the image column) → the relation renders as a
|
|
17
17
|
* thumbnail gallery instead of a table.
|
|
18
|
+
* - `main_from_parent: <k>` (on the image column) → the parent's `<k>` image
|
|
19
|
+
* is the gallery's main photo; while no gallery row holds it, it shows as a
|
|
20
|
+
* read-only first tile.
|
|
18
21
|
* A column with none of them behaves exactly as before.
|
|
19
22
|
*/
|
|
20
23
|
export interface RelationColumnUi {
|
|
@@ -23,6 +26,8 @@ export interface RelationColumnUi {
|
|
|
23
26
|
defaultFromParent?: string;
|
|
24
27
|
emptyLabel?: string;
|
|
25
28
|
gallery?: boolean;
|
|
29
|
+
/** Campo del padre cuya imagen es la principal de la galería (p. ej. `image`). */
|
|
30
|
+
mainFromParent?: string;
|
|
26
31
|
}
|
|
27
32
|
export declare function relationColumnUi(col: ColumnDefinition): RelationColumnUi;
|
|
28
33
|
/** The gallery image column (media + `display_config.gallery: true`), if any. */
|
|
@@ -51,6 +56,20 @@ export declare function relationPositionSortable(metadata: Pick<TableMetadata, '
|
|
|
51
56
|
export declare function sortRelationRows<T extends Record<string, any>>(rows: T[], positionKey?: string): T[];
|
|
52
57
|
/** Default position for a new child row: one past the highest loaded, 0 when empty. */
|
|
53
58
|
export declare function nextRelationPosition(rows: Record<string, any>[], positionKey?: string): number;
|
|
59
|
+
/**
|
|
60
|
+
* Renumbers a gallery contiguously (0..n-1). Order: current `position`
|
|
61
|
+
* ascending (empty/invalid last); ties — the duplicated positions an older
|
|
62
|
+
* client could leave — go oldest first (`created_at`, then `id`), so a
|
|
63
|
+
* product's original photo stays ahead of the ones uploaded later.
|
|
64
|
+
* `updates` holds only the rows whose stored position differs.
|
|
65
|
+
*/
|
|
66
|
+
export declare function contiguousPositionUpdates(rows: Record<string, any>[], positionKey?: string): {
|
|
67
|
+
ordered: Record<string, any>[];
|
|
68
|
+
updates: Array<{
|
|
69
|
+
id: string | number;
|
|
70
|
+
position: number;
|
|
71
|
+
}>;
|
|
72
|
+
};
|
|
54
73
|
export declare function objectLabel(value: unknown): string | undefined;
|
|
55
74
|
export declare function formatRelationCell(row: Record<string, unknown>, col: ColumnDefinition): string;
|
|
56
75
|
export interface PivotRowLike {
|
|
@@ -127,4 +146,12 @@ export declare function diffSelection(prev: ReadonlyArray<string>, next: Readonl
|
|
|
127
146
|
* non-FK string-ish value. Falls back to the row id, then to '—'.
|
|
128
147
|
*/
|
|
129
148
|
export declare function pickOptionLabel(row: TargetRowLike | null | undefined, displayKey: string | undefined, columns: ReadonlyArray<ColumnDefinition> | null | undefined): string;
|
|
149
|
+
/**
|
|
150
|
+
* The parent's own image (e.g. `Product.image`) when it is the one the store
|
|
151
|
+
* serves first: the image column declares `main_from_parent`, the parent has
|
|
152
|
+
* that image and the gallery has NO rows at all (variant photos included). With
|
|
153
|
+
* any row, the store serves the gallery first, so the first photo is the main
|
|
154
|
+
* one and showing the parent's image as «Principal» would be wrong.
|
|
155
|
+
*/
|
|
156
|
+
export declare function galleryLeadImage(imageColumn: ColumnDefinition | undefined, parent: Record<string, unknown> | null | undefined, rows: Array<Record<string, any>>): string | undefined;
|
|
130
157
|
//# sourceMappingURL=dynamic-relation-helpers.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dynamic-relation-helpers.d.ts","sourceRoot":"","sources":["../src/dynamic-relation-helpers.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,cAAc,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AAiB9E,MAAM,MAAM,mBAAmB,GAAG,aAAa,GAAG,cAAc,CAAA;AAuBhE,wBAAgB,uBAAuB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAI5D;AAUD,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,gBAAgB,GAAG,OAAO,GAAG,MAAM,GAAG,SAAS,CAQrF;AAED,MAAM,MAAM,cAAc,GAAG,aAAa,GAAG,cAAc,GAAG,eAAe,CAAA;AAE7E
|
|
1
|
+
{"version":3,"file":"dynamic-relation-helpers.d.ts","sourceRoot":"","sources":["../src/dynamic-relation-helpers.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,cAAc,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AAiB9E,MAAM,MAAM,mBAAmB,GAAG,aAAa,GAAG,cAAc,CAAA;AAuBhE,wBAAgB,uBAAuB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAI5D;AAUD,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,gBAAgB,GAAG,OAAO,GAAG,MAAM,GAAG,SAAS,CAQrF;AAED,MAAM,MAAM,cAAc,GAAG,aAAa,GAAG,cAAc,GAAG,eAAe,CAAA;AAE7E;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,WAAW,gBAAgB;IAC7B,IAAI,CAAC,EAAE,QAAQ,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EAAE,MAAM,GACtB,MAAM,EAAE,CASV;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAC9B,SAAS,EAAE,aAAa,CAAC,YAAY,CAAC,GAAG,IAAI,GAAG,SAAS,EACzD,aAAa,EAAE,MAAM,GACtB,GAAG,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC,CAU9B;AAED;;;;;GAKG;AACH,wBAAgB,aAAa,CACzB,IAAI,EAAE,aAAa,CAAC,MAAM,CAAC,EAC3B,IAAI,EAAE,aAAa,CAAC,MAAM,CAAC,GAC5B;IAAE,KAAK,EAAE,MAAM,EAAE,CAAC;IAAC,QAAQ,EAAE,MAAM,EAAE,CAAA;CAAE,CAYzC;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAC3B,GAAG,EAAE,aAAa,GAAG,IAAI,GAAG,SAAS,EACrC,UAAU,EAAE,MAAM,GAAG,SAAS,EAC9B,OAAO,EAAE,aAAa,CAAC,gBAAgB,CAAC,GAAG,IAAI,GAAG,SAAS,GAC5D,MAAM,CAiBR;AAED;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAC5B,WAAW,EAAE,gBAAgB,GAAG,SAAS,EACzC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,GAAG,SAAS,EAClD,IAAI,EAAE,KAAK,CAAC,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,GACjC,MAAM,GAAG,SAAS,CAOpB"}
|
|
@@ -75,6 +75,9 @@ export function relationColumnUi(col) {
|
|
|
75
75
|
out.emptyLabel = empty;
|
|
76
76
|
if (sc.gallery === true)
|
|
77
77
|
out.gallery = true;
|
|
78
|
+
const mfp = sc.main_from_parent ?? sc.mainFromParent;
|
|
79
|
+
if (typeof mfp === 'string' && mfp.trim() !== '')
|
|
80
|
+
out.mainFromParent = mfp.trim();
|
|
78
81
|
return out;
|
|
79
82
|
}
|
|
80
83
|
/** The gallery image column (media + `display_config.gallery: true`), if any. */
|
|
@@ -149,6 +152,45 @@ export function nextRelationPosition(rows, positionKey = 'position') {
|
|
|
149
152
|
}
|
|
150
153
|
return max + 1;
|
|
151
154
|
}
|
|
155
|
+
/**
|
|
156
|
+
* Renumbers a gallery contiguously (0..n-1). Order: current `position`
|
|
157
|
+
* ascending (empty/invalid last); ties — the duplicated positions an older
|
|
158
|
+
* client could leave — go oldest first (`created_at`, then `id`), so a
|
|
159
|
+
* product's original photo stays ahead of the ones uploaded later.
|
|
160
|
+
* `updates` holds only the rows whose stored position differs.
|
|
161
|
+
*/
|
|
162
|
+
export function contiguousPositionUpdates(rows, positionKey = 'position') {
|
|
163
|
+
const pos = (r) => {
|
|
164
|
+
const raw = r?.[positionKey];
|
|
165
|
+
const n = Number(raw);
|
|
166
|
+
return raw === null || raw === undefined || raw === '' || !Number.isFinite(n) ? Infinity : n;
|
|
167
|
+
};
|
|
168
|
+
const ordered = rows
|
|
169
|
+
.map((r, i) => ({ r, i }))
|
|
170
|
+
.sort((a, b) => {
|
|
171
|
+
const pa = pos(a.r);
|
|
172
|
+
const pb = pos(b.r);
|
|
173
|
+
if (pa !== pb)
|
|
174
|
+
return pa < pb ? -1 : 1;
|
|
175
|
+
const ca = String(a.r?.created_at ?? '');
|
|
176
|
+
const cb = String(b.r?.created_at ?? '');
|
|
177
|
+
if (ca && cb && ca !== cb)
|
|
178
|
+
return ca < cb ? -1 : 1;
|
|
179
|
+
// Last resort: the id, so two tabs (or two runs) agree on the order.
|
|
180
|
+
const ia = String(a.r?.id ?? '');
|
|
181
|
+
const ib = String(b.r?.id ?? '');
|
|
182
|
+
if (ia !== ib)
|
|
183
|
+
return ia < ib ? -1 : 1;
|
|
184
|
+
return a.i - b.i;
|
|
185
|
+
})
|
|
186
|
+
.map((x) => x.r);
|
|
187
|
+
const updates = [];
|
|
188
|
+
ordered.forEach((r, i) => {
|
|
189
|
+
if (pos(r) !== i && r?.id !== undefined && r?.id !== null)
|
|
190
|
+
updates.push({ id: r.id, position: i });
|
|
191
|
+
});
|
|
192
|
+
return { ordered, updates };
|
|
193
|
+
}
|
|
152
194
|
// Pulls a human label off a resolved relation/user object a backend serves:
|
|
153
195
|
// `{ value, label }` (FK sibling), `{ name, … }` (user object such as
|
|
154
196
|
// created_by) or `{ title }`. Returns undefined for plain/empty objects so the
|
|
@@ -440,3 +482,20 @@ export function pickOptionLabel(row, displayKey, columns) {
|
|
|
440
482
|
return String(row.id);
|
|
441
483
|
return '—';
|
|
442
484
|
}
|
|
485
|
+
/**
|
|
486
|
+
* The parent's own image (e.g. `Product.image`) when it is the one the store
|
|
487
|
+
* serves first: the image column declares `main_from_parent`, the parent has
|
|
488
|
+
* that image and the gallery has NO rows at all (variant photos included). With
|
|
489
|
+
* any row, the store serves the gallery first, so the first photo is the main
|
|
490
|
+
* one and showing the parent's image as «Principal» would be wrong.
|
|
491
|
+
*/
|
|
492
|
+
export function galleryLeadImage(imageColumn, parent, rows) {
|
|
493
|
+
if (!imageColumn || !parent || rows.length > 0)
|
|
494
|
+
return undefined;
|
|
495
|
+
const field = relationColumnUi(imageColumn).mainFromParent;
|
|
496
|
+
if (!field)
|
|
497
|
+
return undefined;
|
|
498
|
+
const raw = parent[field];
|
|
499
|
+
const url = typeof raw === 'string' ? raw.trim() : '';
|
|
500
|
+
return url || undefined;
|
|
501
|
+
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dynamic-relation.d.ts","sourceRoot":"","sources":["../src/dynamic-relation.tsx"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"dynamic-relation.d.ts","sourceRoot":"","sources":["../src/dynamic-relation.tsx"],"names":[],"mappings":"AAiFA,YAAY,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAA;AACrE,OAAO,EACH,kBAAkB,EAClB,uBAAuB,EACvB,kBAAkB,EAClB,yBAAyB,EACzB,wBAAwB,EACxB,aAAa,EACb,wBAAwB,EACxB,kBAAkB,EAClB,WAAW,EACX,eAAe,EACf,cAAc,GACjB,MAA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