@eldrajs/theme-cli 0.2.1 → 0.2.3

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 (67) hide show
  1. package/package.json +3 -3
  2. package/template/.eldra/previews.json +35 -35
  3. package/template/.github/workflows/eldra-deploy.yml +29 -2
  4. package/template/.gitlab-ci.yml +37 -10
  5. package/template/README.md +4 -4
  6. package/template/app/composables/useFormSpam.ts +1 -0
  7. package/template/app/plugins/chunk-reload.client.ts +29 -0
  8. package/template/app/plugins/eldra-storefront.ts +8 -0
  9. package/template/app/storefront/gateway.ts +34 -11
  10. package/template/app/storefront/sharedRead.ts +34 -0
  11. package/template/app/storefront/structuredData.ts +17 -0
  12. package/template/app/utils/chunkReload.ts +11 -0
  13. package/template/bitbucket-pipelines.yml +26 -6
  14. package/template/blocks/announcement-bar/preview.png +0 -0
  15. package/template/blocks/article/preview.png +0 -0
  16. package/template/blocks/article-list/preview.png +0 -0
  17. package/template/blocks/breadcrumbs/preview.png +0 -0
  18. package/template/blocks/cart/preview.png +0 -0
  19. package/template/blocks/collection-grid/Block.vue +146 -94
  20. package/template/blocks/collection-grid/__tests__/Block.spec.ts +116 -2
  21. package/template/blocks/collection-grid/preview.png +0 -0
  22. package/template/blocks/collection-header/preview.png +0 -0
  23. package/template/blocks/contact/preview.png +0 -0
  24. package/template/blocks/cta/preview.png +0 -0
  25. package/template/blocks/faq/preview.png +0 -0
  26. package/template/blocks/feature-grid/preview.png +0 -0
  27. package/template/blocks/footer/Block.vue +11 -4
  28. package/template/blocks/footer/__tests__/Block.spec.ts +68 -3
  29. package/template/blocks/footer/preview.png +0 -0
  30. package/template/blocks/form/preview.png +0 -0
  31. package/template/blocks/gallery/preview.png +0 -0
  32. package/template/blocks/hero/preview.png +0 -0
  33. package/template/blocks/image/preview.png +0 -0
  34. package/template/blocks/logo-cloud/preview.png +0 -0
  35. package/template/blocks/navigation/Block.vue +125 -541
  36. package/template/blocks/navigation/__tests__/Block.spec.ts +172 -73
  37. package/template/blocks/navigation/parts/MenuLink.vue +15 -0
  38. package/template/blocks/navigation/preview.png +0 -0
  39. package/template/blocks/newsletter/preview.png +0 -0
  40. package/template/blocks/order-status/preview.png +0 -0
  41. package/template/blocks/pricing-table/preview.png +0 -0
  42. package/template/blocks/product-carousel/preview.png +0 -0
  43. package/template/blocks/product-detail/preview.png +0 -0
  44. package/template/blocks/quote/preview.png +0 -0
  45. package/template/blocks/rich-text/preview.png +0 -0
  46. package/template/blocks/search/preview.png +0 -0
  47. package/template/blocks/split-content/preview.png +0 -0
  48. package/template/blocks/stats/preview.png +0 -0
  49. package/template/blocks/tabs/preview.png +0 -0
  50. package/template/blocks/team/preview.png +0 -0
  51. package/template/blocks/testimonials/preview.png +0 -0
  52. package/template/blocks/timeline/preview.png +0 -0
  53. package/template/blocks/trust-strip/preview.png +0 -0
  54. package/template/blocks/video-embed/preview.png +0 -0
  55. package/template/blocks/wishlist/preview.png +0 -0
  56. package/template/test/chunkReload.spec.ts +20 -0
  57. package/template/test/imageFraming.browser.spec.ts +125 -0
  58. package/template/test/pages/article.spec.ts +1 -1
  59. package/template/test/pages/collection.spec.ts +1 -1
  60. package/template/test/pages/home.spec.ts +1 -1
  61. package/template/test/pages/product.spec.ts +1 -1
  62. package/template/test/prerenderRefresh.browser.spec.ts +8 -13
  63. package/template/test/storefront/gateway.spec.ts +6 -0
  64. package/template/test/storefront/gatewayPrerender.spec.ts +26 -1
  65. package/template/test/storefront/sharedRead.spec.ts +43 -0
  66. package/template/test/storefront/structuredData.spec.ts +31 -0
  67. package/template/blocks/navigation/useMegaMenuKeys.ts +0 -276
