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
package/CHANGELOG.md CHANGED
@@ -1,5 +1,34 @@
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
+
16
+ ## 1.6.0
17
+
18
+ ### Minor Changes
19
+
20
+ - eec6f3d: New starter sections and editor features.
21
+
22
+ - **Gallery** section: grid, masonry and featured layouts, a keyboard-friendly lightbox, an optional box around each picture, and required alt text.
23
+ - **Text** section: long-form rich text for an About or policy page, with a narrow, readable column on by default. Rich-text fields can opt into **H2** and **H3** (`data-rich-headings`); `renderRichText`, `sanitizeRichHtml` and `stripPlainRich` take a `{ headings }` option.
24
+ - **Media** now covers video: the separate Video section is gone, and Media gains `playback` (`controls` or `loop`). Content `schemaVersion` 2 migrates existing Video sections to Media automatically.
25
+ - **Video uploads**: upload an mp4, webm, mov or ogv to `public/videos` from the editor (`videosDir`, `maxVideoBytes`, default 50 MB), pick an uploaded one, and see what a pasted link is or why it will not play. New API routes `GET`/`POST /videos` and `DELETE /videos/:filename`.
26
+ - `parseMediaSource` and `VIDEO_FILE` are exported from `bearminion`.
27
+
28
+ ### Patch Changes
29
+
30
+ - eec6f3d: Clearer package descriptions and READMEs: what BearMinion is, who it is for, and what `create-bearminion` refuses (a folder that is not new or empty).
31
+
3
32
  ## 1.5.0
4
33
 
5
34
  ### Patch Changes
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  </p>
4
4
 
5
5
  <p align="center">
6
- Create a website you edit by clicking on it. No database, no admin panel, no server.<br />
6
+ The BearMinion for the bare minimum. Create a website you edit by clicking on it: no database to patch at 3 AM, no admin panel, no server.<br />
7
7
  Built on <a href="https://astro.build">Astro</a>.
8
8
  </p>
9
9
 
