@sinnstack/ui 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.
Files changed (138) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/README.md +6 -4
  3. package/docs/blocks.md +373 -364
  4. package/docs/data.md +128 -128
  5. package/docs/finishes.md +165 -0
  6. package/docs/primitives.md +4 -4
  7. package/docs/seo.md +191 -187
  8. package/package.json +15 -24
  9. package/src/blocks/BlockRenderer.astro +13 -7
  10. package/src/blocks/CTABanner.astro +8 -8
  11. package/src/blocks/CTAPair.astro +9 -9
  12. package/src/blocks/CardGrid.astro +7 -7
  13. package/src/blocks/ConsentEmbed.astro +1 -1
  14. package/src/blocks/ConsentManager.astro +1 -1
  15. package/src/blocks/ContactCard.astro +14 -14
  16. package/src/blocks/ContactForm.astro +4 -4
  17. package/src/blocks/ErrorPage.astro +1 -1
  18. package/src/blocks/FAQ.astro +9 -9
  19. package/src/blocks/FeatureGrid.astro +7 -7
  20. package/src/blocks/Hero.astro +11 -11
  21. package/src/blocks/HeroCarousel.astro +11 -11
  22. package/src/blocks/HighlightCards.astro +10 -10
  23. package/src/blocks/LocationHours.astro +14 -14
  24. package/src/blocks/LogoCloud.astro +7 -7
  25. package/src/blocks/MaintenancePage.astro +8 -3
  26. package/src/blocks/MediaText.astro +12 -12
  27. package/src/blocks/PageHeader.astro +9 -9
  28. package/src/blocks/ProseSection.astro +8 -8
  29. package/src/blocks/Reviews.astro +11 -11
  30. package/src/blocks/RichText.astro +58 -57
  31. package/src/blocks/StatsBand.astro +117 -117
  32. package/src/blocks/Steps.astro +9 -9
  33. package/src/blocks/Testimonials.astro +13 -13
  34. package/src/blocks/cms/card-grid.ts +48 -80
  35. package/src/blocks/cms/consent.ts +1 -30
  36. package/src/blocks/cms/contact-card.ts +4 -46
  37. package/src/blocks/cms/contact-form.ts +2 -20
  38. package/src/blocks/cms/cta-banner.ts +2 -23
  39. package/src/blocks/cms/cta-pair.ts +4 -37
  40. package/src/blocks/cms/data-base.ts +2 -4
  41. package/src/blocks/cms/data.ts +19 -19
  42. package/src/blocks/cms/faq.ts +4 -36
  43. package/src/blocks/cms/feature-grid.ts +47 -80
  44. package/src/blocks/cms/fixtures.ts +591 -599
  45. package/src/blocks/cms/hero-carousel.ts +4 -48
  46. package/src/blocks/cms/hero.ts +2 -46
  47. package/src/blocks/cms/highlight-cards.ts +4 -39
  48. package/src/blocks/cms/images.ts +1 -2
  49. package/src/blocks/cms/index.ts +59 -87
  50. package/src/blocks/cms/location-hours.ts +3 -85
  51. package/src/blocks/cms/logo-cloud.ts +36 -62
  52. package/src/blocks/cms/media-text.ts +2 -20
  53. package/src/blocks/cms/page-header.ts +27 -49
  54. package/src/blocks/cms/pages.ts +35 -81
  55. package/src/blocks/cms/prose-section.ts +2 -22
  56. package/src/blocks/cms/reviews.ts +5 -56
  57. package/src/blocks/cms/schema-dsl.ts +134 -0
  58. package/src/blocks/cms/schema.ts +794 -0
  59. package/src/blocks/cms/shared.ts +63 -115
  60. package/src/blocks/cms/stats-band.ts +35 -61
  61. package/src/blocks/cms/steps.ts +4 -31
  62. package/src/blocks/cms/testimonials.ts +4 -38
  63. package/src/blocks/cms/topbar.ts +4 -41
  64. package/src/blocks/cms/types.ts +1 -37
  65. package/src/blocks/consent.ts +2 -2
  66. package/src/blocks/index.ts +2 -2
  67. package/src/blocks/internal/Actions.astro +11 -5
  68. package/src/blocks/internal/BlockHeader.astro +7 -7
  69. package/src/blocks/internal/Placeholder.astro +3 -3
  70. package/src/blocks/internal/fields.ts +18 -0
  71. package/src/blocks/internal/registry-contract.ts +67 -0
  72. package/src/blocks/internal/util.ts +4 -4
  73. package/src/blocks/lib/contact.ts +10 -4
  74. package/src/blocks/lib/faq.ts +1 -1
  75. package/src/blocks/lib/markdown.ts +350 -0
  76. package/src/blocks/lib/rich-text.ts +132 -143
  77. package/src/blocks/scripts/consent-manager.ts +1 -1
  78. package/src/blocks/scripts/consent-store.ts +1 -1
  79. package/src/blocks/scripts/hours.ts +3 -2
  80. package/src/blocks/types.ts +33 -23
  81. package/src/data/ChartContainer.astro +2 -1
  82. package/src/data/cms.ts +130 -190
  83. package/src/data/lib/chart.ts +13 -4
  84. package/src/data/schema.ts +65 -0
  85. package/src/finishes/aurora.css +75 -0
  86. package/src/finishes/autumn.css +87 -0
  87. package/src/finishes/blueprint.css +69 -0
  88. package/src/finishes/brutalist.css +55 -0
  89. package/src/finishes/clay.css +48 -0
  90. package/src/finishes/day-cycle.css +46 -0
  91. package/src/finishes/fog.css +71 -0
  92. package/src/finishes/glass.css +149 -0
  93. package/src/finishes/holographic.css +91 -0
  94. package/src/finishes/night.css +77 -0
  95. package/src/finishes/paper.css +58 -0
  96. package/src/finishes/polished-glass.css +159 -0
  97. package/src/finishes/rain.css +84 -0
  98. package/src/finishes/scripts/day-cycle.ts +30 -0
  99. package/src/finishes/scripts/holographic.ts +37 -0
  100. package/src/finishes/scripts/spotlight.ts +30 -0
  101. package/src/finishes/spotlight.css +41 -0
  102. package/src/finishes/spring.css +80 -0
  103. package/src/finishes/terminal.css +49 -0
  104. package/src/primitives/Divider.astro +1 -1
  105. package/src/primitives/FocusRing.astro +1 -1
  106. package/src/primitives/FormField.astro +2 -2
  107. package/src/primitives/Image.astro +3 -3
  108. package/src/primitives/Input.astro +4 -2
  109. package/src/primitives/MetricCard.astro +3 -1
  110. package/src/primitives/Picture.astro +3 -3
  111. package/src/primitives/Prose.astro +1 -1
  112. package/src/primitives/Select.astro +4 -2
  113. package/src/primitives/Slider.astro +1 -1
  114. package/src/primitives/Table.astro +1 -1
  115. package/src/primitives/Textarea.astro +4 -2
  116. package/src/primitives/Thumbnail.astro +2 -2
  117. package/src/primitives/index.ts +4 -4
  118. package/src/primitives/internal/ChoiceField.astro +4 -2
  119. package/src/primitives/scripts/slider.ts +1 -1
  120. package/src/primitives/scripts/table-sort.ts +2 -2
  121. package/src/seo/cms.ts +59 -80
  122. package/src/seo/index.ts +1 -1
  123. package/src/seo/integration.ts +40 -3
  124. package/src/seo/lib/jsonld.ts +10 -2
  125. package/src/seo/lib/meta.ts +2 -2
  126. package/src/seo/lib/redirects.ts +14 -4
  127. package/src/seo/lib/rss.ts +1 -1
  128. package/src/seo/lib/sitemap.ts +1 -1
  129. package/src/seo/schema.ts +43 -0
  130. package/src/blocks/internal/tina.ts +0 -19
  131. /package/src/blocks/{lib → internal}/consent.ts +0 -0
  132. /package/src/blocks/{lib → internal}/reviews.ts +0 -0
  133. /package/src/blocks/{lib → internal}/slug.ts +0 -0
  134. /package/src/data/{lib → internal}/scale.ts +0 -0
  135. /package/src/primitives/{lib → internal}/image-plan.ts +0 -0
  136. /package/src/primitives/{lib → internal}/image.ts +0 -0
  137. /package/src/primitives/{lib → internal}/slider.ts +0 -0
  138. /package/src/seo/{lib → internal}/url.ts +0 -0
