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

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 (92) hide show
  1. package/CHANGELOG.md +450 -0
  2. package/README.md +1754 -156
  3. package/bin/capa-codegen.js +192 -5
  4. package/bin/capa.js +235 -0
  5. package/bin/graphql-project.js +142 -0
  6. package/bin/project-env.js +58 -0
  7. package/dist/client.d.ts +5 -0
  8. package/dist/client.js +17 -0
  9. package/dist/codegen.d.ts +55 -0
  10. package/dist/codegen.js +320 -39
  11. package/dist/config.d.ts +5 -36
  12. package/dist/config.js +47 -1
  13. package/dist/esm/image/index.d.ts +120 -0
  14. package/dist/esm/image/index.js +250 -0
  15. package/dist/esm/image/shared-params.generated.d.ts +190 -0
  16. package/dist/esm/image/shared-params.generated.js +461 -0
  17. package/dist/esm/nextjs/image-loader.d.ts +60 -0
  18. package/dist/esm/nextjs/image-loader.js +67 -0
  19. package/dist/esm/nextjs/overlay.d.ts +30 -0
  20. package/dist/esm/nextjs/overlay.js +75 -0
  21. package/dist/esm/overlay/index.d.ts +32 -0
  22. package/dist/esm/overlay/index.js +576 -0
  23. package/dist/esm/overlay/protocol.d.ts +187 -0
  24. package/dist/esm/overlay/protocol.js +240 -0
  25. package/dist/esm/package.json +4 -0
  26. package/dist/graphql-codegen.d.ts +117 -0
  27. package/dist/graphql-codegen.js +705 -0
  28. package/dist/http.js +1 -1
  29. package/dist/image/index.d.ts +120 -0
  30. package/dist/image/index.js +257 -0
  31. package/dist/image/shared-params.generated.d.ts +190 -0
  32. package/dist/image/shared-params.generated.js +471 -0
  33. package/dist/index.d.ts +2 -2
  34. package/dist/index.js +2 -1
  35. package/dist/next/attrs.d.ts +98 -0
  36. package/dist/next/attrs.js +125 -0
  37. package/dist/next/client.d.ts +176 -32
  38. package/dist/next/client.js +212 -90
  39. package/dist/next/entry-fields.d.ts +162 -0
  40. package/dist/next/entry-fields.js +2 -0
  41. package/dist/next/errors.d.ts +136 -0
  42. package/dist/next/errors.js +214 -0
  43. package/dist/next/field-names.d.ts +37 -0
  44. package/dist/next/field-names.js +145 -0
  45. package/dist/next/graphql/build.d.ts +27 -0
  46. package/dist/next/graphql/build.js +98 -0
  47. package/dist/next/graphql/documents.d.ts +67 -0
  48. package/dist/next/graphql/documents.js +35 -0
  49. package/dist/next/graphql/edit-mode.d.ts +16 -0
  50. package/dist/next/graphql/edit-mode.js +93 -0
  51. package/dist/next/graphql/filter-values.d.ts +34 -0
  52. package/dist/next/graphql/filter-values.js +96 -0
  53. package/dist/next/graphql/introspection.d.ts +89 -0
  54. package/dist/next/graphql/introspection.js +102 -0
  55. package/dist/next/graphql/plan.d.ts +115 -0
  56. package/dist/next/graphql/plan.js +531 -0
  57. package/dist/next/graphql/request.d.ts +228 -0
  58. package/dist/next/graphql/request.js +283 -0
  59. package/dist/next/graphql/rest.d.ts +66 -0
  60. package/dist/next/graphql/rest.js +502 -0
  61. package/dist/next/graphql/selection.d.ts +55 -0
  62. package/dist/next/graphql/selection.js +212 -0
  63. package/dist/next/graphql/sha256.d.ts +13 -0
  64. package/dist/next/graphql/sha256.js +86 -0
  65. package/dist/next/graphql/summary.d.ts +83 -0
  66. package/dist/next/graphql/summary.js +151 -0
  67. package/dist/next/graphql/tree-layout.d.ts +36 -0
  68. package/dist/next/graphql/tree-layout.js +20 -0
  69. package/dist/next/graphql/tree.d.ts +171 -0
  70. package/dist/next/graphql/tree.js +249 -0
  71. package/dist/next/graphql/typed.d.ts +261 -0
  72. package/dist/next/graphql/typed.js +146 -0
  73. package/dist/next/index.d.ts +30 -3
  74. package/dist/next/index.js +34 -1
  75. package/dist/next/inflate.d.ts +51 -0
  76. package/dist/next/inflate.js +243 -0
  77. package/dist/next/key-family.d.ts +31 -0
  78. package/dist/next/key-family.js +66 -0
  79. package/dist/next/select-types.d.ts +58 -5
  80. package/dist/next/system-keys.d.ts +27 -0
  81. package/dist/next/system-keys.js +42 -0
  82. package/dist/nextjs/image-loader.d.ts +60 -0
  83. package/dist/nextjs/image-loader.js +71 -0
  84. package/dist/nextjs/index.d.ts +484 -5
  85. package/dist/nextjs/index.js +704 -9
  86. package/dist/nextjs/overlay.d.ts +30 -0
  87. package/dist/nextjs/overlay.js +78 -0
  88. package/dist/overlay/index.d.ts +32 -0
  89. package/dist/overlay/index.js +596 -0
  90. package/dist/overlay/protocol.d.ts +187 -0
  91. package/dist/overlay/protocol.js +253 -0
  92. package/package.json +70 -15
