@easy-web/content-blocks 1.0.0 → 1.1.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.
@@ -1,102 +1,102 @@
1
- ---
2
- /**
3
- * UniversalMedia — renders an image from any source type.
4
- *
5
- * @remarks
6
- * Supported image formats: JPEG, PNG, WebP, AVIF, SVG, GIF.
7
- * Unsupported formats (upload rejected at CMS level): HEIC, JXL.
8
- *
9
- * 4-case dispatch:
10
- * 1. ImageMetadata object → <Image> (Astro-optimised, with srcset)
11
- * 2. "/src/assets/..." string → glob lookup via `images` prop → <Image> (fallback to fallbackSrc)
12
- * 3. External URL ("http..." or "https...") → <Image inferSize>
13
- * 4. Everything else (public-folder path "/foo/bar.png") → plain <img>
14
- */
15
- import { Image } from 'astro:assets';
16
- import type { ImageMetadata } from 'astro';
17
-
18
- interface Props {
19
- /** The image source: an Astro ImageMetadata object or a URL/path string. */
20
- src: ImageMetadata | string;
21
- /** Alt text for the image (required). */
22
- alt: string;
23
- /**
24
- * Consumer-supplied glob result mapping paths to lazy image loaders.
25
- * Consumer generates this via Vite's glob-import helper (see Astro/Vite docs)
26
- * matching `/src/assets/**` with `{ import: 'default' }` so entries yield
27
- * `() => Promise<{ default: ImageMetadata }>`.
28
- * The component does NOT resolve the glob itself.
29
- */
30
- images: Record<string, () => Promise<{ default: ImageMetadata }>>;
31
- /** Fallback image path to use when a /src/assets/... glob lookup misses. Defaults to empty (renders nothing gracefully). */
32
- fallbackSrc?: string;
33
- /** Fallback alt text used when fallbackSrc is rendered. Defaults to alt. */
34
- fallbackAlt?: string;
35
- width?: number;
36
- height?: number;
37
- class?: string;
38
- decoding?: 'async' | 'auto' | 'sync';
39
- }
40
-
41
- const {
42
- src,
43
- alt,
44
- images,
45
- fallbackSrc,
46
- fallbackAlt,
47
- width = 800,
48
- height = 600,
49
- class: cssClass = '',
50
- decoding = 'async',
51
- } = Astro.props;
52
-
53
- // Case 1: already a resolved ImageMetadata object
54
- const isImageMetadata = typeof src !== 'string';
55
-
56
- // Normalise string to check against known patterns
57
- const srcStr = isImageMetadata ? '' : (src as string);
58
-
59
- // Case 2: /src/assets/... path — must be resolved via consumer-supplied glob
60
- const isInternalSrcAssets = srcStr.startsWith('/src/assets/');
61
-
62
- // Case 3: external URL
63
- const isExternalUrl = srcStr.startsWith('http://') || srcStr.startsWith('https://');
64
-
65
- // Resolve ImageMetadata for cases 1 & 2
66
- let resolvedSrc: ImageMetadata | null = null;
67
- let resolvedAlt = alt;
68
-
69
- if (isImageMetadata) {
70
- resolvedSrc = src as ImageMetadata;
71
- } else if (isInternalSrcAssets) {
72
- const loader = images[srcStr];
73
- if (typeof loader === 'function') {
74
- const mod = await loader();
75
- resolvedSrc = mod.default ?? (mod as unknown as ImageMetadata);
76
- }
77
- if (!resolvedSrc && fallbackSrc) {
78
- const fallbackLoader = images[fallbackSrc];
79
- if (typeof fallbackLoader === 'function') {
80
- const mod = await fallbackLoader();
81
- resolvedSrc = mod.default ?? (mod as unknown as ImageMetadata);
82
- resolvedAlt = fallbackAlt ?? alt;
83
- } else {
84
- console.warn(
85
- `UniversalMedia: "${srcStr}" not found in glob, and fallbackSrc "${fallbackSrc}" is also missing. Rendering as plain <img>.`
86
- );
87
- }
88
- }
89
- }
90
- ---
91
-
92
- {isImageMetadata || isInternalSrcAssets ? (
93
- resolvedSrc ? (
94
- <Image class={cssClass} src={resolvedSrc} alt={resolvedAlt} width={width} height={height} decoding={decoding} />
95
- ) : (
96
- <img class={cssClass} src={srcStr} alt={alt} width={width} height={height} decoding={decoding} />
97
- )
98
- ) : isExternalUrl ? (
99
- <Image class={cssClass} src={srcStr} alt={alt} inferSize decoding={decoding} />
100
- ) : (
101
- <img class={cssClass} src={srcStr} alt={alt} width={width} height={height} decoding={decoding} />
102
- )}
1
+ ---
2
+ /**
3
+ * UniversalMedia — renders an image from any source type.
4
+ *
5
+ * @remarks
6
+ * Supported image formats: JPEG, PNG, WebP, AVIF, SVG, GIF.
7
+ * Unsupported formats (upload rejected at CMS level): HEIC, JXL.
8
+ *
9
+ * 4-case dispatch:
10
+ * 1. ImageMetadata object → <Image> (Astro-optimised, with srcset)
11
+ * 2. "/src/assets/..." string → glob lookup via `images` prop → <Image> (fallback to fallbackSrc)
12
+ * 3. External URL ("http..." or "https...") → <Image inferSize>
13
+ * 4. Everything else (public-folder path "/foo/bar.png") → plain <img>
14
+ */
15
+ import { Image } from 'astro:assets';
16
+ import type { ImageMetadata } from 'astro';
17
+
18
+ interface Props {
19
+ /** The image source: an Astro ImageMetadata object or a URL/path string. */
20
+ src: ImageMetadata | string;
21
+ /** Alt text for the image (required). */
22
+ alt: string;
23
+ /**
24
+ * Consumer-supplied glob result mapping paths to lazy image loaders.
25
+ * Consumer generates this via Vite's glob-import helper (see Astro/Vite docs)
26
+ * matching `/src/assets/**` with `{ import: 'default' }` so entries yield
27
+ * `() => Promise<{ default: ImageMetadata }>`.
28
+ * The component does NOT resolve the glob itself.
29
+ */
30
+ images: Record<string, () => Promise<{ default: ImageMetadata }>>;
31
+ /** Fallback image path to use when a /src/assets/... glob lookup misses. Defaults to empty (renders nothing gracefully). */
32
+ fallbackSrc?: string;
33
+ /** Fallback alt text used when fallbackSrc is rendered. Defaults to alt. */
34
+ fallbackAlt?: string;
35
+ width?: number;
36
+ height?: number;
37
+ class?: string;
38
+ decoding?: 'async' | 'auto' | 'sync';
39
+ }
40
+
41
+ const {
42
+ src,
43
+ alt,
44
+ images,
45
+ fallbackSrc,
46
+ fallbackAlt,
47
+ width = 800,
48
+ height = 600,
49
+ class: cssClass = '',
50
+ decoding = 'async',
51
+ } = Astro.props;
52
+
53
+ // Case 1: already a resolved ImageMetadata object
54
+ const isImageMetadata = typeof src !== 'string';
55
+
56
+ // Normalise string to check against known patterns
57
+ const srcStr = isImageMetadata ? '' : (src as string);
58
+
59
+ // Case 2: /src/assets/... path — must be resolved via consumer-supplied glob
60
+ const isInternalSrcAssets = srcStr.startsWith('/src/assets/');
61
+
62
+ // Case 3: external URL
63
+ const isExternalUrl = srcStr.startsWith('http://') || srcStr.startsWith('https://');
64
+
65
+ // Resolve ImageMetadata for cases 1 & 2
66
+ let resolvedSrc: ImageMetadata | null = null;
67
+ let resolvedAlt = alt;
68
+
69
+ if (isImageMetadata) {
70
+ resolvedSrc = src as ImageMetadata;
71
+ } else if (isInternalSrcAssets) {
72
+ const loader = images[srcStr];
73
+ if (typeof loader === 'function') {
74
+ const mod = await loader();
75
+ resolvedSrc = mod.default ?? (mod as unknown as ImageMetadata);
76
+ }
77
+ if (!resolvedSrc && fallbackSrc) {
78
+ const fallbackLoader = images[fallbackSrc];
79
+ if (typeof fallbackLoader === 'function') {
80
+ const mod = await fallbackLoader();
81
+ resolvedSrc = mod.default ?? (mod as unknown as ImageMetadata);
82
+ resolvedAlt = fallbackAlt ?? alt;
83
+ } else {
84
+ console.warn(
85
+ `UniversalMedia: "${srcStr}" not found in glob, and fallbackSrc "${fallbackSrc}" is also missing. Rendering as plain <img>.`
86
+ );
87
+ }
88
+ }
89
+ }
90
+ ---
91
+
92
+ {isImageMetadata || isInternalSrcAssets ? (
93
+ resolvedSrc ? (
94
+ <Image class={cssClass} src={resolvedSrc} alt={resolvedAlt} width={width} height={height} decoding={decoding} />
95
+ ) : (
96
+ <img class={cssClass} src={srcStr} alt={alt} width={width} height={height} decoding={decoding} />
97
+ )
98
+ ) : isExternalUrl ? (
99
+ <Image class={cssClass} src={srcStr} alt={alt} inferSize decoding={decoding} />
100
+ ) : (
101
+ <img class={cssClass} src={srcStr} alt={alt} width={width} height={height} decoding={decoding} />
102
+ )}
@@ -1,65 +1,65 @@
1
- import { describe, it, expect } from 'vitest';
2
- import type { ImageMetadata } from 'astro';
3
-
4
- /**
5
- * Mirrors the dispatch logic inside UniversalMedia.astro.
6
- * Tests the categorisation, not the Astro rendering (which requires a full Astro setup).
7
- *
8
- * The component branches on 4 cases:
9
- * 1. ImageMetadata object → <Image> (Astro-optimised)
10
- * 2. "/src/assets/..." string → glob lookup → <Image> (with fallback path)
11
- * 3. "http(s)://..." string → <Image inferSize>
12
- * 4. Everything else (public path) → plain <img>
13
- */
14
- type DispatchCase = 'image-metadata' | 'internal-src-assets' | 'external-url' | 'public-path';
15
-
16
- function classifySource(src: ImageMetadata | string): DispatchCase {
17
- if (typeof src !== 'string') return 'image-metadata';
18
- if (src.startsWith('/src/assets/')) return 'internal-src-assets';
19
- if (src.startsWith('http://') || src.startsWith('https://')) return 'external-url';
20
- return 'public-path';
21
- }
22
-
23
- // Minimal ImageMetadata stub for test case 1
24
- const mockImageMetadata: ImageMetadata = {
25
- src: '/src/assets/images/test.png',
26
- width: 100,
27
- height: 100,
28
- format: 'png',
29
- };
30
-
31
- describe('<UniversalMedia> dispatch logic', () => {
32
- it('case 1: ImageMetadata object → image-metadata', () => {
33
- expect(classifySource(mockImageMetadata)).toBe('image-metadata');
34
- });
35
-
36
- it('case 2: /src/assets/ string → internal-src-assets (glob lookup path)', () => {
37
- expect(classifySource('/src/assets/images/photo.jpg')).toBe('internal-src-assets');
38
- });
39
-
40
- it('case 3: https:// URL → external-url (inferSize path)', () => {
41
- expect(classifySource('https://example.com/photo.jpg')).toBe('external-url');
42
- });
43
-
44
- it('case 4: public path /foo/bar.png → public-path (plain img)', () => {
45
- expect(classifySource('/uploads/photo.jpg')).toBe('public-path');
46
- });
47
-
48
- it('case 5: glob miss + fallbackSrc → fallback branch applies when resolvedSrc is null', () => {
49
- // Simulate glob miss: empty images map for a /src/assets/ URL
50
- const images: Record<string, () => Promise<{ default: ImageMetadata }>> = {};
51
- const src = '/src/assets/images/missing.png';
52
- const fallbackSrc = '/src/assets/images/default.png';
53
-
54
- const dispatch = classifySource(src);
55
- expect(dispatch).toBe('internal-src-assets');
56
-
57
- // Verify fallback key lookup works
58
- const hasMainImage = src in images;
59
- const hasFallback = fallbackSrc in images;
60
- expect(hasMainImage).toBe(false); // glob miss
61
- expect(hasFallback).toBe(false); // fallback also missing → plain img fallback
62
-
63
- // The component would render plain <img> when both are missing (documented in UniversalMedia)
64
- });
65
- });
1
+ import { describe, it, expect } from 'vitest';
2
+ import type { ImageMetadata } from 'astro';
3
+
4
+ /**
5
+ * Mirrors the dispatch logic inside UniversalMedia.astro.
6
+ * Tests the categorisation, not the Astro rendering (which requires a full Astro setup).
7
+ *
8
+ * The component branches on 4 cases:
9
+ * 1. ImageMetadata object → <Image> (Astro-optimised)
10
+ * 2. "/src/assets/..." string → glob lookup → <Image> (with fallback path)
11
+ * 3. "http(s)://..." string → <Image inferSize>
12
+ * 4. Everything else (public path) → plain <img>
13
+ */
14
+ type DispatchCase = 'image-metadata' | 'internal-src-assets' | 'external-url' | 'public-path';
15
+
16
+ function classifySource(src: ImageMetadata | string): DispatchCase {
17
+ if (typeof src !== 'string') return 'image-metadata';
18
+ if (src.startsWith('/src/assets/')) return 'internal-src-assets';
19
+ if (src.startsWith('http://') || src.startsWith('https://')) return 'external-url';
20
+ return 'public-path';
21
+ }
22
+
23
+ // Minimal ImageMetadata stub for test case 1
24
+ const mockImageMetadata: ImageMetadata = {
25
+ src: '/src/assets/images/test.png',
26
+ width: 100,
27
+ height: 100,
28
+ format: 'png',
29
+ };
30
+
31
+ describe('<UniversalMedia> dispatch logic', () => {
32
+ it('case 1: ImageMetadata object → image-metadata', () => {
33
+ expect(classifySource(mockImageMetadata)).toBe('image-metadata');
34
+ });
35
+
36
+ it('case 2: /src/assets/ string → internal-src-assets (glob lookup path)', () => {
37
+ expect(classifySource('/src/assets/images/photo.jpg')).toBe('internal-src-assets');
38
+ });
39
+
40
+ it('case 3: https:// URL → external-url (inferSize path)', () => {
41
+ expect(classifySource('https://example.com/photo.jpg')).toBe('external-url');
42
+ });
43
+
44
+ it('case 4: public path /foo/bar.png → public-path (plain img)', () => {
45
+ expect(classifySource('/uploads/photo.jpg')).toBe('public-path');
46
+ });
47
+
48
+ it('case 5: glob miss + fallbackSrc → fallback branch applies when resolvedSrc is null', () => {
49
+ // Simulate glob miss: empty images map for a /src/assets/ URL
50
+ const images: Record<string, () => Promise<{ default: ImageMetadata }>> = {};
51
+ const src = '/src/assets/images/missing.png';
52
+ const fallbackSrc = '/src/assets/images/default.png';
53
+
54
+ const dispatch = classifySource(src);
55
+ expect(dispatch).toBe('internal-src-assets');
56
+
57
+ // Verify fallback key lookup works
58
+ const hasMainImage = src in images;
59
+ const hasFallback = fallbackSrc in images;
60
+ expect(hasMainImage).toBe(false); // glob miss
61
+ expect(hasFallback).toBe(false); // fallback also missing → plain img fallback
62
+
63
+ // The component would render plain <img> when both are missing (documented in UniversalMedia)
64
+ });
65
+ });
@@ -1,32 +1,32 @@
1
- import { describe, it, expect } from 'vitest';
2
- import { notFoundSchema } from '../notFound.js';
3
-
4
- describe('notFoundSchema', () => {
5
- it('parses a multi-locale object with partial fields', () => {
6
- const input = {
7
- de: { heading: 'Seite nicht gefunden', message: 'Existiert nicht.' },
8
- en: { heading: 'Not found' },
9
- };
10
- expect(() => notFoundSchema.parse(input)).not.toThrow();
11
- const result = notFoundSchema.parse(input);
12
- expect(result.de.heading).toBe('Seite nicht gefunden');
13
- expect(result.en.heading).toBe('Not found');
14
- });
15
-
16
- it('parses an empty object (all fields optional)', () => {
17
- expect(() => notFoundSchema.parse({})).not.toThrow();
18
- expect(notFoundSchema.parse({})).toEqual({});
19
- });
20
-
21
- it('parses arbitrary locale keys (open record)', () => {
22
- const input = { de: {}, fr: {}, sq: {} };
23
- expect(() => notFoundSchema.parse(input)).not.toThrow();
24
- const result = notFoundSchema.parse(input);
25
- expect(Object.keys(result)).toEqual(expect.arrayContaining(['de', 'fr', 'sq']));
26
- });
27
-
28
- it('rejects a record where image is not a string', () => {
29
- const input = { de: { image: 42 } };
30
- expect(() => notFoundSchema.parse(input)).toThrow();
31
- });
32
- });
1
+ import { describe, it, expect } from 'vitest';
2
+ import { notFoundSchema } from '../notFound.js';
3
+
4
+ describe('notFoundSchema', () => {
5
+ it('parses a multi-locale object with partial fields', () => {
6
+ const input = {
7
+ de: { heading: 'Seite nicht gefunden', message: 'Existiert nicht.' },
8
+ en: { heading: 'Not found' },
9
+ };
10
+ expect(() => notFoundSchema.parse(input)).not.toThrow();
11
+ const result = notFoundSchema.parse(input);
12
+ expect(result.de.heading).toBe('Seite nicht gefunden');
13
+ expect(result.en.heading).toBe('Not found');
14
+ });
15
+
16
+ it('parses an empty object (all fields optional)', () => {
17
+ expect(() => notFoundSchema.parse({})).not.toThrow();
18
+ expect(notFoundSchema.parse({})).toEqual({});
19
+ });
20
+
21
+ it('parses arbitrary locale keys (open record)', () => {
22
+ const input = { de: {}, fr: {}, sq: {} };
23
+ expect(() => notFoundSchema.parse(input)).not.toThrow();
24
+ const result = notFoundSchema.parse(input);
25
+ expect(Object.keys(result)).toEqual(expect.arrayContaining(['de', 'fr', 'sq']));
26
+ });
27
+
28
+ it('rejects a record where image is not a string', () => {
29
+ const input = { de: { image: 42 } };
30
+ expect(() => notFoundSchema.parse(input)).toThrow();
31
+ });
32
+ });
@@ -1,33 +1,33 @@
1
- /**
2
- * Not-found (404) singleton schema — locale-keyed CMS-editable content.
3
- *
4
- * Each locale key maps to an optional set of fields rendered by the site's
5
- * 404 page. All fields are optional so partial translations are valid; a
6
- * consuming page falls back to defaults when a field is absent.
7
- *
8
- * The record key is an open `z.string()` so any IETF locale tag (e.g. `de`,
9
- * `en`, `fr`, `sq`, `de-AT`) is accepted without schema changes. Do NOT add
10
- * SEO metadata (title, canonical) here — those belong to the page layer.
11
- *
12
- * Usage:
13
- *
14
- * ```ts
15
- * import { notFoundSchema } from '@easy-web/content-blocks/schemas/notFound';
16
- *
17
- * const data = notFoundSchema.parse(await import('../content/not-found.json'));
18
- * ```
19
- *
20
- * @see docs/decisions/0011-content-architecture-strategy.md
21
- * @see docs/decisions/0013-shared-not-found-primitives.md
22
- */
23
- import { z } from 'zod';
24
-
25
- export const localizedNotFoundSchema = z.object({
26
- image: z.string().optional(),
27
- heading: z.string().optional(),
28
- message: z.string().optional(),
29
- });
30
-
31
- export const notFoundSchema = z.record(z.string(), localizedNotFoundSchema);
32
-
33
- export type NotFoundData = z.infer<typeof notFoundSchema>;
1
+ /**
2
+ * Not-found (404) singleton schema — locale-keyed CMS-editable content.
3
+ *
4
+ * Each locale key maps to an optional set of fields rendered by the site's
5
+ * 404 page. All fields are optional so partial translations are valid; a
6
+ * consuming page falls back to defaults when a field is absent.
7
+ *
8
+ * The record key is an open `z.string()` so any IETF locale tag (e.g. `de`,
9
+ * `en`, `fr`, `sq`, `de-AT`) is accepted without schema changes. Do NOT add
10
+ * SEO metadata (title, canonical) here — those belong to the page layer.
11
+ *
12
+ * Usage:
13
+ *
14
+ * ```ts
15
+ * import { notFoundSchema } from '@easy-web/content-blocks/schemas/notFound';
16
+ *
17
+ * const data = notFoundSchema.parse(await import('../content/not-found.json'));
18
+ * ```
19
+ *
20
+ * @see docs/decisions/0011-content-architecture-strategy.md
21
+ * @see docs/decisions/0013-shared-not-found-primitives.md
22
+ */
23
+ import { z } from 'zod';
24
+
25
+ export const localizedNotFoundSchema = z.object({
26
+ image: z.string().optional(),
27
+ heading: z.string().optional(),
28
+ message: z.string().optional(),
29
+ });
30
+
31
+ export const notFoundSchema = z.record(z.string(), localizedNotFoundSchema);
32
+
33
+ export type NotFoundData = z.infer<typeof notFoundSchema>;