create-bearminion 1.6.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # create-bearminion
2
2
 
3
+ ## 1.7.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 2978aaf: Run your own code behind the Contact form, with its keys on the server and in the environment. The new `bearminion/forms` entry has `defineForm(handler, options)`: put it in `src/forms/contact.ts` and add a few lines of glue for Vercel, Netlify, Cloudflare or an Astro endpoint (all in the Forms guide). The form always posts to `/api/contact`; nothing about it is stored in the content files. The handler receives the message and your environment, and returns nothing, `{ ok: true, message }`, `{ ok: false, error, fieldErrors }`, or throws a `FormError`; any other error becomes a plain "could not be delivered" for the visitor and goes to your log. It answers `POST` only, reads JSON, multipart and urlencoded posts, refuses posts over 64 KB and posts from other sites (`origins` lists the exceptions), and drops a filled trap field on the server too. It uses only `Request` and `Response`, so one file runs on every host. `astro dev` serves each file in `src/forms` at `/api/<name>`: a dry run that prints the message by default, and your handler for real with `BEARMINION_FORMS_LIVE=on` in `.env.local` (turn the route off with the `forms: false` option). Cloudflare Turnstile: set the public site key as `PUBLIC_TURNSTILE_SITE_KEY` where the site is built, and `defineForm(handler, { turnstile: true })` checks the token with `TURNSTILE_SECRET_KEY`; `verifyTurnstile` is exported too. A failed send now shows its error in a message at the bottom of the screen that stays until the visitor closes it. A handler's `{ ok: true, message }` replaces the thank-you text. The starter gets a `.env.example` listing those variables. The Forms guide is rewritten so you can set all of it up yourself.
8
+ - 2978aaf: The Contact form no longer says "Message sent." for a message that went nowhere. It posts with `fetch` to `/api/contact` and shows the states: sending, sent, an error from the handler, field errors under their fields, and no connection. A trap field and a 1.5 second minimum time drop what a script sends. While `src/forms/contact.ts` does not exist, `astro dev` and `astro build` print a warning (never an error), the section's settings in the editor show the same warning, and a visitor who sends the form gets an error. `bearminion` exports the types `FormSubmission` and `FormResult` for handlers you write yourself. `defineSection` takes a `form` option: the handler a section posts to, which the editor's sidebar reports on, and a new editor route `GET /forms` says whether its file exists. **Breaking for sites that set an endpoint:** the Contact section no longer has an `action` prop. Content version 3 drops `action` (and `format` and `turnstile`) from every Contact section, and the file is rewritten the next time it is saved. Copy a form service's address into a handler first: the Forms guide has complete files for Formspree and Web3Forms. New guide: Forms.
9
+
10
+ ### Patch Changes
11
+
12
+ - 2978aaf: Fixed an error in the browser console, "Cannot read properties of undefined (reading 'toLowerCase')", when the browser autofilled a form on a page with the editor. Autofill sends key events without a `key`, and the editor's keyboard shortcuts assumed one.
13
+ - 60cfb70: The Contact form works with JavaScript off. A browser that posts the form itself is no longer left on the raw JSON answer: `defineForm` redirects it back to the page, to a "Message sent." block or a "not sent" line (only when the `Referer` is on the same site; otherwise the JSON answer stays). Pages with section motion were also invisible without JavaScript, because sections start transparent and a script reveals them; they now show.
14
+ - 2978aaf: Fix: a video uploaded in the editor now plays in the dev site straight away. Vite learns which files `public/` holds from its file watcher, and the editor keeps the videos folder out of that watcher so uploads do not reload the page, so a new video answered 404 until `astro dev` was restarted. The editor now tells Vite about the one file that was added or removed. The template's `astro.config.ts` also reads `BEARMINION_VIDEOS_DIR` (used by the tests, like the content and uploads overrides).
15
+
3
16
  ## 1.6.0
4
17
 
5
18
  ### Minor Changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-bearminion",
