magic-editor-x 1.6.0 → 2.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 (97) hide show
  1. package/CHANGELOG.md +268 -0
  2. package/LICENSE +1 -7
  3. package/README.md +324 -981
  4. package/dist/admin/ConfigurationPage-B1uCIE3J.js +767 -0
  5. package/dist/admin/ConfigurationPage-DvAifELO.mjs +767 -0
  6. package/dist/admin/CustomBlocksPage-6-OQwpXQ.mjs +1741 -0
  7. package/dist/admin/CustomBlocksPage-6eWCOreU.js +1743 -0
  8. package/dist/admin/EditorField-DocyD2Q3.js +5506 -0
  9. package/dist/admin/EditorField-ThSoOCPm.mjs +5471 -0
  10. package/dist/admin/api-B-RsxJCs.js +34 -0
  11. package/dist/admin/api-C4XsDZxd.mjs +35 -0
  12. package/dist/admin/de-B8XFFhHh.js +95 -0
  13. package/dist/admin/de-BMxADn2Z.mjs +231 -0
  14. package/dist/admin/de-DBR893G4.js +13 -0
  15. package/dist/admin/de-DcDPRzV4.js +155 -0
  16. package/dist/admin/de-Dx7vUW0Z.js +231 -0
  17. package/dist/admin/de-RAxzvrwm.mjs +95 -0
  18. package/dist/admin/de-fBFh09Wl.mjs +13 -0
  19. package/dist/admin/de-n5V6c5RT.mjs +155 -0
  20. package/dist/admin/en-BQ5Pxe2o.mjs +231 -0
  21. package/dist/admin/en-BqNm3nMQ.mjs +155 -0
  22. package/dist/admin/en-BzfyifEU.mjs +95 -0
  23. package/dist/admin/en-D-DGftl0.js +155 -0
  24. package/dist/admin/en-D9Nfccux.mjs +13 -0
  25. package/dist/admin/en-DcWUTE2J.js +95 -0
  26. package/dist/admin/en-gueRT44P.js +13 -0
  27. package/dist/admin/en-sNn4z9lA.js +231 -0
  28. package/dist/admin/es-B0Zy8DVg.mjs +13 -0
  29. package/dist/admin/es-B6NYq0VH.mjs +231 -0
  30. package/dist/admin/es-BOtVc9qv.js +95 -0
  31. package/dist/admin/es-C2OJVYkV.mjs +95 -0
  32. package/dist/admin/es-DRGs7meF.js +13 -0
  33. package/dist/admin/es-DVsXnS0N.js +231 -0
  34. package/dist/admin/es-Di0pyQCh.js +155 -0
  35. package/dist/admin/es-SzeTV4q8.mjs +155 -0
  36. package/dist/admin/fr-B8rdLAIL.js +13 -0
  37. package/dist/admin/fr-Bpo5Uq1f.mjs +95 -0
  38. package/dist/admin/fr-D6F--jIB.js +155 -0
  39. package/dist/admin/fr-DfxKaOc_.js +95 -0
  40. package/dist/admin/fr-DhgPYHIH.mjs +155 -0
  41. package/dist/admin/fr-DmG3_Cn-.mjs +231 -0
  42. package/dist/admin/fr-Fwxcj4SM.js +231 -0
  43. package/dist/admin/fr-oiUb2bb_.mjs +13 -0
  44. package/dist/admin/index-CwfaB5-e.js +155 -0
  45. package/dist/admin/index-D1Q5Rlt6.mjs +156 -0
  46. package/dist/admin/index.js +1 -1
  47. package/dist/admin/index.mjs +2 -2
  48. package/dist/admin/pt-B3Jce6uT.mjs +13 -0
  49. package/dist/admin/pt-BPo0ex21.js +155 -0
  50. package/dist/admin/pt-BbdwHlWF.mjs +231 -0
  51. package/dist/admin/pt-BiWuSBcH.js +13 -0
  52. package/dist/admin/pt-BvSl1btT.mjs +155 -0
  53. package/dist/admin/pt-C6nr71Yw.js +231 -0
  54. package/dist/admin/pt-DqCXuI4S.mjs +95 -0
  55. package/dist/admin/pt-LCvjwk0y.js +95 -0
  56. package/dist/admin/sanitize-9UVcXFfc.js +552 -0
  57. package/dist/admin/sanitize-D4kfZ_ly.mjs +551 -0
  58. package/dist/admin/useT-B5M49wGH.js +130 -0
  59. package/dist/admin/useT-CjX6fL2m.mjs +131 -0
  60. package/dist/server/index.js +4150 -64739
  61. package/dist/server/index.mjs +4150 -64748
  62. package/package.json +90 -66
  63. package/strapi-admin.js +3 -0
  64. package/strapi-server.js +3 -0
  65. package/COPYRIGHT_NOTICE.txt +0 -20
  66. package/dist/admin/App-BwMEZnS-.mjs +0 -2144
  67. package/dist/admin/App-HNr2tizR.js +0 -2147
  68. package/dist/admin/CustomBlocksPage-BjcA7MGz.js +0 -1519
  69. package/dist/admin/CustomBlocksPage-COPOZ2-_.mjs +0 -1517
  70. package/dist/admin/LicensePage-D0DMTF41.mjs +0 -392
  71. package/dist/admin/LicensePage-D0_9yPkw.js +0 -394
  72. package/dist/admin/LiveCollaborationPanel-CZAbgAVr.js +0 -223
  73. package/dist/admin/LiveCollaborationPanel-D8z72afw.mjs +0 -221
  74. package/dist/admin/Settings-DRenvRcG.js +0 -441
  75. package/dist/admin/Settings-DjyNURlS.mjs +0 -439
  76. package/dist/admin/de-C_0Mj-Zo.mjs +0 -296
  77. package/dist/admin/de-DVNVpAt9.js +0 -296
  78. package/dist/admin/en-B7AAf1ie.mjs +0 -296
  79. package/dist/admin/en-C2hv5GsA.js +0 -296
  80. package/dist/admin/es-BzJqcIST.js +0 -274
  81. package/dist/admin/es-zdP8sd-f.mjs +0 -274
  82. package/dist/admin/fr-CtAgOgH1.mjs +0 -274
  83. package/dist/admin/fr-D3GwqAAJ.js +0 -274
  84. package/dist/admin/getTranslation-2OiEgVGt.mjs +0 -49459
  85. package/dist/admin/getTranslation-DQ_WJ-7M.js +0 -49475
  86. package/dist/admin/index-Bn2tfJrC.js +0 -2186
  87. package/dist/admin/index-DAtClhqy.js +0 -6956
  88. package/dist/admin/index-FVEbTfqO.mjs +0 -2187
  89. package/dist/admin/index-gjWl-6E2.mjs +0 -6934
  90. package/dist/admin/magic-editor-x.css +0 -1103
  91. package/dist/admin/pt-BmUw6YMP.mjs +0 -274
  92. package/dist/admin/pt-CFo0nTbj.js +0 -274
  93. package/dist/admin/tools-CzHTZaY_.mjs +0 -2268
  94. package/dist/admin/tools-DALFhvPO.js +0 -2299
  95. package/pics/collab-magiceditorX.png +0 -0
  96. package/pics/editorX.png +0 -0
  97. package/pics/liveCollabwidget1.png +0 -0