@@ -0,0 +1,125 @@
1
+ // @vitest-environment jsdom
2
+ import { readFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { chromium, type Browser, type Page } from '@playwright/test';
5
+ import { compile } from '@tailwindcss/node';
6
+ import { mount } from '@vue/test-utils';
7
+ import { imageFramingStyle, type ImageFraming } from '@eldrajs/theme-vue';
8
+ import { afterAll, beforeAll, describe, expect, it } from 'vitest';
9
+ import UiImage from '../app/components/ui/UiImage.vue';
10
+
11
+ // Studio previews a framing with theme-core's imageFramingStyle; UiImage must draw the same pixels, out-of-band framings too.
12
+
13
+ const assetsDir = `${join(import.meta.dirname, '../app/assets')}/`;
14
+ const PICTURE = 'https://picture.test/frame.png';
15
+
16
+ const FRAMINGS: Array<ImageFraming | null> = [
17
+ null,
18
+ { x: 0.5, y: 0.5, zoom: 1.6 },
19
+ { x: 0.2, y: 0.6, zoom: 2 },
20
+ { x: 0.05, y: 0.95, zoom: 3.5 },
21
+ { x: 1, y: 0, zoom: 4 },
22
+ { x: 0, y: 1, zoom: 2.5 },
23
+ ];
24
+ const ASPECTS = ['16/9', '1/1', '4/5'];
25
+ const CASES = ASPECTS.flatMap((aspect) => FRAMINGS.map((framing) => ({ aspect, framing })));
26
+
27
+ const styleText = (style: Record<string, string>) =>
28
+ Object.entries(style)
29
+ .map(([property, value]) => `${property}:${value}`)
30
+ .join(';');
31
+
32
+ describe('a page-builder framing through UiImage, in a real browser', () => {
33
+ let browser: Browser;
34
+ let page: Page;
35
+
36
+ beforeAll(async () => {
37
+ const rendered = CASES.map(({ aspect, framing }) => {
38
+ const wrapper = mount(UiImage, { props: { src: PICTURE, alt: '', aspect, framing } });
39
+ const html = wrapper.html();
40
+ wrapper.unmount();
41
+ return html;
42
+ });
43
+ const candidates = [...rendered.join('').matchAll(/class="([^"]*)"/g)].flatMap((match) =>
44
+ match[1]!.split(/\s+/).filter(Boolean)
45
+ );
46
+ const compiler = await compile(readFileSync(`${assetsDir}main.css`, 'utf8'), {
47
+ base: assetsDir,
48
+ onDependency() {},
49
+ });
50
+ const css = compiler.build([...new Set(candidates)]);
51
+ const columns = CASES.map(({ aspect, framing }, i) => {
52
+ const reference =
53
+ `<div class="ref" style="position:relative;overflow:hidden;aspect-ratio:${aspect}">` +
54
+ `<img src="${PICTURE}" alt="" style="display:block;width:100%;height:100%;${styleText(imageFramingStyle(framing))}"></div>`;
55
+ return `<div class="case">${rendered[i]}${reference}</div>`;
56
+ });
57
+
58
+ browser = await chromium.launch();
59
+ page = await browser.newPage({ viewport: { width: 1200, height: 900 } });
60
+ await page.route(PICTURE, async (route) => {
61
+ const png = await page.evaluate(() => {
62
+ const canvas = Object.assign(document.createElement('canvas'), {
63
+ width: 1600,
64
+ height: 900,
65
+ });
66
+ const ctx = canvas.getContext('2d')!;
67
+ const gradient = ctx.createLinearGradient(0, 0, 1600, 900);
68
+ gradient.addColorStop(0, '#1d3557');
69
+ gradient.addColorStop(0.5, '#e9c46a');
70
+ gradient.addColorStop(1, '#e63946');
71
+ ctx.fillStyle = gradient;
72
+ ctx.fillRect(0, 0, 1600, 900);
73
+ ctx.strokeStyle = '#fff';
74
+ for (let x = 0; x < 1600; x += 37) ctx.strokeRect(x, (x * 7) % 900, 23, 23);
75
+ return canvas.toDataURL('image/png').split(',')[1]!;
76
+ });
77
+ await route.fulfill({ body: Buffer.from(png, 'base64'), contentType: 'image/png' });
78
+ });
79
+ await page.setContent(
80
+ `<style>${css} body{margin:0} .case{display:flex;gap:20px;height:400px;align-items:flex-start}` +
81
+ `.case>*{flex:none;width:300px}</style>` +
82
+ `<main>${columns.join('')}</main>`
83
+ );
84
+ await page.evaluate(() =>
85
+ Promise.all([...document.images].map((img) => ((img.loading = 'eager'), img.decode())))
86
+ );
87
+ }, 120_000);
88
+
89
+ // theme-core prints percentages to 4 places and UiImage passes x * 100 as is, so an edge pixel can differ by a few levels.
90
+ const largestDifference = (a: Buffer, b: Buffer) =>
91
+ page.evaluate(
92
+ async ([a, b]) => {
93
+ const pixels = async (data: string) => {
94
+ const bitmap = await createImageBitmap(
95
+ await (await fetch(`data:image/png;base64,${data}`)).blob()
96
+ );
97
+ const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
98
+ const ctx = canvas.getContext('2d')!;
99
+ ctx.drawImage(bitmap, 0, 0);
100
+ return ctx.getImageData(0, 0, bitmap.width, bitmap.height);
101
+ };
102
+ const [pa, pb] = await Promise.all([pixels(a!), pixels(b!)]);
103
+ if (pa.width !== pb.width || pa.height !== pb.height) return Number.POSITIVE_INFINITY;
104
+ let largest = 0;
105
+ for (let i = 0; i < pa.data.length; i++)
106
+ largest = Math.max(largest, Math.abs(pa.data[i]! - pb.data[i]!));
107
+ return largest;
108
+ },
109
+ [a.toString('base64'), b.toString('base64')]
110
+ );
111
+
112
+ afterAll(async () => {
113
+ await browser?.close();
114
+ });
115
+
116
+ it.each(CASES.map((c, i) => [c.aspect, JSON.stringify(c.framing), i] as const))(
117
+ 'draws %s at %s exactly as Studio previews it',
118
+ async (_aspect, _framing, i) => {
119
+ const item = page.locator('.case').nth(i);
120
+ const site = await item.locator('[data-part="frame"]').screenshot();
121
+ const studio = await item.locator('.ref').screenshot();
122
+ expect(await largestDifference(site, studio)).toBeLessThanOrEqual(8);
123
+ }
124
+ );
125
+ });
@@ -31,7 +31,7 @@ describe('article sample page', () => {
31
31
 
32
32
  // Tag + landmark identity, in document order.
33
33
  expect(headerEl!.tagName).toBe('HEADER');
34
- expect(headerEl!.querySelector('nav')).not.toBeNull();
34
+ expect(headerEl!.querySelector('[data-eldra-header-focus]')).not.toBeNull();
35
35
  expect(breadcrumbsEl!.tagName).toBe('DIV');
36
36
  expect(breadcrumbsEl!.querySelector('nav[aria-label]')).not.toBeNull();
37
37
  expect(articleEl!.querySelector('article')).not.toBeNull();
@@ -109,7 +109,7 @@ describe('collection sample page', () => {
109
109
  const [navEl, breadcrumbsEl, headerEl, gridEl, ctaEl, footerEl] = children;
110
110
 
111
111
  expect(navEl!.tagName).toBe('HEADER');
112
- expect(navEl!.querySelector('nav')).not.toBeNull();
112
+ expect(navEl!.querySelector('[data-eldra-header-focus]')).not.toBeNull();
113
113
  expect(breadcrumbsEl!.tagName).toBe('DIV');
114
114
  expect(breadcrumbsEl!.querySelector('nav[aria-label]')).not.toBeNull();
115
115
  expect(headerEl!.tagName).toBe('HEADER');
@@ -84,7 +84,7 @@ describe('home page (pages/home.page.json)', () => {
84
84
  expect(announcement.textContent).toContain('Free shipping on orders over $80');
85
85
 
86
86
  expect(header.tagName).toBe('HEADER');
87
- expect(header.querySelector('nav')).not.toBeNull();
87
+ expect(header.querySelector('[data-eldra-header-focus]')).not.toBeNull();
88
88
 
89
89
  expect(hero.querySelector('h1')?.textContent).toBe('Made slowly, used daily');
90
90
 
@@ -71,7 +71,7 @@ describe('product sample page', () => {
71
71
  const html = wrapper.html();
72
72
  const markers = [
73
73
  'Free shipping on orders over $80', // announcement-bar
74
- 'aria-label="Primary navigation"', // navigation
74
+ 'data-eldra-header-focus', // navigation
75
75
  'aria-label="Breadcrumb"', // breadcrumbs
76
76
  'aria-label="Product images"', // product-detail (gallery)
77
77
  'You may also like', // product-carousel
@@ -747,15 +747,10 @@ describe('prerendered commerce data on the generated static site', () => {
747
747
  expect(panelId).not.toBeNull();
748
748
  // Vitest's `expect` here, not Playwright's — the wait is the locator's own.
749
749
  await page.locator(`#${panelId ?? ''}`).waitFor({ state: 'visible' });
750
- // "Visible" is true from the *first* frame of the panel's entrance, and that entrance carries
751
- // a 4px rise (`-translate-y-1` over 150ms, `panelTransition` in `blocks/navigation/Block.vue`).
752
- // Measuring there reads the panel 4px above where it settles — which, plus the bar's own 1px
753
- // border, is exactly the 5px this geometry case used to fail by whenever the machine got to
754
- // `evaluate` inside 150ms. So wait for the transition itself to finish, not just for the
755
- // element to exist.
750
+ // "Visible" holds from the entrance's first frame, so wait for the panel's animations to end.
756
751
  await page.waitForFunction(
757
752
  (id) =>
758
- (document.getElementById(id)?.getAnimations() ?? []).every(
753
+ (document.getElementById(id)?.getAnimations({ subtree: true }) ?? []).every(
759
754
  (animation) => animation.playState !== 'running'
760
755
  ),
761
756
  panelId ?? ''
@@ -774,7 +769,7 @@ describe('prerendered commerce data on the generated static site', () => {
774
769
  const rect = panel.getBoundingClientRect();
775
770
  // The first column of the grid, and the "View all" anchor — the two pieces of content
776
771
  // that decide whether the panel has an inset at all.
777
- const firstColumn = panel.firstElementChild!.getBoundingClientRect();
772
+ const firstColumn = panel.querySelector('[data-part="group"]')!.getBoundingClientRect();
778
773
  const viewAll = panel.querySelector('[data-eldra-mega-view-all]')!.getBoundingClientRect();
779
774
  return {
780
775
  panel: { left: rect.left, right: rect.right, bottom: rect.bottom, top: rect.top },
@@ -810,7 +805,7 @@ describe('prerendered commerce data on the generated static site', () => {
810
805
  // resolve `--eldra-header-surface` through the theme's token variables, which exist only in a
811
806
  // real stylesheet — jsdom sees the class names and no colour at all. Second the leave: a panel
812
807
  // that merely stops being `display: block` is indistinguishable, in a mounted test, from one
813
- // that fades out over 120ms, and the fade is the whole point of the change.
808
+ // that fades out over `--eldra-duration-fast`, and the fade is the whole point of the change.
814
809
  //
815
810
  // Both bar states are measured, because they are the two different grounds the bar can be
816
811
  // asked about: the home page's header is solid, and the collection template's carries
@@ -851,8 +846,9 @@ describe('prerendered commerce data on the generated static site', () => {
851
846
 
852
847
  const open = await page.evaluate((id) => {
853
848
  const bar = document.querySelector('header')!;
849
+ const sheet = document.getElementById(id)!.querySelector('[data-part="content"]')!;
854
850
  return {
855
- panel: getComputedStyle(document.getElementById(id)!).backgroundColor,
851
+ panel: getComputedStyle(sheet).backgroundColor,
856
852
  bar: getComputedStyle(bar).backgroundColor,
857
853
  transparentAttribute: bar.getAttribute('data-eldra-transparent'),
858
854
  };
@@ -888,8 +884,7 @@ describe('prerendered commerce data on the generated static site', () => {
888
884
  panelId
889
885
  );
890
886
  expect(leave.faded, `${path} fades out`).toBe(true);
891
- // 120ms of leave: comfortably more than the frame a bare `v-show` would have taken, and
892
- // nowhere near a panel that never leaves at all.
887
+ // 150ms of leave (`--eldra-duration-fast`): more than a bare `v-show`'s one frame, less than never.
893
888
  expect(leave.hiddenAfterMs, path).toBeGreaterThanOrEqual(60);
894
889
  expect(leave.hiddenAfterMs, path).toBeLessThan(1000);
895
890
  expect(await trigger.getAttribute('aria-expanded'), path).toBe('false');
@@ -959,7 +954,7 @@ describe('prerendered commerce data on the generated static site', () => {
959
954
  // same classes. A difference here is a page that jumps on hydration.
960
955
  reserved:
961
956
  spacer === null ? null : spacer.firstElementChild!.getBoundingClientRect().height,
962
- nav: element.querySelector('nav')!.getBoundingClientRect().height,
957
+ nav: element.querySelector('[data-eldra-header-bar]')!.getBoundingClientRect().height,
963
958
  wrapper: wrapper === null ? null : wrapper.getBoundingClientRect().height,
964
959
  };
965
960
  });
@@ -976,6 +976,12 @@ describe('createGatewayStorefront', () => {
976
976
  * cannot read stock into an error for no reason. One box is sent in the platform's own
977
977
  * spelling, which the retired hyphenated one folds into.
978
978
  */
979
+ it('sends the on-sale switch as onSale=true, and nothing for a switch the platform does not name', async () => {
980
+ expect((await paramsFor({ 'toggle:on_sale': ['1'] })).get('onSale')).toBe('true');
981
+ expect((await paramsFor({ 'toggle:pre_order': ['1'] })).has('onSale')).toBe(false);
982
+ expect((await paramsFor({ 'toggle:on_sale': [] })).has('onSale')).toBe(false);
983
+ });
984
+
979
985
  it('sends one availability value, never both, and never an unknown one', async () => {
980
986
  expect((await paramsFor({ availability: ['in_stock'] })).get('availability')).toBe(
981
987
  'in_stock'
@@ -3,8 +3,10 @@ import { describe, expect, it } from 'vitest';
3
3
  import { createEldraClient, type EldraClient, type EldraHttpRequest } from '@eldrajs/sdk';
4
4
  import {
5
5
  createGatewayStorefront,
6
+ type GatewayStorefrontOptions,
6
7
  type StorefrontPrerenderHandle,
7
8
  } from '../../app/storefront/gateway';
9
+ import { CATEGORIES_MEMO_NAME } from '../../app/storefront/sharedRead';
8
10
  import { createVolatileRefresher, type VolatileRefresher } from '../../app/storefront/refresh';
9
11
  import {
10
12
  prerenderThroughAsyncData,
@@ -171,7 +173,8 @@ function asyncDataStub(payload: Record<string, unknown> = {}) {
171
173
  function wire(
172
174
  client: EldraClient,
173
175
  prerender?: <T>(key: string, load: () => Promise<T | null>) => StorefrontPrerenderHandle<T>,
174
- locale?: () => string | undefined
176
+ locale?: () => string | undefined,
177
+ shared?: GatewayStorefrontOptions['shared']
175
178
  ): { storefront: StorefrontSource; refresher: VolatileRefresher } {
176
179
  // The refresh runs when this spec says so, not on a schedule of its own. It reaches the
177
180
  // storefront declared below through the closure, exactly as the plugin's does.
@@ -183,6 +186,7 @@ function wire(
183
186
  route: fakeRoute(),
184
187
  runtime: { prerender, register: refresher.register },
185
188
  locale,
189
+ shared,
186
190
  });
187
191
  return { storefront, refresher };
188
192
  }
@@ -1035,3 +1039,24 @@ describe('gateway storefront — `loading`, and who is allowed to write', () =>
1035
1039
  expect(grid.loading.value).toBe(false);
1036
1040
  });
1037
1041
  });
1042
+
1043
+ describe('gateway storefront — the shared category read (WS-406)', () => {
1044
+ it('asks for the category rows under the kit name and the page locale', async () => {
1045
+ const asked: Array<{ name: string; locale: string | undefined }> = [];
1046
+ const shared: GatewayStorefrontOptions['shared'] = (name, load, locale) => {
1047
+ asked.push({ name, locale });
1048
+ return load();
1049
+ };
1050
+ for (const locale of [undefined, 'is-IS']) {
1051
+ const ssr = asyncDataStub();
1052
+ wire(fakeClient().client, ssr.prerender, () => locale, shared).storefront.catalog.product(
1053
+ ref('merino-crew-sweater')
1054
+ );
1055
+ await ssr.settleAll();
1056
+ }
1057
+ expect(asked).toEqual([
1058
+ { name: CATEGORIES_MEMO_NAME, locale: undefined },
1059
+ { name: CATEGORIES_MEMO_NAME, locale: 'is-IS' },
1060
+ ]);
1061
+ });
1062
+ });
@@ -0,0 +1,43 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { createSharedRead } from '../../app/storefront/sharedRead';
3
+
4
+ const CONFIG = {
5
+ gatewayUrl: 'https://origin.example/api',
6
+ orgId: 'org-1',
7
+ };
8
+
9
+ describe('storefront shared reads (WS-406)', () => {
10
+ function keys(config: typeof CONFIG, name: string, locale: string | undefined) {
11
+ const seen: Array<string | null> = [];
12
+ const shared = createSharedRead(config, (scope, _name, load) => {
13
+ seen.push(scope === null ? null : `${scope}|${_name}`);
14
+ return load();
15
+ });
16
+ void shared(name, async () => 1, locale);
17
+ return seen[0];
18
+ }
19
+
20
+ it('keys on gateway, organisation, locale and read name', () => {
21
+ const base = keys(CONFIG, 'categories', 'is-IS');
22
+ expect(base).toBe('https://origin.example/api|org-1|is-IS|categories');
23
+ expect(keys({ ...CONFIG, orgId: 'org-2' }, 'categories', 'is-IS')).not.toBe(base);
24
+ expect(keys(CONFIG, 'categories', 'en-US')).not.toBe(base);
25
+ expect(keys(CONFIG, 'categories', undefined)).toBe(
26
+ 'https://origin.example/api|org-1||categories'
27
+ );
28
+ });
29
+
30
+ it('never shares a read without a gateway and organisation to key on', () => {
31
+ expect(keys({ ...CONFIG, orgId: '' }, 'categories', undefined)).toBeNull();
32
+ });
33
+
34
+ it('keys by the origin gateway, not the browser base', () => {
35
+ const seen: Array<string | null> = [];
36
+ const shared = createSharedRead(CONFIG, (scope, _name, load) => {
37
+ seen.push(scope);
38
+ return load();
39
+ });
40
+ void shared('categories', async () => 1, undefined);
41
+ expect(seen[0]).toContain(CONFIG.gatewayUrl);
42
+ });
43
+ });
@@ -39,6 +39,7 @@ const parts = (over: Partial<PageLdParts> = {}): PageLdParts => ({
39
39
  logoUrl: 'https://media.test/icon-512',
40
40
  sameAs: [],
41
41
  contact: { email: null, telephone: null },
42
+ legal: null,
42
43
  },
43
44
  searchPath: '/search',
44
45
  ...over,
@@ -63,6 +64,36 @@ describe('pageStructuredData', () => {
63
64
  ]);
64
65
  });
65
66
 
67
+ it('writes the registered company on the home Organization', () => {
68
+ const legal = {
69
+ name: 'Eldra Tech ehf.',
70
+ kennitala: '500826-1770',
71
+ streetAddress: null,
72
+ postalCode: '101',
73
+ city: 'Reykjavík',
74
+ countryCode: 'IS',
75
+ };
76
+ const [organization] = pageStructuredData(
77
+ parts({ kind: 'home', profile: { ...parts().profile, legal } })
78
+ );
79
+ expect(organization!.node).toMatchObject({
80
+ legalName: 'Eldra Tech ehf.',
81
+ taxID: '500826-1770',
82
+ address: {
83
+ '@type': 'PostalAddress',
84
+ postalCode: '101',
85
+ addressLocality: 'Reykjavík',
86
+ addressCountry: 'IS',
87
+ },
88
+ });
89
+ expect(organization!.node).not.toHaveProperty('address.streetAddress');
90
+
91
+ const [bare] = pageStructuredData(parts({ kind: 'home' }));
92
+ expect(bare!.node).not.toHaveProperty('legalName');
93
+ expect(bare!.node).not.toHaveProperty('taxID');
94
+ expect(bare!.node).not.toHaveProperty('address');
95
+ });
96
+
66
97
  it('writes nothing for the not-found shell', () => {
67
98
  expect(pageStructuredData(parts({ kind: 'notFound' }))).toEqual([]);
68
99
  });
@@ -1,276 +0,0 @@
1
- /**
2
- * The header bar's mega-menu keyboard model, kept out of `Block.vue` because it is a self-contained
3
- * piece of behaviour over the bar's own DOM — the block keeps the open state and this drives focus
4
- * through it.
5
- *
6
- * The pattern is the WAI-ARIA APG's **Disclosure Navigation Menu** with its arrow-key extension.
7
- * Not a `combobox` (that role belongs to a text input) and not a `menubar` (these are site
8
- * navigation links, not application commands), so there is no `role="menu"`, no
9
- * `aria-activedescendant` and no roving `tabindex`: focus moves to the real links with `.focus()`,
10
- * every one of them stays in the tab sequence, and the only ARIA on the trigger is
11
- * `aria-expanded` / `aria-controls`.
12
- *
13
- * Reading order is the DOM's: the bar's list renders one `<li>` per resolved link — the trigger (or
14
- * plain link) first, then that item's panel — so the `<li>`'s position *is* the `links` index, and
15
- * a panel's links come out of `querySelectorAll` already in the order a visitor reads them (the
16
- * group columns, then the trailing "View all" row). Nothing here keeps a parallel list of elements
17
- * that could fall out of step with what is rendered.
18
- *
19
- * Arrow keys clamp at both ends rather than wrapping: a visitor holding ArrowDown should stop at
20
- * the last row instead of silently landing back on the first.
21
- */
22
- import { nextTick, type Ref } from 'vue';
23
-
24
- /** A focusable top-level item of the bar's list, with the `links` index its `<li>` sits at. */
25
- interface TopLevelItem {
26
- el: HTMLElement;
27
- index: number;
28
- }
29
-
30
- type Edge = 'first' | 'last';
31
-
32
- export interface MegaMenuKeysOptions {
33
- /** The bar's own `<ul>` of top-level items (`null` while the bar renders without it). */
34
- list: Ref<HTMLElement | null>;
35
- /** Which panel is open, `null` for none. */
36
- openIndex: Ref<number | null>;
37
- /** Whether the item at `index` has a mega-menu panel at all. */
38
- hasPanel: (index: number) => boolean;
39
- /** Open `index`'s panel (closing any other) as a keyboard-owned one, which hover never closes. */
40
- open: (index: number) => void;
41
- /** Toggle `index`'s panel. */
42
- toggle: (index: number) => void;
43
- /** Close whatever is open, leaving focus where it is. */
44
- close: () => void;
45
- /** Close `index`'s panel and put focus back on its trigger. */
46
- closeAndFocusTrigger: (index: number) => void;
47
- }
48
-
49
- export interface MegaMenuKeys {
50
- onTriggerKeydown: (index: number, event: KeyboardEvent) => void;
51
- onPanelKeydown: (index: number, event: KeyboardEvent) => void;
52
- onBarLinkKeydown: (index: number, event: KeyboardEvent) => void;
53
- }
54
-
55
- export function useMegaMenuKeys(options: MegaMenuKeysOptions): MegaMenuKeys {
56
- function itemElement(index: number): HTMLElement | null {
57
- const li = options.list.value?.children[index];
58
- return li instanceof HTMLElement ? li : null;
59
- }
60
-
61
- /**
62
- * The bar's focusable top-level items in bar order: a mega-menu trigger (`<button>`) or a plain
63
- * link (`<a>`), each the first element child of its `<li>`. This walks the `<li>` children rather
64
- * than querying the list for `a, button` because an open panel's own links live deeper in that
65
- * same `<li>` and must never be mistaken for a top-level item. An item whose destination no
66
- * longer resolves renders as a `<span>`: not focusable, so an arrow key steps over it instead of
67
- * landing on a dead row.
68
- */
69
- function topLevelItems(): TopLevelItem[] {
70
- const list = options.list.value;
71
- if (list === null) return [];
72
- const items: TopLevelItem[] = [];
73
- const rows = Array.from(list.children);
74
- for (let index = 0; index < rows.length; index += 1) {
75
- for (const child of Array.from(rows[index]!.children)) {
76
- if (child instanceof HTMLElement && (child.tagName === 'BUTTON' || child.tagName === 'A')) {
77
- items.push({ el: child, index });
78
- break;
79
- }
80
- }
81
- }
82
- return items;
83
- }
84
-
85
- /**
86
- * One panel's focusable links, in the panel's own DOM order. A row with no destination renders as
87
- * a `<span>`, so `a[href]` doubles as the "is it focusable" test; `button` is matched too so a
88
- * panel part that grows one later is walked without a change here.
89
- */
90
- function panelLinks(index: number): HTMLElement[] {
91
- const panel = itemElement(index)?.querySelector('[data-eldra-mega-panel]');
92
- if (!(panel instanceof HTMLElement)) return [];
93
- return Array.from(panel.querySelectorAll<HTMLElement>('a[href], button:not([disabled])'));
94
- }
95
-
96
- function clamp(position: number, length: number): number {
97
- return Math.min(Math.max(position, 0), length - 1);
98
- }
99
-
100
- /**
101
- * The panel is `v-show`n, so between the open state changing and Vue flushing it the element is
102
- * still `display: none` — and `focus()` on a hidden element does nothing. Always focus on the
103
- * next tick, which is also harmless when the panel was open already (Home/End inside one).
104
- */
105
- function focusPanelEdge(index: number, edge: Edge): void {
106
- void nextTick(() => {
107
- const links = panelLinks(index);
108
- const target = edge === 'first' ? links[0] : links[links.length - 1];
109
- target?.focus();
110
- });
111
- }
112
-
113
- function focusPanelLink(index: number, position: number): void {
114
- const links = panelLinks(index);
115
- if (links.length === 0) return;
116
- links[clamp(position, links.length)]?.focus();
117
- }
118
-
119
- /** Which link in the panel has focus now, `-1` when focus sits somewhere else in it. */
120
- function focusedPanelPosition(index: number): number {
121
- const active = typeof document === 'undefined' ? null : document.activeElement;
122
- if (active === null) return -1;
123
- return panelLinks(index).findIndex((link) => link === active || link.contains(active));
124
- }
125
-
126
- /**
127
- * Moves focus to another top-level item, and takes the open panel with it.
128
- *
129
- * Focus always lands on the item itself — the trigger button or the plain link — never inside the
130
- * neighbour's panel, wherever it travelled from: the pattern's own rule is "move to the next
131
- * button and expand its dropdown", and `ArrowDown` from there is what enters the panel. That also
132
- * means nothing can strand focus: an open panel with no focusable row of its own (every child's
133
- * destination deleted, and a `kind: "none"` parent so there is no "View all" either) leaves focus
134
- * sitting on its trigger, where every key still works.
135
- *
136
- * The open panel follows: landing on another trigger opens that one, and landing on a plain link
137
- * closes what was open. With nothing open to begin with, this is a plain focus move.
138
- */
139
- function focusTopLevel(position: number): void {
140
- const items = topLevelItems();
141
- const target = items[position];
142
- if (target === undefined) return;
143
- if (options.openIndex.value !== null) {
144
- if (options.hasPanel(target.index)) options.open(target.index);
145
- else options.close();
146
- }
147
- target.el.focus();
148
- }
149
-
150
- /** ArrowRight / ArrowLeft: one step along the bar, clamped at both ends. */
151
- function stepTopLevel(index: number, delta: number): void {
152
- const items = topLevelItems();
153
- const position = items.findIndex((item) => item.index === index);
154
- if (position === -1) return;
155
- const next = clamp(position + delta, items.length);
156
- // Already at that end: nothing moves, and focus stays exactly where the visitor left it.
157
- if (next === position) return;
158
- focusTopLevel(next);
159
- }
160
-
161
- /** Home / End: the bar's first or last item. */
162
- function edgeTopLevel(edge: Edge): void {
163
- const items = topLevelItems();
164
- if (items.length === 0) return;
165
- focusTopLevel(edge === 'first' ? 0 : items.length - 1);
166
- }
167
-
168
- /**
169
- * The four keys that travel the bar's own row, shared by every handler below so they cannot drift
170
- * apart as keys are added. Returns whether it took the key, which is what keeps `preventDefault`
171
- * to the keys actually handled.
172
- */
173
- function barTravel(index: number, event: KeyboardEvent): boolean {
174
- switch (event.key) {
175
- case 'ArrowRight':
176
- event.preventDefault();
177
- stepTopLevel(index, 1);
178
- return true;
179
- case 'ArrowLeft':
180
- event.preventDefault();
181
- stepTopLevel(index, -1);
182
- return true;
183
- case 'Home':
184
- event.preventDefault();
185
- edgeTopLevel('first');
186
- return true;
187
- case 'End':
188
- event.preventDefault();
189
- edgeTopLevel('last');
190
- return true;
191
- default:
192
- return false;
193
- }
194
- }
195
-
196
- function onTriggerKeydown(index: number, event: KeyboardEvent): void {
197
- // `preventDefault` is called only on the keys handled here, so page scrolling and every
198
- // shortcut this block has no business in behave exactly as they do anywhere else.
199
- switch (event.key) {
200
- case 'Enter':
201
- case ' ':
202
- event.preventDefault();
203
- options.toggle(index);
204
- return;
205
- case 'Escape':
206
- if (options.openIndex.value !== index) return;
207
- event.preventDefault();
208
- options.closeAndFocusTrigger(index);
209
- return;
210
- // ArrowDown / ArrowUp open the panel if it is closed and step straight into it, at the end
211
- // the key points at — the APG's own "open and move focus into the disclosure" keys. `open()`
212
- // runs either way, so a panel the pointer opened is the keyboard's from this point on.
213
- case 'ArrowDown':
214
- case 'ArrowUp': {
215
- event.preventDefault();
216
- options.open(index);
217
- focusPanelEdge(index, event.key === 'ArrowDown' ? 'first' : 'last');
218
- return;
219
- }
220
- default:
221
- barTravel(index, event);
222
- return;
223
- }
224
- }
225
-
226
- /**
227
- * The same left/right/Home/End travel along the bar, for a top-level item that is a plain link
228
- * rather than a disclosure. Without it the arrow keys would be a one-way street: a visitor
229
- * arrowing out of a mega-menu onto an ordinary link could not arrow any further, and the bar's
230
- * row would read as navigable in one direction only. Down and up are *not* handled here — a plain
231
- * link has no panel to open, so those keys stay the page's own scroll.
232
- */
233
- function onBarLinkKeydown(index: number, event: KeyboardEvent): void {
234
- barTravel(index, event);
235
- }
236
-
237
- function onPanelKeydown(index: number, event: KeyboardEvent): void {
238
- switch (event.key) {
239
- case 'Escape':
240
- event.preventDefault();
241
- options.closeAndFocusTrigger(index);
242
- return;
243
- // Down and up walk the panel's own reading order, clamped at its ends; Home and End jump to
244
- // them. Tab still moves through the very same links, in the very same order.
245
- case 'ArrowDown':
246
- case 'ArrowUp': {
247
- event.preventDefault();
248
- const position = focusedPanelPosition(index);
249
- if (position < 0) {
250
- // Focus is inside the panel but not on one of its links. Enter at the end the key points
251
- // at, exactly as entering from the trigger does, rather than clamping to the first row.
252
- focusPanelEdge(index, event.key === 'ArrowDown' ? 'first' : 'last');
253
- return;
254
- }
255
- focusPanelLink(index, position + (event.key === 'ArrowDown' ? 1 : -1));
256
- return;
257
- }
258
- case 'Home':
259
- event.preventDefault();
260
- focusPanelEdge(index, 'first');
261
- return;
262
- case 'End':
263
- event.preventDefault();
264
- focusPanelEdge(index, 'last');
265
- return;
266
- // Left and right travel the bar from in here too, landing on the neighbouring item itself.
267
- // Home and End never reach this: in a panel they belong to the panel, and the cases above
268
- // have already taken them.
269
- default:
270
- barTravel(index, event);
271
- return;
272
- }
273
- }
274
-
275
- return { onTriggerKeydown, onPanelKeydown, onBarLinkKeydown };
276
- }