@asteby/metacore-runtime-react 53.11.0 → 53.12.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 +20 -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 +14 -0
- package/dist/dynamic-relation-helpers.d.ts.map +1 -1
- package/dist/dynamic-relation-helpers.js +39 -0
- package/dist/dynamic-relation.d.ts.map +1 -1
- package/dist/dynamic-relation.js +94 -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.js +1 -1
- 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 +60 -1
- 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 +39 -0
- package/src/dynamic-relation.tsx +92 -21
- package/src/index.ts +12 -0
- package/src/relation-gallery.tsx +5 -4
|
@@ -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":"AAwBA,OAAO,KAKN,MAAM,OAAO,CAAA;AAMd,OAAO,EAKH,KAA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Aa,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
|
}
|
|
@@ -51,6 +51,20 @@ export declare function relationPositionSortable(metadata: Pick<TableMetadata, '
|
|
|
51
51
|
export declare function sortRelationRows<T extends Record<string, any>>(rows: T[], positionKey?: string): T[];
|
|
52
52
|
/** Default position for a new child row: one past the highest loaded, 0 when empty. */
|
|
53
53
|
export declare function nextRelationPosition(rows: Record<string, any>[], positionKey?: string): number;
|
|
54
|
+
/**
|
|
55
|
+
* Renumbers a gallery contiguously (0..n-1). Order: current `position`
|
|
56
|
+
* ascending (empty/invalid last); ties — the duplicated positions an older
|
|
57
|
+
* client could leave — go oldest first (`created_at`, then `id`), so a
|
|
58
|
+
* product's original photo stays ahead of the ones uploaded later.
|
|
59
|
+
* `updates` holds only the rows whose stored position differs.
|
|
60
|
+
*/
|
|
61
|
+
export declare function contiguousPositionUpdates(rows: Record<string, any>[], positionKey?: string): {
|
|
62
|
+
ordered: Record<string, any>[];
|
|
63
|
+
updates: Array<{
|
|
64
|
+
id: string | number;
|
|
65
|
+
position: number;
|
|
66
|
+
}>;
|
|
67
|
+
};
|
|
54
68
|
export declare function objectLabel(value: unknown): string | undefined;
|
|
55
69
|
export declare function formatRelationCell(row: Record<string, unknown>, col: ColumnDefinition): string;
|
|
56
70
|
export interface PivotRowLike {
|
|
@@ -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;;;;;;;;;;;;;GAaG;AACH,MAAM,WAAW,gBAAgB;IAC7B,IAAI,CAAC,EAAE,QAAQ,GAAG,UAAU,CAAA;IAC5B,MAAM,CAAC,EAAE,cAAc,CAAA;IACvB,iBAAiB,CAAC,EAAE,MAAM,CAAA;IAC1B,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,OAAO,CAAC,EAAE,OAAO,CAAA;CACpB;AAID,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,gBAAgB,GAAG,gBAAgB,CAaxE;AAED,iFAAiF;AACjF,wBAAgB,qBAAqB,CACjC,QAAQ,EAAE,IAAI,CAAC,aAAa,EAAE,SAAS,CAAC,GAAG,IAAI,GAAG,SAAS,GAC5D,gBAAgB,GAAG,SAAS,CAE9B;AAED,MAAM,WAAW,SAAS;IACtB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,MAAM,CAAC,EAAE,MAAM,CAAA;CAClB;AAED;;;;GAIG;AACH,wBAAgB,qBAAqB,CACjC,QAAQ,EAAE,IAAI,CAAC,aAAa,EAAE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MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAC5B,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAcrB;AAED;;;;GAIG;AACH,wBAAgB,wBAAwB,CACpC,SAAS,EAAE,aAAa,CAAC,YAAY,CAAC,GAAG,IAAI,GAAG,SAAS,EACzD,aAAa,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"}
|
|
@@ -149,6 +149,45 @@ export function nextRelationPosition(rows, positionKey = 'position') {
|
|
|
149
149
|
}
|
|
150
150
|
return max + 1;
|
|
151
151
|
}
|
|
152
|
+
/**
|
|
153
|
+
* Renumbers a gallery contiguously (0..n-1). Order: current `position`
|
|
154
|
+
* ascending (empty/invalid last); ties — the duplicated positions an older
|
|
155
|
+
* client could leave — go oldest first (`created_at`, then `id`), so a
|
|
156
|
+
* product's original photo stays ahead of the ones uploaded later.
|
|
157
|
+
* `updates` holds only the rows whose stored position differs.
|
|
158
|
+
*/
|
|
159
|
+
export function contiguousPositionUpdates(rows, positionKey = 'position') {
|
|
160
|
+
const pos = (r) => {
|
|
161
|
+
const raw = r?.[positionKey];
|
|
162
|
+
const n = Number(raw);
|
|
163
|
+
return raw === null || raw === undefined || raw === '' || !Number.isFinite(n) ? Infinity : n;
|
|
164
|
+
};
|
|
165
|
+
const ordered = rows
|
|
166
|
+
.map((r, i) => ({ r, i }))
|
|
167
|
+
.sort((a, b) => {
|
|
168
|
+
const pa = pos(a.r);
|
|
169
|
+
const pb = pos(b.r);
|
|
170
|
+
if (pa !== pb)
|
|
171
|
+
return pa < pb ? -1 : 1;
|
|
172
|
+
const ca = String(a.r?.created_at ?? '');
|
|
173
|
+
const cb = String(b.r?.created_at ?? '');
|
|
174
|
+
if (ca && cb && ca !== cb)
|
|
175
|
+
return ca < cb ? -1 : 1;
|
|
176
|
+
// Last resort: the id, so two tabs (or two runs) agree on the order.
|
|
177
|
+
const ia = String(a.r?.id ?? '');
|
|
178
|
+
const ib = String(b.r?.id ?? '');
|
|
179
|
+
if (ia !== ib)
|
|
180
|
+
return ia < ib ? -1 : 1;
|
|
181
|
+
return a.i - b.i;
|
|
182
|
+
})
|
|
183
|
+
.map((x) => x.r);
|
|
184
|
+
const updates = [];
|
|
185
|
+
ordered.forEach((r, i) => {
|
|
186
|
+
if (pos(r) !== i && r?.id !== undefined && r?.id !== null)
|
|
187
|
+
updates.push({ id: r.id, position: i });
|
|
188
|
+
});
|
|
189
|
+
return { ordered, updates };
|
|
190
|
+
}
|
|
152
191
|
// Pulls a human label off a resolved relation/user object a backend serves:
|
|
153
192
|
// `{ value, label }` (FK sibling), `{ name, … }` (user object such as
|
|
154
193
|
// created_by) or `{ title }`. Returns undefined for plain/empty objects so the
|
|
@@ -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":[],"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;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAA;CACtB;AAED,MAAM,MAAM,oBAAoB,GAC1B,6BAA6B,GAC7B,8BAA8B,CAAA;AAEpC,wBAAgB,eAAe,CAAC,KAAK,EAAE,oBAAoB,+BAK1D"}
|
package/dist/dynamic-relation.js
CHANGED
|
@@ -24,7 +24,7 @@ import { dedupeById, useInfiniteScrollSentinel } from './use-infinite-scroll';
|
|
|
24
24
|
import { toast } from 'sonner';
|
|
25
25
|
import { RelationGallery } from './relation-gallery';
|
|
26
26
|
import { extractUploadedValue, readImageSize } from './upload-field';
|
|
27
|
-
import { buildCreatePayload, buildPivotAttachPayload, buildPivotRowIndex, buildRelationFilterParams, deriveRelationFormFields, diffSelection, extractSelectedTargetIds, pickOptionLabel, relationColumnUi, relationDerivedValues, relationGalleryColumn, relationInitialValues, relationPositionKey, relationPositionSortable, relationRowKey, sortRelationRows, } from './dynamic-relation-helpers';
|
|
27
|
+
import { buildCreatePayload, buildPivotAttachPayload, buildPivotRowIndex, buildRelationFilterParams, deriveRelationFormFields, diffSelection, extractSelectedTargetIds, pickOptionLabel, relationColumnUi, relationDerivedValues, contiguousPositionUpdates, relationGalleryColumn, relationInitialValues, relationPositionKey, relationPositionSortable, relationRowKey, sortRelationRows, } from './dynamic-relation-helpers';
|
|
28
28
|
export { buildCreatePayload, buildPivotAttachPayload, buildPivotRowIndex, buildRelationFilterParams, deriveRelationFormFields, diffSelection, extractSelectedTargetIds, formatRelationCell, objectLabel, pickOptionLabel, relationRowKey, } from './dynamic-relation-helpers';
|
|
29
29
|
const DEFAULT_STRINGS = {
|
|
30
30
|
title: '',
|
|
@@ -340,10 +340,74 @@ function OneToManyRelation({ kind, model, foreignKey, parentId, filters, endpoin
|
|
|
340
340
|
}
|
|
341
341
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
342
342
|
}, [api, dataEndpoint, editingRow, fetchAll, foreignKey, filtersKey, onChange, parentId, metadata, rows]);
|
|
343
|
+
// Highest position this panel created itself. `rows` can lag behind the
|
|
344
|
+
// rows just created (the list refreshes after the batch), so two uploads in
|
|
345
|
+
// a row must not both read the same stale maximum. Reset per parent.
|
|
346
|
+
const createdMaxPositionRef = useRef(-1);
|
|
347
|
+
useEffect(() => { createdMaxPositionRef.current = -1; }, [parentId]);
|
|
348
|
+
// Position writes (reorder and renumber) run one after another, never
|
|
349
|
+
// interleaved: a renumber that read the server before a drag would
|
|
350
|
+
// otherwise overwrite the order the user just chose.
|
|
351
|
+
const positionQueueRef = useRef(Promise.resolve());
|
|
352
|
+
const enqueuePositions = useCallback((fn) => {
|
|
353
|
+
const run = positionQueueRef.current.then(fn, fn);
|
|
354
|
+
positionQueueRef.current = run.catch(() => undefined);
|
|
355
|
+
return run;
|
|
356
|
+
}, []);
|
|
357
|
+
// Renumbers the gallery 0..n-1 from what the SERVER holds (read when the
|
|
358
|
+
// job runs, not from state): heals duplicated positions left by older
|
|
359
|
+
// clients and closes the gap a deleted photo leaves. Reads every page;
|
|
360
|
+
// writes only the rows that differ; a failed write does not stop the rest.
|
|
361
|
+
const normalizePositions = useCallback(() => enqueuePositions(async () => {
|
|
362
|
+
if (!positionKey || !relationGalleryColumn(metadataRef.current))
|
|
363
|
+
return;
|
|
364
|
+
try {
|
|
365
|
+
const fresh = [];
|
|
366
|
+
for (let page = 1; page <= 20; page++) {
|
|
367
|
+
const res = (await api.get(dataEndpoint, {
|
|
368
|
+
params: {
|
|
369
|
+
...buildRelationFilterParams(foreignKey, parentId, filters),
|
|
370
|
+
page,
|
|
371
|
+
per_page: GALLERY_PAGE_SIZE,
|
|
372
|
+
sortBy: positionKey,
|
|
373
|
+
order: 'asc',
|
|
374
|
+
},
|
|
375
|
+
}));
|
|
376
|
+
if (!res?.data?.success)
|
|
377
|
+
return;
|
|
378
|
+
const got = res.data.data ?? [];
|
|
379
|
+
fresh.push(...got);
|
|
380
|
+
if (got.length < GALLERY_PAGE_SIZE)
|
|
381
|
+
break;
|
|
382
|
+
if (page === 20)
|
|
383
|
+
return; // too many to renumber safely
|
|
384
|
+
}
|
|
385
|
+
const { updates } = contiguousPositionUpdates(dedupeById([], fresh), positionKey);
|
|
386
|
+
let failed = 0;
|
|
387
|
+
for (const u of updates) {
|
|
388
|
+
try {
|
|
389
|
+
const r = (await api.put(`${dataEndpoint}/${u.id}`, { [positionKey]: u.position }));
|
|
390
|
+
if (r?.data?.success === false)
|
|
391
|
+
failed++;
|
|
392
|
+
}
|
|
393
|
+
catch {
|
|
394
|
+
failed++;
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
createdMaxPositionRef.current = Math.max(createdMaxPositionRef.current, fresh.length - 1);
|
|
398
|
+
if (failed)
|
|
399
|
+
toast.error(labels.reorderError ?? 'No se pudo guardar el nuevo orden.');
|
|
400
|
+
}
|
|
401
|
+
catch (err) {
|
|
402
|
+
console.error('DynamicRelation normalize positions error', err);
|
|
403
|
+
}
|
|
404
|
+
}),
|
|
405
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
406
|
+
[api, dataEndpoint, positionKey, foreignKey, parentId, filtersKey, enqueuePositions]);
|
|
343
407
|
// ── Gallery (opt-in: image column with display_config.gallery) ─────────
|
|
344
408
|
// Same contracts as the table: POST /upload (multipart) for the file, then
|
|
345
409
|
// POST /data/<model> for the row. Positions are assigned in pick order.
|
|
346
|
-
const galleryUpload = useCallback(async (file,
|
|
410
|
+
const galleryUpload = useCallback(async (file, _offset, onProgress, reuseUrl) => {
|
|
347
411
|
if (!galleryColumn)
|
|
348
412
|
return;
|
|
349
413
|
const size = await readImageSize(file);
|
|
@@ -371,8 +435,10 @@ function OneToManyRelation({ kind, model, foreignKey, parentId, filters, endpoin
|
|
|
371
435
|
throw new Error('upload failed');
|
|
372
436
|
}
|
|
373
437
|
const derived = relationDerivedValues(metadata, { isCreate: true, rows, image: size });
|
|
374
|
-
if (positionKey && typeof derived[positionKey] === 'number')
|
|
375
|
-
derived[positionKey]
|
|
438
|
+
if (positionKey && typeof derived[positionKey] === 'number') {
|
|
439
|
+
derived[positionKey] = Math.max(derived[positionKey], createdMaxPositionRef.current + 1);
|
|
440
|
+
createdMaxPositionRef.current = derived[positionKey];
|
|
441
|
+
}
|
|
376
442
|
const payload = {
|
|
377
443
|
...(filters || {}),
|
|
378
444
|
...buildCreatePayload(foreignKey, parentId, {
|
|
@@ -400,24 +466,26 @@ function OneToManyRelation({ kind, model, foreignKey, parentId, filters, endpoin
|
|
|
400
466
|
return;
|
|
401
467
|
// Optimistic: show the new order now, persist only what changed.
|
|
402
468
|
setRows(ordered.map((r, i) => ({ ...r, [positionKey]: i })));
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
469
|
+
await enqueuePositions(async () => {
|
|
470
|
+
try {
|
|
471
|
+
await Promise.all(ordered.map((r, i) => {
|
|
472
|
+
const raw = r[positionKey];
|
|
473
|
+
const same = raw !== null && raw !== undefined && raw !== '' && Number(raw) === i;
|
|
474
|
+
return same ? null : api.put(`${dataEndpoint}/${r.id}`, { [positionKey]: i });
|
|
475
|
+
}));
|
|
476
|
+
onChange?.();
|
|
477
|
+
}
|
|
478
|
+
catch (err) {
|
|
479
|
+
console.error('DynamicRelation reorder error', err);
|
|
480
|
+
toast.error(labels.reorderError ?? 'No se pudo guardar el nuevo orden.');
|
|
481
|
+
}
|
|
482
|
+
finally {
|
|
483
|
+
await refreshSilently();
|
|
484
|
+
}
|
|
485
|
+
});
|
|
418
486
|
},
|
|
419
487
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
420
|
-
[api, dataEndpoint, positionKey, refreshSilently, onChange]);
|
|
488
|
+
[api, dataEndpoint, positionKey, refreshSilently, onChange, enqueuePositions]);
|
|
421
489
|
// Confirmed delete → hidden at once, «Deshacer» for a few seconds, then the
|
|
422
490
|
// real DELETE. Closing the panel before the toast ends still deletes.
|
|
423
491
|
const deleteWithUndo = useCallback((row) => {
|
|
@@ -431,6 +499,7 @@ function OneToManyRelation({ kind, model, foreignKey, parentId, filters, endpoin
|
|
|
431
499
|
const res = await api.delete(`${dataEndpoint}/${row.id}`);
|
|
432
500
|
if (!res.data?.success)
|
|
433
501
|
throw new Error('delete failed');
|
|
502
|
+
await normalizePositions();
|
|
434
503
|
onChange?.();
|
|
435
504
|
}
|
|
436
505
|
catch (err) {
|
|
@@ -454,6 +523,7 @@ function OneToManyRelation({ kind, model, foreignKey, parentId, filters, endpoin
|
|
|
454
523
|
onClick: () => {
|
|
455
524
|
undone = true;
|
|
456
525
|
clearTimeout(timer);
|
|
526
|
+
void normalizePositions().then(() => refreshSilently());
|
|
457
527
|
setPendingDelete((s) => {
|
|
458
528
|
const n = new Set(s);
|
|
459
529
|
n.delete(key);
|
|
@@ -464,7 +534,7 @@ function OneToManyRelation({ kind, model, foreignKey, parentId, filters, endpoin
|
|
|
464
534
|
});
|
|
465
535
|
},
|
|
466
536
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
467
|
-
[api, dataEndpoint, refreshSilently, onChange]);
|
|
537
|
+
[api, dataEndpoint, refreshSilently, onChange, normalizePositions]);
|
|
468
538
|
const handleDelete = useCallback(async () => {
|
|
469
539
|
if (!rowToDelete)
|
|
470
540
|
return;
|
|
@@ -475,6 +545,7 @@ function OneToManyRelation({ kind, model, foreignKey, parentId, filters, endpoin
|
|
|
475
545
|
throw new Error('delete failed');
|
|
476
546
|
setRowToDelete(null);
|
|
477
547
|
await fetchAll();
|
|
548
|
+
void normalizePositions().then(() => refreshSilently());
|
|
478
549
|
onChange?.();
|
|
479
550
|
}
|
|
480
551
|
catch (err) {
|
|
@@ -483,12 +554,12 @@ function OneToManyRelation({ kind, model, foreignKey, parentId, filters, endpoin
|
|
|
483
554
|
finally {
|
|
484
555
|
setSubmitting(false);
|
|
485
556
|
}
|
|
486
|
-
}, [api, dataEndpoint, fetchAll, onChange, rowToDelete]);
|
|
557
|
+
}, [api, dataEndpoint, fetchAll, onChange, rowToDelete, normalizePositions, refreshSilently]);
|
|
487
558
|
return (_jsxs("div", { className: className, "data-relation-kind": kind, "data-relation-model": model, children: [(labels.title || canCreate || showSearch) && (_jsxs("div", { className: "flex items-center justify-between gap-2 pb-3", children: [labels.title ? _jsx("h3", { className: "text-sm font-medium", children: labels.title }) : _jsx("span", {}), _jsxs("div", { className: "flex items-center gap-2", children: [showSearch && (_jsxs("div", { className: "relative", children: [_jsx(Search, { className: "absolute start-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" }), _jsx(Input, { value: search, onChange: (e) => setSearch(e.target.value), placeholder: labels.searchPlaceholder, className: "h-8 w-40 ps-7 sm:w-56" })] })), canCreate && !galleryColumn && (_jsxs(Button, { size: "sm", variant: "outline", onClick: () => { setEditingRow(null); uploadedImageRef.current = null; setFormOpen(true); }, children: [_jsx(Plus, { className: "h-4 w-4 mr-1" }), labels.addLabel] }))] })] })), loading ? (_jsx("div", { className: "space-y-2", children: Array.from({ length: 3 }).map((_, i) => (_jsx(Skeleton, { className: "h-10 w-full" }, `rel-skeleton-${i}`))) })) : galleryColumn && fetchErrorStatus === null ? (_jsx(RelationGallery, { rows: orderedRows, rowKey: (row, i) => relationRowKey(row, i, foreignKey), imageKey: galleryColumn.key, captionKey: captionKey, getImageUrl: (p) => getImageUrl(p), accept: galleryColumn.accept || 'image/*', maxSize: (() => {
|
|
488
559
|
const sc = (galleryColumn.styleConfig ?? {});
|
|
489
560
|
const n = Number(sc.max_size ?? sc.maxSize);
|
|
490
561
|
return Number.isFinite(n) && n > 0 ? n : undefined;
|
|
491
|
-
})(), canCreate: canCreate, canEdit: canEdit, canReorder: canEdit && !!positionKey, canDelete: canDelete, hiddenKeys: pendingDelete, onUpload: galleryUpload, onUploadsSettled: () => { void refreshSilently(); onChange?.(); }, onReorder: galleryReorder, onEdit: canEdit ? (row) => { setEditingRow(row); uploadedImageRef.current = null; setFormOpen(true); } : undefined, onDelete: canDelete ? (row) => setRowToDelete(row) : undefined })) : rows.length === 0 ? (_jsx("div", { className: "text-center text-sm text-muted-foreground py-8 border rounded-md bg-muted/30", children: fetchErrorStatus === 403
|
|
562
|
+
})(), canCreate: canCreate, canEdit: canEdit, canReorder: canEdit && !!positionKey, canDelete: canDelete, hiddenKeys: pendingDelete, onUpload: galleryUpload, onUploadsSettled: () => { void normalizePositions().then(() => refreshSilently()); onChange?.(); }, onReorder: galleryReorder, onEdit: canEdit ? (row) => { setEditingRow(row); uploadedImageRef.current = null; setFormOpen(true); } : undefined, onDelete: canDelete ? (row) => setRowToDelete(row) : undefined })) : rows.length === 0 ? (_jsx("div", { className: "text-center text-sm text-muted-foreground py-8 border rounded-md bg-muted/30", children: fetchErrorStatus === 403
|
|
492
563
|
? (labels.forbiddenState ?? 'Sin permiso para ver estos registros.')
|
|
493
564
|
: fetchErrorStatus !== null
|
|
494
565
|
? (labels.errorState ?? 'No se pudieron cargar los registros relacionados.')
|
package/dist/index.d.ts
CHANGED
|
@@ -150,4 +150,6 @@ export { RecordPrefillBar, type RecordPrefillBarProps } from './record-prefill-b
|
|
|
150
150
|
export { RowActionsMenu, RowActionMenuItem, RowActionsModelContext, type RowActionsMenuProps, } from './row-actions-menu';
|
|
151
151
|
export { classifyActionPriority, isActionProviderActive, isRecordActionProviderActive, resolveRecordActions, splitActionsByPriority, useRecordActions, type ActionPriority, type PrioritizableAction, type RecordActionContext, type RecordActionContribution, type ResolvedRecordAction, type SplitActions, } from './record-actions';
|
|
152
152
|
export * from './capability-providers';
|
|
153
|
+
export { BulkImageImportButton, BulkImageDialog, type BulkImageImportButtonProps, } from './bulk-image-dialog';
|
|
154
|
+
export { buildPreview as buildBulkImagePreview, parseImageName as parseBulkImageName, deriveBulkImageTarget, type BulkImageTarget, type BatchLog as BulkImageBatchLog, } from './bulk-image-import';
|
|
153
155
|
//# sourceMappingURL=index.d.ts.map
|