@cervio/plugin-sdk 2.2.0 → 2.3.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/README.md +62 -0
- package/dist/forms/index.d.ts +360 -0
- package/dist/forms/index.js +416 -0
- package/dist/forms/react.d.ts +381 -0
- package/dist/forms/react.js +1159 -0
- package/dist/index.d.ts +12 -1
- package/dist/views/index.d.ts +450 -0
- package/dist/views/index.js +570 -0
- package/dist/views/react.d.ts +406 -0
- package/dist/views/react.js +1368 -0
- package/package.json +22 -2
|
@@ -0,0 +1,1368 @@
|
|
|
1
|
+
import { useCallback, useSyncExternalStore, useState, useEffect, useMemo, useRef } from 'react';
|
|
2
|
+
import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
|
|
3
|
+
|
|
4
|
+
// src/views/react.ts
|
|
5
|
+
|
|
6
|
+
// ../view-core/dist/index.js
|
|
7
|
+
var __defProp = Object.defineProperty;
|
|
8
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
9
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
10
|
+
function isFilterValueActive(f) {
|
|
11
|
+
switch (f.type) {
|
|
12
|
+
case "text":
|
|
13
|
+
return f.operator === "equals" ? f.values.length > 0 : (f.value?.trim() ?? "") !== "";
|
|
14
|
+
case "number":
|
|
15
|
+
return f.operator === "between" ? f.min !== void 0 || f.max !== void 0 : f.value !== void 0;
|
|
16
|
+
case "date":
|
|
17
|
+
return f.operator === "between" ? !!f.from || !!f.to : !!f.value;
|
|
18
|
+
case "relation":
|
|
19
|
+
return f.values.length > 0;
|
|
20
|
+
case "boolean":
|
|
21
|
+
return typeof f.value === "boolean";
|
|
22
|
+
default:
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
function filtersStateToRules(state) {
|
|
27
|
+
return Object.entries(state).filter(([, f]) => isFilterValueActive(f)).map(([field, f]) => {
|
|
28
|
+
const { labels: _labels, ...rule } = f;
|
|
29
|
+
return { field, ...rule };
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
function filtersToQuery(state) {
|
|
33
|
+
return filtersStateToRules(state).map((rule) => {
|
|
34
|
+
const { type: _type, ...rest } = rule;
|
|
35
|
+
return rest;
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
var ViewApiError = class extends Error {
|
|
39
|
+
constructor(status, code, message) {
|
|
40
|
+
super(message);
|
|
41
|
+
__publicField(this, "status", status);
|
|
42
|
+
__publicField(this, "code", code);
|
|
43
|
+
this.name = "ViewApiError";
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
function createFetchTransport(opts = {}) {
|
|
47
|
+
const base = (opts.baseUrl ?? "").replace(/\/$/, "");
|
|
48
|
+
const doFetch = opts.fetchImpl ?? ((...a) => fetch(...a));
|
|
49
|
+
async function call(path, init = {}) {
|
|
50
|
+
const res = await doFetch(`${base}/api/v1${path}`, {
|
|
51
|
+
...init,
|
|
52
|
+
credentials: opts.credentials ?? "include",
|
|
53
|
+
headers: {
|
|
54
|
+
Accept: "application/json",
|
|
55
|
+
...init.body ? { "Content-Type": "application/json" } : {},
|
|
56
|
+
...opts.headers
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
let body = null;
|
|
60
|
+
try {
|
|
61
|
+
body = await res.json();
|
|
62
|
+
} catch {
|
|
63
|
+
}
|
|
64
|
+
if (!res.ok) {
|
|
65
|
+
const b = body ?? {};
|
|
66
|
+
throw new ViewApiError(res.status, b.error ?? `http_${res.status}`, b.message ?? b.error ?? res.statusText);
|
|
67
|
+
}
|
|
68
|
+
return body;
|
|
69
|
+
}
|
|
70
|
+
const scopeQs = (scope) => scope === "shared" ? "" : `?scope=${encodeURIComponent(scope)}`;
|
|
71
|
+
const v = (id) => encodeURIComponent(id);
|
|
72
|
+
return {
|
|
73
|
+
getFilterOptions: (viewId, key, opts2, signal) => {
|
|
74
|
+
const q = new URLSearchParams();
|
|
75
|
+
if (opts2.search?.trim()) q.set("search", opts2.search.trim());
|
|
76
|
+
if (opts2.limit) q.set("limit", String(opts2.limit));
|
|
77
|
+
if (opts2.cursor) q.set("cursor", opts2.cursor);
|
|
78
|
+
const qs = q.toString();
|
|
79
|
+
return call(`/views/${v(viewId)}/columns/${encodeURIComponent(key)}/options${qs ? `?${qs}` : ""}`, {
|
|
80
|
+
signal
|
|
81
|
+
});
|
|
82
|
+
},
|
|
83
|
+
getDefinition: (viewId, signal) => call(`/views/${v(viewId)}`, { signal }),
|
|
84
|
+
query: (viewId, body, signal) => call(`/views/${v(viewId)}/query`, { method: "POST", body: JSON.stringify(body), signal }),
|
|
85
|
+
getLayout: async (viewId, scope) => (await call(`/me/view-prefs/${v(viewId)}${scopeQs(scope)}`)).prefs ?? {},
|
|
86
|
+
putLayout: async (viewId, scope, layout) => (await call(`/me/view-prefs/${v(viewId)}${scopeQs(scope)}`, {
|
|
87
|
+
method: "PUT",
|
|
88
|
+
body: JSON.stringify({ prefs: layout })
|
|
89
|
+
})).prefs ?? {}
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
var NUMBER_TYPES = /* @__PURE__ */ new Set(["number", "currency", "integer", "decimal"]);
|
|
93
|
+
function isEmpty(v) {
|
|
94
|
+
return v == null || v === "" || Array.isArray(v) && v.length === 0;
|
|
95
|
+
}
|
|
96
|
+
function cellRawValue(v) {
|
|
97
|
+
if (isEmpty(v)) return "";
|
|
98
|
+
if (Array.isArray(v)) return v.map(cellRawValue).join(",");
|
|
99
|
+
if (typeof v === "object") {
|
|
100
|
+
const o = v;
|
|
101
|
+
return String(o.id ?? o.value ?? o.label ?? "");
|
|
102
|
+
}
|
|
103
|
+
return String(v);
|
|
104
|
+
}
|
|
105
|
+
function cellLabel(column, v) {
|
|
106
|
+
if (isEmpty(v)) return "";
|
|
107
|
+
if (Array.isArray(v)) return v.map((x) => cellLabel(column, x)).join(", ");
|
|
108
|
+
if (typeof v === "object") {
|
|
109
|
+
const o = v;
|
|
110
|
+
return String(o.label ?? o.id ?? "");
|
|
111
|
+
}
|
|
112
|
+
if (typeof v === "boolean") return v ? "true" : "false";
|
|
113
|
+
const opt = column?.options?.find((o) => o.value === String(v));
|
|
114
|
+
return opt ? opt.label : String(v);
|
|
115
|
+
}
|
|
116
|
+
function sortKey(column, v) {
|
|
117
|
+
if (isEmpty(v)) return null;
|
|
118
|
+
if (typeof v === "boolean") return v ? 1 : 0;
|
|
119
|
+
if (column && NUMBER_TYPES.has(column.type)) {
|
|
120
|
+
const n = typeof v === "number" ? v : Number(v);
|
|
121
|
+
if (Number.isFinite(n)) return n;
|
|
122
|
+
}
|
|
123
|
+
return cellLabel(column, v);
|
|
124
|
+
}
|
|
125
|
+
function compareKeys(a, b, collator) {
|
|
126
|
+
if (a === null && b === null) return 0;
|
|
127
|
+
if (a === null) return 1;
|
|
128
|
+
if (b === null) return -1;
|
|
129
|
+
if (typeof a === "number" && typeof b === "number") return a - b;
|
|
130
|
+
return collator.compare(String(a), String(b));
|
|
131
|
+
}
|
|
132
|
+
function collatorFor(locale) {
|
|
133
|
+
try {
|
|
134
|
+
return new Intl.Collator(locale || "it", { numeric: true, sensitivity: "base" });
|
|
135
|
+
} catch {
|
|
136
|
+
return new Intl.Collator("it", { numeric: true, sensitivity: "base" });
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
function sortRows(rows, columns, sorting, locale) {
|
|
140
|
+
const keys = sorting.filter((s) => columns.some((c) => c.key === s.key));
|
|
141
|
+
if (keys.length === 0) return rows;
|
|
142
|
+
const byKey = new Map(columns.map((c) => [c.key, c]));
|
|
143
|
+
const collator = collatorFor(locale);
|
|
144
|
+
return rows.map((row, i) => ({ row, i, k: keys.map((s) => sortKey(byKey.get(s.key), row.data[s.key])) })).sort((a, b) => {
|
|
145
|
+
for (let j = 0; j < keys.length; j++) {
|
|
146
|
+
const ka = a.k[j];
|
|
147
|
+
const kb = b.k[j];
|
|
148
|
+
const c = compareKeys(ka, kb, collator);
|
|
149
|
+
if (c !== 0) return ka === null || kb === null || !keys[j].desc ? c : -c;
|
|
150
|
+
}
|
|
151
|
+
return a.i - b.i;
|
|
152
|
+
}).map((x) => x.row);
|
|
153
|
+
}
|
|
154
|
+
function groupRows(rows, columns, grouping, sorting = [], locale) {
|
|
155
|
+
const byKey = new Map(columns.map((c) => [c.key, c]));
|
|
156
|
+
const keys = grouping.filter((k) => byKey.has(k));
|
|
157
|
+
if (keys.length === 0) return [];
|
|
158
|
+
const collator = collatorFor(locale);
|
|
159
|
+
const build = (list, level) => {
|
|
160
|
+
const key = keys[level];
|
|
161
|
+
const column = byKey.get(key);
|
|
162
|
+
const buckets = /* @__PURE__ */ new Map();
|
|
163
|
+
for (const row of list) {
|
|
164
|
+
const v = row.data[key];
|
|
165
|
+
const value = cellRawValue(v);
|
|
166
|
+
let b = buckets.get(value);
|
|
167
|
+
if (!b) {
|
|
168
|
+
b = { label: cellLabel(column, v), sortK: sortKey(column, v), rows: [] };
|
|
169
|
+
buckets.set(value, b);
|
|
170
|
+
}
|
|
171
|
+
b.rows.push(row);
|
|
172
|
+
}
|
|
173
|
+
const dir = sorting.find((s) => s.key === key);
|
|
174
|
+
const groups = [...buckets.entries()].map(([value, b]) => ({ value, ...b }));
|
|
175
|
+
groups.sort((a, b) => {
|
|
176
|
+
const c = dir ? compareKeys(a.sortK, b.sortK, collator) : compareKeys(a.label || null, b.label || null, collator);
|
|
177
|
+
return dir?.desc && a.sortK !== null && b.sortK !== null ? -c : c;
|
|
178
|
+
});
|
|
179
|
+
return groups.map((g) => ({
|
|
180
|
+
column: key,
|
|
181
|
+
value: g.value,
|
|
182
|
+
label: g.label,
|
|
183
|
+
count: g.rows.length,
|
|
184
|
+
rows: g.rows,
|
|
185
|
+
...level + 1 < keys.length ? { groups: build(g.rows, level + 1) } : {}
|
|
186
|
+
}));
|
|
187
|
+
};
|
|
188
|
+
return build(rows, 0);
|
|
189
|
+
}
|
|
190
|
+
var MIN_WIDTH = 40;
|
|
191
|
+
var MAX_WIDTH = 2e3;
|
|
192
|
+
function applyLayout(def, layout) {
|
|
193
|
+
if (!def) return { columns: [], visibleColumns: [] };
|
|
194
|
+
const byKey = new Map(def.columns.map((c) => [c.key, c]));
|
|
195
|
+
const ordered = [];
|
|
196
|
+
for (const k of layout.order ?? []) {
|
|
197
|
+
const c = byKey.get(k);
|
|
198
|
+
if (c && !ordered.includes(c)) ordered.push(c);
|
|
199
|
+
}
|
|
200
|
+
for (const c of def.columns) if (!ordered.includes(c)) ordered.push(c);
|
|
201
|
+
const left = new Set(layout.pinning?.left ?? []);
|
|
202
|
+
const right = new Set(layout.pinning?.right ?? []);
|
|
203
|
+
const columns = ordered.map((c) => ({
|
|
204
|
+
...c,
|
|
205
|
+
width: layout.sizing?.[c.key],
|
|
206
|
+
visible: layout.visibility?.[c.key] !== false,
|
|
207
|
+
pinned: left.has(c.key) ? "left" : right.has(c.key) ? "right" : false
|
|
208
|
+
}));
|
|
209
|
+
const visible = columns.filter((c) => c.visible);
|
|
210
|
+
return {
|
|
211
|
+
columns,
|
|
212
|
+
visibleColumns: [
|
|
213
|
+
...visible.filter((c) => c.pinned === "left"),
|
|
214
|
+
...visible.filter((c) => c.pinned === false),
|
|
215
|
+
...visible.filter((c) => c.pinned === "right")
|
|
216
|
+
]
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
function asError(e) {
|
|
220
|
+
return e instanceof Error ? e : new Error(String(e));
|
|
221
|
+
}
|
|
222
|
+
function createViewController(opts) {
|
|
223
|
+
const { transport } = opts;
|
|
224
|
+
const scope = opts.layoutScope === void 0 ? "shared" : opts.layoutScope;
|
|
225
|
+
const searchDelay = opts.searchDebounceMs ?? 250;
|
|
226
|
+
const saveDelay = opts.saveLayoutDelayMs ?? 400;
|
|
227
|
+
let state = {
|
|
228
|
+
status: "loading",
|
|
229
|
+
error: null,
|
|
230
|
+
definition: null,
|
|
231
|
+
columns: [],
|
|
232
|
+
visibleColumns: [],
|
|
233
|
+
rows: [],
|
|
234
|
+
groups: null,
|
|
235
|
+
sorting: [],
|
|
236
|
+
grouping: [],
|
|
237
|
+
complete: false,
|
|
238
|
+
loadingAll: false,
|
|
239
|
+
total: null,
|
|
240
|
+
hasMore: false,
|
|
241
|
+
loading: true,
|
|
242
|
+
loadingMore: false,
|
|
243
|
+
filters: { ...opts.initialFilters ?? {} },
|
|
244
|
+
search: opts.initialSearch ?? "",
|
|
245
|
+
layout: {},
|
|
246
|
+
layoutSaveError: null
|
|
247
|
+
};
|
|
248
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
249
|
+
let cursor;
|
|
250
|
+
let seq = 0;
|
|
251
|
+
let abort = null;
|
|
252
|
+
let searchTimer = null;
|
|
253
|
+
let saveTimer = null;
|
|
254
|
+
let pendingLayout = {};
|
|
255
|
+
let destroyed = false;
|
|
256
|
+
let raw = [];
|
|
257
|
+
const arrangeLimit = opts.arrangeLoadLimit ?? 1e3;
|
|
258
|
+
function arranged() {
|
|
259
|
+
const sorting = (state.layout.sorting ?? []).slice(0, 5);
|
|
260
|
+
const grouping = (state.layout.grouping ?? []).slice(0, 3);
|
|
261
|
+
const cols = state.definition?.columns ?? [];
|
|
262
|
+
const locale = opts.locale ?? state.definition?.locale;
|
|
263
|
+
const rows = sortRows(raw, cols, sorting, locale);
|
|
264
|
+
const known = grouping.filter((k) => cols.some((c) => c.key === k));
|
|
265
|
+
return { rows, groups: known.length ? groupRows(rows, cols, known, sorting, locale) : null, sorting, grouping };
|
|
266
|
+
}
|
|
267
|
+
function set(patch) {
|
|
268
|
+
if (destroyed) return;
|
|
269
|
+
if (patch.rows) raw = patch.rows;
|
|
270
|
+
state = { ...state, ...patch };
|
|
271
|
+
if ("layout" in patch || "definition" in patch) state = { ...state, ...applyLayout(state.definition, state.layout) };
|
|
272
|
+
if ("rows" in patch || "layout" in patch || "definition" in patch) state = { ...state, ...arranged() };
|
|
273
|
+
if (patch.loading === true || "filters" in patch || "search" in patch) state = { ...state, complete: false };
|
|
274
|
+
else if ("hasMore" in patch) state = { ...state, complete: !state.hasMore && !state.loading };
|
|
275
|
+
for (const l of [...listeners]) l(state);
|
|
276
|
+
}
|
|
277
|
+
const needsAll = () => !destroyed && (state.sorting.length > 0 || state.grouping.length > 0) && state.hasMore && !state.loading && raw.length < arrangeLimit;
|
|
278
|
+
async function loadAllIfArranged() {
|
|
279
|
+
if (state.loadingAll || !needsAll()) return;
|
|
280
|
+
set({ loadingAll: true });
|
|
281
|
+
let restart = false;
|
|
282
|
+
try {
|
|
283
|
+
while (needsAll()) {
|
|
284
|
+
if (inFlight && inFlight.seq === seq) {
|
|
285
|
+
await inFlight.promise.catch(() => {
|
|
286
|
+
});
|
|
287
|
+
continue;
|
|
288
|
+
}
|
|
289
|
+
const before = raw.length;
|
|
290
|
+
const my = seq;
|
|
291
|
+
await loadMorePage();
|
|
292
|
+
if (my !== seq) {
|
|
293
|
+
restart = true;
|
|
294
|
+
break;
|
|
295
|
+
}
|
|
296
|
+
if (raw.length === before) break;
|
|
297
|
+
}
|
|
298
|
+
} finally {
|
|
299
|
+
set({ loadingAll: false });
|
|
300
|
+
}
|
|
301
|
+
if (restart) await loadAllIfArranged();
|
|
302
|
+
}
|
|
303
|
+
function request(extra) {
|
|
304
|
+
const filters = filtersToQuery(state.filters);
|
|
305
|
+
return {
|
|
306
|
+
...filters.length ? { filters } : {},
|
|
307
|
+
...state.search.trim() ? { search: state.search.trim() } : {},
|
|
308
|
+
...opts.pageSize ? { limit: opts.pageSize } : {},
|
|
309
|
+
...opts.locale ? { locale: opts.locale } : {},
|
|
310
|
+
...opts.options ? { options: opts.options } : {},
|
|
311
|
+
...opts.relations ? { relations: opts.relations } : {},
|
|
312
|
+
...extra
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
async function reload() {
|
|
316
|
+
const my = ++seq;
|
|
317
|
+
abort?.abort();
|
|
318
|
+
abort = typeof AbortController !== "undefined" ? new AbortController() : null;
|
|
319
|
+
set({ loading: true, loadingMore: false });
|
|
320
|
+
try {
|
|
321
|
+
const countIt = (opts.count ?? true) && !state.search.trim();
|
|
322
|
+
const res = await transport.query(opts.view, request(countIt ? { count: true } : {}), abort?.signal);
|
|
323
|
+
if (my !== seq || destroyed) return;
|
|
324
|
+
cursor = res.page.next_cursor;
|
|
325
|
+
set({
|
|
326
|
+
status: "ready",
|
|
327
|
+
error: null,
|
|
328
|
+
rows: res.records,
|
|
329
|
+
hasMore: res.page.has_more,
|
|
330
|
+
total: typeof res.total === "number" ? res.total : null,
|
|
331
|
+
loading: false
|
|
332
|
+
});
|
|
333
|
+
void loadAllIfArranged().catch(() => {
|
|
334
|
+
});
|
|
335
|
+
} catch (e) {
|
|
336
|
+
if (my !== seq || destroyed) return;
|
|
337
|
+
if (e?.name === "AbortError") return;
|
|
338
|
+
set({ error: asError(e), loading: false, status: state.definition ? "ready" : "error" });
|
|
339
|
+
throw e;
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
let inFlight = null;
|
|
343
|
+
function loadMorePage() {
|
|
344
|
+
if (inFlight && inFlight.seq === seq) return inFlight.promise;
|
|
345
|
+
if (!state.hasMore || !cursor || state.loading) return Promise.resolve();
|
|
346
|
+
let resolve;
|
|
347
|
+
let reject;
|
|
348
|
+
const entry = { seq, promise: new Promise((res, rej) => (resolve = res, reject = rej)) };
|
|
349
|
+
inFlight = entry;
|
|
350
|
+
const done = () => {
|
|
351
|
+
if (inFlight === entry) inFlight = null;
|
|
352
|
+
};
|
|
353
|
+
loadOnePage().then(
|
|
354
|
+
() => (done(), resolve()),
|
|
355
|
+
(e) => (done(), reject(e))
|
|
356
|
+
);
|
|
357
|
+
return entry.promise;
|
|
358
|
+
}
|
|
359
|
+
async function loadOnePage() {
|
|
360
|
+
const my = seq;
|
|
361
|
+
set({ loadingMore: true });
|
|
362
|
+
try {
|
|
363
|
+
const res = await transport.query(opts.view, request({ cursor }));
|
|
364
|
+
if (my !== seq || destroyed) return;
|
|
365
|
+
cursor = res.page.next_cursor;
|
|
366
|
+
set({ rows: [...raw, ...res.records], hasMore: res.page.has_more, loadingMore: false, error: null });
|
|
367
|
+
} catch (e) {
|
|
368
|
+
if (my !== seq || destroyed) return;
|
|
369
|
+
set({ error: asError(e), loadingMore: false });
|
|
370
|
+
throw e;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
const ready = (async () => {
|
|
374
|
+
try {
|
|
375
|
+
const [definition, layout] = await Promise.all([
|
|
376
|
+
transport.getDefinition(opts.view),
|
|
377
|
+
scope ? transport.getLayout(opts.view, scope).catch(() => ({})) : Promise.resolve({})
|
|
378
|
+
]);
|
|
379
|
+
const filterable = new Set(definition.columns.filter((c) => c.filter && c.field).map((c) => c.field));
|
|
380
|
+
const filters = {};
|
|
381
|
+
const byField = new Map(definition.columns.map((c) => [c.field, c]));
|
|
382
|
+
for (const [k, v] of Object.entries(state.filters)) {
|
|
383
|
+
const f = byField.get(k)?.filter;
|
|
384
|
+
if (filterable.has(k) && f && f.type === v.type && f.operators.includes(v.operator)) filters[k] = v;
|
|
385
|
+
}
|
|
386
|
+
set({ definition, layout, filters });
|
|
387
|
+
await reload();
|
|
388
|
+
} catch (e) {
|
|
389
|
+
set({ status: "error", error: asError(e), loading: false });
|
|
390
|
+
throw e;
|
|
391
|
+
}
|
|
392
|
+
})();
|
|
393
|
+
ready.catch(() => {
|
|
394
|
+
});
|
|
395
|
+
function assertFilterable(field, value) {
|
|
396
|
+
if (!state.definition) return;
|
|
397
|
+
const col = state.definition.columns.find((c) => c.field === field);
|
|
398
|
+
if (!col?.filter) throw new Error(`"${field}" is not a filterable column of this view`);
|
|
399
|
+
if (!value) return;
|
|
400
|
+
if (value.type !== col.filter.type) {
|
|
401
|
+
throw new Error(`"${field}" filters as ${col.filter.type}, not ${value.type}`);
|
|
402
|
+
}
|
|
403
|
+
if (!col.filter.operators.includes(value.operator)) {
|
|
404
|
+
throw new Error(`"${field}" does not support the operator ${value.operator}`);
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
function afterChange() {
|
|
408
|
+
if (state.definition) reload().catch(() => {
|
|
409
|
+
});
|
|
410
|
+
}
|
|
411
|
+
function scheduleSave(patch) {
|
|
412
|
+
if (!scope) return;
|
|
413
|
+
const prev = pendingLayout;
|
|
414
|
+
pendingLayout = { ...prev, ...patch };
|
|
415
|
+
if (patch.sizing) pendingLayout.sizing = { ...prev.sizing, ...patch.sizing };
|
|
416
|
+
if (patch.visibility) pendingLayout.visibility = { ...prev.visibility, ...patch.visibility };
|
|
417
|
+
if (saveTimer) clearTimeout(saveTimer);
|
|
418
|
+
saveTimer = setTimeout(() => {
|
|
419
|
+
saveTimer = null;
|
|
420
|
+
void flushLayout();
|
|
421
|
+
}, saveDelay);
|
|
422
|
+
}
|
|
423
|
+
let saving = Promise.resolve();
|
|
424
|
+
function flushLayout() {
|
|
425
|
+
if (saveTimer) {
|
|
426
|
+
clearTimeout(saveTimer);
|
|
427
|
+
saveTimer = null;
|
|
428
|
+
}
|
|
429
|
+
saving = saving.then(async () => {
|
|
430
|
+
if (!scope || Object.keys(pendingLayout).length === 0) return;
|
|
431
|
+
const toSave = pendingLayout;
|
|
432
|
+
pendingLayout = {};
|
|
433
|
+
try {
|
|
434
|
+
await transport.putLayout(opts.view, scope, toSave);
|
|
435
|
+
set({ layoutSaveError: null });
|
|
436
|
+
} catch (e) {
|
|
437
|
+
set({ layoutSaveError: asError(e) });
|
|
438
|
+
}
|
|
439
|
+
});
|
|
440
|
+
return saving;
|
|
441
|
+
}
|
|
442
|
+
function changeLayout(patch) {
|
|
443
|
+
const layout = { ...state.layout, ...patch };
|
|
444
|
+
if (patch.sizing) layout.sizing = { ...state.layout.sizing, ...patch.sizing };
|
|
445
|
+
if (patch.visibility) layout.visibility = { ...state.layout.visibility, ...patch.visibility };
|
|
446
|
+
set({ layout });
|
|
447
|
+
scheduleSave(patch);
|
|
448
|
+
}
|
|
449
|
+
return {
|
|
450
|
+
ready,
|
|
451
|
+
getState: () => state,
|
|
452
|
+
subscribe(listener) {
|
|
453
|
+
listeners.add(listener);
|
|
454
|
+
return () => listeners.delete(listener);
|
|
455
|
+
},
|
|
456
|
+
setFilter(field, value) {
|
|
457
|
+
assertFilterable(field, value);
|
|
458
|
+
const filters = { ...state.filters };
|
|
459
|
+
if (value) filters[field] = value;
|
|
460
|
+
else delete filters[field];
|
|
461
|
+
set({ filters });
|
|
462
|
+
afterChange();
|
|
463
|
+
},
|
|
464
|
+
setFilters(filters) {
|
|
465
|
+
for (const [k, v] of Object.entries(filters)) assertFilterable(k, v);
|
|
466
|
+
set({ filters: { ...filters } });
|
|
467
|
+
afterChange();
|
|
468
|
+
},
|
|
469
|
+
clearFilters() {
|
|
470
|
+
set({ filters: {} });
|
|
471
|
+
afterChange();
|
|
472
|
+
},
|
|
473
|
+
setSearch(text) {
|
|
474
|
+
if (text === state.search) return;
|
|
475
|
+
seq++;
|
|
476
|
+
abort?.abort();
|
|
477
|
+
cursor = void 0;
|
|
478
|
+
set({ search: text, loading: state.definition ? true : state.loading, loadingMore: false, hasMore: false });
|
|
479
|
+
if (searchTimer) clearTimeout(searchTimer);
|
|
480
|
+
if (searchDelay <= 0) return afterChange();
|
|
481
|
+
searchTimer = setTimeout(() => {
|
|
482
|
+
searchTimer = null;
|
|
483
|
+
afterChange();
|
|
484
|
+
}, searchDelay);
|
|
485
|
+
},
|
|
486
|
+
refresh: () => reload(),
|
|
487
|
+
loadMore: () => loadMorePage(),
|
|
488
|
+
setColumnSize(key, width) {
|
|
489
|
+
const w = Math.min(MAX_WIDTH, Math.max(MIN_WIDTH, Math.round(width)));
|
|
490
|
+
changeLayout({ sizing: { [key]: w } });
|
|
491
|
+
},
|
|
492
|
+
setColumnOrder(keys) {
|
|
493
|
+
changeLayout({ order: [...keys] });
|
|
494
|
+
},
|
|
495
|
+
setColumnVisibility(key, visible) {
|
|
496
|
+
changeLayout({ visibility: { [key]: visible } });
|
|
497
|
+
},
|
|
498
|
+
setColumnPinning(pinning) {
|
|
499
|
+
changeLayout({ pinning: { left: [...pinning.left], right: [...pinning.right] } });
|
|
500
|
+
},
|
|
501
|
+
setSorting(sorting) {
|
|
502
|
+
changeLayout({ sorting: sorting.slice(0, 5).map((x) => ({ key: x.key, desc: x.desc === true })) });
|
|
503
|
+
void loadAllIfArranged().catch(() => {
|
|
504
|
+
});
|
|
505
|
+
},
|
|
506
|
+
toggleSort(key, multi) {
|
|
507
|
+
const cur = state.sorting.find((x) => x.key === key);
|
|
508
|
+
const next = !cur ? { key, desc: false } : !cur.desc ? { key, desc: true } : null;
|
|
509
|
+
const others = multi ? state.sorting.filter((x) => x.key !== key) : [];
|
|
510
|
+
const sorting = next ? multi ? [...others, next] : [next] : others;
|
|
511
|
+
changeLayout({ sorting: sorting.slice(0, 5) });
|
|
512
|
+
void loadAllIfArranged().catch(() => {
|
|
513
|
+
});
|
|
514
|
+
},
|
|
515
|
+
setGrouping(keys) {
|
|
516
|
+
changeLayout({ grouping: [...new Set(keys)].slice(0, 3) });
|
|
517
|
+
void loadAllIfArranged().catch(() => {
|
|
518
|
+
});
|
|
519
|
+
},
|
|
520
|
+
filterOptions(key, o = {}) {
|
|
521
|
+
if (!transport.getFilterOptions) return Promise.reject(new Error("This transport has no filter options"));
|
|
522
|
+
const col = state.definition?.columns.find((c) => c.key === key);
|
|
523
|
+
if (state.definition && col?.filter?.type !== "relation") {
|
|
524
|
+
return Promise.reject(new Error(`"${key}" is not a relation filter of this view`));
|
|
525
|
+
}
|
|
526
|
+
return transport.getFilterOptions(opts.view, key, o);
|
|
527
|
+
},
|
|
528
|
+
flushLayout,
|
|
529
|
+
destroy() {
|
|
530
|
+
void flushLayout();
|
|
531
|
+
destroyed = true;
|
|
532
|
+
abort?.abort();
|
|
533
|
+
if (searchTimer) clearTimeout(searchTimer);
|
|
534
|
+
listeners.clear();
|
|
535
|
+
}
|
|
536
|
+
};
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
// src/context.ts
|
|
540
|
+
function getPluginContext() {
|
|
541
|
+
if (typeof window === "undefined") return null;
|
|
542
|
+
return window.__CERVIO_PLUGIN_CONTEXT__ ?? null;
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
// src/client.ts
|
|
546
|
+
function resolveApiBaseUrl(explicitBaseUrl) {
|
|
547
|
+
const explicit = explicitBaseUrl?.trim();
|
|
548
|
+
if (explicit) return explicit.replace(/\/$/, "");
|
|
549
|
+
const parentOrigin = getPluginContext()?.parentOrigin?.trim();
|
|
550
|
+
if (parentOrigin && parentOrigin !== "null") {
|
|
551
|
+
return parentOrigin.replace(/\/$/, "");
|
|
552
|
+
}
|
|
553
|
+
throw new Error(
|
|
554
|
+
"Unable to resolve the Cervio API base URL. Pass { baseUrl } explicitly, or run inside the Cervio plugin sandbox so window.__CERVIO_PLUGIN_CONTEXT__.parentOrigin is set. Do not fall back to window.location.origin."
|
|
555
|
+
);
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
// src/views/index.ts
|
|
559
|
+
function pluginLayoutScope() {
|
|
560
|
+
const key = getPluginContext()?.pluginKey;
|
|
561
|
+
return typeof key === "string" && key.trim() ? `plugin:${key.trim().toLowerCase()}` : null;
|
|
562
|
+
}
|
|
563
|
+
function createPluginViewController(opts) {
|
|
564
|
+
const { baseUrl, fetchImpl, transport, layoutScope, ...rest } = opts;
|
|
565
|
+
return createViewController({
|
|
566
|
+
...rest,
|
|
567
|
+
transport: transport ?? createFetchTransport({ baseUrl: resolveApiBaseUrl(baseUrl), fetchImpl }),
|
|
568
|
+
layoutScope: layoutScope === void 0 ? pluginLayoutScope() : layoutScope
|
|
569
|
+
});
|
|
570
|
+
}
|
|
571
|
+
var CERVIO_VIEW_CSS = `
|
|
572
|
+
.cv-root{--cv-accent:var(--primary,#2f5fd0);--cv-border:var(--border,#e2e5ea);--cv-muted:var(--muted,#f3f4f6);--cv-muted-fg:var(--muted-foreground,#6b7280);--cv-bg:var(--background,#fff);--cv-fg:var(--foreground,#111827);--cv-card:var(--card,var(--cv-bg));--cv-radius:10px;--cv-row:38px;color:var(--cv-fg);font-size:13px;display:flex;flex-direction:column;gap:8px;min-width:0;min-height:0}
|
|
573
|
+
.cv-root[data-density=compact]{--cv-row:30px}
|
|
574
|
+
.cv-toolbar{display:flex;flex-wrap:wrap;align-items:center;gap:8px}
|
|
575
|
+
.cv-input{height:30px;border:1px solid var(--cv-border);border-radius:6px;background:var(--cv-bg);color:inherit;padding:0 10px;font:inherit;min-width:0}
|
|
576
|
+
.cv-input:focus-visible,.cv-btn:focus-visible,.cv-chip:focus-visible{outline:2px solid var(--cv-accent);outline-offset:1px}
|
|
577
|
+
.cv-search{flex:1 1 200px;max-width:340px}
|
|
578
|
+
.cv-btn{height:30px;border:1px solid var(--cv-border);border-radius:6px;background:var(--cv-bg);color:inherit;padding:0 10px;font:inherit;cursor:pointer;display:inline-flex;align-items:center;gap:6px;white-space:nowrap}
|
|
579
|
+
.cv-btn:hover{background:var(--cv-muted)}
|
|
580
|
+
.cv-btn[data-variant=primary]{background:var(--cv-accent);border-color:var(--cv-accent);color:var(--primary-foreground,#fff)}
|
|
581
|
+
.cv-btn[data-variant=ghost]{border-color:transparent}
|
|
582
|
+
.cv-chip{height:26px;border:1px dashed var(--cv-border);border-radius:999px;background:transparent;color:var(--cv-muted-fg);padding:0 10px;font:inherit;font-size:12px;cursor:pointer;white-space:nowrap}
|
|
583
|
+
.cv-chip[data-active=true]{border-style:solid;border-color:color-mix(in srgb,var(--cv-accent) 45%,transparent);background:color-mix(in srgb,var(--cv-accent) 10%,transparent);color:var(--cv-fg)}
|
|
584
|
+
.cv-filterbar{display:flex;flex-wrap:wrap;gap:6px;align-items:center}
|
|
585
|
+
.cv-pop-wrap{position:relative;display:inline-flex}
|
|
586
|
+
.cv-pop{position:absolute;top:calc(100% + 4px);left:0;z-index:30;min-width:220px;max-width:320px;background:var(--popover,var(--cv-bg));color:var(--popover-foreground,var(--cv-fg));border:1px solid var(--cv-border);border-radius:8px;box-shadow:0 8px 24px rgb(0 0 0 / .12);padding:10px;display:grid;gap:8px}
|
|
587
|
+
.cv-pop[data-align=end]{left:auto;right:0}
|
|
588
|
+
.cv-pop-title{font-weight:600;font-size:12px}
|
|
589
|
+
.cv-pop-row{display:flex;gap:6px;align-items:center}
|
|
590
|
+
.cv-pop-row .cv-input{flex:1}
|
|
591
|
+
.cv-check{display:flex;gap:8px;align-items:center;cursor:pointer;padding:2px 0}
|
|
592
|
+
.cv-pop-actions{display:flex;justify-content:space-between;gap:6px}
|
|
593
|
+
.cv-colitem{display:flex;align-items:center;gap:6px}
|
|
594
|
+
.cv-colitem label{flex:1;display:flex;gap:8px;align-items:center;cursor:pointer;min-width:0}
|
|
595
|
+
.cv-icon-btn{width:24px;height:24px;border:0;background:transparent;color:var(--cv-muted-fg);border-radius:4px;cursor:pointer;font:inherit}
|
|
596
|
+
.cv-icon-btn:hover:not(:disabled){background:var(--cv-muted);color:var(--cv-fg)}
|
|
597
|
+
.cv-icon-btn:disabled{opacity:.35;cursor:default}
|
|
598
|
+
.cv-grid-wrap{position:relative;min-width:0;min-height:0;overflow:auto;border:1px solid var(--cv-border);border-radius:var(--cv-radius);background:var(--cv-card)}
|
|
599
|
+
.cv-grid{border-collapse:separate;border-spacing:0;table-layout:fixed;width:max-content;min-width:100%}
|
|
600
|
+
.cv-grid th{position:sticky;top:0;z-index:2;background:var(--table-header,var(--cv-muted));color:var(--cv-muted-fg);font-weight:500;font-size:12px;text-align:left;height:34px;padding:0 10px;border-bottom:1px solid var(--cv-border);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
|
601
|
+
.cv-grid td{height:var(--cv-row);padding:0 10px;border-bottom:1px solid var(--cv-border);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-variant-numeric:tabular-nums}
|
|
602
|
+
.cv-grid tbody tr:last-child td{border-bottom:0}
|
|
603
|
+
.cv-grid tbody tr[data-clickable=true]{cursor:pointer}
|
|
604
|
+
.cv-grid tbody tr:hover td{background:color-mix(in srgb,var(--cv-muted) 60%,transparent)}
|
|
605
|
+
.cv-grid tbody tr[data-selected=true] td{background:color-mix(in srgb,var(--cv-accent) 10%,transparent)}
|
|
606
|
+
.cv-grid tbody tr[data-tone=danger] td:first-child{box-shadow:inset 3px 0 0 var(--destructive,#dc2626)}
|
|
607
|
+
.cv-grid tbody tr[data-tone=warning] td:first-child{box-shadow:inset 3px 0 0 #d97706}
|
|
608
|
+
.cv-grid tbody tr[data-tone=success] td:first-child{box-shadow:inset 3px 0 0 #16a34a}
|
|
609
|
+
.cv-grid tbody tr[data-tone=info] td:first-child{box-shadow:inset 3px 0 0 var(--cv-accent)}
|
|
610
|
+
.cv-th{position:relative}
|
|
611
|
+
.cv-resize{position:absolute;top:0;right:0;bottom:0;width:8px;cursor:col-resize;touch-action:none}
|
|
612
|
+
.cv-resize::after{content:"";position:absolute;top:8px;bottom:8px;right:3px;width:2px;border-radius:2px;background:transparent}
|
|
613
|
+
.cv-resize:hover::after,.cv-resize[data-active=true]::after{background:var(--cv-accent)}
|
|
614
|
+
.cv-num{text-align:right}
|
|
615
|
+
.cv-badge{display:inline-block;padding:0 8px;border-radius:999px;font-size:11.5px;line-height:20px;background:var(--cv-muted);color:var(--cv-fg)}
|
|
616
|
+
.cv-badge[data-tone=info]{background:color-mix(in srgb,var(--cv-accent) 14%,transparent);color:var(--cv-accent)}
|
|
617
|
+
.cv-badge[data-tone=success]{background:color-mix(in srgb,#16a34a 14%,transparent);color:#15803d}
|
|
618
|
+
.cv-badge[data-tone=warning]{background:color-mix(in srgb,#d97706 16%,transparent);color:#b45309}
|
|
619
|
+
.cv-badge[data-tone=danger]{background:color-mix(in srgb,var(--destructive,#dc2626) 14%,transparent);color:var(--destructive,#dc2626)}
|
|
620
|
+
.cv-empty{padding:28px 12px;text-align:center;color:var(--cv-muted-fg)}
|
|
621
|
+
.cv-footer{display:flex;justify-content:space-between;align-items:center;gap:8px;color:var(--cv-muted-fg);font-size:12px}
|
|
622
|
+
.cv-loading{position:absolute;inset:0;background:color-mix(in srgb,var(--cv-card) 55%,transparent);pointer-events:none}
|
|
623
|
+
.cv-error{color:var(--destructive,#dc2626);font-size:12px}
|
|
624
|
+
.cv-grid-error{padding:10px 12px;border-top:1px solid var(--cv-border)}
|
|
625
|
+
.cv-muted{color:var(--cv-muted-fg);font-size:12px;padding:4px 0}
|
|
626
|
+
.cv-groupby{display:inline-flex;align-items:center;gap:6px;color:var(--cv-muted-fg);font-size:12px}
|
|
627
|
+
.cv-sort{all:unset;cursor:pointer;display:inline-flex;align-items:center;gap:4px;max-width:100%;overflow:hidden;text-overflow:ellipsis}
|
|
628
|
+
.cv-sort:focus-visible{outline:2px solid var(--cv-accent);outline-offset:2px;border-radius:3px}
|
|
629
|
+
.cv-sort-mark{font-size:10px;opacity:.85}
|
|
630
|
+
.cv-th.cv-num .cv-sort{display:flex;justify-content:flex-end;width:100%}
|
|
631
|
+
.cv-root input[type=checkbox],.cv-root input[type=radio],.cv-pop input[type=checkbox],.cv-pop input[type=radio]{accent-color:var(--cv-accent)}
|
|
632
|
+
.cv-th[aria-sort=ascending],.cv-th[aria-sort=descending]{color:var(--cv-fg)}
|
|
633
|
+
.cv-grid tbody tr.cv-group td{overflow:visible;background:color-mix(in srgb,var(--cv-muted) 70%,transparent);font-weight:600;cursor:pointer;height:32px}
|
|
634
|
+
.cv-group-label{position:sticky;display:inline-block;white-space:nowrap}
|
|
635
|
+
.cv-group-toggle{display:inline-block;width:14px;color:var(--cv-muted-fg)}
|
|
636
|
+
.cv-muted-inline{color:var(--cv-muted-fg);font-weight:400}
|
|
637
|
+
.cv-group-count{color:var(--cv-muted-fg);font-weight:400;margin-left:6px}
|
|
638
|
+
@media (prefers-reduced-motion:no-preference){.cv-loading{transition:opacity .15s}}
|
|
639
|
+
`;
|
|
640
|
+
function ensureCervioViewStyles(doc = typeof document === "undefined" ? void 0 : document) {
|
|
641
|
+
if (!doc || doc.querySelector("style[data-cervio-view]")) return;
|
|
642
|
+
const el = doc.createElement("style");
|
|
643
|
+
el.setAttribute("data-cervio-view", "");
|
|
644
|
+
el.textContent = CERVIO_VIEW_CSS;
|
|
645
|
+
doc.head.appendChild(el);
|
|
646
|
+
}
|
|
647
|
+
function useViewState(controller) {
|
|
648
|
+
const subscribe = useCallback(
|
|
649
|
+
(cb) => {
|
|
650
|
+
const off = controller.subscribe(cb);
|
|
651
|
+
return () => {
|
|
652
|
+
off();
|
|
653
|
+
};
|
|
654
|
+
},
|
|
655
|
+
[controller]
|
|
656
|
+
);
|
|
657
|
+
return useSyncExternalStore(subscribe, controller.getState, controller.getState);
|
|
658
|
+
}
|
|
659
|
+
function usePopover() {
|
|
660
|
+
const [open, setOpen] = useState(false);
|
|
661
|
+
const ref = useRef(null);
|
|
662
|
+
useEffect(() => {
|
|
663
|
+
if (!open) return;
|
|
664
|
+
const onDown = (e) => {
|
|
665
|
+
if (ref.current && !ref.current.contains(e.target)) setOpen(false);
|
|
666
|
+
};
|
|
667
|
+
const onKey = (e) => {
|
|
668
|
+
if (e.key === "Escape") setOpen(false);
|
|
669
|
+
};
|
|
670
|
+
document.addEventListener("mousedown", onDown);
|
|
671
|
+
document.addEventListener("keydown", onKey);
|
|
672
|
+
return () => {
|
|
673
|
+
document.removeEventListener("mousedown", onDown);
|
|
674
|
+
document.removeEventListener("keydown", onKey);
|
|
675
|
+
};
|
|
676
|
+
}, [open]);
|
|
677
|
+
return { open, setOpen, ref };
|
|
678
|
+
}
|
|
679
|
+
function useCervioViewStyles(unstyled) {
|
|
680
|
+
useEffect(() => {
|
|
681
|
+
if (unstyled) return;
|
|
682
|
+
ensureCervioViewStyles();
|
|
683
|
+
}, [unstyled]);
|
|
684
|
+
}
|
|
685
|
+
var NUMBER_TYPES2 = /* @__PURE__ */ new Set(["number", "currency", "integer", "decimal"]);
|
|
686
|
+
function label(v) {
|
|
687
|
+
if (v == null) return "";
|
|
688
|
+
if (typeof v === "object" && !Array.isArray(v)) {
|
|
689
|
+
const o = v;
|
|
690
|
+
return String(o.label ?? o.id ?? "");
|
|
691
|
+
}
|
|
692
|
+
return String(v);
|
|
693
|
+
}
|
|
694
|
+
function intlTag(locale) {
|
|
695
|
+
const raw = locale.trim();
|
|
696
|
+
const tag = raw === "en" ? "en-GB" : raw.includes("-") ? raw : `${raw.toLowerCase()}-${raw.toUpperCase()}`;
|
|
697
|
+
try {
|
|
698
|
+
return Intl.getCanonicalLocales(tag)[0] ?? "it-IT";
|
|
699
|
+
} catch {
|
|
700
|
+
return "it-IT";
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
function isNumberColumn(column) {
|
|
704
|
+
return NUMBER_TYPES2.has(column.type);
|
|
705
|
+
}
|
|
706
|
+
function formatViewValue(column, value, locale = "it") {
|
|
707
|
+
if (value == null || value === "") return "";
|
|
708
|
+
if (Array.isArray(value)) return value.map((v) => formatViewValue(column, v, locale)).filter(Boolean).join(", ");
|
|
709
|
+
if (typeof value === "object") return label(value);
|
|
710
|
+
if (column.options?.length) {
|
|
711
|
+
const opt = column.options.find((o) => o.value === String(value));
|
|
712
|
+
if (opt) return opt.label;
|
|
713
|
+
}
|
|
714
|
+
const tag = intlTag(locale);
|
|
715
|
+
if (column.type === "date" && typeof value === "string" && /^\d{4}-\d{2}-\d{2}/.test(value)) {
|
|
716
|
+
const [y, m, d] = value.slice(0, 10).split("-").map(Number);
|
|
717
|
+
return new Intl.DateTimeFormat(tag, { day: "2-digit", month: "2-digit", year: "numeric" }).format(
|
|
718
|
+
new Date(y, m - 1, d)
|
|
719
|
+
);
|
|
720
|
+
}
|
|
721
|
+
if (column.type === "datetime" && typeof value === "string") {
|
|
722
|
+
const dt = new Date(value);
|
|
723
|
+
if (!Number.isNaN(dt.getTime())) {
|
|
724
|
+
return new Intl.DateTimeFormat(tag, { dateStyle: "short", timeStyle: "short" }).format(dt);
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
if (NUMBER_TYPES2.has(column.type) && (typeof value === "number" || /^-?\d+(\.\d+)?$/.test(String(value)))) {
|
|
728
|
+
const n = Number(value);
|
|
729
|
+
const grouping = { useGrouping: "always" };
|
|
730
|
+
return column.type === "currency" ? new Intl.NumberFormat(tag, { style: "currency", currency: "EUR", ...grouping }).format(n) : new Intl.NumberFormat(tag, { maximumFractionDigits: 4, ...grouping }).format(n);
|
|
731
|
+
}
|
|
732
|
+
if (typeof value === "boolean") return value ? "\u2713" : "";
|
|
733
|
+
return String(value);
|
|
734
|
+
}
|
|
735
|
+
function rawViewValue(value) {
|
|
736
|
+
if (value && typeof value === "object" && !Array.isArray(value)) {
|
|
737
|
+
const o = value;
|
|
738
|
+
if (o.id != null) return String(o.id);
|
|
739
|
+
}
|
|
740
|
+
return value == null ? "" : String(value);
|
|
741
|
+
}
|
|
742
|
+
function FieldValue(props) {
|
|
743
|
+
const text = formatViewValue(props.column, props.value, props.locale);
|
|
744
|
+
if (!text) return null;
|
|
745
|
+
if (props.tone) {
|
|
746
|
+
return /* @__PURE__ */ jsx("span", { className: "cv-badge", "data-tone": props.tone, children: text });
|
|
747
|
+
}
|
|
748
|
+
return /* @__PURE__ */ jsx("span", { className: "cv-value", children: text });
|
|
749
|
+
}
|
|
750
|
+
var it = {
|
|
751
|
+
search: "Cerca\u2026",
|
|
752
|
+
columns: "Colonne",
|
|
753
|
+
noResults: "Nessun risultato",
|
|
754
|
+
loadMore: "Carica altri",
|
|
755
|
+
clear: "Rimuovi",
|
|
756
|
+
clearFilters: "Azzera filtri",
|
|
757
|
+
apply: "Applica",
|
|
758
|
+
from: "Da",
|
|
759
|
+
to: "A",
|
|
760
|
+
any: "Tutti",
|
|
761
|
+
rows: (shown, total) => total == null ? `${shown} righe` : `${shown} di ${total}`,
|
|
762
|
+
error: "Errore nel caricamento",
|
|
763
|
+
resize: (c) => `Allarga la colonna ${c}`,
|
|
764
|
+
moveUp: "Sposta su",
|
|
765
|
+
moveDown: "Sposta gi\xF9",
|
|
766
|
+
yes: "S\xEC",
|
|
767
|
+
no: "No",
|
|
768
|
+
groupBy: "Raggruppa",
|
|
769
|
+
noGrouping: "Nessun raggruppamento",
|
|
770
|
+
sortAsc: "Crescente",
|
|
771
|
+
sortDesc: "Decrescente",
|
|
772
|
+
loadingAll: "Carico tutte le righe\u2026",
|
|
773
|
+
empty: "(vuoto)",
|
|
774
|
+
ops: { equals: "=", gt: ">", gte: "\u2265", lt: "<", lte: "\u2264", between: "tra", contains: "contiene" }
|
|
775
|
+
};
|
|
776
|
+
var en = {
|
|
777
|
+
...it,
|
|
778
|
+
search: "Search\u2026",
|
|
779
|
+
columns: "Columns",
|
|
780
|
+
noResults: "No results",
|
|
781
|
+
loadMore: "Load more",
|
|
782
|
+
clear: "Remove",
|
|
783
|
+
clearFilters: "Clear filters",
|
|
784
|
+
apply: "Apply",
|
|
785
|
+
from: "From",
|
|
786
|
+
to: "To",
|
|
787
|
+
any: "All",
|
|
788
|
+
rows: (shown, total) => total == null ? `${shown} rows` : `${shown} of ${total}`,
|
|
789
|
+
error: "Could not load",
|
|
790
|
+
resize: (c) => `Resize column ${c}`,
|
|
791
|
+
moveUp: "Move up",
|
|
792
|
+
moveDown: "Move down",
|
|
793
|
+
yes: "Yes",
|
|
794
|
+
no: "No",
|
|
795
|
+
groupBy: "Group",
|
|
796
|
+
noGrouping: "No grouping",
|
|
797
|
+
sortAsc: "Ascending",
|
|
798
|
+
sortDesc: "Descending",
|
|
799
|
+
loadingAll: "Loading all rows\u2026",
|
|
800
|
+
empty: "(empty)",
|
|
801
|
+
ops: { ...it.ops, between: "between", contains: "contains" }
|
|
802
|
+
};
|
|
803
|
+
function viewLabels(locale, override) {
|
|
804
|
+
return { ...locale?.startsWith("en") ? en : it, ...override };
|
|
805
|
+
}
|
|
806
|
+
function SearchBox(props) {
|
|
807
|
+
useCervioViewStyles(props.unstyled);
|
|
808
|
+
const state = useViewState(props.controller);
|
|
809
|
+
const t = viewLabels(props.locale ?? state.definition?.locale, props.labels);
|
|
810
|
+
const [text, setText] = useState(state.search);
|
|
811
|
+
useEffect(() => setText(state.search), [state.search]);
|
|
812
|
+
if (state.definition && !state.definition.search) return null;
|
|
813
|
+
return /* @__PURE__ */ jsx(
|
|
814
|
+
"input",
|
|
815
|
+
{
|
|
816
|
+
type: "search",
|
|
817
|
+
className: ["cv-input", "cv-search", props.className].filter(Boolean).join(" "),
|
|
818
|
+
placeholder: props.placeholder ?? t.search,
|
|
819
|
+
"aria-label": props.placeholder ?? t.search,
|
|
820
|
+
value: text,
|
|
821
|
+
onChange: (e) => {
|
|
822
|
+
setText(e.target.value);
|
|
823
|
+
props.controller.setSearch(e.target.value);
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
);
|
|
827
|
+
}
|
|
828
|
+
function filterSummary(col, f, t, locale) {
|
|
829
|
+
if (!f || !isFilterValueActive(f)) return "";
|
|
830
|
+
if (f.type === "relation") {
|
|
831
|
+
const names = f.values.map((v) => f.labels?.[v] ?? v);
|
|
832
|
+
return names.length > 2 ? `${names.slice(0, 2).join(", ")} +${names.length - 2}` : names.join(", ");
|
|
833
|
+
}
|
|
834
|
+
if (f.type === "boolean") return f.value ? t.yes : t.no;
|
|
835
|
+
const fmt = (v) => formatViewValue(col, v, locale);
|
|
836
|
+
if (f.type === "text") {
|
|
837
|
+
if (f.operator === "contains") return `${t.ops.contains} "${f.value}"`;
|
|
838
|
+
const shown = f.values.slice(0, 2).map(fmt).join(", ");
|
|
839
|
+
return f.values.length > 2 ? `${shown} +${f.values.length - 2}` : shown;
|
|
840
|
+
}
|
|
841
|
+
if (f.operator === "between") {
|
|
842
|
+
const a = f.type === "number" ? f.min : f.from;
|
|
843
|
+
const b = f.type === "number" ? f.max : f.to;
|
|
844
|
+
if (a !== void 0 && a !== "" && b !== void 0 && b !== "") return `${fmt(a)} \u2013 ${fmt(b)}`;
|
|
845
|
+
return a !== void 0 && a !== "" ? `${t.ops.gte} ${fmt(a)}` : `${t.ops.lte} ${fmt(b)}`;
|
|
846
|
+
}
|
|
847
|
+
return `${t.ops[f.operator]} ${fmt(f.value)}`;
|
|
848
|
+
}
|
|
849
|
+
function emptyFilter(col) {
|
|
850
|
+
const type = col.filter?.type ?? "text";
|
|
851
|
+
if (type === "relation") return { type, operator: "equals", values: [], labels: {} };
|
|
852
|
+
if (type === "boolean") return { type, operator: "equals" };
|
|
853
|
+
if (type === "text") {
|
|
854
|
+
const canContain = col.filter?.operators.includes("contains");
|
|
855
|
+
return col.options?.length || !canContain ? { type, operator: "equals", values: [] } : { type, operator: "contains", value: "" };
|
|
856
|
+
}
|
|
857
|
+
const ops = (col.filter?.operators ?? []).filter((o) => o !== "contains");
|
|
858
|
+
const op = ops.includes("equals") ? "equals" : ops[0] ?? "equals";
|
|
859
|
+
if (op === "between") return { type, operator: "between" };
|
|
860
|
+
return { type, operator: op };
|
|
861
|
+
}
|
|
862
|
+
function RelationOptions(props) {
|
|
863
|
+
const { controller, col, value, onChange, t } = props;
|
|
864
|
+
const [search, setSearch] = useState("");
|
|
865
|
+
const [opts, setOpts] = useState(null);
|
|
866
|
+
const [error, setError] = useState(false);
|
|
867
|
+
const [next, setNext] = useState(void 0);
|
|
868
|
+
const [loadingMore, setLoadingMore] = useState(false);
|
|
869
|
+
const generation = useRef(0);
|
|
870
|
+
useEffect(() => {
|
|
871
|
+
let live = true;
|
|
872
|
+
generation.current += 1;
|
|
873
|
+
setNext(void 0);
|
|
874
|
+
const timer = setTimeout(() => {
|
|
875
|
+
controller.filterOptions(col.key, { search, limit: 30 }).then((r) => live && (setOpts(r.options), setNext(r.has_more ? r.next_cursor : void 0), setError(false))).catch(() => live && setError(true));
|
|
876
|
+
}, search ? 250 : 0);
|
|
877
|
+
return () => {
|
|
878
|
+
live = false;
|
|
879
|
+
clearTimeout(timer);
|
|
880
|
+
};
|
|
881
|
+
}, [controller, col.key, search]);
|
|
882
|
+
const loadMore = () => {
|
|
883
|
+
if (!next || loadingMore) return;
|
|
884
|
+
const gen = generation.current;
|
|
885
|
+
setLoadingMore(true);
|
|
886
|
+
controller.filterOptions(col.key, { search, limit: 30, cursor: next }).then((r) => {
|
|
887
|
+
if (gen !== generation.current) return;
|
|
888
|
+
setOpts((prev) => [...prev ?? [], ...r.options.filter((o) => !(prev ?? []).some((p) => p.value === o.value))]);
|
|
889
|
+
setNext(r.has_more ? r.next_cursor : void 0);
|
|
890
|
+
}).catch(() => gen === generation.current && setError(true)).finally(() => setLoadingMore(false));
|
|
891
|
+
};
|
|
892
|
+
const picked = value.values.map((v) => ({ value: v, label: value.labels?.[v] ?? v }));
|
|
893
|
+
const list = [...picked, ...(opts ?? []).filter((o) => !value.values.includes(o.value))];
|
|
894
|
+
return /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
895
|
+
/* @__PURE__ */ jsx(
|
|
896
|
+
"input",
|
|
897
|
+
{
|
|
898
|
+
className: "cv-input",
|
|
899
|
+
type: "search",
|
|
900
|
+
autoFocus: true,
|
|
901
|
+
placeholder: t.search,
|
|
902
|
+
"aria-label": `${t.search} ${col.label}`,
|
|
903
|
+
value: search,
|
|
904
|
+
onChange: (e) => setSearch(e.target.value)
|
|
905
|
+
}
|
|
906
|
+
),
|
|
907
|
+
/* @__PURE__ */ jsxs("div", { style: { maxHeight: 220, overflow: "auto" }, children: [
|
|
908
|
+
error ? /* @__PURE__ */ jsx("div", { className: "cv-error", children: t.error }) : null,
|
|
909
|
+
opts === null && !error ? /* @__PURE__ */ jsx("div", { className: "cv-muted", children: "\u2026" }) : null,
|
|
910
|
+
opts !== null && list.length === 0 ? /* @__PURE__ */ jsx("div", { className: "cv-muted", children: t.noResults }) : null,
|
|
911
|
+
list.map((o) => /* @__PURE__ */ jsxs("label", { className: "cv-check", children: [
|
|
912
|
+
/* @__PURE__ */ jsx(
|
|
913
|
+
"input",
|
|
914
|
+
{
|
|
915
|
+
type: "checkbox",
|
|
916
|
+
checked: value.values.includes(o.value),
|
|
917
|
+
onChange: (e) => {
|
|
918
|
+
const labels = { ...value.labels ?? {}, [o.value]: o.label };
|
|
919
|
+
onChange({
|
|
920
|
+
...value,
|
|
921
|
+
labels,
|
|
922
|
+
values: e.target.checked ? [...value.values, o.value] : value.values.filter((v) => v !== o.value)
|
|
923
|
+
});
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
),
|
|
927
|
+
o.label
|
|
928
|
+
] }, o.value)),
|
|
929
|
+
next ? /* @__PURE__ */ jsx("button", { type: "button", className: "cv-btn", "data-variant": "ghost", disabled: loadingMore, onClick: loadMore, children: t.loadMore }) : null
|
|
930
|
+
] })
|
|
931
|
+
] });
|
|
932
|
+
}
|
|
933
|
+
function FilterEditor(props) {
|
|
934
|
+
const { col, value, onChange, t } = props;
|
|
935
|
+
if (value.type === "relation") {
|
|
936
|
+
return /* @__PURE__ */ jsx(RelationOptions, { controller: props.controller, col, value, onChange, t });
|
|
937
|
+
}
|
|
938
|
+
if (value.type === "boolean") {
|
|
939
|
+
return /* @__PURE__ */ jsx("div", { className: "cv-pop-row", role: "radiogroup", "aria-label": col.label, children: [true, false].map((b) => /* @__PURE__ */ jsxs("label", { className: "cv-check", children: [
|
|
940
|
+
/* @__PURE__ */ jsx(
|
|
941
|
+
"input",
|
|
942
|
+
{
|
|
943
|
+
type: "radio",
|
|
944
|
+
name: `cv-bool-${col.key}`,
|
|
945
|
+
checked: value.value === b,
|
|
946
|
+
onChange: () => onChange({ type: "boolean", operator: "equals", value: b })
|
|
947
|
+
}
|
|
948
|
+
),
|
|
949
|
+
b ? t.yes : t.no
|
|
950
|
+
] }, String(b))) });
|
|
951
|
+
}
|
|
952
|
+
if (value.type === "text" && value.operator === "equals" && !col.options?.length) {
|
|
953
|
+
return /* @__PURE__ */ jsx(
|
|
954
|
+
"input",
|
|
955
|
+
{
|
|
956
|
+
className: "cv-input",
|
|
957
|
+
autoFocus: true,
|
|
958
|
+
value: value.values[0] ?? "",
|
|
959
|
+
"aria-label": col.label,
|
|
960
|
+
onChange: (e) => onChange({ type: "text", operator: "equals", values: e.target.value ? [e.target.value] : [] })
|
|
961
|
+
}
|
|
962
|
+
);
|
|
963
|
+
}
|
|
964
|
+
if (value.type === "text" && value.operator === "equals") {
|
|
965
|
+
const opts = col.options ?? [];
|
|
966
|
+
return /* @__PURE__ */ jsx("div", { style: { maxHeight: 220, overflow: "auto" }, children: opts.map((o) => /* @__PURE__ */ jsxs("label", { className: "cv-check", children: [
|
|
967
|
+
/* @__PURE__ */ jsx(
|
|
968
|
+
"input",
|
|
969
|
+
{
|
|
970
|
+
type: "checkbox",
|
|
971
|
+
checked: value.values.includes(o.value),
|
|
972
|
+
onChange: (e) => onChange({
|
|
973
|
+
...value,
|
|
974
|
+
values: e.target.checked ? [...value.values, o.value] : value.values.filter((v) => v !== o.value)
|
|
975
|
+
})
|
|
976
|
+
}
|
|
977
|
+
),
|
|
978
|
+
o.label
|
|
979
|
+
] }, o.value)) });
|
|
980
|
+
}
|
|
981
|
+
if (value.type === "text") {
|
|
982
|
+
return /* @__PURE__ */ jsx(
|
|
983
|
+
"input",
|
|
984
|
+
{
|
|
985
|
+
className: "cv-input",
|
|
986
|
+
autoFocus: true,
|
|
987
|
+
value: value.operator === "contains" ? value.value : "",
|
|
988
|
+
"aria-label": col.label,
|
|
989
|
+
onChange: (e) => onChange({ type: "text", operator: "contains", value: e.target.value })
|
|
990
|
+
}
|
|
991
|
+
);
|
|
992
|
+
}
|
|
993
|
+
const ops = (col.filter?.operators ?? ["equals"]).filter((o) => o !== "contains");
|
|
994
|
+
const inputType = value.type === "number" ? "number" : col.type === "datetime" ? "date" : "date";
|
|
995
|
+
const parse = (s) => s === "" ? void 0 : value.type === "number" ? Number(s) : s;
|
|
996
|
+
const setOp = (op) => {
|
|
997
|
+
if (op === "between") {
|
|
998
|
+
onChange(value.type === "number" ? { type: "number", operator: "between" } : { type: "date", operator: "between" });
|
|
999
|
+
} else {
|
|
1000
|
+
const v = value.operator === "between" ? void 0 : value.value;
|
|
1001
|
+
onChange({ type: value.type, operator: op, value: v });
|
|
1002
|
+
}
|
|
1003
|
+
};
|
|
1004
|
+
return /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
1005
|
+
/* @__PURE__ */ jsx("select", { className: "cv-input", value: value.operator, onChange: (e) => setOp(e.target.value), "aria-label": col.label, children: ops.map((o) => /* @__PURE__ */ jsx("option", { value: o, children: t.ops[o] }, o)) }),
|
|
1006
|
+
value.operator === "between" ? /* @__PURE__ */ jsxs("div", { className: "cv-pop-row", children: [
|
|
1007
|
+
/* @__PURE__ */ jsx(
|
|
1008
|
+
"input",
|
|
1009
|
+
{
|
|
1010
|
+
className: "cv-input",
|
|
1011
|
+
type: inputType,
|
|
1012
|
+
placeholder: t.from,
|
|
1013
|
+
"aria-label": t.from,
|
|
1014
|
+
value: String((value.type === "number" ? value.min : value.from) ?? ""),
|
|
1015
|
+
onChange: (e) => onChange(
|
|
1016
|
+
value.type === "number" ? { ...value, min: parse(e.target.value) } : { ...value, from: parse(e.target.value) }
|
|
1017
|
+
)
|
|
1018
|
+
}
|
|
1019
|
+
),
|
|
1020
|
+
/* @__PURE__ */ jsx(
|
|
1021
|
+
"input",
|
|
1022
|
+
{
|
|
1023
|
+
className: "cv-input",
|
|
1024
|
+
type: inputType,
|
|
1025
|
+
placeholder: t.to,
|
|
1026
|
+
"aria-label": t.to,
|
|
1027
|
+
value: String((value.type === "number" ? value.max : value.to) ?? ""),
|
|
1028
|
+
onChange: (e) => onChange(
|
|
1029
|
+
value.type === "number" ? { ...value, max: parse(e.target.value) } : { ...value, to: parse(e.target.value) }
|
|
1030
|
+
)
|
|
1031
|
+
}
|
|
1032
|
+
)
|
|
1033
|
+
] }) : /* @__PURE__ */ jsx(
|
|
1034
|
+
"input",
|
|
1035
|
+
{
|
|
1036
|
+
className: "cv-input",
|
|
1037
|
+
type: inputType,
|
|
1038
|
+
autoFocus: true,
|
|
1039
|
+
"aria-label": col.label,
|
|
1040
|
+
value: String(value.value ?? ""),
|
|
1041
|
+
onChange: (e) => onChange({ ...value, value: parse(e.target.value) })
|
|
1042
|
+
}
|
|
1043
|
+
)
|
|
1044
|
+
] });
|
|
1045
|
+
}
|
|
1046
|
+
function FilterChip(props) {
|
|
1047
|
+
const { col, current, t } = props;
|
|
1048
|
+
const pop = usePopover();
|
|
1049
|
+
const [draft, setDraft] = useState(current ?? emptyFilter(col));
|
|
1050
|
+
const summary = filterSummary(col, current, t, props.locale);
|
|
1051
|
+
const field = col.field;
|
|
1052
|
+
const apply = (v) => {
|
|
1053
|
+
props.controller.setFilter(field, v && isFilterValueActive(v) ? v : null);
|
|
1054
|
+
pop.setOpen(false);
|
|
1055
|
+
};
|
|
1056
|
+
return /* @__PURE__ */ jsxs("div", { className: "cv-pop-wrap", ref: pop.ref, children: [
|
|
1057
|
+
/* @__PURE__ */ jsx(
|
|
1058
|
+
"button",
|
|
1059
|
+
{
|
|
1060
|
+
type: "button",
|
|
1061
|
+
className: "cv-chip",
|
|
1062
|
+
"data-active": summary ? "true" : "false",
|
|
1063
|
+
"aria-expanded": pop.open,
|
|
1064
|
+
onClick: () => {
|
|
1065
|
+
setDraft(current ?? emptyFilter(col));
|
|
1066
|
+
pop.setOpen(!pop.open);
|
|
1067
|
+
},
|
|
1068
|
+
children: summary ? `${col.label}: ${summary}` : col.label
|
|
1069
|
+
}
|
|
1070
|
+
),
|
|
1071
|
+
pop.open ? (
|
|
1072
|
+
// Not a <form>: the plugin sandbox has no allow-forms, so a submit is blocked.
|
|
1073
|
+
/* @__PURE__ */ jsxs(
|
|
1074
|
+
"div",
|
|
1075
|
+
{
|
|
1076
|
+
className: "cv-pop",
|
|
1077
|
+
role: "dialog",
|
|
1078
|
+
"aria-label": col.label,
|
|
1079
|
+
onKeyDown: (e) => {
|
|
1080
|
+
if (e.key === "Enter" && e.target.tagName === "INPUT") {
|
|
1081
|
+
e.preventDefault();
|
|
1082
|
+
apply(draft);
|
|
1083
|
+
}
|
|
1084
|
+
},
|
|
1085
|
+
children: [
|
|
1086
|
+
/* @__PURE__ */ jsx("div", { className: "cv-pop-title", children: col.label }),
|
|
1087
|
+
/* @__PURE__ */ jsx(FilterEditor, { controller: props.controller, col, value: draft, onChange: setDraft, t }),
|
|
1088
|
+
/* @__PURE__ */ jsxs("div", { className: "cv-pop-actions", children: [
|
|
1089
|
+
/* @__PURE__ */ jsx("button", { type: "button", className: "cv-btn", "data-variant": "ghost", onClick: () => apply(null), children: t.clear }),
|
|
1090
|
+
/* @__PURE__ */ jsx("button", { type: "button", className: "cv-btn", "data-variant": "primary", onClick: () => apply(draft), children: t.apply })
|
|
1091
|
+
] })
|
|
1092
|
+
]
|
|
1093
|
+
}
|
|
1094
|
+
)
|
|
1095
|
+
) : null
|
|
1096
|
+
] });
|
|
1097
|
+
}
|
|
1098
|
+
function FilterBar(props) {
|
|
1099
|
+
useCervioViewStyles(props.unstyled);
|
|
1100
|
+
const state = useViewState(props.controller);
|
|
1101
|
+
const locale = props.locale ?? state.definition?.locale ?? "it";
|
|
1102
|
+
const t = viewLabels(locale, props.labels);
|
|
1103
|
+
const filterable = state.columns.filter((c) => c.filter && c.field);
|
|
1104
|
+
const cols = props.fields ? props.fields.map((f) => filterable.find((c) => c.field === f)).filter((c) => !!c) : filterable.filter((c) => c.visible);
|
|
1105
|
+
if (!cols.length) return null;
|
|
1106
|
+
const active = Object.values(state.filters).some(isFilterValueActive);
|
|
1107
|
+
return /* @__PURE__ */ jsxs("div", { className: ["cv-filterbar", props.className].filter(Boolean).join(" "), children: [
|
|
1108
|
+
cols.map((c) => /* @__PURE__ */ jsx(
|
|
1109
|
+
FilterChip,
|
|
1110
|
+
{
|
|
1111
|
+
controller: props.controller,
|
|
1112
|
+
col: c,
|
|
1113
|
+
current: state.filters[c.field],
|
|
1114
|
+
t,
|
|
1115
|
+
locale
|
|
1116
|
+
},
|
|
1117
|
+
c.key
|
|
1118
|
+
)),
|
|
1119
|
+
active ? /* @__PURE__ */ jsx("button", { type: "button", className: "cv-btn", "data-variant": "ghost", onClick: () => props.controller.clearFilters(), children: t.clearFilters }) : null
|
|
1120
|
+
] });
|
|
1121
|
+
}
|
|
1122
|
+
function ColumnsMenu(props) {
|
|
1123
|
+
useCervioViewStyles(props.unstyled);
|
|
1124
|
+
const state = useViewState(props.controller);
|
|
1125
|
+
const t = viewLabels(props.locale ?? state.definition?.locale, props.labels);
|
|
1126
|
+
const pop = usePopover();
|
|
1127
|
+
const keys = state.columns.map((c) => c.key);
|
|
1128
|
+
const move = (i, d) => {
|
|
1129
|
+
const next = [...keys];
|
|
1130
|
+
const [k] = next.splice(i, 1);
|
|
1131
|
+
next.splice(i + d, 0, k);
|
|
1132
|
+
props.controller.setColumnOrder(next);
|
|
1133
|
+
};
|
|
1134
|
+
const visibleCount = state.columns.filter((c) => c.visible).length;
|
|
1135
|
+
return /* @__PURE__ */ jsxs("div", { className: ["cv-pop-wrap", props.className].filter(Boolean).join(" "), ref: pop.ref, children: [
|
|
1136
|
+
/* @__PURE__ */ jsx("button", { type: "button", className: "cv-btn", "aria-expanded": pop.open, onClick: () => pop.setOpen(!pop.open), children: t.columns }),
|
|
1137
|
+
pop.open ? /* @__PURE__ */ jsx("div", { className: "cv-pop", "data-align": props.align ?? "end", role: "dialog", "aria-label": t.columns, children: state.columns.map((c, i) => /* @__PURE__ */ jsxs("div", { className: "cv-colitem", children: [
|
|
1138
|
+
/* @__PURE__ */ jsxs("label", { children: [
|
|
1139
|
+
/* @__PURE__ */ jsx(
|
|
1140
|
+
"input",
|
|
1141
|
+
{
|
|
1142
|
+
type: "checkbox",
|
|
1143
|
+
checked: c.visible,
|
|
1144
|
+
disabled: c.visible && visibleCount === 1,
|
|
1145
|
+
onChange: (e) => props.controller.setColumnVisibility(c.key, e.target.checked)
|
|
1146
|
+
}
|
|
1147
|
+
),
|
|
1148
|
+
/* @__PURE__ */ jsx("span", { style: { overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }, children: c.label })
|
|
1149
|
+
] }),
|
|
1150
|
+
/* @__PURE__ */ jsx("button", { type: "button", className: "cv-icon-btn", "aria-label": `${t.moveUp}: ${c.label}`, disabled: i === 0, onClick: () => move(i, -1), children: "\u2191" }),
|
|
1151
|
+
/* @__PURE__ */ jsx(
|
|
1152
|
+
"button",
|
|
1153
|
+
{
|
|
1154
|
+
type: "button",
|
|
1155
|
+
className: "cv-icon-btn",
|
|
1156
|
+
"aria-label": `${t.moveDown}: ${c.label}`,
|
|
1157
|
+
disabled: i === keys.length - 1,
|
|
1158
|
+
onClick: () => move(i, 1),
|
|
1159
|
+
children: "\u2193"
|
|
1160
|
+
}
|
|
1161
|
+
)
|
|
1162
|
+
] }, c.key)) }) : null
|
|
1163
|
+
] });
|
|
1164
|
+
}
|
|
1165
|
+
function GroupByMenu(props) {
|
|
1166
|
+
useCervioViewStyles(props.unstyled);
|
|
1167
|
+
const state = useViewState(props.controller);
|
|
1168
|
+
const t = viewLabels(props.locale ?? state.definition?.locale, props.labels);
|
|
1169
|
+
const cols = props.fields ? props.fields.map((k) => state.columns.find((c) => c.key === k)).filter((c) => !!c) : state.columns.filter((c) => c.visible);
|
|
1170
|
+
return /* @__PURE__ */ jsxs("label", { className: ["cv-groupby", props.className].filter(Boolean).join(" "), children: [
|
|
1171
|
+
/* @__PURE__ */ jsx("span", { children: t.groupBy }),
|
|
1172
|
+
/* @__PURE__ */ jsxs(
|
|
1173
|
+
"select",
|
|
1174
|
+
{
|
|
1175
|
+
className: "cv-input",
|
|
1176
|
+
value: state.grouping[0] ?? "",
|
|
1177
|
+
onChange: (e) => props.controller.setGrouping(e.target.value ? [e.target.value] : []),
|
|
1178
|
+
children: [
|
|
1179
|
+
/* @__PURE__ */ jsx("option", { value: "", children: t.noGrouping }),
|
|
1180
|
+
cols.map((c) => /* @__PURE__ */ jsx("option", { value: c.key, children: c.label }, c.key))
|
|
1181
|
+
]
|
|
1182
|
+
}
|
|
1183
|
+
)
|
|
1184
|
+
] });
|
|
1185
|
+
}
|
|
1186
|
+
var DEFAULT_COLUMN_WIDTH = 160;
|
|
1187
|
+
function ResizeHandle(props) {
|
|
1188
|
+
const start = useRef(null);
|
|
1189
|
+
const [active, setActive] = useState(false);
|
|
1190
|
+
return /* @__PURE__ */ jsx(
|
|
1191
|
+
"span",
|
|
1192
|
+
{
|
|
1193
|
+
className: "cv-resize",
|
|
1194
|
+
role: "separator",
|
|
1195
|
+
"aria-orientation": "vertical",
|
|
1196
|
+
"aria-label": props.label,
|
|
1197
|
+
"aria-valuenow": props.width,
|
|
1198
|
+
tabIndex: 0,
|
|
1199
|
+
"data-active": active ? "true" : "false",
|
|
1200
|
+
onClick: (e) => e.stopPropagation(),
|
|
1201
|
+
onPointerDown: (e) => {
|
|
1202
|
+
e.preventDefault();
|
|
1203
|
+
e.stopPropagation();
|
|
1204
|
+
e.currentTarget.setPointerCapture?.(e.pointerId);
|
|
1205
|
+
start.current = { x: e.clientX, w: props.width };
|
|
1206
|
+
setActive(true);
|
|
1207
|
+
},
|
|
1208
|
+
onPointerMove: (e) => {
|
|
1209
|
+
if (!start.current) return;
|
|
1210
|
+
props.controller.setColumnSize(props.column.key, start.current.w + e.clientX - start.current.x);
|
|
1211
|
+
},
|
|
1212
|
+
onPointerUp: () => {
|
|
1213
|
+
start.current = null;
|
|
1214
|
+
setActive(false);
|
|
1215
|
+
},
|
|
1216
|
+
onPointerCancel: () => {
|
|
1217
|
+
start.current = null;
|
|
1218
|
+
setActive(false);
|
|
1219
|
+
},
|
|
1220
|
+
onKeyDown: (e) => {
|
|
1221
|
+
if (e.key === "ArrowLeft" || e.key === "ArrowRight") {
|
|
1222
|
+
e.preventDefault();
|
|
1223
|
+
props.controller.setColumnSize(props.column.key, props.width + (e.key === "ArrowRight" ? 16 : -16));
|
|
1224
|
+
}
|
|
1225
|
+
}
|
|
1226
|
+
}
|
|
1227
|
+
);
|
|
1228
|
+
}
|
|
1229
|
+
function DataGrid(props) {
|
|
1230
|
+
useCervioViewStyles(props.unstyled);
|
|
1231
|
+
const { controller } = props;
|
|
1232
|
+
const state = useViewState(controller);
|
|
1233
|
+
const locale = props.locale ?? state.definition?.locale ?? "it";
|
|
1234
|
+
const t = viewLabels(locale, props.labels);
|
|
1235
|
+
const cols = state.visibleColumns;
|
|
1236
|
+
const resizable = props.resizable ?? true;
|
|
1237
|
+
const clickable = !!(props.onRowClick || props.onRowDoubleClick);
|
|
1238
|
+
const onScroll = (e) => {
|
|
1239
|
+
if (props.autoLoadMore === false) return;
|
|
1240
|
+
const el = e.currentTarget;
|
|
1241
|
+
if (el.scrollHeight - el.scrollTop - el.clientHeight < 120) controller.loadMore().catch(() => {
|
|
1242
|
+
});
|
|
1243
|
+
};
|
|
1244
|
+
const showEmpty = !state.loading && state.status !== "loading" && state.rows.length === 0;
|
|
1245
|
+
const sortable = props.sortable ?? true;
|
|
1246
|
+
const [collapsed, setCollapsed] = useState(() => /* @__PURE__ */ new Set());
|
|
1247
|
+
const toggleGroup = (path) => setCollapsed((prev) => {
|
|
1248
|
+
const next = new Set(prev);
|
|
1249
|
+
if (next.has(path)) next.delete(path);
|
|
1250
|
+
else next.add(path);
|
|
1251
|
+
return next;
|
|
1252
|
+
});
|
|
1253
|
+
const renderRow = (row) => /* @__PURE__ */ jsx(
|
|
1254
|
+
"tr",
|
|
1255
|
+
{
|
|
1256
|
+
"data-clickable": clickable ? "true" : void 0,
|
|
1257
|
+
"data-selected": props.selectedId === row.id ? "true" : void 0,
|
|
1258
|
+
"data-tone": props.rowTone?.(row) ?? void 0,
|
|
1259
|
+
"aria-selected": props.selectedId != null ? props.selectedId === row.id : void 0,
|
|
1260
|
+
onClick: props.onRowClick ? () => props.onRowClick(row) : void 0,
|
|
1261
|
+
onDoubleClick: props.onRowDoubleClick ? () => props.onRowDoubleClick(row) : void 0,
|
|
1262
|
+
children: cols.map((c) => {
|
|
1263
|
+
const value = row.data[c.key];
|
|
1264
|
+
const children = /* @__PURE__ */ jsx(FieldValue, { column: c, value, locale, tone: props.cellTone?.(c, row) });
|
|
1265
|
+
return /* @__PURE__ */ jsx("td", { className: isNumberColumn(c) ? "cv-num" : void 0, children: props.renderCell ? props.renderCell({ column: c, row, value, children }) : children }, c.key);
|
|
1266
|
+
})
|
|
1267
|
+
},
|
|
1268
|
+
row.id
|
|
1269
|
+
);
|
|
1270
|
+
const renderGroups = (groups, parent, level) => groups.flatMap((g) => {
|
|
1271
|
+
const path = `${parent}/${g.column}:${g.value}`;
|
|
1272
|
+
const open = !collapsed.has(path);
|
|
1273
|
+
const colLabel = state.columns.find((c) => c.key === g.column)?.label ?? g.column;
|
|
1274
|
+
return [
|
|
1275
|
+
/* @__PURE__ */ jsx("tr", { className: "cv-group", "aria-expanded": open, onClick: () => toggleGroup(path), children: /* @__PURE__ */ jsx("td", { colSpan: Math.max(1, cols.length), style: { paddingLeft: 10 + level * 16 }, children: /* @__PURE__ */ jsxs("span", { className: "cv-group-label", style: { left: 10 + level * 16 }, children: [
|
|
1276
|
+
/* @__PURE__ */ jsx("span", { className: "cv-group-toggle", "aria-hidden": true, children: open ? "\u25BE" : "\u25B8" }),
|
|
1277
|
+
/* @__PURE__ */ jsxs("span", { className: "cv-muted-inline", children: [
|
|
1278
|
+
colLabel,
|
|
1279
|
+
": "
|
|
1280
|
+
] }),
|
|
1281
|
+
g.label || t.empty,
|
|
1282
|
+
/* @__PURE__ */ jsx("span", { className: "cv-group-count", children: g.count })
|
|
1283
|
+
] }) }) }, `g${path}`),
|
|
1284
|
+
...open ? g.groups ? renderGroups(g.groups, path, level + 1) : g.rows.map(renderRow) : []
|
|
1285
|
+
];
|
|
1286
|
+
});
|
|
1287
|
+
return /* @__PURE__ */ jsxs(
|
|
1288
|
+
"div",
|
|
1289
|
+
{
|
|
1290
|
+
className: ["cv-grid-wrap", props.className].filter(Boolean).join(" "),
|
|
1291
|
+
style: props.style,
|
|
1292
|
+
onScroll,
|
|
1293
|
+
"aria-busy": state.loading,
|
|
1294
|
+
children: [
|
|
1295
|
+
/* @__PURE__ */ jsxs("table", { className: "cv-grid", role: "grid", "aria-rowcount": state.total ?? void 0, children: [
|
|
1296
|
+
/* @__PURE__ */ jsx("colgroup", { children: cols.map((c) => /* @__PURE__ */ jsx("col", { style: { width: c.width ?? DEFAULT_COLUMN_WIDTH } }, c.key)) }),
|
|
1297
|
+
/* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsx("tr", { children: cols.map((c) => /* @__PURE__ */ jsxs(
|
|
1298
|
+
"th",
|
|
1299
|
+
{
|
|
1300
|
+
className: ["cv-th", isNumberColumn(c) ? "cv-num" : ""].join(" ").trim(),
|
|
1301
|
+
scope: "col",
|
|
1302
|
+
title: c.label,
|
|
1303
|
+
"aria-sort": (() => {
|
|
1304
|
+
const s = state.sorting.find((x) => x.key === c.key);
|
|
1305
|
+
return s ? s.desc ? "descending" : "ascending" : void 0;
|
|
1306
|
+
})(),
|
|
1307
|
+
children: [
|
|
1308
|
+
sortable ? /* @__PURE__ */ jsxs("button", { type: "button", className: "cv-sort", onClick: (e) => controller.toggleSort(c.key, e.shiftKey), children: [
|
|
1309
|
+
props.renderHeader ? props.renderHeader(c) : c.label,
|
|
1310
|
+
(() => {
|
|
1311
|
+
const i = state.sorting.findIndex((x) => x.key === c.key);
|
|
1312
|
+
if (i < 0) return null;
|
|
1313
|
+
const s = state.sorting[i];
|
|
1314
|
+
return /* @__PURE__ */ jsxs("span", { className: "cv-sort-mark", "aria-label": s.desc ? t.sortDesc : t.sortAsc, children: [
|
|
1315
|
+
s.desc ? "\u25BC" : "\u25B2",
|
|
1316
|
+
state.sorting.length > 1 ? i + 1 : ""
|
|
1317
|
+
] });
|
|
1318
|
+
})()
|
|
1319
|
+
] }) : props.renderHeader ? props.renderHeader(c) : c.label,
|
|
1320
|
+
resizable ? /* @__PURE__ */ jsx(ResizeHandle, { column: c, width: c.width ?? DEFAULT_COLUMN_WIDTH, controller, label: t.resize(c.label) }) : null
|
|
1321
|
+
]
|
|
1322
|
+
},
|
|
1323
|
+
c.key
|
|
1324
|
+
)) }) }),
|
|
1325
|
+
/* @__PURE__ */ jsx("tbody", { children: state.groups?.length ? renderGroups(state.groups, "", 0) : state.rows.map(renderRow) })
|
|
1326
|
+
] }),
|
|
1327
|
+
state.error ? (
|
|
1328
|
+
// A failed load is not an empty result; rows from before stay visible under it.
|
|
1329
|
+
/* @__PURE__ */ jsxs("div", { className: "cv-error cv-grid-error", role: "alert", children: [
|
|
1330
|
+
t.error,
|
|
1331
|
+
": ",
|
|
1332
|
+
state.error.message
|
|
1333
|
+
] })
|
|
1334
|
+
) : showEmpty ? /* @__PURE__ */ jsx("div", { className: "cv-empty", children: props.renderEmpty ? props.renderEmpty() : t.noResults }) : null,
|
|
1335
|
+
(state.loading || state.loadingAll) && state.rows.length > 0 ? /* @__PURE__ */ jsx("div", { className: "cv-loading", title: state.loadingAll ? t.loadingAll : void 0 }) : null
|
|
1336
|
+
]
|
|
1337
|
+
}
|
|
1338
|
+
);
|
|
1339
|
+
}
|
|
1340
|
+
|
|
1341
|
+
// src/views/react.ts
|
|
1342
|
+
function useCervioView(opts) {
|
|
1343
|
+
const controller = useMemo(() => createPluginViewController(opts), [opts.view, opts.layoutScope]);
|
|
1344
|
+
useEffect(() => () => controller.destroy(), [controller]);
|
|
1345
|
+
const state = useSyncExternalStore(controller.subscribe, controller.getState, controller.getState);
|
|
1346
|
+
return {
|
|
1347
|
+
...state,
|
|
1348
|
+
controller,
|
|
1349
|
+
ready: controller.ready,
|
|
1350
|
+
setFilter: controller.setFilter,
|
|
1351
|
+
setFilters: controller.setFilters,
|
|
1352
|
+
clearFilters: controller.clearFilters,
|
|
1353
|
+
setSearch: controller.setSearch,
|
|
1354
|
+
refresh: controller.refresh,
|
|
1355
|
+
loadMore: controller.loadMore,
|
|
1356
|
+
setColumnSize: controller.setColumnSize,
|
|
1357
|
+
setColumnOrder: controller.setColumnOrder,
|
|
1358
|
+
setColumnVisibility: controller.setColumnVisibility,
|
|
1359
|
+
setColumnPinning: controller.setColumnPinning,
|
|
1360
|
+
setSorting: controller.setSorting,
|
|
1361
|
+
toggleSort: controller.toggleSort,
|
|
1362
|
+
setGrouping: controller.setGrouping,
|
|
1363
|
+
filterOptions: controller.filterOptions,
|
|
1364
|
+
flushLayout: controller.flushLayout
|
|
1365
|
+
};
|
|
1366
|
+
}
|
|
1367
|
+
|
|
1368
|
+
export { CERVIO_VIEW_CSS, ColumnsMenu, DEFAULT_COLUMN_WIDTH, DataGrid, FieldValue, FilterBar, GroupByMenu, SearchBox, ensureCervioViewStyles, formatViewValue, isNumberColumn, rawViewValue, useCervioView, useViewState, viewLabels };
|