@@ -50,11 +50,13 @@ Pass options after `--` with npm (`npm create bearminion@latest my-site -- --yes
50
50
  | `--no-git` | Skip creating a git repository |
51
51
  | `-y`, `--yes` | Ask nothing and use the defaults, for scripts and AI agents |
52
52
 
53
- The folder must be new or empty. Inside an existing git repository, the site is added as a folder and no new repository is made.
53
+ > **Don't poke the bear:** the folder must be new or empty (`.git` and `.DS_Store` are fine). It refuses anything else, and neither of us wants to untangle that.
54
+
55
+ Inside an existing git repository, the site is added as a folder and no new repository is made.
54
56
 
55
57
  ## What you get
56
58
 
57
- The [default BearMinion template](https://github.com/langehelp-software/bearminion/tree/main/templates/default): an Astro and Tailwind site with thirteen section types, the [`bearminion`](https://www.npmjs.com/package/bearminion) editor at the same version as this package, and content as JSON files you own and commit. The template ships inside this package, so it works offline and always matches its editor.
59
+ The [default BearMinion template](https://github.com/langehelp-software/bearminion/tree/main/templates/default): an Astro and Tailwind site with fourteen section types, the [`bearminion`](https://www.npmjs.com/package/bearminion) editor at the same version as this package, and content as JSON files you own and commit. The template ships inside this package, so it works offline and always matches its editor.
58
60
 
59
61
  ## Learn more
60
62
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "create-bearminion",
3
- "version": "1.5.0",
4
- "description": "Create a BearMinion site: an Astro website you edit by clicking on it.",
3
+ "version": "1.7.0",
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",
7
7
  "homepage": "https://bearminion.com",
@@ -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
@@ -29,7 +29,7 @@ This template is yours to change: it is the theme. `bearminion` is the only runt
29
29
 
30
30
  Organisms are Header, Navigation, MobileMenu, and Footer. A modal, a dialog, and a cookie banner belong in this folder too. They are the chrome around every page (or a standalone widget), and they are fed by `content/site.json`.
31
31
 
32
- Sections are `hero`, `logoStrip`, `steps`, `features`, `textImage`, `stats`, `testimonials`, `pricing`, `video`, `media`, `faq`, `cta`, and `contact`. Each page entry is `{ id, anchor?, type, variant, tone, motion?, props }`. `anchor` is an optional lowercase slug, unique on the page, and it becomes the section element's `id`. `data-section-id` stays the section id. `[data-section-id]` sets `scroll-margin-top: 7rem` so a sticky or floating header does not cover the target. `html` uses `scroll-behavior: smooth`, and `prefers-reduced-motion: reduce` forces `scroll-behavior: auto`. Section components are built from molecules and atoms. A section may use an organism when it needs one, such as a modal. The section root carries `data-section-id`, `data-section-type`, `data-variant`, `data-tone`, and `data-motion`. Atoms accept a `class` and forward `data-*` attributes, including `data-field`, so the editor can find the text.
32
+ Sections are `hero`, `logoStrip`, `steps`, `gallery`, `features`, `text`, `textImage`, `stats`, `testimonials`, `pricing`, `media`, `faq`, `cta`, and `contact`. Each page entry is `{ id, anchor?, type, variant, tone, motion?, props }`. `anchor` is an optional lowercase slug, unique on the page, and it becomes the section element's `id`. `data-section-id` stays the section id. `[data-section-id]` sets `scroll-margin-top: 7rem` so a sticky or floating header does not cover the target. `html` uses `scroll-behavior: smooth`, and `prefers-reduced-motion: reduce` forces `scroll-behavior: auto`. Section components are built from molecules and atoms. A section may use an organism when it needs one, such as a modal. The section root carries `data-section-id`, `data-section-type`, `data-variant`, `data-tone`, and `data-motion`. Atoms accept a `class` and forward `data-*` attributes, including `data-field`, so the editor can find the text.
33
33
 
34
34
  Paragraph fields (`sub`, `intro`, `body`, `description`, `quote`, `note`, `thanks`, FAQ answers and Text + Image `points`) are markdown. The template renders bold, italic, inline `code` (a mono chip), links, and paragraphs through `bearminion/rich-text`, escapes every other character, and adds `rel="noopener noreferrer"` on `http` and `https` links.
35
35
 
@@ -40,7 +40,7 @@ src/components/
40
40
  organisms/ Header, Navigation, MobileMenu, Footer, plus site-definition.ts (header and footer layouts, limits)
41
41
  sections/ one directory per type, plus definitions.ts, registry.ts, shared.ts, SectionList.astro
42
42
  hero/ definition.ts (zod schema, defaults, options), wireframe.ts (picker thumbnail), Hero.astro, Hero.stories.ts
43
- logo-strip/ steps/ features/ text-image/ stats/ testimonials/ pricing/ video/ media/ faq/ cta/ contact/
43
+ logo-strip/ steps/ gallery/ features/ text/ text-image/ stats/ testimonials/ pricing/ media/ faq/ cta/ contact/
44
44
  seo/ Seo
45
45
  ```
46
46
 
@@ -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.5.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",
@@ -18,6 +18,8 @@ interface Props {
18
18
  id?: string
19
19
  /** Markdown subset (bold, italic, links, lists, paragraphs). Renders sanitized HTML. */
20
20
  markdown?: string
21
+ /** The markdown may hold `##` and `###` headings, and the editor offers them. */
22
+ richHeadings?: boolean
21
23
  'data-field'?: string
22
24
  }
23
25
 
@@ -30,10 +32,11 @@ const {
30
32
  align,
31
33
  class: className,
32
34
  markdown,
35
+ richHeadings = false,
33
36
  ...rest
34
37
  } = Astro.props
35
38
 
36
- const html = markdown !== undefined ? renderRichText(markdown) : undefined
39
+ const html = markdown !== undefined ? renderRichText(markdown, { headings: richHeadings }) : undefined
37
40
  // Rich text is `<p>`s and lists, which a `<p>`, `<span>` or heading cannot hold. A `blockquote`, `li` or `figcaption` can.
38
41
  const Tag = html !== undefined && PHRASING_ONLY.has(TagName) ? 'div' : TagName
39
42
  const classes = cn(typography({ size, color, weight, font, align }), className)
@@ -41,7 +44,7 @@ const classes = cn(typography({ size, color, weight, font, align }), className)
41
44
 
42
45
  {
43
46
  html !== undefined ? (
44
- <Tag class={classes} data-field-kind="rich" set:html={html} {...rest} />
47
+ <Tag class={classes} data-field-kind="rich" data-rich-headings={richHeadings ? 'true' : undefined} set:html={html} {...rest} />
45
48
  ) : (
46
49
  <TagName class={classes} {...rest}>
47
50
  <slot />
@@ -12,12 +12,13 @@ const { sections, motion = true } = Astro.props
12
12
  const Hero = sectionComponents.hero
13
13
  const LogoStrip = sectionComponents.logoStrip
14
14
  const Steps = sectionComponents.steps
15
+ const Gallery = sectionComponents.gallery
15
16
  const Features = sectionComponents.features
17
+ const Text = sectionComponents.text
16
18
  const TextImage = sectionComponents.textImage
17
19
  const Stats = sectionComponents.stats
18
20
  const Testimonials = sectionComponents.testimonials
19
21
  const Pricing = sectionComponents.pricing
20
- const Video = sectionComponents.video
21
22
  const Media = sectionComponents.media
22
23
  const Faq = sectionComponents.faq
23
24
  const Cta = sectionComponents.cta
@@ -33,8 +34,12 @@ const Contact = sectionComponents.contact
33
34
  return <LogoStrip section={section} index={index} motion={motion} />
34
35
  case 'steps':
35
36
  return <Steps section={section} index={index} motion={motion} />
37
+ case 'gallery':
38
+ return <Gallery section={section} index={index} motion={motion} />
36
39
  case 'features':
37
40
  return <Features section={section} index={index} motion={motion} />
41
+ case 'text':
42
+ return <Text section={section} index={index} motion={motion} />
38
43
  case 'textImage':
39
44
  return <TextImage section={section} index={index} motion={motion} />
40
45
  case 'stats':
@@ -43,8 +48,6 @@ const Contact = sectionComponents.contact
43
48
  return <Testimonials section={section} index={index} motion={motion} />
44
49
  case 'pricing':
45
50
  return <Pricing section={section} index={index} motion={motion} />
46
- case 'video':
47
- return <Video section={section} index={index} motion={motion} />
48
51
  case 'media':
49
52
  return <Media section={section} index={index} motion={motion} />
50
53
  case 'faq':
@@ -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,