magic-editor-x 2.0.0 → 2.1.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 (51) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/README.md +154 -68
  3. package/dist/admin/{ConfigurationPage-DvAifELO.mjs → ConfigurationPage-CK2AbfGW.mjs} +126 -7
  4. package/dist/admin/{ConfigurationPage-B1uCIE3J.js → ConfigurationPage-CzsT_dO_.js} +125 -4
  5. package/dist/admin/{CustomBlocksPage-6-OQwpXQ.mjs → CustomBlocksPage-B2A8S5MV.mjs} +4 -4
  6. package/dist/admin/{CustomBlocksPage-6eWCOreU.js → CustomBlocksPage-CvLrsBds.js} +4 -4
  7. package/dist/admin/{EditorField-ThSoOCPm.mjs → EditorField-7YCdXx-v.mjs} +2019 -661
  8. package/dist/admin/{EditorField-DocyD2Q3.js → EditorField-BdBCW15Q.js} +2015 -657
  9. package/dist/admin/{api-B-RsxJCs.js → api-CmccMxlN.js} +2 -0
  10. package/dist/admin/{api-C4XsDZxd.mjs → api-D5CAH0nh.mjs} +2 -0
  11. package/dist/admin/{de-RAxzvrwm.mjs → de-BHPyA2S-.mjs} +10 -2
  12. package/dist/admin/{de-BMxADn2Z.mjs → de-Bt6pYIWi.mjs} +16 -1
  13. package/dist/admin/{de-Dx7vUW0Z.js → de-CVbi685U.js} +16 -1
  14. package/dist/admin/{de-DcDPRzV4.js → de-CkUYGb7U.js} +22 -1
  15. package/dist/admin/{de-B8XFFhHh.js → de-RMs-_SCK.js} +10 -2
  16. package/dist/admin/{de-n5V6c5RT.mjs → de-rRIutpYJ.mjs} +22 -1
  17. package/dist/admin/{en-sNn4z9lA.js → en-BX362fTp.js} +16 -1
  18. package/dist/admin/{en-BQ5Pxe2o.mjs → en-B_HltUxZ.mjs} +16 -1
  19. package/dist/admin/{en-BzfyifEU.mjs → en-BluCStLw.mjs} +10 -2
  20. package/dist/admin/{en-DcWUTE2J.js → en-C81faOHP.js} +10 -2
  21. package/dist/admin/{en-D-DGftl0.js → en-DulOcmXb.js} +22 -1
  22. package/dist/admin/{en-BqNm3nMQ.mjs → en-Puup8TFi.mjs} +22 -1
  23. package/dist/admin/{es-SzeTV4q8.mjs → es-257SSB7f.mjs} +22 -1
  24. package/dist/admin/{es-Di0pyQCh.js → es-BoQZC86B.js} +22 -1
  25. package/dist/admin/{es-DVsXnS0N.js → es-CHHEZi44.js} +16 -1
  26. package/dist/admin/{es-C2OJVYkV.mjs → es-CQRI2Prp.mjs} +10 -2
  27. package/dist/admin/{es-B6NYq0VH.mjs → es-CrhwOq-5.mjs} +16 -1
  28. package/dist/admin/{es-BOtVc9qv.js → es-D1QzY0JW.js} +10 -2
  29. package/dist/admin/{fr-DmG3_Cn-.mjs → fr-5djKfQ3s.mjs} +16 -1
  30. package/dist/admin/{fr-Fwxcj4SM.js → fr-B3SL0TBV.js} +16 -1
  31. package/dist/admin/{fr-DhgPYHIH.mjs → fr-C5rSdKU4.mjs} +22 -1
  32. package/dist/admin/{fr-Bpo5Uq1f.mjs → fr-Di3R6gOX.mjs} +10 -2
  33. package/dist/admin/{fr-D6F--jIB.js → fr-HxFcPpv4.js} +22 -1
  34. package/dist/admin/{fr-DfxKaOc_.js → fr-R3_MbzT5.js} +10 -2
  35. package/dist/admin/{index-D1Q5Rlt6.mjs → index-0_b1iroK.mjs} +18 -18
  36. package/dist/admin/{index-CwfaB5-e.js → index-6SZLli70.js} +18 -18
  37. package/dist/admin/index.js +1 -1
  38. package/dist/admin/index.mjs +1 -1
  39. package/dist/admin/{pt-LCvjwk0y.js → pt-BCW1u_Hp.js} +10 -2
  40. package/dist/admin/{pt-BbdwHlWF.mjs → pt-BdnY2Cth.mjs} +16 -1
  41. package/dist/admin/{pt-BPo0ex21.js → pt-Cjn2Sc9k.js} +22 -1
  42. package/dist/admin/{pt-DqCXuI4S.mjs → pt-Cr9AL408.mjs} +10 -2
  43. package/dist/admin/{pt-BvSl1btT.mjs → pt-D6UuEtPy.mjs} +22 -1
  44. package/dist/admin/{pt-C6nr71Yw.js → pt-EVwCuBUK.js} +16 -1
  45. package/dist/admin/{sanitize-9UVcXFfc.js → sanitize-DP5aeU7V.js} +46 -1
  46. package/dist/admin/{sanitize-D4kfZ_ly.mjs → sanitize-jjCot5PM.mjs} +47 -2
  47. package/dist/admin/{useT-B5M49wGH.js → useT-91ruePzq.js} +1 -1
  48. package/dist/admin/{useT-CjX6fL2m.mjs → useT-vgY88N_H.mjs} +1 -1
  49. package/dist/server/index.js +1561 -321
  50. package/dist/server/index.mjs +1561 -321
  51. package/package.json +1 -1
@@ -3,6 +3,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const jsxRuntime = require("react/jsx-runtime");
4
4
  const react = require("react");
5
5
  const reactIntl = require("react-intl");
6
+ const reactRouterDom = require("react-router-dom");
6
7
  const EditorJS = require("@editorjs/editorjs");
7
8
  const designSystem = require("@strapi/design-system");
8
9
  const admin = require("@strapi/strapi/admin");
@@ -20,7 +21,8 @@ const ImageTool = require("@editorjs/image");
20
21
  const Attaches = require("@editorjs/attaches");
21
22
  const InlineCode = require("@editorjs/inline-code");
22
23
  const IndentTune = require("editorjs-indent-tune");
23
- const sanitize = require("./sanitize-9UVcXFfc.js");
24
+ const sanitize = require("./sanitize-DP5aeU7V.js");
25
+ const api = require("./api-CmccMxlN.js");
24
26
  const Prism = require("prismjs");
25
27
  require("prismjs/components/prism-markup-templating");
26
28
  require("prismjs/components/prism-typescript");
@@ -47,8 +49,7 @@ require("prismjs/components/prism-markdown");
47
49
  require("prismjs/components/prism-docker");
48
50
  require("prismjs/components/prism-diff");
49
51
  const Y = require("yjs");
50
- const api = require("./api-B-RsxJCs.js");
51
- const index = require("./index-CwfaB5-e.js");
52
+ const index = require("./index-6SZLli70.js");
52
53
  const socket_ioClient = require("socket.io-client");
53
54
  const icons = require("@strapi/icons");
54
55
  const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
@@ -185,70 +186,567 @@ const ICONS = {
185
186
  stretch: '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M3 12h18m-15-3-3 3 3 3m12-6 3 3-3 3" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',
186
187
  lineNumbers: '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M4 6h2M4 12h2M4 18h2M10 6h10M10 12h10M10 18h10" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>'
187
188
  };