@@ -0,0 +1,596 @@
1
+ "use strict";
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;
4
+ exports.startOverlay = startOverlay;
5
+ /**
6
+ * `@capacms/sdk/overlay`: the site half of Capa's live preview.
7
+ *
8
+ * "use client";
9
+ * useEffect(() => startOverlay({ adminOrigins: ["https://app.capacms.com"] }), []);
10
+ *
11
+ * Inside the Capa editor's preview frame this outlines the element an editor is
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:
15
+ * no listeners, no DOM, no cost.
16
+ *
17
+ * A click on a tagged element selects its field. A ⌘-click (Ctrl-click on
18
+ * Windows and Linux) on a tagged element that is a link, or sits inside one,
19
+ * follows the link in the frame instead, so an editor can move between pages.
20
+ *
21
+ * Vanilla DOM and no imports beyond the pure protocol module, so it works in
22
+ * any framework and adds nothing to a bundle that does not call it.
23
+ */
24
+ const protocol_js_1 = require("./protocol.js");
25
+ var protocol_js_2 = require("./protocol.js");
26
+ Object.defineProperty(exports, "acceptMessage", { enumerable: true, get: function () { return protocol_js_2.acceptMessage; } });
27
+ Object.defineProperty(exports, "hoverMessage", { enumerable: true, get: function () { return protocol_js_2.hoverMessage; } });
28
+ Object.defineProperty(exports, "normaliseOrigins", { enumerable: true, get: function () { return protocol_js_2.normaliseOrigins; } });
29
+ Object.defineProperty(exports, "patchedText", { enumerable: true, get: function () { return protocol_js_2.patchedText; } });
30
+ Object.defineProperty(exports, "pickCentred", { enumerable: true, get: function () { return protocol_js_2.pickCentred; } });
31
+ Object.defineProperty(exports, "readyMessage", { enumerable: true, get: function () { return protocol_js_2.readyMessage; } });
32
+ Object.defineProperty(exports, "scrollEdge", { enumerable: true, get: function () { return protocol_js_2.scrollEdge; } });
33
+ Object.defineProperty(exports, "selectMessage", { enumerable: true, get: function () { return protocol_js_2.selectMessage; } });
34
+ Object.defineProperty(exports, "textAround", { enumerable: true, get: function () { return protocol_js_2.textAround; } });
35
+ Object.defineProperty(exports, "visibleMessage", { enumerable: true, get: function () { return protocol_js_2.visibleMessage; } });
36
+ Object.defineProperty(exports, "ADMIN_SOURCE", { enumerable: true, get: function () { return protocol_js_2.ADMIN_SOURCE; } });
37
+ Object.defineProperty(exports, "PATCH_MAX_FIELDS", { enumerable: true, get: function () { return protocol_js_2.PATCH_MAX_FIELDS; } });
38
+ Object.defineProperty(exports, "PATCH_MAX_LENGTH", { enumerable: true, get: function () { return protocol_js_2.PATCH_MAX_LENGTH; } });
39
+ Object.defineProperty(exports, "PROTOCOL_VERSION", { enumerable: true, get: function () { return protocol_js_2.PROTOCOL_VERSION; } });
40
+ Object.defineProperty(exports, "SITE_FEATURES", { enumerable: true, get: function () { return protocol_js_2.SITE_FEATURES; } });
41
+ Object.defineProperty(exports, "SITE_SOURCE", { enumerable: true, get: function () { return protocol_js_2.SITE_SOURCE; } });
42
+ const BLUE = "#2563eb";
43
+ const TAGGED = "[data-capa-entry][data-capa-field]";
44
+ /** What a ⌘-click on a tagged element follows when it sits in one. */
45
+ const LINK = "a[href]";
46
+ /** Survives the `location.reload()` fallback so the page comes back where it was. */
47
+ const SCROLL_KEY = "capa-overlay:scrollY";
48
+ /** How long a refresh keeps putting the scroll position back once the page has re-rendered. */
49
+ const RESTORE_WINDOW_MS = 1500;
50
+ /** How long an in-place refresh may take before the page reloads instead. */
51
+ exports.REFRESH_TIMEOUT_MS = 10_000;
52
+ /** `visible` is sent at most this often while the page scrolls. */
53
+ const VISIBLE_THROTTLE_MS = 150;
54
+ /**
55
+ * Apple platforms open a link with ⌘, Windows and Linux with Ctrl. Read from
56
+ * the browser's own platform report, falling back to the user agent.
57
+ */
58
+ function isApple(nav) {
59
+ if (!nav)
60
+ return false;
61
+ const data = nav.userAgentData;
62
+ return /mac|iphone|ipad|ipod/i.test(data?.platform || nav.platform || nav.userAgent || "");
63
+ }
64
+ /** A usable refresh timeout: a positive number of milliseconds, or the default. */
65
+ function timeoutOf(ms) {
66
+ return typeof ms === "number" && ms > 0 && Number.isFinite(ms) ? ms : exports.REFRESH_TIMEOUT_MS;
67
+ }
68
+ const noop = () => { };
69
+ let running = null;
70
+ /**
71
+ * Start the overlay. Returns a disposer that removes every listener and the
72
+ * drawing layer. Calling it again while it runs updates the options and returns
73
+ * the same disposer, so a React effect that runs twice does not listen twice.
74
+ */
75
+ function startOverlay(options) {
76
+ if (typeof window === "undefined" || typeof document === "undefined")
77
+ return noop;
78
+ // Not framed: this is an ordinary visit to the site.
79
+ if (window.parent === window)
80
+ return noop;
81
+ if (running) {
82
+ running.setOptions(options);
83
+ return running.dispose;
84
+ }
85
+ running = createOverlay(options);
86
+ return running.dispose;
87
+ }
88
+ function createOverlay(initial) {
89
+ let origins = (0, protocol_js_1.normaliseOrigins)(initial.adminOrigins ?? []);
90
+ let onRefresh = initial.onRefresh;
91
+ let refreshTimeout = timeoutOf(initial.refreshTimeoutMs);
92
+ const apple = isApple(typeof navigator === "undefined" ? undefined : navigator);
93
+ const linkHint = apple ? "⌘-click to open link" : "Ctrl-click to open link";
94
+ /** The origin that said hello. Every message this page sends goes there and nowhere else. */
95
+ let adminOrigin = null;
96
+ let highlight = null;
97
+ let outlineAll = false;
98
+ let hovered = null;
99
+ /** The link the pointer is in, when it is also over a tagged element: a ⌘-click follows it. */
100
+ let hoveredLink = null;
101
+ let lastReady = "";
102
+ /** Where a refresh keeps the page. `until` is Infinity while the refresh is still pending. */
103
+ let pendingScroll = null;
104
+ /** Counts refreshes, so only the latest one settles the scroll or reloads. */
105
+ let refreshes = 0;
106
+ let refreshTimer = 0;
107
+ /** True while this overlay replays a ⌘-click as a plain click, which it must let through. */
108
+ let following = false;
109
+ let layer = null;
110
+ let frame = 0;
111
+ let readyFrame = 0;
112
+ let hoverFrame = 0;
113
+ let lastPointer = null;
114
+ let visibleTimer = 0;
115
+ let lastVisible = "";
116
+ const post = (message) => {
117
+ if (!adminOrigin)
118
+ return;
119
+ window.parent.postMessage(message, adminOrigin);
120
+ };
121
+ // ------------------------------------------------------------- drawing ---
122
+ const ensureLayer = () => {
123
+ if (layer && layer.isConnected)
124
+ return layer;
125
+ layer = document.createElement("div");
126
+ layer.setAttribute("data-capa-overlay", "");
127
+ layer.setAttribute("aria-hidden", "true");
128
+ Object.assign(layer.style, {
129
+ position: "fixed",
130
+ inset: "0",
131
+ pointerEvents: "none",
132
+ zIndex: "2147483647",
133
+ overflow: "hidden",
134
+ });
135
+ document.body.appendChild(layer);
136
+ return layer;
137
+ };
138
+ const tagged = () => Array.from(document.querySelectorAll(TAGGED));
139
+ const matching = (entryId, field) => tagged().filter((el) => el.getAttribute("data-capa-entry") === entryId &&
140
+ (field === null || el.getAttribute("data-capa-field") === field));
141
+ const box = (el, style, label) => {
142
+ const rect = el.getBoundingClientRect();
143
+ if (rect.width === 0 && rect.height === 0)
144
+ return null;
145
+ const pad = style === "faint" ? 1 : 3;
146
+ const div = document.createElement("div");
147
+ Object.assign(div.style, {
148
+ position: "absolute",
149
+ left: `${rect.left - pad}px`,
150
+ top: `${rect.top - pad}px`,
151
+ width: `${rect.width + pad * 2}px`,
152
+ height: `${rect.height + pad * 2}px`,
153
+ boxSizing: "border-box",
154
+ borderRadius: "3px",
155
+ border: style === "faint"
156
+ ? "1px solid rgba(37, 99, 235, 0.35)"
157
+ : style === "hover"
158
+ ? `2px dashed ${BLUE}`
159
+ : `2px solid ${BLUE}`,
160
+ });
161
+ if (label) {
162
+ const chip = document.createElement("span");
163
+ chip.textContent = label;
164
+ // Above the box when there is room, tucked inside its top edge when the
165
+ // element sits at the very top of the viewport.
166
+ const above = rect.top - pad >= 20;
167
+ Object.assign(chip.style, {
168
+ position: "absolute",
169
+ left: "-2px",
170
+ top: above ? "-20px" : "0px",
171
+ background: BLUE,
172
+ color: "#fff",
173
+ font: "500 11px/18px system-ui, -apple-system, 'Segoe UI', sans-serif",
174
+ padding: "0 6px",
175
+ borderRadius: "3px",
176
+ whiteSpace: "nowrap",
177
+ letterSpacing: "0",
178
+ });
179
+ div.appendChild(chip);
180
+ }
181
+ return div;
182
+ };
183
+ const draw = () => {
184
+ frame = 0;
185
+ const nothing = !outlineAll && !highlight && !hovered;
186
+ if (nothing) {
187
+ if (layer)
188
+ layer.replaceChildren();
189
+ return;
190
+ }
191
+ const target = ensureLayer();
192
+ const boxes = [];
193
+ const active = highlight ? matching(highlight.entryId, highlight.field) : [];
194
+ if (outlineAll) {
195
+ for (const el of tagged()) {
196
+ if (active.includes(el))
197
+ continue;
198
+ const b = box(el, "faint", null);
199
+ if (b)
200
+ boxes.push(b);
201
+ }
202
+ }
203
+ // Over a link, the label says how to follow it.
204
+ const hint = hovered && hoveredLink ? ` · ${linkHint}` : "";
205
+ if (hovered && hovered.isConnected && !active.includes(hovered)) {
206
+ const b = box(hovered, "hover", `${hovered.getAttribute("data-capa-field") ?? ""}${hint}`);
207
+ if (b)
208
+ boxes.push(b);
209
+ }
210
+ 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;
213
+ const b = box(el, "active", label);
214
+ if (b)
215
+ boxes.push(b);
216
+ });
217
+ target.replaceChildren(...boxes);
218
+ };
219
+ const render = () => {
220
+ if (frame)
221
+ return;
222
+ frame = window.requestAnimationFrame(draw);
223
+ };
224
+ // --------------------------------------------------------------- ready ---
225
+ const sendReady = (force) => {
226
+ readyFrame = 0;
227
+ if (!adminOrigin)
228
+ return;
229
+ const entries = [];
230
+ for (const el of tagged()) {
231
+ const id = el.getAttribute("data-capa-entry");
232
+ if (id && !entries.includes(id))
233
+ entries.push(id);
234
+ }
235
+ const path = window.location.pathname;
236
+ const key = `${path}\n${entries.join(",")}`;
237
+ if (!force && key === lastReady)
238
+ return;
239
+ lastReady = key;
240
+ post((0, protocol_js_1.readyMessage)(path, entries, protocol_js_1.SITE_FEATURES));
241
+ };
242
+ const scheduleReady = () => {
243
+ if (readyFrame)
244
+ return;
245
+ readyFrame = window.requestAnimationFrame(() => sendReady(false));
246
+ };
247
+ // ------------------------------------------------------------- visible ---
248
+ /**
249
+ * Which tagged element sits at the centre of the viewport, reported when it
250
+ * changes. The editor's "Follow the page" scrolls the form to match. Sent
251
+ * only to an admin that has said hello, and only on a change, so a still
252
+ * page sends nothing.
253
+ */
254
+ const reportVisible = () => {
255
+ visibleTimer = 0;
256
+ if (!adminOrigin)
257
+ return;
258
+ const boxes = tagged().map((el) => {
259
+ const rect = el.getBoundingClientRect();
260
+ return {
261
+ entryId: el.getAttribute("data-capa-entry") ?? "",
262
+ field: el.getAttribute("data-capa-field") ?? "",
263
+ top: rect.top,
264
+ bottom: rect.bottom,
265
+ };
266
+ });
267
+ const edge = (0, protocol_js_1.scrollEdge)(window.scrollY, window.innerHeight, document.documentElement.scrollHeight);
268
+ const pick = (0, protocol_js_1.pickCentred)(boxes, window.innerHeight, edge);
269
+ if (!pick)
270
+ return;
271
+ const key = `${pick.entryId}\n${pick.field}`;
272
+ if (key === lastVisible)
273
+ return;
274
+ lastVisible = key;
275
+ post((0, protocol_js_1.visibleMessage)(pick.entryId, pick.field));
276
+ };
277
+ const onScroll = () => {
278
+ render();
279
+ if (!visibleTimer)
280
+ visibleTimer = window.setTimeout(reportVisible, VISIBLE_THROTTLE_MS);
281
+ };
282
+ // -------------------------------------------------------------- scroll ---
283
+ const restoreScroll = () => {
284
+ if (!pendingScroll)
285
+ return;
286
+ if (Date.now() > pendingScroll.until) {
287
+ pendingScroll = null;
288
+ return;
289
+ }
290
+ if (Math.abs(window.scrollY - pendingScroll.y) > 1)
291
+ window.scrollTo(0, pendingScroll.y);
292
+ };
293
+ // A `location.reload()` fallback left the position behind before it went.
294
+ try {
295
+ const saved = window.sessionStorage.getItem(SCROLL_KEY);
296
+ if (saved !== null) {
297
+ window.sessionStorage.removeItem(SCROLL_KEY);
298
+ const y = Number(saved);
299
+ if (Number.isFinite(y)) {
300
+ pendingScroll = { y, until: Date.now() + RESTORE_WINDOW_MS };
301
+ window.requestAnimationFrame(restoreScroll);
302
+ }
303
+ }
304
+ }
305
+ catch {
306
+ // Storage blocked (a sandboxed or third-party frame): start at the top.
307
+ }
308
+ /** The editor scrolled on purpose: stop putting the old position back. */
309
+ const onScrollIntent = () => {
310
+ pendingScroll = null;
311
+ };
312
+ const reload = (y) => {
313
+ try {
314
+ window.sessionStorage.setItem(SCROLL_KEY, String(y));
315
+ }
316
+ catch {
317
+ // Nowhere to keep it; the reload lands at the top.
318
+ }
319
+ window.location.reload();
320
+ };
321
+ /**
322
+ * Re-render the draft in place, or reload. While an in-place refresh is
323
+ * pending the position is held (a page whose re-render moves things keeps
324
+ * its place), and for a moment after it lands. A refresh that fails, or is
325
+ * still pending after `refreshTimeout`, reloads from where the editor is.
326
+ */
327
+ const refresh = () => {
328
+ const y = window.scrollY;
329
+ const refreshFn = onRefresh;
330
+ if (!refreshFn) {
331
+ reload(y);
332
+ return;
333
+ }
334
+ const id = ++refreshes;
335
+ pendingScroll = { y, until: Infinity };
336
+ if (refreshTimer)
337
+ window.clearTimeout(refreshTimer);
338
+ refreshTimer = window.setTimeout(() => {
339
+ refreshTimer = 0;
340
+ if (id === refreshes)
341
+ reload(pendingScroll?.y ?? window.scrollY);
342
+ }, refreshTimeout);
343
+ Promise.resolve()
344
+ .then(() => refreshFn())
345
+ .then(() => {
346
+ // A later refresh owns the timer and the scroll from here on.
347
+ if (id !== refreshes)
348
+ return;
349
+ window.clearTimeout(refreshTimer);
350
+ refreshTimer = 0;
351
+ if (pendingScroll)
352
+ pendingScroll = { y: pendingScroll.y, until: Date.now() + RESTORE_WINDOW_MS };
353
+ window.requestAnimationFrame(restoreScroll);
354
+ }, () => {
355
+ if (id !== refreshes)
356
+ return;
357
+ window.clearTimeout(refreshTimer);
358
+ refreshTimer = 0;
359
+ reload(pendingScroll?.y ?? window.scrollY);
360
+ });
361
+ };
362
+ // ---------------------------------------------------- unsaved text, live ---
363
+ /** What this overlay last wrote into a text node, and the whitespace it found around the text. */
364
+ const written = new WeakMap();
365
+ /** The text node a patch wrote into, by element, so one typed away to nothing is found again. */
366
+ const writtenIn = new WeakMap();
367
+ /**
368
+ * The one text node that holds a tagged element's text: through a chain of
369
+ * single elements (`<a><span>Book now</span></a>`), and only when there is
370
+ * exactly one. Text split across elements is not one field's text, and is
371
+ * left alone. Comments (React's text separators) do not count.
372
+ */
373
+ const textNodeOf = (el) => {
374
+ const kept = writtenIn.get(el);
375
+ if (kept && kept.parentNode && el.contains(kept))
376
+ return kept;
377
+ let node = el;
378
+ for (;;) {
379
+ const kids = Array.from(node.childNodes).filter((c) => c.nodeType === 1 || (c.nodeType === 3 && c.data.trim() !== ""));
380
+ if (kids.length === 1 && kids[0].nodeType === 3)
381
+ return kids[0];
382
+ if (kids.length === 1 && kids[0].nodeType === 1) {
383
+ node = kids[0];
384
+ continue;
385
+ }
386
+ if (kids.length === 0 && node === el) {
387
+ return Array.from(el.childNodes).find((c) => c.nodeType === 3) ?? null;
388
+ }
389
+ return null;
390
+ }
391
+ };
392
+ /**
393
+ * Put the text being typed into the tagged elements of these fields, while
394
+ * they show the saved text or what this page last patched them to
395
+ * (`patchedText`). As text, through a text node's `data`, never as markup.
396
+ */
397
+ const applyPatch = (entryId, fields) => {
398
+ 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)
412
+ continue;
413
+ node.data = next;
414
+ written.set(node, { text: change.value, lead: around.lead, trail: around.trail });
415
+ writtenIn.set(el, node);
416
+ }
417
+ }
418
+ // The boxes follow the text's new size.
419
+ render();
420
+ };
421
+ // ------------------------------------------------------------ messages ---
422
+ const onMessage = (event) => {
423
+ const message = (0, protocol_js_1.acceptMessage)(event, origins, window.parent);
424
+ if (!message)
425
+ return;
426
+ switch (message.type) {
427
+ case "hello":
428
+ adminOrigin = event.origin;
429
+ lastVisible = "";
430
+ sendReady(true);
431
+ render();
432
+ return;
433
+ case "highlight": {
434
+ if (message.entryId === "") {
435
+ highlight = null;
436
+ render();
437
+ return;
438
+ }
439
+ highlight = { entryId: message.entryId, field: message.field };
440
+ const first = matching(message.entryId, message.field)[0];
441
+ if (first)
442
+ first.scrollIntoView({ block: "center", behavior: "smooth" });
443
+ render();
444
+ return;
445
+ }
446
+ case "outline":
447
+ outlineAll = message.on;
448
+ render();
449
+ return;
450
+ case "refresh":
451
+ refresh();
452
+ return;
453
+ case "patch":
454
+ // Only from the admin this page is talking to.
455
+ if (!adminOrigin || event.origin !== adminOrigin)
456
+ return;
457
+ applyPatch(message.entryId, message.fields);
458
+ return;
459
+ }
460
+ };
461
+ // --------------------------------------------------------- interaction ---
462
+ const closestFrom = (target, selector) => {
463
+ const el = target;
464
+ return el && typeof el.closest === "function" ? el.closest(selector) : null;
465
+ };
466
+ const taggedFrom = (target) => closestFrom(target, TAGGED);
467
+ /**
468
+ * A ⌘-click on a tagged link: click the same spot again, without the
469
+ * modifier, and let it through. The site then follows the link in this
470
+ * frame exactly as it would for a visitor's click: a Next `<Link>`
471
+ * navigates client-side, a plain `<a>` loads the page, `target` and the
472
+ * site's own handlers are honoured. The browser's own ⌘-click would open a
473
+ * new tab, outside the editor.
474
+ */
475
+ const follow = (event) => {
476
+ const target = event.target;
477
+ const click = new MouseEvent("click", {
478
+ bubbles: true,
479
+ cancelable: true,
480
+ composed: true,
481
+ view: window,
482
+ detail: event.detail,
483
+ screenX: event.screenX,
484
+ screenY: event.screenY,
485
+ clientX: event.clientX,
486
+ clientY: event.clientY,
487
+ button: 0,
488
+ });
489
+ following = true;
490
+ try {
491
+ target.dispatchEvent(click);
492
+ }
493
+ finally {
494
+ following = false;
495
+ }
496
+ };
497
+ const onClick = (event) => {
498
+ // Only once the admin has said hello: a framed page that is not talking to
499
+ // Capa keeps its links working. And never the plain click `follow` sends.
500
+ if (!adminOrigin || following)
501
+ return;
502
+ const el = taggedFrom(event.target);
503
+ if (!el)
504
+ return;
505
+ event.preventDefault();
506
+ event.stopPropagation();
507
+ if ((apple ? event.metaKey : event.ctrlKey) && closestFrom(event.target, LINK)) {
508
+ follow(event);
509
+ return;
510
+ }
511
+ post((0, protocol_js_1.selectMessage)(el.getAttribute("data-capa-entry") ?? "", el.getAttribute("data-capa-field") ?? ""));
512
+ };
513
+ const updateHover = () => {
514
+ hoverFrame = 0;
515
+ const el = taggedFrom(lastPointer);
516
+ const link = el ? closestFrom(lastPointer, LINK) : null;
517
+ if (el === hovered && link === hoveredLink)
518
+ return;
519
+ const moved = el !== hovered;
520
+ hovered = el;
521
+ hoveredLink = link;
522
+ if (moved) {
523
+ post(el
524
+ ? (0, protocol_js_1.hoverMessage)(el.getAttribute("data-capa-entry") ?? "", el.getAttribute("data-capa-field"))
525
+ : (0, protocol_js_1.hoverMessage)("", null));
526
+ }
527
+ render();
528
+ };
529
+ const onPointerMove = (event) => {
530
+ if (!adminOrigin)
531
+ return;
532
+ lastPointer = event.target;
533
+ if (!hoverFrame)
534
+ hoverFrame = window.requestAnimationFrame(updateHover);
535
+ };
536
+ const onPointerLeave = () => {
537
+ lastPointer = null;
538
+ if (!hoverFrame)
539
+ hoverFrame = window.requestAnimationFrame(updateHover);
540
+ };
541
+ const observer = new MutationObserver((records) => {
542
+ // Our own layer redrawing is not the page changing.
543
+ if (records.every((r) => layer !== null && (r.target === layer || layer.contains(r.target))))
544
+ return;
545
+ scheduleReady();
546
+ render();
547
+ restoreScroll();
548
+ });
549
+ const INTENT = ["wheel", "touchmove", "keydown"];
550
+ window.addEventListener("message", onMessage);
551
+ window.addEventListener("scroll", onScroll, { capture: true, passive: true });
552
+ window.addEventListener("resize", render, { passive: true });
553
+ window.addEventListener("popstate", scheduleReady);
554
+ for (const type of INTENT)
555
+ window.addEventListener(type, onScrollIntent, { capture: true, passive: true });
556
+ document.addEventListener("click", onClick, true);
557
+ document.addEventListener("pointermove", onPointerMove, { capture: true, passive: true });
558
+ document.documentElement.addEventListener("pointerleave", onPointerLeave);
559
+ observer.observe(document.body, { childList: true, subtree: true, characterData: true });
560
+ const dispose = () => {
561
+ window.removeEventListener("message", onMessage);
562
+ window.removeEventListener("scroll", onScroll, { capture: true });
563
+ window.removeEventListener("resize", render);
564
+ window.removeEventListener("popstate", scheduleReady);
565
+ for (const type of INTENT)
566
+ window.removeEventListener(type, onScrollIntent, { capture: true });
567
+ document.removeEventListener("click", onClick, true);
568
+ document.removeEventListener("pointermove", onPointerMove, { capture: true });
569
+ document.documentElement.removeEventListener("pointerleave", onPointerLeave);
570
+ observer.disconnect();
571
+ for (const id of [frame, readyFrame, hoverFrame])
572
+ if (id)
573
+ window.cancelAnimationFrame(id);
574
+ if (visibleTimer)
575
+ window.clearTimeout(visibleTimer);
576
+ // A refresh still pending when the overlay goes must not reload the page later.
577
+ if (refreshTimer)
578
+ window.clearTimeout(refreshTimer);
579
+ refreshTimer = 0;
580
+ refreshes++;
581
+ layer?.remove();
582
+ layer = null;
583
+ if (running?.dispose === dispose)
584
+ running = null;
585
+ };
586
+ return {
587
+ dispose,
588
+ setOptions: (next) => {
589
+ origins = (0, protocol_js_1.normaliseOrigins)(next.adminOrigins ?? []);
590
+ onRefresh = next.onRefresh;
591
+ refreshTimeout = timeoutOf(next.refreshTimeoutMs);
592
+ if (adminOrigin && !origins.includes(adminOrigin))
593
+ adminOrigin = null;
594
+ },
595
+ };
596
+ }