@tanqory/theme-kit 0.1.0 → 2.0.0-alpha.17

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 (210) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +125 -10
  3. package/dist/abi/canvas-live.d.ts +67 -0
  4. package/dist/abi/canvas-live.js +154 -0
  5. package/dist/abi/cart.d.ts +59 -0
  6. package/dist/abi/cart.js +387 -0
  7. package/dist/abi/convert.d.ts +344 -0
  8. package/dist/abi/convert.js +1278 -0
  9. package/dist/abi/data-api.d.ts +15 -0
  10. package/dist/abi/data-api.js +209 -0
  11. package/dist/abi/jcs.d.ts +6 -0
  12. package/dist/abi/jcs.js +28 -0
  13. package/dist/abi/labels.d.ts +3 -0
  14. package/dist/abi/labels.js +34 -0
  15. package/dist/abi/page-data.d.ts +256 -0
  16. package/dist/abi/page-data.js +678 -0
  17. package/dist/abi/page.d.ts +28 -0
  18. package/dist/abi/page.js +57 -0
  19. package/dist/abi/referrals.d.ts +23 -0
  20. package/dist/abi/referrals.js +89 -0
  21. package/dist/abi/rewards.d.ts +27 -0
  22. package/dist/abi/rewards.js +82 -0
  23. package/dist/abi/seo.d.ts +47 -0
  24. package/dist/abi/seo.js +68 -0
  25. package/dist/abi/shell.d.ts +23 -0
  26. package/dist/abi/shell.js +10 -0
  27. package/dist/abi/state-pack.d.ts +17 -0
  28. package/dist/abi/state-pack.js +43 -0
  29. package/dist/abi/wire.d.ts +38 -0
  30. package/dist/abi/wire.js +84 -0
  31. package/dist/build.d.ts +116 -0
  32. package/dist/build.js +310 -0
  33. package/dist/client.d.ts +19 -0
  34. package/dist/client.js +87 -0
  35. package/dist/contract.d.ts +6 -0
  36. package/dist/contract.js +6 -0
  37. package/dist/headless/ai.d.ts +132 -0
  38. package/dist/headless/ai.js +99 -0
  39. package/dist/headless/hooks.d.ts +276 -0
  40. package/dist/headless/hooks.js +540 -0
  41. package/dist/headless/i18n.d.ts +13 -0
  42. package/dist/headless/i18n.js +45 -0
  43. package/dist/headless/index.d.ts +37 -0
  44. package/dist/headless/index.js +38 -0
  45. package/dist/headless/money.d.ts +25 -0
  46. package/dist/headless/money.js +61 -0
  47. package/dist/headless/page.d.ts +43 -0
  48. package/dist/headless/page.js +53 -0
  49. package/dist/headless/platform.d.ts +55 -0
  50. package/dist/headless/platform.js +77 -0
  51. package/dist/headless/primitives/cart.d.ts +90 -0
  52. package/dist/headless/primitives/cart.js +153 -0
  53. package/dist/headless/primitives/collection.d.ts +68 -0
  54. package/dist/headless/primitives/collection.js +80 -0
  55. package/dist/headless/primitives/product.d.ts +101 -0
  56. package/dist/headless/primitives/product.js +117 -0
  57. package/dist/headless/primitives/storefront.d.ts +106 -0
  58. package/dist/headless/primitives/storefront.js +186 -0
  59. package/dist/headless/primitives/util.d.ts +19 -0
  60. package/dist/headless/primitives/util.js +42 -0
  61. package/dist/headless/strings.d.ts +9 -0
  62. package/dist/headless/strings.js +190 -0
  63. package/dist/headless/structured-data.d.ts +31 -0
  64. package/dist/headless/structured-data.js +57 -0
  65. package/dist/headless/theme.d.ts +99 -0
  66. package/dist/headless/theme.js +54 -0
  67. package/dist/index.d.ts +20 -0
  68. package/dist/index.js +18 -553
  69. package/dist/runtime/data/StoreProvider.d.ts +84 -0
  70. package/dist/runtime/data/StoreProvider.js +373 -0
  71. package/dist/runtime/data/handle.d.ts +14 -0
  72. package/dist/runtime/data/handle.js +16 -0
  73. package/dist/runtime/data/routes.d.ts +87 -0
  74. package/dist/runtime/data/routes.js +158 -0
  75. package/dist/runtime/data/to-ui.d.ts +281 -0
  76. package/dist/runtime/data/to-ui.js +977 -0
  77. package/dist/runtime/entries/register.d.ts +9 -0
  78. package/dist/runtime/entries/register.js +9 -0
  79. package/dist/runtime/entries/sections.d.ts +16 -0
  80. package/dist/runtime/entries/sections.js +19 -0
  81. package/dist/{types → runtime/kit}/SectionTree.d.ts +2 -1
  82. package/dist/runtime/kit/SectionTree.js +100 -0
  83. package/dist/runtime/kit/analytics.d.ts +63 -0
  84. package/dist/runtime/kit/analytics.js +250 -0
  85. package/dist/runtime/kit/cart.d.ts +215 -0
  86. package/dist/runtime/kit/cart.js +545 -0
  87. package/dist/{types → runtime/kit}/composition.d.ts +1 -1
  88. package/dist/runtime/kit/composition.js +3 -0
  89. package/dist/{types → runtime/kit}/config.d.ts +2 -2
  90. package/dist/runtime/kit/config.js +6 -0
  91. package/dist/runtime/kit/consent.d.ts +29 -0
  92. package/dist/runtime/kit/consent.js +159 -0
  93. package/dist/runtime/kit/contract/content.d.ts +199 -0
  94. package/dist/runtime/kit/contract/content.js +106 -0
  95. package/dist/runtime/kit/contract/field-types.d.ts +337 -0
  96. package/dist/runtime/kit/contract/field-types.js +206 -0
  97. package/dist/runtime/kit/contract/groups.d.ts +230 -0
  98. package/dist/runtime/kit/contract/groups.js +402 -0
  99. package/dist/runtime/kit/contract/index.d.ts +33 -0
  100. package/dist/runtime/kit/contract/index.js +33 -0
  101. package/dist/runtime/kit/contract/transform.d.ts +82 -0
  102. package/dist/runtime/kit/contract/transform.js +133 -0
  103. package/dist/runtime/kit/contract/validate.d.ts +75 -0
  104. package/dist/runtime/kit/contract/validate.js +480 -0
  105. package/dist/runtime/kit/data.d.ts +720 -0
  106. package/dist/runtime/kit/data.js +1117 -0
  107. package/dist/{types → runtime/kit}/defineSection.d.ts +1 -1
  108. package/dist/runtime/kit/defineSection.js +10 -0
  109. package/dist/{types → runtime/kit}/dynamic-source.d.ts +40 -18
  110. package/dist/runtime/kit/dynamic-source.js +294 -0
  111. package/dist/runtime/kit/index.d.ts +24 -0
  112. package/dist/runtime/kit/index.js +24 -0
  113. package/dist/{types → runtime/kit}/jsx-to-json.d.ts +1 -1
  114. package/dist/runtime/kit/jsx-to-json.js +28 -0
  115. package/dist/{types → runtime/kit}/mount.d.ts +25 -4
  116. package/dist/runtime/kit/mount.js +124 -0
  117. package/dist/{types → runtime/kit}/registry.d.ts +1 -1
  118. package/dist/runtime/kit/registry.js +12 -0
  119. package/dist/{types → runtime/kit}/ssg.d.ts +9 -3
  120. package/dist/runtime/kit/ssg.js +56 -0
  121. package/dist/runtime/kit/storefront.d.ts +639 -0
  122. package/dist/runtime/kit/storefront.js +723 -0
  123. package/dist/{types → runtime/kit}/theme-context.d.ts +8 -2
  124. package/dist/runtime/kit/theme-context.js +25 -0
  125. package/dist/runtime/kit/types.d.ts +147 -0
  126. package/dist/runtime/kit/types.js +1 -0
  127. package/dist/runtime/platform/TrackingPixels.d.ts +14 -0
  128. package/dist/runtime/platform/TrackingPixels.js +63 -0
  129. package/dist/runtime/platform/environment.d.ts +68 -0
  130. package/dist/runtime/platform/environment.js +85 -0
  131. package/dist/runtime/platform/locale.d.ts +27 -0
  132. package/dist/runtime/platform/locale.js +42 -0
  133. package/dist/runtime/platform/route-analytics.d.ts +15 -0
  134. package/dist/runtime/platform/route-analytics.js +72 -0
  135. package/dist/runtime/platform/safe-href.d.ts +25 -0
  136. package/dist/runtime/platform/safe-href.js +69 -0
  137. package/dist/runtime/platform/safe-values.d.ts +37 -0
  138. package/dist/runtime/platform/safe-values.js +140 -0
  139. package/dist/runtime/render/SectionRenderer.d.ts +4 -0
  140. package/dist/runtime/render/SectionRenderer.js +166 -0
  141. package/dist/runtime/render/listing-query.d.ts +52 -0
  142. package/dist/runtime/render/listing-query.js +122 -0
  143. package/dist/runtime/render/localized-copy.d.ts +86 -0
  144. package/dist/runtime/render/localized-copy.js +129 -0
  145. package/dist/runtime/render/product-listing.d.ts +11 -0
  146. package/dist/runtime/render/product-listing.js +243 -0
  147. package/dist/runtime/render/section-actions.d.ts +66 -0
  148. package/dist/runtime/render/section-actions.js +202 -0
  149. package/dist/runtime/render/starter.d.ts +11 -0
  150. package/dist/runtime/render/starter.js +81 -0
  151. package/dist/runtime/seo/head.d.ts +115 -0
  152. package/dist/runtime/seo/head.js +281 -0
  153. package/dist/runtime/seo/structured-data.d.ts +83 -0
  154. package/dist/runtime/seo/structured-data.js +252 -0
  155. package/dist/runtime/shell/PageShell.d.ts +18 -0
  156. package/dist/runtime/shell/PageShell.js +113 -0
  157. package/dist/runtime/shell/RuntimeBridge.d.ts +14 -0
  158. package/dist/runtime/shell/RuntimeBridge.js +93 -0
  159. package/dist/runtime/shell/overlay-state.d.ts +31 -0
  160. package/dist/runtime/shell/overlay-state.js +59 -0
  161. package/dist/runtime/shell/preview-mode.d.ts +2 -0
  162. package/dist/runtime/shell/preview-mode.js +11 -0
  163. package/dist/runtime/shell/spa-router.d.ts +14 -0
  164. package/dist/runtime/shell/spa-router.js +76 -0
  165. package/dist/runtime/shell/url-redirects.d.ts +6 -0
  166. package/dist/runtime/shell/url-redirects.js +37 -0
  167. package/dist/runtime/slots.d.ts +74 -0
  168. package/dist/runtime/slots.js +16 -0
  169. package/dist/runtime.d.ts +34 -0
  170. package/dist/runtime.js +40 -0
  171. package/dist/sdk/app-block.d.ts +29 -0
  172. package/dist/sdk/app-block.js +22 -0
  173. package/dist/sdk/index.d.ts +26 -0
  174. package/dist/sdk/index.js +26 -0
  175. package/dist/sdk/referrals.d.ts +62 -0
  176. package/dist/sdk/referrals.js +20 -0
  177. package/dist/sdk/rewards.d.ts +85 -0
  178. package/dist/sdk/rewards.js +29 -0
  179. package/dist/sdk/runtime-context.d.ts +202 -0
  180. package/dist/sdk/runtime-context.js +73 -0
  181. package/dist/sdk/schema.d.ts +206 -0
  182. package/dist/sdk/schema.js +121 -0
  183. package/dist/sdk/server-render.d.ts +8 -0
  184. package/dist/sdk/server-render.js +12 -0
  185. package/dist/sdk/store-lookup.d.ts +27 -0
  186. package/dist/sdk/store-lookup.js +29 -0
  187. package/dist/sdk/store.d.ts +149 -0
  188. package/dist/sdk/store.js +5 -0
  189. package/dist/sdk/sx.d.ts +40 -0
  190. package/dist/sdk/sx.js +112 -0
  191. package/dist/sdk/theme.d.ts +191 -0
  192. package/dist/sdk/theme.js +10 -0
  193. package/dist/sdk/types.d.ts +757 -0
  194. package/dist/sdk/types.js +7 -0
  195. package/dist/server.d.ts +111 -0
  196. package/dist/server.js +533 -0
  197. package/docs/headless-api.md +220 -0
  198. package/package.json +76 -22
  199. package/dist/index.js.map +0 -1
  200. package/dist/ssg-BZ5FYTw7.js +0 -1802
  201. package/dist/ssg-BZ5FYTw7.js.map +0 -1
  202. package/dist/ssg.js +0 -8
  203. package/dist/ssg.js.map +0 -1
  204. package/dist/types/cart.d.ts +0 -86
  205. package/dist/types/data.d.ts +0 -357
  206. package/dist/types/editor.d.ts +0 -5
  207. package/dist/types/index.d.ts +0 -20
  208. package/dist/types/preview-bridge.d.ts +0 -9
  209. package/dist/types/storefront.d.ts +0 -333
  210. package/dist/types/types.d.ts +0 -44
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Shipped copy in the page's language (theme `shippedCopy`).
3
+ *
4
+ * A theme ships words a merchant may keep or replace: setting defaults
5
+ * ("Send message"), and the starter templates and presets that are copied into
6
+ * a store's content when the theme is installed ("Get in touch"). They are
7
+ * written once, in English. A Thai store that never touched them showed
8
+ * English to a Thai shopper — after a contact form was sent, "Thanks — we'll
9
+ * reply soon." (production store 3b866d32, 2026-10-17).
10
+ *
11
+ * The rule, per copy field (text / textarea / richtext) of a section or block:
12
+ *
13
+ * - unset → its default; saved → the saved value (as before);
14
+ * - if that value is, exactly (trimmed), an English string the theme shipped,
15
+ * it is the theme's word, not the merchant's: it renders as that string's
16
+ * entry in the active locale file (`copy.*` in locales/<code>.json);
17
+ * - anything else is the merchant's and renders verbatim.
18
+ *
19
+ * Why match the English text rather than mark the default. Installed stores
20
+ * already hold the shipped English literally — the starter template was copied
21
+ * into their content, so "untouched" and "typed" cannot be told apart by
22
+ * presence. A marker (a `t:` token) would only reach stores installed after
23
+ * this change, and the editor's settings panel would show the raw token. The
24
+ * English text is the one thing every existing store's untouched copy has in
25
+ * common. The cost is narrow: a merchant who types exactly a shipped English
26
+ * string on a store whose shopper reads Thai gets the Thai string — the same
27
+ * words, in the shopper's language.
28
+ *
29
+ * Pure (no React): SectionRenderer applies it to the node before `data()`.
30
+ */
31
+ import type { ContentNode } from '../kit/types.js';
32
+ /** English shipped text (trimmed) → its locale key. */
33
+ export type ShippedCopy = ReadonlyMap<string, string>;
34
+ /** One node type's copy fields and what each renders when unset (absent: no single default). */
35
+ export interface CopyFields {
36
+ readonly fields: ReadonlySet<string>;
37
+ readonly defaults: Readonly<Record<string, string>>;
38
+ }
39
+ /** Copy fields per node type; a section and a block may share a name, so they are looked up apart. */
40
+ export interface CopyPlan {
41
+ section(type: string): CopyFields | undefined;
42
+ block(type: string): CopyFields | undefined;
43
+ }
44
+ type ThemeLike = {
45
+ sections: readonly {
46
+ id: string;
47
+ schema: unknown;
48
+ blocks?: readonly unknown[];
49
+ }[];
50
+ shippedCopy?: {
51
+ keep?: readonly string[];
52
+ derivedWhenUnset?: readonly string[];
53
+ };
54
+ };
55
+ /**
56
+ * A field reference in a theme's `shippedCopy` lists: `section:<type>.<key>` or `block:<type>.<key>`.
57
+ *
58
+ * - `keep`: the renderer compares the value with the shipped English (a sentinel: "the default title is
59
+ * not an override", "this tagline is the editor placeholder"). Localizing it would break that test,
60
+ * so the field is never touched.
61
+ * - `derivedWhenUnset`: an unset value means "derive it from data" (a footer column's heading → its
62
+ * menu's name). The default is never filled in; a saved value is still localized.
63
+ */
64
+ export type CopyFieldRef = `${'section' | 'block'}:${string}.${string}`;
65
+ /**
66
+ * The copy plan of a theme, built once. A block name several schemas share
67
+ * (`newsletter`, `image` …) gets the union of their copy fields, and a default
68
+ * only where every one of those schemas agrees on it — an unset field is never
69
+ * filled with another schema's default.
70
+ */
71
+ /** The `shippedCopy` references that name no copy field of the theme (a test asserts there are none). */
72
+ export declare function unknownCopyRefs(theme: ThemeLike): string[];
73
+ export declare function copyPlanOf(theme: ThemeLike): CopyPlan;
74
+ /**
75
+ * The lookup for a theme: every `<prefix>*` key of its English locale map,
76
+ * inverted. The English file is the list, so a new shipped string is one new
77
+ * locale key and nothing else.
78
+ */
79
+ export declare function shippedCopyOf(english: Readonly<Record<string, string>> | undefined, prefix: string): ShippedCopy;
80
+ /**
81
+ * The section node with every shipped-English copy field (its own and its
82
+ * blocks') in the active language — the same object when nothing changes
83
+ * (an English page, or copy that is all the merchant's), so renders stay put.
84
+ */
85
+ export declare function localizeShippedCopy(node: ContentNode, copy: ShippedCopy, strings: Readonly<Record<string, string>>, plan: CopyPlan): ContentNode;
86
+ export {};
@@ -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,243 @@
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, metafieldBooleanLabelKey, 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
+ 'filter.metafield.true': 'Yes', 'filter.metafield.false': 'No',
42
+ },
43
+ th: {
44
+ featured: 'แนะนำ', 'price-asc': 'ราคา ต่ำไปสูง', 'price-desc': 'ราคา สูงไปต่ำ', 'title-asc': 'ชื่อ ก–ฮ',
45
+ 'filter.available': 'สถานะสินค้า', 'filter.productType': 'ประเภทสินค้า', 'filter.vendor': 'แบรนด์', 'filter.price': 'ราคา',
46
+ 'filter.available.true': 'มีสินค้า', 'filter.available.false': 'สินค้าหมด',
47
+ 'filter.metafield.true': 'ใช่', 'filter.metafield.false': 'ไม่ใช่',
48
+ },
49
+ ar: {
50
+ featured: 'مميز', 'price-asc': 'السعر، من الأقل إلى الأعلى', 'price-desc': 'السعر، من الأعلى إلى الأقل', 'title-asc': 'الاسم، أ–ي',
51
+ 'filter.available': 'التوفر', 'filter.productType': 'نوع المنتج', 'filter.vendor': 'العلامة التجارية', 'filter.price': 'السعر',
52
+ 'filter.available.true': 'متوفر', 'filter.available.false': 'غير متوفر',
53
+ 'filter.metafield.true': 'نعم', 'filter.metafield.false': 'لا',
54
+ },
55
+ };
56
+ const SORTS = ['featured', 'price-asc', 'price-desc', 'title-asc'];
57
+ const parse = (input) => {
58
+ try {
59
+ return JSON.parse(input);
60
+ }
61
+ catch {
62
+ return null;
63
+ }
64
+ };
65
+ const priceOf = (p) => Number(p.priceRange?.min?.amount ?? 0);
66
+ export function useListing(props) {
67
+ const data = useData();
68
+ const store = useStore();
69
+ const { locale } = useThemeContext();
70
+ const t = LABELS[(locale || 'en').split('-')[0]] ?? LABELS.en;
71
+ const handle = props?.collection?.handle ?? '';
72
+ const key = `collection-products:${handle}`;
73
+ const firstPage = handle ? store?.resources.get(key, undefined) : undefined;
74
+ const status = handle && store ? store.resources.status(key) : 'idle';
75
+ const [more, setMore] = useState(null);
76
+ const [, setLoading] = useState(false);
77
+ const [failed, setFailed] = useState(false);
78
+ const generation = useRef(0);
79
+ const inFlight = useRef(false);
80
+ const mine = more && more.handle === handle ? more : null;
81
+ // On the route's own collection the selection is the URL's (listing-query.ts).
82
+ const urlBound = Boolean(handle) && store?.ctx.currentCollection?.handle === handle;
83
+ const facetsForUrl = (firstPage?.filters ?? []).filter((f) => !HIDDEN_FACETS.has(f.id));
84
+ const fromUrl = () => {
85
+ if (!urlBound)
86
+ return { handle, values: {}, sort: 'featured' };
87
+ return { handle, ...stateFromQuery(store?.location.split('?')[1] ?? '', facetsForUrl) };
88
+ };
89
+ // ── Selection (filters + sort), keyed to the collection it was made on.
90
+ const [selection, setSelection] = useState(fromUrl);
91
+ const sel = selection.handle === handle ? selection : { handle, values: {}, sort: 'featured' };
92
+ const update = useCallback((f) => setSelection((s) => f(s.handle === handle ? s : { handle, values: {}, sort: 'featured' })), [handle]);
93
+ const filtered = Object.values(sel.values).some((v) => v.length > 0) || sel.price != null;
94
+ // The unfiltered facets: their values, counts and the price bounds stay put while
95
+ // the shopper narrows, so a value never vanishes from under the pointer.
96
+ const baseFilters = (firstPage?.filters ?? []).filter((f) => !HIDDEN_FACETS.has(f.id));
97
+ const priceFilter = baseFilters.find((f) => f.type === 'PRICE_RANGE');
98
+ const bounds = priceFilter ? (parse(priceFilter.values[0]?.input ?? '')?.price ?? null) : null;
99
+ // ── Filtered results.
100
+ const selKey = JSON.stringify([handle, sel.values, sel.price ?? null]);
101
+ // A filtered first render the server already answered (a shared filtered URL): its products are
102
+ // in the page data, so the server HTML and the hydrating browser show them without a fetch.
103
+ const [result, setResult] = useState(() => {
104
+ if (!filtered || !handle || !data.listingSeed)
105
+ return null;
106
+ const requests = filterRequests(sel, baseFilters, MAX_REQUESTS);
107
+ const seed = requests.length === 1 ? data.listingSeed(handle, requests[0]) : null;
108
+ return seed ? { key: selKey, products: map.toProducts(seed.products), pageInfo: seed.pageInfo ?? {}, filters: requests } : null;
109
+ });
110
+ const filterGeneration = useRef(0);
111
+ const [attempt, setAttempt] = useState(0);
112
+ useEffect(() => {
113
+ if (!filtered || !handle || !data.collectionProducts)
114
+ return;
115
+ if (result?.key === selKey && attempt === 0 && !result.failed)
116
+ return;
117
+ const id = ++filterGeneration.current;
118
+ const requests = filterRequests(sel, baseFilters, MAX_REQUESTS);
119
+ const fetchPage = data.collectionProducts;
120
+ Promise.all(requests.map((filters) => fetchPage(handle, { first: PER_REQUEST, filters })))
121
+ .then((pages) => {
122
+ if (id !== filterGeneration.current)
123
+ return;
124
+ const seen = new Set();
125
+ const union = pages.flatMap((p) => p.products).filter((p) => {
126
+ const pid = p?.id ?? '';
127
+ if (!p || seen.has(pid))
128
+ return false;
129
+ seen.add(pid);
130
+ return true;
131
+ });
132
+ const pageInfo = requests.length === 1 ? (pages[0].pageInfo ?? {}) : { hasNextPage: false };
133
+ setResult({ key: selKey, products: map.toProducts(union), pageInfo, filters: requests });
134
+ })
135
+ .catch(() => {
136
+ if (id === filterGeneration.current)
137
+ setResult({ key: selKey, products: [], pageInfo: {}, filters: requests, failed: true });
138
+ });
139
+ // selKey carries every input of this request.
140
+ // eslint-disable-next-line react-hooks/exhaustive-deps
141
+ }, [selKey, data, attempt]);
142
+ const current = filtered && result?.key === selKey ? result : null;
143
+ // ── Load more: the next page of whichever list is showing.
144
+ const pageInfo = filtered ? (current?.pageInfo ?? {}) : (mine?.pageInfo ?? firstPage?.pageInfo ?? {});
145
+ const onLoadMore = useCallback(async () => {
146
+ if (!handle || !data.collectionProducts || inFlight.current || !pageInfo.hasNextPage || !pageInfo.endCursor)
147
+ return;
148
+ inFlight.current = true;
149
+ const id = ++generation.current;
150
+ setLoading(true);
151
+ setFailed(false);
152
+ try {
153
+ const filters = current?.filters[0];
154
+ const page = await data.collectionProducts(handle, { first: PER_REQUEST, after: pageInfo.endCursor, ...(filters ? { filters } : {}) });
155
+ if (id !== generation.current)
156
+ return;
157
+ const next = map.toProducts(page.products);
158
+ if (current)
159
+ setResult({ ...current, products: [...current.products, ...next], pageInfo: page.pageInfo ?? {} });
160
+ else
161
+ setMore((prev) => ({
162
+ handle,
163
+ products: [...(prev && prev.handle === handle ? prev.products : []), ...next],
164
+ pageInfo: page.pageInfo ?? {},
165
+ }));
166
+ }
167
+ catch {
168
+ if (id === generation.current)
169
+ setFailed(true);
170
+ }
171
+ finally {
172
+ inFlight.current = false;
173
+ if (id === generation.current)
174
+ setLoading(false);
175
+ }
176
+ }, [data, handle, pageInfo.hasNextPage, pageInfo.endCursor, current]);
177
+ // Every change of the route collection's selection is written to the URL (never on the first
178
+ // render: a page opened from a shared URL keeps it as it is).
179
+ const urlQuery = urlBound ? queryOfState(sel, baseFilters) : null;
180
+ const wrote = useRef(urlQuery);
181
+ useEffect(() => {
182
+ if (urlQuery === null || typeof window === 'undefined' || urlQuery === wrote.current)
183
+ return;
184
+ wrote.current = urlQuery;
185
+ try {
186
+ window.history.replaceState(window.history.state, '', withListingQuery(window.location.href, urlQuery));
187
+ }
188
+ catch {
189
+ /* a sandboxed frame may refuse history writes */
190
+ }
191
+ }, [urlQuery]);
192
+ if (!props)
193
+ return {};
194
+ const unfiltered = [...(props.products ?? []), ...(mine?.products ?? [])];
195
+ const list = filtered ? (current?.products ?? []) : unfiltered;
196
+ const complete = !pageInfo.hasNextPage;
197
+ const sortable = complete && list.length > 1;
198
+ const sort = sortable ? sel.sort : 'featured';
199
+ const products = sort === 'price-asc' ? [...list].sort((a, b) => priceOf(a) - priceOf(b))
200
+ : sort === 'price-desc' ? [...list].sort((a, b) => priceOf(b) - priceOf(a))
201
+ : sort === 'title-asc' ? [...list].sort((a, b) => a.title.localeCompare(b.title, locale || undefined))
202
+ : list;
203
+ const known = props.total;
204
+ const total = filtered
205
+ ? products.length + (pageInfo.hasNextPage ? PER_REQUEST : 0)
206
+ : typeof known === 'number' && known >= products.length ? known : products.length + (pageInfo.hasNextPage ? PER_REQUEST : 0);
207
+ const state = failed || current?.failed ? 'error'
208
+ : filtered && !current ? 'loading'
209
+ : status === 'error' && !products.length ? 'error'
210
+ : status === 'loading' && !products.length ? 'loading'
211
+ : 'ready';
212
+ const currencyCode = unfiltered[0]?.priceRange?.min?.currencyCode;
213
+ const facets = baseFilters.flatMap((f) => {
214
+ if (f.type === 'PRICE_RANGE') {
215
+ if (!bounds || !currencyCode || bounds.min == null || bounds.max == null || bounds.min >= bounds.max)
216
+ return [];
217
+ 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 } }];
218
+ }
219
+ // A facet with one value (one brand for the whole store) narrows nothing.
220
+ if (f.values.length < 2)
221
+ return [];
222
+ const active = sel.values[f.id] ?? [];
223
+ return [{ id: f.id, label: t[f.id] ?? f.label, type: 'list', values: f.values.map((v) => ({ id: v.id, label: t[v.id] ?? t[metafieldBooleanLabelKey(v.id) ?? ''] ?? v.label, count: v.count, active: active.includes(v.id) })) }];
224
+ });
225
+ const sortOptions = sortable ? SORTS.map((id) => ({ id, label: t[id] })) : [];
226
+ return {
227
+ products,
228
+ total,
229
+ state,
230
+ facets,
231
+ sortOptions,
232
+ sort,
233
+ onToggleFilter: (facetId, valueId) => update((s) => {
234
+ const now = s.values[facetId] ?? [];
235
+ return { ...s, values: { ...s.values, [facetId]: now.includes(valueId) ? now.filter((v) => v !== valueId) : [...now, valueId] } };
236
+ }),
237
+ onPriceFilter: (_facetId, from, to) => update((s) => ({ ...s, price: from == null && to == null ? undefined : { from, to } })),
238
+ onClearFilters: () => update((s) => ({ ...s, values: {}, price: undefined })),
239
+ onSortChange: (id) => update((s) => ({ ...s, sort: id })),
240
+ onLoadMore: pageInfo.hasNextPage ? onLoadMore : undefined,
241
+ onRetry: failed ? onLoadMore : current?.failed ? () => setAttempt((n) => n + 1) : undefined,
242
+ };
243
+ }
@@ -0,0 +1,66 @@
1
+ import type { CartAddStock, CartRefusal } from '../kit/cart.js';
2
+ import type { AddToCartOptions, DiscountCodeRefusal, DiscountCodeResult } from '../../sdk/runtime-context.js';
3
+ /**
4
+ * The shopper-facing words for a refusal, in the page's language (locales/*.json): the merchant's
5
+ * limit when it is known, else that the most has been reached.
6
+ */
7
+ export declare function refusalMessage(t: (key: string, fallback?: string) => string, refusal: CartRefusal): string;
8
+ /**
9
+ * The shopper-facing words for an add stock cut (theme-abi Cart-2), in the page's language (locales/*.json): sold out,
10
+ * only some added, or none added because the cart already holds all that is in stock.
11
+ */
12
+ export declare function addStockMessage(t: (key: string, fallback?: string) => string, stock: CartAddStock): string;
13
+ /** The well-formed `{ key, value }` string pairs of an add's `options.attributes` (anything else is dropped). */
14
+ export declare function cartLineAttributes(raw: unknown): {
15
+ key: string;
16
+ value: string;
17
+ }[];
18
+ export interface CartActions {
19
+ /**
20
+ * Resolves true when the line is in the cart; never rejects. `options.sellingPlanId` adds a subscription line;
21
+ * `options.attributes` the line's custom attributes. An add stock cut (Cart-2) never opens the cart; it is told in a
22
+ * toast unless `options.showsStock` (the theme reads `lastAddStock`).
23
+ */
24
+ addToCart: (variantId: string, quantity: number, options?: AddToCartOptions) => Promise<boolean>;
25
+ /** What stock let the last add put in the cart when the platform cut it (Cart-2), else null. */
26
+ lastAddStock: () => CartAddStock | null;
27
+ setQuantity: (lineId: string, quantity: number) => Promise<void>;
28
+ removeLine: (lineId: string) => Promise<void>;
29
+ /** Lines with a request in flight — one slot per line, never one for the whole cart. */
30
+ busyLines: ReadonlySet<string>;
31
+ failedLines: ReadonlySet<string>;
32
+ /** Failed lines the store said why for (Cart-1). */
33
+ refusedLines: ReadonlyMap<string, CartRefusal>;
34
+ setNote: (note: string) => Promise<void>;
35
+ /** Absent when the cart source cannot tell whether a code applied (`CartApi.applyDiscountCode`). */
36
+ applyDiscountCode?: (code: string) => Promise<DiscountCodeResult>;
37
+ removeDiscountCode?: (code: string) => Promise<boolean>;
38
+ lastDiscountRefusal?: () => DiscountCodeRefusal | null;
39
+ lastDiscountReplaced?: () => readonly string[];
40
+ }
41
+ export declare function useCartActions(): CartActions;
42
+ /** Go to a storefront URL through the SPA router when it is on (a real click), else a full load. */
43
+ export declare function navigate(href: string): void;
44
+ export declare const searchHref: (query: string) => string;
45
+ /**
46
+ * The URL a Region & language choice loads: `?country=CC` when the country changes, `?locale=ll`
47
+ * when the language changes (the platform honours both and remembers them for later pages). Only
48
+ * what changed is set, so a language switch never pins a country the visitor never picked.
49
+ */
50
+ export declare function localeHref(href: string, next: {
51
+ countryCode?: string;
52
+ languageCode?: string;
53
+ }, current?: {
54
+ countryCode?: string;
55
+ languageCode?: string;
56
+ }): string | null;
57
+ /** Region & language change: a fresh load, since prices and copy are answered for the new market and language. */
58
+ export declare function changeLocale(next: {
59
+ countryCode?: string;
60
+ languageCode?: string;
61
+ }, current?: {
62
+ countryCode?: string;
63
+ languageCode?: string;
64
+ }): void;
65
+ /** Market change: prices are fetched for a country, so a change is a fresh load (same as the old switcher). */
66
+ export declare function changeCountry(countryCode: string): void;