3
- "version": "1.6.0",
3
+ "version": "1.7.0",
4
4
  "description": "Create a BearMinion site: an Astro website you edit by clicking on it. No database, no server.",
5
5
  "license": "MIT",
6
6
  "author": "Jakub Lange",
@@ -0,0 +1,18 @@
1
+ # Copy this file to .env (git keeps .env out of the repository) and fill in what you use.
2
+ # Nothing here is required: the site builds and runs without any of it.
3
+ # Guide: https://docs.bearminion.com/forms
4
+
5
+ # --- Cloudflare Turnstile, the spam check for the Contact form -------------------------------------------------------
6
+ # The site key is public. Astro reads it when the site is built, so set it where the site is built and rebuild after a change.
7
+ # The secret key stays on the server. Set both, or neither.
8
+ # To try it, Cloudflare publishes keys that always pass: site key 1x00000000000000000000AA, secret key 1x0000000000000000000000000000000AA
9
+ # PUBLIC_TURNSTILE_SITE_KEY=
10
+ # TURNSTILE_SECRET_KEY=
11
+
12
+ # --- Your form handler, src/forms/contact.ts ------------------------------------------------------------------------
13
+ # Whatever the handler reads from `env` (a service key, a webhook URL): add the names you use, and set the same names in your host's settings.
14
+
15
+ # --- astro dev -------------------------------------------------------------------------------------------------------
16
+ # While `astro dev` runs, /api/contact only prints the message (a dry run). Turn this on to run your handler for real.
17
+ # It fits .env.local better than .env, so nobody sends real messages by accident.
18
+ # BEARMINION_FORMS_LIVE=on
@@ -215,6 +215,12 @@ In dev and previews the banner and its choices work, and nothing is loaded or se
215
215
 
216
216
  A theme with its own layout needs three things: render the `template` elements and a banner element carrying `data-consent-banner` (hidden by default) with `data-consent-accept` and `data-consent-reject` buttons, put `data-consent-open` on any element that should reopen it, and import `initConsent` from the script. The default words come from `consentCopy(site.consent)`, which `bearminion` exports.
217
217
 
218
+ ## Contact form
219
+
220
+ The Contact section always posts to `/api/contact` and never shows "sent" for a message that went nowhere. Nothing about the form is stored in the content files: the handler is code in `src/forms/contact.ts`, and the public Turnstile site key is `PUBLIC_TURNSTILE_SITE_KEY` in the environment. `src/lib/contact-form.ts` holds the rules (what is sent, how an answer is read, the `_gotcha` trap and the 1.5 s minimum time) and `src/components/sections/contact/form.ts` wires them to the page: sending, sent, a failure shown in a message at the bottom of the screen that stays until the visitor closes it, field errors under their fields, the Cloudflare Turnstile widget when `PUBLIC_TURNSTILE_SITE_KEY` is set at build time, and a success `message` from the handler in place of the thank-you text. The page sends JSON. While `src/forms/contact.ts` does not exist, `astro dev` and `astro build` print a warning (`src/lib/form-check.ts`, wired in `astro.config.ts`) and the section's settings in the editor say so; it never fails the build.
221
+
222
+ The handler holds the keys that must stay private. Put `defineForm(...)` from `bearminion/forms` in `src/forms/contact.ts`; `astro dev` answers it at `/api/contact` (a dry run until `BEARMINION_FORMS_LIVE=on` is in `.env.local`), and a few lines of glue for Vercel, Netlify, Cloudflare or an Astro endpoint serve it once published. The template ships no `src/forms` folder and no server code, so the build stays static and warns until you add one. `.env.example` lists the environment variables the form uses (the Turnstile keys, `BEARMINION_FORMS_LIVE`); copy it to `.env`. `BEARMINION_VIDEOS_DIR` and `BEARMINION_FORMS_DIR` move the editor's video uploads and the dev forms folder for tests, like the content and uploads variables. See the [Forms guide](https://docs.bearminion.com/forms).
223
+
218
224
  ## Dev editor
219
225
 
220
226
  `astro.config.ts` registers `bearminion()`. It is active only while `pnpm dev` is running. The production build does not add editor routes, scripts, or the overlay.
