@tanqory/theme-kit 0.1.0 → 2.0.0-alpha.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 (202) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +98 -10
  3. package/dist/abi/canvas-live.d.ts +49 -0
  4. package/dist/abi/canvas-live.js +88 -0
  5. package/dist/abi/cart.d.ts +48 -0
  6. package/dist/abi/cart.js +256 -0
  7. package/dist/abi/convert.d.ts +126 -0
  8. package/dist/abi/convert.js +493 -0
  9. package/dist/abi/data-api.d.ts +11 -0
  10. package/dist/abi/data-api.js +178 -0
  11. package/dist/abi/jcs.d.ts +6 -0
  12. package/dist/abi/jcs.js +28 -0
  13. package/dist/abi/page-data.d.ts +198 -0
  14. package/dist/abi/page-data.js +577 -0
  15. package/dist/abi/page.d.ts +23 -0
  16. package/dist/abi/page.js +46 -0
  17. package/dist/abi/referrals.d.ts +23 -0
  18. package/dist/abi/referrals.js +89 -0
  19. package/dist/abi/rewards.d.ts +27 -0
  20. package/dist/abi/rewards.js +82 -0
  21. package/dist/abi/seo.d.ts +47 -0
  22. package/dist/abi/seo.js +68 -0
  23. package/dist/abi/shell.d.ts +22 -0
  24. package/dist/abi/shell.js +10 -0
  25. package/dist/abi/wire.d.ts +38 -0
  26. package/dist/abi/wire.js +84 -0
  27. package/dist/build.d.ts +113 -0
  28. package/dist/build.js +294 -0
  29. package/dist/client.d.ts +19 -0
  30. package/dist/client.js +76 -0
  31. package/dist/contract.d.ts +6 -0
  32. package/dist/contract.js +6 -0
  33. package/dist/headless/ai.d.ts +132 -0
  34. package/dist/headless/ai.js +99 -0
  35. package/dist/headless/hooks.d.ts +273 -0
  36. package/dist/headless/hooks.js +533 -0
  37. package/dist/headless/i18n.d.ts +13 -0
  38. package/dist/headless/i18n.js +45 -0
  39. package/dist/headless/index.d.ts +36 -0
  40. package/dist/headless/index.js +38 -0
  41. package/dist/headless/money.d.ts +25 -0
  42. package/dist/headless/money.js +61 -0
  43. package/dist/headless/page.d.ts +43 -0
  44. package/dist/headless/page.js +53 -0
  45. package/dist/headless/platform.d.ts +55 -0
  46. package/dist/headless/platform.js +77 -0
  47. package/dist/headless/primitives/cart.d.ts +90 -0
  48. package/dist/headless/primitives/cart.js +153 -0
  49. package/dist/headless/primitives/collection.d.ts +68 -0
  50. package/dist/headless/primitives/collection.js +80 -0
  51. package/dist/headless/primitives/product.d.ts +101 -0
  52. package/dist/headless/primitives/product.js +117 -0
  53. package/dist/headless/primitives/storefront.d.ts +106 -0
  54. package/dist/headless/primitives/storefront.js +186 -0
  55. package/dist/headless/primitives/util.d.ts +19 -0
  56. package/dist/headless/primitives/util.js +42 -0
  57. package/dist/headless/strings.d.ts +9 -0
  58. package/dist/headless/strings.js +186 -0
  59. package/dist/headless/structured-data.d.ts +31 -0
  60. package/dist/headless/structured-data.js +57 -0
  61. package/dist/headless/theme.d.ts +99 -0
  62. package/dist/headless/theme.js +54 -0
  63. package/dist/index.d.ts +20 -0
  64. package/dist/index.js +18 -553
  65. package/dist/runtime/data/StoreProvider.d.ts +56 -0
  66. package/dist/runtime/data/StoreProvider.js +308 -0
  67. package/dist/runtime/data/handle.d.ts +14 -0
  68. package/dist/runtime/data/handle.js +16 -0
  69. package/dist/runtime/data/routes.d.ts +87 -0
  70. package/dist/runtime/data/routes.js +154 -0
  71. package/dist/runtime/data/to-ui.d.ts +237 -0
  72. package/dist/runtime/data/to-ui.js +759 -0
  73. package/dist/runtime/entries/register.d.ts +9 -0
  74. package/dist/runtime/entries/register.js +9 -0
  75. package/dist/runtime/entries/sections.d.ts +16 -0
  76. package/dist/runtime/entries/sections.js +19 -0
  77. package/dist/{types → runtime/kit}/SectionTree.d.ts +2 -1
  78. package/dist/runtime/kit/SectionTree.js +100 -0
  79. package/dist/runtime/kit/analytics.d.ts +63 -0
  80. package/dist/runtime/kit/analytics.js +233 -0
  81. package/dist/runtime/kit/cart.d.ts +167 -0
  82. package/dist/runtime/kit/cart.js +544 -0
  83. package/dist/{types → runtime/kit}/composition.d.ts +1 -1
  84. package/dist/runtime/kit/composition.js +3 -0
  85. package/dist/{types → runtime/kit}/config.d.ts +2 -2
  86. package/dist/runtime/kit/config.js +6 -0
  87. package/dist/runtime/kit/consent.d.ts +29 -0
  88. package/dist/runtime/kit/consent.js +159 -0
  89. package/dist/runtime/kit/contract/content.d.ts +164 -0
  90. package/dist/runtime/kit/contract/content.js +83 -0
  91. package/dist/runtime/kit/contract/field-types.d.ts +290 -0
  92. package/dist/runtime/kit/contract/field-types.js +129 -0
  93. package/dist/runtime/kit/contract/groups.d.ts +230 -0
  94. package/dist/runtime/kit/contract/groups.js +402 -0
  95. package/dist/runtime/kit/contract/index.d.ts +33 -0
  96. package/dist/runtime/kit/contract/index.js +33 -0
  97. package/dist/runtime/kit/contract/transform.d.ts +82 -0
  98. package/dist/runtime/kit/contract/transform.js +133 -0
  99. package/dist/runtime/kit/contract/validate.d.ts +67 -0
  100. package/dist/runtime/kit/contract/validate.js +388 -0
  101. package/dist/{types → runtime/kit}/data.d.ts +276 -7
  102. package/dist/runtime/kit/data.js +1117 -0
  103. package/dist/{types → runtime/kit}/defineSection.d.ts +1 -1
  104. package/dist/runtime/kit/defineSection.js +10 -0
  105. package/dist/{types → runtime/kit}/dynamic-source.d.ts +4 -4
  106. package/dist/runtime/kit/dynamic-source.js +143 -0
  107. package/dist/runtime/kit/index.d.ts +24 -0
  108. package/dist/runtime/kit/index.js +24 -0
  109. package/dist/{types → runtime/kit}/jsx-to-json.d.ts +1 -1
  110. package/dist/runtime/kit/jsx-to-json.js +28 -0
  111. package/dist/{types → runtime/kit}/mount.d.ts +25 -4
  112. package/dist/runtime/kit/mount.js +124 -0
  113. package/dist/{types → runtime/kit}/registry.d.ts +1 -1
  114. package/dist/runtime/kit/registry.js +12 -0
  115. package/dist/{types → runtime/kit}/ssg.d.ts +9 -3
  116. package/dist/runtime/kit/ssg.js +56 -0
  117. package/dist/{types → runtime/kit}/storefront.d.ts +206 -7
  118. package/dist/runtime/kit/storefront.js +723 -0
  119. package/dist/{types → runtime/kit}/theme-context.d.ts +8 -2
  120. package/dist/runtime/kit/theme-context.js +25 -0
  121. package/dist/runtime/kit/types.d.ts +142 -0
  122. package/dist/runtime/kit/types.js +1 -0
  123. package/dist/runtime/platform/TrackingPixels.d.ts +14 -0
  124. package/dist/runtime/platform/TrackingPixels.js +63 -0
  125. package/dist/runtime/platform/environment.d.ts +68 -0
  126. package/dist/runtime/platform/environment.js +85 -0
  127. package/dist/runtime/platform/locale.d.ts +27 -0
  128. package/dist/runtime/platform/locale.js +42 -0
  129. package/dist/runtime/platform/route-analytics.d.ts +15 -0
  130. package/dist/runtime/platform/route-analytics.js +72 -0
  131. package/dist/runtime/platform/safe-href.d.ts +25 -0
  132. package/dist/runtime/platform/safe-href.js +69 -0
  133. package/dist/runtime/platform/safe-values.d.ts +37 -0
  134. package/dist/runtime/platform/safe-values.js +140 -0
  135. package/dist/runtime/render/SectionRenderer.d.ts +4 -0
  136. package/dist/runtime/render/SectionRenderer.js +111 -0
  137. package/dist/runtime/render/listing-query.d.ts +47 -0
  138. package/dist/runtime/render/listing-query.js +114 -0
  139. package/dist/runtime/render/localized-copy.d.ts +86 -0
  140. package/dist/runtime/render/localized-copy.js +129 -0
  141. package/dist/runtime/render/product-listing.d.ts +11 -0
  142. package/dist/runtime/render/product-listing.js +240 -0
  143. package/dist/runtime/render/section-actions.d.ts +44 -0
  144. package/dist/runtime/render/section-actions.js +169 -0
  145. package/dist/runtime/render/starter.d.ts +11 -0
  146. package/dist/runtime/render/starter.js +81 -0
  147. package/dist/runtime/seo/head.d.ts +87 -0
  148. package/dist/runtime/seo/head.js +224 -0
  149. package/dist/runtime/seo/structured-data.d.ts +22 -0
  150. package/dist/runtime/seo/structured-data.js +115 -0
  151. package/dist/runtime/shell/PageShell.d.ts +18 -0
  152. package/dist/runtime/shell/PageShell.js +113 -0
  153. package/dist/runtime/shell/RuntimeBridge.d.ts +14 -0
  154. package/dist/runtime/shell/RuntimeBridge.js +82 -0
  155. package/dist/runtime/shell/overlay-state.d.ts +31 -0
  156. package/dist/runtime/shell/overlay-state.js +59 -0
  157. package/dist/runtime/shell/preview-mode.d.ts +2 -0
  158. package/dist/runtime/shell/preview-mode.js +11 -0
  159. package/dist/runtime/shell/spa-router.d.ts +14 -0
  160. package/dist/runtime/shell/spa-router.js +76 -0
  161. package/dist/runtime/shell/url-redirects.d.ts +6 -0
  162. package/dist/runtime/shell/url-redirects.js +37 -0
  163. package/dist/runtime/slots.d.ts +74 -0
  164. package/dist/runtime/slots.js +16 -0
  165. package/dist/runtime.d.ts +34 -0
  166. package/dist/runtime.js +40 -0
  167. package/dist/sdk/index.d.ts +24 -0
  168. package/dist/sdk/index.js +24 -0
  169. package/dist/sdk/referrals.d.ts +62 -0
  170. package/dist/sdk/referrals.js +20 -0
  171. package/dist/sdk/rewards.d.ts +85 -0
  172. package/dist/sdk/rewards.js +29 -0
  173. package/dist/sdk/runtime-context.d.ts +120 -0
  174. package/dist/sdk/runtime-context.js +73 -0
  175. package/dist/sdk/schema.d.ts +197 -0
  176. package/dist/sdk/schema.js +121 -0
  177. package/dist/sdk/server-render.d.ts +8 -0
  178. package/dist/sdk/server-render.js +12 -0
  179. package/dist/sdk/store-lookup.d.ts +27 -0
  180. package/dist/sdk/store-lookup.js +29 -0
  181. package/dist/sdk/store.d.ts +115 -0
  182. package/dist/sdk/store.js +1 -0
  183. package/dist/sdk/sx.d.ts +40 -0
  184. package/dist/sdk/sx.js +112 -0
  185. package/dist/sdk/theme.d.ts +152 -0
  186. package/dist/sdk/theme.js +10 -0
  187. package/dist/sdk/types.d.ts +395 -0
  188. package/dist/sdk/types.js +7 -0
  189. package/dist/server.d.ts +65 -0
  190. package/dist/server.js +370 -0
  191. package/docs/headless-api.md +220 -0
  192. package/package.json +77 -23
  193. package/dist/index.js.map +0 -1
  194. package/dist/ssg-BZ5FYTw7.js +0 -1802
  195. package/dist/ssg-BZ5FYTw7.js.map +0 -1
  196. package/dist/ssg.js +0 -8
  197. package/dist/ssg.js.map +0 -1
  198. package/dist/types/cart.d.ts +0 -86
  199. package/dist/types/editor.d.ts +0 -5
  200. package/dist/types/index.d.ts +0 -20
  201. package/dist/types/preview-bridge.d.ts +0 -9
  202. package/dist/types/types.d.ts +0 -44
