@hagicode/hagilight-core 0.14.1-dev.146.1.e98244c → 0.14.1-dev.149.1.1dadf5c

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/Footer.astro CHANGED
@@ -10,9 +10,13 @@ interface Props {
10
10
  locale?: string;
11
11
  links?: SiteLinksOptions;
12
12
  buildInfo?: BuildInfo;
13
+ /** Show the decorative avatar in the brand block. Defaults to `true`. */
14
+ avatar?: boolean;
15
+ /** Swap the avatar for one random pool entry per page view. Defaults to `true`. */
16
+ randomAvatar?: boolean;
13
17
  }
14
18
 
15
- const { locale: propLocale, links, buildInfo: propBuildInfo } = Astro.props;
19
+ const { locale: propLocale, links, buildInfo: propBuildInfo, avatar, randomAvatar } = Astro.props;
16
20
  const locale = propLocale ?? Astro.currentLocale ?? 'en-US';
17
21
  const footerLinks = resolveRssFooterLinks(Astro.locals, locale, links);
18
22
  const buildItems = buildInfoItems(propBuildInfo ?? buildInfoFromLocals(Astro.locals));
@@ -32,7 +36,7 @@ const resolvedLinks = resolveSiteLinks(locale, {
32
36
  ---
33
37
 
34
38
  <footer class="hagilight-footer">
35
- <FooterBrand locale={resolvedLinks.locale} links={resolvedLinks.quick} />
39
+ <FooterBrand locale={resolvedLinks.locale} links={resolvedLinks.quick} avatar={avatar} randomAvatar={randomAvatar} />
36
40
  <div class="hagilight-footer__sections">
37
41
  {resolvedLinks.relatedSites.length > 0 && (
38
42
  <section>
@@ -0,0 +1,9 @@
1
+ ---
2
+ // Rendered only when the footer avatar's random option is on, so a site that turns it off ships no picker script.
3
+ ---
4
+
5
+ <script>
6
+ import { mountRandomImages } from './dist/random-image.js';
7
+
8
+ void mountRandomImages(document);
9
+ </script>
package/FooterBrand.astro CHANGED
@@ -2,22 +2,43 @@
2
2
  import { siteLinkGaAttributes } from './dist/analytics-events.js';
3
3
  import type { SiteLink } from './dist/links.js';
4
4
  import { pickFooterBrandLinks, resolveFooterBrand } from './dist/footer-brand.js';
5
+ import { footerAvatarImageAttributes, resolveFooterAvatarOptions } from './dist/footer-avatar.js';
6
+ import { randomPoolAttribute, randomPoolFromManifest } from './dist/random-image.js';
7
+ import avatarAvif from './assets/footer/avatar.avif';
8
+ import avatarWebp from './assets/footer/avatar.webp';
9
+ import avatarManifest from './assets/footer/manifest.json';
10
+ import FooterAvatarPicker from './FooterAvatarPicker.astro';
5
11
 
6
12
  interface Props {
7
13
  /** The locale `resolveSiteLinks` returned, so copy and links always agree. */
8
14
  locale?: string;
9
15
  /** The footer's resolved quick links; the calls to action come from here. */
10
16
  links: readonly SiteLink[];
17
+ /** Show the decorative avatar. Defaults to `true`. */
18
+ avatar?: boolean;
19
+ /** Swap the avatar for one random pool entry per page view. Defaults to `true`. */
20
+ randomAvatar?: boolean;
11
21
  }
12
22
 
13
- const { locale, links } = Astro.props;
23
+ const { locale, links, avatar, randomAvatar } = Astro.props;
14
24
  const brand = resolveFooterBrand(locale);
15
25
  const { primary, secondary } = pickFooterBrandLinks(links);
26
+ const avatarOptions = resolveFooterAvatarOptions({ avatar, randomAvatar });
27
+ const avatarPool = avatarOptions.randomAvatar ? randomPoolFromManifest(avatarManifest.pool) : undefined;
16
28
  ---
17
29
 
18
30
  <section class="hagilight-brand" lang={brand.locale} aria-labelledby="hagilight-brand-title">
19
31
  <div class="hagilight-brand__lead">
20
- <h2 class="hagilight-brand__headline" id="hagilight-brand-title">{brand.headline}</h2>
32
+ <div class="hagilight-brand__title">
33
+ {avatarOptions.avatar && (
34
+ <picture class="hagilight-brand__avatar" data-random-pool={avatarPool && randomPoolAttribute(avatarPool)}>
35
+ <source type="image/avif" srcset={avatarAvif.src} />
36
+ <source type="image/webp" srcset={avatarWebp.src} />
37
+ <img src={avatarWebp.src} {...footerAvatarImageAttributes()} />
38
+ </picture>
39
+ )}
40
+ <h2 class="hagilight-brand__headline" id="hagilight-brand-title">{brand.headline}</h2>
41
+ </div>
21
42
  <div class="hagilight-brand__body">
22
43
  <p class="hagilight-brand__summary">{brand.summary}</p>
23
44
  {(primary || secondary) && (
@@ -59,6 +80,7 @@ const { primary, secondary } = pickFooterBrandLinks(links);
59
80
  </div>
60
81
  ))}
61
82
  </dl>
83
+ {avatarOptions.randomAvatar && <FooterAvatarPicker />}
62
84
  </section>
63
85
 
64
86
  <style>
@@ -87,6 +109,36 @@ const { primary, secondary } = pickFooterBrandLinks(links);
87
109
  gap: 1.5rem 3.5rem;
88
110
  }
89
111
 
112
+ .hagilight-brand__title {
113
+ display: flex;
114
+ align-items: center;
115
+ gap: 1.25rem;
116
+ min-width: 0;
117
+ }
118
+
119
+ /* The decorative avatar keeps a fixed 64 px box, so a random swap never moves the headline. */
120
+ .hagilight-brand__avatar {
121
+ display: block;
122
+ flex: none;
123
+ width: 64px;
124
+ height: 64px;
125
+ }
126
+
127
+ .hagilight-brand__avatar img {
128
+ display: block;
129
+ width: 100%;
130
+ height: 100%;
131
+ border-radius: 0.5rem;
132
+ object-fit: cover;
133
+ }
134
+
135
+ /* Hidden in a brand block narrower than 360 px, where the headline needs the full width. */
136
+ @container hagilight-brand (max-width: 359.98px) {
137
+ .hagilight-brand__avatar {
138
+ display: none;
139
+ }
140
+ }
141
+
90
142
  .hagilight-brand__headline {
91
143
  margin: 0;
92
144
  color: var(--_heading);
package/README.md CHANGED
@@ -37,6 +37,16 @@ import { resolveSiteLinks } from '@hagicode/hagilight-core/links';
37
37
  const links = resolveSiteLinks('en-US');
38
38
  ```
39
39
 
40
+ ## Footer avatar
41
+
42
+ The footer brand block shows one decorative HagiCode avatar beside the headline. `avatar` defaults to `true`; `avatar={false}` removes the element and its request. The default is `assets/footer/avatar.avif` (128 px, with `avatar.webp` as the fallback) in a 64 px box, hidden below a 360 px container. `randomAvatar` defaults to `true`: each page view swaps the default for one entry of the `cat-head-gallery` pool listed in `assets/footer/manifest.json`. The browser picker is `@hagicode/hagilight-core/random-image` (browser-safe, under 2 KiB minified) and it preloads with a plain `Image()`, not `fetch`, waits up to 3 seconds, and keeps the default on error or timeout. `randomAvatar={false}` ships no pool list and no picker script.
43
+
44
+ `@hagicode/hagilight-core/footer-avatar` resolves the two options (a non-boolean throws a `TypeError`) and gives the shared image attributes. The Astro footers and the Docusaurus footer render the same `<picture class="hagilight-brand__avatar">` markup.
45
+
46
+ A site with a strict `img-src` policy must allow `https://img-gen.hagicode.com` for the random swap. Without it the swap fails and the default stays.
47
+
48
+ **Pool refresh.** The pool is the `pool` object in `assets/footer/manifest.json`: `album`, `maxBytes` (40 KiB) and `entries` (`key`, `bytes`). To change it, take keys from the album's `index.json`, keep 12 to 200 unique keys each at or under `maxBytes`, audit each one as text-free, current and private-data free, and update the list. Then run `npm test`: `test/footer-imagery.test.mjs` fails on a missing file, a size or dimension mismatch, an entry over the cap, or a pool outside 12 to 200. The vendored default is `source.objectKey` in the same manifest.
49
+
40
50
  ## Root transit (explicit opt-in)
41
51
 
42
52
  Use this full-page component in an Astro root route (`src/pages/index.astro`):
Binary file
Binary file
@@ -0,0 +1,253 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "id": "footer-avatar",
4
+ "surface": "hagilight-footer-brand",
5
+ "decorative": true,
6
+ "source": {
7
+ "repo": "img-gen",
8
+ "album": "cat-head-gallery",
9
+ "objectKey": "cat-head-gallery/g001-flat-vector-01.avif",
10
+ "width": 1024,
11
+ "height": 1024,
12
+ "bytes": 11948
13
+ },
14
+ "transforms": [
15
+ "resize 1024x1024 to 128x128 (cover, lanczos3)",
16
+ "avif: libaom-av1 still picture, crf 4, yuv420p (ffmpeg)",
17
+ "webp: libwebp quality 94, effort 6, smart subsample (sharp)"
18
+ ],
19
+ "display": {
20
+ "cssPx": 64,
21
+ "sourcePx": 128
22
+ },
23
+ "files": [
24
+ {
25
+ "file": "avatar.avif",
26
+ "type": "image/avif",
27
+ "width": 128,
28
+ "height": 128,
29
+ "bytes": 4535
30
+ },
31
+ {
32
+ "file": "avatar.webp",
33
+ "type": "image/webp",
34
+ "width": 128,
35
+ "height": 128,
36
+ "bytes": 4558
37
+ }
38
+ ],
39
+ "budgets": {
40
+ "perFileKiB": 12
41
+ },
42
+ "audit": {
43
+ "verdict": "pass",
44
+ "checkedOn": "2026-10-22",
45
+ "notes": "Flat-vector cat head, text-free, from cat-head-gallery (style flat-vector). The album review (audit2, 2026-10-22) covered all 506 entries at or under 40 KiB on labelled contact sheets and excluded none. Pool: the 50 keys of cat-head-pool.json, each at or under 40 KiB. Neither default is in the pool, so a swap always changes the image and never shows the showcase default."
46
+ },
47
+ "pool": {
48
+ "album": "cat-head-gallery",
49
+ "maxBytes": 40960,
50
+ "entries": [
51
+ {
52
+ "key": "g002-ukiyo-e-01",
53
+ "bytes": 25795
54
+ },
55
+ {
56
+ "key": "g003-watercolor-wash-02",
57
+ "bytes": 30932
58
+ },
59
+ {
60
+ "key": "g004-pixel-art-03",
61
+ "bytes": 24154
62
+ },
63
+ {
64
+ "key": "g005-oil-impasto-06",
65
+ "bytes": 37209
66
+ },
67
+ {
68
+ "key": "g006-paper-cut-layers-07",
69
+ "bytes": 15837
70
+ },
71
+ {
72
+ "key": "g008-low-poly-07",
73
+ "bytes": 17251
74
+ },
75
+ {
76
+ "key": "g009-claymation-07",
77
+ "bytes": 16599
78
+ },
79
+ {
80
+ "key": "g010-neon-line-07",
81
+ "bytes": 21312
82
+ },
83
+ {
84
+ "key": "g016-bauhaus-geometry-06",
85
+ "bytes": 13663
86
+ },
87
+ {
88
+ "key": "g017-cyanotype-06",
89
+ "bytes": 18762
90
+ },
91
+ {
92
+ "key": "g020-origami-03",
93
+ "bytes": 26060
94
+ },
95
+ {
96
+ "key": "g022-blueprint-03",
97
+ "bytes": 23845
98
+ },
99
+ {
100
+ "key": "g023-chalk-pastel-10",
101
+ "bytes": 29427
102
+ },
103
+ {
104
+ "key": "g025-voxel-03",
105
+ "bytes": 8242
106
+ },
107
+ {
108
+ "key": "g031-illuminated-manuscript-04",
109
+ "bytes": 32530
110
+ },
111
+ {
112
+ "key": "g034-vaporwave-04",
113
+ "bytes": 36264
114
+ },
115
+ {
116
+ "key": "g035-synthwave-chrome-09",
117
+ "bytes": 18415
118
+ },
119
+ {
120
+ "key": "g038-frosted-glass-02",
121
+ "bytes": 28185
122
+ },
123
+ {
124
+ "key": "g039-needle-felt-09",
125
+ "bytes": 33696
126
+ },
127
+ {
128
+ "key": "g041-glossy-balloon-05",
129
+ "bytes": 14623
130
+ },
131
+ {
132
+ "key": "g042-blue-white-porcelain-05",
133
+ "bytes": 31257
134
+ },
135
+ {
136
+ "key": "g043-glazed-ceramic-06",
137
+ "bytes": 11086
138
+ },
139
+ {
140
+ "key": "g045-impressionist-08",
141
+ "bytes": 32479
142
+ },
143
+ {
144
+ "key": "g047-fauvist-09",
145
+ "bytes": 18358
146
+ },
147
+ {
148
+ "key": "g048-cubist-10",
149
+ "bytes": 31586
150
+ },
151
+ {
152
+ "key": "g051-naive-folk-art-07",
153
+ "bytes": 19613
154
+ },
155
+ {
156
+ "key": "g056-wax-print-fabric-07",
157
+ "bytes": 16978
158
+ },
159
+ {
160
+ "key": "g058-red-paper-cut-10",
161
+ "bytes": 20948
162
+ },
163
+ {
164
+ "key": "g060-kawaii-pastel-01",
165
+ "bytes": 12179
166
+ },
167
+ {
168
+ "key": "g061-retro-90s-anime-01",
169
+ "bytes": 29377
170
+ },
171
+ {
172
+ "key": "g062-shoujo-sparkle-08",
173
+ "bytes": 27048
174
+ },
175
+ {
176
+ "key": "g065-saturday-cartoon-09",
177
+ "bytes": 19421
178
+ },
179
+ {
180
+ "key": "g067-pixar-style-3d-03",
181
+ "bytes": 16925
182
+ },
183
+ {
184
+ "key": "g068-toon-shaded-3d-04",
185
+ "bytes": 14116
186
+ },
187
+ {
188
+ "key": "g069-ps1-lowpoly-06",
189
+ "bytes": 18227
190
+ },
191
+ {
192
+ "key": "g070-matte-clay-render-07",
193
+ "bytes": 12775
194
+ },
195
+ {
196
+ "key": "g071-y2k-chrome-08",
197
+ "bytes": 24059
198
+ },
199
+ {
200
+ "key": "g072-glossy-3d-icon-08",
201
+ "bytes": 13376
202
+ },
203
+ {
204
+ "key": "g073-marble-bust-08",
205
+ "bytes": 17446
206
+ },
207
+ {
208
+ "key": "g075-wood-carving-10",
209
+ "bytes": 38433
210
+ },
211
+ {
212
+ "key": "g076-carved-jade-10",
213
+ "bytes": 14512
214
+ },
215
+ {
216
+ "key": "g078-toy-brick-02",
217
+ "bytes": 11910
218
+ },
219
+ {
220
+ "key": "g079-designer-vinyl-toy-02",
221
+ "bytes": 10594
222
+ },
223
+ {
224
+ "key": "g081-patchwork-quilt-03",
225
+ "bytes": 25601
226
+ },
227
+ {
228
+ "key": "g083-warhol-silkscreen-04",
229
+ "bytes": 14747
230
+ },
231
+ {
232
+ "key": "g088-vintage-lithograph-02",
233
+ "bytes": 27832
234
+ },
235
+ {
236
+ "key": "g090-alcohol-marker-09",
237
+ "bytes": 34894
238
+ },
239
+ {
240
+ "key": "g091-painterly-concept-art-09",
241
+ "bytes": 18574
242
+ },
243
+ {
244
+ "key": "g092-gradient-minimal-09",
245
+ "bytes": 14823
246
+ },
247
+ {
248
+ "key": "g095-constellation-map-09",
249
+ "bytes": 25940
250
+ }
251
+ ]
252
+ }
253
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Public contract for the shared footer avatar (`hagilight-footer-imagery`): option parsing and the decorative
3
+ * image attributes that the Astro and Docusaurus footers both render. Browser-safe: no `node:` import.
4
+ */
5
+ export interface FooterAvatarOptions {
6
+ /** Show the avatar in the brand block. Defaults to `true`; `false` removes the element and its request. */
7
+ avatar?: boolean;
8
+ /** Swap the avatar for one random pool entry per page view. Defaults to `true`. */
9
+ randomAvatar?: boolean;
10
+ }
11
+ export interface ResolvedFooterAvatarOptions {
12
+ avatar: boolean;
13
+ randomAvatar: boolean;
14
+ }
15
+ export declare const FOOTER_AVATAR_DISPLAY_PX = 64;
16
+ export declare const FOOTER_AVATAR_SOURCE_PX = 128;
17
+ /** Below this container width the avatar is hidden, so a narrow footer keeps its text layout. */
18
+ export declare const FOOTER_AVATAR_MIN_CONTAINER_PX = 360;
19
+ export interface FooterAvatarImageAttributes {
20
+ width: number;
21
+ height: number;
22
+ alt: '';
23
+ 'aria-hidden': 'true';
24
+ loading: 'lazy';
25
+ decoding: 'async';
26
+ }
27
+ /**
28
+ * Attributes of the decorative `<img>`: no alternative text and hidden from assistive technology. A fresh object on
29
+ * every call, because Astro adds its scoping class to spread attributes and would fail on a shared frozen object.
30
+ */
31
+ export declare function footerAvatarImageAttributes(): FooterAvatarImageAttributes;
32
+ /**
33
+ * Resolves the footer avatar options. `undefined` gives the defaults; anything that is not an object or a boolean
34
+ * throws a `TypeError`, so bad configuration fails the build.
35
+ */
36
+ export declare function resolveFooterAvatarOptions(input?: {
37
+ avatar?: unknown;
38
+ randomAvatar?: unknown;
39
+ }): ResolvedFooterAvatarOptions;
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Public contract for the shared footer avatar (`hagilight-footer-imagery`): option parsing and the decorative
3
+ * image attributes that the Astro and Docusaurus footers both render. Browser-safe: no `node:` import.
4
+ */
5
+ export const FOOTER_AVATAR_DISPLAY_PX = 64;
6
+ export const FOOTER_AVATAR_SOURCE_PX = 128;
7
+ /** Below this container width the avatar is hidden, so a narrow footer keeps its text layout. */
8
+ export const FOOTER_AVATAR_MIN_CONTAINER_PX = 360;
9
+ /**
10
+ * Attributes of the decorative `<img>`: no alternative text and hidden from assistive technology. A fresh object on
11
+ * every call, because Astro adds its scoping class to spread attributes and would fail on a shared frozen object.
12
+ */
13
+ export function footerAvatarImageAttributes() {
14
+ return {
15
+ width: FOOTER_AVATAR_DISPLAY_PX,
16
+ height: FOOTER_AVATAR_DISPLAY_PX,
17
+ alt: '',
18
+ 'aria-hidden': 'true',
19
+ loading: 'lazy',
20
+ decoding: 'async',
21
+ };
22
+ }
23
+ function booleanOption(value, name) {
24
+ if (value === undefined)
25
+ return undefined;
26
+ if (typeof value !== 'boolean')
27
+ throw new TypeError(`Hagilight footer ${name} option must be a boolean.`);
28
+ return value;
29
+ }
30
+ /**
31
+ * Resolves the footer avatar options. `undefined` gives the defaults; anything that is not an object or a boolean
32
+ * throws a `TypeError`, so bad configuration fails the build.
33
+ */
34
+ export function resolveFooterAvatarOptions(input) {
35
+ if (input !== undefined && (typeof input !== 'object' || input === null || Array.isArray(input))) {
36
+ throw new TypeError('Hagilight footer avatar options must be an object.');
37
+ }
38
+ const avatar = booleanOption(input?.avatar, 'avatar') ?? true;
39
+ const randomAvatar = booleanOption(input?.randomAvatar, 'randomAvatar') ?? true;
40
+ // The random pool only exists when the avatar does, so a disabled avatar carries no pool list or picker.
41
+ return { avatar, randomAvatar: avatar && randomAvatar };
42
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Browser-safe picker for decorative R2 images (`r2-image-random-display`).
3
+ *
4
+ * A slot keeps its vendored default in the markup and carries a `data-random-pool` JSON list of R2 object paths.
5
+ * After load, one entry is picked uniformly, preloaded with a plain `Image()` (never `fetch`, so the R2 CORS rule
6
+ * does not apply), and swapped in only when it loads within the timeout. Every failure keeps the default. No node:
7
+ * import, no library. The environment is injectable so tests can use a fake image and a seeded random source.
8
+ */
9
+ export declare const R2_IMAGE_ORIGIN = "https://img-gen.hagicode.com";
10
+ export declare const RANDOM_POOL_ATTRIBUTE = "data-random-pool";
11
+ export declare const RANDOM_POOL_MIN_ENTRIES = 12;
12
+ export declare const RANDOM_POOL_MAX_ENTRIES = 200;
13
+ export declare const RANDOM_IMAGE_TIMEOUT_MS = 3000;
14
+ export interface PreloadImage {
15
+ src: string;
16
+ onload: (() => void) | null;
17
+ onerror: (() => void) | null;
18
+ }
19
+ export interface RandomImageEnvironment {
20
+ /** Returns a value in [0, 1). Defaults to `Math.random`. */
21
+ readonly random?: () => number;
22
+ /** Defaults to `new Image()`. */
23
+ readonly createImage?: () => PreloadImage;
24
+ /** Defaults to the global `setTimeout` and `clearTimeout`. */
25
+ readonly setTimer?: (callback: () => void, ms: number) => unknown;
26
+ readonly clearTimer?: (handle: unknown) => void;
27
+ /** Defaults to the browser's data-saver preference. */
28
+ readonly saveData?: () => boolean;
29
+ }
30
+ /**
31
+ * Checks a pool: 12 to 200 unique `<album>/<key>.avif` object paths, all from one album. Throws a `TypeError`, so a
32
+ * bad pool fails the build instead of the page.
33
+ */
34
+ export declare function validateRandomPool(entries: unknown): readonly string[];
35
+ /** Picks one entry uniformly. Out-of-range or non-finite random values clamp to the first or last entry. */
36
+ export declare function pickRandomEntry<T>(entries: readonly T[], random?: () => number): T;
37
+ /** The full image URL of an R2 object path. */
38
+ export declare function poolImageUrl(objectPath: string): string;
39
+ /**
40
+ * Loads `url` in an image element. Resolves `true` only when it loads within the timeout; an error, a timeout or a
41
+ * missing `Image` resolves `false`. Never rejects and never retries.
42
+ */
43
+ export declare function preloadImage(url: string, env?: RandomImageEnvironment): Promise<boolean>;
44
+ /**
45
+ * Swaps a loaded URL into a `<picture>` or `<img>` slot. The `<source>` elements are removed so the browser uses the
46
+ * swapped `src`; the `<img>` keeps its width, height and alt text, so the box does not change.
47
+ */
48
+ export declare function showPoolImage(slot: Element, url: string): void;
49
+ /**
50
+ * Runs the picker for every `[data-random-pool]` slot under `root` that has not been handled yet. Each slot is marked
51
+ * with `data-random-state` so it is picked once per page view. Returns the number of slots that swapped.
52
+ * Never rejects: an invalid pool, a data saver, or a failed load leaves the default in place.
53
+ */
54
+ export declare function mountRandomImages(root: ParentNode, env?: RandomImageEnvironment): Promise<number>;
55
+ export interface RandomPoolManifest {
56
+ readonly album: string;
57
+ readonly maxBytes: number;
58
+ readonly entries: readonly {
59
+ readonly key: string;
60
+ readonly bytes: number;
61
+ }[];
62
+ }
63
+ /**
64
+ * Build-time: turns a manifest pool into validated object paths. An entry over `maxBytes` fails the build, so an
65
+ * oversized object never reaches a page.
66
+ */
67
+ export declare function randomPoolFromManifest(pool: RandomPoolManifest): readonly string[];
68
+ /** Build-time: the `data-random-pool` attribute value for a validated pool. */
69
+ export declare function randomPoolAttribute(entries: readonly string[]): string;
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Browser-safe picker for decorative R2 images (`r2-image-random-display`).
3
+ *
4
+ * A slot keeps its vendored default in the markup and carries a `data-random-pool` JSON list of R2 object paths.
5
+ * After load, one entry is picked uniformly, preloaded with a plain `Image()` (never `fetch`, so the R2 CORS rule
6
+ * does not apply), and swapped in only when it loads within the timeout. Every failure keeps the default. No node:
7
+ * import, no library. The environment is injectable so tests can use a fake image and a seeded random source.
8
+ */
9
+ export const R2_IMAGE_ORIGIN = 'https://img-gen.hagicode.com';
10
+ export const RANDOM_POOL_ATTRIBUTE = 'data-random-pool';
11
+ export const RANDOM_POOL_MIN_ENTRIES = 12;
12
+ export const RANDOM_POOL_MAX_ENTRIES = 200;
13
+ export const RANDOM_IMAGE_TIMEOUT_MS = 3000;
14
+ const OBJECT_PATH_PATTERN = /^([a-z0-9][a-z0-9_-]*)\/[a-z0-9][a-z0-9_-]*\.avif$/u;
15
+ /**
16
+ * Checks a pool: 12 to 200 unique `<album>/<key>.avif` object paths, all from one album. Throws a `TypeError`, so a
17
+ * bad pool fails the build instead of the page.
18
+ */
19
+ export function validateRandomPool(entries) {
20
+ if (!Array.isArray(entries) || entries.length < RANDOM_POOL_MIN_ENTRIES || entries.length > RANDOM_POOL_MAX_ENTRIES) {
21
+ throw new TypeError(`Hagilight random pool must list ${RANDOM_POOL_MIN_ENTRIES} to ${RANDOM_POOL_MAX_ENTRIES} R2 objects.`);
22
+ }
23
+ let album;
24
+ for (const entry of entries) {
25
+ const match = typeof entry === 'string' ? OBJECT_PATH_PATTERN.exec(entry) : null;
26
+ if (!match)
27
+ throw new TypeError(`Hagilight random pool entry "${String(entry)}" must be an <album>/<key>.avif object path.`);
28
+ album ??= match[1];
29
+ if (match[1] !== album)
30
+ throw new TypeError('Hagilight random pool entries must all come from one album.');
31
+ }
32
+ if (new Set(entries).size !== entries.length)
33
+ throw new TypeError('Hagilight random pool entries must be unique.');
34
+ return Object.freeze([...entries]);
35
+ }
36
+ /** Picks one entry uniformly. Out-of-range or non-finite random values clamp to the first or last entry. */
37
+ export function pickRandomEntry(entries, random = Math.random) {
38
+ const value = random();
39
+ const fraction = Number.isFinite(value) ? Math.min(Math.max(value, 0), 1 - Number.EPSILON) : 0;
40
+ return entries[Math.floor(fraction * entries.length)];
41
+ }
42
+ /** The full image URL of an R2 object path. */
43
+ export function poolImageUrl(objectPath) {
44
+ return `${R2_IMAGE_ORIGIN}/${objectPath}`;
45
+ }
46
+ /**
47
+ * Loads `url` in an image element. Resolves `true` only when it loads within the timeout; an error, a timeout or a
48
+ * missing `Image` resolves `false`. Never rejects and never retries.
49
+ */
50
+ export function preloadImage(url, env = {}) {
51
+ return new Promise((resolve) => {
52
+ const setTimer = env.setTimer ?? ((callback, ms) => setTimeout(callback, ms));
53
+ const clearTimer = env.clearTimer ?? ((handle) => clearTimeout(handle));
54
+ let timer;
55
+ const finish = (loaded) => {
56
+ clearTimer(timer);
57
+ resolve(loaded);
58
+ };
59
+ try {
60
+ const image = env.createImage ? env.createImage() : new Image();
61
+ image.onload = () => finish(true);
62
+ image.onerror = () => finish(false);
63
+ timer = setTimer(() => finish(false), RANDOM_IMAGE_TIMEOUT_MS);
64
+ image.src = url;
65
+ }
66
+ catch {
67
+ finish(false);
68
+ }
69
+ });
70
+ }
71
+ /**
72
+ * Swaps a loaded URL into a `<picture>` or `<img>` slot. The `<source>` elements are removed so the browser uses the
73
+ * swapped `src`; the `<img>` keeps its width, height and alt text, so the box does not change.
74
+ */
75
+ export function showPoolImage(slot, url) {
76
+ slot.querySelectorAll('source').forEach((source) => source.remove());
77
+ const img = slot.querySelector('img');
78
+ if (!img)
79
+ return;
80
+ img.removeAttribute('srcset');
81
+ img.removeAttribute('sizes');
82
+ img.src = url;
83
+ }
84
+ function dataSaverEnabled() {
85
+ const connection = typeof navigator === 'undefined'
86
+ ? undefined
87
+ : navigator.connection;
88
+ return connection?.saveData === true;
89
+ }
90
+ /**
91
+ * Runs the picker for every `[data-random-pool]` slot under `root` that has not been handled yet. Each slot is marked
92
+ * with `data-random-state` so it is picked once per page view. Returns the number of slots that swapped.
93
+ * Never rejects: an invalid pool, a data saver, or a failed load leaves the default in place.
94
+ */
95
+ export async function mountRandomImages(root, env = {}) {
96
+ const random = env.random ?? Math.random;
97
+ const saveData = env.saveData ?? dataSaverEnabled;
98
+ const slots = Array.from(root.querySelectorAll(`[${RANDOM_POOL_ATTRIBUTE}]:not([data-random-state])`));
99
+ const outcomes = await Promise.all(slots.map(async (slot) => {
100
+ slot.setAttribute('data-random-state', 'default');
101
+ if (saveData())
102
+ return false;
103
+ try {
104
+ const pool = validateRandomPool(JSON.parse(slot.getAttribute(RANDOM_POOL_ATTRIBUTE) ?? 'null'));
105
+ const url = poolImageUrl(pickRandomEntry(pool, random));
106
+ if (!(await preloadImage(url, env)))
107
+ return false;
108
+ showPoolImage(slot, url);
109
+ slot.setAttribute('data-random-state', 'swapped');
110
+ return true;
111
+ }
112
+ catch {
113
+ return false;
114
+ }
115
+ }));
116
+ return outcomes.filter(Boolean).length;
117
+ }
118
+ /**
119
+ * Build-time: turns a manifest pool into validated object paths. An entry over `maxBytes` fails the build, so an
120
+ * oversized object never reaches a page.
121
+ */
122
+ export function randomPoolFromManifest(pool) {
123
+ for (const entry of pool.entries) {
124
+ if (entry.bytes > pool.maxBytes) {
125
+ throw new TypeError(`Hagilight random pool entry ${entry.key} is ${entry.bytes} bytes, over the ${pool.maxBytes} byte cap.`);
126
+ }
127
+ }
128
+ return validateRandomPool(pool.entries.map(({ key }) => `${pool.album}/${key}.avif`));
129
+ }
130
+ /** Build-time: the `data-random-pool` attribute value for a validated pool. */
131
+ export function randomPoolAttribute(entries) {
132
+ return JSON.stringify(validateRandomPool(entries));
133
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hagicode/hagilight-core",
3
- "version": "0.14.1-dev.146.1.e98244c",
3
+ "version": "0.14.1-dev.149.1.1dadf5c",
4
4
  "type": "module",
5
5
  "description": "Shared TypeScript utilities, components, and assets for HagiCode Astro and Starlight sites",
6
6
  "repository": {
@@ -26,6 +26,14 @@
26
26
  "types": "./dist/splash-images.d.ts",
27
27
  "default": "./dist/splash-images.js"
28
28
  },
29
+ "./random-image": {
30
+ "types": "./dist/random-image.d.ts",
31
+ "default": "./dist/random-image.js"
32
+ },
33
+ "./footer-avatar": {
34
+ "types": "./dist/footer-avatar.d.ts",
35
+ "default": "./dist/footer-avatar.js"
36
+ },
29
37
  "./Footer": "./Footer.astro",
30
38
  "./links": {
31
39
  "types": "./dist/links.d.ts",
@@ -111,7 +119,10 @@
111
119
  },
112
120
  "./Analytics51LA": "./Analytics51LA.astro",
113
121
  "./logo.png": "./logo.png",
114
- "./favicon.ico": "./favicon.ico"
122
+ "./favicon.ico": "./favicon.ico",
123
+ "./assets/footer/avatar.avif": "./assets/footer/avatar.avif",
124
+ "./assets/footer/avatar.webp": "./assets/footer/avatar.webp",
125
+ "./assets/footer/manifest.json": "./assets/footer/manifest.json"
115
126
  },
116
127
  "files": [
117
128
  "README.md",
@@ -119,6 +130,7 @@
119
130
  "dist/**/*.d.ts",
120
131
  "dist/**/*.json",
121
132
  "data/**/*.json",
133
+ "assets/**/*",
122
134
  "*.astro",
123
135
  "logo.png",
124
136
  "favicon.ico"