@@ -1,4 +1,5 @@
1
1
  import path from 'node:path'
2
+ import { fileURLToPath } from 'node:url'
2
3
  import sitemap from '@astrojs/sitemap'
3
4
  import tailwindcss from '@tailwindcss/vite'
4
5
  import bearminion, { loadContent } from 'bearminion/astro'
@@ -6,6 +7,7 @@ import type { AstroIntegration } from 'astro'
6
7
  import { defineConfig } from 'astro/config'
7
8
  import { contentDirectory } from './src/lib/content-dir'
8
9
  import { contentModel } from './src/lib/content-model'
10
+ import { hasFormHandler, unhandledFormMessage, unhandledForms } from './src/lib/form-check'
9
11
  import { createSitemapFilter } from './src/lib/sitemap'
10
12
 
11
13
  const contentDir = contentDirectory()
@@ -24,6 +26,24 @@ const devPages: AstroIntegration = {
24
26
  },
25
27
  }
26
28
 
29
+ /** The folder with the site's form handlers. The Contact form posts to `/api/contact`, which `src/forms/contact.ts` answers. */
30
+ const formsDir = process.env.BEARMINION_FORMS_DIR
31
+ ? path.resolve(process.env.BEARMINION_FORMS_DIR)
32
+ : fileURLToPath(new URL('./src/forms', import.meta.url))
33
+
34
+ /** A form without a handler is a warning, not an error: a new site must still start and build. */
35
+ const formCheck: AstroIntegration = {
36
+ name: 'bearminion-site:form-check',
37
+ hooks: {
38
+ 'astro:server:start': ({ logger }) => {
39
+ for (const form of unhandledForms(content.pages, hasFormHandler(formsDir))) logger.warn(unhandledFormMessage(form))
40
+ },
41
+ 'astro:build:start': ({ logger }) => {
42
+ for (const form of unhandledForms(content.pages, hasFormHandler(formsDir))) logger.warn(unhandledFormMessage(form))
43
+ },
44
+ },
45
+ }
46
+
27
47
  export default defineConfig({
28
48
  site: content.site.url,
29
49
  integrations: [
@@ -34,11 +54,16 @@ export default defineConfig({
34
54
  uploadsDir: process.env.BEARMINION_UPLOADS_DIR
35
55
  ? path.resolve(process.env.BEARMINION_UPLOADS_DIR)
36
56
  : path.resolve(contentDir, '../src/assets/uploads'),
57
+ // Test isolation only, like the two overrides above: uploaded videos go to `public/videos` unless it is set.
58
+ ...(process.env.BEARMINION_VIDEOS_DIR ? { videosDir: path.resolve(process.env.BEARMINION_VIDEOS_DIR) } : {}),
59
+ // Test isolation only: the folder with the forms to serve in dev. Your forms live in `src/forms`.
60
+ ...(process.env.BEARMINION_FORMS_DIR ? { forms: { dir: path.resolve(process.env.BEARMINION_FORMS_DIR) } } : {}),
37
61
  }),
38
62
  sitemap({
39
63
  filter: createSitemapFilter(content.pages),
40
64
  }),
41
65
  devPages,
66
+ formCheck,
42
67
  ],
43
68
  vite: {
44
69
  plugins: [tailwindcss()],
@@ -19,7 +19,7 @@
19
19
  "@fontsource/jetbrains-mono": "^5.3.0",
20
20
  "@tailwindcss/vite": "^4.1.12",
21
21
  "astro": "^7.4.1",
22
- "bearminion": "^1.6.0",
22
+ "bearminion": "^1.7.0",
23
23
  "class-variance-authority": "^0.7.1",
24
24
  "sharp": "^0.35.5",
25
25
  "tailwind-merge": "^3.7.0",
@@ -17,6 +17,15 @@ const props = section.props
17
17
  const field = (path: string) => `sections.${index}.props.${path}`
18
18
  const reveal = section.motion ?? motion
19
19
  const formId = `contact-form-${section.id}`
20
+ // The form always posts to /api/contact, where the site's own handler (src/forms/contact.ts) answers. The public
21
+ // Turnstile site key comes from the environment at build time, so it never lives in the content files.
22
+ const turnstileKey: string | undefined = import.meta.env.PUBLIC_TURNSTILE_SITE_KEY || undefined
23
+ const formAttrs = {
24
+ 'data-form-id': section.id,
25
+ 'data-turnstile-key': turnstileKey,
26
+ action: '/api/contact',
27
+ method: 'post',
28
+ }
20
29
  ---
21
30
 
22
31
  <SectionShell id={section.id} anchor={section.anchor} type={section.type} variant={section.variant} tone={section.tone} motion={reveal}>
@@ -42,7 +51,8 @@ const formId = `contact-form-${section.id}`
42
51
  }
43
52
  </div>
44
53
  <div class="rounded-panel bg-surface p-6 ring-line @min-[700px]:p-8">
45
- <form id={formId} class="grid gap-4 @min-[700px]:grid-cols-2" data-contact-form action={props.action} method="post" novalidate>
54
+ <form id={formId} class="grid gap-4 @min-[700px]:grid-cols-2" data-contact-form {...formAttrs} novalidate>
55
+ <input type="hidden" name="formId" value={section.id} />
46
56
  <label class="flex flex-col gap-2 text-[0.8125rem]">
47
57
  Name
48
58
  <input class="bm-field" name="name" required autocomplete="name" />
@@ -67,18 +77,26 @@ const formId = `contact-form-${section.id}`
67
77
  Message
68
78
  <textarea class="bm-field h-32 py-3" name="message" required></textarea>
69
79
  </label>
80
+ <div class="absolute -left-[9999px] size-px overflow-hidden" aria-hidden="true">
81
+ <label>
82
+ Leave this field empty
83
+ <input name="_gotcha" tabindex="-1" autocomplete="off" />
84
+ </label>
85
+ </div>
86
+ {turnstileKey && <div class="@min-[700px]:col-span-2" data-turnstile-widget></div>}
70
87
  <div class="@min-[700px]:col-span-2">
71
88
  <Button type="submit">Send message</Button>
72
89
  {props.note && <Typography as="p" size="small" color="muted" class="mt-3" data-field={field('note')} markdown={props.note} />}
73
90
  </div>
74
91
  </form>
75
- <div data-contact-success hidden>
92
+ <div id={`${section.id}-sent`} data-contact-success tabindex="-1">
76
93
  <p class="text-[1.5rem] font-semibold tracking-[-0.03em]">Message sent.</p>
77
94
  {props.thanks && <Typography as="p" size="body" color="muted" class="mt-3" data-field={field('thanks')} markdown={props.thanks} />}
78
95
  <Button type="button" variant="secondary" class="mt-6" data-contact-reset>
79
96
  Send another
80
97
  </Button>
81
98
  </div>
99
+ <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>
82
100
  </div>
83
101
  </div>
84
102
  )
@@ -88,7 +106,8 @@ const formId = `contact-form-${section.id}`
88
106
  <div class="section-container" data-contact>
89
107
  <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" />
90
108
  <div class="mx-auto mt-10 max-w-[42rem] rounded-panel bg-surface p-6 ring-line @min-[700px]:p-8">
91
- <form id={formId} class="grid gap-4 @min-[700px]:grid-cols-2" data-contact-form action={props.action} method="post" novalidate>
109
+ <form id={formId} class="grid gap-4 @min-[700px]:grid-cols-2" data-contact-form {...formAttrs} novalidate>
110
+ <input type="hidden" name="formId" value={section.id} />
92
111
  <label class="flex flex-col gap-2 text-[0.8125rem]">
93
112
  Name
94
113
  <input class="bm-field" name="name" required autocomplete="name" />
@@ -116,18 +135,26 @@ const formId = `contact-form-${section.id}`
116
135
  Message
117
136
  <textarea class="bm-field h-32 py-3" name="message" required></textarea>
118
137
  </label>
138
+ <div class="absolute -left-[9999px] size-px overflow-hidden" aria-hidden="true">
139
+ <label>
140
+ Leave this field empty
141
+ <input name="_gotcha" tabindex="-1" autocomplete="off" />
142
+ </label>
143
+ </div>
144
+ {turnstileKey && <div class="@min-[700px]:col-span-2" data-turnstile-widget></div>}
119
145
  <div class="@min-[700px]:col-span-2">
120
146
  <Button type="submit" class="w-full">Send message</Button>
121
147
  {props.note && <Typography as="p" size="small" color="muted" class="mt-3 text-center" data-field={field('note')} markdown={props.note} />}
122
148
  </div>
123
149
  </form>
124
- <div data-contact-success hidden>
150
+ <div id={`${section.id}-sent`} data-contact-success tabindex="-1">
125
151
  <p class="text-[1.5rem] font-semibold tracking-[-0.03em]">Message sent.</p>
126
152
  {props.thanks && <Typography as="p" size="body" color="muted" class="mt-3" data-field={field('thanks')} markdown={props.thanks} />}
127
153
  <Button type="button" variant="secondary" class="mt-6" data-contact-reset>
128
154
  Send another
129
155
  </Button>
130
156
  </div>
157
+ <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>
131
158
  </div>
132
159
  </div>
133
160
  )
