@parhelia/head 1.0.12903 → 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.
- package/README.md +49 -12
- package/package.json +16 -2
- package/src/contentful.d.ts +29 -0
- package/src/contentful.js +185 -0
- package/src/picture-crops.d.ts +168 -0
- package/src/picture-crops.js +355 -0
- package/src/sitecore.d.ts +53 -0
- package/src/sitecore.js +228 -0
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
|
|
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`](
|
|
21
|
-
| [`@parhelia/astro`](
|
|
22
|
-
| [`@parhelia/next`](
|
|
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
|
|
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
|
-
|
|
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.
|
|
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,
|
|
3
|
+
"version": "1.0.12951",
|
|
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,10 @@
|
|
|
46
50
|
"types": "./src/typo3.d.ts",
|
|
47
51
|
"default": "./src/typo3.js"
|
|
48
52
|
},
|
|
53
|
+
"./sitecore": {
|
|
54
|
+
"types": "./src/sitecore.d.ts",
|
|
55
|
+
"default": "./src/sitecore.js"
|
|
56
|
+
},
|
|
49
57
|
"./vite": {
|
|
50
58
|
"types": "./src/vite.d.ts",
|
|
51
59
|
"default": "./src/vite.js"
|
|
@@ -69,6 +77,9 @@
|
|
|
69
77
|
"rich-text": [
|
|
70
78
|
"./src/rich-text.d.ts"
|
|
71
79
|
],
|
|
80
|
+
"picture-crops": [
|
|
81
|
+
"./src/picture-crops.d.ts"
|
|
82
|
+
],
|
|
72
83
|
"contentful": [
|
|
73
84
|
"./src/contentful.d.ts"
|
|
74
85
|
],
|
|
@@ -81,6 +92,9 @@
|
|
|
81
92
|
"typo3": [
|
|
82
93
|
"./src/typo3.d.ts"
|
|
83
94
|
],
|
|
95
|
+
"sitecore": [
|
|
96
|
+
"./src/sitecore.d.ts"
|
|
97
|
+
],
|
|
84
98
|
"vite": [
|
|
85
99
|
"./src/vite.d.ts"
|
|
86
100
|
],
|
package/src/contentful.d.ts
CHANGED
|
@@ -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: `"`) 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,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
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/** Where the CM serves the editing bridge. */
|
|
2
|
+
export declare const SITECORE_BRIDGE_PATH: "/parhelia/editor-bridge/v1/parhelia-bridge.js";
|
|
3
|
+
/** The attribute that marks the bridge's script tag; a page that carries it gets no second one. */
|
|
4
|
+
export declare const SITECORE_BRIDGE_ATTRIBUTE: "data-parhelia-editor-bridge";
|
|
5
|
+
/** The canvas parameters the CM's request carries and the edit-mode render passes on. */
|
|
6
|
+
export declare const PARHELIA_RENDER_PARAMS: readonly ["parhelia", "parhelia_layout"];
|
|
7
|
+
|
|
8
|
+
/** The page the CM asked an editing host to render, read from its request. */
|
|
9
|
+
export type SitecoreRenderRequest = {
|
|
10
|
+
/** The editing secret the CM sent; the SDK's handler checks it. */
|
|
11
|
+
secret: string;
|
|
12
|
+
site: string;
|
|
13
|
+
language: string;
|
|
14
|
+
/** The item's id without braces. */
|
|
15
|
+
itemId: string;
|
|
16
|
+
itemPath: string;
|
|
17
|
+
/** The site-relative route of the item. */
|
|
18
|
+
route: string;
|
|
19
|
+
version?: string;
|
|
20
|
+
/** The canvas parameters (`parhelia`, `parhelia_layout`) the request carries. */
|
|
21
|
+
parhelia: Record<string, string>;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
/** A refused request: the status and the `html` an editing host answers with. */
|
|
25
|
+
export type SitecoreRenderRefusal = { ok: false; status: 400 | 401; html: string };
|
|
26
|
+
|
|
27
|
+
export type SitecoreRenderRequestOptions = {
|
|
28
|
+
/** The query of the request itself, read for a canvas parameter the browser's request does not carry. */
|
|
29
|
+
fallbackQuery?: URLSearchParams;
|
|
30
|
+
/** The site when the layout data names none (for example the app's default site). */
|
|
31
|
+
defaultSite?: string;
|
|
32
|
+
/** The language when the request names none; `en` without one. */
|
|
33
|
+
defaultLanguage?: string;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
/** The site-relative route of an item path: `/sitecore/content/<…>/<site>/About` is `/About`. */
|
|
37
|
+
export declare function sitecoreRoute(itemPath: string, site: string): string;
|
|
38
|
+
/** Reads the CM's render request (`{ args: [path, layoutData, viewBag], jssEditingSecret }`). */
|
|
39
|
+
export declare function readSitecoreRenderRequest(
|
|
40
|
+
body: unknown,
|
|
41
|
+
options?: SitecoreRenderRequestOptions,
|
|
42
|
+
): { ok: true; request: SitecoreRenderRequest } | SitecoreRenderRefusal;
|
|
43
|
+
/** The query of the edit-mode render the SDK's own handler takes, plus the canvas parameters. */
|
|
44
|
+
export declare function sitecoreEditingQuery(request: SitecoreRenderRequest): URLSearchParams;
|
|
45
|
+
/** Whether the canvas asked for this render (`parhelia=1`). */
|
|
46
|
+
export declare function isParheliaRender(request: SitecoreRenderRequest): boolean;
|
|
47
|
+
/** The editing bridge's address on the CM; a SitecoreAI CM is always reached over HTTPS. */
|
|
48
|
+
export declare function parheliaBridgeUrl(sitecoreOrigin: string): string;
|
|
49
|
+
/** The page with the editing bridge's script before `</head>`; a page that carries it already is returned as it is. */
|
|
50
|
+
export declare function addParheliaBridge(
|
|
51
|
+
html: string,
|
|
52
|
+
options: { sitecoreOrigin: string; bridgeUrl?: string; source?: string },
|
|
53
|
+
): string;
|
package/src/sitecore.js
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@parhelia/head/sitecore` — **a SitecoreAI editing host's side of Parhelia's canvas**, framework-free.
|
|
3
|
+
*
|
|
4
|
+
* On SitecoreAI the editor runs inside the CM, and an editing host refuses to be framed by another site. So the canvas frames the
|
|
5
|
+
* CM, and the CM renders the page the way Experience Editor always did: Sitecore's JSS code on the CM sends the page's layout data
|
|
6
|
+
* as a `POST` to the editing host's `/api/editing/render` and serves the `{ "html": … }` it gets back. The SDKs Sitecore ships
|
|
7
|
+
* today answer only Pages' `GET`, so the editing host has to take that `POST` itself:
|
|
8
|
+
*
|
|
9
|
+
* 1. read the CM's request ({@link readSitecoreRenderRequest}): the item, site, language, version, route and editing secret;
|
|
10
|
+
* 2. render it in edit mode through the SDK's own handler, with the parameters Pages would have sent ({@link sitecoreEditingQuery});
|
|
11
|
+
* 3. add Parhelia's editing bridge to the page when the canvas asked for it ({@link addParheliaBridge}), and answer `{ "html": … }`.
|
|
12
|
+
*
|
|
13
|
+
* Steps 1 and 3 live here; step 2 is the framework's (`@parhelia/next/sitecore` for the Content SDK on Next.js). The bridge loads
|
|
14
|
+
* from the CM (`/parhelia/editor-bridge/v1/parhelia-bridge.js`) and talks only to the CM's origin, the frame's parent.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
/** Where the CM serves the editing bridge. */
|
|
18
|
+
export const SITECORE_BRIDGE_PATH = "/parhelia/editor-bridge/v1/parhelia-bridge.js";
|
|
19
|
+
|
|
20
|
+
/** The attribute that marks the bridge's script tag; a page that carries it gets no second one. */
|
|
21
|
+
export const SITECORE_BRIDGE_ATTRIBUTE = "data-parhelia-editor-bridge";
|
|
22
|
+
|
|
23
|
+
/** The canvas parameters the CM's request carries and the edit-mode render passes on. */
|
|
24
|
+
export const PARHELIA_RENDER_PARAMS = Object.freeze(["parhelia", "parhelia_layout"]);
|
|
25
|
+
|
|
26
|
+
const CONTENT_ROOT = "/sitecore/content/";
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* A trimmed non-empty string (or a number as text); undefined for anything else.
|
|
30
|
+
* @param {unknown} value
|
|
31
|
+
* @returns {string | undefined}
|
|
32
|
+
*/
|
|
33
|
+
function text(value) {
|
|
34
|
+
if (typeof value === "string") return value.trim() || undefined;
|
|
35
|
+
if (typeof value === "number") return String(value);
|
|
36
|
+
return undefined;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* A JSON string parsed into an object; undefined when it is not one.
|
|
41
|
+
* @param {unknown} value
|
|
42
|
+
* @returns {Record<string, any> | undefined}
|
|
43
|
+
*/
|
|
44
|
+
function json(value) {
|
|
45
|
+
if (typeof value !== "string") return undefined;
|
|
46
|
+
try {
|
|
47
|
+
const parsed = JSON.parse(value);
|
|
48
|
+
return parsed && typeof parsed === "object" ? parsed : undefined;
|
|
49
|
+
} catch {
|
|
50
|
+
return undefined;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* @param {unknown} value
|
|
56
|
+
* @returns {Record<string, any> | undefined}
|
|
57
|
+
*/
|
|
58
|
+
function object(value) {
|
|
59
|
+
return value && typeof value === "object" ? /** @type {Record<string, any>} */ (value) : undefined;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** @param {Record<string, any> | undefined} context */
|
|
63
|
+
function siteName(context) {
|
|
64
|
+
const site = context?.site;
|
|
65
|
+
return typeof site === "string" ? text(site) : text(object(site)?.name);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* The query of the browser's request to the CM, which the view bag names: its URL, then its query string.
|
|
70
|
+
* @param {Record<string, any> | undefined} httpRequest
|
|
71
|
+
*/
|
|
72
|
+
function browserQuery(httpRequest) {
|
|
73
|
+
const query = new URLSearchParams();
|
|
74
|
+
const url = text(httpRequest?.url) ?? text(httpRequest?.rawUrl) ?? text(httpRequest?.pathAndQuery);
|
|
75
|
+
if (url) {
|
|
76
|
+
try {
|
|
77
|
+
new URL(url, "http://localhost").searchParams.forEach((value, key) => query.set(key, value));
|
|
78
|
+
} catch {
|
|
79
|
+
// A malformed URL names no parameters.
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
const queryString = text(httpRequest?.queryString);
|
|
83
|
+
if (queryString)
|
|
84
|
+
new URLSearchParams(queryString.startsWith("?") ? queryString.slice(1) : queryString).forEach((value, key) => query.set(key, value));
|
|
85
|
+
return query;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* The site-relative route of an item: `/sitecore/content/<…>/<site>/About` is `/About` for the site `<site>`. A path outside
|
|
90
|
+
* `/sitecore/content/`, or one that does not name the site, is the route as it stands.
|
|
91
|
+
* @param {string} itemPath
|
|
92
|
+
* @param {string} site
|
|
93
|
+
*/
|
|
94
|
+
export function sitecoreRoute(itemPath, site) {
|
|
95
|
+
const path = itemPath.startsWith("/") ? itemPath : `/${itemPath}`;
|
|
96
|
+
const lower = path.toLowerCase();
|
|
97
|
+
if (!lower.startsWith(CONTENT_ROOT)) return path;
|
|
98
|
+
const siteSegment = `/${site.toLowerCase()}`;
|
|
99
|
+
const siteRoot = lower.lastIndexOf(siteSegment);
|
|
100
|
+
if (siteRoot < CONTENT_ROOT.length) return path;
|
|
101
|
+
return path.slice(siteRoot + siteSegment.length) || "/";
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Reads the CM's render request: the JSON body Sitecore's JSS code on the CM posts to `/api/editing/render`
|
|
106
|
+
* (`{ args: [path, layoutData, viewBag], jssEditingSecret }`, the two last arguments as JSON strings).
|
|
107
|
+
*
|
|
108
|
+
* `fallbackQuery` is the query of the request itself, read for a canvas parameter the browser's request does not carry. `defaultSite` and
|
|
109
|
+
* `defaultLanguage` stand in when the layout data names no site or language. A request without the editing secret is refused with
|
|
110
|
+
* `401`; one without an item, or with no site to render it in, with `400`.
|
|
111
|
+
* @param {unknown} body
|
|
112
|
+
* @param {{ fallbackQuery?: URLSearchParams, defaultSite?: string, defaultLanguage?: string }} [options]
|
|
113
|
+
*/
|
|
114
|
+
export function readSitecoreRenderRequest(body, options = {}) {
|
|
115
|
+
const payload = object(body);
|
|
116
|
+
if (!payload) return refusal(400, "Invalid Sitecore editor render payload");
|
|
117
|
+
|
|
118
|
+
const args = Array.isArray(payload.args) ? payload.args : [];
|
|
119
|
+
const layoutData = json(args[1]);
|
|
120
|
+
const viewBag = json(args[2]);
|
|
121
|
+
const context = object(layoutData?.sitecore?.context);
|
|
122
|
+
const route = object(layoutData?.sitecore?.route);
|
|
123
|
+
const httpContext = object(viewBag?.httpContext) ?? json(viewBag?.httpContext);
|
|
124
|
+
const httpRequest = object(httpContext?.request);
|
|
125
|
+
|
|
126
|
+
const secret = text(payload.jssEditingSecret);
|
|
127
|
+
if (!secret) return refusal(401, "Missing Sitecore editor render secret");
|
|
128
|
+
|
|
129
|
+
const itemId = (text(route?.itemId) ?? text(context?.itemId) ?? text(context?.itemID))?.replace(/[{}]/g, "");
|
|
130
|
+
const itemPath = text(args[0]) ?? text(context?.itemPath) ?? text(httpRequest?.path);
|
|
131
|
+
if (!itemId || !itemPath) return refusal(400, "Missing Sitecore editor render item data");
|
|
132
|
+
|
|
133
|
+
const site = siteName(context) ?? text(options.defaultSite);
|
|
134
|
+
if (!site) return refusal(400, "Missing Sitecore editor render site");
|
|
135
|
+
const language = text(viewBag?.language) ?? text(context?.language) ?? text(options.defaultLanguage) ?? "en";
|
|
136
|
+
|
|
137
|
+
const query = browserQuery(httpRequest);
|
|
138
|
+
const fallback = new URLSearchParams(options.fallbackQuery);
|
|
139
|
+
/** @type {Record<string, string>} */
|
|
140
|
+
const parhelia = {};
|
|
141
|
+
for (const name of PARHELIA_RENDER_PARAMS) {
|
|
142
|
+
const value = query.get(name) || fallback.get(name);
|
|
143
|
+
if (value) parhelia[name] = value;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
return {
|
|
147
|
+
ok: true,
|
|
148
|
+
request: {
|
|
149
|
+
secret,
|
|
150
|
+
site,
|
|
151
|
+
language,
|
|
152
|
+
itemId,
|
|
153
|
+
itemPath,
|
|
154
|
+
route: sitecoreRoute(itemPath, site),
|
|
155
|
+
version: text(route?.version) ?? text(context?.version),
|
|
156
|
+
parhelia,
|
|
157
|
+
},
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* @param {400 | 401} status
|
|
163
|
+
* @param {string} message
|
|
164
|
+
* @returns {{ ok: false, status: 400 | 401, html: string }}
|
|
165
|
+
*/
|
|
166
|
+
function refusal(status, message) {
|
|
167
|
+
return { ok: false, status, html: `<html><body>${message}</body></html>` };
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* The query of the edit-mode render the SDK's own handler takes, as Pages would have sent it, plus the canvas parameters.
|
|
172
|
+
* @param {{ secret: string, site: string, language: string, itemId: string, route: string, version?: string, parhelia: Record<string, string> }} request
|
|
173
|
+
*/
|
|
174
|
+
export function sitecoreEditingQuery(request) {
|
|
175
|
+
const query = new URLSearchParams({
|
|
176
|
+
secret: request.secret,
|
|
177
|
+
sc_site: request.site,
|
|
178
|
+
sc_itemid: request.itemId,
|
|
179
|
+
sc_lang: request.language,
|
|
180
|
+
route: request.route,
|
|
181
|
+
mode: "edit",
|
|
182
|
+
});
|
|
183
|
+
for (const [name, value] of Object.entries(request.parhelia)) query.set(name, value);
|
|
184
|
+
if (request.version) query.set("sc_version", request.version);
|
|
185
|
+
return query;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Whether the canvas asked for this render (`parhelia=1`), so the page gets the bridge.
|
|
190
|
+
* @param {{ parhelia: Record<string, string> }} request
|
|
191
|
+
*/
|
|
192
|
+
export function isParheliaRender(request) {
|
|
193
|
+
return request.parhelia.parhelia === "1";
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* The editing bridge's address on the CM. A SitecoreAI CM (`*.sitecorecloud.io`) is always reached over HTTPS.
|
|
198
|
+
* @param {string} sitecoreOrigin
|
|
199
|
+
*/
|
|
200
|
+
export function parheliaBridgeUrl(sitecoreOrigin) {
|
|
201
|
+
const base = /^https?:\/\//i.test(sitecoreOrigin.trim()) ? sitecoreOrigin.trim() : `https://${sitecoreOrigin.trim()}`;
|
|
202
|
+
const url = new URL(SITECORE_BRIDGE_PATH, base);
|
|
203
|
+
if (url.protocol === "http:" && url.hostname.endsWith(".sitecorecloud.io")) url.protocol = "https:";
|
|
204
|
+
return url.toString();
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** @param {string} value */
|
|
208
|
+
function attribute(value) {
|
|
209
|
+
return value.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<").replace(/>/g, ">");
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* The page with the editing bridge's script before `</head>` (at the start when it has no head). The bridge talks only to the CM,
|
|
214
|
+
* the frame's parent. A page that already carries the bridge is returned as it is.
|
|
215
|
+
* @param {string} html
|
|
216
|
+
* @param {{ sitecoreOrigin: string, bridgeUrl?: string, source?: string }} options
|
|
217
|
+
*/
|
|
218
|
+
export function addParheliaBridge(html, options) {
|
|
219
|
+
if (html.includes(`${SITECORE_BRIDGE_ATTRIBUTE}="runtime"`)) return html;
|
|
220
|
+
const parentOrigin = new URL(parheliaBridgeUrl(options.sitecoreOrigin)).origin;
|
|
221
|
+
const src = options.bridgeUrl ?? parheliaBridgeUrl(options.sitecoreOrigin);
|
|
222
|
+
const tag =
|
|
223
|
+
`<script src="${attribute(src)}" ${SITECORE_BRIDGE_ATTRIBUTE}="runtime" data-parhelia-parent-origin="${attribute(parentOrigin)}"` +
|
|
224
|
+
` data-parhelia-allowed-parent-origins="${attribute(parentOrigin)}" data-parhelia-source="${attribute(options.source ?? "sitecore")}"` +
|
|
225
|
+
` defer></script>`;
|
|
226
|
+
const headEnd = html.indexOf("</head>");
|
|
227
|
+
return headEnd >= 0 ? html.slice(0, headEnd) + tag + html.slice(headEnd) : tag + html;
|
|
228
|
+
}
|