strapi-plugin-magic-mark 3.4.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/CHANGELOG.md +366 -0
  2. package/README.md +390 -619
  3. package/dist/admin/App-C9PsvW9C.mjs +580 -0
  4. package/dist/admin/App-KJvUCwN1.js +580 -0
  5. package/dist/admin/PinnedBookmarksWidget-ClskVR1i.mjs +55 -0
  6. package/dist/admin/PinnedBookmarksWidget-DlD8lDhq.js +55 -0
  7. package/dist/admin/de-BF0nCjGF.mjs +183 -0
  8. package/dist/admin/de-Cn90CcnC.js +183 -0
  9. package/dist/admin/en-D-EGHodf.mjs +183 -0
  10. package/dist/admin/en-GDfO_EfL.js +183 -0
  11. package/dist/admin/es-6o-_RABX.js +183 -0
  12. package/dist/admin/es-C33BufuB.mjs +183 -0
  13. package/dist/admin/fr-BOZS5mJT.js +183 -0
  14. package/dist/admin/fr-DJHTjkmb.mjs +183 -0
  15. package/dist/admin/index-CLjQOzqv.js +1770 -0
  16. package/dist/admin/index-X8I03cOT.mjs +1769 -0
  17. package/dist/admin/index.js +4 -2
  18. package/dist/admin/index.mjs +2 -1
  19. package/dist/admin/pt-D13SxuK2.js +183 -0
  20. package/dist/admin/pt-yoB1jrsq.mjs +183 -0
  21. package/dist/server/index.js +1129 -1542
  22. package/dist/server/index.mjs +1126 -1539
  23. package/package.json +90 -54
  24. package/strapi-admin.js +5 -0
  25. package/strapi-server.js +2 -1
  26. package/COPYRIGHT_NOTICE.txt +0 -20
  27. package/dist/_chunks/App-DNyxeldt.js +0 -1451
  28. package/dist/_chunks/App-D_Vllkur.mjs +0 -1449
  29. package/dist/_chunks/UpgradePage-DuyIskve.mjs +0 -351
  30. package/dist/_chunks/UpgradePage-SzlmS6po.js +0 -353
  31. package/dist/_chunks/de-Cs9dd3Mr.js +0 -138
  32. package/dist/_chunks/de-DOVki5VS.mjs +0 -138
  33. package/dist/_chunks/en-CE3r46Y2.js +0 -138
  34. package/dist/_chunks/en-Cf5-O03L.mjs +0 -138
  35. package/dist/_chunks/es-Ba6JcPIm.mjs +0 -138
  36. package/dist/_chunks/es-D4AOyJYJ.js +0 -138
  37. package/dist/_chunks/fr-CWSfoA8i.js +0 -138
  38. package/dist/_chunks/fr-CrMBXR3c.mjs +0 -138
  39. package/dist/_chunks/index-CBwb0AEf.js +0 -3618
  40. package/dist/_chunks/index-JirQF8zE.mjs +0 -328
  41. package/dist/_chunks/index-QkINaIgJ.mjs +0 -3614
  42. package/dist/_chunks/index-uUErgmi9.js +0 -330
  43. package/dist/_chunks/pt-BXxZ1Zym.mjs +0 -138
  44. package/dist/_chunks/pt-DW_6r_mP.js +0 -138
  45. package/pics/advancedFilters.png +0 -0
  46. package/pics/dashboard.png +0 -0
  47. package/pics/quickaccesinContentmanager.png +0 -0
  48. package/pics/saveAsMagicMark.png +0 -0
