bearminion 1.7.0 → 1.9.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 (92) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/astro.d.ts +2 -2
  3. package/dist/astro.js +17 -5
  4. package/dist/cli.d.ts +1 -0
  5. package/dist/cli.js +819 -0
  6. package/dist/content.d.ts +1 -1
  7. package/dist/content.js +2 -2
  8. package/dist/hash-BeBymBO1.js +59 -0
  9. package/dist/index.d.ts +2 -2
  10. package/dist/index.js +4 -4
  11. package/dist/marks-DPBilumg.js +174 -0
  12. package/dist/marks.js +1 -174
  13. package/dist/{options-BeJQnsZM.d.ts → options-4HWVEj9O.d.ts} +7 -1
  14. package/dist/{page-BfI9cD8g.d.ts → page-CA4iyFDS.d.ts} +7 -7
  15. package/dist/{page-NOFVEqn1.js → page-X-WnOu7-.js} +1 -1
  16. package/dist/{preview--S1QUrMM.js → preview-B_88I5Jm.js} +1 -1
  17. package/dist/{reload-BPkPoQ-P.js → reload-Dkp3xC0l.js} +1 -1
  18. package/dist/rich-text-70hddxMC.js +403 -0
  19. package/dist/rich-text.js +1 -403
  20. package/dist/sections-manifest-CO9QfJPG.js +97 -0
  21. package/dist/{theme-DFjHjgFO.js → theme-Dv7_7B56.js} +2 -2
  22. package/dist/ui/mount.js +20 -7
  23. package/package.json +7 -1
  24. package/registry/default/files/src/components/atoms/Button.astro +64 -0
  25. package/registry/default/files/src/components/atoms/Emphasis.astro +24 -0
  26. package/registry/default/files/src/components/atoms/Image.astro +78 -0
  27. package/registry/default/files/src/components/atoms/Typography.astro +53 -0
  28. package/registry/default/files/src/components/atoms/button.ts +31 -0
  29. package/registry/default/files/src/components/atoms/image.ts +34 -0
  30. package/registry/default/files/src/components/atoms/options.ts +39 -0
  31. package/registry/default/files/src/components/atoms/typography.ts +64 -0
  32. package/registry/default/files/src/components/molecules/CommandLine.astro +109 -0
  33. package/registry/default/files/src/components/molecules/MediaFrame.astro +71 -0
  34. package/registry/default/files/src/components/molecules/Pill.astro +24 -0
  35. package/registry/default/files/src/components/molecules/SectionHeader.astro +63 -0
  36. package/registry/default/files/src/components/molecules/SectionShell.astro +33 -0
  37. package/registry/default/files/src/components/sections/contact/Contact.astro +231 -0
  38. package/registry/default/files/src/components/sections/contact/definition.ts +52 -0
  39. package/registry/default/files/src/components/sections/contact/form.ts +313 -0
  40. package/registry/default/files/src/components/sections/contact/wireframe.ts +15 -0
  41. package/registry/default/files/src/components/sections/cta/Cta.astro +206 -0
  42. package/registry/default/files/src/components/sections/cta/definition.ts +49 -0
  43. package/registry/default/files/src/components/sections/cta/wireframe.ts +9 -0
  44. package/registry/default/files/src/components/sections/faq/Faq.astro +136 -0
  45. package/registry/default/files/src/components/sections/faq/definition.ts +54 -0
  46. package/registry/default/files/src/components/sections/faq/wireframe.ts +19 -0
  47. package/registry/default/files/src/components/sections/features/Features.astro +146 -0
  48. package/registry/default/files/src/components/sections/features/definition.ts +54 -0
  49. package/registry/default/files/src/components/sections/features/wireframe.ts +19 -0
  50. package/registry/default/files/src/components/sections/gallery/Gallery.astro +128 -0
  51. package/registry/default/files/src/components/sections/gallery/definition.ts +59 -0
  52. package/registry/default/files/src/components/sections/gallery/lightbox.ts +159 -0
  53. package/registry/default/files/src/components/sections/gallery/wireframe.ts +12 -0
  54. package/registry/default/files/src/components/sections/hero/Hero.astro +185 -0
  55. package/registry/default/files/src/components/sections/hero/HeroBadge.astro +26 -0
  56. package/registry/default/files/src/components/sections/hero/definition.ts +74 -0
  57. package/registry/default/files/src/components/sections/hero/wireframe.ts +12 -0
  58. package/registry/default/files/src/components/sections/logo-strip/LogoStrip.astro +107 -0
  59. package/registry/default/files/src/components/sections/logo-strip/definition.ts +30 -0
  60. package/registry/default/files/src/components/sections/logo-strip/wireframe.ts +11 -0
  61. package/registry/default/files/src/components/sections/media/Media.astro +118 -0
  62. package/registry/default/files/src/components/sections/media/MediaPlayer.astro +176 -0
  63. package/registry/default/files/src/components/sections/media/definition.ts +77 -0
  64. package/registry/default/files/src/components/sections/media/source.ts +3 -0
  65. package/registry/default/files/src/components/sections/media/wireframe.ts +9 -0
  66. package/registry/default/files/src/components/sections/pricing/Pricing.astro +210 -0
  67. package/registry/default/files/src/components/sections/pricing/definition.ts +62 -0
  68. package/registry/default/files/src/components/sections/pricing/wireframe.ts +18 -0
  69. package/registry/default/files/src/components/sections/shared.ts +13 -0
  70. package/registry/default/files/src/components/sections/stats/Stats.astro +110 -0
  71. package/registry/default/files/src/components/sections/stats/definition.ts +41 -0
  72. package/registry/default/files/src/components/sections/stats/wireframe.ts +15 -0
  73. package/registry/default/files/src/components/sections/steps/Steps.astro +139 -0
  74. package/registry/default/files/src/components/sections/steps/definition.ts +62 -0
  75. package/registry/default/files/src/components/sections/steps/icons.ts +27 -0
  76. package/registry/default/files/src/components/sections/steps/wireframe.ts +16 -0
  77. package/registry/default/files/src/components/sections/testimonials/Testimonials.astro +172 -0
  78. package/registry/default/files/src/components/sections/testimonials/definition.ts +42 -0
  79. package/registry/default/files/src/components/sections/testimonials/wireframe.ts +21 -0
  80. package/registry/default/files/src/components/sections/text/Text.astro +43 -0
  81. package/registry/default/files/src/components/sections/text/definition.ts +36 -0
  82. package/registry/default/files/src/components/sections/text/wireframe.ts +12 -0
  83. package/registry/default/files/src/components/sections/text-image/TextImage.astro +107 -0
  84. package/registry/default/files/src/components/sections/text-image/definition.ts +39 -0
  85. package/registry/default/files/src/components/sections/text-image/wireframe.ts +12 -0
  86. package/registry/default/files/src/lib/assets.ts +13 -0
  87. package/registry/default/files/src/lib/cn.ts +6 -0
  88. package/registry/default/files/src/lib/contact-form.ts +97 -0
  89. package/registry/default/files/src/lib/hidden-text.ts +32 -0
  90. package/registry/default/files/src/lib/image-url.ts +38 -0
  91. package/registry/default/files/src/lib/link-attrs.ts +74 -0
  92. package/registry/default/registry.json +670 -0
