@parhelia/head 0.0.0-stage → 1.0.12951

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.
@@ -0,0 +1,355 @@
1
+ /**
2
+ * `@parhelia/head/picture-crops` — a picture's crops, read alike by every side that touches them (plan
3
+ * `docs/contentful-picture-crops-plan.md`): the head that renders a crop, the editor that draws one, the Parhelia Contentful
4
+ * app that edits one. The Contentful provider's C# twin (`Mapping/PictureCrops.cs`) runs the same vector file
5
+ * (`picture-crops.vectors.json`), so the two cannot drift.
6
+ *
7
+ * - **Units.** Every crop and point is in fractions (0–1) of the original image, as Alpaca's picture regions are. A variant
8
+ * names a ratio — width over height in pixels, `"16:9"`, `"4/3"` or `1.5` — or none: a free variant, the whole image
9
+ * unless someone crops it.
10
+ * - **The stored value** (`v: 1`) is the JSON a Contentful entry keeps beside its asset link:
11
+ * `{ v, asset, file, size: { width, height }, focalPoint: { x, y }, crops: { [variant]: { ratio, x, y, width, height } } }`.
12
+ * `asset`, `file` and `size` name the image the crops and the point were made on; a value made on another image is stale,
13
+ * and none of its crops or its point is used. A writer keeps every member this version does not know.
14
+ * - **Derived crops.** A variant without a usable stored crop gets the largest box of its ratio, centered on the focal point
15
+ * (else on the image's center) and kept inside the image.
16
+ *
17
+ * No React and no DOM: a head, the editor and the app import it alike.
18
+ */
19
+
20
+ /** The version of the stored value this module reads and writes. */
21
+ export const PICTURE_CROPS_VERSION = 1;
22
+
23
+ /** The largest width or height Contentful's Images API serves. */
24
+ export const IMAGES_API_MAX_PIXELS = 4000;
25
+
26
+ /**
27
+ * The attribute a rendered `<source>` or `<img>` states its crop in (`"x y width height"`, fractions of the original), beside
28
+ * the `data-variant` it is rendered for; the editor's bridge reads both to know which part of the image the visitor sees.
29
+ */
30
+ export const PICTURE_CROP_ATTRIBUTE = "data-parhelia-crop";
31
+
32
+ const EPSILON = 1e-6;
33
+ /** How far a stored crop's pixel ratio may stray from its variant's (rounding of the stored fractions) and still be that variant's. */
34
+ const RATIO_TOLERANCE = 0.01;
35
+
36
+ /** @param {unknown} value @returns {value is number} */
37
+ const isNumber = (value) => typeof value === "number" && Number.isFinite(value);
38
+ /** @param {number} value @param {number} min @param {number} max */
39
+ const clamp = (value, min, max) => Math.min(Math.max(value, min), max);
40
+ /** @param {unknown} value @returns {value is Record<string, unknown>} */
41
+ const isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
42
+
43
+ /**
44
+ * A ratio as a number (width over height), or null when it names none: `"16:9"`, `"16/9"`, `"1.5"` and `1.5` read; zero,
45
+ * negative and unreadable ratios are null.
46
+ * @param {unknown} ratio
47
+ * @returns {number | null}
48
+ */
49
+ export function parseRatio(ratio) {
50
+ if (isNumber(ratio)) return ratio > 0 ? ratio : null;
51
+ if (typeof ratio !== "string") return null;
52
+ const text = ratio.trim();
53
+ const pair = /^(\d+(?:\.\d+)?)\s*[:/]\s*(\d+(?:\.\d+)?)$/.exec(text);
54
+ if (pair) {
55
+ const width = Number(pair[1]);
56
+ const height = Number(pair[2]);
57
+ return width > 0 && height > 0 ? width / height : null;
58
+ }
59
+ if (!/^\d+(?:\.\d+)?$/.test(text)) return null;
60
+ const value = Number(text);
61
+ return value > 0 ? value : null;
62
+ }
63
+
64
+ /**
65
+ * Whether two ratios name the same shape: both none, or both within the stored fractions' rounding of each other.
66
+ * @param {unknown} a @param {unknown} b
67
+ */
68
+ export function sameRatio(a, b) {
69
+ const left = parseRatio(a);
70
+ const right = parseRatio(b);
71
+ if (left === null || right === null) return left === right;
72
+ return Math.abs(left / right - 1) <= RATIO_TOLERANCE;
73
+ }
74
+
75
+ /** @param {unknown} size @returns {size is { width: number, height: number }} */
76
+ export const isImageSize = (size) =>
77
+ isPlainObject(size) && isNumber(size.width) && isNumber(size.height) && size.width > 0 && size.height > 0;
78
+
79
+ /** @param {unknown} point @returns {point is { x: number, y: number }} */
80
+ export const isFocalPoint = (point) =>
81
+ isPlainObject(point) && isNumber(point.x) && isNumber(point.y) && point.x >= 0 && point.x <= 1 && point.y >= 0 && point.y <= 1;
82
+
83
+ /**
84
+ * Whether a crop lies inside the image: four finite fractions, a positive size, and no edge past the image's.
85
+ * @param {unknown} crop
86
+ * @returns {crop is { x: number, y: number, width: number, height: number }}
87
+ */
88
+ export function isCrop(crop) {
89
+ if (!isPlainObject(crop)) return false;
90
+ const { x, y, width, height } = crop;
91
+ if (!isNumber(x) || !isNumber(y) || !isNumber(width) || !isNumber(height)) return false;
92
+ return x >= -EPSILON && y >= -EPSILON && width > EPSILON && height > EPSILON &&
93
+ x + width <= 1 + EPSILON && y + height <= 1 + EPSILON;
94
+ }
95
+
96
+ /**
97
+ * The crop's shape in pixels of the image (width over height).
98
+ * @param {{ width: number, height: number }} crop @param {{ width: number, height: number }} size
99
+ */
100
+ export const cropPixelRatio = (crop, size) => (crop.width * size.width) / (crop.height * size.height);
101
+
102
+ /**
103
+ * The largest box of the ratio inside the image, in fractions; the whole image for no ratio; null without the image's size.
104
+ * @param {unknown} ratio @param {unknown} size
105
+ * @returns {{ width: number, height: number } | null}
106
+ */
107
+ export function fitRatio(ratio, size) {
108
+ if (!isImageSize(size)) return null;
109
+ const value = parseRatio(ratio);
110
+ if (value === null) return { width: 1, height: 1 };
111
+ const imageRatio = size.width / size.height;
112
+ return value >= imageRatio ? { width: 1, height: imageRatio / value } : { width: value / imageRatio, height: 1 };
113
+ }
114
+
115
+ /**
116
+ * A variant's derived crop: the largest box of its ratio, centered on the focal point (the image's center without a usable
117
+ * one) and moved inside the image where the point is near an edge. Null without the image's size.
118
+ * @param {unknown} ratio @param {unknown} size @param {unknown} [focalPoint]
119
+ * @returns {{ x: number, y: number, width: number, height: number } | null}
120
+ */
121
+ export function deriveCrop(ratio, size, focalPoint) {
122
+ const box = fitRatio(ratio, size);
123
+ if (!box) return null;
124
+ const point = isFocalPoint(focalPoint) ? focalPoint : { x: 0.5, y: 0.5 };
125
+ return {
126
+ x: clamp(point.x - box.width / 2, 0, 1 - box.width),
127
+ y: clamp(point.y - box.height / 2, 0, 1 - box.height),
128
+ width: box.width,
129
+ height: box.height,
130
+ };
131
+ }
132
+
133
+ /**
134
+ * A crop as a writer stores it: each fraction rounded (6 places) and kept inside the image after rounding.
135
+ * @param {{ x: number, y: number, width: number, height: number }} crop
136
+ */
137
+ export function roundCrop(crop) {
138
+ const round = (/** @type {number} */ value) => Math.round(value * 1e6) / 1e6;
139
+ const width = clamp(round(crop.width), 0, 1);
140
+ const height = clamp(round(crop.height), 0, 1);
141
+ return {
142
+ x: clamp(round(crop.x), 0, 1 - width),
143
+ y: clamp(round(crop.y), 0, 1 - height),
144
+ width,
145
+ height,
146
+ };
147
+ }
148
+
149
+ /**
150
+ * @typedef {{ asset: string | null, file: string | null, size: { width: number, height: number } | null }} PictureImageIdentity
151
+ * @typedef {{ ratio: string | number | null, x: number, y: number, width: number, height: number }} StoredCrop
152
+ * @typedef {{
153
+ * status: "empty" | "ok" | "unknown-version" | "invalid",
154
+ * raw: Record<string, unknown> | null,
155
+ * image: PictureImageIdentity,
156
+ * focalPoint: { x: number, y: number } | null,
157
+ * crops: Record<string, StoredCrop>,
158
+ * }} PictureCropsRead
159
+ */
160
+
161
+ const noImage = () => ({ asset: null, file: null, size: null });
162
+
163
+ /**
164
+ * A stored value read: its status, the original object (for a writer that keeps unknown members), the image it names, and
165
+ * its usable focal point and crops. A member that is not well-formed is left out of the read (never used), not an error;
166
+ * a value that is not an object of this version reads `invalid`, a value of a later version `unknown-version`, and neither
167
+ * offers anything to use. Takes the parsed JSON or its text.
168
+ * @param {unknown} stored
169
+ * @returns {PictureCropsRead}
170
+ */
171
+ export function readPictureCrops(stored) {
172
+ /** @type {(status: PictureCropsRead["status"], raw?: Record<string, unknown> | null) => PictureCropsRead} */
173
+ const none = (status, raw = null) => ({ status, raw, image: noImage(), focalPoint: null, crops: {} });
174
+ if (stored === null || stored === undefined || stored === "") return none("empty");
175
+ let value = stored;
176
+ if (typeof stored === "string") {
177
+ try {
178
+ value = JSON.parse(stored);
179
+ } catch {
180
+ return none("invalid");
181
+ }
182
+ }
183
+ if (!isPlainObject(value)) return none("invalid");
184
+ if (value.v !== PICTURE_CROPS_VERSION) {
185
+ return isNumber(value.v) && Number.isInteger(value.v) && value.v > PICTURE_CROPS_VERSION
186
+ ? none("unknown-version", value)
187
+ : none("invalid", value);
188
+ }
189
+ /** @type {Record<string, StoredCrop>} */
190
+ const crops = {};
191
+ if (isPlainObject(value.crops)) {
192
+ for (const [name, crop] of Object.entries(value.crops)) {
193
+ if (!name || !isCrop(crop)) continue;
194
+ const ratio = /** @type {Record<string, unknown>} */ (crop).ratio;
195
+ if (ratio !== undefined && ratio !== null && parseRatio(ratio) === null) continue;
196
+ crops[name] = {
197
+ ratio: ratio === undefined || ratio === null ? null : /** @type {string | number} */ (ratio),
198
+ x: crop.x, y: crop.y, width: crop.width, height: crop.height,
199
+ };
200
+ }
201
+ }
202
+ return {
203
+ status: "ok",
204
+ raw: value,
205
+ image: {
206
+ asset: typeof value.asset === "string" && value.asset ? value.asset : null,
207
+ file: typeof value.file === "string" && value.file ? value.file : null,
208
+ size: isImageSize(value.size) ? { width: value.size.width, height: value.size.height } : null,
209
+ },
210
+ focalPoint: isFocalPoint(value.focalPoint) ? { x: value.focalPoint.x, y: value.focalPoint.y } : null,
211
+ crops,
212
+ };
213
+ }
214
+
215
+ /**
216
+ * Whether a read value was made on another image than the one now linked: another asset, another file (a file replaced in
217
+ * place gets a new upload path, even at the same size), or another size. A file's address is compared without its scheme:
218
+ * Contentful gives it protocol-relative (`//images.ctfassets.net/…`), a server may spell it with `https:`. A value that does not
219
+ * name its asset and size is stale too: it cannot say what it was made on. Only an `ok` read can be current.
220
+ * @param {PictureCropsRead} read
221
+ * @param {Partial<PictureImageIdentity>} image
222
+ */
223
+ export function isStale(read, image) {
224
+ if (read.status !== "ok") return true;
225
+ const stored = read.image;
226
+ if (!stored.asset || !stored.size || !image.asset || !isImageSize(image.size)) return true;
227
+ return stored.asset !== image.asset ||
228
+ !sameFile(stored.file, image.file) ||
229
+ stored.size.width !== image.size.width ||
230
+ stored.size.height !== image.size.height;
231
+ }
232
+
233
+ /** Whether two file addresses name the same file: equal once a leading `http:` / `https:` is left out; none equals none. */
234
+ const sameFile = (/** @type {string | null | undefined} */ a, /** @type {string | null | undefined} */ b) => {
235
+ const bare = (/** @type {string | null | undefined} */ address) => (address ? address.replace(/^https?:/i, "") : null);
236
+ return bare(a) === bare(b);
237
+ };
238
+
239
+ /**
240
+ * The crop a variant shows on the linked image: its stored crop when the value is current and the crop is of the variant's
241
+ * ratio (a set whose ratio changed leaves the old crop unused), else the derived crop around the value's focal point (when
242
+ * current). Null without the image's size.
243
+ * @param {PictureCropsRead} read
244
+ * @param {{ name: string, ratio?: string | number | null }} variant
245
+ * @param {Partial<PictureImageIdentity>} image
246
+ * @returns {{ crop: { x: number, y: number, width: number, height: number }, source: "stored" | "derived" } | null}
247
+ */
248
+ export function cropFor(read, variant, image) {
249
+ if (!isImageSize(image.size)) return null;
250
+ const current = !isStale(read, image);
251
+ const stored = current ? read.crops[variant.name] : undefined;
252
+ const ratio = variant.ratio ?? null;
253
+ if (stored && sameRatio(stored.ratio, ratio) &&
254
+ (parseRatio(ratio) === null || sameRatio(cropPixelRatio(stored, image.size), ratio))) {
255
+ return { crop: { x: stored.x, y: stored.y, width: stored.width, height: stored.height }, source: "stored" };
256
+ }
257
+ const derived = deriveCrop(ratio, image.size, current ? read.focalPoint : null);
258
+ return derived ? { crop: derived, source: "derived" } : null;
259
+ }
260
+
261
+ /**
262
+ * The value a writer stores: the previous object's members kept (unknown ones included), the image it now names, the focal
263
+ * point and the crops given — the variants someone cropped by hand, each rounded and tagged with its ratio. A previous value
264
+ * made on another image keeps no point and no crop of its own. Throws for a previous value of a later version, which this
265
+ * module cannot rewrite without losing what it does not know.
266
+ * @param {unknown} previous
267
+ * @param {{
268
+ * image: { asset: string, file?: string | null, size: { width: number, height: number } },
269
+ * focalPoint?: { x: number, y: number } | null,
270
+ * crops?: Record<string, { ratio?: string | number | null, x: number, y: number, width: number, height: number }>,
271
+ * }} next
272
+ * @returns {Record<string, unknown>}
273
+ */
274
+ export function writePictureCrops(previous, next) {
275
+ const read = readPictureCrops(previous);
276
+ if (read.status === "unknown-version") {
277
+ throw new Error(`The stored crops are of version ${String(read.raw?.v)}; this writer knows version ${PICTURE_CROPS_VERSION}.`);
278
+ }
279
+ if (!next || !next.image || typeof next.image.asset !== "string" || !next.image.asset || !isImageSize(next.image.size)) {
280
+ throw new TypeError("Crops are written for an image: its asset id and its size.");
281
+ }
282
+ const { v: _v, asset: _asset, file: _file, size: _size, focalPoint: _point, crops: _crops, ...kept } =
283
+ read.status === "ok" && read.raw ? read.raw : {};
284
+ /** @type {Record<string, unknown>} */
285
+ const value = { v: PICTURE_CROPS_VERSION, asset: next.image.asset };
286
+ if (next.image.file) value.file = next.image.file;
287
+ value.size = { width: next.image.size.width, height: next.image.size.height };
288
+ if (next.focalPoint) {
289
+ if (!isFocalPoint(next.focalPoint)) throw new RangeError("A focal point is two fractions of the image, 0 to 1.");
290
+ value.focalPoint = { x: next.focalPoint.x, y: next.focalPoint.y };
291
+ }
292
+ const entries = Object.entries(next.crops ?? {});
293
+ if (entries.length > 0) {
294
+ /** @type {Record<string, unknown>} */
295
+ const crops = {};
296
+ for (const [name, crop] of entries) {
297
+ if (!name || !isCrop(crop)) throw new RangeError(`The crop of '${name}' does not lie inside the image.`);
298
+ const ratio = crop.ratio ?? null;
299
+ if (ratio !== null && parseRatio(ratio) === null) throw new RangeError(`The ratio of '${name}' is not one.`);
300
+ crops[name] = ratio === null ? roundCrop(crop) : { ratio, ...roundCrop(crop) };
301
+ }
302
+ value.crops = crops;
303
+ }
304
+ // The members this version does not know follow its own, unchanged.
305
+ return { ...value, ...kept };
306
+ }
307
+
308
+ /**
309
+ * The CSS that shows a crop of the image in a box: the box's aspect ratio (the crop's shape in pixels), and the image's
310
+ * size and offset inside it, as percentages of the box. The box clips (`overflow: hidden`, `position: relative`); the image
311
+ * is `position: absolute` with these four values and `max-width: none`.
312
+ * @param {{ x: number, y: number, width: number, height: number }} crop
313
+ * @param {{ width: number, height: number }} size
314
+ */
315
+ export function cropStyle(crop, size) {
316
+ const percent = (/** @type {number} */ value) => `${Number(value.toFixed(4))}%`;
317
+ return {
318
+ aspectRatio: Number(cropPixelRatio(crop, size).toFixed(6)),
319
+ width: percent(100 / crop.width),
320
+ height: percent(100 / crop.height),
321
+ left: percent((-100 * crop.x) / crop.width),
322
+ top: percent((-100 * crop.y) / crop.height),
323
+ };
324
+ }
325
+
326
+ /**
327
+ * The width to ask the Images API for, so a crop fills a box of `boxWidth` CSS pixels at the device's pixel ratio: the
328
+ * whole image is fetched, so it must be `1 / crop.width` times the box; never wider than the original or the API's limit.
329
+ * @param {number} boxWidth @param {{ width: number }} crop @param {{ width: number } | null | undefined} size @param {number} [pixelRatio]
330
+ */
331
+ export function requestWidth(boxWidth, crop, size, pixelRatio = 1) {
332
+ const wanted = Math.ceil((boxWidth * pixelRatio) / crop.width);
333
+ const limit = isNumber(size?.width) && size.width > 0 ? Math.min(size.width, IMAGES_API_MAX_PIXELS) : IMAGES_API_MAX_PIXELS;
334
+ return Math.max(1, Math.min(wanted, limit));
335
+ }
336
+
337
+ /**
338
+ * A crop as the value of {@link PICTURE_CROP_ATTRIBUTE}: four fractions, space-separated.
339
+ * @param {{ x: number, y: number, width: number, height: number }} crop
340
+ */
341
+ export const cropAttribute = (crop) =>
342
+ [crop.x, crop.y, crop.width, crop.height].map((value) => String(Math.round(value * 1e6) / 1e6)).join(" ");
343
+
344
+ /**
345
+ * The crop a {@link PICTURE_CROP_ATTRIBUTE} value names, or null when it names none that lies inside the image.
346
+ * @param {string | null | undefined} text
347
+ */
348
+ export function parseCropAttribute(text) {
349
+ if (typeof text !== "string") return null;
350
+ const parts = text.trim().split(/\s+/);
351
+ if (parts.length !== 4 || parts.some((part) => !/^-?\d+(?:\.\d+)?(?:e-?\d+)?$/i.test(part))) return null;
352
+ const [x, y, width, height] = parts.map(Number);
353
+ const crop = { x, y, width, height };
354
+ return isCrop(crop) ? crop : null;
355
+ }
@@ -0,0 +1,9 @@
1
+ export declare const REFRESH_ROOT_ATTRIBUTE: "data-parhelia-refresh-root";
2
+ export declare const REFRESH_SIGNATURE_ATTRIBUTE: "data-parhelia-refresh-signature";
3
+ export declare const REFRESH_DEADLINE_ATTRIBUTE: "data-parhelia-refresh-deadline";
4
+
5
+ /** Patches `live` from the render it showed (`before`) to the new render (`after`), touching only what differs. */
6
+ export declare function patchRendered(live: Node, before: Node, after: Node): Node;
7
+
8
+ /** Installs `window.requestRefresh` for the document's refresh root (read again, patch in place); answers the uninstall. */
9
+ export declare function installParheliaDomRefresh(options?: { deadlineMs?: number }): () => void;
@@ -0,0 +1,92 @@
1
+ /**
2
+ * The in-place refresh for a head without a client framework (Astro, server-rendered HTML): `window.requestRefresh` reads the
3
+ * page again and patches what changed into the live document, as React's reconciliation does for a React head. Nodes the new
4
+ * render did not change stay the very same nodes, with whatever the editing bridge added to them (an inline edit in progress,
5
+ * its own attributes); changed text and attributes update in place; an element whose children changed in number gets the new
6
+ * children. Wrap what the editor shows in an element with `data-parhelia-refresh-root` (and its render's
7
+ * `data-parhelia-refresh-signature`); `ParheliaRefresh` of `@parhelia/astro` renders it.
8
+ */
9
+ import { installParheliaRefresh } from "./refresh.js";
10
+
11
+ export const REFRESH_ROOT_ATTRIBUTE = "data-parhelia-refresh-root";
12
+ export const REFRESH_SIGNATURE_ATTRIBUTE = "data-parhelia-refresh-signature";
13
+ export const REFRESH_DEADLINE_ATTRIBUTE = "data-parhelia-refresh-deadline";
14
+
15
+ const ELEMENT = 1;
16
+ const TEXT = 3;
17
+ const COMMENT = 8;
18
+
19
+ /**
20
+ * Patches `live` (in the document) from the render it showed (`before`) to the new render (`after`): only what differs between
21
+ * the two renders is touched. Answers the node now in `live`'s place.
22
+ * @param {Node} live @param {Node} before @param {Node} after
23
+ * @returns {Node}
24
+ */
25
+ export function patchRendered(live, before, after) {
26
+ if (before.isEqualNode(after)) return live;
27
+ const document = /** @type {Document} */ (live.ownerDocument);
28
+ if (before.nodeType !== after.nodeType || before.nodeName !== after.nodeName || live.nodeName !== before.nodeName) {
29
+ const next = document.importNode(after, true);
30
+ /** @type {ChildNode} */ (live).replaceWith(next);
31
+ return next;
32
+ }
33
+ if (after.nodeType === TEXT || after.nodeType === COMMENT) {
34
+ if (live.nodeValue !== after.nodeValue) live.nodeValue = after.nodeValue;
35
+ return live;
36
+ }
37
+ if (after.nodeType !== ELEMENT) return live;
38
+ const [element, was, now] = /** @type {[Element, Element, Element]} */ ([live, before, after]);
39
+ for (const { name, value } of [...now.attributes]) if (was.getAttribute(name) !== value) element.setAttribute(name, value);
40
+ for (const { name } of [...was.attributes]) if (!now.hasAttribute(name)) element.removeAttribute(name);
41
+ const [liveChildren, wasChildren, nowChildren] = [[...element.childNodes], [...was.childNodes], [...now.childNodes]];
42
+ if (wasChildren.length === nowChildren.length && liveChildren.length === wasChildren.length) {
43
+ nowChildren.forEach((child, index) => patchRendered(/** @type {Node} */ (liveChildren[index]), /** @type {Node} */ (wasChildren[index]), child));
44
+ } else {
45
+ element.replaceChildren(...nowChildren.map((child) => document.importNode(child, true)));
46
+ }
47
+ return live;
48
+ }
49
+
50
+ /** Whether `url` names the document shown (its `edit_rev` aside). @param {URL} url */
51
+ const showsDocument = (url) => {
52
+ const here = new URL(window.location.href);
53
+ const there = new URL(url);
54
+ here.searchParams.delete("edit_rev");
55
+ there.searchParams.delete("edit_rev");
56
+ return here.href === there.href;
57
+ };
58
+
59
+ /**
60
+ * Installs `window.requestRefresh` for the document's refresh root; the answer removes it again. A refresh reads the page again
61
+ * (the same URL with a fresh `edit_rev`) and patches the root until its signature changed and settled; a new URI on this
62
+ * origin is navigated to.
63
+ * @param {{ deadlineMs?: number }} [options]
64
+ * @returns {() => void}
65
+ */
66
+ export function installParheliaDomRefresh({ deadlineMs } = {}) {
67
+ const selector = `[${REFRESH_ROOT_ATTRIBUTE}]`;
68
+ const root = () => document.querySelector(selector);
69
+ /** What the server rendered last, as it rendered it (the live root may carry the bridge's additions). */
70
+ let rendered = root()?.cloneNode(true) ?? null;
71
+ return installParheliaRefresh({
72
+ deadlineMs: deadlineMs ?? (Number(root()?.getAttribute(REFRESH_DEADLINE_ATTRIBUTE)) || undefined),
73
+ signature: () => root()?.getAttribute(REFRESH_SIGNATURE_ATTRIBUTE) ?? "",
74
+ refetch: async (newUri) => {
75
+ const target = new URL(newUri ?? window.location.href, window.location.href);
76
+ if (target.origin !== window.location.origin) return;
77
+ if (!showsDocument(target)) {
78
+ window.location.replace(target.href);
79
+ return;
80
+ }
81
+ target.searchParams.set("edit_rev", `${Date.now()}-${Math.random().toString(36).slice(2)}`);
82
+ const response = await fetch(target, { credentials: "same-origin", headers: { Accept: "text/html" } });
83
+ if (!response.ok) return;
84
+ const next = new DOMParser().parseFromString(await response.text(), "text/html").querySelector(selector);
85
+ const live = root();
86
+ if (!next || !live) return;
87
+ if (rendered) patchRendered(live, rendered, next);
88
+ else live.replaceWith(document.importNode(next, true));
89
+ rendered = next;
90
+ },
91
+ });
92
+ }
@@ -0,0 +1,14 @@
1
+ export interface ParheliaRefreshInstall {
2
+ /** Reads the page again: the editor's `newUri` when it named one (every read of one request gets the same). */
3
+ refetch: (newUri?: string) => unknown;
4
+ /** A stable string of what the page rendered now; the loop stops once it changed and read the same twice. */
5
+ signature: () => string | undefined;
6
+ /** How long one request keeps reading again (default 8000). */
7
+ deadlineMs?: number;
8
+ }
9
+
10
+ /**
11
+ * Installs `window.requestRefresh(newUri?)`, which reads the page again through `refetch` once a second until the signature
12
+ * changed and settled, or the deadline passed. The answer removes it again and stops a running loop. Imports no React.
13
+ */
14
+ export declare function installParheliaRefresh(options: ParheliaRefreshInstall): () => void;
package/src/refresh.js ADDED
@@ -0,0 +1,63 @@
1
+ /**
2
+ * `@parhelia/head/refresh` — **the in-place canvas refresh**: the `window.requestRefresh(newUri?)` contract Parhelia's editor
3
+ * calls after a save, so the page renders again in place instead of the frame reloading. The head says how to read the page
4
+ * again (`refetch`: the Pages Router's `router.replace` with a fresh query, the App Router's `router.refresh()`); this module
5
+ * decides when to stop.
6
+ *
7
+ * A save can land a moment after the editor asks, and a CMS's preview read can answer intermediate states, so the loop
8
+ * compares `signature()` (a stable string of what the page rendered): it reads again once a second until the signature changed
9
+ * from its state before the request and read the same twice (settled), or `deadlineMs` passed (an edit that changes nothing on
10
+ * this page). A new request restarts the loop. Every read of one request gets the editor's `newUri`.
11
+ *
12
+ * The module imports nothing (no React), so a head that links this package from a checkout and runs another React can call it
13
+ * from its own effect; `useParheliaRefresh` (the root entry) is the React hook around it.
14
+ */
15
+
16
+ /** How long a request keeps reading again by default. */
17
+ const DEFAULT_DEADLINE_MS = 8000;
18
+
19
+ /** The pause between two reads. */
20
+ const INTERVAL_MS = 1000;
21
+
22
+ /** @typedef {{ baseline?: string, lastSeen?: string, deadline: number, timer?: ReturnType<typeof setTimeout> }} PendingRefresh */
23
+
24
+ /**
25
+ * Installs `window.requestRefresh`; the answer removes it again and stops a running loop (an effect's cleanup).
26
+ * @param {{ refetch: (newUri?: string) => unknown, signature: () => string | undefined, deadlineMs?: number }} options
27
+ * @returns {() => void}
28
+ */
29
+ export function installParheliaRefresh({ refetch, signature, deadlineMs = DEFAULT_DEADLINE_MS }) {
30
+ /** @type {PendingRefresh | null} */
31
+ let pending = null;
32
+
33
+ /** @param {string | undefined} newUri */
34
+ const tick = newUri => {
35
+ const state = pending;
36
+ if (!state) return;
37
+ const current = signature();
38
+ if ((current !== state.baseline && current === state.lastSeen) || Date.now() > state.deadline) {
39
+ pending = null;
40
+ return;
41
+ }
42
+ state.lastSeen = current;
43
+ void refetch(newUri);
44
+ state.timer = setTimeout(() => tick(newUri), INTERVAL_MS);
45
+ };
46
+
47
+ const host = /** @type {{ requestRefresh?: (newUri?: string) => boolean }} */ (/** @type {unknown} */ (window));
48
+ host.requestRefresh = newUri => {
49
+ if (pending?.timer) clearTimeout(pending.timer);
50
+ /** @type {PendingRefresh} */
51
+ const state = { baseline: signature(), deadline: Date.now() + deadlineMs };
52
+ pending = state;
53
+ void refetch(newUri);
54
+ state.timer = setTimeout(() => tick(newUri), INTERVAL_MS);
55
+ return true;
56
+ };
57
+
58
+ return () => {
59
+ if (pending?.timer) clearTimeout(pending.timer);
60
+ pending = null;
61
+ delete host.requestRefresh;
62
+ };
63
+ }