@@ -0,0 +1,1770 @@
1
+ "use strict";
2
+ const icons = require("@strapi/icons");
3
+ const jsxRuntime = require("react/jsx-runtime");
4
+ const designSystem = require("@strapi/design-system");
5
+ const admin = require("@strapi/strapi/admin");
6
+ const react = require("react");
7
+ const reactIntl = require("react-intl");
8
+ const reactRouterDom = require("react-router-dom");
9
+ const qs = require("qs");
10
+ const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
11
+ const qs__default = /* @__PURE__ */ _interopDefault(qs);
12
+ const __variableDynamicImportRuntimeHelper = (glob, path, segs) => {
13
+ const v = glob[path];
14
+ if (v) {
15
+ return typeof v === "function" ? v() : Promise.resolve(v);
16
+ }
17
+ return new Promise((_, reject) => {
18
+ (typeof queueMicrotask === "function" ? queueMicrotask : setTimeout)(
19
+ reject.bind(
20
+ null,
21
+ new Error(
22
+ "Unknown variable dynamic import: " + path + (path.split("/").length !== segs ? ". Note that variables only represent file names one level deep." : "")
23
+ )
24
+ )
25
+ );
26
+ });
27
+ };
28
+ const action = (uid) => [{ action: `plugin::magic-mark.${uid}`, subject: null }];
29
+ const PERMISSIONS = {
30
+ read: action("bookmarks.read"),
31
+ create: action("bookmarks.create"),
32
+ update: action("bookmarks.update"),
33
+ delete: action("bookmarks.delete"),
34
+ share: action("bookmarks.share"),
35
+ manage: action("bookmarks.manage")
36
+ };
37
+ const ALL_PERMISSIONS = Object.values(PERMISSIONS).flat();
38
+ const LIST_VIEW_PATH = /^\/content-manager\/(collection-types|single-types)\/((?:api|plugin)::[a-z0-9_-]{1,80}\.[a-z0-9_-]{1,80})\/?$/;
39
+ const SAVED_QUERY_KEYS = ["filters", "sort", "pageSize", "_q", "plugins"];
40
+ const PERSISTED_KEYS = ["sort", "filters", "pageSize"];
41
+ const parseListViewPath = (pathname) => {
42
+ if (typeof pathname !== "string") return null;
43
+ const match = LIST_VIEW_PATH.exec(pathname);
44
+ if (!match) return null;
45
+ return {
46
+ kind: match[1],
47
+ uid: match[2],
48
+ path: `/content-manager/${match[1]}/${match[2]}`
49
+ };
50
+ };
51
+ const pickSavedQuery = (query) => {
52
+ const out = {};
53
+ for (const key of SAVED_QUERY_KEYS) {
54
+ const value = query[key];
55
+ if (value === void 0 || value === "") continue;
56
+ if (key === "plugins") {
57
+ const locale = value?.i18n?.locale;
58
+ if (typeof locale === "string") out.plugins = { i18n: { locale } };
59
+ continue;
60
+ }
61
+ out[key] = value;
62
+ }
63
+ return out;
64
+ };
65
+ const syncPersistedListSettings = (storage, uid, saved) => {
66
+ const prefix = `STRAPI_LIST_VIEW_SETTINGS:${uid}`;
67
+ const value = {};
68
+ for (const key of PERSISTED_KEYS) {
69
+ if (saved[key] !== void 0) value[key] = saved[key];
70
+ }
71
+ const keys = [];
72
+ for (let i = 0; i < storage.length; i += 1) {
73
+ const key = storage.key(i);
74
+ if (key && (key === prefix || key.startsWith(`${prefix}:`))) keys.push(key);
75
+ }
76
+ for (const key of keys) {
77
+ if (Object.keys(value).length) storage.setItem(key, JSON.stringify(value));
78
+ else storage.removeItem(key);
79
+ }
80
+ };
81
+ const pluginId = "magic-mark";
82
+ const msg = (key, defaultMessage) => ({
83
+ id: `${pluginId}.${key}`,
84
+ defaultMessage
85
+ });
86
+ const NATIVE_OPERATOR_LABELS = {
87
+ $eq: "is",
88
+ $ne: "is not",
89
+ $null: "is null",
90
+ $notNull: "is not null",
91
+ $eqi: "is (case insensitive)",
92
+ $nei: "is not (case insensitive)",
93
+ $contains: "contains",
94
+ $containsi: "contains (case insensitive)",
95
+ $notContains: "does not contain",
96
+ $notContainsi: "does not contain (case insensitive)",
97
+ $startsWith: "starts with",
98
+ $startsWithi: "starts with (case insensitive)",
99
+ $endsWith: "ends with",
100
+ $endsWithi: "ends with (case insensitive)",
101
+ $gt: "is greater than",
102
+ $gte: "is greater than or equal to",
103
+ $lt: "is lower than",
104
+ $lte: "is lower than or equal to"
105
+ };
106
+ const PLUGIN_OPERATOR_LABELS = {
107
+ $in: msg("operators.in", "is one of"),
108
+ $notIn: msg("operators.notIn", "is none of"),
109
+ $between: msg("operators.between", "is between")
110
+ };
111
+ const operatorLabel = (operator) => PLUGIN_OPERATOR_LABELS[operator] ?? {
112
+ id: `components.FilterOptions.FILTER_TYPES.${operator}`,
113
+ defaultMessage: NATIVE_OPERATOR_LABELS[operator] ?? operator
114
+ };
115
+ const NOT_FILTERABLE = /* @__PURE__ */ new Set([
116
+ "json",
117
+ "component",
118
+ "media",
119
+ "richtext",
120
+ "dynamiczone",
121
+ "password",
122
+ "blocks",
123
+ "relation"
124
+ ]);
125
+ const SCALAR_SUB_TYPES = /* @__PURE__ */ new Set([
126
+ "string",
127
+ "text",
128
+ "email",
129
+ "uid",
130
+ "integer",
131
+ "biginteger",
132
+ "float",
133
+ "decimal",
134
+ "date",
135
+ "datetime",
136
+ "time",
137
+ "boolean",
138
+ "enumeration"
139
+ ]);
140
+ const COMPONENT_INTERNAL_KEYS = /* @__PURE__ */ new Set(["id", "documentId"]);
141
+ const mainFieldName = (meta) => {
142
+ const main = meta?.list?.mainField ?? meta?.edit?.mainField;
143
+ return typeof main === "string" ? main : main?.name;
144
+ };
145
+ const buildFieldOptions = (uid, init, metadatas, readable) => {
146
+ const schema = init.contentTypes.find((ct) => ct.uid === uid);
147
+ if (!schema) return [];
148
+ const fields = [
149
+ { path: "id", label: "id", type: "integer" },
150
+ { path: "documentId", label: "documentId", type: "string" }
151
+ ];
152
+ const canRead = (name) => readable === null || readable.some((field) => field === name || field.startsWith(`${name}.`));
153
+ for (const [name, attribute] of Object.entries(schema.attributes)) {
154
+ if (!canRead(name) || attribute.private) continue;
155
+ const label = metadatas[name]?.list?.label || metadatas[name]?.edit?.label || name;
156
+ if (attribute.type === "relation") {
157
+ const target = attribute.targetModel ?? attribute.target;
158
+ if (!target || target === "admin::user") continue;
159
+ const targetSchema = init.contentTypes.find((ct) => ct.uid === target);
160
+ const main = mainFieldName(metadatas[name]);
161
+ const mainType = main ? targetSchema?.attributes?.[main]?.type : void 0;
162
+ if (main && mainType && SCALAR_SUB_TYPES.has(mainType)) {
163
+ fields.push({
164
+ path: `${name}.${main}`,
165
+ label: `${label} (${main})`,
166
+ type: mainType,
167
+ group: label
168
+ });
169
+ }
170
+ fields.push({ path: `${name}.id`, label: `${label} (id)`, type: "integer", group: label });
171
+ continue;
172
+ }
173
+ if (attribute.type === "component" && !attribute.repeatable && attribute.component) {
174
+ const component = init.components.find((c) => c.uid === attribute.component);
175
+ for (const [subName, sub] of Object.entries(component?.attributes ?? {})) {
176
+ if (COMPONENT_INTERNAL_KEYS.has(subName)) continue;
177
+ if (!SCALAR_SUB_TYPES.has(sub.type) || sub.private) continue;
178
+ fields.push({
179
+ path: `${name}.${subName}`,
180
+ label: `${label} (${subName})`,
181
+ type: sub.type,
182
+ enum: sub.enum,
183
+ group: label
184
+ });
185
+ }
186
+ continue;
187
+ }
188
+ if (NOT_FILTERABLE.has(attribute.type)) continue;
189
+ fields.push({ path: name, label, type: attribute.type, enum: attribute.enum });
190
+ }
191
+ for (const name of ["createdAt", "updatedAt"]) {
192
+ if (!fields.some((field) => field.path === name)) {
193
+ fields.push({ path: name, label: metadatas[name]?.list?.label || name, type: "datetime" });
194
+ }
195
+ }
196
+ return fields;
197
+ };
198
+ let initCache = null;
199
+ const configCache = /* @__PURE__ */ new Map();
200
+ const loadInit = (get) => {
201
+ if (!initCache) {
202
+ initCache = get("/content-manager/init").then(({ data }) => data.data).catch((error) => {
203
+ initCache = null;
204
+ throw error;
205
+ });
206
+ }
207
+ return initCache;
208
+ };
209
+ const loadMetadatas = (get, uid) => {
210
+ let promise = configCache.get(uid);
211
+ if (!promise) {
212
+ promise = get(
213
+ `/content-manager/content-types/${uid}/configuration`
214
+ ).then(({ data }) => data.data.contentType.metadatas ?? {}).catch((error) => {
215
+ configCache.delete(uid);
216
+ throw error;
217
+ });
218
+ configCache.set(uid, promise);
219
+ }
220
+ return promise;
221
+ };
222
+ const useContentTypeNames = () => {
223
+ const { get } = admin.useFetchClient();
224
+ const [state, setState] = react.useState({
225
+ names: /* @__PURE__ */ new Map(),
226
+ isLoading: true,
227
+ error: null
228
+ });
229
+ react.useEffect(() => {
230
+ let active = true;
231
+ loadInit(get).then((init) => {
232
+ if (!active) return;
233
+ setState({
234
+ names: new Map(init.contentTypes.map((ct) => [ct.uid, ct.info?.displayName ?? ct.uid])),
235
+ isLoading: false,
236
+ error: null
237
+ });
238
+ }).catch((error) => active && setState({ names: /* @__PURE__ */ new Map(), isLoading: false, error }));
239
+ return () => {
240
+ active = false;
241
+ };
242
+ }, [get]);
243
+ return state;
244
+ };
245
+ const useFilterFields = (uid) => {
246
+ const { get } = admin.useFetchClient();
247
+ const permissions = admin.useAuth("MagicMarkFilters", (state2) => state2.permissions);
248
+ const [attempt, setAttempt] = react.useState(0);
249
+ const [state, setState] = react.useState({
250
+ key: "",
251
+ fields: [],
252
+ error: null
253
+ });
254
+ const readable = react.useMemo(() => {
255
+ const permission = permissions.find(
256
+ (p) => p.action === "plugin::content-manager.explorer.read" && p.subject === uid
257
+ );
258
+ const fields = permission?.properties?.fields;
259
+ return Array.isArray(fields) ? fields : null;
260
+ }, [permissions, uid]);
261
+ const key = uid ? `${uid}:${attempt}` : "";
262
+ react.useEffect(() => {
263
+ if (!uid) return void 0;
264
+ let active = true;
265
+ Promise.all([loadInit(get), loadMetadatas(get, uid)]).then(([init, metadatas]) => {
266
+ if (active) {
267
+ setState({ key, fields: buildFieldOptions(uid, init, metadatas, readable), error: null });
268
+ }
269
+ }).catch((error) => active && setState({ key, fields: [], error }));
270
+ return () => {
271
+ active = false;
272
+ };
273
+ }, [get, uid, readable, key]);
274
+ const current = state.key === key;
275
+ return {
276
+ fields: current ? state.fields : [],
277
+ error: current ? state.error : null,
278
+ isLoading: !!uid && !current,
279
+ retry: () => setAttempt((n) => n + 1)
280
+ };
281
+ };
282
+ const ADMIN_QUERY_DEPTH = 5;
283
+ const NO_VALUE_OPERATORS = ["$null", "$notNull"];
284
+ const LIST_OPERATORS = ["$in", "$notIn"];
285
+ const RANGE_OPERATORS = ["$between"];
286
+ const BASE$1 = ["$eq", "$ne", "$null", "$notNull"];
287
+ const NUMERIC = ["$gt", "$gte", "$lt", "$lte"];
288
+ const SENSITIVE = ["$eqi", "$nei"];
289
+ const CONTAINS = ["$contains", "$containsi", "$notContains", "$notContainsi"];
290
+ const STRING_PARSE = ["$startsWith", "$startsWithi", "$endsWith", "$endsWithi"];
291
+ const ALL_OPERATORS = [
292
+ ...BASE$1,
293
+ ...SENSITIVE,
294
+ ...CONTAINS,
295
+ ...STRING_PARSE,
296
+ ...NUMERIC,
297
+ ...LIST_OPERATORS,
298
+ ...RANGE_OPERATORS
299
+ ];
300
+ const operatorsForType = (type, isSubField = false) => {
301
+ let ops;
302
+ switch (type) {
303
+ case "email":
304
+ case "string":
305
+ case "text":
306
+ case "uid":
307
+ ops = [...BASE$1, ...SENSITIVE, ...CONTAINS, ...STRING_PARSE, ...LIST_OPERATORS];
308
+ break;
309
+ case "float":
310
+ case "integer":
311
+ case "biginteger":
312
+ case "decimal":
313
+ ops = [...BASE$1, ...NUMERIC, ...LIST_OPERATORS, ...RANGE_OPERATORS];
314
+ break;
315
+ case "date":
316
+ case "time":
317
+ ops = [...BASE$1, ...NUMERIC, ...CONTAINS, ...RANGE_OPERATORS];
318
+ break;
319
+ case "datetime":
320
+ ops = [...BASE$1, ...NUMERIC, ...RANGE_OPERATORS];
321
+ break;
322
+ case "enumeration":
323
+ ops = [...BASE$1, ...LIST_OPERATORS];
324
+ break;
325
+ case "boolean":
326
+ ops = [...BASE$1];
327
+ break;
328
+ default:
329
+ ops = [...BASE$1, ...SENSITIVE];
330
+ }
331
+ return isSubField ? ops.filter((op) => !LIST_OPERATORS.includes(op) && !RANGE_OPERATORS.includes(op)) : ops;
332
+ };
333
+ const splitList = (value) => value.split(",").map((item) => item.trim()).filter(Boolean);
334
+ const validateRow = (row, fields) => {
335
+ const field = fields.get(row.field);
336
+ if (!field) return "field";
337
+ if (!operatorsForType(field.type, row.field.includes(".")).includes(row.operator)) {
338
+ return "operator";
339
+ }
340
+ if (NO_VALUE_OPERATORS.includes(row.operator)) return null;
341
+ if (LIST_OPERATORS.includes(row.operator)) return splitList(row.value).length ? null : "value";
342
+ if (!row.value.trim()) return "value";
343
+ if (RANGE_OPERATORS.includes(row.operator) && !(row.valueTo ?? "").trim()) return "valueTo";
344
+ return null;
345
+ };
346
+ const operatorValue = (row) => {
347
+ if (NO_VALUE_OPERATORS.includes(row.operator)) return { [row.operator]: "true" };
348
+ if (LIST_OPERATORS.includes(row.operator)) return { [row.operator]: splitList(row.value) };
349
+ if (RANGE_OPERATORS.includes(row.operator)) {
350
+ return { [row.operator]: [row.value.trim(), (row.valueTo ?? "").trim()] };
351
+ }
352
+ return { [row.operator]: row.value.trim() };
353
+ };
354
+ const rowToFilter = (row) => {
355
+ const [head, sub] = row.field.split(".");
356
+ return sub ? { [head]: { [sub]: operatorValue(row) } } : { [head]: operatorValue(row) };
357
+ };
358
+ const buildFilters = (match, rows) => {
359
+ if (!rows.length) return void 0;
360
+ return { [match === "any" ? "$or" : "$and"]: rows.map(rowToFilter) };
361
+ };
362
+ const filterDepth = (value) => {
363
+ if (Array.isArray(value)) {
364
+ return value.length ? 1 + Math.max(...value.map(filterDepth)) : 1;
365
+ }
366
+ if (value && typeof value === "object") {
367
+ const entries = Object.values(value);
368
+ return entries.length ? 1 + Math.max(...entries.map(filterDepth)) : 1;
369
+ }
370
+ return 0;
371
+ };
372
+ const fitsAdminQueryDepth = (filters) => filterDepth(filters) <= ADMIN_QUERY_DEPTH;
373
+ const isPlainObject = (value) => !!value && typeof value === "object" && !Array.isArray(value);
374
+ const SAFE_KEY = /^[A-Za-z_][A-Za-z0-9_]{0,99}$/;
375
+ const OPERATOR = /^\$[A-Za-z]{1,20}$/;
376
+ let rowCounter = 0;
377
+ const nextRowId = () => {
378
+ rowCounter += 1;
379
+ return `row-${rowCounter}`;
380
+ };
381
+ const entryToRow = (entry) => {
382
+ if (!isPlainObject(entry)) return null;
383
+ const keys = Object.keys(entry);
384
+ if (keys.length !== 1 || !SAFE_KEY.test(keys[0])) return null;
385
+ const head = keys[0];
386
+ const inner = entry[head];
387
+ if (!isPlainObject(inner)) return null;
388
+ const innerKeys = Object.keys(inner);
389
+ if (innerKeys.length !== 1) return null;
390
+ let path = head;
391
+ let opObject = inner;
392
+ if (!OPERATOR.test(innerKeys[0])) {
393
+ if (!SAFE_KEY.test(innerKeys[0])) return null;
394
+ const nested = inner[innerKeys[0]];
395
+ if (!isPlainObject(nested) || Object.keys(nested).length !== 1) return null;
396
+ path = `${head}.${innerKeys[0]}`;
397
+ opObject = nested;
398
+ }
399
+ const operator = Object.keys(opObject)[0];
400
+ if (!ALL_OPERATORS.includes(operator)) return null;
401
+ const raw = opObject[operator];
402
+ if (NO_VALUE_OPERATORS.includes(operator)) {
403
+ return { id: nextRowId(), field: path, operator, value: "" };
404
+ }
405
+ if (LIST_OPERATORS.includes(operator)) {
406
+ const list = Array.isArray(raw) ? raw : [raw];
407
+ if (!list.every((item) => typeof item === "string")) return null;
408
+ return { id: nextRowId(), field: path, operator, value: list.join(", ") };
409
+ }
410
+ if (RANGE_OPERATORS.includes(operator)) {
411
+ if (!Array.isArray(raw) || raw.length !== 2 || !raw.every((v) => typeof v === "string")) {
412
+ return null;
413
+ }
414
+ return { id: nextRowId(), field: path, operator, value: raw[0], valueTo: raw[1] };
415
+ }
416
+ if (typeof raw !== "string") return null;
417
+ return { id: nextRowId(), field: path, operator, value: raw };
418
+ };
419
+ const parseFilters = (filters) => {
420
+ if (filters === void 0 || filters === null || filters === "") {
421
+ return { match: "all", rows: [], unsupported: false };
422
+ }
423
+ if (!isPlainObject(filters)) return { match: "all", rows: [], unsupported: true };
424
+ const keys = Object.keys(filters);
425
+ if (keys.length !== 1 || !["$and", "$or"].includes(keys[0])) {
426
+ return { match: "all", rows: [], unsupported: true };
427
+ }
428
+ const match = keys[0] === "$or" ? "any" : "all";
429
+ const list = filters[keys[0]];
430
+ const entries = Array.isArray(list) ? list : isPlainObject(list) ? Object.values(list) : [];
431
+ const rows = [];
432
+ let unsupported = !Array.isArray(list) && !isPlainObject(list);
433
+ for (const entry of entries) {
434
+ const row = entryToRow(entry);
435
+ if (row) rows.push(row);
436
+ else unsupported = true;
437
+ }
438
+ return { match, rows, unsupported };
439
+ };
440
+ const countConditions = (filters) => {
441
+ if (!isPlainObject(filters)) return 0;
442
+ let count = 0;
443
+ for (const [key, value] of Object.entries(filters)) {
444
+ if (key === "$and" || key === "$or") {
445
+ count += Array.isArray(value) ? value.length : isPlainObject(value) ? Object.keys(value).length : 0;
446
+ } else {
447
+ count += 1;
448
+ }
449
+ }
450
+ return count;
451
+ };
452
+ const FOCUSABLE = [
453
+ "a[href]",
454
+ "button:not([disabled])",
455
+ 'input:not([disabled]):not([type="hidden"])',
456
+ "select:not([disabled])",
457
+ "textarea:not([disabled])",
458
+ '[tabindex]:not([tabindex="-1"])',
459
+ '[contenteditable="true"]'
460
+ ].join(",");
461
+ const loopTarget = (nodes, active, backwards) => {
462
+ if (!nodes.length) return null;
463
+ const first = nodes[0];
464
+ const last = nodes[nodes.length - 1];
465
+ const index2 = active === null ? -1 : nodes.indexOf(active);
466
+ if (index2 === -1) return backwards ? last : first;
467
+ if (!backwards && active === last) return first;
468
+ if (backwards && active === first) return last;
469
+ return null;
470
+ };
471
+ const keepFocusInside = (event) => {
472
+ if (event.key !== "Tab" || event.defaultPrevented) return;
473
+ const container = event.currentTarget;
474
+ const active = document.activeElement;
475
+ if (active && !container.contains(active)) return;
476
+ const nodes = Array.from(container.querySelectorAll(FOCUSABLE)).filter(
477
+ (node) => node.getClientRects().length > 0 && node.getAttribute("aria-hidden") !== "true"
478
+ );
479
+ const target = loopTarget(nodes, active, event.shiftKey);
480
+ if (target) {
481
+ event.preventDefault();
482
+ target.focus();
483
+ }
484
+ };
485
+ const LINK_TARGET = {
486
+ paddingTop: "0.6rem",
487
+ paddingBottom: "0.6rem",
488
+ marginTop: "-0.6rem",
489
+ marginBottom: "-0.6rem"
490
+ };
491
+ const TEXT_BUTTON_TARGET = {
492
+ paddingTop: "0.8rem",
493
+ paddingBottom: "0.8rem",
494
+ marginTop: "-0.8rem",
495
+ marginBottom: "-0.8rem"
496
+ };
497
+ const INPUT_TYPES = {
498
+ integer: "number",
499
+ biginteger: "text",
500
+ float: "number",
501
+ decimal: "number",
502
+ date: "date",
503
+ time: "time",
504
+ datetime: "datetime-local",
505
+ email: "text"
506
+ };
507
+ const isoToLocalInput = (value) => {
508
+ const date = new Date(value);
509
+ if (!value.includes("T") || Number.isNaN(date.getTime())) return value;
510
+ const pad = (n) => String(n).padStart(2, "0");
511
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
512
+ };
513
+ const localInputToIso = (value) => {
514
+ const date = new Date(value);
515
+ return value && !Number.isNaN(date.getTime()) ? date.toISOString() : value;
516
+ };
517
+ const emptyRow = () => ({ id: nextRowId(), field: "", operator: "$eq", value: "" });
518
+ const AdvancedFiltersModal = ({ open, onOpenChange, uid }) => {
519
+ const { formatMessage } = reactIntl.useIntl();
520
+ const [{ query }, setQuery] = admin.useQueryParams();
521
+ const { fields, isLoading, error, retry } = useFilterFields(open ? uid : null);
522
+ const fieldMap = react.useMemo(() => new Map(fields.map((field) => [field.path, field])), [fields]);
523
+ const [initial] = react.useState(() => parseFilters(query.filters));
524
+ const [match, setMatch] = react.useState(initial.match);
525
+ const [rows, setRows] = react.useState(
526
+ () => initial.rows.length ? initial.rows.map((row) => ({
527
+ ...row,
528
+ value: isoToLocalInput(row.value),
529
+ valueTo: row.valueTo && isoToLocalInput(row.valueTo)
530
+ })) : [emptyRow()]
531
+ );
532
+ const [unsupported, setUnsupported] = react.useState(initial.unsupported);
533
+ const [showErrors, setShowErrors] = react.useState(false);
534
+ const updateRow = (id, patch) => setRows((prev) => prev.map((row) => row.id === id ? { ...row, ...patch } : row));
535
+ const activeRows = rows.filter((row) => row.field || row.value);
536
+ const rowErrors = new Map(activeRows.map((row) => [row.id, validateRow(row, fieldMap)]));
537
+ const hasErrors = [...rowErrors.values()].some(Boolean);
538
+ const apply = () => {
539
+ setShowErrors(true);
540
+ if (hasErrors) return;
541
+ const prepared = activeRows.map(
542
+ (row) => fieldMap.get(row.field)?.type === "datetime" ? {
543
+ ...row,
544
+ value: localInputToIso(row.value),
545
+ valueTo: row.valueTo && localInputToIso(row.valueTo)
546
+ } : row
547
+ );
548
+ const filters = buildFilters(match, prepared);
549
+ if (filters && !fitsAdminQueryDepth(filters)) return;
550
+ setQuery(
551
+ {
552
+ ...admin.withEncodedUserParams(query, { page: 1 }),
553
+ filters: filters ? admin.deepEncodeQueryValues(filters) : void 0
554
+ },
555
+ "push",
556
+ true
557
+ );
558
+ onOpenChange(false);
559
+ };
560
+ const clearAll = () => {
561
+ setQuery({ ...admin.withEncodedUserParams(query, { page: 1 }), filters: void 0 }, "push", true);
562
+ onOpenChange(false);
563
+ };
564
+ const errorText = (row, part) => {
565
+ if (!showErrors || rowErrors.get(row.id) !== part) return void 0;
566
+ if (part === "field") return formatMessage(msg("filters.errorField", "Choose a field."));
567
+ if (part === "operator")
568
+ return formatMessage(msg("filters.errorOperator", "Choose a condition."));
569
+ return formatMessage(msg("filters.errorValue", "Enter a value."));
570
+ };
571
+ return /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Root, { open, onOpenChange, children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Modal.Content, { onKeyDown: keepFocusInside, children: [
572
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Header, { closeLabel: formatMessage(msg("form.close", "Close")), children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Title, { children: formatMessage(msg("filters.title", "Advanced filters")) }) }),
573
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Body, { children: isLoading ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Flex, { justifyContent: "center", padding: 6, children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Loader, { small: true, children: formatMessage(msg("state.loading", "Loading")) }) }) : error ? /* @__PURE__ */ jsxRuntime.jsx(
574
+ designSystem.Alert,
575
+ {
576
+ variant: "danger",
577
+ closeLabel: formatMessage(msg("form.close", "Close")),
578
+ title: formatMessage(msg("filters.loadErrorTitle", "Fields could not be loaded")),
579
+ action: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Button, { variant: "secondary", size: "S", onClick: retry, children: formatMessage(msg("state.retry", "Try again")) }),
580
+ children: formatMessage(
581
+ msg("filters.loadError", "The fields of this content type could not be loaded.")
582
+ )
583
+ }
584
+ ) : /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "stretch", gap: 6, children: [
585
+ unsupported ? /* @__PURE__ */ jsxRuntime.jsx(
586
+ designSystem.Alert,
587
+ {
588
+ variant: "warning",
589
+ closeLabel: formatMessage(msg("form.close", "Close")),
590
+ onClose: () => setUnsupported(false),
591
+ children: formatMessage(
592
+ msg(
593
+ "filters.unsupported",
594
+ "The list has filters this editor cannot show. Applying replaces them."
595
+ )
596
+ )
597
+ }
598
+ ) : null,
599
+ /* @__PURE__ */ jsxRuntime.jsxs(
600
+ designSystem.Field.Root,
601
+ {
602
+ name: "match",
603
+ hint: match === "any" ? formatMessage(
604
+ msg(
605
+ "filters.matchAnyHint",
606
+ "These conditions are not shown as filter tags above the list."
607
+ )
608
+ ) : void 0,
609
+ children: [
610
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Label, { children: formatMessage(msg("filters.match", "Show entries that match")) }),
611
+ /* @__PURE__ */ jsxRuntime.jsxs(
612
+ designSystem.SingleSelect,
613
+ {
614
+ value: match,
615
+ onChange: (value) => setMatch(value),
616
+ children: [
617
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.SingleSelectOption, { value: "all", children: formatMessage(msg("filters.matchAll", "All conditions")) }),
618
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.SingleSelectOption, { value: "any", children: formatMessage(msg("filters.matchAny", "Any condition")) })
619
+ ]
620
+ }
621
+ ),
622
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Hint, {})
623
+ ]
624
+ }
625
+ ),
626
+ /* @__PURE__ */ jsxRuntime.jsx(
627
+ designSystem.Flex,
628
+ {
629
+ direction: "column",
630
+ alignItems: "stretch",
631
+ gap: 4,
632
+ tag: "ol",
633
+ "aria-label": formatMessage(msg("filters.conditions", "Conditions")),
634
+ children: rows.map((row, index2) => /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { tag: "li", background: "neutral100", hasRadius: true, padding: 4, children: /* @__PURE__ */ jsxRuntime.jsx(
635
+ FilterRowEditor,
636
+ {
637
+ row,
638
+ index: index2,
639
+ fields,
640
+ field: fieldMap.get(row.field),
641
+ onChange: (patch) => updateRow(row.id, patch),
642
+ onRemove: () => setRows((prev) => {
643
+ const next = prev.filter((r) => r.id !== row.id);
644
+ return next.length ? next : [emptyRow()];
645
+ }),
646
+ errorText: (part) => errorText(row, part)
647
+ }
648
+ ) }, row.id))
649
+ }
650
+ ),
651
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { children: /* @__PURE__ */ jsxRuntime.jsx(
652
+ designSystem.TextButton,
653
+ {
654
+ startIcon: /* @__PURE__ */ jsxRuntime.jsx(icons.Plus, {}),
655
+ ...TEXT_BUTTON_TARGET,
656
+ onClick: () => setRows((prev) => [...prev, emptyRow()]),
657
+ children: formatMessage(msg("filters.add", "Add condition"))
658
+ }
659
+ ) })
660
+ ] }) }),
661
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Modal.Footer, { children: [
662
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Button, { variant: "danger-light", onClick: clearAll, disabled: !query.filters, children: formatMessage(msg("filters.clear", "Clear all")) }),
663
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 2, children: [
664
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Close, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Button, { variant: "tertiary", children: formatMessage(msg("form.cancel", "Cancel")) }) }),
665
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Button, { onClick: apply, disabled: isLoading || !!error, children: formatMessage(msg("filters.apply", "Apply")) })
666
+ ] })
667
+ ] })
668
+ ] }) });
669
+ };
670
+ const FilterRowEditor = ({
671
+ row,
672
+ index: index2,
673
+ fields,
674
+ field,
675
+ onChange,
676
+ onRemove,
677
+ errorText
678
+ }) => {
679
+ const { formatMessage } = reactIntl.useIntl();
680
+ const operators = field ? operatorsForType(field.type, row.field.includes(".")) : [];
681
+ const needsValue = !NO_VALUE_OPERATORS.includes(row.operator);
682
+ const position = { number: index2 + 1 };
683
+ return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Grid.Root, { gap: 4, children: [
684
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Grid.Item, { col: 4, s: 6, xs: 12, direction: "column", alignItems: "stretch", children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Field.Root, { name: `field-${row.id}`, error: errorText("field"), children: [
685
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Label, { children: formatMessage(msg("filters.field", "Field")) }),
686
+ /* @__PURE__ */ jsxRuntime.jsx(
687
+ designSystem.Combobox,
688
+ {
689
+ value: row.field,
690
+ onChange: (value) => {
691
+ const next = fields.find((f) => f.path === value);
692
+ const ops = next ? operatorsForType(next.type, (value ?? "").includes(".")) : [];
693
+ onChange({
694
+ field: value ?? "",
695
+ operator: ops.includes(row.operator) ? row.operator : ops[0] ?? "$eq",
696
+ value: "",
697
+ valueTo: void 0
698
+ });
699
+ },
700
+ placeholder: formatMessage(msg("filters.fieldPlaceholder", "Choose a field")),
701
+ noOptionsMessage: () => formatMessage(msg("filters.noFields", "No matching fields")),
702
+ children: fields.map((option) => /* @__PURE__ */ jsxRuntime.jsx(designSystem.ComboboxOption, { value: option.path, children: option.label }, option.path))
703
+ }
704
+ ),
705
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Error, {})
706
+ ] }) }),
707
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Grid.Item, { col: 3, s: 6, xs: 12, direction: "column", alignItems: "stretch", children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Field.Root, { name: `operator-${row.id}`, error: errorText("operator"), children: [
708
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Label, { children: formatMessage(msg("filters.operator", "Condition")) }),
709
+ /* @__PURE__ */ jsxRuntime.jsx(
710
+ designSystem.SingleSelect,
711
+ {
712
+ value: row.operator,
713
+ disabled: !field,
714
+ onChange: (value) => onChange({ operator: String(value) }),
715
+ children: operators.map((op) => /* @__PURE__ */ jsxRuntime.jsx(designSystem.SingleSelectOption, { value: op, children: formatMessage(operatorLabel(op)) }, op))
716
+ }
717
+ ),
718
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Error, {})
719
+ ] }) }),
720
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Grid.Item, { col: 4, s: 10, xs: 10, direction: "column", alignItems: "stretch", children: needsValue ? /* @__PURE__ */ jsxRuntime.jsx(ValueInput, { row, field, onChange, errorText }) : null }),
721
+ /* @__PURE__ */ jsxRuntime.jsx(
722
+ designSystem.Grid.Item,
723
+ {
724
+ col: 1,
725
+ s: 2,
726
+ xs: 2,
727
+ direction: "column",
728
+ alignItems: "flex-end",
729
+ justifyContent: "flex-end",
730
+ children: /* @__PURE__ */ jsxRuntime.jsx(
731
+ designSystem.IconButton,
732
+ {
733
+ label: formatMessage(msg("filters.remove", "Remove condition {number}"), position),
734
+ variant: "ghost",
735
+ onClick: onRemove,
736
+ children: /* @__PURE__ */ jsxRuntime.jsx(icons.Trash, {})
737
+ }
738
+ )
739
+ }
740
+ )
741
+ ] });
742
+ };
743
+ const ValueInput = ({ row, field, onChange, errorText }) => {
744
+ const { formatMessage } = reactIntl.useIntl();
745
+ const valueLabel = formatMessage(msg("filters.value", "Value"));
746
+ const isList = LIST_OPERATORS.includes(row.operator);
747
+ const isRange = RANGE_OPERATORS.includes(row.operator);
748
+ const type = field?.type ?? "string";
749
+ if (type === "boolean") {
750
+ return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Field.Root, { name: `value-${row.id}`, error: errorText("value"), children: [
751
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Label, { children: valueLabel }),
752
+ /* @__PURE__ */ jsxRuntime.jsxs(
753
+ designSystem.SingleSelect,
754
+ {
755
+ value: row.value,
756
+ onChange: (value) => onChange({ value: String(value) }),
757
+ children: [
758
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.SingleSelectOption, { value: "true", children: formatMessage(msg("filters.true", "true")) }),
759
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.SingleSelectOption, { value: "false", children: formatMessage(msg("filters.false", "false")) })
760
+ ]
761
+ }
762
+ ),
763
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Error, {})
764
+ ] });
765
+ }
766
+ if (type === "enumeration" && field?.enum) {
767
+ return isList ? /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Field.Root, { name: `value-${row.id}`, error: errorText("value"), children: [
768
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Label, { children: valueLabel }),
769
+ /* @__PURE__ */ jsxRuntime.jsx(
770
+ designSystem.MultiSelect,
771
+ {
772
+ withTags: true,
773
+ value: splitList(row.value),
774
+ onChange: (values) => onChange({ value: values.join(", ") }),
775
+ children: field.enum.map((option) => /* @__PURE__ */ jsxRuntime.jsx(designSystem.MultiSelectOption, { value: option, children: option }, option))
776
+ }
777
+ ),
778
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Error, {})
779
+ ] }) : /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Field.Root, { name: `value-${row.id}`, error: errorText("value"), children: [
780
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Label, { children: valueLabel }),
781
+ /* @__PURE__ */ jsxRuntime.jsx(
782
+ designSystem.SingleSelect,
783
+ {
784
+ value: row.value,
785
+ onChange: (value) => onChange({ value: String(value) }),
786
+ children: field.enum.map((option) => /* @__PURE__ */ jsxRuntime.jsx(designSystem.SingleSelectOption, { value: option, children: option }, option))
787
+ }
788
+ ),
789
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Error, {})
790
+ ] });
791
+ }
792
+ const inputType = isList ? "text" : INPUT_TYPES[type] ?? "text";
793
+ if (isRange) {
794
+ return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 2, alignItems: "flex-start", children: [
795
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Field.Root, { name: `from-${row.id}`, error: errorText("value"), flex: 1, minWidth: 0, children: [
796
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Label, { children: formatMessage(msg("filters.from", "From")) }),
797
+ /* @__PURE__ */ jsxRuntime.jsx(
798
+ designSystem.TextInput,
799
+ {
800
+ type: inputType,
801
+ value: row.value,
802
+ onChange: (event) => onChange({ value: event.target.value })
803
+ }
804
+ ),
805
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Error, {})
806
+ ] }),
807
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Field.Root, { name: `to-${row.id}`, error: errorText("valueTo"), flex: 1, minWidth: 0, children: [
808
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Label, { children: formatMessage(msg("filters.to", "To")) }),
809
+ /* @__PURE__ */ jsxRuntime.jsx(
810
+ designSystem.TextInput,
811
+ {
812
+ type: inputType,
813
+ value: row.valueTo ?? "",
814
+ onChange: (event) => onChange({ valueTo: event.target.value })
815
+ }
816
+ ),
817
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Error, {})
818
+ ] })
819
+ ] });
820
+ }
821
+ return /* @__PURE__ */ jsxRuntime.jsxs(
822
+ designSystem.Field.Root,
823
+ {
824
+ name: `value-${row.id}`,
825
+ error: errorText("value"),
826
+ hint: isList ? formatMessage(msg("filters.listHint", "Separate values with commas.")) : void 0,
827
+ children: [
828
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Label, { children: valueLabel }),
829
+ /* @__PURE__ */ jsxRuntime.jsx(
830
+ designSystem.TextInput,
831
+ {
832
+ type: inputType,
833
+ value: row.value,
834
+ onChange: (event) => onChange({ value: event.target.value })
835
+ }
836
+ ),
837
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Hint, {}),
838
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Error, {})
839
+ ]
840
+ }
841
+ );
842
+ };
843
+ const BASE = "/magic-mark";
844
+ const useBookmarksApi = () => {
845
+ const { get, post, put, del } = admin.useFetchClient();
846
+ return react.useMemo(
847
+ () => ({
848
+ list: async (params, signal) => {
849
+ const clean = Object.fromEntries(
850
+ Object.entries(params).filter(([, value]) => value !== void 0 && value !== "")
851
+ );
852
+ const { data } = await get(`${BASE}/bookmarks`, { params: clean, signal });
853
+ return data;
854
+ },
855
+ get: async (id) => (await get(`${BASE}/bookmarks/${id}`)).data.data,
856
+ create: async (input) => (await post(`${BASE}/bookmarks`, input)).data.data,
857
+ update: async (id, input) => (await put(`${BASE}/bookmarks/${id}`, input)).data.data,
858
+ updateView: async (id, query) => (await put(`${BASE}/bookmarks/${id}/view`, { query })).data.data,
859
+ duplicate: async (id, name) => (await post(`${BASE}/bookmarks/${id}/duplicate`, name ? { name } : {})).data.data,
860
+ pin: async (id, pinned) => (await put(`${BASE}/bookmarks/${id}/pin`, { pinned })).data.data,
861
+ remove: async (id) => {
862
+ await del(`${BASE}/bookmarks/${id}`);
863
+ },
864
+ roles: async () => (await get(`${BASE}/sharing/roles`)).data.data,
865
+ users: async (q, page = 1, signal) => (await get(
866
+ `${BASE}/sharing/users`,
867
+ { params: q ? { q, page } : { page }, signal }
868
+ )).data
869
+ }),
870
+ [get, post, put, del]
871
+ );
872
+ };
873
+ const QS_PARSE_OPTIONS = {
874
+ allowPrototypes: false,
875
+ plainObjects: true,
876
+ depth: 8,
877
+ parameterLimit: 500,
878
+ arrayLimit: 100
879
+ };
880
+ const parseQuery = (query) => {
881
+ if (!query) return {};
882
+ return qs__default.default.parse(query.startsWith("?") ? query.slice(1) : query, QS_PARSE_OPTIONS);
883
+ };
884
+ const stringifyQuery = (query) => qs__default.default.stringify(query, { encodeValuesOnly: true });
885
+ const bookmarkLocation = (bookmark) => {
886
+ const location = parseListViewPath(bookmark.path);
887
+ if (!location) return null;
888
+ return { pathname: location.path, search: bookmark.query ? `?${bookmark.query}` : "" };
889
+ };
890
+ const useOpenBookmark = () => {
891
+ const navigate = reactRouterDom.useNavigate();
892
+ const { toggleNotification } = admin.useNotification();
893
+ const { formatMessage } = reactIntl.useIntl();
894
+ return react.useCallback(
895
+ (bookmark) => {
896
+ const target = bookmarkLocation(bookmark);
897
+ const location = parseListViewPath(bookmark.path);
898
+ if (!target || !location) {
899
+ toggleNotification({
900
+ type: "danger",
901
+ message: formatMessage(
902
+ msg("notification.invalidPath", "This bookmark does not point to a list view.")
903
+ )
904
+ });
905
+ return;
906
+ }
907
+ try {
908
+ syncPersistedListSettings(window.localStorage, location.uid, parseQuery(bookmark.query));
909
+ } catch {
910
+ }
911
+ navigate(target);
912
+ },
913
+ [navigate, toggleNotification, formatMessage]
914
+ );
915
+ };
916
+ const errorBody = (error) => error?.response?.data?.error;
917
+ const fieldErrors = (error) => {
918
+ const fields = errorBody(error)?.details?.fieldErrors ?? {};
919
+ return Object.fromEntries(
920
+ Object.entries(fields).filter(([, messages]) => Array.isArray(messages) && messages.length).map(([field, messages]) => [field, messages[0]])
921
+ );
922
+ };
923
+ const ICON_OPTIONS = [
924
+ { key: "bookmark", Icon: icons.Book },
925
+ { key: "star", Icon: icons.Star },
926
+ { key: "heart", Icon: icons.Heart },
927
+ { key: "bolt", Icon: icons.Lightning },
928
+ { key: "rocket", Icon: icons.Rocket },
929
+ { key: "sparkles", Icon: icons.Sparkle },
930
+ { key: "pencil", Icon: icons.Pencil },
931
+ { key: "document", Icon: icons.File },
932
+ { key: "folder", Icon: icons.Folder },
933
+ { key: "photo", Icon: icons.Image },
934
+ { key: "link", Icon: icons.Link },
935
+ { key: "tag", Icon: icons.PriceTag },
936
+ { key: "filter", Icon: icons.Filter },
937
+ { key: "search", Icon: icons.Search },
938
+ { key: "calendar", Icon: icons.Calendar },
939
+ { key: "clock", Icon: icons.Clock },
940
+ { key: "bell", Icon: icons.Bell },
941
+ { key: "check", Icon: icons.CheckCircle },
942
+ { key: "mail", Icon: icons.Mail },
943
+ { key: "user", Icon: icons.User },
944
+ { key: "briefcase", Icon: icons.Briefcase },
945
+ { key: "gift", Icon: icons.Gift },
946
+ { key: "globe", Icon: icons.Globe },
947
+ { key: "home", Icon: icons.House },
948
+ { key: "flag", Icon: icons.Feather },
949
+ { key: "fire", Icon: icons.TrendUp },
950
+ { key: "cube", Icon: icons.Stack },
951
+ { key: "cog", Icon: icons.Cog },
952
+ { key: "wrench", Icon: icons.PuzzlePiece },
953
+ { key: "terminal", Icon: icons.Code },
954
+ { key: "chart", Icon: icons.ChartPie }
955
+ ];
956
+ const ALIASES = { book: "bookmark", users: "user" };
957
+ const BY_KEY = new Map(ICON_OPTIONS.map((option) => [option.key, option.Icon]));
958
+ const getIcon = (key) => BY_KEY.get(ALIASES[key ?? ""] ?? key ?? "") ?? icons.Book;
959
+ const ICON_LABELS = {
960
+ bookmark: msg("icons.bookmark", "Book"),
961
+ star: msg("icons.star", "Star"),
962
+ heart: msg("icons.heart", "Heart"),
963
+ bolt: msg("icons.bolt", "Lightning"),
964
+ rocket: msg("icons.rocket", "Rocket"),
965
+ sparkles: msg("icons.sparkles", "Sparkle"),
966
+ pencil: msg("icons.pencil", "Pencil"),
967
+ document: msg("icons.document", "Document"),
968
+ folder: msg("icons.folder", "Folder"),
969
+ photo: msg("icons.photo", "Image"),
970
+ link: msg("icons.link", "Link"),
971
+ tag: msg("icons.tag", "Tag"),
972
+ filter: msg("icons.filter", "Filter"),
973
+ search: msg("icons.search", "Search"),
974
+ calendar: msg("icons.calendar", "Calendar"),
975
+ clock: msg("icons.clock", "Clock"),
976
+ bell: msg("icons.bell", "Bell"),
977
+ check: msg("icons.check", "Check mark"),
978
+ mail: msg("icons.mail", "Mail"),
979
+ user: msg("icons.user", "Person"),
980
+ briefcase: msg("icons.briefcase", "Briefcase"),
981
+ gift: msg("icons.gift", "Gift"),
982
+ globe: msg("icons.globe", "Globe"),
983
+ home: msg("icons.home", "House"),
984
+ flag: msg("icons.flag", "Feather"),
985
+ fire: msg("icons.fire", "Trend"),
986
+ cube: msg("icons.cube", "Stack"),
987
+ cog: msg("icons.cog", "Gear"),
988
+ wrench: msg("icons.wrench", "Puzzle piece"),
989
+ terminal: msg("icons.terminal", "Code"),
990
+ chart: msg("icons.chart", "Chart")
991
+ };
992
+ const FilterSummary = ({ contentType, query }) => {
993
+ const { formatMessage } = reactIntl.useIntl();
994
+ const { fields } = useFilterFields(contentType);
995
+ const parsed = parseQuery(query);
996
+ const state = parseFilters(parsed.filters);
997
+ const labels = new Map(fields.map((field) => [field.path, field.label]));
998
+ const tags = state.rows.map((row) => {
999
+ const field = labels.get(row.field) ?? row.field;
1000
+ const op = formatMessage(operatorLabel(row.operator));
1001
+ if (NO_VALUE_OPERATORS.includes(row.operator)) return `${field} ${op}`;
1002
+ if (RANGE_OPERATORS.includes(row.operator)) {
1003
+ return formatMessage(msg("summary.range", "{field} {operator} {from} and {to}"), {
1004
+ field,
1005
+ operator: op,
1006
+ from: row.value,
1007
+ to: row.valueTo ?? ""
1008
+ });
1009
+ }
1010
+ return `${field} ${op} ${row.value}`;
1011
+ });
1012
+ const sort = typeof parsed.sort === "string" ? parsed.sort.split(":") : null;
1013
+ const locale = parsed.plugins?.i18n?.locale;
1014
+ return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "stretch", gap: 2, children: [
1015
+ tags.length === 0 && !state.unsupported ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral600", children: formatMessage(msg("summary.noFilters", "No filters. The bookmark opens the full list.")) }) : null,
1016
+ tags.length > 0 ? /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 2, wrap: "wrap", children: [
1017
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral600", children: formatMessage(
1018
+ state.match === "any" ? msg("summary.matchAny", "Any of") : msg("summary.matchAll", "All of")
1019
+ ) }),
1020
+ tags.map((label, index2) => /* @__PURE__ */ jsxRuntime.jsx(
1021
+ designSystem.Box,
1022
+ {
1023
+ background: "primary100",
1024
+ borderColor: "primary200",
1025
+ hasRadius: true,
1026
+ paddingLeft: 2,
1027
+ paddingRight: 2,
1028
+ paddingTop: 1,
1029
+ paddingBottom: 1,
1030
+ minWidth: 0,
1031
+ children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", fontWeight: "bold", textColor: "primary600", children: label })
1032
+ },
1033
+ `${index2}-${label}`
1034
+ ))
1035
+ ] }) : null,
1036
+ state.unsupported ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral600", children: formatMessage(msg("summary.customFilters", "Includes filters set outside the editor.")) }) : null,
1037
+ sort || locale ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral600", children: [
1038
+ sort ? formatMessage(msg("summary.sort", "Sorted by {field}, {direction}"), {
1039
+ field: labels.get(sort[0]) ?? sort[0],
1040
+ direction: formatMessage(
1041
+ sort[1]?.toUpperCase() === "DESC" ? msg("summary.descending", "descending") : msg("summary.ascending", "ascending")
1042
+ )
1043
+ }) : null,
1044
+ locale ? formatMessage(msg("summary.locale", "Locale: {locale}"), { locale }) : null
1045
+ ].filter(Boolean).join(" · ") }) : null
1046
+ ] });
1047
+ };
1048
+ const SharingFields = ({ value, onChange, error }) => {
1049
+ const { formatMessage } = reactIntl.useIntl();
1050
+ const api = useBookmarksApi();
1051
+ const [roles, setRoles] = react.useState([]);
1052
+ const [rolesLoading, setRolesLoading] = react.useState(true);
1053
+ const [search, setSearch] = react.useState("");
1054
+ const [results, setResults] = react.useState([]);
1055
+ const [usersLoading, setUsersLoading] = react.useState(false);
1056
+ const [loadError, setLoadError] = react.useState(false);
1057
+ const timer = react.useRef(null);
1058
+ react.useEffect(() => {
1059
+ let active = true;
1060
+ api.roles().then((data) => active && setRoles(data)).catch(() => active && setLoadError(true)).finally(() => active && setRolesLoading(false));
1061
+ return () => {
1062
+ active = false;
1063
+ };
1064
+ }, [api]);
1065
+ react.useEffect(() => {
1066
+ if (value.visibility !== "shared") return void 0;
1067
+ const controller = new AbortController();
1068
+ if (timer.current) clearTimeout(timer.current);
1069
+ timer.current = setTimeout(() => {
1070
+ setUsersLoading(true);
1071
+ api.users(search.trim(), 1, controller.signal).then(({ data }) => setResults(data)).catch(() => {
1072
+ if (!controller.signal.aborted) setLoadError(true);
1073
+ }).finally(() => !controller.signal.aborted && setUsersLoading(false));
1074
+ }, 250);
1075
+ return () => {
1076
+ controller.abort();
1077
+ if (timer.current) clearTimeout(timer.current);
1078
+ };
1079
+ }, [api, search, value.visibility]);
1080
+ const userLabel = (user) => [
1081
+ user.name ?? formatMessage(msg("sharing.unnamedUser", "Unnamed user")),
1082
+ user.email ? `(${user.email})` : ""
1083
+ ].filter(Boolean).join(" ");
1084
+ const selectedIds = new Set(value.users.map((user) => user.documentId));
1085
+ const options = results.filter((user) => !selectedIds.has(user.documentId));
1086
+ return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "stretch", gap: 4, children: [
1087
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Field.Root, { name: "visibility", children: [
1088
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Label, { children: formatMessage(msg("form.visibility", "Who can see it")) }),
1089
+ /* @__PURE__ */ jsxRuntime.jsxs(
1090
+ designSystem.Radio.Group,
1091
+ {
1092
+ value: value.visibility,
1093
+ onValueChange: (next) => onChange({ ...value, visibility: next }),
1094
+ "aria-label": formatMessage(msg("form.visibility", "Who can see it")),
1095
+ children: [
1096
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Radio.Item, { value: "private", children: formatMessage(msg("visibility.private", "Only me")) }),
1097
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Radio.Item, { value: "shared", children: formatMessage(msg("visibility.sharedOption", "Specific roles and users")) }),
1098
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Radio.Item, { value: "public", children: formatMessage(msg("visibility.publicOption", "All admin users")) })
1099
+ ]
1100
+ }
1101
+ )
1102
+ ] }),
1103
+ value.visibility === "shared" ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { background: "neutral100", hasRadius: true, padding: 4, children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "stretch", gap: 4, children: [
1104
+ loadError ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "danger600", children: formatMessage(
1105
+ msg(
1106
+ "sharing.loadError",
1107
+ "Roles and users could not be loaded. Close the dialog and try again."
1108
+ )
1109
+ ) }) : null,
1110
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Field.Root, { name: "roles", error, children: [
1111
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Label, { children: formatMessage(msg("form.roles", "Roles")) }),
1112
+ /* @__PURE__ */ jsxRuntime.jsx(
1113
+ designSystem.MultiSelect,
1114
+ {
1115
+ loading: rolesLoading,
1116
+ value: value.roles,
1117
+ onChange: (next) => onChange({ ...value, roles: next }),
1118
+ placeholder: formatMessage(msg("form.rolesPlaceholder", "Choose roles")),
1119
+ children: roles.map((role) => /* @__PURE__ */ jsxRuntime.jsx(designSystem.MultiSelectOption, { value: role.documentId, children: role.name }, role.documentId))
1120
+ }
1121
+ ),
1122
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Error, {})
1123
+ ] }),
1124
+ /* @__PURE__ */ jsxRuntime.jsxs(
1125
+ designSystem.Field.Root,
1126
+ {
1127
+ name: "users",
1128
+ hint: formatMessage(msg("form.usersHint", "Type a name to search admin users.")),
1129
+ children: [
1130
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Label, { children: formatMessage(msg("form.users", "Users")) }),
1131
+ /* @__PURE__ */ jsxRuntime.jsx(
1132
+ designSystem.Combobox,
1133
+ {
1134
+ value: "",
1135
+ textValue: search,
1136
+ onTextValueChange: setSearch,
1137
+ loading: usersLoading,
1138
+ loadingMessage: formatMessage(msg("sharing.searching", "Searching users")),
1139
+ noOptionsMessage: () => formatMessage(msg("sharing.noUsers", "No matching users")),
1140
+ placeholder: formatMessage(msg("form.usersPlaceholder", "Search users")),
1141
+ onChange: (id) => {
1142
+ const user = options.find((option) => option.documentId === id);
1143
+ if (user) onChange({ ...value, users: [...value.users, user] });
1144
+ setSearch("");
1145
+ },
1146
+ children: options.map((user) => /* @__PURE__ */ jsxRuntime.jsx(designSystem.ComboboxOption, { value: user.documentId, children: userLabel(user) }, user.documentId))
1147
+ }
1148
+ ),
1149
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Hint, {})
1150
+ ]
1151
+ }
1152
+ ),
1153
+ value.users.length ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Flex, { gap: 2, wrap: "wrap", children: value.users.map((user) => /* @__PURE__ */ jsxRuntime.jsx(
1154
+ designSystem.Tag,
1155
+ {
1156
+ icon: /* @__PURE__ */ jsxRuntime.jsx(icons.Cross, {}),
1157
+ label: formatMessage(msg("sharing.removeUser", "Remove {name}"), {
1158
+ name: userLabel(user)
1159
+ }),
1160
+ onClick: () => onChange({
1161
+ ...value,
1162
+ users: value.users.filter((u) => u.documentId !== user.documentId)
1163
+ }),
1164
+ children: userLabel(user)
1165
+ },
1166
+ user.documentId
1167
+ )) }) : null
1168
+ ] }) }) : null
1169
+ ] });
1170
+ };
1171
+ const NAME_MAX = 100;
1172
+ const snapshot = (name, description, icon, sharing) => JSON.stringify([
1173
+ name,
1174
+ description,
1175
+ icon,
1176
+ sharing.visibility,
1177
+ [...sharing.roles].sort(),
1178
+ sharing.users.map((user) => user.documentId).sort()
1179
+ ]);
1180
+ const DESCRIPTION_MAX = 500;
1181
+ const BookmarkFormModal = ({
1182
+ open,
1183
+ onOpenChange,
1184
+ view,
1185
+ bookmarkId,
1186
+ canShare,
1187
+ onSaved
1188
+ }) => {
1189
+ const { formatMessage } = reactIntl.useIntl();
1190
+ const { toggleNotification } = admin.useNotification();
1191
+ const api = useBookmarksApi();
1192
+ const { names } = useContentTypeNames();
1193
+ const isEdit = !!bookmarkId;
1194
+ const [name, setName] = react.useState("");
1195
+ const [description, setDescription] = react.useState("");
1196
+ const [icon, setIcon] = react.useState("bookmark");
1197
+ const [sharing, setSharing] = react.useState({
1198
+ visibility: "private",
1199
+ roles: [],
1200
+ users: []
1201
+ });
1202
+ const [loaded, setLoaded] = react.useState(null);
1203
+ const [loading, setLoading] = react.useState(!!bookmarkId);
1204
+ const [loadFailed, setLoadFailed] = react.useState(false);
1205
+ const [saving, setSaving] = react.useState(false);
1206
+ const [errors, setErrors] = react.useState({});
1207
+ const [queryRejected, setQueryRejected] = react.useState(false);
1208
+ const [initial, setInitial] = react.useState(
1209
+ () => snapshot("", "", "bookmark", { visibility: "private", roles: [], users: [] })
1210
+ );
1211
+ const [confirmDiscard, setConfirmDiscard] = react.useState(false);
1212
+ react.useEffect(() => {
1213
+ if (!bookmarkId) return void 0;
1214
+ let active = true;
1215
+ api.get(bookmarkId).then((bookmark) => {
1216
+ if (!active) return;
1217
+ const loadedSharing = {
1218
+ visibility: bookmark.visibility,
1219
+ roles: bookmark.sharing?.roles.map((role) => role.documentId) ?? [],
1220
+ users: bookmark.sharing?.users ?? []
1221
+ };
1222
+ setLoaded(bookmark);
1223
+ setName(bookmark.name);
1224
+ setDescription(bookmark.description ?? "");
1225
+ setIcon(bookmark.icon);
1226
+ setSharing(loadedSharing);
1227
+ setInitial(
1228
+ snapshot(bookmark.name, bookmark.description ?? "", bookmark.icon, loadedSharing)
1229
+ );
1230
+ }).catch(() => active && setLoadFailed(true)).finally(() => active && setLoading(false));
1231
+ return () => {
1232
+ active = false;
1233
+ };
1234
+ }, [bookmarkId, api]);
1235
+ const validate = () => {
1236
+ const next = {};
1237
+ if (!name.trim()) next.name = formatMessage(msg("form.nameRequired", "Enter a name."));
1238
+ else if (name.trim().length > NAME_MAX) {
1239
+ next.name = formatMessage(msg("form.nameTooLong", "Use at most {max} characters."), {
1240
+ max: NAME_MAX
1241
+ });
1242
+ }
1243
+ if (description.length > DESCRIPTION_MAX) {
1244
+ next.description = formatMessage(
1245
+ msg("form.descriptionTooLong", "Use at most {max} characters."),
1246
+ {
1247
+ max: DESCRIPTION_MAX
1248
+ }
1249
+ );
1250
+ }
1251
+ if (canShare && sharing.visibility === "shared" && !sharing.roles.length && !sharing.users.length) {
1252
+ next.roles = formatMessage(msg("form.targetsRequired", "Choose at least one role or user."));
1253
+ }
1254
+ setErrors(next);
1255
+ return Object.keys(next).length === 0;
1256
+ };
1257
+ const submit = async () => {
1258
+ if (!validate()) return;
1259
+ setSaving(true);
1260
+ const sharingInput = canShare ? {
1261
+ visibility: sharing.visibility,
1262
+ roles: sharing.visibility === "shared" ? sharing.roles : [],
1263
+ users: sharing.visibility === "shared" ? sharing.users.map((u) => u.documentId) : []
1264
+ } : {};
1265
+ try {
1266
+ const saved = isEdit ? await api.update(bookmarkId, {
1267
+ name: name.trim(),
1268
+ description: description.trim(),
1269
+ icon,
1270
+ ...sharingInput
1271
+ }) : await api.create({
1272
+ name: name.trim(),
1273
+ description: description.trim(),
1274
+ icon,
1275
+ path: view?.path,
1276
+ query: view?.query ?? "",
1277
+ ...sharingInput
1278
+ });
1279
+ toggleNotification({
1280
+ type: "success",
1281
+ message: formatMessage(
1282
+ isEdit ? msg("notification.updated", "Bookmark saved.") : msg("notification.created", "Bookmark created.")
1283
+ )
1284
+ });
1285
+ onSaved(saved);
1286
+ onOpenChange(false);
1287
+ } catch (error) {
1288
+ const fields = fieldErrors(error);
1289
+ setQueryRejected(!!fields.query);
1290
+ if (Object.keys(fields).length) {
1291
+ setErrors({
1292
+ ...fields.name ? { name: formatMessage(msg("form.nameInvalid", "Check the name.")) } : {},
1293
+ ...fields.roles || fields.users ? {
1294
+ roles: formatMessage(
1295
+ msg("form.targetsInvalid", "One of the roles or users no longer exists.")
1296
+ )
1297
+ } : {}
1298
+ });
1299
+ }
1300
+ if (fields.query) return;
1301
+ toggleNotification({
1302
+ type: "danger",
1303
+ message: formatMessage(
1304
+ msg(
1305
+ "notification.saveError",
1306
+ "The bookmark could not be saved. Your changes are still in the form."
1307
+ )
1308
+ )
1309
+ });
1310
+ } finally {
1311
+ setSaving(false);
1312
+ }
1313
+ };
1314
+ const isDirty = !loading && !loadFailed && snapshot(name, description, icon, sharing) !== initial;
1315
+ const handleOpenChange = (next) => {
1316
+ if (!next && isDirty && !saving) {
1317
+ setConfirmDiscard(true);
1318
+ return;
1319
+ }
1320
+ onOpenChange(next);
1321
+ };
1322
+ const title = isEdit ? formatMessage(msg("form.editTitle", "Edit bookmark")) : formatMessage(msg("form.createTitle", "Save view as bookmark"));
1323
+ const contentType = view?.contentType ?? loaded?.contentType ?? null;
1324
+ const query = view?.query ?? loaded?.query ?? "";
1325
+ return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1326
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Root, { open, onOpenChange: handleOpenChange, children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Modal.Content, { onKeyDown: keepFocusInside, children: [
1327
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Header, { closeLabel: formatMessage(msg("form.close", "Close")), children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Title, { children: title }) }),
1328
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Body, { children: loading ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Flex, { justifyContent: "center", padding: 6, children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Loader, { small: true, children: formatMessage(msg("state.loading", "Loading")) }) }) : loadFailed ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { textColor: "danger600", children: formatMessage(msg("form.loadError", "The bookmark could not be loaded.")) }) : /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "stretch", gap: 6, children: [
1329
+ queryRejected ? /* @__PURE__ */ jsxRuntime.jsx(
1330
+ designSystem.Alert,
1331
+ {
1332
+ variant: "danger",
1333
+ closeLabel: formatMessage(msg("form.close", "Close")),
1334
+ onClose: () => setQueryRejected(false),
1335
+ children: formatMessage(
1336
+ msg(
1337
+ "form.queryTooLong",
1338
+ "This view cannot be saved: the search text or a filter value is too long. Shorten it in the list and try again."
1339
+ )
1340
+ )
1341
+ }
1342
+ ) : null,
1343
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { background: "neutral100", hasRadius: true, padding: 4, children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "stretch", gap: 2, children: [
1344
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", textColor: "neutral600", tag: "h3", children: formatMessage(msg("form.savedView", "Saved view")) }),
1345
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { fontWeight: "semiBold", children: view?.contentTypeName ?? (contentType ? names.get(contentType) ?? contentType : "") }),
1346
+ /* @__PURE__ */ jsxRuntime.jsx(FilterSummary, { contentType, query })
1347
+ ] }) }),
1348
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Field.Root, { name: "name", error: errors.name, required: true, children: [
1349
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Label, { children: formatMessage(msg("form.name", "Name")) }),
1350
+ /* @__PURE__ */ jsxRuntime.jsx(
1351
+ designSystem.TextInput,
1352
+ {
1353
+ value: name,
1354
+ maxLength: NAME_MAX,
1355
+ onChange: (event) => setName(event.target.value),
1356
+ placeholder: formatMessage(
1357
+ msg("form.namePlaceholder", "e.g. Drafts waiting for review")
1358
+ )
1359
+ }
1360
+ ),
1361
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Error, {})
1362
+ ] }),
1363
+ /* @__PURE__ */ jsxRuntime.jsxs(
1364
+ designSystem.Field.Root,
1365
+ {
1366
+ name: "description",
1367
+ error: errors.description,
1368
+ hint: formatMessage(
1369
+ msg("form.descriptionHint", "Optional. Shown below the name.")
1370
+ ),
1371
+ children: [
1372
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Label, { children: formatMessage(msg("form.description", "Description")) }),
1373
+ /* @__PURE__ */ jsxRuntime.jsx(
1374
+ designSystem.Textarea,
1375
+ {
1376
+ value: description,
1377
+ onChange: (event) => setDescription(event.target.value)
1378
+ }
1379
+ ),
1380
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Hint, {}),
1381
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Error, {})
1382
+ ]
1383
+ }
1384
+ ),
1385
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Field.Root, { name: "icon", children: [
1386
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Label, { children: formatMessage(msg("form.icon", "Icon")) }),
1387
+ /* @__PURE__ */ jsxRuntime.jsx(
1388
+ designSystem.SingleSelect,
1389
+ {
1390
+ value: icon,
1391
+ onChange: (value) => setIcon(String(value)),
1392
+ children: ICON_OPTIONS.map(({ key, Icon }) => /* @__PURE__ */ jsxRuntime.jsx(designSystem.SingleSelectOption, { value: key, startIcon: /* @__PURE__ */ jsxRuntime.jsx(Icon, { "aria-hidden": true }), children: formatMessage(ICON_LABELS[key]) }, key))
1393
+ }
1394
+ )
1395
+ ] }),
1396
+ canShare ? /* @__PURE__ */ jsxRuntime.jsx(SharingFields, { value: sharing, onChange: setSharing, error: errors.roles }) : null
1397
+ ] }) }),
1398
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Modal.Footer, { children: [
1399
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Close, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Button, { variant: "tertiary", children: formatMessage(msg("form.cancel", "Cancel")) }) }),
1400
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Button, { onClick: submit, loading: saving, disabled: loading || loadFailed, children: formatMessage(msg("form.save", "Save")) })
1401
+ ] })
1402
+ ] }) }),
1403
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Dialog.Root, { open: confirmDiscard, onOpenChange: setConfirmDiscard, children: /* @__PURE__ */ jsxRuntime.jsx(
1404
+ admin.ConfirmDialog,
1405
+ {
1406
+ variant: "danger",
1407
+ onConfirm: () => {
1408
+ setConfirmDiscard(false);
1409
+ onOpenChange(false);
1410
+ },
1411
+ children: formatMessage(
1412
+ msg(
1413
+ "form.discardBody",
1414
+ "Close without saving? Your changes to this bookmark will be lost."
1415
+ )
1416
+ )
1417
+ }
1418
+ ) })
1419
+ ] });
1420
+ };
1421
+ const POPOVER_LIMIT = 100;
1422
+ const sortBookmarks = (list) => [...list].sort((a, b) => Number(b.isPinned) - Number(a.isPinned) || a.name.localeCompare(b.name));
1423
+ const BookmarksPopover = ({
1424
+ listView,
1425
+ canCreate,
1426
+ canUpdate,
1427
+ canShare
1428
+ }) => {
1429
+ const { formatMessage } = reactIntl.useIntl();
1430
+ const { toggleNotification } = admin.useNotification();
1431
+ const api = useBookmarksApi();
1432
+ const openBookmark = useOpenBookmark();
1433
+ const [{ query }] = admin.useQueryParams();
1434
+ const { names } = useContentTypeNames();
1435
+ const [open, setOpen] = react.useState(false);
1436
+ const [items, setItems] = react.useState([]);
1437
+ const [total, setTotal] = react.useState(0);
1438
+ const [status, setStatus] = react.useState("idle");
1439
+ const [busyId, setBusyId] = react.useState(null);
1440
+ const [captured, setCaptured] = react.useState(null);
1441
+ const load = react.useCallback(async () => {
1442
+ setStatus("loading");
1443
+ try {
1444
+ const base = {
1445
+ contentType: listView.uid,
1446
+ pageSize: POPOVER_LIMIT,
1447
+ sort: "name:asc"
1448
+ };
1449
+ const [pinned, all] = await Promise.all([
1450
+ api.list({ ...base, scope: "pinned" }),
1451
+ api.list(base)
1452
+ ]);
1453
+ const pinnedIds = new Set(pinned.data.map((b) => b.documentId));
1454
+ const rest = all.data.filter((b) => !pinnedIds.has(b.documentId));
1455
+ setItems(sortBookmarks([...pinned.data, ...rest]).slice(0, POPOVER_LIMIT));
1456
+ setTotal(all.meta.pagination.total);
1457
+ setStatus("ready");
1458
+ } catch {
1459
+ setStatus("error");
1460
+ }
1461
+ }, [api, listView.uid]);
1462
+ const handleOpenChange = (next) => {
1463
+ setOpen(next);
1464
+ if (next) load();
1465
+ };
1466
+ const currentQuery = stringifyQuery(pickSavedQuery(query));
1467
+ const contentTypeName = names.get(listView.uid) ?? listView.uid;
1468
+ const saveView = () => {
1469
+ setOpen(false);
1470
+ setCaptured({
1471
+ path: listView.path,
1472
+ query: currentQuery,
1473
+ contentType: listView.uid,
1474
+ contentTypeName
1475
+ });
1476
+ };
1477
+ const togglePin = async (bookmark) => {
1478
+ setBusyId(bookmark.documentId);
1479
+ try {
1480
+ await api.pin(bookmark.documentId, !bookmark.isPinned);
1481
+ setItems(
1482
+ (prev) => sortBookmarks(
1483
+ prev.map(
1484
+ (b) => b.documentId === bookmark.documentId ? { ...b, isPinned: !b.isPinned } : b
1485
+ )
1486
+ )
1487
+ );
1488
+ } catch {
1489
+ toggleNotification({
1490
+ type: "danger",
1491
+ message: formatMessage(msg("notification.pinError", "The bookmark could not be pinned."))
1492
+ });
1493
+ } finally {
1494
+ setBusyId(null);
1495
+ }
1496
+ };
1497
+ const updateView = async (bookmark) => {
1498
+ setBusyId(bookmark.documentId);
1499
+ try {
1500
+ const updated = await api.updateView(bookmark.documentId, currentQuery);
1501
+ setItems(
1502
+ (prev) => prev.map((b) => b.documentId === updated.documentId ? { ...b, ...updated } : b)
1503
+ );
1504
+ toggleNotification({
1505
+ type: "success",
1506
+ message: formatMessage(
1507
+ msg("notification.viewUpdated", '"{name}" now saves the current view.'),
1508
+ {
1509
+ name: bookmark.name
1510
+ }
1511
+ )
1512
+ });
1513
+ } catch (error) {
1514
+ toggleNotification({
1515
+ type: "danger",
1516
+ message: formatMessage(
1517
+ fieldErrors(error).query ? msg(
1518
+ "form.queryTooLong",
1519
+ "This view cannot be saved: the search text or a filter value is too long. Shorten it in the list and try again."
1520
+ ) : msg("notification.viewUpdateError", "The bookmark could not be updated.")
1521
+ )
1522
+ });
1523
+ } finally {
1524
+ setBusyId(null);
1525
+ }
1526
+ };
1527
+ return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1528
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Popover.Root, { open, onOpenChange: handleOpenChange, children: [
1529
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Popover.Trigger, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.IconButton, { label: formatMessage(msg("popover.trigger", "Bookmarks")), children: /* @__PURE__ */ jsxRuntime.jsx(icons.Star, {}) }) }),
1530
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Popover.Content, { side: "bottom", align: "end", sideOffset: 4, children: /* @__PURE__ */ jsxRuntime.jsx(
1531
+ designSystem.Box,
1532
+ {
1533
+ width: "32rem",
1534
+ maxWidth: "calc(100vw - 32px)",
1535
+ maxHeight: "var(--radix-popover-content-available-height)",
1536
+ overflow: "auto",
1537
+ padding: 3,
1538
+ children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "stretch", gap: 3, children: [
1539
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { justifyContent: "space-between", gap: 2, children: [
1540
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", textColor: "neutral600", tag: "h2", children: formatMessage(msg("popover.title", "Bookmarks for {name}"), {
1541
+ name: contentTypeName
1542
+ }) }),
1543
+ canCreate ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Button, { size: "S", variant: "secondary", startIcon: /* @__PURE__ */ jsxRuntime.jsx(icons.Plus, {}), onClick: saveView, children: formatMessage(msg("popover.save", "Save view")) }) : null
1544
+ ] }),
1545
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Divider, {}),
1546
+ status === "loading" ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Flex, { justifyContent: "center", padding: 4, children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Loader, { small: true, children: formatMessage(msg("state.loading", "Loading")) }) }) : null,
1547
+ status === "error" ? /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "flex-start", gap: 2, children: [
1548
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "danger600", children: formatMessage(msg("popover.error", "Bookmarks could not be loaded.")) }),
1549
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.TextButton, { startIcon: /* @__PURE__ */ jsxRuntime.jsx(icons.ArrowClockwise, {}), onClick: load, children: formatMessage(msg("state.retry", "Try again")) })
1550
+ ] }) : null,
1551
+ status === "ready" && items.length === 0 ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral600", children: canCreate ? formatMessage(
1552
+ msg(
1553
+ "popover.empty",
1554
+ "No bookmarks for this content type yet. Filter the list, then choose Save view."
1555
+ )
1556
+ ) : formatMessage(
1557
+ msg("popover.emptyReadOnly", "No bookmarks for this content type yet.")
1558
+ ) }) : null,
1559
+ status === "ready" && items.length > 0 ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { maxHeight: "40rem", overflow: "auto", children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Flex, { direction: "column", alignItems: "stretch", gap: 1, tag: "ul", children: items.map((bookmark) => {
1560
+ const Icon = getIcon(bookmark.icon);
1561
+ const target = bookmarkLocation(bookmark);
1562
+ const isCurrent = bookmark.query === currentQuery;
1563
+ return /* @__PURE__ */ jsxRuntime.jsxs(
1564
+ designSystem.Flex,
1565
+ {
1566
+ tag: "li",
1567
+ gap: 2,
1568
+ alignItems: "center",
1569
+ paddingTop: 1,
1570
+ paddingBottom: 1,
1571
+ children: [
1572
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 2, alignItems: "flex-start", flex: 1, minWidth: 0, children: [
1573
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { paddingTop: 1, color: "neutral600", children: /* @__PURE__ */ jsxRuntime.jsx(Icon, { "aria-hidden": true }) }),
1574
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "flex-start", minWidth: 0, children: [
1575
+ target ? /* @__PURE__ */ jsxRuntime.jsx(
1576
+ designSystem.Link,
1577
+ {
1578
+ tag: reactRouterDom.NavLink,
1579
+ to: target,
1580
+ ...LINK_TARGET,
1581
+ onClick: (event) => {
1582
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.button !== 0)
1583
+ return;
1584
+ event.preventDefault();
1585
+ setOpen(false);
1586
+ openBookmark(bookmark);
1587
+ },
1588
+ "aria-current": isCurrent ? "page" : void 0,
1589
+ children: bookmark.name
1590
+ }
1591
+ ) : /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { children: bookmark.name }),
1592
+ bookmark.description ? /* @__PURE__ */ jsxRuntime.jsx(
1593
+ designSystem.Typography,
1594
+ {
1595
+ variant: "pi",
1596
+ textColor: "neutral600",
1597
+ ellipsis: true,
1598
+ title: bookmark.description,
1599
+ children: bookmark.description
1600
+ }
1601
+ ) : null
1602
+ ] })
1603
+ ] }),
1604
+ canUpdate && bookmark.canEdit && !isCurrent ? /* @__PURE__ */ jsxRuntime.jsx(
1605
+ designSystem.IconButton,
1606
+ {
1607
+ label: formatMessage(
1608
+ msg("actions.updateViewNamed", "Save the current view in {name}"),
1609
+ {
1610
+ name: bookmark.name
1611
+ }
1612
+ ),
1613
+ variant: "ghost",
1614
+ disabled: busyId === bookmark.documentId,
1615
+ onClick: () => updateView(bookmark),
1616
+ children: /* @__PURE__ */ jsxRuntime.jsx(icons.ArrowClockwise, {})
1617
+ }
1618
+ ) : null,
1619
+ /* @__PURE__ */ jsxRuntime.jsx(
1620
+ designSystem.IconButton,
1621
+ {
1622
+ label: formatMessage(
1623
+ bookmark.isPinned ? msg("actions.unpinNamed", "Unpin {name}") : msg("actions.pinNamed", "Pin {name}"),
1624
+ { name: bookmark.name }
1625
+ ),
1626
+ variant: bookmark.isPinned ? "secondary" : "ghost",
1627
+ disabled: busyId === bookmark.documentId,
1628
+ onClick: () => togglePin(bookmark),
1629
+ "aria-pressed": bookmark.isPinned,
1630
+ children: /* @__PURE__ */ jsxRuntime.jsx(icons.Pin, {})
1631
+ }
1632
+ )
1633
+ ]
1634
+ },
1635
+ bookmark.documentId
1636
+ );
1637
+ }) }) }) : null,
1638
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Divider, {}),
1639
+ status === "ready" && total > items.length ? /* @__PURE__ */ jsxRuntime.jsx(
1640
+ designSystem.Link,
1641
+ {
1642
+ tag: reactRouterDom.NavLink,
1643
+ to: `/plugins/${pluginId}?contentType=${encodeURIComponent(listView.uid)}`,
1644
+ ...LINK_TARGET,
1645
+ onClick: () => setOpen(false),
1646
+ children: formatMessage(msg("popover.showAll", "Show all {total} bookmarks"), { total })
1647
+ }
1648
+ ) : /* @__PURE__ */ jsxRuntime.jsx(
1649
+ designSystem.Link,
1650
+ {
1651
+ tag: reactRouterDom.NavLink,
1652
+ to: `/plugins/${pluginId}`,
1653
+ onClick: () => setOpen(false),
1654
+ ...LINK_TARGET,
1655
+ children: formatMessage(msg("popover.manage", "Manage bookmarks"))
1656
+ }
1657
+ )
1658
+ ] })
1659
+ }
1660
+ ) })
1661
+ ] }),
1662
+ captured ? /* @__PURE__ */ jsxRuntime.jsx(
1663
+ BookmarkFormModal,
1664
+ {
1665
+ open: !!captured,
1666
+ onOpenChange: (next) => !next && setCaptured(null),
1667
+ view: captured,
1668
+ canShare,
1669
+ onSaved: () => setCaptured(null)
1670
+ }
1671
+ ) : null
1672
+ ] });
1673
+ };
1674
+ const ListViewActions = () => {
1675
+ const { formatMessage } = reactIntl.useIntl();
1676
+ const { pathname } = reactRouterDom.useLocation();
1677
+ const listView = parseListViewPath(pathname);
1678
+ const { allowedActions, isLoading } = admin.useRBAC(ALL_PERMISSIONS);
1679
+ const [filtersOpen, setFiltersOpen] = react.useState(false);
1680
+ if (!listView || listView.kind !== "collection-types") return null;
1681
+ return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1682
+ /* @__PURE__ */ jsxRuntime.jsx(
1683
+ designSystem.IconButton,
1684
+ {
1685
+ label: formatMessage(msg("filters.title", "Advanced filters")),
1686
+ onClick: () => setFiltersOpen(true),
1687
+ children: /* @__PURE__ */ jsxRuntime.jsx(icons.SlidersHorizontal, {})
1688
+ }
1689
+ ),
1690
+ filtersOpen ? /* @__PURE__ */ jsxRuntime.jsx(AdvancedFiltersModal, { open: filtersOpen, onOpenChange: setFiltersOpen, uid: listView.uid }) : null,
1691
+ !isLoading && allowedActions.canRead ? /* @__PURE__ */ jsxRuntime.jsx(
1692
+ BookmarksPopover,
1693
+ {
1694
+ listView,
1695
+ canCreate: !!allowedActions.canCreate,
1696
+ canUpdate: !!allowedActions.canUpdate,
1697
+ canShare: !!allowedActions.canShare
1698
+ }
1699
+ ) : null
1700
+ ] });
1701
+ };
1702
+ const PluginIcon = () => /* @__PURE__ */ jsxRuntime.jsx(icons.Book, {});
1703
+ const index = {
1704
+ register(app) {
1705
+ app.addMenuLink({
1706
+ to: `plugins/${pluginId}`,
1707
+ icon: PluginIcon,
1708
+ intlLabel: { id: `${pluginId}.plugin.name`, defaultMessage: "Magic Mark" },
1709
+ Component: () => Promise.resolve().then(() => require("./App-KJvUCwN1.js")),
1710
+ permissions: PERMISSIONS.read
1711
+ });
1712
+ app.registerPlugin({ id: pluginId, name: "Magic Mark" });
1713
+ const widgets = app.widgets;
1714
+ if (widgets && typeof widgets.register === "function") {
1715
+ widgets.register({
1716
+ id: "pinned-bookmarks",
1717
+ pluginId,
1718
+ icon: icons.Star,
1719
+ title: { id: `${pluginId}.widget.title`, defaultMessage: "Pinned bookmarks" },
1720
+ link: {
1721
+ label: { id: `${pluginId}.widget.link`, defaultMessage: "Manage bookmarks" },
1722
+ href: `/plugins/${pluginId}`
1723
+ },
1724
+ component: async () => (await Promise.resolve().then(() => require("./PinnedBookmarksWidget-DlD8lDhq.js"))).default,
1725
+ permissions: PERMISSIONS.read
1726
+ });
1727
+ }
1728
+ },
1729
+ bootstrap(app) {
1730
+ const contentManager = app.getPlugin("content-manager");
1731
+ contentManager?.injectComponent("listView", "actions", {
1732
+ name: `${pluginId}-list-view-actions`,
1733
+ Component: ListViewActions
1734
+ });
1735
+ },
1736
+ async registerTrads({ locales }) {
1737
+ return Promise.all(
1738
+ locales.map(async (locale) => {
1739
+ try {
1740
+ const { default: data } = await __variableDynamicImportRuntimeHelper(/* @__PURE__ */ Object.assign({ "./translations/de.json": () => Promise.resolve().then(() => require("./de-Cn90CcnC.js")), "./translations/en.json": () => Promise.resolve().then(() => require("./en-GDfO_EfL.js")), "./translations/es.json": () => Promise.resolve().then(() => require("./es-6o-_RABX.js")), "./translations/fr.json": () => Promise.resolve().then(() => require("./fr-BOZS5mJT.js")), "./translations/pt.json": () => Promise.resolve().then(() => require("./pt-D13SxuK2.js")) }), `./translations/${locale}.json`, 3);
1741
+ return {
1742
+ data: Object.fromEntries(
1743
+ Object.entries(data).map(([key, value]) => [
1744
+ `${pluginId}.${key}`,
1745
+ value
1746
+ ])
1747
+ ),
1748
+ locale
1749
+ };
1750
+ } catch {
1751
+ return { data: {}, locale };
1752
+ }
1753
+ })
1754
+ );
1755
+ }
1756
+ };
1757
+ exports.ALL_PERMISSIONS = ALL_PERMISSIONS;
1758
+ exports.BookmarkFormModal = BookmarkFormModal;
1759
+ exports.LINK_TARGET = LINK_TARGET;
1760
+ exports.PERMISSIONS = PERMISSIONS;
1761
+ exports.bookmarkLocation = bookmarkLocation;
1762
+ exports.countConditions = countConditions;
1763
+ exports.getIcon = getIcon;
1764
+ exports.index = index;
1765
+ exports.msg = msg;
1766
+ exports.parseQuery = parseQuery;
1767
+ exports.pluginId = pluginId;
1768
+ exports.useBookmarksApi = useBookmarksApi;
1769
+ exports.useContentTypeNames = useContentTypeNames;
1770
+ exports.useOpenBookmark = useOpenBookmark;