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