188
- const wrapRange = (api2, range, tag, className) => {
189
- const wrapper = document.createElement(tag);
190
- if (className) wrapper.classList.add(className);
191
- wrapper.appendChild(range.extractContents());
192
- range.insertNode(wrapper);
193
- api2.selection.expandToTag(wrapper);
194
- return wrapper;
189
+ const ALERT_TYPES = Object.freeze([
190
+ "primary",
191
+ "secondary",
192
+ "info",
193
+ "success",
194
+ "warning",
195
+ "danger",
196
+ "light",
197
+ "dark"
198
+ ]);
199
+ const ALERT_ALIGNMENTS = Object.freeze(["left", "center", "right"]);
200
+ const ALIGNMENTS = Object.freeze(["left", "center", "right", "justify"]);
201
+ const TEXT_VARIANTS = Object.freeze(["call-out", "citation", "details"]);
202
+ const BUTTON_STYLES = Object.freeze(["primary", "secondary", "outline", "ghost", "danger", "success"]);
203
+ const CODE_LANGUAGES = Object.freeze([
204
+ "plaintext",
205
+ "javascript",
206
+ "typescript",
207
+ "jsx",
208
+ "tsx",
209
+ "json",
210
+ "markup",
211
+ "css",
212
+ "scss",
213
+ "bash",
214
+ "python",
215
+ "php",
216
+ "ruby",
217
+ "java",
218
+ "kotlin",
219
+ "swift",
220
+ "csharp",
221
+ "c",
222
+ "cpp",
223
+ "go",
224
+ "rust",
225
+ "sql",
226
+ "graphql",
227
+ "yaml",
228
+ "markdown",
229
+ "docker",
230
+ "diff"
231
+ ]);
232
+ const LANGUAGE_ALIASES = {
233
+ js: "javascript",
234
+ ts: "typescript",
235
+ html: "markup",
236
+ xml: "markup",
237
+ svg: "markup",
238
+ sh: "bash",
239
+ shell: "bash",
240
+ py: "python",
241
+ yml: "yaml",
242
+ md: "markdown",
243
+ dockerfile: "docker",
244
+ "c#": "csharp",
245
+ cs: "csharp",
246
+ "c++": "cpp",
247
+ text: "plaintext",
248
+ plain: "plaintext",
249
+ none: "plaintext"
195
250
  };
196
- const unwrap = (api2, wrapper) => {
197
- api2.selection.expandToTag(wrapper);
198
- const selection = window.getSelection();
199
- if (!selection || selection.rangeCount === 0) return;
200
- const range = selection.getRangeAt(0);
201
- const contents = range.extractContents();
202
- if (wrapper.parentNode) wrapper.parentNode.removeChild(wrapper);
203
- range.insertNode(contents);
204
- selection.removeAllRanges();
205
- selection.addRange(range);
251
+ const str = (value) => typeof value === "string" ? value : "";
252
+ const pick = (value, allowed, fallback) => typeof value === "string" && allowed.includes(value) ? value : fallback;
253
+ const normalizeAlert = (data, config = {}) => {
254
+ const d = data && typeof data === "object" ? data : {};
255
+ return {
256
+ type: pick(d.type, ALERT_TYPES, pick(config.defaultType, ALERT_TYPES, "info")),
257
+ align: pick(d.align, ALERT_ALIGNMENTS, pick(config.defaultAlign, ALERT_ALIGNMENTS, "left")),
258
+ // Some editorjs-alert versions wrote `text` instead of `message`.
259
+ message: str(d.message) || str(d.text)
260
+ };
206
261
  };
207
- const createFormatTool = (spec) => class FormatInlineTool {
208
- static get isInline() {
209
- return true;
210
- }
211
- static get title() {
212
- return spec.title;
213
- }
214
- static get sanitize() {
215
- return { [spec.tag]: { class: spec.className } };
216
- }
217
- constructor({ api: api2 }) {
218
- this.api = api2;
219
- this.button = null;
220
- }
221
- get shortcut() {
222
- return spec.shortcut;
223
- }
224
- render() {
225
- this.button = el("button", { className: this.api.styles.inlineToolButton, attrs: { type: "button" } });
226
- this.button.innerHTML = spec.icon;
227
- return this.button;
228
- }
229
- surround(range) {
230
- if (!range) return;
231
- const existing = this.api.selection.findParentTag(spec.tag.toUpperCase(), spec.className);
232
- if (existing) unwrap(this.api, existing);
233
- else wrapRange(this.api, range, spec.tag, spec.className);
234
- }
235
- checkState() {
236
- const active = Boolean(this.api.selection.findParentTag(spec.tag.toUpperCase(), spec.className));
237
- if (this.button) this.button.classList.toggle(this.api.styles.inlineToolButtonActive, active);
238
- return active;
262
+ const normalizeAlignment = (data, fallback = "left") => ({
263
+ alignment: pick(data && data.alignment, ALIGNMENTS, pick(fallback, ALIGNMENTS, "left"))
264
+ });
265
+ const normalizeTextVariant = (data) => pick(data, TEXT_VARIANTS, "");
266
+ const normalizeLanguage = (language) => {
267
+ const raw = str(language).trim().toLowerCase();
268
+ const mapped = LANGUAGE_ALIASES[raw] || raw;
269
+ return CODE_LANGUAGES.includes(mapped) ? mapped : "plaintext";
270
+ };
271
+ const normalizeCodeFlask = (data, config = {}) => {
272
+ const d = data && typeof data === "object" ? data : {};
273
+ return {
274
+ code: str(d.code),
275
+ language: d.language ? normalizeLanguage(d.language) : normalizeLanguage(config.language || "plaintext"),
276
+ showlinenumbers: d.showlinenumbers !== false
277
+ };
278
+ };
279
+ const checklistToList = (data) => {
280
+ const items = data && Array.isArray(data.items) ? data.items : [];
281
+ return {
282
+ style: "checklist",
283
+ meta: {},
284
+ items: items.map((item) => {
285
+ if (typeof item === "string") return { content: item, meta: { checked: false }, items: [] };
286
+ const value = item && typeof item === "object" ? item : {};
287
+ return {
288
+ content: str(value.text) || str(value.content),
289
+ meta: { checked: Boolean(value.checked ?? (value.meta && value.meta.checked)) },
290
+ items: []
291
+ };
292
+ })
293
+ };
294
+ };
295
+ const listToChecklist = (data) => {
296
+ const out = [];
297
+ const walk = (items, depth) => {
298
+ if (!Array.isArray(items) || depth > 12) return;
299
+ for (const item of items) {
300
+ if (!item || typeof item !== "object") continue;
301
+ out.push({ text: str(item.content), checked: Boolean(item.meta && item.meta.checked) });
302
+ walk(item.items, depth + 1);
303
+ }
304
+ };
305
+ walk(data && data.items, 0);
306
+ return { items: out };
307
+ };
308
+ const normalizeToggle = (data, fallbackKey) => {
309
+ const d = data && typeof data === "object" ? data : {};
310
+ const items = Number(d.items);
311
+ return {
312
+ text: str(d.text),
313
+ status: d.status === "closed" ? "closed" : "open",
314
+ fk: str(d.fk) || str(fallbackKey),
315
+ items: Number.isInteger(items) && items > 0 ? Math.min(items, 5e3) : 0
316
+ };
317
+ };
318
+ const toggleChildIndexes = (toggleIndex, items, total) => {
319
+ if (!Number.isInteger(toggleIndex) || toggleIndex < 0) return [];
320
+ const count = Math.max(0, Math.min(Number(items) || 0, total - toggleIndex - 1));
321
+ return Array.from({ length: count }, (_, i) => toggleIndex + 1 + i);
322
+ };
323
+ const nextToggleItems = (toggleIndex, items, total, action) => {
324
+ const current = toggleChildIndexes(toggleIndex, items, total).length;
325
+ if (action === "include") return Math.min(current + 1, Math.max(0, total - toggleIndex - 1));
326
+ return Math.max(0, current - 1);
327
+ };
328
+ const normalizeButton = (data) => {
329
+ const d = data && typeof data === "object" ? data : {};
330
+ return {
331
+ text: str(d.text),
332
+ link: str(d.link),
333
+ style: pick(d.style, BUTTON_STYLES, "primary"),
334
+ openInNewTab: d.openInNewTab === true
335
+ };
336
+ };
337
+ const normalizeSimpleImage = (data) => {
338
+ const d = data && typeof data === "object" ? data : {};
339
+ return {
340
+ url: str(d.url),
341
+ caption: str(d.caption),
342
+ withBorder: d.withBorder === true,
343
+ withBackground: d.withBackground === true,
344
+ stretched: d.stretched === true
345
+ };
346
+ };
347
+ const normalizePersonality = (data) => {
348
+ const d = data && typeof data === "object" ? data : {};
349
+ return { name: str(d.name), description: str(d.description), link: str(d.link), photo: str(d.photo) };
350
+ };
351
+ const normalizeLinkTool = (data) => {
352
+ const d = data && typeof data === "object" ? data : {};
353
+ const meta = d.meta && typeof d.meta === "object" ? d.meta : {};
354
+ const out = { title: str(meta.title), description: str(meta.description) };
355
+ if (str(meta.site_name)) out.site_name = str(meta.site_name);
356
+ if (meta.image && typeof meta.image === "object" && str(meta.image.url))
357
+ out.image = { url: str(meta.image.url) };
358
+ return { link: str(d.link), meta: out };
359
+ };
360
+ const normalizeEmbeddedEntry = (data, config = {}) => {
361
+ const d = data && typeof data === "object" ? data : {};
362
+ return {
363
+ entry: d.entry && typeof d.entry === "object" ? d.entry : null,
364
+ contentType: str(d.contentType) || config.contentType || null,
365
+ displayMode: pick(d.displayMode, ["card", "inline", "minimal"], "card")
366
+ };
367
+ };
368
+ const summarizeEntry = (entry, config = {}) => {
369
+ const titleField = config.titleField || "title";
370
+ const title = [entry[titleField], entry.title, entry.name, entry.label, entry.slug].find(
371
+ (v) => typeof v === "string" && v.trim()
372
+ );
373
+ const out = {
374
+ id: entry.id,
375
+ documentId: entry.documentId,
376
+ title: title || String(entry.documentId || entry.id || "")
377
+ };
378
+ for (const field2 of config.displayFields || []) {
379
+ const value = entry[field2];
380
+ if (["string", "number", "boolean"].includes(typeof value)) out[field2] = value;
239
381
  }
382
+ return out;
240
383
  };
241
- const MarkerTool = createFormatTool({
242
- tag: "mark",
243
- className: "cdx-marker",
244
- title: "Marker",
245
- icon: ICONS.marker,
246
- shortcut: "CMD+SHIFT+M"
384
+ const fillTemplate = (template, data) => String(template || "").replace(/\{\{\s*([A-Za-z_][A-Za-z0-9_]{0,39})\s*\}\}/g, (_match, name) => {
385
+ const value = data && Object.prototype.hasOwnProperty.call(data, name) ? data[name] : "";
386
+ let text = "";
387
+ if (value && typeof value === "object") text = typeof value.url === "string" ? value.url : "";
388
+ else if (value !== null && value !== void 0) text = String(value);
389
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
247
390
  });
248
- const UnderlineTool = createFormatTool({
249
- tag: "u",
250
- className: "cdx-underline",
251
- title: "Underline",
391
+ const createHistoryStack = ({ maxSteps = 50 } = {}) => {
392
+ let past = [];
393
+ let present = null;
394
+ let future = [];
395
+ return {
396
+ /** Sets the starting state without an undo step. */
397
+ init(state) {
398
+ past = [];
399
+ future = [];
400
+ present = state;
401
+ },
402
+ /** Records a new state; identical consecutive states are ignored. @returns {boolean} Recorded. */
403
+ push(state) {
404
+ if (state === present) return false;
405
+ if (present !== null) past.push(present);
406
+ if (past.length > maxSteps) past = past.slice(past.length - maxSteps);
407
+ present = state;
408
+ future = [];
409
+ return true;
410
+ },
411
+ /** @returns {string|null} State to show after undo. */
412
+ undo() {
413
+ if (past.length === 0) return null;
414
+ future.push(present);
415
+ present = past.pop();
416
+ return present;
417
+ },
418
+ /** @returns {string|null} State to show after redo. */
419
+ redo() {
420
+ if (future.length === 0) return null;
421
+ past.push(present);
422
+ present = future.pop();
423
+ return present;
424
+ },
425
+ /** Replaces the current state without touching undo/redo (re-serialised after a render). */
426
+ replacePresent(state) {
427
+ present = state;
428
+ },
429
+ canUndo: () => past.length > 0,
430
+ canRedo: () => future.length > 0,
431
+ current: () => present,
432
+ clear() {
433
+ past = [];
434
+ future = [];
435
+ present = null;
436
+ }
437
+ };
438
+ };
439
+ const historyKey = (data) => JSON.stringify(data && data.blocks || []);
440
+ const dropIndex = (rects, y, fromIndex) => {
441
+ if (rects.length === 0) return fromIndex;
442
+ let insertBefore = rects.length;
443
+ for (let i = 0; i < rects.length; i += 1) {
444
+ const middle = (rects[i].top + rects[i].bottom) / 2;
445
+ if (y < middle) {
446
+ insertBefore = i;
447
+ break;
448
+ }
449
+ }
450
+ const to = insertBefore > fromIndex ? insertBefore - 1 : insertBefore;
451
+ return Math.max(0, Math.min(rects.length - 1, to));
452
+ };
453
+ const moveActiveIndex = (current, delta, length) => {
454
+ if (!Number.isInteger(length) || length <= 0) return -1;
455
+ if (!Number.isInteger(current) || current < 0 || current >= length) return delta < 0 ? length - 1 : 0;
456
+ return (current + delta + length) % length;
457
+ };
458
+ const readInternalLink = (node) => {
459
+ if (!node || typeof node.getAttribute !== "function") return null;
460
+ const uid = node.getAttribute("data-mex-uid");
461
+ const documentId = node.getAttribute("data-mex-document-id");
462
+ if (!uid || !documentId) return null;
463
+ return {
464
+ href: node.getAttribute("href") || "",
465
+ uid,
466
+ documentId,
467
+ locale: node.getAttribute("data-mex-locale") || null
468
+ };
469
+ };
470
+ const internalLinkAttributes = (internal, href) => {
471
+ const keep = Boolean(internal && internal.uid && internal.documentId && internal.href === href);
472
+ return {
473
+ "data-mex-uid": keep ? internal.uid : null,
474
+ "data-mex-document-id": keep ? internal.documentId : null,
475
+ "data-mex-locale": keep && internal.locale ? internal.locale : null
476
+ };
477
+ };
478
+ const typeCache = /* @__PURE__ */ new WeakMap();
479
+ let pickerCount = 0;
480
+ const loadTypes = (fetchClient) => {
481
+ if (!typeCache.has(fetchClient)) {
482
+ const promise = fetchClient.get(api.API.linkTypes).then(({ data }) => data && Array.isArray(data.data) ? data.data : []).catch((error) => {
483
+ typeCache.delete(fetchClient);
484
+ throw error;
485
+ });
486
+ typeCache.set(fetchClient, promise);
487
+ }
488
+ return typeCache.get(fetchClient);
489
+ };
490
+ const createLinkPicker = ({ t, fetchClient, getLocale, onPick, onClose }) => {
491
+ pickerCount += 1;
492
+ const id = `mex-link-picker-${pickerCount}`;
493
+ const element = el("div", {
494
+ className: "mex-link-picker",
495
+ attrs: { id, role: "group", "aria-label": t("tools.hyperlink.internal.title", "Link to an entry") }
496
+ });
497
+ element.hidden = true;
498
+ let types = [];
499
+ let items = [];
500
+ let active = -1;
501
+ let timer = null;
502
+ let requestId = 0;
503
+ let typeSelect = null;
504
+ let search = null;
505
+ const status = el("p", { className: "mex-tool__muted", attrs: { role: "status", "aria-live": "polite" } });
506
+ const list = el("ul", {
507
+ className: "mex-link-picker__results",
508
+ attrs: {
509
+ id: `${id}-results`,
510
+ role: "listbox",
511
+ "aria-label": t("tools.hyperlink.internal.results", "Entries")
512
+ }
513
+ });
514
+ const setStatus = (text, isError = false) => {
515
+ status.className = isError ? "mex-tool__error" : "mex-tool__muted";
516
+ status.textContent = text;
517
+ };
518
+ const setActive = (index2) => {
519
+ active = index2;
520
+ Array.from(list.children).forEach((option, i) => {
521
+ option.setAttribute("aria-selected", i === active ? "true" : "false");
522
+ if (i === active && typeof option.scrollIntoView === "function")
523
+ option.scrollIntoView({ block: "nearest" });
524
+ });
525
+ if (search) {
526
+ if (active >= 0) search.setAttribute("aria-activedescendant", `${id}-option-${active}`);
527
+ else search.removeAttribute("aria-activedescendant");
528
+ }
529
+ };
530
+ const pick2 = (index2) => {
531
+ const item = items[index2];
532
+ if (item && item.href) onPick(item);
533
+ };
534
+ const renderResults = () => {
535
+ list.replaceChildren();
536
+ items.forEach((item, index2) => {
537
+ const statusLabel = item.status === "published" ? t("tools.hyperlink.internal.published", "Published") : item.status === "draft" ? t("tools.hyperlink.internal.draft", "Draft") : "";
538
+ const meta = [statusLabel, item.locale || ""].filter(Boolean).join(" · ");
539
+ const option = el("li", {
540
+ className: "mex-link-picker__option",
541
+ attrs: {
542
+ id: `${id}-option-${index2}`,
543
+ role: "option",
544
+ "aria-selected": "false",
545
+ "aria-disabled": item.href ? null : "true"
546
+ },
547
+ children: [
548
+ el("span", {
549
+ className: "mex-link-picker__title",
550
+ text: item.title || t("tools.hyperlink.internal.untitled", "Untitled entry")
551
+ }),
552
+ meta ? el("span", { className: "mex-link-picker__meta", text: meta }) : null
553
+ ]
554
+ });
555
+ option.addEventListener("mousedown", (event) => event.preventDefault());
556
+ option.addEventListener("click", () => pick2(index2));
557
+ list.appendChild(option);
558
+ });
559
+ if (search) search.setAttribute("aria-expanded", items.length ? "true" : "false");
560
+ setActive(items.length ? 0 : -1);
561
+ };
562
+ const run = async () => {
563
+ window.clearTimeout(timer);
564
+ const current = requestId += 1;
565
+ const type = types.find((candidate) => candidate.uid === (typeSelect && typeSelect.value));
566
+ if (!type) return;
567
+ const q = search ? search.value.trim().slice(0, 100) : "";
568
+ const locale = type.localized && typeof getLocale === "function" ? getLocale() : null;
569
+ setStatus(t("tools.hyperlink.internal.searching", "Searching"));
570
+ list.setAttribute("aria-busy", "true");
571
+ try {
572
+ const { data } = await fetchClient.get(api.API.linkSearch, {
573
+ params: { uid: type.uid, ...q ? { q } : {}, ...locale ? { locale } : {} }
574
+ });
575
+ if (current !== requestId) return;
576
+ items = data && Array.isArray(data.data) ? data.data : [];
577
+ renderResults();
578
+ setStatus(items.length ? "" : t("tools.hyperlink.internal.empty", "No entries match your search"));
579
+ } catch {
580
+ if (current !== requestId) return;
581
+ items = [];
582
+ renderResults();
583
+ setStatus(t("tools.hyperlink.internal.failed", "Entries could not be loaded"), true);
584
+ } finally {
585
+ if (current === requestId) list.removeAttribute("aria-busy");
586
+ }
587
+ };
588
+ const onKeyDown = (event) => {
589
+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {
590
+ event.preventDefault();
591
+ event.stopPropagation();
592
+ setActive(moveActiveIndex(active, event.key === "ArrowDown" ? 1 : -1, items.length));
593
+ } else if (event.key === "Enter") {
594
+ event.preventDefault();
595
+ event.stopPropagation();
596
+ if (active >= 0 && items[active]) pick2(active);
597
+ else run();
598
+ } else if (event.key === "Escape") {
599
+ event.preventDefault();
600
+ event.stopPropagation();
601
+ close();
602
+ }
603
+ };
604
+ const build = () => {
605
+ element.replaceChildren();
606
+ typeSelect = select(
607
+ types.map((type) => ({ value: type.uid, label: type.displayName })),
608
+ types[0].uid
609
+ );
610
+ search = input({
611
+ type: "search",
612
+ placeholder: t("tools.hyperlink.internal.searchPlaceholder", "Search by title")
613
+ });
614
+ search.setAttribute("role", "combobox");
615
+ search.setAttribute("aria-autocomplete", "list");
616
+ search.setAttribute("aria-controls", list.id);
617
+ search.setAttribute("aria-expanded", "false");
618
+ search.setAttribute("maxlength", "100");
619
+ search.addEventListener("input", () => {
620
+ window.clearTimeout(timer);
621
+ timer = window.setTimeout(run, 250);
622
+ });
623
+ typeSelect.addEventListener("change", run);
624
+ typeSelect.addEventListener("keydown", (event) => {
625
+ if (event.key === "Escape") {
626
+ event.preventDefault();
627
+ event.stopPropagation();
628
+ close();
629
+ }
630
+ });
631
+ element.append(
632
+ el("div", {
633
+ className: "mex-link-picker__controls",
634
+ children: [
635
+ field(t("tools.hyperlink.internal.type", "Content type"), typeSelect),
636
+ field(t("tools.hyperlink.internal.search", "Search"), search)
637
+ ]
638
+ }),
639
+ status,
640
+ list
641
+ );
642
+ };
643
+ const guard = (event) => {
644
+ if (element.hidden || !element.contains(event.target)) return;
645
+ if (!["Enter", "ArrowDown", "ArrowUp", "Escape", "Tab"].includes(event.key)) return;
646
+ event.stopPropagation();
647
+ if (event.key === "Tab") return;
648
+ if (event.target === search) onKeyDown(event);
649
+ else if (event.key === "Escape") {
650
+ event.preventDefault();
651
+ close();
652
+ }
653
+ };
654
+ const open = async () => {
655
+ window.addEventListener("keydown", guard, true);
656
+ element.hidden = false;
657
+ element.replaceChildren(status);
658
+ setStatus(t("tools.hyperlink.internal.loading", "Loading content types"));
659
+ try {
660
+ types = await loadTypes(fetchClient);
661
+ } catch {
662
+ setStatus(t("tools.hyperlink.internal.typesFailed", "Content types could not be loaded"), true);
663
+ return;
664
+ }
665
+ if (element.hidden) return;
666
+ if (!types.length) {
667
+ setStatus(t("tools.hyperlink.internal.noTypes", "There is no content type you can read"));
668
+ return;
669
+ }
670
+ build();
671
+ search.focus();
672
+ run();
673
+ };
674
+ function close() {
675
+ window.removeEventListener("keydown", guard, true);
676
+ window.clearTimeout(timer);
677
+ requestId += 1;
678
+ element.hidden = true;
679
+ element.replaceChildren();
680
+ items = [];
681
+ active = -1;
682
+ onClose();
683
+ }
684
+ return { element, open, close, isOpen: () => !element.hidden };
685
+ };
686
+ const wrapRange = (api2, range, tag, className) => {
687
+ const wrapper = document.createElement(tag);
688
+ if (className) wrapper.classList.add(className);
689
+ wrapper.appendChild(range.extractContents());
690
+ range.insertNode(wrapper);
691
+ api2.selection.expandToTag(wrapper);
692
+ return wrapper;
693
+ };
694
+ const unwrap = (api2, wrapper) => {
695
+ api2.selection.expandToTag(wrapper);
696
+ const selection = window.getSelection();
697
+ if (!selection || selection.rangeCount === 0) return;
698
+ const range = selection.getRangeAt(0);
699
+ const contents = range.extractContents();
700
+ if (wrapper.parentNode) wrapper.parentNode.removeChild(wrapper);
701
+ range.insertNode(contents);
702
+ selection.removeAllRanges();
703
+ selection.addRange(range);
704
+ };
705
+ const createFormatTool = (spec) => class FormatInlineTool {
706
+ static get isInline() {
707
+ return true;
708
+ }
709
+ static get title() {
710
+ return spec.title;
711
+ }
712
+ static get sanitize() {
713
+ return { [spec.tag]: { class: spec.className } };
714
+ }
715
+ constructor({ api: api2 }) {
716
+ this.api = api2;
717
+ this.button = null;
718
+ }
719
+ get shortcut() {
720
+ return spec.shortcut;
721
+ }
722
+ render() {
723
+ this.button = el("button", { className: this.api.styles.inlineToolButton, attrs: { type: "button" } });
724
+ this.button.innerHTML = spec.icon;
725
+ return this.button;
726
+ }
727
+ surround(range) {
728
+ if (!range) return;
729
+ const existing = this.api.selection.findParentTag(spec.tag.toUpperCase(), spec.className);
730
+ if (existing) unwrap(this.api, existing);
731
+ else wrapRange(this.api, range, spec.tag, spec.className);
732
+ }
733
+ checkState() {
734
+ const active = Boolean(this.api.selection.findParentTag(spec.tag.toUpperCase(), spec.className));
735
+ if (this.button) this.button.classList.toggle(this.api.styles.inlineToolButtonActive, active);
736
+ return active;
737
+ }
738
+ };
739
+ const MarkerTool = createFormatTool({
740
+ tag: "mark",
741
+ className: "cdx-marker",
742
+ title: "Marker",
743
+ icon: ICONS.marker,
744
+ shortcut: "CMD+SHIFT+M"
745
+ });
746
+ const UnderlineTool = createFormatTool({
747
+ tag: "u",
748
+ className: "cdx-underline",
749
+ title: "Underline",
252
750
  icon: ICONS.underline,
253
751
  shortcut: "CMD+U"
254
752
  });
@@ -303,7 +801,10 @@ class AttributeInlineTool {
303
801
  this.api.inlineToolbar.close();
304
802
  }
305
803
  });
306
- this.input.addEventListener("blur", () => this.commit());
804
+ this.input.addEventListener("blur", (event) => {
805
+ if (this.actions && event.relatedTarget && this.actions.contains(event.relatedTarget)) return;
806
+ this.commit();
807
+ });
307
808
  this.actions = el("div", { className: "mex-inline-actions", children: [this.input] });
308
809
  this.actions.hidden = true;
309
810
  return this.actions;
@@ -388,7 +889,22 @@ class HyperlinkTool extends AttributeInlineTool {
388
889
  return "Link";
389
890
  }
390
891
  static get sanitize() {
391
- return { a: { href: true, target: true, rel: true } };
892
+ return {
893
+ a: {
894
+ href: true,
895
+ target: true,
896
+ rel: true,
897
+ "data-mex-uid": true,
898
+ "data-mex-document-id": true,
899
+ "data-mex-locale": true
900
+ }
901
+ };
902
+ }
903
+ constructor(options) {
904
+ super(options);
905
+ this.internal = null;
906
+ this.picker = null;
907
+ this.pickerToggle = null;
392
908
  }
393
909
  get shortcut() {
394
910
  return "CMD+K";
@@ -400,341 +916,127 @@ class HyperlinkTool extends AttributeInlineTool {
400
916
  placeholderKey: "tools.hyperlink.placeholder",
401
917
  placeholder: "Paste a link and press Enter",
402
918
  labelKey: "tools.hyperlink.label",
403
- label: "Link address"
404
- };
405
- }
406
- renderActions() {
407
- const actions = super.renderActions();
408
- const newTabId = `mex-newtab-${Math.random().toString(36).slice(2, 8)}`;
409
- this.newTab = el("input", { attrs: { type: "checkbox", id: newTabId } });
410
- this.newTab.checked = this.config.target === "_blank";
411
- this.newTab.addEventListener("change", () => this.commit());
412
- actions.appendChild(
413
- el("label", {
414
- className: "mex-inline-check",
415
- attrs: { for: newTabId },
416
- children: [this.newTab, el("span", { text: this.t("tools.hyperlink.newTab", "Open in a new tab") })]
417
- })
418
- );
419
- return actions;
420
- }
421
- readValue(node) {
422
- if (this.newTab) this.newTab.checked = node.getAttribute("target") === "_blank";
423
- return node.getAttribute("href") || "";
424
- }
425
- writeValue(node, value) {
426
- let url = value;
427
- if (url && !/^[a-z][a-z0-9+.-]*:|^[/#?.]/i.test(url) && /^[^\s/]+\.[^\s]+/.test(url))
428
- url = `https://${url}`;
429
- const safe = sanitize.sanitizeUrl(url);
430
- if (!safe) return false;
431
- node.setAttribute("href", safe);
432
- if (this.newTab && this.newTab.checked) {
433
- node.setAttribute("target", "_blank");
434
- node.setAttribute("rel", "noopener noreferrer");
435
- } else {
436
- node.removeAttribute("target");
437
- node.removeAttribute("rel");
438
- }
439
- return true;
440
- }
441
- }
442
- class AiInlineTool {
443
- static get isInline() {
444
- return true;
445
- }
446
- static get title() {
447
- return "AI assistant";
448
- }
449
- constructor({ api: api2, config }) {
450
- this.api = api2;
451
- this.config = config || {};
452
- this.button = null;
453
- }
454
- get shortcut() {
455
- return "CMD+SHIFT+G";
456
- }
457
- render() {
458
- this.button = el("button", { className: this.api.styles.inlineToolButton, attrs: { type: "button" } });
459
- this.button.innerHTML = ICONS.sparkle;
460
- return this.button;
461
- }
462
- surround(range) {
463
- if (!range || typeof this.config.onAiRequest !== "function") return;
464
- const holder = document.createElement("div");
465
- holder.appendChild(range.cloneContents());
466
- const text = range.toString();
467
- if (!text.trim()) return;
468
- this.config.onAiRequest({ text, html: holder.innerHTML, range: range.cloneRange() });
469
- }
470
- checkState() {
471
- return false;
472
- }
473
- }
474
- const ALERT_TYPES = Object.freeze([
475
- "primary",
476
- "secondary",
477
- "info",
478
- "success",
479
- "warning",
480
- "danger",
481
- "light",
482
- "dark"
483
- ]);
484
- const ALERT_ALIGNMENTS = Object.freeze(["left", "center", "right"]);
485
- const ALIGNMENTS = Object.freeze(["left", "center", "right", "justify"]);
486
- const TEXT_VARIANTS = Object.freeze(["call-out", "citation", "details"]);
487
- const BUTTON_STYLES = Object.freeze(["primary", "secondary", "outline", "ghost", "danger", "success"]);
488
- const CODE_LANGUAGES = Object.freeze([
489
- "plaintext",
490
- "javascript",
491
- "typescript",
492
- "jsx",
493
- "tsx",
494
- "json",
495
- "markup",
496
- "css",
497
- "scss",
498
- "bash",
499
- "python",
500
- "php",
501
- "ruby",
502
- "java",
503
- "kotlin",
504
- "swift",
505
- "csharp",
506
- "c",
507
- "cpp",
508
- "go",
509
- "rust",
510
- "sql",
511
- "graphql",
512
- "yaml",
513
- "markdown",
514
- "docker",
515
- "diff"
516
- ]);
517
- const LANGUAGE_ALIASES = {
518
- js: "javascript",
519
- ts: "typescript",
520
- html: "markup",
521
- xml: "markup",
522
- svg: "markup",
523
- sh: "bash",
524
- shell: "bash",
525
- py: "python",
526
- yml: "yaml",
527
- md: "markdown",
528
- dockerfile: "docker",
529
- "c#": "csharp",
530
- cs: "csharp",
531
- "c++": "cpp",
532
- text: "plaintext",
533
- plain: "plaintext",
534
- none: "plaintext"
535
- };
536
- const str = (value) => typeof value === "string" ? value : "";
537
- const pick = (value, allowed, fallback) => typeof value === "string" && allowed.includes(value) ? value : fallback;
538
- const normalizeAlert = (data, config = {}) => {
539
- const d = data && typeof data === "object" ? data : {};
540
- return {
541
- type: pick(d.type, ALERT_TYPES, pick(config.defaultType, ALERT_TYPES, "info")),
542
- align: pick(d.align, ALERT_ALIGNMENTS, pick(config.defaultAlign, ALERT_ALIGNMENTS, "left")),
543
- // Some editorjs-alert versions wrote `text` instead of `message`.
544
- message: str(d.message) || str(d.text)
545
- };
546
- };
547
- const normalizeAlignment = (data, fallback = "left") => ({
548
- alignment: pick(data && data.alignment, ALIGNMENTS, pick(fallback, ALIGNMENTS, "left"))
549
- });
550
- const normalizeTextVariant = (data) => pick(data, TEXT_VARIANTS, "");
551
- const normalizeLanguage = (language) => {
552
- const raw = str(language).trim().toLowerCase();
553
- const mapped = LANGUAGE_ALIASES[raw] || raw;
554
- return CODE_LANGUAGES.includes(mapped) ? mapped : "plaintext";
555
- };
556
- const normalizeCodeFlask = (data, config = {}) => {
557
- const d = data && typeof data === "object" ? data : {};
558
- return {
559
- code: str(d.code),
560
- language: d.language ? normalizeLanguage(d.language) : normalizeLanguage(config.language || "plaintext"),
561
- showlinenumbers: d.showlinenumbers !== false
562
- };
563
- };
564
- const checklistToList = (data) => {
565
- const items = data && Array.isArray(data.items) ? data.items : [];
566
- return {
567
- style: "checklist",
568
- meta: {},
569
- items: items.map((item) => {
570
- if (typeof item === "string") return { content: item, meta: { checked: false }, items: [] };
571
- const value = item && typeof item === "object" ? item : {};
572
- return {
573
- content: str(value.text) || str(value.content),
574
- meta: { checked: Boolean(value.checked ?? (value.meta && value.meta.checked)) },
575
- items: []
576
- };
577
- })
578
- };
579
- };
580
- const listToChecklist = (data) => {
581
- const out = [];
582
- const walk = (items, depth) => {
583
- if (!Array.isArray(items) || depth > 12) return;
584
- for (const item of items) {
585
- if (!item || typeof item !== "object") continue;
586
- out.push({ text: str(item.content), checked: Boolean(item.meta && item.meta.checked) });
587
- walk(item.items, depth + 1);
588
- }
589
- };
590
- walk(data && data.items, 0);
591
- return { items: out };
592
- };
593
- const normalizeToggle = (data, fallbackKey) => {
594
- const d = data && typeof data === "object" ? data : {};
595
- const items = Number(d.items);
596
- return {
597
- text: str(d.text),
598
- status: d.status === "closed" ? "closed" : "open",
599
- fk: str(d.fk) || str(fallbackKey),
600
- items: Number.isInteger(items) && items > 0 ? Math.min(items, 5e3) : 0
601
- };
602
- };
603
- const toggleChildIndexes = (toggleIndex, items, total) => {
604
- if (!Number.isInteger(toggleIndex) || toggleIndex < 0) return [];
605
- const count = Math.max(0, Math.min(Number(items) || 0, total - toggleIndex - 1));
606
- return Array.from({ length: count }, (_, i) => toggleIndex + 1 + i);
607
- };
608
- const nextToggleItems = (toggleIndex, items, total, action) => {
609
- const current = toggleChildIndexes(toggleIndex, items, total).length;
610
- if (action === "include") return Math.min(current + 1, Math.max(0, total - toggleIndex - 1));
611
- return Math.max(0, current - 1);
612
- };
613
- const normalizeButton = (data) => {
614
- const d = data && typeof data === "object" ? data : {};
615
- return {
616
- text: str(d.text),
617
- link: str(d.link),
618
- style: pick(d.style, BUTTON_STYLES, "primary"),
619
- openInNewTab: d.openInNewTab === true
620
- };
621
- };
622
- const normalizeSimpleImage = (data) => {
623
- const d = data && typeof data === "object" ? data : {};
624
- return {
625
- url: str(d.url),
626
- caption: str(d.caption),
627
- withBorder: d.withBorder === true,
628
- withBackground: d.withBackground === true,
629
- stretched: d.stretched === true
630
- };
631
- };
632
- const normalizePersonality = (data) => {
633
- const d = data && typeof data === "object" ? data : {};
634
- return { name: str(d.name), description: str(d.description), link: str(d.link), photo: str(d.photo) };
635
- };
636
- const normalizeLinkTool = (data) => {
637
- const d = data && typeof data === "object" ? data : {};
638
- const meta = d.meta && typeof d.meta === "object" ? d.meta : {};
639
- const out = { title: str(meta.title), description: str(meta.description) };
640
- if (str(meta.site_name)) out.site_name = str(meta.site_name);
641
- if (meta.image && typeof meta.image === "object" && str(meta.image.url))
642
- out.image = { url: str(meta.image.url) };
643
- return { link: str(d.link), meta: out };
644
- };
645
- const normalizeEmbeddedEntry = (data, config = {}) => {
646
- const d = data && typeof data === "object" ? data : {};
647
- return {
648
- entry: d.entry && typeof d.entry === "object" ? d.entry : null,
649
- contentType: str(d.contentType) || config.contentType || null,
650
- displayMode: pick(d.displayMode, ["card", "inline", "minimal"], "card")
651
- };
652
- };
653
- const summarizeEntry = (entry, config = {}) => {
654
- const titleField = config.titleField || "title";
655
- const title = [entry[titleField], entry.title, entry.name, entry.label, entry.slug].find(
656
- (v) => typeof v === "string" && v.trim()
657
- );
658
- const out = {
659
- id: entry.id,
660
- documentId: entry.documentId,
661
- title: title || String(entry.documentId || entry.id || "")
662
- };
663
- for (const field2 of config.displayFields || []) {
664
- const value = entry[field2];
665
- if (["string", "number", "boolean"].includes(typeof value)) out[field2] = value;
666
- }
667
- return out;
668
- };
669
- const fillTemplate = (template, data) => String(template || "").replace(/\{\{\s*([A-Za-z_][A-Za-z0-9_]{0,39})\s*\}\}/g, (_match, name) => {
670
- const value = data && Object.prototype.hasOwnProperty.call(data, name) ? data[name] : "";
671
- let text = "";
672
- if (value && typeof value === "object") text = typeof value.url === "string" ? value.url : "";
673
- else if (value !== null && value !== void 0) text = String(value);
674
- return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
675
- });
676
- const createHistoryStack = ({ maxSteps = 50 } = {}) => {
677
- let past = [];
678
- let present = null;
679
- let future = [];
680
- return {
681
- /** Sets the starting state without an undo step. */
682
- init(state) {
683
- past = [];
684
- future = [];
685
- present = state;
686
- },
687
- /** Records a new state; identical consecutive states are ignored. @returns {boolean} Recorded. */
688
- push(state) {
689
- if (state === present) return false;
690
- if (present !== null) past.push(present);
691
- if (past.length > maxSteps) past = past.slice(past.length - maxSteps);
692
- present = state;
693
- future = [];
694
- return true;
695
- },
696
- /** @returns {string|null} State to show after undo. */
697
- undo() {
698
- if (past.length === 0) return null;
699
- future.push(present);
700
- present = past.pop();
701
- return present;
702
- },
703
- /** @returns {string|null} State to show after redo. */
704
- redo() {
705
- if (future.length === 0) return null;
706
- past.push(present);
707
- present = future.pop();
708
- return present;
709
- },
710
- /** Replaces the current state without touching undo/redo (re-serialised after a render). */
711
- replacePresent(state) {
712
- present = state;
713
- },
714
- canUndo: () => past.length > 0,
715
- canRedo: () => future.length > 0,
716
- current: () => present,
717
- clear() {
718
- past = [];
719
- future = [];
720
- present = null;
919
+ label: "Link address"
920
+ };
921
+ }
922
+ renderActions() {
923
+ const actions = super.renderActions();
924
+ const newTabId = `mex-newtab-${Math.random().toString(36).slice(2, 8)}`;
925
+ this.newTab = el("input", { attrs: { type: "checkbox", id: newTabId } });
926
+ this.newTab.checked = this.config.target === "_blank";
927
+ this.newTab.addEventListener("change", () => this.commit());
928
+ actions.appendChild(
929
+ el("label", {
930
+ className: "mex-inline-check",
931
+ attrs: { for: newTabId },
932
+ children: [this.newTab, el("span", { text: this.t("tools.hyperlink.newTab", "Open in a new tab") })]
933
+ })
934
+ );
935
+ if (this.config.fetchClient && typeof this.config.fetchClient.get === "function")
936
+ this.renderPicker(actions);
937
+ return actions;
938
+ }
939
+ /**
940
+ * Adds the "Link to an entry" toggle and the picker to the actions panel.
941
+ * @param {HTMLElement} actions - Actions panel.
942
+ */
943
+ renderPicker(actions) {
944
+ this.picker = createLinkPicker({
945
+ t: (id, fallback, values) => this.t(id, fallback, values),
946
+ fetchClient: this.config.fetchClient,
947
+ getLocale: this.config.getLocale,
948
+ onPick: (item) => this.applyInternal(item),
949
+ onClose: () => {
950
+ if (this.pickerToggle) this.pickerToggle.setAttribute("aria-expanded", "false");
951
+ if (this.input) this.input.focus();
952
+ }
953
+ });
954
+ this.pickerToggle = button(this.t("tools.hyperlink.internal.open", "Link to an entry"), {
955
+ icon: ICONS.entry
956
+ });
957
+ this.pickerToggle.classList.add("mex-link-picker__toggle");
958
+ this.pickerToggle.setAttribute("aria-expanded", "false");
959
+ this.pickerToggle.setAttribute("aria-controls", this.picker.element.id);
960
+ this.pickerToggle.addEventListener("click", () => {
961
+ if (this.picker.isOpen()) {
962
+ this.picker.close();
963
+ return;
964
+ }
965
+ this.pickerToggle.setAttribute("aria-expanded", "true");
966
+ this.picker.open();
967
+ });
968
+ actions.append(this.pickerToggle, this.picker.element);
969
+ }
970
+ /**
971
+ * Writes a picked entry into the current link and closes the toolbar.
972
+ * @param {{ href: string, uid: string, documentId: string, locale: string|null }} item - Search result.
973
+ */
974
+ applyInternal(item) {
975
+ if (!this.input) return;
976
+ this.internal = { href: item.href, uid: item.uid, documentId: item.documentId, locale: item.locale };
977
+ this.input.value = item.href;
978
+ if (this.newTab) this.newTab.checked = false;
979
+ this.commit();
980
+ this.api.inlineToolbar.close();
981
+ }
982
+ readValue(node) {
983
+ if (this.newTab) this.newTab.checked = node.getAttribute("target") === "_blank";
984
+ this.internal = readInternalLink(node);
985
+ return node.getAttribute("href") || "";
986
+ }
987
+ writeValue(node, value) {
988
+ let url = value;
989
+ if (url && !/^[a-z][a-z0-9+.-]*:|^[/#?.]/i.test(url) && /^[^\s/]+\.[^\s]+/.test(url))
990
+ url = `https://${url}`;
991
+ const safe = sanitize.sanitizeUrl(url);
992
+ if (!safe) return false;
993
+ node.setAttribute("href", safe);
994
+ for (const [name, attribute] of Object.entries(internalLinkAttributes(this.internal, safe))) {
995
+ if (attribute) node.setAttribute(name, attribute);
996
+ else node.removeAttribute(name);
721
997
  }
722
- };
723
- };
724
- const historyKey = (data) => JSON.stringify(data && data.blocks || []);
725
- const dropIndex = (rects, y, fromIndex) => {
726
- if (rects.length === 0) return fromIndex;
727
- let insertBefore = rects.length;
728
- for (let i = 0; i < rects.length; i += 1) {
729
- const middle = (rects[i].top + rects[i].bottom) / 2;
730
- if (y < middle) {
731
- insertBefore = i;
732
- break;
998
+ if (this.newTab && this.newTab.checked) {
999
+ node.setAttribute("target", "_blank");
1000
+ node.setAttribute("rel", "noopener noreferrer");
1001
+ } else {
1002
+ node.removeAttribute("target");
1003
+ node.removeAttribute("rel");
733
1004
  }
1005
+ return true;
734
1006
  }
735
- const to = insertBefore > fromIndex ? insertBefore - 1 : insertBefore;
736
- return Math.max(0, Math.min(rects.length - 1, to));
737
- };
1007
+ }
1008
+ class AiInlineTool {
1009
+ static get isInline() {
1010
+ return true;
1011
+ }
1012
+ static get title() {
1013
+ return "AI assistant";
1014
+ }
1015
+ constructor({ api: api2, config }) {
1016
+ this.api = api2;
1017
+ this.config = config || {};
1018
+ this.button = null;
1019
+ }
1020
+ get shortcut() {
1021
+ return "CMD+SHIFT+G";
1022
+ }
1023
+ render() {
1024
+ this.button = el("button", { className: this.api.styles.inlineToolButton, attrs: { type: "button" } });
1025
+ this.button.innerHTML = ICONS.sparkle;
1026
+ return this.button;
1027
+ }
1028
+ surround(range) {
1029
+ if (!range || typeof this.config.onAiRequest !== "function") return;
1030
+ const holder = document.createElement("div");
1031
+ holder.appendChild(range.cloneContents());
1032
+ const text = range.toString();
1033
+ if (!text.trim()) return;
1034
+ this.config.onAiRequest({ text, html: holder.innerHTML, range: range.cloneRange() });
1035
+ }
1036
+ checkState() {
1037
+ return false;
1038
+ }
1039
+ }
738
1040
  const ALIGN_ICONS = {
739
1041
  left: ICONS.alignLeft,
740
1042
  center: ICONS.alignCenter,
@@ -1030,6 +1332,7 @@ class SimpleImageTool extends BaseTool {
1030
1332
  urlInput.addEventListener("keydown", (event) => {
1031
1333
  if (event.key === "Enter") {
1032
1334
  event.preventDefault();
1335
+ event.stopPropagation();
1033
1336
  apply();
1034
1337
  }
1035
1338
  });
@@ -1360,6 +1663,7 @@ class LinkPreviewTool extends BaseTool {
1360
1663
  urlInput.addEventListener("keydown", (event) => {
1361
1664
  if (event.key === "Enter") {
1362
1665
  event.preventDefault();
1666
+ event.stopPropagation();
1363
1667
  this.fetch(urlInput.value.trim(), status, urlInput);
1364
1668
  }
1365
1669
  });
@@ -2206,6 +2510,7 @@ const createUndoManager = (editor, options = {}) => {
2206
2510
  let timer = null;
2207
2511
  let applying = false;
2208
2512
  let destroyed = false;
2513
+ let delegate = null;
2209
2514
  const states = /* @__PURE__ */ new Map();
2210
2515
  const notify = () => {
2211
2516
  if (typeof options.onChange === "function")
@@ -2257,14 +2562,23 @@ const createUndoManager = (editor, options = {}) => {
2257
2562
  };
2258
2563
  if (holder) holder.addEventListener("keydown", onKeyDown, true);
2259
2564
  const manager = {
2565
+ /**
2566
+ * Routes undo/redo to another history (live collaboration) or back (null).
2567
+ * @param {{ undo: () => boolean, redo: () => boolean, stopCapturing?: () => void }|null} next - Delegate.
2568
+ */
2569
+ setDelegate(next) {
2570
+ delegate = next;
2571
+ notify();
2572
+ },
2260
2573
  /** Records the current state after the debounce. */
2261
2574
  record() {
2262
- if (destroyed || paused > 0 || applying) return;
2575
+ if (destroyed || paused > 0 || applying || delegate) return;
2263
2576
  window.clearTimeout(timer);
2264
2577
  timer = window.setTimeout(snapshot, debounceMs);
2265
2578
  },
2266
2579
  /** Steps back. @returns {Promise<boolean>} True when something changed. */
2267
2580
  async undo() {
2581
+ if (delegate) return delegate.undo();
2268
2582
  window.clearTimeout(timer);
2269
2583
  await snapshot();
2270
2584
  const key = stack.undo();
@@ -2274,6 +2588,7 @@ const createUndoManager = (editor, options = {}) => {
2274
2588
  },
2275
2589
  /** Steps forward. @returns {Promise<boolean>} True when something changed. */
2276
2590
  async redo() {
2591
+ if (delegate) return delegate.redo();
2277
2592
  const key = stack.redo();
2278
2593
  if (!key) return false;
2279
2594
  await apply(key);
@@ -2544,7 +2859,11 @@ function buildTools(ctx) {
2544
2859
  strikethrough: { class: StrikethroughTool, shortcut: "CMD+SHIFT+X" },
2545
2860
  inlineCode: { class: InlineCode__default.default, shortcut: "CMD+SHIFT+I" },
2546
2861
  tooltip: { class: TooltipTool, config: { t } },
2547
- hyperlink: { class: HyperlinkTool, shortcut: "CMD+K", config: { t, target: "_blank" } },
2862
+ hyperlink: {
2863
+ class: HyperlinkTool,
2864
+ shortcut: "CMD+K",
2865
+ config: { t, target: "_blank", fetchClient: ctx.fetchClient, getLocale: ctx.getContentLocale }
2866
+ },
2548
2867
  alignmentTune: { class: AlignmentTune, config: { t, default: "left" } },
2549
2868
  textVariant: { class: TextVariantTune, config: { t } },
2550
2869
  indentTune: {
@@ -3064,6 +3383,78 @@ const editorStyles = styled.css`
3064
3383
  min-width: 24rem;
3065
3384
  }
3066
3385
 
3386
+ .mex-link-picker__toggle {
3387
+ align-self: flex-start;
3388
+ }
3389
+
3390
+ .mex-link-picker {
3391
+ display: flex;
3392
+ flex-direction: column;
3393
+ gap: ${s(2)};
3394
+ width: 100%;
3395
+ min-width: 0;
3396
+ border-top: 1px solid ${c("neutral150")};
3397
+ padding-top: ${s(2)};
3398
+
3399
+ &[hidden] {
3400
+ display: none;
3401
+ }
3402
+ }
3403
+
3404
+ .mex-link-picker__controls {
3405
+ display: grid;
3406
+ grid-template-columns: minmax(0, 1fr);
3407
+ gap: ${s(2)};
3408
+ }
3409
+
3410
+ .mex-link-picker__results {
3411
+ list-style: none;
3412
+ margin: 0;
3413
+ padding: 0;
3414
+ display: flex;
3415
+ flex-direction: column;
3416
+ gap: ${s(1)};
3417
+ max-height: 24rem;
3418
+ overflow: auto;
3419
+
3420
+ &:empty {
3421
+ display: none;
3422
+ }
3423
+ }
3424
+
3425
+ .mex-link-picker__option {
3426
+ display: flex;
3427
+ flex-direction: column;
3428
+ gap: ${s(1)};
3429
+ border: 1px solid ${c("neutral150")};
3430
+ border-radius: ${radius};
3431
+ background: ${c("neutral0")};
3432
+ color: ${c("neutral800")};
3433
+ padding: ${s(2)} ${s(3)};
3434
+ cursor: pointer;
3435
+ font-size: ${f(2)};
3436
+
3437
+ &:hover,
3438
+ &[aria-selected='true'] {
3439
+ background: ${c("primary100")};
3440
+ border-color: ${c("primary600")};
3441
+ }
3442
+
3443
+ &[aria-disabled='true'] {
3444
+ cursor: not-allowed;
3445
+ color: ${c("neutral600")};
3446
+ }
3447
+ }
3448
+
3449
+ .mex-link-picker__title {
3450
+ overflow-wrap: anywhere;
3451
+ }
3452
+
3453
+ .mex-link-picker__meta {
3454
+ color: ${c("neutral600")};
3455
+ font-size: ${f(1)};
3456
+ }
3457
+
3067
3458
  .ce-stub {
3068
3459
  background: ${c("neutral100")};
3069
3460
  color: ${c("neutral800")};
@@ -3800,6 +4191,63 @@ const editorStyles = styled.css`
3800
4191
  font-size: ${f(1)};
3801
4192
  }
3802
4193
 
4194
+ /* Placeholder for embeds and images the admin CSP blocks (csp-guard.js). */
4195
+ .mex-csp-blocked {
4196
+ display: flex;
4197
+ align-items: flex-start;
4198
+ gap: ${s(3)};
4199
+ max-width: 100%;
4200
+ box-sizing: border-box;
4201
+ padding: ${s(4)};
4202
+ border: 1px solid ${c("warning200")};
4203
+ border-inline-start: 4px solid ${c("warning600")};
4204
+ border-radius: ${radius};
4205
+ background: ${c("warning100")};
4206
+ color: ${c("neutral800")};
4207
+ font-size: ${f(2)};
4208
+ line-height: 1.5;
4209
+ overflow-wrap: anywhere;
4210
+ }
4211
+
4212
+ .mex-csp-blocked + iframe,
4213
+ .mex-csp-blocked + img {
4214
+ display: none !important;
4215
+ }
4216
+
4217
+ .mex-csp-blocked__icon {
4218
+ flex: 0 0 auto;
4219
+ display: inline-flex;
4220
+ color: ${c("warning700")};
4221
+ }
4222
+
4223
+ .mex-csp-blocked__text {
4224
+ display: flex;
4225
+ flex-direction: column;
4226
+ gap: ${s(1)};
4227
+ min-width: 0;
4228
+ }
4229
+
4230
+ .mex-csp-blocked__text p {
4231
+ margin: 0;
4232
+ }
4233
+
4234
+ .mex-csp-blocked__title {
4235
+ font-weight: 600;
4236
+ }
4237
+
4238
+ .mex-csp-blocked__link {
4239
+ align-self: flex-start;
4240
+ color: ${c("primary700")};
4241
+ font-weight: 600;
4242
+ text-decoration: underline;
4243
+ }
4244
+
4245
+ .mex-csp-blocked__link:focus-visible {
4246
+ outline: 2px solid ${c("primary600")};
4247
+ outline-offset: 2px;
4248
+ border-radius: ${radius};
4249
+ }
4250
+
3803
4251
  ${({ theme }) => theme.breakpoints.medium} {
3804
4252
  .ce-block__content {
3805
4253
  padding-inline-start: ${s(10)};
@@ -3807,7 +4255,136 @@ const editorStyles = styled.css`
3807
4255
  }
3808
4256
  }
3809
4257
  `;
3810
- const YDOC_SCHEMA = 2;
4258
+ const matchesBlockedUri = (elementUrl, blockedUri) => {
4259
+ if (typeof elementUrl !== "string" || typeof blockedUri !== "string" || !elementUrl || !blockedUri) {
4260
+ return false;
4261
+ }
4262
+ if (elementUrl === blockedUri) return true;
4263
+ let element;
4264
+ let blocked;
4265
+ try {
4266
+ element = new URL(elementUrl);
4267
+ blocked = new URL(blockedUri);
4268
+ } catch {
4269
+ return false;
4270
+ }
4271
+ if (element.origin !== blocked.origin) return false;
4272
+ if (blocked.pathname === "/" && !blocked.search) return true;
4273
+ return element.href.split("#")[0] === blocked.href.split("#")[0];
4274
+ };
4275
+ const createCspGuard = (holder, options) => {
4276
+ const { t, settingsHref = null, onOpenSettings = null } = options;
4277
+ const violations = [];
4278
+ const timers = /* @__PURE__ */ new Set();
4279
+ let destroyed = false;
4280
+ const kindOf2 = (directive) => {
4281
+ if (directive === "frame-src" || directive === "child-src") return "frame";
4282
+ if (directive === "img-src") return "image";
4283
+ return null;
4284
+ };
4285
+ const placeholder = (kind, url) => {
4286
+ let host;
4287
+ try {
4288
+ host = new URL(url).host;
4289
+ } catch {
4290
+ host = "";
4291
+ }
4292
+ const title = kind === "frame" ? t("tools.csp.embedBlocked", "This embed is blocked by your Content Security Policy.") : t("tools.csp.imageBlocked", "This image is blocked by your Content Security Policy.");
4293
+ const body = host ? t(
4294
+ "tools.csp.hostBlocked",
4295
+ "The admin does not allow content from {host}. The block is saved unchanged and still appears on your website.",
4296
+ { host }
4297
+ ) : t(
4298
+ "tools.csp.blockedGeneric",
4299
+ "The admin does not allow this content. The block is saved unchanged and still appears on your website."
4300
+ );
4301
+ const icon = el("span", { className: "mex-csp-blocked__icon", attrs: { "aria-hidden": "true" } });
4302
+ icon.innerHTML = ICONS.alert;
4303
+ const text = el("div", {
4304
+ className: "mex-csp-blocked__text",
4305
+ children: [
4306
+ el("p", { className: "mex-csp-blocked__title", text: title }),
4307
+ el("p", { className: "mex-csp-blocked__body", text: body })
4308
+ ]
4309
+ });
4310
+ if (settingsHref) {
4311
+ const link = el("a", {
4312
+ className: "mex-csp-blocked__link",
4313
+ text: t("tools.csp.howTo", "How to allow it"),
4314
+ attrs: { href: settingsHref }
4315
+ });
4316
+ link.addEventListener("click", (event) => {
4317
+ if (!onOpenSettings || event.button !== 0) return;
4318
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
4319
+ event.preventDefault();
4320
+ onOpenSettings();
4321
+ });
4322
+ text.appendChild(link);
4323
+ } else {
4324
+ text.appendChild(
4325
+ el("p", {
4326
+ className: "mex-csp-blocked__body",
4327
+ text: t("tools.csp.askAdmin", "Ask an administrator to allow it in the Content Security Policy.")
4328
+ })
4329
+ );
4330
+ }
4331
+ return el("div", {
4332
+ className: "mex-csp-blocked",
4333
+ attrs: { role: "note", contenteditable: "false", "data-mutation-free": "true" },
4334
+ children: [icon, text]
4335
+ });
4336
+ };
4337
+ const mark = (element, kind) => {
4338
+ const previous = element.previousElementSibling;
4339
+ if (previous && previous.classList.contains("mex-csp-blocked")) return;
4340
+ if (!element.parentNode) return;
4341
+ element.parentNode.insertBefore(placeholder(kind, element.getAttribute("src") || ""), element);
4342
+ };
4343
+ const scan = (kind, blockedUri) => {
4344
+ const selector = kind === "frame" ? "iframe" : "img";
4345
+ holder.querySelectorAll(selector).forEach((element) => {
4346
+ if (matchesBlockedUri(element.src, blockedUri)) mark(element, kind);
4347
+ });
4348
+ };
4349
+ const onViolation = (event) => {
4350
+ if (destroyed || event.disposition === "report") return;
4351
+ const kind = kindOf2(event.effectiveDirective || event.violatedDirective);
4352
+ if (!kind || !event.blockedURI) return;
4353
+ violations.push({ kind, uri: event.blockedURI });
4354
+ if (violations.length > 100) violations.shift();
4355
+ scan(kind, event.blockedURI);
4356
+ };
4357
+ const checkImage = (image) => {
4358
+ if (destroyed || !holder.contains(image)) return false;
4359
+ const hit = violations.find((entry) => entry.kind === "image" && matchesBlockedUri(image.src, entry.uri));
4360
+ if (hit) mark(image, "image");
4361
+ return Boolean(hit);
4362
+ };
4363
+ const onError = (event) => {
4364
+ const image = event.target;
4365
+ if (!image || image.tagName !== "IMG" || checkImage(image)) return;
4366
+ const timer = setTimeout(() => {
4367
+ timers.delete(timer);
4368
+ checkImage(image);
4369
+ }, 150);
4370
+ timers.add(timer);
4371
+ };
4372
+ document.addEventListener("securitypolicyviolation", onViolation);
4373
+ holder.addEventListener("error", onError, true);
4374
+ return {
4375
+ destroy() {
4376
+ destroyed = true;
4377
+ document.removeEventListener("securitypolicyviolation", onViolation);
4378
+ holder.removeEventListener("error", onError, true);
4379
+ timers.forEach((timer) => clearTimeout(timer));
4380
+ timers.clear();
4381
+ }
4382
+ };
4383
+ };
4384
+ const YDOC_SCHEMA = 3;
4385
+ const MAX_DEPTH = sanitize.EDITOR_DATA_LIMITS.maxDepth;
4386
+ const FORBIDDEN_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
4387
+ const hasOwn = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
3811
4388
  const getTypes = (doc) => ({
3812
4389
  meta: doc.getMap("meta"),
3813
4390
  order: doc.getArray("order"),
@@ -3816,9 +4393,10 @@ const getTypes = (doc) => ({
3816
4393
  const stableStringify = (value) => {
3817
4394
  if (value === null || typeof value !== "object") return JSON.stringify(value === void 0 ? null : value);
3818
4395
  if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
3819
- const keys = Object.keys(value).sort();
3820
- return `{${keys.map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(",")}}`;
4396
+ const keys2 = Object.keys(value).sort();
4397
+ return `{${keys2.map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(",")}}`;
3821
4398
  };
4399
+ const equal = (a, b) => a === b || stableStringify(a) === stableStringify(b);
3822
4400
  const applyTextDiff = (ytext, next) => {
3823
4401
  const current = ytext.toString();
3824
4402
  if (current === next) return false;
@@ -3835,31 +4413,95 @@ const applyTextDiff = (ytext, next) => {
3835
4413
  if (endNext > start) ytext.insert(start, next.slice(start, endNext));
3836
4414
  return true;
3837
4415
  };
4416
+ const applyTextEdit = (ytext, base, local) => {
4417
+ if (base === local) return false;
4418
+ const shared = ytext.toString();
4419
+ if (shared === base) return applyTextDiff(ytext, local);
4420
+ let start = 0;
4421
+ while (start < base.length && start < local.length && base.charCodeAt(start) === local.charCodeAt(start))
4422
+ start += 1;
4423
+ let endBase = base.length;
4424
+ let endLocal = local.length;
4425
+ while (endBase > start && endLocal > start && base.charCodeAt(endBase - 1) === local.charCodeAt(endLocal - 1)) {
4426
+ endBase -= 1;
4427
+ endLocal -= 1;
4428
+ }
4429
+ let rp = 0;
4430
+ while (rp < base.length && rp < shared.length && base.charCodeAt(rp) === shared.charCodeAt(rp)) rp += 1;
4431
+ let rsBase = base.length;
4432
+ let rsShared = shared.length;
4433
+ while (rsBase > rp && rsShared > rp && base.charCodeAt(rsBase - 1) === shared.charCodeAt(rsShared - 1)) {
4434
+ rsBase -= 1;
4435
+ rsShared -= 1;
4436
+ }
4437
+ const shift = shared.length - base.length;
4438
+ const map = (index2) => index2 <= rp ? index2 : index2 >= rsBase ? index2 + shift : Math.min(index2 + shift, shared.length);
4439
+ const from = map(start);
4440
+ const to = Math.max(from, map(endBase));
4441
+ if (to > from) ytext.delete(from, Math.min(to, shared.length) - from);
4442
+ const inserted = local.slice(start, endLocal);
4443
+ if (inserted) ytext.insert(Math.min(from, ytext.length), inserted);
4444
+ return true;
4445
+ };
4446
+ const toShared = (value, depth = 0) => {
4447
+ if (depth > MAX_DEPTH) return null;
4448
+ if (typeof value === "string") return value ? new Y__namespace.Text(value) : new Y__namespace.Text();
4449
+ if (Array.isArray(value)) return Y__namespace.Array.from(value.map((item) => toShared(item, depth + 1)));
4450
+ if (sanitize.isPlainObject(value)) {
4451
+ const entries = [];
4452
+ for (const key of Object.keys(value)) {
4453
+ if (FORBIDDEN_KEYS.has(key) || value[key] === void 0) continue;
4454
+ entries.push([key, toShared(value[key], depth + 1)]);
4455
+ }
4456
+ return new Y__namespace.Map(entries);
4457
+ }
4458
+ if (typeof value === "number") return Number.isFinite(value) ? value : null;
4459
+ if (typeof value === "boolean" || value === null) return value;
4460
+ return null;
4461
+ };
4462
+ const readShared = (value, depth = 0) => {
4463
+ if (value instanceof Y__namespace.Text) return value.toString();
4464
+ if (depth > MAX_DEPTH) return null;
4465
+ if (value instanceof Y__namespace.Array) return value.toArray().map((item) => readShared(item, depth + 1));
4466
+ if (value instanceof Y__namespace.Map) {
4467
+ const out = {};
4468
+ value.forEach((item, key) => {
4469
+ if (!FORBIDDEN_KEYS.has(key)) out[key] = readShared(item, depth + 1);
4470
+ });
4471
+ return out;
4472
+ }
4473
+ if (value instanceof Y__namespace.AbstractType) return null;
4474
+ if (value === void 0) return null;
4475
+ if (value !== null && typeof value === "object") {
4476
+ try {
4477
+ return sanitize.cloneJsonSafe(value, depth) ?? null;
4478
+ } catch {
4479
+ return null;
4480
+ }
4481
+ }
4482
+ if (typeof value === "number" && !Number.isFinite(value)) return null;
4483
+ return value;
4484
+ };
3838
4485
  const readBlock = (id, entry) => {
3839
4486
  if (!(entry instanceof Y__namespace.Map)) return null;
3840
4487
  const type = entry.get("type");
3841
4488
  if (typeof type !== "string" || !type) return null;
3842
- const dataMap = entry.get("data");
3843
- const data = {};
3844
- if (dataMap instanceof Y__namespace.Map) {
3845
- dataMap.forEach((value, key) => {
3846
- data[key] = value instanceof Y__namespace.Text ? value.toString() : value;
3847
- });
3848
- }
3849
- const block = { id, type, data };
3850
- const tunes = entry.get("tunes");
4489
+ const rawData = readShared(entry.get("data"), 2);
4490
+ const block = { id, type, data: sanitize.isPlainObject(rawData) ? rawData : {} };
4491
+ const tunes = readShared(entry.get("tunes"), 2);
3851
4492
  if (sanitize.isPlainObject(tunes) && Object.keys(tunes).length > 0) block.tunes = tunes;
3852
4493
  return block;
3853
4494
  };
3854
- const docToEditorData = (doc) => {
4495
+ const docToEditorData = (doc, read = readBlock) => {
3855
4496
  const { meta, order, blocks } = getTypes(doc);
3856
4497
  const seen = /* @__PURE__ */ new Set();
3857
4498
  const out = [];
3858
4499
  for (const id of order.toArray()) {
3859
4500
  if (typeof id !== "string" || seen.has(id)) continue;
3860
4501
  seen.add(id);
3861
- const block = readBlock(id, blocks.get(id));
4502
+ const block = read(id, blocks.get(id));
3862
4503
  if (block) out.push(block);
4504
+ if (out.length >= sanitize.EDITOR_DATA_LIMITS.maxBlocks) break;
3863
4505
  }
3864
4506
  return {
3865
4507
  time: Number(meta.get("time")) || 0,
@@ -3867,38 +4509,34 @@ const docToEditorData = (doc) => {
3867
4509
  version: typeof meta.get("version") === "string" ? meta.get("version") : "2.31.7"
3868
4510
  };
3869
4511
  };
3870
- const writeData = (entry, data) => {
3871
- let dataMap = entry.get("data");
3872
- if (!(dataMap instanceof Y__namespace.Map)) {
3873
- dataMap = new Y__namespace.Map();
3874
- entry.set("data", dataMap);
3875
- }
3876
- let changed = false;
3877
- for (const key of Array.from(dataMap.keys())) {
3878
- if (!Object.prototype.hasOwnProperty.call(data, key)) {
3879
- dataMap.delete(key);
3880
- changed = true;
3881
- }
3882
- }
3883
- for (const [key, value] of Object.entries(data)) {
3884
- const current = dataMap.get(key);
3885
- if (typeof value === "string") {
3886
- if (current instanceof Y__namespace.Text) {
3887
- changed = applyTextDiff(current, value) || changed;
3888
- } else {
3889
- const text = new Y__namespace.Text();
3890
- dataMap.set(key, text);
3891
- text.insert(0, value);
3892
- changed = true;
4512
+ const createDocReader = (doc) => {
4513
+ const { blocks } = getTypes(doc);
4514
+ const cache = /* @__PURE__ */ new Map();
4515
+ const observer = (events) => {
4516
+ for (const event of events) {
4517
+ if (event.target === blocks) {
4518
+ event.keysChanged.forEach((key) => cache.delete(key));
4519
+ } else if (event.path.length > 0) {
4520
+ cache.delete(event.path[0]);
3893
4521
  }
3894
- } else if (current instanceof Y__namespace.Text || stableStringify(current) !== stableStringify(value)) {
3895
- dataMap.set(key, value === void 0 ? null : value);
3896
- changed = true;
3897
4522
  }
3898
- }
3899
- return changed;
4523
+ };
4524
+ blocks.observeDeep(observer);
4525
+ const read = (id, entry) => {
4526
+ if (cache.has(id)) return cache.get(id);
4527
+ const block = readBlock(id, entry);
4528
+ cache.set(id, block);
4529
+ return block;
4530
+ };
4531
+ return {
4532
+ read: () => docToEditorData(doc, read),
4533
+ destroy: () => {
4534
+ blocks.unobserveDeep(observer);
4535
+ cache.clear();
4536
+ }
4537
+ };
3900
4538
  };
3901
- const lcsKeep = (a, b) => {
4539
+ const lcsPairs = (a, b) => {
3902
4540
  let start = 0;
3903
4541
  while (start < a.length && start < b.length && a[start] === b[start]) start += 1;
3904
4542
  let endA = a.length;
@@ -3907,68 +4545,161 @@ const lcsKeep = (a, b) => {
3907
4545
  endA -= 1;
3908
4546
  endB -= 1;
3909
4547
  }
3910
- const keep = /* @__PURE__ */ new Set();
3911
- for (let i2 = 0; i2 < start; i2 += 1) keep.add(i2);
3912
- for (let i2 = endA; i2 < a.length; i2 += 1) keep.add(i2);
3913
- const midA = a.slice(start, endA);
3914
- const midB = b.slice(start, endB);
3915
- if (midA.length === 0 || midB.length === 0) return keep;
3916
- if (midA.length * midB.length > 4e6) return keep;
3917
- const rows = midA.length + 1;
3918
- const cols = midB.length + 1;
3919
- const table = new Uint16Array(rows * cols);
3920
- for (let i2 = midA.length - 1; i2 >= 0; i2 -= 1) {
3921
- for (let j2 = midB.length - 1; j2 >= 0; j2 -= 1) {
3922
- table[i2 * cols + j2] = midA[i2] === midB[j2] ? table[(i2 + 1) * cols + j2 + 1] + 1 : Math.max(table[(i2 + 1) * cols + j2], table[i2 * cols + j2 + 1]);
3923
- }
3924
- }
3925
- let i = 0;
3926
- let j = 0;
3927
- while (i < midA.length && j < midB.length) {
3928
- if (midA[i] === midB[j]) {
3929
- keep.add(start + i);
3930
- i += 1;
3931
- j += 1;
3932
- } else if (table[(i + 1) * cols + j] >= table[i * cols + j + 1]) i += 1;
3933
- else j += 1;
3934
- }
3935
- return keep;
4548
+ const pairs = [];
4549
+ for (let i = 0; i < start; i += 1) pairs.push([i, i]);
4550
+ const midA = endA - start;
4551
+ const midB = endB - start;
4552
+ if (midA > 0 && midB > 0 && midA * midB <= 4e6) {
4553
+ const cols = midB + 1;
4554
+ const table = new Uint16Array((midA + 1) * cols);
4555
+ for (let i2 = midA - 1; i2 >= 0; i2 -= 1) {
4556
+ for (let j2 = midB - 1; j2 >= 0; j2 -= 1) {
4557
+ table[i2 * cols + j2] = a[start + i2] === b[start + j2] ? table[(i2 + 1) * cols + j2 + 1] + 1 : Math.max(table[(i2 + 1) * cols + j2], table[i2 * cols + j2 + 1]);
4558
+ }
4559
+ }
4560
+ let i = 0;
4561
+ let j = 0;
4562
+ while (i < midA && j < midB) {
4563
+ if (a[start + i] === b[start + j]) {
4564
+ pairs.push([start + i, start + j]);
4565
+ i += 1;
4566
+ j += 1;
4567
+ } else if (table[(i + 1) * cols + j] >= table[i * cols + j + 1]) i += 1;
4568
+ else j += 1;
4569
+ }
4570
+ }
4571
+ for (let k = 0; k < a.length - endA; k += 1) pairs.push([endA + k, endB + k]);
4572
+ return pairs;
3936
4573
  };
3937
- const applyTextEdit = (ytext, base, local) => {
3938
- if (base === local) return false;
3939
- const shared = ytext.toString();
3940
- if (shared === base) return applyTextDiff(ytext, local);
3941
- let start = 0;
3942
- while (start < base.length && start < local.length && base.charCodeAt(start) === local.charCodeAt(start))
3943
- start += 1;
3944
- let endBase = base.length;
3945
- let endLocal = local.length;
3946
- while (endBase > start && endLocal > start && base.charCodeAt(endBase - 1) === local.charCodeAt(endLocal - 1)) {
3947
- endBase -= 1;
3948
- endLocal -= 1;
4574
+ const kindOf = (value) => {
4575
+ if (typeof value === "string" || value instanceof Y__namespace.Text) return "text";
4576
+ if (Array.isArray(value) || value instanceof Y__namespace.Array) return "array";
4577
+ if (sanitize.isPlainObject(value) || value instanceof Y__namespace.Map) return "map";
4578
+ return "scalar";
4579
+ };
4580
+ const diffHunks = (a, b) => {
4581
+ const pairs = lcsPairs(a.map(stableStringify), b.map(stableStringify));
4582
+ const hunks = [];
4583
+ let pa = 0;
4584
+ let pb = 0;
4585
+ for (const [i, j] of [...pairs, [a.length, b.length]]) {
4586
+ if (i > pa || j > pb) hunks.push({ a0: pa, a1: i, b0: pb, b1: j });
4587
+ pa = i + 1;
4588
+ pb = j + 1;
4589
+ }
4590
+ return hunks;
4591
+ };
4592
+ const alignIndexes = (base, current) => {
4593
+ const map = new Array(base.length).fill(-1);
4594
+ if (base.length === current.length && equal(base, current)) return base.map((_, i) => i);
4595
+ for (const [i, j] of lcsPairs(base.map(stableStringify), current.map(stableStringify))) map[i] = j;
4596
+ for (const hunk of diffHunks(base, current)) {
4597
+ const n = Math.min(hunk.a1 - hunk.a0, hunk.b1 - hunk.b0);
4598
+ for (let k = 0; k < n; k += 1) {
4599
+ if (kindOf(base[hunk.a0 + k]) === kindOf(current[hunk.b0 + k])) map[hunk.a0 + k] = hunk.b0 + k;
4600
+ }
3949
4601
  }
3950
- let rp = 0;
3951
- while (rp < base.length && rp < shared.length && base.charCodeAt(rp) === shared.charCodeAt(rp)) rp += 1;
3952
- let rsBase = base.length;
3953
- let rsShared = shared.length;
3954
- while (rsBase > rp && rsShared > rp && base.charCodeAt(rsBase - 1) === shared.charCodeAt(rsShared - 1)) {
3955
- rsBase -= 1;
3956
- rsShared -= 1;
4602
+ return map;
4603
+ };
4604
+ const mergeValue = (current, base, local, depth) => {
4605
+ if (base !== void 0 && equal(base, local)) return "same";
4606
+ if (depth > MAX_DEPTH) return "replace";
4607
+ if (typeof local === "string" && current instanceof Y__namespace.Text) {
4608
+ applyTextEdit(current, typeof base === "string" ? base : current.toString(), local);
4609
+ return "merged";
4610
+ }
4611
+ if (Array.isArray(local) && current instanceof Y__namespace.Array) {
4612
+ mergeArray(current, Array.isArray(base) ? base : readShared(current, depth), local, depth);
4613
+ return "merged";
4614
+ }
4615
+ if (sanitize.isPlainObject(local) && current instanceof Y__namespace.Map) {
4616
+ mergeMap(current, sanitize.isPlainObject(base) ? base : readShared(current, depth), local, depth);
4617
+ return "merged";
4618
+ }
4619
+ if (!(current instanceof Y__namespace.AbstractType) && equal(readShared(current, depth), local)) return "same";
4620
+ return "replace";
4621
+ };
4622
+ const mergeMap = (ymap, base, local, depth) => {
4623
+ const keys2 = /* @__PURE__ */ new Set([...Object.keys(base), ...Object.keys(local)]);
4624
+ for (const key of keys2) {
4625
+ if (FORBIDDEN_KEYS.has(key)) continue;
4626
+ const inLocal = hasOwn(local, key) && local[key] !== void 0;
4627
+ const inBase = hasOwn(base, key) && base[key] !== void 0;
4628
+ if (!inLocal) {
4629
+ if (inBase && ymap.has(key)) ymap.delete(key);
4630
+ continue;
4631
+ }
4632
+ const result = mergeValue(ymap.get(key), inBase ? base[key] : void 0, local[key], depth + 1);
4633
+ if (result === "replace") ymap.set(key, toShared(local[key], depth + 1));
4634
+ }
4635
+ };
4636
+ const mergeArray = (yarray, base, local, depth) => {
4637
+ if (equal(base, local)) return;
4638
+ const raw = yarray.toArray();
4639
+ const current = raw.map((item) => readShared(item, depth + 1));
4640
+ const target = alignIndexes(base, current);
4641
+ const ops = [];
4642
+ for (const hunk of diffHunks(base, local)) {
4643
+ const n = Math.min(hunk.a1 - hunk.a0, hunk.b1 - hunk.b0);
4644
+ for (let k = 0; k < n; k += 1) {
4645
+ const bi = hunk.a0 + k;
4646
+ if (target[bi] >= 0)
4647
+ ops.push({ at: target[bi], rank: 0, kind: "modify", bi, value: local[hunk.b0 + k] });
4648
+ }
4649
+ for (let bi = hunk.a0 + n; bi < hunk.a1; bi += 1) {
4650
+ if (target[bi] >= 0) ops.push({ at: target[bi], rank: 0, kind: "delete" });
4651
+ }
4652
+ if (hunk.b1 - hunk.b0 > n) {
4653
+ let at = 0;
4654
+ for (let bi = hunk.a0 + n - 1; bi >= 0; bi -= 1) {
4655
+ if (target[bi] >= 0) {
4656
+ at = target[bi] + 1;
4657
+ break;
4658
+ }
4659
+ }
4660
+ ops.push({ at, rank: 1, order: hunk.b0, kind: "insert", values: local.slice(hunk.b0 + n, hunk.b1) });
4661
+ }
4662
+ }
4663
+ ops.sort((x, y) => y.at - x.at || x.rank - y.rank || (y.order || 0) - (x.order || 0));
4664
+ for (const op of ops) {
4665
+ if (op.kind === "insert") {
4666
+ yarray.insert(
4667
+ Math.min(op.at, yarray.length),
4668
+ op.values.map((value) => toShared(value, depth + 1))
4669
+ );
4670
+ } else if (op.kind === "delete") {
4671
+ yarray.delete(op.at, 1);
4672
+ } else {
4673
+ const result = mergeValue(raw[op.at], base[op.bi], op.value, depth + 1);
4674
+ if (result === "replace") {
4675
+ yarray.delete(op.at, 1);
4676
+ yarray.insert(op.at, [toShared(op.value, depth + 1)]);
4677
+ }
4678
+ }
3957
4679
  }
3958
- const shift = shared.length - base.length;
3959
- const map = (index2) => index2 <= rp ? index2 : index2 >= rsBase ? index2 + shift : Math.min(index2 + shift, shared.length);
3960
- const from = map(start);
3961
- const to = Math.max(from, map(endBase));
3962
- if (to > from) ytext.delete(from, Math.min(to, shared.length) - from);
3963
- const inserted = local.slice(start, endLocal);
3964
- if (inserted) ytext.insert(Math.min(from, ytext.length), inserted);
3965
- return true;
3966
4680
  };
4681
+ const mergeSlot = (ymap, key, base, local, depth) => {
4682
+ const result = mergeValue(ymap.get(key), base, local, depth);
4683
+ if (result === "replace") ymap.set(key, toShared(local, depth));
4684
+ return result !== "same";
4685
+ };
4686
+ const createEntry = (block) => new Y__namespace.Map([
4687
+ ["type", block.type],
4688
+ ["tunes", toShared(sanitize.isPlainObject(block.tunes) ? block.tunes : {}, 2)],
4689
+ ["data", toShared(sanitize.isPlainObject(block.data) ? block.data : {}, 2)]
4690
+ ]);
3967
4691
  const applyLocalChanges = (doc, base, local, origin = "local") => {
3968
4692
  const { meta, order, blocks } = getTypes(doc);
3969
4693
  const baseById = new Map((base.blocks || []).map((block) => [block.id, block]));
3970
- const localIds = (local.blocks || []).map((block) => block.id);
3971
- const localSet = new Set(localIds);
4694
+ const localBlocks = [];
4695
+ const localSet = /* @__PURE__ */ new Set();
4696
+ for (const block of local.blocks || []) {
4697
+ if (!block || typeof block.id !== "string" || typeof block.type !== "string" || localSet.has(block.id))
4698
+ continue;
4699
+ localSet.add(block.id);
4700
+ localBlocks.push(block);
4701
+ }
4702
+ const localIds = localBlocks.map((block) => block.id);
3972
4703
  let changed = false;
3973
4704
  doc.transact(() => {
3974
4705
  if (meta.get("schema") !== YDOC_SCHEMA) meta.set("schema", YDOC_SCHEMA);
@@ -3983,7 +4714,7 @@ const applyLocalChanges = (doc, base, local, origin = "local") => {
3983
4714
  }
3984
4715
  }
3985
4716
  const baseIds = (base.blocks || []).map((block) => block.id).filter((id) => localSet.has(id));
3986
- const keep = lcsKeepIds(baseIds, localIds);
4717
+ const keep = new Set(lcsPairs(baseIds, localIds).map(([i]) => baseIds[i]));
3987
4718
  localIds.forEach((id, index2) => {
3988
4719
  if (baseById.has(id) && keep.has(id)) return;
3989
4720
  const current = order.toArray();
@@ -4002,67 +4733,48 @@ const applyLocalChanges = (doc, base, local, origin = "local") => {
4002
4733
  order.insert(position, [id]);
4003
4734
  changed = true;
4004
4735
  });
4005
- for (const block of local.blocks || []) {
4736
+ for (const block of localBlocks) {
4006
4737
  const before = baseById.get(block.id);
4007
- let entry = blocks.get(block.id);
4738
+ const entry = blocks.get(block.id);
4008
4739
  if (!(entry instanceof Y__namespace.Map)) {
4009
- entry = new Y__namespace.Map();
4010
- blocks.set(block.id, entry);
4011
- entry.set("type", block.type);
4012
- entry.set("tunes", sanitize.isPlainObject(block.tunes) ? block.tunes : {});
4013
- writeData(entry, sanitize.isPlainObject(block.data) ? block.data : {});
4740
+ blocks.set(block.id, createEntry(block));
4014
4741
  changed = true;
4015
4742
  continue;
4016
4743
  }
4017
- if (!before) {
4018
- changed = writeData(entry, sanitize.isPlainObject(block.data) ? block.data : {}) || changed;
4019
- continue;
4020
- }
4021
- if (before.type !== block.type) {
4744
+ const reference = before || readBlock(block.id, entry) || { type: block.type, data: {}, tunes: {} };
4745
+ if (entry.get("type") !== block.type && reference.type !== block.type) {
4022
4746
  entry.set("type", block.type);
4747
+ entry.set("data", toShared(sanitize.isPlainObject(block.data) ? block.data : {}, 2));
4023
4748
  changed = true;
4024
- }
4025
- if (stableStringify(before.tunes || {}) !== stableStringify(block.tunes || {})) {
4026
- entry.set("tunes", sanitize.isPlainObject(block.tunes) ? block.tunes : {});
4027
- changed = true;
4028
- }
4029
- let dataMap = entry.get("data");
4030
- if (!(dataMap instanceof Y__namespace.Map)) {
4031
- dataMap = new Y__namespace.Map();
4032
- entry.set("data", dataMap);
4033
- }
4034
- const baseData = sanitize.isPlainObject(before.data) ? before.data : {};
4035
- const localData = sanitize.isPlainObject(block.data) ? block.data : {};
4036
- for (const key of /* @__PURE__ */ new Set([...Object.keys(baseData), ...Object.keys(localData)])) {
4037
- const a = baseData[key];
4038
- const b = localData[key];
4039
- if (stableStringify(a) === stableStringify(b)) continue;
4040
- changed = true;
4041
- if (!(key in localData)) {
4042
- dataMap.delete(key);
4043
- } else if (typeof b === "string") {
4044
- const current = dataMap.get(key);
4045
- if (current instanceof Y__namespace.Text)
4046
- applyTextEdit(current, typeof a === "string" ? a : current.toString(), b);
4047
- else {
4048
- const text = new Y__namespace.Text();
4049
- dataMap.set(key, text);
4050
- text.insert(0, b);
4051
- }
4052
- } else {
4053
- dataMap.set(key, b === void 0 ? null : b);
4749
+ } else {
4750
+ if (!before && entry.get("type") !== block.type) {
4751
+ entry.set("type", block.type);
4752
+ changed = true;
4054
4753
  }
4754
+ changed = mergeSlot(entry, "data", reference.data || {}, sanitize.isPlainObject(block.data) ? block.data : {}, 2) || changed;
4055
4755
  }
4756
+ changed = mergeSlot(entry, "tunes", reference.tunes || {}, sanitize.isPlainObject(block.tunes) ? block.tunes : {}, 2) || changed;
4757
+ }
4758
+ if (changed) {
4759
+ if (local.time && meta.get("time") !== local.time) meta.set("time", local.time);
4760
+ if (local.version && meta.get("version") !== local.version) meta.set("version", local.version);
4056
4761
  }
4057
- if (changed && local.time) meta.set("time", local.time);
4058
4762
  }, origin);
4059
4763
  return changed;
4060
4764
  };
4061
- const lcsKeepIds = (a, b) => {
4062
- const indexes = lcsKeep(a, b);
4063
- return new Set(Array.from(indexes).map((i) => a[i]));
4765
+ const epochOf = (doc) => {
4766
+ const epoch = doc.getMap("meta").get("epoch");
4767
+ return typeof epoch === "string" ? epoch.slice(0, 64) : "";
4768
+ };
4769
+ const keys = /* @__PURE__ */ new WeakMap();
4770
+ const blockKey = (block) => {
4771
+ let key = keys.get(block);
4772
+ if (key === void 0) {
4773
+ key = stableStringify({ type: block.type, data: block.data || {}, tunes: block.tunes || {} });
4774
+ keys.set(block, key);
4775
+ }
4776
+ return key;
4064
4777
  };
4065
- const blockKey = (block) => stableStringify({ type: block.type, data: block.data || {}, tunes: block.tunes || {} });
4066
4778
  const caretOffset = (element) => {
4067
4779
  const selection = window.getSelection();
4068
4780
  if (!selection || selection.rangeCount === 0) return null;
@@ -4213,58 +4925,262 @@ const useFieldTarget = (name) => {
4213
4925
  field: name
4214
4926
  };
4215
4927
  };
4928
+ const LOCAL_ORIGIN = Object.freeze({ name: "magic-editor-x-local" });
4929
+ const REMOTE_ORIGIN = Object.freeze({ name: "magic-editor-x-remote" });
4930
+ const SHADOW_EDIT = Object.freeze({ name: "magic-editor-x-shadow-edit" });
4931
+ const SHADOW_SYNC = Object.freeze({ name: "magic-editor-x-shadow-sync" });
4932
+ const createReplica = ({
4933
+ onLocalUpdate = () => {
4934
+ },
4935
+ onShouldRender = () => {
4936
+ },
4937
+ captureTimeout = 500,
4938
+ maxUndoSteps = 200
4939
+ } = {}) => {
4940
+ const doc = new Y__namespace.Doc();
4941
+ const shadow = new Y__namespace.Doc();
4942
+ const reader = createDocReader(doc);
4943
+ let base = { blocks: [] };
4944
+ const undo = new Y__namespace.UndoManager([doc.getArray("order"), doc.getMap("blocks")], {
4945
+ trackedOrigins: /* @__PURE__ */ new Set([LOCAL_ORIGIN]),
4946
+ captureTimeout
4947
+ });
4948
+ undo.on("stack-item-added", () => {
4949
+ while (undo.undoStack.length > maxUndoSteps) undo.undoStack.shift();
4950
+ });
4951
+ shadow.on("update", (update, origin) => {
4952
+ if (origin === SHADOW_EDIT) Y__namespace.applyUpdate(doc, update, LOCAL_ORIGIN);
4953
+ });
4954
+ doc.on("update", (update, origin) => {
4955
+ if (origin !== REMOTE_ORIGIN) onLocalUpdate(update);
4956
+ if (origin === REMOTE_ORIGIN || origin === undo) onShouldRender();
4957
+ });
4958
+ return {
4959
+ doc,
4960
+ shadow,
4961
+ undoManager: undo,
4962
+ /** Applies an update from the server. */
4963
+ applyRemote(update) {
4964
+ Y__namespace.applyUpdate(doc, update, REMOTE_ORIGIN);
4965
+ },
4966
+ /**
4967
+ * Applies the editor's content: only the difference to what the editor
4968
+ * showed before is written.
4969
+ * @param {object} data - Editor content now.
4970
+ * @returns {boolean} True when something changed.
4971
+ */
4972
+ pushLocal(data) {
4973
+ const changed = applyLocalChanges(shadow, base, data, SHADOW_EDIT);
4974
+ base = data;
4975
+ return changed;
4976
+ },
4977
+ /**
4978
+ * Applies an edit made against an older state (`from` -> `data`) to the
4979
+ * current one, for example unsent edits after the room was replaced.
4980
+ * @param {object} from - State the edit started from.
4981
+ * @param {object} data - Edited state.
4982
+ * @returns {boolean} True when something changed.
4983
+ */
4984
+ rebase(from, data) {
4985
+ const changed = applyLocalChanges(shadow, from, data, SHADOW_EDIT);
4986
+ base = docToEditorData(shadow);
4987
+ return changed;
4988
+ },
4989
+ /**
4990
+ * Reads the state the editor should show, with a token for `markShown`.
4991
+ * @returns {{ data: object, catchUp: Uint8Array }} Data and catch-up update.
4992
+ */
4993
+ snapshot() {
4994
+ return { data: reader.read(), catchUp: Y__namespace.encodeStateAsUpdate(doc, Y__namespace.encodeStateVector(shadow)) };
4995
+ },
4996
+ /**
4997
+ * Records that the editor now shows the snapshot.
4998
+ * @param {Uint8Array} catchUp - Token from `snapshot()`.
4999
+ * @param {object} [shown] - What the editor reports after rendering (its own normalised form); defaults to the shadow content.
5000
+ */
5001
+ markShown(catchUp, shown) {
5002
+ Y__namespace.applyUpdate(shadow, catchUp, SHADOW_SYNC);
5003
+ base = shown || docToEditorData(shadow);
5004
+ },
5005
+ /** Content of the shared state. */
5006
+ read: () => reader.read(),
5007
+ /** Room generation. */
5008
+ epoch: () => epochOf(doc),
5009
+ /** Starts a new undo step (next change is not merged with the previous one). */
5010
+ stopCapturing: () => undo.stopCapturing(),
5011
+ undo: () => undo.undo() !== null,
5012
+ redo: () => undo.redo() !== null,
5013
+ canUndo: () => undo.undoStack.length > 0,
5014
+ canRedo: () => undo.redoStack.length > 0,
5015
+ /** Frees both documents. */
5016
+ destroy() {
5017
+ undo.destroy();
5018
+ reader.destroy();
5019
+ doc.destroy();
5020
+ shadow.destroy();
5021
+ }
5022
+ };
5023
+ };
5024
+ const PROTOCOL = 3;
4216
5025
  const RESYNC_MS = 2e4;
4217
5026
  const ACK_TIMEOUT_MS = 1e4;
5027
+ const RETRY_BASE_MS = 500;
5028
+ const RETRY_MAX_MS = 15e3;
5029
+ const IDLE_AFTER_MS = 6e4;
4218
5030
  const isEmptyUpdate = (update) => !update || update.byteLength <= 2;
5031
+ const backoffDelay = (attempt, random = Math.random) => {
5032
+ const cap = Math.min(RETRY_MAX_MS, RETRY_BASE_MS * 2 ** Math.min(attempt, 10));
5033
+ return Math.round(cap / 2 + random() * cap / 2);
5034
+ };
4219
5035
  const createCollabClient = ({
4220
5036
  requestSession,
4221
5037
  url,
4222
5038
  onRemoteData,
4223
5039
  onFirstSync,
4224
5040
  onState,
4225
- socketFactory = socket_ioClient.io
5041
+ onUndoState = () => {
5042
+ },
5043
+ socketFactory = socket_ioClient.io,
5044
+ win = typeof window !== "undefined" ? window : null
4226
5045
  }) => {
4227
- const doc = new Y__namespace.Doc();
5046
+ let replica = null;
4228
5047
  let socket = null;
4229
5048
  let destroyed = false;
4230
5049
  let pending = null;
4231
- let state = { status: "connecting", canEdit: false, peers: [], error: null, presenceId: null, color: null };
5050
+ let inFlight = false;
5051
+ let state = {
5052
+ status: "connecting",
5053
+ canEdit: false,
5054
+ peers: [],
5055
+ error: null,
5056
+ presenceId: null,
5057
+ color: null,
5058
+ pending: false
5059
+ };
4232
5060
  let resyncTimer = null;
5061
+ let idleTimer = null;
4233
5062
  let notifyTimer = null;
5063
+ let retryTimer = null;
5064
+ let flushTimer = null;
4234
5065
  let firstToken = null;
4235
5066
  let synced = false;
4236
5067
  let seededBySelf = false;
4237
- let base = { blocks: [] };
5068
+ let epoch = null;
5069
+ let attempt = 0;
5070
+ let confirmed = { blocks: [] };
5071
+ let lastLocal = null;
5072
+ let rescue = null;
5073
+ let lastActivity = Date.now();
5074
+ let lastCursor = null;
5075
+ let idle = false;
4238
5076
  const setState = (patch) => {
4239
- state = { ...state, ...patch };
5077
+ state = { ...state, ...patch, pending: Boolean(pending) || inFlight };
4240
5078
  onState({ ...state });
4241
5079
  };
4242
5080
  const notifyRemote = () => {
4243
- if (notifyTimer) return;
5081
+ if (notifyTimer || destroyed) return;
4244
5082
  notifyTimer = setTimeout(() => {
4245
5083
  notifyTimer = null;
4246
- if (!destroyed) onRemoteData(docToEditorData(doc));
5084
+ if (!destroyed) onRemoteData();
4247
5085
  }, 30);
4248
5086
  };
5087
+ const undoState = () => {
5088
+ if (replica) onUndoState({ canUndo: replica.canUndo(), canRedo: replica.canRedo() });
5089
+ };
5090
+ let startOver = () => {
5091
+ };
4249
5092
  const flush = () => {
4250
- if (!socket || !socket.connected || !pending || !state.canEdit) return;
5093
+ if (!socket || !socket.connected || !pending || inFlight || !state.canEdit || !synced) return;
4251
5094
  const update = pending;
4252
5095
  pending = null;
5096
+ inFlight = true;
5097
+ const sentWith = replica;
4253
5098
  socket.timeout(ACK_TIMEOUT_MS).emit("mx:update", update, (error, reply) => {
4254
- if (error || !reply || !reply.ok) {
4255
- pending = pending ? Y__namespace.mergeUpdates([update, pending]) : update;
4256
- if (reply && reply.code === "READ_ONLY") setState({ canEdit: false });
5099
+ inFlight = false;
5100
+ if (sentWith !== replica || destroyed) return;
5101
+ if (!error && reply && reply.ok) {
5102
+ if (!pending) confirmed = replica.read();
5103
+ setState({});
5104
+ flush();
5105
+ return;
5106
+ }
5107
+ const code = reply && reply.code;
5108
+ if (code === "READ_ONLY") {
5109
+ setState({ canEdit: false });
5110
+ startOver(false);
5111
+ return;
4257
5112
  }
5113
+ if (code === "INVALID_UPDATE") {
5114
+ startOver(false);
5115
+ return;
5116
+ }
5117
+ pending = pending ? Y__namespace.mergeUpdates([update, pending]) : update;
5118
+ setState({});
5119
+ clearTimeout(flushTimer);
5120
+ flushTimer = setTimeout(flush, code === "RATE_LIMITED" ? 2e3 : 400);
4258
5121
  });
5122
+ setState({});
4259
5123
  };
4260
- doc.on("update", (update, origin) => {
4261
- if (origin === "remote") {
4262
- notifyRemote();
4263
- return;
5124
+ const createDocs = () => {
5125
+ if (replica) replica.destroy();
5126
+ replica = createReplica({
5127
+ onLocalUpdate: (update) => {
5128
+ pending = pending ? Y__namespace.mergeUpdates([pending, update]) : update;
5129
+ flush();
5130
+ undoState();
5131
+ },
5132
+ onShouldRender: notifyRemote
5133
+ });
5134
+ replica.undoManager.on("stack-item-added", undoState);
5135
+ replica.undoManager.on("stack-item-popped", undoState);
5136
+ pending = null;
5137
+ inFlight = false;
5138
+ synced = false;
5139
+ undoState();
5140
+ };
5141
+ startOver = (keepUnsent) => {
5142
+ const unsent = keepUnsent && (pending || inFlight) ? lastLocal : null;
5143
+ const base = confirmed;
5144
+ createDocs();
5145
+ epoch = null;
5146
+ rescue = unsent ? { base, local: unsent } : null;
5147
+ if (socket && socket.connected) socket.emit("mx:resync", new Uint8Array([0]));
5148
+ };
5149
+ const scheduleReconnect = () => {
5150
+ if (destroyed || !socket || socket.connected || socket.active || state.status === "denied") return;
5151
+ clearTimeout(retryTimer);
5152
+ retryTimer = setTimeout(() => {
5153
+ if (!destroyed && socket && !socket.connected) socket.connect();
5154
+ }, backoffDelay(attempt));
5155
+ attempt += 1;
5156
+ };
5157
+ const offline = () => Boolean(win && win.navigator && win.navigator.onLine === false);
5158
+ const sendPresence = () => {
5159
+ if (socket && socket.connected) socket.emit("mx:cursor", { ...lastCursor || {}, idle });
5160
+ };
5161
+ const onOnline = () => {
5162
+ attempt = 0;
5163
+ if (!socket || state.status === "denied") return;
5164
+ if (!socket.connected) socket.connect();
5165
+ else if (replica) socket.emit("mx:resync", Y__namespace.encodeStateVector(replica.doc));
5166
+ };
5167
+ const onOffline = () => setState({ status: "offline" });
5168
+ const onVisibility = () => {
5169
+ if (!win || !win.document) return;
5170
+ const hidden = win.document.visibilityState === "hidden";
5171
+ if (!hidden) {
5172
+ lastActivity = Date.now();
5173
+ onOnline();
5174
+ }
5175
+ if (hidden !== idle) {
5176
+ idle = hidden;
5177
+ sendPresence();
4264
5178
  }
4265
- pending = pending ? Y__namespace.mergeUpdates([pending, update]) : update;
4266
- flush();
4267
- });
5179
+ };
5180
+ const onPageHide = () => {
5181
+ if (socket) socket.disconnect();
5182
+ };
5183
+ createDocs();
4268
5184
  const connect = async () => {
4269
5185
  const session = await requestSession();
4270
5186
  if (destroyed) return;
@@ -4275,59 +5191,120 @@ const createCollabClient = ({
4275
5191
  path: session.path,
4276
5192
  transports: ["websocket"],
4277
5193
  reconnection: true,
4278
- reconnectionDelay: 1e3,
4279
- reconnectionDelayMax: 1e4,
5194
+ reconnectionDelay: RETRY_BASE_MS,
5195
+ reconnectionDelayMax: RETRY_MAX_MS,
5196
+ randomizationFactor: 0.5,
4280
5197
  auth: (callback) => {
4281
5198
  if (firstToken) {
4282
5199
  const token = firstToken;
4283
5200
  firstToken = null;
4284
- callback({ token });
5201
+ callback({ token, protocol: PROTOCOL });
4285
5202
  return;
4286
5203
  }
4287
5204
  requestSession().then((next) => {
4288
5205
  setState({ canEdit: next.canEdit });
4289
- callback({ token: next.token });
4290
- }).catch(() => callback({ token: "" }));
5206
+ callback({ token: next.token, protocol: PROTOCOL });
5207
+ }).catch((error) => {
5208
+ const status = error && error.response && error.response.status;
5209
+ if (status === 403 || status === 404) setState({ status: "denied", error: `HTTP_${status}` });
5210
+ callback({ token: "", protocol: PROTOCOL });
5211
+ });
4291
5212
  }
4292
5213
  });
4293
- socket.on("connect", () => setState({ status: "syncing", error: null }));
4294
- socket.on("disconnect", () => setState({ status: "offline", peers: [] }));
4295
- socket.on("connect_error", () => setState({ status: "offline" }));
4296
- socket.on(
4297
- "mx:welcome",
4298
- (welcome) => setState({ canEdit: Boolean(welcome.canEdit), presenceId: welcome.presenceId, color: welcome.color })
4299
- );
4300
- socket.on("mx:sync", ({ update, stateVector }) => {
4301
- const bytes = new Uint8Array(update);
4302
- Y__namespace.applyUpdate(doc, bytes, "remote");
4303
- if (stateVector && state.canEdit) {
4304
- const missing = Y__namespace.encodeStateAsUpdate(doc, new Uint8Array(stateVector));
4305
- if (!isEmptyUpdate(missing)) {
4306
- pending = pending ? Y__namespace.mergeUpdates([pending, missing]) : missing;
4307
- }
5214
+ socket.on("connect", () => {
5215
+ attempt = 0;
5216
+ setState({ status: "syncing", error: null });
5217
+ });
5218
+ socket.on("disconnect", () => {
5219
+ inFlight = false;
5220
+ if (state.status !== "denied") setState({ status: offline() ? "offline" : "reconnecting", peers: [] });
5221
+ scheduleReconnect();
5222
+ });
5223
+ socket.on("connect_error", (error) => {
5224
+ const code = error && error.data && error.data.code || null;
5225
+ if (code === "UPGRADE_REQUIRED") {
5226
+ setState({ status: "error", error: code });
5227
+ return;
5228
+ }
5229
+ if (state.status === "denied") return;
5230
+ setState({ status: offline() ? "offline" : "reconnecting", error: code });
5231
+ scheduleReconnect();
5232
+ });
5233
+ socket.on("mx:welcome", (welcome = {}) => {
5234
+ if (epoch !== null && welcome.epoch !== epoch) startOver(true);
5235
+ setState({
5236
+ canEdit: Boolean(welcome.canEdit),
5237
+ presenceId: welcome.presenceId,
5238
+ color: welcome.color
5239
+ });
5240
+ sendPresence();
5241
+ });
5242
+ socket.on("mx:sync", (message) => {
5243
+ if (!message || !message.update) return;
5244
+ if (epoch !== null && message.epoch !== void 0 && message.epoch !== epoch) startOver(true);
5245
+ replica.applyRemote(new Uint8Array(message.update));
5246
+ epoch = message.epoch !== void 0 ? message.epoch : replica.epoch();
5247
+ if (message.stateVector && state.canEdit) {
5248
+ const missing = Y__namespace.encodeStateAsUpdate(replica.doc, new Uint8Array(message.stateVector));
5249
+ if (!isEmptyUpdate(missing)) pending = pending ? Y__namespace.mergeUpdates([pending, missing]) : missing;
4308
5250
  }
4309
5251
  const first = !synced;
4310
5252
  synced = true;
4311
- if (first) base = docToEditorData(doc);
5253
+ if (first) {
5254
+ const shown = replica.snapshot();
5255
+ replica.markShown(shown.catchUp);
5256
+ if (!pending && !inFlight) confirmed = shown.data;
5257
+ }
5258
+ if (rescue) {
5259
+ const { base, local } = rescue;
5260
+ rescue = null;
5261
+ if (state.canEdit) replica.rebase(base, local);
5262
+ }
4312
5263
  setState({ status: "live" });
4313
5264
  Promise.resolve(first && typeof onFirstSync === "function" ? onFirstSync(seededBySelf) : null).catch(() => null).then(() => {
4314
- notifyRemote();
5265
+ if (first) notifyRemote();
4315
5266
  flush();
4316
5267
  });
4317
5268
  });
4318
- socket.on("mx:update", (update) => Y__namespace.applyUpdate(doc, new Uint8Array(update), "remote"));
5269
+ socket.on("mx:update", (update) => {
5270
+ if (replica) replica.applyRemote(new Uint8Array(update));
5271
+ });
4319
5272
  socket.on("mx:presence", (peers) => {
4320
- setState({ peers: Array.isArray(peers) ? peers.filter((peer) => peer.id !== state.presenceId) : [] });
5273
+ setState({
5274
+ peers: Array.isArray(peers) ? peers.filter((peer) => peer && peer.id !== state.presenceId) : []
5275
+ });
5276
+ });
5277
+ socket.on("mx:role", ({ canEdit } = {}) => {
5278
+ setState({ canEdit: Boolean(canEdit) });
5279
+ if (canEdit) flush();
5280
+ else if (pending || inFlight) startOver(false);
5281
+ });
5282
+ socket.on("mx:error", ({ code } = {}) => {
5283
+ if (code === "ACCESS_REVOKED") {
5284
+ setState({ status: "denied", error: code, canEdit: false, peers: [] });
5285
+ if (socket) socket.disconnect();
5286
+ return;
5287
+ }
5288
+ if (code === "ROOM_RESET") startOver(true);
5289
+ if (code === "INVALID_UPDATE") startOver(false);
5290
+ setState({ error: code });
4321
5291
  });
4322
- socket.on("mx:role", ({ canEdit }) => setState({ canEdit: Boolean(canEdit) }));
4323
- socket.on(
4324
- "mx:error",
4325
- ({ code }) => setState({ status: code === "ACCESS_REVOKED" ? "denied" : "error", error: code })
4326
- );
4327
5292
  resyncTimer = setInterval(() => {
4328
- if (socket && socket.connected) socket.emit("mx:resync", Y__namespace.encodeStateVector(doc));
5293
+ if (socket && socket.connected && replica) socket.emit("mx:resync", Y__namespace.encodeStateVector(replica.doc));
4329
5294
  }, RESYNC_MS);
5295
+ idleTimer = setInterval(() => {
5296
+ if (!idle && Date.now() - lastActivity > IDLE_AFTER_MS) {
5297
+ idle = true;
5298
+ sendPresence();
5299
+ }
5300
+ }, 5e3);
4330
5301
  };
5302
+ if (win && typeof win.addEventListener === "function") {
5303
+ win.addEventListener("online", onOnline);
5304
+ win.addEventListener("offline", onOffline);
5305
+ win.addEventListener("pagehide", onPageHide);
5306
+ if (win.document) win.document.addEventListener("visibilitychange", onVisibility);
5307
+ }
4331
5308
  connect().catch((error) => {
4332
5309
  const status = error && error.response && error.response.status;
4333
5310
  setState({
@@ -4336,42 +5313,92 @@ const createCollabClient = ({
4336
5313
  });
4337
5314
  });
4338
5315
  return {
4339
- /** Applies the local editor content to the shared document. */
5316
+ /**
5317
+ * Applies the editor content: only the difference to what the editor showed is written.
5318
+ * @param {object} data - Editor content now.
5319
+ */
4340
5320
  pushLocal(data) {
4341
5321
  if (destroyed || !synced || !state.canEdit) return;
4342
- applyLocalChanges(doc, base, data, "local");
4343
- base = data;
5322
+ lastLocal = data;
5323
+ lastActivity = Date.now();
5324
+ if (idle) {
5325
+ idle = false;
5326
+ sendPresence();
5327
+ }
5328
+ replica.pushLocal(data);
4344
5329
  },
4345
- /** Records what the editor shows now (after remote content was applied). */
4346
- markShown(data) {
4347
- base = data;
5330
+ /**
5331
+ * Reads what the editor should show and a token for `markShown`.
5332
+ * @returns {{ data: object, catchUp: Uint8Array }} Snapshot.
5333
+ */
5334
+ snapshot: () => replica.snapshot(),
5335
+ /**
5336
+ * Records that the editor now shows a snapshot.
5337
+ * @param {Uint8Array} catchUp - Token from `snapshot()`.
5338
+ * @param {object} [shown] - The editor's own output right after rendering.
5339
+ */
5340
+ markShown(catchUp, shown) {
5341
+ if (replica) replica.markShown(catchUp, shown);
4348
5342
  },
4349
- /** Shares the caret position with the room. */
5343
+ /**
5344
+ * Shares the caret (block and character offsets) with the room.
5345
+ * @param {{ blockId: string, anchor: number, focus: number }|null} cursor - Caret or null.
5346
+ */
4350
5347
  sendCursor(cursor) {
4351
- if (socket && socket.connected) socket.emit("mx:cursor", cursor);
5348
+ lastCursor = cursor;
5349
+ lastActivity = Date.now();
5350
+ idle = false;
5351
+ sendPresence();
4352
5352
  },
5353
+ /** Undoes the last own change. @returns {boolean} True when something was undone. */
5354
+ undo: () => Boolean(replica && state.canEdit && replica.undo()),
5355
+ /** Redoes the last undone own change. @returns {boolean} True when something was redone. */
5356
+ redo: () => Boolean(replica && state.canEdit && replica.redo()),
5357
+ /** Starts a new undo step. */
5358
+ stopCapturing: () => replica && replica.stopCapturing(),
5359
+ canUndo: () => Boolean(replica && replica.canUndo()),
5360
+ canRedo: () => Boolean(replica && replica.canRedo()),
4353
5361
  /** Current shared document. */
4354
- getData() {
4355
- return docToEditorData(doc);
4356
- },
5362
+ getData: () => replica ? replica.read() : docToEditorData(new Y__namespace.Doc()),
4357
5363
  /** True when the room has content (it was seeded). */
4358
5364
  hasContent() {
4359
- return doc.getArray("order").length > 0 || doc.getMap("blocks").size > 0;
5365
+ return Boolean(
5366
+ replica && (replica.doc.getArray("order").length > 0 || replica.doc.getMap("blocks").size > 0)
5367
+ );
4360
5368
  },
4361
- /** Disconnects and frees the document. */
5369
+ /** Disconnects and frees the documents. */
4362
5370
  destroy() {
4363
5371
  destroyed = true;
4364
5372
  clearInterval(resyncTimer);
5373
+ clearInterval(idleTimer);
4365
5374
  clearTimeout(notifyTimer);
5375
+ clearTimeout(retryTimer);
5376
+ clearTimeout(flushTimer);
5377
+ if (win && typeof win.removeEventListener === "function") {
5378
+ win.removeEventListener("online", onOnline);
5379
+ win.removeEventListener("offline", onOffline);
5380
+ win.removeEventListener("pagehide", onPageHide);
5381
+ if (win.document) win.document.removeEventListener("visibilitychange", onVisibility);
5382
+ }
4366
5383
  if (socket) {
4367
5384
  socket.removeAllListeners();
4368
5385
  socket.disconnect();
4369
5386
  }
4370
- doc.destroy();
5387
+ if (replica) replica.destroy();
5388
+ replica = null;
4371
5389
  }
4372
5390
  };
4373
5391
  };
4374
- const INITIAL = { status: "off", canEdit: false, peers: [], error: null, color: null };
5392
+ const INITIAL = {
5393
+ status: "off",
5394
+ canEdit: false,
5395
+ peers: [],
5396
+ error: null,
5397
+ color: null,
5398
+ pending: false,
5399
+ canUndo: false,
5400
+ canRedo: false
5401
+ };
4375
5402
  const useCollaboration = ({ target, getLocalData, ready, onRemoteData, onFirstSync }) => {
4376
5403
  const { post } = admin.useFetchClient();
4377
5404
  const [state, setState] = react.useState(INITIAL);
@@ -4400,9 +5427,10 @@ const useCollaboration = ({ target, getLocalData, ready, onRemoteData, onFirstSy
4400
5427
  });
4401
5428
  return data.data;
4402
5429
  },
4403
- onRemoteData: (data) => onRemoteRef.current(data),
5430
+ onRemoteData: () => onRemoteRef.current(),
4404
5431
  onFirstSync: (seeded) => onFirstSyncRef.current ? onFirstSyncRef.current(seeded, instance) : null,
4405
- onState: (next) => setState(next)
5432
+ onState: (next) => setState((previous) => ({ ...previous, ...next })),
5433
+ onUndoState: (undo) => setState((previous) => ({ ...previous, ...undo }))
4406
5434
  });
4407
5435
  setClient(instance);
4408
5436
  return () => {
@@ -4411,16 +5439,7 @@ const useCollaboration = ({ target, getLocalData, ready, onRemoteData, onFirstSy
4411
5439
  setState(INITIAL);
4412
5440
  };
4413
5441
  }, [key, post]);
4414
- if (!key)
4415
- return {
4416
- active: false,
4417
- status: "off",
4418
- canEdit: false,
4419
- peers: [],
4420
- error: null,
4421
- color: null,
4422
- client: null
4423
- };
5442
+ if (!key) return { ...INITIAL, active: false, client: null };
4424
5443
  return {
4425
5444
  active: !["off", "denied", "error"].includes(state.status),
4426
5445
  status: state.status === "off" ? "connecting" : state.status,
@@ -4428,17 +5447,240 @@ const useCollaboration = ({ target, getLocalData, ready, onRemoteData, onFirstSy
4428
5447
  peers: state.peers,
4429
5448
  error: state.error,
4430
5449
  color: state.color,
5450
+ pending: state.pending,
5451
+ canUndo: state.canUndo,
5452
+ canRedo: state.canRedo,
4431
5453
  client
4432
5454
  };
4433
5455
  };
5456
+ const PEER_FAMILIES = ["primary", "danger", "success", "warning", "secondary", "alternative"];
5457
+ const peerFamily = (family) => PEER_FAMILIES.includes(family) ? family : "neutral";
5458
+ const blink = styled.keyframes`
5459
+ 0%, 49% { opacity: 1; }
5460
+ 50%, 100% { opacity: 0.2; }
5461
+ `;
5462
+ const Layer = styled__default.default.div`
5463
+ position: absolute;
5464
+ inset: 0;
5465
+ pointer-events: none;
5466
+ overflow: hidden;
5467
+ z-index: 1;
5468
+ `;
5469
+ const Highlight = styled__default.default.div`
5470
+ position: absolute;
5471
+ background: ${({ theme, $family }) => theme.colors[`${$family}200`] || theme.colors.neutral200};
5472
+ opacity: 0.55;
5473
+ border-radius: 2px;
5474
+ `;
5475
+ const Caret = styled__default.default.div`
5476
+ position: absolute;
5477
+ width: 2px;
5478
+ background: ${({ theme, $family }) => theme.colors[`${$family}600`] || theme.colors.neutral600};
5479
+ opacity: ${({ $idle }) => $idle ? 0.4 : 1};
5480
+ @media (prefers-reduced-motion: no-preference) {
5481
+ ${({ $idle }) => $idle ? "" : styled.css`
5482
+ animation: ${blink} 1.1s step-end infinite;
5483
+ `}
5484
+ }
5485
+ `;
5486
+ const Label = styled__default.default.div`
5487
+ position: absolute;
5488
+ transform: translateY(-100%);
5489
+ padding: 0 ${({ theme }) => theme.spaces[1]};
5490
+ border-radius: ${({ theme }) => theme.borderRadius};
5491
+ background: ${({ theme, $family }) => theme.colors[`${$family}600`] || theme.colors.neutral600};
5492
+ color: ${({ theme }) => theme.colors.neutral0};
5493
+ font-size: ${({ theme }) => theme.fontSizes[0]};
5494
+ line-height: 1.6;
5495
+ white-space: nowrap;
5496
+ max-width: 16rem;
5497
+ overflow: hidden;
5498
+ text-overflow: ellipsis;
5499
+ opacity: ${({ $idle }) => $idle ? 0.6 : 1};
5500
+ `;
5501
+ const BlockMarker = styled__default.default.div`
5502
+ position: absolute;
5503
+ width: 3px;
5504
+ border-radius: 2px;
5505
+ background: ${({ theme, $family }) => theme.colors[`${$family}500`] || theme.colors.neutral500};
5506
+ opacity: ${({ $idle }) => $idle ? 0.4 : 0.9};
5507
+ `;
5508
+ const pointAt = (root, offset) => {
5509
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
5510
+ let remaining = Math.max(0, offset);
5511
+ let node = walker.nextNode();
5512
+ let last = null;
5513
+ while (node) {
5514
+ last = node;
5515
+ if (remaining <= node.textContent.length) return { node, offset: remaining };
5516
+ remaining -= node.textContent.length;
5517
+ node = walker.nextNode();
5518
+ }
5519
+ if (last) return { node: last, offset: last.textContent.length };
5520
+ return null;
5521
+ };
5522
+ const offsetOf = (root, node, offset) => {
5523
+ if (!root.contains(node)) return null;
5524
+ const range = document.createRange();
5525
+ range.selectNodeContents(root);
5526
+ try {
5527
+ range.setEnd(node, offset);
5528
+ } catch {
5529
+ return null;
5530
+ }
5531
+ return range.toString().length;
5532
+ };
5533
+ const measure = (container, holder, peer) => {
5534
+ const { blockId, anchor = 0, focus = anchor } = peer.cursor || {};
5535
+ if (!blockId) return null;
5536
+ const escaped = window.CSS && window.CSS.escape ? window.CSS.escape(blockId) : blockId;
5537
+ const block = holder.querySelector(`.ce-block[data-id="${escaped}"]`);
5538
+ if (!block) return null;
5539
+ const content = block.querySelector(".ce-block__content") || block;
5540
+ const origin = container.getBoundingClientRect();
5541
+ const blockRect = content.getBoundingClientRect();
5542
+ const geometry = {
5543
+ marker: {
5544
+ left: blockRect.left - origin.left - 8,
5545
+ top: blockRect.top - origin.top,
5546
+ height: Math.max(8, blockRect.height)
5547
+ },
5548
+ caret: null,
5549
+ highlights: []
5550
+ };
5551
+ const start = pointAt(content, Math.min(anchor, focus));
5552
+ const end = pointAt(content, Math.max(anchor, focus));
5553
+ if (!start || !end) {
5554
+ geometry.caret = { left: blockRect.left - origin.left, top: blockRect.top - origin.top, height: 20 };
5555
+ return geometry;
5556
+ }
5557
+ const range = document.createRange();
5558
+ try {
5559
+ range.setStart(start.node, start.offset);
5560
+ range.setEnd(end.node, end.offset);
5561
+ } catch {
5562
+ return geometry;
5563
+ }
5564
+ if (anchor !== focus) {
5565
+ geometry.highlights = Array.from(range.getClientRects()).slice(0, 50).map((rect2) => ({
5566
+ left: rect2.left - origin.left,
5567
+ top: rect2.top - origin.top,
5568
+ width: rect2.width,
5569
+ height: rect2.height
5570
+ }));
5571
+ }
5572
+ const caretRange = document.createRange();
5573
+ const caretPoint = focus >= anchor ? end : start;
5574
+ caretRange.setStart(caretPoint.node, caretPoint.offset);
5575
+ caretRange.collapse(true);
5576
+ const rects = caretRange.getClientRects();
5577
+ const rect = rects.length ? rects[0] : caretPoint.node.parentElement?.getBoundingClientRect();
5578
+ if (rect) {
5579
+ geometry.caret = {
5580
+ left: rect.left - origin.left,
5581
+ top: rect.top - origin.top,
5582
+ height: Math.max(14, rect.height || 18)
5583
+ };
5584
+ }
5585
+ return geometry;
5586
+ };
5587
+ const RemoteCarets = ({ containerRef, holderRef, peers, version, t }) => {
5588
+ const [shapes, setShapes] = react.useState([]);
5589
+ const frame = react.useRef(0);
5590
+ const peersRef = react.useRef(peers);
5591
+ react.useEffect(() => {
5592
+ peersRef.current = peers;
5593
+ }, [peers]);
5594
+ react.useLayoutEffect(() => {
5595
+ const container = containerRef.current;
5596
+ const holder = holderRef.current;
5597
+ if (!container || !holder) return void 0;
5598
+ const update = () => {
5599
+ cancelAnimationFrame(frame.current);
5600
+ frame.current = requestAnimationFrame(() => {
5601
+ const next = [];
5602
+ for (const peer of peersRef.current || []) {
5603
+ if (!peer.cursor) continue;
5604
+ const geometry = measure(container, holder, peer);
5605
+ if (geometry) next.push({ peer, geometry });
5606
+ }
5607
+ setShapes(next);
5608
+ });
5609
+ };
5610
+ update();
5611
+ const observer = typeof ResizeObserver === "function" ? new ResizeObserver(update) : null;
5612
+ if (observer) observer.observe(holder);
5613
+ window.addEventListener("resize", update);
5614
+ holder.addEventListener("scroll", update, true);
5615
+ return () => {
5616
+ cancelAnimationFrame(frame.current);
5617
+ if (observer) observer.disconnect();
5618
+ window.removeEventListener("resize", update);
5619
+ holder.removeEventListener("scroll", update, true);
5620
+ };
5621
+ }, [containerRef, holderRef, peers, version]);
5622
+ if (shapes.length === 0) return null;
5623
+ return /* @__PURE__ */ jsxRuntime.jsx(Layer, { "aria-hidden": "true", "data-testid": "mex-remote-carets", children: shapes.map(({ peer, geometry }) => {
5624
+ const family = peerFamily(peer.color);
5625
+ const label = peer.idle ? t("editor.collab.away", "{name} (away)", { name: peer.name }) : peer.name;
5626
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { "data-peer": peer.id, children: [
5627
+ /* @__PURE__ */ jsxRuntime.jsx(
5628
+ BlockMarker,
5629
+ {
5630
+ $family: family,
5631
+ $idle: peer.idle,
5632
+ style: {
5633
+ left: geometry.marker.left,
5634
+ top: geometry.marker.top,
5635
+ height: geometry.marker.height
5636
+ },
5637
+ title: t("editor.collab.editingBlock", "{name} is editing this block", { name: peer.name })
5638
+ }
5639
+ ),
5640
+ geometry.highlights.map((rect, index2) => /* @__PURE__ */ jsxRuntime.jsx(
5641
+ Highlight,
5642
+ {
5643
+ $family: family,
5644
+ style: { left: rect.left, top: rect.top, width: rect.width, height: rect.height }
5645
+ },
5646
+ index2
5647
+ )),
5648
+ geometry.caret ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
5649
+ /* @__PURE__ */ jsxRuntime.jsx(
5650
+ Caret,
5651
+ {
5652
+ $family: family,
5653
+ $idle: peer.idle,
5654
+ "data-testid": "mex-remote-caret",
5655
+ style: {
5656
+ left: geometry.caret.left,
5657
+ top: geometry.caret.top,
5658
+ height: geometry.caret.height
5659
+ }
5660
+ }
5661
+ ),
5662
+ /* @__PURE__ */ jsxRuntime.jsx(
5663
+ Label,
5664
+ {
5665
+ $family: family,
5666
+ $idle: peer.idle,
5667
+ style: { left: geometry.caret.left, top: geometry.caret.top },
5668
+ children: label
5669
+ }
5670
+ )
5671
+ ] }) : null
5672
+ ] }, peer.id);
5673
+ }) });
5674
+ };
4434
5675
  const Bar = styled__default.default(designSystem.Flex)`
4435
5676
  min-width: 0;
4436
5677
  border-bottom: 1px solid ${({ theme }) => theme.colors.neutral150};
4437
5678
  flex-wrap: wrap;
4438
5679
  `;
4439
5680
  const Peer = styled__default.default(designSystem.Avatar.Item)`
4440
- outline: 2px solid ${({ $color }) => $color};
5681
+ outline: 2px solid ${({ theme, $family }) => theme.colors[`${$family}600`] || theme.colors.neutral600};
4441
5682
  outline-offset: 1px;
5683
+ opacity: ${({ $idle }) => $idle ? 0.55 : 1};
4442
5684
  `;
4443
5685
  const STATUS = {
4444
5686
  connecting: {
@@ -4449,7 +5691,13 @@ const STATUS = {
4449
5691
  },
4450
5692
  syncing: { key: "editor.collab.status.syncing", text: "Syncing", bg: "neutral150", fg: "neutral800" },
4451
5693
  live: { key: "editor.collab.status.live", text: "Live", bg: "success100", fg: "success700" },
4452
- offline: { key: "editor.collab.status.offline", text: "Reconnecting", bg: "warning200", fg: "neutral800" },
5694
+ reconnecting: {
5695
+ key: "editor.collab.status.reconnecting",
5696
+ text: "Reconnecting",
5697
+ bg: "warning100",
5698
+ fg: "warning700"
5699
+ },
5700
+ offline: { key: "editor.collab.status.offline", text: "Offline", bg: "danger100", fg: "danger700" },
4453
5701
  denied: {
4454
5702
  key: "editor.collab.status.denied",
4455
5703
  text: "Live editing unavailable",
@@ -4482,6 +5730,11 @@ const EditorToolbar = ({
4482
5730
  }) => {
4483
5731
  const status = STATUS[collaboration.status];
4484
5732
  const peers = collaboration.peers || [];
5733
+ const upgrade = collaboration.status === "error" && collaboration.error === "UPGRADE_REQUIRED";
5734
+ const peerLabel = (peer) => {
5735
+ const base = peer.canEdit ? peer.name : t("editor.collab.viewer", "{name} (viewing)", { name: peer.name });
5736
+ return peer.idle ? t("editor.collab.away", "{name} (away)", { name: base }) : base;
5737
+ };
4485
5738
  return /* @__PURE__ */ jsxRuntime.jsxs(
4486
5739
  Bar,
4487
5740
  {
@@ -4536,24 +5789,31 @@ const EditorToolbar = ({
4536
5789
  )
4537
5790
  ] }),
4538
5791
  /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 3, wrap: "wrap", justifyContent: "flex-end", minWidth: 0, children: [
4539
- status ? /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 2, "aria-live": "polite", children: [
4540
- peers.length > 0 ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Avatar.Group, { children: peers.slice(0, 4).map((peer) => /* @__PURE__ */ jsxRuntime.jsx(
4541
- designSystem.Tooltip,
5792
+ status ? /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 2, wrap: "wrap", children: [
5793
+ peers.length > 0 ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Avatar.Group, { children: peers.slice(0, 4).map((peer) => /* @__PURE__ */ jsxRuntime.jsx(designSystem.Tooltip, { label: peerLabel(peer), children: /* @__PURE__ */ jsxRuntime.jsx(
5794
+ Peer,
4542
5795
  {
4543
- label: peer.canEdit ? peer.name : t("editor.collab.viewer", "{name} (viewing)", { name: peer.name }),
4544
- children: /* @__PURE__ */ jsxRuntime.jsx(Peer, { $color: peer.color, fallback: initials(peer.name) })
4545
- },
4546
- peer.id
4547
- )) }) : null,
4548
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Badge, { backgroundColor: status.bg, textColor: status.fg, children: t(status.key, status.text) }),
4549
- collaboration.status === "live" && !collaboration.canEdit ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral600", children: t("editor.collab.readOnly", "View only") }) : null,
4550
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.VisuallyHidden, { children: t(
4551
- "editor.collab.peers",
4552
- "{count, plural, =0 {Nobody else is editing} one {# other person is editing} other {# other people are editing}}",
4553
- {
4554
- count: peers.length
5796
+ $family: peerFamily(peer.color),
5797
+ $idle: peer.idle,
5798
+ fallback: initials(peer.name),
5799
+ "aria-label": peerLabel(peer)
4555
5800
  }
4556
- ) })
5801
+ ) }, peer.id)) }) : null,
5802
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { "aria-live": "polite", "data-testid": "mex-collab-status", "data-status": collaboration.status, children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Badge, { backgroundColor: status.bg, textColor: status.fg, children: t(status.key, status.text) }) }),
5803
+ peers.length > 4 ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral600", children: t("editor.collab.more", "+{count}", { count: peers.length - 4 }) }) : null,
5804
+ collaboration.status === "live" && !collaboration.canEdit ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Badge, { backgroundColor: "neutral150", textColor: "neutral800", children: t("editor.collab.readOnly", "View only") }) : null,
5805
+ collaboration.pending && collaboration.status !== "live" ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral600", children: t("editor.collab.unsent", "Changes are kept and sent when the connection is back") }) : null,
5806
+ upgrade ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral600", children: t("editor.collab.upgrade", "Reload the page to keep editing live") }) : null,
5807
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.VisuallyHidden, { children: [
5808
+ peers.length > 0 ? `${peers.map(peerLabel).join(", ")}. ` : "",
5809
+ t(
5810
+ "editor.collab.peers",
5811
+ "{count, plural, =0 {Nobody else is editing} one {# other person is editing} other {# other people are editing}}",
5812
+ {
5813
+ count: peers.length
5814
+ }
5815
+ )
5816
+ ] })
4557
5817
  ] }) : null,
4558
5818
  /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral600", children: t(
4559
5819
  "editor.stats",
@@ -4914,8 +6174,25 @@ const AiDialog = ({ t, request, config, onApply, onClose }) => {
4914
6174
  ] })
4915
6175
  ] }) });
4916
6176
  };
6177
+ const usePresenceAnnouncements = (peers, t) => {
6178
+ const [previous, setPrevious] = react.useState(peers);
6179
+ const [message, setMessage] = react.useState("");
6180
+ if (peers !== previous) {
6181
+ const before = new Map((previous || []).map((peer) => [peer.id, peer.name]));
6182
+ const current = new Map((peers || []).map((peer) => [peer.id, peer.name]));
6183
+ const joined = [...current.keys()].filter((id) => !before.has(id)).map((id) => current.get(id));
6184
+ const left = [...before.keys()].filter((id) => !current.has(id)).map((id) => before.get(id));
6185
+ const parts = [];
6186
+ if (joined.length) parts.push(t("editor.collab.joined", "{names} joined", { names: joined.join(", ") }));
6187
+ if (left.length) parts.push(t("editor.collab.left", "{names} left", { names: left.join(", ") }));
6188
+ setPrevious(peers);
6189
+ if (parts.length) setMessage(parts.join(". "));
6190
+ }
6191
+ return message;
6192
+ };
4917
6193
  const SAVE_DEBOUNCE_MS = 150;
4918
6194
  const EditorStyles = styled.createGlobalStyle`${editorStyles}`;
6195
+ const SETTINGS_PATH = "/settings/magic-editor-x/configuration";
4919
6196
  const Frame = styled__default.default(designSystem.Box)`
4920
6197
  min-width: 0;
4921
6198
  border: 1px solid ${({ theme, $error }) => $error ? theme.colors.danger600 : theme.colors.neutral200};
@@ -4936,6 +6213,11 @@ const Frame = styled__default.default(designSystem.Box)`
4936
6213
  overflow: hidden;
4937
6214
  ` : ""}
4938
6215
  `;
6216
+ const EditorArea = styled__default.default.div`
6217
+ position: relative;
6218
+ min-width: 0;
6219
+ ${({ $fullscreen }) => $fullscreen ? "flex: 1 1 auto; display: flex; flex-direction: column; min-height: 0;" : ""}
6220
+ `;
4939
6221
  const Holder = styled__default.default.div`
4940
6222
  min-width: 0;
4941
6223
  padding: ${({ theme }) => `${theme.spaces[4]} ${theme.spaces[3]}`};
@@ -4969,6 +6251,12 @@ const EditorField = ({
4969
6251
  const MediaLibraryDialog = admin.useStrapiApp("MagicEditorX", (state) => state.components["media-library"]);
4970
6252
  const { config, customBlocks, error: configError, loading: configLoading, retry } = useEditorConfig();
4971
6253
  const target = useFieldTarget(name);
6254
+ const navigate = reactRouterDom.useNavigate();
6255
+ const settingsHref = reactRouterDom.useHref(SETTINGS_PATH);
6256
+ const contentLocaleRef = react.useRef(target.locale);
6257
+ react.useEffect(() => {
6258
+ contentLocaleRef.current = target.locale;
6259
+ }, [target.locale]);
4972
6260
  const t = react.useCallback(
4973
6261
  (id, defaultMessage, values) => formatMessage({ id: index.getTranslation(id), defaultMessage }, values),
4974
6262
  [formatMessage]
@@ -4985,6 +6273,10 @@ const EditorField = ({
4985
6273
  const pendingLocalRef = react.useRef(false);
4986
6274
  const syncedOnceRef = react.useRef(false);
4987
6275
  const historyButtonRef = react.useRef(null);
6276
+ const areaRef = react.useRef(null);
6277
+ const remoteCacheRef = react.useRef(/* @__PURE__ */ new WeakMap());
6278
+ const userTouchedRef = react.useRef(false);
6279
+ const [contentVersion, setContentVersion] = react.useState(0);
4988
6280
  const onChangeRef = react.useRef(onChange);
4989
6281
  const [ready, setReady] = react.useState(false);
4990
6282
  const [stats, setStats] = react.useState({ blocks: 0, words: 0, characters: 0 });
@@ -5002,7 +6294,7 @@ const EditorField = ({
5002
6294
  const permissions = config && config.permissions || {};
5003
6295
  const collaborationTarget = config && config.collaboration.enabled && permissions.collaborate && target.uid && target.documentId ? target : null;
5004
6296
  const emit = react.useCallback(
5005
- (data) => {
6297
+ (data, { baselineOnly = false } = {}) => {
5006
6298
  const meaningful = data && Array.isArray(data.blocks) && data.blocks.some(
5007
6299
  (block) => block.type !== "paragraph" || String(block.data && block.data.text || "").replace(/<br\s*\/?>|&nbsp;|\s/g, "") !== ""
5008
6300
  );
@@ -5011,6 +6303,7 @@ const EditorField = ({
5011
6303
  if (key === lastEmittedRawRef.current) return;
5012
6304
  lastEmittedRawRef.current = key;
5013
6305
  lastEmittedRef.current = renderedKey(next);
6306
+ if (baselineOnly) return;
5014
6307
  onChangeRef.current(name, next ? JSON.parse(JSON.stringify(next)) : null);
5015
6308
  },
5016
6309
  [name]
@@ -5028,6 +6321,11 @@ const EditorField = ({
5028
6321
  const data = await editor.save();
5029
6322
  rememberBlocks(knownRef.current, data);
5030
6323
  setStats(sanitize.computeStats(data));
6324
+ setContentVersion((version) => version + 1);
6325
+ if (!userTouchedRef.current) {
6326
+ emit(data, { baselineOnly: true });
6327
+ return;
6328
+ }
5031
6329
  emit(data);
5032
6330
  if (collabRef.current) collabRef.current.pushLocal(data);
5033
6331
  if (undoRef.current) undoRef.current.record();
@@ -5074,12 +6372,18 @@ const EditorField = ({
5074
6372
  }
5075
6373
  if (!["Shift", "Control", "Alt", "Meta"].includes(event.key)) leaveArmed = false;
5076
6374
  };
6375
+ const onTouch = () => {
6376
+ userTouchedRef.current = true;
6377
+ };
6378
+ const touchEvents = ["pointerdown", "keydown", "input", "paste", "drop"];
6379
+ touchEvents.forEach((type) => holder.addEventListener(type, onTouch, true));
5077
6380
  window.addEventListener("keydown", onKeyDown, true);
5078
6381
  holder.addEventListener("focusout", onFocusOut);
5079
6382
  holder.addEventListener("input", onInput);
5080
6383
  holder.addEventListener("click", onClick);
5081
6384
  holder.addEventListener("keyup", onKeyUp);
5082
6385
  return () => {
6386
+ touchEvents.forEach((type) => holder.removeEventListener(type, onTouch, true));
5083
6387
  holder.removeEventListener("click", onClick);
5084
6388
  holder.removeEventListener("keyup", onKeyUp);
5085
6389
  holder.removeEventListener("focusout", onFocusOut);
@@ -5096,6 +6400,7 @@ const EditorField = ({
5096
6400
  try {
5097
6401
  await applyToEditor(editor, data || { blocks: [] }, knownRef.current);
5098
6402
  setStats(sanitize.computeStats(data));
6403
+ setContentVersion((version) => version + 1);
5099
6404
  if (emitToForm) emit(data);
5100
6405
  else {
5101
6406
  const shown = data && data.blocks && data.blocks.length ? data : null;
@@ -5136,19 +6441,37 @@ const EditorField = ({
5136
6441
  },
5137
6442
  onRemoteData: async () => {
5138
6443
  const client = collabRef.current;
5139
- if (!client) return;
6444
+ const editor = editorRef.current;
6445
+ if (!client || !editor) return;
5140
6446
  await flushLocal(client);
5141
- const shared = client.getData();
6447
+ const { data, catchUp } = client.snapshot();
6448
+ const own = new Set(
6449
+ data.blocks.filter((block) => knownRef.current.get(block.id) === blockKey(block)).map((b) => b.id)
6450
+ );
6451
+ const shared = sanitize.prepareRemoteData(data, remoteCacheRef.current);
6452
+ shared.blocks.forEach((block) => {
6453
+ if (own.has(block.id)) knownRef.current.set(block.id, blockKey(block));
6454
+ });
5142
6455
  const first = !syncedOnceRef.current;
5143
6456
  syncedOnceRef.current = true;
5144
6457
  await applyExternal(shared, { emitToForm: !first });
5145
- client.markShown(shared);
6458
+ const shown = await editor.save().catch(() => null);
6459
+ client.markShown(catchUp, shown || shared);
5146
6460
  }
5147
6461
  });
5148
6462
  react.useEffect(() => {
5149
6463
  collabRef.current = collaboration.client;
5150
6464
  }, [collaboration.client]);
5151
6465
  const readOnly = Boolean(disabled) || collaboration.status === "live" && !collaboration.canEdit;
6466
+ const collabUndo = collaboration.active && collaboration.client && collaboration.canEdit;
6467
+ react.useEffect(() => {
6468
+ if (!ready || !undoRef.current) return void 0;
6469
+ undoRef.current.setDelegate(collabUndo ? collaboration.client : null);
6470
+ return () => {
6471
+ if (undoRef.current) undoRef.current.setDelegate(null);
6472
+ };
6473
+ }, [ready, collabUndo, collaboration.client]);
6474
+ const announcement = usePresenceAnnouncements(collaboration.peers, t);
5152
6475
  const upload = react.useCallback(
5153
6476
  async (path, field2, file) => {
5154
6477
  const body = new FormData();
@@ -5201,6 +6524,11 @@ const EditorField = ({
5201
6524
  setStats(sanitize.computeStats(initial));
5202
6525
  let destroyed = false;
5203
6526
  let dragDrop = null;
6527
+ const cspGuard = createCspGuard(holderRef.current, {
6528
+ t,
6529
+ settingsHref: permissions.settingsRead ? settingsHref : null,
6530
+ onOpenSettings: () => navigate(SETTINGS_PATH)
6531
+ });
5204
6532
  const editor = new EditorJS__default.default({
5205
6533
  holder: holderRef.current,
5206
6534
  data: initial || void 0,
@@ -5213,6 +6541,7 @@ const EditorField = ({
5213
6541
  tools: buildTools({
5214
6542
  t,
5215
6543
  fetchClient: { get, post },
6544
+ getContentLocale: () => contentLocaleRef.current,
5216
6545
  uploadImage: (file) => upload(api.API.imageByFile, "image", file),
5217
6546
  uploadImageByUrl,
5218
6547
  uploadFile: (file) => upload(api.API.fileUpload, "file", file),
@@ -5239,6 +6568,7 @@ const EditorField = ({
5239
6568
  });
5240
6569
  return () => {
5241
6570
  destroyed = true;
6571
+ cspGuard.destroy();
5242
6572
  clearTimeout(saveTimerRef.current);
5243
6573
  setReady(false);
5244
6574
  if (undoRef.current) undoRef.current.destroy();
@@ -5289,7 +6619,18 @@ const EditorField = ({
5289
6619
  return;
5290
6620
  const index2 = editor.blocks.getCurrentBlockIndex();
5291
6621
  const block = index2 >= 0 ? editor.blocks.getBlockByIndex(index2) : null;
5292
- collaboration.client.sendCursor(block ? { blockId: block.id, offset: selection.anchorOffset } : null);
6622
+ const content = block && block.holder && (block.holder.querySelector(".ce-block__content") || block.holder);
6623
+ if (!block || !content) {
6624
+ collaboration.client.sendCursor(null);
6625
+ return;
6626
+ }
6627
+ const anchor = offsetOf(content, selection.anchorNode, selection.anchorOffset);
6628
+ const focus = offsetOf(content, selection.focusNode, selection.focusOffset);
6629
+ collaboration.client.sendCursor({
6630
+ blockId: block.id,
6631
+ anchor: anchor ?? 0,
6632
+ focus: focus ?? anchor ?? 0
6633
+ });
5293
6634
  }, 120);
5294
6635
  };
5295
6636
  document.addEventListener("selectionchange", onSelection);
@@ -5365,7 +6706,11 @@ const EditorField = ({
5365
6706
  const prepared = sanitize.prepareEditorValue(content);
5366
6707
  if (!prepared.data) return false;
5367
6708
  await applyExternal(prepared.data, { emitToForm: true });
5368
- if (collabRef.current) collabRef.current.pushLocal(prepared.data);
6709
+ if (collabRef.current && editorRef.current) {
6710
+ const shown = await editorRef.current.save().catch(() => prepared.data);
6711
+ collabRef.current.stopCapturing();
6712
+ collabRef.current.pushLocal(shown);
6713
+ }
5369
6714
  if (undoRef.current) undoRef.current.record();
5370
6715
  return true;
5371
6716
  },
@@ -5423,8 +6768,8 @@ const EditorField = ({
5423
6768
  readOnly,
5424
6769
  fullscreen,
5425
6770
  onToggleFullscreen: () => setFullscreen((value2) => !value2),
5426
- canUndo: undoState.canUndo,
5427
- canRedo: undoState.canRedo,
6771
+ canUndo: collabUndo ? collaboration.canUndo : undoState.canUndo,
6772
+ canRedo: collabUndo ? collaboration.canRedo : undoState.canRedo,
5428
6773
  onUndo: () => undoRef.current && undoRef.current.undo(),
5429
6774
  onRedo: () => undoRef.current && undoRef.current.redo(),
5430
6775
  historyAvailable: Boolean(target.uid && target.documentId),
@@ -5439,18 +6784,31 @@ const EditorField = ({
5439
6784
  /* @__PURE__ */ jsxRuntime.jsx(designSystem.Button, { variant: "secondary", onClick: retry, children: t("editor.config.retry", "Try again") })
5440
6785
  ] }) : null,
5441
6786
  configLoading ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Flex, { padding: 4, justifyContent: "center", children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Loader, { small: true, children: t("editor.loading", "Loading the editor") }) }) : null,
5442
- /* @__PURE__ */ jsxRuntime.jsx(
5443
- Holder,
5444
- {
5445
- ref: holderRef,
5446
- className: "mex-editor",
5447
- $minHeight: minHeight,
5448
- $fullscreen: fullscreen,
5449
- "data-testid": "magic-editor-x",
5450
- "aria-busy": !ready,
5451
- "aria-describedby": `${name}-mex-keyboard`
5452
- }
5453
- ),
6787
+ /* @__PURE__ */ jsxRuntime.jsxs(EditorArea, { ref: areaRef, $fullscreen: fullscreen, children: [
6788
+ /* @__PURE__ */ jsxRuntime.jsx(
6789
+ Holder,
6790
+ {
6791
+ ref: holderRef,
6792
+ className: "mex-editor",
6793
+ $minHeight: minHeight,
6794
+ $fullscreen: fullscreen,
6795
+ "data-testid": "magic-editor-x",
6796
+ "aria-busy": !ready,
6797
+ "aria-describedby": `${name}-mex-keyboard`
6798
+ }
6799
+ ),
6800
+ collaboration.active && collaboration.peers.length > 0 ? /* @__PURE__ */ jsxRuntime.jsx(
6801
+ RemoteCarets,
6802
+ {
6803
+ containerRef: areaRef,
6804
+ holderRef,
6805
+ peers: collaboration.peers,
6806
+ version: contentVersion,
6807
+ t
6808
+ }
6809
+ ) : null
6810
+ ] }),
6811
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.VisuallyHidden, { "aria-live": "polite", "aria-atomic": "true", children: announcement }),
5454
6812
  /* @__PURE__ */ jsxRuntime.jsx(designSystem.VisuallyHidden, { id: `${name}-mex-keyboard`, children: t(
5455
6813
  "editor.keyboard",
5456
6814
  "Press Tab in an empty block to choose a block type. Press Escape, then Tab, to leave the editor."