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.
- package/CHANGELOG.md +54 -0
- package/README.md +154 -68
- package/dist/admin/{ConfigurationPage-DvAifELO.mjs → ConfigurationPage-CK2AbfGW.mjs} +126 -7
- package/dist/admin/{ConfigurationPage-B1uCIE3J.js → ConfigurationPage-CzsT_dO_.js} +125 -4
- package/dist/admin/{CustomBlocksPage-6-OQwpXQ.mjs → CustomBlocksPage-B2A8S5MV.mjs} +4 -4
- package/dist/admin/{CustomBlocksPage-6eWCOreU.js → CustomBlocksPage-CvLrsBds.js} +4 -4
- package/dist/admin/{EditorField-ThSoOCPm.mjs → EditorField-7YCdXx-v.mjs} +2019 -661
- package/dist/admin/{EditorField-DocyD2Q3.js → EditorField-BdBCW15Q.js} +2015 -657
- package/dist/admin/{api-B-RsxJCs.js → api-CmccMxlN.js} +2 -0
- package/dist/admin/{api-C4XsDZxd.mjs → api-D5CAH0nh.mjs} +2 -0
- package/dist/admin/{de-RAxzvrwm.mjs → de-BHPyA2S-.mjs} +10 -2
- package/dist/admin/{de-BMxADn2Z.mjs → de-Bt6pYIWi.mjs} +16 -1
- package/dist/admin/{de-Dx7vUW0Z.js → de-CVbi685U.js} +16 -1
- package/dist/admin/{de-DcDPRzV4.js → de-CkUYGb7U.js} +22 -1
- package/dist/admin/{de-B8XFFhHh.js → de-RMs-_SCK.js} +10 -2
- package/dist/admin/{de-n5V6c5RT.mjs → de-rRIutpYJ.mjs} +22 -1
- package/dist/admin/{en-sNn4z9lA.js → en-BX362fTp.js} +16 -1
- package/dist/admin/{en-BQ5Pxe2o.mjs → en-B_HltUxZ.mjs} +16 -1
- package/dist/admin/{en-BzfyifEU.mjs → en-BluCStLw.mjs} +10 -2
- package/dist/admin/{en-DcWUTE2J.js → en-C81faOHP.js} +10 -2
- package/dist/admin/{en-D-DGftl0.js → en-DulOcmXb.js} +22 -1
- package/dist/admin/{en-BqNm3nMQ.mjs → en-Puup8TFi.mjs} +22 -1
- package/dist/admin/{es-SzeTV4q8.mjs → es-257SSB7f.mjs} +22 -1
- package/dist/admin/{es-Di0pyQCh.js → es-BoQZC86B.js} +22 -1
- package/dist/admin/{es-DVsXnS0N.js → es-CHHEZi44.js} +16 -1
- package/dist/admin/{es-C2OJVYkV.mjs → es-CQRI2Prp.mjs} +10 -2
- package/dist/admin/{es-B6NYq0VH.mjs → es-CrhwOq-5.mjs} +16 -1
- package/dist/admin/{es-BOtVc9qv.js → es-D1QzY0JW.js} +10 -2
- package/dist/admin/{fr-DmG3_Cn-.mjs → fr-5djKfQ3s.mjs} +16 -1
- package/dist/admin/{fr-Fwxcj4SM.js → fr-B3SL0TBV.js} +16 -1
- package/dist/admin/{fr-DhgPYHIH.mjs → fr-C5rSdKU4.mjs} +22 -1
- package/dist/admin/{fr-Bpo5Uq1f.mjs → fr-Di3R6gOX.mjs} +10 -2
- package/dist/admin/{fr-D6F--jIB.js → fr-HxFcPpv4.js} +22 -1
- package/dist/admin/{fr-DfxKaOc_.js → fr-R3_MbzT5.js} +10 -2
- package/dist/admin/{index-D1Q5Rlt6.mjs → index-0_b1iroK.mjs} +18 -18
- package/dist/admin/{index-CwfaB5-e.js → index-6SZLli70.js} +18 -18
- package/dist/admin/index.js +1 -1
- package/dist/admin/index.mjs +1 -1
- package/dist/admin/{pt-LCvjwk0y.js → pt-BCW1u_Hp.js} +10 -2
- package/dist/admin/{pt-BbdwHlWF.mjs → pt-BdnY2Cth.mjs} +16 -1
- package/dist/admin/{pt-BPo0ex21.js → pt-Cjn2Sc9k.js} +22 -1
- package/dist/admin/{pt-DqCXuI4S.mjs → pt-Cr9AL408.mjs} +10 -2
- package/dist/admin/{pt-BvSl1btT.mjs → pt-D6UuEtPy.mjs} +22 -1
- package/dist/admin/{pt-C6nr71Yw.js → pt-EVwCuBUK.js} +16 -1
- package/dist/admin/{sanitize-9UVcXFfc.js → sanitize-DP5aeU7V.js} +46 -1
- package/dist/admin/{sanitize-D4kfZ_ly.mjs → sanitize-jjCot5PM.mjs} +47 -2
- package/dist/admin/{useT-B5M49wGH.js → useT-91ruePzq.js} +1 -1
- package/dist/admin/{useT-CjX6fL2m.mjs → useT-vgY88N_H.mjs} +1 -1
- package/dist/server/index.js +1561 -321
- package/dist/server/index.mjs +1561 -321
- package/package.json +1 -1
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import { jsxs,
|
|
2
|
-
import { useState, useEffect, useRef, useCallback, useMemo } from "react";
|
|
1
|
+
import { jsx, jsxs, Fragment } from "react/jsx-runtime";
|
|
2
|
+
import { useState, useEffect, useRef, useLayoutEffect, useCallback, useMemo } from "react";
|
|
3
3
|
import { useIntl } from "react-intl";
|
|
4
|
+
import { useNavigate, useHref } from "react-router-dom";
|
|
4
5
|
import EditorJS from "@editorjs/editorjs";
|
|
5
|
-
import { Flex, IconButton, Avatar, Tooltip, Badge, Typography, VisuallyHidden,
|
|
6
|
+
import { Flex, IconButton, Avatar, Tooltip, Box, Badge, Typography, VisuallyHidden, Modal, Loader, Button, Dialog, Field, SingleSelect, SingleSelectOption } from "@strapi/design-system";
|
|
6
7
|
import { useFetchClient, unstable_useContentManagerContext, useQueryParams, useNotification, ConfirmDialog, useStrapiApp } from "@strapi/strapi/admin";
|
|
7
|
-
import styled, { css, createGlobalStyle } from "styled-components";
|
|
8
|
+
import styled, { css, keyframes, createGlobalStyle } from "styled-components";
|
|
8
9
|
import Header from "@editorjs/header";
|
|
9
10
|
import Paragraph from "@editorjs/paragraph";
|
|
10
11
|
import List from "@editorjs/list";
|
|
@@ -18,7 +19,8 @@ import ImageTool from "@editorjs/image";
|
|
|
18
19
|
import Attaches from "@editorjs/attaches";
|
|
19
20
|
import InlineCode from "@editorjs/inline-code";
|
|
20
21
|
import IndentTune from "editorjs-indent-tune";
|
|
21
|
-
import { s as sanitizeUrl, a as sanitizeInline, b as sanitizeSvg, c as sanitizeTemplate, i as isPlainObject, d as computeStats, p as prepareEditorValue } from "./sanitize-
|
|
22
|
+
import { s as sanitizeUrl, a as sanitizeInline, b as sanitizeSvg, c as sanitizeTemplate, E as EDITOR_DATA_LIMITS, i as isPlainObject, d as cloneJsonSafe, e as computeStats, p as prepareEditorValue, f as prepareRemoteData } from "./sanitize-jjCot5PM.mjs";
|
|
23
|
+
import { A as API, r as readApiError } from "./api-D5CAH0nh.mjs";
|
|
22
24
|
import Prism from "prismjs";
|
|
23
25
|
import "prismjs/components/prism-markup-templating";
|
|
24
26
|
import "prismjs/components/prism-typescript";
|
|
@@ -45,8 +47,7 @@ import "prismjs/components/prism-markdown";
|
|
|
45
47
|
import "prismjs/components/prism-docker";
|
|
46
48
|
import "prismjs/components/prism-diff";
|
|
47
49
|
import * as Y from "yjs";
|
|
48
|
-
import {
|
|
49
|
-
import { g as getTranslation } from "./index-D1Q5Rlt6.mjs";
|
|
50
|
+
import { g as getTranslation } from "./index-0_b1iroK.mjs";
|
|
50
51
|
import { io } from "socket.io-client";
|
|
51
52
|
import { ArrowsCounterClockwise, ArrowClockwise, ClockCounterClockwise, Collapse, Expand, Eye } from "@strapi/icons";
|
|
52
53
|
const el = (tag, options = {}) => {
|
|
@@ -148,70 +149,567 @@ const ICONS = {
|
|
|
148
149
|
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>',
|
|
149
150
|
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>'
|
|
150
151
|
};
|
|
151
|
-
const
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
152
|
+
const ALERT_TYPES = Object.freeze([
|
|
153
|
+
"primary",
|
|
154
|
+
"secondary",
|
|
155
|
+
"info",
|
|
156
|
+
"success",
|
|
157
|
+
"warning",
|
|
158
|
+
"danger",
|
|
159
|
+
"light",
|
|
160
|
+
"dark"
|
|
161
|
+
]);
|
|
162
|
+
const ALERT_ALIGNMENTS = Object.freeze(["left", "center", "right"]);
|
|
163
|
+
const ALIGNMENTS = Object.freeze(["left", "center", "right", "justify"]);
|
|
164
|
+
const TEXT_VARIANTS = Object.freeze(["call-out", "citation", "details"]);
|
|
165
|
+
const BUTTON_STYLES = Object.freeze(["primary", "secondary", "outline", "ghost", "danger", "success"]);
|
|
166
|
+
const CODE_LANGUAGES = Object.freeze([
|
|
167
|
+
"plaintext",
|
|
168
|
+
"javascript",
|
|
169
|
+
"typescript",
|
|
170
|
+
"jsx",
|
|
171
|
+
"tsx",
|
|
172
|
+
"json",
|
|
173
|
+
"markup",
|
|
174
|
+
"css",
|
|
175
|
+
"scss",
|
|
176
|
+
"bash",
|
|
177
|
+
"python",
|
|
178
|
+
"php",
|
|
179
|
+
"ruby",
|
|
180
|
+
"java",
|
|
181
|
+
"kotlin",
|
|
182
|
+
"swift",
|
|
183
|
+
"csharp",
|
|
184
|
+
"c",
|
|
185
|
+
"cpp",
|
|
186
|
+
"go",
|
|
187
|
+
"rust",
|
|
188
|
+
"sql",
|
|
189
|
+
"graphql",
|
|
190
|
+
"yaml",
|
|
191
|
+
"markdown",
|
|
192
|
+
"docker",
|
|
193
|
+
"diff"
|
|
194
|
+
]);
|
|
195
|
+
const LANGUAGE_ALIASES = {
|
|
196
|
+
js: "javascript",
|
|
197
|
+
ts: "typescript",
|
|
198
|
+
html: "markup",
|
|
199
|
+
xml: "markup",
|
|
200
|
+
svg: "markup",
|
|
201
|
+
sh: "bash",
|
|
202
|
+
shell: "bash",
|
|
203
|
+
py: "python",
|
|
204
|
+
yml: "yaml",
|
|
205
|
+
md: "markdown",
|
|
206
|
+
dockerfile: "docker",
|
|
207
|
+
"c#": "csharp",
|
|
208
|
+
cs: "csharp",
|
|
209
|
+
"c++": "cpp",
|
|
210
|
+
text: "plaintext",
|
|
211
|
+
plain: "plaintext",
|
|
212
|
+
none: "plaintext"
|
|
158
213
|
};
|
|
159
|
-
const
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
214
|
+
const str = (value) => typeof value === "string" ? value : "";
|
|
215
|
+
const pick = (value, allowed, fallback) => typeof value === "string" && allowed.includes(value) ? value : fallback;
|
|
216
|
+
const normalizeAlert = (data, config = {}) => {
|
|
217
|
+
const d = data && typeof data === "object" ? data : {};
|
|
218
|
+
return {
|
|
219
|
+
type: pick(d.type, ALERT_TYPES, pick(config.defaultType, ALERT_TYPES, "info")),
|
|
220
|
+
align: pick(d.align, ALERT_ALIGNMENTS, pick(config.defaultAlign, ALERT_ALIGNMENTS, "left")),
|
|
221
|
+
// Some editorjs-alert versions wrote `text` instead of `message`.
|
|
222
|
+
message: str(d.message) || str(d.text)
|
|
223
|
+
};
|
|
169
224
|
};
|
|
170
|
-
const
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
225
|
+
const normalizeAlignment = (data, fallback = "left") => ({
|
|
226
|
+
alignment: pick(data && data.alignment, ALIGNMENTS, pick(fallback, ALIGNMENTS, "left"))
|
|
227
|
+
});
|
|
228
|
+
const normalizeTextVariant = (data) => pick(data, TEXT_VARIANTS, "");
|
|
229
|
+
const normalizeLanguage = (language) => {
|
|
230
|
+
const raw = str(language).trim().toLowerCase();
|
|
231
|
+
const mapped = LANGUAGE_ALIASES[raw] || raw;
|
|
232
|
+
return CODE_LANGUAGES.includes(mapped) ? mapped : "plaintext";
|
|
233
|
+
};
|
|
234
|
+
const normalizeCodeFlask = (data, config = {}) => {
|
|
235
|
+
const d = data && typeof data === "object" ? data : {};
|
|
236
|
+
return {
|
|
237
|
+
code: str(d.code),
|
|
238
|
+
language: d.language ? normalizeLanguage(d.language) : normalizeLanguage(config.language || "plaintext"),
|
|
239
|
+
showlinenumbers: d.showlinenumbers !== false
|
|
240
|
+
};
|
|
241
|
+
};
|
|
242
|
+
const checklistToList = (data) => {
|
|
243
|
+
const items = data && Array.isArray(data.items) ? data.items : [];
|
|
244
|
+
return {
|
|
245
|
+
style: "checklist",
|
|
246
|
+
meta: {},
|
|
247
|
+
items: items.map((item) => {
|
|
248
|
+
if (typeof item === "string") return { content: item, meta: { checked: false }, items: [] };
|
|
249
|
+
const value = item && typeof item === "object" ? item : {};
|
|
250
|
+
return {
|
|
251
|
+
content: str(value.text) || str(value.content),
|
|
252
|
+
meta: { checked: Boolean(value.checked ?? (value.meta && value.meta.checked)) },
|
|
253
|
+
items: []
|
|
254
|
+
};
|
|
255
|
+
})
|
|
256
|
+
};
|
|
257
|
+
};
|
|
258
|
+
const listToChecklist = (data) => {
|
|
259
|
+
const out = [];
|
|
260
|
+
const walk = (items, depth) => {
|
|
261
|
+
if (!Array.isArray(items) || depth > 12) return;
|
|
262
|
+
for (const item of items) {
|
|
263
|
+
if (!item || typeof item !== "object") continue;
|
|
264
|
+
out.push({ text: str(item.content), checked: Boolean(item.meta && item.meta.checked) });
|
|
265
|
+
walk(item.items, depth + 1);
|
|
266
|
+
}
|
|
267
|
+
};
|
|
268
|
+
walk(data && data.items, 0);
|
|
269
|
+
return { items: out };
|
|
270
|
+
};
|
|
271
|
+
const normalizeToggle = (data, fallbackKey) => {
|
|
272
|
+
const d = data && typeof data === "object" ? data : {};
|
|
273
|
+
const items = Number(d.items);
|
|
274
|
+
return {
|
|
275
|
+
text: str(d.text),
|
|
276
|
+
status: d.status === "closed" ? "closed" : "open",
|
|
277
|
+
fk: str(d.fk) || str(fallbackKey),
|
|
278
|
+
items: Number.isInteger(items) && items > 0 ? Math.min(items, 5e3) : 0
|
|
279
|
+
};
|
|
280
|
+
};
|
|
281
|
+
const toggleChildIndexes = (toggleIndex, items, total) => {
|
|
282
|
+
if (!Number.isInteger(toggleIndex) || toggleIndex < 0) return [];
|
|
283
|
+
const count = Math.max(0, Math.min(Number(items) || 0, total - toggleIndex - 1));
|
|
284
|
+
return Array.from({ length: count }, (_, i) => toggleIndex + 1 + i);
|
|
285
|
+
};
|
|
286
|
+
const nextToggleItems = (toggleIndex, items, total, action) => {
|
|
287
|
+
const current = toggleChildIndexes(toggleIndex, items, total).length;
|
|
288
|
+
if (action === "include") return Math.min(current + 1, Math.max(0, total - toggleIndex - 1));
|
|
289
|
+
return Math.max(0, current - 1);
|
|
290
|
+
};
|
|
291
|
+
const normalizeButton = (data) => {
|
|
292
|
+
const d = data && typeof data === "object" ? data : {};
|
|
293
|
+
return {
|
|
294
|
+
text: str(d.text),
|
|
295
|
+
link: str(d.link),
|
|
296
|
+
style: pick(d.style, BUTTON_STYLES, "primary"),
|
|
297
|
+
openInNewTab: d.openInNewTab === true
|
|
298
|
+
};
|
|
299
|
+
};
|
|
300
|
+
const normalizeSimpleImage = (data) => {
|
|
301
|
+
const d = data && typeof data === "object" ? data : {};
|
|
302
|
+
return {
|
|
303
|
+
url: str(d.url),
|
|
304
|
+
caption: str(d.caption),
|
|
305
|
+
withBorder: d.withBorder === true,
|
|
306
|
+
withBackground: d.withBackground === true,
|
|
307
|
+
stretched: d.stretched === true
|
|
308
|
+
};
|
|
309
|
+
};
|
|
310
|
+
const normalizePersonality = (data) => {
|
|
311
|
+
const d = data && typeof data === "object" ? data : {};
|
|
312
|
+
return { name: str(d.name), description: str(d.description), link: str(d.link), photo: str(d.photo) };
|
|
313
|
+
};
|
|
314
|
+
const normalizeLinkTool = (data) => {
|
|
315
|
+
const d = data && typeof data === "object" ? data : {};
|
|
316
|
+
const meta = d.meta && typeof d.meta === "object" ? d.meta : {};
|
|
317
|
+
const out = { title: str(meta.title), description: str(meta.description) };
|
|
318
|
+
if (str(meta.site_name)) out.site_name = str(meta.site_name);
|
|
319
|
+
if (meta.image && typeof meta.image === "object" && str(meta.image.url))
|
|
320
|
+
out.image = { url: str(meta.image.url) };
|
|
321
|
+
return { link: str(d.link), meta: out };
|
|
322
|
+
};
|
|
323
|
+
const normalizeEmbeddedEntry = (data, config = {}) => {
|
|
324
|
+
const d = data && typeof data === "object" ? data : {};
|
|
325
|
+
return {
|
|
326
|
+
entry: d.entry && typeof d.entry === "object" ? d.entry : null,
|
|
327
|
+
contentType: str(d.contentType) || config.contentType || null,
|
|
328
|
+
displayMode: pick(d.displayMode, ["card", "inline", "minimal"], "card")
|
|
329
|
+
};
|
|
330
|
+
};
|
|
331
|
+
const summarizeEntry = (entry, config = {}) => {
|
|
332
|
+
const titleField = config.titleField || "title";
|
|
333
|
+
const title = [entry[titleField], entry.title, entry.name, entry.label, entry.slug].find(
|
|
334
|
+
(v) => typeof v === "string" && v.trim()
|
|
335
|
+
);
|
|
336
|
+
const out = {
|
|
337
|
+
id: entry.id,
|
|
338
|
+
documentId: entry.documentId,
|
|
339
|
+
title: title || String(entry.documentId || entry.id || "")
|
|
340
|
+
};
|
|
341
|
+
for (const field2 of config.displayFields || []) {
|
|
342
|
+
const value = entry[field2];
|
|
343
|
+
if (["string", "number", "boolean"].includes(typeof value)) out[field2] = value;
|
|
202
344
|
}
|
|
345
|
+
return out;
|
|
203
346
|
};
|
|
204
|
-
const
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
347
|
+
const fillTemplate = (template, data) => String(template || "").replace(/\{\{\s*([A-Za-z_][A-Za-z0-9_]{0,39})\s*\}\}/g, (_match, name) => {
|
|
348
|
+
const value = data && Object.prototype.hasOwnProperty.call(data, name) ? data[name] : "";
|
|
349
|
+
let text = "";
|
|
350
|
+
if (value && typeof value === "object") text = typeof value.url === "string" ? value.url : "";
|
|
351
|
+
else if (value !== null && value !== void 0) text = String(value);
|
|
352
|
+
return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
210
353
|
});
|
|
211
|
-
const
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
354
|
+
const createHistoryStack = ({ maxSteps = 50 } = {}) => {
|
|
355
|
+
let past = [];
|
|
356
|
+
let present = null;
|
|
357
|
+
let future = [];
|
|
358
|
+
return {
|
|
359
|
+
/** Sets the starting state without an undo step. */
|
|
360
|
+
init(state) {
|
|
361
|
+
past = [];
|
|
362
|
+
future = [];
|
|
363
|
+
present = state;
|
|
364
|
+
},
|
|
365
|
+
/** Records a new state; identical consecutive states are ignored. @returns {boolean} Recorded. */
|
|
366
|
+
push(state) {
|
|
367
|
+
if (state === present) return false;
|
|
368
|
+
if (present !== null) past.push(present);
|
|
369
|
+
if (past.length > maxSteps) past = past.slice(past.length - maxSteps);
|
|
370
|
+
present = state;
|
|
371
|
+
future = [];
|
|
372
|
+
return true;
|
|
373
|
+
},
|
|
374
|
+
/** @returns {string|null} State to show after undo. */
|
|
375
|
+
undo() {
|
|
376
|
+
if (past.length === 0) return null;
|
|
377
|
+
future.push(present);
|
|
378
|
+
present = past.pop();
|
|
379
|
+
return present;
|
|
380
|
+
},
|
|
381
|
+
/** @returns {string|null} State to show after redo. */
|
|
382
|
+
redo() {
|
|
383
|
+
if (future.length === 0) return null;
|
|
384
|
+
past.push(present);
|
|
385
|
+
present = future.pop();
|
|
386
|
+
return present;
|
|
387
|
+
},
|
|
388
|
+
/** Replaces the current state without touching undo/redo (re-serialised after a render). */
|
|
389
|
+
replacePresent(state) {
|
|
390
|
+
present = state;
|
|
391
|
+
},
|
|
392
|
+
canUndo: () => past.length > 0,
|
|
393
|
+
canRedo: () => future.length > 0,
|
|
394
|
+
current: () => present,
|
|
395
|
+
clear() {
|
|
396
|
+
past = [];
|
|
397
|
+
future = [];
|
|
398
|
+
present = null;
|
|
399
|
+
}
|
|
400
|
+
};
|
|
401
|
+
};
|
|
402
|
+
const historyKey = (data) => JSON.stringify(data && data.blocks || []);
|
|
403
|
+
const dropIndex = (rects, y, fromIndex) => {
|
|
404
|
+
if (rects.length === 0) return fromIndex;
|
|
405
|
+
let insertBefore = rects.length;
|
|
406
|
+
for (let i = 0; i < rects.length; i += 1) {
|
|
407
|
+
const middle = (rects[i].top + rects[i].bottom) / 2;
|
|
408
|
+
if (y < middle) {
|
|
409
|
+
insertBefore = i;
|
|
410
|
+
break;
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
const to = insertBefore > fromIndex ? insertBefore - 1 : insertBefore;
|
|
414
|
+
return Math.max(0, Math.min(rects.length - 1, to));
|
|
415
|
+
};
|
|
416
|
+
const moveActiveIndex = (current, delta, length) => {
|
|
417
|
+
if (!Number.isInteger(length) || length <= 0) return -1;
|
|
418
|
+
if (!Number.isInteger(current) || current < 0 || current >= length) return delta < 0 ? length - 1 : 0;
|
|
419
|
+
return (current + delta + length) % length;
|
|
420
|
+
};
|
|
421
|
+
const readInternalLink = (node) => {
|
|
422
|
+
if (!node || typeof node.getAttribute !== "function") return null;
|
|
423
|
+
const uid = node.getAttribute("data-mex-uid");
|
|
424
|
+
const documentId = node.getAttribute("data-mex-document-id");
|
|
425
|
+
if (!uid || !documentId) return null;
|
|
426
|
+
return {
|
|
427
|
+
href: node.getAttribute("href") || "",
|
|
428
|
+
uid,
|
|
429
|
+
documentId,
|
|
430
|
+
locale: node.getAttribute("data-mex-locale") || null
|
|
431
|
+
};
|
|
432
|
+
};
|
|
433
|
+
const internalLinkAttributes = (internal, href) => {
|
|
434
|
+
const keep = Boolean(internal && internal.uid && internal.documentId && internal.href === href);
|
|
435
|
+
return {
|
|
436
|
+
"data-mex-uid": keep ? internal.uid : null,
|
|
437
|
+
"data-mex-document-id": keep ? internal.documentId : null,
|
|
438
|
+
"data-mex-locale": keep && internal.locale ? internal.locale : null
|
|
439
|
+
};
|
|
440
|
+
};
|
|
441
|
+
const typeCache = /* @__PURE__ */ new WeakMap();
|
|
442
|
+
let pickerCount = 0;
|
|
443
|
+
const loadTypes = (fetchClient) => {
|
|
444
|
+
if (!typeCache.has(fetchClient)) {
|
|
445
|
+
const promise = fetchClient.get(API.linkTypes).then(({ data }) => data && Array.isArray(data.data) ? data.data : []).catch((error) => {
|
|
446
|
+
typeCache.delete(fetchClient);
|
|
447
|
+
throw error;
|
|
448
|
+
});
|
|
449
|
+
typeCache.set(fetchClient, promise);
|
|
450
|
+
}
|
|
451
|
+
return typeCache.get(fetchClient);
|
|
452
|
+
};
|
|
453
|
+
const createLinkPicker = ({ t, fetchClient, getLocale, onPick, onClose }) => {
|
|
454
|
+
pickerCount += 1;
|
|
455
|
+
const id = `mex-link-picker-${pickerCount}`;
|
|
456
|
+
const element = el("div", {
|
|
457
|
+
className: "mex-link-picker",
|
|
458
|
+
attrs: { id, role: "group", "aria-label": t("tools.hyperlink.internal.title", "Link to an entry") }
|
|
459
|
+
});
|
|
460
|
+
element.hidden = true;
|
|
461
|
+
let types = [];
|
|
462
|
+
let items = [];
|
|
463
|
+
let active = -1;
|
|
464
|
+
let timer = null;
|
|
465
|
+
let requestId = 0;
|
|
466
|
+
let typeSelect = null;
|
|
467
|
+
let search = null;
|
|
468
|
+
const status = el("p", { className: "mex-tool__muted", attrs: { role: "status", "aria-live": "polite" } });
|
|
469
|
+
const list = el("ul", {
|
|
470
|
+
className: "mex-link-picker__results",
|
|
471
|
+
attrs: {
|
|
472
|
+
id: `${id}-results`,
|
|
473
|
+
role: "listbox",
|
|
474
|
+
"aria-label": t("tools.hyperlink.internal.results", "Entries")
|
|
475
|
+
}
|
|
476
|
+
});
|
|
477
|
+
const setStatus = (text, isError = false) => {
|
|
478
|
+
status.className = isError ? "mex-tool__error" : "mex-tool__muted";
|
|
479
|
+
status.textContent = text;
|
|
480
|
+
};
|
|
481
|
+
const setActive = (index) => {
|
|
482
|
+
active = index;
|
|
483
|
+
Array.from(list.children).forEach((option, i) => {
|
|
484
|
+
option.setAttribute("aria-selected", i === active ? "true" : "false");
|
|
485
|
+
if (i === active && typeof option.scrollIntoView === "function")
|
|
486
|
+
option.scrollIntoView({ block: "nearest" });
|
|
487
|
+
});
|
|
488
|
+
if (search) {
|
|
489
|
+
if (active >= 0) search.setAttribute("aria-activedescendant", `${id}-option-${active}`);
|
|
490
|
+
else search.removeAttribute("aria-activedescendant");
|
|
491
|
+
}
|
|
492
|
+
};
|
|
493
|
+
const pick2 = (index) => {
|
|
494
|
+
const item = items[index];
|
|
495
|
+
if (item && item.href) onPick(item);
|
|
496
|
+
};
|
|
497
|
+
const renderResults = () => {
|
|
498
|
+
list.replaceChildren();
|
|
499
|
+
items.forEach((item, index) => {
|
|
500
|
+
const statusLabel = item.status === "published" ? t("tools.hyperlink.internal.published", "Published") : item.status === "draft" ? t("tools.hyperlink.internal.draft", "Draft") : "";
|
|
501
|
+
const meta = [statusLabel, item.locale || ""].filter(Boolean).join(" · ");
|
|
502
|
+
const option = el("li", {
|
|
503
|
+
className: "mex-link-picker__option",
|
|
504
|
+
attrs: {
|
|
505
|
+
id: `${id}-option-${index}`,
|
|
506
|
+
role: "option",
|
|
507
|
+
"aria-selected": "false",
|
|
508
|
+
"aria-disabled": item.href ? null : "true"
|
|
509
|
+
},
|
|
510
|
+
children: [
|
|
511
|
+
el("span", {
|
|
512
|
+
className: "mex-link-picker__title",
|
|
513
|
+
text: item.title || t("tools.hyperlink.internal.untitled", "Untitled entry")
|
|
514
|
+
}),
|
|
515
|
+
meta ? el("span", { className: "mex-link-picker__meta", text: meta }) : null
|
|
516
|
+
]
|
|
517
|
+
});
|
|
518
|
+
option.addEventListener("mousedown", (event) => event.preventDefault());
|
|
519
|
+
option.addEventListener("click", () => pick2(index));
|
|
520
|
+
list.appendChild(option);
|
|
521
|
+
});
|
|
522
|
+
if (search) search.setAttribute("aria-expanded", items.length ? "true" : "false");
|
|
523
|
+
setActive(items.length ? 0 : -1);
|
|
524
|
+
};
|
|
525
|
+
const run = async () => {
|
|
526
|
+
window.clearTimeout(timer);
|
|
527
|
+
const current = requestId += 1;
|
|
528
|
+
const type = types.find((candidate) => candidate.uid === (typeSelect && typeSelect.value));
|
|
529
|
+
if (!type) return;
|
|
530
|
+
const q = search ? search.value.trim().slice(0, 100) : "";
|
|
531
|
+
const locale = type.localized && typeof getLocale === "function" ? getLocale() : null;
|
|
532
|
+
setStatus(t("tools.hyperlink.internal.searching", "Searching"));
|
|
533
|
+
list.setAttribute("aria-busy", "true");
|
|
534
|
+
try {
|
|
535
|
+
const { data } = await fetchClient.get(API.linkSearch, {
|
|
536
|
+
params: { uid: type.uid, ...q ? { q } : {}, ...locale ? { locale } : {} }
|
|
537
|
+
});
|
|
538
|
+
if (current !== requestId) return;
|
|
539
|
+
items = data && Array.isArray(data.data) ? data.data : [];
|
|
540
|
+
renderResults();
|
|
541
|
+
setStatus(items.length ? "" : t("tools.hyperlink.internal.empty", "No entries match your search"));
|
|
542
|
+
} catch {
|
|
543
|
+
if (current !== requestId) return;
|
|
544
|
+
items = [];
|
|
545
|
+
renderResults();
|
|
546
|
+
setStatus(t("tools.hyperlink.internal.failed", "Entries could not be loaded"), true);
|
|
547
|
+
} finally {
|
|
548
|
+
if (current === requestId) list.removeAttribute("aria-busy");
|
|
549
|
+
}
|
|
550
|
+
};
|
|
551
|
+
const onKeyDown = (event) => {
|
|
552
|
+
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
|
|
553
|
+
event.preventDefault();
|
|
554
|
+
event.stopPropagation();
|
|
555
|
+
setActive(moveActiveIndex(active, event.key === "ArrowDown" ? 1 : -1, items.length));
|
|
556
|
+
} else if (event.key === "Enter") {
|
|
557
|
+
event.preventDefault();
|
|
558
|
+
event.stopPropagation();
|
|
559
|
+
if (active >= 0 && items[active]) pick2(active);
|
|
560
|
+
else run();
|
|
561
|
+
} else if (event.key === "Escape") {
|
|
562
|
+
event.preventDefault();
|
|
563
|
+
event.stopPropagation();
|
|
564
|
+
close();
|
|
565
|
+
}
|
|
566
|
+
};
|
|
567
|
+
const build = () => {
|
|
568
|
+
element.replaceChildren();
|
|
569
|
+
typeSelect = select(
|
|
570
|
+
types.map((type) => ({ value: type.uid, label: type.displayName })),
|
|
571
|
+
types[0].uid
|
|
572
|
+
);
|
|
573
|
+
search = input({
|
|
574
|
+
type: "search",
|
|
575
|
+
placeholder: t("tools.hyperlink.internal.searchPlaceholder", "Search by title")
|
|
576
|
+
});
|
|
577
|
+
search.setAttribute("role", "combobox");
|
|
578
|
+
search.setAttribute("aria-autocomplete", "list");
|
|
579
|
+
search.setAttribute("aria-controls", list.id);
|
|
580
|
+
search.setAttribute("aria-expanded", "false");
|
|
581
|
+
search.setAttribute("maxlength", "100");
|
|
582
|
+
search.addEventListener("input", () => {
|
|
583
|
+
window.clearTimeout(timer);
|
|
584
|
+
timer = window.setTimeout(run, 250);
|
|
585
|
+
});
|
|
586
|
+
typeSelect.addEventListener("change", run);
|
|
587
|
+
typeSelect.addEventListener("keydown", (event) => {
|
|
588
|
+
if (event.key === "Escape") {
|
|
589
|
+
event.preventDefault();
|
|
590
|
+
event.stopPropagation();
|
|
591
|
+
close();
|
|
592
|
+
}
|
|
593
|
+
});
|
|
594
|
+
element.append(
|
|
595
|
+
el("div", {
|
|
596
|
+
className: "mex-link-picker__controls",
|
|
597
|
+
children: [
|
|
598
|
+
field(t("tools.hyperlink.internal.type", "Content type"), typeSelect),
|
|
599
|
+
field(t("tools.hyperlink.internal.search", "Search"), search)
|
|
600
|
+
]
|
|
601
|
+
}),
|
|
602
|
+
status,
|
|
603
|
+
list
|
|
604
|
+
);
|
|
605
|
+
};
|
|
606
|
+
const guard = (event) => {
|
|
607
|
+
if (element.hidden || !element.contains(event.target)) return;
|
|
608
|
+
if (!["Enter", "ArrowDown", "ArrowUp", "Escape", "Tab"].includes(event.key)) return;
|
|
609
|
+
event.stopPropagation();
|
|
610
|
+
if (event.key === "Tab") return;
|
|
611
|
+
if (event.target === search) onKeyDown(event);
|
|
612
|
+
else if (event.key === "Escape") {
|
|
613
|
+
event.preventDefault();
|
|
614
|
+
close();
|
|
615
|
+
}
|
|
616
|
+
};
|
|
617
|
+
const open = async () => {
|
|
618
|
+
window.addEventListener("keydown", guard, true);
|
|
619
|
+
element.hidden = false;
|
|
620
|
+
element.replaceChildren(status);
|
|
621
|
+
setStatus(t("tools.hyperlink.internal.loading", "Loading content types"));
|
|
622
|
+
try {
|
|
623
|
+
types = await loadTypes(fetchClient);
|
|
624
|
+
} catch {
|
|
625
|
+
setStatus(t("tools.hyperlink.internal.typesFailed", "Content types could not be loaded"), true);
|
|
626
|
+
return;
|
|
627
|
+
}
|
|
628
|
+
if (element.hidden) return;
|
|
629
|
+
if (!types.length) {
|
|
630
|
+
setStatus(t("tools.hyperlink.internal.noTypes", "There is no content type you can read"));
|
|
631
|
+
return;
|
|
632
|
+
}
|
|
633
|
+
build();
|
|
634
|
+
search.focus();
|
|
635
|
+
run();
|
|
636
|
+
};
|
|
637
|
+
function close() {
|
|
638
|
+
window.removeEventListener("keydown", guard, true);
|
|
639
|
+
window.clearTimeout(timer);
|
|
640
|
+
requestId += 1;
|
|
641
|
+
element.hidden = true;
|
|
642
|
+
element.replaceChildren();
|
|
643
|
+
items = [];
|
|
644
|
+
active = -1;
|
|
645
|
+
onClose();
|
|
646
|
+
}
|
|
647
|
+
return { element, open, close, isOpen: () => !element.hidden };
|
|
648
|
+
};
|
|
649
|
+
const wrapRange = (api, range, tag, className) => {
|
|
650
|
+
const wrapper = document.createElement(tag);
|
|
651
|
+
if (className) wrapper.classList.add(className);
|
|
652
|
+
wrapper.appendChild(range.extractContents());
|
|
653
|
+
range.insertNode(wrapper);
|
|
654
|
+
api.selection.expandToTag(wrapper);
|
|
655
|
+
return wrapper;
|
|
656
|
+
};
|
|
657
|
+
const unwrap = (api, wrapper) => {
|
|
658
|
+
api.selection.expandToTag(wrapper);
|
|
659
|
+
const selection = window.getSelection();
|
|
660
|
+
if (!selection || selection.rangeCount === 0) return;
|
|
661
|
+
const range = selection.getRangeAt(0);
|
|
662
|
+
const contents = range.extractContents();
|
|
663
|
+
if (wrapper.parentNode) wrapper.parentNode.removeChild(wrapper);
|
|
664
|
+
range.insertNode(contents);
|
|
665
|
+
selection.removeAllRanges();
|
|
666
|
+
selection.addRange(range);
|
|
667
|
+
};
|
|
668
|
+
const createFormatTool = (spec) => class FormatInlineTool {
|
|
669
|
+
static get isInline() {
|
|
670
|
+
return true;
|
|
671
|
+
}
|
|
672
|
+
static get title() {
|
|
673
|
+
return spec.title;
|
|
674
|
+
}
|
|
675
|
+
static get sanitize() {
|
|
676
|
+
return { [spec.tag]: { class: spec.className } };
|
|
677
|
+
}
|
|
678
|
+
constructor({ api }) {
|
|
679
|
+
this.api = api;
|
|
680
|
+
this.button = null;
|
|
681
|
+
}
|
|
682
|
+
get shortcut() {
|
|
683
|
+
return spec.shortcut;
|
|
684
|
+
}
|
|
685
|
+
render() {
|
|
686
|
+
this.button = el("button", { className: this.api.styles.inlineToolButton, attrs: { type: "button" } });
|
|
687
|
+
this.button.innerHTML = spec.icon;
|
|
688
|
+
return this.button;
|
|
689
|
+
}
|
|
690
|
+
surround(range) {
|
|
691
|
+
if (!range) return;
|
|
692
|
+
const existing = this.api.selection.findParentTag(spec.tag.toUpperCase(), spec.className);
|
|
693
|
+
if (existing) unwrap(this.api, existing);
|
|
694
|
+
else wrapRange(this.api, range, spec.tag, spec.className);
|
|
695
|
+
}
|
|
696
|
+
checkState() {
|
|
697
|
+
const active = Boolean(this.api.selection.findParentTag(spec.tag.toUpperCase(), spec.className));
|
|
698
|
+
if (this.button) this.button.classList.toggle(this.api.styles.inlineToolButtonActive, active);
|
|
699
|
+
return active;
|
|
700
|
+
}
|
|
701
|
+
};
|
|
702
|
+
const MarkerTool = createFormatTool({
|
|
703
|
+
tag: "mark",
|
|
704
|
+
className: "cdx-marker",
|
|
705
|
+
title: "Marker",
|
|
706
|
+
icon: ICONS.marker,
|
|
707
|
+
shortcut: "CMD+SHIFT+M"
|
|
708
|
+
});
|
|
709
|
+
const UnderlineTool = createFormatTool({
|
|
710
|
+
tag: "u",
|
|
711
|
+
className: "cdx-underline",
|
|
712
|
+
title: "Underline",
|
|
215
713
|
icon: ICONS.underline,
|
|
216
714
|
shortcut: "CMD+U"
|
|
217
715
|
});
|
|
@@ -266,7 +764,10 @@ class AttributeInlineTool {
|
|
|
266
764
|
this.api.inlineToolbar.close();
|
|
267
765
|
}
|
|
268
766
|
});
|
|
269
|
-
this.input.addEventListener("blur", () =>
|
|
767
|
+
this.input.addEventListener("blur", (event) => {
|
|
768
|
+
if (this.actions && event.relatedTarget && this.actions.contains(event.relatedTarget)) return;
|
|
769
|
+
this.commit();
|
|
770
|
+
});
|
|
270
771
|
this.actions = el("div", { className: "mex-inline-actions", children: [this.input] });
|
|
271
772
|
this.actions.hidden = true;
|
|
272
773
|
return this.actions;
|
|
@@ -351,7 +852,22 @@ class HyperlinkTool extends AttributeInlineTool {
|
|
|
351
852
|
return "Link";
|
|
352
853
|
}
|
|
353
854
|
static get sanitize() {
|
|
354
|
-
return {
|
|
855
|
+
return {
|
|
856
|
+
a: {
|
|
857
|
+
href: true,
|
|
858
|
+
target: true,
|
|
859
|
+
rel: true,
|
|
860
|
+
"data-mex-uid": true,
|
|
861
|
+
"data-mex-document-id": true,
|
|
862
|
+
"data-mex-locale": true
|
|
863
|
+
}
|
|
864
|
+
};
|
|
865
|
+
}
|
|
866
|
+
constructor(options) {
|
|
867
|
+
super(options);
|
|
868
|
+
this.internal = null;
|
|
869
|
+
this.picker = null;
|
|
870
|
+
this.pickerToggle = null;
|
|
355
871
|
}
|
|
356
872
|
get shortcut() {
|
|
357
873
|
return "CMD+K";
|
|
@@ -363,341 +879,127 @@ class HyperlinkTool extends AttributeInlineTool {
|
|
|
363
879
|
placeholderKey: "tools.hyperlink.placeholder",
|
|
364
880
|
placeholder: "Paste a link and press Enter",
|
|
365
881
|
labelKey: "tools.hyperlink.label",
|
|
366
|
-
label: "Link address"
|
|
367
|
-
};
|
|
368
|
-
}
|
|
369
|
-
renderActions() {
|
|
370
|
-
const actions = super.renderActions();
|
|
371
|
-
const newTabId = `mex-newtab-${Math.random().toString(36).slice(2, 8)}`;
|
|
372
|
-
this.newTab = el("input", { attrs: { type: "checkbox", id: newTabId } });
|
|
373
|
-
this.newTab.checked = this.config.target === "_blank";
|
|
374
|
-
this.newTab.addEventListener("change", () => this.commit());
|
|
375
|
-
actions.appendChild(
|
|
376
|
-
el("label", {
|
|
377
|
-
className: "mex-inline-check",
|
|
378
|
-
attrs: { for: newTabId },
|
|
379
|
-
children: [this.newTab, el("span", { text: this.t("tools.hyperlink.newTab", "Open in a new tab") })]
|
|
380
|
-
})
|
|
381
|
-
);
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
this.
|
|
416
|
-
}
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
this.
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
if (
|
|
431
|
-
this.
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
"light",
|
|
445
|
-
"dark"
|
|
446
|
-
]);
|
|
447
|
-
const ALERT_ALIGNMENTS = Object.freeze(["left", "center", "right"]);
|
|
448
|
-
const ALIGNMENTS = Object.freeze(["left", "center", "right", "justify"]);
|
|
449
|
-
const TEXT_VARIANTS = Object.freeze(["call-out", "citation", "details"]);
|
|
450
|
-
const BUTTON_STYLES = Object.freeze(["primary", "secondary", "outline", "ghost", "danger", "success"]);
|
|
451
|
-
const CODE_LANGUAGES = Object.freeze([
|
|
452
|
-
"plaintext",
|
|
453
|
-
"javascript",
|
|
454
|
-
"typescript",
|
|
455
|
-
"jsx",
|
|
456
|
-
"tsx",
|
|
457
|
-
"json",
|
|
458
|
-
"markup",
|
|
459
|
-
"css",
|
|
460
|
-
"scss",
|
|
461
|
-
"bash",
|
|
462
|
-
"python",
|
|
463
|
-
"php",
|
|
464
|
-
"ruby",
|
|
465
|
-
"java",
|
|
466
|
-
"kotlin",
|
|
467
|
-
"swift",
|
|
468
|
-
"csharp",
|
|
469
|
-
"c",
|
|
470
|
-
"cpp",
|
|
471
|
-
"go",
|
|
472
|
-
"rust",
|
|
473
|
-
"sql",
|
|
474
|
-
"graphql",
|
|
475
|
-
"yaml",
|
|
476
|
-
"markdown",
|
|
477
|
-
"docker",
|
|
478
|
-
"diff"
|
|
479
|
-
]);
|
|
480
|
-
const LANGUAGE_ALIASES = {
|
|
481
|
-
js: "javascript",
|
|
482
|
-
ts: "typescript",
|
|
483
|
-
html: "markup",
|
|
484
|
-
xml: "markup",
|
|
485
|
-
svg: "markup",
|
|
486
|
-
sh: "bash",
|
|
487
|
-
shell: "bash",
|
|
488
|
-
py: "python",
|
|
489
|
-
yml: "yaml",
|
|
490
|
-
md: "markdown",
|
|
491
|
-
dockerfile: "docker",
|
|
492
|
-
"c#": "csharp",
|
|
493
|
-
cs: "csharp",
|
|
494
|
-
"c++": "cpp",
|
|
495
|
-
text: "plaintext",
|
|
496
|
-
plain: "plaintext",
|
|
497
|
-
none: "plaintext"
|
|
498
|
-
};
|
|
499
|
-
const str = (value) => typeof value === "string" ? value : "";
|
|
500
|
-
const pick = (value, allowed, fallback) => typeof value === "string" && allowed.includes(value) ? value : fallback;
|
|
501
|
-
const normalizeAlert = (data, config = {}) => {
|
|
502
|
-
const d = data && typeof data === "object" ? data : {};
|
|
503
|
-
return {
|
|
504
|
-
type: pick(d.type, ALERT_TYPES, pick(config.defaultType, ALERT_TYPES, "info")),
|
|
505
|
-
align: pick(d.align, ALERT_ALIGNMENTS, pick(config.defaultAlign, ALERT_ALIGNMENTS, "left")),
|
|
506
|
-
// Some editorjs-alert versions wrote `text` instead of `message`.
|
|
507
|
-
message: str(d.message) || str(d.text)
|
|
508
|
-
};
|
|
509
|
-
};
|
|
510
|
-
const normalizeAlignment = (data, fallback = "left") => ({
|
|
511
|
-
alignment: pick(data && data.alignment, ALIGNMENTS, pick(fallback, ALIGNMENTS, "left"))
|
|
512
|
-
});
|
|
513
|
-
const normalizeTextVariant = (data) => pick(data, TEXT_VARIANTS, "");
|
|
514
|
-
const normalizeLanguage = (language) => {
|
|
515
|
-
const raw = str(language).trim().toLowerCase();
|
|
516
|
-
const mapped = LANGUAGE_ALIASES[raw] || raw;
|
|
517
|
-
return CODE_LANGUAGES.includes(mapped) ? mapped : "plaintext";
|
|
518
|
-
};
|
|
519
|
-
const normalizeCodeFlask = (data, config = {}) => {
|
|
520
|
-
const d = data && typeof data === "object" ? data : {};
|
|
521
|
-
return {
|
|
522
|
-
code: str(d.code),
|
|
523
|
-
language: d.language ? normalizeLanguage(d.language) : normalizeLanguage(config.language || "plaintext"),
|
|
524
|
-
showlinenumbers: d.showlinenumbers !== false
|
|
525
|
-
};
|
|
526
|
-
};
|
|
527
|
-
const checklistToList = (data) => {
|
|
528
|
-
const items = data && Array.isArray(data.items) ? data.items : [];
|
|
529
|
-
return {
|
|
530
|
-
style: "checklist",
|
|
531
|
-
meta: {},
|
|
532
|
-
items: items.map((item) => {
|
|
533
|
-
if (typeof item === "string") return { content: item, meta: { checked: false }, items: [] };
|
|
534
|
-
const value = item && typeof item === "object" ? item : {};
|
|
535
|
-
return {
|
|
536
|
-
content: str(value.text) || str(value.content),
|
|
537
|
-
meta: { checked: Boolean(value.checked ?? (value.meta && value.meta.checked)) },
|
|
538
|
-
items: []
|
|
539
|
-
};
|
|
540
|
-
})
|
|
541
|
-
};
|
|
542
|
-
};
|
|
543
|
-
const listToChecklist = (data) => {
|
|
544
|
-
const out = [];
|
|
545
|
-
const walk = (items, depth) => {
|
|
546
|
-
if (!Array.isArray(items) || depth > 12) return;
|
|
547
|
-
for (const item of items) {
|
|
548
|
-
if (!item || typeof item !== "object") continue;
|
|
549
|
-
out.push({ text: str(item.content), checked: Boolean(item.meta && item.meta.checked) });
|
|
550
|
-
walk(item.items, depth + 1);
|
|
551
|
-
}
|
|
552
|
-
};
|
|
553
|
-
walk(data && data.items, 0);
|
|
554
|
-
return { items: out };
|
|
555
|
-
};
|
|
556
|
-
const normalizeToggle = (data, fallbackKey) => {
|
|
557
|
-
const d = data && typeof data === "object" ? data : {};
|
|
558
|
-
const items = Number(d.items);
|
|
559
|
-
return {
|
|
560
|
-
text: str(d.text),
|
|
561
|
-
status: d.status === "closed" ? "closed" : "open",
|
|
562
|
-
fk: str(d.fk) || str(fallbackKey),
|
|
563
|
-
items: Number.isInteger(items) && items > 0 ? Math.min(items, 5e3) : 0
|
|
564
|
-
};
|
|
565
|
-
};
|
|
566
|
-
const toggleChildIndexes = (toggleIndex, items, total) => {
|
|
567
|
-
if (!Number.isInteger(toggleIndex) || toggleIndex < 0) return [];
|
|
568
|
-
const count = Math.max(0, Math.min(Number(items) || 0, total - toggleIndex - 1));
|
|
569
|
-
return Array.from({ length: count }, (_, i) => toggleIndex + 1 + i);
|
|
570
|
-
};
|
|
571
|
-
const nextToggleItems = (toggleIndex, items, total, action) => {
|
|
572
|
-
const current = toggleChildIndexes(toggleIndex, items, total).length;
|
|
573
|
-
if (action === "include") return Math.min(current + 1, Math.max(0, total - toggleIndex - 1));
|
|
574
|
-
return Math.max(0, current - 1);
|
|
575
|
-
};
|
|
576
|
-
const normalizeButton = (data) => {
|
|
577
|
-
const d = data && typeof data === "object" ? data : {};
|
|
578
|
-
return {
|
|
579
|
-
text: str(d.text),
|
|
580
|
-
link: str(d.link),
|
|
581
|
-
style: pick(d.style, BUTTON_STYLES, "primary"),
|
|
582
|
-
openInNewTab: d.openInNewTab === true
|
|
583
|
-
};
|
|
584
|
-
};
|
|
585
|
-
const normalizeSimpleImage = (data) => {
|
|
586
|
-
const d = data && typeof data === "object" ? data : {};
|
|
587
|
-
return {
|
|
588
|
-
url: str(d.url),
|
|
589
|
-
caption: str(d.caption),
|
|
590
|
-
withBorder: d.withBorder === true,
|
|
591
|
-
withBackground: d.withBackground === true,
|
|
592
|
-
stretched: d.stretched === true
|
|
593
|
-
};
|
|
594
|
-
};
|
|
595
|
-
const normalizePersonality = (data) => {
|
|
596
|
-
const d = data && typeof data === "object" ? data : {};
|
|
597
|
-
return { name: str(d.name), description: str(d.description), link: str(d.link), photo: str(d.photo) };
|
|
598
|
-
};
|
|
599
|
-
const normalizeLinkTool = (data) => {
|
|
600
|
-
const d = data && typeof data === "object" ? data : {};
|
|
601
|
-
const meta = d.meta && typeof d.meta === "object" ? d.meta : {};
|
|
602
|
-
const out = { title: str(meta.title), description: str(meta.description) };
|
|
603
|
-
if (str(meta.site_name)) out.site_name = str(meta.site_name);
|
|
604
|
-
if (meta.image && typeof meta.image === "object" && str(meta.image.url))
|
|
605
|
-
out.image = { url: str(meta.image.url) };
|
|
606
|
-
return { link: str(d.link), meta: out };
|
|
607
|
-
};
|
|
608
|
-
const normalizeEmbeddedEntry = (data, config = {}) => {
|
|
609
|
-
const d = data && typeof data === "object" ? data : {};
|
|
610
|
-
return {
|
|
611
|
-
entry: d.entry && typeof d.entry === "object" ? d.entry : null,
|
|
612
|
-
contentType: str(d.contentType) || config.contentType || null,
|
|
613
|
-
displayMode: pick(d.displayMode, ["card", "inline", "minimal"], "card")
|
|
614
|
-
};
|
|
615
|
-
};
|
|
616
|
-
const summarizeEntry = (entry, config = {}) => {
|
|
617
|
-
const titleField = config.titleField || "title";
|
|
618
|
-
const title = [entry[titleField], entry.title, entry.name, entry.label, entry.slug].find(
|
|
619
|
-
(v) => typeof v === "string" && v.trim()
|
|
620
|
-
);
|
|
621
|
-
const out = {
|
|
622
|
-
id: entry.id,
|
|
623
|
-
documentId: entry.documentId,
|
|
624
|
-
title: title || String(entry.documentId || entry.id || "")
|
|
625
|
-
};
|
|
626
|
-
for (const field2 of config.displayFields || []) {
|
|
627
|
-
const value = entry[field2];
|
|
628
|
-
if (["string", "number", "boolean"].includes(typeof value)) out[field2] = value;
|
|
629
|
-
}
|
|
630
|
-
return out;
|
|
631
|
-
};
|
|
632
|
-
const fillTemplate = (template, data) => String(template || "").replace(/\{\{\s*([A-Za-z_][A-Za-z0-9_]{0,39})\s*\}\}/g, (_match, name) => {
|
|
633
|
-
const value = data && Object.prototype.hasOwnProperty.call(data, name) ? data[name] : "";
|
|
634
|
-
let text = "";
|
|
635
|
-
if (value && typeof value === "object") text = typeof value.url === "string" ? value.url : "";
|
|
636
|
-
else if (value !== null && value !== void 0) text = String(value);
|
|
637
|
-
return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
638
|
-
});
|
|
639
|
-
const createHistoryStack = ({ maxSteps = 50 } = {}) => {
|
|
640
|
-
let past = [];
|
|
641
|
-
let present = null;
|
|
642
|
-
let future = [];
|
|
643
|
-
return {
|
|
644
|
-
/** Sets the starting state without an undo step. */
|
|
645
|
-
init(state) {
|
|
646
|
-
past = [];
|
|
647
|
-
future = [];
|
|
648
|
-
present = state;
|
|
649
|
-
},
|
|
650
|
-
/** Records a new state; identical consecutive states are ignored. @returns {boolean} Recorded. */
|
|
651
|
-
push(state) {
|
|
652
|
-
if (state === present) return false;
|
|
653
|
-
if (present !== null) past.push(present);
|
|
654
|
-
if (past.length > maxSteps) past = past.slice(past.length - maxSteps);
|
|
655
|
-
present = state;
|
|
656
|
-
future = [];
|
|
657
|
-
return true;
|
|
658
|
-
},
|
|
659
|
-
/** @returns {string|null} State to show after undo. */
|
|
660
|
-
undo() {
|
|
661
|
-
if (past.length === 0) return null;
|
|
662
|
-
future.push(present);
|
|
663
|
-
present = past.pop();
|
|
664
|
-
return present;
|
|
665
|
-
},
|
|
666
|
-
/** @returns {string|null} State to show after redo. */
|
|
667
|
-
redo() {
|
|
668
|
-
if (future.length === 0) return null;
|
|
669
|
-
past.push(present);
|
|
670
|
-
present = future.pop();
|
|
671
|
-
return present;
|
|
672
|
-
},
|
|
673
|
-
/** Replaces the current state without touching undo/redo (re-serialised after a render). */
|
|
674
|
-
replacePresent(state) {
|
|
675
|
-
present = state;
|
|
676
|
-
},
|
|
677
|
-
canUndo: () => past.length > 0,
|
|
678
|
-
canRedo: () => future.length > 0,
|
|
679
|
-
current: () => present,
|
|
680
|
-
clear() {
|
|
681
|
-
past = [];
|
|
682
|
-
future = [];
|
|
683
|
-
present = null;
|
|
882
|
+
label: "Link address"
|
|
883
|
+
};
|
|
884
|
+
}
|
|
885
|
+
renderActions() {
|
|
886
|
+
const actions = super.renderActions();
|
|
887
|
+
const newTabId = `mex-newtab-${Math.random().toString(36).slice(2, 8)}`;
|
|
888
|
+
this.newTab = el("input", { attrs: { type: "checkbox", id: newTabId } });
|
|
889
|
+
this.newTab.checked = this.config.target === "_blank";
|
|
890
|
+
this.newTab.addEventListener("change", () => this.commit());
|
|
891
|
+
actions.appendChild(
|
|
892
|
+
el("label", {
|
|
893
|
+
className: "mex-inline-check",
|
|
894
|
+
attrs: { for: newTabId },
|
|
895
|
+
children: [this.newTab, el("span", { text: this.t("tools.hyperlink.newTab", "Open in a new tab") })]
|
|
896
|
+
})
|
|
897
|
+
);
|
|
898
|
+
if (this.config.fetchClient && typeof this.config.fetchClient.get === "function")
|
|
899
|
+
this.renderPicker(actions);
|
|
900
|
+
return actions;
|
|
901
|
+
}
|
|
902
|
+
/**
|
|
903
|
+
* Adds the "Link to an entry" toggle and the picker to the actions panel.
|
|
904
|
+
* @param {HTMLElement} actions - Actions panel.
|
|
905
|
+
*/
|
|
906
|
+
renderPicker(actions) {
|
|
907
|
+
this.picker = createLinkPicker({
|
|
908
|
+
t: (id, fallback, values) => this.t(id, fallback, values),
|
|
909
|
+
fetchClient: this.config.fetchClient,
|
|
910
|
+
getLocale: this.config.getLocale,
|
|
911
|
+
onPick: (item) => this.applyInternal(item),
|
|
912
|
+
onClose: () => {
|
|
913
|
+
if (this.pickerToggle) this.pickerToggle.setAttribute("aria-expanded", "false");
|
|
914
|
+
if (this.input) this.input.focus();
|
|
915
|
+
}
|
|
916
|
+
});
|
|
917
|
+
this.pickerToggle = button(this.t("tools.hyperlink.internal.open", "Link to an entry"), {
|
|
918
|
+
icon: ICONS.entry
|
|
919
|
+
});
|
|
920
|
+
this.pickerToggle.classList.add("mex-link-picker__toggle");
|
|
921
|
+
this.pickerToggle.setAttribute("aria-expanded", "false");
|
|
922
|
+
this.pickerToggle.setAttribute("aria-controls", this.picker.element.id);
|
|
923
|
+
this.pickerToggle.addEventListener("click", () => {
|
|
924
|
+
if (this.picker.isOpen()) {
|
|
925
|
+
this.picker.close();
|
|
926
|
+
return;
|
|
927
|
+
}
|
|
928
|
+
this.pickerToggle.setAttribute("aria-expanded", "true");
|
|
929
|
+
this.picker.open();
|
|
930
|
+
});
|
|
931
|
+
actions.append(this.pickerToggle, this.picker.element);
|
|
932
|
+
}
|
|
933
|
+
/**
|
|
934
|
+
* Writes a picked entry into the current link and closes the toolbar.
|
|
935
|
+
* @param {{ href: string, uid: string, documentId: string, locale: string|null }} item - Search result.
|
|
936
|
+
*/
|
|
937
|
+
applyInternal(item) {
|
|
938
|
+
if (!this.input) return;
|
|
939
|
+
this.internal = { href: item.href, uid: item.uid, documentId: item.documentId, locale: item.locale };
|
|
940
|
+
this.input.value = item.href;
|
|
941
|
+
if (this.newTab) this.newTab.checked = false;
|
|
942
|
+
this.commit();
|
|
943
|
+
this.api.inlineToolbar.close();
|
|
944
|
+
}
|
|
945
|
+
readValue(node) {
|
|
946
|
+
if (this.newTab) this.newTab.checked = node.getAttribute("target") === "_blank";
|
|
947
|
+
this.internal = readInternalLink(node);
|
|
948
|
+
return node.getAttribute("href") || "";
|
|
949
|
+
}
|
|
950
|
+
writeValue(node, value) {
|
|
951
|
+
let url = value;
|
|
952
|
+
if (url && !/^[a-z][a-z0-9+.-]*:|^[/#?.]/i.test(url) && /^[^\s/]+\.[^\s]+/.test(url))
|
|
953
|
+
url = `https://${url}`;
|
|
954
|
+
const safe = sanitizeUrl(url);
|
|
955
|
+
if (!safe) return false;
|
|
956
|
+
node.setAttribute("href", safe);
|
|
957
|
+
for (const [name, attribute] of Object.entries(internalLinkAttributes(this.internal, safe))) {
|
|
958
|
+
if (attribute) node.setAttribute(name, attribute);
|
|
959
|
+
else node.removeAttribute(name);
|
|
684
960
|
}
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
for (let i = 0; i < rects.length; i += 1) {
|
|
692
|
-
const middle = (rects[i].top + rects[i].bottom) / 2;
|
|
693
|
-
if (y < middle) {
|
|
694
|
-
insertBefore = i;
|
|
695
|
-
break;
|
|
961
|
+
if (this.newTab && this.newTab.checked) {
|
|
962
|
+
node.setAttribute("target", "_blank");
|
|
963
|
+
node.setAttribute("rel", "noopener noreferrer");
|
|
964
|
+
} else {
|
|
965
|
+
node.removeAttribute("target");
|
|
966
|
+
node.removeAttribute("rel");
|
|
696
967
|
}
|
|
968
|
+
return true;
|
|
697
969
|
}
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
970
|
+
}
|
|
971
|
+
class AiInlineTool {
|
|
972
|
+
static get isInline() {
|
|
973
|
+
return true;
|
|
974
|
+
}
|
|
975
|
+
static get title() {
|
|
976
|
+
return "AI assistant";
|
|
977
|
+
}
|
|
978
|
+
constructor({ api, config }) {
|
|
979
|
+
this.api = api;
|
|
980
|
+
this.config = config || {};
|
|
981
|
+
this.button = null;
|
|
982
|
+
}
|
|
983
|
+
get shortcut() {
|
|
984
|
+
return "CMD+SHIFT+G";
|
|
985
|
+
}
|
|
986
|
+
render() {
|
|
987
|
+
this.button = el("button", { className: this.api.styles.inlineToolButton, attrs: { type: "button" } });
|
|
988
|
+
this.button.innerHTML = ICONS.sparkle;
|
|
989
|
+
return this.button;
|
|
990
|
+
}
|
|
991
|
+
surround(range) {
|
|
992
|
+
if (!range || typeof this.config.onAiRequest !== "function") return;
|
|
993
|
+
const holder = document.createElement("div");
|
|
994
|
+
holder.appendChild(range.cloneContents());
|
|
995
|
+
const text = range.toString();
|
|
996
|
+
if (!text.trim()) return;
|
|
997
|
+
this.config.onAiRequest({ text, html: holder.innerHTML, range: range.cloneRange() });
|
|
998
|
+
}
|
|
999
|
+
checkState() {
|
|
1000
|
+
return false;
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
701
1003
|
const ALIGN_ICONS = {
|
|
702
1004
|
left: ICONS.alignLeft,
|
|
703
1005
|
center: ICONS.alignCenter,
|
|
@@ -993,6 +1295,7 @@ class SimpleImageTool extends BaseTool {
|
|
|
993
1295
|
urlInput.addEventListener("keydown", (event) => {
|
|
994
1296
|
if (event.key === "Enter") {
|
|
995
1297
|
event.preventDefault();
|
|
1298
|
+
event.stopPropagation();
|
|
996
1299
|
apply();
|
|
997
1300
|
}
|
|
998
1301
|
});
|
|
@@ -1323,6 +1626,7 @@ class LinkPreviewTool extends BaseTool {
|
|
|
1323
1626
|
urlInput.addEventListener("keydown", (event) => {
|
|
1324
1627
|
if (event.key === "Enter") {
|
|
1325
1628
|
event.preventDefault();
|
|
1629
|
+
event.stopPropagation();
|
|
1326
1630
|
this.fetch(urlInput.value.trim(), status, urlInput);
|
|
1327
1631
|
}
|
|
1328
1632
|
});
|
|
@@ -2169,6 +2473,7 @@ const createUndoManager = (editor, options = {}) => {
|
|
|
2169
2473
|
let timer = null;
|
|
2170
2474
|
let applying = false;
|
|
2171
2475
|
let destroyed = false;
|
|
2476
|
+
let delegate = null;
|
|
2172
2477
|
const states = /* @__PURE__ */ new Map();
|
|
2173
2478
|
const notify = () => {
|
|
2174
2479
|
if (typeof options.onChange === "function")
|
|
@@ -2220,14 +2525,23 @@ const createUndoManager = (editor, options = {}) => {
|
|
|
2220
2525
|
};
|
|
2221
2526
|
if (holder) holder.addEventListener("keydown", onKeyDown, true);
|
|
2222
2527
|
const manager = {
|
|
2528
|
+
/**
|
|
2529
|
+
* Routes undo/redo to another history (live collaboration) or back (null).
|
|
2530
|
+
* @param {{ undo: () => boolean, redo: () => boolean, stopCapturing?: () => void }|null} next - Delegate.
|
|
2531
|
+
*/
|
|
2532
|
+
setDelegate(next) {
|
|
2533
|
+
delegate = next;
|
|
2534
|
+
notify();
|
|
2535
|
+
},
|
|
2223
2536
|
/** Records the current state after the debounce. */
|
|
2224
2537
|
record() {
|
|
2225
|
-
if (destroyed || paused > 0 || applying) return;
|
|
2538
|
+
if (destroyed || paused > 0 || applying || delegate) return;
|
|
2226
2539
|
window.clearTimeout(timer);
|
|
2227
2540
|
timer = window.setTimeout(snapshot, debounceMs);
|
|
2228
2541
|
},
|
|
2229
2542
|
/** Steps back. @returns {Promise<boolean>} True when something changed. */
|
|
2230
2543
|
async undo() {
|
|
2544
|
+
if (delegate) return delegate.undo();
|
|
2231
2545
|
window.clearTimeout(timer);
|
|
2232
2546
|
await snapshot();
|
|
2233
2547
|
const key = stack.undo();
|
|
@@ -2237,6 +2551,7 @@ const createUndoManager = (editor, options = {}) => {
|
|
|
2237
2551
|
},
|
|
2238
2552
|
/** Steps forward. @returns {Promise<boolean>} True when something changed. */
|
|
2239
2553
|
async redo() {
|
|
2554
|
+
if (delegate) return delegate.redo();
|
|
2240
2555
|
const key = stack.redo();
|
|
2241
2556
|
if (!key) return false;
|
|
2242
2557
|
await apply(key);
|
|
@@ -2507,7 +2822,11 @@ function buildTools(ctx) {
|
|
|
2507
2822
|
strikethrough: { class: StrikethroughTool, shortcut: "CMD+SHIFT+X" },
|
|
2508
2823
|
inlineCode: { class: InlineCode, shortcut: "CMD+SHIFT+I" },
|
|
2509
2824
|
tooltip: { class: TooltipTool, config: { t } },
|
|
2510
|
-
hyperlink: {
|
|
2825
|
+
hyperlink: {
|
|
2826
|
+
class: HyperlinkTool,
|
|
2827
|
+
shortcut: "CMD+K",
|
|
2828
|
+
config: { t, target: "_blank", fetchClient: ctx.fetchClient, getLocale: ctx.getContentLocale }
|
|
2829
|
+
},
|
|
2511
2830
|
alignmentTune: { class: AlignmentTune, config: { t, default: "left" } },
|
|
2512
2831
|
textVariant: { class: TextVariantTune, config: { t } },
|
|
2513
2832
|
indentTune: {
|
|
@@ -3027,6 +3346,78 @@ const editorStyles = css`
|
|
|
3027
3346
|
min-width: 24rem;
|
|
3028
3347
|
}
|
|
3029
3348
|
|
|
3349
|
+
.mex-link-picker__toggle {
|
|
3350
|
+
align-self: flex-start;
|
|
3351
|
+
}
|
|
3352
|
+
|
|
3353
|
+
.mex-link-picker {
|
|
3354
|
+
display: flex;
|
|
3355
|
+
flex-direction: column;
|
|
3356
|
+
gap: ${s(2)};
|
|
3357
|
+
width: 100%;
|
|
3358
|
+
min-width: 0;
|
|
3359
|
+
border-top: 1px solid ${c("neutral150")};
|
|
3360
|
+
padding-top: ${s(2)};
|
|
3361
|
+
|
|
3362
|
+
&[hidden] {
|
|
3363
|
+
display: none;
|
|
3364
|
+
}
|
|
3365
|
+
}
|
|
3366
|
+
|
|
3367
|
+
.mex-link-picker__controls {
|
|
3368
|
+
display: grid;
|
|
3369
|
+
grid-template-columns: minmax(0, 1fr);
|
|
3370
|
+
gap: ${s(2)};
|
|
3371
|
+
}
|
|
3372
|
+
|
|
3373
|
+
.mex-link-picker__results {
|
|
3374
|
+
list-style: none;
|
|
3375
|
+
margin: 0;
|
|
3376
|
+
padding: 0;
|
|
3377
|
+
display: flex;
|
|
3378
|
+
flex-direction: column;
|
|
3379
|
+
gap: ${s(1)};
|
|
3380
|
+
max-height: 24rem;
|
|
3381
|
+
overflow: auto;
|
|
3382
|
+
|
|
3383
|
+
&:empty {
|
|
3384
|
+
display: none;
|
|
3385
|
+
}
|
|
3386
|
+
}
|
|
3387
|
+
|
|
3388
|
+
.mex-link-picker__option {
|
|
3389
|
+
display: flex;
|
|
3390
|
+
flex-direction: column;
|
|
3391
|
+
gap: ${s(1)};
|
|
3392
|
+
border: 1px solid ${c("neutral150")};
|
|
3393
|
+
border-radius: ${radius};
|
|
3394
|
+
background: ${c("neutral0")};
|
|
3395
|
+
color: ${c("neutral800")};
|
|
3396
|
+
padding: ${s(2)} ${s(3)};
|
|
3397
|
+
cursor: pointer;
|
|
3398
|
+
font-size: ${f(2)};
|
|
3399
|
+
|
|
3400
|
+
&:hover,
|
|
3401
|
+
&[aria-selected='true'] {
|
|
3402
|
+
background: ${c("primary100")};
|
|
3403
|
+
border-color: ${c("primary600")};
|
|
3404
|
+
}
|
|
3405
|
+
|
|
3406
|
+
&[aria-disabled='true'] {
|
|
3407
|
+
cursor: not-allowed;
|
|
3408
|
+
color: ${c("neutral600")};
|
|
3409
|
+
}
|
|
3410
|
+
}
|
|
3411
|
+
|
|
3412
|
+
.mex-link-picker__title {
|
|
3413
|
+
overflow-wrap: anywhere;
|
|
3414
|
+
}
|
|
3415
|
+
|
|
3416
|
+
.mex-link-picker__meta {
|
|
3417
|
+
color: ${c("neutral600")};
|
|
3418
|
+
font-size: ${f(1)};
|
|
3419
|
+
}
|
|
3420
|
+
|
|
3030
3421
|
.ce-stub {
|
|
3031
3422
|
background: ${c("neutral100")};
|
|
3032
3423
|
color: ${c("neutral800")};
|
|
@@ -3763,6 +4154,63 @@ const editorStyles = css`
|
|
|
3763
4154
|
font-size: ${f(1)};
|
|
3764
4155
|
}
|
|
3765
4156
|
|
|
4157
|
+
/* Placeholder for embeds and images the admin CSP blocks (csp-guard.js). */
|
|
4158
|
+
.mex-csp-blocked {
|
|
4159
|
+
display: flex;
|
|
4160
|
+
align-items: flex-start;
|
|
4161
|
+
gap: ${s(3)};
|
|
4162
|
+
max-width: 100%;
|
|
4163
|
+
box-sizing: border-box;
|
|
4164
|
+
padding: ${s(4)};
|
|
4165
|
+
border: 1px solid ${c("warning200")};
|
|
4166
|
+
border-inline-start: 4px solid ${c("warning600")};
|
|
4167
|
+
border-radius: ${radius};
|
|
4168
|
+
background: ${c("warning100")};
|
|
4169
|
+
color: ${c("neutral800")};
|
|
4170
|
+
font-size: ${f(2)};
|
|
4171
|
+
line-height: 1.5;
|
|
4172
|
+
overflow-wrap: anywhere;
|
|
4173
|
+
}
|
|
4174
|
+
|
|
4175
|
+
.mex-csp-blocked + iframe,
|
|
4176
|
+
.mex-csp-blocked + img {
|
|
4177
|
+
display: none !important;
|
|
4178
|
+
}
|
|
4179
|
+
|
|
4180
|
+
.mex-csp-blocked__icon {
|
|
4181
|
+
flex: 0 0 auto;
|
|
4182
|
+
display: inline-flex;
|
|
4183
|
+
color: ${c("warning700")};
|
|
4184
|
+
}
|
|
4185
|
+
|
|
4186
|
+
.mex-csp-blocked__text {
|
|
4187
|
+
display: flex;
|
|
4188
|
+
flex-direction: column;
|
|
4189
|
+
gap: ${s(1)};
|
|
4190
|
+
min-width: 0;
|
|
4191
|
+
}
|
|
4192
|
+
|
|
4193
|
+
.mex-csp-blocked__text p {
|
|
4194
|
+
margin: 0;
|
|
4195
|
+
}
|
|
4196
|
+
|
|
4197
|
+
.mex-csp-blocked__title {
|
|
4198
|
+
font-weight: 600;
|
|
4199
|
+
}
|
|
4200
|
+
|
|
4201
|
+
.mex-csp-blocked__link {
|
|
4202
|
+
align-self: flex-start;
|
|
4203
|
+
color: ${c("primary700")};
|
|
4204
|
+
font-weight: 600;
|
|
4205
|
+
text-decoration: underline;
|
|
4206
|
+
}
|
|
4207
|
+
|
|
4208
|
+
.mex-csp-blocked__link:focus-visible {
|
|
4209
|
+
outline: 2px solid ${c("primary600")};
|
|
4210
|
+
outline-offset: 2px;
|
|
4211
|
+
border-radius: ${radius};
|
|
4212
|
+
}
|
|
4213
|
+
|
|
3766
4214
|
${({ theme }) => theme.breakpoints.medium} {
|
|
3767
4215
|
.ce-block__content {
|
|
3768
4216
|
padding-inline-start: ${s(10)};
|
|
@@ -3770,7 +4218,136 @@ const editorStyles = css`
|
|
|
3770
4218
|
}
|
|
3771
4219
|
}
|
|
3772
4220
|
`;
|
|
3773
|
-
const
|
|
4221
|
+
const matchesBlockedUri = (elementUrl, blockedUri) => {
|
|
4222
|
+
if (typeof elementUrl !== "string" || typeof blockedUri !== "string" || !elementUrl || !blockedUri) {
|
|
4223
|
+
return false;
|
|
4224
|
+
}
|
|
4225
|
+
if (elementUrl === blockedUri) return true;
|
|
4226
|
+
let element;
|
|
4227
|
+
let blocked;
|
|
4228
|
+
try {
|
|
4229
|
+
element = new URL(elementUrl);
|
|
4230
|
+
blocked = new URL(blockedUri);
|
|
4231
|
+
} catch {
|
|
4232
|
+
return false;
|
|
4233
|
+
}
|
|
4234
|
+
if (element.origin !== blocked.origin) return false;
|
|
4235
|
+
if (blocked.pathname === "/" && !blocked.search) return true;
|
|
4236
|
+
return element.href.split("#")[0] === blocked.href.split("#")[0];
|
|
4237
|
+
};
|
|
4238
|
+
const createCspGuard = (holder, options) => {
|
|
4239
|
+
const { t, settingsHref = null, onOpenSettings = null } = options;
|
|
4240
|
+
const violations = [];
|
|
4241
|
+
const timers = /* @__PURE__ */ new Set();
|
|
4242
|
+
let destroyed = false;
|
|
4243
|
+
const kindOf2 = (directive) => {
|
|
4244
|
+
if (directive === "frame-src" || directive === "child-src") return "frame";
|
|
4245
|
+
if (directive === "img-src") return "image";
|
|
4246
|
+
return null;
|
|
4247
|
+
};
|
|
4248
|
+
const placeholder = (kind, url) => {
|
|
4249
|
+
let host;
|
|
4250
|
+
try {
|
|
4251
|
+
host = new URL(url).host;
|
|
4252
|
+
} catch {
|
|
4253
|
+
host = "";
|
|
4254
|
+
}
|
|
4255
|
+
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.");
|
|
4256
|
+
const body = host ? t(
|
|
4257
|
+
"tools.csp.hostBlocked",
|
|
4258
|
+
"The admin does not allow content from {host}. The block is saved unchanged and still appears on your website.",
|
|
4259
|
+
{ host }
|
|
4260
|
+
) : t(
|
|
4261
|
+
"tools.csp.blockedGeneric",
|
|
4262
|
+
"The admin does not allow this content. The block is saved unchanged and still appears on your website."
|
|
4263
|
+
);
|
|
4264
|
+
const icon = el("span", { className: "mex-csp-blocked__icon", attrs: { "aria-hidden": "true" } });
|
|
4265
|
+
icon.innerHTML = ICONS.alert;
|
|
4266
|
+
const text = el("div", {
|
|
4267
|
+
className: "mex-csp-blocked__text",
|
|
4268
|
+
children: [
|
|
4269
|
+
el("p", { className: "mex-csp-blocked__title", text: title }),
|
|
4270
|
+
el("p", { className: "mex-csp-blocked__body", text: body })
|
|
4271
|
+
]
|
|
4272
|
+
});
|
|
4273
|
+
if (settingsHref) {
|
|
4274
|
+
const link = el("a", {
|
|
4275
|
+
className: "mex-csp-blocked__link",
|
|
4276
|
+
text: t("tools.csp.howTo", "How to allow it"),
|
|
4277
|
+
attrs: { href: settingsHref }
|
|
4278
|
+
});
|
|
4279
|
+
link.addEventListener("click", (event) => {
|
|
4280
|
+
if (!onOpenSettings || event.button !== 0) return;
|
|
4281
|
+
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
|
|
4282
|
+
event.preventDefault();
|
|
4283
|
+
onOpenSettings();
|
|
4284
|
+
});
|
|
4285
|
+
text.appendChild(link);
|
|
4286
|
+
} else {
|
|
4287
|
+
text.appendChild(
|
|
4288
|
+
el("p", {
|
|
4289
|
+
className: "mex-csp-blocked__body",
|
|
4290
|
+
text: t("tools.csp.askAdmin", "Ask an administrator to allow it in the Content Security Policy.")
|
|
4291
|
+
})
|
|
4292
|
+
);
|
|
4293
|
+
}
|
|
4294
|
+
return el("div", {
|
|
4295
|
+
className: "mex-csp-blocked",
|
|
4296
|
+
attrs: { role: "note", contenteditable: "false", "data-mutation-free": "true" },
|
|
4297
|
+
children: [icon, text]
|
|
4298
|
+
});
|
|
4299
|
+
};
|
|
4300
|
+
const mark = (element, kind) => {
|
|
4301
|
+
const previous = element.previousElementSibling;
|
|
4302
|
+
if (previous && previous.classList.contains("mex-csp-blocked")) return;
|
|
4303
|
+
if (!element.parentNode) return;
|
|
4304
|
+
element.parentNode.insertBefore(placeholder(kind, element.getAttribute("src") || ""), element);
|
|
4305
|
+
};
|
|
4306
|
+
const scan = (kind, blockedUri) => {
|
|
4307
|
+
const selector = kind === "frame" ? "iframe" : "img";
|
|
4308
|
+
holder.querySelectorAll(selector).forEach((element) => {
|
|
4309
|
+
if (matchesBlockedUri(element.src, blockedUri)) mark(element, kind);
|
|
4310
|
+
});
|
|
4311
|
+
};
|
|
4312
|
+
const onViolation = (event) => {
|
|
4313
|
+
if (destroyed || event.disposition === "report") return;
|
|
4314
|
+
const kind = kindOf2(event.effectiveDirective || event.violatedDirective);
|
|
4315
|
+
if (!kind || !event.blockedURI) return;
|
|
4316
|
+
violations.push({ kind, uri: event.blockedURI });
|
|
4317
|
+
if (violations.length > 100) violations.shift();
|
|
4318
|
+
scan(kind, event.blockedURI);
|
|
4319
|
+
};
|
|
4320
|
+
const checkImage = (image) => {
|
|
4321
|
+
if (destroyed || !holder.contains(image)) return false;
|
|
4322
|
+
const hit = violations.find((entry) => entry.kind === "image" && matchesBlockedUri(image.src, entry.uri));
|
|
4323
|
+
if (hit) mark(image, "image");
|
|
4324
|
+
return Boolean(hit);
|
|
4325
|
+
};
|
|
4326
|
+
const onError = (event) => {
|
|
4327
|
+
const image = event.target;
|
|
4328
|
+
if (!image || image.tagName !== "IMG" || checkImage(image)) return;
|
|
4329
|
+
const timer = setTimeout(() => {
|
|
4330
|
+
timers.delete(timer);
|
|
4331
|
+
checkImage(image);
|
|
4332
|
+
}, 150);
|
|
4333
|
+
timers.add(timer);
|
|
4334
|
+
};
|
|
4335
|
+
document.addEventListener("securitypolicyviolation", onViolation);
|
|
4336
|
+
holder.addEventListener("error", onError, true);
|
|
4337
|
+
return {
|
|
4338
|
+
destroy() {
|
|
4339
|
+
destroyed = true;
|
|
4340
|
+
document.removeEventListener("securitypolicyviolation", onViolation);
|
|
4341
|
+
holder.removeEventListener("error", onError, true);
|
|
4342
|
+
timers.forEach((timer) => clearTimeout(timer));
|
|
4343
|
+
timers.clear();
|
|
4344
|
+
}
|
|
4345
|
+
};
|
|
4346
|
+
};
|
|
4347
|
+
const YDOC_SCHEMA = 3;
|
|
4348
|
+
const MAX_DEPTH = EDITOR_DATA_LIMITS.maxDepth;
|
|
4349
|
+
const FORBIDDEN_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
|
|
4350
|
+
const hasOwn = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
|
|
3774
4351
|
const getTypes = (doc) => ({
|
|
3775
4352
|
meta: doc.getMap("meta"),
|
|
3776
4353
|
order: doc.getArray("order"),
|
|
@@ -3779,9 +4356,10 @@ const getTypes = (doc) => ({
|
|
|
3779
4356
|
const stableStringify = (value) => {
|
|
3780
4357
|
if (value === null || typeof value !== "object") return JSON.stringify(value === void 0 ? null : value);
|
|
3781
4358
|
if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
|
|
3782
|
-
const
|
|
3783
|
-
return `{${
|
|
4359
|
+
const keys2 = Object.keys(value).sort();
|
|
4360
|
+
return `{${keys2.map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(",")}}`;
|
|
3784
4361
|
};
|
|
4362
|
+
const equal = (a, b) => a === b || stableStringify(a) === stableStringify(b);
|
|
3785
4363
|
const applyTextDiff = (ytext, next) => {
|
|
3786
4364
|
const current = ytext.toString();
|
|
3787
4365
|
if (current === next) return false;
|
|
@@ -3798,31 +4376,95 @@ const applyTextDiff = (ytext, next) => {
|
|
|
3798
4376
|
if (endNext > start) ytext.insert(start, next.slice(start, endNext));
|
|
3799
4377
|
return true;
|
|
3800
4378
|
};
|
|
4379
|
+
const applyTextEdit = (ytext, base, local) => {
|
|
4380
|
+
if (base === local) return false;
|
|
4381
|
+
const shared = ytext.toString();
|
|
4382
|
+
if (shared === base) return applyTextDiff(ytext, local);
|
|
4383
|
+
let start = 0;
|
|
4384
|
+
while (start < base.length && start < local.length && base.charCodeAt(start) === local.charCodeAt(start))
|
|
4385
|
+
start += 1;
|
|
4386
|
+
let endBase = base.length;
|
|
4387
|
+
let endLocal = local.length;
|
|
4388
|
+
while (endBase > start && endLocal > start && base.charCodeAt(endBase - 1) === local.charCodeAt(endLocal - 1)) {
|
|
4389
|
+
endBase -= 1;
|
|
4390
|
+
endLocal -= 1;
|
|
4391
|
+
}
|
|
4392
|
+
let rp = 0;
|
|
4393
|
+
while (rp < base.length && rp < shared.length && base.charCodeAt(rp) === shared.charCodeAt(rp)) rp += 1;
|
|
4394
|
+
let rsBase = base.length;
|
|
4395
|
+
let rsShared = shared.length;
|
|
4396
|
+
while (rsBase > rp && rsShared > rp && base.charCodeAt(rsBase - 1) === shared.charCodeAt(rsShared - 1)) {
|
|
4397
|
+
rsBase -= 1;
|
|
4398
|
+
rsShared -= 1;
|
|
4399
|
+
}
|
|
4400
|
+
const shift = shared.length - base.length;
|
|
4401
|
+
const map = (index) => index <= rp ? index : index >= rsBase ? index + shift : Math.min(index + shift, shared.length);
|
|
4402
|
+
const from = map(start);
|
|
4403
|
+
const to = Math.max(from, map(endBase));
|
|
4404
|
+
if (to > from) ytext.delete(from, Math.min(to, shared.length) - from);
|
|
4405
|
+
const inserted = local.slice(start, endLocal);
|
|
4406
|
+
if (inserted) ytext.insert(Math.min(from, ytext.length), inserted);
|
|
4407
|
+
return true;
|
|
4408
|
+
};
|
|
4409
|
+
const toShared = (value, depth = 0) => {
|
|
4410
|
+
if (depth > MAX_DEPTH) return null;
|
|
4411
|
+
if (typeof value === "string") return value ? new Y.Text(value) : new Y.Text();
|
|
4412
|
+
if (Array.isArray(value)) return Y.Array.from(value.map((item) => toShared(item, depth + 1)));
|
|
4413
|
+
if (isPlainObject(value)) {
|
|
4414
|
+
const entries = [];
|
|
4415
|
+
for (const key of Object.keys(value)) {
|
|
4416
|
+
if (FORBIDDEN_KEYS.has(key) || value[key] === void 0) continue;
|
|
4417
|
+
entries.push([key, toShared(value[key], depth + 1)]);
|
|
4418
|
+
}
|
|
4419
|
+
return new Y.Map(entries);
|
|
4420
|
+
}
|
|
4421
|
+
if (typeof value === "number") return Number.isFinite(value) ? value : null;
|
|
4422
|
+
if (typeof value === "boolean" || value === null) return value;
|
|
4423
|
+
return null;
|
|
4424
|
+
};
|
|
4425
|
+
const readShared = (value, depth = 0) => {
|
|
4426
|
+
if (value instanceof Y.Text) return value.toString();
|
|
4427
|
+
if (depth > MAX_DEPTH) return null;
|
|
4428
|
+
if (value instanceof Y.Array) return value.toArray().map((item) => readShared(item, depth + 1));
|
|
4429
|
+
if (value instanceof Y.Map) {
|
|
4430
|
+
const out = {};
|
|
4431
|
+
value.forEach((item, key) => {
|
|
4432
|
+
if (!FORBIDDEN_KEYS.has(key)) out[key] = readShared(item, depth + 1);
|
|
4433
|
+
});
|
|
4434
|
+
return out;
|
|
4435
|
+
}
|
|
4436
|
+
if (value instanceof Y.AbstractType) return null;
|
|
4437
|
+
if (value === void 0) return null;
|
|
4438
|
+
if (value !== null && typeof value === "object") {
|
|
4439
|
+
try {
|
|
4440
|
+
return cloneJsonSafe(value, depth) ?? null;
|
|
4441
|
+
} catch {
|
|
4442
|
+
return null;
|
|
4443
|
+
}
|
|
4444
|
+
}
|
|
4445
|
+
if (typeof value === "number" && !Number.isFinite(value)) return null;
|
|
4446
|
+
return value;
|
|
4447
|
+
};
|
|
3801
4448
|
const readBlock = (id, entry) => {
|
|
3802
4449
|
if (!(entry instanceof Y.Map)) return null;
|
|
3803
4450
|
const type = entry.get("type");
|
|
3804
4451
|
if (typeof type !== "string" || !type) return null;
|
|
3805
|
-
const
|
|
3806
|
-
const
|
|
3807
|
-
|
|
3808
|
-
dataMap.forEach((value, key) => {
|
|
3809
|
-
data[key] = value instanceof Y.Text ? value.toString() : value;
|
|
3810
|
-
});
|
|
3811
|
-
}
|
|
3812
|
-
const block = { id, type, data };
|
|
3813
|
-
const tunes = entry.get("tunes");
|
|
4452
|
+
const rawData = readShared(entry.get("data"), 2);
|
|
4453
|
+
const block = { id, type, data: isPlainObject(rawData) ? rawData : {} };
|
|
4454
|
+
const tunes = readShared(entry.get("tunes"), 2);
|
|
3814
4455
|
if (isPlainObject(tunes) && Object.keys(tunes).length > 0) block.tunes = tunes;
|
|
3815
4456
|
return block;
|
|
3816
4457
|
};
|
|
3817
|
-
const docToEditorData = (doc) => {
|
|
4458
|
+
const docToEditorData = (doc, read = readBlock) => {
|
|
3818
4459
|
const { meta, order, blocks } = getTypes(doc);
|
|
3819
4460
|
const seen = /* @__PURE__ */ new Set();
|
|
3820
4461
|
const out = [];
|
|
3821
4462
|
for (const id of order.toArray()) {
|
|
3822
4463
|
if (typeof id !== "string" || seen.has(id)) continue;
|
|
3823
4464
|
seen.add(id);
|
|
3824
|
-
const block =
|
|
4465
|
+
const block = read(id, blocks.get(id));
|
|
3825
4466
|
if (block) out.push(block);
|
|
4467
|
+
if (out.length >= EDITOR_DATA_LIMITS.maxBlocks) break;
|
|
3826
4468
|
}
|
|
3827
4469
|
return {
|
|
3828
4470
|
time: Number(meta.get("time")) || 0,
|
|
@@ -3830,38 +4472,34 @@ const docToEditorData = (doc) => {
|
|
|
3830
4472
|
version: typeof meta.get("version") === "string" ? meta.get("version") : "2.31.7"
|
|
3831
4473
|
};
|
|
3832
4474
|
};
|
|
3833
|
-
const
|
|
3834
|
-
|
|
3835
|
-
|
|
3836
|
-
|
|
3837
|
-
|
|
3838
|
-
|
|
3839
|
-
|
|
3840
|
-
|
|
3841
|
-
|
|
3842
|
-
dataMap.delete(key);
|
|
3843
|
-
changed = true;
|
|
3844
|
-
}
|
|
3845
|
-
}
|
|
3846
|
-
for (const [key, value] of Object.entries(data)) {
|
|
3847
|
-
const current = dataMap.get(key);
|
|
3848
|
-
if (typeof value === "string") {
|
|
3849
|
-
if (current instanceof Y.Text) {
|
|
3850
|
-
changed = applyTextDiff(current, value) || changed;
|
|
3851
|
-
} else {
|
|
3852
|
-
const text = new Y.Text();
|
|
3853
|
-
dataMap.set(key, text);
|
|
3854
|
-
text.insert(0, value);
|
|
3855
|
-
changed = true;
|
|
4475
|
+
const createDocReader = (doc) => {
|
|
4476
|
+
const { blocks } = getTypes(doc);
|
|
4477
|
+
const cache = /* @__PURE__ */ new Map();
|
|
4478
|
+
const observer = (events) => {
|
|
4479
|
+
for (const event of events) {
|
|
4480
|
+
if (event.target === blocks) {
|
|
4481
|
+
event.keysChanged.forEach((key) => cache.delete(key));
|
|
4482
|
+
} else if (event.path.length > 0) {
|
|
4483
|
+
cache.delete(event.path[0]);
|
|
3856
4484
|
}
|
|
3857
|
-
} else if (current instanceof Y.Text || stableStringify(current) !== stableStringify(value)) {
|
|
3858
|
-
dataMap.set(key, value === void 0 ? null : value);
|
|
3859
|
-
changed = true;
|
|
3860
4485
|
}
|
|
3861
|
-
}
|
|
3862
|
-
|
|
4486
|
+
};
|
|
4487
|
+
blocks.observeDeep(observer);
|
|
4488
|
+
const read = (id, entry) => {
|
|
4489
|
+
if (cache.has(id)) return cache.get(id);
|
|
4490
|
+
const block = readBlock(id, entry);
|
|
4491
|
+
cache.set(id, block);
|
|
4492
|
+
return block;
|
|
4493
|
+
};
|
|
4494
|
+
return {
|
|
4495
|
+
read: () => docToEditorData(doc, read),
|
|
4496
|
+
destroy: () => {
|
|
4497
|
+
blocks.unobserveDeep(observer);
|
|
4498
|
+
cache.clear();
|
|
4499
|
+
}
|
|
4500
|
+
};
|
|
3863
4501
|
};
|
|
3864
|
-
const
|
|
4502
|
+
const lcsPairs = (a, b) => {
|
|
3865
4503
|
let start = 0;
|
|
3866
4504
|
while (start < a.length && start < b.length && a[start] === b[start]) start += 1;
|
|
3867
4505
|
let endA = a.length;
|
|
@@ -3870,68 +4508,161 @@ const lcsKeep = (a, b) => {
|
|
|
3870
4508
|
endA -= 1;
|
|
3871
4509
|
endB -= 1;
|
|
3872
4510
|
}
|
|
3873
|
-
const
|
|
3874
|
-
for (let
|
|
3875
|
-
|
|
3876
|
-
const
|
|
3877
|
-
|
|
3878
|
-
|
|
3879
|
-
|
|
3880
|
-
|
|
3881
|
-
|
|
3882
|
-
|
|
3883
|
-
|
|
3884
|
-
|
|
3885
|
-
|
|
3886
|
-
|
|
3887
|
-
|
|
3888
|
-
|
|
3889
|
-
|
|
3890
|
-
|
|
3891
|
-
|
|
3892
|
-
|
|
3893
|
-
|
|
3894
|
-
|
|
3895
|
-
|
|
3896
|
-
|
|
3897
|
-
|
|
3898
|
-
return keep;
|
|
4511
|
+
const pairs = [];
|
|
4512
|
+
for (let i = 0; i < start; i += 1) pairs.push([i, i]);
|
|
4513
|
+
const midA = endA - start;
|
|
4514
|
+
const midB = endB - start;
|
|
4515
|
+
if (midA > 0 && midB > 0 && midA * midB <= 4e6) {
|
|
4516
|
+
const cols = midB + 1;
|
|
4517
|
+
const table = new Uint16Array((midA + 1) * cols);
|
|
4518
|
+
for (let i2 = midA - 1; i2 >= 0; i2 -= 1) {
|
|
4519
|
+
for (let j2 = midB - 1; j2 >= 0; j2 -= 1) {
|
|
4520
|
+
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]);
|
|
4521
|
+
}
|
|
4522
|
+
}
|
|
4523
|
+
let i = 0;
|
|
4524
|
+
let j = 0;
|
|
4525
|
+
while (i < midA && j < midB) {
|
|
4526
|
+
if (a[start + i] === b[start + j]) {
|
|
4527
|
+
pairs.push([start + i, start + j]);
|
|
4528
|
+
i += 1;
|
|
4529
|
+
j += 1;
|
|
4530
|
+
} else if (table[(i + 1) * cols + j] >= table[i * cols + j + 1]) i += 1;
|
|
4531
|
+
else j += 1;
|
|
4532
|
+
}
|
|
4533
|
+
}
|
|
4534
|
+
for (let k = 0; k < a.length - endA; k += 1) pairs.push([endA + k, endB + k]);
|
|
4535
|
+
return pairs;
|
|
3899
4536
|
};
|
|
3900
|
-
const
|
|
3901
|
-
if (
|
|
3902
|
-
|
|
3903
|
-
if (
|
|
3904
|
-
|
|
3905
|
-
|
|
3906
|
-
|
|
3907
|
-
|
|
3908
|
-
|
|
3909
|
-
|
|
3910
|
-
|
|
3911
|
-
|
|
4537
|
+
const kindOf = (value) => {
|
|
4538
|
+
if (typeof value === "string" || value instanceof Y.Text) return "text";
|
|
4539
|
+
if (Array.isArray(value) || value instanceof Y.Array) return "array";
|
|
4540
|
+
if (isPlainObject(value) || value instanceof Y.Map) return "map";
|
|
4541
|
+
return "scalar";
|
|
4542
|
+
};
|
|
4543
|
+
const diffHunks = (a, b) => {
|
|
4544
|
+
const pairs = lcsPairs(a.map(stableStringify), b.map(stableStringify));
|
|
4545
|
+
const hunks = [];
|
|
4546
|
+
let pa = 0;
|
|
4547
|
+
let pb = 0;
|
|
4548
|
+
for (const [i, j] of [...pairs, [a.length, b.length]]) {
|
|
4549
|
+
if (i > pa || j > pb) hunks.push({ a0: pa, a1: i, b0: pb, b1: j });
|
|
4550
|
+
pa = i + 1;
|
|
4551
|
+
pb = j + 1;
|
|
4552
|
+
}
|
|
4553
|
+
return hunks;
|
|
4554
|
+
};
|
|
4555
|
+
const alignIndexes = (base, current) => {
|
|
4556
|
+
const map = new Array(base.length).fill(-1);
|
|
4557
|
+
if (base.length === current.length && equal(base, current)) return base.map((_, i) => i);
|
|
4558
|
+
for (const [i, j] of lcsPairs(base.map(stableStringify), current.map(stableStringify))) map[i] = j;
|
|
4559
|
+
for (const hunk of diffHunks(base, current)) {
|
|
4560
|
+
const n = Math.min(hunk.a1 - hunk.a0, hunk.b1 - hunk.b0);
|
|
4561
|
+
for (let k = 0; k < n; k += 1) {
|
|
4562
|
+
if (kindOf(base[hunk.a0 + k]) === kindOf(current[hunk.b0 + k])) map[hunk.a0 + k] = hunk.b0 + k;
|
|
4563
|
+
}
|
|
3912
4564
|
}
|
|
3913
|
-
|
|
3914
|
-
|
|
3915
|
-
|
|
3916
|
-
|
|
3917
|
-
|
|
3918
|
-
|
|
3919
|
-
|
|
4565
|
+
return map;
|
|
4566
|
+
};
|
|
4567
|
+
const mergeValue = (current, base, local, depth) => {
|
|
4568
|
+
if (base !== void 0 && equal(base, local)) return "same";
|
|
4569
|
+
if (depth > MAX_DEPTH) return "replace";
|
|
4570
|
+
if (typeof local === "string" && current instanceof Y.Text) {
|
|
4571
|
+
applyTextEdit(current, typeof base === "string" ? base : current.toString(), local);
|
|
4572
|
+
return "merged";
|
|
4573
|
+
}
|
|
4574
|
+
if (Array.isArray(local) && current instanceof Y.Array) {
|
|
4575
|
+
mergeArray(current, Array.isArray(base) ? base : readShared(current, depth), local, depth);
|
|
4576
|
+
return "merged";
|
|
4577
|
+
}
|
|
4578
|
+
if (isPlainObject(local) && current instanceof Y.Map) {
|
|
4579
|
+
mergeMap(current, isPlainObject(base) ? base : readShared(current, depth), local, depth);
|
|
4580
|
+
return "merged";
|
|
4581
|
+
}
|
|
4582
|
+
if (!(current instanceof Y.AbstractType) && equal(readShared(current, depth), local)) return "same";
|
|
4583
|
+
return "replace";
|
|
4584
|
+
};
|
|
4585
|
+
const mergeMap = (ymap, base, local, depth) => {
|
|
4586
|
+
const keys2 = /* @__PURE__ */ new Set([...Object.keys(base), ...Object.keys(local)]);
|
|
4587
|
+
for (const key of keys2) {
|
|
4588
|
+
if (FORBIDDEN_KEYS.has(key)) continue;
|
|
4589
|
+
const inLocal = hasOwn(local, key) && local[key] !== void 0;
|
|
4590
|
+
const inBase = hasOwn(base, key) && base[key] !== void 0;
|
|
4591
|
+
if (!inLocal) {
|
|
4592
|
+
if (inBase && ymap.has(key)) ymap.delete(key);
|
|
4593
|
+
continue;
|
|
4594
|
+
}
|
|
4595
|
+
const result = mergeValue(ymap.get(key), inBase ? base[key] : void 0, local[key], depth + 1);
|
|
4596
|
+
if (result === "replace") ymap.set(key, toShared(local[key], depth + 1));
|
|
4597
|
+
}
|
|
4598
|
+
};
|
|
4599
|
+
const mergeArray = (yarray, base, local, depth) => {
|
|
4600
|
+
if (equal(base, local)) return;
|
|
4601
|
+
const raw = yarray.toArray();
|
|
4602
|
+
const current = raw.map((item) => readShared(item, depth + 1));
|
|
4603
|
+
const target = alignIndexes(base, current);
|
|
4604
|
+
const ops = [];
|
|
4605
|
+
for (const hunk of diffHunks(base, local)) {
|
|
4606
|
+
const n = Math.min(hunk.a1 - hunk.a0, hunk.b1 - hunk.b0);
|
|
4607
|
+
for (let k = 0; k < n; k += 1) {
|
|
4608
|
+
const bi = hunk.a0 + k;
|
|
4609
|
+
if (target[bi] >= 0)
|
|
4610
|
+
ops.push({ at: target[bi], rank: 0, kind: "modify", bi, value: local[hunk.b0 + k] });
|
|
4611
|
+
}
|
|
4612
|
+
for (let bi = hunk.a0 + n; bi < hunk.a1; bi += 1) {
|
|
4613
|
+
if (target[bi] >= 0) ops.push({ at: target[bi], rank: 0, kind: "delete" });
|
|
4614
|
+
}
|
|
4615
|
+
if (hunk.b1 - hunk.b0 > n) {
|
|
4616
|
+
let at = 0;
|
|
4617
|
+
for (let bi = hunk.a0 + n - 1; bi >= 0; bi -= 1) {
|
|
4618
|
+
if (target[bi] >= 0) {
|
|
4619
|
+
at = target[bi] + 1;
|
|
4620
|
+
break;
|
|
4621
|
+
}
|
|
4622
|
+
}
|
|
4623
|
+
ops.push({ at, rank: 1, order: hunk.b0, kind: "insert", values: local.slice(hunk.b0 + n, hunk.b1) });
|
|
4624
|
+
}
|
|
4625
|
+
}
|
|
4626
|
+
ops.sort((x, y) => y.at - x.at || x.rank - y.rank || (y.order || 0) - (x.order || 0));
|
|
4627
|
+
for (const op of ops) {
|
|
4628
|
+
if (op.kind === "insert") {
|
|
4629
|
+
yarray.insert(
|
|
4630
|
+
Math.min(op.at, yarray.length),
|
|
4631
|
+
op.values.map((value) => toShared(value, depth + 1))
|
|
4632
|
+
);
|
|
4633
|
+
} else if (op.kind === "delete") {
|
|
4634
|
+
yarray.delete(op.at, 1);
|
|
4635
|
+
} else {
|
|
4636
|
+
const result = mergeValue(raw[op.at], base[op.bi], op.value, depth + 1);
|
|
4637
|
+
if (result === "replace") {
|
|
4638
|
+
yarray.delete(op.at, 1);
|
|
4639
|
+
yarray.insert(op.at, [toShared(op.value, depth + 1)]);
|
|
4640
|
+
}
|
|
4641
|
+
}
|
|
3920
4642
|
}
|
|
3921
|
-
const shift = shared.length - base.length;
|
|
3922
|
-
const map = (index) => index <= rp ? index : index >= rsBase ? index + shift : Math.min(index + shift, shared.length);
|
|
3923
|
-
const from = map(start);
|
|
3924
|
-
const to = Math.max(from, map(endBase));
|
|
3925
|
-
if (to > from) ytext.delete(from, Math.min(to, shared.length) - from);
|
|
3926
|
-
const inserted = local.slice(start, endLocal);
|
|
3927
|
-
if (inserted) ytext.insert(Math.min(from, ytext.length), inserted);
|
|
3928
|
-
return true;
|
|
3929
4643
|
};
|
|
4644
|
+
const mergeSlot = (ymap, key, base, local, depth) => {
|
|
4645
|
+
const result = mergeValue(ymap.get(key), base, local, depth);
|
|
4646
|
+
if (result === "replace") ymap.set(key, toShared(local, depth));
|
|
4647
|
+
return result !== "same";
|
|
4648
|
+
};
|
|
4649
|
+
const createEntry = (block) => new Y.Map([
|
|
4650
|
+
["type", block.type],
|
|
4651
|
+
["tunes", toShared(isPlainObject(block.tunes) ? block.tunes : {}, 2)],
|
|
4652
|
+
["data", toShared(isPlainObject(block.data) ? block.data : {}, 2)]
|
|
4653
|
+
]);
|
|
3930
4654
|
const applyLocalChanges = (doc, base, local, origin = "local") => {
|
|
3931
4655
|
const { meta, order, blocks } = getTypes(doc);
|
|
3932
4656
|
const baseById = new Map((base.blocks || []).map((block) => [block.id, block]));
|
|
3933
|
-
const
|
|
3934
|
-
const localSet = new Set(
|
|
4657
|
+
const localBlocks = [];
|
|
4658
|
+
const localSet = /* @__PURE__ */ new Set();
|
|
4659
|
+
for (const block of local.blocks || []) {
|
|
4660
|
+
if (!block || typeof block.id !== "string" || typeof block.type !== "string" || localSet.has(block.id))
|
|
4661
|
+
continue;
|
|
4662
|
+
localSet.add(block.id);
|
|
4663
|
+
localBlocks.push(block);
|
|
4664
|
+
}
|
|
4665
|
+
const localIds = localBlocks.map((block) => block.id);
|
|
3935
4666
|
let changed = false;
|
|
3936
4667
|
doc.transact(() => {
|
|
3937
4668
|
if (meta.get("schema") !== YDOC_SCHEMA) meta.set("schema", YDOC_SCHEMA);
|
|
@@ -3946,7 +4677,7 @@ const applyLocalChanges = (doc, base, local, origin = "local") => {
|
|
|
3946
4677
|
}
|
|
3947
4678
|
}
|
|
3948
4679
|
const baseIds = (base.blocks || []).map((block) => block.id).filter((id) => localSet.has(id));
|
|
3949
|
-
const keep =
|
|
4680
|
+
const keep = new Set(lcsPairs(baseIds, localIds).map(([i]) => baseIds[i]));
|
|
3950
4681
|
localIds.forEach((id, index) => {
|
|
3951
4682
|
if (baseById.has(id) && keep.has(id)) return;
|
|
3952
4683
|
const current = order.toArray();
|
|
@@ -3965,67 +4696,48 @@ const applyLocalChanges = (doc, base, local, origin = "local") => {
|
|
|
3965
4696
|
order.insert(position, [id]);
|
|
3966
4697
|
changed = true;
|
|
3967
4698
|
});
|
|
3968
|
-
for (const block of
|
|
4699
|
+
for (const block of localBlocks) {
|
|
3969
4700
|
const before = baseById.get(block.id);
|
|
3970
|
-
|
|
4701
|
+
const entry = blocks.get(block.id);
|
|
3971
4702
|
if (!(entry instanceof Y.Map)) {
|
|
3972
|
-
|
|
3973
|
-
blocks.set(block.id, entry);
|
|
3974
|
-
entry.set("type", block.type);
|
|
3975
|
-
entry.set("tunes", isPlainObject(block.tunes) ? block.tunes : {});
|
|
3976
|
-
writeData(entry, isPlainObject(block.data) ? block.data : {});
|
|
4703
|
+
blocks.set(block.id, createEntry(block));
|
|
3977
4704
|
changed = true;
|
|
3978
4705
|
continue;
|
|
3979
4706
|
}
|
|
3980
|
-
|
|
3981
|
-
|
|
3982
|
-
continue;
|
|
3983
|
-
}
|
|
3984
|
-
if (before.type !== block.type) {
|
|
4707
|
+
const reference = before || readBlock(block.id, entry) || { type: block.type, data: {}, tunes: {} };
|
|
4708
|
+
if (entry.get("type") !== block.type && reference.type !== block.type) {
|
|
3985
4709
|
entry.set("type", block.type);
|
|
4710
|
+
entry.set("data", toShared(isPlainObject(block.data) ? block.data : {}, 2));
|
|
3986
4711
|
changed = true;
|
|
3987
|
-
}
|
|
3988
|
-
|
|
3989
|
-
|
|
3990
|
-
|
|
3991
|
-
}
|
|
3992
|
-
let dataMap = entry.get("data");
|
|
3993
|
-
if (!(dataMap instanceof Y.Map)) {
|
|
3994
|
-
dataMap = new Y.Map();
|
|
3995
|
-
entry.set("data", dataMap);
|
|
3996
|
-
}
|
|
3997
|
-
const baseData = isPlainObject(before.data) ? before.data : {};
|
|
3998
|
-
const localData = isPlainObject(block.data) ? block.data : {};
|
|
3999
|
-
for (const key of /* @__PURE__ */ new Set([...Object.keys(baseData), ...Object.keys(localData)])) {
|
|
4000
|
-
const a = baseData[key];
|
|
4001
|
-
const b = localData[key];
|
|
4002
|
-
if (stableStringify(a) === stableStringify(b)) continue;
|
|
4003
|
-
changed = true;
|
|
4004
|
-
if (!(key in localData)) {
|
|
4005
|
-
dataMap.delete(key);
|
|
4006
|
-
} else if (typeof b === "string") {
|
|
4007
|
-
const current = dataMap.get(key);
|
|
4008
|
-
if (current instanceof Y.Text)
|
|
4009
|
-
applyTextEdit(current, typeof a === "string" ? a : current.toString(), b);
|
|
4010
|
-
else {
|
|
4011
|
-
const text = new Y.Text();
|
|
4012
|
-
dataMap.set(key, text);
|
|
4013
|
-
text.insert(0, b);
|
|
4014
|
-
}
|
|
4015
|
-
} else {
|
|
4016
|
-
dataMap.set(key, b === void 0 ? null : b);
|
|
4712
|
+
} else {
|
|
4713
|
+
if (!before && entry.get("type") !== block.type) {
|
|
4714
|
+
entry.set("type", block.type);
|
|
4715
|
+
changed = true;
|
|
4017
4716
|
}
|
|
4717
|
+
changed = mergeSlot(entry, "data", reference.data || {}, isPlainObject(block.data) ? block.data : {}, 2) || changed;
|
|
4018
4718
|
}
|
|
4719
|
+
changed = mergeSlot(entry, "tunes", reference.tunes || {}, isPlainObject(block.tunes) ? block.tunes : {}, 2) || changed;
|
|
4720
|
+
}
|
|
4721
|
+
if (changed) {
|
|
4722
|
+
if (local.time && meta.get("time") !== local.time) meta.set("time", local.time);
|
|
4723
|
+
if (local.version && meta.get("version") !== local.version) meta.set("version", local.version);
|
|
4019
4724
|
}
|
|
4020
|
-
if (changed && local.time) meta.set("time", local.time);
|
|
4021
4725
|
}, origin);
|
|
4022
4726
|
return changed;
|
|
4023
4727
|
};
|
|
4024
|
-
const
|
|
4025
|
-
const
|
|
4026
|
-
return
|
|
4728
|
+
const epochOf = (doc) => {
|
|
4729
|
+
const epoch = doc.getMap("meta").get("epoch");
|
|
4730
|
+
return typeof epoch === "string" ? epoch.slice(0, 64) : "";
|
|
4731
|
+
};
|
|
4732
|
+
const keys = /* @__PURE__ */ new WeakMap();
|
|
4733
|
+
const blockKey = (block) => {
|
|
4734
|
+
let key = keys.get(block);
|
|
4735
|
+
if (key === void 0) {
|
|
4736
|
+
key = stableStringify({ type: block.type, data: block.data || {}, tunes: block.tunes || {} });
|
|
4737
|
+
keys.set(block, key);
|
|
4738
|
+
}
|
|
4739
|
+
return key;
|
|
4027
4740
|
};
|
|
4028
|
-
const blockKey = (block) => stableStringify({ type: block.type, data: block.data || {}, tunes: block.tunes || {} });
|
|
4029
4741
|
const caretOffset = (element) => {
|
|
4030
4742
|
const selection = window.getSelection();
|
|
4031
4743
|
if (!selection || selection.rangeCount === 0) return null;
|
|
@@ -4176,58 +4888,262 @@ const useFieldTarget = (name) => {
|
|
|
4176
4888
|
field: name
|
|
4177
4889
|
};
|
|
4178
4890
|
};
|
|
4891
|
+
const LOCAL_ORIGIN = Object.freeze({ name: "magic-editor-x-local" });
|
|
4892
|
+
const REMOTE_ORIGIN = Object.freeze({ name: "magic-editor-x-remote" });
|
|
4893
|
+
const SHADOW_EDIT = Object.freeze({ name: "magic-editor-x-shadow-edit" });
|
|
4894
|
+
const SHADOW_SYNC = Object.freeze({ name: "magic-editor-x-shadow-sync" });
|
|
4895
|
+
const createReplica = ({
|
|
4896
|
+
onLocalUpdate = () => {
|
|
4897
|
+
},
|
|
4898
|
+
onShouldRender = () => {
|
|
4899
|
+
},
|
|
4900
|
+
captureTimeout = 500,
|
|
4901
|
+
maxUndoSteps = 200
|
|
4902
|
+
} = {}) => {
|
|
4903
|
+
const doc = new Y.Doc();
|
|
4904
|
+
const shadow = new Y.Doc();
|
|
4905
|
+
const reader = createDocReader(doc);
|
|
4906
|
+
let base = { blocks: [] };
|
|
4907
|
+
const undo = new Y.UndoManager([doc.getArray("order"), doc.getMap("blocks")], {
|
|
4908
|
+
trackedOrigins: /* @__PURE__ */ new Set([LOCAL_ORIGIN]),
|
|
4909
|
+
captureTimeout
|
|
4910
|
+
});
|
|
4911
|
+
undo.on("stack-item-added", () => {
|
|
4912
|
+
while (undo.undoStack.length > maxUndoSteps) undo.undoStack.shift();
|
|
4913
|
+
});
|
|
4914
|
+
shadow.on("update", (update, origin) => {
|
|
4915
|
+
if (origin === SHADOW_EDIT) Y.applyUpdate(doc, update, LOCAL_ORIGIN);
|
|
4916
|
+
});
|
|
4917
|
+
doc.on("update", (update, origin) => {
|
|
4918
|
+
if (origin !== REMOTE_ORIGIN) onLocalUpdate(update);
|
|
4919
|
+
if (origin === REMOTE_ORIGIN || origin === undo) onShouldRender();
|
|
4920
|
+
});
|
|
4921
|
+
return {
|
|
4922
|
+
doc,
|
|
4923
|
+
shadow,
|
|
4924
|
+
undoManager: undo,
|
|
4925
|
+
/** Applies an update from the server. */
|
|
4926
|
+
applyRemote(update) {
|
|
4927
|
+
Y.applyUpdate(doc, update, REMOTE_ORIGIN);
|
|
4928
|
+
},
|
|
4929
|
+
/**
|
|
4930
|
+
* Applies the editor's content: only the difference to what the editor
|
|
4931
|
+
* showed before is written.
|
|
4932
|
+
* @param {object} data - Editor content now.
|
|
4933
|
+
* @returns {boolean} True when something changed.
|
|
4934
|
+
*/
|
|
4935
|
+
pushLocal(data) {
|
|
4936
|
+
const changed = applyLocalChanges(shadow, base, data, SHADOW_EDIT);
|
|
4937
|
+
base = data;
|
|
4938
|
+
return changed;
|
|
4939
|
+
},
|
|
4940
|
+
/**
|
|
4941
|
+
* Applies an edit made against an older state (`from` -> `data`) to the
|
|
4942
|
+
* current one, for example unsent edits after the room was replaced.
|
|
4943
|
+
* @param {object} from - State the edit started from.
|
|
4944
|
+
* @param {object} data - Edited state.
|
|
4945
|
+
* @returns {boolean} True when something changed.
|
|
4946
|
+
*/
|
|
4947
|
+
rebase(from, data) {
|
|
4948
|
+
const changed = applyLocalChanges(shadow, from, data, SHADOW_EDIT);
|
|
4949
|
+
base = docToEditorData(shadow);
|
|
4950
|
+
return changed;
|
|
4951
|
+
},
|
|
4952
|
+
/**
|
|
4953
|
+
* Reads the state the editor should show, with a token for `markShown`.
|
|
4954
|
+
* @returns {{ data: object, catchUp: Uint8Array }} Data and catch-up update.
|
|
4955
|
+
*/
|
|
4956
|
+
snapshot() {
|
|
4957
|
+
return { data: reader.read(), catchUp: Y.encodeStateAsUpdate(doc, Y.encodeStateVector(shadow)) };
|
|
4958
|
+
},
|
|
4959
|
+
/**
|
|
4960
|
+
* Records that the editor now shows the snapshot.
|
|
4961
|
+
* @param {Uint8Array} catchUp - Token from `snapshot()`.
|
|
4962
|
+
* @param {object} [shown] - What the editor reports after rendering (its own normalised form); defaults to the shadow content.
|
|
4963
|
+
*/
|
|
4964
|
+
markShown(catchUp, shown) {
|
|
4965
|
+
Y.applyUpdate(shadow, catchUp, SHADOW_SYNC);
|
|
4966
|
+
base = shown || docToEditorData(shadow);
|
|
4967
|
+
},
|
|
4968
|
+
/** Content of the shared state. */
|
|
4969
|
+
read: () => reader.read(),
|
|
4970
|
+
/** Room generation. */
|
|
4971
|
+
epoch: () => epochOf(doc),
|
|
4972
|
+
/** Starts a new undo step (next change is not merged with the previous one). */
|
|
4973
|
+
stopCapturing: () => undo.stopCapturing(),
|
|
4974
|
+
undo: () => undo.undo() !== null,
|
|
4975
|
+
redo: () => undo.redo() !== null,
|
|
4976
|
+
canUndo: () => undo.undoStack.length > 0,
|
|
4977
|
+
canRedo: () => undo.redoStack.length > 0,
|
|
4978
|
+
/** Frees both documents. */
|
|
4979
|
+
destroy() {
|
|
4980
|
+
undo.destroy();
|
|
4981
|
+
reader.destroy();
|
|
4982
|
+
doc.destroy();
|
|
4983
|
+
shadow.destroy();
|
|
4984
|
+
}
|
|
4985
|
+
};
|
|
4986
|
+
};
|
|
4987
|
+
const PROTOCOL = 3;
|
|
4179
4988
|
const RESYNC_MS = 2e4;
|
|
4180
4989
|
const ACK_TIMEOUT_MS = 1e4;
|
|
4990
|
+
const RETRY_BASE_MS = 500;
|
|
4991
|
+
const RETRY_MAX_MS = 15e3;
|
|
4992
|
+
const IDLE_AFTER_MS = 6e4;
|
|
4181
4993
|
const isEmptyUpdate = (update) => !update || update.byteLength <= 2;
|
|
4994
|
+
const backoffDelay = (attempt, random = Math.random) => {
|
|
4995
|
+
const cap = Math.min(RETRY_MAX_MS, RETRY_BASE_MS * 2 ** Math.min(attempt, 10));
|
|
4996
|
+
return Math.round(cap / 2 + random() * cap / 2);
|
|
4997
|
+
};
|
|
4182
4998
|
const createCollabClient = ({
|
|
4183
4999
|
requestSession,
|
|
4184
5000
|
url,
|
|
4185
5001
|
onRemoteData,
|
|
4186
5002
|
onFirstSync,
|
|
4187
5003
|
onState,
|
|
4188
|
-
|
|
5004
|
+
onUndoState = () => {
|
|
5005
|
+
},
|
|
5006
|
+
socketFactory = io,
|
|
5007
|
+
win = typeof window !== "undefined" ? window : null
|
|
4189
5008
|
}) => {
|
|
4190
|
-
|
|
5009
|
+
let replica = null;
|
|
4191
5010
|
let socket = null;
|
|
4192
5011
|
let destroyed = false;
|
|
4193
5012
|
let pending = null;
|
|
4194
|
-
let
|
|
5013
|
+
let inFlight = false;
|
|
5014
|
+
let state = {
|
|
5015
|
+
status: "connecting",
|
|
5016
|
+
canEdit: false,
|
|
5017
|
+
peers: [],
|
|
5018
|
+
error: null,
|
|
5019
|
+
presenceId: null,
|
|
5020
|
+
color: null,
|
|
5021
|
+
pending: false
|
|
5022
|
+
};
|
|
4195
5023
|
let resyncTimer = null;
|
|
5024
|
+
let idleTimer = null;
|
|
4196
5025
|
let notifyTimer = null;
|
|
5026
|
+
let retryTimer = null;
|
|
5027
|
+
let flushTimer = null;
|
|
4197
5028
|
let firstToken = null;
|
|
4198
5029
|
let synced = false;
|
|
4199
5030
|
let seededBySelf = false;
|
|
4200
|
-
let
|
|
5031
|
+
let epoch = null;
|
|
5032
|
+
let attempt = 0;
|
|
5033
|
+
let confirmed = { blocks: [] };
|
|
5034
|
+
let lastLocal = null;
|
|
5035
|
+
let rescue = null;
|
|
5036
|
+
let lastActivity = Date.now();
|
|
5037
|
+
let lastCursor = null;
|
|
5038
|
+
let idle = false;
|
|
4201
5039
|
const setState = (patch) => {
|
|
4202
|
-
state = { ...state, ...patch };
|
|
5040
|
+
state = { ...state, ...patch, pending: Boolean(pending) || inFlight };
|
|
4203
5041
|
onState({ ...state });
|
|
4204
5042
|
};
|
|
4205
5043
|
const notifyRemote = () => {
|
|
4206
|
-
if (notifyTimer) return;
|
|
5044
|
+
if (notifyTimer || destroyed) return;
|
|
4207
5045
|
notifyTimer = setTimeout(() => {
|
|
4208
5046
|
notifyTimer = null;
|
|
4209
|
-
if (!destroyed) onRemoteData(
|
|
5047
|
+
if (!destroyed) onRemoteData();
|
|
4210
5048
|
}, 30);
|
|
4211
5049
|
};
|
|
5050
|
+
const undoState = () => {
|
|
5051
|
+
if (replica) onUndoState({ canUndo: replica.canUndo(), canRedo: replica.canRedo() });
|
|
5052
|
+
};
|
|
5053
|
+
let startOver = () => {
|
|
5054
|
+
};
|
|
4212
5055
|
const flush = () => {
|
|
4213
|
-
if (!socket || !socket.connected || !pending || !state.canEdit) return;
|
|
5056
|
+
if (!socket || !socket.connected || !pending || inFlight || !state.canEdit || !synced) return;
|
|
4214
5057
|
const update = pending;
|
|
4215
5058
|
pending = null;
|
|
5059
|
+
inFlight = true;
|
|
5060
|
+
const sentWith = replica;
|
|
4216
5061
|
socket.timeout(ACK_TIMEOUT_MS).emit("mx:update", update, (error, reply) => {
|
|
4217
|
-
|
|
4218
|
-
|
|
4219
|
-
|
|
5062
|
+
inFlight = false;
|
|
5063
|
+
if (sentWith !== replica || destroyed) return;
|
|
5064
|
+
if (!error && reply && reply.ok) {
|
|
5065
|
+
if (!pending) confirmed = replica.read();
|
|
5066
|
+
setState({});
|
|
5067
|
+
flush();
|
|
5068
|
+
return;
|
|
5069
|
+
}
|
|
5070
|
+
const code = reply && reply.code;
|
|
5071
|
+
if (code === "READ_ONLY") {
|
|
5072
|
+
setState({ canEdit: false });
|
|
5073
|
+
startOver(false);
|
|
5074
|
+
return;
|
|
4220
5075
|
}
|
|
5076
|
+
if (code === "INVALID_UPDATE") {
|
|
5077
|
+
startOver(false);
|
|
5078
|
+
return;
|
|
5079
|
+
}
|
|
5080
|
+
pending = pending ? Y.mergeUpdates([update, pending]) : update;
|
|
5081
|
+
setState({});
|
|
5082
|
+
clearTimeout(flushTimer);
|
|
5083
|
+
flushTimer = setTimeout(flush, code === "RATE_LIMITED" ? 2e3 : 400);
|
|
4221
5084
|
});
|
|
5085
|
+
setState({});
|
|
4222
5086
|
};
|
|
4223
|
-
|
|
4224
|
-
if (
|
|
4225
|
-
|
|
4226
|
-
|
|
5087
|
+
const createDocs = () => {
|
|
5088
|
+
if (replica) replica.destroy();
|
|
5089
|
+
replica = createReplica({
|
|
5090
|
+
onLocalUpdate: (update) => {
|
|
5091
|
+
pending = pending ? Y.mergeUpdates([pending, update]) : update;
|
|
5092
|
+
flush();
|
|
5093
|
+
undoState();
|
|
5094
|
+
},
|
|
5095
|
+
onShouldRender: notifyRemote
|
|
5096
|
+
});
|
|
5097
|
+
replica.undoManager.on("stack-item-added", undoState);
|
|
5098
|
+
replica.undoManager.on("stack-item-popped", undoState);
|
|
5099
|
+
pending = null;
|
|
5100
|
+
inFlight = false;
|
|
5101
|
+
synced = false;
|
|
5102
|
+
undoState();
|
|
5103
|
+
};
|
|
5104
|
+
startOver = (keepUnsent) => {
|
|
5105
|
+
const unsent = keepUnsent && (pending || inFlight) ? lastLocal : null;
|
|
5106
|
+
const base = confirmed;
|
|
5107
|
+
createDocs();
|
|
5108
|
+
epoch = null;
|
|
5109
|
+
rescue = unsent ? { base, local: unsent } : null;
|
|
5110
|
+
if (socket && socket.connected) socket.emit("mx:resync", new Uint8Array([0]));
|
|
5111
|
+
};
|
|
5112
|
+
const scheduleReconnect = () => {
|
|
5113
|
+
if (destroyed || !socket || socket.connected || socket.active || state.status === "denied") return;
|
|
5114
|
+
clearTimeout(retryTimer);
|
|
5115
|
+
retryTimer = setTimeout(() => {
|
|
5116
|
+
if (!destroyed && socket && !socket.connected) socket.connect();
|
|
5117
|
+
}, backoffDelay(attempt));
|
|
5118
|
+
attempt += 1;
|
|
5119
|
+
};
|
|
5120
|
+
const offline = () => Boolean(win && win.navigator && win.navigator.onLine === false);
|
|
5121
|
+
const sendPresence = () => {
|
|
5122
|
+
if (socket && socket.connected) socket.emit("mx:cursor", { ...lastCursor || {}, idle });
|
|
5123
|
+
};
|
|
5124
|
+
const onOnline = () => {
|
|
5125
|
+
attempt = 0;
|
|
5126
|
+
if (!socket || state.status === "denied") return;
|
|
5127
|
+
if (!socket.connected) socket.connect();
|
|
5128
|
+
else if (replica) socket.emit("mx:resync", Y.encodeStateVector(replica.doc));
|
|
5129
|
+
};
|
|
5130
|
+
const onOffline = () => setState({ status: "offline" });
|
|
5131
|
+
const onVisibility = () => {
|
|
5132
|
+
if (!win || !win.document) return;
|
|
5133
|
+
const hidden = win.document.visibilityState === "hidden";
|
|
5134
|
+
if (!hidden) {
|
|
5135
|
+
lastActivity = Date.now();
|
|
5136
|
+
onOnline();
|
|
5137
|
+
}
|
|
5138
|
+
if (hidden !== idle) {
|
|
5139
|
+
idle = hidden;
|
|
5140
|
+
sendPresence();
|
|
4227
5141
|
}
|
|
4228
|
-
|
|
4229
|
-
|
|
4230
|
-
|
|
5142
|
+
};
|
|
5143
|
+
const onPageHide = () => {
|
|
5144
|
+
if (socket) socket.disconnect();
|
|
5145
|
+
};
|
|
5146
|
+
createDocs();
|
|
4231
5147
|
const connect = async () => {
|
|
4232
5148
|
const session = await requestSession();
|
|
4233
5149
|
if (destroyed) return;
|
|
@@ -4238,59 +5154,120 @@ const createCollabClient = ({
|
|
|
4238
5154
|
path: session.path,
|
|
4239
5155
|
transports: ["websocket"],
|
|
4240
5156
|
reconnection: true,
|
|
4241
|
-
reconnectionDelay:
|
|
4242
|
-
reconnectionDelayMax:
|
|
5157
|
+
reconnectionDelay: RETRY_BASE_MS,
|
|
5158
|
+
reconnectionDelayMax: RETRY_MAX_MS,
|
|
5159
|
+
randomizationFactor: 0.5,
|
|
4243
5160
|
auth: (callback) => {
|
|
4244
5161
|
if (firstToken) {
|
|
4245
5162
|
const token = firstToken;
|
|
4246
5163
|
firstToken = null;
|
|
4247
|
-
callback({ token });
|
|
5164
|
+
callback({ token, protocol: PROTOCOL });
|
|
4248
5165
|
return;
|
|
4249
5166
|
}
|
|
4250
5167
|
requestSession().then((next) => {
|
|
4251
5168
|
setState({ canEdit: next.canEdit });
|
|
4252
|
-
callback({ token: next.token });
|
|
4253
|
-
}).catch(() =>
|
|
5169
|
+
callback({ token: next.token, protocol: PROTOCOL });
|
|
5170
|
+
}).catch((error) => {
|
|
5171
|
+
const status = error && error.response && error.response.status;
|
|
5172
|
+
if (status === 403 || status === 404) setState({ status: "denied", error: `HTTP_${status}` });
|
|
5173
|
+
callback({ token: "", protocol: PROTOCOL });
|
|
5174
|
+
});
|
|
4254
5175
|
}
|
|
4255
5176
|
});
|
|
4256
|
-
socket.on("connect", () =>
|
|
4257
|
-
|
|
4258
|
-
|
|
4259
|
-
|
|
4260
|
-
|
|
4261
|
-
|
|
4262
|
-
|
|
4263
|
-
|
|
4264
|
-
|
|
4265
|
-
|
|
4266
|
-
|
|
4267
|
-
|
|
4268
|
-
|
|
4269
|
-
|
|
4270
|
-
|
|
5177
|
+
socket.on("connect", () => {
|
|
5178
|
+
attempt = 0;
|
|
5179
|
+
setState({ status: "syncing", error: null });
|
|
5180
|
+
});
|
|
5181
|
+
socket.on("disconnect", () => {
|
|
5182
|
+
inFlight = false;
|
|
5183
|
+
if (state.status !== "denied") setState({ status: offline() ? "offline" : "reconnecting", peers: [] });
|
|
5184
|
+
scheduleReconnect();
|
|
5185
|
+
});
|
|
5186
|
+
socket.on("connect_error", (error) => {
|
|
5187
|
+
const code = error && error.data && error.data.code || null;
|
|
5188
|
+
if (code === "UPGRADE_REQUIRED") {
|
|
5189
|
+
setState({ status: "error", error: code });
|
|
5190
|
+
return;
|
|
5191
|
+
}
|
|
5192
|
+
if (state.status === "denied") return;
|
|
5193
|
+
setState({ status: offline() ? "offline" : "reconnecting", error: code });
|
|
5194
|
+
scheduleReconnect();
|
|
5195
|
+
});
|
|
5196
|
+
socket.on("mx:welcome", (welcome = {}) => {
|
|
5197
|
+
if (epoch !== null && welcome.epoch !== epoch) startOver(true);
|
|
5198
|
+
setState({
|
|
5199
|
+
canEdit: Boolean(welcome.canEdit),
|
|
5200
|
+
presenceId: welcome.presenceId,
|
|
5201
|
+
color: welcome.color
|
|
5202
|
+
});
|
|
5203
|
+
sendPresence();
|
|
5204
|
+
});
|
|
5205
|
+
socket.on("mx:sync", (message) => {
|
|
5206
|
+
if (!message || !message.update) return;
|
|
5207
|
+
if (epoch !== null && message.epoch !== void 0 && message.epoch !== epoch) startOver(true);
|
|
5208
|
+
replica.applyRemote(new Uint8Array(message.update));
|
|
5209
|
+
epoch = message.epoch !== void 0 ? message.epoch : replica.epoch();
|
|
5210
|
+
if (message.stateVector && state.canEdit) {
|
|
5211
|
+
const missing = Y.encodeStateAsUpdate(replica.doc, new Uint8Array(message.stateVector));
|
|
5212
|
+
if (!isEmptyUpdate(missing)) pending = pending ? Y.mergeUpdates([pending, missing]) : missing;
|
|
4271
5213
|
}
|
|
4272
5214
|
const first = !synced;
|
|
4273
5215
|
synced = true;
|
|
4274
|
-
if (first)
|
|
5216
|
+
if (first) {
|
|
5217
|
+
const shown = replica.snapshot();
|
|
5218
|
+
replica.markShown(shown.catchUp);
|
|
5219
|
+
if (!pending && !inFlight) confirmed = shown.data;
|
|
5220
|
+
}
|
|
5221
|
+
if (rescue) {
|
|
5222
|
+
const { base, local } = rescue;
|
|
5223
|
+
rescue = null;
|
|
5224
|
+
if (state.canEdit) replica.rebase(base, local);
|
|
5225
|
+
}
|
|
4275
5226
|
setState({ status: "live" });
|
|
4276
5227
|
Promise.resolve(first && typeof onFirstSync === "function" ? onFirstSync(seededBySelf) : null).catch(() => null).then(() => {
|
|
4277
|
-
notifyRemote();
|
|
5228
|
+
if (first) notifyRemote();
|
|
4278
5229
|
flush();
|
|
4279
5230
|
});
|
|
4280
5231
|
});
|
|
4281
|
-
socket.on("mx:update", (update) =>
|
|
5232
|
+
socket.on("mx:update", (update) => {
|
|
5233
|
+
if (replica) replica.applyRemote(new Uint8Array(update));
|
|
5234
|
+
});
|
|
4282
5235
|
socket.on("mx:presence", (peers) => {
|
|
4283
|
-
setState({
|
|
5236
|
+
setState({
|
|
5237
|
+
peers: Array.isArray(peers) ? peers.filter((peer) => peer && peer.id !== state.presenceId) : []
|
|
5238
|
+
});
|
|
5239
|
+
});
|
|
5240
|
+
socket.on("mx:role", ({ canEdit } = {}) => {
|
|
5241
|
+
setState({ canEdit: Boolean(canEdit) });
|
|
5242
|
+
if (canEdit) flush();
|
|
5243
|
+
else if (pending || inFlight) startOver(false);
|
|
5244
|
+
});
|
|
5245
|
+
socket.on("mx:error", ({ code } = {}) => {
|
|
5246
|
+
if (code === "ACCESS_REVOKED") {
|
|
5247
|
+
setState({ status: "denied", error: code, canEdit: false, peers: [] });
|
|
5248
|
+
if (socket) socket.disconnect();
|
|
5249
|
+
return;
|
|
5250
|
+
}
|
|
5251
|
+
if (code === "ROOM_RESET") startOver(true);
|
|
5252
|
+
if (code === "INVALID_UPDATE") startOver(false);
|
|
5253
|
+
setState({ error: code });
|
|
4284
5254
|
});
|
|
4285
|
-
socket.on("mx:role", ({ canEdit }) => setState({ canEdit: Boolean(canEdit) }));
|
|
4286
|
-
socket.on(
|
|
4287
|
-
"mx:error",
|
|
4288
|
-
({ code }) => setState({ status: code === "ACCESS_REVOKED" ? "denied" : "error", error: code })
|
|
4289
|
-
);
|
|
4290
5255
|
resyncTimer = setInterval(() => {
|
|
4291
|
-
if (socket && socket.connected) socket.emit("mx:resync", Y.encodeStateVector(doc));
|
|
5256
|
+
if (socket && socket.connected && replica) socket.emit("mx:resync", Y.encodeStateVector(replica.doc));
|
|
4292
5257
|
}, RESYNC_MS);
|
|
5258
|
+
idleTimer = setInterval(() => {
|
|
5259
|
+
if (!idle && Date.now() - lastActivity > IDLE_AFTER_MS) {
|
|
5260
|
+
idle = true;
|
|
5261
|
+
sendPresence();
|
|
5262
|
+
}
|
|
5263
|
+
}, 5e3);
|
|
4293
5264
|
};
|
|
5265
|
+
if (win && typeof win.addEventListener === "function") {
|
|
5266
|
+
win.addEventListener("online", onOnline);
|
|
5267
|
+
win.addEventListener("offline", onOffline);
|
|
5268
|
+
win.addEventListener("pagehide", onPageHide);
|
|
5269
|
+
if (win.document) win.document.addEventListener("visibilitychange", onVisibility);
|
|
5270
|
+
}
|
|
4294
5271
|
connect().catch((error) => {
|
|
4295
5272
|
const status = error && error.response && error.response.status;
|
|
4296
5273
|
setState({
|
|
@@ -4299,42 +5276,92 @@ const createCollabClient = ({
|
|
|
4299
5276
|
});
|
|
4300
5277
|
});
|
|
4301
5278
|
return {
|
|
4302
|
-
/**
|
|
5279
|
+
/**
|
|
5280
|
+
* Applies the editor content: only the difference to what the editor showed is written.
|
|
5281
|
+
* @param {object} data - Editor content now.
|
|
5282
|
+
*/
|
|
4303
5283
|
pushLocal(data) {
|
|
4304
5284
|
if (destroyed || !synced || !state.canEdit) return;
|
|
4305
|
-
|
|
4306
|
-
|
|
5285
|
+
lastLocal = data;
|
|
5286
|
+
lastActivity = Date.now();
|
|
5287
|
+
if (idle) {
|
|
5288
|
+
idle = false;
|
|
5289
|
+
sendPresence();
|
|
5290
|
+
}
|
|
5291
|
+
replica.pushLocal(data);
|
|
4307
5292
|
},
|
|
4308
|
-
/**
|
|
4309
|
-
|
|
4310
|
-
|
|
5293
|
+
/**
|
|
5294
|
+
* Reads what the editor should show and a token for `markShown`.
|
|
5295
|
+
* @returns {{ data: object, catchUp: Uint8Array }} Snapshot.
|
|
5296
|
+
*/
|
|
5297
|
+
snapshot: () => replica.snapshot(),
|
|
5298
|
+
/**
|
|
5299
|
+
* Records that the editor now shows a snapshot.
|
|
5300
|
+
* @param {Uint8Array} catchUp - Token from `snapshot()`.
|
|
5301
|
+
* @param {object} [shown] - The editor's own output right after rendering.
|
|
5302
|
+
*/
|
|
5303
|
+
markShown(catchUp, shown) {
|
|
5304
|
+
if (replica) replica.markShown(catchUp, shown);
|
|
4311
5305
|
},
|
|
4312
|
-
/**
|
|
5306
|
+
/**
|
|
5307
|
+
* Shares the caret (block and character offsets) with the room.
|
|
5308
|
+
* @param {{ blockId: string, anchor: number, focus: number }|null} cursor - Caret or null.
|
|
5309
|
+
*/
|
|
4313
5310
|
sendCursor(cursor) {
|
|
4314
|
-
|
|
5311
|
+
lastCursor = cursor;
|
|
5312
|
+
lastActivity = Date.now();
|
|
5313
|
+
idle = false;
|
|
5314
|
+
sendPresence();
|
|
4315
5315
|
},
|
|
5316
|
+
/** Undoes the last own change. @returns {boolean} True when something was undone. */
|
|
5317
|
+
undo: () => Boolean(replica && state.canEdit && replica.undo()),
|
|
5318
|
+
/** Redoes the last undone own change. @returns {boolean} True when something was redone. */
|
|
5319
|
+
redo: () => Boolean(replica && state.canEdit && replica.redo()),
|
|
5320
|
+
/** Starts a new undo step. */
|
|
5321
|
+
stopCapturing: () => replica && replica.stopCapturing(),
|
|
5322
|
+
canUndo: () => Boolean(replica && replica.canUndo()),
|
|
5323
|
+
canRedo: () => Boolean(replica && replica.canRedo()),
|
|
4316
5324
|
/** Current shared document. */
|
|
4317
|
-
getData()
|
|
4318
|
-
return docToEditorData(doc);
|
|
4319
|
-
},
|
|
5325
|
+
getData: () => replica ? replica.read() : docToEditorData(new Y.Doc()),
|
|
4320
5326
|
/** True when the room has content (it was seeded). */
|
|
4321
5327
|
hasContent() {
|
|
4322
|
-
return
|
|
5328
|
+
return Boolean(
|
|
5329
|
+
replica && (replica.doc.getArray("order").length > 0 || replica.doc.getMap("blocks").size > 0)
|
|
5330
|
+
);
|
|
4323
5331
|
},
|
|
4324
|
-
/** Disconnects and frees the
|
|
5332
|
+
/** Disconnects and frees the documents. */
|
|
4325
5333
|
destroy() {
|
|
4326
5334
|
destroyed = true;
|
|
4327
5335
|
clearInterval(resyncTimer);
|
|
5336
|
+
clearInterval(idleTimer);
|
|
4328
5337
|
clearTimeout(notifyTimer);
|
|
5338
|
+
clearTimeout(retryTimer);
|
|
5339
|
+
clearTimeout(flushTimer);
|
|
5340
|
+
if (win && typeof win.removeEventListener === "function") {
|
|
5341
|
+
win.removeEventListener("online", onOnline);
|
|
5342
|
+
win.removeEventListener("offline", onOffline);
|
|
5343
|
+
win.removeEventListener("pagehide", onPageHide);
|
|
5344
|
+
if (win.document) win.document.removeEventListener("visibilitychange", onVisibility);
|
|
5345
|
+
}
|
|
4329
5346
|
if (socket) {
|
|
4330
5347
|
socket.removeAllListeners();
|
|
4331
5348
|
socket.disconnect();
|
|
4332
5349
|
}
|
|
4333
|
-
|
|
5350
|
+
if (replica) replica.destroy();
|
|
5351
|
+
replica = null;
|
|
4334
5352
|
}
|
|
4335
5353
|
};
|
|
4336
5354
|
};
|
|
4337
|
-
const INITIAL = {
|
|
5355
|
+
const INITIAL = {
|
|
5356
|
+
status: "off",
|
|
5357
|
+
canEdit: false,
|
|
5358
|
+
peers: [],
|
|
5359
|
+
error: null,
|
|
5360
|
+
color: null,
|
|
5361
|
+
pending: false,
|
|
5362
|
+
canUndo: false,
|
|
5363
|
+
canRedo: false
|
|
5364
|
+
};
|
|
4338
5365
|
const useCollaboration = ({ target, getLocalData, ready, onRemoteData, onFirstSync }) => {
|
|
4339
5366
|
const { post } = useFetchClient();
|
|
4340
5367
|
const [state, setState] = useState(INITIAL);
|
|
@@ -4363,9 +5390,10 @@ const useCollaboration = ({ target, getLocalData, ready, onRemoteData, onFirstSy
|
|
|
4363
5390
|
});
|
|
4364
5391
|
return data.data;
|
|
4365
5392
|
},
|
|
4366
|
-
onRemoteData: (
|
|
5393
|
+
onRemoteData: () => onRemoteRef.current(),
|
|
4367
5394
|
onFirstSync: (seeded) => onFirstSyncRef.current ? onFirstSyncRef.current(seeded, instance) : null,
|
|
4368
|
-
onState: (next) => setState(next)
|
|
5395
|
+
onState: (next) => setState((previous) => ({ ...previous, ...next })),
|
|
5396
|
+
onUndoState: (undo) => setState((previous) => ({ ...previous, ...undo }))
|
|
4369
5397
|
});
|
|
4370
5398
|
setClient(instance);
|
|
4371
5399
|
return () => {
|
|
@@ -4374,16 +5402,7 @@ const useCollaboration = ({ target, getLocalData, ready, onRemoteData, onFirstSy
|
|
|
4374
5402
|
setState(INITIAL);
|
|
4375
5403
|
};
|
|
4376
5404
|
}, [key, post]);
|
|
4377
|
-
if (!key)
|
|
4378
|
-
return {
|
|
4379
|
-
active: false,
|
|
4380
|
-
status: "off",
|
|
4381
|
-
canEdit: false,
|
|
4382
|
-
peers: [],
|
|
4383
|
-
error: null,
|
|
4384
|
-
color: null,
|
|
4385
|
-
client: null
|
|
4386
|
-
};
|
|
5405
|
+
if (!key) return { ...INITIAL, active: false, client: null };
|
|
4387
5406
|
return {
|
|
4388
5407
|
active: !["off", "denied", "error"].includes(state.status),
|
|
4389
5408
|
status: state.status === "off" ? "connecting" : state.status,
|
|
@@ -4391,17 +5410,240 @@ const useCollaboration = ({ target, getLocalData, ready, onRemoteData, onFirstSy
|
|
|
4391
5410
|
peers: state.peers,
|
|
4392
5411
|
error: state.error,
|
|
4393
5412
|
color: state.color,
|
|
5413
|
+
pending: state.pending,
|
|
5414
|
+
canUndo: state.canUndo,
|
|
5415
|
+
canRedo: state.canRedo,
|
|
4394
5416
|
client
|
|
4395
5417
|
};
|
|
4396
5418
|
};
|
|
5419
|
+
const PEER_FAMILIES = ["primary", "danger", "success", "warning", "secondary", "alternative"];
|
|
5420
|
+
const peerFamily = (family) => PEER_FAMILIES.includes(family) ? family : "neutral";
|
|
5421
|
+
const blink = keyframes`
|
|
5422
|
+
0%, 49% { opacity: 1; }
|
|
5423
|
+
50%, 100% { opacity: 0.2; }
|
|
5424
|
+
`;
|
|
5425
|
+
const Layer = styled.div`
|
|
5426
|
+
position: absolute;
|
|
5427
|
+
inset: 0;
|
|
5428
|
+
pointer-events: none;
|
|
5429
|
+
overflow: hidden;
|
|
5430
|
+
z-index: 1;
|
|
5431
|
+
`;
|
|
5432
|
+
const Highlight = styled.div`
|
|
5433
|
+
position: absolute;
|
|
5434
|
+
background: ${({ theme, $family }) => theme.colors[`${$family}200`] || theme.colors.neutral200};
|
|
5435
|
+
opacity: 0.55;
|
|
5436
|
+
border-radius: 2px;
|
|
5437
|
+
`;
|
|
5438
|
+
const Caret = styled.div`
|
|
5439
|
+
position: absolute;
|
|
5440
|
+
width: 2px;
|
|
5441
|
+
background: ${({ theme, $family }) => theme.colors[`${$family}600`] || theme.colors.neutral600};
|
|
5442
|
+
opacity: ${({ $idle }) => $idle ? 0.4 : 1};
|
|
5443
|
+
@media (prefers-reduced-motion: no-preference) {
|
|
5444
|
+
${({ $idle }) => $idle ? "" : css`
|
|
5445
|
+
animation: ${blink} 1.1s step-end infinite;
|
|
5446
|
+
`}
|
|
5447
|
+
}
|
|
5448
|
+
`;
|
|
5449
|
+
const Label = styled.div`
|
|
5450
|
+
position: absolute;
|
|
5451
|
+
transform: translateY(-100%);
|
|
5452
|
+
padding: 0 ${({ theme }) => theme.spaces[1]};
|
|
5453
|
+
border-radius: ${({ theme }) => theme.borderRadius};
|
|
5454
|
+
background: ${({ theme, $family }) => theme.colors[`${$family}600`] || theme.colors.neutral600};
|
|
5455
|
+
color: ${({ theme }) => theme.colors.neutral0};
|
|
5456
|
+
font-size: ${({ theme }) => theme.fontSizes[0]};
|
|
5457
|
+
line-height: 1.6;
|
|
5458
|
+
white-space: nowrap;
|
|
5459
|
+
max-width: 16rem;
|
|
5460
|
+
overflow: hidden;
|
|
5461
|
+
text-overflow: ellipsis;
|
|
5462
|
+
opacity: ${({ $idle }) => $idle ? 0.6 : 1};
|
|
5463
|
+
`;
|
|
5464
|
+
const BlockMarker = styled.div`
|
|
5465
|
+
position: absolute;
|
|
5466
|
+
width: 3px;
|
|
5467
|
+
border-radius: 2px;
|
|
5468
|
+
background: ${({ theme, $family }) => theme.colors[`${$family}500`] || theme.colors.neutral500};
|
|
5469
|
+
opacity: ${({ $idle }) => $idle ? 0.4 : 0.9};
|
|
5470
|
+
`;
|
|
5471
|
+
const pointAt = (root, offset) => {
|
|
5472
|
+
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
|
|
5473
|
+
let remaining = Math.max(0, offset);
|
|
5474
|
+
let node = walker.nextNode();
|
|
5475
|
+
let last = null;
|
|
5476
|
+
while (node) {
|
|
5477
|
+
last = node;
|
|
5478
|
+
if (remaining <= node.textContent.length) return { node, offset: remaining };
|
|
5479
|
+
remaining -= node.textContent.length;
|
|
5480
|
+
node = walker.nextNode();
|
|
5481
|
+
}
|
|
5482
|
+
if (last) return { node: last, offset: last.textContent.length };
|
|
5483
|
+
return null;
|
|
5484
|
+
};
|
|
5485
|
+
const offsetOf = (root, node, offset) => {
|
|
5486
|
+
if (!root.contains(node)) return null;
|
|
5487
|
+
const range = document.createRange();
|
|
5488
|
+
range.selectNodeContents(root);
|
|
5489
|
+
try {
|
|
5490
|
+
range.setEnd(node, offset);
|
|
5491
|
+
} catch {
|
|
5492
|
+
return null;
|
|
5493
|
+
}
|
|
5494
|
+
return range.toString().length;
|
|
5495
|
+
};
|
|
5496
|
+
const measure = (container, holder, peer) => {
|
|
5497
|
+
const { blockId, anchor = 0, focus = anchor } = peer.cursor || {};
|
|
5498
|
+
if (!blockId) return null;
|
|
5499
|
+
const escaped = window.CSS && window.CSS.escape ? window.CSS.escape(blockId) : blockId;
|
|
5500
|
+
const block = holder.querySelector(`.ce-block[data-id="${escaped}"]`);
|
|
5501
|
+
if (!block) return null;
|
|
5502
|
+
const content = block.querySelector(".ce-block__content") || block;
|
|
5503
|
+
const origin = container.getBoundingClientRect();
|
|
5504
|
+
const blockRect = content.getBoundingClientRect();
|
|
5505
|
+
const geometry = {
|
|
5506
|
+
marker: {
|
|
5507
|
+
left: blockRect.left - origin.left - 8,
|
|
5508
|
+
top: blockRect.top - origin.top,
|
|
5509
|
+
height: Math.max(8, blockRect.height)
|
|
5510
|
+
},
|
|
5511
|
+
caret: null,
|
|
5512
|
+
highlights: []
|
|
5513
|
+
};
|
|
5514
|
+
const start = pointAt(content, Math.min(anchor, focus));
|
|
5515
|
+
const end = pointAt(content, Math.max(anchor, focus));
|
|
5516
|
+
if (!start || !end) {
|
|
5517
|
+
geometry.caret = { left: blockRect.left - origin.left, top: blockRect.top - origin.top, height: 20 };
|
|
5518
|
+
return geometry;
|
|
5519
|
+
}
|
|
5520
|
+
const range = document.createRange();
|
|
5521
|
+
try {
|
|
5522
|
+
range.setStart(start.node, start.offset);
|
|
5523
|
+
range.setEnd(end.node, end.offset);
|
|
5524
|
+
} catch {
|
|
5525
|
+
return geometry;
|
|
5526
|
+
}
|
|
5527
|
+
if (anchor !== focus) {
|
|
5528
|
+
geometry.highlights = Array.from(range.getClientRects()).slice(0, 50).map((rect2) => ({
|
|
5529
|
+
left: rect2.left - origin.left,
|
|
5530
|
+
top: rect2.top - origin.top,
|
|
5531
|
+
width: rect2.width,
|
|
5532
|
+
height: rect2.height
|
|
5533
|
+
}));
|
|
5534
|
+
}
|
|
5535
|
+
const caretRange = document.createRange();
|
|
5536
|
+
const caretPoint = focus >= anchor ? end : start;
|
|
5537
|
+
caretRange.setStart(caretPoint.node, caretPoint.offset);
|
|
5538
|
+
caretRange.collapse(true);
|
|
5539
|
+
const rects = caretRange.getClientRects();
|
|
5540
|
+
const rect = rects.length ? rects[0] : caretPoint.node.parentElement?.getBoundingClientRect();
|
|
5541
|
+
if (rect) {
|
|
5542
|
+
geometry.caret = {
|
|
5543
|
+
left: rect.left - origin.left,
|
|
5544
|
+
top: rect.top - origin.top,
|
|
5545
|
+
height: Math.max(14, rect.height || 18)
|
|
5546
|
+
};
|
|
5547
|
+
}
|
|
5548
|
+
return geometry;
|
|
5549
|
+
};
|
|
5550
|
+
const RemoteCarets = ({ containerRef, holderRef, peers, version, t }) => {
|
|
5551
|
+
const [shapes, setShapes] = useState([]);
|
|
5552
|
+
const frame = useRef(0);
|
|
5553
|
+
const peersRef = useRef(peers);
|
|
5554
|
+
useEffect(() => {
|
|
5555
|
+
peersRef.current = peers;
|
|
5556
|
+
}, [peers]);
|
|
5557
|
+
useLayoutEffect(() => {
|
|
5558
|
+
const container = containerRef.current;
|
|
5559
|
+
const holder = holderRef.current;
|
|
5560
|
+
if (!container || !holder) return void 0;
|
|
5561
|
+
const update = () => {
|
|
5562
|
+
cancelAnimationFrame(frame.current);
|
|
5563
|
+
frame.current = requestAnimationFrame(() => {
|
|
5564
|
+
const next = [];
|
|
5565
|
+
for (const peer of peersRef.current || []) {
|
|
5566
|
+
if (!peer.cursor) continue;
|
|
5567
|
+
const geometry = measure(container, holder, peer);
|
|
5568
|
+
if (geometry) next.push({ peer, geometry });
|
|
5569
|
+
}
|
|
5570
|
+
setShapes(next);
|
|
5571
|
+
});
|
|
5572
|
+
};
|
|
5573
|
+
update();
|
|
5574
|
+
const observer = typeof ResizeObserver === "function" ? new ResizeObserver(update) : null;
|
|
5575
|
+
if (observer) observer.observe(holder);
|
|
5576
|
+
window.addEventListener("resize", update);
|
|
5577
|
+
holder.addEventListener("scroll", update, true);
|
|
5578
|
+
return () => {
|
|
5579
|
+
cancelAnimationFrame(frame.current);
|
|
5580
|
+
if (observer) observer.disconnect();
|
|
5581
|
+
window.removeEventListener("resize", update);
|
|
5582
|
+
holder.removeEventListener("scroll", update, true);
|
|
5583
|
+
};
|
|
5584
|
+
}, [containerRef, holderRef, peers, version]);
|
|
5585
|
+
if (shapes.length === 0) return null;
|
|
5586
|
+
return /* @__PURE__ */ jsx(Layer, { "aria-hidden": "true", "data-testid": "mex-remote-carets", children: shapes.map(({ peer, geometry }) => {
|
|
5587
|
+
const family = peerFamily(peer.color);
|
|
5588
|
+
const label = peer.idle ? t("editor.collab.away", "{name} (away)", { name: peer.name }) : peer.name;
|
|
5589
|
+
return /* @__PURE__ */ jsxs("div", { "data-peer": peer.id, children: [
|
|
5590
|
+
/* @__PURE__ */ jsx(
|
|
5591
|
+
BlockMarker,
|
|
5592
|
+
{
|
|
5593
|
+
$family: family,
|
|
5594
|
+
$idle: peer.idle,
|
|
5595
|
+
style: {
|
|
5596
|
+
left: geometry.marker.left,
|
|
5597
|
+
top: geometry.marker.top,
|
|
5598
|
+
height: geometry.marker.height
|
|
5599
|
+
},
|
|
5600
|
+
title: t("editor.collab.editingBlock", "{name} is editing this block", { name: peer.name })
|
|
5601
|
+
}
|
|
5602
|
+
),
|
|
5603
|
+
geometry.highlights.map((rect, index) => /* @__PURE__ */ jsx(
|
|
5604
|
+
Highlight,
|
|
5605
|
+
{
|
|
5606
|
+
$family: family,
|
|
5607
|
+
style: { left: rect.left, top: rect.top, width: rect.width, height: rect.height }
|
|
5608
|
+
},
|
|
5609
|
+
index
|
|
5610
|
+
)),
|
|
5611
|
+
geometry.caret ? /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
5612
|
+
/* @__PURE__ */ jsx(
|
|
5613
|
+
Caret,
|
|
5614
|
+
{
|
|
5615
|
+
$family: family,
|
|
5616
|
+
$idle: peer.idle,
|
|
5617
|
+
"data-testid": "mex-remote-caret",
|
|
5618
|
+
style: {
|
|
5619
|
+
left: geometry.caret.left,
|
|
5620
|
+
top: geometry.caret.top,
|
|
5621
|
+
height: geometry.caret.height
|
|
5622
|
+
}
|
|
5623
|
+
}
|
|
5624
|
+
),
|
|
5625
|
+
/* @__PURE__ */ jsx(
|
|
5626
|
+
Label,
|
|
5627
|
+
{
|
|
5628
|
+
$family: family,
|
|
5629
|
+
$idle: peer.idle,
|
|
5630
|
+
style: { left: geometry.caret.left, top: geometry.caret.top },
|
|
5631
|
+
children: label
|
|
5632
|
+
}
|
|
5633
|
+
)
|
|
5634
|
+
] }) : null
|
|
5635
|
+
] }, peer.id);
|
|
5636
|
+
}) });
|
|
5637
|
+
};
|
|
4397
5638
|
const Bar = styled(Flex)`
|
|
4398
5639
|
min-width: 0;
|
|
4399
5640
|
border-bottom: 1px solid ${({ theme }) => theme.colors.neutral150};
|
|
4400
5641
|
flex-wrap: wrap;
|
|
4401
5642
|
`;
|
|
4402
5643
|
const Peer = styled(Avatar.Item)`
|
|
4403
|
-
outline: 2px solid ${({ $
|
|
5644
|
+
outline: 2px solid ${({ theme, $family }) => theme.colors[`${$family}600`] || theme.colors.neutral600};
|
|
4404
5645
|
outline-offset: 1px;
|
|
5646
|
+
opacity: ${({ $idle }) => $idle ? 0.55 : 1};
|
|
4405
5647
|
`;
|
|
4406
5648
|
const STATUS = {
|
|
4407
5649
|
connecting: {
|
|
@@ -4412,7 +5654,13 @@ const STATUS = {
|
|
|
4412
5654
|
},
|
|
4413
5655
|
syncing: { key: "editor.collab.status.syncing", text: "Syncing", bg: "neutral150", fg: "neutral800" },
|
|
4414
5656
|
live: { key: "editor.collab.status.live", text: "Live", bg: "success100", fg: "success700" },
|
|
4415
|
-
|
|
5657
|
+
reconnecting: {
|
|
5658
|
+
key: "editor.collab.status.reconnecting",
|
|
5659
|
+
text: "Reconnecting",
|
|
5660
|
+
bg: "warning100",
|
|
5661
|
+
fg: "warning700"
|
|
5662
|
+
},
|
|
5663
|
+
offline: { key: "editor.collab.status.offline", text: "Offline", bg: "danger100", fg: "danger700" },
|
|
4416
5664
|
denied: {
|
|
4417
5665
|
key: "editor.collab.status.denied",
|
|
4418
5666
|
text: "Live editing unavailable",
|
|
@@ -4445,6 +5693,11 @@ const EditorToolbar = ({
|
|
|
4445
5693
|
}) => {
|
|
4446
5694
|
const status = STATUS[collaboration.status];
|
|
4447
5695
|
const peers = collaboration.peers || [];
|
|
5696
|
+
const upgrade = collaboration.status === "error" && collaboration.error === "UPGRADE_REQUIRED";
|
|
5697
|
+
const peerLabel = (peer) => {
|
|
5698
|
+
const base = peer.canEdit ? peer.name : t("editor.collab.viewer", "{name} (viewing)", { name: peer.name });
|
|
5699
|
+
return peer.idle ? t("editor.collab.away", "{name} (away)", { name: base }) : base;
|
|
5700
|
+
};
|
|
4448
5701
|
return /* @__PURE__ */ jsxs(
|
|
4449
5702
|
Bar,
|
|
4450
5703
|
{
|
|
@@ -4499,24 +5752,31 @@ const EditorToolbar = ({
|
|
|
4499
5752
|
)
|
|
4500
5753
|
] }),
|
|
4501
5754
|
/* @__PURE__ */ jsxs(Flex, { gap: 3, wrap: "wrap", justifyContent: "flex-end", minWidth: 0, children: [
|
|
4502
|
-
status ? /* @__PURE__ */ jsxs(Flex, { gap: 2,
|
|
4503
|
-
peers.length > 0 ? /* @__PURE__ */ jsx(Avatar.Group, { children: peers.slice(0, 4).map((peer) => /* @__PURE__ */ jsx(
|
|
4504
|
-
|
|
5755
|
+
status ? /* @__PURE__ */ jsxs(Flex, { gap: 2, wrap: "wrap", children: [
|
|
5756
|
+
peers.length > 0 ? /* @__PURE__ */ jsx(Avatar.Group, { children: peers.slice(0, 4).map((peer) => /* @__PURE__ */ jsx(Tooltip, { label: peerLabel(peer), children: /* @__PURE__ */ jsx(
|
|
5757
|
+
Peer,
|
|
4505
5758
|
{
|
|
4506
|
-
|
|
4507
|
-
|
|
4508
|
-
|
|
4509
|
-
|
|
4510
|
-
)) }) : null,
|
|
4511
|
-
/* @__PURE__ */ jsx(Badge, { backgroundColor: status.bg, textColor: status.fg, children: t(status.key, status.text) }),
|
|
4512
|
-
collaboration.status === "live" && !collaboration.canEdit ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: t("editor.collab.readOnly", "View only") }) : null,
|
|
4513
|
-
/* @__PURE__ */ jsx(VisuallyHidden, { children: t(
|
|
4514
|
-
"editor.collab.peers",
|
|
4515
|
-
"{count, plural, =0 {Nobody else is editing} one {# other person is editing} other {# other people are editing}}",
|
|
4516
|
-
{
|
|
4517
|
-
count: peers.length
|
|
5759
|
+
$family: peerFamily(peer.color),
|
|
5760
|
+
$idle: peer.idle,
|
|
5761
|
+
fallback: initials(peer.name),
|
|
5762
|
+
"aria-label": peerLabel(peer)
|
|
4518
5763
|
}
|
|
4519
|
-
) })
|
|
5764
|
+
) }, peer.id)) }) : null,
|
|
5765
|
+
/* @__PURE__ */ jsx(Box, { "aria-live": "polite", "data-testid": "mex-collab-status", "data-status": collaboration.status, children: /* @__PURE__ */ jsx(Badge, { backgroundColor: status.bg, textColor: status.fg, children: t(status.key, status.text) }) }),
|
|
5766
|
+
peers.length > 4 ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: t("editor.collab.more", "+{count}", { count: peers.length - 4 }) }) : null,
|
|
5767
|
+
collaboration.status === "live" && !collaboration.canEdit ? /* @__PURE__ */ jsx(Badge, { backgroundColor: "neutral150", textColor: "neutral800", children: t("editor.collab.readOnly", "View only") }) : null,
|
|
5768
|
+
collaboration.pending && collaboration.status !== "live" ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: t("editor.collab.unsent", "Changes are kept and sent when the connection is back") }) : null,
|
|
5769
|
+
upgrade ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: t("editor.collab.upgrade", "Reload the page to keep editing live") }) : null,
|
|
5770
|
+
/* @__PURE__ */ jsxs(VisuallyHidden, { children: [
|
|
5771
|
+
peers.length > 0 ? `${peers.map(peerLabel).join(", ")}. ` : "",
|
|
5772
|
+
t(
|
|
5773
|
+
"editor.collab.peers",
|
|
5774
|
+
"{count, plural, =0 {Nobody else is editing} one {# other person is editing} other {# other people are editing}}",
|
|
5775
|
+
{
|
|
5776
|
+
count: peers.length
|
|
5777
|
+
}
|
|
5778
|
+
)
|
|
5779
|
+
] })
|
|
4520
5780
|
] }) : null,
|
|
4521
5781
|
/* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: t(
|
|
4522
5782
|
"editor.stats",
|
|
@@ -4877,8 +6137,25 @@ const AiDialog = ({ t, request, config, onApply, onClose }) => {
|
|
|
4877
6137
|
] })
|
|
4878
6138
|
] }) });
|
|
4879
6139
|
};
|
|
6140
|
+
const usePresenceAnnouncements = (peers, t) => {
|
|
6141
|
+
const [previous, setPrevious] = useState(peers);
|
|
6142
|
+
const [message, setMessage] = useState("");
|
|
6143
|
+
if (peers !== previous) {
|
|
6144
|
+
const before = new Map((previous || []).map((peer) => [peer.id, peer.name]));
|
|
6145
|
+
const current = new Map((peers || []).map((peer) => [peer.id, peer.name]));
|
|
6146
|
+
const joined = [...current.keys()].filter((id) => !before.has(id)).map((id) => current.get(id));
|
|
6147
|
+
const left = [...before.keys()].filter((id) => !current.has(id)).map((id) => before.get(id));
|
|
6148
|
+
const parts = [];
|
|
6149
|
+
if (joined.length) parts.push(t("editor.collab.joined", "{names} joined", { names: joined.join(", ") }));
|
|
6150
|
+
if (left.length) parts.push(t("editor.collab.left", "{names} left", { names: left.join(", ") }));
|
|
6151
|
+
setPrevious(peers);
|
|
6152
|
+
if (parts.length) setMessage(parts.join(". "));
|
|
6153
|
+
}
|
|
6154
|
+
return message;
|
|
6155
|
+
};
|
|
4880
6156
|
const SAVE_DEBOUNCE_MS = 150;
|
|
4881
6157
|
const EditorStyles = createGlobalStyle`${editorStyles}`;
|
|
6158
|
+
const SETTINGS_PATH = "/settings/magic-editor-x/configuration";
|
|
4882
6159
|
const Frame = styled(Box)`
|
|
4883
6160
|
min-width: 0;
|
|
4884
6161
|
border: 1px solid ${({ theme, $error }) => $error ? theme.colors.danger600 : theme.colors.neutral200};
|
|
@@ -4899,6 +6176,11 @@ const Frame = styled(Box)`
|
|
|
4899
6176
|
overflow: hidden;
|
|
4900
6177
|
` : ""}
|
|
4901
6178
|
`;
|
|
6179
|
+
const EditorArea = styled.div`
|
|
6180
|
+
position: relative;
|
|
6181
|
+
min-width: 0;
|
|
6182
|
+
${({ $fullscreen }) => $fullscreen ? "flex: 1 1 auto; display: flex; flex-direction: column; min-height: 0;" : ""}
|
|
6183
|
+
`;
|
|
4902
6184
|
const Holder = styled.div`
|
|
4903
6185
|
min-width: 0;
|
|
4904
6186
|
padding: ${({ theme }) => `${theme.spaces[4]} ${theme.spaces[3]}`};
|
|
@@ -4932,6 +6214,12 @@ const EditorField = ({
|
|
|
4932
6214
|
const MediaLibraryDialog = useStrapiApp("MagicEditorX", (state) => state.components["media-library"]);
|
|
4933
6215
|
const { config, customBlocks, error: configError, loading: configLoading, retry } = useEditorConfig();
|
|
4934
6216
|
const target = useFieldTarget(name);
|
|
6217
|
+
const navigate = useNavigate();
|
|
6218
|
+
const settingsHref = useHref(SETTINGS_PATH);
|
|
6219
|
+
const contentLocaleRef = useRef(target.locale);
|
|
6220
|
+
useEffect(() => {
|
|
6221
|
+
contentLocaleRef.current = target.locale;
|
|
6222
|
+
}, [target.locale]);
|
|
4935
6223
|
const t = useCallback(
|
|
4936
6224
|
(id, defaultMessage, values) => formatMessage({ id: getTranslation(id), defaultMessage }, values),
|
|
4937
6225
|
[formatMessage]
|
|
@@ -4948,6 +6236,10 @@ const EditorField = ({
|
|
|
4948
6236
|
const pendingLocalRef = useRef(false);
|
|
4949
6237
|
const syncedOnceRef = useRef(false);
|
|
4950
6238
|
const historyButtonRef = useRef(null);
|
|
6239
|
+
const areaRef = useRef(null);
|
|
6240
|
+
const remoteCacheRef = useRef(/* @__PURE__ */ new WeakMap());
|
|
6241
|
+
const userTouchedRef = useRef(false);
|
|
6242
|
+
const [contentVersion, setContentVersion] = useState(0);
|
|
4951
6243
|
const onChangeRef = useRef(onChange);
|
|
4952
6244
|
const [ready, setReady] = useState(false);
|
|
4953
6245
|
const [stats, setStats] = useState({ blocks: 0, words: 0, characters: 0 });
|
|
@@ -4965,7 +6257,7 @@ const EditorField = ({
|
|
|
4965
6257
|
const permissions = config && config.permissions || {};
|
|
4966
6258
|
const collaborationTarget = config && config.collaboration.enabled && permissions.collaborate && target.uid && target.documentId ? target : null;
|
|
4967
6259
|
const emit = useCallback(
|
|
4968
|
-
(data) => {
|
|
6260
|
+
(data, { baselineOnly = false } = {}) => {
|
|
4969
6261
|
const meaningful = data && Array.isArray(data.blocks) && data.blocks.some(
|
|
4970
6262
|
(block) => block.type !== "paragraph" || String(block.data && block.data.text || "").replace(/<br\s*\/?>| |\s/g, "") !== ""
|
|
4971
6263
|
);
|
|
@@ -4974,6 +6266,7 @@ const EditorField = ({
|
|
|
4974
6266
|
if (key === lastEmittedRawRef.current) return;
|
|
4975
6267
|
lastEmittedRawRef.current = key;
|
|
4976
6268
|
lastEmittedRef.current = renderedKey(next);
|
|
6269
|
+
if (baselineOnly) return;
|
|
4977
6270
|
onChangeRef.current(name, next ? JSON.parse(JSON.stringify(next)) : null);
|
|
4978
6271
|
},
|
|
4979
6272
|
[name]
|
|
@@ -4991,6 +6284,11 @@ const EditorField = ({
|
|
|
4991
6284
|
const data = await editor.save();
|
|
4992
6285
|
rememberBlocks(knownRef.current, data);
|
|
4993
6286
|
setStats(computeStats(data));
|
|
6287
|
+
setContentVersion((version) => version + 1);
|
|
6288
|
+
if (!userTouchedRef.current) {
|
|
6289
|
+
emit(data, { baselineOnly: true });
|
|
6290
|
+
return;
|
|
6291
|
+
}
|
|
4994
6292
|
emit(data);
|
|
4995
6293
|
if (collabRef.current) collabRef.current.pushLocal(data);
|
|
4996
6294
|
if (undoRef.current) undoRef.current.record();
|
|
@@ -5037,12 +6335,18 @@ const EditorField = ({
|
|
|
5037
6335
|
}
|
|
5038
6336
|
if (!["Shift", "Control", "Alt", "Meta"].includes(event.key)) leaveArmed = false;
|
|
5039
6337
|
};
|
|
6338
|
+
const onTouch = () => {
|
|
6339
|
+
userTouchedRef.current = true;
|
|
6340
|
+
};
|
|
6341
|
+
const touchEvents = ["pointerdown", "keydown", "input", "paste", "drop"];
|
|
6342
|
+
touchEvents.forEach((type) => holder.addEventListener(type, onTouch, true));
|
|
5040
6343
|
window.addEventListener("keydown", onKeyDown, true);
|
|
5041
6344
|
holder.addEventListener("focusout", onFocusOut);
|
|
5042
6345
|
holder.addEventListener("input", onInput);
|
|
5043
6346
|
holder.addEventListener("click", onClick);
|
|
5044
6347
|
holder.addEventListener("keyup", onKeyUp);
|
|
5045
6348
|
return () => {
|
|
6349
|
+
touchEvents.forEach((type) => holder.removeEventListener(type, onTouch, true));
|
|
5046
6350
|
holder.removeEventListener("click", onClick);
|
|
5047
6351
|
holder.removeEventListener("keyup", onKeyUp);
|
|
5048
6352
|
holder.removeEventListener("focusout", onFocusOut);
|
|
@@ -5059,6 +6363,7 @@ const EditorField = ({
|
|
|
5059
6363
|
try {
|
|
5060
6364
|
await applyToEditor(editor, data || { blocks: [] }, knownRef.current);
|
|
5061
6365
|
setStats(computeStats(data));
|
|
6366
|
+
setContentVersion((version) => version + 1);
|
|
5062
6367
|
if (emitToForm) emit(data);
|
|
5063
6368
|
else {
|
|
5064
6369
|
const shown = data && data.blocks && data.blocks.length ? data : null;
|
|
@@ -5099,19 +6404,37 @@ const EditorField = ({
|
|
|
5099
6404
|
},
|
|
5100
6405
|
onRemoteData: async () => {
|
|
5101
6406
|
const client = collabRef.current;
|
|
5102
|
-
|
|
6407
|
+
const editor = editorRef.current;
|
|
6408
|
+
if (!client || !editor) return;
|
|
5103
6409
|
await flushLocal(client);
|
|
5104
|
-
const
|
|
6410
|
+
const { data, catchUp } = client.snapshot();
|
|
6411
|
+
const own = new Set(
|
|
6412
|
+
data.blocks.filter((block) => knownRef.current.get(block.id) === blockKey(block)).map((b) => b.id)
|
|
6413
|
+
);
|
|
6414
|
+
const shared = prepareRemoteData(data, remoteCacheRef.current);
|
|
6415
|
+
shared.blocks.forEach((block) => {
|
|
6416
|
+
if (own.has(block.id)) knownRef.current.set(block.id, blockKey(block));
|
|
6417
|
+
});
|
|
5105
6418
|
const first = !syncedOnceRef.current;
|
|
5106
6419
|
syncedOnceRef.current = true;
|
|
5107
6420
|
await applyExternal(shared, { emitToForm: !first });
|
|
5108
|
-
|
|
6421
|
+
const shown = await editor.save().catch(() => null);
|
|
6422
|
+
client.markShown(catchUp, shown || shared);
|
|
5109
6423
|
}
|
|
5110
6424
|
});
|
|
5111
6425
|
useEffect(() => {
|
|
5112
6426
|
collabRef.current = collaboration.client;
|
|
5113
6427
|
}, [collaboration.client]);
|
|
5114
6428
|
const readOnly = Boolean(disabled) || collaboration.status === "live" && !collaboration.canEdit;
|
|
6429
|
+
const collabUndo = collaboration.active && collaboration.client && collaboration.canEdit;
|
|
6430
|
+
useEffect(() => {
|
|
6431
|
+
if (!ready || !undoRef.current) return void 0;
|
|
6432
|
+
undoRef.current.setDelegate(collabUndo ? collaboration.client : null);
|
|
6433
|
+
return () => {
|
|
6434
|
+
if (undoRef.current) undoRef.current.setDelegate(null);
|
|
6435
|
+
};
|
|
6436
|
+
}, [ready, collabUndo, collaboration.client]);
|
|
6437
|
+
const announcement = usePresenceAnnouncements(collaboration.peers, t);
|
|
5115
6438
|
const upload = useCallback(
|
|
5116
6439
|
async (path, field2, file) => {
|
|
5117
6440
|
const body = new FormData();
|
|
@@ -5164,6 +6487,11 @@ const EditorField = ({
|
|
|
5164
6487
|
setStats(computeStats(initial));
|
|
5165
6488
|
let destroyed = false;
|
|
5166
6489
|
let dragDrop = null;
|
|
6490
|
+
const cspGuard = createCspGuard(holderRef.current, {
|
|
6491
|
+
t,
|
|
6492
|
+
settingsHref: permissions.settingsRead ? settingsHref : null,
|
|
6493
|
+
onOpenSettings: () => navigate(SETTINGS_PATH)
|
|
6494
|
+
});
|
|
5167
6495
|
const editor = new EditorJS({
|
|
5168
6496
|
holder: holderRef.current,
|
|
5169
6497
|
data: initial || void 0,
|
|
@@ -5176,6 +6504,7 @@ const EditorField = ({
|
|
|
5176
6504
|
tools: buildTools({
|
|
5177
6505
|
t,
|
|
5178
6506
|
fetchClient: { get, post },
|
|
6507
|
+
getContentLocale: () => contentLocaleRef.current,
|
|
5179
6508
|
uploadImage: (file) => upload(API.imageByFile, "image", file),
|
|
5180
6509
|
uploadImageByUrl,
|
|
5181
6510
|
uploadFile: (file) => upload(API.fileUpload, "file", file),
|
|
@@ -5202,6 +6531,7 @@ const EditorField = ({
|
|
|
5202
6531
|
});
|
|
5203
6532
|
return () => {
|
|
5204
6533
|
destroyed = true;
|
|
6534
|
+
cspGuard.destroy();
|
|
5205
6535
|
clearTimeout(saveTimerRef.current);
|
|
5206
6536
|
setReady(false);
|
|
5207
6537
|
if (undoRef.current) undoRef.current.destroy();
|
|
@@ -5252,7 +6582,18 @@ const EditorField = ({
|
|
|
5252
6582
|
return;
|
|
5253
6583
|
const index = editor.blocks.getCurrentBlockIndex();
|
|
5254
6584
|
const block = index >= 0 ? editor.blocks.getBlockByIndex(index) : null;
|
|
5255
|
-
|
|
6585
|
+
const content = block && block.holder && (block.holder.querySelector(".ce-block__content") || block.holder);
|
|
6586
|
+
if (!block || !content) {
|
|
6587
|
+
collaboration.client.sendCursor(null);
|
|
6588
|
+
return;
|
|
6589
|
+
}
|
|
6590
|
+
const anchor = offsetOf(content, selection.anchorNode, selection.anchorOffset);
|
|
6591
|
+
const focus = offsetOf(content, selection.focusNode, selection.focusOffset);
|
|
6592
|
+
collaboration.client.sendCursor({
|
|
6593
|
+
blockId: block.id,
|
|
6594
|
+
anchor: anchor ?? 0,
|
|
6595
|
+
focus: focus ?? anchor ?? 0
|
|
6596
|
+
});
|
|
5256
6597
|
}, 120);
|
|
5257
6598
|
};
|
|
5258
6599
|
document.addEventListener("selectionchange", onSelection);
|
|
@@ -5328,7 +6669,11 @@ const EditorField = ({
|
|
|
5328
6669
|
const prepared = prepareEditorValue(content);
|
|
5329
6670
|
if (!prepared.data) return false;
|
|
5330
6671
|
await applyExternal(prepared.data, { emitToForm: true });
|
|
5331
|
-
if (collabRef.current
|
|
6672
|
+
if (collabRef.current && editorRef.current) {
|
|
6673
|
+
const shown = await editorRef.current.save().catch(() => prepared.data);
|
|
6674
|
+
collabRef.current.stopCapturing();
|
|
6675
|
+
collabRef.current.pushLocal(shown);
|
|
6676
|
+
}
|
|
5332
6677
|
if (undoRef.current) undoRef.current.record();
|
|
5333
6678
|
return true;
|
|
5334
6679
|
},
|
|
@@ -5386,8 +6731,8 @@ const EditorField = ({
|
|
|
5386
6731
|
readOnly,
|
|
5387
6732
|
fullscreen,
|
|
5388
6733
|
onToggleFullscreen: () => setFullscreen((value2) => !value2),
|
|
5389
|
-
canUndo: undoState.canUndo,
|
|
5390
|
-
canRedo: undoState.canRedo,
|
|
6734
|
+
canUndo: collabUndo ? collaboration.canUndo : undoState.canUndo,
|
|
6735
|
+
canRedo: collabUndo ? collaboration.canRedo : undoState.canRedo,
|
|
5391
6736
|
onUndo: () => undoRef.current && undoRef.current.undo(),
|
|
5392
6737
|
onRedo: () => undoRef.current && undoRef.current.redo(),
|
|
5393
6738
|
historyAvailable: Boolean(target.uid && target.documentId),
|
|
@@ -5402,18 +6747,31 @@ const EditorField = ({
|
|
|
5402
6747
|
/* @__PURE__ */ jsx(Button, { variant: "secondary", onClick: retry, children: t("editor.config.retry", "Try again") })
|
|
5403
6748
|
] }) : null,
|
|
5404
6749
|
configLoading ? /* @__PURE__ */ jsx(Flex, { padding: 4, justifyContent: "center", children: /* @__PURE__ */ jsx(Loader, { small: true, children: t("editor.loading", "Loading the editor") }) }) : null,
|
|
5405
|
-
/* @__PURE__ */
|
|
5406
|
-
|
|
5407
|
-
|
|
5408
|
-
|
|
5409
|
-
|
|
5410
|
-
|
|
5411
|
-
|
|
5412
|
-
|
|
5413
|
-
|
|
5414
|
-
|
|
5415
|
-
|
|
5416
|
-
|
|
6750
|
+
/* @__PURE__ */ jsxs(EditorArea, { ref: areaRef, $fullscreen: fullscreen, children: [
|
|
6751
|
+
/* @__PURE__ */ jsx(
|
|
6752
|
+
Holder,
|
|
6753
|
+
{
|
|
6754
|
+
ref: holderRef,
|
|
6755
|
+
className: "mex-editor",
|
|
6756
|
+
$minHeight: minHeight,
|
|
6757
|
+
$fullscreen: fullscreen,
|
|
6758
|
+
"data-testid": "magic-editor-x",
|
|
6759
|
+
"aria-busy": !ready,
|
|
6760
|
+
"aria-describedby": `${name}-mex-keyboard`
|
|
6761
|
+
}
|
|
6762
|
+
),
|
|
6763
|
+
collaboration.active && collaboration.peers.length > 0 ? /* @__PURE__ */ jsx(
|
|
6764
|
+
RemoteCarets,
|
|
6765
|
+
{
|
|
6766
|
+
containerRef: areaRef,
|
|
6767
|
+
holderRef,
|
|
6768
|
+
peers: collaboration.peers,
|
|
6769
|
+
version: contentVersion,
|
|
6770
|
+
t
|
|
6771
|
+
}
|
|
6772
|
+
) : null
|
|
6773
|
+
] }),
|
|
6774
|
+
/* @__PURE__ */ jsx(VisuallyHidden, { "aria-live": "polite", "aria-atomic": "true", children: announcement }),
|
|
5417
6775
|
/* @__PURE__ */ jsx(VisuallyHidden, { id: `${name}-mex-keyboard`, children: t(
|
|
5418
6776
|
"editor.keyboard",
|
|
5419
6777
|
"Press Tab in an empty block to choose a block type. Press Escape, then Tab, to leave the editor."
|