magic-editor-x 2.2.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/CHANGELOG.md +72 -0
  2. package/README.md +493 -168
  3. package/dist/admin/{ConfigurationPage-3Dir3dAf.mjs → ConfigurationPage-BxLHIQdo.mjs} +450 -21
  4. package/dist/admin/{ConfigurationPage-YvnPnna6.js → ConfigurationPage-C-UktL1x.js} +479 -50
  5. package/dist/admin/ConfirmAction-DuQwvRYi.mjs +125 -0
  6. package/dist/admin/ConfirmAction-zLuIFj8t.js +124 -0
  7. package/dist/admin/{CustomBlocksPage-BiiL2ORG.js → CustomBlocksPage-CxcTfdOT.js} +135 -84
  8. package/dist/admin/{CustomBlocksPage-CR2BaP9O.mjs → CustomBlocksPage-D8aMbVXc.mjs} +92 -41
  9. package/dist/admin/DraftSync-BIA8cZgA.js +11 -0
  10. package/dist/admin/DraftSync-CUxOMG-E.mjs +12 -0
  11. package/dist/admin/TemplatesPage-Hn6gyu2l.js +993 -0
  12. package/dist/admin/TemplatesPage-jhYi6Zdf.mjs +993 -0
  13. package/dist/admin/{de-BmmLBJli.mjs → de-1cFMs-4c.mjs} +2 -0
  14. package/dist/admin/{de-BteRx2iA.js → de-2Ie5jy7j.js} +79 -1
  15. package/dist/admin/{de-62Vxb2iw.js → de-B1X46JJZ.js} +205 -2
  16. package/dist/admin/{de-CFX5atOk.mjs → de-BMY2LBaa.mjs} +79 -1
  17. package/dist/admin/{de-Bt6pYIWi.mjs → de-BUS1hUw0.mjs} +145 -0
  18. package/dist/admin/{de-CVbi685U.js → de-C3AsGauQ.js} +145 -0
  19. package/dist/admin/{de-BVvwSYYO.mjs → de-DOiGaTNX.mjs} +205 -2
  20. package/dist/admin/{de-DaJwN6nk.js → de-Dn8athM8.js} +2 -0
  21. package/dist/admin/{en-CyjAcccB.js → en-Ah-Cw0Wd.js} +79 -1
  22. package/dist/admin/{en-BX362fTp.js → en-BkEjpC3i.js} +145 -0
  23. package/dist/admin/{en-VlkaIzrM.js → en-CDg_18Bt.js} +205 -2
  24. package/dist/admin/{en-Cn78RZs-.js → en-CIZ5Ggod.js} +2 -0
  25. package/dist/admin/{en-Cg2Ak5Cr.mjs → en-CU6UzV4g.mjs} +205 -2
  26. package/dist/admin/{en-ea0tfA5i.mjs → en-CvFiqti2.mjs} +79 -1
  27. package/dist/admin/{en-D7mZWLGp.mjs → en-Dc9y-6n9.mjs} +2 -0
  28. package/dist/admin/{en-B_HltUxZ.mjs → en-GCzgS9Aw.mjs} +145 -0
  29. package/dist/admin/{es-BT9oAcHf.js → es-BCpJmUEM.js} +205 -2
  30. package/dist/admin/{es-C9-cXdb6.mjs → es-BmfffNM2.mjs} +205 -2
  31. package/dist/admin/{es-BmGtLkJD.js → es-C4IRHV5d.js} +2 -0
  32. package/dist/admin/{es-CHHEZi44.js → es-C4pEnDRv.js} +145 -0
  33. package/dist/admin/{es-C8GZFGjv.js → es-Cr8JH85N.js} +79 -1
  34. package/dist/admin/{es-joykG5I9.mjs → es-D2Kw6E4N.mjs} +2 -0
  35. package/dist/admin/{es-CrhwOq-5.mjs → es-DHBBZKl2.mjs} +145 -0
  36. package/dist/admin/{es-CEi_ycX8.mjs → es-DbKHZz5l.mjs} +79 -1
  37. package/dist/admin/{fr-CrzxGe5e.mjs → fr-BOvvfEH7.mjs} +2 -0
  38. package/dist/admin/{fr-B3SL0TBV.js → fr-C2aLSwEu.js} +145 -0
  39. package/dist/admin/{fr-BAMSvQbR.mjs → fr-DQJ_7aq5.mjs} +79 -1
  40. package/dist/admin/{fr-DpU_qiXR.mjs → fr-DZd2XJP6.mjs} +205 -2
  41. package/dist/admin/{fr-5djKfQ3s.mjs → fr-Dvq4xk2e.mjs} +145 -0
  42. package/dist/admin/{fr-oRCJNdeJ.js → fr-OJ4VW1kh.js} +79 -1
  43. package/dist/admin/{fr-D6KJqPWi.js → fr-ZcN0yM_2.js} +205 -2
  44. package/dist/admin/{fr-Ct_uPqxV.js → fr-Zkb8vfjN.js} +2 -0
  45. package/dist/admin/index-BHBRr562.js +1940 -0
  46. package/dist/admin/index-CQk1XeNb.mjs +1939 -0
  47. package/dist/admin/{EditorField-Diq1j8kc.js → index-Cm-fFUhE.js} +13704 -6766
  48. package/dist/admin/{EditorField-B8pyAxPE.mjs → index-XgfwqLfV.mjs} +10203 -3265
  49. package/dist/admin/index.js +1 -1
  50. package/dist/admin/index.mjs +2 -2
  51. package/dist/admin/{pt-chN2jrXl.js → pt-1IUyx6ae.js} +2 -0
  52. package/dist/admin/{pt-CQrfqsCN.mjs → pt-BSLzA17U.mjs} +79 -1
  53. package/dist/admin/{pt-jUqOR7Xh.mjs → pt-C3UdeIpd.mjs} +205 -2
  54. package/dist/admin/{pt-BOrl6x-r.js → pt-CImqDnLB.js} +205 -2
  55. package/dist/admin/{pt-BdnY2Cth.mjs → pt-CilDggGF.mjs} +145 -0
  56. package/dist/admin/{pt-tUeJ2Ywd.js → pt-D0I0_JYs.js} +79 -1
  57. package/dist/admin/{pt-EVwCuBUK.js → pt-DX0OAIoL.js} +145 -0
  58. package/dist/admin/{pt-Ga-4Hsv0.mjs → pt-etwsg3G4.mjs} +2 -0
  59. package/dist/admin/useBreakpoint-D30eNTkF.js +37 -0
  60. package/dist/admin/useBreakpoint-DCfn6pDG.mjs +38 -0
  61. package/dist/admin/useT-CmaeZbCr.mjs +65 -0
  62. package/dist/admin/{useT-BWZ_-Hel.js → useT-D3sM9Zf7.js} +4 -70
  63. package/dist/blocks/index.d.mts +167 -0
  64. package/dist/blocks/index.d.ts +167 -0
  65. package/dist/blocks/index.js +631 -0
  66. package/dist/blocks/index.mjs +609 -0
  67. package/dist/react/index.d.mts +39 -0
  68. package/dist/react/index.d.ts +39 -0
  69. package/dist/react/index.js +2687 -0
  70. package/dist/react/index.mjs +2657 -0
  71. package/dist/render/index.d.mts +131 -5
  72. package/dist/render/index.d.ts +131 -5
  73. package/dist/render/index.js +1679 -181
  74. package/dist/render/index.mjs +1679 -181
  75. package/dist/server/index.js +10645 -3716
  76. package/dist/server/index.mjs +10645 -3716
  77. package/dist/vue/index.d.mts +41 -0
  78. package/dist/vue/index.d.ts +41 -0
  79. package/dist/vue/index.js +2630 -0
  80. package/dist/vue/index.mjs +2610 -0
  81. package/package.json +30 -6
  82. package/schema/magic-editor-x.schema.json +540 -1
  83. package/types/blocks.d.ts +167 -0
  84. package/types/index.d.ts +127 -0
  85. package/types/react.d.ts +39 -0
  86. package/types/render.d.ts +131 -5
  87. package/types/vue.d.ts +41 -0
  88. package/dist/admin/api-Dsq53giv.js +0 -37
  89. package/dist/admin/api-RZ0Fz0BD.mjs +0 -38
  90. package/dist/admin/index-C-lyON1B.mjs +0 -303
  91. package/dist/admin/index-iA0lued_.js +0 -302
  92. package/dist/admin/sanitize-Cb4jvBhj.js +0 -628
  93. package/dist/admin/sanitize-ClkX823p.mjs +0 -627
  94. package/dist/admin/useT-pvHmgBFj.mjs +0 -131
