@capacms/sdk 1.0.0-next.10 → 1.0.0-next.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/CHANGELOG.md +170 -0
  2. package/README.md +368 -5
  3. package/bin/capa-check-bundle.js +80 -0
  4. package/bin/capa.js +3 -3
  5. package/bin/graphql-project.js +1 -1
  6. package/dist/client.d.ts +84 -4
  7. package/dist/client.js +23 -5
  8. package/dist/esm/image/index.d.ts +69 -2
  9. package/dist/esm/image/index.js +108 -5
  10. package/dist/esm/image/shared-params.generated.d.ts +126 -2
  11. package/dist/esm/image/shared-params.generated.js +224 -5
  12. package/dist/esm/overlay/index.d.ts +4 -1
  13. package/dist/esm/overlay/index.js +382 -30
  14. package/dist/esm/overlay/live-fields.d.ts +133 -0
  15. package/dist/esm/overlay/live-fields.js +478 -0
  16. package/dist/esm/overlay/markdown.d.ts +38 -0
  17. package/dist/esm/overlay/markdown.js +536 -0
  18. package/dist/esm/overlay/protocol.d.ts +51 -5
  19. package/dist/esm/overlay/protocol.js +79 -9
  20. package/dist/image/index.d.ts +69 -2
  21. package/dist/image/index.js +109 -4
  22. package/dist/image/shared-params.generated.d.ts +126 -2
  23. package/dist/image/shared-params.generated.js +235 -6
  24. package/dist/index.d.ts +1 -1
  25. package/dist/next/attrs.d.ts +42 -1
  26. package/dist/next/attrs.js +42 -3
  27. package/dist/next/client.d.ts +48 -1
  28. package/dist/next/client.js +33 -2
  29. package/dist/next/entry-fields.d.ts +43 -2
  30. package/dist/next/graphql/request.d.ts +4 -0
  31. package/dist/next/graphql/request.js +4 -0
  32. package/dist/next/graphql/tree.js +9 -0
  33. package/dist/next/index.d.ts +4 -4
  34. package/dist/next/index.js +3 -1
  35. package/dist/nextjs/index.d.ts +91 -7
  36. package/dist/nextjs/index.js +230 -17
  37. package/dist/nextjs/write-key-guard.d.ts +117 -0
  38. package/dist/nextjs/write-key-guard.js +285 -0
  39. package/dist/overlay/index.d.ts +4 -1
  40. package/dist/overlay/index.js +399 -29
  41. package/dist/overlay/live-fields.d.ts +133 -0
  42. package/dist/overlay/live-fields.js +493 -0
  43. package/dist/overlay/markdown.d.ts +38 -0
  44. package/dist/overlay/markdown.js +539 -0
  45. package/dist/overlay/protocol.d.ts +51 -5
  46. package/dist/overlay/protocol.js +82 -9
  47. package/dist/server/browser.d.ts +1 -0
  48. package/dist/server/browser.js +20 -0
  49. package/dist/server/client.d.ts +268 -0
  50. package/dist/server/client.js +335 -0
  51. package/dist/server/errors.d.ts +60 -0
  52. package/dist/server/errors.js +120 -0
  53. package/dist/server/index.d.ts +14 -0
  54. package/dist/server/index.js +32 -0
  55. package/dist/server/key-format.d.ts +41 -0
  56. package/dist/server/key-format.js +91 -0
  57. package/dist/server/transport.d.ts +47 -0
  58. package/dist/server/transport.js +114 -0
  59. package/dist/webhooks.d.ts +8 -0
  60. package/package.json +18 -4
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.REFRESH_TIMEOUT_MS = exports.SITE_SOURCE = exports.SITE_FEATURES = exports.PROTOCOL_VERSION = exports.PATCH_MAX_LENGTH = exports.PATCH_MAX_FIELDS = exports.ADMIN_SOURCE = exports.visibleMessage = exports.textAround = exports.selectMessage = exports.scrollEdge = exports.readyMessage = exports.pickCentred = exports.patchedText = exports.normaliseOrigins = exports.hoverMessage = exports.acceptMessage = void 0;
3
+ exports.REFRESH_TIMEOUT_MS = exports.renderMarkdown = exports.FIELDS_MAX_LENGTH = exports.FIELDS_MAX_FIELDS = exports.swapImageUrl = exports.swapDatetime = exports.sanitizeHtml = exports.safeImageUrl = exports.safeHref = exports.richTextHtml = exports.preparedHtml = exports.parseHtml = exports.formatDateAs = exports.findDateFormat = exports.canonicalHtml = exports.acceptLiveFields = exports.SITE_SOURCE = exports.SITE_FEATURES = exports.PROTOCOL_VERSION = exports.PATCH_MAX_LENGTH = exports.PATCH_MAX_FIELDS = exports.ADMIN_SOURCE = exports.visibleMessage = exports.textAround = exports.selectMessage = exports.scrollEdge = exports.readyMessage = exports.pickCentred = exports.patchedText = exports.normaliseOrigins = exports.itemMatches = exports.itemLabel = exports.isItemPath = exports.hoverMessage = exports.acceptMessage = void 0;
4
4
  exports.startOverlay = startOverlay;
