@parhelia/head 1.0.12903 → 1.0.13030

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,145 @@
1
+ /**
2
+ * `@parhelia/head/orchardcore` — **the Orchard Core marker grammar, and the walk over a rendered page** (Orchard Core OC7a, wire `oc-1` §7). The
3
+ * module's editing render marks its shapes with HTML comment pairs (`<!--parhelia:{kind} {attributes}-->…<!--/parhelia:{kind}-->`), so no template
4
+ * of a theme is touched and Razor and Liquid themes alike are marked. This module is the one JavaScript source of that grammar: the editor's
5
+ * `orchardcore` vocabulary (`@parhelia/core`, `bridge/vocabularies/orchardcore/`) reads a page with it. The vector
6
+ * `providers/orchardcore/protocol-vectors/orchardcore.markers.json` pins it, the same file the module's rows (`MarkersVectorRows`) and the
7
+ * provider's name pins read: a renamed kind or attribute fails a test in each language.
8
+ *
9
+ * A marker's first attribute names its coordinate: `key` (the Parhelia key of a coordinate the render exposed, the rendered item, a displayed item, a
10
+ * widget instance) or `id` in its place (a content item's id, for a shape no display built: no identity was recorded, so a store answers nothing). A
11
+ * `field` marker adds `path` (the save's path, wire §5.1), `type` and `kind`, or `source` for the theme's own marker (the Liquid filter
12
+ * `parhelia_field`, the Razor tag helper `parhelia-field`). A `widget` pair of the rendered page's own composition adds `guid`, the Guid the store issues for the
13
+ * instance, and a `slot` pair of it adds `guid` and `slot`, the owner's Guid and the slot's key as the store's composition lists it (wire amendment OC5-1); an empty slot's
14
+ * pair holds a block with `data-parhelia-empty-slot`. A text field whose shape shows nothing holds a placeholder with `data-parhelia-blank-field` and its label as
15
+ * `data-empty-hint` (amendment OC5-3). Attribute values are HTML-encoded as .NET's `HtmlEncoder.Default` encodes them.
16
+ *
17
+ * Markers appear in Parhelia's editing renders only; every other render is the theme's markup, byte for byte.
18
+ */
19
+
20
+ /** The vocabulary's wire name: what the canvas sends with the markers it found, and what the Orchard Core store states. */
21
+ export const ORCHARDCORE_MARKER_VOCABULARY = "orchardcore";
22
+
23
+ /** The marker kinds of an editing render. */
24
+ export const ORCHARDCORE_MARKER_KINDS = ["item", "widget", "slot", "part", "field"];
25
+
26
+ /** The entity kind of a field marker naming an item (`item:`, `set:`). */
27
+ export const ORCHARDCORE_ITEM_KIND = "item";
28
+ /** The entity kind of a field marker naming a widget instance (`widget:`). */
29
+ export const ORCHARDCORE_WIDGET_KIND = "widget";
30
+
31
+ /**
32
+ * On the inert coordinate script of a session's page: the one element a selector finds on a page whose markers are comments. The editor's frame
33
+ * of the proxied canvas is told by it that the page is editable.
34
+ */
35
+ export const ORCHARDCORE_RENDER_ATTRIBUTE = "data-orchardcore-markers";
36
+
37
+ /** The attributes the vocabulary writes on the element a field comment pair stands for: elements are what the bridge reads. */
38
+ export const ORCHARDCORE_KEY_ATTRIBUTE = "data-orchardcore-key";
39
+ export const ORCHARDCORE_PATH_ATTRIBUTE = "data-orchardcore-path";
40
+ export const ORCHARDCORE_TYPE_ATTRIBUTE = "data-orchardcore-type";
41
+ export const ORCHARDCORE_KIND_ATTRIBUTE = "data-orchardcore-kind";
42
+
43
+ const OPEN = /^parhelia:([a-z]+)((?:\s+[A-Za-z]+="[^"]*")*)\s*$/;
44
+ const CLOSE = /^\/parhelia:([a-z]+)$/;
45
+ const ATTRIBUTE = /\s+([A-Za-z]+)="([^"]*)"/g;
46
+ const ENTITY = /&(?:lt|gt|amp|quot|#x([0-9A-Fa-f]+));/g;
47
+ /** @type {Record<string, string>} */
48
+ const NAMED = { "&lt;": "<", "&gt;": ">", "&amp;": "&", "&quot;": '"' };
49
+
50
+ /**
51
+ * A value as the marker wrote it, decoded: `&lt; &gt; &amp; &quot;`, `&#x…;` (.NET's `HtmlEncoder.Default`, which encodes `'` and every non-ASCII
52
+ * character numerically).
53
+ * @param {string} value
54
+ * @returns {string}
55
+ */
56
+ export const decodeMarkerValue = value =>
57
+ value.replace(ENTITY, (/** @type {string} */ entity, /** @type {string | undefined} */ hex) =>
58
+ hex ? String.fromCodePoint(parseInt(hex, 16)) : (NAMED[entity] ?? entity));
59
+
60
+ /**
61
+ * One comment's marker, or undefined for a comment that is none of the grammar's (the theme's own, the module's `parhelia-sentinel`, a kind it does
62
+ * not know): `{ close: true, kind }` for a closing comment; else `{ close: false, kind, key?, id?, attributes }` with `attributes` decoded, in order,
63
+ * `key` and `id` lifted from them too.
64
+ * @param {string} data the comment's text
65
+ * @returns {import("./orchardcore.js").OrchardMarker | undefined}
66
+ */
67
+ export const parseOrchardMarker = data => {
68
+ const text = typeof data === "string" ? data.trim() : "";
69
+ const closing = CLOSE.exec(text);
70
+ if (closing) {
71
+ const kind = closing[1] ?? "";
72
+ return ORCHARDCORE_MARKER_KINDS.includes(kind) ? { close: true, kind } : undefined;
73
+ }
74
+ const opening = OPEN.exec(text);
75
+ const kind = opening?.[1] ?? "";
76
+ if (!opening || !ORCHARDCORE_MARKER_KINDS.includes(kind)) return undefined;
77
+ /** @type {Record<string, string>} */
78
+ const attributes = {};
79
+ for (const [, name, value] of (opening[2] ?? "").matchAll(ATTRIBUTE)) if (name) attributes[name] = decodeMarkerValue(value ?? "");
80
+ return {
81
+ close: false,
82
+ kind,
83
+ ...(attributes.key !== undefined ? { key: attributes.key } : {}),
84
+ ...(attributes.id !== undefined ? { id: attributes.id } : {}),
85
+ attributes,
86
+ };
87
+ };
88
+
89
+ /**
90
+ * The entity a coordinate's key names, as the store's marker extension reads it: kind `widget` for a `widget:` key, kind `item` for `item:` and
91
+ * `set:`; undefined for anything else (a marker naming only an `id` names no key, and no store answers it).
92
+ * @param {string | undefined} key
93
+ * @returns {{ entityKind: string; entityKey: string } | undefined}
94
+ */
95
+ export const orchardEntityOf = key => {
96
+ if (typeof key !== "string") return undefined;
97
+ if (/^widget:\S+$/.test(key)) return { entityKind: ORCHARDCORE_WIDGET_KIND, entityKey: key };
98
+ if (/^(?:item|set):\S+$/.test(key)) return { entityKind: ORCHARDCORE_ITEM_KIND, entityKey: key };
99
+ return undefined;
100
+ };
101
+
102
+ /**
103
+ * Every balanced marker pair below `root`, in document order of their opening comments. A pair whose two comments do not share a parent (the
104
+ * parser moved one, a template broke the shape's nesting) stands for no run of nodes and is left out, as is a stray closing comment.
105
+ * @param {Document | Element} root
106
+ * @returns {import("./orchardcore.js").OrchardMarkerPair[]}
107
+ */
108
+ export const orchardMarkerPairs = root => {
109
+ const doc = root.ownerDocument ?? root;
110
+ const walker = doc.createTreeWalker(root, 128 /* NodeFilter.SHOW_COMMENT */);
111
+ /** @type {{ open: Comment; marker: import("./orchardcore.js").OrchardOpenMarker; slot: number }[]} */
112
+ const open = [];
113
+ /** @type {(import("./orchardcore.js").OrchardMarkerPair | null)[]} */
114
+ const pairs = [];
115
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
116
+ const comment = /** @type {Comment} */ (node);
117
+ const marker = parseOrchardMarker(comment.data);
118
+ if (!marker) continue;
119
+ if (!marker.close) {
120
+ open.push({ open: comment, marker, slot: pairs.length });
121
+ pairs.push(null);
122
+ continue;
123
+ }
124
+ let index = open.length - 1;
125
+ while (index >= 0 && open[index]?.marker.kind !== marker.kind) index--;
126
+ const opened = index < 0 ? undefined : open.splice(index, 1)[0];
127
+ if (opened && opened.open.parentNode === comment.parentNode) pairs[opened.slot] = { marker: opened.marker, open: opened.open, close: comment };
128
+ }
129
+ return /** @type {import("./orchardcore.js").OrchardMarkerPair[]} */ (pairs.filter(pair => pair !== null));
130
+ };
131
+
132
+ /**
133
+ * The nodes between a pair's two comments that are content: elements and text with more than white space. Comments (nested markers, the module's
134
+ * sentinel) and white space say nothing about the shape's output.
135
+ * @param {import("./orchardcore.js").OrchardMarkerPair} pair
136
+ * @returns {ChildNode[]}
137
+ */
138
+ export const orchardPairContent = pair => {
139
+ /** @type {ChildNode[]} */
140
+ const content = [];
141
+ for (let node = pair.open.nextSibling; node && node !== pair.close; node = node.nextSibling) {
142
+ if (node.nodeType === 1 || (node.nodeType === 3 && (node.nodeValue ?? "").trim())) content.push(node);
143
+ }
144
+ return content;
145
+ };
@@ -0,0 +1,168 @@
1
+ /** The version of the stored value this module reads and writes. */
2
+ export declare const PICTURE_CROPS_VERSION: 1;
3
+
4
+ /** The largest width or height Contentful's Images API serves. */
5
+ export declare const IMAGES_API_MAX_PIXELS: 4000;
6
+
7
+ /** The attribute a rendered `<source>` or `<img>` states its crop in (`"x y width height"`, fractions of the original). */
8
+ export declare const PICTURE_CROP_ATTRIBUTE: "data-parhelia-crop";
9
+
10
+ /** A part of the image in fractions (0–1) of the original. */
11
+ export interface PictureCrop {
12
+ x: number;
13
+ y: number;
14
+ width: number;
15
+ height: number;
16
+ }
17
+
18
+ /** A point of the image in fractions (0–1) of the original. */
19
+ export interface FocalPoint {
20
+ x: number;
21
+ y: number;
22
+ }
23
+
24
+ /** The original image's size in pixels. */
25
+ export interface ImageSize {
26
+ width: number;
27
+ height: number;
28
+ }
29
+
30
+ /** A variant's ratio: width over height in pixels (`"16:9"`, `"4/3"`, `1.5`), or null for a free variant. */
31
+ export type PictureRatio = string | number | null;
32
+
33
+ /** A crop as stored, tagged with the ratio of the variant it was made for. */
34
+ export interface StoredCrop extends PictureCrop {
35
+ ratio: PictureRatio;
36
+ }
37
+
38
+ /** The image a stored value names: the asset's id, its file's address and the file's size. */
39
+ export interface PictureImageIdentity {
40
+ asset: string | null;
41
+ file: string | null;
42
+ size: ImageSize | null;
43
+ }
44
+
45
+ /** A stored value read (see {@link readPictureCrops}). */
46
+ export interface PictureCropsRead {
47
+ status: "empty" | "ok" | "unknown-version" | "invalid";
48
+ /** The stored object as found, for a writer that keeps the members it does not know; null for none. */
49
+ raw: Record<string, unknown> | null;
50
+ image: PictureImageIdentity;
51
+ focalPoint: FocalPoint | null;
52
+ /** The well-formed crops, by variant name. */
53
+ crops: Record<string, StoredCrop>;
54
+ }
55
+
56
+ /** A ratio as a number (width over height), or null when it names none. */
57
+ export declare function parseRatio(ratio: unknown): number | null;
58
+
59
+ /** Whether two ratios name the same shape (both none, or within the stored fractions' rounding). */
60
+ export declare function sameRatio(a: unknown, b: unknown): boolean;
61
+
62
+ export declare function isImageSize(size: unknown): size is ImageSize;
63
+ export declare function isFocalPoint(point: unknown): point is FocalPoint;
64
+
65
+ /** Whether a crop lies inside the image. */
66
+ export declare function isCrop(crop: unknown): crop is PictureCrop;
67
+
68
+ /** The crop's shape in pixels of the image (width over height). */
69
+ export declare function cropPixelRatio(crop: Pick<PictureCrop, "width" | "height">, size: ImageSize): number;
70
+
71
+ /** The largest box of the ratio inside the image, in fractions; the whole image for no ratio; null without a size. */
72
+ export declare function fitRatio(ratio: unknown, size: unknown): { width: number; height: number } | null;
73
+
74
+ /** A variant's derived crop: the largest box of its ratio around the focal point (else the center), inside the image. */
75
+ export declare function deriveCrop(ratio: unknown, size: unknown, focalPoint?: unknown): PictureCrop | null;
76
+
77
+ /** A crop as a writer stores it: rounded to 6 places and kept inside the image. */
78
+ export declare function roundCrop(crop: PictureCrop): PictureCrop;
79
+
80
+ /** A stored value (parsed JSON or its text) read; malformed members are left out of the read, never used. */
81
+ export declare function readPictureCrops(stored: unknown): PictureCropsRead;
82
+
83
+ /** Whether a read value was made on another image than the one now linked (asset, file or size differ, or unknown). */
84
+ export declare function isStale(read: PictureCropsRead, image: Partial<PictureImageIdentity>): boolean;
85
+
86
+ /** The crop a variant shows on the linked image: its current stored crop of the right ratio, else the derived one. */
87
+ export declare function cropFor(
88
+ read: PictureCropsRead,
89
+ variant: { name: string; ratio?: PictureRatio },
90
+ image: Partial<PictureImageIdentity>,
91
+ ): { crop: PictureCrop; source: "stored" | "derived" } | null;
92
+
93
+ /**
94
+ * The value a writer stores: unknown members of the previous value kept, the image it now names, the focal point and the
95
+ * hand-made crops given. Throws for a previous value of a later version, and for a crop outside the image.
96
+ */
97
+ export declare function writePictureCrops(
98
+ previous: unknown,
99
+ next: {
100
+ image: { asset: string; file?: string | null; size: ImageSize };
101
+ focalPoint?: FocalPoint | null;
102
+ crops?: Record<string, PictureCrop & { ratio?: PictureRatio }>;
103
+ },
104
+ ): Record<string, unknown>;
105
+
106
+ /** The CSS that shows a crop in a clipping box: the box's aspect ratio and the image's size and offset (percent of the box). */
107
+ export declare function cropStyle(
108
+ crop: PictureCrop,
109
+ size: ImageSize,
110
+ ): { aspectRatio: number; width: string; height: string; left: string; top: string };
111
+
112
+ /** The width to ask the Images API for so the crop fills a box of `boxWidth` CSS pixels; capped at the original and 4000. */
113
+ export declare function requestWidth(
114
+ boxWidth: number,
115
+ crop: Pick<PictureCrop, "width">,
116
+ size: { width: number } | null | undefined,
117
+ pixelRatio?: number,
118
+ ): number;
119
+
120
+ /** A crop as the value of {@link PICTURE_CROP_ATTRIBUTE}. */
121
+ export declare function cropAttribute(crop: PictureCrop): string;
122
+
123
+ /** The crop a {@link PICTURE_CROP_ATTRIBUTE} value names, or null. */
124
+ export declare function parseCropAttribute(text: string | null | undefined): PictureCrop | null;
125
+
126
+ /** One variant a head shows: its name and ratio (the variant set's), the media query its source switches on, the box's width. */
127
+ export interface CroppedPictureVariant {
128
+ name: string;
129
+ ratio?: string | number | null;
130
+ /** The media query the variant's `<source>` applies under; the variant without one is the default. */
131
+ media?: string;
132
+ /** The box's width as a `sizes` value: one length, or a list with media conditions (`100vw` when absent). */
133
+ sizes?: string;
134
+ }
135
+
136
+ /** The file and markup values of one `<source>` or the `<img>` of a cropped picture. */
137
+ export interface CroppedPictureElement {
138
+ srcset: string;
139
+ /** The width of the image inside the box: the box's width over the crop's. */
140
+ sizes: string;
141
+ /** The crop's size in pixels of the original. */
142
+ width: number;
143
+ height: number;
144
+ /** The variant's name, for `data-variant`. */
145
+ variant: string;
146
+ /** The crop applied, for `data-parhelia-crop`. */
147
+ crop: string;
148
+ }
149
+
150
+ /**
151
+ * How a head shows an image with the crops the browser applies, as a CMS helper computes it (the Contentful one:
152
+ * `contentfulPictureSources` of `@parhelia/head/contentful`) and `ParheliaPicture` of `@parhelia/react` renders it.
153
+ */
154
+ export interface CroppedPicture {
155
+ key: string;
156
+ /** The rules for this picture, keyed by its box: render them in a `<style>` beside the markup. */
157
+ css: string;
158
+ /** The clipping box's attribute (the field's annotations go on the box too). */
159
+ box: { "data-parhelia-picture": string };
160
+ sources: Array<CroppedPictureElement & { media: string }>;
161
+ img: CroppedPictureElement & { src: string };
162
+ variants: Array<{
163
+ name: string;
164
+ media: string | null;
165
+ crop: PictureCrop;
166
+ source: "stored" | "derived";
167
+ }>;
168
+ }
@@ -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
+ }