@sinnstack/ui 0.0.0-stage → 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 (306) hide show
  1. package/CHANGELOG.md +89 -0
  2. package/LICENSE +373 -0
  3. package/README.md +188 -2
  4. package/docs/blocks.md +373 -0
  5. package/docs/data.md +128 -0
  6. package/docs/finishes.md +165 -0
  7. package/docs/motion.md +166 -0
  8. package/docs/primitives.md +510 -0
  9. package/docs/seo.md +191 -0
  10. package/docs/tokens.md +122 -0
  11. package/package.json +132 -3
  12. package/scripts/check-contrast.mjs +180 -0
  13. package/src/blocks/BlockRenderer.astro +60 -0
  14. package/src/blocks/CTABanner.astro +121 -0
  15. package/src/blocks/CTAPair.astro +110 -0
  16. package/src/blocks/CardGrid.astro +167 -0
  17. package/src/blocks/ConsentEmbed.astro +125 -0
  18. package/src/blocks/ConsentManager.astro +147 -0
  19. package/src/blocks/ConsentScript.astro +47 -0
  20. package/src/blocks/ContactCard.astro +164 -0
  21. package/src/blocks/ContactForm.astro +224 -0
  22. package/src/blocks/ErrorPage.astro +242 -0
  23. package/src/blocks/FAQ.astro +135 -0
  24. package/src/blocks/FeatureGrid.astro +148 -0
  25. package/src/blocks/Hero.astro +171 -0
  26. package/src/blocks/HeroCarousel.astro +220 -0
  27. package/src/blocks/HighlightCards.astro +107 -0
  28. package/src/blocks/LocationHours.astro +311 -0
  29. package/src/blocks/LogoCloud.astro +135 -0
  30. package/src/blocks/MaintenancePage.astro +173 -0
  31. package/src/blocks/MediaText.astro +177 -0
  32. package/src/blocks/PageHeader.astro +126 -0
  33. package/src/blocks/ProseSection.astro +98 -0
  34. package/src/blocks/Reviews.astro +194 -0
  35. package/src/blocks/RichText.astro +58 -0
  36. package/src/blocks/StatsBand.astro +117 -0
  37. package/src/blocks/Steps.astro +141 -0
  38. package/src/blocks/Testimonials.astro +144 -0
  39. package/src/blocks/Topbar.astro +158 -0
  40. package/src/blocks/cms/card-grid.ts +48 -0
  41. package/src/blocks/cms/consent.ts +16 -0
  42. package/src/blocks/cms/contact-card.ts +46 -0
  43. package/src/blocks/cms/contact-form.ts +37 -0
  44. package/src/blocks/cms/cta-banner.ts +27 -0
  45. package/src/blocks/cms/cta-pair.ts +30 -0
  46. package/src/blocks/cms/data-base.ts +5 -0
  47. package/src/blocks/cms/data.ts +257 -0
  48. package/src/blocks/cms/faq.ts +38 -0
  49. package/src/blocks/cms/feature-grid.ts +47 -0
  50. package/src/blocks/cms/fixtures.ts +591 -0
  51. package/src/blocks/cms/hero-carousel.ts +36 -0
  52. package/src/blocks/cms/hero.ts +33 -0
  53. package/src/blocks/cms/highlight-cards.ts +41 -0
  54. package/src/blocks/cms/images.ts +37 -0
  55. package/src/blocks/cms/index.ts +59 -0
  56. package/src/blocks/cms/location-hours.ts +67 -0
  57. package/src/blocks/cms/logo-cloud.ts +36 -0
  58. package/src/blocks/cms/media-text.ts +26 -0
  59. package/src/blocks/cms/page-header.ts +27 -0
  60. package/src/blocks/cms/pages.ts +35 -0
  61. package/src/blocks/cms/prose-section.ts +25 -0
  62. package/src/blocks/cms/reviews.ts +50 -0
  63. package/src/blocks/cms/schema-dsl.ts +134 -0
  64. package/src/blocks/cms/schema.ts +794 -0
  65. package/src/blocks/cms/shared.ts +63 -0
  66. package/src/blocks/cms/stats-band.ts +35 -0
  67. package/src/blocks/cms/steps.ts +40 -0
  68. package/src/blocks/cms/testimonials.ts +46 -0
  69. package/src/blocks/cms/topbar.ts +27 -0
  70. package/src/blocks/cms/types.ts +27 -0
  71. package/src/blocks/consent.ts +14 -0
  72. package/src/blocks/icons.ts +47 -0
  73. package/src/blocks/index.ts +42 -0
  74. package/src/blocks/internal/Actions.astro +35 -0
  75. package/src/blocks/internal/BlockHeader.astro +45 -0
  76. package/src/blocks/internal/BlockShell.astro +58 -0
  77. package/src/blocks/internal/CarouselScript.astro +7 -0
  78. package/src/blocks/internal/ConsentEmbedScript.astro +7 -0
  79. package/src/blocks/internal/ConsentManagerScript.astro +7 -0
  80. package/src/blocks/internal/HoursScript.astro +7 -0
  81. package/src/blocks/internal/Placeholder.astro +13 -0
  82. package/src/blocks/internal/RichTextNode.astro +133 -0
  83. package/src/blocks/internal/StandaloneDocument.astro +53 -0
  84. package/src/blocks/internal/consent.ts +96 -0
  85. package/src/blocks/internal/fields.ts +18 -0
  86. package/src/blocks/internal/registry-contract.ts +67 -0
  87. package/src/blocks/internal/reviews.ts +22 -0
  88. package/src/blocks/internal/slug.ts +12 -0
  89. package/src/blocks/internal/util.ts +23 -0
  90. package/src/blocks/lib/contact.ts +92 -0
  91. package/src/blocks/lib/error-pages.ts +119 -0
  92. package/src/blocks/lib/faq.ts +37 -0
  93. package/src/blocks/lib/hours.ts +201 -0
  94. package/src/blocks/lib/maintenance.ts +129 -0
  95. package/src/blocks/lib/markdown.ts +350 -0
  96. package/src/blocks/lib/rich-text.ts +132 -0
  97. package/src/blocks/registry.ts +79 -0
  98. package/src/blocks/scripts/carousel.ts +218 -0
  99. package/src/blocks/scripts/consent-embed.ts +105 -0
  100. package/src/blocks/scripts/consent-manager.ts +112 -0
  101. package/src/blocks/scripts/consent-store.ts +86 -0
  102. package/src/blocks/scripts/error-page.ts +71 -0
  103. package/src/blocks/scripts/hours.ts +107 -0
  104. package/src/blocks/scripts/maintenance.ts +109 -0
  105. package/src/blocks/styles/blocks.css +1320 -0
  106. package/src/blocks/styles/consent.css +102 -0
  107. package/src/blocks/styles/faq.css +28 -0
  108. package/src/blocks/styles/location.css +92 -0
  109. package/src/blocks/styles/prose-section.css +13 -0
  110. package/src/blocks/styles/quotes.css +123 -0
  111. package/src/blocks/styles/rich-text.css +14 -0
  112. package/src/blocks/types.ts +293 -0
  113. package/src/data/ChartAxis.astro +19 -0
  114. package/src/data/ChartContainer.astro +152 -0
  115. package/src/data/ChartLegend.astro +25 -0
  116. package/src/data/ChartSeries.astro +14 -0
  117. package/src/data/ChartTable.astro +17 -0
  118. package/src/data/ChartTooltip.astro +20 -0
  119. package/src/data/Sparkline.astro +55 -0
  120. package/src/data/cms.ts +130 -0
  121. package/src/data/index.ts +10 -0
  122. package/src/data/internal/scale.ts +107 -0
  123. package/src/data/lib/chart.ts +459 -0
  124. package/src/data/lib/render.ts +219 -0
  125. package/src/data/lib/sparkline.ts +117 -0
  126. package/src/data/schema.ts +65 -0
  127. package/src/data/scripts/chart.ts +324 -0
  128. package/src/data/styles/chart.css +392 -0
  129. package/src/finishes/aurora.css +75 -0
  130. package/src/finishes/autumn.css +87 -0
  131. package/src/finishes/blueprint.css +69 -0
  132. package/src/finishes/brutalist.css +55 -0
  133. package/src/finishes/clay.css +48 -0
  134. package/src/finishes/day-cycle.css +46 -0
  135. package/src/finishes/fog.css +71 -0
  136. package/src/finishes/glass.css +149 -0
  137. package/src/finishes/holographic.css +91 -0
  138. package/src/finishes/night.css +77 -0
  139. package/src/finishes/paper.css +58 -0
  140. package/src/finishes/polished-glass.css +159 -0
  141. package/src/finishes/rain.css +84 -0
  142. package/src/finishes/scripts/day-cycle.ts +30 -0
  143. package/src/finishes/scripts/holographic.ts +37 -0
  144. package/src/finishes/scripts/spotlight.ts +30 -0
  145. package/src/finishes/spotlight.css +41 -0
  146. package/src/finishes/spring.css +80 -0
  147. package/src/finishes/terminal.css +49 -0
  148. package/src/motion/Marquee.astro +90 -0
  149. package/src/motion/MotionProvider.astro +50 -0
  150. package/src/motion/PageTransitions.astro +61 -0
  151. package/src/motion/Parallax.astro +44 -0
  152. package/src/motion/ParallaxLayer.astro +31 -0
  153. package/src/motion/RevealOnScroll.astro +59 -0
  154. package/src/motion/SceneRegistry.astro +38 -0
  155. package/src/motion/ScrollScene.astro +81 -0
  156. package/src/motion/index.ts +12 -0
  157. package/src/motion/integration.ts +48 -0
  158. package/src/motion/runtime/page-transitions.ts +68 -0
  159. package/src/motion/runtime/runtime.ts +180 -0
  160. package/src/motion/runtime/scenes.ts +248 -0
  161. package/src/motion/runtime/types.ts +103 -0
  162. package/src/motion/styles/motion.css +332 -0
  163. package/src/motion/transitions.ts +74 -0
  164. package/src/motion/virtual.d.ts +4 -0
  165. package/src/primitives/Accordion.astro +129 -0
  166. package/src/primitives/Breadcrumbs.astro +50 -0
  167. package/src/primitives/BulletList.astro +69 -0
  168. package/src/primitives/Button.astro +73 -0
  169. package/src/primitives/ButtonGroup.astro +54 -0
  170. package/src/primitives/Callout.astro +137 -0
  171. package/src/primitives/Caption.astro +35 -0
  172. package/src/primitives/Card.astro +72 -0
  173. package/src/primitives/CardContent.astro +24 -0
  174. package/src/primitives/CardFooter.astro +36 -0
  175. package/src/primitives/CardHeader.astro +86 -0
  176. package/src/primitives/Checkbox.astro +38 -0
  177. package/src/primitives/ChoiceGroup.astro +23 -0
  178. package/src/primitives/Cluster.astro +49 -0
  179. package/src/primitives/Container.astro +44 -0
  180. package/src/primitives/DescriptionList.astro +83 -0
  181. package/src/primitives/Dialog.astro +38 -0
  182. package/src/primitives/Disclosure.astro +67 -0
  183. package/src/primitives/Divider.astro +93 -0
  184. package/src/primitives/Drawer.astro +33 -0
  185. package/src/primitives/Fieldset.astro +80 -0
  186. package/src/primitives/Flex.astro +64 -0
  187. package/src/primitives/FocusRing.astro +63 -0
  188. package/src/primitives/FocusTrap.astro +64 -0
  189. package/src/primitives/Footer.astro +155 -0
  190. package/src/primitives/Form.astro +68 -0
  191. package/src/primitives/FormDescription.astro +26 -0
  192. package/src/primitives/FormError.astro +106 -0
  193. package/src/primitives/FormField.astro +72 -0
  194. package/src/primitives/Grid.astro +64 -0
  195. package/src/primitives/Heading.astro +45 -0
  196. package/src/primitives/IconButton.astro +48 -0
  197. package/src/primitives/Image.astro +125 -0
  198. package/src/primitives/Input.astro +86 -0
  199. package/src/primitives/Label.astro +50 -0
  200. package/src/primitives/Link.astro +81 -0
  201. package/src/primitives/LinkButton.astro +66 -0
  202. package/src/primitives/List.astro +39 -0
  203. package/src/primitives/ListItem.astro +178 -0
  204. package/src/primitives/MediaObject.astro +66 -0
  205. package/src/primitives/MetricCard.astro +278 -0
  206. package/src/primitives/NavLink.astro +81 -0
  207. package/src/primitives/NavMenu.astro +109 -0
  208. package/src/primitives/Navbar.astro +197 -0
  209. package/src/primitives/Panel.astro +153 -0
  210. package/src/primitives/Picture.astro +167 -0
  211. package/src/primitives/Popover.astro +95 -0
  212. package/src/primitives/Prose.astro +45 -0
  213. package/src/primitives/Radio.astro +21 -0
  214. package/src/primitives/Rating.astro +135 -0
  215. package/src/primitives/ReducedMotion.astro +90 -0
  216. package/src/primitives/SegmentedControl.astro +132 -0
  217. package/src/primitives/Select.astro +109 -0
  218. package/src/primitives/Sheet.astro +45 -0
  219. package/src/primitives/SkipLink.astro +31 -0
  220. package/src/primitives/Slider.astro +186 -0
  221. package/src/primitives/Spacer.astro +35 -0
  222. package/src/primitives/Stack.astro +51 -0
  223. package/src/primitives/Surface.astro +70 -0
  224. package/src/primitives/Switch.astro +22 -0
  225. package/src/primitives/Table.astro +382 -0
  226. package/src/primitives/Tabs.astro +126 -0
  227. package/src/primitives/Text.astro +56 -0
  228. package/src/primitives/Textarea.astro +75 -0
  229. package/src/primitives/Thumbnail.astro +154 -0
  230. package/src/primitives/Toggle.astro +99 -0
  231. package/src/primitives/Tooltip.astro +50 -0
  232. package/src/primitives/VisuallyHidden.astro +29 -0
  233. package/src/primitives/index.ts +103 -0
  234. package/src/primitives/internal/AccordionScript.astro +7 -0
  235. package/src/primitives/internal/ChoiceField.astro +91 -0
  236. package/src/primitives/internal/FocusTrapScript.astro +8 -0
  237. package/src/primitives/internal/FormValidationScript.astro +10 -0
  238. package/src/primitives/internal/IndeterminateScript.astro +13 -0
  239. package/src/primitives/internal/ModalPanel.astro +114 -0
  240. package/src/primitives/internal/OverlayScript.astro +7 -0
  241. package/src/primitives/internal/ReducedMotionScript.astro +7 -0
  242. package/src/primitives/internal/SliderScript.astro +7 -0
  243. package/src/primitives/internal/SparklineScript.astro +7 -0
  244. package/src/primitives/internal/TableSortScript.astro +7 -0
  245. package/src/primitives/internal/TabsScript.astro +7 -0
  246. package/src/primitives/internal/TooltipScript.astro +7 -0
  247. package/src/primitives/internal/image-plan.ts +82 -0
  248. package/src/primitives/internal/image.ts +129 -0
  249. package/src/primitives/internal/slider.ts +170 -0
  250. package/src/primitives/lib/deprecate.ts +47 -0
  251. package/src/primitives/lib/focus-trap.ts +197 -0
  252. package/src/primitives/lib/focus.ts +60 -0
  253. package/src/primitives/lib/motion.ts +68 -0
  254. package/src/primitives/scripts/accordion.ts +123 -0
  255. package/src/primitives/scripts/form-validation.ts +225 -0
  256. package/src/primitives/scripts/overlay.ts +71 -0
  257. package/src/primitives/scripts/reduced-motion.ts +59 -0
  258. package/src/primitives/scripts/slider.ts +150 -0
  259. package/src/primitives/scripts/sparkline.ts +131 -0
  260. package/src/primitives/scripts/table-sort.ts +68 -0
  261. package/src/primitives/scripts/tabs.ts +151 -0
  262. package/src/primitives/scripts/tooltip.ts +28 -0
  263. package/src/primitives/styles/a11y.css +104 -0
  264. package/src/primitives/styles/accordion.css +53 -0
  265. package/src/primitives/styles/breadcrumbs.css +59 -0
  266. package/src/primitives/styles/bullet-list.css +89 -0
  267. package/src/primitives/styles/button.css +237 -0
  268. package/src/primitives/styles/choice.css +164 -0
  269. package/src/primitives/styles/cluster.css +24 -0
  270. package/src/primitives/styles/container.css +19 -0
  271. package/src/primitives/styles/data.css +849 -0
  272. package/src/primitives/styles/disclosure.css +140 -0
  273. package/src/primitives/styles/divider.css +50 -0
  274. package/src/primitives/styles/flex.css +42 -0
  275. package/src/primitives/styles/form.css +241 -0
  276. package/src/primitives/styles/grid.css +36 -0
  277. package/src/primitives/styles/media.css +247 -0
  278. package/src/primitives/styles/nav.css +792 -0
  279. package/src/primitives/styles/overlay.css +362 -0
  280. package/src/primitives/styles/prose.css +146 -0
  281. package/src/primitives/styles/scale.css +175 -0
  282. package/src/primitives/styles/segmented.css +165 -0
  283. package/src/primitives/styles/slider.css +170 -0
  284. package/src/primitives/styles/spacer.css +17 -0
  285. package/src/primitives/styles/stack.css +25 -0
  286. package/src/primitives/styles/surface.css +403 -0
  287. package/src/primitives/styles/tabs.css +223 -0
  288. package/src/primitives/styles/typography.css +144 -0
  289. package/src/primitives/styles/utilities.css +24 -0
  290. package/src/primitives/types.ts +385 -0
  291. package/src/primitives/utils.ts +254 -0
  292. package/src/seo/JSONLD.astro +35 -0
  293. package/src/seo/SEOHead.astro +47 -0
  294. package/src/seo/cms.ts +59 -0
  295. package/src/seo/index.ts +10 -0
  296. package/src/seo/integration.ts +268 -0
  297. package/src/seo/internal/url.ts +68 -0
  298. package/src/seo/lib/jsonld.ts +342 -0
  299. package/src/seo/lib/meta.ts +205 -0
  300. package/src/seo/lib/redirects.ts +293 -0
  301. package/src/seo/lib/robots.ts +33 -0
  302. package/src/seo/lib/rss.ts +98 -0
  303. package/src/seo/lib/sitemap.ts +105 -0
  304. package/src/seo/schema.ts +43 -0
  305. package/src/tokens/base.css +71 -0
  306. package/src/tokens/tokens.css +210 -0
