@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.
package/README.md CHANGED
@@ -10,16 +10,17 @@ plain server-rendered HTML. Plain JavaScript, no build step, no React: it can be
10
10
  | `@parhelia/head/identity` | the rendered-identity script |
11
11
  | `@parhelia/head/refresh` | the in-place refresh loop |
12
12
  | `@parhelia/head/rich-text` | `sanitizeRichTextHtml` for CMS rich text |
13
- | `@parhelia/head/<cms>` | a CMS's own helpers: `contentful` (Live Preview origins), `umbraco`, `magnolia`, `typo3` (marker names) |
13
+ | `@parhelia/head/picture-crops` | a picture's crops and focal point: which crop a variant shows, and the CSS that shows it |
14
+ | `@parhelia/head/<cms>` | a CMS's own helpers: `contentful` (Live Preview origins, `contentfulPictureSources`), `umbraco` (marker names) |
14
15
  | `@parhelia/head/vite` | `parhelia()`, the Vite build adapter |
15
16
 
16
17
  The framework adapters build on it:
17
18
 
18
19
  | Package | For |
19
20
  |---|---|
20
- | [`@parhelia/react`](../react/README.md) | a React head on any framework: `ParheliaBridge`, `ParheliaBridgeScript`, `ParheliaSlot`, `useParheliaRefresh` |
21
- | [`@parhelia/astro`](../astro/README.md) | an Astro head: the integration and the slot, bridge and refresh components |
22
- | [`@parhelia/next`](../next/README.md) | a Next.js head: `withParhelia` (`/config`), re-exporting this package and `@parhelia/react` under the same entries |
21
+ | [`@parhelia/react`](https://www.npmjs.com/package/@parhelia/react) | a React head on any framework: `ParheliaBridge`, `ParheliaBridgeScript`, `ParheliaSlot`, `useParheliaRefresh`, `ParheliaPicture` |
22
+ | [`@parhelia/astro`](https://www.npmjs.com/package/@parhelia/astro) | an Astro head: the integration and the slot, bridge and refresh components |
23
+ | [`@parhelia/next`](https://www.npmjs.com/package/@parhelia/next) | a Next.js head: `withParhelia` (`/config`), re-exporting this package and `@parhelia/react` under the same entries |
23
24
 
24
25
  ## The build: base path and editor origin
25
26
 
@@ -77,8 +78,7 @@ html[data-parhelia-editor-mode="preview"] [data-empty-hint]:empty {
77
78
 
78
79
  `PARHELIA_EDITING_SELECTOR` is that selector (edit and suggestions mode) and `PARHELIA_EDITOR_MODE_ATTRIBUTE` the attribute,
79
80
  for CSS-in-JS. The same marker is set on every head that loads the bridge, whatever loads it (`ParheliaBridge`, Parhelia's
80
- proxy, the Umbraco package, the Magnolia connector). See
81
- [Render empty components in edit mode](../../../docs/integration/render-empty-components.md).
81
+ proxy, the Umbraco package).
82
82
 
83
83
  ## Empty slots
84
84
 
@@ -122,7 +122,7 @@ return { props: { ..., parheliaIdentity: frameRenderedIdentity(query, { itemId:
122
122
  {pageProps.parheliaIdentity && <script {...renderedIdentityScriptProps(pageProps.parheliaIdentity)} />}
123
123
  ```
124
124
 
125
- The Contentful Marketing starter does exactly this (P7, `docs/migration/w12-cfsite-starter-changes.md`). Settings ›
125
+ Contentful's marketing starter, made editable in Parhelia, does exactly this. Settings ›
126
126
  Rendering Hosts › the head's settings lists the `PARHELIA_STORE` line for a head of a Contentful mount.
127
127
 
128
128
  The module imports nothing (no React, no Next.js), so a head that links this package from a checkout never resolves a
@@ -179,6 +179,48 @@ content, every event handler, other `data-*` attributes, URLs other than `http(s
179
179
  `getServerSideProps`) and no dependency. The editing bridge applies the same rule (`richTextElementAction`,
180
180
  `sanitizeRichTextAttribute`) to the values it writes into the canvas.
181
181
 
182
+ ## Picture crops: `@parhelia/head/picture-crops`
183
+
184
+ A Contentful entry whose crops field uses the Parhelia app keeps its crops beside the asset link, as JSON (`v: 1`): the
185
+ image it was made on, a focal point, and the variants someone cropped by hand, in fractions of the original. The image service
186
+ cannot cut out a rectangle, so a head shows a crop with CSS:
187
+
188
+ ```ts
189
+ import { cropFor, cropStyle, readPictureCrops, requestWidth } from '@parhelia/head/picture-crops';
190
+
191
+ const read = readPictureCrops(entry.fields.crops);
192
+ const image = { asset: asset.sys.id, file: file.url, size: file.details.image };
193
+ const shown = cropFor(read, { name: 'landscape', ratio: '16:9' }, image); // the stored crop, else one around the focal point
194
+ const style = shown && cropStyle(shown.crop, image.size); // the box's aspect ratio, the image's size and offset in it
195
+ const width = shown && requestWidth(800, shown.crop, image.size, 2); // the `w` to ask the Images API for
196
+ ```
197
+
198
+ The box clips (`position: relative; overflow: hidden; aspect-ratio: <style.aspectRatio>`); the image inside is
199
+ `position: absolute; max-width: none` with `style.width`, `style.height`, `style.left` and `style.top`. Put `data-variant` and
200
+ `data-parhelia-crop` (`cropAttribute(shown.crop)`) on the image, so the editor knows which part of it the visitor sees.
201
+
202
+ `contentfulPictureSources` (`@parhelia/head/contentful`) does all of that for a `<picture>` whose variants switch by media query:
203
+
204
+ ```ts
205
+ import { contentfulPictureSources } from '@parhelia/head/contentful';
206
+
207
+ const picture = contentfulPictureSources(
208
+ { id: asset.sys.id, url: file.url, ...file.details.image },
209
+ entry.fields.crops,
210
+ [
211
+ { name: 'square', ratio: '1:1', media: '(max-width: 61.99em)', sizes: '50vw' },
212
+ { name: 'landscape', ratio: '16:9', sizes: '33vw' },
213
+ ],
214
+ );
215
+ ```
216
+
217
+ It answers the picture's CSS (render it in a `<style>` as raw text; React sets it with `dangerouslySetInnerHTML`, as a child
218
+ its server rendering escapes it), the clipping box's key attribute (`box`; put the field's annotations on the box too), and
219
+ each `<source>` and the `<img>` with its Images API `srcset`, `sizes`, size, variant and crop. The box also gets
220
+ `--parhelia-crop-ratio`, so a site that caps its height can cap its width at the same ratio. `options.focalPoint` (fractions) is
221
+ the point the automatic crops follow where the stored value names none for this file: a head with a focal point of its own
222
+ keeps it as the fallback. A React head renders it with `ParheliaPicture` (`@parhelia/react`).
223
+
182
224
  ## In-place refresh
183
225
 
184
226
  The editor calls `window.requestRefresh(newUri?)` after a save. `installParheliaRefresh({ refetch, signature, deadlineMs })`
@@ -188,8 +230,3 @@ loop reads again once a second until it changed and settled, or the deadline pas
188
230
  `installParheliaDomRefresh()`: it reads the page again and patches what changed into the live document, keeping every node the
189
231
  new render left alone (and what the editing bridge added to it), inside the element marked `data-parhelia-refresh-root`;
190
232
  `ParheliaRefresh` of `@parhelia/astro` renders that element and installs it.
191
-
192
- ## See also
193
-
194
- - [Render empty components in edit mode](../../../docs/integration/render-empty-components.md): a recommendation (never a
195
- requirement) so that an empty component is on the canvas and editable in place.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@parhelia/head",
3
- "version": "1.0.12903",
4
- "description": "Make a rendering head editable in Parhelia, on any framework and without one: the editing bridge, slot markers, the in-place refresh (with a DOM-patching one for heads without a client framework), the rendered-content identity capture reads, the editor signal a head's server checks (/server), rich-text sanitising (/rich-text), per-CMS marker helpers (/contentful, /umbraco, /magnolia, /typo3), the build values and the Vite build adapter (/vite). No React: React heads add @parhelia/react, Next.js heads @parhelia/next, Astro heads @parhelia/astro.",
3
+ "version": "1.0.13030",
4
+ "description": "Make a rendering head editable in Parhelia, on any framework and without one: the editing bridge, slot markers, the in-place refresh (with a DOM-patching one for heads without a client framework), the rendered-content identity capture reads, the editor signal a head's server checks (/server), rich-text sanitising (/rich-text), per-CMS marker helpers (/contentful, /umbraco), a SitecoreAI editing host's canvas render (/sitecore), the build values and the Vite build adapter (/vite). No React: React heads add @parhelia/react, Next.js heads @parhelia/next, Astro heads @parhelia/astro.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "publishConfig": {
7
7
  "access": "public"
@@ -30,6 +30,10 @@
30
30
  "types": "./src/rich-text.d.ts",
31
31
  "default": "./src/rich-text.js"
32
32
  },
33
+ "./picture-crops": {
34
+ "types": "./src/picture-crops.d.ts",
35
+ "default": "./src/picture-crops.js"
36
+ },
33
37
  "./contentful": {
34
38
  "types": "./src/contentful.d.ts",
35
39
  "default": "./src/contentful.js"
@@ -46,6 +50,18 @@
46
50
  "types": "./src/typo3.d.ts",
47
51
  "default": "./src/typo3.js"
48
52
  },
53
+ "./aem": {
54
+ "types": "./src/aem.d.ts",
55
+ "default": "./src/aem.js"
56
+ },
57
+ "./orchardcore": {
58
+ "types": "./src/orchardcore.d.ts",
59
+ "default": "./src/orchardcore.js"
60
+ },
61
+ "./sitecore": {
62
+ "types": "./src/sitecore.d.ts",
63
+ "default": "./src/sitecore.js"
64
+ },
49
65
  "./vite": {
50
66
  "types": "./src/vite.d.ts",
51
67
  "default": "./src/vite.js"
@@ -69,6 +85,9 @@
69
85
  "rich-text": [
70
86
  "./src/rich-text.d.ts"
71
87
  ],
88
+ "picture-crops": [
89
+ "./src/picture-crops.d.ts"
90
+ ],
72
91
  "contentful": [
73
92
  "./src/contentful.d.ts"
74
93
  ],
@@ -81,6 +100,15 @@
81
100
  "typo3": [
82
101
  "./src/typo3.d.ts"
83
102
  ],
103
+ "aem": [
104
+ "./src/aem.d.ts"
105
+ ],
106
+ "orchardcore": [
107
+ "./src/orchardcore.d.ts"
108
+ ],
109
+ "sitecore": [
110
+ "./src/sitecore.d.ts"
111
+ ],
84
112
  "vite": [
85
113
  "./src/vite.d.ts"
86
114
  ],
package/src/aem.d.ts ADDED
@@ -0,0 +1,30 @@
1
+ /** One rendered field's identity, as an AEM render knows it. */
2
+ export type AemFieldRef = {
3
+ /** The item's connector id (a component's, or the page's for a field of its `jcr:content`). */
4
+ item: string;
5
+ /** The merged dialog's field name (`jcr:title`, `text`, a nested `a/b`). */
6
+ field: string;
7
+ /** The field's element holds rich text. */
8
+ richText?: boolean;
9
+ };
10
+
11
+ /** The vocabulary's wire name. */
12
+ export declare const AEM_MARKER_VOCABULARY: "aem";
13
+ /** The entity kind of a field marker: an item. */
14
+ export declare const AEM_ITEM_KIND: "item";
15
+ export declare const AEM_ITEM_ATTRIBUTE: string;
16
+ export declare const AEM_FIELD_ATTRIBUTE: string;
17
+ export declare const AEM_RICHTEXT_ATTRIBUTE: string;
18
+ /** The component sentinel's attribute carrying the connector's id. */
19
+ export declare const AEM_ID_ATTRIBUTE: string;
20
+ /** The component sentinel's attribute carrying the component's path below the page's `jcr:content`. */
21
+ export declare const AEM_PATH_ATTRIBUTE: string;
22
+ /** Parhelia addresses an AEM item as its current state. */
23
+ export declare const PARHELIA_AEM_VERSION: "0";
24
+
25
+ /** The key of an item marker: the connector's id (a lowercase UUID); undefined for anything else. */
26
+ export declare function aemItemKey(id: string): string | undefined;
27
+ /** The attributes of one rendered field; nothing when `edit` is false. */
28
+ export declare function aemFieldAttributes(ref: AemFieldRef, edit: boolean): Record<string, string>;
29
+ /** Whether `field` is a dialog field's name a marker may carry. */
30
+ export declare function isAemFieldName(field: string): boolean;
package/src/aem.js ADDED
@@ -0,0 +1,80 @@
1
+ /**
2
+ * `@parhelia/head/aem` — **the AEM marker names, and the helpers a head renders them with** (AEM AEM7a, wire `aem-1` §7.3). This module
3
+ * is the one JavaScript source: the editor's `aem` vocabulary (`@parhelia/core`, `bridge/vocabularies/aem/`) reads them by importing
4
+ * this module, a headless AEM head (AEM7b) renders them, the Parhelia connector inside AEM writes them in its editing renders (the HTL
5
+ * helper `io.parhelia.aem.connector.markup.FieldMarker`, the component filter's sentinels) and the AEM store answers them
6
+ * (`Parhelia.Aem.Protocol.MarkerNames`). All of them are pinned to one test vector, `providers/aem/protocol-vectors/aem.markers.json`:
7
+ * a renamed attribute fails a test in each language.
8
+ *
9
+ * Fields carry the **AEM vocabulary** (store-resolved: a render knows the item and the dialog field's name, never Parhelia's field ids,
10
+ * so the page's store answers which item and field a marker names):
11
+ *
12
+ * data-aem-item="<connector id>" the item (entity kind `item`, key: the connector's id, a lowercase UUIDv7): a component's, or the
13
+ * page's for a field of its `jcr:content`
14
+ * data-aem-field="<field name>" the field (the merged dialog's property name: `jcr:title`, `text`, a nested `a/b`)
15
+ * data-aem-richtext="true" on a rich-text field's element
16
+ *
17
+ * An AEM item lies in one language root, so a marker names no locale: an edit writes in the locale of the page the canvas shows.
18
+ * Components use Parhelia's own sentinels: a `data-component-start` / `-end` script pair carrying the component's Guid (the store's
19
+ * name-based Guid over `{installation}:{id}`), `data-component-name` its `sling:resourceType`, `data-aem-id` the connector's id and
20
+ * `data-aem-path` its path below the page's `jcr:content`; the bridge reads them itself.
21
+ *
22
+ * Markers appear in Parhelia's editing renders only; every other render is AEM's own markup.
23
+ */
24
+
25
+ /** The vocabulary's wire name: what the canvas sends with the markers it found, and what the AEM store states. */
26
+ export const AEM_MARKER_VOCABULARY = "aem";
27
+
28
+ /** The entity kind of a field marker: an item (a page or a component). */
29
+ export const AEM_ITEM_KIND = "item";
30
+
31
+ export const AEM_ITEM_ATTRIBUTE = "data-aem-item";
32
+ export const AEM_FIELD_ATTRIBUTE = "data-aem-field";
33
+ export const AEM_RICHTEXT_ATTRIBUTE = "data-aem-richtext";
34
+
35
+ /** The component sentinel's attribute carrying the connector's id. */
36
+ export const AEM_ID_ATTRIBUTE = "data-aem-id";
37
+
38
+ /** The component sentinel's attribute carrying the component's path below the page's `jcr:content`. */
39
+ export const AEM_PATH_ATTRIBUTE = "data-aem-path";
40
+
41
+ /** Parhelia addresses an AEM item as its current state (version 0). */
42
+ export const PARHELIA_AEM_VERSION = "0";
43
+
44
+ const ITEM_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
45
+ const FIELD = /^[^\s"'<>&=]{1,256}$/;
46
+
47
+ /**
48
+ * The key of an item marker: the connector's id as it spells it (a lowercase UUID); undefined for anything else (an uppercase or
49
+ * braced spelling is no connector id).
50
+ * @param {string} id
51
+ * @returns {string | undefined}
52
+ */
53
+ export const aemItemKey = id => (typeof id === "string" && ITEM_ID.test(id) ? id : undefined);
54
+
55
+ /**
56
+ * The attributes of one rendered field: the item and the field, and the rich-text flag. Nothing when `edit` is false (a render outside
57
+ * Parhelia's editing render carries no marker).
58
+ * @param {{ item: string; field: string; richText?: boolean }} ref
59
+ * @param {boolean} edit
60
+ * @returns {Record<string, string>}
61
+ */
62
+ export const aemFieldAttributes = (ref, edit) => {
63
+ if (!edit) return {};
64
+ const key = aemItemKey(ref.item);
65
+ if (!key) throw new TypeError(`An AEM field marker needs the item's connector id; got ${JSON.stringify(ref.item)}.`);
66
+ if (typeof ref.field !== "string" || !FIELD.test(ref.field))
67
+ throw new TypeError(`An AEM field marker needs the dialog field's name; got ${JSON.stringify(ref.field)}.`);
68
+ /** @type {Record<string, string>} */
69
+ const attributes = { [AEM_ITEM_ATTRIBUTE]: key, [AEM_FIELD_ATTRIBUTE]: ref.field };
70
+ if (ref.richText) attributes[AEM_RICHTEXT_ATTRIBUTE] = "true";
71
+ return attributes;
72
+ };
73
+
74
+ /**
75
+ * Whether `field` is a dialog field's name a marker may carry (no whitespace, quotes, angle brackets, `&` or `=`; at most 256
76
+ * characters).
77
+ * @param {string} field
78
+ * @returns {boolean}
79
+ */
80
+ export const isAemFieldName = field => typeof field === "string" && FIELD.test(field);
@@ -57,6 +57,8 @@ export interface ParheliaBridgeScriptOptions {
57
57
  crossOrigin?: ParheliaBridgeCrossOrigin;
58
58
  integrity?: string;
59
59
  referrerPolicy?: ParheliaBridgeReferrerPolicy;
60
+ /** The host's label (`data-parhelia-source`), which the bridge's `ready` handshake carries, e.g. `sxa`. */
61
+ source?: string;
60
62
  }
61
63
 
62
64
  export type ParheliaBridgeScriptProps = ParheliaBridgeActivationOptions & ParheliaBridgeScriptOptions;
@@ -74,6 +76,8 @@ export interface ParheliaBridgeScriptAttributes {
74
76
  "data-parhelia-editor-bridge": "runtime";
75
77
  /** The Parhelia origin when it serves the bridge; absent for a bridge origin. */
76
78
  "data-parhelia-parent-origin"?: string;
79
+ /** The host's label when one is given (`source`). */
80
+ "data-parhelia-source"?: string;
77
81
  }
78
82
 
79
83
  /** The bridge's URL on `origin`; without one, on the Parhelia origin, then on the environment's bridge origin. */
@@ -115,6 +115,7 @@ export function parheliaBridgeScriptProps({
115
115
  crossOrigin,
116
116
  integrity,
117
117
  referrerPolicy,
118
+ source,
118
119
  } = {}) {
119
120
  const editorOrigin = origin || originAlias || (bridgeOrigin ? "" : parheliaOrigin());
120
121
  const src = resolveParheliaBridgeUrl(editorOrigin || bridgeOrigin);
@@ -130,6 +131,7 @@ export function parheliaBridgeScriptProps({
130
131
  referrerPolicy,
131
132
  "data-parhelia-editor-bridge": "runtime",
132
133
  "data-parhelia-parent-origin": editorOrigin ? new URL(src).origin : undefined,
134
+ "data-parhelia-source": source || undefined,
133
135
  };
134
136
  }
135
137
 
@@ -168,6 +170,8 @@ export function loadParheliaBridge({ queryParam = "parhelia", ...options } = {})
168
170
  script.setAttribute("data-parhelia-editor-bridge", props["data-parhelia-editor-bridge"]);
169
171
  const parent = props["data-parhelia-parent-origin"];
170
172
  if (parent) script.setAttribute("data-parhelia-parent-origin", parent);
173
+ const source = props["data-parhelia-source"];
174
+ if (source) script.setAttribute("data-parhelia-source", source);
171
175
  document.body.appendChild(script);
172
176
  return true;
173
177
  }
@@ -3,3 +3,32 @@ export declare const CONTENTFUL_APP_ORIGINS: readonly string[];
3
3
 
4
4
  /** The `targetOrigin` list for `ContentfulLivePreviewProvider`: Contentful's app, this page's origin, Parhelia's. */
5
5
  export declare function contentfulLivePreviewOrigins(): string[];
6
+
7
+ /** One variant a head shows (the neutral {@link CroppedPictureVariant}). */
8
+ export type ContentfulPictureVariant = import("./picture-crops.js").CroppedPictureVariant;
9
+
10
+ /** The file and markup values of one `<source>` or the `<img>` (the neutral {@link CroppedPictureElement}). */
11
+ export type ContentfulPictureElement = import("./picture-crops.js").CroppedPictureElement;
12
+
13
+ /** How a head shows a cropped Contentful image (see {@link contentfulPictureSources}; the neutral {@link CroppedPicture}). */
14
+ export type ContentfulPicture = import("./picture-crops.js").CroppedPicture;
15
+
16
+ /** The file widths a picture offers by default. */
17
+ export declare const PICTURE_FILE_WIDTHS: readonly number[];
18
+
19
+ /**
20
+ * How a head shows a Contentful image with the crops Parhelia's app keeps beside it, cropped by the browser: the CSS, the
21
+ * clipping box's key, and the `<picture>`'s sources and image. Null when the asset has no file address or size.
22
+ */
23
+ export declare function contentfulPictureSources(
24
+ asset: { id: string; url: string; width: number; height: number },
25
+ cropsValue: unknown,
26
+ variants: readonly ContentfulPictureVariant[],
27
+ options?: {
28
+ widths?: readonly number[];
29
+ format?: string;
30
+ quality?: number;
31
+ /** The focal point (fractions) automatic crops follow where the stored value names none for this file. */
32
+ focalPoint?: { x: number; y: number } | null;
33
+ },
34
+ ): ContentfulPicture | null;
package/src/contentful.js CHANGED
@@ -4,6 +4,17 @@
4
4
  * until @parhelia/next 2.0).
5
5
  */
6
6
  import { parheliaOrigin } from "./env.js";
7
+ import {
8
+ IMAGES_API_MAX_PIXELS,
9
+ cropAttribute,
10
+ cropFor,
11
+ cropStyle,
12
+ deriveCrop,
13
+ isFocalPoint,
14
+ isImageSize,
15
+ isStale,
16
+ readPictureCrops,
17
+ } from "./picture-crops.js";
7
18
 
8
19
  /** The origins of Contentful's own web app, whose Live Preview keeps working. */
9
20
  export const CONTENTFUL_APP_ORIGINS = Object.freeze(["https://app.contentful.com", "https://app.eu.contentful.com"]);
@@ -26,3 +37,177 @@ export function contentfulLivePreviewOrigins() {
26
37
 
27
38
  /** @param {string[]} values */
28
39
  const unique = (values) => [...new Set(values.filter(Boolean))];
40
+
41
+ /**
42
+ * Picture crops (docs/contentful-picture-crops-plan.md §4.7, decision D4). How a head shows a Contentful image with the crops
43
+ * Parhelia's app keeps beside it (`@parhelia/head/picture-crops`): Contentful's Images API cannot cut a rectangle out, so the
44
+ * whole image is fetched and the browser crops it — a box of the crop's shape that clips the image, scaled and moved so the
45
+ * crop fills it.
46
+ *
47
+ * The answer is data, for any framework to render:
48
+ * - `css`: the rules for this picture, keyed by `[data-parhelia-picture=<key>]` — the box's shape and the image's size and
49
+ * offset, switched with the `<source>`s under the same media queries. Render it in a `<style>` beside the markup, unescaped
50
+ * (React: `dangerouslySetInnerHTML`; the text is this module's and the head's own media queries).
51
+ * - `box`: the clipping element's key attribute. The field's annotations go on the box too, so the editor measures the
52
+ * visible box.
53
+ * - `sources` and `img`: a `<picture>`'s sources and image, each with its file candidates (Images API `w`), the `sizes` of
54
+ * the image inside the box (the box's width over the crop's), its crop's size in pixels, the variant's name
55
+ * (`data-variant`) and the crop it applied (`data-parhelia-crop`), which the editor reads.
56
+ *
57
+ * Each variant shows its stored crop where the value is current for this file and of the variant's ratio, else the crop
58
+ * derived around the stored focal point — or, where the value names none for this file, around `options.focalPoint` (a
59
+ * point the site keeps elsewhere, such as an older focal point field), else the center. The box states the crop's ratio as
60
+ * `--parhelia-crop-ratio`, so a site that caps its height can cap its width at the same ratio. Null when the asset has no
61
+ * file address or size.
62
+ *
63
+ * @param {{ id: string, url: string, width: number, height: number }} asset the linked asset: its id, its file's address
64
+ * (`fields.file.url`, protocol-relative as Contentful gives it) and the file's size (`fields.file.details.image`)
65
+ * @param {unknown} cropsValue the crops field's stored value (the parsed JSON or its text; empty for none)
66
+ * @param {ReadonlyArray<{ name: string, ratio?: string | number | null, media?: string, sizes?: string }>} variants the
67
+ * variants the head shows, in the order its sources switch: each with its media query and its ratio (the variant set's),
68
+ * the one without a query the default; `sizes` is the box's width as a `sizes` value (one length, or a list with media
69
+ * conditions; `100vw` when absent)
70
+ * @param {{ widths?: readonly number[], format?: string, quality?: number, focalPoint?: { x: number, y: number } | null }} [options]
71
+ * the file widths to offer, the Images API's `fm` / `q`, and the focal point (fractions) to fall back on
72
+ */
73
+ export function contentfulPictureSources(asset, cropsValue, variants, options = {}) {
74
+ if (!asset || typeof asset.url !== "string" || !asset.url) return null;
75
+ if (!isImageSize({ width: asset.width, height: asset.height })) return null;
76
+ if (!Array.isArray(variants) || variants.length === 0) return null;
77
+ const size = { width: asset.width, height: asset.height };
78
+ const read = readPictureCrops(cropsValue);
79
+ const identity = { asset: asset.id, file: asset.url, size };
80
+ const widths = fileWidths(size, options.widths ?? PICTURE_FILE_WIDTHS);
81
+ // The point an automatic crop follows: the value's own, where it is current for this file; else the site's.
82
+ const current = !isStale(read, identity);
83
+ const point = current && read.focalPoint ? read.focalPoint : isFocalPoint(options.focalPoint) ? options.focalPoint : null;
84
+ const shown = variants.map((variant) => {
85
+ const stored = cropFor(read, variant, identity);
86
+ const chosen =
87
+ stored?.source === "stored"
88
+ ? stored
89
+ : {
90
+ crop: deriveCrop(variant.ratio ?? null, size, point) ?? { x: 0, y: 0, width: 1, height: 1 },
91
+ source: /** @type {const} */ ("derived"),
92
+ };
93
+ const crop = chosen.crop;
94
+ const boxSizes = variant.sizes ?? "100vw";
95
+ return {
96
+ name: variant.name,
97
+ media: variant.media ?? null,
98
+ crop,
99
+ source: chosen.source,
100
+ style: cropStyle(crop, size),
101
+ srcset: widths.map((width) => `${imagesApiUrl(asset.url, width, options)} ${width}w`).join(", "),
102
+ src: imagesApiUrl(asset.url, widths[Math.floor((widths.length - 1) / 2)] ?? size.width, options),
103
+ sizes: crop.width >= 1 ? boxSizes : scaledSizes(boxSizes, Number(crop.width.toFixed(6))),
104
+ width: Math.round(crop.width * size.width),
105
+ height: Math.round(crop.height * size.height),
106
+ attribute: cropAttribute(crop),
107
+ };
108
+ });
109
+ const fallback = shown.find((variant) => !variant.media) ?? /** @type {typeof shown[number]} */ (shown[shown.length - 1]);
110
+ const switched = shown.filter((variant) => variant !== fallback && variant.media);
111
+ const key = pictureKey([asset.id, asset.url, ...shown.map((variant) => `${variant.media}|${variant.attribute}`)].join("\n"));
112
+ // Unquoted (the key is a CSS identifier): a renderer that escapes the <style> text (React 18 on the server: `&quot;`) leaves
113
+ // the selector intact.
114
+ const selector = `[data-parhelia-picture=${key}]`;
115
+ /** @param {typeof shown[number]} variant */
116
+ const rules = (variant) =>
117
+ `${selector}{aspect-ratio:${variant.style.aspectRatio};--parhelia-crop-ratio:${variant.style.aspectRatio}}` +
118
+ `${selector} img{width:${variant.style.width};height:${variant.style.height};` +
119
+ `left:${variant.style.left};top:${variant.style.top}}`;
120
+ // The <picture> takes the first source whose query matches; CSS lets the last matching rule win, so the switched
121
+ // variants' rules come in reverse order.
122
+ const css =
123
+ `${selector}{position:relative;overflow:hidden;display:block}` +
124
+ `${selector} img{position:absolute;max-width:none;display:block}` +
125
+ rules(fallback) +
126
+ [...switched].reverse().map((variant) => `@media ${variant.media}{${rules(variant)}}`).join("");
127
+ /** @param {typeof shown[number]} variant */
128
+ const element = (variant) => ({
129
+ srcset: variant.srcset,
130
+ sizes: variant.sizes,
131
+ width: variant.width,
132
+ height: variant.height,
133
+ variant: variant.name,
134
+ crop: variant.attribute,
135
+ });
136
+ return {
137
+ key,
138
+ css,
139
+ box: { "data-parhelia-picture": key },
140
+ sources: switched.map((variant) => ({ media: /** @type {string} */ (variant.media), ...element(variant) })),
141
+ img: { src: fallback.src, ...element(fallback) },
142
+ variants: shown.map(({ name, media, crop, source }) => ({ name, media, crop, source })),
143
+ };
144
+ }
145
+
146
+ /**
147
+ * A `sizes` value for the image inside the box: each length divided by the crop's width (the whole image is that much wider
148
+ * than the box), each media condition kept. A length is the last whitespace-separated part of a candidate outside
149
+ * parentheses (`(min-width: 1024px) 40vw`, `calc(100vw - 2rem)`).
150
+ * @param {string} sizes @param {number} width
151
+ */
152
+ const scaledSizes = (sizes, width) =>
153
+ splitTopLevel(sizes, ",")
154
+ .map((candidate) => {
155
+ const parts = splitTopLevel(candidate.trim(), " ").filter(Boolean);
156
+ const length = parts.pop() ?? "100vw";
157
+ return [...parts, `calc(${length} / ${width})`].join(" ");
158
+ })
159
+ .join(", ");
160
+
161
+ /**
162
+ * The parts of a text between separators that stand outside parentheses.
163
+ * @param {string} text @param {string} separator
164
+ */
165
+ const splitTopLevel = (text, separator) => {
166
+ const parts = [""];
167
+ let depth = 0;
168
+ for (const character of text) {
169
+ if (character === "(") depth++;
170
+ else if (character === ")") depth = Math.max(0, depth - 1);
171
+ if (character === separator && depth === 0) parts.push("");
172
+ else parts[parts.length - 1] += character;
173
+ }
174
+ return parts;
175
+ };
176
+
177
+ /** The file widths a picture offers by default (the device widths Next.js's image loader asks for). */
178
+ export const PICTURE_FILE_WIDTHS = Object.freeze([640, 750, 828, 1080, 1200, 1920, 2048, 3840]);
179
+
180
+ /**
181
+ * The widths to offer: those below the original's width and the Images API's limit, then that cap itself.
182
+ * @param {{ width: number }} size @param {readonly number[]} widths
183
+ */
184
+ const fileWidths = (size, widths) => {
185
+ const cap = Math.min(size.width, IMAGES_API_MAX_PIXELS);
186
+ const below = widths.map(Math.round).filter((width) => width > 0 && width < cap);
187
+ return [...new Set(below)].sort((a, b) => a - b).concat(cap);
188
+ };
189
+
190
+ /**
191
+ * An Images API address of the file at `width` (`https:` added to Contentful's protocol-relative address).
192
+ * @param {string} url @param {number} width @param {{ format?: string, quality?: number }} options
193
+ */
194
+ const imagesApiUrl = (url, width, options) => {
195
+ const base = url.startsWith("//") ? `https:${url}` : url;
196
+ const query = [`w=${width}`];
197
+ if (options.format) query.push(`fm=${encodeURIComponent(options.format)}`);
198
+ if (options.quality) query.push(`q=${Math.round(options.quality)}`);
199
+ return `${base}${base.includes("?") ? "&" : "?"}${query.join("&")}`;
200
+ };
201
+
202
+ /**
203
+ * A short, stable key of the picture's content (FNV-1a), the same on the server and in the browser.
204
+ * @param {string} text
205
+ */
206
+ const pictureKey = (text) => {
207
+ let hash = 0x811c9dc5;
208
+ for (let index = 0; index < text.length; index++) {
209
+ hash ^= text.charCodeAt(index);
210
+ hash = Math.imul(hash, 0x01000193) >>> 0;
211
+ }
212
+ return `p${hash.toString(36)}`;
213
+ };
@@ -0,0 +1,41 @@
1
+ /** An opening marker comment, its attributes decoded. */
2
+ export type OrchardOpenMarker = {
3
+ close: false;
4
+ kind: string;
5
+ /** The Parhelia key of a coordinate the render exposed. */
6
+ key?: string;
7
+ /** The content item's id: a coordinate's, or in the key's place for one the render did not expose. */
8
+ id?: string;
9
+ attributes: Record<string, string>;
10
+ };
11
+ /** A closing marker comment. */
12
+ export type OrchardCloseMarker = { close: true; kind: string };
13
+ export type OrchardMarker = OrchardOpenMarker | OrchardCloseMarker;
14
+ /** One balanced marker pair: its two comments share a parent. */
15
+ export type OrchardMarkerPair = { marker: OrchardOpenMarker; open: Comment; close: Comment };
16
+
17
+ /** The vocabulary's wire name. */
18
+ export declare const ORCHARDCORE_MARKER_VOCABULARY: "orchardcore";
19
+ /** The marker kinds of an editing render. */
20
+ export declare const ORCHARDCORE_MARKER_KINDS: readonly string[];
21
+ /** The entity kind of a field marker naming an item. */
22
+ export declare const ORCHARDCORE_ITEM_KIND: "item";
23
+ /** The entity kind of a field marker naming a widget instance. */
24
+ export declare const ORCHARDCORE_WIDGET_KIND: "widget";
25
+ /** On the inert coordinate script of a session's page: the one element a selector finds there. */
26
+ export declare const ORCHARDCORE_RENDER_ATTRIBUTE: string;
27
+ export declare const ORCHARDCORE_KEY_ATTRIBUTE: string;
28
+ export declare const ORCHARDCORE_PATH_ATTRIBUTE: string;
29
+ export declare const ORCHARDCORE_TYPE_ATTRIBUTE: string;
30
+ export declare const ORCHARDCORE_KIND_ATTRIBUTE: string;
31
+
32
+ /** A value as the marker wrote it, decoded (.NET's `HtmlEncoder.Default`). */
33
+ export declare function decodeMarkerValue(value: string): string;
34
+ /** One comment's marker; undefined for a comment that is none of the grammar's. */
35
+ export declare function parseOrchardMarker(data: string): OrchardMarker | undefined;
36
+ /** The entity a coordinate's key names; undefined for anything that is no key. */
37
+ export declare function orchardEntityOf(key: string | undefined): { entityKind: string; entityKey: string } | undefined;
38
+ /** Every balanced marker pair below `root`, in document order of their opening comments. */
39
+ export declare function orchardMarkerPairs(root: Document | Element): OrchardMarkerPair[];
40
+ /** The nodes between a pair's comments that are content: elements and text with more than white space. */
41
+ export declare function orchardPairContent(pair: OrchardMarkerPair): ChildNode[];