@@ -0,0 +1,129 @@
1
+ const COPY_CONTROLS = new Set(['text', 'textarea', 'richtext']);
2
+ const plans = new WeakMap();
3
+ /**
4
+ * The copy plan of a theme, built once. A block name several schemas share
5
+ * (`newsletter`, `image` …) gets the union of their copy fields, and a default
6
+ * only where every one of those schemas agrees on it — an unset field is never
7
+ * filled with another schema's default.
8
+ */
9
+ /** The `shippedCopy` references that name no copy field of the theme (a test asserts there are none). */
10
+ export function unknownCopyRefs(theme) {
11
+ const bare = copyPlanOf({ sections: theme.sections });
12
+ return [...(theme.shippedCopy?.keep ?? []), ...(theme.shippedCopy?.derivedWhenUnset ?? [])].filter((ref) => {
13
+ const m = /^(section|block):([^.]+)\.(.+)$/.exec(ref);
14
+ return !m || !(m[1] === 'section' ? bare.section(m[2]) : bare.block(m[2]))?.fields.has(m[3]);
15
+ });
16
+ }
17
+ export function copyPlanOf(theme) {
18
+ let plan = plans.get(theme);
19
+ if (plan)
20
+ return plan;
21
+ const sections = new Map();
22
+ const blockSchemas = new Map();
23
+ const fieldsOf = (schemas) => {
24
+ const fields = new Set();
25
+ for (const sc of schemas)
26
+ for (const [k, f] of Object.entries(sc.fields ?? {}))
27
+ if (COPY_CONTROLS.has(f?.control ?? ''))
28
+ fields.add(k);
29
+ const defaults = {};
30
+ for (const k of fields) {
31
+ // An unset legacy-hidden field stays absent (resolveSettings), so it has no default to show.
32
+ const ds = schemas.map((sc) => sc.fields?.[k]).map((f) => (f && !f.legacyHidden && typeof f.default === 'string' ? f.default : undefined));
33
+ if (ds[0] !== undefined && ds.every((d) => d === ds[0]))
34
+ defaults[k] = ds[0];
35
+ }
36
+ return { fields, defaults };
37
+ };
38
+ for (const s of theme.sections) {
39
+ sections.set(s.id, fieldsOf([s.schema]));
40
+ for (const b of s.blocks ?? []) {
41
+ const name = b.name;
42
+ if (!name)
43
+ continue;
44
+ // A block saved under an earlier name (`legacyNames`) is localized as this block.
45
+ for (const n of [name, ...(b.legacyNames ?? [])]) {
46
+ const list = blockSchemas.get(n) ?? [];
47
+ if (!list.includes(b))
48
+ list.push(b);
49
+ blockSchemas.set(n, list);
50
+ }
51
+ }
52
+ }
53
+ const blocks = new Map([...blockSchemas].map(([name, list]) => [name, fieldsOf(list)]));
54
+ const apply = (refs, fn) => {
55
+ for (const ref of refs ?? []) {
56
+ const m = /^(section|block):([^.]+)\.(.+)$/.exec(ref);
57
+ const c = m ? (m[1] === 'section' ? sections : blocks).get(m[2]) : undefined;
58
+ // A stale reference must not take a page down; tests/localized-copy.test.ts fails on one instead.
59
+ if (!m || !c?.fields.has(m[3]))
60
+ continue;
61
+ fn(c, m[3]);
62
+ }
63
+ };
64
+ apply(theme.shippedCopy?.keep, (c, k) => { c.fields.delete(k); delete c.defaults[k]; });
65
+ apply(theme.shippedCopy?.derivedWhenUnset, (c, k) => { delete c.defaults[k]; });
66
+ plan = { section: (t) => sections.get(t), block: (t) => blocks.get(t) };
67
+ plans.set(theme, plan);
68
+ return plan;
69
+ }
70
+ const maps = new WeakMap();
71
+ /**
72
+ * The lookup for a theme: every `<prefix>*` key of its English locale map,
73
+ * inverted. The English file is the list, so a new shipped string is one new
74
+ * locale key and nothing else.
75
+ */
76
+ export function shippedCopyOf(english, prefix) {
77
+ if (!english || !prefix)
78
+ return EMPTY;
79
+ let m = maps.get(english);
80
+ if (!m) {
81
+ const built = new Map();
82
+ for (const [k, v] of Object.entries(english))
83
+ if (k.startsWith(prefix) && typeof v === 'string' && v.trim() && !built.has(v.trim()))
84
+ built.set(v.trim(), k);
85
+ maps.set(english, (m = built));
86
+ }
87
+ return m;
88
+ }
89
+ const EMPTY = new Map();
90
+ function localizedSettings(settings, plan, copy, strings) {
91
+ if (!plan?.fields.size)
92
+ return settings;
93
+ let next = null;
94
+ for (const k of plan.fields) {
95
+ const saved = settings?.[k];
96
+ const has = saved !== undefined && saved !== null;
97
+ const v = has ? saved : plan.defaults[k];
98
+ if (typeof v !== 'string')
99
+ continue;
100
+ const key = copy.get(v.trim());
101
+ if (!key)
102
+ continue;
103
+ const word = strings[key];
104
+ if (typeof word !== 'string' || !word.trim() || word === v)
105
+ continue;
106
+ (next ??= { ...settings })[k] = word;
107
+ }
108
+ return next ?? settings;
109
+ }
110
+ function localizeNode(node, isBlock, copy, strings, plan) {
111
+ const settings = localizedSettings(node.settings, isBlock ? plan.block(node.type) : plan.section(node.type), copy, strings);
112
+ let blocks = node.blocks;
113
+ if (blocks?.length) {
114
+ const mapped = blocks.map((b) => localizeNode(b, true, copy, strings, plan));
115
+ if (mapped.some((b, i) => b !== blocks[i]))
116
+ blocks = mapped;
117
+ }
118
+ return settings === node.settings && blocks === node.blocks ? node : { ...node, settings, blocks };
119
+ }
120
+ /**
121
+ * The section node with every shipped-English copy field (its own and its
122
+ * blocks') in the active language — the same object when nothing changes
123
+ * (an English page, or copy that is all the merchant's), so renders stay put.
124
+ */
125
+ export function localizeShippedCopy(node, copy, strings, plan) {
126
+ if (copy.size === 0)
127
+ return node;
128
+ return localizeNode(node, false, copy, strings, plan);
129
+ }
@@ -0,0 +1,11 @@
1
+ import { type ListingData, type Product } from '../../sdk/index.js';
2
+ /** The section's props that matter here: which collection, and its first page. */
3
+ interface ListingProps {
4
+ collection?: {
5
+ handle: string;
6
+ } | null;
7
+ products?: Product[];
8
+ total?: number;
9
+ }
10
+ export declare function useListing(props: ListingProps | null): Partial<ListingData>;
11
+ export {};
@@ -0,0 +1,240 @@
1
+ /**
2
+ * The host for a product listing (main-collection, product-grid): the first
3
+ * page comes from the store's `collection-products:<handle>` load, later pages
4
+ * are fetched here by cursor, and the shopper's filters and sort live here.
5
+ *
6
+ * Guards, each from a defect a listing shipped before:
7
+ * - the extra pages and the selection are keyed to the handle they belong to,
8
+ * so a soft navigation to another collection never shows the last one's
9
+ * products or filters;
10
+ * - a generation counter drops a response that a newer request superseded,
11
+ * and a second "load more" while one is open is ignored — two requests on
12
+ * the same cursor appended the same slice twice.
13
+ *
14
+ * Facets come from the storefront's own `filters` for the collection. The
15
+ * storefront ANDs every filter it is given, so two values of one facet
16
+ * ("T-shirts" or "Shirts") are asked for one request each and unioned here.
17
+ * It also ignores `sortKey`, so sorting is done here — and only offered when
18
+ * every matching product is loaded, since sorting a partial list would lie.
19
+ *
20
+ * On the route's own collection the selection lives in the URL too
21
+ * (listing-query.ts): read on the first render — the server's and the
22
+ * hydrating browser's alike — and written with `history.replaceState` on
23
+ * every change, so a sorted / filtered page can be shared and reloaded.
24
+ */
25
+ import { useCallback, useEffect, useRef, useState } from 'react';
26
+ import { useThemeContext } from '../../sdk/index.js';
27
+ import { useData } from '../kit/data.js';
28
+ import { useStore } from '../data/StoreProvider.js';
29
+ import * as map from '../data/to-ui.js';
30
+ import { filterRequests, queryOfState, stateFromQuery, withListingQuery } from './listing-query.js';
31
+ const PER_REQUEST = 24;
32
+ /** Two multi-value facets multiply requests; past this the extra values are dropped. */
33
+ const MAX_REQUESTS = 12;
34
+ /** Product tags are the merchant's internal labels ("bestseller", "sale"), not a shopper filter. */
35
+ const HIDDEN_FACETS = new Set(['filter.tag']);
36
+ const LABELS = {
37
+ en: {
38
+ featured: 'Featured', 'price-asc': 'Price, low to high', 'price-desc': 'Price, high to low', 'title-asc': 'Name, A–Z',
39
+ 'filter.available': 'Availability', 'filter.productType': 'Product type', 'filter.vendor': 'Brand', 'filter.price': 'Price',
40
+ 'filter.available.true': 'In stock', 'filter.available.false': 'Out of stock',
41
+ },
42
+ th: {
43
+ featured: 'แนะนำ', 'price-asc': 'ราคา ต่ำไปสูง', 'price-desc': 'ราคา สูงไปต่ำ', 'title-asc': 'ชื่อ ก–ฮ',
44
+ 'filter.available': 'สถานะสินค้า', 'filter.productType': 'ประเภทสินค้า', 'filter.vendor': 'แบรนด์', 'filter.price': 'ราคา',
45
+ 'filter.available.true': 'มีสินค้า', 'filter.available.false': 'สินค้าหมด',
46
+ },
47
+ ar: {
48
+ featured: 'مميز', 'price-asc': 'السعر، من الأقل إلى الأعلى', 'price-desc': 'السعر، من الأعلى إلى الأقل', 'title-asc': 'الاسم، أ–ي',
49
+ 'filter.available': 'التوفر', 'filter.productType': 'نوع المنتج', 'filter.vendor': 'العلامة التجارية', 'filter.price': 'السعر',
50
+ 'filter.available.true': 'متوفر', 'filter.available.false': 'غير متوفر',
51
+ },
52
+ };
53
+ const SORTS = ['featured', 'price-asc', 'price-desc', 'title-asc'];
54
+ const parse = (input) => {
55
+ try {
56
+ return JSON.parse(input);
57
+ }
58
+ catch {
59
+ return null;
60
+ }
61
+ };
62
+ const priceOf = (p) => Number(p.priceRange?.min?.amount ?? 0);
63
+ export function useListing(props) {
64
+ const data = useData();
65
+ const store = useStore();
66
+ const { locale } = useThemeContext();
67
+ const t = LABELS[(locale || 'en').split('-')[0]] ?? LABELS.en;
68
+ const handle = props?.collection?.handle ?? '';
69
+ const key = `collection-products:${handle}`;
70
+ const firstPage = handle ? store?.resources.get(key, undefined) : undefined;
71
+ const status = handle && store ? store.resources.status(key) : 'idle';
72
+ const [more, setMore] = useState(null);
73
+ const [, setLoading] = useState(false);
74
+ const [failed, setFailed] = useState(false);
75
+ const generation = useRef(0);
76
+ const inFlight = useRef(false);
77
+ const mine = more && more.handle === handle ? more : null;
78
+ // On the route's own collection the selection is the URL's (listing-query.ts).
79
+ const urlBound = Boolean(handle) && store?.ctx.currentCollection?.handle === handle;
80
+ const facetsForUrl = (firstPage?.filters ?? []).filter((f) => !HIDDEN_FACETS.has(f.id));
81
+ const fromUrl = () => {
82
+ if (!urlBound)
83
+ return { handle, values: {}, sort: 'featured' };
84
+ return { handle, ...stateFromQuery(store?.location.split('?')[1] ?? '', facetsForUrl) };
85
+ };
86
+ // ── Selection (filters + sort), keyed to the collection it was made on.
87
+ const [selection, setSelection] = useState(fromUrl);
88
+ const sel = selection.handle === handle ? selection : { handle, values: {}, sort: 'featured' };
89
+ const update = useCallback((f) => setSelection((s) => f(s.handle === handle ? s : { handle, values: {}, sort: 'featured' })), [handle]);
90
+ const filtered = Object.values(sel.values).some((v) => v.length > 0) || sel.price != null;
91
+ // The unfiltered facets: their values, counts and the price bounds stay put while
92
+ // the shopper narrows, so a value never vanishes from under the pointer.
93
+ const baseFilters = (firstPage?.filters ?? []).filter((f) => !HIDDEN_FACETS.has(f.id));
94
+ const priceFilter = baseFilters.find((f) => f.type === 'PRICE_RANGE');
95
+ const bounds = priceFilter ? (parse(priceFilter.values[0]?.input ?? '')?.price ?? null) : null;
96
+ // ── Filtered results.
97
+ const selKey = JSON.stringify([handle, sel.values, sel.price ?? null]);
98
+ // A filtered first render the server already answered (a shared filtered URL): its products are
99
+ // in the page data, so the server HTML and the hydrating browser show them without a fetch.
100
+ const [result, setResult] = useState(() => {
101
+ if (!filtered || !handle || !data.listingSeed)
102
+ return null;
103
+ const requests = filterRequests(sel, baseFilters, MAX_REQUESTS);
104
+ const seed = requests.length === 1 ? data.listingSeed(handle, requests[0]) : null;
105
+ return seed ? { key: selKey, products: map.toProducts(seed.products), pageInfo: seed.pageInfo ?? {}, filters: requests } : null;
106
+ });
107
+ const filterGeneration = useRef(0);
108
+ const [attempt, setAttempt] = useState(0);
109
+ useEffect(() => {
110
+ if (!filtered || !handle || !data.collectionProducts)
111
+ return;
112
+ if (result?.key === selKey && attempt === 0 && !result.failed)
113
+ return;
114
+ const id = ++filterGeneration.current;
115
+ const requests = filterRequests(sel, baseFilters, MAX_REQUESTS);
116
+ const fetchPage = data.collectionProducts;
117
+ Promise.all(requests.map((filters) => fetchPage(handle, { first: PER_REQUEST, filters })))
118
+ .then((pages) => {
119
+ if (id !== filterGeneration.current)
120
+ return;
121
+ const seen = new Set();
122
+ const union = pages.flatMap((p) => p.products).filter((p) => {
123
+ const pid = p?.id ?? '';
124
+ if (!p || seen.has(pid))
125
+ return false;
126
+ seen.add(pid);
127
+ return true;
128
+ });
129
+ const pageInfo = requests.length === 1 ? (pages[0].pageInfo ?? {}) : { hasNextPage: false };
130
+ setResult({ key: selKey, products: map.toProducts(union), pageInfo, filters: requests });
131
+ })
132
+ .catch(() => {
133
+ if (id === filterGeneration.current)
134
+ setResult({ key: selKey, products: [], pageInfo: {}, filters: requests, failed: true });
135
+ });
136
+ // selKey carries every input of this request.
137
+ // eslint-disable-next-line react-hooks/exhaustive-deps
138
+ }, [selKey, data, attempt]);
139
+ const current = filtered && result?.key === selKey ? result : null;
140
+ // ── Load more: the next page of whichever list is showing.
141
+ const pageInfo = filtered ? (current?.pageInfo ?? {}) : (mine?.pageInfo ?? firstPage?.pageInfo ?? {});
142
+ const onLoadMore = useCallback(async () => {
143
+ if (!handle || !data.collectionProducts || inFlight.current || !pageInfo.hasNextPage || !pageInfo.endCursor)
144
+ return;
145
+ inFlight.current = true;
146
+ const id = ++generation.current;
147
+ setLoading(true);
148
+ setFailed(false);
149
+ try {
150
+ const filters = current?.filters[0];
151
+ const page = await data.collectionProducts(handle, { first: PER_REQUEST, after: pageInfo.endCursor, ...(filters ? { filters } : {}) });
152
+ if (id !== generation.current)
153
+ return;
154
+ const next = map.toProducts(page.products);
155
+ if (current)
156
+ setResult({ ...current, products: [...current.products, ...next], pageInfo: page.pageInfo ?? {} });
157
+ else
158
+ setMore((prev) => ({
159
+ handle,
160
+ products: [...(prev && prev.handle === handle ? prev.products : []), ...next],
161
+ pageInfo: page.pageInfo ?? {},
162
+ }));
163
+ }
164
+ catch {
165
+ if (id === generation.current)
166
+ setFailed(true);
167
+ }
168
+ finally {
169
+ inFlight.current = false;
170
+ if (id === generation.current)
171
+ setLoading(false);
172
+ }
173
+ }, [data, handle, pageInfo.hasNextPage, pageInfo.endCursor, current]);
174
+ // Every change of the route collection's selection is written to the URL (never on the first
175
+ // render: a page opened from a shared URL keeps it as it is).
176
+ const urlQuery = urlBound ? queryOfState(sel, baseFilters) : null;
177
+ const wrote = useRef(urlQuery);
178
+ useEffect(() => {
179
+ if (urlQuery === null || typeof window === 'undefined' || urlQuery === wrote.current)
180
+ return;
181
+ wrote.current = urlQuery;
182
+ try {
183
+ window.history.replaceState(window.history.state, '', withListingQuery(window.location.href, urlQuery));
184
+ }
185
+ catch {
186
+ /* a sandboxed frame may refuse history writes */
187
+ }
188
+ }, [urlQuery]);
189
+ if (!props)
190
+ return {};
191
+ const unfiltered = [...(props.products ?? []), ...(mine?.products ?? [])];
192
+ const list = filtered ? (current?.products ?? []) : unfiltered;
193
+ const complete = !pageInfo.hasNextPage;
194
+ const sortable = complete && list.length > 1;
195
+ const sort = sortable ? sel.sort : 'featured';
196
+ const products = sort === 'price-asc' ? [...list].sort((a, b) => priceOf(a) - priceOf(b))
197
+ : sort === 'price-desc' ? [...list].sort((a, b) => priceOf(b) - priceOf(a))
198
+ : sort === 'title-asc' ? [...list].sort((a, b) => a.title.localeCompare(b.title, locale || undefined))
199
+ : list;
200
+ const known = props.total;
201
+ const total = filtered
202
+ ? products.length + (pageInfo.hasNextPage ? PER_REQUEST : 0)
203
+ : typeof known === 'number' && known >= products.length ? known : products.length + (pageInfo.hasNextPage ? PER_REQUEST : 0);
204
+ const state = failed || current?.failed ? 'error'
205
+ : filtered && !current ? 'loading'
206
+ : status === 'error' && !products.length ? 'error'
207
+ : status === 'loading' && !products.length ? 'loading'
208
+ : 'ready';
209
+ const currencyCode = unfiltered[0]?.priceRange?.min?.currencyCode;
210
+ const facets = baseFilters.flatMap((f) => {
211
+ if (f.type === 'PRICE_RANGE') {
212
+ if (!bounds || !currencyCode || bounds.min == null || bounds.max == null || bounds.min >= bounds.max)
213
+ return [];
214
+ return [{ id: f.id, label: t[f.id] ?? f.label, type: 'price', range: { min: Math.floor(bounds.min), max: Math.ceil(bounds.max), from: sel.price?.from, to: sel.price?.to, currencyCode } }];
215
+ }
216
+ // A facet with one value (one brand for the whole store) narrows nothing.
217
+ if (f.values.length < 2)
218
+ return [];
219
+ const active = sel.values[f.id] ?? [];
220
+ return [{ id: f.id, label: t[f.id] ?? f.label, type: 'list', values: f.values.map((v) => ({ id: v.id, label: t[v.id] ?? v.label, count: v.count, active: active.includes(v.id) })) }];
221
+ });
222
+ const sortOptions = sortable ? SORTS.map((id) => ({ id, label: t[id] })) : [];
223
+ return {
224
+ products,
225
+ total,
226
+ state,
227
+ facets,
228
+ sortOptions,
229
+ sort,
230
+ onToggleFilter: (facetId, valueId) => update((s) => {
231
+ const now = s.values[facetId] ?? [];
232
+ return { ...s, values: { ...s.values, [facetId]: now.includes(valueId) ? now.filter((v) => v !== valueId) : [...now, valueId] } };
233
+ }),
234
+ onPriceFilter: (_facetId, from, to) => update((s) => ({ ...s, price: from == null && to == null ? undefined : { from, to } })),
235
+ onClearFilters: () => update((s) => ({ ...s, values: {}, price: undefined })),
236
+ onSortChange: (id) => update((s) => ({ ...s, sort: id })),
237
+ onLoadMore: pageInfo.hasNextPage ? onLoadMore : undefined,
238
+ onRetry: failed ? onLoadMore : current?.failed ? () => setAttempt((n) => n + 1) : undefined,
239
+ };
240
+ }
@@ -0,0 +1,44 @@
1
+ import type { CartRefusal } from '../kit/cart.js';
2
+ /**
3
+ * The shopper-facing words for a refusal, in the page's language (locales/*.json): the merchant's
4
+ * limit when it is known, else that the most has been reached.
5
+ */
6
+ export declare function refusalMessage(t: (key: string, fallback?: string) => string, refusal: CartRefusal): string;
7
+ export interface CartActions {
8
+ /** Resolves true when the line is in the cart; never rejects. */
9
+ addToCart: (variantId: string, quantity: number) => Promise<boolean>;
10
+ setQuantity: (lineId: string, quantity: number) => Promise<void>;
11
+ removeLine: (lineId: string) => Promise<void>;
12
+ /** Lines with a request in flight — one slot per line, never one for the whole cart. */
13
+ busyLines: ReadonlySet<string>;
14
+ failedLines: ReadonlySet<string>;
15
+ /** Failed lines the store said why for (Cart-1). */
16
+ refusedLines: ReadonlyMap<string, CartRefusal>;
17
+ setNote: (note: string) => Promise<void>;
18
+ }
19
+ export declare function useCartActions(): CartActions;
20
+ /** Go to a storefront URL through the SPA router when it is on (a real click), else a full load. */
21
+ export declare function navigate(href: string): void;
22
+ export declare const searchHref: (query: string) => string;
23
+ /**
24
+ * The URL a Region & language choice loads: `?country=CC` when the country changes, `?locale=ll`
25
+ * when the language changes (the platform honours both and remembers them for later pages). Only
26
+ * what changed is set, so a language switch never pins a country the visitor never picked.
27
+ */
28
+ export declare function localeHref(href: string, next: {
29
+ countryCode?: string;
30
+ languageCode?: string;
31
+ }, current?: {
32
+ countryCode?: string;
33
+ languageCode?: string;
34
+ }): string | null;
35
+ /** Region & language change: a fresh load, since prices and copy are answered for the new market and language. */
36
+ export declare function changeLocale(next: {
37
+ countryCode?: string;
38
+ languageCode?: string;
39
+ }, current?: {
40
+ countryCode?: string;
41
+ languageCode?: string;
42
+ }): void;
43
+ /** Market change: prices are fetched for a country, so a change is a fresh load (same as the old switcher). */
44
+ export declare function changeCountry(countryCode: string): void;
@@ -0,0 +1,169 @@
1
+ /**
2
+ * The actions Nova's sections expose as props, wired to the platform: cart
3
+ * mutations, search, locale/market change. Sections stay presentational; this
4
+ * is the one place a click becomes a request.
5
+ */
6
+ import { useCallback, useMemo, useRef, useState } from 'react';
7
+ import { useCart } from '../kit/cart.js';
8
+ import { useT } from '../kit/theme-context.js';
9
+ import { useOpenCartAfterAdd, useOverlays } from '../shell/overlay-state.js';
10
+ /** A quantity change the store refused and said why (theme-abi Cart-1). */
11
+ class RefusedWrite extends Error {
12
+ constructor(refusal) {
13
+ super(refusal.code);
14
+ this.refusal = refusal;
15
+ }
16
+ }
17
+ /**
18
+ * The shopper-facing words for a refusal, in the page's language (locales/*.json): the merchant's
19
+ * limit when it is known, else that the most has been reached.
20
+ */
21
+ export function refusalMessage(t, refusal) {
22
+ return refusal.maxQuantity
23
+ ? t('cartLimitReached', 'You can buy up to {max} of this item.').replace('{max}', String(refusal.maxQuantity))
24
+ : t('cartLimitReachedAny', "You've reached the maximum quantity for this item.");
25
+ }
26
+ export function useCartActions() {
27
+ const cart = useCart();
28
+ const overlays = useOverlays();
29
+ const openCartAfterAdd = useOpenCartAfterAdd();
30
+ const [busy, setBusy] = useState(() => new Set());
31
+ const [failed, setFailed] = useState(() => new Set());
32
+ const [refused, setRefused] = useState(() => new Map());
33
+ const t = useT();
34
+ // A second click on the same line while its request is open is dropped: the
35
+ // state update above is async, so the guard reads a ref.
36
+ const inFlight = useRef(new Set());
37
+ const mark = (set, id, on) => set((prev) => {
38
+ const next = new Set(prev);
39
+ if (on)
40
+ next.add(id);
41
+ else
42
+ next.delete(id);
43
+ return next;
44
+ });
45
+ const withLine = useCallback(async (lineId, run) => {
46
+ if (inFlight.current.has(lineId))
47
+ return;
48
+ inFlight.current.add(lineId);
49
+ mark(setBusy, lineId, true);
50
+ mark(setFailed, lineId, false);
51
+ const refuse = (refusal) => setRefused((prev) => {
52
+ if (!refusal && !prev.has(lineId))
53
+ return prev;
54
+ const next = new Map(prev);
55
+ if (refusal)
56
+ next.set(lineId, refusal);
57
+ else
58
+ next.delete(lineId);
59
+ return next;
60
+ });
61
+ refuse(null);
62
+ try {
63
+ await run();
64
+ }
65
+ catch (e) {
66
+ mark(setFailed, lineId, true);
67
+ if (e instanceof RefusedWrite)
68
+ refuse(e.refusal);
69
+ }
70
+ finally {
71
+ inFlight.current.delete(lineId);
72
+ mark(setBusy, lineId, false);
73
+ }
74
+ }, []);
75
+ const addToCart = useCallback(async (variantId, quantity) => {
76
+ const ok = await cart.add({ variantId, quantity });
77
+ if (ok)
78
+ openCartAfterAdd();
79
+ else {
80
+ // Read now, not from `cart.error`: this render's cart predates the add.
81
+ const refusal = cart.lastRefusal?.() ?? null;
82
+ overlays.toast(refusal ? refusalMessage(t, refusal) : t('addFailed', 'This item could not be added to your cart.'), 'error');
83
+ }
84
+ return ok;
85
+ }, [cart, openCartAfterAdd, overlays, t]);
86
+ return useMemo(() => ({
87
+ addToCart,
88
+ setQuantity: (lineId, quantity) => withLine(lineId, async () => {
89
+ await cart.updateQuantity(lineId, quantity);
90
+ // A refusal the store explained marks the line failed, with its reason (Cart-1).
91
+ const refusal = cart.lastRefusal?.() ?? null;
92
+ if (refusal)
93
+ throw new RefusedWrite(refusal);
94
+ }),
95
+ removeLine: (lineId) => withLine(lineId, () => cart.remove(lineId)),
96
+ busyLines: busy,
97
+ failedLines: failed,
98
+ refusedLines: refused,
99
+ setNote: (note) => cart.updateNote(note),
100
+ }), [addToCart, withLine, cart, busy, failed, refused]);
101
+ }
102
+ /** Go to a storefront URL through the SPA router when it is on (a real click), else a full load. */
103
+ export function navigate(href) {
104
+ if (typeof window === 'undefined')
105
+ return;
106
+ const a = document.createElement('a');
107
+ a.href = href;
108
+ a.hidden = true;
109
+ document.body.appendChild(a);
110
+ a.click();
111
+ a.remove();
112
+ }
113
+ export const searchHref = (query) => `/search?q=${encodeURIComponent(query.trim())}`;
114
+ const LANGUAGE_TAG = /^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/;
115
+ /**
116
+ * The URL a Region & language choice loads: `?country=CC` when the country changes, `?locale=ll`
117
+ * when the language changes (the platform honours both and remembers them for later pages). Only
118
+ * what changed is set, so a language switch never pins a country the visitor never picked.
119
+ */
120
+ export function localeHref(href, next, current = {}) {
121
+ const url = new URL(href);
122
+ const country = (next.countryCode ?? '').toUpperCase();
123
+ const language = next.languageCode ?? '';
124
+ let changed = false;
125
+ if (/^[A-Z]{2}$/.test(country) && country !== (current.countryCode ?? '').toUpperCase()) {
126
+ url.searchParams.set('country', country);
127
+ changed = true;
128
+ }
129
+ if (LANGUAGE_TAG.test(language) && language.toLowerCase() !== (current.languageCode ?? '').toLowerCase()) {
130
+ url.searchParams.set('locale', language);
131
+ changed = true;
132
+ }
133
+ if (!changed)
134
+ return null;
135
+ // A new market or language is a new listing: the page number belongs to the old one.
136
+ url.searchParams.delete('page');
137
+ return url.toString();
138
+ }
139
+ /** Region & language change: a fresh load, since prices and copy are answered for the new market and language. */
140
+ export function changeLocale(next, current) {
141
+ if (typeof window === 'undefined')
142
+ return;
143
+ const href = localeHref(window.location.href, next, current);
144
+ if (!href)
145
+ return;
146
+ if (next.countryCode && /^[A-Za-z]{2}$/.test(next.countryCode)) {
147
+ try {
148
+ window.localStorage.setItem('tq-country', next.countryCode.toUpperCase());
149
+ }
150
+ catch {
151
+ /* private mode */
152
+ }
153
+ }
154
+ window.location.href = href;
155
+ }
156
+ /** Market change: prices are fetched for a country, so a change is a fresh load (same as the old switcher). */
157
+ export function changeCountry(countryCode) {
158
+ if (typeof window === 'undefined' || !/^[A-Za-z]{2}$/.test(countryCode))
159
+ return;
160
+ try {
161
+ window.localStorage.setItem('tq-country', countryCode.toUpperCase());
162
+ }
163
+ catch {
164
+ /* private mode */
165
+ }
166
+ const url = new URL(window.location.href);
167
+ url.searchParams.set('country', countryCode.toUpperCase());
168
+ window.location.href = url.toString();
169
+ }
@@ -0,0 +1,11 @@
1
+ import type { ContentNode } from '../kit/types.js';
2
+ /** True where starter text is the point — the editor's "Add section" preview shows a section as its preset reads. */
3
+ export declare const ShowStarterContext: import("react").Context<boolean>;
4
+ /** A node type's setting defaults — what an unset field renders. */
5
+ export type DefaultsOf = (type: string) => Record<string, unknown> | undefined;
6
+ /** A node type's copy fields (text / textarea / richtext) — what a shopper reads. */
7
+ export type CopyFieldsOf = (type: string) => ReadonlySet<string> | undefined;
8
+ /** The node a shopper sees, or null when the section is still starter content. */
9
+ export declare function withoutStarter(node: ContentNode, starter: ReadonlySet<string>, defaultsOf?: DefaultsOf, copyFieldsOf?: CopyFieldsOf): ContentNode | null;
10
+ /** The theme's starter text as a lookup set (built once per theme). */
11
+ export declare function starterSet(list: readonly string[] | undefined): ReadonlySet<string>;