@eldrajs/theme-cli 0.2.0 → 0.2.2

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 (66) hide show
  1. package/package.json +3 -3
  2. package/template/.eldra/block-types.d.ts +12 -3
  3. package/template/.eldra/manifest.json +315 -25
  4. package/template/.eldra/previews.json +35 -34
  5. package/template/.github/workflows/eldra-deploy.yml +31 -2
  6. package/template/.gitlab-ci.yml +37 -8
  7. package/template/.storybook/main.ts +3 -0
  8. package/template/README.md +25 -13
  9. package/template/app/components/FormHoneypot.vue +21 -0
  10. package/template/app/composables/useFormSpam.ts +56 -0
  11. package/template/app/composables/usePageStructuredData.ts +112 -0
  12. package/template/app/composables/useTurnstile.ts +111 -0
  13. package/template/app/formSeeds.ts +93 -0
  14. package/template/app/pages/[...slug].vue +48 -12
  15. package/template/app/plugins/eldra-storefront.ts +22 -2
  16. package/template/app/seededPages.ts +7 -0
  17. package/template/app/storefront/analytics.ts +202 -0
  18. package/template/app/storefront/cart.ts +7 -0
  19. package/template/app/storefront/demo.ts +48 -2
  20. package/template/app/storefront/forms.ts +133 -0
  21. package/template/app/storefront/gateway.ts +113 -7
  22. package/template/app/storefront/structuredData.ts +161 -0
  23. package/template/app/storefront/types.ts +101 -2
  24. package/template/app/utils/seoInput.ts +172 -0
  25. package/template/bitbucket-pipelines.yml +25 -3
  26. package/template/blocks/breadcrumbs/Block.vue +1 -0
  27. package/template/blocks/cart/Block.vue +1 -0
  28. package/template/blocks/cart/parts/Summary.vue +1 -0
  29. package/template/blocks/contact/Block.vue +50 -21
  30. package/template/blocks/contact/__tests__/Block.spec.ts +89 -8
  31. package/template/blocks/contact/block.json +2 -9
  32. package/template/blocks/contact/mock.json +1 -2
  33. package/template/blocks/footer/Block.vue +66 -9
  34. package/template/blocks/footer/__tests__/Block.spec.ts +136 -17
  35. package/template/blocks/footer/preview.png +0 -0
  36. package/template/blocks/form/Block.vue +614 -0
  37. package/template/blocks/form/__tests__/Block.spec.ts +536 -0
  38. package/template/blocks/form/block.json +69 -0
  39. package/template/blocks/form/mock.json +25 -0
  40. package/template/blocks/form/preview.png +0 -0
  41. package/template/blocks/form/validate.ts +68 -0
  42. package/template/blocks/newsletter/Block.vue +57 -3
  43. package/template/blocks/newsletter/__tests__/Block.spec.ts +89 -31
  44. package/template/blocks/newsletter/block.json +4 -5
  45. package/template/blocks/newsletter/mock.json +1 -1
  46. package/template/blocks/newsletter/preview.png +0 -0
  47. package/template/i18n/en-US.json +33 -2
  48. package/template/i18n/is-IS.json +33 -2
  49. package/template/nuxt.config.ts +6 -0
  50. package/template/stories/generated/form.stories.ts +68 -0
  51. package/template/test/formValidate.spec.ts +46 -0
  52. package/template/test/prerenderFailure.spec.ts +1 -1
  53. package/template/test/prerenderRefresh.browser.spec.ts +5 -1
  54. package/template/test/seededPages.spec.ts +13 -0
  55. package/template/test/seoInput.spec.ts +119 -0
  56. package/template/test/slugPage.spec.ts +62 -26
  57. package/template/test/slugPageTemplate.spec.ts +5 -1
  58. package/template/test/starter.spec.ts +41 -3
  59. package/template/test/storefront/analytics.spec.ts +283 -0
  60. package/template/test/storefront/forms.spec.ts +385 -0
  61. package/template/test/storefront/structuredData.spec.ts +138 -0
  62. package/template/test/structuredData.generate.spec.ts +159 -0
  63. package/template/test/support/mockGateway.ts +29 -1
  64. package/template/test/support/turnstileForms.ts +53 -0
  65. package/template/app/utils/pageTitle.ts +0 -37
  66. package/template/test/pageTitle.spec.ts +0 -49
