ferst-core 0.14.0 → 0.15.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.
@@ -28,6 +28,7 @@ import CookieBanner from '../components/CookieBanner.astro';
28
28
  import StickyCallout from '../components/StickyCallout.astro';
29
29
  import SecondaryLogo from '../components/SecondaryLogo.astro';
30
30
  import { loadSiteSettings } from '../lib/siteSettings';
31
+ import { logoHeaderSchema, type HeaderLogoOverride } from '../content/schemas';
31
32
  import { getCalloutSettings } from '../lib/callout';
32
33
  import { buildThemeStyle } from '../lib/themeTokens';
33
34
  import { canonicalUrl, previewTags } from '../lib/seo.mjs';
@@ -51,6 +52,8 @@ interface Props {
51
52
  indexable?: boolean;
52
53
  /** A post: shared and described to search engines as an article with this date. */
53
54
  article?: { date: Date | string; image?: string };
55
+ /** This page's header logo in place of the site's: a preview, or a test fixture. */
56
+ logo?: HeaderLogoOverride;
54
57
  }
55
58
 
56
59
  const {
@@ -64,6 +67,7 @@ const {
64
67
  align = 'start',
65
68
  indexable = true,
66
69
  article,
70
+ logo,
67
71
  } = Astro.props;
68
72
 
69
73
  const settings = await loadSiteSettings();
@@ -86,8 +90,13 @@ const { css: themeCss, field: themeField } = buildThemeStyle(theme);
86
90
  // text wordmark (the site name) rather than pointing <img> at a baked-in path
87
91
  // that may not exist — a broken logo by default was the old bug. Dark falls back
88
92
  // to the light variant when only one is supplied.
89
- const primaryLogoLight = settings.primaryLogoLight;
90
- const primaryLogoDark = settings.primaryLogoDark ?? settings.primaryLogoLight;
93
+ const primaryLogoLight = logo ? logo.light : settings.primaryLogoLight;
94
+ const primaryLogoDark = logo ? logo.dark ?? logo.light : settings.primaryLogoDark ?? settings.primaryLogoLight;
95
+ // The header logo's size and placement, and its own width and height (read at build time by
96
+ // the ferst() integration) so the page keeps the logo's real shape before it loads.
97
+ const logoHeader = logoHeaderSchema.parse(logo ? logo.header ?? {} : settings.header);
98
+ const builtLogoSize = (import.meta.env.FERST_LOGO_SIZE ?? null) as { width: number; height: number } | null;
99
+ const logoSize = logo ? (logo.width && logo.height ? { width: logo.width, height: logo.height } : undefined) : builtLogoSize ?? undefined;
91
100
  const secondaryLogoLight = settings.secondaryLogoLight;
92
101
  const secondaryLogoDark = settings.secondaryLogoDark;
93
102
  const secondaryLogoLink = settings.secondaryLogoLink;
@@ -263,6 +272,8 @@ const hasFeed = Boolean(siteUrl) && import.meta.env.FERST_ROUTES_BLOG !== false;
263
272
  headerClass={headerClass}
264
273
  primaryLogoLight={primaryLogoLight}
265
274
  primaryLogoDark={primaryLogoDark}
275
+ logoHeader={logoHeader}
276
+ logoSize={logoSize}
266
277
  brandAlt={brandAlt}
267
278
  primaryNav={navigation.primary}
268
279
  dropdown={navigation.dropdown}
@@ -497,6 +508,9 @@ const hasFeed = Boolean(siteUrl) && import.meta.env.FERST_ROUTES_BLOG !== false;
497
508
  flex-direction: column;
498
509
  gap: clamp(2rem, 4vw, 3rem);
499
510
  padding-block: clamp(3rem, 6vw, 5rem);
511
+ /* A header logo that hangs below the bar (--logo-overhang, SiteHeader) never sits
512
+ over the page's first words. */
513
+ padding-block-start: max(clamp(3rem, 6vw, 5rem), calc(var(--logo-overhang, 0px) + 1rem));
500
514
  }
