@getquick/content 0.2.0 → 0.3.0

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.
@@ -64,12 +64,12 @@ const BLOCKS_WITH_RENDERED_CHILDREN = /* @__PURE__ */ new Set([
64
64
  "core/navigation",
65
65
  "core/navigation-submenu"
66
66
  ]);
67
- function isRecord(value) {
67
+ function isRecord$1(value) {
68
68
  return typeof value === "object" && value !== null && !Array.isArray(value);
69
69
  }
70
70
  function normalizeBlock(value) {
71
- if (!isRecord(value) || typeof value.name !== "string") return null;
72
- const attributes = isRecord(value.attributes) ? value.attributes : void 0;
71
+ if (!isRecord$1(value) || typeof value.name !== "string") return null;
72
+ const attributes = isRecord$1(value.attributes) ? value.attributes : void 0;
73
73
  const innerBlocks = Array.isArray(value.innerBlocks) ? value.innerBlocks.map(normalizeBlock).filter((block) => block !== null) : [];
74
74
  return {
75
75
  name: value.name,
@@ -173,52 +173,6 @@ function renderWordPressBlocks(blocks) {
173
173
  return blocks.map((block) => renderBlock(block)).join("");
174
174
  }
175
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
176
  //#region frontend/src/formatting.ts
223
177
  function responseStatus(delivery) {
224
178
  if (delivery.kind === "found") return 200;
@@ -257,6 +211,33 @@ function menuItemHref(url, internalOrigins) {
257
211
  function stripHtml(value) {
258
212
  return value.replace(/<[^>]*>/g, "").replace(/\s+/g, " ").trim();
259
213
  }
214
+ /** The named character references WordPress's text commonly has (wptexturize writes most as numbers). */
215
+ const NAMED_ENTITIES = {
216
+ amp: "&",
217
+ lt: "<",
218
+ gt: ">",
219
+ quot: "\"",
220
+ apos: "'",
221
+ nbsp: "\xA0",
222
+ ndash: "–",
223
+ mdash: "—",
224
+ lsquo: "‘",
225
+ rsquo: "’",
226
+ ldquo: "“",
227
+ rdquo: "”",
228
+ hellip: "…"
229
+ };
230
+ /**
231
+ * Text with its HTML character references decoded: numeric ones, and the
232
+ * named ones in NAMED_ENTITIES (any other is left as written).
233
+ */
234
+ function decodeEntities(value) {
235
+ return value.replace(/&(#x[0-9a-f]+|#[0-9]+|[a-z]+);/gi, (reference, name) => {
236
+ if (name[0] !== "#") return NAMED_ENTITIES[name.toLowerCase()] ?? reference;
237
+ const code = name[1] === "x" || name[1] === "X" ? parseInt(name.slice(2), 16) : Number(name.slice(1));
238
+ return code > 0 && code <= 1114111 ? String.fromCodePoint(code) : reference;
239
+ });
240
+ }
260
241
  function formatDate(value, lang = "en") {
261
242
  return new Intl.DateTimeFormat(lang, {
262
243
  day: "numeric",
@@ -273,4 +254,275 @@ function routeOf(path) {
273
254
  return route.endsWith("/") ? route : `${route}/`;
274
255
  }
275
256
  //#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 };
257
+ //#region frontend/src/design-patterns.ts
258
+ function isRecord(value) {
259
+ return typeof value === "object" && value !== null && !Array.isArray(value);
260
+ }
261
+ /**
262
+ * A complete pattern tree from JSON text or a parsed list. Malformed nodes
263
+ * fail the whole read: dropping one could promote a partial header or footer.
264
+ * PHP's empty attributes (`[]`) normalize to an object.
265
+ */
266
+ function parseDesignBlocks(value) {
267
+ let parsed = value;
268
+ if (typeof parsed === "string") try {
269
+ parsed = JSON.parse(parsed);
270
+ } catch {
271
+ return;
272
+ }
273
+ let count = 0;
274
+ const blocks = (value, depth) => {
275
+ if (!Array.isArray(value) || value.length > 0 && depth > 32) return void 0;
276
+ const result = [];
277
+ for (const item of value) {
278
+ if (++count > 1e3 || !isRecord(item) || typeof item.name !== "string" || !item.name) return void 0;
279
+ const attributes = isRecord(item.attributes) ? item.attributes : Array.isArray(item.attributes) && item.attributes.length === 0 ? {} : void 0;
280
+ if (!attributes || item.content !== null && typeof item.content !== "string") return void 0;
281
+ const children = blocks(item.children, depth + 1);
282
+ if (!children) return void 0;
283
+ result.push({
284
+ name: item.name,
285
+ attributes,
286
+ content: item.content,
287
+ children
288
+ });
289
+ }
290
+ return result;
291
+ };
292
+ return blocks(parsed, 0);
293
+ }
294
+ function escapeHtml(value) {
295
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&#39;");
296
+ }
297
+ /** Inserts children before the HTML's last closing tag, where WordPress's wrappers keep them. */
298
+ function insertChildren(html, children) {
299
+ if (!children) return html;
300
+ const closingTag = html.lastIndexOf("</");
301
+ if (closingTag < 0) return `${html}${children}`;
302
+ return `${html.slice(0, closingTag)}${children}${html.slice(closingTag)}`;
303
+ }
304
+ function linkHref(url, internalOrigins) {
305
+ if (typeof url !== "string" || !url.trim()) return "#";
306
+ const href = internalOrigins.length > 0 ? menuItemHref(url.trim(), internalOrigins) : url.trim();
307
+ if (/^\/(?!\/)/.test(href) || href.startsWith("#") || href.startsWith("?")) return href;
308
+ try {
309
+ const protocol = new URL(href).protocol;
310
+ return protocol === "https:" || protocol === "http:" || protocol === "mailto:" || protocol === "tel:" ? href : "#";
311
+ } catch {
312
+ return "#";
313
+ }
314
+ }
315
+ /** A media URL as an image source: http(s) only, never another scheme. */
316
+ function mediaUrl(value) {
317
+ if (typeof value !== "string") return null;
318
+ try {
319
+ const protocol = new URL(value).protocol;
320
+ return protocol === "https:" || protocol === "http:" ? value : null;
321
+ } catch {
322
+ return null;
323
+ }
324
+ }
325
+ function designLogo(value) {
326
+ const url = isRecord(value) ? mediaUrl(value.url) : null;
327
+ if (!isRecord(value) || !url) return null;
328
+ const size = (item) => typeof item === "number" && item > 0 ? item : null;
329
+ return {
330
+ url,
331
+ alt: typeof value.alt === "string" ? value.alt : "",
332
+ width: size(value.width),
333
+ height: size(value.height)
334
+ };
335
+ }
336
+ /**
337
+ * GQ Design's Site Logo node carries the Branding logo itself (`logo`, null
338
+ * when unset) and its authored `width`, `isLink` and `linkTarget`, so it
339
+ * renders without another read. Without a logo, nothing: the Site's own
340
+ * renderer can show its title instead.
341
+ */
342
+ const renderSiteLogo = (block, context) => {
343
+ const logo = designLogo(block.attributes.logo);
344
+ if (!logo) return "";
345
+ const width = typeof block.attributes.width === "number" ? block.attributes.width : logo.width;
346
+ const size = [width ? ` width="${width}"` : "", width && logo.width && logo.height ? ` height="${Math.round(width * logo.height / logo.width)}"` : !width && logo.height ? ` height="${logo.height}"` : ""].join("");
347
+ const image = `<img class="custom-logo" src="${escapeHtml(logo.url)}" alt="${escapeHtml(logo.alt)}"${size} decoding="async" />`;
348
+ const className = typeof block.attributes.className === "string" ? ` ${block.attributes.className}` : "";
349
+ const linked = block.attributes.isLink === false ? image : `<a href="${escapeHtml(context.href(context.home))}" class="custom-logo-link" ${block.attributes.linkTarget === "_blank" ? "target=\"_blank\" rel=\"home noopener\"" : "rel=\"home\""}>${image}</a>`;
350
+ return `<div class="wp-block-site-logo${escapeHtml(className)}">${linked}</div>`;
351
+ };
352
+ const BUILT_IN = { "core/site-logo": renderSiteLogo };
353
+ /** The elements a container's `tagName` may choose, as WordPress's Group block offers them. */
354
+ const CONTAINER_TAGS = /* @__PURE__ */ new Set([
355
+ "div",
356
+ "header",
357
+ "footer",
358
+ "main",
359
+ "section",
360
+ "article",
361
+ "aside",
362
+ "nav"
363
+ ]);
364
+ const SLUG = /^[a-z0-9-]+$/;
365
+ /** GQ Design's layout container, whose width, gap and padding content also restores. */
366
+ const DESIGN_CONTAINER = "getquick-design/container";
367
+ /**
368
+ * A container block (one with children) as WordPress wraps it. GQ Design
369
+ * sends saved HTML only for blocks without children, so a container's wrapper
370
+ * is rebuilt from its name and attributes: its element (`tagName`), its default
371
+ * class (`wp-block-group` for `core/group`, `wp-block-acme-hero` for
372
+ * `acme/hero`), and the classes WordPress derives from `className`, `align`,
373
+ * its preset colours and its layout type. Other styles (custom colours,
374
+ * spacing) need a Site renderer. GQ Design's own container
375
+ * (`getquick-design/container`) also gets its layout, as in content.
376
+ */
377
+ function containerHtml(block, children) {
378
+ const { tagName, className, align, backgroundColor, textColor, layout } = block.attributes;
379
+ const tag = typeof tagName === "string" && CONTAINER_TAGS.has(tagName) ? tagName : "div";
380
+ const classes = [`wp-block-${block.name.replace(/^core\//, "").replaceAll("/", "-")}`];
381
+ if (typeof className === "string" && className.trim()) classes.push(className.trim());
382
+ if (typeof align === "string" && SLUG.test(align)) classes.push(`align${align}`);
383
+ if (typeof backgroundColor === "string" && SLUG.test(backgroundColor)) classes.push(`has-${backgroundColor}-background-color`, "has-background");
384
+ if (typeof textColor === "string" && SLUG.test(textColor)) classes.push(`has-${textColor}-color`, "has-text-color");
385
+ const layoutType = isRecord(layout) ? layout.type : void 0;
386
+ if (typeof layoutType === "string" && SLUG.test(layoutType)) classes.push(`is-layout-${layoutType}`);
387
+ return `<${tag} class="${escapeHtml(classes.join(" "))}">${children}</${tag}>`;
388
+ }
389
+ /**
390
+ * A pattern (or blocks of one) as HTML. Each block is rendered by the Site's
391
+ * renderer for its name, else a built-in one, else as the HTML WordPress saved
392
+ * for it, else, with children, as a WordPress container wrapping them. A block
393
+ * with none of those (a dynamic block, such as a Site's own) renders nothing
394
+ * and is reported to `onUnrendered`. Null renders nothing, so the Site keeps
395
+ * its own header or footer.
396
+ */
397
+ function renderDesignPattern(pattern, options = {}) {
398
+ if (!pattern) return "";
399
+ const renderers = {
400
+ ...BUILT_IN,
401
+ ...options.blocks
402
+ };
403
+ const internalOrigins = options.internalOrigins ?? [];
404
+ const href = (url) => linkHref(url, internalOrigins);
405
+ const renderAll = (blocks, ancestors, parentContainer = "") => blocks.map((block) => renderOne(block, ancestors, parentContainer)).join("");
406
+ function renderOne(block, ancestors, parentContainer) {
407
+ const inside = [...ancestors, block];
408
+ const renderer = Object.hasOwn(renderers, block.name) ? renderers[block.name] : void 0;
409
+ if (renderer) {
410
+ let children;
411
+ return renderer(block, {
412
+ get children() {
413
+ return children ??= renderAll(block.children, inside);
414
+ },
415
+ ancestors,
416
+ render: (blocks) => renderAll(blocks, inside),
417
+ href,
418
+ home: options.home ?? "/"
419
+ });
420
+ }
421
+ if (block.name === DESIGN_CONTAINER && (block.children.length > 0 || block.content !== null)) {
422
+ let wrapper = containerLayoutHtml(block.content ?? containerHtml(block, ""), block.attributes);
423
+ if (parentContainer) wrapper = containerChildLayoutHtml(wrapper, parentContainer);
424
+ return insertChildren(wrapper, renderAll(block.children, inside, wrapper));
425
+ }
426
+ const children = renderAll(block.children, inside);
427
+ if (block.content !== null) return insertChildren(block.content, children);
428
+ if (block.children.length > 0) return containerHtml(block, children);
429
+ options.onUnrendered?.(block);
430
+ return "";
431
+ }
432
+ return renderAll(Array.isArray(pattern) ? pattern : pattern.blocks, []);
433
+ }
434
+ /**
435
+ * A menu a Site block carries in its attributes (a flat list of `{ id,
436
+ * parentId, label, url, target }`, as GQ Design's serializer filter documents
437
+ * for `getquick/header-navigation`) as a tree, with each link as the
438
+ * Frontend serves it. Items that aren't menu items are left out; one whose
439
+ * parent isn't listed, or that is in a cycle of parents, is a top-level item.
440
+ */
441
+ function designMenuItems(value, href = (url) => linkHref(url, [])) {
442
+ if (!Array.isArray(value)) return [];
443
+ const id = (item) => typeof item === "number" || typeof item === "string" ? String(item) : "";
444
+ const seen = /* @__PURE__ */ new Set();
445
+ const items = value.filter(isRecord).filter((item) => {
446
+ const key = id(item.id);
447
+ if (!key || seen.has(key)) return false;
448
+ seen.add(key);
449
+ return true;
450
+ });
451
+ const byId = /* @__PURE__ */ new Map();
452
+ const parentOf = /* @__PURE__ */ new Map();
453
+ for (const item of items) {
454
+ const parentId = id(item.parentId);
455
+ if (parentId && parentId !== "0") parentOf.set(id(item.id), parentId);
456
+ byId.set(id(item.id), {
457
+ id: id(item.id),
458
+ label: typeof item.label === "string" ? item.label : "",
459
+ href: href(item.url),
460
+ target: item.target === "_blank" ? "_blank" : null,
461
+ children: []
462
+ });
463
+ }
464
+ const inCycle = (start) => {
465
+ const visited = /* @__PURE__ */ new Set();
466
+ for (let at = parentOf.get(start); at !== void 0; at = parentOf.get(at)) {
467
+ if (at === start) return true;
468
+ if (visited.has(at)) return false;
469
+ visited.add(at);
470
+ }
471
+ return false;
472
+ };
473
+ const roots = [];
474
+ for (const [key, node] of byId) {
475
+ const parentId = parentOf.get(key);
476
+ const parent = parentId !== void 0 && !inCycle(key) ? byId.get(parentId) : void 0;
477
+ (parent ? parent.children : roots).push(node);
478
+ }
479
+ return roots;
480
+ }
481
+ //#endregion
482
+ //#region frontend/src/site-language.ts
483
+ /**
484
+ * The `<html lang>` for a WordPress locale: its language and region as a
485
+ * BCP 47 tag (pt_PT_ao90 → pt-PT). WordPress's variants (ao90, formal) aren't
486
+ * BCP 47 subtags, so they are left out; no locale means English.
487
+ */
488
+ function htmlLang(locale) {
489
+ if (!locale) return "en";
490
+ return locale.split("_").slice(0, 2).join("-");
491
+ }
492
+ /**
493
+ * configuration's languages: wordpress.locale, the default, served at /, then
494
+ * each of wordpress.languages under its slug. A monolingual Site has one.
495
+ */
496
+ function siteLanguages(wordpress) {
497
+ const locale = wordpress?.locale ?? "";
498
+ const language = (locale, slug, isDefault) => ({
499
+ locale,
500
+ slug,
501
+ code: slug.toUpperCase().replaceAll("-", "_"),
502
+ lang: htmlLang(locale),
503
+ isDefault,
504
+ home: isDefault ? "/" : `/${slug}/`
505
+ });
506
+ return [language(locale, locale.split("_")[0] || "en", true), ...(wordpress?.languages ?? []).map(({ locale, slug }) => language(locale, slug, false))];
507
+ }
508
+ /**
509
+ * A route's language: the one whose slug is its first segment, else the
510
+ * default language, which has no directory.
511
+ */
512
+ function routeLanguage(route, among) {
513
+ const segment = route.split("/")[1];
514
+ return among.find((language) => !language.isDefault && language.slug === segment) ?? among[0];
515
+ }
516
+ /**
517
+ * How logs and reports name something a language has: "the front page" for
518
+ * the default language's, "the en front page" for another's.
519
+ */
520
+ function languageSubject(language, what) {
521
+ return language.isDefault ? `the ${what}` : `the ${language.slug} ${what}`;
522
+ }
523
+ /** Whether a route is a language's home (/, /en/): served as a home, never as an entry. */
524
+ function isLanguageHome(route, among) {
525
+ return among.some((language) => language.home === route);
526
+ }
527
+ //#endregion
528
+ export { containerChildLayoutHtml as C, youtubeVideoId as S, uriPath as _, siteLanguages as a, parseWordPressBlocks as b, parseDesignBlocks as c, decodeEntities as d, formatDate as f, stripHtml as g, routeOf as h, routeLanguage as i, renderDesignPattern as l, responseStatus as m, isLanguageHome as n, designMenuItems as o, menuItemHref as p, languageSubject as r, escapeHtml as s, htmlLang as t, cmsTime as u, VIDEO_HERO_BLOCK as v, containerLayoutHtml as w, renderWordPressBlocks as x, hasVideoHero as y };
@@ -1,6 +1,6 @@
1
1
  //#endregion
2
2
  //#region frontend/src/consent/version.ts
3
3
  /** The UI/adapter version recorded with each decision (CN-R7). */
4
- const CONSENT_UI_VERSION = `gq-content@0.2.0`;
4
+ const CONSENT_UI_VERSION = `gq-content@0.3.0`;
5
5
  //#endregion
6
6
  export { CONSENT_UI_VERSION as t };