@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,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,47 @@
|
|
|
1
|
+
import { type Schema } from '../../sdk/schema.js';
|
|
2
|
+
import type { ContentNode } from '../kit/types.js';
|
|
3
|
+
/** A node's settings as `resolveSettings` returned them, and its blocks' by block id (or `#<index>`). */
|
|
4
|
+
export interface ResolvedNode {
|
|
5
|
+
readonly settings: Readonly<Record<string, unknown>>;
|
|
6
|
+
readonly handles: Readonly<Record<string, string | string[]>>;
|
|
7
|
+
readonly blocks: Readonly<Record<string, ResolvedNode>>;
|
|
8
|
+
}
|
|
9
|
+
/** The schema a `defineClientSection` carries in place of a real one: no fields, recognised by identity. */
|
|
10
|
+
export declare const CLIENT_ONLY_SCHEMA: Schema;
|
|
11
|
+
export declare const isClientOnly: (section: {
|
|
12
|
+
schema?: unknown;
|
|
13
|
+
} | undefined) => boolean;
|
|
14
|
+
/**
|
|
15
|
+
* A block's position in its parent's list as the page saved it, before anything drops blocks (starter pruning): the
|
|
16
|
+
* kit tags every block with it (`withBlockIndex`) before binding, pruning and the shipped copy, and keeps it on the
|
|
17
|
+
* saved block a `data()` receives. A block with no id is filed under `#<that position>`, so the server, which renders
|
|
18
|
+
* the pruned list, and the browser, whose shopper bundle receives the list as saved (it cannot prune without the
|
|
19
|
+
* schemas), use the same key for the same block. (Its index in the pruned list would differ from the browser's as soon
|
|
20
|
+
* as a block before it was dropped.)
|
|
21
|
+
*/
|
|
22
|
+
export declare const BLOCK_INDEX: unique symbol;
|
|
23
|
+
/** The key a block's resolution is filed under: its id, else `#<its position as saved>` (`i` when the block is untagged). */
|
|
24
|
+
export declare function blockKey(b: {
|
|
25
|
+
id?: unknown;
|
|
26
|
+
}, i: number): string;
|
|
27
|
+
/**
|
|
28
|
+
* The node with each block (at every depth) tagged with its position as saved (BLOCK_INDEX, an enumerable symbol: the
|
|
29
|
+
* object spreads that bind, prune and localize keep it; JSON never sees it). Cached per node, so an unchanged node
|
|
30
|
+
* stays the same object.
|
|
31
|
+
*/
|
|
32
|
+
export declare function withBlockIndex(node: ContentNode): ContentNode;
|
|
33
|
+
/**
|
|
34
|
+
* The block definition a saved block renders with: the first of the section's block schemas named like it, or that
|
|
35
|
+
* lists its type among its earlier names (`legacyNames`): the rule the kit's renderers use (headless/theme.tsx), so a
|
|
36
|
+
* block saved under an old name is resolved as the block it now is.
|
|
37
|
+
*/
|
|
38
|
+
export declare function blockDefOf(blocks: readonly unknown[] | undefined, type: string): unknown;
|
|
39
|
+
/** Resolve a node with its definition's schema and block schemas (server; and the preview profile in the browser). */
|
|
40
|
+
export declare function resolveNode(def: {
|
|
41
|
+
schema: unknown;
|
|
42
|
+
blocks?: readonly unknown[];
|
|
43
|
+
}, node: ContentNode): ResolvedNode;
|
|
44
|
+
/** Server: where SectionRenderer records each rendered node's resolution (server.tsx puts it in the state). */
|
|
45
|
+
export declare const ResolvedSinkContext: import("react").Context<Map<string, ResolvedNode> | null>;
|
|
46
|
+
/** Browser: the state's resolutions, by node id. */
|
|
47
|
+
export declare const ResolvedStateContext: import("react").Context<Readonly<Record<string, ResolvedNode>> | null>;
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Server-resolved settings (theme-abi-v2.md §2.2.2, board 36 card B): the shopper bundle needs no section schema.
|
|
3
|
+
*
|
|
4
|
+
* The server resolves every node it renders (`resolveSettings` with the section's schema and its block schemas, after
|
|
5
|
+
* dynamic-source binding, starter pruning and the shipped copy) and puts the result in the page's hydration state, per
|
|
6
|
+
* node id. In the browser, `SectionRenderer` hands that result to the section's `data()` as `resolved`, so a section
|
|
7
|
+
* defined for the shopper bundle (`defineClientSection`: no schema, presets or block metadata) renders the same thing.
|
|
8
|
+
*
|
|
9
|
+
* Only nodes the server rendered are in the state (the host already stripped disabled nodes); everything a rendered
|
|
10
|
+
* section's settings hold is readable in page source, so a visible section's settings are public (§2.2.2 MUST 3).
|
|
11
|
+
*/
|
|
12
|
+
import { createContext } from 'react';
|
|
13
|
+
import { resolveSettings } from '../../sdk/schema.js';
|
|
14
|
+
/** The schema a `defineClientSection` carries in place of a real one: no fields, recognised by identity. */
|
|
15
|
+
export const CLIENT_ONLY_SCHEMA = Object.freeze({ kind: 'section', name: '@tanqory/client-only', family: 'client-only', fields: Object.freeze({}) });
|
|
16
|
+
export const isClientOnly = (section) => !!section && section.schema === CLIENT_ONLY_SCHEMA;
|
|
17
|
+
/**
|
|
18
|
+
* A block's position in its parent's list as the page saved it, before anything drops blocks (starter pruning): the
|
|
19
|
+
* kit tags every block with it (`withBlockIndex`) before binding, pruning and the shipped copy, and keeps it on the
|
|
20
|
+
* saved block a `data()` receives. A block with no id is filed under `#<that position>`, so the server, which renders
|
|
21
|
+
* the pruned list, and the browser, whose shopper bundle receives the list as saved (it cannot prune without the
|
|
22
|
+
* schemas), use the same key for the same block. (Its index in the pruned list would differ from the browser's as soon
|
|
23
|
+
* as a block before it was dropped.)
|
|
24
|
+
*/
|
|
25
|
+
export const BLOCK_INDEX = Symbol.for('tanqory.theme-kit.blockIndex');
|
|
26
|
+
/** The key a block's resolution is filed under: its id, else `#<its position as saved>` (`i` when the block is untagged). */
|
|
27
|
+
export function blockKey(b, i) {
|
|
28
|
+
if (typeof b.id === 'string' && b.id)
|
|
29
|
+
return b.id;
|
|
30
|
+
const at = b[BLOCK_INDEX];
|
|
31
|
+
return `#${typeof at === 'number' ? at : i}`;
|
|
32
|
+
}
|
|
33
|
+
const indexed = new WeakMap();
|
|
34
|
+
/**
|
|
35
|
+
* The node with each block (at every depth) tagged with its position as saved (BLOCK_INDEX, an enumerable symbol: the
|
|
36
|
+
* object spreads that bind, prune and localize keep it; JSON never sees it). Cached per node, so an unchanged node
|
|
37
|
+
* stays the same object.
|
|
38
|
+
*/
|
|
39
|
+
export function withBlockIndex(node) {
|
|
40
|
+
if (!node.blocks?.length)
|
|
41
|
+
return node;
|
|
42
|
+
const hit = indexed.get(node);
|
|
43
|
+
if (hit)
|
|
44
|
+
return hit;
|
|
45
|
+
const tag = (list) => list.map((b, i) => ({ ...b, [BLOCK_INDEX]: i, ...(b.blocks?.length ? { blocks: tag(b.blocks) } : {}) }));
|
|
46
|
+
const out = { ...node, blocks: tag(node.blocks) };
|
|
47
|
+
indexed.set(node, out);
|
|
48
|
+
return out;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* The block definition a saved block renders with: the first of the section's block schemas named like it, or that
|
|
52
|
+
* lists its type among its earlier names (`legacyNames`): the rule the kit's renderers use (headless/theme.tsx), so a
|
|
53
|
+
* block saved under an old name is resolved as the block it now is.
|
|
54
|
+
*/
|
|
55
|
+
export function blockDefOf(blocks, type) {
|
|
56
|
+
return blocks?.find((x) => x.name === type || !!x.legacyNames?.includes(type));
|
|
57
|
+
}
|
|
58
|
+
/** Resolve a node with its definition's schema and block schemas (server; and the preview profile in the browser). */
|
|
59
|
+
export function resolveNode(def, node) {
|
|
60
|
+
const r = resolveSettings(def.schema, node.settings);
|
|
61
|
+
const blocks = {};
|
|
62
|
+
const walk = (list, into) => {
|
|
63
|
+
;
|
|
64
|
+
(list ?? []).forEach((b, i) => {
|
|
65
|
+
const bdef = blockDefOf(def.blocks, b.type);
|
|
66
|
+
if (!bdef)
|
|
67
|
+
return;
|
|
68
|
+
const br = resolveSettings(bdef, b.settings);
|
|
69
|
+
const kids = {};
|
|
70
|
+
walk(b.blocks, kids);
|
|
71
|
+
into[blockKey(b, i)] = { settings: br.settings, handles: br.handles, blocks: kids };
|
|
72
|
+
});
|
|
73
|
+
};
|
|
74
|
+
walk(node.blocks, blocks);
|
|
75
|
+
return { settings: r.settings, handles: r.handles, blocks };
|
|
76
|
+
}
|
|
77
|
+
/** Server: where SectionRenderer records each rendered node's resolution (server.tsx puts it in the state). */
|
|
78
|
+
export const ResolvedSinkContext = createContext(null);
|
|
79
|
+
/** Browser: the state's resolutions, by node id. */
|
|
80
|
+
export const ResolvedStateContext = createContext(null);
|