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,296 @@
1
+ import {
2
+ NETWORK_ERROR,
3
+ TURNSTILE_FAILED,
4
+ TURNSTILE_FIELD,
5
+ TURNSTILE_PENDING,
6
+ botVerdict,
7
+ buildRequest,
8
+ collectSubmission,
9
+ readResponse,
10
+ } from '../../../lib/contact-form'
11
+
12
+ /**
13
+ * Wires every Contact form on the page: the states idle, sending, sent and error, field errors under their fields,
14
+ * a message the visitor closes themselves when something went wrong, the spam trap and Cloudflare Turnstile. The
15
+ * message goes to `/api/contact` as JSON. With JavaScript off the browser posts the form there itself and leaves the
16
+ * page; there is no status handling in that case.
17
+ */
18
+
19
+ const FIELD_ERROR = 'data-field-error'
20
+
21
+ function clearFieldErrors(form: HTMLFormElement) {
22
+ for (const note of form.querySelectorAll(`[${FIELD_ERROR}]`)) note.remove()
23
+ for (const control of form.querySelectorAll('[aria-invalid]')) {
24
+ control.removeAttribute('aria-invalid')
25
+ control.removeAttribute('aria-describedby')
26
+ }
27
+ }
28
+
29
+ /** Puts each message under the field it names. Returns the first control marked, so focus can go there. */
30
+ function showFieldErrors(form: HTMLFormElement, errors: Readonly<Record<string, string>>): HTMLElement | null {
31
+ let first: HTMLElement | null = null
32
+ let count = 0
33
+ for (const [name, message] of Object.entries(errors)) {
34
+ const control = form.elements.namedItem(name)
35
+ if (!(control instanceof HTMLInputElement || control instanceof HTMLTextAreaElement || control instanceof HTMLSelectElement)) continue
36
+ if (control.type === 'hidden') continue
37
+ const note = document.createElement('p')
38
+ note.className = 'bm-form-error'
39
+ note.setAttribute(FIELD_ERROR, '')
40
+ note.id = `${form.id || 'contact-form'}-error-${count++}`
41
+ note.textContent = message
42
+ const holder = control.closest('label') ?? control.parentElement ?? form
43
+ holder.append(note)
44
+ control.setAttribute('aria-invalid', 'true')
45
+ control.setAttribute('aria-describedby', note.id)
46
+ first ??= control
47
+ }
48
+ return first
49
+ }
50
+
51
+ /**
52
+ * A failed send is shown in a message that stays until the visitor closes it. It does not fade: an error that
53
+ * disappears on its own is an error nobody finishes reading. One per form; a new one replaces the old.
54
+ */
55
+ function toastRegion(): HTMLElement {
56
+ const existing = document.querySelector<HTMLElement>('[data-bm-toasts]')
57
+ if (existing) return existing
58
+ const region = document.createElement('div')
59
+ region.className = 'bm-toasts'
60
+ region.setAttribute('data-bm-toasts', '')
61
+ // In the top layer, so nothing on the page (or the editor in `astro dev`) can sit over the close button.
62
+ region.setAttribute('popover', 'manual')
63
+ document.body.append(region)
64
+ return region
65
+ }
66
+
67
+ function raise(region: HTMLElement) {
68
+ try {
69
+ if (!region.matches(':popover-open')) region.showPopover()
70
+ } catch {
71
+ // No popover support: the fixed position and z-index in the stylesheet still show it.
72
+ }
73
+ }
74
+
75
+ function closeToast(owner: string) {
76
+ for (const toast of toastRegion().querySelectorAll('[data-toast-for]')) {
77
+ if (toast.getAttribute('data-toast-for') === owner) toast.remove()
78
+ }
79
+ }
80
+
81
+ function showToast(owner: string, message: string) {
82
+ closeToast(owner)
83
+ const toast = document.createElement('div')
84
+ toast.className = 'bm-toast'
85
+ toast.setAttribute('role', 'alert')
86
+ toast.setAttribute('data-toast-for', owner)
87
+ const text = document.createElement('p')
88
+ text.className = 'bm-toast-text'
89
+ text.textContent = message
90
+ const close = document.createElement('button')
91
+ close.type = 'button'
92
+ close.className = 'bm-toast-close'
93
+ close.setAttribute('aria-label', 'Dismiss message')
94
+ close.textContent = '×'
95
+ close.addEventListener('click', () => toast.remove())
96
+ toast.append(text, close)
97
+ const region = toastRegion()
98
+ region.append(toast)
99
+ raise(region)
100
+ }
101
+
102
+ /** The part of Cloudflare's script the form uses. */
103
+ interface TurnstileApi {
104
+ render(container: HTMLElement, options: Record<string, unknown>): string | undefined
105
+ reset(widgetId?: string): void
106
+ }
107
+
108
+ const TURNSTILE_SCRIPT = 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit'
109
+ let turnstileScript: Promise<TurnstileApi> | undefined
110
+
111
+ function loadTurnstile(): Promise<TurnstileApi> {
112
+ const present = (window as unknown as { turnstile?: TurnstileApi }).turnstile
113
+ if (present) return Promise.resolve(present)
114
+ turnstileScript ??= new Promise<TurnstileApi>((resolve, reject) => {
115
+ const script = document.createElement('script')
116
+ script.src = TURNSTILE_SCRIPT
117
+ script.async = true
118
+ script.onload = () => {
119
+ const api = (window as unknown as { turnstile?: TurnstileApi }).turnstile
120
+ if (api) resolve(api)
121
+ else reject(new Error('Turnstile did not load.'))
122
+ }
123
+ script.onerror = () => {
124
+ turnstileScript = undefined
125
+ reject(new Error('Turnstile is blocked.'))
126
+ }
127
+ document.head.append(script)
128
+ })
129
+ return turnstileScript
130
+ }
131
+
132
+ interface TurnstileWidget {
133
+ /** The current token, or an empty string while there is none. */
134
+ token: string
135
+ /** The widget reported an error, or its script never loaded. */
136
+ failed: boolean
137
+ /** A token works once. Ask for a new one after every send. */
138
+ reset: () => void
139
+ }
140
+
141
+ function mountTurnstile(container: HTMLElement, siteKey: string): TurnstileWidget {
142
+ const widget: TurnstileWidget = { token: '', failed: false, reset: () => undefined }
143
+ loadTurnstile().then(
144
+ (api) => {
145
+ const id = api.render(container, {
146
+ sitekey: siteKey,
147
+ // The token is added to the request by the form script, not as a hidden field.
148
+ 'response-field': false,
149
+ callback: (token: string) => {
150
+ widget.token = token
151
+ widget.failed = false
152
+ },
153
+ 'expired-callback': () => {
154
+ widget.token = ''
155
+ },
156
+ 'error-callback': () => {
157
+ widget.token = ''
158
+ widget.failed = true
159
+ },
160
+ })
161
+ widget.reset = () => {
162
+ widget.token = ''
163
+ api.reset(id)
164
+ }
165
+ },
166
+ () => {
167
+ widget.failed = true
168
+ },
169
+ )
170
+ return widget
171
+ }
172
+
173
+ function bind(root: HTMLElement) {
174
+ if (root.dataset.bound === 'true') return
175
+ root.dataset.bound = 'true'
176
+ const form = root.querySelector('[data-contact-form]')
177
+ const success = root.querySelector('[data-contact-success]')
178
+ const reset = root.querySelector('[data-contact-reset]')
179
+ const topicInput = root.querySelector('[data-topic-input]')
180
+ if (!(form instanceof HTMLFormElement) || !(success instanceof HTMLElement)) return
181
+ const submit = form.querySelector('button[type="submit"]')
182
+ const label = submit?.textContent ?? ''
183
+ const owner = form.dataset.formId ?? form.id
184
+ // The clock for the "too fast" check starts when the form is on the page.
185
+ const openedAt = Date.now()
186
+
187
+ const container = form.querySelector('[data-turnstile-widget]')
188
+ const siteKey = form.dataset.turnstileKey
189
+ const turnstile = container instanceof HTMLElement && siteKey ? mountTurnstile(container, siteKey) : null
190
+
191
+ const busy = (on: boolean) => {
192
+ form.toggleAttribute('aria-busy', on)
193
+ if (!(submit instanceof HTMLButtonElement)) return
194
+ submit.disabled = on
195
+ submit.textContent = on ? 'Sending…' : label
196
+ }
197
+ const thanksLine = () => success.querySelector<HTMLElement>('[data-field$=".props.thanks"]')
198
+ const finish = (message?: string) => {
199
+ form.hidden = true
200
+ success.dataset.shown = ''
201
+ success.querySelector('[data-contact-message]')?.remove()
202
+ const thanks = thanksLine()
203
+ if (message) {
204
+ // The endpoint's own words replace the section's thank-you text. Plain text only.
205
+ const line = document.createElement('p')
206
+ line.setAttribute('data-contact-message', '')
207
+ line.className = thanks?.className ?? 'mt-3 text-muted'
208
+ line.textContent = message
209
+ if (thanks) thanks.hidden = true
210
+ success.querySelector('p')?.after(line)
211
+ } else if (thanks) {
212
+ thanks.hidden = false
213
+ }
214
+ success.focus({ preventScroll: true })
215
+ }
216
+ const failed = (message: string, field?: HTMLElement | null) => {
217
+ busy(false)
218
+ showToast(owner, message)
219
+ if (field) field.focus()
220
+ else if (submit instanceof HTMLButtonElement) submit.focus()
221
+ }
222
+
223
+ for (const chip of root.querySelectorAll('[data-topic]')) {
224
+ chip.addEventListener('click', () => {
225
+ for (const item of root.querySelectorAll('[data-topic]')) item.setAttribute('aria-pressed', 'false')
226
+ chip.setAttribute('aria-pressed', 'true')
227
+ if (topicInput instanceof HTMLInputElement) topicInput.value = chip.textContent?.trim() ?? ''
228
+ })
229
+ }
230
+
231
+ // A field marked wrong stops being marked as soon as it is edited.
232
+ form.addEventListener('input', (event) => {
233
+ const target = event.target
234
+ if (!(target instanceof HTMLElement) || target.getAttribute('aria-invalid') !== 'true') return
235
+ document.getElementById(target.getAttribute('aria-describedby') ?? '')?.remove()
236
+ target.removeAttribute('aria-invalid')
237
+ target.removeAttribute('aria-describedby')
238
+ })
239
+
240
+ form.addEventListener('submit', (event) => {
241
+ event.preventDefault()
242
+ if (!form.reportValidity()) return
243
+ clearFieldErrors(form)
244
+ closeToast(owner)
245
+ const trap = form.elements.namedItem('_gotcha')
246
+ const verdict = botVerdict(trap instanceof HTMLInputElement ? trap.value : '', openedAt, Date.now())
247
+ if (verdict) {
248
+ // A script filled the trap or submitted at once. Look as if it worked, and send nothing.
249
+ finish()
250
+ return
251
+ }
252
+ if (turnstile && turnstile.token === '') {
253
+ showToast(owner, turnstile.failed ? TURNSTILE_FAILED : TURNSTILE_PENDING)
254
+ return
255
+ }
256
+ const submission = collectSubmission(new FormData(form).entries(), owner, location.pathname)
257
+ if (turnstile) submission[TURNSTILE_FIELD] = turnstile.token
258
+ const request = buildRequest(submission)
259
+ busy(true)
260
+ void fetch(request.url, request.init).then(
261
+ async (response) => {
262
+ const body: unknown = await response.json().catch(() => undefined)
263
+ const result = readResponse(response.status, body)
264
+ // The token is spent whether the send worked or not.
265
+ turnstile?.reset()
266
+ if (result.ok) {
267
+ busy(false)
268
+ finish(result.message)
269
+ return
270
+ }
271
+ failed(result.error, result.fieldErrors ? showFieldErrors(form, result.fieldErrors) : null)
272
+ },
273
+ () => {
274
+ turnstile?.reset()
275
+ failed(NETWORK_ERROR)
276
+ },
277
+ )
278
+ })
279
+
280
+ reset?.addEventListener('click', () => {
281
+ form.reset()
282
+ clearFieldErrors(form)
283
+ closeToast(owner)
284
+ success.querySelector('[data-contact-message]')?.remove()
285
+ const thanks = thanksLine()
286
+ if (thanks) thanks.hidden = false
287
+ form.hidden = false
288
+ delete success.dataset.shown
289
+ })
290
+ }
291
+
292
+ export function bindContacts(): void {
293
+ for (const root of document.querySelectorAll('[data-contact]')) {
294
+ if (root instanceof HTMLElement) bind(root)
295
+ }
296
+ }
@@ -10,6 +10,7 @@ import { contact } from './contact/definition'
10
10
  import { cta } from './cta/definition'