@@ -0,0 +1,1741 @@
1
+ import { jsx, jsxs } from "react/jsx-runtime";
2
+ import { useMemo, useState, useEffect, useRef, useCallback } from "react";
3
+ import { Box, Typography, Flex, Badge, Table, Thead, Tr, Th, VisuallyHidden, Tbody, Td, Switch, IconButton, Grid, Field, TextInput, SingleSelect, SingleSelectOption, Textarea, Checkbox, Button, Modal, Alert, Divider, MultiSelect, MultiSelectOption, EmptyStateLayout } from "@strapi/design-system";
4
+ import { Pencil, Duplicate, ArrowUp, ArrowDown, Trash, Plus, Upload, Download } from "@strapi/icons";
5
+ import { EmptyDocuments } from "@strapi/icons/symbols";
6
+ import { useFetchClient, useNotification, useRBAC, Page } from "@strapi/strapi/admin";
7
+ import { P as PERMISSIONS } from "./index-D1Q5Rlt6.mjs";
8
+ import { A as API, r as readApiError } from "./api-C4XsDZxd.mjs";
9
+ import { u as useT, C as ConfirmAction, P as PageShell, S as SectionCard, r as refocusIfLost } from "./useT-CjX6fL2m.mjs";
10
+ import styled, { useTheme } from "styled-components";
11
+ import { b as sanitizeSvg, c as sanitizeTemplate } from "./sanitize-D4kfZ_ly.mjs";
12
+ const toQuery = (breakpoint) => typeof breakpoint === "string" ? breakpoint.replace(/^\s*@media\s*/i, "").trim() : "";
13
+ const useBreakpoint = () => {
14
+ const theme = useTheme();
15
+ const queries = useMemo(
16
+ () => ({
17
+ small: toQuery(theme && theme.breakpoints && theme.breakpoints.small) || "(min-width: 520px)",
18
+ medium: toQuery(theme && theme.breakpoints && theme.breakpoints.medium) || "(min-width: 768px)",
19
+ large: toQuery(theme && theme.breakpoints && theme.breakpoints.large) || "(min-width: 1080px)"
20
+ }),
21
+ [theme]
22
+ );
23
+ const read = useMemo(
24
+ () => () => {
25
+ if (typeof window === "undefined" || typeof window.matchMedia !== "function") {
26
+ return { small: true, medium: true, large: true };
27
+ }
28
+ return Object.fromEntries(
29
+ Object.entries(queries).map(([key, query]) => [key, window.matchMedia(query).matches])
30
+ );
31
+ },
32
+ [queries]
33
+ );
34
+ const [matches, setMatches] = useState(read);
35
+ useEffect(() => {
36
+ if (typeof window === "undefined" || typeof window.matchMedia !== "function") return void 0;
37
+ const lists = Object.values(queries).map((query) => window.matchMedia(query));
38
+ const update = () => setMatches(read());
39
+ update();
40
+ lists.forEach((list) => list.addEventListener("change", update));
41
+ return () => lists.forEach((list) => list.removeEventListener("change", update));
42
+ }, [queries, read]);
43
+ return { isBelowSmall: !matches.small, isBelowMedium: !matches.medium, isBelowLarge: !matches.large };
44
+ };
45
+ const FIELD_TYPES = Object.freeze([
46
+ "text",
47
+ "textarea",
48
+ "url",
49
+ "number",
50
+ "select",
51
+ "checkbox",
52
+ "image",
53
+ "color"
54
+ ]);
55
+ const TUNES = Object.freeze(["alignmentTune", "textVariant", "indentTune"]);
56
+ const BLOCK_TYPES = Object.freeze(["simple", "embedded-entry"]);
57
+ const RESERVED_NAMES = Object.freeze(
58
+ [
59
+ "paragraph",
60
+ "header",
61
+ "list",
62
+ "checklist",
63
+ "quote",
64
+ "warning",
65
+ "code",
66
+ "codeFlask",
67
+ "delimiter",
68
+ "table",
69
+ "embed",
70
+ "raw",
71
+ "image",
72
+ "simpleImage",
73
+ "linkTool",
74
+ "attaches",
75
+ "personality",
76
+ "mediaLib",
77
+ "alert",
78
+ "toggle",
79
+ "button",
80
+ "bold",
81
+ "italic",
82
+ "marker",
83
+ "inlineCode",
84
+ "underline",
85
+ "strikethrough",
86
+ "tooltip",
87
+ "hyperlink",
88
+ "aiAssistant",
89
+ "textVariant",
90
+ "alignmentTune",
91
+ "indentTune",
92
+ "embeddedEntry"
93
+ ].map((name) => name.toLowerCase())
94
+ );
95
+ const NAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9_-]{1,49}$/;
96
+ const FIELD_NAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9_]{0,39}$/;
97
+ const SHORTCUT_PATTERN = /^(CMD|CTRL|ALT|SHIFT|OPTION)(\+(CMD|CTRL|ALT|SHIFT|OPTION|[A-Z0-9]))+$/;
98
+ let keySeed = 0;
99
+ const nextKey = () => {
100
+ keySeed += 1;
101
+ return `field-${keySeed}`;
102
+ };
103
+ const deriveName = (label) => {
104
+ const words = String(label || "").normalize("NFKD").replace(/[̀-ͯ]/g, "").replace(/[^A-Za-z0-9]+/g, " ").trim().split(" ").filter(Boolean);
105
+ if (!words.length) return "";
106
+ let name = words.map(
107
+ (word, index) => index === 0 ? word.toLowerCase() : word[0].toUpperCase() + word.slice(1).toLowerCase()
108
+ ).join("");
109
+ if (!/^[a-zA-Z]/.test(name)) name = `block${name}`;
110
+ if (name.length < 2) name = `${name}Block`;
111
+ return name.slice(0, 50);
112
+ };
113
+ const optionsToText = (options) => (Array.isArray(options) ? options : []).map(
114
+ (option) => typeof option === "string" ? option : option.label && option.label !== option.value ? `${option.value} | ${option.label}` : option.value
115
+ ).join("\n");
116
+ const textToOptions = (text) => String(text || "").split("\n").map((line) => line.trim()).filter(Boolean).map((line) => {
117
+ const index = line.indexOf("|");
118
+ if (index < 0) return line;
119
+ const value = line.slice(0, index).trim();
120
+ const label = line.slice(index + 1).trim();
121
+ return label && label !== value ? { value, label } : value;
122
+ });
123
+ const emptyValues = () => ({
124
+ name: "",
125
+ nameTouched: false,
126
+ label: "",
127
+ blockType: "simple",
128
+ description: "",
129
+ icon: "",
130
+ contentType: "",
131
+ titleField: "",
132
+ displayFields: [],
133
+ previewFields: [],
134
+ fields: [],
135
+ template: "",
136
+ placeholder: "",
137
+ inlineToolbar: true,
138
+ tunes: [],
139
+ shortcut: "",
140
+ enabled: true,
141
+ sortOrder: null
142
+ });
143
+ const emptyField = (index = 0) => ({
144
+ key: nextKey(),
145
+ name: `field${index + 1}`,
146
+ label: "",
147
+ type: "text",
148
+ required: false,
149
+ placeholder: "",
150
+ default: "",
151
+ optionsText: ""
152
+ });
153
+ const fromDto = (dto) => ({
154
+ ...emptyValues(),
155
+ name: dto.name || "",
156
+ nameTouched: true,
157
+ label: dto.label || "",
158
+ blockType: BLOCK_TYPES.includes(dto.blockType) ? dto.blockType : "simple",
159
+ description: dto.description || "",
160
+ icon: dto.icon || "",
161
+ contentType: dto.contentType || "",
162
+ titleField: dto.titleField || "",
163
+ displayFields: Array.isArray(dto.displayFields) ? dto.displayFields : [],
164
+ previewFields: Array.isArray(dto.previewFields) ? dto.previewFields : [],
165
+ fields: (Array.isArray(dto.fields) ? dto.fields : []).map((field) => ({
166
+ key: nextKey(),
167
+ name: field.name || "",
168
+ label: field.label || "",
169
+ type: FIELD_TYPES.includes(field.type) ? field.type : "text",
170
+ required: Boolean(field.required),
171
+ placeholder: field.placeholder || "",
172
+ default: field.default === void 0 || field.default === null ? "" : field.default,
173
+ optionsText: optionsToText(field.options)
174
+ })),
175
+ template: dto.template || "",
176
+ placeholder: dto.placeholder || "",
177
+ inlineToolbar: dto.inlineToolbar !== false,
178
+ tunes: Array.isArray(dto.tunes) ? dto.tunes.filter((tune) => TUNES.includes(tune)) : [],
179
+ shortcut: dto.shortcut || "",
180
+ enabled: dto.enabled !== false,
181
+ sortOrder: Number.isInteger(dto.sortOrder) ? dto.sortOrder : null
182
+ });
183
+ const toPayload = (values) => {
184
+ const simple = values.blockType === "simple";
185
+ const optional = (value) => {
186
+ const text = String(value || "").trim();
187
+ return text ? text : null;
188
+ };
189
+ const payload = {
190
+ name: String(values.name || "").trim(),
191
+ label: String(values.label || "").trim(),
192
+ blockType: values.blockType,
193
+ description: optional(values.description),
194
+ icon: optional(values.icon),
195
+ contentType: simple ? null : optional(values.contentType),
196
+ titleField: simple ? null : optional(values.titleField),
197
+ displayFields: simple ? [] : values.displayFields,
198
+ previewFields: simple ? [] : values.previewFields,
199
+ fields: simple ? values.fields.map((field) => {
200
+ const out = {
201
+ name: String(field.name || "").trim(),
202
+ label: String(field.label || "").trim(),
203
+ type: field.type
204
+ };
205
+ if (field.required) out.required = true;
206
+ if (String(field.placeholder || "").trim()) out.placeholder = String(field.placeholder).trim();
207
+ if (field.type === "checkbox") {
208
+ if (field.default === true || field.default === "true") out.default = true;
209
+ } else if (field.type === "number") {
210
+ if (field.default !== "" && field.default !== null && Number.isFinite(Number(field.default)))
211
+ out.default = Number(field.default);
212
+ } else if (String(field.default ?? "") !== "") out.default = String(field.default);
213
+ if (field.type === "select") out.options = textToOptions(field.optionsText);
214
+ return out;
215
+ }) : [],
216
+ template: simple ? optional(values.template) : null,
217
+ placeholder: optional(values.placeholder),
218
+ inlineToolbar: Boolean(values.inlineToolbar),
219
+ tunes: values.tunes.filter((tune) => TUNES.includes(tune)),
220
+ shortcut: optional(values.shortcut ? String(values.shortcut).toUpperCase().replace(/\s+/g, "") : ""),
221
+ enabled: Boolean(values.enabled)
222
+ };
223
+ if (Number.isInteger(values.sortOrder)) payload.sortOrder = values.sortOrder;
224
+ return payload;
225
+ };
226
+ const validateBlock = (values, context = {}) => {
227
+ const errors = {};
228
+ const name = String(values.name || "").trim();
229
+ if (!name) errors.name = "required";
230
+ else if (!NAME_PATTERN.test(name)) errors.name = "namePattern";
231
+ else if (RESERVED_NAMES.includes(name.toLowerCase())) errors.name = "reserved";
232
+ else if ((context.existingNames || []).some((other) => other.toLowerCase() === name.toLowerCase()))
233
+ errors.name = "taken";
234
+ const label = String(values.label || "").trim();
235
+ if (!label) errors.label = "required";
236
+ else if (label.length > 100) errors.label = "tooLong";
237
+ if (!BLOCK_TYPES.includes(values.blockType)) errors.blockType = "required";
238
+ if (String(values.description || "").length > 1e3) errors.description = "tooLong";
239
+ if (String(values.icon || "").length > 1e4) errors.icon = "tooLong";
240
+ if (String(values.placeholder || "").length > 200) errors.placeholder = "tooLong";
241
+ const shortcut = String(values.shortcut || "").toUpperCase().replace(/\s+/g, "");
242
+ if (shortcut && !SHORTCUT_PATTERN.test(shortcut)) errors.shortcut = "shortcut";
243
+ if (values.blockType === "simple") {
244
+ if (String(values.template || "").length > 2e4) errors.template = "tooLong";
245
+ if (values.fields.length > 20) errors.fields = "tooMany";
246
+ const seen = /* @__PURE__ */ new Set();
247
+ values.fields.forEach((field, index) => {
248
+ const fieldName = String(field.name || "").trim();
249
+ if (!fieldName) errors[`fields.${index}.name`] = "required";
250
+ else if (!FIELD_NAME_PATTERN.test(fieldName)) errors[`fields.${index}.name`] = "fieldName";
251
+ else if (seen.has(fieldName)) errors[`fields.${index}.name`] = "duplicate";
252
+ seen.add(fieldName);
253
+ const fieldLabel = String(field.label || "").trim();
254
+ if (!fieldLabel) errors[`fields.${index}.label`] = "required";
255
+ else if (fieldLabel.length > 100) errors[`fields.${index}.label`] = "tooLong";
256
+ if (String(field.placeholder || "").length > 200) errors[`fields.${index}.placeholder`] = "tooLong";
257
+ if (String(field.default ?? "").length > 2e3) errors[`fields.${index}.default`] = "tooLong";
258
+ if (field.type === "number" && field.default !== "" && field.default !== null && !Number.isFinite(Number(field.default))) {
259
+ errors[`fields.${index}.default`] = "number";
260
+ }
261
+ if (field.type === "select") {
262
+ const options = textToOptions(field.optionsText);
263
+ if (!options.length) errors[`fields.${index}.options`] = "options";
264
+ else if (options.length > 50) errors[`fields.${index}.options`] = "tooMany";
265
+ else if (options.some(
266
+ (option) => (typeof option === "string" ? option : option.value).length > 100 || typeof option === "object" && option.label.length > 100
267
+ )) {
268
+ errors[`fields.${index}.options`] = "tooLong";
269
+ }
270
+ }
271
+ });
272
+ } else {
273
+ if (values.titleField && !FIELD_NAME_PATTERN.test(values.titleField)) errors.titleField = "fieldName";
274
+ if (values.displayFields.length > 20) errors.displayFields = "tooMany";
275
+ if (values.previewFields.length > 20) errors.previewFields = "tooMany";
276
+ }
277
+ return errors;
278
+ };
279
+ const mapServerErrors = (details) => {
280
+ const out = {};
281
+ const fieldErrors = details && typeof details === "object" ? details.fieldErrors || {} : {};
282
+ for (const [key, messages] of Object.entries(fieldErrors)) {
283
+ const message = Array.isArray(messages) ? messages[0] : String(messages || "");
284
+ if (message) out[key] = { server: message };
285
+ }
286
+ const formErrors = details && Array.isArray(details.formErrors) ? details.formErrors : [];
287
+ if (formErrors[0]) out._form = { server: formErrors[0] };
288
+ return out;
289
+ };
290
+ const withEnabled = (dto, enabled) => ({ ...toPayload(fromDto(dto)), enabled });
291
+ const moveId = (ids, id, direction) => {
292
+ const index = ids.indexOf(id);
293
+ const target = index + direction;
294
+ if (index < 0 || target < 0 || target >= ids.length) return null;
295
+ const next = ids.slice();
296
+ [next[index], next[target]] = [next[target], next[index]];
297
+ return next;
298
+ };
299
+ const fillTemplate = (template, fields) => {
300
+ const escape = (text) => String(text).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
301
+ const values = new Map(
302
+ fields.map((field) => [
303
+ String(field.name),
304
+ String(field.default ?? "") || String(field.label || field.name)
305
+ ])
306
+ );
307
+ values.set("content", "Content");
308
+ return String(template || "").replace(
309
+ /\{\{\s*([A-Za-z][A-Za-z0-9_]{0,39})\s*\}\}/g,
310
+ (match, key) => values.has(key) ? escape(values.get(key)) : match
311
+ );
312
+ };
313
+ const useCustomBlocks = () => {
314
+ const { get } = useFetchClient();
315
+ const [status, setStatus] = useState("loading");
316
+ const [blocks, setBlocks] = useState([]);
317
+ const [refreshError, setRefreshError] = useState(false);
318
+ const [contentTypes, setContentTypes] = useState({ status: "loading", items: [] });
319
+ const mounted = useRef(true);
320
+ const loaded = useRef(false);
321
+ useEffect(() => {
322
+ mounted.current = true;
323
+ return () => {
324
+ mounted.current = false;
325
+ };
326
+ }, []);
327
+ const fetchBlocks = useCallback(
328
+ () => get(API.customBlocks, { params: { all: "true" } }).then(
329
+ ({ data }) => {
330
+ if (!mounted.current) return;
331
+ setBlocks(Array.isArray(data.data) ? data.data : []);
332
+ setRefreshError(false);
333
+ loaded.current = true;
334
+ setStatus("ready");
335
+ },
336
+ () => {
337
+ if (!mounted.current) return;
338
+ if (loaded.current) setRefreshError(true);
339
+ else setStatus("error");
340
+ }
341
+ ),
342
+ [get]
343
+ );
344
+ const fetchContentTypes = useCallback(
345
+ () => get(API.contentTypes).then(
346
+ ({ data }) => {
347
+ if (mounted.current)
348
+ setContentTypes({ status: "ready", items: Array.isArray(data.data) ? data.data : [] });
349
+ },
350
+ () => {
351
+ if (mounted.current) setContentTypes({ status: "error", items: [] });
352
+ }
353
+ ),
354
+ [get]
355
+ );
356
+ useEffect(() => {
357
+ fetchBlocks();
358
+ fetchContentTypes();
359
+ }, [fetchBlocks, fetchContentTypes]);
360
+ const load = useCallback(() => {
361
+ if (!loaded.current) setStatus("loading");
362
+ return fetchBlocks();
363
+ }, [fetchBlocks]);
364
+ const loadContentTypes = useCallback(() => {
365
+ setContentTypes((current) => ({ ...current, status: "loading" }));
366
+ return fetchContentTypes();
367
+ }, [fetchContentTypes]);
368
+ return {
369
+ status,
370
+ blocks,
371
+ setBlocks,
372
+ refreshError,
373
+ reload: load,
374
+ contentTypes,
375
+ reloadContentTypes: loadContentTypes
376
+ };
377
+ };
378
+ const blockErrorText = (t, error) => {
379
+ if (!error) return void 0;
380
+ if (typeof error === "object") return error.server;
381
+ switch (error) {
382
+ case "required":
383
+ return t("settings.validation.required", "This field is required.");
384
+ case "namePattern":
385
+ return t(
386
+ "settings.blocks.validation.name",
387
+ "Start with a letter; use 2 to 50 letters, digits, - or _."
388
+ );
389
+ case "reserved":
390
+ return t(
391
+ "settings.blocks.validation.reserved",
392
+ "This name is used by a built-in tool. Choose another one."
393
+ );
394
+ case "taken":
395
+ return t("settings.blocks.validation.taken", "Another block already uses this name.");
396
+ case "fieldName":
397
+ return t(
398
+ "settings.blocks.validation.fieldName",
399
+ "Start with a letter; use up to 40 letters, digits or _."
400
+ );
401
+ case "duplicate":
402
+ return t("settings.blocks.validation.duplicate", "Field names must be unique.");
403
+ case "options":
404
+ return t("settings.blocks.validation.options", "A select field needs at least one option.");
405
+ case "number":
406
+ return t("settings.blocks.validation.number", "Enter a number.");
407
+ case "shortcut":
408
+ return t("settings.blocks.validation.shortcut", "Use a combination such as CMD+SHIFT+K.");
409
+ case "tooMany":
410
+ return t("settings.blocks.validation.tooMany", "Too many entries.");
411
+ case "tooLong":
412
+ return t("settings.blocks.validation.tooLong", "This text is too long.");
413
+ default:
414
+ return t("settings.validation.invalid", "Check this value.");
415
+ }
416
+ };
417
+ const fieldTypeLabel = (t, type) => ({
418
+ text: t("settings.blocks.fieldType.text", "Text"),
419
+ textarea: t("settings.blocks.fieldType.textarea", "Long text"),
420
+ url: t("settings.blocks.fieldType.url", "Link (URL)"),
421
+ number: t("settings.blocks.fieldType.number", "Number"),
422
+ select: t("settings.blocks.fieldType.select", "Choice list"),
423
+ checkbox: t("settings.blocks.fieldType.checkbox", "Checkbox"),
424
+ image: t("settings.blocks.fieldType.image", "Image (Media Library)"),
425
+ color: t("settings.blocks.fieldType.color", "Colour")
426
+ })[type] || type;
427
+ const blockTypeLabel = (t, type) => type === "embedded-entry" ? t("settings.blocks.type.embedded", "Embedded entry") : t("settings.blocks.type.simple", "Simple block");
428
+ const IconFrame = styled.span`
429
+ display: inline-flex;
430
+ align-items: center;
431
+ justify-content: center;
432
+ width: 3.2rem;
433
+ height: 3.2rem;
434
+ border: 1px solid ${({ theme }) => theme.colors.neutral200};
435
+ border-radius: ${({ theme }) => theme.borderRadius};
436
+ color: ${({ theme }) => theme.colors.neutral800};
437
+ background: ${({ theme }) => theme.colors.neutral0};
438
+
439
+ svg {
440
+ width: 2rem;
441
+ height: 2rem;
442
+ }
443
+ `;
444
+ const TemplateFrame = styled(Box)`
445
+ overflow-wrap: anywhere;
446
+ color: ${({ theme }) => theme.colors.neutral800};
447
+ font-size: ${({ theme }) => theme.fontSizes[2]};
448
+
449
+ img {
450
+ max-width: 100%;
451
+ height: auto;
452
+ }
453
+ `;
454
+ const IconPreview = ({ svg, label }) => {
455
+ const clean = useMemo(() => sanitizeSvg(svg), [svg]);
456
+ return /* @__PURE__ */ jsx(IconFrame, { role: "img", "aria-label": label, dangerouslySetInnerHTML: { __html: clean } });
457
+ };
458
+ const TemplatePreview = ({ template, fields, label, empty }) => {
459
+ const clean = useMemo(() => sanitizeTemplate(fillTemplate(template, fields)), [template, fields]);
460
+ return /* @__PURE__ */ jsxs(Box, { children: [
461
+ /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", tag: "p", children: label }),
462
+ /* @__PURE__ */ jsx(TemplateFrame, { marginTop: 2, padding: 4, hasRadius: true, borderColor: "neutral200", background: "neutral100", children: clean ? (
463
+ // sanitised template HTML from sanitizeTemplate (DOMPurify)
464
+ /* @__PURE__ */ jsx("div", { dangerouslySetInnerHTML: { __html: clean } })
465
+ ) : /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: empty }) })
466
+ ] });
467
+ };
468
+ const RowActions = ({
469
+ block,
470
+ index,
471
+ count,
472
+ busy,
473
+ onEdit,
474
+ onDuplicate,
475
+ onMove,
476
+ onDelete,
477
+ fallbackFocusRef
478
+ }) => {
479
+ const t = useT();
480
+ const label = block.label || block.name;
481
+ return /* @__PURE__ */ jsxs(Flex, { gap: 1, wrap: "wrap", children: [
482
+ /* @__PURE__ */ jsx(
483
+ IconButton,
484
+ {
485
+ label: t("settings.blocks.action.edit", "Edit {label}", { label }),
486
+ variant: "ghost",
487
+ onClick: () => onEdit(block),
488
+ children: /* @__PURE__ */ jsx(Pencil, {})
489
+ }
490
+ ),
491
+ /* @__PURE__ */ jsx(
492
+ IconButton,
493
+ {
494
+ label: t("settings.blocks.action.duplicate", "Duplicate {label}", { label }),
495
+ variant: "ghost",
496
+ disabled: busy,
497
+ onClick: () => onDuplicate(block),
498
+ children: /* @__PURE__ */ jsx(Duplicate, {})
499
+ }
500
+ ),
501
+ /* @__PURE__ */ jsx(
502
+ IconButton,
503
+ {
504
+ label: t("settings.blocks.action.moveUp", "Move {label} up", { label }),
505
+ variant: "ghost",
506
+ disabled: busy || index === 0,
507
+ onClick: () => onMove(block, -1),
508
+ children: /* @__PURE__ */ jsx(ArrowUp, {})
509
+ }
510
+ ),
511
+ /* @__PURE__ */ jsx(
512
+ IconButton,
513
+ {
514
+ label: t("settings.blocks.action.moveDown", "Move {label} down", { label }),
515
+ variant: "ghost",
516
+ disabled: busy || index === count - 1,
517
+ onClick: () => onMove(block, 1),
518
+ children: /* @__PURE__ */ jsx(ArrowDown, {})
519
+ }
520
+ ),
521
+ /* @__PURE__ */ jsx(
522
+ ConfirmAction,
523
+ {
524
+ fallbackFocusRef,
525
+ trigger: /* @__PURE__ */ jsx(
526
+ IconButton,
527
+ {
528
+ label: t("settings.blocks.action.delete", "Delete {label}", { label }),
529
+ variant: "ghost",
530
+ disabled: busy,
531
+ children: /* @__PURE__ */ jsx(Trash, {})
532
+ }
533
+ ),
534
+ title: t("settings.blocks.delete.title", "Delete the block {label}?", { label }),
535
+ body: t(
536
+ "settings.blocks.delete.body",
537
+ "The block disappears from the editor toolbox. Content that already uses it keeps its data, but the editor shows it as unavailable until a block named {name} exists again. This cannot be undone.",
538
+ { name: block.name }
539
+ ),
540
+ confirmLabel: t("settings.blocks.delete.confirm", "Delete block"),
541
+ onConfirm: () => onDelete(block)
542
+ }
543
+ )
544
+ ] });
545
+ };
546
+ const EnabledSwitch = ({ block, busy, onToggle }) => {
547
+ const t = useT();
548
+ return /* @__PURE__ */ jsx(
549
+ Switch,
550
+ {
551
+ checked: block.enabled,
552
+ disabled: busy,
553
+ onCheckedChange: (checked) => onToggle(block, checked === true),
554
+ "aria-label": t("settings.blocks.action.toggle", "Show {label} in the editor toolbox", {
555
+ label: block.label || block.name
556
+ }),
557
+ onLabel: t("settings.switch.on", "On"),
558
+ offLabel: t("settings.switch.off", "Off"),
559
+ visibleLabels: true
560
+ }
561
+ );
562
+ };
563
+ const Identity = ({ block }) => {
564
+ const t = useT();
565
+ return /* @__PURE__ */ jsxs(Flex, { gap: 3, alignItems: "center", minWidth: 0, children: [
566
+ block.icon ? /* @__PURE__ */ jsx(
567
+ IconPreview,
568
+ {
569
+ svg: block.icon,
570
+ label: t("settings.blocks.list.icon", "Icon of {label}", { label: block.label })
571
+ }
572
+ ) : null,
573
+ /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "flex-start", gap: 1, minWidth: 0, children: [
574
+ /* @__PURE__ */ jsx(
575
+ Typography,
576
+ {
577
+ variant: "omega",
578
+ fontWeight: "bold",
579
+ textColor: "neutral800",
580
+ style: { overflowWrap: "anywhere" },
581
+ children: block.label
582
+ }
583
+ ),
584
+ /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", style: { overflowWrap: "anywhere" }, children: block.name })
585
+ ] })
586
+ ] });
587
+ };
588
+ const BlockList = ({
589
+ blocks,
590
+ busyId,
591
+ onEdit,
592
+ onDuplicate,
593
+ onMove,
594
+ onDelete,
595
+ onToggle,
596
+ fallbackFocusRef
597
+ }) => {
598
+ const t = useT();
599
+ const { isBelowLarge } = useBreakpoint();
600
+ const actions = { onEdit, onDuplicate, onMove, onDelete, fallbackFocusRef };
601
+ if (isBelowLarge) {
602
+ return /* @__PURE__ */ jsx(
603
+ Flex,
604
+ {
605
+ tag: "ul",
606
+ direction: "column",
607
+ alignItems: "stretch",
608
+ gap: 3,
609
+ "aria-label": t("settings.blocks.list.label", "Custom blocks"),
610
+ children: blocks.map((block, index) => /* @__PURE__ */ jsx(
611
+ Box,
612
+ {
613
+ tag: "li",
614
+ background: "neutral0",
615
+ hasRadius: true,
616
+ shadow: "tableShadow",
617
+ padding: 4,
618
+ minWidth: 0,
619
+ children: /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 3, children: [
620
+ /* @__PURE__ */ jsxs(Flex, { justifyContent: "space-between", alignItems: "flex-start", gap: 3, children: [
621
+ /* @__PURE__ */ jsx(Identity, { block }),
622
+ /* @__PURE__ */ jsx(EnabledSwitch, { block, busy: busyId === block.id, onToggle })
623
+ ] }),
624
+ /* @__PURE__ */ jsx(Flex, { gap: 2, wrap: "wrap", children: /* @__PURE__ */ jsx(Badge, { children: blockTypeLabel(t, block.blockType) }) }),
625
+ block.description ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: block.description }) : null,
626
+ /* @__PURE__ */ jsx(
627
+ RowActions,
628
+ {
629
+ block,
630
+ index,
631
+ count: blocks.length,
632
+ busy: busyId === block.id,
633
+ ...actions
634
+ }
635
+ )
636
+ ] })
637
+ },
638
+ block.id
639
+ ))
640
+ }
641
+ );
642
+ }
643
+ return /* @__PURE__ */ jsxs(Table, { colCount: 5, rowCount: blocks.length + 1, children: [
644
+ /* @__PURE__ */ jsx(Thead, { children: /* @__PURE__ */ jsxs(Tr, { children: [
645
+ /* @__PURE__ */ jsx(Th, { children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", children: t("settings.blocks.list.block", "Block") }) }),
646
+ /* @__PURE__ */ jsx(Th, { children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", children: t("settings.blocks.list.type", "Type") }) }),
647
+ /* @__PURE__ */ jsx(Th, { children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", children: t("settings.blocks.list.description", "Description") }) }),
648
+ /* @__PURE__ */ jsx(Th, { children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", children: t("settings.blocks.list.enabled", "In toolbox") }) }),
649
+ /* @__PURE__ */ jsx(Th, { children: /* @__PURE__ */ jsx(VisuallyHidden, { children: t("settings.blocks.list.actions", "Actions") }) })
650
+ ] }) }),
651
+ /* @__PURE__ */ jsx(Tbody, { children: blocks.map((block, index) => /* @__PURE__ */ jsxs(Tr, { children: [
652
+ /* @__PURE__ */ jsx(Td, { children: /* @__PURE__ */ jsx(Identity, { block }) }),
653
+ /* @__PURE__ */ jsx(Td, { children: /* @__PURE__ */ jsx(Badge, { children: blockTypeLabel(t, block.blockType) }) }),
654
+ /* @__PURE__ */ jsx(Td, { children: /* @__PURE__ */ jsx(
655
+ Typography,
656
+ {
657
+ textColor: block.description ? "neutral800" : "neutral600",
658
+ style: { overflowWrap: "anywhere" },
659
+ children: block.description || t("settings.blocks.list.noDescription", "No description")
660
+ }
661
+ ) }),
662
+ /* @__PURE__ */ jsx(Td, { children: /* @__PURE__ */ jsx(EnabledSwitch, { block, busy: busyId === block.id, onToggle }) }),
663
+ /* @__PURE__ */ jsx(Td, { children: /* @__PURE__ */ jsx(Flex, { justifyContent: "flex-end", children: /* @__PURE__ */ jsx(
664
+ RowActions,
665
+ {
666
+ block,
667
+ index,
668
+ count: blocks.length,
669
+ busy: busyId === block.id,
670
+ ...actions
671
+ }
672
+ ) }) })
673
+ ] }, block.id)) })
674
+ ] });
675
+ };
676
+ const FieldsEditor = ({ fields, onChange, errors }) => {
677
+ const t = useT();
678
+ const update = (index, patch) => onChange(fields.map((field, i) => i === index ? { ...field, ...patch } : field));
679
+ const move = (index, direction) => {
680
+ const target = index + direction;
681
+ if (target < 0 || target >= fields.length) return;
682
+ const next = fields.slice();
683
+ [next[index], next[target]] = [next[target], next[index]];
684
+ onChange(next);
685
+ };
686
+ const err = (path) => blockErrorText(t, errors[path]);
687
+ return /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 4, children: [
688
+ fields.length === 0 ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: t(
689
+ "settings.blocks.fields.empty",
690
+ "No fields yet. Without fields the block has one text area named content."
691
+ ) }) : null,
692
+ fields.map((field, index) => {
693
+ const name = field.label || field.name || t("settings.blocks.fields.unnamed", "Field {number}", { number: index + 1 });
694
+ return /* @__PURE__ */ jsx(
695
+ Box,
696
+ {
697
+ padding: 4,
698
+ hasRadius: true,
699
+ borderColor: "neutral200",
700
+ background: "neutral100",
701
+ minWidth: 0,
702
+ children: /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 4, children: [
703
+ /* @__PURE__ */ jsxs(Flex, { justifyContent: "space-between", alignItems: "center", gap: 2, wrap: "wrap", children: [
704
+ /* @__PURE__ */ jsx(Typography, { variant: "omega", fontWeight: "bold", tag: "h4", textColor: "neutral800", children: t("settings.blocks.fields.heading", "Field {number}", { number: index + 1 }) }),
705
+ /* @__PURE__ */ jsxs(Flex, { gap: 1, children: [
706
+ /* @__PURE__ */ jsx(
707
+ IconButton,
708
+ {
709
+ label: t("settings.blocks.fields.moveUp", "Move field {name} up", { name }),
710
+ variant: "ghost",
711
+ disabled: index === 0,
712
+ onClick: () => move(index, -1),
713
+ children: /* @__PURE__ */ jsx(ArrowUp, {})
714
+ }
715
+ ),
716
+ /* @__PURE__ */ jsx(
717
+ IconButton,
718
+ {
719
+ label: t("settings.blocks.fields.moveDown", "Move field {name} down", { name }),
720
+ variant: "ghost",
721
+ disabled: index === fields.length - 1,
722
+ onClick: () => move(index, 1),
723
+ children: /* @__PURE__ */ jsx(ArrowDown, {})
724
+ }
725
+ ),
726
+ /* @__PURE__ */ jsx(
727
+ IconButton,
728
+ {
729
+ label: t("settings.blocks.fields.remove", "Remove field {name}", { name }),
730
+ variant: "ghost",
731
+ onClick: () => onChange(fields.filter((_, i) => i !== index)),
732
+ children: /* @__PURE__ */ jsx(Trash, {})
733
+ }
734
+ )
735
+ ] })
736
+ ] }),
737
+ /* @__PURE__ */ jsxs(Grid.Root, { gap: 4, children: [
738
+ /* @__PURE__ */ jsx(Grid.Item, { col: 6, xs: 12, s: 12, m: 6, direction: "column", alignItems: "stretch", minWidth: 0, children: /* @__PURE__ */ jsxs(Field.Root, { name: `fields.${index}.label`, error: err(`fields.${index}.label`), required: true, children: [
739
+ /* @__PURE__ */ jsx(Field.Label, { children: t("settings.blocks.fields.label", "Label") }),
740
+ /* @__PURE__ */ jsx(
741
+ TextInput,
742
+ {
743
+ value: field.label,
744
+ onChange: (event) => update(index, { label: event.target.value })
745
+ }
746
+ ),
747
+ /* @__PURE__ */ jsx(Field.Error, {})
748
+ ] }) }),
749
+ /* @__PURE__ */ jsx(Grid.Item, { col: 6, xs: 12, s: 12, m: 6, direction: "column", alignItems: "stretch", minWidth: 0, children: /* @__PURE__ */ jsxs(
750
+ Field.Root,
751
+ {
752
+ name: `fields.${index}.name`,
753
+ error: err(`fields.${index}.name`),
754
+ hint: t("settings.blocks.fields.nameHint", "Stored data key and template placeholder."),
755
+ required: true,
756
+ children: [
757
+ /* @__PURE__ */ jsx(Field.Label, { children: t("settings.blocks.fields.name", "Key") }),
758
+ /* @__PURE__ */ jsx(
759
+ TextInput,
760
+ {
761
+ value: field.name,
762
+ onChange: (event) => update(index, { name: event.target.value })
763
+ }
764
+ ),
765
+ /* @__PURE__ */ jsx(Field.Hint, {}),
766
+ /* @__PURE__ */ jsx(Field.Error, {})
767
+ ]
768
+ }
769
+ ) }),
770
+ /* @__PURE__ */ jsx(Grid.Item, { col: 6, xs: 12, s: 12, m: 6, direction: "column", alignItems: "stretch", minWidth: 0, children: /* @__PURE__ */ jsxs(Field.Root, { name: `fields.${index}.type`, children: [
771
+ /* @__PURE__ */ jsx(Field.Label, { children: t("settings.blocks.fields.type", "Type") }),
772
+ /* @__PURE__ */ jsx(
773
+ SingleSelect,
774
+ {
775
+ value: field.type,
776
+ onChange: (value) => update(index, { type: String(value), default: "" }),
777
+ children: FIELD_TYPES.map((type) => /* @__PURE__ */ jsx(SingleSelectOption, { value: type, children: fieldTypeLabel(t, type) }, type))
778
+ }
779
+ )
780
+ ] }) }),
781
+ /* @__PURE__ */ jsx(Grid.Item, { col: 6, xs: 12, s: 12, m: 6, direction: "column", alignItems: "stretch", minWidth: 0, children: /* @__PURE__ */ jsxs(Field.Root, { name: `fields.${index}.placeholder`, error: err(`fields.${index}.placeholder`), children: [
782
+ /* @__PURE__ */ jsx(Field.Label, { children: t("settings.blocks.fields.placeholder", "Placeholder") }),
783
+ /* @__PURE__ */ jsx(
784
+ TextInput,
785
+ {
786
+ value: field.placeholder,
787
+ disabled: ["checkbox", "image", "select", "color"].includes(field.type),
788
+ onChange: (event) => update(index, { placeholder: event.target.value })
789
+ }
790
+ ),
791
+ /* @__PURE__ */ jsx(Field.Error, {})
792
+ ] }) }),
793
+ field.type === "select" ? /* @__PURE__ */ jsx(Grid.Item, { col: 12, direction: "column", alignItems: "stretch", minWidth: 0, children: /* @__PURE__ */ jsxs(
794
+ Field.Root,
795
+ {
796
+ name: `fields.${index}.options`,
797
+ error: err(`fields.${index}.options`),
798
+ hint: t(
799
+ "settings.blocks.fields.optionsHint",
800
+ 'One option per line. Use "value | label" when the label differs.'
801
+ ),
802
+ required: true,
803
+ children: [
804
+ /* @__PURE__ */ jsx(Field.Label, { children: t("settings.blocks.fields.options", "Options") }),
805
+ /* @__PURE__ */ jsx(
806
+ Textarea,
807
+ {
808
+ value: field.optionsText,
809
+ onChange: (event) => update(index, { optionsText: event.target.value })
810
+ }
811
+ ),
812
+ /* @__PURE__ */ jsx(Field.Hint, {}),
813
+ /* @__PURE__ */ jsx(Field.Error, {})
814
+ ]
815
+ }
816
+ ) }) : null,
817
+ field.type !== "image" && field.type !== "checkbox" ? /* @__PURE__ */ jsx(
818
+ Grid.Item,
819
+ {
820
+ col: 6,
821
+ xs: 12,
822
+ s: 12,
823
+ m: 6,
824
+ direction: "column",
825
+ alignItems: "stretch",
826
+ minWidth: 0,
827
+ children: /* @__PURE__ */ jsxs(Field.Root, { name: `fields.${index}.default`, error: err(`fields.${index}.default`), children: [
828
+ /* @__PURE__ */ jsx(Field.Label, { children: t("settings.blocks.fields.default", "Default value") }),
829
+ /* @__PURE__ */ jsx(
830
+ TextInput,
831
+ {
832
+ value: String(field.default ?? ""),
833
+ onChange: (event) => update(index, { default: event.target.value })
834
+ }
835
+ ),
836
+ /* @__PURE__ */ jsx(Field.Error, {})
837
+ ] })
838
+ }
839
+ ) : null,
840
+ field.type === "checkbox" ? /* @__PURE__ */ jsx(
841
+ Grid.Item,
842
+ {
843
+ col: 6,
844
+ xs: 12,
845
+ s: 12,
846
+ m: 6,
847
+ direction: "column",
848
+ alignItems: "flex-start",
849
+ minWidth: 0,
850
+ children: /* @__PURE__ */ jsx(
851
+ Checkbox,
852
+ {
853
+ checked: field.default === true || field.default === "true",
854
+ onCheckedChange: (checked) => update(index, { default: checked === true }),
855
+ children: t("settings.blocks.fields.defaultChecked", "Checked by default")
856
+ }
857
+ )
858
+ }
859
+ ) : null,
860
+ /* @__PURE__ */ jsx(
861
+ Grid.Item,
862
+ {
863
+ col: 6,
864
+ xs: 12,
865
+ s: 12,
866
+ m: 6,
867
+ direction: "column",
868
+ alignItems: "flex-start",
869
+ minWidth: 0,
870
+ children: /* @__PURE__ */ jsx(
871
+ Checkbox,
872
+ {
873
+ checked: field.required,
874
+ onCheckedChange: (checked) => update(index, { required: checked === true }),
875
+ children: t("settings.blocks.fields.required", "Required")
876
+ }
877
+ )
878
+ }
879
+ )
880
+ ] })
881
+ ] })
882
+ },
883
+ field.key
884
+ );
885
+ }),
886
+ /* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsx(
887
+ Button,
888
+ {
889
+ variant: "secondary",
890
+ startIcon: /* @__PURE__ */ jsx(Plus, {}),
891
+ disabled: fields.length >= 20,
892
+ onClick: () => onChange([...fields, emptyField(fields.length)]),
893
+ children: t("settings.blocks.fields.add", "Add field")
894
+ }
895
+ ) }),
896
+ errors.fields ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "danger600", children: blockErrorText(t, errors.fields) }) : null
897
+ ] });
898
+ };
899
+ const SubHeading = ({ title, subtitle }) => /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "flex-start", gap: 1, children: [
900
+ /* @__PURE__ */ jsx(Typography, { variant: "delta", tag: "h3", textColor: "neutral800", children: title }),
901
+ subtitle ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: subtitle }) : null
902
+ ] });
903
+ const BlockFormModal = ({
904
+ open,
905
+ block,
906
+ otherNames,
907
+ contentTypes,
908
+ onRetryContentTypes,
909
+ onSubmit,
910
+ onClose
911
+ }) => {
912
+ const t = useT();
913
+ const [values, setValues] = useState(() => block ? fromDto(block) : emptyValues());
914
+ const [serverErrors, setServerErrors] = useState({});
915
+ const [showErrors, setShowErrors] = useState(false);
916
+ const [saving, setSaving] = useState(false);
917
+ const errors = useMemo(() => validateBlock(values, { existingNames: otherNames }), [values, otherNames]);
918
+ const visible = useMemo(
919
+ () => ({ ...showErrors ? errors : {}, ...serverErrors }),
920
+ [errors, serverErrors, showErrors]
921
+ );
922
+ const err = (path) => blockErrorText(t, visible[path]);
923
+ const set = (patch) => {
924
+ setValues((current) => ({ ...current, ...patch }));
925
+ setServerErrors((current) => {
926
+ const next = { ...current };
927
+ Object.keys(patch).forEach((key) => delete next[key]);
928
+ delete next._form;
929
+ return next;
930
+ });
931
+ };
932
+ const onLabel = (label) => {
933
+ if (values.nameTouched) set({ label });
934
+ else set({ label, name: deriveName(label) });
935
+ };
936
+ const selectedType = contentTypes.items.find((ct) => ct.uid === values.contentType);
937
+ const attributeOptions = selectedType ? selectedType.attributes : Array.from(new Set(contentTypes.items.flatMap((ct) => ct.attributes)));
938
+ const submit = async () => {
939
+ setShowErrors(true);
940
+ if (Object.keys(errors).length) return;
941
+ setSaving(true);
942
+ try {
943
+ const result = await onSubmit(values);
944
+ if (!result.ok && result.errors) setServerErrors(result.errors);
945
+ } finally {
946
+ setSaving(false);
947
+ }
948
+ };
949
+ const title = block ? t("settings.blocks.modal.editTitle", "Edit block {label}", { label: block.label }) : t("settings.blocks.modal.createTitle", "Create a custom block");
950
+ return /* @__PURE__ */ jsx(
951
+ Modal.Root,
952
+ {
953
+ open,
954
+ onOpenChange: (next) => {
955
+ if (!next && !saving) onClose();
956
+ },
957
+ children: /* @__PURE__ */ jsxs(Modal.Content, { children: [
958
+ /* @__PURE__ */ jsx(Modal.Header, { closeLabel: t("settings.close", "Close"), children: /* @__PURE__ */ jsx(Modal.Title, { children: title }) }),
959
+ /* @__PURE__ */ jsx(Modal.Body, { children: /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 6, children: [
960
+ visible._form ? /* @__PURE__ */ jsx(
961
+ Alert,
962
+ {
963
+ variant: "danger",
964
+ closeLabel: t("settings.close", "Close"),
965
+ onClose: () => setServerErrors({}),
966
+ children: visible._form.server
967
+ }
968
+ ) : null,
969
+ showErrors && Object.keys(errors).length ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "danger600", role: "status", children: t("settings.blocks.modal.invalid", "Some values need attention. They are marked below.") }) : null,
970
+ /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 4, children: [
971
+ /* @__PURE__ */ jsx(SubHeading, { title: t("settings.blocks.modal.basics", "Basics") }),
972
+ /* @__PURE__ */ jsxs(Grid.Root, { gap: 4, children: [
973
+ /* @__PURE__ */ jsx(Grid.Item, { col: 6, xs: 12, s: 12, m: 6, direction: "column", alignItems: "stretch", minWidth: 0, children: /* @__PURE__ */ jsxs(
974
+ Field.Root,
975
+ {
976
+ name: "label",
977
+ error: err("label"),
978
+ hint: t("settings.blocks.form.labelHint", "Shown in the editor toolbox."),
979
+ required: true,
980
+ children: [
981
+ /* @__PURE__ */ jsx(Field.Label, { children: t("settings.blocks.form.label", "Label") }),
982
+ /* @__PURE__ */ jsx(TextInput, { value: values.label, onChange: (event) => onLabel(event.target.value) }),
983
+ /* @__PURE__ */ jsx(Field.Hint, {}),
984
+ /* @__PURE__ */ jsx(Field.Error, {})
985
+ ]
986
+ }
987
+ ) }),
988
+ /* @__PURE__ */ jsx(Grid.Item, { col: 6, xs: 12, s: 12, m: 6, direction: "column", alignItems: "stretch", minWidth: 0, children: /* @__PURE__ */ jsxs(
989
+ Field.Root,
990
+ {
991
+ name: "name",
992
+ error: err("name"),
993
+ hint: block ? t(
994
+ "settings.blocks.form.nameHintEdit",
995
+ "Stored as the block type in content. Renaming hides existing blocks of the old name."
996
+ ) : t(
997
+ "settings.blocks.form.nameHint",
998
+ "Identifier stored with the content. Filled from the label until you edit it."
999
+ ),
1000
+ required: true,
1001
+ children: [
1002
+ /* @__PURE__ */ jsx(Field.Label, { children: t("settings.blocks.form.name", "Name") }),
1003
+ /* @__PURE__ */ jsx(
1004
+ TextInput,
1005
+ {
1006
+ value: values.name,
1007
+ onChange: (event) => set({ name: event.target.value, nameTouched: true })
1008
+ }
1009
+ ),
1010
+ /* @__PURE__ */ jsx(Field.Hint, {}),
1011
+ /* @__PURE__ */ jsx(Field.Error, {})
1012
+ ]
1013
+ }
1014
+ ) }),
1015
+ /* @__PURE__ */ jsx(Grid.Item, { col: 6, xs: 12, s: 12, m: 6, direction: "column", alignItems: "stretch", minWidth: 0, children: /* @__PURE__ */ jsxs(Field.Root, { name: "blockType", error: err("blockType"), required: true, children: [
1016
+ /* @__PURE__ */ jsx(Field.Label, { children: t("settings.blocks.form.type", "Type") }),
1017
+ /* @__PURE__ */ jsxs(
1018
+ SingleSelect,
1019
+ {
1020
+ value: values.blockType,
1021
+ onChange: (value) => set({ blockType: String(value) }),
1022
+ children: [
1023
+ /* @__PURE__ */ jsx(SingleSelectOption, { value: "simple", children: blockTypeLabel(t, "simple") }),
1024
+ /* @__PURE__ */ jsx(SingleSelectOption, { value: "embedded-entry", children: blockTypeLabel(t, "embedded-entry") })
1025
+ ]
1026
+ }
1027
+ ),
1028
+ /* @__PURE__ */ jsx(Field.Error, {})
1029
+ ] }) }),
1030
+ /* @__PURE__ */ jsx(
1031
+ Grid.Item,
1032
+ {
1033
+ col: 6,
1034
+ xs: 12,
1035
+ s: 12,
1036
+ m: 6,
1037
+ direction: "column",
1038
+ alignItems: "flex-start",
1039
+ minWidth: 0,
1040
+ children: /* @__PURE__ */ jsxs(Flex, { gap: 3, paddingTop: { initial: 0, medium: 6 }, alignItems: "center", children: [
1041
+ /* @__PURE__ */ jsx(
1042
+ Switch,
1043
+ {
1044
+ checked: values.enabled,
1045
+ onCheckedChange: (checked) => set({ enabled: checked === true }),
1046
+ "aria-label": t("settings.blocks.form.enabled", "Show in the editor toolbox"),
1047
+ onLabel: t("settings.switch.on", "On"),
1048
+ offLabel: t("settings.switch.off", "Off")
1049
+ }
1050
+ ),
1051
+ /* @__PURE__ */ jsx(Typography, { variant: "omega", textColor: "neutral800", children: t("settings.blocks.form.enabled", "Show in the editor toolbox") })
1052
+ ] })
1053
+ }
1054
+ ),
1055
+ /* @__PURE__ */ jsx(Grid.Item, { col: 12, direction: "column", alignItems: "stretch", minWidth: 0, children: /* @__PURE__ */ jsxs(Field.Root, { name: "description", error: err("description"), children: [
1056
+ /* @__PURE__ */ jsx(Field.Label, { children: t("settings.blocks.form.description", "Description") }),
1057
+ /* @__PURE__ */ jsx(
1058
+ Textarea,
1059
+ {
1060
+ value: values.description,
1061
+ onChange: (event) => set({ description: event.target.value })
1062
+ }
1063
+ ),
1064
+ /* @__PURE__ */ jsx(Field.Error, {})
1065
+ ] }) }),
1066
+ /* @__PURE__ */ jsx(Grid.Item, { col: 12, direction: "column", alignItems: "stretch", minWidth: 0, children: /* @__PURE__ */ jsxs(
1067
+ Field.Root,
1068
+ {
1069
+ name: "icon",
1070
+ error: err("icon"),
1071
+ hint: t(
1072
+ "settings.blocks.form.iconHint",
1073
+ "Optional SVG markup. Scripts, styles and links are removed."
1074
+ ),
1075
+ children: [
1076
+ /* @__PURE__ */ jsx(Field.Label, { children: t("settings.blocks.form.icon", "Icon (SVG)") }),
1077
+ /* @__PURE__ */ jsxs(Flex, { gap: 3, alignItems: "flex-start", children: [
1078
+ /* @__PURE__ */ jsx(Box, { flex: "1 1 auto", minWidth: 0, children: /* @__PURE__ */ jsx(
1079
+ Textarea,
1080
+ {
1081
+ value: values.icon,
1082
+ onChange: (event) => set({ icon: event.target.value })
1083
+ }
1084
+ ) }),
1085
+ /* @__PURE__ */ jsx(
1086
+ IconPreview,
1087
+ {
1088
+ svg: values.icon,
1089
+ label: t("settings.blocks.form.iconPreview", "Icon preview")
1090
+ }
1091
+ )
1092
+ ] }),
1093
+ /* @__PURE__ */ jsx(Field.Hint, {}),
1094
+ /* @__PURE__ */ jsx(Field.Error, {})
1095
+ ]
1096
+ }
1097
+ ) })
1098
+ ] })
1099
+ ] }),
1100
+ /* @__PURE__ */ jsx(Divider, {}),
1101
+ values.blockType === "simple" ? /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 4, children: [
1102
+ /* @__PURE__ */ jsx(
1103
+ SubHeading,
1104
+ {
1105
+ title: t("settings.blocks.modal.fields", "Fields"),
1106
+ subtitle: t(
1107
+ "settings.blocks.modal.fieldsHint",
1108
+ "Inputs editors fill in for each block. Use {example} in the template to show a value.",
1109
+ {
1110
+ example: "{{key}}"
1111
+ }
1112
+ )
1113
+ }
1114
+ ),
1115
+ /* @__PURE__ */ jsx(
1116
+ FieldsEditor,
1117
+ {
1118
+ fields: values.fields,
1119
+ errors: visible,
1120
+ onChange: (fields) => set({ fields })
1121
+ }
1122
+ ),
1123
+ /* @__PURE__ */ jsxs(
1124
+ Field.Root,
1125
+ {
1126
+ name: "template",
1127
+ error: err("template"),
1128
+ hint: t(
1129
+ "settings.blocks.form.templateHint",
1130
+ "Optional HTML layout for the block. Allowed: basic text, list, image and link tags."
1131
+ ),
1132
+ children: [
1133
+ /* @__PURE__ */ jsx(Field.Label, { children: t("settings.blocks.form.template", "HTML template") }),
1134
+ /* @__PURE__ */ jsx(
1135
+ Textarea,
1136
+ {
1137
+ value: values.template,
1138
+ onChange: (event) => set({ template: event.target.value })
1139
+ }
1140
+ ),
1141
+ /* @__PURE__ */ jsx(Field.Hint, {}),
1142
+ /* @__PURE__ */ jsx(Field.Error, {})
1143
+ ]
1144
+ }
1145
+ ),
1146
+ /* @__PURE__ */ jsx(
1147
+ TemplatePreview,
1148
+ {
1149
+ template: values.template,
1150
+ fields: values.fields,
1151
+ label: t("settings.blocks.form.templatePreview", "Preview"),
1152
+ empty: t(
1153
+ "settings.blocks.form.templateEmpty",
1154
+ "No template. The editor shows the fields as a form."
1155
+ )
1156
+ }
1157
+ ),
1158
+ /* @__PURE__ */ jsxs(Field.Root, { name: "placeholder", error: err("placeholder"), children: [
1159
+ /* @__PURE__ */ jsx(Field.Label, { children: t("settings.blocks.form.placeholder", "Placeholder") }),
1160
+ /* @__PURE__ */ jsx(
1161
+ TextInput,
1162
+ {
1163
+ value: values.placeholder,
1164
+ onChange: (event) => set({ placeholder: event.target.value })
1165
+ }
1166
+ ),
1167
+ /* @__PURE__ */ jsx(Field.Error, {})
1168
+ ] })
1169
+ ] }) : /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 4, children: [
1170
+ /* @__PURE__ */ jsx(
1171
+ SubHeading,
1172
+ {
1173
+ title: t("settings.blocks.modal.entry", "Embedded entry"),
1174
+ subtitle: t(
1175
+ "settings.blocks.modal.entryHint",
1176
+ "Editors pick an entry; only entries they can read in the Content Manager are listed."
1177
+ )
1178
+ }
1179
+ ),
1180
+ contentTypes.status === "error" ? /* @__PURE__ */ jsx(
1181
+ Alert,
1182
+ {
1183
+ variant: "warning",
1184
+ closeLabel: t("settings.close", "Close"),
1185
+ action: /* @__PURE__ */ jsx(Button, { variant: "tertiary", size: "S", onClick: onRetryContentTypes, children: t("settings.retry", "Try again") }),
1186
+ children: t("settings.blocks.contentTypes.error", "Content types could not be loaded.")
1187
+ }
1188
+ ) : null,
1189
+ /* @__PURE__ */ jsxs(Grid.Root, { gap: 4, children: [
1190
+ /* @__PURE__ */ jsx(
1191
+ Grid.Item,
1192
+ {
1193
+ col: 6,
1194
+ xs: 12,
1195
+ s: 12,
1196
+ m: 6,
1197
+ direction: "column",
1198
+ alignItems: "stretch",
1199
+ minWidth: 0,
1200
+ children: /* @__PURE__ */ jsxs(
1201
+ Field.Root,
1202
+ {
1203
+ name: "contentType",
1204
+ hint: t("settings.blocks.form.contentTypeHint", "Leave empty to let editors choose."),
1205
+ children: [
1206
+ /* @__PURE__ */ jsx(Field.Label, { children: t("settings.blocks.form.contentType", "Content type") }),
1207
+ /* @__PURE__ */ jsx(
1208
+ SingleSelect,
1209
+ {
1210
+ value: values.contentType,
1211
+ placeholder: t("settings.blocks.form.anyContentType", "Any content type"),
1212
+ onClear: () => set({ contentType: "" }),
1213
+ clearLabel: t("settings.blocks.form.clearContentType", "Clear content type"),
1214
+ onChange: (value) => set({ contentType: String(value) }),
1215
+ children: contentTypes.items.map((ct) => /* @__PURE__ */ jsx(SingleSelectOption, { value: ct.uid, children: ct.displayName }, ct.uid))
1216
+ }
1217
+ ),
1218
+ /* @__PURE__ */ jsx(Field.Hint, {})
1219
+ ]
1220
+ }
1221
+ )
1222
+ }
1223
+ ),
1224
+ /* @__PURE__ */ jsx(
1225
+ Grid.Item,
1226
+ {
1227
+ col: 6,
1228
+ xs: 12,
1229
+ s: 12,
1230
+ m: 6,
1231
+ direction: "column",
1232
+ alignItems: "stretch",
1233
+ minWidth: 0,
1234
+ children: /* @__PURE__ */ jsxs(Field.Root, { name: "titleField", error: err("titleField"), children: [
1235
+ /* @__PURE__ */ jsx(Field.Label, { children: t("settings.blocks.form.titleField", "Title field") }),
1236
+ /* @__PURE__ */ jsx(
1237
+ SingleSelect,
1238
+ {
1239
+ value: values.titleField,
1240
+ placeholder: t(
1241
+ "settings.blocks.form.titleFieldPlaceholder",
1242
+ "Detected automatically"
1243
+ ),
1244
+ onClear: () => set({ titleField: "" }),
1245
+ clearLabel: t("settings.blocks.form.clearTitleField", "Clear title field"),
1246
+ onChange: (value) => set({ titleField: String(value) }),
1247
+ children: attributeOptions.map((name) => /* @__PURE__ */ jsx(SingleSelectOption, { value: name, children: name }, name))
1248
+ }
1249
+ ),
1250
+ /* @__PURE__ */ jsx(Field.Error, {})
1251
+ ] })
1252
+ }
1253
+ ),
1254
+ /* @__PURE__ */ jsx(
1255
+ Grid.Item,
1256
+ {
1257
+ col: 6,
1258
+ xs: 12,
1259
+ s: 12,
1260
+ m: 6,
1261
+ direction: "column",
1262
+ alignItems: "stretch",
1263
+ minWidth: 0,
1264
+ children: /* @__PURE__ */ jsxs(
1265
+ Field.Root,
1266
+ {
1267
+ name: "displayFields",
1268
+ error: err("displayFields"),
1269
+ hint: t("settings.blocks.form.displayFieldsHint", "Stored with the block."),
1270
+ children: [
1271
+ /* @__PURE__ */ jsx(Field.Label, { children: t("settings.blocks.form.displayFields", "Stored fields") }),
1272
+ /* @__PURE__ */ jsx(
1273
+ MultiSelect,
1274
+ {
1275
+ value: values.displayFields,
1276
+ withTags: true,
1277
+ onChange: (value) => set({ displayFields: value }),
1278
+ children: attributeOptions.map((name) => /* @__PURE__ */ jsx(MultiSelectOption, { value: name, children: name }, name))
1279
+ }
1280
+ ),
1281
+ /* @__PURE__ */ jsx(Field.Hint, {}),
1282
+ /* @__PURE__ */ jsx(Field.Error, {})
1283
+ ]
1284
+ }
1285
+ )
1286
+ }
1287
+ ),
1288
+ /* @__PURE__ */ jsx(
1289
+ Grid.Item,
1290
+ {
1291
+ col: 6,
1292
+ xs: 12,
1293
+ s: 12,
1294
+ m: 6,
1295
+ direction: "column",
1296
+ alignItems: "stretch",
1297
+ minWidth: 0,
1298
+ children: /* @__PURE__ */ jsxs(
1299
+ Field.Root,
1300
+ {
1301
+ name: "previewFields",
1302
+ error: err("previewFields"),
1303
+ hint: t("settings.blocks.form.previewFieldsHint", "Shown in the editor card."),
1304
+ children: [
1305
+ /* @__PURE__ */ jsx(Field.Label, { children: t("settings.blocks.form.previewFields", "Preview fields") }),
1306
+ /* @__PURE__ */ jsx(
1307
+ MultiSelect,
1308
+ {
1309
+ value: values.previewFields,
1310
+ withTags: true,
1311
+ onChange: (value) => set({ previewFields: value }),
1312
+ children: attributeOptions.map((name) => /* @__PURE__ */ jsx(MultiSelectOption, { value: name, children: name }, name))
1313
+ }
1314
+ ),
1315
+ /* @__PURE__ */ jsx(Field.Hint, {}),
1316
+ /* @__PURE__ */ jsx(Field.Error, {})
1317
+ ]
1318
+ }
1319
+ )
1320
+ }
1321
+ )
1322
+ ] })
1323
+ ] }),
1324
+ /* @__PURE__ */ jsx(Divider, {}),
1325
+ /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 4, children: [
1326
+ /* @__PURE__ */ jsx(SubHeading, { title: t("settings.blocks.modal.advanced", "Advanced") }),
1327
+ /* @__PURE__ */ jsxs(Flex, { gap: 3, alignItems: "center", children: [
1328
+ /* @__PURE__ */ jsx(
1329
+ Switch,
1330
+ {
1331
+ checked: values.inlineToolbar,
1332
+ onCheckedChange: (checked) => set({ inlineToolbar: checked === true }),
1333
+ "aria-label": t(
1334
+ "settings.blocks.form.inlineToolbar",
1335
+ "Allow text formatting (inline toolbar)"
1336
+ ),
1337
+ onLabel: t("settings.switch.on", "On"),
1338
+ offLabel: t("settings.switch.off", "Off")
1339
+ }
1340
+ ),
1341
+ /* @__PURE__ */ jsx(Typography, { variant: "omega", textColor: "neutral800", children: t("settings.blocks.form.inlineToolbar", "Allow text formatting (inline toolbar)") })
1342
+ ] }),
1343
+ /* @__PURE__ */ jsxs(Box, { tag: "fieldset", margin: 0, padding: 0, borderWidth: 0, children: [
1344
+ /* @__PURE__ */ jsx(Typography, { variant: "pi", fontWeight: "bold", textColor: "neutral800", tag: "legend", children: t("settings.blocks.form.tunes", "Block settings") }),
1345
+ /* @__PURE__ */ jsx(Flex, { gap: 4, wrap: "wrap", paddingTop: 2, children: TUNES.map((tune) => /* @__PURE__ */ jsx(
1346
+ Checkbox,
1347
+ {
1348
+ checked: values.tunes.includes(tune),
1349
+ onCheckedChange: (checked) => set({
1350
+ tunes: checked === true ? [...values.tunes, tune] : values.tunes.filter((item) => item !== tune)
1351
+ }),
1352
+ children: {
1353
+ alignmentTune: t("settings.blocks.tune.alignment", "Alignment"),
1354
+ textVariant: t("settings.blocks.tune.textVariant", "Text variant"),
1355
+ indentTune: t("settings.blocks.tune.indent", "Indent")
1356
+ }[tune]
1357
+ },
1358
+ tune
1359
+ )) })
1360
+ ] }),
1361
+ /* @__PURE__ */ jsxs(
1362
+ Field.Root,
1363
+ {
1364
+ name: "shortcut",
1365
+ error: err("shortcut"),
1366
+ hint: t("settings.blocks.form.shortcutHint", "Optional, for example CMD+SHIFT+K."),
1367
+ children: [
1368
+ /* @__PURE__ */ jsx(Field.Label, { children: t("settings.blocks.form.shortcut", "Keyboard shortcut") }),
1369
+ /* @__PURE__ */ jsx(
1370
+ TextInput,
1371
+ {
1372
+ value: values.shortcut,
1373
+ onChange: (event) => set({ shortcut: event.target.value })
1374
+ }
1375
+ ),
1376
+ /* @__PURE__ */ jsx(Field.Hint, {}),
1377
+ /* @__PURE__ */ jsx(Field.Error, {})
1378
+ ]
1379
+ }
1380
+ )
1381
+ ] })
1382
+ ] }) }),
1383
+ /* @__PURE__ */ jsxs(Modal.Footer, { children: [
1384
+ /* @__PURE__ */ jsx(Modal.Close, { children: /* @__PURE__ */ jsx(Button, { variant: "tertiary", disabled: saving, children: t("settings.cancel", "Cancel") }) }),
1385
+ /* @__PURE__ */ jsx(Button, { onClick: submit, loading: saving, disabled: saving, children: block ? t("settings.blocks.modal.save", "Save block") : t("settings.blocks.modal.create", "Create block") })
1386
+ ] })
1387
+ ] })
1388
+ }
1389
+ );
1390
+ };
1391
+ const CustomBlocksPage = () => {
1392
+ const t = useT();
1393
+ const { post, put, del, get } = useFetchClient();
1394
+ const { toggleNotification } = useNotification();
1395
+ const { allowedActions, isLoading: rbacLoading } = useRBAC(PERMISSIONS.customBlocksManage);
1396
+ const data = useCustomBlocks();
1397
+ const [modal, setModal] = useState({ open: false, block: null, key: 0 });
1398
+ const [busyId, setBusyId] = useState(null);
1399
+ const [exporting, setExporting] = useState(false);
1400
+ const [importing, setImporting] = useState(false);
1401
+ const [importReport, setImportReport] = useState(null);
1402
+ const createRef = useRef(null);
1403
+ const fileRef = useRef(null);
1404
+ const title = t("settings.blocks.title", "Custom blocks");
1405
+ const otherNames = useMemo(
1406
+ () => data.blocks.filter((block) => !modal.block || block.id !== modal.block.id).map((block) => block.name),
1407
+ [data.blocks, modal.block]
1408
+ );
1409
+ if (rbacLoading || data.status === "loading") {
1410
+ return /* @__PURE__ */ jsxs(Page.Main, { children: [
1411
+ /* @__PURE__ */ jsx(Page.Title, { children: title }),
1412
+ /* @__PURE__ */ jsx(Page.Loading, {})
1413
+ ] });
1414
+ }
1415
+ if (!allowedActions.canManage) {
1416
+ return /* @__PURE__ */ jsxs(Page.Main, { children: [
1417
+ /* @__PURE__ */ jsx(Page.Title, { children: title }),
1418
+ /* @__PURE__ */ jsx(Page.NoPermissions, {})
1419
+ ] });
1420
+ }
1421
+ if (data.status === "error") {
1422
+ return /* @__PURE__ */ jsxs(Page.Main, { children: [
1423
+ /* @__PURE__ */ jsx(Page.Title, { children: title }),
1424
+ /* @__PURE__ */ jsx(
1425
+ Page.Error,
1426
+ {
1427
+ content: t("settings.blocks.loadError", "The custom blocks could not be loaded."),
1428
+ action: /* @__PURE__ */ jsx(Button, { variant: "secondary", onClick: data.reload, children: t("settings.retry", "Try again") })
1429
+ }
1430
+ )
1431
+ ] });
1432
+ }
1433
+ const failed = (error, fallback) => {
1434
+ const info = readApiError(error);
1435
+ toggleNotification({
1436
+ type: "danger",
1437
+ message: info.status === 404 ? t("settings.blocks.notFound", "This block no longer exists.") : fallback
1438
+ });
1439
+ };
1440
+ const onSubmit = async (values) => {
1441
+ const payload = toPayload(values);
1442
+ try {
1443
+ if (modal.block) await put(API.customBlock(modal.block.id), payload);
1444
+ else await post(API.customBlocks, payload);
1445
+ toggleNotification({
1446
+ type: "success",
1447
+ message: modal.block ? t("settings.blocks.saved", "Block {label} saved.", { label: payload.label }) : t("settings.blocks.created", "Block {label} created.", { label: payload.label })
1448
+ });
1449
+ setModal((current) => ({ ...current, open: false, block: null }));
1450
+ await data.reload();
1451
+ return { ok: true };
1452
+ } catch (error) {
1453
+ const info = readApiError(error);
1454
+ if (info.status === 400) {
1455
+ toggleNotification({
1456
+ type: "warning",
1457
+ message: t(
1458
+ "settings.blocks.rejected",
1459
+ "The server rejected some values. They are marked in the form."
1460
+ )
1461
+ });
1462
+ return { ok: false, errors: mapServerErrors(info.details) };
1463
+ }
1464
+ failed(
1465
+ error,
1466
+ t("settings.blocks.saveError", "The block could not be saved. Your changes are still in the form.")
1467
+ );
1468
+ return { ok: false };
1469
+ }
1470
+ };
1471
+ const onToggle = async (block, enabled) => {
1472
+ setBusyId(block.id);
1473
+ try {
1474
+ const { data: response } = await put(API.customBlock(block.id), withEnabled(block, enabled));
1475
+ data.setBlocks((current) => current.map((item) => item.id === block.id ? response.data : item));
1476
+ toggleNotification({
1477
+ type: "success",
1478
+ message: enabled ? t("settings.blocks.enabled", "Block {label} is shown in the toolbox.", { label: block.label }) : t("settings.blocks.disabled", "Block {label} is hidden from the toolbox.", {
1479
+ label: block.label
1480
+ })
1481
+ });
1482
+ } catch (error) {
1483
+ const info = readApiError(error);
1484
+ if (info.status === 400) {
1485
+ toggleNotification({
1486
+ type: "warning",
1487
+ message: t(
1488
+ "settings.blocks.toggleInvalid",
1489
+ "Block {label} has invalid settings. Edit it to fix them first.",
1490
+ { label: block.label }
1491
+ )
1492
+ });
1493
+ } else failed(error, t("settings.blocks.toggleError", "The block could not be updated."));
1494
+ } finally {
1495
+ setBusyId(null);
1496
+ }
1497
+ };
1498
+ const onDuplicate = async (block) => {
1499
+ setBusyId(block.id);
1500
+ try {
1501
+ const { data: response } = await post(API.customBlockDuplicate(block.id), {});
1502
+ toggleNotification({
1503
+ type: "success",
1504
+ message: t("settings.blocks.duplicated", "Copy {label} created.", { label: response.data.label })
1505
+ });
1506
+ await data.reload();
1507
+ } catch (error) {
1508
+ failed(error, t("settings.blocks.duplicateError", "The block could not be duplicated."));
1509
+ } finally {
1510
+ setBusyId(null);
1511
+ }
1512
+ };
1513
+ const onMove = async (block, direction) => {
1514
+ const ids = moveId(
1515
+ data.blocks.map((item) => item.id),
1516
+ block.id,
1517
+ direction
1518
+ );
1519
+ if (!ids) return;
1520
+ const opener = typeof document !== "undefined" ? document.activeElement : null;
1521
+ setBusyId(block.id);
1522
+ try {
1523
+ const { data: response } = await put(API.customBlocksOrder, { ids });
1524
+ data.setBlocks(response.data);
1525
+ } catch (error) {
1526
+ failed(error, t("settings.blocks.moveError", "The order could not be saved."));
1527
+ } finally {
1528
+ setBusyId(null);
1529
+ requestAnimationFrame(() => refocusIfLost(opener, createRef.current));
1530
+ }
1531
+ };
1532
+ const onDelete = async (block) => {
1533
+ try {
1534
+ await del(API.customBlock(block.id));
1535
+ toggleNotification({
1536
+ type: "success",
1537
+ message: t("settings.blocks.deleted", "Block {label} deleted.", { label: block.label })
1538
+ });
1539
+ data.setBlocks((current) => current.filter((item) => item.id !== block.id));
1540
+ } catch (error) {
1541
+ failed(error, t("settings.blocks.deleteError", "The block could not be deleted."));
1542
+ throw error;
1543
+ }
1544
+ };
1545
+ const onExport = async () => {
1546
+ setExporting(true);
1547
+ try {
1548
+ const { data: response } = await get(API.customBlocksExport);
1549
+ const blob = new Blob([JSON.stringify(response.data, null, 2)], { type: "application/json" });
1550
+ const url = URL.createObjectURL(blob);
1551
+ const link = document.createElement("a");
1552
+ link.href = url;
1553
+ link.download = "magic-editor-x-custom-blocks.json";
1554
+ document.body.appendChild(link);
1555
+ link.click();
1556
+ link.remove();
1557
+ setTimeout(() => URL.revokeObjectURL(url), 1e3);
1558
+ toggleNotification({
1559
+ type: "success",
1560
+ message: t("settings.blocks.exported", "Exported {count, plural, one {# block} other {# blocks}}.", {
1561
+ count: response.data.blocks.length
1562
+ })
1563
+ });
1564
+ } catch (error) {
1565
+ failed(error, t("settings.blocks.exportError", "The export could not be created."));
1566
+ } finally {
1567
+ setExporting(false);
1568
+ }
1569
+ };
1570
+ const onImportFile = async (event) => {
1571
+ const input = event.target;
1572
+ const file = input.files && input.files[0];
1573
+ input.value = "";
1574
+ if (!file) return;
1575
+ setImporting(true);
1576
+ try {
1577
+ let parsed;
1578
+ try {
1579
+ parsed = JSON.parse(await file.text());
1580
+ } catch {
1581
+ toggleNotification({
1582
+ type: "danger",
1583
+ message: t("settings.blocks.importInvalidFile", "The file is not valid JSON.")
1584
+ });
1585
+ return;
1586
+ }
1587
+ const { data: response } = await post(API.customBlocksImport, parsed);
1588
+ const { created, skipped } = response.data;
1589
+ setImportReport({ created, skipped });
1590
+ toggleNotification({
1591
+ type: created.length ? "success" : "warning",
1592
+ message: t("settings.blocks.imported", "Import finished: {created} created, {skipped} skipped.", {
1593
+ created: created.length,
1594
+ skipped: skipped.length
1595
+ })
1596
+ });
1597
+ await data.reload();
1598
+ } catch (error) {
1599
+ const info = readApiError(error);
1600
+ toggleNotification({
1601
+ type: "danger",
1602
+ message: info.status === 400 ? t("settings.blocks.importRejected", "The file is not a Magic Editor X custom block export.") : t("settings.blocks.importError", "The import failed. Nothing was imported.")
1603
+ });
1604
+ } finally {
1605
+ setImporting(false);
1606
+ }
1607
+ };
1608
+ const createButton = /* @__PURE__ */ jsx(
1609
+ Button,
1610
+ {
1611
+ ref: createRef,
1612
+ startIcon: /* @__PURE__ */ jsx(Plus, {}),
1613
+ onClick: () => setModal((current) => ({ open: true, block: null, key: current.key + 1 })),
1614
+ children: t("settings.blocks.create", "Create block")
1615
+ }
1616
+ );
1617
+ return /* @__PURE__ */ jsxs(
1618
+ PageShell,
1619
+ {
1620
+ title,
1621
+ subtitle: t(
1622
+ "settings.blocks.subtitle",
1623
+ "Define your own blocks for the editor toolbox: simple blocks with fields and an HTML layout, or blocks that embed a Content Manager entry."
1624
+ ),
1625
+ primaryAction: createButton,
1626
+ secondaryAction: /* @__PURE__ */ jsxs(Flex, { gap: 2, wrap: "wrap", children: [
1627
+ /* @__PURE__ */ jsx(
1628
+ Button,
1629
+ {
1630
+ variant: "tertiary",
1631
+ startIcon: /* @__PURE__ */ jsx(Upload, {}),
1632
+ loading: importing,
1633
+ disabled: importing,
1634
+ onClick: () => fileRef.current && fileRef.current.click(),
1635
+ children: t("settings.blocks.import", "Import")
1636
+ }
1637
+ ),
1638
+ /* @__PURE__ */ jsx(
1639
+ Button,
1640
+ {
1641
+ variant: "tertiary",
1642
+ startIcon: /* @__PURE__ */ jsx(Download, {}),
1643
+ loading: exporting,
1644
+ disabled: exporting || data.blocks.length === 0,
1645
+ onClick: onExport,
1646
+ children: t("settings.blocks.export", "Export")
1647
+ }
1648
+ ),
1649
+ /* @__PURE__ */ jsx(
1650
+ "input",
1651
+ {
1652
+ ref: fileRef,
1653
+ type: "file",
1654
+ accept: "application/json,.json",
1655
+ hidden: true,
1656
+ "aria-label": t("settings.blocks.importFile", "Custom block export file"),
1657
+ onChange: onImportFile
1658
+ }
1659
+ )
1660
+ ] }),
1661
+ children: [
1662
+ data.refreshError ? /* @__PURE__ */ jsx(
1663
+ Alert,
1664
+ {
1665
+ variant: "danger",
1666
+ closeLabel: t("settings.close", "Close"),
1667
+ action: /* @__PURE__ */ jsx(Button, { variant: "tertiary", size: "S", onClick: data.reload, children: t("settings.retry", "Try again") }),
1668
+ children: t(
1669
+ "settings.blocks.refreshError",
1670
+ "The list could not be refreshed. It shows the last loaded state."
1671
+ )
1672
+ }
1673
+ ) : null,
1674
+ importReport && importReport.skipped.length ? /* @__PURE__ */ jsx(
1675
+ Alert,
1676
+ {
1677
+ variant: "warning",
1678
+ closeLabel: t("settings.close", "Close"),
1679
+ onClose: () => setImportReport(null),
1680
+ title: t("settings.blocks.importSkippedTitle", "Some blocks were not imported"),
1681
+ children: /* @__PURE__ */ jsx(Box, { tag: "ul", paddingTop: 1, children: importReport.skipped.map((entry, index) => /* @__PURE__ */ jsx(Typography, { tag: "li", variant: "pi", textColor: "neutral800", children: entry.reason === "exists" ? t(
1682
+ "settings.blocks.importSkippedExists",
1683
+ "{name}: a block with this name already exists.",
1684
+ { name: entry.name || "?" }
1685
+ ) : t("settings.blocks.importSkippedInvalid", "{name}: the definition is not valid.", {
1686
+ name: entry.name || "?"
1687
+ }) }, `${entry.name}-${index}`)) })
1688
+ }
1689
+ ) : null,
1690
+ data.blocks.length === 0 ? /* @__PURE__ */ jsx(SectionCard, { children: /* @__PURE__ */ jsx(
1691
+ EmptyStateLayout,
1692
+ {
1693
+ icon: /* @__PURE__ */ jsx(EmptyDocuments, { width: "16rem", height: "8.8rem" }),
1694
+ content: t(
1695
+ "settings.blocks.empty",
1696
+ "No custom blocks yet. Blocks you create here appear in the editor toolbox of every Magic Editor X field."
1697
+ ),
1698
+ action: /* @__PURE__ */ jsx(
1699
+ Button,
1700
+ {
1701
+ variant: "secondary",
1702
+ startIcon: /* @__PURE__ */ jsx(Plus, {}),
1703
+ onClick: () => setModal((current) => ({ open: true, block: null, key: current.key + 1 })),
1704
+ children: t("settings.blocks.create", "Create block")
1705
+ }
1706
+ )
1707
+ }
1708
+ ) }) : /* @__PURE__ */ jsx(
1709
+ BlockList,
1710
+ {
1711
+ blocks: data.blocks,
1712
+ busyId,
1713
+ onEdit: (block) => setModal((current) => ({ open: true, block, key: current.key + 1 })),
1714
+ onDuplicate,
1715
+ onMove,
1716
+ onDelete,
1717
+ onToggle,
1718
+ fallbackFocusRef: createRef
1719
+ }
1720
+ ),
1721
+ /* @__PURE__ */ jsx(
1722
+ BlockFormModal,
1723
+ {
1724
+ open: modal.open,
1725
+ block: modal.block,
1726
+ otherNames,
1727
+ contentTypes: data.contentTypes,
1728
+ onRetryContentTypes: data.reloadContentTypes,
1729
+ onSubmit,
1730
+ onClose: () => setModal((current) => ({ ...current, open: false, block: null }))
1731
+ },
1732
+ modal.key
1733
+ )
1734
+ ]
1735
+ }
1736
+ );
1737
+ };
1738
+ export {
1739
+ CustomBlocksPage,
1740
+ CustomBlocksPage as default
1741
+ };