strapi-plugin-magic-mark 3.4.0 → 4.0.1

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