@@ -142,7 +169,8 @@ const formId = `contact-form-${section.id}`
142
169
  </h2>
143
170
  )
144
171
  }
145
- <form id={formId} class="mt-10 grid gap-8 @min-[760px]:grid-cols-2" data-contact-form action={props.action} method="post" novalidate>
172
+ <form id={formId} class="mt-10 grid gap-8 @min-[760px]:grid-cols-2" data-contact-form {...formAttrs} novalidate>
173
+ <input type="hidden" name="formId" value={section.id} />
146
174
  <label class="flex flex-col gap-2">
147
175
  <span class="font-mono text-[0.75rem] tracking-[0.08em] text-muted uppercase">Name</span>
148
176
  <input class="bm-underline" name="name" required autocomplete="name" />
@@ -155,6 +183,13 @@ const formId = `contact-form-${section.id}`
155
183
  <span class="font-mono text-[0.75rem] tracking-[0.08em] text-muted uppercase">Message</span>
156
184
  <textarea class="bm-underline" name="message" required rows="3"></textarea>
157
185
  </label>
186
+ <div class="absolute -left-[9999px] size-px overflow-hidden" aria-hidden="true">
187
+ <label>
188
+ Leave this field empty
189
+ <input name="_gotcha" tabindex="-1" autocomplete="off" />
190
+ </label>
191
+ </div>
192
+ {turnstileKey && <div class="@min-[760px]:col-span-2" data-turnstile-widget></div>}
158
193
  <div class="flex flex-wrap items-end justify-between gap-6 @min-[760px]:col-span-2">
