@tanqory/theme-kit 0.1.0 → 2.0.0-alpha.5
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 +98 -10
- package/dist/abi/canvas-live.d.ts +49 -0
- package/dist/abi/canvas-live.js +88 -0
- package/dist/abi/cart.d.ts +48 -0
- package/dist/abi/cart.js +321 -0
- package/dist/abi/convert.d.ts +192 -0
- package/dist/abi/convert.js +670 -0
- package/dist/abi/data-api.d.ts +15 -0
- package/dist/abi/data-api.js +198 -0
- package/dist/abi/jcs.d.ts +6 -0
- package/dist/abi/jcs.js +28 -0
- package/dist/abi/page-data.d.ts +209 -0
- package/dist/abi/page-data.js +583 -0
- package/dist/abi/page.d.ts +23 -0
- package/dist/abi/page.js +46 -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 +22 -0
- package/dist/abi/shell.js +10 -0
- package/dist/abi/wire.d.ts +38 -0
- package/dist/abi/wire.js +84 -0
- package/dist/build.d.ts +113 -0
- package/dist/build.js +294 -0
- package/dist/client.d.ts +19 -0
- package/dist/client.js +76 -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 +273 -0
- package/dist/headless/hooks.js +533 -0
- package/dist/headless/i18n.d.ts +13 -0
- package/dist/headless/i18n.js +45 -0
- package/dist/headless/index.d.ts +36 -0
- package/dist/headless/index.js +38 -0
- package/dist/headless/money.d.ts +25 -0
- package/dist/headless/money.js +61 -0
- package/dist/headless/page.d.ts +43 -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 +186 -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 +186 -0
- package/dist/headless/structured-data.d.ts +31 -0
- package/dist/headless/structured-data.js +57 -0
- package/dist/headless/theme.d.ts +99 -0
- package/dist/headless/theme.js +54 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.js +18 -553
- package/dist/runtime/data/StoreProvider.d.ts +56 -0
- package/dist/runtime/data/StoreProvider.js +308 -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 +154 -0
- package/dist/runtime/data/to-ui.d.ts +258 -0
- package/dist/runtime/data/to-ui.js +820 -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 +233 -0
- package/dist/runtime/kit/cart.d.ts +186 -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 +164 -0
- package/dist/runtime/kit/contract/content.js +83 -0
- package/dist/runtime/kit/contract/field-types.d.ts +290 -0
- package/dist/runtime/kit/contract/field-types.js +129 -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 +67 -0
- package/dist/runtime/kit/contract/validate.js +388 -0
- package/dist/runtime/kit/data.d.ts +636 -0
- package/dist/runtime/kit/data.js +1117 -0
- package/dist/{types → runtime/kit}/defineSection.d.ts +1 -1
- package/dist/runtime/kit/defineSection.js +10 -0
- package/dist/{types → runtime/kit}/dynamic-source.d.ts +4 -4
- package/dist/runtime/kit/dynamic-source.js +143 -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 +566 -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 +142 -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 +111 -0
- package/dist/runtime/render/listing-query.d.ts +47 -0
- package/dist/runtime/render/listing-query.js +114 -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 +240 -0
- package/dist/runtime/render/section-actions.d.ts +48 -0
- package/dist/runtime/render/section-actions.js +170 -0
- package/dist/runtime/render/starter.d.ts +11 -0
- package/dist/runtime/render/starter.js +81 -0
- package/dist/runtime/seo/head.d.ts +87 -0
- package/dist/runtime/seo/head.js +224 -0
- package/dist/runtime/seo/structured-data.d.ts +22 -0
- package/dist/runtime/seo/structured-data.js +115 -0
- package/dist/runtime/shell/PageShell.d.ts +18 -0
- package/dist/runtime/shell/PageShell.js +113 -0
- package/dist/runtime/shell/RuntimeBridge.d.ts +14 -0
- package/dist/runtime/shell/RuntimeBridge.js +85 -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/index.d.ts +24 -0
- package/dist/sdk/index.js +24 -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 +135 -0
- package/dist/sdk/runtime-context.js +73 -0
- package/dist/sdk/schema.d.ts +197 -0
- package/dist/sdk/schema.js +121 -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 +27 -0
- package/dist/sdk/store-lookup.js +29 -0
- package/dist/sdk/store.d.ts +115 -0
- package/dist/sdk/store.js +1 -0
- package/dist/sdk/sx.d.ts +40 -0
- package/dist/sdk/sx.js +112 -0
- package/dist/sdk/theme.d.ts +152 -0
- package/dist/sdk/theme.js +10 -0
- package/dist/sdk/types.d.ts +470 -0
- package/dist/sdk/types.js +7 -0
- package/dist/server.d.ts +65 -0
- package/dist/server.js +370 -0
- package/docs/headless-api.md +220 -0
- package/package.json +77 -23
- 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/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
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Tanqory
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,17 +1,105 @@
|
|
|
1
|
-
# @tanqory/theme-kit
|
|
1
|
+
# @tanqory/theme-kit (v2, Theme ABI v2)
|
|
2
2
|
|
|
3
|
-
The
|
|
4
|
-
|
|
3
|
+
The platform layer a Tanqory theme is built on: the theme-authoring API, the runtime behind it
|
|
4
|
+
(store data plan over `ctx.data`, cart, SEO head and JSON-LD, localisation, live edit on the editor
|
|
5
|
+
canvas) and the two entry factories that turn a theme into a Theme ABI v2 artifact.
|
|
5
6
|
|
|
6
|
-
|
|
7
|
-
|
|
7
|
+
A theme supplies its sections, components and styles. Everything else comes from the kit, so a new
|
|
8
|
+
theme does not re-implement cart, variants, markets or live edit.
|
|
8
9
|
|
|
9
|
-
**
|
|
10
|
-
|
|
10
|
+
> **Alpha.** `2.0.0-alpha.*` carries the `alpha` dist-tag (`latest` is still the incompatible v1 kit, `0.x`).
|
|
11
|
+
> The `./runtime` surface may still move between pre-releases.
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
npm create tanqory-theme@latest my-theme # a complete theme on the kit (Blank or a Nova fork)
|
|
15
|
+
# or, in an existing theme:
|
|
16
|
+
npm install @tanqory/theme-kit@alpha react@18.3.1 react-dom@18.3.1
|
|
17
|
+
npm install --save-dev @tanqory/theme-abi@alpha
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
**Source.** Extracted, behaviour-identical, from the Nova V3 theme's platform layer. Nova V3 renders
|
|
21
|
+
byte-identical HTML on it (render diff over 58 fixture routes, en + th).
|
|
22
|
+
|
|
23
|
+
## Entry points
|
|
24
|
+
|
|
25
|
+
| Import | What it is |
|
|
26
|
+
|---|---|
|
|
27
|
+
| `@tanqory/theme-kit` | The authoring API: `defineTheme`, `defineSection`, `defineSchema`, `field.*`, `resolveSettings`, `useThemeContext`, `useThemeActions`, `useSearchSuggestions`, `useRewards`, `useReferrals`, `imageFor` / `menuFor` / `collectionFor` / `productFor`, `sx()`, and the data types (`Shop`, `Menu`, `MenuItem`, `Link`, `Image`, `Video`, `Localization`, `Market`, `CartSummary`, `Customer`, `Product`, `Collection`, `Cart`, …). The earlier `Nova*` type names are kept as `@deprecated` aliases. |
|
|
28
|
+
| `@tanqory/theme-kit/headless` | **The headless storefront API** (2.0.0-alpha.1): data hooks (`useProduct`, `useCollection`, `useCart`, `useSearch`, `useLocalization`, …), accessible commerce primitives with no styling (`<ProductForm>`, `<VariantPicker>`, `<AddToCart>`, `<CartDrawer>`, `<FacetFilters>`, `<SortSelect>`, `<LocalizationForm>`, `<NewsletterForm>`, `<ConsentBanner>`, …), `<Seo>`, `<Image>`, `t()`, `formatMoney`, `defineSection` / `defineBlock` / `defineTheme` and the `ai.*` roles. Reference: [docs/headless-api.md](docs/headless-api.md). |
|
|
29
|
+
| `@tanqory/theme-kit/build` | `buildManifest(...)`: the theme's ABI manifest (components, settings, routes, forms, capabilities with `data:shop`, `x-tanqory-ai`) from its declarations; `checkContent`, `withKitStrings`. Pure, for a theme's build script. |
|
|
30
|
+
| `@tanqory/theme-kit/server` | `createRender(options)` → the ABI `render(request, ctx)`. Every theme gets hreflang alternates (`<canonical>?locale=<lang>` per published language, plus `x-default`; 2.0.0-alpha.2, `hreflang: false` turns them off). `storefront: {}` turns on what the headless API needs (Breadcrumb/Collection JSON-LD, `<Seo>`, merchant strings, data-plan flags); absent, the render is otherwise the alpha.0 one. |
|
|
31
|
+
| `@tanqory/theme-kit/client` | `hydrate(options)`: the browser entry. Wires the editor canvas live edit (`tq:canvas` / `tq:canvas-live`) automatically in preview mode. |
|
|
32
|
+
| `@tanqory/theme-kit/runtime` | Low-level runtime pieces (providers, data plan, wire client, cart provider, converters, SEO helpers). For a theme's own tests and for custom entries. |
|
|
33
|
+
| `@tanqory/theme-kit/contract` | The content contract (page and section-group documents, roles, validation, transforms). Pure, loads in Node. |
|
|
34
|
+
|
|
35
|
+
## Headless themes
|
|
36
|
+
|
|
37
|
+
A theme written against `@tanqory/theme-kit/headless` owns all its markup and CSS and gets every storefront
|
|
38
|
+
function from the kit: variants and `?variant=`, add to cart and the cart drawer, cart lines and checkout
|
|
39
|
+
hand-off, sort / filter / paging, predictive search, market and language, consent, platform forms, account
|
|
40
|
+
slot, SEO and JSON-LD, th/en strings with merchant overrides, live edit on the editor canvas, and the AI-compat
|
|
41
|
+
profile. The primitives render semantic HTML with the `tq-storefront-hooks/1` attributes and accept
|
|
42
|
+
`className` and render-prop children. See [docs/headless-api.md](docs/headless-api.md) and the complete example
|
|
43
|
+
theme Aurora (in the kit's source repository, not part of the published package; `npm create tanqory-theme` gives you an equivalent Blank starter).
|
|
44
|
+
|
|
45
|
+
## Using it
|
|
46
|
+
|
|
47
|
+
```tsx
|
|
48
|
+
// entry.abi.tsx: the server entry, built into ONE file with no imports
|
|
49
|
+
import type { ThemeManifest } from '@tanqory/theme-abi'
|
|
50
|
+
import { createRender } from '@tanqory/theme-kit/server'
|
|
51
|
+
import { bundle } from './lib/bundle'
|
|
52
|
+
import manifestJson from './lib/abi/generated/manifest.json'
|
|
53
|
+
|
|
54
|
+
export const manifest = manifestJson as unknown as ThemeManifest
|
|
55
|
+
export const render = createRender({ manifest, bundle })
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
```tsx
|
|
59
|
+
// main.abi.tsx: the browser entry
|
|
60
|
+
import { hydrate } from '@tanqory/theme-kit/client'
|
|
61
|
+
import { bundle } from './lib/bundle'
|
|
62
|
+
|
|
63
|
+
hydrate({ bundle })
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
`bundle` is the theme's `ThemeBundle`: its `defineTheme(...)` definition, `templates/*.json`,
|
|
67
|
+
`groups/*.json`, `locales/*.json`, settings and settings schema. The not-found section shown for an
|
|
68
|
+
unknown product, collection, page or blog comes from the bundle's `templates/404.json`.
|
|
69
|
+
|
|
70
|
+
Optional hooks (all default to "unchanged"):
|
|
71
|
+
|
|
72
|
+
| Hook | Where | Runs |
|
|
73
|
+
|---|---|---|
|
|
74
|
+
| `effectiveSettings(settings)` | `createRender` | first: manifest defaults + the store's values → what the theme renders (and hydrates) with |
|
|
75
|
+
| `transformNodes(nodes, settings)` | `createRender` and `hydrate` (pass the same function to both) | on the page's section nodes before render, server and browser |
|
|
76
|
+
| `shopSettings(settings, shop)` | `createRender` | once the store's shop record is loaded |
|
|
77
|
+
|
|
78
|
+
## What the compiled output guarantees
|
|
79
|
+
|
|
80
|
+
`pnpm build` runs `tsc` and then `scripts/check-dist.mjs`, which fails the build unless:
|
|
81
|
+
|
|
82
|
+
- every relative import names an existing `.js` file (Node ESM and the platform build sandbox resolve it as written);
|
|
83
|
+
- there is no dynamic `import()` and no `import.meta.glob`, so the theme's server entry stays one file with no imports;
|
|
84
|
+
- there are no `node:` / Node built-in imports and no CSS imports in runtime code;
|
|
85
|
+
- the only bare imports are the peer dependencies (`react`, `react-dom`, `@tanqory/theme-abi`).
|
|
86
|
+
|
|
87
|
+
The runtime reads `import.meta.env` (`DEV`, and the optional `VITE_TANQORY_*` build variables), as
|
|
88
|
+
every theme bundler on the platform defines it. Under Vitest, list the kit in
|
|
89
|
+
`test.server.deps.inline` so it is transformed like the theme's own source.
|
|
90
|
+
|
|
91
|
+
## Layout
|
|
11
92
|
|
|
12
93
|
```
|
|
13
94
|
src/
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
95
|
+
index.ts @tanqory/theme-kit (= sdk/ + ThemeBundle, ContentNode)
|
|
96
|
+
server.tsx @tanqory/theme-kit/server createRender()
|
|
97
|
+
client.tsx @tanqory/theme-kit/client hydrate()
|
|
98
|
+
runtime.ts @tanqory/theme-kit/runtime
|
|
99
|
+
contract.ts @tanqory/theme-kit/contract
|
|
100
|
+
sdk/ the authoring API: schema, theme, runtime context, data types, sx
|
|
101
|
+
runtime/ rendering: section tree, store data layer, cart, SEO head, render helpers, content contract
|
|
102
|
+
abi/ the ABI v2 layer: data plan over ctx.data, data API, wire client, cart, loyalty, live edit
|
|
103
|
+
test/ vitest
|
|
104
|
+
scripts/ check-dist.mjs, check-release-integrity.mjs
|
|
17
105
|
```
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Live section edits on the editor canvas (a PREVIEW render only — `ctx.mode === 'preview'`).
|
|
3
|
+
*
|
|
4
|
+
* The platform gateway injects its editor bridge into every preview page.
|
|
5
|
+
* The bridge checks the editor's origin and hands each content message to the page as a `tq:canvas` DOM event; this
|
|
6
|
+
* module applies those messages to the section nodes the page rendered, so a setting edit re-renders its section at
|
|
7
|
+
* once instead of waiting for a save and a reload. The bridge also does selection, scrolling and click-to-select; the
|
|
8
|
+
* theme does none of that here.
|
|
9
|
+
*
|
|
10
|
+
* tanqory-preview-update-section {sectionId, settings, blocks?, order?} that section's settings (and blocks)
|
|
11
|
+
* tq:set-content {doc: ContentNode[]} the editor's tree: every node it names
|
|
12
|
+
* that is on this page takes its settings
|
|
13
|
+
*
|
|
14
|
+
* Structure (add / remove / reorder) is NOT applied here: the editor reloads the canvas for those, from the saved
|
|
15
|
+
* workspace. A node the editor names that this page does not render is ignored, never inserted.
|
|
16
|
+
*
|
|
17
|
+
* Pure (no DOM, no React): the store is the boundary — main.abi.tsx subscribes React to it and wires the window
|
|
18
|
+
* events. Unit-tested in lib/abi/canvas-live.test.ts.
|
|
19
|
+
*/
|
|
20
|
+
import type { ContentNode } from '../runtime/kit/types.js';
|
|
21
|
+
export declare const CANVAS_EVENT = "tq:canvas";
|
|
22
|
+
export declare const CANVAS_LIVE_EVENT = "tq:canvas-live";
|
|
23
|
+
export declare const CANVAS_BRIDGE_EVENT = "tq:canvas-bridge";
|
|
24
|
+
/** The message types this theme applies live (announced to the bridge, which tells the editor). */
|
|
25
|
+
export declare const LIVE_TYPES: readonly string[];
|
|
26
|
+
/** The editor's block shapes → an array: an id-keyed map with an `order`, or already an array. */
|
|
27
|
+
export declare function blocksOf(raw: unknown, order: unknown): ContentNode[] | undefined;
|
|
28
|
+
/**
|
|
29
|
+
* The nodes after one canvas message. Returns the SAME array when the message changes nothing on this page (an
|
|
30
|
+
* unknown type, a section that is not here), so React does not re-render for it.
|
|
31
|
+
*/
|
|
32
|
+
export declare function applyCanvasMessage(nodes: ContentNode[], msg: unknown): ContentNode[];
|
|
33
|
+
export interface CanvasStore {
|
|
34
|
+
get(): ContentNode[];
|
|
35
|
+
subscribe(listener: () => void): () => void;
|
|
36
|
+
apply(msg: unknown): void;
|
|
37
|
+
}
|
|
38
|
+
/** The page's section nodes as a small external store (React subscribes with useSyncExternalStore). */
|
|
39
|
+
export declare function createCanvasStore(initial: ContentNode[]): CanvasStore;
|
|
40
|
+
interface EventWindow {
|
|
41
|
+
addEventListener(type: string, listener: (e: Event) => void): void;
|
|
42
|
+
dispatchEvent(e: Event): boolean;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Connects the store to the bridge: every `tq:canvas` event is applied, and the theme announces what it applies —
|
|
46
|
+
* now, and again whenever a bridge says it started (it may load after this script).
|
|
47
|
+
*/
|
|
48
|
+
export declare function connectCanvas(win: EventWindow, store: CanvasStore, makeEvent: (type: string, detail?: unknown) => Event): void;
|
|
49
|
+
export {};
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
export const CANVAS_EVENT = 'tq:canvas';
|
|
2
|
+
export const CANVAS_LIVE_EVENT = 'tq:canvas-live';
|
|
3
|
+
export const CANVAS_BRIDGE_EVENT = 'tq:canvas-bridge';
|
|
4
|
+
/** The message types this theme applies live (announced to the bridge, which tells the editor). */
|
|
5
|
+
export const LIVE_TYPES = ['tanqory-preview-update-section', 'tq:set-content'];
|
|
6
|
+
const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
7
|
+
/** The editor's block shapes → an array: an id-keyed map with an `order`, or already an array. */
|
|
8
|
+
export function blocksOf(raw, order) {
|
|
9
|
+
if (Array.isArray(raw))
|
|
10
|
+
return raw.filter((b) => isObj(b) && typeof b.type === 'string');
|
|
11
|
+
if (!isObj(raw))
|
|
12
|
+
return undefined;
|
|
13
|
+
const ids = Array.isArray(order) && order.length ? order.filter((x) => typeof x === 'string') : Object.keys(raw);
|
|
14
|
+
const out = [];
|
|
15
|
+
for (const id of ids) {
|
|
16
|
+
const b = raw[id];
|
|
17
|
+
if (!isObj(b) || typeof b.type !== 'string')
|
|
18
|
+
continue;
|
|
19
|
+
out.push({ ...b, id: typeof b.id === 'string' ? b.id : id });
|
|
20
|
+
}
|
|
21
|
+
return out;
|
|
22
|
+
}
|
|
23
|
+
function patched(node, settings, blocks) {
|
|
24
|
+
return {
|
|
25
|
+
...node,
|
|
26
|
+
settings: { ...(node.settings ?? {}), ...(isObj(settings) ? settings : {}) },
|
|
27
|
+
...(blocks ? { blocks } : {}),
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* The nodes after one canvas message. Returns the SAME array when the message changes nothing on this page (an
|
|
32
|
+
* unknown type, a section that is not here), so React does not re-render for it.
|
|
33
|
+
*/
|
|
34
|
+
export function applyCanvasMessage(nodes, msg) {
|
|
35
|
+
if (!isObj(msg))
|
|
36
|
+
return nodes;
|
|
37
|
+
if (msg.type === 'tanqory-preview-update-section') {
|
|
38
|
+
const id = msg.sectionId;
|
|
39
|
+
if (typeof id !== 'string' || !nodes.some((n) => n.id === id))
|
|
40
|
+
return nodes;
|
|
41
|
+
const blocks = blocksOf(msg.blocks, msg.order);
|
|
42
|
+
return nodes.map((n) => (n.id === id ? patched(n, msg.settings, blocks) : n));
|
|
43
|
+
}
|
|
44
|
+
if (msg.type === 'tq:set-content' && Array.isArray(msg.doc)) {
|
|
45
|
+
const byId = new Map();
|
|
46
|
+
for (const d of msg.doc)
|
|
47
|
+
if (isObj(d) && typeof d.id === 'string')
|
|
48
|
+
byId.set(d.id, d);
|
|
49
|
+
if (!nodes.some((n) => n.id !== undefined && byId.has(n.id)))
|
|
50
|
+
return nodes;
|
|
51
|
+
return nodes.map((n) => {
|
|
52
|
+
const d = n.id !== undefined ? byId.get(n.id) : undefined;
|
|
53
|
+
// a node whose TYPE changed is structure, not a setting: leave it for the reload
|
|
54
|
+
return d && d.type === n.type ? patched(n, d.settings, blocksOf(d.blocks, d.order)) : n;
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
return nodes;
|
|
58
|
+
}
|
|
59
|
+
/** The page's section nodes as a small external store (React subscribes with useSyncExternalStore). */
|
|
60
|
+
export function createCanvasStore(initial) {
|
|
61
|
+
let nodes = initial;
|
|
62
|
+
const listeners = new Set();
|
|
63
|
+
return {
|
|
64
|
+
get: () => nodes,
|
|
65
|
+
subscribe(l) {
|
|
66
|
+
listeners.add(l);
|
|
67
|
+
return () => listeners.delete(l);
|
|
68
|
+
},
|
|
69
|
+
apply(msg) {
|
|
70
|
+
const next = applyCanvasMessage(nodes, msg);
|
|
71
|
+
if (next === nodes)
|
|
72
|
+
return;
|
|
73
|
+
nodes = next;
|
|
74
|
+
for (const l of listeners)
|
|
75
|
+
l();
|
|
76
|
+
},
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Connects the store to the bridge: every `tq:canvas` event is applied, and the theme announces what it applies —
|
|
81
|
+
* now, and again whenever a bridge says it started (it may load after this script).
|
|
82
|
+
*/
|
|
83
|
+
export function connectCanvas(win, store, makeEvent) {
|
|
84
|
+
const announce = () => win.dispatchEvent(makeEvent(CANVAS_LIVE_EVENT, { types: [...LIVE_TYPES] }));
|
|
85
|
+
win.addEventListener(CANVAS_EVENT, (e) => store.apply(e.detail));
|
|
86
|
+
win.addEventListener(CANVAS_BRIDGE_EVENT, announce);
|
|
87
|
+
announce();
|
|
88
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The cart over Theme ABI v2 (theme-abi-v2.md §4): the same `useCart()` every section already uses,
|
|
3
|
+
* driven by `POST /_tq/actions/cart.*` and `GET /_tq/data/cart.get` instead of a GraphQL endpoint
|
|
4
|
+
* (wire envelope: lib/abi/wire.ts).
|
|
5
|
+
*
|
|
6
|
+
* - Identity is the platform's cart cookie — invisible to the theme. There is no cart id in
|
|
7
|
+
* localStorage any more; `cart.get` answers for the current shopper.
|
|
8
|
+
* - Every mutation carries the cart `version`; a stale version answers `cart_version_conflict`
|
|
9
|
+
* with the current cart, which is applied and the mutation retried once.
|
|
10
|
+
* - Server render never mutates (§4 A3): on the server `remote` is null, the cart route renders
|
|
11
|
+
* the cart the platform resolved (`snapshot().resource.cart`) and every other page renders the
|
|
12
|
+
* empty cart until the browser has asked for it.
|
|
13
|
+
* - A first `cart.get` that FAILS is not an empty cart (QA test-2 F1: a 429 showed "Your cart is
|
|
14
|
+
* empty" over a cart holding a line). `ready` stays false, `loadError` records the code, and the
|
|
15
|
+
* load is retried after the server's `Retry-After` (else exponential backoff). Surfaces show
|
|
16
|
+
* "Couldn't load your cart — retrying". An add before the cart has loaded reads it first; it
|
|
17
|
+
* never `cart.create`s over a cart it could not see.
|
|
18
|
+
*
|
|
19
|
+
* A refused write may say why (theme-abi Cart-1, alpha.13): `refusal` on the `invalid` CartResult,
|
|
20
|
+
* or `error.refusal` when `cart.create` is refused. It is kept for `lastRefusal()`, so the surface
|
|
21
|
+
* that made the write can word it ("You can buy up to 5 of this item").
|
|
22
|
+
*
|
|
23
|
+
* Not in the ABI cart, so not offered: gift-card codes and cart-level attributes after creation.
|
|
24
|
+
* Those methods resolve and set `error`, never pretend to succeed (MISMATCHES.md).
|
|
25
|
+
*/
|
|
26
|
+
import { type ReactNode } from 'react';
|
|
27
|
+
import type { Cart as AbiCart } from '@tanqory/theme-abi';
|
|
28
|
+
import { type CartRefusal } from '../runtime/kit/cart.js';
|
|
29
|
+
import { type AbiRemote } from './wire.js';
|
|
30
|
+
/**
|
|
31
|
+
* The refusal the platform sent with a refused write (theme-abi Cart-1), or null. Only a code this
|
|
32
|
+
* theme knows counts; `maxQuantity` only when it is a whole number of at least 1.
|
|
33
|
+
*/
|
|
34
|
+
export declare function refusalOf(raw: unknown): CartRefusal | null;
|
|
35
|
+
/** The wire code of a failed request, for `loadError` / `error`. */
|
|
36
|
+
export declare function wireCode(e: unknown): string;
|
|
37
|
+
/**
|
|
38
|
+
* When to try `cart.get` again after failure number `attempt` (0-based), or null when another try
|
|
39
|
+
* cannot help. The server's Retry-After wins; a 4xx that is not about timing (403
|
|
40
|
+
* capability_denied, 400 …) is final; everything else (network, 5xx, 429 without the header)
|
|
41
|
+
* backs off 1 s, 2 s, 4 s … up to 30 s.
|
|
42
|
+
*/
|
|
43
|
+
export declare function retryDelay(e: unknown, attempt: number): number | null;
|
|
44
|
+
export declare function AbiCartProvider({ initial, remote, children }: {
|
|
45
|
+
initial: AbiCart | null;
|
|
46
|
+
remote: AbiRemote | null;
|
|
47
|
+
children: ReactNode;
|
|
48
|
+
}): JSX.Element;
|
package/dist/abi/cart.js
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
/**
|
|
3
|
+
* The cart over Theme ABI v2 (theme-abi-v2.md §4): the same `useCart()` every section already uses,
|
|
4
|
+
* driven by `POST /_tq/actions/cart.*` and `GET /_tq/data/cart.get` instead of a GraphQL endpoint
|
|
5
|
+
* (wire envelope: lib/abi/wire.ts).
|
|
6
|
+
*
|
|
7
|
+
* - Identity is the platform's cart cookie — invisible to the theme. There is no cart id in
|
|
8
|
+
* localStorage any more; `cart.get` answers for the current shopper.
|
|
9
|
+
* - Every mutation carries the cart `version`; a stale version answers `cart_version_conflict`
|
|
10
|
+
* with the current cart, which is applied and the mutation retried once.
|
|
11
|
+
* - Server render never mutates (§4 A3): on the server `remote` is null, the cart route renders
|
|
12
|
+
* the cart the platform resolved (`snapshot().resource.cart`) and every other page renders the
|
|
13
|
+
* empty cart until the browser has asked for it.
|
|
14
|
+
* - A first `cart.get` that FAILS is not an empty cart (QA test-2 F1: a 429 showed "Your cart is
|
|
15
|
+
* empty" over a cart holding a line). `ready` stays false, `loadError` records the code, and the
|
|
16
|
+
* load is retried after the server's `Retry-After` (else exponential backoff). Surfaces show
|
|
17
|
+
* "Couldn't load your cart — retrying". An add before the cart has loaded reads it first; it
|
|
18
|
+
* never `cart.create`s over a cart it could not see.
|
|
19
|
+
*
|
|
20
|
+
* A refused write may say why (theme-abi Cart-1, alpha.13): `refusal` on the `invalid` CartResult,
|
|
21
|
+
* or `error.refusal` when `cart.create` is refused. It is kept for `lastRefusal()`, so the surface
|
|
22
|
+
* that made the write can word it ("You can buy up to 5 of this item").
|
|
23
|
+
*
|
|
24
|
+
* Not in the ABI cart, so not offered: gift-card codes and cart-level attributes after creation.
|
|
25
|
+
* Those methods resolve and set `error`, never pretend to succeed (MISMATCHES.md).
|
|
26
|
+
*/
|
|
27
|
+
import { useCallback, useEffect, useRef, useState } from 'react';
|
|
28
|
+
import { CartContext } from '../runtime/kit/cart.js';
|
|
29
|
+
import { cartState } from './convert.js';
|
|
30
|
+
import { AbiWireError } from './wire.js';
|
|
31
|
+
const ZERO = { amount: '0.00', currencyCode: 'USD' };
|
|
32
|
+
function stateOf(c, ready) {
|
|
33
|
+
if (!c) {
|
|
34
|
+
return { id: null, lines: [], subtotal: ZERO, total: ZERO, totalQuantity: 0, checkoutUrl: null, discountCodes: [], discountAmount: null, appliedGiftCards: [], loading: false, ready, error: null };
|
|
35
|
+
}
|
|
36
|
+
// `discountAmount` is the cart-level amount off, derived from the cart's own totals (convert.ts).
|
|
37
|
+
const s = cartState(c);
|
|
38
|
+
return { ...s, appliedGiftCards: [], loading: false, ready, error: null };
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* The refusal the platform sent with a refused write (theme-abi Cart-1), or null. Only a code this
|
|
42
|
+
* theme knows counts; `maxQuantity` only when it is a whole number of at least 1.
|
|
43
|
+
*/
|
|
44
|
+
export function refusalOf(raw) {
|
|
45
|
+
if (typeof raw !== 'object' || raw === null || raw.code !== 'cart_limit_exceeded')
|
|
46
|
+
return null;
|
|
47
|
+
const max = raw.maxQuantity;
|
|
48
|
+
return typeof max === 'number' && Number.isSafeInteger(max) && max >= 1 ? { code: 'cart_limit_exceeded', maxQuantity: max } : { code: 'cart_limit_exceeded' };
|
|
49
|
+
}
|
|
50
|
+
/** Discount codes compare case-insensitively (store-api stores them upper-cased). */
|
|
51
|
+
const sameCode = (a, b) => a.localeCompare(b, undefined, { sensitivity: 'accent' }) === 0;
|
|
52
|
+
const UNSUPPORTED = 'unsupported';
|
|
53
|
+
const MAX_RETRY_MS = 5 * 60_000;
|
|
54
|
+
const MAX_BACKOFF_MS = 30_000;
|
|
55
|
+
/** The wire code of a failed request, for `loadError` / `error`. */
|
|
56
|
+
export function wireCode(e) {
|
|
57
|
+
if (e instanceof AbiWireError)
|
|
58
|
+
return e.code ?? `http_${e.status}`;
|
|
59
|
+
return 'network_error';
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* When to try `cart.get` again after failure number `attempt` (0-based), or null when another try
|
|
63
|
+
* cannot help. The server's Retry-After wins; a 4xx that is not about timing (403
|
|
64
|
+
* capability_denied, 400 …) is final; everything else (network, 5xx, 429 without the header)
|
|
65
|
+
* backs off 1 s, 2 s, 4 s … up to 30 s.
|
|
66
|
+
*/
|
|
67
|
+
export function retryDelay(e, attempt) {
|
|
68
|
+
if (e instanceof AbiWireError) {
|
|
69
|
+
if (e.retryAfterMs !== null)
|
|
70
|
+
return Math.min(Math.max(e.retryAfterMs, 1000), MAX_RETRY_MS);
|
|
71
|
+
if (e.status >= 400 && e.status < 500 && e.status !== 408 && e.status !== 425 && e.status !== 429)
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
return Math.min(1000 * 2 ** attempt, MAX_BACKOFF_MS);
|
|
75
|
+
}
|
|
76
|
+
export function AbiCartProvider({ initial, remote, children }) {
|
|
77
|
+
const [state, setState] = useState(() => stateOf(initial, initial !== null));
|
|
78
|
+
const cartRef = useRef(initial);
|
|
79
|
+
/** True once the shopper's cart is known (server-resolved, or a `cart.get` answered). */
|
|
80
|
+
const loadedRef = useRef(initial !== null);
|
|
81
|
+
const inFlight = useRef(null);
|
|
82
|
+
/** Why the latest write was refused, when the platform said (Cart-1). */
|
|
83
|
+
const refusalRef = useRef(null);
|
|
84
|
+
const lastRefusal = useCallback(() => refusalRef.current, []);
|
|
85
|
+
/** The wire code of the latest failed write (`invalid` = the store refused it), else null. */
|
|
86
|
+
const failRef = useRef(null);
|
|
87
|
+
const apply = useCallback((c) => {
|
|
88
|
+
cartRef.current = c;
|
|
89
|
+
loadedRef.current = true;
|
|
90
|
+
setState(stateOf(c, true));
|
|
91
|
+
}, []);
|
|
92
|
+
const fail = useCallback((message) => setState((s) => ({ ...s, loading: false, error: message })), []);
|
|
93
|
+
const failState = fail;
|
|
94
|
+
useEffect(() => {
|
|
95
|
+
if (!remote || loadedRef.current)
|
|
96
|
+
return;
|
|
97
|
+
let cancelled = false;
|
|
98
|
+
let timer;
|
|
99
|
+
let attempt = 0;
|
|
100
|
+
const load = () => {
|
|
101
|
+
// A mutation may have loaded the cart while this attempt was waiting.
|
|
102
|
+
if (cancelled || loadedRef.current)
|
|
103
|
+
return;
|
|
104
|
+
remote
|
|
105
|
+
.data('cart.get', [])
|
|
106
|
+
.then((c) => { if (!cancelled && !loadedRef.current)
|
|
107
|
+
apply(c ?? null); })
|
|
108
|
+
.catch((e) => {
|
|
109
|
+
if (cancelled || loadedRef.current)
|
|
110
|
+
return;
|
|
111
|
+
const delay = retryDelay(e, attempt++);
|
|
112
|
+
// Not ready, not empty: the surfaces say the cart could not be loaded.
|
|
113
|
+
setState((s) => ({ ...s, ready: false, loadError: wireCode(e), loadRetrying: delay !== null }));
|
|
114
|
+
if (delay !== null)
|
|
115
|
+
timer = setTimeout(load, delay);
|
|
116
|
+
});
|
|
117
|
+
};
|
|
118
|
+
load();
|
|
119
|
+
return () => {
|
|
120
|
+
cancelled = true;
|
|
121
|
+
if (timer !== undefined)
|
|
122
|
+
clearTimeout(timer);
|
|
123
|
+
};
|
|
124
|
+
}, [remote, apply]);
|
|
125
|
+
/** Run one versioned mutation; on a version conflict apply the current cart and retry once. */
|
|
126
|
+
const mutate = useCallback(async (name, args) => {
|
|
127
|
+
if (!remote)
|
|
128
|
+
return false;
|
|
129
|
+
const fail = (code) => {
|
|
130
|
+
failRef.current = code;
|
|
131
|
+
failState(code);
|
|
132
|
+
};
|
|
133
|
+
const run = async () => {
|
|
134
|
+
failRef.current = null;
|
|
135
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
136
|
+
refusalRef.current = null;
|
|
137
|
+
const version = cartRef.current?.version ?? 0;
|
|
138
|
+
const env = await remote.action(name, args(version));
|
|
139
|
+
// ok ⇒ `data` is the CartResult; a stale version ⇒ error.code cart_version_conflict with the
|
|
140
|
+
// current cart in `data` (§4 wire envelope).
|
|
141
|
+
if (env.ok) {
|
|
142
|
+
const r = env.data;
|
|
143
|
+
if (r.ok) {
|
|
144
|
+
apply(r.cart);
|
|
145
|
+
return true;
|
|
146
|
+
}
|
|
147
|
+
if (r.reason === 'cart_version_conflict') {
|
|
148
|
+
apply(r.cart);
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
if (r.reason === 'invalid')
|
|
152
|
+
refusalRef.current = refusalOf(r.refusal);
|
|
153
|
+
fail(r.reason);
|
|
154
|
+
return false;
|
|
155
|
+
}
|
|
156
|
+
if (env.error.code === 'cart_version_conflict' && env.data) {
|
|
157
|
+
apply(env.data);
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
refusalRef.current = refusalOf(env.error.refusal);
|
|
161
|
+
fail(env.error.code);
|
|
162
|
+
return false;
|
|
163
|
+
}
|
|
164
|
+
fail('cart_version_conflict');
|
|
165
|
+
return false;
|
|
166
|
+
};
|
|
167
|
+
setState((s) => ({ ...s, loading: true }));
|
|
168
|
+
// Mutations are serialised: two quick taps must not race on the same version.
|
|
169
|
+
const prev = inFlight.current ?? Promise.resolve();
|
|
170
|
+
const next = prev.catch(() => undefined).then(run);
|
|
171
|
+
inFlight.current = next;
|
|
172
|
+
try {
|
|
173
|
+
return await next;
|
|
174
|
+
}
|
|
175
|
+
catch (e) {
|
|
176
|
+
fail(e.message);
|
|
177
|
+
return false;
|
|
178
|
+
}
|
|
179
|
+
}, [remote, apply, failState]);
|
|
180
|
+
const add = useCallback(async (input) => {
|
|
181
|
+
const quantity = input.quantity ?? 1;
|
|
182
|
+
refusalRef.current = null;
|
|
183
|
+
if (quantity < 1 || !remote)
|
|
184
|
+
return false;
|
|
185
|
+
const attributes = Object.fromEntries((input.attributes ?? []).filter((a) => a.value.trim() !== '').map((a) => [a.key, a.value]));
|
|
186
|
+
const line = { merchandiseId: input.variantId, quantity, ...(Object.keys(attributes).length ? { attributes } : {}) };
|
|
187
|
+
if (!cartRef.current && !loadedRef.current) {
|
|
188
|
+
// The shopper may already hold a cart we have not read (first load pending or failed):
|
|
189
|
+
// read it now, and never create a second cart over one we could not see.
|
|
190
|
+
setState((s) => ({ ...s, loading: true }));
|
|
191
|
+
try {
|
|
192
|
+
apply((await remote.data('cart.get', [])) ?? null);
|
|
193
|
+
}
|
|
194
|
+
catch (e) {
|
|
195
|
+
fail(wireCode(e));
|
|
196
|
+
return false;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
if (!cartRef.current) {
|
|
200
|
+
setState((s) => ({ ...s, loading: true }));
|
|
201
|
+
try {
|
|
202
|
+
const env = await remote.action('cart.create', [{ lines: [line] }]);
|
|
203
|
+
if (!env.ok) {
|
|
204
|
+
refusalRef.current = refusalOf(env.error.refusal);
|
|
205
|
+
fail(env.error.code);
|
|
206
|
+
return false;
|
|
207
|
+
}
|
|
208
|
+
apply(env.data);
|
|
209
|
+
return true;
|
|
210
|
+
}
|
|
211
|
+
catch (e) {
|
|
212
|
+
fail(e.message);
|
|
213
|
+
return false;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
return mutate('cart.addLines', (v) => [[line], v]);
|
|
217
|
+
}, [remote, apply, fail, mutate]);
|
|
218
|
+
const updateQuantity = useCallback(async (lineId, quantity) => {
|
|
219
|
+
if (quantity <= 0)
|
|
220
|
+
await mutate('cart.removeLines', (v) => [[lineId], v]);
|
|
221
|
+
else
|
|
222
|
+
await mutate('cart.updateLines', (v) => [[{ id: lineId, quantity }], v]);
|
|
223
|
+
}, [mutate]);
|
|
224
|
+
const remove = useCallback(async (lineId) => { await mutate('cart.removeLines', (v) => [[lineId], v]); }, [mutate]);
|
|
225
|
+
const clear = useCallback(async () => {
|
|
226
|
+
const ids = cartRef.current?.lines.map((l) => l.id) ?? [];
|
|
227
|
+
if (ids.length)
|
|
228
|
+
await mutate('cart.removeLines', (v) => [ids, v]);
|
|
229
|
+
}, [mutate]);
|
|
230
|
+
const applyDiscountCodes = useCallback(async (codes) => {
|
|
231
|
+
const current = cartRef.current?.discountCodes.map((d) => d.code) ?? [];
|
|
232
|
+
for (const code of current.filter((c) => !codes.includes(c)))
|
|
233
|
+
if (!(await mutate('cart.removeDiscountCode', (v) => [code, v])))
|
|
234
|
+
return;
|
|
235
|
+
for (const code of codes.filter((c) => !current.includes(c)))
|
|
236
|
+
if (!(await mutate('cart.applyDiscountCode', (v) => [code, v])))
|
|
237
|
+
return;
|
|
238
|
+
}, [mutate]);
|
|
239
|
+
/**
|
|
240
|
+
* One code on the cart (store-api holds one: `cartUpdateDiscountCodes` reads `codes[0]`, and the gateway's
|
|
241
|
+
* `cart.applyDiscountCode` sends the current codes first), so a new code first takes the old one off. A code the store
|
|
242
|
+
* keeps as not applicable is taken off again and the old code put back, so checkout never receives a code the
|
|
243
|
+
* shopper was told did not work. A gateway that answers that refusal as `invalid` (it drops the cart store-api sent
|
|
244
|
+
* with `DISCOUNT_INAPPLICABLE`) is read back with `cart.get`.
|
|
245
|
+
*/
|
|
246
|
+
const applyDiscountCode = useCallback(async (raw) => {
|
|
247
|
+
const code = raw.trim();
|
|
248
|
+
if (!code || code.length > 255 || !remote)
|
|
249
|
+
return code ? 'failed' : 'not_applicable';
|
|
250
|
+
const held = () => cartRef.current?.discountCodes ?? [];
|
|
251
|
+
const find = (c) => held().find((d) => sameCode(d.code, c));
|
|
252
|
+
if (find(code)?.applicable)
|
|
253
|
+
return 'applied';
|
|
254
|
+
const previous = held().find((d) => d.applicable)?.code ?? null;
|
|
255
|
+
for (const d of held())
|
|
256
|
+
if (!sameCode(d.code, code) && !(await mutate('cart.removeDiscountCode', (v) => [d.code, v])))
|
|
257
|
+
return 'failed';
|
|
258
|
+
const putBack = async () => {
|
|
259
|
+
if (previous && !find(previous))
|
|
260
|
+
await mutate('cart.applyDiscountCode', (v) => [previous, v]);
|
|
261
|
+
};
|
|
262
|
+
if (!(await mutate('cart.applyDiscountCode', (v) => [code, v]))) {
|
|
263
|
+
const refused = failRef.current === 'invalid';
|
|
264
|
+
try {
|
|
265
|
+
apply((await remote.data('cart.get', [])) ?? null);
|
|
266
|
+
}
|
|
267
|
+
catch {
|
|
268
|
+
/* keep what we have */
|
|
269
|
+
}
|
|
270
|
+
if (!find(code)) {
|
|
271
|
+
if (refused)
|
|
272
|
+
await putBack();
|
|
273
|
+
return refused ? 'not_applicable' : 'failed';
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
const hit = find(code);
|
|
277
|
+
if (!hit)
|
|
278
|
+
return 'failed';
|
|
279
|
+
if (hit.applicable)
|
|
280
|
+
return 'applied';
|
|
281
|
+
await mutate('cart.removeDiscountCode', (v) => [hit.code, v]);
|
|
282
|
+
await putBack();
|
|
283
|
+
return 'not_applicable';
|
|
284
|
+
}, [remote, mutate, apply]);
|
|
285
|
+
const removeDiscountCode = useCallback(async (raw) => {
|
|
286
|
+
const code = raw.trim();
|
|
287
|
+
const hit = cartRef.current?.discountCodes.find((d) => sameCode(d.code, code));
|
|
288
|
+
if (!hit)
|
|
289
|
+
return true;
|
|
290
|
+
return mutate('cart.removeDiscountCode', (v) => [hit.code, v]);
|
|
291
|
+
}, [mutate]);
|
|
292
|
+
const updateNote = useCallback(async (note) => { await mutate('cart.updateNote', (v) => [note, v]); }, [mutate]);
|
|
293
|
+
const unsupported = useCallback(async () => fail(UNSUPPORTED), [fail]);
|
|
294
|
+
const reload = useCallback(async () => {
|
|
295
|
+
if (!remote)
|
|
296
|
+
return;
|
|
297
|
+
try {
|
|
298
|
+
apply((await remote.data('cart.get', [])) ?? null);
|
|
299
|
+
}
|
|
300
|
+
catch {
|
|
301
|
+
/* keep the cart on screen; the next mutation re-syncs it */
|
|
302
|
+
}
|
|
303
|
+
}, [remote, apply]);
|
|
304
|
+
const value = {
|
|
305
|
+
...state,
|
|
306
|
+
add,
|
|
307
|
+
updateQuantity,
|
|
308
|
+
remove,
|
|
309
|
+
clear,
|
|
310
|
+
applyDiscountCodes,
|
|
311
|
+
applyGiftCardCodes: unsupported,
|
|
312
|
+
removeGiftCards: unsupported,
|
|
313
|
+
updateNote,
|
|
314
|
+
updateAttributes: unsupported,
|
|
315
|
+
reload,
|
|
316
|
+
lastRefusal,
|
|
317
|
+
applyDiscountCode,
|
|
318
|
+
removeDiscountCode,
|
|
319
|
+
};
|
|
320
|
+
return _jsx(CartContext.Provider, { value: value, children: children });
|
|
321
|
+
}
|