@tanqory/theme-kit 0.1.0 → 2.0.0-alpha.19
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.
- package/LICENSE +21 -0
- package/README.md +128 -10
- package/dist/abi/canvas-live.d.ts +72 -0
- package/dist/abi/canvas-live.js +159 -0
- package/dist/abi/cart.d.ts +60 -0
- package/dist/abi/cart.js +396 -0
- package/dist/abi/convert.d.ts +360 -0
- package/dist/abi/convert.js +1330 -0
- package/dist/abi/data-api.d.ts +15 -0
- package/dist/abi/data-api.js +213 -0
- package/dist/abi/jcs.d.ts +6 -0
- package/dist/abi/jcs.js +28 -0
- package/dist/abi/labels.d.ts +3 -0
- package/dist/abi/labels.js +34 -0
- package/dist/abi/page-data.d.ts +264 -0
- package/dist/abi/page-data.js +746 -0
- package/dist/abi/page.d.ts +28 -0
- package/dist/abi/page.js +57 -0
- package/dist/abi/referrals.d.ts +23 -0
- package/dist/abi/referrals.js +89 -0
- package/dist/abi/rewards.d.ts +27 -0
- package/dist/abi/rewards.js +82 -0
- package/dist/abi/seo.d.ts +47 -0
- package/dist/abi/seo.js +68 -0
- package/dist/abi/shell.d.ts +23 -0
- package/dist/abi/shell.js +10 -0
- package/dist/abi/state-pack.d.ts +17 -0
- package/dist/abi/state-pack.js +43 -0
- package/dist/abi/wire.d.ts +46 -0
- package/dist/abi/wire.js +114 -0
- package/dist/build.d.ts +121 -0
- package/dist/build.js +401 -0
- package/dist/chunks.d.ts +23 -0
- package/dist/chunks.js +41 -0
- package/dist/client.d.ts +26 -0
- package/dist/client.js +101 -0
- package/dist/contract.d.ts +6 -0
- package/dist/contract.js +6 -0
- package/dist/headless/ai.d.ts +132 -0
- package/dist/headless/ai.js +99 -0
- package/dist/headless/hooks.d.ts +276 -0
- package/dist/headless/hooks.js +544 -0
- package/dist/headless/i18n.d.ts +13 -0
- package/dist/headless/i18n.js +45 -0
- package/dist/headless/index.d.ts +44 -0
- package/dist/headless/index.js +48 -0
- package/dist/headless/lazy-component.d.ts +72 -0
- package/dist/headless/lazy-component.js +225 -0
- package/dist/headless/lazy-section.d.ts +38 -0
- package/dist/headless/lazy-section.js +97 -0
- package/dist/headless/model.d.ts +73 -0
- package/dist/headless/model.js +115 -0
- package/dist/headless/money.d.ts +17 -0
- package/dist/headless/money.js +63 -0
- package/dist/headless/page.d.ts +45 -0
- package/dist/headless/page.js +53 -0
- package/dist/headless/platform.d.ts +55 -0
- package/dist/headless/platform.js +77 -0
- package/dist/headless/primitives/cart.d.ts +90 -0
- package/dist/headless/primitives/cart.js +153 -0
- package/dist/headless/primitives/collection.d.ts +68 -0
- package/dist/headless/primitives/collection.js +80 -0
- package/dist/headless/primitives/product.d.ts +101 -0
- package/dist/headless/primitives/product.js +117 -0
- package/dist/headless/primitives/storefront.d.ts +106 -0
- package/dist/headless/primitives/storefront.js +187 -0
- package/dist/headless/primitives/util.d.ts +19 -0
- package/dist/headless/primitives/util.js +42 -0
- package/dist/headless/strings.d.ts +9 -0
- package/dist/headless/strings.js +198 -0
- package/dist/headless/structured-data.d.ts +31 -0
- package/dist/headless/structured-data.js +57 -0
- package/dist/headless/tanqory-money.generated.d.ts +493 -0
- package/dist/headless/tanqory-money.generated.js +507 -0
- package/dist/headless/theme.d.ts +109 -0
- package/dist/headless/theme.js +62 -0
- package/dist/index.d.ts +21 -0
- package/dist/index.js +21 -553
- package/dist/runtime/data/StoreProvider.d.ts +84 -0
- package/dist/runtime/data/StoreProvider.js +380 -0
- package/dist/runtime/data/handle.d.ts +14 -0
- package/dist/runtime/data/handle.js +16 -0
- package/dist/runtime/data/routes.d.ts +87 -0
- package/dist/runtime/data/routes.js +158 -0
- package/dist/runtime/data/to-ui.d.ts +286 -0
- package/dist/runtime/data/to-ui.js +1009 -0
- package/dist/runtime/entries/register.d.ts +9 -0
- package/dist/runtime/entries/register.js +9 -0
- package/dist/runtime/entries/sections.d.ts +16 -0
- package/dist/runtime/entries/sections.js +19 -0
- package/dist/{types → runtime/kit}/SectionTree.d.ts +2 -1
- package/dist/runtime/kit/SectionTree.js +100 -0
- package/dist/runtime/kit/analytics.d.ts +63 -0
- package/dist/runtime/kit/analytics.js +250 -0
- package/dist/runtime/kit/cart.d.ts +222 -0
- package/dist/runtime/kit/cart.js +545 -0
- package/dist/{types → runtime/kit}/composition.d.ts +1 -1
- package/dist/runtime/kit/composition.js +3 -0
- package/dist/{types → runtime/kit}/config.d.ts +2 -2
- package/dist/runtime/kit/config.js +6 -0
- package/dist/runtime/kit/consent.d.ts +29 -0
- package/dist/runtime/kit/consent.js +159 -0
- package/dist/runtime/kit/contract/content.d.ts +213 -0
- package/dist/runtime/kit/contract/content.js +119 -0
- package/dist/runtime/kit/contract/field-types.d.ts +360 -0
- package/dist/runtime/kit/contract/field-types.js +216 -0
- package/dist/runtime/kit/contract/groups.d.ts +230 -0
- package/dist/runtime/kit/contract/groups.js +402 -0
- package/dist/runtime/kit/contract/index.d.ts +33 -0
- package/dist/runtime/kit/contract/index.js +33 -0
- package/dist/runtime/kit/contract/transform.d.ts +82 -0
- package/dist/runtime/kit/contract/transform.js +133 -0
- package/dist/runtime/kit/contract/validate.d.ts +77 -0
- package/dist/runtime/kit/contract/validate.js +520 -0
- package/dist/runtime/kit/data.d.ts +732 -0
- package/dist/runtime/kit/data.js +1131 -0
- package/dist/{types → runtime/kit}/defineSection.d.ts +1 -1
- package/dist/runtime/kit/defineSection.js +10 -0
- package/dist/runtime/kit/dynamic-source.d.ts +118 -0
- package/dist/runtime/kit/dynamic-source.js +311 -0
- package/dist/runtime/kit/index.d.ts +24 -0
- package/dist/runtime/kit/index.js +24 -0
- package/dist/{types → runtime/kit}/jsx-to-json.d.ts +1 -1
- package/dist/runtime/kit/jsx-to-json.js +28 -0
- package/dist/{types → runtime/kit}/mount.d.ts +25 -4
- package/dist/runtime/kit/mount.js +124 -0
- package/dist/{types → runtime/kit}/registry.d.ts +1 -1
- package/dist/runtime/kit/registry.js +12 -0
- package/dist/{types → runtime/kit}/ssg.d.ts +9 -3
- package/dist/runtime/kit/ssg.js +56 -0
- package/dist/runtime/kit/storefront.d.ts +652 -0
- package/dist/runtime/kit/storefront.js +723 -0
- package/dist/{types → runtime/kit}/theme-context.d.ts +8 -2
- package/dist/runtime/kit/theme-context.js +25 -0
- package/dist/runtime/kit/types.d.ts +155 -0
- package/dist/runtime/kit/types.js +1 -0
- package/dist/runtime/platform/TrackingPixels.d.ts +14 -0
- package/dist/runtime/platform/TrackingPixels.js +63 -0
- package/dist/runtime/platform/environment.d.ts +68 -0
- package/dist/runtime/platform/environment.js +85 -0
- package/dist/runtime/platform/locale.d.ts +27 -0
- package/dist/runtime/platform/locale.js +42 -0
- package/dist/runtime/platform/route-analytics.d.ts +15 -0
- package/dist/runtime/platform/route-analytics.js +72 -0
- package/dist/runtime/platform/safe-href.d.ts +25 -0
- package/dist/runtime/platform/safe-href.js +69 -0
- package/dist/runtime/platform/safe-values.d.ts +37 -0
- package/dist/runtime/platform/safe-values.js +140 -0
- package/dist/runtime/render/SectionRenderer.d.ts +4 -0
- package/dist/runtime/render/SectionRenderer.js +199 -0
- package/dist/runtime/render/listing-query.d.ts +52 -0
- package/dist/runtime/render/listing-query.js +122 -0
- package/dist/runtime/render/localized-copy.d.ts +86 -0
- package/dist/runtime/render/localized-copy.js +129 -0
- package/dist/runtime/render/product-listing.d.ts +11 -0
- package/dist/runtime/render/product-listing.js +243 -0
- package/dist/runtime/render/resolved.d.ts +47 -0
- package/dist/runtime/render/resolved.js +80 -0
- package/dist/runtime/render/section-actions.d.ts +67 -0
- package/dist/runtime/render/section-actions.js +205 -0
- package/dist/runtime/render/starter.d.ts +11 -0
- package/dist/runtime/render/starter.js +96 -0
- package/dist/runtime/seo/head.d.ts +115 -0
- package/dist/runtime/seo/head.js +281 -0
- package/dist/runtime/seo/structured-data.d.ts +83 -0
- package/dist/runtime/seo/structured-data.js +252 -0
- package/dist/runtime/shell/PageShell.d.ts +18 -0
- package/dist/runtime/shell/PageShell.js +118 -0
- package/dist/runtime/shell/RuntimeBridge.d.ts +18 -0
- package/dist/runtime/shell/RuntimeBridge.js +124 -0
- package/dist/runtime/shell/overlay-state.d.ts +31 -0
- package/dist/runtime/shell/overlay-state.js +59 -0
- package/dist/runtime/shell/preview-mode.d.ts +2 -0
- package/dist/runtime/shell/preview-mode.js +11 -0
- package/dist/runtime/shell/spa-router.d.ts +14 -0
- package/dist/runtime/shell/spa-router.js +76 -0
- package/dist/runtime/shell/url-redirects.d.ts +6 -0
- package/dist/runtime/shell/url-redirects.js +37 -0
- package/dist/runtime/slots.d.ts +74 -0
- package/dist/runtime/slots.js +16 -0
- package/dist/runtime.d.ts +34 -0
- package/dist/runtime.js +40 -0
- package/dist/sdk/app-block.d.ts +29 -0
- package/dist/sdk/app-block.js +22 -0
- package/dist/sdk/font-hooks.d.ts +7 -0
- package/dist/sdk/font-hooks.js +21 -0
- package/dist/sdk/fonts.d.ts +144 -0
- package/dist/sdk/fonts.js +241 -0
- package/dist/sdk/index.d.ts +32 -0
- package/dist/sdk/index.js +36 -0
- package/dist/sdk/motion-hooks.d.ts +23 -0
- package/dist/sdk/motion-hooks.js +46 -0
- package/dist/sdk/motion.d.ts +78 -0
- package/dist/sdk/motion.js +292 -0
- package/dist/sdk/referrals.d.ts +62 -0
- package/dist/sdk/referrals.js +20 -0
- package/dist/sdk/rewards.d.ts +85 -0
- package/dist/sdk/rewards.js +29 -0
- package/dist/sdk/runtime-context.d.ts +230 -0
- package/dist/sdk/runtime-context.js +73 -0
- package/dist/sdk/schema.d.ts +249 -0
- package/dist/sdk/schema.js +168 -0
- package/dist/sdk/server-render.d.ts +8 -0
- package/dist/sdk/server-render.js +12 -0
- package/dist/sdk/store-lookup.d.ts +32 -0
- package/dist/sdk/store-lookup.js +48 -0
- package/dist/sdk/store.d.ts +164 -0
- package/dist/sdk/store.js +5 -0
- package/dist/sdk/sx.d.ts +45 -0
- package/dist/sdk/sx.js +117 -0
- package/dist/sdk/theme.d.ts +212 -0
- package/dist/sdk/theme.js +27 -0
- package/dist/sdk/types.d.ts +789 -0
- package/dist/sdk/types.js +7 -0
- package/dist/server.d.ts +112 -0
- package/dist/server.js +589 -0
- package/dist/vite-chunks.d.ts +10 -0
- package/dist/vite-chunks.js +44 -0
- package/docs/headless-api.md +250 -0
- package/package.json +72 -26
- package/dist/index.js.map +0 -1
- package/dist/ssg-BZ5FYTw7.js +0 -1802
- package/dist/ssg-BZ5FYTw7.js.map +0 -1
- package/dist/ssg.js +0 -8
- package/dist/ssg.js.map +0 -1
- package/dist/types/cart.d.ts +0 -86
- package/dist/types/data.d.ts +0 -357
- package/dist/types/dynamic-source.d.ts +0 -84
- package/dist/types/editor.d.ts +0 -5
- package/dist/types/index.d.ts +0 -20
- package/dist/types/preview-bridge.d.ts +0 -9
- package/dist/types/storefront.d.ts +0 -333
- package/dist/types/types.d.ts +0 -44
|
@@ -0,0 +1,544 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Data hooks of the headless API. Each reads what the kit runtime already loaded for this page (the server's data
|
|
3
|
+
* plan over `ctx.data`, then the same-origin `/_tq/data` wire in the browser) and returns plain data plus the
|
|
4
|
+
* actions that change it. None of them fetches anything the runtime would not, and none renders markup.
|
|
5
|
+
*
|
|
6
|
+
* They work inside a theme's sections and Layout (the runtime's providers wrap both), on the server and in the
|
|
7
|
+
* hydrating browser alike: the first render of each is built from the same data, so hydration matches.
|
|
8
|
+
*/
|
|
9
|
+
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
|
|
10
|
+
import { useThemeActions, useThemeContext } from '../sdk/runtime-context.js';
|
|
11
|
+
import { useStore } from '../runtime/data/StoreProvider.js';
|
|
12
|
+
// Straight from the defining modules, never the runtime/kit barrel: the barrel re-exports ssg.js, whose
|
|
13
|
+
// `react-dom/server` import is CommonJS, and esbuild (build-service's bundler) keeps it in a client bundle even with
|
|
14
|
+
// sideEffects false. Through the barrel the client carried ~70 kB of react-dom/server (BLD 2026-11-21, Nova 831bc27d).
|
|
15
|
+
import { useCart as useRuntimeCart } from '../runtime/kit/cart.js';
|
|
16
|
+
import { useData } from '../runtime/kit/data.js';
|
|
17
|
+
import * as map from '../runtime/data/to-ui.js';
|
|
18
|
+
import { filterRequests, metafieldBooleanLabelKey, queryOfState, stateFromQuery, withListingQuery } from '../runtime/render/listing-query.js';
|
|
19
|
+
import { localeHref } from '../runtime/render/section-actions.js';
|
|
20
|
+
import { usePage } from './page.js';
|
|
21
|
+
import { useTranslate } from './i18n.js';
|
|
22
|
+
// ── settings · shop · menu ─────────────────────────────────────────────────
|
|
23
|
+
/** The theme's global settings: the manifest defaults with the store's saved values over them. */
|
|
24
|
+
export function useSettings() {
|
|
25
|
+
return useThemeContext().settings;
|
|
26
|
+
}
|
|
27
|
+
/** The store as the page shows it: name, logo, contact, social links, payment methods, policies, cookie banner. */
|
|
28
|
+
export function useShop() {
|
|
29
|
+
const store = useStore();
|
|
30
|
+
const context = useThemeContext();
|
|
31
|
+
return store?.ctx.shop ?? context.shop ?? { name: '' };
|
|
32
|
+
}
|
|
33
|
+
/** A store menu by handle (a `menu` setting's value), with `active` marking the current route; null when absent. */
|
|
34
|
+
export function useMenu(handle) {
|
|
35
|
+
const store = useStore();
|
|
36
|
+
if (!handle || !store)
|
|
37
|
+
return null;
|
|
38
|
+
return store.ctx.menus[handle] ?? null;
|
|
39
|
+
}
|
|
40
|
+
const sameOptions = (v, want) => v.selectedOptions.every((o) => want[o.name] === undefined || want[o.name] === o.value);
|
|
41
|
+
/** The variant to open on: `wanted` when it belongs to the product, else the first available, else the first. */
|
|
42
|
+
export function initialVariant(product, wanted) {
|
|
43
|
+
const list = product?.variants ?? [];
|
|
44
|
+
return (wanted ? list.find((v) => v.id === wanted) : undefined) ?? list.find((v) => v.available) ?? list[0] ?? null;
|
|
45
|
+
}
|
|
46
|
+
/** The option values of `product` around `selected`: each value's availability and the variant it selects. */
|
|
47
|
+
export function optionStates(product, selected) {
|
|
48
|
+
if (!product)
|
|
49
|
+
return [];
|
|
50
|
+
const current = Object.fromEntries((selected?.selectedOptions ?? []).map((o) => [o.name, o.value]));
|
|
51
|
+
return product.options.map((o) => ({
|
|
52
|
+
name: o.name,
|
|
53
|
+
values: o.values.map((value) => {
|
|
54
|
+
const want = { ...current, [o.name]: value };
|
|
55
|
+
const exact = product.variants.find((v) => sameOptions(v, want));
|
|
56
|
+
const any = exact ?? product.variants.find((v) => v.selectedOptions.some((so) => so.name === o.name && so.value === value));
|
|
57
|
+
return { value, selected: current[o.name] === value, available: Boolean(exact?.available), variantId: any?.id ?? null };
|
|
58
|
+
}),
|
|
59
|
+
}));
|
|
60
|
+
}
|
|
61
|
+
/** The product state `<ProductForm>` shares with the primitives inside it. */
|
|
62
|
+
export const ProductContext = createContext(null);
|
|
63
|
+
/**
|
|
64
|
+
* A product and its variant selection. Without an argument: the product of the enclosing `<ProductForm>`, else
|
|
65
|
+
* the route's product (product pages), opened on the `?variant=` the URL names. With a handle: that product (a
|
|
66
|
+
* `product` setting's value). A product object is used as given. Choosing a variant of the route's product keeps
|
|
67
|
+
* `?variant=` in the address bar, so the link shares.
|
|
68
|
+
*/
|
|
69
|
+
export function useProduct(input) {
|
|
70
|
+
const shared = useContext(ProductContext);
|
|
71
|
+
const sameAsShared = shared !== null && (input == null || (typeof input === 'string' ? input === shared.product?.handle : input === shared.product));
|
|
72
|
+
const own = useProductState(input, sameAsShared);
|
|
73
|
+
return sameAsShared ? shared : own;
|
|
74
|
+
}
|
|
75
|
+
/** The state behind `useProduct` (`inactive`: another instance owns this product; no URL writes). */
|
|
76
|
+
export function useProductState(input, inactive = false) {
|
|
77
|
+
const store = useStore();
|
|
78
|
+
const ctx = store?.ctx;
|
|
79
|
+
let product = null;
|
|
80
|
+
let unavailable = false;
|
|
81
|
+
if (input && typeof input === 'object')
|
|
82
|
+
product = input;
|
|
83
|
+
else if (typeof input === 'string' && input) {
|
|
84
|
+
if (ctx?.unavailableProducts?.includes(input))
|
|
85
|
+
unavailable = true;
|
|
86
|
+
else
|
|
87
|
+
product = ctx?.products?.[input] ?? null;
|
|
88
|
+
}
|
|
89
|
+
else
|
|
90
|
+
product = ctx?.currentProduct ?? null;
|
|
91
|
+
const isRoute = Boolean(product && ctx?.currentProduct && ctx.currentProduct.handle === product.handle);
|
|
92
|
+
const wanted = isRoute ? ctx?.currentVariantId : undefined;
|
|
93
|
+
const [selection, setSelection] = useState(() => ({ handle: product?.handle ?? '', id: initialVariant(product, wanted)?.id ?? null }));
|
|
94
|
+
const [quantity, setQuantityState] = useState(1);
|
|
95
|
+
const handle = product?.handle ?? '';
|
|
96
|
+
const selectedId = selection.handle === handle ? selection.id : (initialVariant(product, wanted)?.id ?? null);
|
|
97
|
+
const variant = product?.variants.find((v) => v.id === selectedId) ?? initialVariant(product, wanted);
|
|
98
|
+
// Keep `?variant=` in the URL for the route's product (never on the first render: the URL already says it).
|
|
99
|
+
const wrote = useRef(variant?.id ?? null);
|
|
100
|
+
useEffect(() => {
|
|
101
|
+
if (inactive || !isRoute || !variant || typeof window === 'undefined' || wrote.current === variant.id)
|
|
102
|
+
return;
|
|
103
|
+
wrote.current = variant.id;
|
|
104
|
+
try {
|
|
105
|
+
const url = new URL(window.location.href);
|
|
106
|
+
url.searchParams.set('variant', variant.id);
|
|
107
|
+
window.history.replaceState(window.history.state, '', url.toString());
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
/* a sandboxed frame may refuse history writes */
|
|
111
|
+
}
|
|
112
|
+
}, [inactive, isRoute, variant]);
|
|
113
|
+
const selectVariant = useCallback((id) => setSelection({ handle, id }), [handle]);
|
|
114
|
+
const selectOption = useCallback((name, value) => {
|
|
115
|
+
if (!product)
|
|
116
|
+
return;
|
|
117
|
+
const current = Object.fromEntries((variant?.selectedOptions ?? []).map((o) => [o.name, o.value]));
|
|
118
|
+
const want = { ...current, [name]: value };
|
|
119
|
+
const next = product.variants.find((v) => sameOptions(v, want)) ?? product.variants.find((v) => v.available && v.selectedOptions.some((o) => o.name === name && o.value === value)) ?? product.variants.find((v) => v.selectedOptions.some((o) => o.name === name && o.value === value));
|
|
120
|
+
if (next)
|
|
121
|
+
setSelection({ handle, id: next.id });
|
|
122
|
+
}, [product, variant, handle]);
|
|
123
|
+
const setQuantity = useCallback((q) => setQuantityState(Number.isFinite(q) ? Math.max(1, Math.floor(q)) : 1), []);
|
|
124
|
+
const price = variant?.price ?? product?.priceRange.min ?? null;
|
|
125
|
+
const compareAtPrice = variant?.compareAtPrice ?? null;
|
|
126
|
+
return {
|
|
127
|
+
product,
|
|
128
|
+
unavailable,
|
|
129
|
+
variant,
|
|
130
|
+
options: optionStates(product, variant),
|
|
131
|
+
selectOption,
|
|
132
|
+
selectVariant,
|
|
133
|
+
price,
|
|
134
|
+
compareAtPrice,
|
|
135
|
+
onSale: Boolean(price && compareAtPrice && compareAtPrice.amount > price.amount),
|
|
136
|
+
available: variant ? variant.available : Boolean(product?.available),
|
|
137
|
+
quantityAvailable: typeof variant?.quantityAvailable === 'number' ? variant.quantityAvailable : null,
|
|
138
|
+
image: variant?.image ?? product?.featuredImage ?? product?.images[0] ?? null,
|
|
139
|
+
quantity,
|
|
140
|
+
setQuantity,
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
// ── collection ─────────────────────────────────────────────────────────────
|
|
144
|
+
/** The collection sorts the data plane answers (`?sort=`), in the order a sort control offers them. */
|
|
145
|
+
export const COLLECTION_SORTS = ['featured', 'best-selling', 'title-asc', 'title-desc', 'price-asc', 'price-desc', 'created-desc', 'created-asc'];
|
|
146
|
+
const SORT_ORDER = {
|
|
147
|
+
featured: {},
|
|
148
|
+
'best-selling': { sortKey: 'BEST_SELLING' },
|
|
149
|
+
'title-asc': { sortKey: 'TITLE' },
|
|
150
|
+
'title-desc': { sortKey: 'TITLE', reverse: true },
|
|
151
|
+
'price-asc': { sortKey: 'PRICE' },
|
|
152
|
+
'price-desc': { sortKey: 'PRICE', reverse: true },
|
|
153
|
+
'created-desc': { sortKey: 'CREATED', reverse: true },
|
|
154
|
+
'created-asc': { sortKey: 'CREATED' },
|
|
155
|
+
};
|
|
156
|
+
const isSort = (s) => typeof s === 'string' && COLLECTION_SORTS.includes(s);
|
|
157
|
+
/** Product tags are the merchant's internal labels, never a shopper filter. */
|
|
158
|
+
const HIDDEN_FACETS = new Set(['filter.tag']);
|
|
159
|
+
const PER_PAGE = 24;
|
|
160
|
+
const MAX_FIRST = 250;
|
|
161
|
+
const MAX_REQUESTS = 12;
|
|
162
|
+
/** Comparator for a sort the client applies to a union of several filter requests. */
|
|
163
|
+
function compare(sort, locale) {
|
|
164
|
+
const price = (p) => p.priceRange.min.amount;
|
|
165
|
+
switch (sort) {
|
|
166
|
+
case 'price-asc': return (a, b) => price(a) - price(b);
|
|
167
|
+
case 'price-desc': return (a, b) => price(b) - price(a);
|
|
168
|
+
case 'title-asc': return (a, b) => a.title.localeCompare(b.title, locale || undefined);
|
|
169
|
+
case 'title-desc': return (a, b) => b.title.localeCompare(a.title, locale || undefined);
|
|
170
|
+
default: return null;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
/** The collection state `<CollectionProvider>` shares with the primitives inside it. */
|
|
174
|
+
export const CollectionContext = createContext(null);
|
|
175
|
+
/**
|
|
176
|
+
* A collection with its facets, sort and paging. Inside `<CollectionProvider>` (without an argument, or with its
|
|
177
|
+
* handle) every caller shares that provider's state, so a sort control, the filters and the grid agree.
|
|
178
|
+
* Otherwise, without an argument: the route's collection, whose selection
|
|
179
|
+
* lives in the URL (`?sort=`, `?filter.<facet>=`), so a sorted or filtered page shares and reloads. With a
|
|
180
|
+
* handle: that collection (a `collection` setting's value), selection kept in the component.
|
|
181
|
+
*
|
|
182
|
+
* The first render shows what the server rendered (the data plane applies `?sort=` and `?page=`). A change of
|
|
183
|
+
* selection asks the data plane again through the browser wire, sorted and filtered there.
|
|
184
|
+
*/
|
|
185
|
+
export function useCollection(handle) {
|
|
186
|
+
const shared = useContext(CollectionContext);
|
|
187
|
+
const sameAsShared = shared !== null && (!handle || handle === shared.collection?.handle);
|
|
188
|
+
const own = useCollectionState(handle, sameAsShared);
|
|
189
|
+
return sameAsShared ? shared : own;
|
|
190
|
+
}
|
|
191
|
+
/** The state behind `useCollection` (`inactive`: another instance owns this collection; no requests, no URL writes). */
|
|
192
|
+
export function useCollectionState(handle, inactive = false) {
|
|
193
|
+
const store = useStore();
|
|
194
|
+
const data = useData();
|
|
195
|
+
const page = usePage();
|
|
196
|
+
const t = useTranslate();
|
|
197
|
+
const ctx = store?.ctx;
|
|
198
|
+
const routeHandle = ctx?.currentCollection?.handle;
|
|
199
|
+
const h = handle || routeHandle || '';
|
|
200
|
+
const unavailable = Boolean(handle && ctx?.unavailableCollections?.includes(handle));
|
|
201
|
+
const collection = !h || unavailable ? null : ((handle ? ctx?.collections?.[handle] : ctx?.currentCollection) ?? null);
|
|
202
|
+
const urlBound = Boolean(h) && h === routeHandle;
|
|
203
|
+
const rawFacets = useMemo(() => (data.collectionByHandle?.(h)?.filters ?? []).filter((f) => !HIDDEN_FACETS.has(f.id)), [data, h]);
|
|
204
|
+
const listingFacets = rawFacets;
|
|
205
|
+
const query = urlBound ? (store?.location.split('?')[1] ?? '') : '';
|
|
206
|
+
const pageNumber = urlBound && /^[1-9][0-9]{0,5}$/.test(page.params.page ?? '') ? Number(page.params.page) : 1;
|
|
207
|
+
const serverProducts = collection?.products ?? [];
|
|
208
|
+
const initial = useMemo(() => {
|
|
209
|
+
const parsed = stateFromQuery(query, listingFacets);
|
|
210
|
+
const sortParam = new URLSearchParams(query).get('sort');
|
|
211
|
+
return { handle: h, values: parsed.values, ...(parsed.price ? { price: parsed.price } : {}), sort: isSort(sortParam) ? sortParam : 'featured', first: Math.max(serverProducts.length, PER_PAGE) };
|
|
212
|
+
// The selection the page was rendered with: computed once per collection.
|
|
213
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
214
|
+
}, [h]);
|
|
215
|
+
const [selection, setSelection] = useState(initial);
|
|
216
|
+
const sel = selection.handle === h ? selection : initial;
|
|
217
|
+
const filtered = Object.values(sel.values).some((v) => v.length > 0) || sel.price != null;
|
|
218
|
+
const requests = useMemo(() => filterRequests({ values: sel.values, ...(sel.price ? { price: sel.price } : {}) }, listingFacets, MAX_REQUESTS), [sel.values, sel.price, listingFacets]);
|
|
219
|
+
const key = JSON.stringify([h, sel.values, sel.price ?? null, sel.sort, sel.first]);
|
|
220
|
+
const initialKey = JSON.stringify([h, initial.values, initial.price ?? null, initial.sort, initial.first]);
|
|
221
|
+
// What the server rendered answers the initial selection: the snapshot page, or the filtered seed of a shared URL.
|
|
222
|
+
const seed = useMemo(() => {
|
|
223
|
+
if (!filtered || requests.length !== 1 || !data.listingSeed)
|
|
224
|
+
return null;
|
|
225
|
+
const s = data.listingSeed(h, requests[0]);
|
|
226
|
+
return s ? { products: map.toProducts(s.products), hasNext: Boolean(s.pageInfo?.hasNextPage) } : null;
|
|
227
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
228
|
+
}, [h]);
|
|
229
|
+
const fromServer = key === initialKey && (!filtered || seed !== null);
|
|
230
|
+
const [result, setResult] = useState(null);
|
|
231
|
+
const generation = useRef(0);
|
|
232
|
+
useEffect(() => {
|
|
233
|
+
if (inactive || fromServer || !h || !data.collectionProducts)
|
|
234
|
+
return;
|
|
235
|
+
if (result?.key === key && !result.failed)
|
|
236
|
+
return;
|
|
237
|
+
const id = ++generation.current;
|
|
238
|
+
const order = SORT_ORDER[sel.sort];
|
|
239
|
+
const asks = requests.length ? requests : [[]];
|
|
240
|
+
const fetchPage = data.collectionProducts;
|
|
241
|
+
Promise.all(asks.map((filters) => fetchPage(h, { first: Math.min(sel.first, MAX_FIRST), ...(order.sortKey ? { sortKey: order.sortKey } : {}), ...(order.reverse ? { reverse: true } : {}), ...(filters.length ? { filters } : {}) })))
|
|
242
|
+
.then((pages) => {
|
|
243
|
+
if (id !== generation.current)
|
|
244
|
+
return;
|
|
245
|
+
const seen = new Set();
|
|
246
|
+
let list = map.toProducts(pages.flatMap((p) => p.products)).filter((p) => (seen.has(p.id) ? false : (seen.add(p.id), true)));
|
|
247
|
+
const cmp = asks.length > 1 ? compare(sel.sort, page.ui) : null;
|
|
248
|
+
if (cmp)
|
|
249
|
+
list = [...list].sort(cmp);
|
|
250
|
+
setResult({ key, products: list, hasNext: asks.length === 1 && Boolean(pages[0]?.pageInfo?.hasNextPage) });
|
|
251
|
+
})
|
|
252
|
+
.catch(() => {
|
|
253
|
+
if (id === generation.current)
|
|
254
|
+
setResult((r) => ({ key, products: r?.products ?? [], hasNext: false, failed: true }));
|
|
255
|
+
});
|
|
256
|
+
// `key` carries every input of the request.
|
|
257
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
258
|
+
}, [key, fromServer, data, inactive]);
|
|
259
|
+
// The route collection's selection is the URL's: written on every change (never on the first render).
|
|
260
|
+
const urlQuery = urlBound ? queryOfState({ values: sel.values, ...(sel.price ? { price: sel.price } : {}), sort: sel.sort }, listingFacets) : null;
|
|
261
|
+
const wroteQuery = useRef(urlQuery);
|
|
262
|
+
useEffect(() => {
|
|
263
|
+
if (inactive || urlQuery === null || typeof window === 'undefined' || urlQuery === wroteQuery.current)
|
|
264
|
+
return;
|
|
265
|
+
wroteQuery.current = urlQuery;
|
|
266
|
+
try {
|
|
267
|
+
window.history.replaceState(window.history.state, '', withListingQuery(window.location.href, urlQuery));
|
|
268
|
+
}
|
|
269
|
+
catch {
|
|
270
|
+
/* a sandboxed frame may refuse history writes */
|
|
271
|
+
}
|
|
272
|
+
}, [urlQuery, inactive]);
|
|
273
|
+
const update = useCallback((f) => setSelection((s) => f(s.handle === h ? s : initial)), [h, initial]);
|
|
274
|
+
const current = result && result.key === key ? result : null;
|
|
275
|
+
const products = fromServer ? (seed ? seed.products : serverProducts) : (current?.products ?? (result?.products ?? serverProducts));
|
|
276
|
+
const count = typeof collection?.productsCount === 'number' ? collection.productsCount : null;
|
|
277
|
+
const serverHasMore = seed ? seed.hasNext : count !== null ? serverProducts.length < count : false;
|
|
278
|
+
// While a request is open the control keeps the answer it had, so it does not vanish under the pointer.
|
|
279
|
+
const hasMore = pageNumber > 1 ? false : fromServer ? serverHasMore : current ? current.hasNext : result ? result.hasNext : serverHasMore;
|
|
280
|
+
const status = current?.failed ? 'error' : !fromServer && !current ? 'loading' : 'ready';
|
|
281
|
+
// A value's own word when the theme names it, else Yes / No for a boolean metafield value, else the platform's label.
|
|
282
|
+
const valueLabel = (id, fallback) => {
|
|
283
|
+
if (t(id) !== id)
|
|
284
|
+
return t(id);
|
|
285
|
+
const b = metafieldBooleanLabelKey(id);
|
|
286
|
+
return b && t(b) !== b ? t(b) : fallback;
|
|
287
|
+
};
|
|
288
|
+
const facets = rawFacets.flatMap((f) => {
|
|
289
|
+
const label = t(f.id) === f.id ? f.label : t(f.id);
|
|
290
|
+
if (f.type === 'PRICE_RANGE') {
|
|
291
|
+
let bounds = null;
|
|
292
|
+
try {
|
|
293
|
+
bounds = JSON.parse(f.values[0]?.input ?? '{}').price ?? null;
|
|
294
|
+
}
|
|
295
|
+
catch {
|
|
296
|
+
bounds = null;
|
|
297
|
+
}
|
|
298
|
+
const currencyCode = serverProducts[0]?.priceRange.min.currencyCode;
|
|
299
|
+
if (!bounds || bounds.min == null || bounds.max == null || bounds.min >= bounds.max || !currencyCode)
|
|
300
|
+
return [];
|
|
301
|
+
return [{ id: f.id, label, type: 'price', range: { min: Math.floor(bounds.min), max: Math.ceil(bounds.max), from: sel.price?.from, to: sel.price?.to, currencyCode } }];
|
|
302
|
+
}
|
|
303
|
+
if (f.values.length < 2)
|
|
304
|
+
return [];
|
|
305
|
+
const active = sel.values[f.id] ?? [];
|
|
306
|
+
return [{ id: f.id, label, type: 'list', values: f.values.map((v) => ({ id: v.id, label: valueLabel(v.id, v.label), count: v.count, active: active.includes(v.id) })) }];
|
|
307
|
+
});
|
|
308
|
+
const filteredTotal = current && !current.hasNext ? current.products.length : null;
|
|
309
|
+
return {
|
|
310
|
+
collection,
|
|
311
|
+
unavailable,
|
|
312
|
+
products,
|
|
313
|
+
total: filtered ? (fromServer && seed && !seed.hasNext ? seed.products.length : filteredTotal) : count,
|
|
314
|
+
status,
|
|
315
|
+
facets,
|
|
316
|
+
selected: sel.values,
|
|
317
|
+
price: sel.price ?? null,
|
|
318
|
+
filtered,
|
|
319
|
+
toggleFilter: (facetId, valueId) => update((s) => {
|
|
320
|
+
const now = s.values[facetId] ?? [];
|
|
321
|
+
return { ...s, values: { ...s.values, [facetId]: now.includes(valueId) ? now.filter((v) => v !== valueId) : [...now, valueId] }, first: PER_PAGE };
|
|
322
|
+
}),
|
|
323
|
+
setPrice: (from, to) => update((s) => ({ ...s, ...(from == null && to == null ? { price: undefined } : { price: { ...(from != null ? { from } : {}), ...(to != null ? { to } : {}) } }), first: PER_PAGE })),
|
|
324
|
+
clearFilters: () => update((s) => ({ ...s, values: {}, price: undefined, first: PER_PAGE })),
|
|
325
|
+
sort: sel.sort,
|
|
326
|
+
sortOptions: COLLECTION_SORTS.map((id) => ({ id, label: t(`sort.${id}`) })),
|
|
327
|
+
setSort: (s) => { if (isSort(s))
|
|
328
|
+
update((x) => ({ ...x, sort: s, first: Math.max(x.first, products.length, PER_PAGE) })); },
|
|
329
|
+
hasMore,
|
|
330
|
+
loadMore: () => { if (hasMore)
|
|
331
|
+
update((s) => ({ ...s, first: Math.min(Math.max(s.first, products.length) + PER_PAGE, MAX_FIRST) })); },
|
|
332
|
+
page: pageNumber,
|
|
333
|
+
pageHref: (n) => {
|
|
334
|
+
const base = new URLSearchParams(query);
|
|
335
|
+
if (n > 1)
|
|
336
|
+
base.set('page', String(n));
|
|
337
|
+
else
|
|
338
|
+
base.delete('page');
|
|
339
|
+
const qs = base.toString();
|
|
340
|
+
return `${collection?.url ?? ''}${qs ? `?${qs}` : ''}`;
|
|
341
|
+
},
|
|
342
|
+
};
|
|
343
|
+
}
|
|
344
|
+
// ── search ─────────────────────────────────────────────────────────────────
|
|
345
|
+
export const SEARCH_SORT_IDS = ['relevance', 'price-asc', 'price-desc', 'title-asc', 'created-desc'];
|
|
346
|
+
/** The search page's results (`/search?q=…&sort=…`), rendered by the server. */
|
|
347
|
+
export function useSearch() {
|
|
348
|
+
const store = useStore();
|
|
349
|
+
const t = useTranslate();
|
|
350
|
+
const ctx = store?.ctx;
|
|
351
|
+
const r = ctx?.searchResults ?? null;
|
|
352
|
+
return {
|
|
353
|
+
query: ctx?.searchQuery ?? '',
|
|
354
|
+
products: r?.products ?? [],
|
|
355
|
+
articles: r?.articles ?? [],
|
|
356
|
+
pages: r?.pages ?? [],
|
|
357
|
+
total: r ? r.total : null,
|
|
358
|
+
sort: ctx?.searchSort ?? 'relevance',
|
|
359
|
+
sortOptions: SEARCH_SORT_IDS.map((id) => ({ id, label: t(`sort.${id}`) })),
|
|
360
|
+
href: (q, sort) => `/search?q=${encodeURIComponent(q.trim())}${sort && sort !== 'relevance' ? `&sort=${encodeURIComponent(sort)}` : ''}`,
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
/**
|
|
364
|
+
* Suggestions while the shopper types (`catalog.predictive` over the browser wire; needs `data:search` in the
|
|
365
|
+
* manifest's browser capabilities). Debounced; an answer for an older query never shows under a newer one.
|
|
366
|
+
* On the server, and for an empty query, `results` is null.
|
|
367
|
+
*/
|
|
368
|
+
export function usePredictiveSearch(query, options = {}) {
|
|
369
|
+
const data = useData();
|
|
370
|
+
const limit = options.limit ?? 6;
|
|
371
|
+
const debounceMs = options.debounceMs ?? 200;
|
|
372
|
+
const term = query.trim();
|
|
373
|
+
const [answer, setAnswer] = useState(null);
|
|
374
|
+
useEffect(() => {
|
|
375
|
+
if (!term || !data.predictiveSearch)
|
|
376
|
+
return;
|
|
377
|
+
let alive = true;
|
|
378
|
+
const timer = setTimeout(() => {
|
|
379
|
+
data.predictiveSearch(term, { limit })
|
|
380
|
+
.then((r) => {
|
|
381
|
+
if (!alive)
|
|
382
|
+
return;
|
|
383
|
+
setAnswer({
|
|
384
|
+
term,
|
|
385
|
+
results: {
|
|
386
|
+
products: r.products.map((p) => ({ handle: p.handle, title: p.title, url: map.productUrl(p.handle), price: map.toMoney(p.price), image: map.toImage(p.featuredImage) })),
|
|
387
|
+
collections: r.collections.map((c) => ({ handle: c.handle, title: c.title, url: map.collectionUrl(c.handle) })),
|
|
388
|
+
queries: [...r.queries],
|
|
389
|
+
},
|
|
390
|
+
});
|
|
391
|
+
})
|
|
392
|
+
.catch(() => {
|
|
393
|
+
if (alive)
|
|
394
|
+
setAnswer({ term, results: { products: [], collections: [], queries: [] } });
|
|
395
|
+
});
|
|
396
|
+
}, debounceMs);
|
|
397
|
+
return () => {
|
|
398
|
+
alive = false;
|
|
399
|
+
clearTimeout(timer);
|
|
400
|
+
};
|
|
401
|
+
}, [term, data, limit, debounceMs]);
|
|
402
|
+
const fresh = answer && answer.term === term ? answer.results : null;
|
|
403
|
+
return { results: term ? fresh : null, loading: Boolean(term && data.predictiveSearch) && !fresh };
|
|
404
|
+
}
|
|
405
|
+
/** The shopper's cart and every cart action (`/_tq/actions/cart.*`, versioned, conflicts retried by the runtime). */
|
|
406
|
+
export function useCart() {
|
|
407
|
+
const context = useThemeContext();
|
|
408
|
+
const actions = useThemeActions();
|
|
409
|
+
const raw = useRuntimeCart();
|
|
410
|
+
const cart = context.cart;
|
|
411
|
+
return {
|
|
412
|
+
cart,
|
|
413
|
+
lines: cart?.lines ?? [],
|
|
414
|
+
itemCount: cart?.itemCount ?? 0,
|
|
415
|
+
subtotal: cart && cart.lines.length ? cart.subtotal : null,
|
|
416
|
+
total: cart && cart.lines.length ? cart.total : null,
|
|
417
|
+
checkoutUrl: raw.checkoutUrl ?? context.checkoutUrl,
|
|
418
|
+
ready: raw.ready,
|
|
419
|
+
loading: raw.loading,
|
|
420
|
+
loadError: raw.loadError ?? null,
|
|
421
|
+
isOpen: context.overlay === 'cart',
|
|
422
|
+
justAdded: context.justAddedToCart,
|
|
423
|
+
open: actions.cart.open,
|
|
424
|
+
close: actions.overlays.close,
|
|
425
|
+
add: (variantId, quantity = 1, options) => actions.cart.add(variantId, quantity, options),
|
|
426
|
+
setQuantity: actions.cart.setQuantity,
|
|
427
|
+
remove: actions.cart.remove,
|
|
428
|
+
setNote: actions.cart.setNote,
|
|
429
|
+
isBusy: (id) => context.busyLines.includes(id),
|
|
430
|
+
hasFailed: (id) => context.failedLines.includes(id),
|
|
431
|
+
refusal: (id) => context.refusedLines[id] ?? null,
|
|
432
|
+
};
|
|
433
|
+
}
|
|
434
|
+
/**
|
|
435
|
+
* The shopper's account state. Customer data never reaches theme code: the account area is the platform's
|
|
436
|
+
* iframe (`<AccountSlot>`). `signedIn` is read only when the page asks for it (a `header` section, or
|
|
437
|
+
* `storefront.plan.account`), because the page then varies on it.
|
|
438
|
+
*/
|
|
439
|
+
export function useCustomer() {
|
|
440
|
+
const data = useData();
|
|
441
|
+
return {
|
|
442
|
+
signedIn: typeof data.signedIn === 'boolean' ? data.signedIn : null,
|
|
443
|
+
accountUrl: data.accountUrl ? data.accountUrl('profile') : null,
|
|
444
|
+
accountHref: '/account',
|
|
445
|
+
};
|
|
446
|
+
}
|
|
447
|
+
const languageName = (code) => {
|
|
448
|
+
try {
|
|
449
|
+
return new Intl.DisplayNames([code], { type: 'language' }).of(code) ?? code;
|
|
450
|
+
}
|
|
451
|
+
catch {
|
|
452
|
+
return code;
|
|
453
|
+
}
|
|
454
|
+
};
|
|
455
|
+
/**
|
|
456
|
+
* The shopper's market and language, and the switch between them (`?country=`, `?locale=`; the platform
|
|
457
|
+
* remembers both). The country list exists only on a page that reads the shopper's country: a `header`/`footer`
|
|
458
|
+
* section with `showLocale`, or `storefront.plan.localization`.
|
|
459
|
+
*/
|
|
460
|
+
export function useLocalization() {
|
|
461
|
+
const store = useStore();
|
|
462
|
+
const actions = useThemeActions();
|
|
463
|
+
const page = usePage();
|
|
464
|
+
const loc = store?.ctx.localization ?? null;
|
|
465
|
+
const current = loc?.current ?? null;
|
|
466
|
+
const countries = [];
|
|
467
|
+
for (const m of loc?.available ?? []) {
|
|
468
|
+
if (!m.countryCode || countries.some((c) => c.code === m.countryCode))
|
|
469
|
+
continue;
|
|
470
|
+
countries.push({ code: m.countryCode, name: m.country, currencyCode: m.currencyCode, currencySymbol: m.currencySymbol, current: m.countryCode === current?.countryCode });
|
|
471
|
+
}
|
|
472
|
+
const langCodes = [...new Set([...(page.languages ?? []), ...(loc?.available ?? []).map((m) => m.languageCode)].filter(Boolean))];
|
|
473
|
+
const currentLang = (current?.languageCode || page.language || 'en').split('-')[0].toLowerCase();
|
|
474
|
+
const languages = langCodes.map((code) => ({ code, name: (loc?.available ?? []).find((m) => m.languageCode === code)?.language ?? languageName(code), current: code.split('-')[0].toLowerCase() === currentLang }));
|
|
475
|
+
const now = { countryCode: current?.countryCode ?? '', languageCode: current?.languageCode ?? page.language };
|
|
476
|
+
const change = (next) => {
|
|
477
|
+
if (actions.localization.changeLocale)
|
|
478
|
+
actions.localization.changeLocale(next, now);
|
|
479
|
+
else if (next.countryCode)
|
|
480
|
+
actions.localization.changeCountry(next.countryCode);
|
|
481
|
+
};
|
|
482
|
+
return {
|
|
483
|
+
localization: loc,
|
|
484
|
+
country: countries.find((c) => c.current) ?? null,
|
|
485
|
+
language: languages.find((l) => l.current) ?? { code: currentLang, name: languageName(currentLang), current: true },
|
|
486
|
+
countries,
|
|
487
|
+
languages,
|
|
488
|
+
changeCountry: (code) => change({ countryCode: code }),
|
|
489
|
+
changeLanguage: (code) => change({ languageCode: code }),
|
|
490
|
+
href: (next) => {
|
|
491
|
+
const base = page.canonical || 'https://localhost/';
|
|
492
|
+
return localeHref(base, { countryCode: next.country, languageCode: next.language }, { countryCode: now.countryCode, languageCode: now.languageCode }) ?? base;
|
|
493
|
+
},
|
|
494
|
+
};
|
|
495
|
+
}
|
|
496
|
+
// ── recommendations ────────────────────────────────────────────────────────
|
|
497
|
+
/**
|
|
498
|
+
* Products recommended with the route's product (`catalog.recommendations`). In the server render when the page
|
|
499
|
+
* asks for them (a `product-recommendations` section, or `storefront.plan.recommendations`); otherwise loaded by
|
|
500
|
+
* the browser after the page shows, which needs `data:products.recommendations` in the browser capabilities.
|
|
501
|
+
*/
|
|
502
|
+
export function useRecommendations() {
|
|
503
|
+
const store = useStore();
|
|
504
|
+
const rec = store?.ctx.recommendations;
|
|
505
|
+
return { products: rec?.related ?? [], loading: Boolean(store?.ctx.currentProduct) && rec === undefined };
|
|
506
|
+
}
|
|
507
|
+
/** The cookie banner's state and the shopper's answer (`/_tq/actions/consent.set`). The platform owns consent. */
|
|
508
|
+
export function useConsent() {
|
|
509
|
+
const context = useThemeContext();
|
|
510
|
+
const actions = useThemeActions();
|
|
511
|
+
const shop = useShop();
|
|
512
|
+
return {
|
|
513
|
+
required: context.consentRequired,
|
|
514
|
+
accept: () => actions.consent.decide({ analytics: true, marketing: true }),
|
|
515
|
+
reject: () => actions.consent.decide({ analytics: false, marketing: false }),
|
|
516
|
+
decide: actions.consent.decide,
|
|
517
|
+
reopen: actions.consent.open,
|
|
518
|
+
privacyUrl: context.privacyPolicyUrl,
|
|
519
|
+
text: shop.consentBanner?.text ?? {},
|
|
520
|
+
};
|
|
521
|
+
}
|
|
522
|
+
// ── content: pages, blogs, articles, policies ──────────────────────────────
|
|
523
|
+
/** The route's content page (`/pages/<handle>`): its title and HTML body; null elsewhere or when the store has none. */
|
|
524
|
+
export function usePageContent() {
|
|
525
|
+
const store = useStore();
|
|
526
|
+
return store?.ctx.currentPage ?? null;
|
|
527
|
+
}
|
|
528
|
+
/** A blog with its articles: the route's (`/blogs/<handle>`, and an article's blog), or the one a `blog` setting names. */
|
|
529
|
+
export function useBlog(handle) {
|
|
530
|
+
const store = useStore();
|
|
531
|
+
const page = usePage();
|
|
532
|
+
const h = handle || (page.kind === 'article' ? page.blogHandle : page.kind === 'blog' ? page.handle : undefined);
|
|
533
|
+
return h && store ? (store.ctx.blogs?.[h] ?? null) : null;
|
|
534
|
+
}
|
|
535
|
+
/** The route's article (`/blogs/<blog>/<handle>`) with its HTML body; null elsewhere. */
|
|
536
|
+
export function useArticle() {
|
|
537
|
+
const store = useStore();
|
|
538
|
+
return store?.ctx.currentArticle ?? null;
|
|
539
|
+
}
|
|
540
|
+
/** The route's store policy (`/policies/<handle>`); null elsewhere or when it is not published. */
|
|
541
|
+
export function usePolicy() {
|
|
542
|
+
const store = useStore();
|
|
543
|
+
return store?.ctx.currentPolicy ?? null;
|
|
544
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { KIT_STRINGS, kitStrings, type Strings } from './strings.js';
|
|
2
|
+
export { KIT_STRINGS, kitStrings, type Strings };
|
|
3
|
+
export type TranslateVars = Readonly<Record<string, string | number>>;
|
|
4
|
+
/** Fill `{name}` placeholders; a placeholder with no value stays as written. */
|
|
5
|
+
export declare function interpolate(text: string, vars?: TranslateVars): string;
|
|
6
|
+
/** Pure lookup over the layers, most specific first. */
|
|
7
|
+
export declare function translate(layers: readonly (Strings | null | undefined)[], key: string, vars?: TranslateVars): string;
|
|
8
|
+
export type Translate = (key: string, vars?: TranslateVars) => string;
|
|
9
|
+
/**
|
|
10
|
+
* `t(key, vars?)` for this page: the merchant's wording, then the theme's locale file, then the kit's words.
|
|
11
|
+
* Stable for the render (a new function only when a layer changes).
|
|
12
|
+
*/
|
|
13
|
+
export declare function useTranslate(): Translate;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Interface strings for a headless theme.
|
|
3
|
+
*
|
|
4
|
+
* t(key, vars?) the merchant's dashboard wording → the theme's `locales/<lang>.json` → the kit's own words for
|
|
5
|
+
* that language → the kit's English → the key itself. `{name}` placeholders are filled from `vars`.
|
|
6
|
+
*
|
|
7
|
+
* The kit's primitives render no word that is not looked up here, under the keys in `KIT_STRINGS`. A theme that
|
|
8
|
+
* ships those keys in its own locale files (spread `kitStrings(lang)` in, or override any of them) shows its own
|
|
9
|
+
* words; one that does not still shows a sensible default in English and Thai.
|
|
10
|
+
*
|
|
11
|
+
* The keys end in the names the storefront check recognises (`addToCart`, `soldOut`, `checkout`, `remove`, …),
|
|
12
|
+
* so a theme that keeps them is found by its own strings too.
|
|
13
|
+
*/
|
|
14
|
+
import { useMemo } from 'react';
|
|
15
|
+
import { useLocaleStrings } from '../runtime/kit/theme-context.js';
|
|
16
|
+
import { usePage } from './page.js';
|
|
17
|
+
import { KIT_STRINGS, kitStrings } from './strings.js';
|
|
18
|
+
export { KIT_STRINGS, kitStrings };
|
|
19
|
+
/** Fill `{name}` placeholders; a placeholder with no value stays as written. */
|
|
20
|
+
export function interpolate(text, vars) {
|
|
21
|
+
if (!vars)
|
|
22
|
+
return text;
|
|
23
|
+
return text.replace(/\{([A-Za-z0-9_.-]+)\}/g, (m, k) => (Object.prototype.hasOwnProperty.call(vars, k) ? String(vars[k]) : m));
|
|
24
|
+
}
|
|
25
|
+
/** Pure lookup over the layers, most specific first. */
|
|
26
|
+
export function translate(layers, key, vars) {
|
|
27
|
+
for (const l of layers) {
|
|
28
|
+
const v = l?.[key];
|
|
29
|
+
if (typeof v === 'string')
|
|
30
|
+
return interpolate(v, vars);
|
|
31
|
+
}
|
|
32
|
+
return key;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* `t(key, vars?)` for this page: the merchant's wording, then the theme's locale file, then the kit's words.
|
|
36
|
+
* Stable for the render (a new function only when a layer changes).
|
|
37
|
+
*/
|
|
38
|
+
export function useTranslate() {
|
|
39
|
+
const theme = useLocaleStrings();
|
|
40
|
+
const page = usePage();
|
|
41
|
+
return useMemo(() => {
|
|
42
|
+
const layers = [page.strings, theme, kitStrings(page.ui), KIT_STRINGS.en];
|
|
43
|
+
return (key, vars) => translate(layers, key, vars);
|
|
44
|
+
}, [theme, page]);
|
|
45
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@tanqory/theme-kit/headless` — every storefront function, no styling. A theme supplies all markup and CSS;
|
|
3
|
+
* the kit supplies the data, the behaviour and accessible, semantic primitives carrying the platform's
|
|
4
|
+
* `tq-storefront-hooks/1` attributes (`data-tq-action`, `data-tq-price`, `data-tq-variant-picker`, …).
|
|
5
|
+
*
|
|
6
|
+
* declare defineTheme · defineSection · defineBlock · field · ai.* · AppBlock · APP_BLOCKS ('@app')
|
|
7
|
+
* data useShop · useMenu · useProduct · useCollection · useSearch · usePredictiveSearch · useCart ·
|
|
8
|
+
* useCustomer · useLocalization · useRecommendations · useConsent · usePage
|
|
9
|
+
* commerce ProductForm · VariantPicker · ProductPrice · ProductQuantity · AddToCart · CartToggle · CartDrawer ·
|
|
10
|
+
* CartLine (+ Quantity / Increment / Decrement / Remove) · CheckoutButton · CollectionProvider ·
|
|
11
|
+
* FacetFilters · SortSelect · Pagination · SearchForm · LocalizationForm · NewsletterForm ·
|
|
12
|
+
* ContactForm · ConsentBanner · AccountSlot
|
|
13
|
+
* platform Seo · Image · SkipLink · useTranslate (t) · formatMoney · currencyDecimals · sx
|
|
14
|
+
*
|
|
15
|
+
* The server entry is `createRender({ manifest, bundle, storefront: {} })` (`@tanqory/theme-kit/server`); the
|
|
16
|
+
* browser entry is `hydrate({ bundle })` (`@tanqory/theme-kit/client`), which also applies live edits on the
|
|
17
|
+
* editor canvas. The manifest comes from `buildManifest` (`@tanqory/theme-kit/build`).
|
|
18
|
+
*/
|
|
19
|
+
export { defineTheme, defineSection, defineBlock, type HeadlessThemeDefinition, type SectionDefinition, type SectionComponentProps, type SectionPresetDef, type BlockSchema, type BlockInstance, type HeadlessSection, type SettingsFor } from './theme.js';
|
|
20
|
+
export { ai, aiProfileOf, checkAiProfile, type AiRole, type AiProfile } from './ai.js';
|
|
21
|
+
export { field, defineSchema, resolveSettings, type Field, type Fields, type Schema } from '../sdk/schema.js';
|
|
22
|
+
export { defineSettings, type SettingSpec } from '../sdk/theme.js';
|
|
23
|
+
export { AppBlock, isAppBlock, appBlockSettingsJson, type AppBlockProps } from '../sdk/app-block.js';
|
|
24
|
+
export { APP_BLOCKS } from '../runtime/kit/contract/content.js';
|
|
25
|
+
export { FONT_CATALOGUE, SYSTEM_FONTS, FONT_WEIGHTS, fontSetting, fontOptions, fontStack, isCatalogueFont, type CatalogueFont, type ThemeFont, type FontOption, type FontScript, type FontSettingInput } from '../sdk/fonts.js';
|
|
26
|
+
export { useFont } from '../sdk/font-hooks.js';
|
|
27
|
+
export { useSettings, useShop, useMenu, useProduct, useProductState, useCollection, useCollectionState, useSearch, usePredictiveSearch, useCart, useCustomer, useLocalization, useRecommendations, useConsent, usePageContent, useBlog, useArticle, usePolicy, initialVariant, optionStates, ProductContext, CollectionContext, COLLECTION_SORTS, SEARCH_SORT_IDS, type ProductState, type OptionValueState, type CollectionState, type CollectionSort, type SearchState, type PredictiveResults, type CartStateHeadless as CartState, type CustomerState, type LocalizationState, type CountryChoice, type LanguageChoice, type ConsentState, } from './hooks.js';
|
|
28
|
+
export { usePage, DETACHED_PAGE, type PageInfo } from './page.js';
|
|
29
|
+
export { ProductForm, VariantPicker, ProductPrice, ProductQuantity, AddToCart, useProductForm, type ProductFormState, type ProductFormProps, type VariantPickerProps, type ProductPriceProps, type ProductQuantityProps, type AddToCartProps } from './primitives/product.js';
|
|
30
|
+
export { CartToggle, CartDrawer, CartLine, CartLineQuantity, CartLineIncrement, CartLineDecrement, CartLineRemove, CheckoutButton, useCartLine, type CartLineState, type CartToggleProps, type CartDrawerProps, type CartLineProps } from './primitives/cart.js';
|
|
31
|
+
export { CollectionProvider, SortSelect, FacetFilters, Pagination, type CollectionProviderProps, type SortSelectProps, type FacetFiltersProps, type PaginationProps } from './primitives/collection.js';
|
|
32
|
+
export { SearchForm, LocalizationForm, NewsletterForm, ContactForm, ConsentBanner, AccountSlot, type SearchFormProps, type LocalizationFormProps, type PlatformFormProps, type PlatformFormState, type FormStatus, type ConsentBannerProps } from './primitives/storefront.js';
|
|
33
|
+
export { Seo, Image, SkipLink, resolveImageUrl, type SeoProps, type ImageProps } from './platform.js';
|
|
34
|
+
export { lazySection } from './lazy-section.js';
|
|
35
|
+
export { lazyComponent, preloadOnIdle, type LazyComponent, type LazyComponentOptions } from './lazy-component.js';
|
|
36
|
+
export { ModelViewer, ModelViewerBase, loadModelViewer, MODEL_VIEWER_SRC, MODEL_VIEWER_INTEGRITY, type ModelViewerProps, type ModelViewerBaseProps, type ModelViewerLabels, type ModelMedia } from './model.js';
|
|
37
|
+
export { useTranslate, translate, interpolate, KIT_STRINGS, kitStrings, type Translate, type TranslateVars, type Strings } from './i18n.js';
|
|
38
|
+
export { formatMoney, currencyDecimals, currencySymbol, type MoneyLike, type FormatMoneyOptions } from './money.js';
|
|
39
|
+
export { productJsonLd, homeJsonLd, articleJsonLd, collectionJsonLd, breadcrumbJsonLd, type JsonLd, type Crumb } from './structured-data.js';
|
|
40
|
+
export { sx, cx as sxJoin } from '../sdk/sx.js';
|
|
41
|
+
export { visuallyHidden } from './primitives/util.js';
|
|
42
|
+
export type { Shop, Menu, MenuItem, Link, Image as ImageData, Video, Money, Product, ProductVariant, ProductOption, ProductSellingPlanGroup, ProductSellingPlan, Collection, Facet, FacetValue, SortOption, Cart, CartLine as CartLineData, CartLineSellingPlan, CartLineDiscount, Article, Blog, Policy, Localization, Market, BreadcrumbItem, SearchResults, CartLineAttribute, GiftCardBalance, GiftCardMoney } from '../sdk/types.js';
|
|
43
|
+
export type { AddToCartOptions } from '../sdk/runtime-context.js';
|
|
44
|
+
export type { ThemeBundle } from '../runtime/slots.js';
|