159
194
  {
160
195
  props.details.length > 0 && (
@@ -171,57 +206,21 @@ const formId = `contact-form-${section.id}`
171
206
  <Button type="submit">Send</Button>
172
207
  </div>
173
208
  </form>
174
- <div data-contact-success hidden>
209
+ <div id={`${section.id}-sent`} data-contact-success tabindex="-1">
175
210
  <p class="text-[clamp(2rem,1rem+3cqi,3.5rem)] leading-[0.95] font-semibold tracking-[-0.04em]">Message sent.</p>
176
211
  {props.thanks && <Typography as="p" size="body" color="muted" class="mt-4" data-field={field('thanks')} markdown={props.thanks} />}
177
212
  <Button type="button" variant="secondary" class="mt-6" data-contact-reset>
178
213
  Send another
179
214
  </Button>
180
215
  </div>
216
+ <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>
181
217
  </div>
182
218
  )
183
219
  }
184
220
  </SectionShell>
185
221
 
186
222
  <script>
187
- function bindContact() {
188
- document.querySelectorAll('[data-contact]').forEach((root) => {
189
- if (!(root instanceof HTMLElement) || root.dataset.bound === 'true') return
190
- root.dataset.bound = 'true'
191
- const form = root.querySelector('[data-contact-form]')
192
- const success = root.querySelector('[data-contact-success]')
193
- const reset = root.querySelector('[data-contact-reset]')
194
- const topicInput = root.querySelector('[data-topic-input]')
195
- if (!(form instanceof HTMLFormElement) || !(success instanceof HTMLElement)) return
196
-
197
- root.querySelectorAll('[data-topic]').forEach((chip) => {
198
- chip.addEventListener('click', () => {
199
- root.querySelectorAll('[data-topic]').forEach((item) => {
200
- if (item instanceof HTMLButtonElement) item.setAttribute('aria-pressed', 'false')
201
- })
202
- if (chip instanceof HTMLButtonElement) chip.setAttribute('aria-pressed', 'true')
203
- if (topicInput instanceof HTMLInputElement) topicInput.value = chip.textContent?.trim() ?? ''
204
- })
205
- })
206
-
207
- form.addEventListener('submit', (event) => {
208
- if (!form.reportValidity()) {
209
- event.preventDefault()
210
- return
211
- }
212
- if (form.getAttribute('action')) return
213
- event.preventDefault()
214
- form.hidden = true
215
- success.hidden = false
216
- })
217
-
218
- reset?.addEventListener('click', () => {
219
- form.reset()
220
- form.hidden = false
221
- success.hidden = true
222
- })
223
- })
224
- }
225
- bindContact()
226
- document.addEventListener('bearminion:preview', bindContact)
223
+ import { bindContacts } from './form'
224
+ bindContacts()
225
+ document.addEventListener('bearminion:preview', bindContacts)
227
226
  </script>
