@parhelia/head 0.0.0-stage → 1.0.12951
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +8 -0
- package/README.md +231 -2
- package/package.json +133 -4
- package/src/bridge-core.d.ts +97 -0
- package/src/bridge-core.js +173 -0
- package/src/contentful.d.ts +34 -0
- package/src/contentful.js +213 -0
- package/src/env.d.ts +11 -0
- package/src/env.js +47 -0
- package/src/identity.d.ts +45 -0
- package/src/identity.js +137 -0
- package/src/index.d.ts +6 -0
- package/src/index.js +13 -0
- package/src/magnolia.d.ts +60 -0
- package/src/magnolia.js +199 -0
- package/src/picture-crops.d.ts +168 -0
- package/src/picture-crops.js +355 -0
- package/src/refresh-dom.d.ts +9 -0
- package/src/refresh-dom.js +92 -0
- package/src/refresh.d.ts +14 -0
- package/src/refresh.js +63 -0
- package/src/rich-text-reader.js +263 -0
- package/src/rich-text.d.ts +17 -0
- package/src/rich-text.js +354 -0
- package/src/server.d.ts +38 -0
- package/src/server.js +113 -0
- package/src/settings.cjs +35 -0
- package/src/settings.d.cts +7 -0
- package/src/sitecore.d.ts +53 -0
- package/src/sitecore.js +228 -0
- package/src/slot-markup.d.ts +5 -0
- package/src/slot-markup.js +24 -0
- package/src/typo3.d.ts +34 -0
- package/src/typo3.js +110 -0
- package/src/umbraco.d.ts +51 -0
- package/src/umbraco.js +146 -0
- package/src/vite.d.ts +18 -0
- package/src/vite.js +53 -0
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/** The origins of Contentful's own web app. */
|
|
2
|
+
export declare const CONTENTFUL_APP_ORIGINS: readonly string[];
|
|
3
|
+
|
|
4
|
+
/** The `targetOrigin` list for `ContentfulLivePreviewProvider`: Contentful's app, this page's origin, Parhelia's. */
|
|
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;
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@parhelia/head/contentful` — a Contentful head's helpers (Umbraco program thirdcms-frontend: the vendor's own entry; the
|
|
3
|
+
* package root stays CMS-neutral. `@parhelia/next`'s root still re-exports these for heads built before the entry existed,
|
|
4
|
+
* until @parhelia/next 2.0).
|
|
5
|
+
*/
|
|
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";
|
|
18
|
+
|
|
19
|
+
/** The origins of Contentful's own web app, whose Live Preview keeps working. */
|
|
20
|
+
export const CONTENTFUL_APP_ORIGINS = Object.freeze(["https://app.contentful.com", "https://app.eu.contentful.com"]);
|
|
21
|
+
|
|
22
|
+
/** @type {string[] | undefined} */
|
|
23
|
+
let browserOrigins;
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The `targetOrigin` list for Contentful's `ContentfulLivePreviewProvider`: Contentful's own app, the page's own origin
|
|
27
|
+
* (the editor frames a proxied head from its own origin) and the configured Parhelia origin (a head the editor frames
|
|
28
|
+
* directly). Computed in the browser, so moving the editor needs no rebuild of a proxied head. Without a targetOrigin
|
|
29
|
+
* the SDK throws in every frame but Contentful's.
|
|
30
|
+
*/
|
|
31
|
+
export function contentfulLivePreviewOrigins() {
|
|
32
|
+
const origins = [...CONTENTFUL_APP_ORIGINS];
|
|
33
|
+
if (typeof window === "undefined") return unique([...origins, parheliaOrigin()]);
|
|
34
|
+
// One array per page load: the provider sees the same value on every render.
|
|
35
|
+
return (browserOrigins ??= unique([...origins, window.location.origin, parheliaOrigin()]));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** @param {string[]} values */
|
|
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
|
+
};
|
package/src/env.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** Sets the origin and base path explicitly, for a framework whose build inlines nothing; wins over inlined values. */
|
|
2
|
+
export declare function configureParhelia(values: { origin?: string; basePath?: string }): void;
|
|
3
|
+
|
|
4
|
+
/** The Parhelia editor origin (`PARHELIA_ORIGIN`); "" when unset. */
|
|
5
|
+
export declare function parheliaOrigin(): string;
|
|
6
|
+
|
|
7
|
+
/** The head's base path below the rendering proxy (`PARHELIA_BASE_PATH`); "" when none. */
|
|
8
|
+
export declare function parheliaBasePath(): string;
|
|
9
|
+
|
|
10
|
+
/** A root-relative path below the head's basePath. */
|
|
11
|
+
export declare function withBasePath(path: string): string;
|
package/src/env.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The two values of a head's build that the browser needs as much as the server: the base path below Parhelia's
|
|
3
|
+
* rendering proxy (`PARHELIA_BASE_PATH`) and the Parhelia editor's origin (`PARHELIA_ORIGIN`). A server render and
|
|
4
|
+
* hydration must read the same values, so they come from the build, not from the server's environment:
|
|
5
|
+
*
|
|
6
|
+
* - Next.js: `withParhelia` (`@parhelia/next/config`) puts them into `env`, which Next.js inlines.
|
|
7
|
+
* - Vite (TanStack Start, React Router, …): the `parhelia()` plugin (`@parhelia/head/vite`, used by `@parhelia/astro` too) defines them.
|
|
8
|
+
* - Anything else: call `configureParhelia({ origin, basePath })` in a module both the server and the browser load.
|
|
9
|
+
*
|
|
10
|
+
* The reads are literal `process.env.X` expressions, which is what a bundler's inlining replaces.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** @type {{ origin?: string, basePath?: string }} */
|
|
14
|
+
let configured = {};
|
|
15
|
+
|
|
16
|
+
/** @param {() => string | undefined} value */
|
|
17
|
+
const read = (value) => {
|
|
18
|
+
try {
|
|
19
|
+
return value() || "";
|
|
20
|
+
} catch {
|
|
21
|
+
return ""; // no `process` in this bundle and nothing inlined
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Sets the values explicitly, for a framework whose build inlines nothing. A value given here wins over the inlined one.
|
|
27
|
+
* @param {{ origin?: string, basePath?: string }} values
|
|
28
|
+
*/
|
|
29
|
+
export function configureParhelia(values) {
|
|
30
|
+
const origin = values.origin === undefined ? undefined : String(values.origin).trim().replace(/\/+$/, "");
|
|
31
|
+
const basePath = values.basePath === undefined ? undefined : String(values.basePath).trim().replace(/\/+$/, "");
|
|
32
|
+
configured = {
|
|
33
|
+
...configured,
|
|
34
|
+
...(origin === undefined ? {} : { origin }),
|
|
35
|
+
...(basePath === undefined ? {} : { basePath }),
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The Parhelia editor origin (`PARHELIA_ORIGIN`); "" when unset. */
|
|
40
|
+
export const parheliaOrigin = () => configured.origin ?? read(() => process.env.PARHELIA_ORIGIN);
|
|
41
|
+
|
|
42
|
+
/** The head's base path below the rendering proxy (`PARHELIA_BASE_PATH`); "" when none. */
|
|
43
|
+
export const parheliaBasePath = () => configured.basePath ?? read(() => process.env.PARHELIA_BASE_PATH);
|
|
44
|
+
|
|
45
|
+
/** A root-relative path below the head's basePath: `fetch(withBasePath("/api/content"))`. */
|
|
46
|
+
/** @param {string} path */
|
|
47
|
+
export const withBasePath = (path) => `${parheliaBasePath()}${path.startsWith("/") ? path : `/${path}`}`;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/** The attribute of the inert JSON script that states what a render produced. */
|
|
2
|
+
export declare const RENDERED_IDENTITY_ATTRIBUTE: "data-parhelia-rendered-coordinate";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* What THIS render produced, as the head's own data names it: the Parhelia store the head renders, the item's id as its
|
|
6
|
+
* CMS spells it (a Contentful entry's `sys.id`, a Sitecore item's Guid), the locale, and the version where the CMS keeps
|
|
7
|
+
* numbered versions (omitted where it keeps none).
|
|
8
|
+
*/
|
|
9
|
+
export interface RenderedIdentity {
|
|
10
|
+
store: string;
|
|
11
|
+
itemId: string;
|
|
12
|
+
language: string;
|
|
13
|
+
version?: number;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** The Parhelia store this head renders (`PARHELIA_STORE`), trimmed; "" when unset. Server-side. */
|
|
17
|
+
export declare function parheliaStore(): string;
|
|
18
|
+
|
|
19
|
+
/** The identity as HTML-escaped inert JSON. Throws a TypeError for a blank part or an invalid version. */
|
|
20
|
+
export declare function renderedIdentityJson(identity: RenderedIdentity): string;
|
|
21
|
+
|
|
22
|
+
/** The props of a React `<script>` that states the identity: `<script {...renderedIdentityScriptProps(identity)} />`. */
|
|
23
|
+
export declare function renderedIdentityScriptProps(identity: RenderedIdentity): {
|
|
24
|
+
type: "application/json";
|
|
25
|
+
"data-parhelia-rendered-coordinate": "";
|
|
26
|
+
dangerouslySetInnerHTML: { __html: string };
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
/** The script element as HTML, for a head that writes its markup itself. */
|
|
30
|
+
export declare function renderedIdentityScriptHtml(identity: RenderedIdentity): string;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* The identity a render states, or null: in Parhelia's frames only, with the head's store (`PARHELIA_STORE`) and the ids
|
|
34
|
+
* of the data the page itself read. Null outside Parhelia's frames, when the render produced no item, and when the head
|
|
35
|
+
* names no store (logged once). Throws a TypeError for a malformed part.
|
|
36
|
+
*/
|
|
37
|
+
export declare function frameRenderedIdentity(
|
|
38
|
+
query: URLSearchParams | Record<string, string | string[] | undefined> | null | undefined,
|
|
39
|
+
rendered: { itemId?: string | null; language?: string | null; version?: number },
|
|
40
|
+
): RenderedIdentity | null;
|
|
41
|
+
|
|
42
|
+
/** Whether a request is one of Parhelia's frames (`parhelia=1`): pages-router `query`, App Router `searchParams`, or URLSearchParams. */
|
|
43
|
+
export declare function isParheliaFrameRequest(
|
|
44
|
+
query: URLSearchParams | Record<string, string | string[] | undefined> | null | undefined,
|
|
45
|
+
): boolean;
|
package/src/identity.js
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@parhelia/head/identity` — the renderer-owned content identity (W11 A3 `w11-a3-capture-rendered-identity.md`, multi-cms
|
|
3
|
+
* capturemcms): the one inert JSON script `data-parhelia-rendered-coordinate` in which a head states the item THIS render
|
|
4
|
+
* produced. Parhelia's capture (agent screenshots, DOM captures, component thumbnails) reads it from the rendered document
|
|
5
|
+
* and refuses a document that does not state exactly the target it asked for.
|
|
6
|
+
*
|
|
7
|
+
* - `store`: the Parhelia store the head renders. A Contentful head is configured with it (`PARHELIA_STORE`, see
|
|
8
|
+
* `parheliaStore`): Parhelia names a space by its concrete environment, which an aliased environment does not show.
|
|
9
|
+
* - `itemId`: the item's id as its CMS spells it, from the data the head rendered: a Contentful entry's `sys.id`, a
|
|
10
|
+
* Sitecore item's Guid. Never the request's query or the editor's selection.
|
|
11
|
+
* - `language`: the locale the head rendered.
|
|
12
|
+
* - `version`: the version rendered, where the CMS keeps numbered versions (Sitecore); omitted where it keeps none
|
|
13
|
+
* (Contentful).
|
|
14
|
+
*
|
|
15
|
+
* No React and no Next.js import: any head can call it, and a head that links this package from a checkout (a `file:`
|
|
16
|
+
* dependency) never resolves a second React through it. Render the script only in Parhelia's frames
|
|
17
|
+
* (`isParheliaFrameRequest`), where the editor's capture reads it.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
export const RENDERED_IDENTITY_ATTRIBUTE = "data-parhelia-rendered-coordinate";
|
|
21
|
+
|
|
22
|
+
/** @param {() => string | undefined} value */
|
|
23
|
+
const read = (value) => {
|
|
24
|
+
try {
|
|
25
|
+
return value() || "";
|
|
26
|
+
} catch {
|
|
27
|
+
return ""; // no `process` in this bundle
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The Parhelia store this head renders (`PARHELIA_STORE`, e.g. `contentful:<space>/<environment>`), trimmed; "" when unset.
|
|
33
|
+
* Server-side: read it where the page's data is read (getServerSideProps, a server component) and hand the identity to
|
|
34
|
+
* the component that renders it, so the server's and the browser's render state the same.
|
|
35
|
+
*/
|
|
36
|
+
export const parheliaStore = () => read(() => process.env.PARHELIA_STORE).trim();
|
|
37
|
+
|
|
38
|
+
/** @param {string} name @param {unknown} value */
|
|
39
|
+
const requireText = (name, value) => {
|
|
40
|
+
if (typeof value !== "string" || !value || value !== value.trim() || value.includes("\0")) {
|
|
41
|
+
throw new TypeError(`A rendered identity needs a non-empty ${name} without surrounding blanks; got ${JSON.stringify(value)}.`);
|
|
42
|
+
}
|
|
43
|
+
return value;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* The identity as the inert JSON a `<script type="application/json">` carries, HTML-escaped so the script stays data
|
|
48
|
+
* whatever the values contain.
|
|
49
|
+
* @param {{ store: string, itemId: string, language: string, version?: number }} identity
|
|
50
|
+
* @returns {string}
|
|
51
|
+
*/
|
|
52
|
+
export function renderedIdentityJson(identity) {
|
|
53
|
+
if (!identity || typeof identity !== "object") throw new TypeError("A rendered identity is an object.");
|
|
54
|
+
const { store, itemId, language, version } = identity;
|
|
55
|
+
if (version !== undefined && !(typeof version === "number" && Number.isInteger(version) && version >= 0)) {
|
|
56
|
+
throw new TypeError(`A rendered identity's version is a non-negative integer or absent; got ${JSON.stringify(version)}.`);
|
|
57
|
+
}
|
|
58
|
+
const coordinate = {
|
|
59
|
+
coordinateVersion: 1,
|
|
60
|
+
store: requireText("store", store),
|
|
61
|
+
itemId: requireText("itemId", itemId),
|
|
62
|
+
language: requireText("language", language),
|
|
63
|
+
...(version === undefined ? {} : { version }),
|
|
64
|
+
};
|
|
65
|
+
return JSON.stringify(coordinate)
|
|
66
|
+
.replace(/</g, "\\u003c")
|
|
67
|
+
.replace(/>/g, "\\u003e")
|
|
68
|
+
.replace(/&/g, "\\u0026");
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* The props of a React `<script>` element that states the identity: `<script {...renderedIdentityScriptProps(identity)} />`.
|
|
73
|
+
* @param {{ store: string, itemId: string, language: string, version?: number }} identity
|
|
74
|
+
*/
|
|
75
|
+
export function renderedIdentityScriptProps(identity) {
|
|
76
|
+
return {
|
|
77
|
+
type: "application/json",
|
|
78
|
+
[RENDERED_IDENTITY_ATTRIBUTE]: "",
|
|
79
|
+
dangerouslySetInnerHTML: { __html: renderedIdentityJson(identity) },
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* The script element as HTML, for a head that writes its markup itself.
|
|
85
|
+
* @param {{ store: string, itemId: string, language: string, version?: number }} identity
|
|
86
|
+
*/
|
|
87
|
+
export function renderedIdentityScriptHtml(identity) {
|
|
88
|
+
return `<script type="application/json" ${RENDERED_IDENTITY_ATTRIBUTE}>${renderedIdentityJson(identity)}</script>`;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
let warnedNoStore = false;
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* The identity a render states, or null: in Parhelia's frames (`isParheliaFrameRequest(query)`) only, with the head's
|
|
95
|
+
* store (`PARHELIA_STORE`) and the ids of the data the page itself read (`itemId`: the item's own id as its CMS spells
|
|
96
|
+
* it; `language`; `version` where the CMS keeps numbered versions). Null outside Parhelia's frames and when the render
|
|
97
|
+
* produced no item. In a frame of a head that names no store it is null too, and the server log says once why
|
|
98
|
+
* Parhelia's capture refuses the head's renders.
|
|
99
|
+
*
|
|
100
|
+
* For a pages-router head: call it in getServerSideProps, pass the result as a page prop, and render
|
|
101
|
+
* `<script {...renderedIdentityScriptProps(identity)} />` where it is not null.
|
|
102
|
+
* @param {URLSearchParams | Record<string, string | string[] | undefined> | null | undefined} query
|
|
103
|
+
* @param {{ itemId?: string | null, language?: string | null, version?: number }} rendered
|
|
104
|
+
* @returns {{ store: string, itemId: string, language: string, version?: number } | null}
|
|
105
|
+
*/
|
|
106
|
+
export function frameRenderedIdentity(query, rendered) {
|
|
107
|
+
if (!isParheliaFrameRequest(query)) return null;
|
|
108
|
+
const itemId = rendered?.itemId;
|
|
109
|
+
const language = rendered?.language;
|
|
110
|
+
if (!itemId || !language) return null;
|
|
111
|
+
const store = parheliaStore();
|
|
112
|
+
if (!store) {
|
|
113
|
+
if (!warnedNoStore) {
|
|
114
|
+
warnedNoStore = true;
|
|
115
|
+
console.warn(
|
|
116
|
+
"@parhelia/head: PARHELIA_STORE is not set, so this head states no rendered identity and Parhelia's capture " +
|
|
117
|
+
"(agent screenshots, component thumbnails) refuses its renders. Set it to the store the head renders " +
|
|
118
|
+
"(Settings > Rendering Hosts > the head's settings).",
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
const identity = { store, itemId, language, ...(rendered.version === undefined ? {} : { version: rendered.version }) };
|
|
124
|
+
renderedIdentityJson(identity); // refuses a malformed part by name here, not later at render
|
|
125
|
+
return identity;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Whether a request is one of Parhelia's frames: the editor's canvas and its offscreen capture render with `parhelia=1`.
|
|
130
|
+
* Takes the pages router's `query`, the App Router's `searchParams` object, or a `URLSearchParams`.
|
|
131
|
+
* @param {URLSearchParams | Record<string, string | string[] | undefined> | null | undefined} query
|
|
132
|
+
*/
|
|
133
|
+
export function isParheliaFrameRequest(query) {
|
|
134
|
+
if (!query) return false;
|
|
135
|
+
const value = typeof query.get === "function" ? query.get("parhelia") : /** @type {Record<string, unknown>} */ (query).parhelia;
|
|
136
|
+
return Array.isArray(value) ? value.length === 1 && value[0] === "1" : value === "1";
|
|
137
|
+
}
|
package/src/index.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export * from "./bridge-core.js";
|
|
2
|
+
export * from "./slot-markup.js";
|
|
3
|
+
export * from "./identity.js";
|
|
4
|
+
export { installParheliaRefresh } from "./refresh.js";
|
|
5
|
+
export * from "./refresh-dom.js";
|
|
6
|
+
export { configureParhelia, parheliaOrigin, parheliaBasePath, withBasePath } from "./env.js";
|
package/src/index.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@parhelia/head` — what any rendering head needs to be edited in Parhelia, on any framework and without one (Astro, plain
|
|
3
|
+
* HTML, any server templating; React heads add `@parhelia/react`, Next.js heads `@parhelia/next`, Astro heads `@parhelia/astro`):
|
|
4
|
+
* the build's base path and origin, the editing bridge (its `<script>` attributes, `loadParheliaBridge` for the browser),
|
|
5
|
+
* the slot markers, the rendered-content identity and the in-place refresh. Server-only: `@parhelia/head/server`; a CMS's
|
|
6
|
+
* own markers: `@parhelia/head/<cms>`; rich text: `@parhelia/head/rich-text`. Nothing here imports React.
|
|
7
|
+
*/
|
|
8
|
+
export * from "./bridge-core.js";
|
|
9
|
+
export * from "./slot-markup.js";
|
|
10
|
+
export * from "./identity.js";
|
|
11
|
+
export { installParheliaRefresh } from "./refresh.js";
|
|
12
|
+
export * from "./refresh-dom.js";
|
|
13
|
+
export { configureParhelia, parheliaOrigin, parheliaBasePath, withBasePath } from "./env.js";
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/** One rendered field's identity, as a Magnolia render knows it. */
|
|
2
|
+
export type MgnlFieldRef = {
|
|
3
|
+
/** The node's workspace (`website`, `dam`, a content-type workspace). */
|
|
4
|
+
workspace: string;
|
|
5
|
+
/** The node's `jcr:uuid`. */
|
|
6
|
+
uuid: string;
|
|
7
|
+
/** The form field's name (the property it stores, without a locale suffix). */
|
|
8
|
+
property: string;
|
|
9
|
+
/** The rendered locale for a field stored per locale; null for a field every locale shares (`*`). */
|
|
10
|
+
locale: string | null;
|
|
11
|
+
/** The locale whose value is shown instead, when the node holds none in the rendered locale. */
|
|
12
|
+
fallbackFrom?: string | null;
|
|
13
|
+
/** The field's element holds rich text. */
|
|
14
|
+
richText?: boolean;
|
|
15
|
+
/** A composite's sub-field: the part it belongs to, `{anchor uuid}/{path}` (lane mg-structured). */
|
|
16
|
+
part?: string | null;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
/** The vocabulary's wire name. */
|
|
20
|
+
export declare const MAGNOLIA_MARKER_VOCABULARY: "magnolia";
|
|
21
|
+
/** The entity kind of a field marker naming a node. */
|
|
22
|
+
export declare const MGNL_NODE_KIND: "node";
|
|
23
|
+
/** The entity kind of a field marker naming a structured field's part. */
|
|
24
|
+
export declare const MGNL_PART_KIND: "part";
|
|
25
|
+
export declare const MGNL_NODE_ATTRIBUTE: string;
|
|
26
|
+
export declare const MGNL_WORKSPACE_ATTRIBUTE: string;
|
|
27
|
+
export declare const MGNL_PROPERTY_ATTRIBUTE: string;
|
|
28
|
+
export declare const MGNL_LOCALE_ATTRIBUTE: string;
|
|
29
|
+
export declare const MGNL_FALLBACK_ATTRIBUTE: string;
|
|
30
|
+
export declare const MGNL_RICHTEXT_ATTRIBUTE: string;
|
|
31
|
+
export declare const MGNL_CONTENT_TYPE_ATTRIBUTE: string;
|
|
32
|
+
export declare const MGNL_PART_ATTRIBUTE: string;
|
|
33
|
+
/** The locale a field marker states for a field every locale shares. */
|
|
34
|
+
export declare const MGNL_SHARED_LOCALE: "*";
|
|
35
|
+
/** Parhelia addresses a Magnolia node as its current state. */
|
|
36
|
+
export declare const PARHELIA_MAGNOLIA_VERSION: "0";
|
|
37
|
+
/** The block an empty slot renders in an editing render: `ParheliaSlot`'s own. */
|
|
38
|
+
export { EMPTY_SLOT_ATTRIBUTE } from "./slot-markup.js";
|
|
39
|
+
|
|
40
|
+
/** The key of a node marker, `{workspace}:{uuid}`; undefined for a malformed workspace or uuid. */
|
|
41
|
+
export declare function mgnlNodeKey(workspace: string, uuid: string): string | undefined;
|
|
42
|
+
/** Reads a node key `{workspace}:{uuid}`; undefined when it is not one. */
|
|
43
|
+
export declare function parseMgnlNodeKey(key: string): { workspace: string; uuid: string } | undefined;
|
|
44
|
+
/** The key of a part marker, `{workspace}:{anchor uuid}/{path}`; undefined when it is not one. */
|
|
45
|
+
export declare function mgnlPartKey(workspace: string, part: string): string | undefined;
|
|
46
|
+
/** Reads a part key `{workspace}:{anchor uuid}/{path}`; undefined when it is not one. */
|
|
47
|
+
export declare function parseMgnlPartKey(key: string): { workspace: string; anchor: string; path: string } | undefined;
|
|
48
|
+
/** The field marker attributes of one rendered field; `{}` outside the editor. */
|
|
49
|
+
export declare function mgnlFieldAttributes(ref: MgnlFieldRef, edit: boolean): Record<string, string>;
|
|
50
|
+
/** The slot key of an area: `{areaName}_{OWNER-UUID}`. */
|
|
51
|
+
export declare function mgnlSlotKey(areaName: string, ownerUuid: string): string;
|
|
52
|
+
/** The attributes of a component's start sentinel, as the connector's classic editing render spells them. */
|
|
53
|
+
export declare function mgnlComponentStartAttributes(
|
|
54
|
+
uuid: string,
|
|
55
|
+
template: string | null | undefined,
|
|
56
|
+
language: string | null | undefined,
|
|
57
|
+
workspace?: string,
|
|
58
|
+
): Record<string, string>;
|
|
59
|
+
/** The attributes of a component's end sentinel. */
|
|
60
|
+
export declare function mgnlComponentEndAttributes(uuid: string): Record<string, string>;
|