@@ -0,0 +1,993 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const jsxRuntime = require("react/jsx-runtime");
4
+ const ReactNamespace = require("react");
5
+ const reactRouterDom = require("react-router-dom");
6
+ const designSystem = require("@strapi/design-system");
7
+ const icons = require("@strapi/icons");
8
+ const symbols = require("@strapi/icons/symbols");
9
+ const admin = require("@strapi/strapi/admin");
10
+ const index$1 = require("./index-BHBRr562.js");
11
+ const ConfirmAction = require("./ConfirmAction-zLuIFj8t.js");
12
+ const useT = require("./useT-D3sM9Zf7.js");
13
+ require("styled-components");
14
+ const index = require("./index-Cm-fFUhE.js");
15
+ const useBreakpoint = require("./useBreakpoint-D30eNTkF.js");
16
+ const DraftSync = require("./DraftSync-BIA8cZgA.js");
17
+ const fieldKey = (entry) => `${entry.uid}|${entry.field}`;
18
+ const fieldFromKey = (key) => {
19
+ const [uid, field] = String(key).split("|");
20
+ return { uid, field };
21
+ };
22
+ const emptyValues = () => ({
23
+ name: "",
24
+ description: "",
25
+ kind: "template",
26
+ enabled: true,
27
+ scopeMode: "all",
28
+ presets: [],
29
+ fields: [],
30
+ blocks: null
31
+ });
32
+ const fromDto = (dto) => {
33
+ const scope = index.normalizeScope(dto.scope);
34
+ return {
35
+ name: dto.name || "",
36
+ description: dto.description || "",
37
+ kind: dto.kind === "pattern" || dto.kind === "synced" ? dto.kind : "template",
38
+ enabled: dto.enabled !== false,
39
+ scopeMode: scope.all ? "all" : "limited",
40
+ presets: scope.presets,
41
+ fields: scope.fields.map(fieldKey),
42
+ blocks: dto.blocks && Array.isArray(dto.blocks.blocks) ? dto.blocks : null
43
+ };
44
+ };
45
+ const validateTemplate = (values) => {
46
+ const errors = {};
47
+ const name = String(values.name || "").trim();
48
+ if (!name) errors.name = "required";
49
+ else if (name.length > index.TEMPLATE_LIMITS.name) errors.name = "tooLong";
50
+ if (String(values.description || "").trim().length > index.TEMPLATE_LIMITS.description)
51
+ errors.description = "tooLong";
52
+ if (values.scopeMode === "limited" && !values.presets.length && !values.fields.length)
53
+ errors.scope = "scope";
54
+ if (index.isEmptyDocument(values.blocks)) errors.blocks = "content";
55
+ else if (values.blocks.blocks.length > index.TEMPLATE_LIMITS.blocks) errors.blocks = "tooManyBlocks";
56
+ else if (values.kind === "synced" && index.containsSynced(values.blocks.blocks)) errors.blocks = "nestedSynced";
57
+ return errors;
58
+ };
59
+ const toPayload = (values) => ({
60
+ name: String(values.name).trim(),
61
+ description: String(values.description || "").trim() || null,
62
+ kind: values.kind,
63
+ enabled: values.enabled !== false,
64
+ blocks: values.blocks,
65
+ scope: values.scopeMode === "all" ? { all: true } : { all: false, presets: [...values.presets], fields: values.fields.map(fieldFromKey) }
66
+ });
67
+ const withEnabled = (dto, enabled) => ({ ...toPayload(fromDto(dto)), enabled });
68
+ const mapServerErrors = (details) => {
69
+ const out = {};
70
+ const fieldErrors = details && typeof details === "object" ? details.fieldErrors || {} : {};
71
+ for (const [key, messages] of Object.entries(fieldErrors)) {
72
+ const message = Array.isArray(messages) ? messages[0] : String(messages || "");
73
+ const field = key.split(".")[0];
74
+ if (message && !out[field]) out[field] = message;
75
+ }
76
+ const formErrors = details && Array.isArray(details.formErrors) ? details.formErrors : [];
77
+ if (formErrors[0]) out._form = formErrors[0];
78
+ return out;
79
+ };
80
+ const moveWithin = (ids, visibleIds, id, direction) => {
81
+ const at = visibleIds.indexOf(id);
82
+ const neighbour = visibleIds[at + direction];
83
+ if (at < 0 || neighbour === void 0) return null;
84
+ const next = [...ids];
85
+ const a = next.indexOf(id);
86
+ const b = next.indexOf(neighbour);
87
+ if (a < 0 || b < 0) return null;
88
+ next[a] = neighbour;
89
+ next[b] = id;
90
+ return next;
91
+ };
92
+ const KIND_FILTERS = Object.freeze(["all", "template", "pattern", "synced"]);
93
+ const filterByKind = (templates, filter) => filter && filter !== "all" ? templates.filter((template) => template.kind === filter) : templates;
94
+ const valuesKey = (values) => JSON.stringify({
95
+ ...values,
96
+ blocks: values.blocks && Array.isArray(values.blocks.blocks) ? values.blocks.blocks : null
97
+ });
98
+ const useTemplateList = () => {
99
+ const { get } = admin.useFetchClient();
100
+ const [status, setStatus] = ReactNamespace.useState("loading");
101
+ const [templates, setTemplates] = ReactNamespace.useState([]);
102
+ const [refreshError, setRefreshError] = ReactNamespace.useState(false);
103
+ const [targets, setTargets] = ReactNamespace.useState({ status: "loading", items: [] });
104
+ const mounted = ReactNamespace.useRef(true);
105
+ const loaded = ReactNamespace.useRef(false);
106
+ ReactNamespace.useEffect(() => {
107
+ mounted.current = true;
108
+ return () => {
109
+ mounted.current = false;
110
+ };
111
+ }, []);
112
+ const fetchTemplates = ReactNamespace.useCallback(
113
+ () => get(ConfirmAction.API.templates, { params: { all: "true" } }).then(
114
+ ({ data }) => {
115
+ if (!mounted.current) return;
116
+ setTemplates(Array.isArray(data.data) ? data.data : []);
117
+ setRefreshError(false);
118
+ loaded.current = true;
119
+ setStatus("ready");
120
+ },
121
+ () => {
122
+ if (!mounted.current) return;
123
+ if (loaded.current) setRefreshError(true);
124
+ else setStatus("error");
125
+ }
126
+ ),
127
+ [get]
128
+ );
129
+ const fetchTargets = ReactNamespace.useCallback(
130
+ () => get(ConfirmAction.API.templateTargets).then(
131
+ ({ data }) => {
132
+ if (mounted.current)
133
+ setTargets({ status: "ready", items: Array.isArray(data.data) ? data.data : [] });
134
+ },
135
+ () => {
136
+ if (mounted.current) setTargets({ status: "error", items: [] });
137
+ }
138
+ ),
139
+ [get]
140
+ );
141
+ ReactNamespace.useEffect(() => {
142
+ fetchTemplates();
143
+ fetchTargets();
144
+ }, [fetchTemplates, fetchTargets]);
145
+ const reload = ReactNamespace.useCallback(() => {
146
+ if (!loaded.current) setStatus("loading");
147
+ return fetchTemplates();
148
+ }, [fetchTemplates]);
149
+ const reloadTargets = ReactNamespace.useCallback(() => {
150
+ setTargets((current) => ({ ...current, status: "loading" }));
151
+ return fetchTargets();
152
+ }, [fetchTargets]);
153
+ return { status, templates, setTemplates, refreshError, reload, targets, reloadTargets };
154
+ };
155
+ const kindLabel = (t, kind) => {
156
+ if (kind === "pattern") return t("settings.templates.kind.pattern", "Pattern");
157
+ if (kind === "synced") return t("settings.templates.kind.synced", "Synced block");
158
+ return t("settings.templates.kind.template", "Template");
159
+ };
160
+ const SyncedUsage = ({ template }) => {
161
+ const t = useT.useT();
162
+ const { get } = admin.useFetchClient();
163
+ const [state, setState] = ReactNamespace.useState({ status: "loading", usage: null });
164
+ ReactNamespace.useEffect(() => {
165
+ const controller = new AbortController();
166
+ get(ConfirmAction.API.templateUsage(template.id), { signal: controller.signal }).then(
167
+ ({ data }) => {
168
+ if (!controller.signal.aborted) setState({ status: "ready", usage: data.data });
169
+ },
170
+ () => {
171
+ if (!controller.signal.aborted) setState({ status: "error", usage: null });
172
+ }
173
+ );
174
+ return () => controller.abort();
175
+ }, [get, template.id]);
176
+ const { status, usage } = state;
177
+ return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "stretch", gap: 2, children: [
178
+ status === "loading" ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Loader, { small: true, children: t("settings.templates.usage.loading", "Counting where it is used") }) : null,
179
+ status === "error" ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { textColor: "danger600", children: t("settings.templates.usage.error", "It could not be counted where this synced block is used.") }) : null,
180
+ status === "ready" ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { textColor: "neutral800", "data-testid": "mex-synced-usage", children: !usage.entries && !usage.templates && usage.complete ? t("settings.templates.usage.none", "It is not used in any entry, template or pattern.") : usage.complete ? t(
181
+ "settings.templates.usage.count",
182
+ "It is used in {entries, plural, one {# entry} other {# entries}} ({fields, plural, one {# field} other {# fields}}) and {templates, plural, one {# template or pattern} other {# templates or patterns}}.",
183
+ usage
184
+ ) : t(
185
+ "settings.templates.usage.countAtLeast",
186
+ "It is used in at least {entries, plural, one {# entry} other {# entries}} ({fields, plural, one {# field} other {# fields}}) and {templates, plural, one {# template or pattern} other {# templates or patterns}}. Not every entry could be checked.",
187
+ usage
188
+ ) }) : null,
189
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { textColor: "neutral800", children: t(
190
+ "settings.templates.delete.syncedBody",
191
+ 'After deleting it, these places show nothing where the synced block was, on the website and in the API. Editors see "Synced block removed". This cannot be undone.'
192
+ ) })
193
+ ] });
194
+ };
195
+ const scopeSummary = (t, scope) => {
196
+ const clean = index.normalizeScope(scope);
197
+ if (clean.all) return t("settings.templates.scope.all", "Every field");
198
+ return t("settings.templates.scope.limited", "Selected presets and fields ({count})", {
199
+ count: clean.presets.length + clean.fields.length
200
+ });
201
+ };
202
+ const RowActions = ({
203
+ template,
204
+ index: index2,
205
+ count,
206
+ busy,
207
+ onPreview,
208
+ onEdit,
209
+ onDuplicate,
210
+ onMove,
211
+ onDelete,
212
+ fallbackFocusRef
213
+ }) => {
214
+ const t = useT.useT();
215
+ const name = template.name;
216
+ return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 1, wrap: "wrap", children: [
217
+ /* @__PURE__ */ jsxRuntime.jsx(
218
+ designSystem.IconButton,
219
+ {
220
+ label: t("settings.templates.action.preview", "Preview {name}", { name }),
221
+ variant: "ghost",
222
+ onClick: () => onPreview(template),
223
+ children: /* @__PURE__ */ jsxRuntime.jsx(icons.Eye, {})
224
+ }
225
+ ),
226
+ /* @__PURE__ */ jsxRuntime.jsx(
227
+ designSystem.IconButton,
228
+ {
229
+ label: t("settings.templates.action.edit", "Edit {name}", { name }),
230
+ variant: "ghost",
231
+ onClick: () => onEdit(template),
232
+ children: /* @__PURE__ */ jsxRuntime.jsx(icons.Pencil, {})
233
+ }
234
+ ),
235
+ /* @__PURE__ */ jsxRuntime.jsx(
236
+ designSystem.IconButton,
237
+ {
238
+ label: t("settings.templates.action.duplicate", "Duplicate {name}", { name }),
239
+ variant: "ghost",
240
+ disabled: busy,
241
+ onClick: () => onDuplicate(template),
242
+ children: /* @__PURE__ */ jsxRuntime.jsx(icons.Duplicate, {})
243
+ }
244
+ ),
245
+ /* @__PURE__ */ jsxRuntime.jsx(
246
+ designSystem.IconButton,
247
+ {
248
+ label: t("settings.templates.action.moveUp", "Move {name} up", { name }),
249
+ variant: "ghost",
250
+ disabled: busy || index2 === 0,
251
+ onClick: () => onMove(template, -1),
252
+ children: /* @__PURE__ */ jsxRuntime.jsx(icons.ArrowUp, {})
253
+ }
254
+ ),
255
+ /* @__PURE__ */ jsxRuntime.jsx(
256
+ designSystem.IconButton,
257
+ {
258
+ label: t("settings.templates.action.moveDown", "Move {name} down", { name }),
259
+ variant: "ghost",
260
+ disabled: busy || index2 === count - 1,
261
+ onClick: () => onMove(template, 1),
262
+ children: /* @__PURE__ */ jsxRuntime.jsx(icons.ArrowDown, {})
263
+ }
264
+ ),
265
+ /* @__PURE__ */ jsxRuntime.jsx(
266
+ ConfirmAction.ConfirmAction,
267
+ {
268
+ fallbackFocusRef,
269
+ trigger: /* @__PURE__ */ jsxRuntime.jsx(
270
+ designSystem.IconButton,
271
+ {
272
+ label: t("settings.templates.action.delete", "Delete {name}", { name }),
273
+ variant: "ghost",
274
+ disabled: busy,
275
+ children: /* @__PURE__ */ jsxRuntime.jsx(icons.Trash, {})
276
+ }
277
+ ),
278
+ title: template.kind === "synced" ? t("settings.templates.delete.syncedTitle", "Delete the synced block {name}?", { name }) : t("settings.templates.delete.title", "Delete the template {name}?", { name }),
279
+ body: template.kind === "synced" ? /* @__PURE__ */ jsxRuntime.jsx(SyncedUsage, { template }) : t(
280
+ "settings.templates.delete.body",
281
+ "Editors can no longer insert it. Content that was created from it stays unchanged. This cannot be undone."
282
+ ),
283
+ confirmLabel: template.kind === "synced" ? t("settings.templates.delete.syncedConfirm", "Delete synced block") : t("settings.templates.delete.confirm", "Delete template"),
284
+ onConfirm: () => onDelete(template)
285
+ }
286
+ )
287
+ ] });
288
+ };
289
+ const EnabledSwitch = ({ template, busy, onToggle }) => {
290
+ const t = useT.useT();
291
+ return /* @__PURE__ */ jsxRuntime.jsx(
292
+ designSystem.Switch,
293
+ {
294
+ checked: template.enabled,
295
+ disabled: busy,
296
+ onCheckedChange: (checked) => onToggle(template, checked === true),
297
+ "aria-label": t("settings.templates.action.toggle", "Offer {name} in the editor", {
298
+ name: template.name
299
+ }),
300
+ onLabel: t("settings.switch.on", "On"),
301
+ offLabel: t("settings.switch.off", "Off"),
302
+ visibleLabels: true
303
+ }
304
+ );
305
+ };
306
+ const Identity = ({ template }) => {
307
+ const t = useT.useT();
308
+ return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "flex-start", gap: 1, minWidth: 0, children: [
309
+ /* @__PURE__ */ jsxRuntime.jsx(
310
+ designSystem.Typography,
311
+ {
312
+ variant: "omega",
313
+ fontWeight: "bold",
314
+ textColor: "neutral800",
315
+ style: { overflowWrap: "anywhere" },
316
+ children: template.name
317
+ }
318
+ ),
319
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral600", style: { overflowWrap: "anywhere" }, children: template.description || t("settings.templates.noDescription", "No description") })
320
+ ] });
321
+ };
322
+ const TemplateList = ({ templates, busyId, onToggle, ...actions }) => {
323
+ const t = useT.useT();
324
+ const { isBelowLarge } = useBreakpoint.useBreakpoint();
325
+ const blocksText = (template) => t("settings.templates.blocks", "{count, plural, one {# block} other {# blocks}}", {
326
+ count: template.blockCount
327
+ });
328
+ if (isBelowLarge) {
329
+ return /* @__PURE__ */ jsxRuntime.jsx(
330
+ designSystem.Flex,
331
+ {
332
+ tag: "ul",
333
+ direction: "column",
334
+ alignItems: "stretch",
335
+ gap: 3,
336
+ "aria-label": t("settings.templates.list.label", "Templates"),
337
+ children: templates.map((template, index2) => /* @__PURE__ */ jsxRuntime.jsx(
338
+ designSystem.Box,
339
+ {
340
+ tag: "li",
341
+ background: "neutral0",
342
+ hasRadius: true,
343
+ shadow: "tableShadow",
344
+ padding: 4,
345
+ minWidth: 0,
346
+ children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "stretch", gap: 3, children: [
347
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { justifyContent: "space-between", alignItems: "flex-start", gap: 3, children: [
348
+ /* @__PURE__ */ jsxRuntime.jsx(Identity, { template }),
349
+ /* @__PURE__ */ jsxRuntime.jsx(EnabledSwitch, { template, busy: busyId === template.id, onToggle })
350
+ ] }),
351
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 2, wrap: "wrap", children: [
352
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Badge, { children: kindLabel(t, template.kind) }),
353
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral600", children: scopeSummary(t, template.scope) }),
354
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral600", children: blocksText(template) })
355
+ ] }),
356
+ /* @__PURE__ */ jsxRuntime.jsx(
357
+ RowActions,
358
+ {
359
+ template,
360
+ index: index2,
361
+ count: templates.length,
362
+ busy: busyId === template.id,
363
+ ...actions
364
+ }
365
+ )
366
+ ] })
367
+ },
368
+ template.id
369
+ ))
370
+ }
371
+ );
372
+ }
373
+ return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Table, { colCount: 5, rowCount: templates.length + 1, children: [
374
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Thead, { children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Tr, { children: [
375
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Th, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", children: t("settings.templates.list.name", "Name") }) }),
376
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Th, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", children: t("settings.templates.list.kind", "Type") }) }),
377
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Th, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", children: t("settings.templates.list.scope", "Offered in") }) }),
378
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Th, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", children: t("settings.templates.list.enabled", "In the editor") }) }),
379
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Th, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.VisuallyHidden, { children: t("settings.templates.list.actions", "Actions") }) })
380
+ ] }) }),
381
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Tbody, { children: templates.map((template, index2) => /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Tr, { children: [
382
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Td, { children: /* @__PURE__ */ jsxRuntime.jsx(Identity, { template }) }),
383
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Td, { children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "flex-start", gap: 1, children: [
384
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Badge, { children: kindLabel(t, template.kind) }),
385
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral600", children: blocksText(template) })
386
+ ] }) }),
387
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Td, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { textColor: "neutral800", children: scopeSummary(t, template.scope) }) }),
388
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Td, { children: /* @__PURE__ */ jsxRuntime.jsx(EnabledSwitch, { template, busy: busyId === template.id, onToggle }) }),
389
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Td, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Flex, { justifyContent: "flex-end", children: /* @__PURE__ */ jsxRuntime.jsx(
390
+ RowActions,
391
+ {
392
+ template,
393
+ index: index2,
394
+ count: templates.length,
395
+ busy: busyId === template.id,
396
+ ...actions
397
+ }
398
+ ) }) })
399
+ ] }, template.id)) })
400
+ ] });
401
+ };
402
+ const EDITOR_TARGET = Object.freeze({
403
+ uid: null,
404
+ documentId: null,
405
+ locale: null,
406
+ field: "mexTemplateContent"
407
+ });
408
+ const EDITOR_ATTRIBUTE = Object.freeze({ options: {} });
409
+ const PRESET_LABELS = {
410
+ full: ["settings.templates.preset.full", "Full"],
411
+ article: ["settings.templates.preset.article", "Article"],
412
+ basic: ["settings.templates.preset.basic", "Basic"],
413
+ minimal: ["settings.templates.preset.minimal", "Minimal"]
414
+ };
415
+ const errorText = (t, code) => {
416
+ if (!code) return void 0;
417
+ if (code === "required") return t("settings.templates.form.nameRequired", "Enter a name.");
418
+ if (code === "tooLong") return t("settings.templates.form.tooLong", "This text is too long.");
419
+ if (code === "scope")
420
+ return t("settings.templates.form.scopeRequired", "Choose at least one preset or field.");
421
+ if (code === "content") return t("settings.templates.form.contentRequired", "Add at least one block.");
422
+ if (code === "nestedSynced")
423
+ return t(
424
+ "settings.templates.form.nestedSynced",
425
+ "A synced block cannot contain another synced block. Remove it or detach it first."
426
+ );
427
+ if (code === "tooManyBlocks")
428
+ return t("settings.templates.form.tooManyBlocks", "A template can have at most {max} blocks.", {
429
+ max: index.TEMPLATE_LIMITS.blocks
430
+ });
431
+ return code;
432
+ };
433
+ const TemplateEditor = ({ template, targets, onRetryTargets, onSubmit, onBack }) => {
434
+ const t = useT.useT();
435
+ const saved = ReactNamespace.useMemo(() => template ? fromDto(template) : emptyValues(), [template]);
436
+ const [values, setValues] = ReactNamespace.useState(saved);
437
+ const [showErrors, setShowErrors] = ReactNamespace.useState(false);
438
+ const [serverErrors, setServerErrors] = ReactNamespace.useState({});
439
+ const [saving, setSaving] = ReactNamespace.useState(false);
440
+ const errors = ReactNamespace.useMemo(() => validateTemplate(values), [values]);
441
+ const visible = { ...showErrors ? errors : {}, ...serverErrors };
442
+ const savedKey = ReactNamespace.useMemo(() => ({ key: valuesKey(saved) }), [saved]);
443
+ const draftKey = ReactNamespace.useMemo(() => ({ key: valuesKey(values) }), [values]);
444
+ const dirty = draftKey.key !== savedKey.key;
445
+ const set = (patch) => {
446
+ setValues((current) => ({ ...current, ...patch }));
447
+ setServerErrors((current) => {
448
+ const next = { ...current };
449
+ Object.keys(patch).forEach((key) => delete next[key]);
450
+ if (patch.presets || patch.fields || patch.scopeMode) delete next.scope;
451
+ delete next._form;
452
+ return next;
453
+ });
454
+ };
455
+ const submit = async () => {
456
+ setShowErrors(true);
457
+ if (Object.keys(errors).length) return;
458
+ setSaving(true);
459
+ try {
460
+ const result = await onSubmit(values);
461
+ if (!result.ok && result.errors) setServerErrors(result.errors);
462
+ } finally {
463
+ setSaving(false);
464
+ }
465
+ };
466
+ const title = template ? t("settings.templates.edit.title", "Edit template {name}", { name: template.name }) : t("settings.templates.edit.createTitle", "Create a template");
467
+ const backButton = /* @__PURE__ */ jsxRuntime.jsx(
468
+ designSystem.Button,
469
+ {
470
+ variant: "tertiary",
471
+ startIcon: /* @__PURE__ */ jsxRuntime.jsx(icons.ArrowLeft, {}),
472
+ disabled: saving,
473
+ onClick: dirty ? void 0 : onBack,
474
+ children: t("settings.templates.edit.back", "Back to templates")
475
+ }
476
+ );
477
+ const presetLabel = (name) => t(PRESET_LABELS[name][0], PRESET_LABELS[name][1]);
478
+ const savedSynced = Boolean(template && template.kind === "synced");
479
+ const fieldOptions = targets.items.map((target) => ({
480
+ key: fieldKey(target),
481
+ label: t("settings.templates.form.fieldOption", "{type}: {field} ({preset})", {
482
+ type: target.displayName,
483
+ field: target.field,
484
+ preset: PRESET_LABELS[target.preset] ? presetLabel(target.preset) : target.preset
485
+ })
486
+ }));
487
+ for (const key of values.fields) {
488
+ if (!fieldOptions.some((option) => option.key === key)) fieldOptions.push({ key, label: key });
489
+ }
490
+ return /* @__PURE__ */ jsxRuntime.jsxs(
491
+ useT.PageShell,
492
+ {
493
+ title,
494
+ subtitle: t(
495
+ "settings.templates.edit.subtitle",
496
+ "Templates are starting content for an empty field. Patterns are groups of blocks editors insert anywhere."
497
+ ),
498
+ primaryAction: /* @__PURE__ */ jsxRuntime.jsx(
499
+ designSystem.Button,
500
+ {
501
+ startIcon: /* @__PURE__ */ jsxRuntime.jsx(icons.Check, {}),
502
+ onClick: submit,
503
+ loading: saving,
504
+ disabled: saving,
505
+ "data-testid": "mex-template-submit",
506
+ children: t("settings.templates.edit.save", "Save template")
507
+ }
508
+ ),
509
+ secondaryAction: dirty ? /* @__PURE__ */ jsxRuntime.jsx(
510
+ ConfirmAction.ConfirmAction,
511
+ {
512
+ disabled: saving,
513
+ trigger: backButton,
514
+ title: t("settings.templates.edit.discardTitle", "Discard your changes?"),
515
+ body: t(
516
+ "settings.templates.edit.discardBody",
517
+ "You go back to the list. Your unsaved changes to this template are lost."
518
+ ),
519
+ confirmLabel: t("settings.templates.edit.discardConfirm", "Discard changes"),
520
+ variant: "danger-light",
521
+ onConfirm: onBack
522
+ }
523
+ ) : backButton,
524
+ children: [
525
+ showErrors && Object.keys(errors).length ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "danger600", role: "status", children: t("settings.templates.form.invalid", "Some values need attention. They are marked below.") }) : null,
526
+ visible._form ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Alert, { variant: "danger", closeLabel: t("settings.close", "Close"), onClose: () => setServerErrors({}), children: visible._form }) : null,
527
+ /* @__PURE__ */ jsxRuntime.jsx(useT.SectionCard, { title: t("settings.templates.form.details", "Details"), children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Grid.Root, { gap: { initial: 4, medium: 6 }, children: [
528
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Grid.Item, { col: 6, xs: 12, s: 12, direction: "column", alignItems: "stretch", children: /* @__PURE__ */ jsxRuntime.jsxs(
529
+ designSystem.Field.Root,
530
+ {
531
+ name: "name",
532
+ error: errorText(t, visible.name),
533
+ hint: t(
534
+ "settings.templates.form.nameHint",
535
+ "Shown in the Insert template dialog of the editor."
536
+ ),
537
+ required: true,
538
+ children: [
539
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Label, { children: t("settings.templates.form.name", "Name") }),
540
+ /* @__PURE__ */ jsxRuntime.jsx(
541
+ designSystem.TextInput,
542
+ {
543
+ value: values.name,
544
+ maxLength: index.TEMPLATE_LIMITS.name,
545
+ onChange: (event) => set({ name: event.target.value })
546
+ }
547
+ ),
548
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Hint, {}),
549
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Error, {})
550
+ ]
551
+ }
552
+ ) }),
553
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Grid.Item, { col: 6, xs: 12, s: 12, direction: "column", alignItems: "stretch", children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "stretch", gap: 2, children: [
554
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", fontWeight: "bold", textColor: "neutral800", id: "mex-template-kind", children: t("settings.templates.form.kind", "Type") }),
555
+ /* @__PURE__ */ jsxRuntime.jsxs(
556
+ designSystem.Radio.Group,
557
+ {
558
+ "aria-labelledby": "mex-template-kind",
559
+ value: values.kind,
560
+ onValueChange: (kind) => set({ kind }),
561
+ children: [
562
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Radio.Item, { value: "template", disabled: savedSynced, children: t(
563
+ "settings.templates.form.kindTemplate",
564
+ "Template: starting content, applied to an empty field or replacing its content after a confirmation"
565
+ ) }),
566
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Radio.Item, { value: "pattern", disabled: savedSynced, children: t(
567
+ "settings.templates.form.kindPattern",
568
+ "Pattern: a group of blocks inserted after the current block"
569
+ ) }),
570
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Radio.Item, { value: "synced", disabled: Boolean(template) && !savedSynced, children: t(
571
+ "settings.templates.form.kindSynced",
572
+ "Synced block: inserted as a reference; when you change it here, every field that uses it shows the change"
573
+ ) })
574
+ ]
575
+ }
576
+ ),
577
+ template ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral600", children: t(
578
+ "settings.templates.form.kindLocked",
579
+ "A synced block cannot be turned into a template or pattern, or the other way round."
580
+ ) }) : null
581
+ ] }) }),
582
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Grid.Item, { col: 12, direction: "column", alignItems: "stretch", children: /* @__PURE__ */ jsxRuntime.jsxs(
583
+ designSystem.Field.Root,
584
+ {
585
+ name: "description",
586
+ error: errorText(t, visible.description),
587
+ hint: t("settings.templates.form.descriptionHint", "Optional. Helps editors choose."),
588
+ children: [
589
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Label, { children: t("settings.templates.form.description", "Description") }),
590
+ /* @__PURE__ */ jsxRuntime.jsx(
591
+ designSystem.Textarea,
592
+ {
593
+ value: values.description,
594
+ maxLength: index.TEMPLATE_LIMITS.description,
595
+ onChange: (event) => set({ description: event.target.value })
596
+ }
597
+ ),
598
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Hint, {}),
599
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Error, {})
600
+ ]
601
+ }
602
+ ) }),
603
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Grid.Item, { col: 12, direction: "column", alignItems: "stretch", children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { justifyContent: "space-between", alignItems: "center", gap: 4, wrap: "wrap", children: [
604
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "flex-start", gap: 1, minWidth: 0, flex: "1 1 24rem", children: [
605
+ /* @__PURE__ */ jsxRuntime.jsx(
606
+ designSystem.Typography,
607
+ {
608
+ variant: "omega",
609
+ fontWeight: "bold",
610
+ textColor: "neutral800",
611
+ id: "mex-template-enabled",
612
+ children: t("settings.templates.form.enabled", "Offer in the editor")
613
+ }
614
+ ),
615
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral600", children: t(
616
+ "settings.templates.form.enabledHint",
617
+ "When this is off, editors do not see the template. You can keep working on it."
618
+ ) })
619
+ ] }),
620
+ /* @__PURE__ */ jsxRuntime.jsx(
621
+ designSystem.Switch,
622
+ {
623
+ "aria-labelledby": "mex-template-enabled",
624
+ checked: values.enabled,
625
+ onCheckedChange: (checked) => set({ enabled: checked === true }),
626
+ onLabel: t("settings.switch.on", "On"),
627
+ offLabel: t("settings.switch.off", "Off"),
628
+ visibleLabels: true
629
+ }
630
+ )
631
+ ] }) })
632
+ ] }) }),
633
+ /* @__PURE__ */ jsxRuntime.jsxs(
634
+ useT.SectionCard,
635
+ {
636
+ title: t("settings.templates.form.scope", "Where it is offered"),
637
+ subtitle: t(
638
+ "settings.templates.form.scopeHint",
639
+ "Editors see the template in these fields. Blocks a field does not allow are left out when they insert it."
640
+ ),
641
+ children: [
642
+ /* @__PURE__ */ jsxRuntime.jsxs(
643
+ designSystem.Radio.Group,
644
+ {
645
+ "aria-label": t("settings.templates.form.scope", "Where it is offered"),
646
+ value: values.scopeMode,
647
+ onValueChange: (scopeMode) => set({ scopeMode }),
648
+ children: [
649
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Radio.Item, { value: "all", children: t("settings.templates.form.scopeAll", "Every Magic Editor X field") }),
650
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Radio.Item, { value: "limited", children: t("settings.templates.form.scopeLimited", "Only fields with these presets, and these fields") })
651
+ ]
652
+ }
653
+ ),
654
+ values.scopeMode === "limited" ? /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Grid.Root, { gap: { initial: 4, medium: 6 }, children: [
655
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Grid.Item, { col: 6, xs: 12, s: 12, direction: "column", alignItems: "stretch", children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Field.Root, { name: "presets", error: errorText(t, visible.scope), children: [
656
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Label, { children: t("settings.templates.form.presets", "Presets") }),
657
+ /* @__PURE__ */ jsxRuntime.jsx(
658
+ designSystem.MultiSelect,
659
+ {
660
+ value: values.presets,
661
+ onChange: (presets) => set({ presets }),
662
+ placeholder: t("settings.templates.form.presetsPlaceholder", "Choose presets"),
663
+ withTags: true,
664
+ children: index.PRESET_NAMES.map((name) => /* @__PURE__ */ jsxRuntime.jsx(designSystem.MultiSelectOption, { value: name, children: presetLabel(name) }, name))
665
+ }
666
+ ),
667
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Error, {})
668
+ ] }) }),
669
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Grid.Item, { col: 6, xs: 12, s: 12, direction: "column", alignItems: "stretch", children: [
670
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Field.Root, { name: "fields", error: errorText(t, visible.scope), children: [
671
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Label, { children: t("settings.templates.form.fields", "Fields") }),
672
+ /* @__PURE__ */ jsxRuntime.jsx(
673
+ designSystem.MultiSelect,
674
+ {
675
+ value: values.fields,
676
+ onChange: (fields) => set({ fields }),
677
+ placeholder: t("settings.templates.form.fieldsPlaceholder", "Choose fields"),
678
+ disabled: targets.status === "loading",
679
+ withTags: true,
680
+ children: fieldOptions.map((option) => /* @__PURE__ */ jsxRuntime.jsx(designSystem.MultiSelectOption, { value: option.key, children: option.label }, option.key))
681
+ }
682
+ ),
683
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Error, {})
684
+ ] }),
685
+ targets.status === "error" ? /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 2, wrap: "wrap", alignItems: "center", paddingTop: 2, children: [
686
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "danger600", children: t("settings.templates.form.fieldsError", "The list of fields could not be loaded.") }),
687
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Button, { variant: "tertiary", size: "S", onClick: onRetryTargets, children: t("settings.retry", "Try again") })
688
+ ] }) : null
689
+ ] })
690
+ ] }) : null
691
+ ]
692
+ }
693
+ ),
694
+ /* @__PURE__ */ jsxRuntime.jsx(
695
+ useT.SectionCard,
696
+ {
697
+ title: t("settings.templates.form.content", "Content"),
698
+ subtitle: t(
699
+ "settings.templates.form.contentHint",
700
+ "The blocks the template inserts. Use the preview in the editor toolbar to see the rendered output."
701
+ ),
702
+ children: /* @__PURE__ */ jsxRuntime.jsx(
703
+ index.EditorFieldBody,
704
+ {
705
+ target: EDITOR_TARGET,
706
+ name: "mexTemplateContent",
707
+ value: values.blocks,
708
+ onChange: (_name, blocks) => set({ blocks }),
709
+ attribute: EDITOR_ATTRIBUTE,
710
+ label: t("settings.templates.form.contentLabel", "Template content"),
711
+ error: errorText(t, visible.blocks),
712
+ required: true
713
+ }
714
+ )
715
+ }
716
+ ),
717
+ /* @__PURE__ */ jsxRuntime.jsxs(admin.Form, { method: "PUT", initialValues: savedKey, children: [
718
+ /* @__PURE__ */ jsxRuntime.jsx(DraftSync.DraftSync, { values: draftKey }),
719
+ /* @__PURE__ */ jsxRuntime.jsx(admin.Blocker, {})
720
+ ] })
721
+ ]
722
+ }
723
+ );
724
+ };
725
+ const TemplatesPage = () => {
726
+ const t = useT.useT();
727
+ const { post, put, del } = admin.useFetchClient();
728
+ const { toggleNotification } = admin.useNotification();
729
+ const { allowedActions, isLoading: rbacLoading } = admin.useRBAC(index$1.PERMISSIONS.templatesManage);
730
+ const data = useTemplateList();
731
+ const [editing, setEditing] = ReactNamespace.useState(null);
732
+ const [preview, setPreview] = ReactNamespace.useState(null);
733
+ const [busyId, setBusyId] = ReactNamespace.useState(null);
734
+ const createRef = ReactNamespace.useRef(null);
735
+ const previewOpenerRef = ReactNamespace.useRef(null);
736
+ const [kindFilter, setKindFilter] = ReactNamespace.useState("all");
737
+ const [searchParams, setSearchParams] = reactRouterDom.useSearchParams();
738
+ const editParam = searchParams.get("edit");
739
+ const title = t("settings.templates.title", "Templates");
740
+ const [handledEdit, setHandledEdit] = ReactNamespace.useState(null);
741
+ if (editParam && editParam !== handledEdit && data.status === "ready") {
742
+ setHandledEdit(editParam);
743
+ const found = data.templates.find((item) => item.id === editParam);
744
+ if (found) setEditing({ template: found, key: editParam });
745
+ }
746
+ ReactNamespace.useEffect(() => {
747
+ if (!editParam || editParam !== handledEdit) return;
748
+ const next = new URLSearchParams(searchParams);
749
+ next.delete("edit");
750
+ setSearchParams(next, { replace: true });
751
+ }, [editParam, handledEdit, searchParams, setSearchParams]);
752
+ if (rbacLoading || data.status === "loading") {
753
+ return /* @__PURE__ */ jsxRuntime.jsxs(admin.Page.Main, { children: [
754
+ /* @__PURE__ */ jsxRuntime.jsx(admin.Page.Title, { children: title }),
755
+ /* @__PURE__ */ jsxRuntime.jsx(admin.Page.Loading, {})
756
+ ] });
757
+ }
758
+ if (!allowedActions.canManage) {
759
+ return /* @__PURE__ */ jsxRuntime.jsxs(admin.Page.Main, { children: [
760
+ /* @__PURE__ */ jsxRuntime.jsx(admin.Page.Title, { children: title }),
761
+ /* @__PURE__ */ jsxRuntime.jsx(admin.Page.NoPermissions, {})
762
+ ] });
763
+ }
764
+ if (data.status === "error") {
765
+ return /* @__PURE__ */ jsxRuntime.jsxs(admin.Page.Main, { children: [
766
+ /* @__PURE__ */ jsxRuntime.jsx(admin.Page.Title, { children: title }),
767
+ /* @__PURE__ */ jsxRuntime.jsx(
768
+ admin.Page.Error,
769
+ {
770
+ content: t("settings.templates.loadError", "The templates could not be loaded."),
771
+ action: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Button, { variant: "secondary", onClick: data.reload, children: t("settings.retry", "Try again") })
772
+ }
773
+ )
774
+ ] });
775
+ }
776
+ const failed = (error, fallback) => {
777
+ const info = ConfirmAction.readApiError(error);
778
+ toggleNotification({
779
+ type: "danger",
780
+ message: info.status === 404 ? t("settings.templates.notFound", "This template no longer exists.") : fallback
781
+ });
782
+ };
783
+ const backToList = () => {
784
+ setEditing(null);
785
+ requestAnimationFrame(() => createRef.current && createRef.current.focus());
786
+ };
787
+ const onSubmit = async (values) => {
788
+ const payload = toPayload(values);
789
+ try {
790
+ if (editing.template) await put(ConfirmAction.API.template(editing.template.id), payload);
791
+ else await post(ConfirmAction.API.templates, payload);
792
+ toggleNotification({
793
+ type: "success",
794
+ message: editing.template ? t("settings.templates.saved", "Template {name} saved.", { name: payload.name }) : t("settings.templates.created", "Template {name} created.", { name: payload.name })
795
+ });
796
+ index.resetEditorConfigCache();
797
+ await data.reload();
798
+ backToList();
799
+ return { ok: true };
800
+ } catch (error) {
801
+ const info = ConfirmAction.readApiError(error);
802
+ if (info.status === 400) {
803
+ toggleNotification({
804
+ type: "warning",
805
+ message: t(
806
+ "settings.templates.rejected",
807
+ "The server rejected some values. They are marked in the form."
808
+ )
809
+ });
810
+ return { ok: false, errors: mapServerErrors(info.details) };
811
+ }
812
+ failed(
813
+ error,
814
+ t(
815
+ "settings.templates.saveError",
816
+ "The template could not be saved. Your changes are still in the form."
817
+ )
818
+ );
819
+ return { ok: false };
820
+ }
821
+ };
822
+ if (editing) {
823
+ return /* @__PURE__ */ jsxRuntime.jsx(
824
+ TemplateEditor,
825
+ {
826
+ template: editing.template,
827
+ targets: data.targets,
828
+ onRetryTargets: data.reloadTargets,
829
+ onSubmit,
830
+ onBack: backToList
831
+ },
832
+ editing.key
833
+ );
834
+ }
835
+ const onToggle = async (template, enabled) => {
836
+ setBusyId(template.id);
837
+ try {
838
+ const { data: response } = await put(ConfirmAction.API.template(template.id), withEnabled(template, enabled));
839
+ data.setTemplates((current) => current.map((item) => item.id === template.id ? response.data : item));
840
+ toggleNotification({
841
+ type: "success",
842
+ message: enabled ? t("settings.templates.enabled", "{name} is offered in the editor.", { name: template.name }) : t("settings.templates.disabled", "{name} is no longer offered in the editor.", {
843
+ name: template.name
844
+ })
845
+ });
846
+ } catch (error) {
847
+ failed(error, t("settings.templates.toggleError", "The template could not be updated."));
848
+ } finally {
849
+ setBusyId(null);
850
+ }
851
+ };
852
+ const onDuplicate = async (template) => {
853
+ setBusyId(template.id);
854
+ try {
855
+ const { data: response } = await post(ConfirmAction.API.templateDuplicate(template.id), {});
856
+ toggleNotification({
857
+ type: "success",
858
+ message: t("settings.templates.duplicated", "Copy {name} created. It is off until you turn it on.", {
859
+ name: response.data.name
860
+ })
861
+ });
862
+ await data.reload();
863
+ } catch (error) {
864
+ failed(error, t("settings.templates.duplicateError", "The template could not be duplicated."));
865
+ } finally {
866
+ setBusyId(null);
867
+ }
868
+ };
869
+ const shownTemplates = filterByKind(data.templates, kindFilter);
870
+ const onMove = async (template, direction) => {
871
+ const ids = moveWithin(
872
+ data.templates.map((item) => item.id),
873
+ shownTemplates.map((item) => item.id),
874
+ template.id,
875
+ direction
876
+ );
877
+ if (!ids) return;
878
+ const opener = typeof document !== "undefined" ? document.activeElement : null;
879
+ setBusyId(template.id);
880
+ try {
881
+ const { data: response } = await put(ConfirmAction.API.templatesOrder, { ids });
882
+ data.setTemplates(response.data);
883
+ } catch (error) {
884
+ failed(error, t("settings.templates.moveError", "The order could not be saved."));
885
+ } finally {
886
+ setBusyId(null);
887
+ requestAnimationFrame(() => ConfirmAction.refocusIfLost(opener, createRef.current));
888
+ }
889
+ };
890
+ const onDelete = async (template) => {
891
+ try {
892
+ await del(ConfirmAction.API.template(template.id));
893
+ toggleNotification({
894
+ type: "success",
895
+ message: t("settings.templates.deleted", "Template {name} deleted.", { name: template.name })
896
+ });
897
+ data.setTemplates((current) => current.filter((item) => item.id !== template.id));
898
+ } catch (error) {
899
+ failed(error, t("settings.templates.deleteError", "The template could not be deleted."));
900
+ throw error;
901
+ }
902
+ };
903
+ const openCreate = () => setEditing({ template: null, key: Date.now() });
904
+ return /* @__PURE__ */ jsxRuntime.jsxs(
905
+ useT.PageShell,
906
+ {
907
+ title,
908
+ subtitle: t(
909
+ "settings.templates.subtitle",
910
+ 'Reusable starting content and block patterns. Editors insert them with "Insert template" in the editor toolbar.'
911
+ ),
912
+ primaryAction: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Button, { ref: createRef, startIcon: /* @__PURE__ */ jsxRuntime.jsx(icons.Plus, {}), onClick: openCreate, "data-testid": "mex-template-create", children: t("settings.templates.create", "Create template") }),
913
+ children: [
914
+ data.refreshError ? /* @__PURE__ */ jsxRuntime.jsx(
915
+ designSystem.Alert,
916
+ {
917
+ variant: "danger",
918
+ closeLabel: t("settings.close", "Close"),
919
+ action: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Button, { variant: "tertiary", size: "S", onClick: data.reload, children: t("settings.retry", "Try again") }),
920
+ children: t(
921
+ "settings.templates.refreshError",
922
+ "The list could not be refreshed. It shows the last loaded state."
923
+ )
924
+ }
925
+ ) : null,
926
+ data.templates.length === 0 ? /* @__PURE__ */ jsxRuntime.jsx(useT.SectionCard, { children: /* @__PURE__ */ jsxRuntime.jsx(
927
+ designSystem.EmptyStateLayout,
928
+ {
929
+ icon: /* @__PURE__ */ jsxRuntime.jsx(symbols.EmptyDocuments, { width: "16rem", height: "8.8rem" }),
930
+ content: t(
931
+ "settings.templates.empty",
932
+ "No templates yet. Templates and patterns you create here appear in the Insert template dialog of the fields they are made for."
933
+ ),
934
+ action: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Button, { variant: "secondary", startIcon: /* @__PURE__ */ jsxRuntime.jsx(icons.Plus, {}), onClick: openCreate, children: t("settings.templates.create", "Create template") })
935
+ }
936
+ ) }) : /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "stretch", gap: 4, children: [
937
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { maxWidth: "32rem", children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Field.Root, { name: "mex-template-kind-filter", children: [
938
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Label, { children: t("settings.templates.filter.label", "Show") }),
939
+ /* @__PURE__ */ jsxRuntime.jsxs(
940
+ designSystem.SingleSelect,
941
+ {
942
+ value: kindFilter,
943
+ onChange: (value) => setKindFilter(KIND_FILTERS.includes(value) ? value : "all"),
944
+ "data-testid": "mex-template-filter",
945
+ children: [
946
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.SingleSelectOption, { value: "all", children: t("settings.templates.filter.all", "All types") }),
947
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.SingleSelectOption, { value: "template", children: t("settings.templates.filter.template", "Templates") }),
948
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.SingleSelectOption, { value: "pattern", children: t("settings.templates.filter.pattern", "Patterns") }),
949
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.SingleSelectOption, { value: "synced", children: t("settings.templates.filter.synced", "Synced blocks") })
950
+ ]
951
+ }
952
+ )
953
+ ] }) }),
954
+ shownTemplates.length === 0 ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "omega", textColor: "neutral600", role: "status", children: t("settings.templates.filter.empty", "Nothing of this type yet.") }) : /* @__PURE__ */ jsxRuntime.jsx(
955
+ TemplateList,
956
+ {
957
+ templates: shownTemplates,
958
+ busyId,
959
+ onToggle,
960
+ onPreview: (template) => {
961
+ previewOpenerRef.current = typeof document !== "undefined" ? document.activeElement : null;
962
+ setPreview(template);
963
+ },
964
+ onEdit: (template) => setEditing({ template, key: Date.now() }),
965
+ onDuplicate,
966
+ onMove,
967
+ onDelete,
968
+ fallbackFocusRef: createRef
969
+ }
970
+ )
971
+ ] }),
972
+ preview ? /* @__PURE__ */ jsxRuntime.jsx(
973
+ designSystem.Modal.Root,
974
+ {
975
+ open: true,
976
+ onOpenChange: (next) => {
977
+ if (next) return;
978
+ setPreview(null);
979
+ requestAnimationFrame(() => ConfirmAction.refocusIfLost(previewOpenerRef.current, createRef.current));
980
+ },
981
+ children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Modal.Content, { children: [
982
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Header, { closeLabel: t("settings.close", "Close"), children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Title, { children: t("settings.templates.preview.title", "Preview of {name}", { name: preview.name }) }) }),
983
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Body, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { "data-testid": "mex-settings-template-preview", children: /* @__PURE__ */ jsxRuntime.jsx(index.RenderedContent, { value: preview.blocks, t }) }) }),
984
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Footer, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Close, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Button, { variant: "tertiary", children: t("settings.close", "Close") }) }) })
985
+ ] })
986
+ }
987
+ ) : null
988
+ ]
989
+ }
990
+ );
991
+ };
992
+ exports.TemplatesPage = TemplatesPage;
993
+ exports.default = TemplatesPage;