@@ -20,8 +20,6 @@ export const contactSchema = withEmphasis({
20
20
  topics: z.array(textSchema),
21
21
  note: richTextSchema.optional(),
22
22
  thanks: richTextSchema.optional(),
23
- /** Form endpoint. The starter still shows a success state and does not post anywhere by default. */
24
- action: z.string().min(1).optional(),
25
23
  })
26
24
 
27
25
  export type ContactDetail = z.infer<typeof contactDetailSchema>
@@ -44,6 +42,8 @@ export const contact = defineSection({
44
42
  },
45
43
  variants: contactVariants,
46
44
  defaultVariant: 'split',
45
+ // The form posts to /api/contact: the handler is `src/forms/contact.ts`, written in code, never configured here.
46
+ form: 'contact',
47
47
  optional: { props: ['eyebrow', 'heading', 'body', 'note', 'thanks'] },
48
48
  counts: { details: { recommended: 3 }, topics: { recommended: 3 } },
49
49
  wireframe: contactWireframe,
@@ -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
+ }
@@ -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,7 +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 { migrateVideoToMedia } from './migrations'
4
+ import { migrateContactFormSettings, migrateVideoToMedia } from './migrations'
5
5
 
6
6
  /**
7
7
  * Everything the editor and the loaders need to know about this site's content: its section types
@@ -21,8 +21,9 @@ export const contentModel = {
21
21
  /**
22
22
  * Raise this when a schema change would reject files written before it, and add `migrations[n]`
23
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.
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`.
25
26
  */
26
- schemaVersion: 2,
27
- migrations: { 1: migrateVideoToMedia },
27
+ schemaVersion: 3,
28
+ migrations: { 1: migrateVideoToMedia, 2: migrateContactFormSettings },
28
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
+ }
@@ -25,3 +25,20 @@ export const migrateVideoToMedia: ContentMigration = (document, kind) => {
25
25
  sections: document.sections.map((section) => (isRecord(section) && section.type === 'video' ? videoToMedia(section) : section)),
26
26
  }
27
27
  }
