@getquick/content 0.2.0 → 0.3.1

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.
@@ -1,276 +0,0 @@
1
- //#region frontend/src/wp-container-layout.ts
2
- const record = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
3
- /** WPGraphQL renders nested blocks independently. Restore the parent's resolved
4
- * variables on direct container children without replacing their own layout. */
5
- function containerChildLayoutHtml(html, parentHtml) {
6
- const parentTag = parentHtml.match(/^\s*<div\b[^>]*>/i)?.[0] ?? "";
7
- if (!/\bgqd-container-layout\b/.test(parentTag)) return html;
8
- const declarations = [...(parentTag.match(/\sstyle="([^"]*)"/)?.[1] ?? "").matchAll(/--gqd-layout-([a-z-]+):([^;"']+)/g)].filter(([, , value]) => value === "auto" || layoutValue(value)).map(([, name, value]) => `--gqd-parent-layout-${name}:${value}`).join(";");
9
- if (!declarations) return html;
10
- return html.replace(/^(\s*<div\b)([^>]*)(>)/i, (_, tag, props, end) => {
11
- const style = /\sstyle="([^"]*)"/;
12
- props = style.test(props) ? props.replace(style, (_match, old) => ` style="${old};${declarations}"`) : `${props} style="${declarations}"`;
13
- return `${tag}${props}${end}`;
14
- });
15
- }
16
- function layoutValue(value) {
17
- if (typeof value !== "string" && typeof value !== "number") return "";
18
- const text = String(value);
19
- const preset = text.match(/^var:preset\|spacing\|([a-z0-9-]+)$/);
20
- if (preset) return `var(--wp--preset--spacing--${preset[1]})`;
21
- return /^(?:none|0|[0-9.]+(?:px|rem|em|%|vw|vh|ch)|(?:var|calc|min|max|clamp)\([a-zA-Z0-9_.,%()+*/ -]+\))$/.test(text) ? text : "";
22
- }
23
- /** Rendered CMS shells already carry resolved theme defaults. Saved shells need
24
- * the same opt-in adapter; absent defaults deliberately fall back to no width.
25
- */
26
- function containerLayoutHtml(html, attributes) {
27
- if (/\bgqd-container-layout\b/.test(html.match(/^\s*<[^>]+>/)?.[0] ?? "")) return html;
28
- const layout = record(attributes.layout);
29
- const spacing = record(record(attributes.style).spacing);
30
- const gap = spacing.blockGap;
31
- if (!Object.keys(layout).length && (gap === void 0 || gap === null || gap === "")) return html;
32
- const type = layout.inherit || layout.contentSize ? "constrained" : layout.type ?? "default";
33
- if (type !== "default" && type !== "constrained") return html;
34
- const content = layoutValue(layout.contentSize);
35
- const wide = layoutValue(layout.wideSize);
36
- const variables = [
37
- `--gqd-layout-content:${content || wide || "var(--wp--style--global--content-size, none)"}`,
38
- `--gqd-layout-wide:${wide || content || "var(--wp--style--global--wide-size, none)"}`,
39
- `--gqd-layout-gap:${layoutValue(typeof gap === "object" ? record(gap).top : gap) || "var(--wp--style--block-gap, 0)"}`
40
- ];
41
- let classes = "gqd-container-layout";
42
- if (type === "constrained") {
43
- classes += " gqd-container-layout--constrained";
44
- variables.push(`--gqd-layout-left:${layout.justifyContent === "left" ? "0" : "auto"}`, `--gqd-layout-right:${layout.justifyContent === "right" ? "0" : "auto"}`);
45
- for (const side of ["left", "right"]) variables.push(`--gqd-layout-padding-${side}:${layoutValue(typeof spacing.padding === "object" ? record(spacing.padding)[side] : spacing.padding) || "0px"}`);
46
- }
47
- return (html || "<div class=\"wp-block-getquick-design-container\"></div>").replace(/^(\s*<div\b)([^>]*)(>)/i, (_, tag, props, end) => {
48
- const add = (name, value, separator) => {
49
- const pattern = new RegExp(`(\\s)${name}="([^"]*)"`);
50
- props = pattern.test(props) ? props.replace(pattern, (_match, space, old) => `${space}${name}="${old}${separator}${value}"`) : `${props} ${name}="${value}"`;
51
- };
52
- add("class", classes, " ");
53
- add("style", variables.join(";"), ";");
54
- return `${tag}${props}${end}`;
55
- });
56
- }
57
- //#endregion
58
- //#region frontend/src/wp-block-renderer.ts
59
- const VIDEO_HERO_BLOCK = "getquick-design/video-hero";
60
- const YOUTUBE_ID_PATTERN = /^[A-Za-z0-9_-]{11}$/;
61
- const BLOCKS_WITH_RENDERED_CHILDREN = /* @__PURE__ */ new Set([
62
- "core/cover",
63
- "core/media-text",
64
- "core/navigation",
65
- "core/navigation-submenu"
66
- ]);
67
- function isRecord(value) {
68
- return typeof value === "object" && value !== null && !Array.isArray(value);
69
- }
70
- function normalizeBlock(value) {
71
- if (!isRecord(value) || typeof value.name !== "string") return null;
72
- const attributes = isRecord(value.attributes) ? value.attributes : void 0;
73
- const innerBlocks = Array.isArray(value.innerBlocks) ? value.innerBlocks.map(normalizeBlock).filter((block) => block !== null) : [];
74
- return {
75
- name: value.name,
76
- attributes,
77
- htmlContent: typeof value.htmlContent === "string" ? value.htmlContent : "",
78
- dynamicContent: typeof value.dynamicContent === "string" ? value.dynamicContent : void 0,
79
- innerBlocks
80
- };
81
- }
82
- function parseWordPressBlocks(value) {
83
- let parsed = value;
84
- for (let attempt = 0; attempt < 2 && typeof parsed === "string"; attempt += 1) try {
85
- parsed = JSON.parse(parsed);
86
- } catch {
87
- return [];
88
- }
89
- if (!Array.isArray(parsed)) return [];
90
- return parsed.map(normalizeBlock).filter((block) => block !== null);
91
- }
92
- function hasVideoHero(blocks) {
93
- return blocks.some((block) => block.name === "getquick-design/video-hero" || hasVideoHero(block.innerBlocks ?? []));
94
- }
95
- function escapeAttribute(value) {
96
- return value.replaceAll("&", "&amp;").replaceAll("\"", "&quot;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
97
- }
98
- function safeMediaUrl(value) {
99
- if (typeof value !== "string") return "";
100
- const url = value.trim();
101
- if (!url || url.startsWith("//")) return "";
102
- if (url.startsWith("/")) return url;
103
- try {
104
- const parsed = new URL(url);
105
- return parsed.protocol === "https:" || parsed.protocol === "http:" ? url : "";
106
- } catch {
107
- return "";
108
- }
109
- }
110
- function youtubeVideoId(value) {
111
- try {
112
- const url = new URL(value);
113
- if (url.protocol !== "https:" && url.protocol !== "http:") return "";
114
- const host = url.hostname.toLowerCase().replace(/^www\./, "");
115
- let id = "";
116
- if (host === "youtu.be") id = url.pathname.split("/").filter(Boolean)[0] ?? "";
117
- else if ([
118
- "youtube.com",
119
- "m.youtube.com",
120
- "youtube-nocookie.com"
121
- ].includes(host)) {
122
- id = url.searchParams.get("v") ?? "";
123
- if (!id) id = url.pathname.match(/^\/(?:embed|shorts|live)\/([^/]+)/)?.[1] ?? "";
124
- }
125
- return YOUTUBE_ID_PATTERN.test(id) ? id : "";
126
- } catch {
127
- return "";
128
- }
129
- }
130
- function videoMarkup(attributes) {
131
- const posterUrl = safeMediaUrl(attributes.posterUrl);
132
- const poster = posterUrl ? `<img class="wp-block-getquick-design-video-hero__poster" src="${escapeAttribute(posterUrl)}" alt="" decoding="async" />` : "";
133
- if (attributes.videoType === "youtube") {
134
- const videoId = typeof attributes.videoUrl === "string" ? youtubeVideoId(attributes.videoUrl) : "";
135
- if (!videoId) return poster;
136
- return `${poster}<iframe class="wp-block-getquick-design-video-hero__video wp-block-getquick-design-video-hero__video--youtube" src="https://www.youtube-nocookie.com/embed/${videoId}?${new URLSearchParams({
137
- autoplay: "1",
138
- mute: "1",
139
- controls: "0",
140
- loop: "1",
141
- playlist: videoId,
142
- playsinline: "1",
143
- rel: "0"
144
- }).toString()}" title="Decorative background video" allow="autoplay; encrypted-media" referrerpolicy="strict-origin-when-cross-origin" tabindex="-1" aria-hidden="true"></iframe>`;
145
- }
146
- const videoUrl = safeMediaUrl(attributes.videoUrl);
147
- if (!videoUrl) return poster;
148
- const posterAttribute = posterUrl ? ` poster="${escapeAttribute(posterUrl)}"` : "";
149
- return `<video class="wp-block-getquick-design-video-hero__video" src="${escapeAttribute(videoUrl)}"${posterAttribute} autoplay muted loop playsinline preload="metadata" aria-hidden="true"></video>`;
150
- }
151
- function rootSectionShell(html) {
152
- return html.match(/^\s*(<section\b[^>]*>)/i)?.[1] ?? "<section class=\"wp-block-getquick-design-video-hero\">";
153
- }
154
- function renderVideoHero(block, children) {
155
- return `${rootSectionShell(block.htmlContent ?? "")}<div class="wp-block-getquick-design-video-hero__media" aria-hidden="true">${videoMarkup(block.attributes ?? {})}</div><div class="wp-block-getquick-design-video-hero__content">${children}</div></section>`;
156
- }
157
- function appendChildren(html, children) {
158
- if (!children) return html;
159
- const closingTag = html.lastIndexOf("</");
160
- if (closingTag < 0) return `${html}${children}`;
161
- return `${html.slice(0, closingTag)}${children}${html.slice(closingTag)}`;
162
- }
163
- function renderBlock(block, parentContainerHtml = "") {
164
- const isContainer = block.name === "getquick-design/container";
165
- let html = isContainer ? containerLayoutHtml(block.htmlContent ?? "", block.attributes ?? {}) : block.htmlContent ?? "";
166
- if (isContainer && parentContainerHtml) html = containerChildLayoutHtml(html, parentContainerHtml);
167
- const children = (block.innerBlocks ?? []).map((child) => renderBlock(child, isContainer ? html : "")).join("");
168
- if (block.name === "getquick-design/video-hero") return renderVideoHero(block, children);
169
- if (!children || BLOCKS_WITH_RENDERED_CHILDREN.has(block.name)) return html;
170
- return appendChildren(html, children);
171
- }
172
- function renderWordPressBlocks(blocks) {
173
- return blocks.map((block) => renderBlock(block)).join("");
174
- }
175
- //#endregion
176
- //#region frontend/src/site-language.ts
177
- /**
178
- * The `<html lang>` for a WordPress locale: its language and region as a
179
- * BCP 47 tag (pt_PT_ao90 → pt-PT). WordPress's variants (ao90, formal) aren't
180
- * BCP 47 subtags, so they are left out; no locale means English.
181
- */
182
- function htmlLang(locale) {
183
- if (!locale) return "en";
184
- return locale.split("_").slice(0, 2).join("-");
185
- }
186
- /**
187
- * configuration's languages: wordpress.locale, the default, served at /, then
188
- * each of wordpress.languages under its slug. A monolingual Site has one.
189
- */
190
- function siteLanguages(wordpress) {
191
- const locale = wordpress?.locale ?? "";
192
- const language = (locale, slug, isDefault) => ({
193
- locale,
194
- slug,
195
- code: slug.toUpperCase().replaceAll("-", "_"),
196
- lang: htmlLang(locale),
197
- isDefault,
198
- home: isDefault ? "/" : `/${slug}/`
199
- });
200
- return [language(locale, locale.split("_")[0] || "en", true), ...(wordpress?.languages ?? []).map(({ locale, slug }) => language(locale, slug, false))];
201
- }
202
- /**
203
- * A route's language: the one whose slug is its first segment, else the
204
- * default language, which has no directory.
205
- */
206
- function routeLanguage(route, among) {
207
- const segment = route.split("/")[1];
208
- return among.find((language) => !language.isDefault && language.slug === segment) ?? among[0];
209
- }
210
- /**
211
- * How logs and reports name something a language has: "the front page" for
212
- * the default language's, "the en front page" for another's.
213
- */
214
- function languageSubject(language, what) {
215
- return language.isDefault ? `the ${what}` : `the ${language.slug} ${what}`;
216
- }
217
- /** Whether a route is a language's home (/, /en/): served as a home, never as an entry. */
218
- function isLanguageHome(route, among) {
219
- return among.some((language) => language.home === route);
220
- }
221
- //#endregion
222
- //#region frontend/src/formatting.ts
223
- function responseStatus(delivery) {
224
- if (delivery.kind === "found") return 200;
225
- return delivery.kind === "missing" ? 404 : 503;
226
- }
227
- /**
228
- * WPGraphQL's GMT time ("2026-10-02T09:00:00", without a zone) in ms, or null
229
- * when it is absent or not a time.
230
- */
231
- function cmsTime(value) {
232
- if (!value) return null;
233
- const time = Date.parse(/(Z|[+-]\d\d:?\d\d)$/.test(value) ? value : `${value}Z`);
234
- return Number.isNaN(time) ? null : time;
235
- }
236
- /**
237
- * An entry's URI as a path. A CMS whose permalinks point at the Frontend gives
238
- * absolute URIs (`https://acme.example/team/`); only the path is the route.
239
- * Percent-encoding and the trailing slash are kept as WordPress gives them.
240
- */
241
- function uriPath(uri) {
242
- try {
243
- return new URL(uri, "https://frontend.invalid").pathname;
244
- } catch {
245
- return uri;
246
- }
247
- }
248
- function menuItemHref(url, internalOrigins) {
249
- try {
250
- const parsed = new URL(url, internalOrigins[0]);
251
- if (!internalOrigins.includes(parsed.origin)) return url;
252
- return `${parsed.pathname}${parsed.search}${parsed.hash}`;
253
- } catch {
254
- return url;
255
- }
256
- }
257
- function stripHtml(value) {
258
- return value.replace(/<[^>]*>/g, "").replace(/\s+/g, " ").trim();
259
- }
260
- function formatDate(value, lang = "en") {
261
- return new Intl.DateTimeFormat(lang, {
262
- day: "numeric",
263
- month: "long",
264
- year: "numeric"
265
- }).format(new Date(value));
266
- }
267
- function routeOf(path) {
268
- let route = path;
269
- try {
270
- route = decodeURI(path);
271
- } catch {}
272
- if (!route.startsWith("/")) route = `/${route}`;
273
- return route.endsWith("/") ? route : `${route}/`;
274
- }
275
- //#endregion
276
- export { youtubeVideoId as _, routeOf as a, htmlLang as c, routeLanguage as d, siteLanguages as f, renderWordPressBlocks as g, parseWordPressBlocks as h, responseStatus as i, isLanguageHome as l, hasVideoHero as m, formatDate as n, stripHtml as o, VIDEO_HERO_BLOCK as p, menuItemHref as r, uriPath as s, cmsTime as t, languageSubject as u, containerChildLayoutHtml as v, containerLayoutHtml as y };