5
5
  /**
6
6
  * `@capacms/sdk/overlay`: the site half of Capa's live preview.
@@ -10,21 +10,28 @@ exports.startOverlay = startOverlay;
10
10
  *
11
11
  * Inside the Capa editor's preview frame this outlines the element an editor is
12
12
  * working on, reports clicks on tagged elements back to the editor, shows the
13
- * text being typed in the elements that show it verbatim, and re-renders the
14
- * draft after a save. Outside a frame it does nothing at all:
13
+ * text being typed in the elements that show it verbatim (and unsaved rich
14
+ * text, images, toggles and dates where the page shows them as saved, and
15
+ * Rich Text in the element tagged with it, `./live-fields.ts`), and
16
+ * re-renders the draft after a save. Outside a frame it does nothing at all:
15
17
  * no listeners, no DOM, no cost.
16
18
  *
17
- * A click on a tagged element selects its field. A ⌘-click (Ctrl-click on
19
+ * A click on a tagged element selects its field, and the item of a list it
20
+ * stands for when the site tagged one (`data-capa-item`). A ⌘-click (Ctrl-click on
18
21
  * Windows and Linux) on a tagged element that is a link, or sits inside one,
19
22
  * follows the link in the frame instead, so an editor can move between pages.
20
23
  *
21
- * Vanilla DOM and no imports beyond the pure protocol module, so it works in
24
+ * Vanilla DOM and no imports beyond the pure protocol modules, so it works in
22
25
  * any framework and adds nothing to a bundle that does not call it.
23
26
  */
24
27
  const protocol_js_1 = require("./protocol.js");
28
+ const live_fields_js_1 = require("./live-fields.js");
25
29
  var protocol_js_2 = require("./protocol.js");
26
30
  Object.defineProperty(exports, "acceptMessage", { enumerable: true, get: function () { return protocol_js_2.acceptMessage; } });
27
31
  Object.defineProperty(exports, "hoverMessage", { enumerable: true, get: function () { return protocol_js_2.hoverMessage; } });
32
+ Object.defineProperty(exports, "isItemPath", { enumerable: true, get: function () { return protocol_js_2.isItemPath; } });
33
+ Object.defineProperty(exports, "itemLabel", { enumerable: true, get: function () { return protocol_js_2.itemLabel; } });
34
+ Object.defineProperty(exports, "itemMatches", { enumerable: true, get: function () { return protocol_js_2.itemMatches; } });
28
35
  Object.defineProperty(exports, "normaliseOrigins", { enumerable: true, get: function () { return protocol_js_2.normaliseOrigins; } });
29
36
  Object.defineProperty(exports, "patchedText", { enumerable: true, get: function () { return protocol_js_2.patchedText; } });
30
37
  Object.defineProperty(exports, "pickCentred", { enumerable: true, get: function () { return protocol_js_2.pickCentred; } });
