@eldrajs/theme-cli 0.1.0 → 0.2.1

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 (84) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/cli.js +1 -1
  3. package/dist/index.js +1 -1
  4. package/dist/{validate-C6jB8_Oc.js → validate-DprFpjV7.js} +29 -4
  5. package/package.json +3 -3
  6. package/template/.eldra/block-types.d.ts +12 -3
  7. package/template/.eldra/manifest.json +317 -26
  8. package/template/.eldra/previews.json +35 -34
  9. package/template/.github/workflows/eldra-deploy.yml +2 -0
  10. package/template/.gitlab-ci.yml +2 -0
  11. package/template/.storybook/main.ts +3 -0
  12. package/template/.storybook/preview.ts +2 -1
  13. package/template/.storybook/virtual-eldra.d.ts +5 -0
  14. package/template/README.md +31 -14
  15. package/template/app/components/FormHoneypot.vue +21 -0
  16. package/template/app/composables/useFormSpam.ts +55 -0
  17. package/template/app/composables/usePageStructuredData.ts +112 -0
  18. package/template/app/composables/useTurnstile.ts +111 -0
  19. package/template/app/formSeeds.ts +93 -0
  20. package/template/app/pages/[...slug].vue +48 -12
  21. package/template/app/plugins/eldra-storefront.ts +19 -2
  22. package/template/app/plugins/eldra-ui-messages.ts +1 -1
  23. package/template/app/seededPages.ts +7 -0
  24. package/template/app/storefront/analytics.ts +202 -0
  25. package/template/app/storefront/cart.ts +7 -0
  26. package/template/app/storefront/demo.ts +48 -2
  27. package/template/app/storefront/forms.ts +133 -0
  28. package/template/app/storefront/gateway.ts +113 -7
  29. package/template/app/storefront/money.ts +18 -17
  30. package/template/app/storefront/structuredData.ts +161 -0
  31. package/template/app/storefront/types.ts +101 -2
  32. package/template/app/utils/seoInput.ts +172 -0
  33. package/template/bitbucket-pipelines.yml +3 -1
  34. package/template/blocks/breadcrumbs/Block.vue +1 -0
  35. package/template/blocks/cart/Block.vue +1 -0
  36. package/template/blocks/cart/parts/Summary.vue +1 -0
  37. package/template/blocks/contact/Block.vue +50 -21
  38. package/template/blocks/contact/__tests__/Block.spec.ts +89 -8
  39. package/template/blocks/contact/block.json +2 -9
  40. package/template/blocks/contact/mock.json +1 -2
  41. package/template/blocks/footer/Block.vue +58 -8
  42. package/template/blocks/footer/__tests__/Block.spec.ts +70 -16
  43. package/template/blocks/footer/preview.png +0 -0
  44. package/template/blocks/form/Block.vue +614 -0
  45. package/template/blocks/form/__tests__/Block.spec.ts +536 -0
  46. package/template/blocks/form/block.json +69 -0
  47. package/template/blocks/form/mock.json +25 -0
  48. package/template/blocks/form/preview.png +0 -0
  49. package/template/blocks/form/validate.ts +68 -0
  50. package/template/blocks/newsletter/Block.vue +57 -3
  51. package/template/blocks/newsletter/__tests__/Block.spec.ts +89 -31
  52. package/template/blocks/newsletter/block.json +4 -5
  53. package/template/blocks/newsletter/mock.json +1 -1
  54. package/template/blocks/newsletter/preview.png +0 -0
  55. package/template/blocks/product-detail/__tests__/Block.spec.ts +7 -10
  56. package/template/i18n/en-US.json +33 -2
  57. package/template/i18n/is-IS.json +33 -2
  58. package/template/nuxt.config.ts +15 -1
  59. package/template/package.json +1 -0
  60. package/template/public/apple-touch-icon.png +0 -0
  61. package/template/public/favicon.ico +0 -0
  62. package/template/stories/generated/form.stories.ts +68 -0
  63. package/template/test/formValidate.spec.ts +46 -0
  64. package/template/test/inlineEditable.spec.ts +2 -1
  65. package/template/test/moneyFormatting.spec.ts +4 -8
  66. package/template/test/pages/ssr.spec.ts +5 -11
  67. package/template/test/prerenderFailure.spec.ts +1 -1
  68. package/template/test/prerenderRefresh.browser.spec.ts +5 -1
  69. package/template/test/richText.spec.ts +12 -9
  70. package/template/test/seededPages.spec.ts +13 -0
  71. package/template/test/seoInput.spec.ts +119 -0
  72. package/template/test/slugPage.spec.ts +62 -26
  73. package/template/test/slugPageTemplate.spec.ts +5 -1
  74. package/template/test/starter.spec.ts +42 -4
  75. package/template/test/storefront/analytics.spec.ts +283 -0
  76. package/template/test/storefront/forms.spec.ts +385 -0
  77. package/template/test/storefront/money.spec.ts +11 -12
  78. package/template/test/storefront/structuredData.spec.ts +138 -0
  79. package/template/test/structuredData.generate.spec.ts +159 -0
  80. package/template/test/support/mockGateway.ts +29 -1
  81. package/template/test/support/turnstileForms.ts +53 -0
  82. package/template/test/useBlockData.spec.ts +7 -4
  83. package/template/app/utils/pageTitle.ts +0 -37
  84. package/template/test/pageTitle.spec.ts +0 -49
