create-bearminion 1.5.0 → 1.7.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 (38) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +5 -3
  3. package/package.json +2 -2
  4. package/template/.env.example +18 -0
  5. package/template/README.md +8 -2
  6. package/template/astro.config.ts +25 -0
  7. package/template/package.json +1 -1
  8. package/template/src/components/atoms/Typography.astro +5 -2
  9. package/template/src/components/sections/SectionList.astro +6 -3
  10. package/template/src/components/sections/contact/Contact.astro +45 -46
  11. package/template/src/components/sections/contact/definition.ts +2 -2
  12. package/template/src/components/sections/contact/form.ts +296 -0
  13. package/template/src/components/sections/definitions.ts +4 -2
  14. package/template/src/components/sections/gallery/Gallery.astro +128 -0
  15. package/template/src/components/sections/gallery/Gallery.stories.ts +24 -0
  16. package/template/src/components/sections/gallery/definition.ts +59 -0
  17. package/template/src/components/sections/gallery/lightbox.ts +159 -0
  18. package/template/src/components/sections/gallery/wireframe.ts +12 -0
  19. package/template/src/components/sections/media/Media.astro +1 -0
  20. package/template/src/components/sections/media/MediaPlayer.astro +29 -1
  21. package/template/src/components/sections/media/definition.ts +6 -1
  22. package/template/src/components/sections/media/source.ts +3 -33
  23. package/template/src/components/sections/registry.ts +4 -2
  24. package/template/src/components/sections/text/Text.astro +43 -0
  25. package/template/src/components/sections/text/Text.stories.ts +17 -0
  26. package/template/src/components/sections/text/definition.ts +36 -0
  27. package/template/src/components/sections/text/wireframe.ts +12 -0
  28. package/template/src/layouts/Base.astro +17 -0
  29. package/template/src/lib/contact-form.ts +97 -0
  30. package/template/src/lib/content-model.ts +5 -1
  31. package/template/src/lib/form-check.ts +38 -0
  32. package/template/src/lib/migrations.ts +44 -0
  33. package/template/src/styles/global.css +243 -0
  34. package/template/src/components/sections/video/Video.astro +0 -78
  35. package/template/src/components/sections/video/Video.stories.ts +0 -17
  36. package/template/src/components/sections/video/VideoFrame.astro +0 -60
  37. package/template/src/components/sections/video/definition.ts +0 -58
  38. package/template/src/components/sections/video/wireframe.ts +0 -9