@@ -39,6 +46,23 @@ Object.defineProperty(exports, "PATCH_MAX_LENGTH", { enumerable: true, get: func
39
46
  Object.defineProperty(exports, "PROTOCOL_VERSION", { enumerable: true, get: function () { return protocol_js_2.PROTOCOL_VERSION; } });
40
47
  Object.defineProperty(exports, "SITE_FEATURES", { enumerable: true, get: function () { return protocol_js_2.SITE_FEATURES; } });
41
48
  Object.defineProperty(exports, "SITE_SOURCE", { enumerable: true, get: function () { return protocol_js_2.SITE_SOURCE; } });
49
+ var live_fields_js_2 = require("./live-fields.js");
50
+ Object.defineProperty(exports, "acceptLiveFields", { enumerable: true, get: function () { return live_fields_js_2.acceptLiveFields; } });
51
+ Object.defineProperty(exports, "canonicalHtml", { enumerable: true, get: function () { return live_fields_js_2.canonicalHtml; } });
52
+ Object.defineProperty(exports, "findDateFormat", { enumerable: true, get: function () { return live_fields_js_2.findDateFormat; } });
53
+ Object.defineProperty(exports, "formatDateAs", { enumerable: true, get: function () { return live_fields_js_2.formatDateAs; } });
54
+ Object.defineProperty(exports, "parseHtml", { enumerable: true, get: function () { return live_fields_js_2.parseHtml; } });
55
+ Object.defineProperty(exports, "preparedHtml", { enumerable: true, get: function () { return live_fields_js_2.preparedHtml; } });
56
+ Object.defineProperty(exports, "richTextHtml", { enumerable: true, get: function () { return live_fields_js_2.richTextHtml; } });
57
+ Object.defineProperty(exports, "safeHref", { enumerable: true, get: function () { return live_fields_js_2.safeHref; } });
58
+ Object.defineProperty(exports, "safeImageUrl", { enumerable: true, get: function () { return live_fields_js_2.safeImageUrl; } });
59
+ Object.defineProperty(exports, "sanitizeHtml", { enumerable: true, get: function () { return live_fields_js_2.sanitizeHtml; } });
60
+ Object.defineProperty(exports, "swapDatetime", { enumerable: true, get: function () { return live_fields_js_2.swapDatetime; } });
61
+ Object.defineProperty(exports, "swapImageUrl", { enumerable: true, get: function () { return live_fields_js_2.swapImageUrl; } });
62
+ Object.defineProperty(exports, "FIELDS_MAX_FIELDS", { enumerable: true, get: function () { return live_fields_js_2.FIELDS_MAX_FIELDS; } });
63
+ Object.defineProperty(exports, "FIELDS_MAX_LENGTH", { enumerable: true, get: function () { return live_fields_js_2.FIELDS_MAX_LENGTH; } });
64
+ var markdown_js_1 = require("./markdown.js");
65
+ Object.defineProperty(exports, "renderMarkdown", { enumerable: true, get: function () { return markdown_js_1.renderMarkdown; } });
42
66
  const BLUE = "#2563eb";
43
67
  const TAGGED = "[data-capa-entry][data-capa-field]";
44
68
  /** What a ⌘-click on a tagged element follows when it sits in one. */
@@ -138,6 +162,19 @@ function createOverlay(initial) {
138
162
  const tagged = () => Array.from(document.querySelectorAll(TAGGED));
139
163
  const matching = (entryId, field) => tagged().filter((el) => el.getAttribute("data-capa-entry") === entryId &&
140
164
  (field === null || el.getAttribute("data-capa-field") === field));
165
+ /**
166
+ * The elements a highlight outlines: with an item, the ones tagged with it
167
+ * (or inside it), and the whole field when the page tags no such item.
168
+ */
169
+ const highlighted = (h) => {
170
+ const all = matching(h.entryId, h.field);
171
+ if (h.item === null)
172
+ return { els: all, item: null };
173
+ const items = all.filter((el) => (0, protocol_js_1.itemMatches)(el.getAttribute("data-capa-item"), h.item));
174
+ return items.length > 0 ? { els: items, item: h.item } : { els: all, item: null };
175
+ };
176
+ /** What a box's label says for a tagged element: its field, and its item when it has one. */
177
+ const labelOf = (el) => (0, protocol_js_1.itemLabel)(el.getAttribute("data-capa-field") ?? "", el.getAttribute("data-capa-item"));
141
178
  const box = (el, style, label) => {
142
179
  const rect = el.getBoundingClientRect();
143
180
  if (rect.width === 0 && rect.height === 0)
@@ -190,7 +227,8 @@ function createOverlay(initial) {
190
227
  }
191
228
  const target = ensureLayer();
192
229
  const boxes = [];
193
- const active = highlight ? matching(highlight.entryId, highlight.field) : [];
230
+ const shown = highlight ? highlighted(highlight) : { els: [], item: null };
231
+ const active = shown.els;
194
232
  if (outlineAll) {
195
233
  for (const el of tagged()) {
196
234
  if (active.includes(el))
@@ -203,13 +241,13 @@ function createOverlay(initial) {
203
241
  // Over a link, the label says how to follow it.
204
242
  const hint = hovered && hoveredLink ? ` · ${linkHint}` : "";
205
243
  if (hovered && hovered.isConnected && !active.includes(hovered)) {
206
- const b = box(hovered, "hover", `${hovered.getAttribute("data-capa-field") ?? ""}${hint}`);
244
+ const b = box(hovered, "hover", `${labelOf(hovered)}${hint}`);
207
245
  if (b)
208
246
  boxes.push(b);
209
247
  }
210
248
  active.forEach((el, i) => {
211
- const name = i === 0 ? (highlight?.field ?? "entry") : null;
212
- const label = el === hovered && hint ? `${name ?? el.getAttribute("data-capa-field") ?? ""}${hint}` : name;
249
+ const name = i === 0 ? (highlight?.field ? (0, protocol_js_1.itemLabel)(highlight.field, shown.item) : "entry") : null;
250
+ const label = el === hovered && hint ? `${name ?? labelOf(el)}${hint}` : name;
213
251
  const b = box(el, "active", label);
214
252
  if (b)
215
253
  boxes.push(b);
@@ -325,6 +363,11 @@ function createOverlay(initial) {
325
363
  * still pending after `refreshTimeout`, reloads from where the editor is.
326
364
  */
327
365
  const refresh = () => {
366
+ // The page re-renders from the saved draft: rich text this overlay
367
+ // replaced goes back first, so a framework finds its own nodes, and
368
+ // nothing changed before now is this overlay's to put back after.
369
+ restoreHtml();
370
+ liveGen++;
328
371
  const y = window.scrollY;
329
372
  const refreshFn = onRefresh;
330
373
  if (!refreshFn) {
@@ -394,28 +437,350 @@ function createOverlay(initial) {
394
437
  * they show the saved text or what this page last patched them to
395
438
  * (`patchedText`). As text, through a text node's `data`, never as markup.
396
439
  */
440
+ /** One element's text, patched by the text rule (`patchedText`). */
441
+ const patchElementText = (el, change) => {
442
+ let node = textNodeOf(el);
443
+ // An empty field shows as an empty element: it takes the first text.
444
+ if (!node && change.saved.trim() === "" && el.childNodes.length === 0) {
445
+ node = document.createTextNode("");
446
+ el.appendChild(node);
447
+ }
448
+ if (!node)
449
+ return;
450
+ const before = written.get(node);
451
+ const around = before ?? (0, protocol_js_1.textAround)(node.data);
452
+ const next = (0, protocol_js_1.patchedText)(node.data, change, before ? before.text : null, around);
453
+ if (next === null)
454
+ return;
455
+ node.data = next;
456
+ written.set(node, { text: change.value, lead: around.lead, trail: around.trail });
457
+ writtenIn.set(el, node);
458
+ };
397
459
  const applyPatch = (entryId, fields) => {
398
460
  for (const change of fields) {
399
- for (const el of matching(entryId, change.field)) {
400
- let node = textNodeOf(el);
401
- // An empty field shows as an empty element: it takes the first text.
402
- if (!node && change.saved.trim() === "" && el.childNodes.length === 0) {
403
- node = document.createTextNode("");
404
- el.appendChild(node);
405
- }
406
- if (!node)
407
- continue;
408
- const before = written.get(node);
409
- const around = before ?? (0, protocol_js_1.textAround)(node.data);
410
- const next = (0, protocol_js_1.patchedText)(node.data, change, before ? before.text : null, around);
411
- if (next === null)
461
+ for (const el of matching(entryId, change.field))
462
+ patchElementText(el, change);
463
+ }
464
+ // The boxes follow the text's new size.
465
+ render();
466
+ };
467
+ // ------------------------------- rich text, images, toggles and dates ---
468
+ /**
469
+ * What the overlay changed for a `fields` message, per element, to know its
470
+ * own work again and put the page back. A refresh starts a new generation:
471
+ * the page re-renders from the saved draft, and nothing from before it is
472
+ * this overlay's to put back.
473
+ */
474
+ let liveGen = 0;
475
+ const htmlState = new WeakMap();
476
+ /** The elements whose rich text this overlay replaced, put back before a refresh. */
477
+ const htmlPatched = new Set();
478
+ /** The element inside a tagged one whose rich text was replaced (`htmlTarget`). */
479
+ const htmlTargetOf = new WeakMap();
480
+ const imageState = new WeakMap();
481
+ const shownState = new WeakMap();
482
+ const datetimeState = new WeakMap();
483
+ const dateFormatOf = new WeakMap();
484
+ /** An element or text node as the sanitizer reads it. Comments and the rest are left out. */
485
+ const treeOf = (nodes) => {
486
+ const out = [];
487
+ for (const node of Array.from(nodes)) {
488
+ if (node.nodeType === 3)
489
+ out.push(node.data);
490
+ else if (node.nodeType === 1) {
491
+ const el = node;
492
+ out.push({
493
+ tag: el.localName,
494
+ attrs: el.getAttributeNames().map((name) => [name, el.getAttribute(name) ?? ""]),
495
+ children: treeOf(el.childNodes),
496
+ });
497
+ }
498
+ }
499
+ return out;
500
+ };
501
+ const canonicalOf = (el) => (0, live_fields_js_1.canonicalHtml)((0, live_fields_js_1.sanitizeHtml)(treeOf(el.childNodes)));
502
+ /** Sanitized nodes as page nodes, one `createElement` and `setAttribute` at a time: never markup. */
503
+ const build = (nodes) => nodes.map((node) => {
504
+ if (typeof node === "string")
505
+ return document.createTextNode(node);
506
+ const el = document.createElement(node.tag);
507
+ for (const [name, value] of node.attrs)
508
+ el.setAttribute(name, value);
509
+ for (const child of build(node.children))
510
+ el.appendChild(child);
511
+ return el;
512
+ });
513
+ /** The innermost element that still holds exactly the saved rich text: a wrapper the site put around it keeps its own markup. */
514
+ const htmlTarget = (el, saved) => {
515
+ let target = el;
516
+ for (;;) {
517
+ const kids = Array.from(target.childNodes).filter((c) => c.nodeType === 1 || (c.nodeType === 3 && c.data.trim() !== ""));
518
+ if (kids.length !== 1 || kids[0].nodeType !== 1 || canonicalOf(kids[0]) !== saved)
519
+ return target;
520
+ target = kids[0];
521
+ }
522
+ };
523
+ const applyHtml = (el, change) => {
524
+ const saved = (0, live_fields_js_1.preparedHtml)(change.saved);
525
+ const next = (0, live_fields_js_1.preparedHtml)(change.value);
526
+ if (!saved || !next)
527
+ return;
528
+ let target = htmlTargetOf.get(el) ?? el;
529
+ let state = htmlState.get(target);
530
+ if (!state || state.gen !== liveGen) {
531
+ state = undefined;
532
+ target = htmlTarget(el, saved.canonical);
533
+ }
534
+ if (state && canonicalOf(target) !== state.last) {
535
+ // The site drew it again: what is there now is the site's.
536
+ htmlState.delete(target);
537
+ htmlPatched.delete(target);
538
+ state = undefined;
539
+ }
540
+ if (!state && canonicalOf(target) !== saved.canonical)
541
+ return;
542
+ if (next.canonical === saved.canonical) {
543
+ if (state) {
544
+ target.replaceChildren(...state.originals);
545
+ htmlState.delete(target);
546
+ htmlPatched.delete(target);
547
+ }
548
+ return;
549
+ }
550
+ if (state && state.last === next.canonical)
551
+ return;
552
+ const originals = state ? state.originals : Array.from(target.childNodes);
553
+ target.replaceChildren(...build(next.nodes));
554
+ htmlState.set(target, { gen: liveGen, originals, last: next.canonical });
555
+ htmlPatched.add(target);
556
+ htmlTargetOf.set(el, target);
557
+ };
558
+ /** Wrappers a site puts around rendered markdown (`<div class="prose">`): the content goes inside them. */
559
+ const MARKDOWN_WRAPPERS = new Set(["div", "section", "article", "main"]);
560
+ /** Elements that hold text, not blocks: one paragraph goes in without its `<p>`, and more waits for the save. */
561
+ const PHRASING = new Set(["p", "h1", "h2", "h3", "h4", "h5", "h6", "span", "a", "strong", "em", "b", "i", "small", "label", "summary", "figcaption"]);
562
+ const BLOCKS = new Set(["p", "h1", "h2", "h3", "h4", "h5", "h6", "blockquote", "pre", "ol", "ul", "li", "hr"]);
563
+ /** The element the rendered markdown goes into: the tagged one, or the plain wrapper that is all it holds. */
564
+ const markdownTarget = (el) => {
565
+ let target = el;
566
+ for (let depth = 0; depth < 8; depth++) {
567
+ const kids = Array.from(target.childNodes).filter((c) => c.nodeType === 1 || (c.nodeType === 3 && c.data.trim() !== ""));
568
+ if (kids.length !== 1 || kids[0].nodeType !== 1)
569
+ return target;
570
+ const only = kids[0];
571
+ if (!MARKDOWN_WRAPPERS.has(only.localName) || only.hasAttribute("data-capa-field"))
572
+ return target;
573
+ target = only;
574
+ }
575
+ return target;
576
+ };
577
+ /** Sanitized nodes for an element that holds text only, or null when they are more than one paragraph. */
578
+ const inlineNodes = (nodes) => {
579
+ const kept = nodes.filter((n) => typeof n !== "string" || n.trim() !== "");
580
+ if (kept.length === 1 && typeof kept[0] !== "string" && kept[0].tag === "p")
581
+ return kept[0].children;
582
+ return nodes.every((n) => typeof n === "string" || !BLOCKS.has(n.tag)) ? [...nodes] : null;
583
+ };
584
+ /**
585
+ * Rich Text (markdown). The page shows the site's own rendering of the
586
+ * saved value, which the overlay cannot reproduce, so it does not look for
587
+ * it: the element tagged with the field gets the new value, rendered and
588
+ * sanitized like html (`richTextHtml`, `preparedHtml`), and goes back to
589
+ * the site's own nodes when the editor goes back to the saved value, or
590
+ * before a refresh. An element that is an item of a list, or that holds
591
+ * another field's tags, is left as it is.
592
+ */
593
+ const applyMarkdown = (el, change) => {
594
+ if (el.hasAttribute("data-capa-item"))
595
+ return;
596
+ let target = htmlTargetOf.get(el) ?? el;
597
+ let state = htmlState.get(target);
598
+ if (!state || state.gen !== liveGen) {
599
+ state = undefined;
600
+ target = markdownTarget(el);
601
+ }
602
+ if (state && canonicalOf(target) !== state.last) {
603
+ // The site drew it again: what is there now is the site's.
604
+ htmlState.delete(target);
605
+ htmlPatched.delete(target);
606
+ state = undefined;
607
+ }
608
+ if (change.value === change.saved) {
609
+ if (state) {
610
+ target.replaceChildren(...state.originals);
611
+ htmlState.delete(target);
612
+ htmlPatched.delete(target);
613
+ }
614
+ return;
615
+ }
616
+ if (!state && target.querySelectorAll("[data-capa-field]").length > 0)
617
+ return;
618
+ const next = (0, live_fields_js_1.preparedHtml)((0, live_fields_js_1.richTextHtml)(change.value));
619
+ if (!next)
620
+ return;
621
+ const nodes = PHRASING.has(target.localName) ? inlineNodes(next.nodes) : next.nodes;
622
+ if (!nodes)
623
+ return;
624
+ const canonical = (0, live_fields_js_1.canonicalHtml)(nodes);
625
+ if (state && state.last === canonical)
626
+ return;
627
+ const originals = state ? state.originals : Array.from(target.childNodes);
628
+ target.replaceChildren(...build(nodes));
629
+ htmlState.set(target, { gen: liveGen, originals, last: canonical });
630
+ htmlPatched.add(target);
631
+ htmlTargetOf.set(el, target);
632
+ };
633
+ /** Rich text this overlay replaced, put back: the site's own nodes are there when it re-renders. */
634
+ const restoreHtml = () => {
635
+ for (const el of htmlPatched) {
636
+ const state = htmlState.get(el);
637
+ if (state && canonicalOf(el) === state.last)
638
+ el.replaceChildren(...state.originals);
639
+ htmlState.delete(el);
640
+ }
641
+ htmlPatched.clear();
642
+ };
643
+ const IMAGE_ATTRS = ["src", "srcset", "alt", "hidden"];
644
+ const imageAttrs = (img) => Object.fromEntries(IMAGE_ATTRS.map((name) => [name, img.getAttribute(name)]));
645
+ const setImageAttrs = (img, attrs) => {
646
+ for (const name of IMAGE_ATTRS) {
647
+ const value = attrs[name];
648
+ if (value === null || value === undefined) {
649
+ if (img.hasAttribute(name))
650
+ img.removeAttribute(name);
651
+ }
652
+ else if (img.getAttribute(name) !== value)
653
+ img.setAttribute(name, value);
654
+ }
655
+ };
656
+ const sameImage = (a, b) => a === b || (a !== null && b !== null && a.url === b.url && a.alt === b.alt);
657
+ const applyImage = (el, change) => {
658
+ const images = [
659
+ ...(el.matches("img, source") ? [el] : []),
660
+ ...Array.from(el.querySelectorAll("img, source")),
661
+ ];
662
+ for (const img of images) {
663
+ let state = imageState.get(img);
664
+ if (state && state.gen !== liveGen)
665
+ state = undefined;
666
+ const now = imageAttrs(img);
667
+ if (state && IMAGE_ATTRS.some((name) => now[name] !== state.last[name]))
668
+ state = undefined;
669
+ const base = state ? state.orig : now;
670
+ if (sameImage(change.value, change.saved)) {
671
+ if (state)
672
+ setImageAttrs(img, state.orig);
673
+ imageState.delete(img);
674
+ continue;
675
+ }
676
+ const saved = change.saved;
677
+ if (!saved)
678
+ continue;
679
+ const shows = [base.src, base.srcset].some((v) => v !== null && (0, live_fields_js_1.swapImageUrl)(v, saved.url, saved.url) !== null);
680
+ if (!shows)
681
+ continue;
682
+ const out = { ...base };
683
+ if (change.value === null) {
684
+ out.hidden = "";
685
+ }
686
+ else {
687
+ const value = change.value;
688
+ out.src = base.src === null ? null : ((0, live_fields_js_1.swapImageUrl)(base.src, saved.url, value.url) ?? base.src);
689
+ out.srcset = base.srcset === null ? null : ((0, live_fields_js_1.swapImageUrl)(base.srcset, saved.url, value.url) ?? base.srcset);
690
+ if (out.src === base.src && out.srcset === base.srcset)
412
691
  continue;
413
- node.data = next;
414
- written.set(node, { text: change.value, lead: around.lead, trail: around.trail });
415
- writtenIn.set(el, node);
692
+ if (base.alt !== null && base.alt === saved.alt)
693
+ out.alt = value.alt;
694
+ }
695
+ setImageAttrs(img, out);
696
+ imageState.set(img, { gen: liveGen, orig: base, last: imageAttrs(img) });
697
+ }
698
+ };
699
+ const applyBoolean = (el, change) => {
700
+ const shownWhen = el.getAttribute("data-capa-shown-when");
701
+ if (shownWhen !== "true" && shownWhen !== "false") {
702
+ // Text that reads the saved value follows, as text.
703
+ patchElementText(el, change);
704
+ return;
705
+ }
706
+ let state = shownState.get(el);
707
+ if (state && state.gen !== liveGen)
708
+ state = undefined;
709
+ if (change.value === change.saved) {
710
+ if (state) {
711
+ if (state.hidden)
712
+ el.setAttribute("hidden", "");
713
+ else
714
+ el.removeAttribute("hidden");
715
+ }
716
+ shownState.delete(el);
717
+ return;
718
+ }
719
+ if (!state)
720
+ shownState.set(el, { gen: liveGen, hidden: el.hasAttribute("hidden") });
721
+ if (change.value === shownWhen)
722
+ el.removeAttribute("hidden");
723
+ else
724
+ el.setAttribute("hidden", "");
725
+ };
726
+ /** The page's locales, first, for a date the site printed in words. */
727
+ const pageLocales = () => [
728
+ document.documentElement?.getAttribute("lang") || undefined,
729
+ typeof navigator === "undefined" ? undefined : navigator.language,
730
+ "en-US",
731
+ "en-GB",
732
+ ];
733
+ const applyDate = (el, change) => {
734
+ // A <time datetime> with the saved day keeps its shape with the new one.
735
+ const times = [...(el.matches("time[datetime]") ? [el] : []), ...Array.from(el.querySelectorAll("time[datetime]"))];
736
+ for (const time of times) {
737
+ const current = time.getAttribute("datetime") ?? "";
738
+ let state = datetimeState.get(time);
739
+ if (state && (state.gen !== liveGen || current !== state.last))
740
+ state = undefined;
741
+ const base = state ? state.orig : current;
742
+ if (change.value === change.saved) {
743
+ if (state)
744
+ time.setAttribute("datetime", state.orig);
745
+ datetimeState.delete(time);
746
+ continue;
747
+ }
748
+ const next = (0, live_fields_js_1.swapDatetime)(base, change.saved, change.value);
749
+ if (next === null)
750
+ continue;
751
+ time.setAttribute("datetime", next);
752
+ datetimeState.set(time, { gen: liveGen, orig: base, last: next });
753
+ }
754
+ // The text, in the format the site printed the saved day in.
755
+ let format = dateFormatOf.get(el);
756
+ if (!format) {
757
+ const node = textNodeOf(el);
758
+ format = node ? ((0, live_fields_js_1.findDateFormat)(node.data, change.saved, pageLocales()) ?? undefined) : undefined;
759
+ if (!format)
760
+ return;
761
+ dateFormatOf.set(el, format);
762
+ }
763
+ const saved = (0, live_fields_js_1.formatDateAs)(format, change.saved);
764
+ const value = (0, live_fields_js_1.formatDateAs)(format, change.value);
765
+ if (saved === null || value === null)
766
+ return;
767
+ patchElementText(el, { value, saved });
768
+ };
769
+ const applyFields = (entryId, fields) => {
770
+ for (const change of fields) {
771
+ for (const el of matching(entryId, change.field)) {
772
+ if (change.kind === "html")
773
+ applyHtml(el, change);
774
+ else if (change.kind === "markdown")
775
+ applyMarkdown(el, change);
776
+ else if (change.kind === "image")
777
+ applyImage(el, change);
778
+ else if (change.kind === "boolean")
779
+ applyBoolean(el, change);
780
+ else
781
+ applyDate(el, change);
416
782
  }
417
783
  }
418
- // The boxes follow the text's new size.
419
784
  render();
420
785
  };
421
786
  // ------------------------------------------------------------ messages ---
@@ -436,8 +801,8 @@ function createOverlay(initial) {
436
801
  render();
437
802
  return;
438
803
  }
439
- highlight = { entryId: message.entryId, field: message.field };
440
- const first = matching(message.entryId, message.field)[0];
804
+ highlight = { entryId: message.entryId, field: message.field, item: message.item ?? null };
805
+ const first = highlighted(highlight).els[0];
441
806
  if (first)
442
807
  first.scrollIntoView({ block: "center", behavior: "smooth" });
443
808
  render();
@@ -456,6 +821,11 @@ function createOverlay(initial) {
456
821
  return;
457
822
  applyPatch(message.entryId, message.fields);
458
823
  return;
824
+ case "fields":
825
+ if (!adminOrigin || event.origin !== adminOrigin)
826
+ return;
827
+ applyFields(message.entryId, message.fields);
828
+ return;
459
829
  }
460
830
  };
461
831
  // --------------------------------------------------------- interaction ---
@@ -508,7 +878,7 @@ function createOverlay(initial) {
508
878
  follow(event);
509
879
  return;
510
880
  }
511
- post((0, protocol_js_1.selectMessage)(el.getAttribute("data-capa-entry") ?? "", el.getAttribute("data-capa-field") ?? ""));
881
+ post((0, protocol_js_1.selectMessage)(el.getAttribute("data-capa-entry") ?? "", el.getAttribute("data-capa-field") ?? "", el.getAttribute("data-capa-item")));
512
882
  };
513
883
  const updateHover = () => {
514
884
  hoverFrame = 0;
@@ -0,0 +1,133 @@
1
+ /**
2
+ * The `fields` message: unsaved rich text, images, toggles and dates, as an
3
+ * editor changes them, for the overlay to show before the save. Pure: no DOM,
4
+ * no globals, so it is tested under plain `node --test`. The overlay
5
+ * (`./index.ts`) does the DOM half. Its one import, `./markdown.js`, is pure
6
+ * too.
7
+ *
8
+ * admin -> site fields { entryId, fields: [{ field, kind, value, saved }] }
9
+ *
10
+ * kind "html" value, saved: the HTML field's HTML, as the editor stores it
11
+ * kind "markdown" value, saved: a Rich Text field's value: markdown source,
12
+ * or the HTML Capa's rich text editor writes into it
13
+ * kind "image" value, saved: { url, alt } | null
14
+ * kind "boolean" value, saved: "true" | "false"
15
+ * kind "date" value, saved: "YYYY-MM-DD" | ""
16
+ *
17
+ * Sent only to an overlay whose `ready` lists "fields" (`SITE_FEATURES`), and
18
+ * only where the project has the feature on, so an older overlay never gets
19
+ * one; it would drop an unknown type anyway.
20
+ *
21
+ * THE RULE IS THE TEXT PATCH'S: change only what the page drew from the saved
22
+ * value, exactly, so whatever the site does to a value on its own (a
23
+ * sanitizer, a date format, a resized image URL, markup around it) is either
24
+ * reproduced or left alone until the save re-renders it.
25
+ *
26
+ * html an element whose content IS the saved HTML (compared after the
27
+ * sanitizer below, whitespace aside) gets the new HTML, sanitized,
28
+ * built node by node, never through `innerHTML`.
29
+ * markdown the page shows the site's own rendering of the saved markdown,
30
+ * which nothing here can reproduce, so the element is found by
31
+ * its tag alone: the element `capaAttrs` tagged with the field
32
+ * gets the new value rendered (`richTextHtml`), then put through
33
+ * the same sanitizer as html. A page that tags no element for the
34
+ * field is left as it is.
35
+ * image an `<img>` or `<source>` whose `src` or `srcset` holds the saved
36
+ * image's URL gets the new one in its place, so the site's resize
37
+ * parameters stay; its `alt` follows while it reads the saved alt.
38
+ * boolean an element tagged `data-capa-shown-when` is shown while the value
39
+ * is that, and hidden otherwise; text that reads "true" or "false"
40
+ * follows as text.
41
+ * date text the site formatted from the saved day with a format this
42
+ * module can reproduce (`findDateFormat`) gets the new day in the
43
+ * same format, and a `<time datetime>` follows.
44
+ */
45
+ export type LiveKind = "html" | "markdown" | "image" | "boolean" | "date";
46
+ export interface LiveImage {
47
+ url: string;
48
+ alt: string;
49
+ }
50
+ export type LiveField = {
51
+ field: string;
52
+ kind: "html" | "markdown" | "boolean" | "date";
53
+ value: string;
54
+ saved: string;
55
+ } | {
56
+ field: string;
57
+ kind: "image";
58
+ value: LiveImage | null;
59
+ saved: LiveImage | null;
60
+ };
61
+ /** A `fields` message past these is refused whole, like a `patch`. */
62
+ export declare const FIELDS_MAX_FIELDS = 500;
63
+ export declare const FIELDS_MAX_LENGTH = 100000;
64
+ /** The fields of a `fields` message, checked, or null to refuse the message whole. */
65
+ export declare function acceptLiveFields(raw: unknown): LiveField[] | null;
66
+ /** An element of parsed or walked HTML. Attributes keep their order. */
67
+ export interface HtmlElement {
68
+ tag: string;
69
+ attrs: Array<[string, string]>;
70
+ children: HtmlNode[];
71
+ }
72
+ export type HtmlNode = HtmlElement | string;
73
+ /**
74
+ * The HTML as a tree, or null when it is not markup this module reads with
75
+ * confidence (an unclosed tag or comment, nesting deeper than 64). Strict on
76
+ * purpose: rich text from Capa's editor is well formed, and a value that is
77
+ * not is left for the save to show.
78
+ */
79
+ export declare function parseHtml(html: string): HtmlNode[] | null;
80
+ /** A link target the page may follow: http(s), mailto, tel, or a path or fragment on the site. */
81
+ export declare function safeHref(href: string): boolean;
82
+ /** An image address the page may load: an absolute http(s) URL. */
83
+ export declare function safeImageUrl(url: string): boolean;
84
+ /**
85
+ * Rich text cut down to what the editor makes: its blocks, its inline marks,
86
+ * links that go somewhere safe, http(s) images, Quill's `ql-` classes, and a
87
+ * colour. Scripts, frames, forms, embeds and every event handler are gone,
88
+ * with their content; any other element is unwrapped to its content.
89
+ */
90
+ export declare function sanitizeHtml(nodes: readonly HtmlNode[], depth?: number): HtmlNode[];
91
+ /**
92
+ * One string per tree, for "does this element show exactly the saved rich
93
+ * text": attributes sorted, text with its runs of whitespace as one space,
94
+ * and text that is only whitespace left out, since a template's indentation
95
+ * between blocks is not content.
96
+ */
97
+ export declare function canonicalHtml(nodes: readonly HtmlNode[]): string;
98
+ /** The saved or new rich text, parsed and sanitized, with its canonical form. Null for HTML `parseHtml` refuses. */
99
+ export declare function preparedHtml(html: string): {
100
+ nodes: HtmlNode[];
101
+ canonical: string;
102
+ } | null;
103
+ /**
104
+ * A Rich Text value as HTML for the sanitizer, the way the admin's editor
105
+ * reads it: HTML the editor wrote stays as it is, and markdown source is
106
+ * rendered (`renderMarkdown`). Never written to a page as it is: the overlay
107
+ * puts it through `preparedHtml` first.
108
+ */
109
+ export declare function richTextHtml(value: string): string;
110
+ /**
111
+ * An `src` or `srcset` with the saved image swapped for the new one, or null
112
+ * when it does not hold the saved image. The saved URL is looked for as it
113
+ * is and URL-encoded (`/_next/image?url=...`), then, when both images are on
114
+ * the same host, by path alone, so an image service on another host that
115
+ * keeps the file's path (`https://img.example/t/a.jpg?w=800`) is followed.
116
+ * Whatever the site added around it, a width or a format, stays.
117
+ */
118
+ export declare function swapImageUrl(attr: string, saved: string, value: string): string | null;
119
+ /**
120
+ * A day as a format prints it. `raw` is the stored day (`2026-11-01`), `iso`
121
+ * the instant the API sends (`2026-11-01T00:00:00.000Z`), and
122
+ * `intl:<locale>:<id>` an `Intl.DateTimeFormat` in UTC, which is the day as
123
+ * stored: a calendar day is kept at midnight UTC. "" for an empty day.
124
+ */
125
+ export declare function formatDateAs(format: string, value: string): string | null;
126
+ /**
127
+ * The format the site printed the saved day in, when `text` is exactly the
128
+ * saved day in one of them (`formatDateAs`), trying the page's locales in
129
+ * order. Null when none reproduces it, and the text is left for the save.
130
+ */
131
+ export declare function findDateFormat(text: string, saved: string, locales: ReadonlyArray<string | undefined>): string | null;
132
+ /** A `<time datetime>` with the saved day, in the same shape, or null when it is not the saved day. */
133
+ export declare function swapDatetime(datetime: string, saved: string, value: string): string | null;