@@ -0,0 +1,231 @@
1
+ ---
2
+ import type { Section } from '../definitions'
3
+ import Button from '../../atoms/Button.astro'
4
+ import Emphasis from '../../atoms/Emphasis.astro'
5
+ import Typography from '../../atoms/Typography.astro'
6
+ import SectionHeader from '../../molecules/SectionHeader.astro'
7
+ import SectionShell from '../../molecules/SectionShell.astro'
8
+ import { HIDDEN_FALLBACK, hide } from '../../../lib/hidden-text'
9
+
10
+ interface Props {
11
+ section: Extract<Section, { type: 'contact' }>
12
+ index: number
13
+ motion?: boolean
14
+ }
15
+
16
+ const { section, index, motion = true } = Astro.props
17
+ const props = section.props
18
+ const field = (path: string) => `sections.${index}.props.${path}`
19
+ const reveal = section.motion ?? motion
20
+ const formId = `contact-form-${section.id}`
21
+ // A detail marked "hide from crawlers" is written into the HTML scrambled, and form.ts puts the value back in the browser.
22
+ const hidden = (detail: { value: string; hideFromCrawlers?: boolean | undefined }) =>
23
+ detail.hideFromCrawlers ? { 'data-hidden-value': hide(detail.value) } : {}
24
+ const shown = (detail: { value: string; hideFromCrawlers?: boolean | undefined }) => (detail.hideFromCrawlers ? HIDDEN_FALLBACK : detail.value)
25
+ // The form always posts to /api/contact, where the site's own handler (src/forms/contact.ts) answers. The public
26
+ // Turnstile site key comes from the environment at build time, so it never lives in the content files.
27
+ const turnstileKey: string | undefined = import.meta.env.PUBLIC_TURNSTILE_SITE_KEY || undefined
28
+ const formAttrs = {
29
+ 'data-form-id': section.id,
30
+ 'data-turnstile-key': turnstileKey,
31
+ action: '/api/contact',
32
+ method: 'post',
33
+ }
34
+ ---
35
+
36
+ <SectionShell id={section.id} anchor={section.anchor} type={section.type} variant={section.variant} tone={section.tone} motion={reveal}>
37
+ {
38
+ section.variant === 'split' && (
39
+ <div class="section-container grid items-start gap-12 @min-[880px]:grid-cols-[minmax(22rem,0.85fr)_minmax(0,1.15fr)]" data-contact>
40
+ <div>
41
+ <SectionHeader eyebrow={props.eyebrow} heading={props.heading} marks={props.marks} field={field} />
42
+ {props.body && <Typography as="p" size="lead" color="muted" class="mt-5" data-field={field('body')} markdown={props.body} />}
43
+ {
44
+ props.details.length > 0 && (
45
+ <dl class="mt-8 flex flex-col">
46
+ {props.details.map((detail, detailIndex) => (
47
+ <div class="grid grid-cols-[7rem_1fr] gap-4 border-t border-[var(--line)] py-4">
48
+ <dt class="font-mono text-[0.75rem] tracking-[0.06em] text-muted uppercase" data-field={field(`details.${detailIndex}.label`)}>
49
+ {detail.label}
50
+ </dt>
51
+ <dd data-field={field(`details.${detailIndex}.value`)} {...hidden(detail)}>{shown(detail)}</dd>
52
+ </div>
53
+ ))}
54
+ </dl>
55
+ )
56
+ }
57
+ </div>
58
+ <div class="rounded-panel bg-surface p-6 ring-line @min-[700px]:p-8">
59
+ <form id={formId} class="grid gap-4 @min-[700px]:grid-cols-2" data-contact-form {...formAttrs} novalidate>
60
+ <input type="hidden" name="formId" value={section.id} />
61
+ <label class="flex flex-col gap-2 text-[0.8125rem]">
62
+ Name
63
+ <input class="bm-field" name="name" required autocomplete="name" />
64
+ </label>
65
+ <label class="flex flex-col gap-2 text-[0.8125rem]">
66
+ Email
67
+ <input class="bm-field" type="email" name="email" required autocomplete="email" />
68
+ </label>
69
+ {
70
+ props.topics.length > 0 && (
71
+ <label class="flex flex-col gap-2 text-[0.8125rem] @min-[700px]:col-span-2">
72
+ Topic
73
+ <select class="bm-field" name="topic" required>
74
+ {props.topics.map((topic) => (
75
+ <option value={topic}>{topic}</option>
76
+ ))}
77
+ </select>
78
+ </label>
79
+ )
80
+ }
81
+ <label class="flex flex-col gap-2 text-[0.8125rem] @min-[700px]:col-span-2">
82
+ Message
83
+ <textarea class="bm-field h-32 py-3" name="message" required></textarea>
84
+ </label>
85
+ <div class="absolute -left-[9999px] size-px overflow-hidden" aria-hidden="true">
86
+ <label>
87
+ Leave this field empty
88
+ <input name="_gotcha" tabindex="-1" autocomplete="off" />
89
+ </label>
90
+ </div>
91
+ {turnstileKey && <div class="@min-[700px]:col-span-2" data-turnstile-widget></div>}
92
+ <div class="@min-[700px]:col-span-2">
93
+ <Button type="submit">Send message</Button>
94
+ {props.note && <Typography as="p" size="small" color="muted" class="mt-3" data-field={field('note')} markdown={props.note} />}
95
+ </div>
96
+ </form>
97
+ <div id={`${section.id}-sent`} data-contact-success tabindex="-1">
98
+ <p class="text-[1.5rem] font-semibold tracking-[-0.03em]">Message sent.</p>
99
+ {props.thanks && <Typography as="p" size="body" color="muted" class="mt-3" data-field={field('thanks')} markdown={props.thanks} />}
100
+ <Button type="button" variant="secondary" class="mt-6" data-contact-reset>
101
+ Send another
102
+ </Button>
103
+ </div>
104
+ <p id={`${section.id}-failed`} class="bm-form-error mt-4" data-contact-failed role="alert">The message was not sent. Try again, or reach us another way.</p>
105
+ </div>
106
+ </div>
107
+ )
108
+ }
109
+ {
110
+ section.variant === 'card' && (
111
+ <div class="section-container" data-contact>
112
+ <SectionHeader eyebrow={props.eyebrow} heading={props.heading} marks={props.marks} intro={props.body} introField="body" align="center" field={field} class="mx-auto max-w-2xl" />
113
+ <div class="mx-auto mt-10 max-w-[42rem] rounded-panel bg-surface p-6 ring-line @min-[700px]:p-8">
114
+ <form id={formId} class="grid gap-4 @min-[700px]:grid-cols-2" data-contact-form {...formAttrs} novalidate>
115
+ <input type="hidden" name="formId" value={section.id} />
116
+ <label class="flex flex-col gap-2 text-[0.8125rem]">
117
+ Name
118
+ <input class="bm-field" name="name" required autocomplete="name" />
119
+ </label>
120
+ <label class="flex flex-col gap-2 text-[0.8125rem]">
121
+ Email
122
+ <input class="bm-field" type="email" name="email" required autocomplete="email" />
123
+ </label>
124
+ {
125
+ props.topics.length > 0 && (
126
+ <div class="@min-[700px]:col-span-2">
127
+ <p class="mb-2 text-[0.8125rem]">Topic</p>
128
+ <div class="flex flex-wrap gap-2" data-topics>
129
+ {props.topics.map((topic, topicIndex) => (
130
+ <button type="button" class="h-10 rounded-full px-4 text-[0.875rem] ring-line" data-topic aria-pressed={topicIndex === 0 ? 'true' : 'false'}>
131
+ {topic}
132
+ </button>
133
+ ))}
134
+ </div>
135
+ <input type="hidden" name="topic" value={props.topics[0]} data-topic-input required />
136
+ </div>
137
+ )
138
+ }
139
+ <label class="flex flex-col gap-2 text-[0.8125rem] @min-[700px]:col-span-2">
140
+ Message
141
+ <textarea class="bm-field h-32 py-3" name="message" required></textarea>
142
+ </label>
143
+ <div class="absolute -left-[9999px] size-px overflow-hidden" aria-hidden="true">
144
+ <label>
145
+ Leave this field empty
146
+ <input name="_gotcha" tabindex="-1" autocomplete="off" />
147
+ </label>
148
+ </div>
149
+ {turnstileKey && <div class="@min-[700px]:col-span-2" data-turnstile-widget></div>}
150
+ <div class="@min-[700px]:col-span-2">
151
+ <Button type="submit" class="w-full">Send message</Button>
152
+ {props.note && <Typography as="p" size="small" color="muted" class="mt-3 text-center" data-field={field('note')} markdown={props.note} />}
153
+ </div>
154
+ </form>
155
+ <div id={`${section.id}-sent`} data-contact-success tabindex="-1">
156
+ <p class="text-[1.5rem] font-semibold tracking-[-0.03em]">Message sent.</p>
157
+ {props.thanks && <Typography as="p" size="body" color="muted" class="mt-3" data-field={field('thanks')} markdown={props.thanks} />}
158
+ <Button type="button" variant="secondary" class="mt-6" data-contact-reset>
159
+ Send another
160
+ </Button>
161
+ </div>
162
+ <p id={`${section.id}-failed`} class="bm-form-error mt-4" data-contact-failed role="alert">The message was not sent. Try again, or reach us another way.</p>
163
+ </div>
164
+ </div>
165
+ )
166
+ }
167
+ {
168
+ section.variant === 'minimal' && (
169
+ <div class="section-container" data-contact>
170
+ {
171
+ props.heading && (
172
+ <h2 class="max-w-[12ch] text-[clamp(2.75rem,1rem+6cqi,7rem)] leading-[0.92] font-semibold tracking-[-0.05em]">
173
+ <Emphasis heading={props.heading} marks={props.marks} data-field={field('heading')} />
174
+ </h2>
175
+ )
176
+ }
177
+ <form id={formId} class="mt-10 grid gap-8 @min-[760px]:grid-cols-2" data-contact-form {...formAttrs} novalidate>
178
+ <input type="hidden" name="formId" value={section.id} />
179
+ <label class="flex flex-col gap-2">
180
+ <span class="font-mono text-[0.75rem] tracking-[0.08em] text-muted uppercase">Name</span>
181
+ <input class="bm-underline" name="name" required autocomplete="name" />
182
+ </label>
183
+ <label class="flex flex-col gap-2">
184
+ <span class="font-mono text-[0.75rem] tracking-[0.08em] text-muted uppercase">Email</span>
185
+ <input class="bm-underline" type="email" name="email" required autocomplete="email" />
186
+ </label>
187
+ <label class="flex flex-col gap-2 @min-[760px]:col-span-2">
188
+ <span class="font-mono text-[0.75rem] tracking-[0.08em] text-muted uppercase">Message</span>
189
+ <textarea class="bm-underline" name="message" required rows="3"></textarea>
190
+ </label>
191
+ <div class="absolute -left-[9999px] size-px overflow-hidden" aria-hidden="true">
192
+ <label>
193
+ Leave this field empty
194
+ <input name="_gotcha" tabindex="-1" autocomplete="off" />
195
+ </label>
196
+ </div>
197
+ {turnstileKey && <div class="@min-[760px]:col-span-2" data-turnstile-widget></div>}
198
+ <div class="flex flex-wrap items-end justify-between gap-6 @min-[760px]:col-span-2">
199
+ {
200
+ props.details.length > 0 && (
201
+ <dl class="flex flex-wrap gap-x-8 gap-y-3">
202
+ {props.details.map((detail, detailIndex) => (
203
+ <div>
204
+ <dt class="font-mono text-[0.6875rem] tracking-[0.08em] text-muted uppercase" data-field={field(`details.${detailIndex}.label`)}>{detail.label}</dt>
205
+ <dd class="mt-1" data-field={field(`details.${detailIndex}.value`)} {...hidden(detail)}>{shown(detail)}</dd>
206
+ </div>
207
+ ))}
208
+ </dl>
209
+ )
210
+ }
211
+ <Button type="submit">Send</Button>
212
+ </div>
213
+ </form>
214
+ <div id={`${section.id}-sent`} data-contact-success tabindex="-1">
215
+ <p class="text-[clamp(2rem,1rem+3cqi,3.5rem)] leading-[0.95] font-semibold tracking-[-0.04em]">Message sent.</p>
216
+ {props.thanks && <Typography as="p" size="body" color="muted" class="mt-4" data-field={field('thanks')} markdown={props.thanks} />}
217
+ <Button type="button" variant="secondary" class="mt-6" data-contact-reset>
218
+ Send another
219
+ </Button>
220
+ </div>
221
+ <p id={`${section.id}-failed`} class="bm-form-error mt-4" data-contact-failed role="alert">The message was not sent. Try again, or reach us another way.</p>
222
+ </div>
223
+ )
224
+ }
225
+ </SectionShell>
226
+
227
+ <script>
228
+ import { bindContacts } from './form'
229
+ bindContacts()
230
+ document.addEventListener('bearminion:preview', bindContacts)
231
+ </script>
@@ -0,0 +1,52 @@
1
+ import { z } from 'zod'
2
+ import { defineSection, richTextSchema, textSchema, withEmphasis } from 'bearminion'
3
+ import { accent, eyebrow, heading } from '../shared'
4
+ import { contactWireframe } from './wireframe'
5
+
6
+ export const contactVariants = ['split', 'card', 'minimal'] as const
7
+
8
+ export const contactDetailSchema = z
9
+ .object({
10
+ label: textSchema,
11
+ value: textSchema,
12
+ // The built page carries the value scrambled and a few lines of script show it, so a crawler that only reads the HTML finds none.
13
+ hideFromCrawlers: z.boolean().optional(),
14
+ })
15
+ .strict()
16
+
17
+ export const contactSchema = withEmphasis({
18
+ eyebrow,
19
+ heading,
20
+ body: richTextSchema.optional(),
21
+ details: z.array(contactDetailSchema),
22
+ topics: z.array(textSchema),
23
+ note: richTextSchema.optional(),
24
+ thanks: richTextSchema.optional(),
25
+ })
26
+
27
+ export type ContactDetail = z.infer<typeof contactDetailSchema>
28
+ export type ContactProps = z.infer<typeof contactSchema>
29
+
30
+ export const contact = defineSection({
31
+ type: 'contact',
32
+ label: 'Contact',
33
+ description: 'Contact details beside a form.',
34
+ schema: contactSchema,
35
+ defaults: {
36
+ eyebrow: 'Contact',
37
+ heading: 'Get in touch.',
38
+ marks: accent('Get in touch.', 'in touch.'),
39
+ body: 'Tell people what they can contact you about and when they will hear back.',
40
+ details: [{ label: 'Email', value: 'hello@example.com', hideFromCrawlers: false }],
41
+ topics: ['General'],
42
+ note: 'We only use your details to reply to you.',
43
+ thanks: 'Thanks, your message is on its way.',
44
+ },
45
+ variants: contactVariants,
46
+ defaultVariant: 'split',
47
+ // The form posts to /api/contact: the handler is `src/forms/contact.ts`, written in code, never configured here.
48
+ form: 'contact',
49
+ optional: { props: ['eyebrow', 'heading', 'body', 'note', 'thanks'], items: { details: ['hideFromCrawlers'] } },
50
+ counts: { details: { recommended: 3 }, topics: { recommended: 3 } },
51
+ wireframe: contactWireframe,
52
+ })
@@ -0,0 +1,313 @@
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
+ import { reveal } from '../../../lib/hidden-text'
12
+
13
+ /**
14
+ * Wires every Contact form on the page: the states idle, sending, sent and error, field errors under their fields,
15
+ * a message the visitor closes themselves when something went wrong, the spam trap and Cloudflare Turnstile. The
16
+ * message goes to `/api/contact` as JSON. With JavaScript off the browser posts the form there itself and leaves the
17
+ * page; there is no status handling in that case.
18
+ */
19
+
20
+ const FIELD_ERROR = 'data-field-error'
21
+
22
+ function clearFieldErrors(form: HTMLFormElement) {
23
+ for (const note of form.querySelectorAll(`[${FIELD_ERROR}]`)) note.remove()
24
+ for (const control of form.querySelectorAll('[aria-invalid]')) {
25
+ control.removeAttribute('aria-invalid')
26
+ control.removeAttribute('aria-describedby')
27
+ }
28
+ }
29
+
30
+ /** Puts each message under the field it names. Returns the first control marked, so focus can go there. */
31
+ function showFieldErrors(form: HTMLFormElement, errors: Readonly<Record<string, string>>): HTMLElement | null {
32
+ let first: HTMLElement | null = null
33
+ let count = 0
34
+ for (const [name, message] of Object.entries(errors)) {
35
+ const control = form.elements.namedItem(name)
36
+ if (!(control instanceof HTMLInputElement || control instanceof HTMLTextAreaElement || control instanceof HTMLSelectElement)) continue
37
+ if (control.type === 'hidden') continue
38
+ const note = document.createElement('p')
39
+ note.className = 'bm-form-error'
40
+ note.setAttribute(FIELD_ERROR, '')
41
+ note.id = `${form.id || 'contact-form'}-error-${count++}`
42
+ note.textContent = message
43
+ const holder = control.closest('label') ?? control.parentElement ?? form
44
+ holder.append(note)
45
+ control.setAttribute('aria-invalid', 'true')
46
+ control.setAttribute('aria-describedby', note.id)
47
+ first ??= control
48
+ }
49
+ return first
50
+ }
51
+
52
+ /**
53
+ * A failed send is shown in a message that stays until the visitor closes it. It does not fade: an error that
54
+ * disappears on its own is an error nobody finishes reading. One per form; a new one replaces the old.
55
+ */
56
+ function toastRegion(): HTMLElement {
57
+ const existing = document.querySelector<HTMLElement>('[data-bm-toasts]')
58
+ if (existing) return existing
59
+ const region = document.createElement('div')
60
+ region.className = 'bm-toasts'
61
+ region.setAttribute('data-bm-toasts', '')
62
+ // In the top layer, so nothing on the page (or the editor in `astro dev`) can sit over the close button.
63
+ region.setAttribute('popover', 'manual')
64
+ document.body.append(region)
65
+ return region
66
+ }
67
+
68
+ function raise(region: HTMLElement) {
69
+ try {
70
+ if (!region.matches(':popover-open')) region.showPopover()
71
+ } catch {
72
+ // No popover support: the fixed position and z-index in the stylesheet still show it.
73
+ }
74
+ }
75
+
76
+ function closeToast(owner: string) {
77
+ for (const toast of toastRegion().querySelectorAll('[data-toast-for]')) {
78
+ if (toast.getAttribute('data-toast-for') === owner) toast.remove()
79
+ }
80
+ }
81
+
82
+ function showToast(owner: string, message: string) {
83
+ closeToast(owner)
84
+ const toast = document.createElement('div')
85
+ toast.className = 'bm-toast'
86
+ toast.setAttribute('role', 'alert')
87
+ toast.setAttribute('data-toast-for', owner)
88
+ const text = document.createElement('p')
89
+ text.className = 'bm-toast-text'
90
+ text.textContent = message
91
+ const close = document.createElement('button')
92
+ close.type = 'button'
93
+ close.className = 'bm-toast-close'
94
+ close.setAttribute('aria-label', 'Dismiss message')
95
+ close.textContent = '×'
96
+ close.addEventListener('click', () => toast.remove())
97
+ toast.append(text, close)
98
+ const region = toastRegion()
99
+ region.append(toast)
100
+ raise(region)
101
+ }
102
+
103
+ /** The part of Cloudflare's script the form uses. */
104
+ interface TurnstileApi {
105
+ render(container: HTMLElement, options: Record<string, unknown>): string | undefined
106
+ reset(widgetId?: string): void
107
+ }
108
+
109
+ const TURNSTILE_SCRIPT = 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit'
110
+ let turnstileScript: Promise<TurnstileApi> | undefined
111
+
112
+ function loadTurnstile(): Promise<TurnstileApi> {
113
+ const present = (window as unknown as { turnstile?: TurnstileApi }).turnstile
114
+ if (present) return Promise.resolve(present)
115
+ turnstileScript ??= new Promise<TurnstileApi>((resolve, reject) => {
116
+ const script = document.createElement('script')
117
+ script.src = TURNSTILE_SCRIPT
118
+ script.async = true
119
+ script.onload = () => {
120
+ const api = (window as unknown as { turnstile?: TurnstileApi }).turnstile
121
+ if (api) resolve(api)
122
+ else reject(new Error('Turnstile did not load.'))
123
+ }
124
+ script.onerror = () => {
125
+ turnstileScript = undefined
126
+ reject(new Error('Turnstile is blocked.'))
127
+ }
128
+ document.head.append(script)
129
+ })
130
+ return turnstileScript
131
+ }
132
+
133
+ interface TurnstileWidget {
134
+ /** The current token, or an empty string while there is none. */
135
+ token: string
136
+ /** The widget reported an error, or its script never loaded. */
137
+ failed: boolean
138
+ /** A token works once. Ask for a new one after every send. */
139
+ reset: () => void
140
+ }
141
+
142
+ function mountTurnstile(container: HTMLElement, siteKey: string): TurnstileWidget {
143
+ const widget: TurnstileWidget = { token: '', failed: false, reset: () => undefined }
144
+ loadTurnstile().then(
145
+ (api) => {
146
+ const id = api.render(container, {
147
+ sitekey: siteKey,
148
+ // The token is added to the request by the form script, not as a hidden field.
149
+ 'response-field': false,
150
+ callback: (token: string) => {
151
+ widget.token = token
152
+ widget.failed = false
153
+ },
154
+ 'expired-callback': () => {
155
+ widget.token = ''
156
+ },
157
+ 'error-callback': () => {
158
+ widget.token = ''
159
+ widget.failed = true
160
+ },
161
+ })
162
+ widget.reset = () => {
163
+ widget.token = ''
164
+ api.reset(id)
165
+ }
166
+ },
167
+ () => {
168
+ widget.failed = true
169
+ },
170
+ )
171
+ return widget
172
+ }
173
+
174
+ function bind(root: HTMLElement) {
175
+ if (root.dataset.bound === 'true') return
176
+ root.dataset.bound = 'true'
177
+ const form = root.querySelector('[data-contact-form]')
178
+ const success = root.querySelector('[data-contact-success]')
179
+ const reset = root.querySelector('[data-contact-reset]')
180
+ const topicInput = root.querySelector('[data-topic-input]')
181
+ if (!(form instanceof HTMLFormElement) || !(success instanceof HTMLElement)) return
182
+ const submit = form.querySelector('button[type="submit"]')
183
+ const label = submit?.textContent ?? ''
184
+ const owner = form.dataset.formId ?? form.id
185
+ // The clock for the "too fast" check starts when the form is on the page.
186
+ const openedAt = Date.now()
187
+
188
+ const container = form.querySelector('[data-turnstile-widget]')
189
+ const siteKey = form.dataset.turnstileKey
190
+ const turnstile = container instanceof HTMLElement && siteKey ? mountTurnstile(container, siteKey) : null
191
+
192
+ const busy = (on: boolean) => {
193
+ form.toggleAttribute('aria-busy', on)
194
+ if (!(submit instanceof HTMLButtonElement)) return
195
+ submit.disabled = on
196
+ submit.textContent = on ? 'Sending…' : label
197
+ }
198
+ const thanksLine = () => success.querySelector<HTMLElement>('[data-field$=".props.thanks"]')
199
+ const finish = (message?: string) => {
200
+ form.hidden = true
201
+ success.dataset.shown = ''
202
+ success.querySelector('[data-contact-message]')?.remove()
203
+ const thanks = thanksLine()
204
+ if (message) {
205
+ // The endpoint's own words replace the section's thank-you text. Plain text only.
206
+ const line = document.createElement('p')
207
+ line.setAttribute('data-contact-message', '')
208
+ line.className = thanks?.className ?? 'mt-3 text-muted'
209
+ line.textContent = message
210
+ if (thanks) thanks.hidden = true
211
+ success.querySelector('p')?.after(line)
212
+ } else if (thanks) {
213
+ thanks.hidden = false
214
+ }
215
+ success.focus({ preventScroll: true })
216
+ }
217
+ const failed = (message: string, field?: HTMLElement | null) => {
218
+ busy(false)
219
+ showToast(owner, message)
220
+ if (field) field.focus()
221
+ else if (submit instanceof HTMLButtonElement) submit.focus()
222
+ }
223
+
224
+ for (const chip of root.querySelectorAll('[data-topic]')) {
225
+ chip.addEventListener('click', () => {
226
+ for (const item of root.querySelectorAll('[data-topic]')) item.setAttribute('aria-pressed', 'false')
227
+ chip.setAttribute('aria-pressed', 'true')
228
+ if (topicInput instanceof HTMLInputElement) topicInput.value = chip.textContent?.trim() ?? ''
229
+ })
230
+ }
231
+
232
+ // A field marked wrong stops being marked as soon as it is edited.
233
+ form.addEventListener('input', (event) => {
234
+ const target = event.target
235
+ if (!(target instanceof HTMLElement) || target.getAttribute('aria-invalid') !== 'true') return
236
+ document.getElementById(target.getAttribute('aria-describedby') ?? '')?.remove()
237
+ target.removeAttribute('aria-invalid')
238
+ target.removeAttribute('aria-describedby')
239
+ })
240
+
241
+ form.addEventListener('submit', (event) => {
242
+ event.preventDefault()
243
+ if (!form.reportValidity()) return
244
+ clearFieldErrors(form)
245
+ closeToast(owner)
246
+ const trap = form.elements.namedItem('_gotcha')
247
+ const verdict = botVerdict(trap instanceof HTMLInputElement ? trap.value : '', openedAt, Date.now())
248
+ if (verdict) {
249
+ // A script filled the trap or submitted at once. Look as if it worked, and send nothing.
250
+ finish()
251
+ return
252
+ }
253
+ if (turnstile && turnstile.token === '') {
254
+ showToast(owner, turnstile.failed ? TURNSTILE_FAILED : TURNSTILE_PENDING)
255
+ return
256
+ }
257
+ const submission = collectSubmission(new FormData(form).entries(), owner, location.pathname)
258
+ if (turnstile) submission[TURNSTILE_FIELD] = turnstile.token
259
+ const request = buildRequest(submission)
260
+ busy(true)
261
+ void fetch(request.url, request.init).then(
262
+ async (response) => {
263
+ const body: unknown = await response.json().catch(() => undefined)
264
+ const result = readResponse(response.status, body)
265
+ // The token is spent whether the send worked or not.
266
+ turnstile?.reset()
267
+ if (result.ok) {
268
+ busy(false)
269
+ finish(result.message)
270
+ return
271
+ }
272
+ failed(result.error, result.fieldErrors ? showFieldErrors(form, result.fieldErrors) : null)
273
+ },
274
+ () => {
275
+ turnstile?.reset()
276
+ failed(NETWORK_ERROR)
277
+ },
278
+ )
279
+ })
280
+
281
+ reset?.addEventListener('click', () => {
282
+ form.reset()
283
+ clearFieldErrors(form)
284
+ closeToast(owner)
285
+ success.querySelector('[data-contact-message]')?.remove()
286
+ const thanks = thanksLine()
287
+ if (thanks) thanks.hidden = false
288
+ form.hidden = false
289
+ delete success.dataset.shown
290
+ })
291
+ }
292
+
293
+ /** Puts back the contact details the page was built without (`hideFromCrawlers`). The marker goes, so it runs once. */
294
+ function revealHidden(root: HTMLElement): void {
295
+ for (const element of root.querySelectorAll('[data-hidden-value]')) {
296
+ const hidden = element.getAttribute('data-hidden-value')
297
+ element.removeAttribute('data-hidden-value')
298
+ if (hidden === null) continue
299
+ try {
300
+ element.textContent = reveal(hidden)
301
+ } catch {
302
+ // A damaged value stays as the "turn on JavaScript" line rather than breaking the form.
303
+ }
304
+ }
305
+ }
306
+
307
+ export function bindContacts(): void {
308
+ for (const root of document.querySelectorAll('[data-contact]')) {
309
+ if (!(root instanceof HTMLElement)) continue
310
+ revealHidden(root)
311
+ bind(root)
312
+ }
313
+ }
@@ -0,0 +1,15 @@
1
+ import { defineWireframe } from 'bearminion'
2
+
3
+ /** Add section picker thumbnail: [left %, top %, width %, height %, kind]. */
4
+ export const contactWireframe = defineWireframe([
5
+ [8, 16, 30, 8, 'title'],
6
+ [8, 30, 34, 4, 'text'],
7
+ [8, 38, 28, 4, 'text'],
8
+ [8, 56, 22, 4, 'text'],
9
+ [8, 64, 26, 4, 'text'],
10
+ [52, 12, 40, 76, 'card'],
11
+ [56, 20, 32, 9, 'block'],
12
+ [56, 34, 32, 9, 'block'],
13
+ [56, 48, 32, 18, 'block'],
14
+ [56, 72, 14, 9, 'button'],
15
+ ])