501
515
  .site-main > * {
502
516
  margin-block: 0;
@@ -508,6 +522,11 @@ const hasFeed = Boolean(siteUrl) && import.meta.env.FERST_ROUTES_BLOG !== false;
508
522
  .site-main:has(> .b-banner[data-full-bleed='true']:first-child) {
509
523
  padding-block-start: 0;
510
524
  }
525
+ /* That flush opener keeps its words clear of a hanging header logo itself (Hero). */
526
+ .site-main > .b-hero[data-size='screen']:first-child,
527
+ .site-main > .b-hero[data-full-bleed='true']:first-child {
528
+ --hero-clear: calc(var(--logo-overhang, 0px) + 1.5rem);
529
+ }
511
530
 
512
531
  /* ── Content alignment cascade ──────────────────────────────────────
513
532
  A page sets its default alignment via the `align` prop (→
package/lib/book.ts CHANGED
@@ -96,7 +96,100 @@ export function bookingMessage(code: string): string {
96
96
  }
97
97
 
98
98
  /** One coming date of a class or a concert: its places left and its price. */
99
- export interface EventDate { event_id: string; title: string; description?: string; start: string; end: string; places: number; left: number; price: string }
99
+ export interface EventDate {
100
+ event_id: string; title: string; description?: string; start: string; end: string; places: number; left: number; price: string;
101
+ /** For search engines (0.15.0, slice 6d): a place's price in pence (0 free; null when not priced by the place), its place and who leads it. */
102
+ amount?: number | null; where?: { name: string } | null; with?: string[];
103
+ }
104
+
105
+ // ── For search engines (0.15.0; myai4-webdev docs/EVENTS.md slice 6d) ──────────────────────────────
106
+ // Each coming date of a class or an event is a schema.org Event, written into the page at build and
107
+ // brought up to date (its places left) as the page loads. Only what's booked by places: a haircut or a
108
+ // hire becomes one date only once it's booked, so it's nothing to search for.
109
+
110
+ /** One of the site's places (siteSettings.places), whose address an event there is given. */
111
+ export interface SitePlace { name?: string; streetAddress?: string; locality?: string; postalCode?: string; country?: string }
112
+ /** What the page knows that the platform doesn't: its own address, the organisation, and its places. */
113
+ export interface EventsContext { url: string; organisation: { name?: string; url: string }; places: SitePlace[] }
114
+
115
+ /** '2026-12-19T19:30:00+00:00': a London time with its offset, as schema.org wants it. */
116
+ export function londonWithOffset(local: string): string {
117
+ const [y, m, d] = local.slice(0, 10).split('-').map(Number);
118
+ const guess = new Date(Date.UTC(y, m - 1, d, Number(local.slice(11, 13)), Number(local.slice(14, 16))));
119
+ const name = new Intl.DateTimeFormat('en-GB', { timeZone: 'Europe/London', timeZoneName: 'longOffset' })
120
+ .formatToParts(guess).find((p) => p.type === 'timeZoneName')?.value ?? 'GMT';
121
+ const off = name.replace('GMT', '') || '+00:00';
122
+ return `${local.slice(0, 16)}:00${off}`;
123
+ }
124
+
125
+ const postal = (p: SitePlace) => {
126
+ const a: Record<string, string> = { '@type': 'PostalAddress' };
127
+ if (p.streetAddress) a.streetAddress = p.streetAddress;
128
+ if (p.locality) a.addressLocality = p.locality;
129
+ if (p.postalCode) a.postalCode = p.postalCode;
130
+ a.addressCountry = p.country || 'GB';
131
+ return a;
132
+ };
133
+ const filled = (p: SitePlace) => !!(p && (p.name || p.streetAddress || p.postalCode));
134
+
135
+ /** Where a date is, with its address when it's one of the site's places (or the site has only one). */
136
+ function locationOf(where: { name: string } | null | undefined, places: SitePlace[]): Record<string, unknown> | undefined {
137
+ const known = places.filter(filled);
138
+ const same = where ? known.find((p) => p.name?.trim().toLowerCase() === where.name.trim().toLowerCase()) : undefined;
139
+ const only = known.length === 1 ? known[0] : undefined;
140
+ const at = same ?? (where ? undefined : only);
141
+ if (where && !same && only && !only.name) return { '@type': 'Place', name: where.name, address: postal(only) };
142
+ if (!where && !at) return undefined;
143
+ const place: Record<string, unknown> = { '@type': 'Place', name: where?.name ?? at?.name };
144
+ if (at && (at.streetAddress || at.postalCode || at.locality)) place.address = postal(at);
145
+ return place;
146
+ }
147
+
148
+ /** The schema.org Events for a class's or an event's coming dates, or null when there are none. */
149
+ export function eventsData(dates: EventDate[], ctx: EventsContext): { '@context': string; '@graph': Array<Record<string, unknown>> } | null {
150
+ if (!dates.length) return null;
151
+ const graph = dates.slice(0, 50).map((d) => {
152
+ const e: Record<string, unknown> = { '@type': 'Event', name: d.title };
153
+ if (d.description) e.description = d.description;
154
+ e.startDate = londonWithOffset(d.start);
155
+ e.endDate = londonWithOffset(d.end);
156
+ e.eventStatus = 'https://schema.org/EventScheduled';
157
+ e.eventAttendanceMode = 'https://schema.org/OfflineEventAttendanceMode';
158
+ const location = locationOf(d.where, ctx.places);
159
+ if (location) e.location = location;
160
+ e.organizer = { '@type': 'Organization', ...(ctx.organisation.name ? { name: ctx.organisation.name } : {}), url: ctx.organisation.url };
161
+ if (d.with?.length) e.performer = d.with.map((name) => ({ '@type': 'Person', name }));
162
+ e.maximumAttendeeCapacity = d.places;
163
+ e.remainingAttendeeCapacity = d.left;
164
+ if (typeof d.amount === 'number') {
165
+ e.offers = { '@type': 'Offer', price: (d.amount / 100).toFixed(2), priceCurrency: 'GBP', availability: `https://schema.org/${d.left > 0 ? 'InStock' : 'SoldOut'}`, url: ctx.url };
166
+ }
167
+ e.url = ctx.url;
168
+ return e;
169
+ });
170
+ return { '@context': 'https://schema.org', '@graph': graph };
171
+ }
172
+
173
+ /** The JSON for a page's script tag: `<` escaped so it can't close the tag. */
174
+ export const ldJson = (data: unknown) => JSON.stringify(data).replace(/</g, '\\u003c');
175
+
176
+ /**
177
+ * A class's or an event's dates for the coming month, read at build for search engines. Never fails the
178
+ * build: the block still works (it reads its dates as the page loads), search engines just aren't told.
179
+ */
180
+ export async function loadEventDates(definition: string, opts: { event?: string | null; resource?: string | null; now?: Date; fetch?: FetchFn } = {}): Promise<EventDate[]> {
181
+ const doFetch = opts.fetch ?? ((u: string, i?: RequestInit) => fetch(u, i));
182
+ const from = londonDay(opts.now);
183
+ const q = `from=${from}&to=${addDays(from, 30)}${opts.event ? `&event=${encodeURIComponent(opts.event)}` : ''}${opts.resource ? `&resource=${encodeURIComponent(opts.resource)}` : ''}`;
184
+ try {
185
+ const res = await doFetch(`${definition}?${q}`, { headers: { Accept: 'application/json' } });
186
+ if (!res.ok) return [];
187
+ const body = (await res.json()) as { events?: EventDate[] };
188
+ return Array.isArray(body.events) ? body.events : [];
189
+ } catch {
190
+ return [];
191
+ }
192
+ }
100
193
 
101
194
  /** The platform's answer for an offer's free times (or, booked by places, its coming dates), as the block reads it. */
102
195
  export interface TimesAnswer {
@@ -0,0 +1,73 @@
1
+ /**
2
+ * An image's own width and height, read from the first bytes of the file: PNG, JPEG, GIF,
3
+ * WebP and SVG. Used at build time for the header logo, so the page reserves the logo's
4
+ * real shape before the image arrives (no jump, no wide box for a round badge). Pure and
5
+ * synchronous, with no image library.
6
+ */
7
+ import { existsSync, readFileSync } from 'node:fs';
8
+
9
+ /** @param {Uint8Array} bytes @returns {{ width: number, height: number } | null} */
10
+ export function imageSize(bytes) {
11
+ const b = Buffer.from(bytes);
12
+ if (b.length < 10) return null;
13
+ const ok = (width, height) => (width > 0 && height > 0 ? { width, height } : null);
14
+
15
+ // PNG: the IHDR chunk follows the 8-byte signature.
16
+ if (b.readUInt32BE(0) === 0x89504e47 && b.toString('ascii', 12, 16) === 'IHDR') {
17
+ return ok(b.readUInt32BE(16), b.readUInt32BE(20));
18
+ }
19
+ // GIF: logical screen size.
20
+ if (b.toString('ascii', 0, 4) === 'GIF8') return ok(b.readUInt16LE(6), b.readUInt16LE(8));
21
+ // WebP: lossy (VP8 ), lossless (VP8L) or extended (VP8X).
22
+ if (b.toString('ascii', 0, 4) === 'RIFF' && b.toString('ascii', 8, 12) === 'WEBP' && b.length >= 30) {
23
+ const kind = b.toString('ascii', 12, 16);
24
+ if (kind === 'VP8 ') return ok(b.readUInt16LE(26) & 0x3fff, b.readUInt16LE(28) & 0x3fff);
25
+ if (kind === 'VP8L') {
26
+ const bits = b.readUInt32LE(21);
27
+ return ok((bits & 0x3fff) + 1, ((bits >> 14) & 0x3fff) + 1);
28
+ }
29
+ if (kind === 'VP8X') return ok(b.readUIntLE(24, 3) + 1, b.readUIntLE(27, 3) + 1);
30
+ return null;
31
+ }
32
+ // JPEG: walk the markers to the first start-of-frame.
33
+ if (b[0] === 0xff && b[1] === 0xd8) {
34
+ let i = 2;
35
+ while (i + 9 < b.length) {
36
+ if (b[i] !== 0xff) return null;
37
+ const marker = b[i + 1];
38
+ if (marker === 0xff) { i += 1; continue; }
39
+ const length = b.readUInt16BE(i + 2);
40
+ const isFrame = marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker);
41
+ if (isFrame) return ok(b.readUInt16BE(i + 7), b.readUInt16BE(i + 5));
42
+ i += 2 + length;
43
+ }
44
+ return null;
45
+ }
46
+ // SVG: width and height in pixels on the root element, else its viewBox.
47
+ const text = b.toString('utf8', 0, Math.min(b.length, 4096));
48
+ const root = /<svg\b[^>]*>/i.exec(text)?.[0];
49
+ if (root) {
50
+ const attr = (name) => new RegExp(`\\s${name}\\s*=\\s*["']\\s*([\\d.]+)\\s*(px)?\\s*["']`, 'i').exec(root)?.[1];
51
+ const w = Number(attr('width'));
52
+ const h = Number(attr('height'));
53
+ if (w > 0 && h > 0) return { width: w, height: h };
54
+ const box = /\sviewBox\s*=\s*["']\s*[-\d.]+[\s,]+[-\d.]+[\s,]+([\d.]+)[\s,]+([\d.]+)\s*["']/i.exec(root);
55
+ if (box) return ok(Number(box[1]), Number(box[2]));
56
+ }
57
+ return null;
58
+ }
59
+
60
+ /**
61
+ * The size of a site image given by its address (`/uploads/badge.png` → public/uploads/…).
62
+ * @param {URL | undefined} root the site's folder
63
+ * @param {unknown} path
64
+ */
65
+ export function publicImageSize(root, path) {
66
+ if (!root || typeof path !== 'string' || !path.startsWith('/') || path.includes('..')) return null;
67
+ try {
68
+ const file = new URL(`public${path.split(/[?#]/)[0]}`, root);
69
+ return existsSync(file) ? imageSize(readFileSync(file)) : null;
70
+ } catch {
71
+ return null;
72
+ }
73
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ferst-core",
3
- "version": "0.14.0",
3
+ "version": "0.15.0",
4
4
  "type": "module",
5
5
  "description": "Ferst Core — the shared, brand-agnostic client-site system: Astro components, layouts, content schemas, the layered config resolver, and a neutral styling architecture that every client overrides.",
6
6
  "license": "BUSL-1.1",