11
11
  import { faq } from './faq/definition'
12
12
  import { features } from './features/definition'
13
+ import { gallery } from './gallery/definition'
13
14
  import { hero } from './hero/definition'
14
15
  import { logoStrip } from './logo-strip/definition'
15
16
  import { media } from './media/definition'
@@ -17,8 +18,8 @@ import { pricing } from './pricing/definition'
17
18
  import { stats } from './stats/definition'
18
19
  import { steps } from './steps/definition'
19
20
  import { testimonials } from './testimonials/definition'
21
+ import { text } from './text/definition'
20
22
  import { textImage } from './text-image/definition'
21
- import { video } from './video/definition'
22
23
 
23
24
  /**
24
25
  * Every section type of this site. Each one is defined in its own directory:
@@ -31,12 +32,13 @@ export const sectionDefinitions = {
31
32
  hero,
32
33
  logoStrip,
33
34
  steps,
35
+ gallery,
34
36
  features,
37
+ text,
35
38
  textImage,
36
39
  stats,
37
40
  testimonials,
38
41
  pricing,
39
- video,
40
42
  media,
41
43
  faq,
42
44
  cta,
@@ -0,0 +1,128 @@
1
+ ---
2
+ import type { Section } from '../definitions'
3
+ import Typography from '../../atoms/Typography.astro'
4
+ import MediaFrame from '../../molecules/MediaFrame.astro'
5
+ import SectionHeader from '../../molecules/SectionHeader.astro'
6
+ import SectionShell from '../../molecules/SectionShell.astro'
7
+ import { isRemote, resolveLocalAsset } from '../../../lib/assets'
8
+ import { imageUrl } from '../../../lib/image-url'
9
+ import { cn } from '../../../lib/cn'
10
+
11
+ interface Props {
12
+ section: Extract<Section, { type: 'gallery' }>
13
+ index: number
14
+ motion?: boolean
15
+ }
16
+
17
+ const { section, index, motion = true } = Astro.props
18
+ const props = section.props
19
+ const field = (path: string) => `sections.${index}.props.${path}`
20
+ const reveal = section.motion ?? motion
21
+ const images = props.images.filter((image) => !image.hidden)
22
+ const featured = section.variant === 'featured'
23
+ const masonry = section.variant === 'masonry'
24
+
25
+ // Static class names, so Tailwind sees them.
26
+ const gridColumns = {
27
+ '2': 'grid-cols-1 @min-[560px]:grid-cols-2',
28
+ '3': 'grid-cols-1 @min-[560px]:grid-cols-2 @min-[900px]:grid-cols-3',
29
+ '4': 'grid-cols-2 @min-[700px]:grid-cols-3 @min-[1000px]:grid-cols-4',
30
+ } as const
31
+ const masonryColumns = {
32
+ '2': 'columns-1 @min-[560px]:columns-2',
33
+ '3': 'columns-1 @min-[560px]:columns-2 @min-[900px]:columns-3',
34
+ '4': 'columns-2 @min-[700px]:columns-3 @min-[1000px]:columns-4',
35
+ } as const
36
+
37
+ /** The index of an image in the section's full list, so the editor's field paths stay right when some are hidden. */
38
+ const pathIndex = (image: (typeof images)[number]) => props.images.indexOf(image)
39
+ const aspect = (position: number) => {
40
+ if (featured && position === 0) return 'aspect-[4/3] @min-[900px]:aspect-auto @min-[900px]:h-full'
41
+ if (masonry) return position % 3 === 0 ? 'aspect-[3/4]' : position % 3 === 1 ? 'aspect-[4/3]' : 'aspect-square'
42
+ return 'aspect-[4/3]'
43
+ }
44
+ const tileClass = (position: number) =>
45
+ cn(featured && position === 0 && '@min-[900px]:col-span-2 @min-[900px]:row-span-2', masonry && 'mb-4 break-inside-avoid')
46
+
47
+ /** A picture the lightbox can show: a real file or address, not the placeholder. */
48
+ const viewable = (src: string) => src !== 'placeholder' && (isRemote(src) || Boolean(resolveLocalAsset(src)) || src.replace(/^\//, '').startsWith('src/assets/'))
49
+
50
+ // The large file each link points at. With JavaScript off the link opens it; with JavaScript on it is what the lightbox loads.
51
+ const larges = await Promise.all(images.map((image) => (props.lightbox && viewable(image.src) ? imageUrl(image) : undefined)))
52
+ const lightbox = props.lightbox && larges.some(Boolean)
53
+ ---
54
+
55
+ <SectionShell id={section.id} anchor={section.anchor} type={section.type} variant={section.variant} tone={section.tone} motion={reveal}>
56
+ <div class="section-container flex flex-col gap-[clamp(2rem,4cqi,3.5rem)]">
57
+ <SectionHeader eyebrow={props.eyebrow} heading={props.heading} marks={props.marks} size="h2-md" field={field} class="gap-5" />
58
+ {props.body && <Typography as="div" size="lead" color="muted" class="max-w-[40rem]" data-field={field('body')} markdown={props.body} />}
59
+ <ul
60
+ class={cn(
61
+ masonry ? masonryColumns[props.columns] : gridColumns[props.columns],
62
+ masonry ? 'gap-x-4' : cn('grid gap-4', featured && '@min-[900px]:auto-rows-fr'),
63
+ )}
64
+ >
65
+ {
66
+ images.map((image, position) => {
67
+ const frame = (
68
+ <MediaFrame
69
+ src={image.src}
70
+ alt={image.alt}
71
+ aspectClass={aspect(position)}
72
+ fit={masonry ? 'auto' : image.fit}
73
+ position={image.position}
74
+ class={cn(props.frame && 'border border-line bg-surface', larges[position] && 'transition-transform duration-300 hover:scale-[1.01] motion-reduce:transition-none')}
75
+ data-field={field(`images.${pathIndex(image)}.alt`)}
76
+ />
77
+ )
78
+ return (
79
+ <li class={tileClass(position)}>
80
+ {larges[position] ? (
81
+ <a
82
+ href={larges[position]}
83
+ class="block size-full cursor-zoom-in rounded-card-lg focus-visible:outline-offset-2"
84
+ data-gallery-open
85
+ data-alt={image.alt}
86
+ data-caption={image.caption}
87
+ aria-label={`View larger: ${image.alt}`}
88
+ >
89
+ {frame}
90
+ </a>
91
+ ) : (
92
+ frame
93
+ )}
94
+ </li>
95
+ )
96
+ })
97
+ }
98
+ </ul>
99
+ </div>
100
+ {
101
+ lightbox && (
102
+ <dialog class="bm-lightbox" aria-label={props.heading ? `${props.heading}: pictures` : 'Pictures'} data-gallery-dialog>
103
+ <div class="bm-lightbox-stage" data-gallery-stage>
104
+ <button type="button" class="bm-lightbox-close" aria-label="Close" data-gallery-close>
105
+ <svg viewBox="0 0 24 24" aria-hidden="true" class="bm-lightbox-icon"><path d="M6 6l12 12M18 6L6 18" /></svg>
106
+ </button>
107
+ <p class="bm-lightbox-counter" data-gallery-counter aria-hidden="true" />
108
+ <button type="button" class="bm-lightbox-nav bm-lightbox-prev" aria-label="Previous picture" data-gallery-step="-1">
109
+ <svg viewBox="0 0 24 24" aria-hidden="true" class="bm-lightbox-icon"><path d="M14.5 5.5L8 12l6.5 6.5" /></svg>
110
+ </button>
111
+ <figure class="bm-lightbox-figure" data-gallery-figure>
112
+ <img class="bm-lightbox-image" alt="" data-gallery-image decoding="async" />
113
+ <figcaption class="bm-lightbox-caption" data-gallery-caption hidden />
114
+ </figure>
115
+ <button type="button" class="bm-lightbox-nav bm-lightbox-next" aria-label="Next picture" data-gallery-step="1">
116
+ <svg viewBox="0 0 24 24" aria-hidden="true" class="bm-lightbox-icon"><path d="M9.5 5.5L16 12l-6.5 6.5" /></svg>
117
+ </button>
118
+ <p class="sr-only" role="status" aria-live="polite" data-gallery-status />
119
+ </div>
120
+ </dialog>
121
+ )
122
+ }
123
+ </SectionShell>
124
+
125
+ <script>
126
+ import { initGalleries } from './lightbox'
127
+ initGalleries()
128
+ </script>
@@ -0,0 +1,24 @@
1
+ import { sectionArgTypes } from '../../../stories/options'
2
+ import { gallery } from './definition'
3
+ import Gallery from './Gallery.astro'
4
+
5
+ /** The sample pages hold no Gallery section, so the stories start from its defaults. */
6
+ const section = { id: 'gallery', type: 'gallery', variant: 'grid', tone: 'base', props: gallery.defaults } as const
7
+ const captioned = {
8
+ ...gallery.defaults,
9
+ images: gallery.defaults.images.map((image, index) => ({ ...image, caption: `Caption for picture ${index + 1}` })),
10
+ }
11
+
12
+ export default {
13
+ title: 'Sections/Gallery',
14
+ component: Gallery,
15
+ parameters: { layout: 'fullscreen' },
16
+ argTypes: sectionArgTypes('gallery'),
17
+ }
18
+
19
+ export const Grid = { args: { section, index: 0 } }
20
+ export const Masonry = { args: { section: { ...section, variant: 'masonry', props: { ...gallery.defaults, columns: '4' } }, index: 0 } }
21
+ export const Featured = { args: { section: { ...section, variant: 'featured', tone: 'subtle', props: captioned }, index: 0 } }
22
+ export const TwoColumns = { args: { section: { ...section, props: { ...gallery.defaults, columns: '2' } }, index: 0 } }
23
+ export const Framed = { args: { section: { ...section, props: { ...gallery.defaults, frame: true } }, index: 0 } }
24
+ export const NoLightbox = { args: { section: { ...section, props: { ...gallery.defaults, lightbox: false } }, index: 0 } }
@@ -0,0 +1,59 @@
1
+ import { z } from 'zod'
2
+ import { defineSection, imageSchema, richTextSchema, textSchema, withEmphasis } from 'bearminion'
3
+ import { accent, eyebrow, heading } from '../shared'
4
+ import { galleryWireframe } from './wireframe'
5
+
6
+ export const galleryVariants = ['grid', 'masonry', 'featured'] as const
7
+ export const galleryColumns = ['2', '3', '4'] as const
8
+
9
+ export const galleryCounts = { images: { recommended: '6 to 12', min: 1, max: 24 } } as const
10
+
11
+ /**
12
+ * A gallery picture needs a description: it is the only thing a screen reader or a failed load shows. The optional
13
+ * `caption` is for everyone else: it shows under the picture in the lightbox.
14
+ */
15
+ export const galleryImageSchema = imageSchema.extend({
16
+ alt: z.string().min(1, 'Describe the picture'),
17
+ caption: textSchema.optional(),
18
+ })
19
+
20
+ export const gallerySchema = withEmphasis({
21
+ eyebrow,
22
+ heading,
23
+ body: richTextSchema.optional(),
24
+ images: z.array(galleryImageSchema).min(galleryCounts.images.min).max(galleryCounts.images.max),
25
+ /** Pictures per row on a wide screen. Fewer on narrow ones. */
26
+ columns: z.enum(galleryColumns).default('3'),
27
+ /** Off: pictures stay where they are. On: a click opens the picture large, with arrows to move through the rest. */
28
+ lightbox: z.boolean().default(true),
29
+ /** On: each picture sits in a bordered box, so a picture that does not fill its frame still shows where the frame ends. */
30
+ frame: z.boolean().default(false),
31
+ })
32
+
33
+ export type GalleryProps = z.infer<typeof gallerySchema>
34
+
35
+ export const gallery = defineSection({
36
+ type: 'gallery',
37
+ label: 'Gallery',
38
+ description: 'A set of pictures. Click one to see it large, with captions, arrows and swipe.',
39
+ schema: gallerySchema,
40
+ defaults: {
41
+ eyebrow: 'Gallery',
42
+ heading: 'A few pictures say it faster.',
43
+ marks: accent('A few pictures say it faster.', 'faster.'),
44
+ images: [1, 2, 3, 4, 5, 6].map((n) => ({ src: 'placeholder', alt: `Picture ${n}` })),
45
+ columns: '3',
46
+ lightbox: true,
47
+ frame: false,
48
+ },
49
+ variants: galleryVariants,
50
+ defaultVariant: 'grid',
51
+ options: [
52
+ { name: 'columns', label: 'Pictures per row', type: 'enum', choices: galleryColumns, default: '3' },
53
+ { name: 'lightbox', label: 'Open pictures large on click', type: 'boolean', default: true },
54
+ { name: 'frame', label: 'Draw a box around each picture', type: 'boolean', default: false },
55
+ ],
56
+ optional: { props: ['eyebrow', 'heading', 'body'], items: { images: ['caption'] } },
57
+ counts: galleryCounts,
58
+ wireframe: galleryWireframe,
59
+ })