@@ -145,8 +145,10 @@ const summary = hasTrend
145
145
  // ----- Target meter -----
146
146
  const hasTarget = hasValue && typeof target === 'number' && target > 0;
147
147
  const targetPct = hasTarget ? pct(value!, target!) : 0;
148
+ // Written as `(value as number) /`, not `value! /`: the language server's .astro parser
149
+ // (@astrojs/astro2tsx 0.1.4) reads a `/` after `!` as a regex and misses the closing `---`.
148
150
  const targetText = hasTarget
149
- ? `${formatValue(value! / target!, { kind: 'percent', digits: 0 }, locale)} of ${formatValue(target, valueSpec, locale)} ${targetLabel}`
151
+ ? `${formatValue((value as number) / (target as number), { kind: 'percent', digits: 0 }, locale)} of ${formatValue(target, valueSpec, locale)} ${targetLabel}`
150
152
  : '';
151
153
 
152
154
  const hasIcon = Astro.slots.has('icon');
@@ -15,7 +15,7 @@
15
15
  * sources={[{ media: '(max-width: 40rem)', src: heroTall, aspect: '4/5' }]} />
16
16
  */
17
17
  import type { HTMLAttributes } from 'astro/types';
18
- import type { Aspect, ImageLayout } from './lib/image-plan';
18
+ import type { Aspect, ImageLayout } from './internal/image-plan';
19
19
  import {
20
20
  buildImageSet,
21
21
  fallbackFormatFor,
@@ -24,7 +24,7 @@ import {
24
24
  type ImageSet,
25
25
  type ImageSource,
26
26
  type PictureSource,
27
- } from './lib/image';
27
+ } from './internal/image';
28
28
  import './styles/utilities.css';
29
29
  import './styles/media.css';
30
30
 