@@ -270,6 +270,7 @@ const VALUE_CLASS = 'text-text text-body-sm font-medium tabular-nums';
270
270
  block
271
271
  :href="checkoutHref"
272
272
  :as="checkoutAs"
273
+ @click="cart.beginCheckout()"
273
274
  >
274
275
  <template #leadingIcon>
275
276
  <EldraIcon name="lock" size="sm" />
@@ -40,7 +40,13 @@
40
40
  * (the three `watch`es), which is what lets a corrected field's `aria-invalid` go false in time for
41
41
  * that next submit to get past `FormLayout`'s own scan.
42
42
  *
43
- * **Success.** `forms.sendMessage` resolving `{ ok: true }` swaps the card's content for a
43
+ * **Submitting** is the platform's own form, `forms.submit('contact', { values })`: the seeded
44
+ * `contact` form (`app/formSeeds.ts`) names the fields this block sends (`name`, `email`, `topic`,
45
+ * `orderNumber`, `message`), and who is notified is the merchant's setting on the Forms page, not
46
+ * block data. A `422` marks the field it names (the same three error refs a local check sets);
47
+ * every other failure shows the server summary.
48
+ *
49
+ * **Success.** `forms.submit` resolving `{ ok: true }` swaps the card's content for a
44
50
  * `role="status" tabindex="-1"` panel that receives focus (spec: "the card content is replaced").