28
+
29
+ /** Form settings the Contact section used to keep in the content file. The form now posts to `/api/contact`; the rest lives in code and the environment. */
30
+ const CONTACT_FORM_SETTINGS = ['action', 'turnstile', 'format'] as const
31
+
32
+ /** Version 2 to 3: a Contact section no longer stores its endpoint, Turnstile key or format. */
33
+ export const migrateContactFormSettings: ContentMigration = (document, kind) => {
34
+ if (kind !== 'page' || !Array.isArray(document.sections)) return document
35
+ return {
36
+ ...document,
37
+ sections: document.sections.map((section) => {
38
+ if (!isRecord(section) || section.type !== 'contact' || !isRecord(section.props)) return section
39
+ const props = { ...section.props }
40
+ for (const key of CONTACT_FORM_SETTINGS) delete props[key]
41
+ return { ...section, props }
42
+ }),
43
+ }
44
+ }
@@ -331,6 +331,88 @@
331
331
  outline: none;
332
332
  box-shadow: inset 0 0 0 2px var(--link);
333
333
  }
334
+ /* Colour alone never says a field is wrong: it gets a heavier edge and a message in words. */
335
+ .bm-field[aria-invalid="true"] {
336
+ box-shadow: inset 0 0 0 2px var(--fg);
337
+ }
338
+ .bm-underline[aria-invalid="true"] {
339
+ border-bottom: 2px solid var(--fg);
340
+ }
341
+ .bm-form-error {
342
+ border-inline-start: 2px solid var(--fg);
343
+ padding-inline-start: 0.75rem;
344
+ font-size: 0.8125rem;
345
+ font-weight: 500;
346
+ line-height: 1.4;
347
+ }
348
+ .bm-form-error[hidden] {
349
+ display: none;
350
+ }
351
+ /* Shown by the form script after a send. Without JavaScript the page's own :target rules show them (Base.astro). */
352
+ [data-contact-success],
353
+ [data-contact-failed] {
354
+ display: none;
355
+ }
356
+ [data-contact-success][data-shown] {
357
+ display: block;
358
+ }
359
+ /* A failed send stays on screen until the visitor closes it. */
360
+ .bm-toasts {
361
+ position: fixed;
362
+ inset: auto 1rem 1rem 1rem;
363
+ z-index: 2000;
364
+ width: auto;
365
+ height: auto;
366
+ margin: 0;
367
+ border: 0;
368
+ padding: 0;
369
+ overflow: visible;
370
+ background: transparent;
371
+ color: inherit;
372
+ display: flex;
373
+ flex-direction: column;
374
+ align-items: flex-end;
375
+ gap: 0.5rem;
376
+ pointer-events: none;
377
+ }
378
+ .bm-toast {
379
+ pointer-events: auto;
380
+ display: flex;
381
+ align-items: flex-start;
382
+ gap: 0.75rem;
383
+ max-width: min(26rem, 100%);
384
+ border-radius: var(--radius-field);
385
+ background: var(--fg);
386
+ padding: 0.875rem 0.5rem 0.875rem 1rem;
387
+ color: var(--bg);
388
+ font-size: 0.875rem;
389
+ font-weight: 500;
390
+ line-height: 1.45;
391
+ box-shadow: 0 0.5rem 2rem oklch(0 0 0 / 0.25);
392
+ }
393
+ .bm-toast-text {
394
+ flex: 1;
395
+ margin-block: 0.125rem;
396
+ }
397
+ .bm-toast-close {
398
+ flex: none;
399
+ display: grid;
400
+ place-items: center;
401
+ width: 2rem;
402
+ height: 2rem;
403
+ border-radius: var(--radius-chip);
404
+ font-size: 1.25rem;
405
+ line-height: 1;
406
+ color: inherit;
407
+ cursor: pointer;
408
+ }
409
+ .bm-toast-close:hover {
410
+ background: color-mix(in oklch, currentColor 18%, transparent);
411
+ }
412
+ .bm-toast-close:focus-visible {
413
+ outline: 2px solid var(--bg);
414
+ outline-offset: -2px;
415
+ }
334
416
  .bm-underline {
335
417
  width: 100%;
336
418
  border: 0;