@@ -102,7 +102,7 @@ const fallback = await buildImageSet({ src, width, height, displayWidth, aspect,
102
102
 
103
103
  // With art direction the files are already cropped per source and each <source> carries its
104
104
  // own width/height, so the <img> must not force the base aspect in CSS.
105
- const priorityAttrs = priority ? { loading: 'eager', fetchpriority: 'high' } : { loading: 'lazy', decoding: 'async' };
105
+ const priorityAttrs = priority ? ({ loading: 'eager', fetchpriority: 'high' } as const) : ({ loading: 'lazy', decoding: 'async' } as const);
106
106
  const figure = Boolean(caption || credit);
107
107
  ---
108
108
 
@@ -7,7 +7,7 @@
7
7
  * - Components embedded in the content keep their own look: wrap them in `class="sinn-not-prose"`.
8
8
  * - Links are always underlined, as running text needs (WCAG 1.4.1).
9
9
  * - `measure` caps the line length at about 65 characters.
10
- * - For Tina rich text use `RichText` from `@sinnstack/ui/blocks`, which renders inside a Prose
10
+ * - For CMS rich text use `RichText` from `@sinnstack/ui/blocks`, which renders inside a Prose
11
11
  * and only allows safe elements and URLs.
12
12
  *
13
13
  * @example
@@ -43,12 +43,14 @@ const {
43
43
  placeholder,
44
44
  size = 'm',
45
45
  multiple = false,
46
- id = uid('sinn-select'),
46
+ id: idProp,
47
47
  required = false,
48
48
  'aria-describedby': describedBy,
49
49
  class: className,
50
50
  ...rest
51
51
  } = Astro.props;
52
+ // `??`, not a default: a default only replaces undefined, and id={null} would give "null-error" ids.
53
+ const id = idProp ?? uid('sinn-select');
52
54
 
53
55
  const wrapped = Boolean(label || description || error);
54
56
  // `class` goes on the field wrapper, or on the control itself when there is no wrapper.
@@ -66,7 +68,7 @@ const extraOptions = Astro.slots.has('default') ? await Astro.slots.render('defa
66
68
  error={error}
67
69
  hideLabel={hideLabel}
68
70
  optional={optional}
69
- required={required}
71
+ required={Boolean(required)}
70
72
  messages={messages}
71
73
  aria-describedby={describedBy as string | undefined}
72
74
  class={className}
@@ -22,7 +22,7 @@
22
22
  import type { HTMLAttributes } from 'astro/types';
23
23
  import type { ControlSize, ValueFormat } from './types';
24
24
  import { idList, uid } from './utils';
25
- import { sliderModel, type SliderMarkInput } from './lib/slider';
25
+ import { sliderModel, type SliderMarkInput } from './internal/slider';
26
26
  import FormDescription from './FormDescription.astro';
27
27
  import FormError from './FormError.astro';
28
28
  import SliderScript from './internal/SliderScript.astro';
@@ -115,7 +115,7 @@ const {
115
115
  const id = uid('sinn-table');
116
116
  const captionId = `${id}-caption`;
117
117
  const descId = description ? `${id}-desc` : undefined;
118
- const role = (r: string) => (stack ? r : undefined);
118
+ const role = (r: 'table' | 'rowgroup' | 'row' | 'columnheader' | 'rowheader' | 'cell') => (stack ? r : undefined);
119
119
 
120
120
  const NUMERIC_KINDS = new Set<FormatKind>(['number', 'integer', 'compact', 'currency', 'percent', 'delta', 'delta-percent']);
121
121
  const kindOf = (c: TableColumn<Row>): FormatKind | undefined =>
@@ -33,13 +33,15 @@ const {
33
33
  rows = 4,
34
34
  resize = 'vertical',
35
35
  autosize = false,
36
- id = uid('sinn-textarea'),
36
+ id: idProp,
37
37
  required = false,
38
38
  value,
39
39
  'aria-describedby': describedBy,
40
40
  class: className,
41
41
  ...rest
42
42
  } = Astro.props;
43
+ // `??`, not a default: a default only replaces undefined, and id={null} would give "null-error" ids.
44
+ const id = idProp ?? uid('sinn-textarea');
43
45
 
44
46
  const wrapped = Boolean(label || description || error);
45
47
  // `class` goes on the field wrapper, or on the control itself when there is no wrapper.
@@ -53,7 +55,7 @@ const controlClass = wrapped ? undefined : className;
53
55
  error={error}
54
56
  hideLabel={hideLabel}
55
57
  optional={optional}
56
- required={required}
58
+ required={Boolean(required)}
57
59
  messages={messages}
58
60
  aria-describedby={describedBy as string | undefined}
59
61
  class={className}
@@ -18,8 +18,8 @@
18
18
  * <Thumbnail kind="file" fileType="PDF" href="/forms/consent.pdf" label="Consent form (PDF, 220 KB)" />
19
19
  */
20
20
  import type { HTMLAttributes } from 'astro/types';
21
- import type { Aspect } from './lib/image-plan';
22
- import { buildImageSet, type ImageSource } from './lib/image';
21
+ import type { Aspect } from './internal/image-plan';
22
+ import { buildImageSet, type ImageSource } from './internal/image';
23
23
  import './styles/utilities.css';
24
24
  import './styles/media.css';
25
25
 
@@ -70,8 +70,8 @@ export { default as Slider } from './Slider.astro';
70
70
  export { default as Disclosure } from './Disclosure.astro';
71
71
  export { default as Accordion } from './Accordion.astro';
72
72
  export { default as Tabs } from './Tabs.astro';
73
- export { sliderModel } from './lib/slider';
74
- export type { SliderInput, SliderMarkInput, SliderModel } from './lib/slider';
73
+ export { sliderModel } from './internal/slider';
74
+ export type { SliderInput, SliderMarkInput, SliderModel } from './internal/slider';
75
75
 
76
76
  // Data display
77
77
  export { default as List } from './List.astro';
@@ -87,8 +87,8 @@ export { default as Image } from './Image.astro';
87
87
  export { default as Picture } from './Picture.astro';
88
88
  export { default as Thumbnail } from './Thumbnail.astro';
89
89
  export { default as MediaObject } from './MediaObject.astro';
90
- export type { Aspect, ImageLayout } from './lib/image-plan';
91
- export type { ImageFormat, ImageQuality, ImageSource, PictureSource } from './lib/image';
90
+ export type { Aspect, ImageLayout } from './internal/image-plan';
91
+ export type { ImageFormat, ImageQuality, ImageSource, PictureSource } from './internal/image';
92
92
 
93
93
  // Accessibility utilities
94
94
  export { default as VisuallyHidden } from './VisuallyHidden.astro';
@@ -31,12 +31,14 @@ const {
31
31
  messages,
32
32
  size = 'm',
33
33
  labelPosition = 'end',
34
- id = uid(`sinn-${kind}`),
34
+ id: idProp,
35
35
  required = false,
36
36
  class: className,
37
37
  'aria-describedby': describedBy,
38
38
  ...rest
39
39
  } = Astro.props;
40
+ // `??`, not a default: a default only replaces undefined, and id={null} would give "null-error" ids.
41
+ const id = idProp ?? uid(`sinn-${kind}`);
40
42
 
41
43
  const hasErrorElement = kind !== 'radio';
42
44
  const field = fieldContext({
@@ -52,7 +54,7 @@ const isInvalid = field.invalid || invalid;
52
54
  // Merge into one object so no attribute is rendered twice.
53
55
  const inputAttrs = {
54
56
  ...field.attrs,
55
- 'aria-invalid': isInvalid ? 'true' : undefined,
57
+ 'aria-invalid': isInvalid ? ('true' as const) : undefined,
56
58
  ...extraInputAttrs,
57
59
  ...rest,
58
60
  };
@@ -10,7 +10,7 @@
10
10
  */
11
11
  import type { SinnSliderChangeDetail, ValueFormat } from '../types';
12
12
  import { formatValue } from '../utils';
13
- import { rangeText, snap, toPct, topThumb } from '../lib/slider';
13
+ import { rangeText, snap, toPct, topThumb } from '../internal/slider';
14
14
 
15
15
  const FLAG = '__sinnSlider';
16
16
  const w = window as unknown as Record<string, boolean>;
@@ -58,8 +58,8 @@ if (!w[FLAG]) {
58
58
  const label = button.textContent?.trim() ?? '';
59
59
  const direction = status.dataset[next] ?? next;
60
60
  status.textContent = (status.dataset.template ?? 'Sorted by {column}, {direction}')
61
- .replace('{column}', label)
62
- .replace('{direction}', direction);
61
+ .replace('{column}', () => label)
62
+ .replace('{direction}', () => direction);
63
63
  }
64
64
  });
65
65
  }
package/src/seo/cms.ts CHANGED
@@ -1,80 +1,59 @@
1
- /**
2
- * Tina fields for SEO: a per-page `seo` object and a site-wide redirect list. Structural (no
3
- * tinacms dependency), same shape as Tina's field definitions.
4
- *
5
- * // page collection
6
- * fields: [ ...pageFields, seoField ]
7
- * // site settings singleton
8
- * fields: [ redirectsField ]
9
- *
10
- * In the page: <SEOHead {...seoProps(page.seo, { title: page.title, description: page.summary })} />
11
- * In config: sinnSeo({ redirects: redirectMapFromCms(settings.redirects) })
12
- */
13
- import { RedirectMap, type RedirectStatus } from './lib/redirects';
14
-
15
- type Field = Record<string, unknown>;
16
-
17
- export const seoField: Field = {
18
- type: 'object',
19
- name: 'seo',
20
- label: 'Search & sharing',
21
- fields: [
22
- { type: 'string', name: 'title', label: 'Search title', description: 'Shown in search results and browser tabs. About 50–60 characters. Leave empty to use the page title.' },
23
- { type: 'string', name: 'description', label: 'Search description', description: 'One or two sentences, about 120–160 characters.', ui: { component: 'textarea' } },
24
- { type: 'image', name: 'image', label: 'Share image', description: 'Shown when the page is shared. At least 1200×630.' },
25
- { type: 'string', name: 'imageAlt', label: 'Share image description' },
26
- { type: 'boolean', name: 'noindex', label: 'Hide from search engines', description: 'Also removes the page from the sitemap.' },
27
- { type: 'string', name: 'canonical', label: 'Canonical URL (advanced)', description: 'Only if this page duplicates another one. Full URL.' },
28
- ],
29
- };
30
-
31
- export const redirectsField: Field = {
32
- type: 'object',
33
- name: 'redirects',
34
- label: 'Redirects',
35
- list: true,
36
- ui: { itemProps: (item: { from?: string; to?: string }) => ({ label: item?.from ? `${item.from} → ${item.to ?? ''}` : 'Redirect' }) },
37
- fields: [
38
- { type: 'string', name: 'from', label: 'Old address', required: true, description: 'A path like /old-page (a full old URL works too).' },
39
- { type: 'string', name: 'to', label: 'New address', required: true, description: 'A path on this site or a full URL.' },
40
- {
41
- type: 'string',
42
- name: 'status',
43
- label: 'Type',
44
- options: [
45
- { value: '301', label: 'Permanent (301)' },
46
- { value: '302', label: 'Temporary (302)' },
47
- ],
48
- },
49
- ],
50
- };
51
-
52
- export interface CmsSeo {
53
- title?: string | null;
54
- description?: string | null;
55
- image?: string | null;
56
- imageAlt?: string | null;
57
- noindex?: boolean | null;
58
- canonical?: string | null;
59
- }
60
-
61
- /** SEOHead props from a page's `seo` object, falling back to page-level values. */
62
- export function seoProps(seo: CmsSeo | null | undefined, fallback: { title?: string; description?: string; image?: { src: string; alt: string; width?: number; height?: number } } = {}) {
63
- const s = seo ?? {};
64
- const t = (v?: string | null) => (v && v.trim() ? v.trim() : undefined);
65
- return {
66
- title: t(s.title) ?? fallback.title,
67
- description: t(s.description) ?? fallback.description,
68
- image: t(s.image) ? { src: t(s.image)!, alt: t(s.imageAlt) ?? '' } : fallback.image,
69
- noindex: Boolean(s.noindex),
70
- canonical: t(s.canonical),
71
- };
72
- }
73
-
74
- /** A RedirectMap from the CMS list (empty rows skipped). Check `.errors` before using it. */
75
- export function redirectMapFromCms(rows: Array<{ from?: string | null; to?: string | null; status?: string | null }> | null | undefined, options?: ConstructorParameters<typeof RedirectMap>[1]) {
76
- return new RedirectMap(
77
- (rows ?? []).filter((r) => r?.from?.trim() && r?.to?.trim()).map((r) => ({ from: r.from!, to: r.to!, status: r.status ? (Number(r.status) as RedirectStatus) : undefined })),
78
- options,
79
- );
80
- }
1
+ /**
2
+ * SEO from CMS content: a per-page `seo` object and a site-wide redirect list.
3
+ *
4
+ * In the page: <SEOHead {...seoProps(page.seo, { title: page.title, description: page.summary })} />
5
+ * In config: sinnSeo({ redirects: redirectMapFromCms(settings.redirects) })
6
+ */
7
+ import type { ImageMetadata } from 'astro';
8
+ import { RedirectMap, type RedirectStatus } from './lib/redirects';
9
+ import type { ImageResolver } from '../blocks/cms/types';
10
+
11
+ export interface CmsSeo {
12
+ title?: string | null;
13
+ description?: string | null;
14
+ image?: string | null;
15
+ imageAlt?: string | null;
16
+ noindex?: boolean | null;
17
+ canonical?: string | null;
18
+ }
19
+
20
+ type ShareImage = { src: ImageMetadata | string; alt: string; width?: number; height?: number };
21
+
22
+ /**
23
+ * SEOHead props from a page's `seo` object, falling back to page-level values.
24
+ *
25
+ * CMS image pickers store a path such as `/src/assets/share.jpg`, which isn't a public URL. Pass the
26
+ * same `resolveImage` you give BlockRenderer and SEOHead gets the asset (cropped to 1200×630); paths
27
+ * it can't resolve are left out with a dev warning. Without a resolver the value is used as a URL.
28
+ */
29
+ export function seoProps(
30
+ seo: CmsSeo | null | undefined,
31
+ fallback: { title?: string; description?: string; image?: ShareImage } = {},
32
+ options: { resolveImage?: ImageResolver } = {},
33
+ ) {
34
+ const s = seo ?? {};
35
+ const t = (v?: string | null) => (v && v.trim() ? v.trim() : undefined);
36
+ const path = t(s.image);
37
+ let image: ShareImage | undefined = fallback.image;
38
+ if (path && !options.resolveImage) image = { src: path, alt: t(s.imageAlt) ?? '' };
39
+ else if (path && options.resolveImage) {
40
+ const resolved = options.resolveImage(path);
41
+ if (resolved) image = 'format' in resolved ? { src: resolved, alt: t(s.imageAlt) ?? '' } : { ...resolved, alt: t(s.imageAlt) ?? '' };
42
+ else if (import.meta.env?.DEV) console.warn(`[seo] Share image "${path}" couldn't be resolved; using the fallback.`);
43
+ }
44
+ return {
45
+ title: t(s.title) ?? fallback.title,
46
+ description: t(s.description) ?? fallback.description,
47
+ image,
48
+ noindex: Boolean(s.noindex),
49
+ canonical: t(s.canonical),
50
+ };
51
+ }
52
+
53
+ /** A RedirectMap from the CMS list (empty rows skipped). Check `.errors` before using it. */
54
+ export function redirectMapFromCms(rows: Array<{ from?: string | null; to?: string | null; status?: string | null }> | null | undefined, options?: ConstructorParameters<typeof RedirectMap>[1]) {
55
+ return new RedirectMap(
56
+ (rows ?? []).filter((r) => r?.from?.trim() && r?.to?.trim()).map((r) => ({ from: r.from!, to: r.to!, status: r.status ? (Number(r.status) as RedirectStatus) : undefined })),
57
+ options,
58
+ );
59
+ }
package/src/seo/index.ts CHANGED
@@ -7,4 +7,4 @@ export { RedirectMap, createRedirectMiddleware, type RedirectRule, type Redirect
7
7
  export { buildSitemap, buildSitemapIndex, sitemapEndpoint, type SitemapEntry } from './lib/sitemap';
8
8
  export { buildRss, rssEndpoint, type RssFeed, type RssItem } from './lib/rss';
9
9
  export { buildRobotsTxt } from './lib/robots';
10
- export { canonicalize } from './lib/url';
10
+ export { canonicalize } from './internal/url';
@@ -14,13 +14,14 @@
14
14
  * On-demand (SSR) pages aren't files: add them with `extraEntries` or a `sitemapEndpoint` route
15
15
  * listed in `extraSitemaps`.
16
16
  */
17
+ import { existsSync } from 'node:fs';
17
18
  import { readFile, readdir, writeFile, access } from 'node:fs/promises';
18
19
  import { join, relative, sep } from 'node:path';
19
20
  import { fileURLToPath } from 'node:url';
20
21
  import { buildSitemap, buildSitemapIndex, chunkEntries, type SitemapEntry } from './lib/sitemap';
21
22
  import { buildRobotsTxt, type RobotsRule } from './lib/robots';
22
23
  import { RedirectMap, type RedirectRule } from './lib/redirects';
23
- import { applyTrailingSlash, canonicalize, type TrailingSlash } from './lib/url';
24
+ import { applyTrailingSlash, canonicalize, type TrailingSlash } from './internal/url';
24
25
 
25
26
  export interface SinnSeoOptions {
26
27
  sitemap?:
@@ -189,6 +190,36 @@ export async function writeSitemaps(args: {
189
190
  return report;
190
191
  }
191
192
 
193
+ const PAGE_EXTENSIONS = ['.astro', '.md', '.mdx', '.markdown', '.mdoc', '.html', '.ts', '.js'];
194
+
195
+ /**
196
+ * Splits `redirects.toAstro()` into what Astro can build and what it can't. Astro prerenders a
197
+ * redirect with params (`/news/[slug]`) by calling the getStaticPaths of the page at exactly the
198
+ * destination route (`src/pages/blog/[slug].astro`); without that page the build fails. Only
199
+ * `output: 'server'` redirects at request time instead. The rules left out still work from the
200
+ * host's redirect file (`toRedirectsFile()`, `toVercel()`) or `createRedirectMiddleware`.
201
+ */
202
+ export function astroRedirects(
203
+ map: RedirectMap,
204
+ { output, pagesDir }: { output?: string; pagesDir: string },
205
+ ): { redirects: ReturnType<RedirectMap['toAstro']>; skipped: Array<{ from: string; to: string }> } {
206
+ const redirects = map.toAstro();
207
+ const skipped: Array<{ from: string; to: string }> = [];
208
+ if (output === 'server') return { redirects, skipped };
209
+ const hasPage = (route: string) => {
210
+ if (!route.startsWith('/') || /[?#]/.test(route)) return false;
211
+ const rel = route.slice(1);
212
+ return PAGE_EXTENSIONS.some((ext) => existsSync(join(pagesDir, rel + ext)) || existsSync(join(pagesDir, rel, `index${ext}`)));
213
+ };
214
+ for (const [from, rule] of Object.entries(redirects)) {
215
+ const to = typeof rule === 'string' ? rule : rule.destination;
216
+ if (!from.includes('[') || hasPage(to)) continue;
217
+ delete redirects[from];
218
+ skipped.push({ from, to });
219
+ }
220
+ return { redirects, skipped };
221
+ }
222
+
192
223
  export default function sinnSeo(options: SinnSeoOptions = {}) {
193
224
  let site: string | undefined;
194
225
  let base = '/';
@@ -203,8 +234,14 @@ export default function sinnSeo(options: SinnSeoOptions = {}) {
203
234
  redirects = options.redirects instanceof RedirectMap ? options.redirects : new RedirectMap(options.redirects);
204
235
  for (const w of redirects.warnings) logger.warn(w);
205
236
  redirects.assertValid();
206
- updateConfig({ redirects: { ...redirects.toAstro(), ...(config.redirects ?? {}) } });
207
- logger.info(`${redirects.rules.length} redirects added.`);
237
+ const built = astroRedirects(redirects, { output: config.output, pagesDir: fileURLToPath(new URL('pages/', config.srcDir)) });
238
+ for (const { from, to } of built.skipped) {
239
+ logger.warn(
240
+ `Redirect "${from}" → "${to}" left out of Astro's redirects: a static build makes one redirect page per path from the getStaticPaths of a "${to}" page, and there isn't one. Add that page, or serve this redirect from your host (redirects.toRedirectsFile() or toVercel()).`,
241
+ );
242
+ }
243
+ updateConfig({ redirects: { ...built.redirects, ...(config.redirects ?? {}) } });
244
+ logger.info(`${redirects.rules.length - built.skipped.length} redirects added.`);
208
245
  }
209
246
  // SEOHead reads the trailing-slash policy from here, so canonicals match your routes.
210
247
  updateConfig({ vite: { define: { 'import.meta.env.SINN_TRAILING_SLASH': JSON.stringify(config.trailingSlash ?? 'ignore') } } });
@@ -3,7 +3,7 @@
3
3
  * links them by @id, safe serialization for <script type="application/ld+json">, and checks
4
4
  * against Google's rich-result requirements (warnings, not errors).
5
5
  */
6
- import { absolute, isoDate } from './url';
6
+ import { absolute, isoDate } from '../internal/url';
7
7
 
8
8
  export type Thing = { '@type': string | string[]; '@id'?: string; [key: string]: unknown };
9
9
  export type Ref = { '@id': string };
@@ -226,10 +226,18 @@ export function person(p: { name: string; url?: string; image?: string; jobTitle
226
226
  }
227
227
 
228
228
  /** A service the business offers ("Website design"). Use MedicalTherapy/MedicalProcedure only when accurate. */
229
+ function serviceId(url: string): string {
230
+ const [base, fragment] = url.split('#', 2);
231
+ const slug = fragment?.trim().replace(/[^A-Za-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '');
232
+ return slug ? `${base}#service-${slug}` : `${base}#service`;
233
+ }
234
+
229
235
  export function service(s: { name: string; url: string; description?: string; provider?: string; areaServed?: string[]; serviceType?: string; type?: string }): Thing {
230
236
  return clean({
231
237
  '@type': s.type ?? 'Service',
232
- '@id': `${s.url.replace(/#.*$/, '')}#service`,
238
+ // Several services on one page (`/services/#brakes`, `/services/#cooling`) each keep their own
239
+ // @id (`/services/#service-brakes`); a shared one would merge them into a single node.
240
+ '@id': serviceId(s.url),
233
241
  name: s.name,
234
242
  url: s.url,
235
243
  description: s.description,
@@ -2,7 +2,7 @@
2
2
  * Builds every <head> tag SEOHead renders, as data, plus warnings about likely SEO mistakes.
3
3
  * Pure: SEOHead calls it with Astro.url / Astro.site; tests call it directly.
4
4
  */
5
- import { absolute, canonicalize, escapeXml, isAbsolute, isoDate, type TrailingSlash } from './url';
5
+ import { absolute, canonicalize, escapeXml, isAbsolute, isoDate, type TrailingSlash } from '../internal/url';
6
6
 
7
7
  export interface SeoImage {
8
8
  /** Absolute URL or a path on the site. */
@@ -74,7 +74,7 @@ function applyTemplate(title: string | undefined, input: SeoInput): string {
74
74
  const tpl = input.titleTemplate;
75
75
  if (!tpl || !tpl.includes('%s')) return t;
76
76
  if (input.siteName && t.toLowerCase().includes(input.siteName.toLowerCase())) return t;
77
- return tpl.replace('%s', t);
77
+ return tpl.replace('%s', () => t); // a function, so "$&" in a title stays literal
78
78
  }
79
79
 
80
80
  export function buildHead(input: SeoInput): HeadResult {
@@ -99,9 +99,16 @@ export class RedirectMap {
99
99
  continue;
100
100
  }
101
101
  if (raw.from.includes('?')) this.warnings.push(`"${raw.from}": query strings can't be matched; the rule matches the path only.`);
102
- const from = normalizePath(raw.from, ci);
103
- const [toPathRaw, toQuery] = raw.to.trim().split(/\?(.*)/s);
104
- const to = isExternal(raw.to) ? raw.to.trim() : normalizePath(toPathRaw, false) + (toQuery ? `?${toQuery}` : '');
102
+ let from: string;
103
+ let to: string;
104
+ try {
105
+ from = normalizePath(raw.from, ci);
106
+ const [toPathRaw, toQuery] = raw.to.trim().split(/\?(.*)/s);
107
+ to = isExternal(raw.to) ? (new URL(raw.to.trim()), raw.to.trim()) : normalizePath(toPathRaw, false) + (toQuery ? `?${toQuery}` : '');
108
+ } catch {
109
+ this.errors.push(`"${raw.from}" → "${raw.to}": not a valid URL.`);
110
+ continue;
111
+ }
105
112
  const status = (raw.status ?? 301) as RedirectStatus;
106
113
  if (![301, 302, 303, 307, 308].includes(status)) {
107
114
  this.errors.push(`"${raw.from}": status ${raw.status} isn't a redirect status.`);
@@ -183,7 +190,10 @@ export class RedirectMap {
183
190
  if (!m) continue;
184
191
  let to = d.to;
185
192
  d.params.forEach((name, i) => {
186
- to = to.replace(new RegExp(`\\[(?:\\.\\.\\.)?${name}\\]`, 'g'), (m[i + 1] ?? '').replace(/^\//, ''));
193
+ // Re-encode the (decoded) value: a `\` would make `/\evil.com`, which browsers follow
194
+ // as `//evil.com` (another host). Escapes decodeURI kept (%3F, %2F…) stay as they are.
195
+ const value = encodeURI((m[i + 1] ?? '').replace(/^\//, '')).replace(/%25([0-9A-Fa-f]{2})/g, '%$1');
196
+ to = to.replace(new RegExp(`\\[(?:\\.\\.\\.)?${name}\\]`, 'g'), () => value);
187
197
  });
188
198
  hit = { to: to.replace(/\/{2,}/g, '/').replace(/(.)\/$/, '$1'), status: d.status };
189
199
  break;
@@ -10,7 +10,7 @@
10
10
  * }));
11
11
  * Advertise it with SEOHead `feeds={[{ title: 'Blog', href: '/blog/rss.xml' }]}`.
12
12
  */
13
- import { absolute, escapeXml, stripInvalidXml } from './url';
13
+ import { absolute, escapeXml, stripInvalidXml } from '../internal/url';
14
14
 
15
15
  export interface RssItem {
16
16
  title: string;
@@ -3,7 +3,7 @@
3
3
  * The `sinnSeo` integration builds them from your built pages; use these functions directly for
4
4
  * on-demand routes (`sitemapEndpoint`).
5
5
  */
6
- import { escapeXml, isAbsolute, isoDate, stripInvalidXml } from './url';
6
+ import { escapeXml, isAbsolute, isoDate, stripInvalidXml } from '../internal/url';
7
7
 
8
8
  export interface SitemapEntry {
9
9
  loc: string;
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Ready-made SinnStackCMS fields for SEO, checked against the stored shapes in `./cms`:
3
+ *
4
+ * import { seoSchema, redirectsSchema } from '@sinnstack/ui/seo/schema';
5
+ * pages: fields: { title, seo: seoSchema, blocks } → seoProps(page.seo, { title })
6
+ * settings: fields: { redirects: redirectsSchema } → redirectMapFromCms(settings.redirects)
7
+ */
8
+ import { objectSchema, type FieldFor, type ObjectField, type ListField } from '../blocks/cms/schema-dsl';
9
+ import type { CmsSeo } from './cms';
10
+
11
+ /** A page's `seo` object. */
12
+ export const seoSchema: ObjectField = objectSchema<CmsSeo>({
13
+ label: 'Search and sharing',
14
+ fields: {
15
+ title: { type: 'text', label: 'Title in search results', max: 70, help: 'Leave empty to use the page title.' },
16
+ description: { type: 'textarea', label: 'Description in search results', max: 160, rows: 3 },
17
+ image: { type: 'image', label: 'Sharing image', help: 'Shown when the page is shared. 1200 × 630 works everywhere.' },
18
+ imageAlt: { type: 'text', label: 'Sharing image description' },
19
+ noindex: { type: 'boolean', label: 'Hide from search engines' },
20
+ canonical: { type: 'link', label: 'Canonical URL', help: 'Only when this page copies another one. Leave empty otherwise.' },
21
+ },
22
+ });
23
+
24
+ type RedirectRow = { from?: string | null; to?: string | null; status?: '301' | '302' | '303' | '307' | '308' | null };
25
+
26
+ /** The site's `redirects` list. */
27
+ export const redirectsSchema: ListField = {
28
+ type: 'list',
29
+ label: 'Redirects',
30
+ itemLabel: 'from',
31
+ of: {
32
+ type: 'object',
33
+ fields: {
34
+ from: { type: 'text', label: 'Old path', required: true, placeholder: '/old-page', pattern: '/.*', patternMessage: 'Start with /.' },
35
+ to: { type: 'link', label: 'New path or URL', required: true },
36
+ status: {
37
+ type: 'select',
38
+ label: 'Type',
39
+ options: [{ value: '301', label: 'Permanent (301)' }, { value: '302', label: 'Temporary (302)' }, { value: '307', label: 'Temporary, keep method (307)' }, { value: '308', label: 'Permanent, keep method (308)' }],
40
+ },
41
+ },
42
+ },
43
+ } satisfies FieldFor<RedirectRow[]>;
@@ -1,19 +0,0 @@
1
- /**
2
- * @internal Builds `data-tina-field` values for click-to-edit, without depending on tinacms.
3
- * Mirrors tinacms's `tinaField(object, property, index)`: `${queryId}---${path.join('.')}`.
4
- * Returns undefined (attribute omitted) when the data didn't come from a Tina query.
5
- */
6
- import type { TinaSource } from '../types';
7
-
8
- export function tinaField(source: TinaSource | undefined, property?: string, index?: number): string | undefined {
9
- const cs = source?._content_source;
10
- if (!cs || !cs.queryId || !Array.isArray(cs.path)) return undefined;
11
- const path = property === undefined ? cs.path : typeof index === 'number' ? [...cs.path, property, index] : [...cs.path, property];
12
- return `${cs.queryId}---${path.join('.')}`;
13
- }
14
-
15
- /** Spread helper: {...tf(src, 'heading')} → { 'data-tina-field': '…' } or {}. */
16
- export function tf(source: TinaSource | undefined, property?: string, index?: number): Record<string, string> {
17
- const value = tinaField(source, property, index);
18
- return value ? { 'data-tina-field': value } : {};
19
- }
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes