@parhelia/head 0.0.0-stage → 1.0.12951

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,199 @@
1
+ /**
2
+ * `@parhelia/head/magnolia` — **the Magnolia marker names, and the helpers a head renders them with** (Magnolia MG7a,
3
+ * plan MG-D11). This module is the one JavaScript source: the editor's `magnolia` vocabulary (`@parhelia/core`,
4
+ * `bridge/vocabularies/magnolia/`) reads them by importing this module, a headless Magnolia head (MG7b) renders them, the
5
+ * Parhelia connector inside Magnolia writes them in its editing renders (`FieldMarker`, `ComponentSentinel`,
6
+ * `SlotSentinel`), and the Magnolia store answers them (`Parhelia.Magnolia.Protocol.MarkerNames`, `NodeAddress`). All of
7
+ * them are pinned to one test vector, `magnolia.markers.json` beside this file: a renamed attribute fails a test in each
8
+ * language.
9
+ *
10
+ * Fields carry the **Magnolia vocabulary** (store-resolved: a render knows the node and the form field's name, never
11
+ * Parhelia's field ids, so the page's store answers which item and field a marker names):
12
+ *
13
+ * data-mgnl-node="<jcr:uuid>" data-mgnl-workspace="<workspace>" the node (entity kind `node`, key `{workspace}:{uuid}`)
14
+ * data-mgnl-property="<form field name>" the field (the property it stores, no locale suffix)
15
+ * data-mgnl-locale="<locale>" | "*" where an edit writes; `*` for a field every locale shares
16
+ * data-mgnl-fallback="<locale>" only when the value shown is that locale's (the node holds none in the render's locale)
17
+ * data-mgnl-richtext on a rich text field's element
18
+ * data-mgnl-part="<anchor uuid>/<path>" on a composite's sub-field (lane mg-structured): the part it belongs to, one in every
19
+ * locale (entity kind `part`, key `{workspace}:{anchor uuid}/{path}`); the node attribute still
20
+ * names the node that holds the value
21
+ *
22
+ * Components and slots use Parhelia's own sentinels: a component is a `data-component-start` / `-end` script pair carrying
23
+ * the component node's uuid (its Parhelia item id) and `data-mgnl-content-type` (its template); an area is the slot
24
+ * `{areaName}_{OWNER-UUID}` (the page or component owning the area, uppercase), an area without components carries the
25
+ * empty slot's block (`data-parhelia-empty-slot`).
26
+ *
27
+ * Markers appear in Parhelia's editing renders only; every other render is Magnolia's own markup.
28
+ */
29
+
30
+ /** The vocabulary's wire name: what the canvas sends with the markers it found, and what the Magnolia store states. */
31
+ export const MAGNOLIA_MARKER_VOCABULARY = "magnolia";
32
+
33
+ /** The entity kind of a field marker naming a JCR node. */
34
+ export const MGNL_NODE_KIND = "node";
35
+
36
+ /** The entity kind of a field marker naming a structured field's part (a composite, one in every locale; lane mg-structured). */
37
+ export const MGNL_PART_KIND = "part";
38
+
39
+ export const MGNL_NODE_ATTRIBUTE = "data-mgnl-node";
40
+ export const MGNL_WORKSPACE_ATTRIBUTE = "data-mgnl-workspace";
41
+ export const MGNL_PROPERTY_ATTRIBUTE = "data-mgnl-property";
42
+ export const MGNL_LOCALE_ATTRIBUTE = "data-mgnl-locale";
43
+ export const MGNL_FALLBACK_ATTRIBUTE = "data-mgnl-fallback";
44
+ export const MGNL_RICHTEXT_ATTRIBUTE = "data-mgnl-richtext";
45
+ export const MGNL_CONTENT_TYPE_ATTRIBUTE = "data-mgnl-content-type";
46
+ export const MGNL_PART_ATTRIBUTE = "data-mgnl-part";
47
+
48
+ /** The locale a field marker states for a field every locale shares. */
49
+ export const MGNL_SHARED_LOCALE = "*";
50
+
51
+ /** Parhelia addresses a Magnolia node as its current state (version 0). */
52
+ export const PARHELIA_MAGNOLIA_VERSION = "0";
53
+
54
+ /** The block an empty slot renders in an editing render (its value: the slot's key): `ParheliaSlot`'s own. */
55
+ export { EMPTY_SLOT_ATTRIBUTE } from "./slot-markup.js";
56
+
57
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
58
+ const WORKSPACE = /^[A-Za-z][A-Za-z0-9._-]*$/;
59
+
60
+ /**
61
+ * The key of a node marker, `{workspace}:{uuid}` (the uuid lowercase, as JCR spells it); undefined for a malformed workspace or
62
+ * uuid.
63
+ * @param {string} workspace
64
+ * @param {string} uuid
65
+ * @returns {string | undefined}
66
+ */
67
+ export const mgnlNodeKey = (workspace, uuid) =>
68
+ typeof workspace === "string" && typeof uuid === "string" && WORKSPACE.test(workspace) && UUID.test(uuid)
69
+ ? `${workspace}:${uuid.toLowerCase()}`
70
+ : undefined;
71
+
72
+ /**
73
+ * Reads a node key `{workspace}:{uuid}` (the last colon separates them); undefined when it is not one.
74
+ * @param {string} key
75
+ * @returns {{ workspace: string; uuid: string } | undefined}
76
+ */
77
+ export const parseMgnlNodeKey = key => {
78
+ if (typeof key !== "string") return undefined;
79
+ const colon = key.lastIndexOf(":");
80
+ if (colon <= 0) return undefined;
81
+ const workspace = key.slice(0, colon);
82
+ const uuid = key.slice(colon + 1);
83
+ return mgnlNodeKey(workspace, uuid) ? { workspace, uuid: uuid.toLowerCase() } : undefined;
84
+ };
85
+
86
+ const PART_SEGMENT = /^[A-Za-z0-9_][A-Za-z0-9._-]*$/;
87
+
88
+ /**
89
+ * The key of a part marker, `{workspace}:{anchor uuid}/{path}` (the uuid lowercase; the path one or more field names joined by
90
+ * `/`), from the marker's workspace and its `data-mgnl-part` value; undefined when it is not one.
91
+ * @param {string} workspace
92
+ * @param {string} part
93
+ * @returns {string | undefined}
94
+ */
95
+ export const mgnlPartKey = (workspace, part) => {
96
+ if (typeof part !== "string") return undefined;
97
+ const slash = part.indexOf("/");
98
+ if (slash <= 0) return undefined;
99
+ const anchor = mgnlNodeKey(workspace, part.slice(0, slash));
100
+ const segments = part.slice(slash + 1).split("/");
101
+ if (!anchor || segments.some(segment => !PART_SEGMENT.test(segment) || segment === "..")) return undefined;
102
+ return `${anchor}/${segments.join("/")}`;
103
+ };
104
+
105
+ /**
106
+ * Reads a part key `{workspace}:{anchor uuid}/{path}` (as `mgnlPartKey` spells it); undefined when it is not one.
107
+ * @param {string} key
108
+ * @returns {{ workspace: string; anchor: string; path: string } | undefined}
109
+ */
110
+ export const parseMgnlPartKey = key => {
111
+ if (typeof key !== "string") return undefined;
112
+ const colon = key.indexOf(":");
113
+ if (colon <= 0) return undefined;
114
+ const workspace = key.slice(0, colon);
115
+ const rest = key.slice(colon + 1);
116
+ if (mgnlPartKey(workspace, rest) !== key) return undefined;
117
+ const slash = rest.indexOf("/");
118
+ return { workspace, anchor: rest.slice(0, slash), path: rest.slice(slash + 1) };
119
+ };
120
+
121
+ /**
122
+ * The field marker attributes of one rendered field; `{}` outside the editor. Throws for a malformed node or field name.
123
+ * @param {import("./magnolia.js").MgnlFieldRef} ref
124
+ * @param {boolean} edit
125
+ * @returns {Record<string, string>}
126
+ */
127
+ export const mgnlFieldAttributes = (ref, edit) => {
128
+ if (!edit) return {};
129
+ if (!mgnlNodeKey(ref.workspace, ref.uuid))
130
+ throw new TypeError(`A Magnolia field marker needs a workspace and a uuid; got ${JSON.stringify([ref.workspace, ref.uuid])}.`);
131
+ if (!ref.property) throw new TypeError("A Magnolia field marker needs the form field's name.");
132
+ const locale = ref.locale ?? MGNL_SHARED_LOCALE;
133
+ /** @type {Record<string, string>} */
134
+ const attributes = {
135
+ [MGNL_NODE_ATTRIBUTE]: ref.uuid.toLowerCase(),
136
+ [MGNL_WORKSPACE_ATTRIBUTE]: ref.workspace,
137
+ [MGNL_PROPERTY_ATTRIBUTE]: ref.property,
138
+ [MGNL_LOCALE_ATTRIBUTE]: locale,
139
+ };
140
+ if (ref.fallbackFrom && ref.fallbackFrom !== locale) attributes[MGNL_FALLBACK_ATTRIBUTE] = ref.fallbackFrom;
141
+ if (ref.part) {
142
+ if (!mgnlPartKey(ref.workspace, ref.part))
143
+ throw new TypeError(`A Magnolia part marker needs {anchor uuid}/{path}; got ${JSON.stringify(ref.part)}.`);
144
+ attributes[MGNL_PART_ATTRIBUTE] = ref.part;
145
+ }
146
+ if (ref.richText) attributes[MGNL_RICHTEXT_ATTRIBUTE] = "";
147
+ return attributes;
148
+ };
149
+
150
+ /**
151
+ * The slot key of an area: `{areaName}_{OWNER-UUID}` (the owning page's or component's uuid, uppercase).
152
+ * @param {string} areaName
153
+ * @param {string} ownerUuid
154
+ * @returns {string}
155
+ */
156
+ export const mgnlSlotKey = (areaName, ownerUuid) => {
157
+ if (!areaName) throw new TypeError("A slot key needs the area's name.");
158
+ if (!UUID.test(ownerUuid ?? "")) throw new TypeError(`A slot key needs the owner's uuid; got ${JSON.stringify(ownerUuid)}.`);
159
+ return `${areaName}_${ownerUuid.toUpperCase()}`;
160
+ };
161
+
162
+ /**
163
+ * The attributes of a component's start sentinel (an empty `<script>`), spelled as the connector's classic editing render writes
164
+ * them (`ComponentSentinel.start`): the component node's uuid as its key and item id, its template as its name and content type,
165
+ * its workspace, the rendered locale and the version Parhelia addresses (MG7b: a headless head renders the same sentinels).
166
+ * Throws for a malformed uuid or workspace.
167
+ * @param {string} uuid
168
+ * @param {string | null | undefined} template
169
+ * @param {string | null | undefined} language
170
+ * @param {string} [workspace]
171
+ * @returns {Record<string, string>}
172
+ */
173
+ export const mgnlComponentStartAttributes = (uuid, template, language, workspace = "website") => {
174
+ if (!mgnlNodeKey(workspace, uuid))
175
+ throw new TypeError(`A component sentinel needs a workspace and a uuid; got ${JSON.stringify([workspace, uuid])}.`);
176
+ const key = uuid.toLowerCase();
177
+ const type = template ?? "";
178
+ /** @type {Record<string, string>} */
179
+ const attributes = {
180
+ "data-component-start": key,
181
+ "data-itemid": key,
182
+ "data-component-name": type,
183
+ [MGNL_CONTENT_TYPE_ATTRIBUTE]: type,
184
+ [MGNL_WORKSPACE_ATTRIBUTE]: workspace,
185
+ };
186
+ if (language) attributes["data-language"] = language;
187
+ attributes["data-version"] = PARHELIA_MAGNOLIA_VERSION;
188
+ return attributes;
189
+ };
190
+
191
+ /**
192
+ * The attributes of a component's end sentinel (`ComponentSentinel.end`). Throws for a malformed uuid.
193
+ * @param {string} uuid
194
+ * @returns {Record<string, string>}
195
+ */
196
+ export const mgnlComponentEndAttributes = uuid => {
197
+ if (!UUID.test(uuid ?? "")) throw new TypeError(`A component sentinel needs the component's uuid; got ${JSON.stringify(uuid)}.`);
198
+ return { "data-component-end": uuid.toLowerCase() };
199
+ };
@@ -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
+ }