@@ -0,0 +1,536 @@
1
+ // @vitest-environment jsdom
2
+ import { flushPromises, mount, type VueWrapper } from '@vue/test-utils';
3
+ import { afterEach, describe, expect, it, vi } from 'vitest';
4
+ import { axe } from '../../../test/support/axe';
5
+ import Block from '../Block.vue';
6
+ import mock from '../mock.json';
7
+ import { mountOptions } from '../../../test/support/mountBlock';
8
+ import { STOREFRONT_KEY } from '../../../app/storefront/types';
9
+ import type {
10
+ StorefrontFormDefinition,
11
+ StorefrontFormSubmitResult,
12
+ StorefrontSource,
13
+ } from '../../../app/storefront/types';
14
+ import { createDemoStorefront } from '../../../app/storefront/demo';
15
+ import enUS from '../../../i18n/en-US.json';
16
+
17
+ /** Only what the block requires: `preset`, `formKey`, `heading`. */
18
+ const bare = { preset: 'default', formKey: 'contact', heading: 'Send us a message' };
19
+
20
+ type Submit = StorefrontSource['forms']['submit'];
21
+
22
+ /** The demo storefront with `forms.submit` replaced, and optionally a Turnstile site key on the
23
+ * definition — the two things a spec here needs to steer. */
24
+ function withForms(options: {
25
+ submit?: Submit;
26
+ turnstileSiteKey?: string;
27
+ successRedirect?: string;
28
+ locale?: string;
29
+ }) {
30
+ const base = createDemoStorefront({ formLocale: options.locale });
31
+ return {
32
+ ...base,
33
+ forms: {
34
+ definition: (key: Parameters<StorefrontSource['forms']['definition']>[0]) => {
35
+ const result = base.forms.definition(key);
36
+ if (options.turnstileSiteKey === undefined && options.successRedirect === undefined) {
37
+ return result;
38
+ }
39
+ const { data } = result;
40
+ return {
41
+ ...result,
42
+ get data() {
43
+ return {
44
+ get value(): StorefrontFormDefinition | null {
45
+ return data.value === null
46
+ ? null
47
+ : {
48
+ ...data.value,
49
+ turnstileSiteKey: options.turnstileSiteKey ?? null,
50
+ successRedirect: options.successRedirect ?? null,
51
+ };
52
+ },
53
+ } as typeof data;
54
+ },
55
+ };
56
+ },
57
+ submit: options.submit ?? base.forms.submit,
58
+ },
59
+ };
60
+ }
61
+
62
+ const trackedWrappers: VueWrapper[] = [];
63
+ afterEach(() => {
64
+ vi.unstubAllGlobals();
65
+ for (const wrapper of trackedWrappers.splice(0)) wrapper.unmount();
66
+ document.head.querySelectorAll('script[src*="turnstile"]').forEach((node) => node.remove());
67
+ delete (window as { turnstile?: unknown }).turnstile;
68
+ });
69
+
70
+ async function mountForm(
71
+ data: Record<string, unknown>,
72
+ options: {
73
+ submit?: Submit;
74
+ turnstileSiteKey?: string;
75
+ successRedirect?: string;
76
+ locale?: string;
77
+ } = {}
78
+ ) {
79
+ const base = mountOptions({ entry: { id: 'e1', data } }, { locale: options.locale });
80
+ const custom =
81
+ options.submit ||
82
+ options.turnstileSiteKey !== undefined ||
83
+ options.successRedirect !== undefined
84
+ ? { [STOREFRONT_KEY]: withForms(options) }
85
+ : {};
86
+ const wrapper = mount(Block, {
87
+ ...base,
88
+ attachTo: document.body,
89
+ global: { ...base.global, provide: { ...base.global.provide, ...custom } },
90
+ });
91
+ trackedWrappers.push(wrapper);
92
+ await flushPromises();
93
+ return wrapper;
94
+ }
95
+
96
+ const ok = (pending = false): Submit => vi.fn(async () => ({ ok: true, pending }));
97
+
98
+ async function submit(wrapper: VueWrapper) {
99
+ await wrapper.find('form').trigger('submit');
100
+ await flushPromises();
101
+ }
102
+
103
+ async function fillContact(wrapper: VueWrapper) {
104
+ await wrapper.find('input[name="name"]').setValue('Anna Jónsdóttir');
105
+ await wrapper.find('input[name="email"]').setValue('anna@example.is');
106
+ await wrapper.find('textarea[name="message"]').setValue('Where is my order, please?');
107
+ }
108
+
109
+ describe('form block', () => {
110
+ describe('rendering from the definition', () => {
111
+ it('renders every field of the form the key names, labelled, with no axe violations', async () => {
112
+ const wrapper = await mountForm(mock);
113
+ expect(wrapper.text()).toContain(mock.heading);
114
+ expect(wrapper.text()).toContain(mock.text);
115
+ for (const label of ['Name', 'Email address', 'Message']) {
116
+ expect(wrapper.find('label').exists()).toBe(true);
117
+ expect(wrapper.text()).toContain(label);
118
+ }
119
+ const name = wrapper.get('input[name="name"]');
120
+ const label = wrapper.get(`label[for="${name.attributes('id')}"]`);
121
+ expect(label.text()).toContain('Name');
122
+ expect(wrapper.get('input[name="email"]').attributes('type')).toBe('email');
123
+ expect(wrapper.get('input[name="email"]').attributes('autocomplete')).toBe('email');
124
+ expect(wrapper.find('textarea[name="message"]').exists()).toBe(true);
125
+ expect(await axe(wrapper.element)).toHaveNoViolations();
126
+ });
127
+
128
+ it('renders the bare, required-fields-only content with the default button label', async () => {
129
+ const wrapper = await mountForm(bare);
130
+ expect(wrapper.get('button[type="submit"]').text()).toBe(enUS.form.submit);
131
+ expect(await axe(wrapper.element)).toHaveNoViolations();
132
+ });
133
+
134
+ it('renders the fields in the page locale', async () => {
135
+ const wrapper = await mountForm(mock, { locale: 'is-IS', submit: ok() });
136
+ expect(wrapper.text()).toContain('Netfang');
137
+ expect(wrapper.text()).toContain('Skilaboð');
138
+ });
139
+
140
+ it('is one h2, and the form is named by it or by the form name', async () => {
141
+ const wrapper = await mountForm(mock);
142
+ expect(wrapper.findAll('h1')).toHaveLength(0);
143
+ expect(wrapper.findAll('h2')).toHaveLength(1);
144
+ expect(wrapper.get('form').attributes('aria-label')).toBe('Contact');
145
+ expect(wrapper.get('section').attributes('aria-labelledby')).toBe(
146
+ wrapper.get('h2').attributes('id')
147
+ );
148
+ });
149
+
150
+ it.each(['default', 'inline'] as const)(
151
+ 'renders the %s layout with no axe violations',
152
+ async (variant) => {
153
+ const wrapper = await mountForm({ ...mock, preset: variant });
154
+ expect(await axe(wrapper.element)).toHaveNoViolations();
155
+ }
156
+ );
157
+
158
+ it('the inline layout puts a single field and the button on one grid row', async () => {
159
+ const wrapper = await mountForm({ ...mock, preset: 'inline', formKey: 'newsletter' });
160
+ expect(wrapper.get('[data-part="fields"]').classes().join(' ')).toContain(
161
+ 'grid-cols-[1fr_auto]'
162
+ );
163
+ const fields = wrapper.get('[data-part="fields"]');
164
+ expect(fields.find('button[type="submit"]').exists()).toBe(true);
165
+ expect(await axe(wrapper.element)).toHaveNoViolations();
166
+ });
167
+
168
+ describe('the consent sentence of a subscribing form', () => {
169
+ const SENTENCE =
170
+ 'I want to receive the newsletter from Northwind Goods. I can unsubscribe at any time.';
171
+
172
+ it('shows it under the submit button, tied to it with aria-describedby', async () => {
173
+ const wrapper = await mountForm({ ...mock, formKey: 'newsletter' });
174
+ const sentence = wrapper.get('[data-part="consent-sentence"]');
175
+ expect(sentence.text()).toBe(SENTENCE);
176
+ expect(wrapper.get('button[type="submit"]').attributes('aria-describedby')).toBe(
177
+ sentence.attributes('id')
178
+ );
179
+ expect(await axe(wrapper.element)).toHaveNoViolations();
180
+ });
181
+
182
+ it('shows it for the inline preset too, in the page’s locale', async () => {
183
+ const wrapper = await mountForm(
184
+ { ...mock, preset: 'inline', formKey: 'newsletter' },
185
+ { locale: 'is-IS', submit: ok() }
186
+ );
187
+ expect(wrapper.get('[data-part="consent-sentence"]').text()).toBe(
188
+ 'Ég vil fá fréttabréf frá Northwind Goods. Ég get skráð mig úr áskrift hvenær sem er.'
189
+ );
190
+ });
191
+
192
+ it('shows nothing on a form that does not subscribe', async () => {
193
+ const wrapper = await mountForm(mock);
194
+ expect(wrapper.find('[data-part="consent-sentence"]').exists()).toBe(false);
195
+ expect(wrapper.get('button[type="submit"]').attributes('aria-describedby')).toBeUndefined();
196
+ });
197
+ });
198
+
199
+ it('an inline form of several fields falls back to stacked fields and an actions row', async () => {
200
+ const wrapper = await mountForm({ ...mock, preset: 'inline' });
201
+ expect(wrapper.get('[data-part="fields"]').classes().join(' ')).not.toContain(
202
+ 'grid-cols-[1fr_auto]'
203
+ );
204
+ expect(wrapper.get('[data-part="actions"]').find('button[type="submit"]').exists()).toBe(
205
+ true
206
+ );
207
+ });
208
+
209
+ it('renders on a primary background with no axe violations', async () => {
210
+ const wrapper = await mountForm({ ...mock, sectionBackground: 'primary' });
211
+ expect(await axe(wrapper.element)).toHaveNoViolations();
212
+ });
213
+
214
+ it('says so, and renders no form, for a key the platform does not know', async () => {
215
+ const wrapper = await mountForm({ ...bare, formKey: 'nope' });
216
+ expect(wrapper.find('form').exists()).toBe(false);
217
+ expect(wrapper.get('[role="alert"]').text()).toBe(enUS.form.loadFailed);
218
+ expect(await axe(wrapper.element)).toHaveNoViolations();
219
+ });
220
+ });
221
+
222
+ describe('keyboard', () => {
223
+ it('reaches each field in definition order, then the button; the honeypot is never tabbable', async () => {
224
+ const wrapper = await mountForm(mock);
225
+ const tabbable = [
226
+ ...wrapper.element.querySelectorAll<HTMLElement>(
227
+ 'input, textarea, select, button, a[href], [tabindex]'
228
+ ),
229
+ ].filter((element) => {
230
+ if (element.closest('[inert]')) return false;
231
+ return element.getAttribute('tabindex') !== '-1';
232
+ });
233
+ const names = tabbable.map((element) => element.getAttribute('name') ?? element.tagName);
234
+ expect(names.indexOf('name')).toBeLessThan(names.indexOf('email'));
235
+ expect(names.indexOf('email')).toBeLessThan(names.indexOf('message'));
236
+ expect(names.at(-1)).toBe('BUTTON');
237
+ expect(names).not.toContain('website');
238
+ const honeypot = wrapper.get('input[name="website"]');
239
+ expect(honeypot.element.closest('[inert]')).not.toBeNull();
240
+ expect(honeypot.element.closest('[aria-hidden="true"]')).not.toBeNull();
241
+ });
242
+
243
+ it('moves focus to the first invalid field on a failed submit', async () => {
244
+ const wrapper = await mountForm(mock);
245
+ await submit(wrapper);
246
+ expect(document.activeElement).toBe(wrapper.get('input[name="name"]').element);
247
+ });
248
+
249
+ it('moves focus to the status panel on success, which holds the confirmation', async () => {
250
+ const wrapper = await mountForm(mock, { submit: ok() });
251
+ await fillContact(wrapper);
252
+ await submit(wrapper);
253
+ const status = wrapper.get('[role="status"][tabindex="-1"]');
254
+ expect(document.activeElement).toBe(status.element);
255
+ expect(status.text()).toContain(enUS.form.successTitle);
256
+ expect(status.text()).toContain('Thanks. We reply within one business day');
257
+ expect(wrapper.find('form').exists()).toBe(false);
258
+ expect(await axe(wrapper.element)).toHaveNoViolations();
259
+ });
260
+ });
261
+
262
+ describe('field-keyed errors', () => {
263
+ it('shows a failed local check under the field it names, and sends nothing', async () => {
264
+ const send = ok();
265
+ const wrapper = await mountForm(mock, { submit: send });
266
+ await wrapper.find('input[name="email"]').setValue('not an email');
267
+ await submit(wrapper);
268
+
269
+ expect(send).not.toHaveBeenCalled();
270
+ const email = wrapper.get('input[name="email"]');
271
+ expect(email.attributes('aria-invalid')).toBe('true');
272
+ const describedBy = email.attributes('aria-describedby') ?? '';
273
+ expect(wrapper.get(`[id="${describedBy.split(' ')[0]}"]`).text()).toContain(
274
+ 'Enter a full email address'
275
+ );
276
+ expect(wrapper.get('input[name="name"]').attributes('aria-invalid')).toBe('true');
277
+ expect(wrapper.get('textarea[name="message"]').attributes('aria-invalid')).toBe('true');
278
+ expect(wrapper.get('input[name="topic"]').attributes('aria-invalid')).toBeUndefined();
279
+ expect(await axe(wrapper.element)).toHaveNoViolations();
280
+ });
281
+
282
+ it('applies the definition’s own length rule', async () => {
283
+ const wrapper = await mountForm(mock, { submit: ok() });
284
+ await fillContact(wrapper);
285
+ await wrapper.find('textarea[name="message"]').setValue('short');
286
+ await submit(wrapper);
287
+ expect(wrapper.text()).toContain('Use at least 10 characters.');
288
+ });
289
+
290
+ it('clears a field’s error as soon as that field changes, so a retry is not gated', async () => {
291
+ const send = ok();
292
+ const wrapper = await mountForm(mock, { submit: send });
293
+ await submit(wrapper);
294
+ expect(wrapper.get('input[name="name"]').attributes('aria-invalid')).toBe('true');
295
+ await wrapper.find('input[name="name"]').setValue('Anna');
296
+ expect(wrapper.get('input[name="name"]').attributes('aria-invalid')).toBeUndefined();
297
+ await wrapper.find('input[name="email"]').setValue('anna@example.is');
298
+ await wrapper.find('textarea[name="message"]').setValue('A long enough message.');
299
+ await submit(wrapper);
300
+ expect(send).toHaveBeenCalledOnce();
301
+ });
302
+
303
+ it('shows the platform’s 422 messages under the fields they are keyed by, verbatim', async () => {
304
+ const send: Submit = vi.fn(async () => ({
305
+ ok: false as const,
306
+ reason: 'invalid' as const,
307
+ errors: { email: ['That domain does not accept mail.'], message: ['Too spammy.'] },
308
+ form: ['Check the highlighted answers.'],
309
+ }));
310
+ const wrapper = await mountForm(mock, { submit: send });
311
+ await fillContact(wrapper);
312
+ await submit(wrapper);
313
+
314
+ expect(send).toHaveBeenCalledOnce();
315
+ expect(wrapper.text()).toContain('That domain does not accept mail.');
316
+ expect(wrapper.text()).toContain('Too spammy.');
317
+ expect(wrapper.get('input[name="email"]').attributes('aria-invalid')).toBe('true');
318
+ expect(wrapper.get('input[name="name"]').attributes('aria-invalid')).toBeUndefined();
319
+ expect(wrapper.get('[role="alert"]').text()).toContain('Check the highlighted answers.');
320
+ expect(document.activeElement).toBe(wrapper.get('input[name="email"]').element);
321
+ expect(wrapper.find('form').exists()).toBe(true);
322
+ expect(await axe(wrapper.element)).toHaveNoViolations();
323
+ });
324
+
325
+ it('keeps a message for a field this form does not render, instead of dropping it', async () => {
326
+ const send: Submit = vi.fn(async () => ({
327
+ ok: false as const,
328
+ reason: 'invalid' as const,
329
+ errors: { ghost: ['Unknown field.'] },
330
+ form: [],
331
+ }));
332
+ const wrapper = await mountForm(mock, { submit: send });
333
+ await fillContact(wrapper);
334
+ await submit(wrapper);
335
+ expect(wrapper.get('[role="alert"]').text()).toContain('Unknown field.');
336
+ });
337
+
338
+ it.each([
339
+ ['rate-limited', enUS.form.rateLimited],
340
+ ['too-large', enUS.form.tooLarge],
341
+ ['unavailable', enUS.form.unavailable],
342
+ ['unsupported', enUS.form.unsupported],
343
+ ] as const)(
344
+ 'says what a %s refusal means, keeps the answers and allows a retry',
345
+ async (reason, message) => {
346
+ const send: Submit = vi.fn(async () => ({ ok: false as const, reason }));
347
+ const wrapper = await mountForm(mock, { submit: send });
348
+ await fillContact(wrapper);
349
+ await submit(wrapper);
350
+
351
+ expect(wrapper.get('[role="alert"]').text()).toContain(message);
352
+ expect(wrapper.get('input[name="name"]').element).toHaveProperty(
353
+ 'value',
354
+ 'Anna Jónsdóttir'
355
+ );
356
+ await submit(wrapper);
357
+ expect(send).toHaveBeenCalledTimes(2);
358
+ }
359
+ );
360
+ });
361
+
362
+ describe('submitting', () => {
363
+ it('sends the values keyed by field id, with the honeypot only when something filled it', async () => {
364
+ const send = ok();
365
+ const wrapper = await mountForm(mock, { submit: send });
366
+ await fillContact(wrapper);
367
+ await submit(wrapper);
368
+ expect(send).toHaveBeenCalledWith('contact', {
369
+ values: {
370
+ name: 'Anna Jónsdóttir',
371
+ email: 'anna@example.is',
372
+ topic: '',
373
+ orderNumber: '',
374
+ message: 'Where is my order, please?',
375
+ },
376
+ });
377
+ });
378
+
379
+ it('sends what a bot typed into the honeypot as hp', async () => {
380
+ const send = ok();
381
+ const wrapper = await mountForm(mock, { submit: send });
382
+ await fillContact(wrapper);
383
+ await wrapper.find('input[name="website"]').setValue('http://spam.example');
384
+ await submit(wrapper);
385
+ expect(send).toHaveBeenCalledWith(
386
+ 'contact',
387
+ expect.objectContaining({ hp: 'http://spam.example' })
388
+ );
389
+ });
390
+
391
+ it('ignores repeat submits while one is in flight', async () => {
392
+ let release!: (result: StorefrontFormSubmitResult) => void;
393
+ const send: Submit = vi.fn(
394
+ () =>
395
+ new Promise<StorefrontFormSubmitResult>((resolve) => {
396
+ release = resolve;
397
+ })
398
+ );
399
+ const wrapper = await mountForm(mock, { submit: send });
400
+ await fillContact(wrapper);
401
+ await wrapper.find('form').trigger('submit');
402
+ await wrapper.find('form').trigger('submit');
403
+ expect(send).toHaveBeenCalledOnce();
404
+ release({ ok: true, pending: false });
405
+ await flushPromises();
406
+ expect(wrapper.find('form').exists()).toBe(false);
407
+ });
408
+
409
+ it('a pending (double opt-in) success tells the visitor to check their inbox', async () => {
410
+ const wrapper = await mountForm(
411
+ { ...mock, preset: 'inline', formKey: 'newsletter' },
412
+ { submit: ok(true) }
413
+ );
414
+ await wrapper.find('input[name="email"]').setValue('anna@example.is');
415
+ await submit(wrapper);
416
+ const status = wrapper.get('[role="status"][tabindex="-1"]');
417
+ expect(status.text()).toContain(enUS.form.successTitlePending);
418
+ expect(status.text()).toContain('Check your inbox to confirm your subscription.');
419
+ });
420
+
421
+ it('the block’s own success title wins over the default', async () => {
422
+ const wrapper = await mountForm(
423
+ { ...mock, successTitle: 'Message received' },
424
+ { submit: ok() }
425
+ );
426
+ await fillContact(wrapper);
427
+ await submit(wrapper);
428
+ expect(wrapper.get('[role="status"]').text()).toContain('Message received');
429
+ });
430
+
431
+ it('offers another message after a success and focuses the first field', async () => {
432
+ const wrapper = await mountForm(mock, { submit: ok() });
433
+ await fillContact(wrapper);
434
+ await submit(wrapper);
435
+ await wrapper.get('[role="status"] button').trigger('click');
436
+ await flushPromises();
437
+ expect(wrapper.find('form').exists()).toBe(true);
438
+ expect(wrapper.get('input[name="name"]').element).toHaveProperty('value', '');
439
+ expect(document.activeElement).toBe(wrapper.get('input[name="name"]').element);
440
+ });
441
+ });
442
+
443
+ describe('redirect', () => {
444
+ it('sends the visitor to the merchant’s redirect instead of showing the panel', async () => {
445
+ const assign = vi.fn();
446
+ vi.stubGlobal('location', { ...window.location, assign });
447
+ const wrapper = await mountForm(mock, { submit: ok(), successRedirect: '/thank-you' });
448
+ await fillContact(wrapper);
449
+ await submit(wrapper);
450
+ expect(assign).toHaveBeenCalledWith('/thank-you');
451
+ });
452
+
453
+ it('never follows an executable redirect, and shows the confirmation instead', async () => {
454
+ const assign = vi.fn();
455
+ vi.stubGlobal('location', { ...window.location, assign });
456
+ const wrapper = await mountForm(mock, {
457
+ submit: ok(),
458
+ successRedirect: 'javascript:alert(1)',
459
+ });
460
+ await fillContact(wrapper);
461
+ await submit(wrapper);
462
+ expect(assign).not.toHaveBeenCalled();
463
+ expect(wrapper.get('[role="status"]').text()).toContain(enUS.form.successTitle);
464
+ });
465
+ });
466
+
467
+ describe('turnstile', () => {
468
+ it('loads nothing third-party when the form has no site key', async () => {
469
+ await mountForm(mock);
470
+ expect(document.head.querySelector('script[src*="turnstile"]')).toBeNull();
471
+ });
472
+
473
+ it('renders the widget under the fields and refuses to send before the check is passed', async () => {
474
+ let callback: ((token: string) => void) | undefined;
475
+ const render = vi.fn((_el: HTMLElement, options: { callback: (token: string) => void }) => {
476
+ callback = options.callback;
477
+ return 'widget-1';
478
+ });
479
+ const reset = vi.fn();
480
+ (window as unknown as { turnstile: unknown }).turnstile = { render, reset, remove: vi.fn() };
481
+ const send = ok();
482
+ const wrapper = await mountForm(mock, {
483
+ submit: send,
484
+ turnstileSiteKey: '1x00000000000000000000AA',
485
+ });
486
+ await flushPromises();
487
+
488
+ expect(render).toHaveBeenCalledWith(
489
+ expect.any(HTMLElement),
490
+ expect.objectContaining({ sitekey: '1x00000000000000000000AA' })
491
+ );
492
+ await fillContact(wrapper);
493
+ await submit(wrapper);
494
+ expect(send).not.toHaveBeenCalled();
495
+ expect(wrapper.get('[role="alert"]').text()).toContain(enUS.form.turnstileRequired);
496
+
497
+ callback?.('token-123');
498
+ await flushPromises();
499
+ await submit(wrapper);
500
+ expect(send).toHaveBeenCalledWith(
501
+ 'contact',
502
+ expect.objectContaining({ turnstileToken: 'token-123' })
503
+ );
504
+ });
505
+
506
+ it('resets the single-use token after a refusal', async () => {
507
+ let callback: ((token: string) => void) | undefined;
508
+ const reset = vi.fn();
509
+ (window as unknown as { turnstile: unknown }).turnstile = {
510
+ render: (_el: HTMLElement, options: { callback: (token: string) => void }) => {
511
+ callback = options.callback;
512
+ return 'w';
513
+ },
514
+ reset,
515
+ remove: vi.fn(),
516
+ };
517
+ const send: Submit = vi.fn(async () => ({
518
+ ok: false as const,
519
+ reason: 'unavailable' as const,
520
+ }));
521
+ const wrapper = await mountForm(mock, { submit: send, turnstileSiteKey: 'key' });
522
+ await flushPromises();
523
+ callback?.('t1');
524
+ await fillContact(wrapper);
525
+ await submit(wrapper);
526
+ expect(reset).toHaveBeenCalledOnce();
527
+ });
528
+ });
529
+
530
+ describe('editing', () => {
531
+ it('is empty-safe: a block with no form key renders without crashing', async () => {
532
+ const wrapper = await mountForm({ preset: 'default', formKey: '', heading: 'Hello' });
533
+ expect(wrapper.find('form').exists()).toBe(false);
534
+ });
535
+ });
536
+ });
@@ -0,0 +1,69 @@
1
+ {
2
+ "apiId": "form",
3
+ "name": "Form",
4
+ "description": "A form from the Forms page: contact, newsletter or any form you build, with the fields, spam protection and emails managed in Studio.",
5
+ "icon": "mail",
6
+ "category": "marketing",
7
+ "version": 1,
8
+ "fields": [
9
+ {
10
+ "fieldId": "preset",
11
+ "name": "Layout",
12
+ "type": "select",
13
+ "helpText": "default stacks the fields. inline puts a single field and the button on one row, for a sign-up.",
14
+ "metadata": { "options": ["default", "inline"] },
15
+ "validators": { "required": true }
16
+ },
17
+ {
18
+ "fieldId": "formKey",
19
+ "name": "Form",
20
+ "type": "string",
21
+ "helpText": "The key of the form on the Forms page, for example \"contact\" or \"newsletter\".",
22
+ "validators": { "required": true }
23
+ },
24
+ {
25
+ "fieldId": "heading",
26
+ "name": "Heading",
27
+ "type": "string",
28
+ "isTitle": true,
29
+ "localized": true,
30
+ "validators": { "required": true }
31
+ },
32
+ {
33
+ "fieldId": "text",
34
+ "name": "Text",
35
+ "type": "text",
36
+ "localized": true,
37
+ "helpText": "What the visitor gets, or what happens next."
38
+ },
39
+ {
40
+ "fieldId": "buttonLabel",
41
+ "name": "Button label",
42
+ "type": "string",
43
+ "localized": true,
44
+ "helpText": "Defaults to \"Send\" when unset."
45
+ },
46
+ {
47
+ "fieldId": "consent",
48
+ "name": "Consent",
49
+ "type": "rich-text",
50
+ "localized": true,
51
+ "helpText": "One line with a privacy link, shown under the button. Inline links only.",
52
+ "metadata": { "toolbar": ["bold", "italic", "link", "undo", "redo"] }
53
+ },
54
+ {
55
+ "fieldId": "successTitle",
56
+ "name": "Success title",
57
+ "type": "string",
58
+ "localized": true,
59
+ "helpText": "Shown above the form's own confirmation text. Defaults to \"Thank you\"."
60
+ },
61
+ {
62
+ "fieldId": "sectionBackground",
63
+ "name": "Section background",
64
+ "type": "select",
65
+ "helpText": "Defaults to \"none\" when unset.",
66
+ "metadata": { "options": ["none", "surface", "surface-strong", "primary", "accent"] }
67
+ }
68
+ ]
69
+ }
@@ -0,0 +1,25 @@
1
+ {
2
+ "preset": "default",
3
+ "formKey": "contact",
4
+ "heading": "Send us a message",
5
+ "text": "Questions about an order, a wholesale enquiry or just which glaze to choose: a real person will answer.",
6
+ "buttonLabel": "Send message",
7
+ "consent": {
8
+ "type": "doc",
9
+ "content": [
10
+ {
11
+ "type": "paragraph",
12
+ "content": [
13
+ { "type": "text", "text": "We only use your details to reply. Read our " },
14
+ {
15
+ "type": "text",
16
+ "marks": [{ "type": "link", "attrs": { "href": "/pages/privacy" } }],
17
+ "text": "privacy policy"
18
+ },
19
+ { "type": "text", "text": "." }
20
+ ]
21
+ }
22
+ ]
23
+ },
24
+ "sectionBackground": "none"
25
+ }
Binary file