@@ -0,0 +1,159 @@
1
+ /**
2
+ * The gallery lightbox. Each picture in the page is a link to its large file, so with JavaScript off a click simply
3
+ * opens the picture. With it on, a click opens a native <dialog> that shows one picture at a time. The large file is
4
+ * requested when the dialog opens (and the pictures next to it, so the arrows feel instant), never before.
5
+ */
6
+
7
+ /** The index after moving `step` places from `from` in a list of `count`, wrapping at both ends. */
8
+ export function stepIndex(from: number, step: number, count: number): number {
9
+ if (count <= 0) return 0
10
+ return (((from + step) % count) + count) % count
11
+ }
12
+
13
+ /** Which way a finger moved: a mostly horizontal drag of at least `threshold` px. Positive is toward the next picture. */
14
+ export function swipeStep(dx: number, dy: number, threshold = 48): -1 | 0 | 1 {
15
+ if (Math.abs(dx) < threshold || Math.abs(dx) < Math.abs(dy) * 1.25) return 0
16
+ return dx < 0 ? 1 : -1
17
+ }
18
+
19
+ interface Item {
20
+ src: string
21
+ alt: string
22
+ caption: string
23
+ opener: HTMLElement
24
+ }
25
+
26
+ function itemsOf(section: Element): Item[] {
27
+ return [...section.querySelectorAll<HTMLElement>('[data-gallery-open]')].map((opener) => ({
28
+ src: opener.getAttribute('href') ?? '',
29
+ alt: opener.dataset.alt ?? '',
30
+ caption: opener.dataset.caption ?? '',
31
+ opener,
32
+ }))
33
+ }
34
+
35
+ class Lightbox {
36
+ private items: Item[] = []
37
+ private index = 0
38
+ private touch: { x: number; y: number } | null = null
39
+ private readonly image: HTMLImageElement
40
+ private readonly caption: HTMLElement
41
+ private readonly counter: HTMLElement
42
+ private readonly status: HTMLElement
43
+ private readonly figure: HTMLElement
44
+
45
+ constructor(private readonly dialog: HTMLDialogElement) {
46
+ this.image = this.part<HTMLImageElement>('[data-gallery-image]')
47
+ this.caption = this.part('[data-gallery-caption]')
48
+ this.counter = this.part('[data-gallery-counter]')
49
+ this.status = this.part('[data-gallery-status]')
50
+ this.figure = this.part('[data-gallery-figure]')
51
+
52
+ dialog.addEventListener('click', (event) => {
53
+ const target = event.target as HTMLElement
54
+ if (target.closest('[data-gallery-close]')) return this.close()
55
+ const step = target.closest<HTMLElement>('[data-gallery-step]')
56
+ if (step) return this.go(Number(step.dataset.galleryStep))
57
+ // The backdrop and the empty space around the picture close it; the picture and its caption do not.
58
+ if (target === dialog || target === this.figure || target.hasAttribute('data-gallery-stage')) this.close()
59
+ })
60
+ dialog.addEventListener('keydown', (event) => {
61
+ if (event.key === 'ArrowLeft') this.go(-1)
62
+ else if (event.key === 'ArrowRight') this.go(1)
63
+ else if (event.key === 'Home') this.show(0)
64
+ else if (event.key === 'End') this.show(this.items.length - 1)
65
+ else return
66
+ event.preventDefault()
67
+ })
68
+ // The dialog's own Escape and the close button both end here, so focus always goes back to the picture opened.
69
+ dialog.addEventListener('close', () => this.items[this.index]?.opener.focus({ preventScroll: true }))
70
+ dialog.addEventListener('pointerdown', (event) => {
71
+ if (event.pointerType !== 'touch') return
72
+ this.touch = { x: event.clientX, y: event.clientY }
73
+ })
74
+ dialog.addEventListener('pointerup', (event) => {
75
+ if (!this.touch) return
76
+ const step = swipeStep(event.clientX - this.touch.x, event.clientY - this.touch.y)
77
+ this.touch = null
78
+ if (step !== 0) this.go(step)
79
+ })
80
+ dialog.addEventListener('pointercancel', () => {
81
+ this.touch = null
82
+ })
83
+ this.image.addEventListener('load', () => this.dialog.removeAttribute('data-loading'))
84
+ this.image.addEventListener('error', () => {
85
+ this.dialog.removeAttribute('data-loading')
86
+ this.status.textContent = 'This picture could not be loaded.'
87
+ })
88
+ }
89
+
90
+ private part<T extends HTMLElement = HTMLElement>(selector: string): T {
91
+ const node = this.dialog.querySelector<T>(selector)
92
+ if (!node) throw new Error(`Gallery lightbox is missing ${selector}`)
93
+ return node
94
+ }
95
+
96
+ open(section: Element, opener: Element) {
97
+ this.items = itemsOf(section)
98
+ const start = this.items.findIndex((item) => item.opener === opener)
99
+ this.dialog.toggleAttribute('data-single', this.items.length < 2)
100
+ this.show(Math.max(0, start))
101
+ if (!this.dialog.open) this.dialog.showModal()
102
+ this.dialog.querySelector<HTMLElement>('[data-gallery-close]')?.focus({ preventScroll: true })
103
+ }
104
+
105
+ private go(step: number) {
106
+ this.show(stepIndex(this.index, step, this.items.length))
107
+ }
108
+
109
+ private show(index: number) {
110
+ const item = this.items[index]
111
+ if (!item) return
112
+ this.index = index
113
+ this.status.textContent = ''
114
+ this.dialog.setAttribute('data-loading', '')
115
+ this.image.alt = item.alt
116
+ this.image.src = item.src
117
+ // A picture without a caption shows its description, so every picture in the lightbox says what it is.
118
+ const text = item.caption || item.alt
119
+ this.caption.textContent = text
120
+ this.caption.hidden = text === ''
121
+ this.counter.textContent = `${index + 1} / ${this.items.length}`
122
+ // Fetch the neighbours now, so the next arrow press shows its picture at once.
123
+ for (const near of [stepIndex(index, 1, this.items.length), stepIndex(index, -1, this.items.length)]) {
124
+ if (near !== index) new Image().src = this.items[near]?.src ?? ''
125
+ }
126
+ }
127
+
128
+ close() {
129
+ if (this.dialog.open) this.dialog.close()
130
+ }
131
+ }
132
+
133
+ const lightboxes = new WeakMap<HTMLDialogElement, Lightbox>()
134
+
135
+ /** One delegated listener, so sections added later by the editor's live preview work too. Safe to call twice. */
136
+ export function initGalleries(): void {
137
+ const flag = '__bearminionGallery'
138
+ const scope = window as unknown as Record<string, boolean | undefined>
139
+ if (scope[flag]) return
140
+ scope[flag] = true
141
+ document.addEventListener('click', (event) => {
142
+ const opener = (event.target as Element | null)?.closest<HTMLElement>('[data-gallery-open]')
143
+ if (!opener) return
144
+ // While the editor is on the page a click edits the picture. Either way the link itself must not navigate.
145
+ event.preventDefault()
146
+ // Preview mode shows the page as visitors see it, so the lightbox works there.
147
+ const root = document.documentElement
148
+ if (root.hasAttribute('data-bearminion-ready') && !root.hasAttribute('data-bearminion-preview')) return
149
+ const section = opener.closest('[data-section-id]')
150
+ const dialog = section?.querySelector<HTMLDialogElement>('dialog[data-gallery-dialog]')
151
+ if (!section || !dialog) return
152
+ let box = lightboxes.get(dialog)
153
+ if (!box) {
154
+ box = new Lightbox(dialog)
155
+ lightboxes.set(dialog, box)
156
+ }
157
+ box.open(section, opener)
158
+ })
159
+ }
@@ -0,0 +1,12 @@
1
+ import { defineWireframe } from 'bearminion'
2
+
3
+ /** Add section picker thumbnail: [left %, top %, width %, height %, kind]. */
4
+ export const galleryWireframe = defineWireframe([
5
+ [8, 10, 34, 8, 'title'],
6
+ [8, 24, 20, 12, 'figure'],
7
+ [32, 24, 20, 12, 'figure'],
8
+ [56, 24, 20, 12, 'figure'],
9
+ [8, 40, 20, 12, 'figure'],
10
+ [32, 40, 20, 12, 'figure'],
11
+ [56, 40, 20, 12, 'figure'],
12
+ ])
@@ -28,6 +28,7 @@ const player = {
28
28
  poster: props.poster,
29
29
  image: props.image,
30
30
  label: props.label,
31
+ playback: props.playback,
31
32
  imageField: field('image.alt'),
32
33
  // The first two sections are usually on screen at load, where a lazy cover would hold back the largest paint.
33
34
  eager: index <= 1,
@@ -13,6 +13,7 @@ interface Props {
13
13
  poster?: Image
14
14
  image?: Image
15
15
  label?: string
16
+ playback?: MediaProps['playback']
16
17
  /** `data-field` path for the image, so a click on the frame opens the image picker. */
17
18
  imageField: string
18
19
  /** Near the top of the page: the cover loads at once instead of lazily, since it is likely the largest thing on screen. */
@@ -20,7 +21,7 @@ interface Props {
20
21
  class?: string
21
22
  }
22
23
 
23
- const { kind, aspect, video, poster, image, label, imageField, eager = false, class: className } = Astro.props
24
+ const { kind, aspect, video, poster, image, label, playback = 'controls', imageField, eager = false, class: className } = Astro.props
24
25
  const ASPECT = { '16:9': 'aspect-video', '4:3': 'aspect-[4/3]', '21:9': 'aspect-[21/9]', '1:1': 'aspect-square' } as const
25
26
  const frame = cn(
26
27
  'relative w-full min-h-48 overflow-hidden rounded-[clamp(1rem,2cqi,1.5rem)] bg-surface shadow-[inset_0_0_0_1px_var(--line),0_40px_80px_-48px_oklch(0.2_0.02_255/0.35)]',
@@ -35,6 +36,9 @@ const coverSrcset = source ? await imageSrcset(poster) : undefined
35
36
  // The frame is at most 68rem wide and the full width of a phone.
36
37
  const coverSizes = '(min-width: 72rem) 68rem, 100vw'
37
38
  const name = label || 'Video'
39
+ // A video file on loop starts muted and without controls once the page script sees it on screen. Until then, and without
40
+ // JavaScript or with reduced motion, it keeps its controls so it can still be played.
41
+ const looping = source?.kind === 'file' && playback === 'loop'
38
42
  ---
39
43
 
40
44
  {
@@ -63,6 +67,10 @@ const name = label || 'Video'
63
67
  class="shadow-[inset_0_0_0_1px_var(--line),0_40px_80px_-48px_oklch(0.2_0.02_255/0.35)]"
64
68
  data-field={imageField}
65
69
  />
70
+ ) : looping && source?.kind === 'file' ? (
71
+ <div class={frame}>
72
+ <video class="absolute inset-0 size-full object-cover" src={source.src} poster={cover} preload="metadata" playsinline muted loop controls aria-label={name} data-video-loop />
73
+ </div>
66
74
  ) : (
67
75
  source && (
68
76
  <div
@@ -145,4 +153,24 @@ const name = label || 'Video'
145
153
  }
146
154
  bindMediaPlayers()
147
155
  document.addEventListener('bearminion:preview', bindMediaPlayers)
156
+
157
+ /** Looping videos play while at least a quarter of them is on screen, and not at all with reduced motion. */
158
+ function bindLoopingVideos() {
159
+ const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches
160
+ for (const video of document.querySelectorAll<HTMLVideoElement>('video[data-video-loop]')) {
161
+ if (video.dataset.bound === 'true') continue
162
+ video.dataset.bound = 'true'
163
+ if (reduced) continue
164
+ video.controls = false
165
+ new IntersectionObserver(
166
+ ([entry]) => {
167
+ if (entry?.isIntersecting) void video.play().catch(() => (video.controls = true))
168
+ else video.pause()
169
+ },
170
+ { threshold: 0.25 },
171
+ ).observe(video)
172
+ }
173
+ }
174
+ bindLoopingVideos()
175
+ document.addEventListener('bearminion:preview', bindLoopingVideos)
148
176
  </script>
@@ -6,6 +6,8 @@ import { mediaWireframe } from './wireframe'
6
6
 
7
7
  export const mediaVariants = ['centered', 'wide', 'split'] as const
8
8
  export const mediaKinds = ['video', 'image'] as const
9
+ /** `controls`: the visitor presses play. `loop`: a video file plays silently on repeat while it is on screen, like a moving image. */
10
+ export const mediaPlayback = ['controls', 'loop'] as const
9
11
  export const mediaAspects = ['16:9', '4:3', '21:9', '1:1'] as const
10
12
 
11
13
  /** A YouTube or Vimeo link, a path in `public/` such as `/videos/demo.webm`, or an `https://` link to a video file. */
@@ -32,6 +34,7 @@ export const mediaSchema = withEmphasis({
32
34
  /** What the video shows, read out by screen readers. An image uses its own alt text. */
33
35
  label: textSchema.optional(),
34
36
  caption: textSchema.optional(),
37
+ playback: z.enum(mediaPlayback).default('controls'),
35
38
  })
36
39
 
37
40
  export type MediaProps = z.infer<typeof mediaSchema>
@@ -39,7 +42,7 @@ export type MediaProps = z.infer<typeof mediaSchema>
39
42
  export const media = defineSection({
40
43
  type: 'media',
41
44
  label: 'Media',
42
- description: 'One video or image under a heading. YouTube, Vimeo or a video file.',
45
+ description: 'One video or image under a heading. YouTube, Vimeo or a video file, with a poster and a caption.',
43
46
  schema: mediaSchema,
44
47
  defaults: {
45
48
  eyebrow: 'Demo',
@@ -50,12 +53,14 @@ export const media = defineSection({
50
53
  aspect: '16:9',
51
54
  intro: true,
52
55
  label: 'Product walkthrough',
56
+ playback: 'controls',
53
57
  },
54
58
  variants: mediaVariants,
55
59
  defaultVariant: 'centered',
56
60
  options: [
57
61
  { name: 'kind', label: 'Type', type: 'enum', choices: mediaKinds, default: 'video' },
58
62
  { name: 'aspect', label: 'Shape', type: 'enum', choices: mediaAspects, default: '16:9' },
63
+ { name: 'playback', label: 'Video playback', type: 'enum', choices: mediaPlayback, default: 'controls' },
59
64
  { name: 'intro', label: 'Show heading', type: 'boolean', default: true },
60
65
  ],
61
66
  optional: { props: ['eyebrow', 'heading', 'body', 'video', 'poster', 'image', 'label', 'caption'] },
@@ -1,33 +1,3 @@
1
- /**
2
- * What a Media section's video link points at. YouTube and Vimeo links become privacy-friendly embeds
3
- * (youtube-nocookie.com, Vimeo with Do Not Track) that load only after the visitor presses play. A link to a video file
4
- * plays in a `<video>` element.
5
- */
6
- export type MediaSource =
7
- | { kind: 'youtube'; id: string; embed: string; thumbnail: string }
8
- | { kind: 'vimeo'; id: string; embed: string }
9
- | { kind: 'file'; src: string }
10
-
11
- const YOUTUBE =
12
- /^https?:\/\/(?:(?:www|m)\.)?(?:youtube\.com\/(?:watch\?(?:[^#\s]*&)?v=|embed\/|shorts\/|live\/)|youtube-nocookie\.com\/embed\/|youtu\.be\/)([\w-]{6,})(?:[?&#][^\s]*)?$/i
13
- const VIMEO = /^https?:\/\/(?:(?:www|player)\.)?vimeo\.com\/(?:video\/)?(\d+)(?:[/?#][^\s]*)?$/i
14
- /** A path in `public/` (`/videos/demo.webm`) or an `https://` link to a video file. */
15
- export const VIDEO_FILE = /^(?:\/(?!\/)|https?:\/\/)\S+\.(?:mp4|webm|m4v|mov|ogv)(?:[?#]\S*)?$/i
16
-
17
- export function parseMediaSource(value: string): MediaSource | null {
18
- const src = value.trim()
19
- const youtube = YOUTUBE.exec(src)
20
- if (youtube?.[1]) {
21
- const id = youtube[1]
22
- return {
23
- kind: 'youtube',
24
- id,
25
- embed: `https://www.youtube-nocookie.com/embed/${id}?autoplay=1&rel=0`,
26
- thumbnail: `https://i.ytimg.com/vi/${id}/hqdefault.jpg`,
27
- }
28
- }
29
- const vimeo = VIMEO.exec(src)
30
- if (vimeo?.[1]) return { kind: 'vimeo', id: vimeo[1], embed: `https://player.vimeo.com/video/${vimeo[1]}?autoplay=1&dnt=1` }
31
- if (VIDEO_FILE.test(src)) return { kind: 'file', src }
32
- return null
33
- }
1
+ /** The parser lives in the library, where the editor's video box uses it too. Re-exported so sections keep one import. */
2
+ export { VIDEO_FILE, parseMediaSource } from 'bearminion'
3
+ export type { MediaSource } from 'bearminion'
@@ -3,6 +3,7 @@ import Contact from './contact/Contact.astro'
3
3
  import Cta from './cta/Cta.astro'
4
4
  import Faq from './faq/Faq.astro'
5
5
  import Features from './features/Features.astro'
6
+ import Gallery from './gallery/Gallery.astro'
6
7
  import Hero from './hero/Hero.astro'
7
8
  import LogoStrip from './logo-strip/LogoStrip.astro'
8
9
  import Media from './media/Media.astro'
@@ -10,20 +11,21 @@ import Pricing from './pricing/Pricing.astro'
10
11
  import Stats from './stats/Stats.astro'
11
12
  import Steps from './steps/Steps.astro'
12
13
  import Testimonials from './testimonials/Testimonials.astro'
14
+ import Text from './text/Text.astro'
13
15
  import TextImage from './text-image/TextImage.astro'
14
- import Video from './video/Video.astro'
15
16
 
16
17
  /** Maps a content section `type` to the component that renders it. Definitions live in `definitions.ts`. */
17
18
  export const sectionComponents = {
18
19
  hero: Hero,
19
20
  logoStrip: LogoStrip,
20
21
  steps: Steps,
22
+ gallery: Gallery,
21
23
  features: Features,
24
+ text: Text,
22
25
  textImage: TextImage,
23
26
  stats: Stats,
24
27
  testimonials: Testimonials,
25
28
  pricing: Pricing,
26
- video: Video,
27
29
  media: Media,
28
30
  faq: Faq,
29
31
  cta: Cta,
@@ -0,0 +1,43 @@
1
+ ---
2
+ import type { Section } from '../definitions'
3
+ import Typography from '../../atoms/Typography.astro'
4
+ import SectionHeader from '../../molecules/SectionHeader.astro'
5
+ import SectionShell from '../../molecules/SectionShell.astro'
6
+ import { cn } from '../../../lib/cn'
7
+
8
+ interface Props {
9
+ section: Extract<Section, { type: 'text' }>
10
+ index: number
11
+ motion?: boolean
12
+ }
13
+
14
+ const { section, index, motion = true } = Astro.props
15
+ const props = section.props
16
+ const field = (path: string) => `sections.${index}.props.${path}`
17
+ const reveal = section.motion ?? motion
18
+ const center = section.variant === 'center'
19
+ ---
20
+
21
+ <SectionShell id={section.id} anchor={section.anchor} type={section.type} variant={section.variant} tone={section.tone} motion={reveal}>
22
+ <div class={cn('section-container flex flex-col gap-[clamp(1.75rem,3.5cqi,2.75rem)]', center && 'items-center')}>
23
+ <div class={cn('flex w-full flex-col', props.narrow && 'max-w-[42rem]', center && 'items-center text-center')}>
24
+ <SectionHeader
25
+ eyebrow={props.eyebrow}
26
+ heading={props.heading}
27
+ marks={props.marks}
28
+ size="h2-md"
29
+ align={center ? 'center' : 'left'}
30
+ field={field}
31
+ class="gap-5"
32
+ />
33
+ </div>
34
+ <Typography
35
+ as="div"
36
+ size="lead"
37
+ class={cn('w-full', props.narrow && 'max-w-[42rem]', center && 'text-left')}
38
+ data-field={field('body')}
39
+ markdown={props.body}
40
+ richHeadings
41
+ />
42
+ </div>
43
+ </SectionShell>
@@ -0,0 +1,17 @@
1
+ import { sectionArgTypes } from '../../../stories/options'
2
+ import { text } from './definition'
3
+ import Text from './Text.astro'
4
+
5
+ /** The sample pages hold no Text section, so the stories start from its defaults. */
6
+ const section = { id: 'text', type: 'text', variant: 'left', tone: 'base', props: text.defaults } as const
7
+
8
+ export default {
9
+ title: 'Sections/Text',
10
+ component: Text,
11
+ parameters: { layout: 'fullscreen' },
12
+ argTypes: sectionArgTypes('text'),
13
+ }
14
+
15
+ export const Left = { args: { section, index: 0 } }
16
+ export const Center = { args: { section: { ...section, variant: 'center' }, index: 0 } }
17
+ export const FullWidth = { args: { section: { ...section, props: { ...text.defaults, narrow: false } }, index: 0 } }
@@ -0,0 +1,36 @@
1
+ import { z } from 'zod'
2
+ import { defineSection, richTextSchema, withEmphasis } from 'bearminion'
3
+ import { accent, eyebrow, heading } from '../shared'
4
+ import { textWireframe } from './wireframe'
5
+
6
+ export const textVariants = ['left', 'center'] as const
7
+
8
+ export const textSchema = withEmphasis({
9
+ eyebrow,
10
+ heading,
11
+ /** Long-form text. Besides bold, italic, links, code and lists it may hold `##` and `###` headings. */
12
+ body: richTextSchema,
13
+ /** On: a readable column about 65 characters wide. Off: the full width of the page. */
14
+ narrow: z.boolean().default(true),
15
+ })
16
+
17
+ export type TextProps = z.infer<typeof textSchema>
18
+
19
+ export const text = defineSection({
20
+ type: 'text',
21
+ label: 'Text',
22
+ description: 'Plain long-form text with headings, lists and links. For an About, a policy or any simple page.',
23
+ schema: textSchema,
24
+ defaults: {
25
+ eyebrow: 'About',
26
+ heading: 'A page of plain words.',
27
+ marks: accent('A page of plain words.', 'plain words.'),
28
+ body: 'Write as much as you need. Select a few words to make them **bold**, *italic* or a link.\n\n## A heading\n\nHeadings split a long page into parts a reader can scan.\n\n- Lists work too\n- With as many items as you need',
29
+ narrow: true,
30
+ },
31
+ variants: textVariants,
32
+ defaultVariant: 'left',
33
+ options: [{ name: 'narrow', label: 'Narrow column (easier to read)', type: 'boolean', default: true }],
34
+ optional: { props: ['eyebrow', 'heading'] },
35
+ wireframe: textWireframe,
36
+ })
@@ -0,0 +1,12 @@
1
+ import { defineWireframe } from 'bearminion'
2
+
3
+ /** Add section picker thumbnail: [left %, top %, width %, height %, kind]. */
4
+ export const textWireframe = defineWireframe([
5
+ [20, 12, 40, 8, 'title'],
6
+ [20, 30, 60, 3, 'text'],
7
+ [20, 38, 60, 3, 'text'],
8
+ [20, 46, 52, 3, 'text'],
9
+ [20, 58, 30, 5, 'title'],
10
+ [20, 70, 60, 3, 'text'],
11
+ [20, 78, 44, 3, 'text'],
12
+ ])
@@ -42,6 +42,23 @@ const gated = asks && analyticsOn
42
42
  {gated && analytics?.head && <template data-consent-snippet="head" set:html={analytics.head} />}
43
43
  {/* Always present so the editor can update the palette live. */}
44
44
  <style id="bm-theme" is:inline set:html={paletteCss}></style>
45
+ {/* Without JavaScript the browser posts the contact form itself and comes back to #<id>-sent or #<id>-failed. */}
46
+ <noscript>
47
+ <style is:inline>
48
+ [data-motion="true"] > [data-reveal] {
49
+ opacity: 1;
50
+ transform: none;
51
+ }
52
+ [data-contact-success]:target,
53
+ [data-contact-failed]:target {
54
+ display: block;
55
+ }
56
+ [data-contact]:has([data-contact-success]:target) [data-contact-form],
57
+ [data-contact-reset] {
58
+ display: none;
59
+ }
60
+ </style>
61
+ </noscript>
45
62
  {icon && <link rel="icon" type={iconType} href={icon.src} />}
46
63
  </head>
47
64
  <body class="min-h-screen font-sans antialiased">
@@ -0,0 +1,97 @@
1
+ import type { FormResult, FormSubmission } from 'bearminion'
2
+
3
+ /**
4
+ * The Contact form's rules, apart from the page: what is sent, how an answer is read, and which submissions a
5
+ * person could not have made. `components/sections/contact/form.ts` wires them to the DOM.
6
+ */
7
+
8
+ /** The spam-trap field. People never see it; many bots fill every field they find. Formspree uses the same name. */
9
+ export const HONEYPOT_FIELD = '_gotcha'
10
+
11
+ /** The field Cloudflare Turnstile's token is sent in, which `defineForm` from `bearminion/forms` checks on the server. */
12
+ export const TURNSTILE_FIELD = 'cf-turnstile-response'
13
+
14
+ /** A person needs longer than this to type a message. A submit sooner than this after the form appeared is a script. */
15
+ export const MIN_FILL_MS = 1500
16
+
17
+ /** Why a submission is dropped without being sent, or `null` when it should go out. */
18
+ export function botVerdict(trap: string, openedAt: number, now: number): 'honeypot' | 'too-fast' | null {
19
+ if (trap.trim() !== '') return 'honeypot'
20
+ if (now - openedAt < MIN_FILL_MS) return 'too-fast'
21
+ return null
22
+ }
23
+
24
+ /** The fields of a form as strings, plus where they came from. The trap field and any file input are left out. */
25
+ export function collectSubmission(entries: Iterable<[string, unknown]>, formId: string, page: string): FormSubmission {
26
+ const submission: FormSubmission = { formId, page }
27
+ for (const [name, value] of entries) {
28
+ if (name === HONEYPOT_FIELD || name === 'formId' || name === 'page' || typeof value !== 'string') continue
29
+ submission[name] = value
30
+ }
31
+ return submission
32
+ }
33
+
34
+ /** Where every Contact form posts. The site's own handler, `src/forms/contact.ts`, answers here. */
35
+ export const FORM_ENDPOINT = '/api/contact'
36
+
37
+ export interface FormRequest {
38
+ url: string
39
+ init: RequestInit
40
+ }
41
+
42
+ /** The request: the submission as JSON. The handler (`defineForm`) reads it and answers with JSON. */
43
+ export function buildRequest(submission: FormSubmission): FormRequest {
44
+ return {
45
+ url: FORM_ENDPOINT,
46
+ init: {
47
+ method: 'POST',
48
+ headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
49
+ body: JSON.stringify(submission),
50
+ },
51
+ }
52
+ }
53
+
54
+ const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value)
55
+ const text = (value: unknown): string | undefined => (typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined)
56
+
57
+ /** Field errors from `fieldErrors: { email: '…' }`. */
58
+ function readFieldErrors(body: Record<string, unknown>): Record<string, string> | undefined {
59
+ if (!isRecord(body.fieldErrors)) return undefined
60
+ const found: Record<string, string> = {}
61
+ for (const [name, message] of Object.entries(body.fieldErrors)) {
62
+ const line = text(message)
63
+ if (line) found[name] = line
64
+ }
65
+ return Object.keys(found).length > 0 ? found : undefined
66
+ }
67
+
68
+ /** What to tell a visitor when the endpoint gave no message of its own. */
69
+ function fallbackError(status: number): string {
70
+ if (status === 429) return 'Too many messages in a short time. Wait a minute and try again.'
71
+ if (status >= 500) return 'The server had a problem. Try again in a moment.'
72
+ return 'The message was not accepted. Check the form and try again.'
73
+ }
74
+
75
+ /**
76
+ * Reads the handler's answer. The HTTP status decides: a 2xx is a success unless the body says `ok: false`. `body` is
77
+ * the parsed JSON, or `undefined` when there was none, which a 2xx treats as success.
78
+ */
79
+ export function readResponse(status: number, body: unknown): FormResult {
80
+ const record = isRecord(body) ? body : {}
81
+ if (status >= 200 && status < 300 && record.ok !== false) {
82
+ const note = record.ok === true ? text(record.message) : undefined
83
+ return note ? { ok: true, message: note } : { ok: true }
84
+ }
85
+ const fieldErrors = readFieldErrors(record)
86
+ const error = text(record.error) ?? text(record.message) ?? fallbackError(status >= 200 && status < 300 ? 400 : status)
87
+ return fieldErrors ? { ok: false, error, fieldErrors } : { ok: false, error }
88
+ }
89
+
90
+ /** Shown when the request never got an answer: offline or blocked. */
91
+ export const NETWORK_ERROR = 'The message could not be sent. Check your connection and try again.'
92
+
93
+ /** Shown when the visitor sends before Turnstile has given its token. */
94
+ export const TURNSTILE_PENDING = 'The spam check is still running. Try again in a moment.'
95
+
96
+ /** Shown when Turnstile could not run: its script is blocked, or it reported an error. */
97
+ export const TURNSTILE_FAILED = 'The spam check could not run. Reload the page, turn off any blocker for this site, and try again.'
@@ -1,6 +1,7 @@
1
1
  import { defineTheme } from 'bearminion'
2
2
  import { siteDefinition } from '../components/organisms/site-definition'
3
3
  import { sectionDefinitions } from '../components/sections/definitions'
4
+ import { migrateContactFormSettings, migrateVideoToMedia } from './migrations'
4
5
 
5
6
  /**
6
7
  * Everything the editor and the loaders need to know about this site's content: its section types
@@ -20,6 +21,9 @@ export const contentModel = {
20
21
  /**
21
22
  * Raise this when a schema change would reject files written before it, and add `migrations[n]`
22
23
  * to upgrade version n to n + 1. Files without a `schemaVersion` count as version 1.
24
+ * Version 2 folded the Video section into Media. Version 3 removed the Contact section's endpoint, Turnstile key and
25
+ * format: the form posts to `/api/contact`, and what sits behind it is code in `src/forms`.
23
26
  */
24
- schemaVersion: 1,
27
+ schemaVersion: 3,
28
+ migrations: { 1: migrateVideoToMedia, 2: migrateContactFormSettings },
25
29
  }
@@ -0,0 +1,38 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+
4
+ /** A Contact section on a site with no handler for it: `src/forms/contact.ts` does not exist. */
5
+ export interface UnhandledForm {
6
+ /** The page's slug. */
7
+ page: string
8
+ /** The section's id. */
9
+ section: string
10
+ }
11
+
12
+ interface CheckedPage {
13
+ slug: string
14
+ sections: ReadonlyArray<{ id: string; type: string }>
15
+ }
16
+
17
+ /** The name of the file the Contact form posts to: `/api/contact` is answered by `src/forms/contact.ts`. */
18
+ export const CONTACT_HANDLER = 'contact'
19
+
20
+ /** True when `<dir>/<name>.ts` (or `.mts`, `.js`, `.mjs`) exists. */
21
+ export function hasFormHandler(dir: string, name: string = CONTACT_HANDLER): boolean {
22
+ return ['.ts', '.mts', '.js', '.mjs'].some((extension) => fs.existsSync(path.join(dir, `${name}${extension}`)))
23
+ }
24
+
25
+ /**
26
+ * Every Contact section, on every page, while there is no handler. `astro dev` and `astro build` warn about these;
27
+ * neither ever fails on them, so a new site still starts and builds.
28
+ */
29
+ export function unhandledForms(pages: readonly CheckedPage[], handled: boolean): UnhandledForm[] {
30
+ if (handled) return []
31
+ return pages.flatMap((page) =>
32
+ page.sections.filter((section) => section.type === 'contact').map((section) => ({ page: page.slug, section: section.id })),
33
+ )
34
+ }
35
+
36
+ export function unhandledFormMessage(form: UnhandledForm): string {
37
+ return `The contact form "${form.section}" on page "${form.page}" posts to /api/${CONTACT_HANDLER}, but src/forms/${CONTACT_HANDLER}.ts does not exist. Visitors who send it get an error. Create the file: https://docs.bearminion.com/forms`
38
+ }