@@ -0,0 +1,37 @@
1
+ /** FAQ helpers: item normalization (ids, empty answers) and structured-data input. */
2
+ import type { FaqItem } from '../types';
3
+ import { slugify } from '../internal/slug';
4
+ import { isRichTextEmpty, richTextPlain } from './rich-text';
5
+
6
+ export interface NormalizedFaq extends FaqItem {
7
+ id: string;
8
+ }
9
+
10
+ /**
11
+ * Keeps questions that have an answer and gives each a unique, link-friendly id
12
+ * ("How much does it cost?" → `how-much-does-it-cost`; a repeat becomes `…-2`).
13
+ */
14
+ export function faqItems(items: FaqItem[] | null | undefined): NormalizedFaq[] {
15
+ const used = new Set<string>();
16
+ const out: NormalizedFaq[] = [];
17
+ for (const item of items ?? []) {
18
+ const question = typeof item?.question === 'string' ? item.question.trim() : '';
19
+ if (!question || isRichTextEmpty(item.answer)) continue;
20
+ const base = slugify(item.id?.trim() || question).slice(0, 64).replace(/-+$/, '') || 'question';
21
+ let id = base;
22
+ for (let n = 2; used.has(id); n++) id = `${base}-${n}`;
23
+ used.add(id);
24
+ out.push({ ...item, question, id });
25
+ }
26
+ return out;
27
+ }
28
+
29
+ /**
30
+ * Input for `faqPage()` from `@sinnstack/ui/seo/jsonld`: questions with plain-text answers.
31
+ * <JSONLD data={faqPage(faqStructuredData(items), { url })} />
32
+ */
33
+ export function faqStructuredData(items: FaqItem[] | null | undefined): Array<{ question: string; answer: string }> {
34
+ return faqItems(items)
35
+ .map((f) => ({ question: f.question, answer: richTextPlain(f.answer) }))
36
+ .filter((f) => f.answer);
37
+ }
@@ -0,0 +1,201 @@
1
+ /**
2
+ * Opening hours: grouping for display, formatting, and "open now" in the business's own time
3
+ * zone. Pure functions (no DOM), shared by LocationHours (build time) and its script (browser).
4
+ *
5
+ * Times are 24-hour "HH:MM" strings. A range whose close is at or before its open runs past
6
+ * midnight ("18:00"–"02:00"). "00:00"–"24:00" (or "00:00"–"23:59") is open all day.
7
+ */
8
+ import type { DayCode, HoursRow, PostalAddress, SpecialHours } from '../types';
9
+
10
+ export const DAY_CODES: readonly DayCode[] = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'];
11
+
12
+ export interface DayHours {
13
+ closed: boolean;
14
+ opens?: string;
15
+ closes?: string;
16
+ }
17
+
18
+ /** Minutes after midnight for "HH:MM" (24:00 allowed), or undefined when malformed. */
19
+ export function parseTime(value: string | undefined): number | undefined {
20
+ const m = /^(\d{1,2}):(\d{2})$/.exec(value?.trim() ?? '');
21
+ if (!m) return undefined;
22
+ const h = Number(m[1]);
23
+ const min = Number(m[2]);
24
+ if (min > 59 || h > 24 || (h === 24 && min > 0)) return undefined;
25
+ return h * 60 + min;
26
+ }
27
+
28
+ export function isAllDay(d: DayHours): boolean {
29
+ if (d.closed) return false;
30
+ const o = parseTime(d.opens);
31
+ const c = parseTime(d.closes);
32
+ return o === 0 && (c === 1440 || c === 1439 || c === 0);
33
+ }
34
+
35
+ /** Hours for each day Mo..Su. Days no row mentions are closed; a later row wins for a day. */
36
+ export function weekHours(rows: HoursRow[] | null | undefined): Record<DayCode, DayHours> {
37
+ const week = Object.fromEntries(DAY_CODES.map((d) => [d, { closed: true }])) as Record<DayCode, DayHours>;
38
+ for (const row of rows ?? []) {
39
+ for (const day of row?.days ?? []) {
40
+ if (!DAY_CODES.includes(day)) continue;
41
+ const valid = parseTime(row.opens) !== undefined && parseTime(row.closes) !== undefined;
42
+ week[day] = row.closed || !valid ? { closed: true } : { closed: false, opens: row.opens!.trim(), closes: row.closes!.trim() };
43
+ }
44
+ }
45
+ return week;
46
+ }
47
+
48
+ const same = (a: DayHours, b: DayHours) => a.closed === b.closed && a.opens === b.opens && a.closes === b.closes;
49
+
50
+ /** Consecutive days with the same hours, grouped: [{ days: ['Mo'..'Fr'], hours }, …]. */
51
+ export function groupWeek(week: Record<DayCode, DayHours>): Array<{ days: DayCode[]; hours: DayHours }> {
52
+ const groups: Array<{ days: DayCode[]; hours: DayHours }> = [];
53
+ for (const day of DAY_CODES) {
54
+ const last = groups[groups.length - 1];
55
+ if (last && same(last.hours, week[day])) last.days.push(day);
56
+ else groups.push({ days: [day], hours: week[day] });
57
+ }
58
+ return groups;
59
+ }
60
+
61
+ // 2024-01-01 was a Monday; used to get localized weekday names.
62
+ const dayDate = (code: DayCode) => new Date(Date.UTC(2024, 0, 1 + DAY_CODES.indexOf(code)));
63
+
64
+ export function dayName(code: DayCode, locale = 'en-US', width: 'short' | 'long' = 'short'): string {
65
+ return new Intl.DateTimeFormat(locale, { weekday: width, timeZone: 'UTC' }).format(dayDate(code));
66
+ }
67
+
68
+ /** "Mo".."Fr" → "Mon–Fri" (short) / "Monday to Friday" (long, for screen readers). */
69
+ export function dayRangeLabel(days: DayCode[], locale = 'en-US', width: 'short' | 'long' = 'short', joiner = 'to'): string {
70
+ if (days.length === 1) return dayName(days[0], locale, width);
71
+ const first = dayName(days[0], locale, width);
72
+ const last = dayName(days[days.length - 1], locale, width);
73
+ return width === 'short' ? `${first}–${last}` : `${first} ${joiner} ${last}`;
74
+ }
75
+
76
+ /** "08:00" → "8:00 AM" (en-US) / "08:00" (en-GB). */
77
+ export function formatTime(value: string, locale = 'en-US'): string {
78
+ const mins = parseTime(value);
79
+ if (mins === undefined) return value;
80
+ const m = mins % 1440;
81
+ const d = new Date(Date.UTC(2024, 0, 1, Math.floor(m / 60), m % 60));
82
+ return new Intl.DateTimeFormat(locale, { hour: 'numeric', minute: '2-digit', timeZone: 'UTC' }).format(d);
83
+ }
84
+
85
+ /** "8:00 AM – 5:00 PM", or the closed / all-day label. */
86
+ export function formatHours(d: DayHours, locale = 'en-US', labels = { closed: 'Closed', allDay: 'Open 24 hours' }): string {
87
+ if (d.closed) return labels.closed;
88
+ if (isAllDay(d)) return labels.allDay;
89
+ return `${formatTime(d.opens!, locale)} – ${formatTime(d.closes!, locale)}`;
90
+ }
91
+
92
+ /** The weekday, date and minutes-after-midnight of `now` in an IANA time zone. */
93
+ export function zonedNow(now: Date, timeZone: string): { day: DayCode; date: string; minutes: number } {
94
+ const parts = Object.fromEntries(
95
+ new Intl.DateTimeFormat('en-US', { timeZone, weekday: 'short', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hourCycle: 'h23' })
96
+ .formatToParts(now)
97
+ .map((p) => [p.type, p.value]),
98
+ );
99
+ const map: Record<string, DayCode> = { Mon: 'Mo', Tue: 'Tu', Wed: 'We', Thu: 'Th', Fri: 'Fr', Sat: 'Sa', Sun: 'Su' };
100
+ return { day: map[parts.weekday], date: `${parts.year}-${parts.month}-${parts.day}`, minutes: Number(parts.hour) * 60 + Number(parts.minute) };
101
+ }
102
+
103
+ const nextDay = (d: DayCode, n = 1) => DAY_CODES[(DAY_CODES.indexOf(d) + n) % 7];
104
+ const prevDay = (d: DayCode) => DAY_CODES[(DAY_CODES.indexOf(d) + 6) % 7];
105
+ const addDays = (iso: string, n: number) => {
106
+ const t = new Date(`${iso}T00:00:00Z`);
107
+ t.setUTCDate(t.getUTCDate() + n);
108
+ return t.toISOString().slice(0, 10);
109
+ };
110
+
111
+ /** Hours on a calendar date: a special-hours entry for that date, else the regular weekday hours. */
112
+ export function hoursOn(date: string, day: DayCode, week: Record<DayCode, DayHours>, special: SpecialHours[] = []): DayHours {
113
+ const s = special.find((x) => x?.date === date);
114
+ if (!s) return week[day];
115
+ const valid = parseTime(s.opens) !== undefined && parseTime(s.closes) !== undefined;
116
+ return s.closed || !valid ? { closed: true } : { closed: false, opens: s.opens, closes: s.closes };
117
+ }
118
+
119
+ export type OpenStatus =
120
+ | { open: true; allDay: true }
121
+ | { open: true; allDay?: false; closes: string; closesTomorrow: boolean }
122
+ | { open: false; opens?: string; opensDay?: DayCode; opensIn?: number };
123
+
124
+ /**
125
+ * Whether the business is open at `now`, and when that changes. Checks yesterday's overnight
126
+ * range, then today, then looks ahead up to a week for the next opening.
127
+ */
128
+ export function openStatus(week: Record<DayCode, DayHours>, now: Date, timeZone: string, special: SpecialHours[] = []): OpenStatus {
129
+ const { day, date, minutes } = zonedNow(now, timeZone);
130
+ const today = hoursOn(date, day, week, special);
131
+ const yDate = addDays(date, -1);
132
+ const yesterday = hoursOn(yDate, prevDay(day), week, special);
133
+
134
+ // Still inside yesterday's range that runs past midnight?
135
+ if (!yesterday.closed && !isAllDay(yesterday)) {
136
+ const o = parseTime(yesterday.opens)!;
137
+ const c = parseTime(yesterday.closes)!;
138
+ if (c <= o && minutes < c) return { open: true, closes: yesterday.closes!, closesTomorrow: false };
139
+ }
140
+ if (!today.closed) {
141
+ if (isAllDay(today)) return { open: true, allDay: true };
142
+ const o = parseTime(today.opens)!;
143
+ const c = parseTime(today.closes)!;
144
+ if (c > o && minutes >= o && minutes < c) return { open: true, closes: today.closes!, closesTomorrow: false };
145
+ if (c <= o && minutes >= o) return { open: true, closes: today.closes!, closesTomorrow: true };
146
+ if (minutes < o) return { open: false, opens: today.opens, opensDay: day, opensIn: 0 };
147
+ }
148
+ for (let n = 1; n <= 7; n++) {
149
+ const d = nextDay(day, n);
150
+ const h = hoursOn(addDays(date, n), d, week, special);
151
+ if (!h.closed) return { open: false, opens: isAllDay(h) ? '00:00' : h.opens, opensDay: d, opensIn: n };
152
+ }
153
+ return { open: false };
154
+ }
155
+
156
+ /** One line for the address, for map and directions URLs. */
157
+ export function addressLine(a: PostalAddress): string {
158
+ return [a.street, a.street2, a.city, `${a.region} ${a.postalCode}`.trim(), a.country && a.country !== 'US' ? a.country : undefined].filter(Boolean).join(', ');
159
+ }
160
+
161
+ /** Directions link (opens the visitor's maps app or Google Maps; nothing loads on your page). */
162
+ export function directionsHref(a: PostalAddress): string {
163
+ return `https://www.google.com/maps/dir/?api=1&destination=${encodeURIComponent(addressLine(a))}`;
164
+ }
165
+
166
+ /** "Open in Google Maps" for an address (a plain link: nothing loads on your page). */
167
+ export function mapSearchHref(a: PostalAddress): string {
168
+ return `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(addressLine(a))}`;
169
+ }
170
+
171
+ /** Keyless Google Maps embed for an address (load it only after consent: ConsentEmbed). */
172
+ export function mapEmbedSrc(a: PostalAddress): string {
173
+ return `https://www.google.com/maps?q=${encodeURIComponent(addressLine(a))}&output=embed`;
174
+ }
175
+
176
+ /**
177
+ * Input for `localBusiness()` from `@sinnstack/ui/seo/jsonld` (address, phone, email, hours).
178
+ * <JSONLD data={localBusiness({ ...locationStructuredData(props), name, url, type: 'ProfessionalService' })} />
179
+ */
180
+ export function locationStructuredData(p: { address: PostalAddress; phone?: string; email?: string; hours?: HoursRow[] }): {
181
+ address: { street: string; city: string; region: string; postalCode: string; country: string };
182
+ telephone?: string;
183
+ email?: string;
184
+ hours: Array<{ days: DayCode[]; opens: string; closes: string }>;
185
+ } {
186
+ const groups = groupWeek(weekHours(p.hours)).filter((g) => !g.hours.closed);
187
+ return {
188
+ address: {
189
+ street: [p.address.street, p.address.street2].filter(Boolean).join(', '),
190
+ city: p.address.city,
191
+ region: p.address.region,
192
+ postalCode: p.address.postalCode,
193
+ country: p.address.country ?? 'US',
194
+ },
195
+ ...(p.phone ? { telephone: p.phone } : {}),
196
+ ...(p.email ? { email: p.email } : {}),
197
+ hours: groups.map((g) =>
198
+ isAllDay(g.hours) ? { days: g.days, opens: '00:00', closes: '23:59' } : { days: g.days, opens: g.hours.opens!, closes: g.hours.closes! },
199
+ ),
200
+ };
201
+ }
@@ -0,0 +1,129 @@
1
+ /**
2
+ * Maintenance mode for on-demand (SSR) Astro sites: answers every page request with the
3
+ * maintenance page and a real `503 Service Unavailable` + `Retry-After`, so search engines keep
4
+ * the site indexed and treat the outage as temporary.
5
+ *
6
+ * // src/middleware.ts
7
+ * import { createMaintenanceMiddleware } from '@sinnstack/ui/blocks/maintenance';
8
+ * export const onRequest = createMaintenanceMiddleware({
9
+ * enabled: () => import.meta.env.MAINTENANCE === 'on',
10
+ * until: import.meta.env.MAINTENANCE_UNTIL, // ISO time, e.g. 2026-11-15T15:00:00-06:00
11
+ * bypassToken: import.meta.env.MAINTENANCE_BYPASS, // visit /?maintenance-bypass=<token> once
12
+ * });
13
+ *
14
+ * Static hosts: build the maintenance page and have the host serve it with status 503
15
+ * (see the README for Netlify, Cloudflare and Vercel snippets).
16
+ */
17
+
18
+ /** The parts of Astro's APIContext this needs (kept structural so it's testable). */
19
+ export interface MaintenanceContext {
20
+ request: Request;
21
+ url: URL;
22
+ cookies: {
23
+ get(name: string): { value: string } | undefined;
24
+ set(name: string, value: string, options?: Record<string, unknown>): void;
25
+ };
26
+ rewrite(path: string): Promise<Response>;
27
+ redirect(path: string, status?: 301 | 302 | 303 | 307 | 308): Response;
28
+ }
29
+ export type Next = () => Promise<Response>;
30
+
31
+ export interface MaintenanceOptions {
32
+ /** Whether maintenance mode is on. Re-evaluated per request, so a function can read live config. */
33
+ enabled: boolean | (() => boolean | Promise<boolean>);
34
+ /** Route that renders <MaintenancePage>. */
35
+ path?: string;
36
+ /** When the site should be back (ISO 8601 with offset). Sets Retry-After. */
37
+ until?: string | Date;
38
+ /** Paths that keep working: prefixes ("/api/health") or patterns. Assets are always allowed. */
39
+ allow?: Array<string | RegExp>;
40
+ /** Secret that lets the team through: visit any URL with ?maintenance-bypass=<token> once. */
41
+ bypassToken?: string;
42
+ /** Bypass cookie name and lifetime. */
43
+ bypassCookie?: string;
44
+ bypassMaxAge?: number;
45
+ }
46
+
47
+ export const MAINTENANCE_HEADER = 'x-sinn-maintenance';
48
+ const ALWAYS_ALLOWED = [/^\/_astro\//, /^\/_image/, /^\/_server-islands\//, /^\/favicon/, /^\/robots\.txt$/, /^\/apple-touch-icon/, /^\/manifest\.webmanifest$/, /^\/\.well-known\//];
49
+
50
+ /** Seconds until `until`, clamped to [60, 86400]; 3600 when unknown or past. */
51
+ export function retryAfterSeconds(until: string | Date | undefined, now: number = Date.now()): number {
52
+ const t = until ? new Date(until).getTime() : NaN;
53
+ if (!Number.isFinite(t) || t <= now) return 3600;
54
+ return Math.min(86400, Math.max(60, Math.ceil((t - now) / 1000)));
55
+ }
56
+
57
+ function safeEqual(a: string, b: string): boolean {
58
+ if (a.length !== b.length) return false;
59
+ let diff = 0;
60
+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
61
+ return diff === 0;
62
+ }
63
+
64
+ export function createMaintenanceMiddleware(options: MaintenanceOptions) {
65
+ const path = options.path ?? '/maintenance';
66
+ const cookieName = options.bypassCookie ?? 'sinn-maintenance-bypass';
67
+ const allow = [...ALWAYS_ALLOWED, ...(options.allow ?? [])];
68
+ const allowed = (p: string) => p === path || allow.some((a) => (typeof a === 'string' ? p === a || p.startsWith(a.endsWith('/') ? a : `${a}/`) : a.test(p)));
69
+
70
+ return async function onRequest(context: MaintenanceContext, next: Next): Promise<Response> {
71
+ const on = typeof options.enabled === 'function' ? await options.enabled() : options.enabled;
72
+ const { url } = context;
73
+ if (!on || allowed(url.pathname)) return next();
74
+
75
+ const token = options.bypassToken;
76
+ if (token) {
77
+ const given = url.searchParams.get('maintenance-bypass');
78
+ if (given !== null) {
79
+ if (safeEqual(given, token)) {
80
+ context.cookies.set(cookieName, token, { path: '/', httpOnly: true, secure: url.protocol === 'https:', sameSite: 'lax', maxAge: options.bypassMaxAge ?? 60 * 60 * 12 });
81
+ const clean = new URL(url);
82
+ clean.searchParams.delete('maintenance-bypass');
83
+ return context.redirect(clean.pathname + clean.search, 303);
84
+ }
85
+ }
86
+ const cookie = context.cookies.get(cookieName)?.value;
87
+ if (cookie && safeEqual(cookie, token)) return next();
88
+ }
89
+
90
+ const retryAfter = String(retryAfterSeconds(options.until));
91
+ const headers = new Headers({ 'Retry-After': retryAfter, 'Cache-Control': 'no-store', [MAINTENANCE_HEADER]: '1' });
92
+ const accept = context.request.headers.get('accept') ?? '';
93
+ const wantsHtml = accept.includes('text/html') || accept.includes('*/*') || accept === '';
94
+ if (!wantsHtml || context.request.method !== 'GET' && context.request.method !== 'HEAD') {
95
+ headers.set('Content-Type', 'application/json');
96
+ return new Response(JSON.stringify({ error: 'maintenance', retryAfter: Number(retryAfter) }), { status: 503, headers });
97
+ }
98
+ const page = await context.rewrite(path);
99
+ page.headers.forEach((v, k) => {
100
+ if (!headers.has(k) && k.toLowerCase() !== 'content-length') headers.set(k, v);
101
+ });
102
+ return new Response(context.request.method === 'HEAD' ? null : page.body, { status: 503, statusText: 'Service Unavailable', headers });
103
+ };
104
+ }
105
+
106
+ /** "Saturday, November 15 at 3:00 PM CST" in the given time zone and locale. */
107
+ export function formatUntil(until: string | Date, locale = 'en-US', timeZone?: string): string {
108
+ const d = new Date(until);
109
+ if (!Number.isFinite(d.getTime())) return '';
110
+ const day = new Intl.DateTimeFormat(locale, { weekday: 'long', month: 'long', day: 'numeric', timeZone }).format(d);
111
+ const time = new Intl.DateTimeFormat(locale, { hour: 'numeric', minute: '2-digit', timeZone, timeZoneName: 'short' }).format(d);
112
+ return `${day} at ${time}`;
113
+ }
114
+
115
+ /** "in about 2 hours" / "in 25 minutes" / undefined when past. */
116
+ export function relativeUntil(until: string | Date, locale = 'en-US', now: number = Date.now()): string | undefined {
117
+ const ms = new Date(until).getTime() - now;
118
+ if (!Number.isFinite(ms) || ms <= 0) return undefined;
119
+ const rtf = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' });
120
+ const min = Math.round(ms / 60000);
121
+ if (min < 1) return rtf.format(1, 'minute');
122
+ if (min < 60) return rtf.format(min, 'minute');
123
+ const hours = ms / 3600000;
124
+ if (hours < 24) {
125
+ const h = Math.round(hours * 2) / 2;
126
+ return Number.isInteger(h) ? rtf.format(h, 'hour') : rtf.format(Math.round(min / 15) * 15, 'minute');
127
+ }
128
+ return rtf.format(Math.round(hours / 24), 'day');
129
+ }