@eldrajs/theme-cli 0.2.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 (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 +2 -0
  6. package/template/.gitlab-ci.yml +2 -0
  7. package/template/.storybook/main.ts +3 -0
  8. package/template/README.md +22 -10
  9. package/template/app/components/FormHoneypot.vue +21 -0
  10. package/template/app/composables/useFormSpam.ts +55 -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 +19 -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 +3 -1
  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 +56 -6
  34. package/template/blocks/footer/__tests__/Block.spec.ts +70 -16
  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
@@ -0,0 +1,138 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { formatMoney } from '../../app/storefront/money';
3
+ import { pageStructuredData, type PageLdParts } from '../../app/storefront/structuredData';
4
+ import type { StorefrontProduct } from '../../app/storefront/types';
5
+
6
+ const ORIGIN = 'https://shop.test';
7
+
8
+ const product = (over: Partial<StorefrontProduct> = {}): StorefrontProduct => ({
9
+ handle: 'mug',
10
+ title: 'Mug',
11
+ url: '/products/mug',
12
+ featuredImage: null,
13
+ images: [{ src: 'https://cdn.test/mug.jpg', alt: 'Mug' }],
14
+ price: { amount: 2800, compareAt: null },
15
+ stock: 'in',
16
+ available: true,
17
+ productId: 'p1',
18
+ variantId: 'v1',
19
+ options: [],
20
+ categoryTrail: [],
21
+ description: 'A <b>hand-thrown</b> mug.',
22
+ inventory: null,
23
+ ...over,
24
+ });
25
+
26
+ const parts = (over: Partial<PageLdParts> = {}): PageLdParts => ({
27
+ kind: 'page',
28
+ title: 'About',
29
+ currentUrl: `${ORIGIN}/about`,
30
+ url: (path) => `${ORIGIN}${path}`,
31
+ absolute: true,
32
+ homeLabel: 'Home',
33
+ trail: [],
34
+ product: null,
35
+ currency: 'ISK',
36
+ items: [],
37
+ profile: {
38
+ name: 'Shop',
39
+ logoUrl: 'https://media.test/icon-512',
40
+ sameAs: [],
41
+ contact: { email: null, telephone: null },
42
+ },
43
+ searchPath: '/search',
44
+ ...over,
45
+ });
46
+
47
+ const types = (entries: ReturnType<typeof pageStructuredData>) =>
48
+ entries.map((entry) => entry.type);
49
+
50
+ describe('pageStructuredData', () => {
51
+ it('writes Organization and WebSite on home, and only with an absolute origin', () => {
52
+ expect(types(pageStructuredData(parts({ kind: 'home' })))).toEqual(['organization', 'website']);
53
+ expect(types(pageStructuredData(parts({ kind: 'home', absolute: false })))).toEqual([]);
54
+ });
55
+
56
+ it('writes only a BreadcrumbList on an ordinary page, Home first', () => {
57
+ const [entry, ...rest] = pageStructuredData(parts());
58
+ expect(rest).toEqual([]);
59
+ expect(entry!.type).toBe('breadcrumb');
60
+ expect(entry!.node.itemListElement).toMatchObject([
61
+ { name: 'Home', item: `${ORIGIN}/` },
62
+ { name: 'About', item: `${ORIGIN}/about` },
63
+ ]);
64
+ });
65
+
66
+ it('writes nothing for the not-found shell', () => {
67
+ expect(pageStructuredData(parts({ kind: 'notFound' }))).toEqual([]);
68
+ });
69
+
70
+ it('builds a product from the same price, currency and stock the page renders', () => {
71
+ const entries = pageStructuredData(
72
+ parts({
73
+ kind: 'product',
74
+ title: 'Mug',
75
+ currentUrl: `${ORIGIN}/products/mug`,
76
+ trail: [{ label: 'Cups', path: '/categories/cups' }],
77
+ product: product({ brand: 'Acme' }),
78
+ })
79
+ );
80
+ expect(types(entries)).toEqual(['breadcrumb', 'product']);
81
+ expect(
82
+ (entries[0]!.node.itemListElement as Array<{ name: string }>).map((item) => item.name)
83
+ ).toEqual(['Home', 'Cups', 'Mug']);
84
+ const node = entries[1]!.node as Record<string, any>;
85
+ expect(node).toMatchObject({
86
+ name: 'Mug',
87
+ description: 'A hand-thrown mug.',
88
+ image: ['https://cdn.test/mug.jpg'],
89
+ brand: { name: 'Acme' },
90
+ offers: { price: 2800, priceCurrency: 'ISK', availability: 'https://schema.org/InStock' },
91
+ });
92
+ // The number the markup states is the number the visible price is formatted from.
93
+ expect(formatMoney(node.offers.price, 'ISK', 'en-US')).toContain('2,800');
94
+ });
95
+
96
+ it('maps stock states to availability and falls back to the shop name as brand', () => {
97
+ const availability = (stock: StorefrontProduct['stock']) =>
98
+ (
99
+ pageStructuredData(parts({ kind: 'product', product: product({ stock }) }))[1]!.node
100
+ .offers as Record<string, unknown>
101
+ ).availability;
102
+ expect(availability('out')).toBe('https://schema.org/OutOfStock');
103
+ expect(availability('preorder')).toBe('https://schema.org/PreOrder');
104
+ expect(availability('low')).toBe('https://schema.org/LimitedAvailability');
105
+ expect(
106
+ pageStructuredData(parts({ kind: 'product', product: product() }))[1]!.node.brand
107
+ ).toEqual({ '@type': 'Brand', name: 'Shop' });
108
+ });
109
+
110
+ it('writes one offer per variant, AggregateOffer when prices differ, and drops a bad barcode', () => {
111
+ const entries = pageStructuredData(
112
+ parts({
113
+ kind: 'product',
114
+ product: product({
115
+ variants: [
116
+ { sku: 'S', barcode: '4006381333931', price: 2000, compareAt: null, stock: 'in' },
117
+ { sku: 'L', barcode: 'internal', price: 3000, compareAt: 3500, stock: 'out' },
118
+ ],
119
+ }),
120
+ })
121
+ );
122
+ const offers = entries[1]!.node.offers as Record<string, any>;
123
+ expect(offers).toMatchObject({ '@type': 'AggregateOffer', lowPrice: 2000, highPrice: 3000 });
124
+ expect(offers.offers[0].gtin).toBe('4006381333931');
125
+ expect(offers.offers[1].gtin).toBeUndefined();
126
+ expect(offers.offers[1].availability).toBe('https://schema.org/OutOfStock');
127
+ });
128
+
129
+ it('writes an ItemList on a listing page only when it shows products', () => {
130
+ const listing = (items: PageLdParts['items']) =>
131
+ types(pageStructuredData(parts({ kind: 'collection', items })));
132
+ expect(listing([])).toEqual(['breadcrumb']);
133
+ expect(listing([{ title: 'Mug', url: `${ORIGIN}/products/mug` }])).toEqual([
134
+ 'breadcrumb',
135
+ 'itemList',
136
+ ]);
137
+ });
138
+ });
@@ -0,0 +1,159 @@
1
+ import { execa } from 'execa';
2
+ import { cpSync, existsSync, mkdtempSync, readFileSync, rmSync, symlinkSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { join, relative, sep } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { afterAll, beforeAll, describe, expect, it } from 'vitest';
7
+ import { formatMoney } from '../app/storefront/money';
8
+ import {
9
+ COLLECTION_HANDLE,
10
+ ORG_ID,
11
+ PRODUCT_HANDLE,
12
+ startMockGateway,
13
+ type MockGateway,
14
+ } from './support/mockGateway';
15
+
16
+ /**
17
+ * **A generated page carries its schema.org JSON-LD**, and it is the page's own data.
18
+ *
19
+ * A real `nuxi generate` of the starter, against the mock gateway, as a production build with a
20
+ * known origin (a preview build is `noindex` and writes none): the HTML on disk is what a crawler
21
+ * reads, so this is the only place the tags can be asserted — a unit test of the builders proves
22
+ * the shape, not that the page wired them into the head before the file was written.
23
+ *
24
+ * What is pinned: one `ld+json` script per page; `Organization` and `WebSite` on the home page;
25
+ * `BreadcrumbList` + `Product` on a product page whose price, currency and availability are the
26
+ * ones the page renders; `BreadcrumbList` + `ItemList` on a collection and a category page; and
27
+ * no markup on the not-found shell.
28
+ */
29
+
30
+ const templateDir = fileURLToPath(new URL('..', import.meta.url));
31
+ const nuxi = join(templateDir, 'node_modules', '.bin', 'nuxi');
32
+ const SKIPPED_FROM_COPY = new Set(['node_modules', '.nuxt', '.output', '.git']);
33
+ const ORIGIN = 'https://shop.example.test';
34
+
35
+ let gateway: MockGateway;
36
+ let scratch: string;
37
+ let root: string;
38
+
39
+ const output = (path: string): string => join(root, '.output', 'public', path);
40
+
41
+ type Node = Record<string, any>;
42
+ const SCRIPT = /<script[^>]*type="application\/ld\+json"[^>]*>([\s\S]*?)<\/script>/g;
43
+
44
+ function nodesOf(path: string): { html: string; nodes: Node[] } {
45
+ const html = readFileSync(output(path), 'utf8');
46
+ const scripts = [...html.matchAll(SCRIPT)];
47
+ expect(scripts.length, `${path}: ld+json scripts`).toBeLessThanOrEqual(1);
48
+ const nodes = scripts.flatMap(([, json]) => {
49
+ const parsed = JSON.parse(json!) as Node | Node[];
50
+ return Array.isArray(parsed) ? parsed : [parsed];
51
+ });
52
+ return { html, nodes };
53
+ }
54
+
55
+ describe('generated pages carry schema.org JSON-LD', () => {
56
+ beforeAll(async () => {
57
+ gateway = await startMockGateway();
58
+ scratch = mkdtempSync(join(tmpdir(), 'eldra-structured-data-'));
59
+ root = join(scratch, 'site');
60
+ cpSync(templateDir, root, {
61
+ recursive: true,
62
+ filter: (source) => {
63
+ const [first] = relative(templateDir, source).split(sep);
64
+ return first === undefined || !SKIPPED_FROM_COPY.has(first);
65
+ },
66
+ });
67
+ symlinkSync(join(templateDir, 'node_modules'), join(root, 'node_modules'), 'dir');
68
+ await execa(nuxi, ['generate'], {
69
+ cwd: root,
70
+ env: {
71
+ ELDRA_GATEWAY_URL: gateway.url,
72
+ ELDRA_ORG_ID: ORG_ID,
73
+ ELDRA_BUILD_TARGET: 'production',
74
+ ELDRA_SITE_URL: ORIGIN,
75
+ },
76
+ timeout: 600_000,
77
+ });
78
+ }, 900_000);
79
+
80
+ afterAll(async () => {
81
+ await gateway?.close();
82
+ if (scratch !== undefined) rmSync(scratch, { recursive: true, force: true });
83
+ });
84
+
85
+ it('writes Organization and WebSite on the home page', () => {
86
+ const { nodes } = nodesOf('index.html');
87
+ expect(nodes.map((node) => node['@type'])).toEqual(['Organization', 'WebSite']);
88
+ expect(nodes[0]).toMatchObject({
89
+ name: 'Northwind Goods',
90
+ url: `${ORIGIN}/`,
91
+ sameAs: ['https://social.example.test/northwind'],
92
+ contactPoint: { email: 'hello@northwind.example.test' },
93
+ });
94
+ expect(nodes[1].potentialAction.target.urlTemplate).toBe(
95
+ `${ORIGIN}/search?q={search_term_string}`
96
+ );
97
+ });
98
+
99
+ it('writes BreadcrumbList and a Product the page renders on a product page', () => {
100
+ const { html, nodes } = nodesOf(join('products', PRODUCT_HANDLE, 'index.html'));
101
+ expect(nodes.map((node) => node['@type'])).toEqual(['BreadcrumbList', 'Product']);
102
+
103
+ expect(nodes[0].itemListElement.map((item: Node) => item.name)).toEqual([
104
+ 'Home',
105
+ 'Tableware',
106
+ 'Cups',
107
+ 'Ash glaze mug',
108
+ ]);
109
+ expect(nodes[0].itemListElement.at(-1).item).toBe(`${ORIGIN}/products/${PRODUCT_HANDLE}`);
110
+
111
+ const product = nodes[1];
112
+ expect(product).toMatchObject({
113
+ name: 'Ash glaze mug',
114
+ url: `${ORIGIN}/products/${PRODUCT_HANDLE}`,
115
+ brand: { name: 'Northwind Ceramics' },
116
+ sku: PRODUCT_HANDLE.toUpperCase(),
117
+ gtin: '4006381333931',
118
+ offers: {
119
+ '@type': 'Offer',
120
+ // The store's currency, and the amount the visible price is made from.
121
+ price: 42,
122
+ priceCurrency: 'ISK',
123
+ availability: 'https://schema.org/InStock',
124
+ },
125
+ });
126
+ // The visible price is `formatMoney(42, 'ISK')`: same amount, same currency.
127
+ expect(html).toContain(
128
+ formatMoney(product.offers.price, product.offers.priceCurrency, 'en-US')
129
+ );
130
+ });
131
+
132
+ it('writes BreadcrumbList and an ItemList of the products shown on a collection page', () => {
133
+ const { nodes } = nodesOf(join('collections', COLLECTION_HANDLE, 'index.html'));
134
+ expect(nodes.map((node) => node['@type'])).toEqual(['BreadcrumbList', 'ItemList']);
135
+ const items = nodes[1].itemListElement as Node[];
136
+ expect(items.length).toBeGreaterThan(0);
137
+ expect(items[0]).toMatchObject({
138
+ position: 1,
139
+ name: 'Ash glaze mug',
140
+ url: `${ORIGIN}/products/${PRODUCT_HANDLE}`,
141
+ });
142
+ });
143
+
144
+ it('writes BreadcrumbList and an ItemList on a category page', () => {
145
+ const path = join('categories', 'tableware', 'cups', 'index.html');
146
+ expect(existsSync(output(path)), 'category page generated').toBe(true);
147
+ const { nodes } = nodesOf(path);
148
+ expect(nodes.map((node) => node['@type'])).toEqual(['BreadcrumbList', 'ItemList']);
149
+ expect(nodes[0].itemListElement.map((item: Node) => item.name)).toEqual([
150
+ 'Home',
151
+ 'Tableware',
152
+ 'Cups',
153
+ ]);
154
+ });
155
+
156
+ it('writes none on the not-found shell, which is noindex', () => {
157
+ expect(nodesOf(join('404', 'index.html')).nodes).toEqual([]);
158
+ });
159
+ });
@@ -50,6 +50,7 @@ const PAGE_BLOCK_UUID_OFFSET = 100;
50
50
  interface MockVariant {
51
51
  id: string;
52
52
  sku: string;
53
+ barcode?: string;
53
54
  price: number;
54
55
  compareAtPrice?: number;
55
56
  status: string;
@@ -64,6 +65,7 @@ interface MockProduct {
64
65
  minPrice: number;
65
66
  maxPrice: number;
66
67
  compareAtPrice?: number;
68
+ brand?: string;
67
69
  variants: MockVariant[];
68
70
  }
69
71
 
@@ -89,7 +91,19 @@ export const PRODUCT_HANDLE = 'ash-glaze-mug';
89
91
  export const COLLECTION_HANDLE = 'the-winter-edit';
90
92
 
91
93
  export const PRODUCTS: MockProduct[] = [
92
- product(PRODUCT_HANDLE, 'Ash glaze mug', 42),
94
+ product(PRODUCT_HANDLE, 'Ash glaze mug', 42, {
95
+ brand: 'Northwind Ceramics',
96
+ variants: [
97
+ {
98
+ id: `var-${PRODUCT_HANDLE}`,
99
+ sku: PRODUCT_HANDLE.toUpperCase(),
100
+ // A valid EAN-13: the structured data writes it as `gtin`.
101
+ barcode: '4006381333931',
102
+ price: 42,
103
+ status: 'ACTIVE',
104
+ },
105
+ ],
106
+ }),
93
107
  product('cedar-serving-board', 'Cedar serving board', 68),
94
108
  product('flax-tea-towel', 'Flax tea towel', 24),
95
109
  product('stoneware-bowl', 'Stoneware bowl', 36),
@@ -220,6 +234,7 @@ const detailOf = (row: MockProduct): Record<string, unknown> => ({
220
234
  // already read. Both, with the same value, is what a live response looks like.
221
235
  primaryCategoryId: row.categoryId,
222
236
  categoryIds: [row.categoryId],
237
+ ...(row.brand === undefined ? {} : { brand: row.brand }),
223
238
  description: { text: `${row.title} — thrown by hand, glazed in ash.` },
224
239
  mediaLinks: [],
225
240
  options: [],
@@ -871,6 +886,19 @@ export function startMockGateway(
871
886
  // not ask for one. `client.checkout.url()` reads it to build the cart hand-off, which is the
872
887
  // one thing a restored cart asks for beyond the cart itself; without an answer here that
873
888
  // read is a 400 in the browser's console on every page with a cart in it.
889
+ // The site profile: the `Organization` structured data's name and links. Not org-scoped in
890
+ // the mock either, so a read without credentials is answered like one with.
891
+ if (url.pathname === '/site/v1/site-profile') {
892
+ answer({
893
+ revision: 1,
894
+ name: 'Northwind Goods',
895
+ logoUrl: null,
896
+ sameAs: ['https://social.example.test/northwind'],
897
+ contact: { email: 'hello@northwind.example.test', telephone: null },
898
+ });
899
+ return;
900
+ }
901
+
874
902
  if (url.pathname === '/platform/v1/config') {
875
903
  answer({ checkoutUrl: 'https://checkout.example' });
876
904
  return;
@@ -0,0 +1,53 @@
1
+ import { computed } from 'vue';
2
+ import { vi } from 'vitest';
3
+ import { createDemoStorefront } from '../../app/storefront/demo';
4
+ import type { StorefrontForms, StorefrontSource } from '../../app/storefront/types';
5
+
6
+ export const TURNSTILE_SITE_KEY = '1x00000000000000000000AA';
7
+
8
+ /**
9
+ * The demo storefront whose forms all have Cloudflare Turnstile switched on (a site key on the
10
+ * definition), with `forms.submit` replaced by `submit`: what a spec needs to prove a block that
11
+ * renders its own fields still renders the widget and sends the token.
12
+ */
13
+ export function storefrontWithTurnstile(submit: StorefrontForms['submit']): StorefrontSource {
14
+ const base = createDemoStorefront();
15
+ return {
16
+ ...base,
17
+ forms: {
18
+ definition: (key) => {
19
+ const result = base.forms.definition(key);
20
+ return {
21
+ ...result,
22
+ data: computed(() =>
23
+ result.data.value === null
24
+ ? null
25
+ : { ...result.data.value, turnstileSiteKey: TURNSTILE_SITE_KEY }
26
+ ) as typeof result.data,
27
+ };
28
+ },
29
+ submit,
30
+ },
31
+ };
32
+ }
33
+
34
+ /** A fake `window.turnstile`: `solve(token)` is the visitor passing the check. */
35
+ export function stubTurnstile() {
36
+ let callback: ((token: string) => void) | undefined;
37
+ const render = vi.fn((_el: HTMLElement, options: { callback: (token: string) => void }) => {
38
+ callback = options.callback;
39
+ return 'widget-1';
40
+ });
41
+ const reset = vi.fn();
42
+ (window as unknown as { turnstile: unknown }).turnstile = { render, reset, remove: vi.fn() };
43
+ return {
44
+ render,
45
+ reset,
46
+ solve: (token: string) => callback?.(token),
47
+ };
48
+ }
49
+
50
+ export function cleanUpTurnstile(): void {
51
+ document.head.querySelectorAll('script[src*="turnstile"]').forEach((node) => node.remove());
52
+ delete (window as { turnstile?: unknown }).turnstile;
53
+ }
@@ -1,37 +0,0 @@
1
- /** What the document's `<title>` falls back to when nothing named the page. */
2
- const FALLBACK_TITLE = 'Site';
3
-
4
- export interface PageTitleParts {
5
- /** The route is showing the not-found shell. */
6
- isNotFound: boolean;
7
- /** The translated not-found title. */
8
- notFoundTitle: string;
9
- /**
10
- * The title of the catalog object a catalog-backed route resolved to — a product's or a
11
- * collection's own name. `null`/absent for every other route.
12
- */
13
- catalogTitle?: unknown;
14
- /** The page or route-template document's own `title` field. */
15
- documentTitle?: unknown;
16
- }
17
-
18
- /**
19
- * The document title for one route, in priority order: the not-found shell names itself; a
20
- * catalog-backed route is named by the object it is showing; anything else by its own document.
21
- *
22
- * The catalog case is the reason this is a function rather than one expression in the page: a
23
- * product route renders through a route *template*, and the template's own title is the template's
24
- * name ("Product") — the same three words on every product page, which is what a browser tab, a
25
- * bookmark and a search result would have shown.
26
- *
27
- * Titles arrive as `unknown` (a document field, which is data the CMS holds, not a typed prop), so
28
- * anything that is not a non-blank string is treated as absent rather than rendered.
29
- */
30
- export function pageTitle(parts: PageTitleParts): string {
31
- if (parts.isNotFound) return parts.notFoundTitle;
32
- return text(parts.catalogTitle) ?? text(parts.documentTitle) ?? FALLBACK_TITLE;
33
- }
34
-
35
- function text(value: unknown): string | null {
36
- return typeof value === 'string' && value.trim() !== '' ? value : null;
37
- }
@@ -1,49 +0,0 @@
1
- import { describe, expect, it } from 'vitest';
2
- import { pageTitle } from '../app/utils/pageTitle';
3
-
4
- const notFoundTitle = 'Page not found';
5
-
6
- describe('pageTitle', () => {
7
- it('names a catalog route after the object it is showing, not its template', () => {
8
- // The defect this closes: every product page's tab read "Product" — the route template's own
9
- // title — because that is the document the page renders through.
10
- expect(
11
- pageTitle({
12
- isNotFound: false,
13
- notFoundTitle,
14
- catalogTitle: 'Ash glaze mug',
15
- documentTitle: 'Product',
16
- })
17
- ).toBe('Ash glaze mug');
18
- });
19
-
20
- it('names an ordinary page after its own document', () => {
21
- expect(
22
- pageTitle({ isNotFound: false, notFoundTitle, catalogTitle: null, documentTitle: 'About us' })
23
- ).toBe('About us');
24
- });
25
-
26
- it('falls back to the document when a catalog object has no usable title', () => {
27
- for (const catalogTitle of [null, undefined, '', ' ', 42]) {
28
- expect(
29
- pageTitle({ isNotFound: false, notFoundTitle, catalogTitle, documentTitle: 'Product' })
30
- ).toBe('Product');
31
- }
32
- });
33
-
34
- it('falls back to the site name when nothing names the page', () => {
35
- expect(pageTitle({ isNotFound: false, notFoundTitle })).toBe('Site');
36
- expect(pageTitle({ isNotFound: false, notFoundTitle, documentTitle: ' ' })).toBe('Site');
37
- });
38
-
39
- it('names the not-found shell itself, whatever else resolved', () => {
40
- expect(
41
- pageTitle({
42
- isNotFound: true,
43
- notFoundTitle,
44
- catalogTitle: 'Ash glaze mug',
45
- documentTitle: 'Product',
46
- })
47
- ).toBe(notFoundTitle);
48
- });
49
- });