45
51
  * "Send another message" restores an empty form and focuses the Name field (spec: "moves focus to
46
52
  * its first field").
@@ -64,10 +70,12 @@ import {
64
70
  } from '@eldrajs/ui';
65
71
  import { useBlockData } from '../../app/composables/useBlockData';
66
72
  import { useEditing } from '../../app/composables/useEditing';
73
+ import { useFormSpam } from '../../app/composables/useFormSpam';
67
74
  import { useStorefront } from '../../app/composables/useStorefront';
68
75
  import { useI18n } from 'vue-i18n';
69
76
  import { useUiId } from '../../app/composables/useUiId';
70
77
  import EldraIcon from '../../app/components/EldraIcon.vue';
78
+ import FormHoneypot from '../../app/components/FormHoneypot.vue';
71
79
  import EldraRouterLink from '../../app/components/EldraRouterLink.vue';
72
80
  import UiImage from '../../app/components/ui/UiImage.vue';
73
81
  import { isInternalHref, safeHref } from '../../app/utils/links';
@@ -272,11 +280,13 @@ watch(message, () => {
272
280
  if (messageError.value) messageError.value = null;
273
281
  });
274
282
 
283
+ const spam = useFormSpam(computed(() => (hasForm.value ? 'contact' : '')));
284
+ const { honeypot, honeypotField, siteKey, turnstileRoot } = spam;
275
285
  const sending = ref(false);
276
286
  const serverError = ref(false);
287
+ /** The spam check (Turnstile) is on and the visitor has not passed it. */
288
+ const challengeError = ref<string | null>(null);
277
289
  const sent = ref(false);
278
- const sentFirstName = ref('');
279
- const sentEmail = ref('');
280
290
 
281
291
  const summaryRef = ref<HTMLElement | null>(null);
282
292
  const statusRef = ref<HTMLElement | null>(null);
@@ -284,7 +294,9 @@ const statusRef = ref<HTMLElement | null>(null);
284
294
  const invalidCount = computed(
285
295
  () => [nameError.value, emailError.value, messageError.value].filter(Boolean).length
286
296
  );
287
- const hasFormError = computed(() => invalidCount.value > 0 || serverError.value);
297
+ const hasFormError = computed(
298
+ () => invalidCount.value > 0 || serverError.value || challengeError.value !== null
299
+ );
288
300
  const summaryTitle = computed(() =>
289
301
  invalidCount.value === 1
290
302
  ? t('contact.summaryTitleOne')
@@ -311,10 +323,14 @@ function focusField(id: string): void {
311
323
 
312
324
  async function sendForm(): Promise<void> {
313
325
  serverError.value = false;
326
+ challengeError.value = spam.challenge();
327
+ if (challengeError.value !== null) {
328
+ await focusSummary();
329
+ return;
330
+ }
314
331
  sending.value = true;
315
332
 
316
333
  const payload: Record<string, string> = {
317
- recipient: data.value.recipient,
318
334
  name: name.value.trim(),
319
335
  email: emailValue.value.trim(),
320
336
  message: message.value.trim(),
@@ -324,17 +340,25 @@ async function sendForm(): Promise<void> {
324
340
  }
325
341
  if (hasTopics.value && topic.value !== '') payload.topic = topic.value;
326
342
 
327
- const result = await storefront.forms.sendMessage(payload);
343
+ const result = await storefront.forms.submit('contact', { values: payload, ...spam.signals() });
328
344
  sending.value = false;
345
+ // A Turnstile token is single-use, whatever the outcome.
346
+ spam.reset();
329
347
 
330
348
  if (!result.ok) {
331
- serverError.value = true;
349
+ if (result.reason === 'invalid') {
350
+ // The platform's own message for each field it refused, shown where a local check's would be.
351
+ nameError.value = result.errors.name?.[0] ?? null;
352
+ emailError.value = result.errors.email?.[0] ?? null;
353
+ messageError.value = result.errors.message?.[0] ?? null;
354
+ }
355
+ // A refusal that named none of the three fields (another field, the form as a whole, or no
356
+ // reason at all) would otherwise leave nothing on screen.
357
+ serverError.value = !nameError.value && !emailError.value && !messageError.value;
332
358
  await focusSummary();
333
359
  return;
334
360
  }
335
361
 
336
- sentFirstName.value = name.value.trim().split(/\s+/)[0] ?? '';
337
- sentEmail.value = emailValue.value.trim();
338
362
  sent.value = true;
339
363
  await nextTick();
340
364
  statusRef.value?.focus();
@@ -365,20 +389,15 @@ async function onSendAnother(): Promise<void> {
365
389
  emailError.value = null;
366
390
  messageError.value = null;
367
391
  serverError.value = false;
392
+ challengeError.value = null;
393
+ honeypot.value = '';
368
394
  sent.value = false;
369
395
  await nextTick();
370
396
  focusField(nameFieldId);
371
397
  }
372
398
 
373
- function interpolate(template: string, params: Record<string, string>): string {
374
- return template.replace(/\{(\w+)\}/g, (match, key: string) =>
375
- Object.hasOwn(params, key) ? params[key]! : match
376
- );
377
- }
378
-
379
- const successText = computed(() =>
380
- interpolate(data.value.successText || t('contact.successTextDefault'), { email: sentEmail.value })
381
- );
399
+ /** The receipt never echoes what the visitor typed (no name, no address): it is shown to whoever is at the screen. */
400
+ const successText = computed(() => data.value.successText || t('contact.successTextDefault'));
382
401
  </script>
383
402
 
384
403
  <template>
@@ -468,8 +487,15 @@ const successText = computed(() =>
468
487
  >
469
488
  <template v-if="hasFormError" #errorSummary>
470
489
  <div ref="summaryRef" tabindex="-1">
471
- <template v-if="serverError">
472
- <p>{{ t('contact.serverError', { email: data.recipient }) }}</p>
490
+ <p v-if="challengeError">{{ challengeError }}</p>
491
+ <template v-else-if="serverError">
492
+ <p>
493
+ {{
494
+ email
495
+ ? t('contact.serverError', { email })
496
+ : t('contact.serverErrorGeneric')
497
+ }}
498
+ </p>
473
499
  </template>
474
500
  <template v-else>
475
501
  <p class="font-semibold">{{ summaryTitle }}</p>
@@ -553,6 +579,9 @@ const successText = computed(() =>
553
579
  />
554
580
  </FieldWrapper>
555
581
 
582
+ <FormHoneypot v-model="honeypot" :name="honeypotField" />
583
+ <div v-if="siteKey" ref="turnstileRoot" class="@two-col:col-span-2" />
584
+
556
585
  <template #actions>
557
586
  <Button variant="primary" type="submit" size="lg" :label="t('contact.sending')">{{
558
587
  t('contact.sendMessage')
@@ -564,7 +593,7 @@ const successText = computed(() =>
564
593
  <div v-else ref="statusRef" role="status" tabindex="-1" class="grid gap-4 text-center">
565
594
  <EldraIcon name="circle-check" size="xl" class="text-success mx-auto" />
566
595
  <p class="text-h4 font-heading font-semibold">
567
- {{ t('contact.successTitle', { name: sentFirstName }) }}
596
+ {{ t('contact.successTitle') }}
568
597
  </p>
569
598
  <p class="text-muted text-base">{{ successText }}</p>
570
599
  <Button variant="outline" type="button" class="mx-auto" @click="onSendAnother">{{
@@ -1,19 +1,34 @@
1
1
  // @vitest-environment jsdom
2
2
  import { flushPromises, mount } from '@vue/test-utils';
3
- import { describe, expect, it } from 'vitest';
3
+ import { afterEach, describe, expect, it, vi } from 'vitest';
4
4
  import { axe } from '../../../test/support/axe';
5
5
  import Block from '../Block.vue';
6
6
  import mock from '../mock.json';
7
7
  import preview from '../preview.json';
8
8
  import { mountOptions } from '../../../test/support/mountBlock';
9
9
  import { STOREFRONT_KEY } from '../../../app/storefront/types';
10
+ import type { StorefrontSource } from '../../../app/storefront/types';
10
11
  import { createDemoStorefront } from '../../../app/storefront/demo';
11
12
  import enUS from '../../../i18n/en-US.json';
12
13
  import { renderedMessage } from '../../../test/support/i18nText';
14
+ import {
15
+ cleanUpTurnstile,
16
+ storefrontWithTurnstile,
17
+ stubTurnstile,
18
+ } from '../../../test/support/turnstileForms';
19
+
20
+ afterEach(cleanUpTurnstile);
13
21
 
14
22
  const merged = { ...mock, ...preview };
15
23
 
16
- function mountContact(data: Record<string, unknown>, options: { failForms?: boolean } = {}) {
24
+ function mountContact(
25
+ data: Record<string, unknown>,
26
+ options: {
27
+ failForms?: boolean;
28
+ submit?: StorefrontSource['forms']['submit'];
29
+ storefront?: StorefrontSource;
30
+ } = {}
31
+ ) {
17
32
  const base = mountOptions({ entry: { id: 'e1', data } });
18
33
  return mount(Block, {
19
34
  ...base,
@@ -28,6 +43,15 @@ function mountContact(data: Record<string, unknown>, options: { failForms?: bool
28
43
  ...(options.failForms
29
44
  ? { [STOREFRONT_KEY]: createDemoStorefront({ failForms: true }) }
30
45
  : {}),
46
+ ...(options.submit
47
+ ? {
48
+ [STOREFRONT_KEY]: (() => {
49
+ const base = createDemoStorefront();
50
+ return { ...base, forms: { ...base.forms, submit: options.submit } };
51
+ })(),
52
+ }
53
+ : {}),
54
+ ...(options.storefront ? { [STOREFRONT_KEY]: options.storefront } : {}),
31
55
  },
32
56
  },
33
57
  });
@@ -177,18 +201,50 @@ describe('contact block', () => {
177
201
  expect(document.activeElement).toBe(messageField.element);
178
202
  });
179
203
 
180
- it('a valid submit calls forms.sendMessage and shows a role="status" success panel that receives focus, replacing the form', async () => {
181
- const wrapper = mountContact(mock);
204
+ it('a valid submit posts the seeded contact form’s fields to forms.submit and shows a role="status" success panel that receives focus, replacing the form', async () => {
205
+ const submit = vi.fn(async () => ({ ok: true as const, pending: false }));
206
+ const wrapper = mountContact(mock, { submit });
182
207
  await submitValid(wrapper);
183
208
 
209
+ expect(submit).toHaveBeenCalledWith('contact', {
210
+ values: {
211
+ name: 'Hannah Reyes',
212
+ email: 'hannah@example.com',
213
+ topic: mock.topics[0]!.label,
214
+ message: 'Do you carry the moss glaze in stock right now?',
215
+ },
216
+ });
184
217
  expect(wrapper.find('form').exists()).toBe(false);
185
218
  const status = wrapper.find('[role="status"]');
186
219
  expect(status.exists()).toBe(true);
187
- expect(status.text()).toContain('Hannah');
188
- expect(status.text()).toContain('hannah@example.com');
220
+ // A receipt never echoes what the visitor typed.
221
+ expect(status.text()).not.toContain('Hannah');
222
+ expect(status.text()).not.toContain('hannah@example.com');
189
223
  expect(document.activeElement).toBe(status.element);
190
224
  });
191
225
 
226
+ it('with Turnstile on, renders the widget and honeypot, refuses to send before the check, then sends the token and honeypot', async () => {
227
+ const turnstile = stubTurnstile();
228
+ const submit = vi.fn(async () => ({ ok: true as const, pending: false }));
229
+ const wrapper = mountContact(mock, { storefront: storefrontWithTurnstile(submit) });
230
+ await flushPromises();
231
+ expect(turnstile.render).toHaveBeenCalledOnce();
232
+
233
+ await submitValid(wrapper);
234
+ expect(submit).not.toHaveBeenCalled();
235
+ expect(wrapper.text()).toContain(enUS.form.turnstileRequired);
236
+
237
+ turnstile.solve('token-1');
238
+ await wrapper.find('input[name="website"]').setValue('bot');
239
+ await wrapper.find('form').trigger('submit');
240
+ await flushPromises();
241
+ expect(submit).toHaveBeenCalledWith(
242
+ 'contact',
243
+ expect.objectContaining({ turnstileToken: 'token-1', hp: 'bot' })
244
+ );
245
+ expect(turnstile.reset).toHaveBeenCalled();
246
+ });
247
+
192
248
  it('"Send another message" restores an empty form and focuses the Name field', async () => {
193
249
  const wrapper = mountContact(mock);
194
250
  await submitValid(wrapper);
@@ -206,12 +262,37 @@ describe('contact block', () => {
206
262
  expect(document.activeElement).toBe(name.element);
207
263
  });
208
264
 
209
- it('a server failure (forms.sendMessage ok:false) shows the summary again and keeps the form', async () => {
265
+ it('a server failure (forms.submit ok:false) shows the summary again and keeps the form', async () => {
210
266
  const wrapper = mountContact(mock, { failForms: true });
211
267
  await submitValid(wrapper);
212
268
 
213
269
  expect(wrapper.find('form').exists()).toBe(true);
214
- expect(wrapper.find('[role="alert"]').text()).toContain(mock.recipient);
270
+ expect(wrapper.find('[role="alert"]').text()).toContain(mock.email);
271
+ });
272
+
273
+ it('a server failure with no contact email on the block still says what happened', async () => {
274
+ const { email: _omit, ...withoutEmail } = mock;
275
+ const wrapper = mountContact(withoutEmail, { failForms: true });
276
+ await submitValid(wrapper);
277
+
278
+ expect(wrapper.find('[role="alert"]').text()).toBe(enUS.contact.serverErrorGeneric);
279
+ });
280
+
281
+ it('a 422 marks the field the platform names, with its own message, and focuses the summary', async () => {
282
+ const submit = vi.fn(async () => ({
283
+ ok: false as const,
284
+ reason: 'invalid' as const,
285
+ errors: { email: ['That domain does not accept mail.'] },
286
+ form: [],
287
+ }));
288
+ const wrapper = mountContact(mock, { submit });
289
+ await submitValid(wrapper);
290
+
291
+ expect(wrapper.find('form').exists()).toBe(true);
292
+ expect(wrapper.find('input[type="email"]').attributes('aria-invalid')).toBe('true');
293
+ expect(wrapper.text()).toContain('That domain does not accept mail.');
294
+ expect(wrapper.find('input[autocomplete="name"]').attributes('aria-invalid')).toBeUndefined();
295
+ expect(await axe(wrapper.element)).toHaveNoViolations();
215
296
  });
216
297
 
217
298
  it.each(['Enter', ' ', 'ArrowDown'])(
@@ -4,7 +4,7 @@
4
4
  "description": "The shop's address, opening hours, phone and email beside a short enquiry form, with a map that always offers an \"Open in maps\" link outside any embed.",
5
5
  "icon": "map-pin",
6
6
  "category": "marketing",
7
- "version": 1,
7
+ "version": 2,
8
8
  "fields": [
9
9
  {
10
10
  "fieldId": "variant",
@@ -156,19 +156,12 @@
156
156
  "type": "bool",
157
157
  "default": false
158
158
  },
159
- {
160
- "fieldId": "recipient",
161
- "name": "Recipient",
162
- "type": "string",
163
- "helpText": "Where submissions go. Not shown.",
164
- "validators": { "required": true }
165
- },
166
159
  {
167
160
  "fieldId": "successText",
168
161
  "name": "Success text",
169
162
  "type": "text",
170
163
  "localized": true,
171
- "helpText": "Shown after a successful submit. {email} is replaced with the sender's own address."
164
+ "helpText": "Shown after a successful submit. It never echoes what the visitor typed."
172
165
  }
173
166
  ]
174
167
  }
@@ -23,6 +23,5 @@
23
23
  { "label": "Something else" }
24
24
  ],
25
25
  "showOrderNumber": true,
26
- "recipient": "hello@northwind.example",
27
- "successText": "We reply within one business day, usually sooner. A copy is on its way to {email}."
26
+ "successText": "We reply within one business day, usually sooner."
28
27
  }
@@ -57,7 +57,8 @@
57
57
  * slot renders nothing. The `Select` branch stays for the day the derived list carries two or more
58
58
  * entries; which branch renders is driven by that list's length, not by a separate flag.
59
59
  *
60
- * The newsletter zone posts through `useStorefront().forms.subscribe`. Email format is validated
60
+ * The newsletter zone posts through `useStorefront().forms.submit('newsletter', …)` — the platform's
61
+ * seeded `newsletter` form, the same one the newsletter block defaults to. Email format is validated
61
62
  * locally (empty/malformed never reaches the storefront); a backend `{ ok: false }` shows the same
62
63
  * error slot. Both failure paths return focus to the email field — `FormLayout`'s own submit
63
64
  * handler only refuses a *second* submit while a field is already marked invalid, so the first
@@ -96,8 +97,10 @@ import { useBlockData } from '../../app/composables/useBlockData';
96
97
  import { useEditing } from '../../app/composables/useEditing';
97
98
  import { useI18n } from 'vue-i18n';
98
99
  import { useUiId } from '../../app/composables/useUiId';
100
+ import { useFormSpam } from '../../app/composables/useFormSpam';
99
101
  import { useStorefront } from '../../app/composables/useStorefront';
100
102
  import EldraIcon from '../../app/components/EldraIcon.vue';
103
+ import FormHoneypot from '../../app/components/FormHoneypot.vue';
101
104
  import EldraRouterLink from '../../app/components/EldraRouterLink.vue';
102
105
  import type { ThemeIconName } from '../../app/icons';
103
106
  import { currencyLabel, useMoney } from '../../app/storefront/money';
@@ -109,6 +112,9 @@ type FooterLink = {
109
112
  as: typeof EldraRouterLink | undefined;
110
113
  };
111
114
 
115
+ /** The seeded form the footer's sign-up zone submits to (`app/formSeeds.ts`). */
116
+ const NEWSLETTER_FORM_KEY = 'newsletter';
117
+
112
118
  const props = defineProps<{ entry: EldraBlockEntry<'footer'> }>();
113
119
  const { data } = useBlockData(props, 'footer');
114
120
  const { t } = useI18n();
@@ -308,6 +314,24 @@ const emailFieldRoot = ref<HTMLElement | null>(null);
308
314
  const showNewsletter = computed(
309
315
  () => variant.value === 'default' && (data.value.showNewsletter ?? true)
310
316
  );
317
+ // Only a footer that shows the sign-up reads the form's definition (its honeypot and Turnstile).
318
+ const {
319
+ definition,
320
+ honeypot,
321
+ honeypotField,
322
+ siteKey,
323
+ consentSentence,
324
+ turnstileRoot,
325
+ challenge,
326
+ signals,
327
+ reset,
328
+ } = useFormSpam(computed(() => (showNewsletter.value ? NEWSLETTER_FORM_KEY : '')));
329
+ const consentSentenceId = `footer-consent-sentence-${useUiId()}`;
330
+ // The merchant's own label and placeholder on the form's email field; the theme's wording stands in until the
331
+ // definition has loaded.
332
+ const emailField = computed(() => definition.value?.fields.find((field) => field.type === 'email'));
333
+ const emailLabel = computed(() => emailField.value?.label || t('footer.emailLabel'));
334
+ const emailPlaceholder = computed(() => emailField.value?.placeholder || undefined);
311
335
 
312
336
  /** Mirrors `blocks/newsletter/Block.vue`'s own comment: an error has to clear itself the moment
313
337
  * its own condition is fixed (the visitor edits the address), not only inside a later successful
@@ -353,9 +377,23 @@ async function onNewsletterSubmit(payload: FormLayoutSubmitPayload): Promise<voi
353
377
  return;
354
378
  }
355
379
 
380
+ // Turnstile is on and not passed: nothing about the address is wrong, so a retry is welcome.
381
+ const blocked = challenge();
382
+ if (blocked !== null) {
383
+ retryable.value = true;
384
+ emailError.value = blocked;
385
+ await focusEmailField();
386
+ return;
387
+ }
388
+
356
389
  emailError.value = null;
357
390
  newsletterState.value = 'submitting';
358
- const result = await storefront.forms.subscribe({ email: value, list: 'footer-newsletter' });
391
+ const result = await storefront.forms.submit(NEWSLETTER_FORM_KEY, {
392
+ values: { email: value },
393
+ ...signals(),
394
+ });
395
+ // A Turnstile token is single-use, whatever the outcome.
396
+ reset();
359
397
 
360
398
  if (result.ok) {
361
399
  newsletterState.value = 'success';
@@ -365,7 +403,9 @@ async function onNewsletterSubmit(payload: FormLayoutSubmitPayload): Promise<voi
365
403
  newsletterState.value = 'idle';
366
404
  const serviceFailed = result.reason !== 'invalid';
367
405
  retryable.value = serviceFailed;
368
- emailError.value = serviceFailed ? t('footer.emailError') : t('footer.emailInvalid');
406
+ emailError.value = serviceFailed
407
+ ? t('footer.emailError')
408
+ : (result.errors.email?.[0] ?? t('footer.emailInvalid'));
369
409
  await focusEmailField();
370
410
  }
371
411
  </script>
@@ -487,6 +527,7 @@ async function onNewsletterSubmit(payload: FormLayoutSubmitPayload): Promise<voi
487
527
  :heading-level="3"
488
528
  :aria-label="data.newsletterTitle ? undefined : t('footer.newsletterAriaLabel')"
489
529
  :submitting="newsletterState === 'submitting'"
530
+ :classes="{ actions: 'w-full mt-3' }"
490
531
  @submit="onNewsletterSubmit"
491
532
  @invalid="onNewsletterInvalid"
492
533
  >
@@ -498,23 +539,39 @@ async function onNewsletterSubmit(payload: FormLayoutSubmitPayload): Promise<voi
498
539
  </p>
499
540
  <div ref="emailFieldRoot" class="contents">
500
541
  <FieldWrapper
501
- :label="t('footer.emailLabel')"
542
+ :label="emailLabel"
502
543
  :error="emailError ?? undefined"
503
- :classes="{ label: 'sr-only' }"
544
+ :classes="{ root: 'block w-full' }"
504
545
  >
505
546
  <Input
506
547
  v-model="email"
507
548
  type="email"
508
549
  name="email"
509
550
  autocomplete="email"
510
- :placeholder="t('footer.emailLabel')"
551
+ :placeholder="emailPlaceholder"
511
552
  />
512
553
  </FieldWrapper>
513
554
  </div>
555
+ <FormHoneypot v-model="honeypot" :name="honeypotField" />
556
+ <div v-if="siteKey" ref="turnstileRoot" class="w-full" />
514
557
  <template #actions>
515
- <Button type="submit" variant="primary" :label="t('footer.subscribing')">{{
516
- t('footer.subscribe')
517
- }}</Button>
558
+ <div class="grid w-full grid-cols-[minmax(0,1fr)] gap-2">
559
+ <Button
560
+ type="submit"
561
+ variant="primary"
562
+ :label="t('footer.subscribing')"
563
+ :aria-describedby="consentSentence ? consentSentenceId : undefined"
564
+ >{{ t('footer.subscribe') }}</Button
565
+ >
566
+ <p
567
+ v-if="consentSentence"
568
+ :id="consentSentenceId"
569
+ data-part="consent-sentence"
570
+ class="text-muted text-body-sm"
571
+ >
572
+ {{ consentSentence }}
573
+ </p>
574
+ </div>
518
575
  </template>
519
576
  </FormLayout>
520
577
  </template>