@usequeek/theme-kit 0.1.29 → 0.1.31

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/README.md CHANGED
@@ -131,6 +131,7 @@ they keep the data already on screen. They return `isLoading`, except
131
131
  | `useReviews(block)` | `hooks/use-reviews` | Reviews and the rating summary |
132
132
  | `useProductQuestions(block)` | `hooks/use-product-questions` | Product questions and answers |
133
133
  | `useCart()` / `useShopCart(shopId)` | `hooks/use-cart`, `hooks/use-shop-cart` | The cart and its actions; one shop's lines and totals |
134
+ | `useAddAppBlockLines(shopId)` | `hooks/use-add-app-block-lines` | Adds the products of an add-to-cart app block: `{ addLines, pending }` |
134
135
  | `useAuth()` | `hooks/use-auth` | The signed-in customer and sign-in modal controls |
135
136
  | `useVariantSelection(product)` | `hooks/use-variant-selection` | Option selection state and the add-to-cart gate |
136
137
  | `useSearch(query, products, collections)` | `hooks/use-search` | Instant search over data you hold |
@@ -139,6 +140,87 @@ they keep the data already on screen. They return `isLoading`, except
139
140
  | `useLocales()` | `hooks/use-locales` | The store's languages and the active one |
140
141
  | `useStorefront()` / `useStorefrontLocale()` / `useThemeStrings()` | `provider` | The store, the request locale, the bound `t` |
141
142
 
143
+ ### Cart pricing
144
+
145
+ `useShopCart(shopId)` and `CartPanelController` also return `pricing`: what the
146
+ server charges for exactly the lines on screen (quantity-break and spend-gate
147
+ discounts included), or `null`. Amounts are decimal strings as the server sent
148
+ them; print them with `formatWireMoney(amount, currency)` (from
149
+ `utils/format`) and never compute a discount in a theme. When `pricing` is `null`, print `unit_price x quantity` as
150
+ before.
151
+
152
+ ```tsx
153
+ const { items, total, pricing } = useShopCart(vendor.id);
154
+
155
+ items.map((item) => {
156
+ const line = cartLinePricing(pricing, item.id); // from utils/cart-pricing
157
+ return line ? (
158
+ <Fragment key={item.id}>
159
+ {line.list_line_total ? <del>{formatWireMoney(line.list_line_total, currency)}</del> : null}
160
+ <ins>{formatWireMoney(line.line_total, currency)}</ins>
161
+ </Fragment>
162
+ ) : (
163
+ formatMoney(item.unit_price * item.quantity, currency)
164
+ );
165
+ });
166
+ ```
167
+
168
+ `formatWireMoney` hands the string to Intl at the currency's own precision, so a
169
+ zero-decimal currency prints no decimals and an amount with more digits than the
170
+ currency has is rounded by Intl; it returns an empty string for anything that is
171
+ not a plain non-negative decimal. The storefront app keeps a different
172
+ `formatWireMoney` (it accepts numbers and negatives and returns an em dash for a
173
+ missing amount); the wiring item must converge on one of them.
174
+
175
+ The host app supplies the server pricing once, above every theme, with
176
+ `<CartServerPricingProvider value={pricing}>` (`hooks/use-cart-server-pricing`).
177
+
178
+ ### Add-to-cart app blocks
179
+
180
+ An add-to-cart app block puts the products its app named into the cart with one
181
+ press. The storefront reads the block's lines (type `AppBlockAddToCartRead`, from
182
+ `types/app-block`), then calls `useAddAppBlockLines(shopId)` and prints ONE notice
183
+ from the result. No app code runs, the app never writes to the cart, and no price
184
+ is touched: each line is priced like the same product added from its page.
185
+
186
+ ```tsx
187
+ const { addLines, pending } = useAddAppBlockLines(vendor.id);
188
+
189
+ async function onPress(): Promise<void> {
190
+ const result = await addLines(read.lines);
191
+ if (result.complete) {
192
+ notify('added');
193
+ } else {
194
+ // result.outcomes: one { index, status, title, ... } per line, in order
195
+ notifyNotAdded(result.outcomes.filter((outcome) => outcome.status !== 'added'));
196
+ }
197
+ }
198
+ ```
199
+
200
+ Each line ends as `added`, `customise` (any required add-on group, pack groups
201
+ included, or required line text: the shopper must choose on the product page),
202
+ `variant_required`, `unavailable` (gone, inactive, `in_stock` false, another
203
+ store; the quantity is never compared with stock, which checkout enforces), `failed` (the
204
+ product could not be read; retry can help) or `over_limit` (past the 20th line).
205
+ A line that is not added never stops the others. Say "added" only when
206
+ `complete` is true. The statuses are what the kit can know from the product as
207
+ read; it cannot see the host's cart write, so the host keeps handling that
208
+ write's own answers.
209
+
210
+ While a press is pending, an `addLines` call with the same lines in the same
211
+ order returns the pending result and adds nothing, so a double click adds the
212
+ pack once; a different pack runs on its own (also disable the button on
213
+ `pending`). A malformed entry in `lines` is `failed`, and a throw while handling
214
+ one line never loses the outcomes of the others.
215
+
216
+ Limits: a line's `properties` are not written to the cart in this version (an app
217
+ claim or other app text never reaches the line). The outcome carries
218
+ `properties_dropped` and the result `propertiesDropped` (true when an added line
219
+ had some), so the renderer can say so. Products are read fresh on every press.
220
+ `addItemWithAddons` takes an optional fifth argument `{ silent: true }` that
221
+ suppresses its toasts, and now returns `'added' | 'variant_required' |
222
+ 'text_required'`.
223
+
142
224
  ## Errors
143
225
 
144
226
  Requests go through one place (`sdk/client.ts`). A non-2xx answer throws
package/client.ts CHANGED
@@ -17,6 +17,7 @@ export * from './components/image';
17
17
  export * from './components/product-metafields';
18
18
  export * from './components/powered-by-queek';
19
19
  export * from './components/language-switcher';
20
+ export * from './components/market-switcher';
20
21
  export * from './components/default-metaobject-page';
21
22
  export * from './components/product-media-frame';
22
23
  export * from './components/variant-picker';
@@ -33,9 +34,12 @@ export * from './api/collections';
33
34
  export * from './api/orders';
34
35
  export * from './hooks/use-href';
35
36
  export * from './hooks/use-locales';
37
+ export * from './hooks/use-markets';
36
38
  export * from './hooks/use-auth';
37
39
  export * from './hooks/use-cart';
38
40
  export * from './hooks/use-shop-cart';
41
+ export * from './hooks/use-add-app-block-lines';
42
+ export * from './hooks/use-cart-server-pricing';
39
43
  export * from './hooks/use-products';
40
44
  export * from './hooks/use-product-detail';
41
45
  export * from './hooks/use-product-sections';
@@ -8,13 +8,16 @@ import { useStorefront } from '../../provider';
8
8
  import { useHref } from '../../hooks/use-href';
9
9
  import { useShopCart } from '../../hooks/use-shop-cart';
10
10
  import { useCartPanelStore } from '../../stores/cart-panel-store';
11
- import { normalizeCurrencyCode } from '../../utils/format';
11
+ import { useDisplayCurrency } from '../../hooks/use-markets';
12
+ import type { CartServerPricing } from '../../utils/cart-pricing';
12
13
 
13
14
  /** What {@link CartPanelController} hands to your render function: the panel state, this shop's lines, and the actions that change them. */
14
15
  export interface CartPanelControllerRenderProps {
15
16
  isOpen: boolean;
16
17
  items: CartItem[];
17
18
  total: number;
19
+ /** What the server charges for these lines (decimal strings; print them with `formatWireMoney`), or `null`/absent: print list prices. Never compute a discount. The controller always passes it; it is optional in the type so a hand-built props object (a test, a story) stays valid. */
20
+ pricing?: CartServerPricing | null;
18
21
  currency: string;
19
22
  onClose: () => void;
20
23
  onCheckout: () => void;
@@ -42,11 +45,12 @@ export function CartPanelController({
42
45
  children: (props: CartPanelControllerRenderProps) => ReactNode;
43
46
  }): JSX.Element {
44
47
  const { vendor } = useStorefront();
48
+ const currency = useDisplayCurrency();
45
49
  const href = useHref();
46
50
  const router = useRouter();
47
51
  const isOpen = useCartPanelStore((state) => state.isOpen);
48
52
  const closePanel = useCartPanelStore((state) => state.close);
49
- const { items, total, setQuantity, removeItem } = useShopCart(vendor.id);
53
+ const { items, total, pricing, setQuantity, removeItem } = useShopCart(vendor.id);
50
54
 
51
55
  useEffect(() => {
52
56
  if (!isOpen) return;
@@ -71,9 +75,10 @@ export function CartPanelController({
71
75
  isOpen,
72
76
  items,
73
77
  total,
74
- // Store-wide display uses the vendor's currency; item rows carry their own.
78
+ pricing,
79
+ // Store-wide display uses the shopper's market currency, else the vendor's; item rows carry their own.
75
80
  // List-level meta.currency is never read (platform default, wrong per store).
76
- currency: normalizeCurrencyCode(vendor.currency),
81
+ currency,
77
82
  onClose: closePanel,
78
83
  onCheckout: () => navigate('/checkout'),
79
84
  onViewCart: () => navigate('/cart'),
@@ -1,6 +1,6 @@
1
1
  'use client';
2
2
 
3
- import type { JSX } from 'react';
3
+ import type { CSSProperties, JSX } from 'react';
4
4
  import { useRef, useState } from 'react';
5
5
  import Link from 'next/link';
6
6
  import type { CartShellProps } from '../../types/theme';
@@ -9,11 +9,58 @@ import { useThemeStrings } from '../../provider';
9
9
  import { useCheckoutStore } from '../../stores/checkout-store';
10
10
  import { useRelatedProducts } from '../../hooks/use-related-products';
11
11
  import { useCart } from '../../hooks/use-cart';
12
- import { formatMoney } from '../../utils/format';
12
+ import { formatMoney, formatWireMoney } from '../../utils/format';
13
+ import { cartLinePricing, resolveCartPricing } from '../../utils/cart-pricing';
14
+ import { useCartServerPricing } from '../../hooks/use-cart-server-pricing';
13
15
  import { productRequiresVariant } from '../../utils/match-variant';
14
16
  import { visibleLineProperties } from '../../utils/line-properties';
15
17
  import { Image } from '../image';
16
18
 
19
+ /** The standard visually-hidden recipe, inline because the kit ships no CSS for the cart page. */
20
+ const VISUALLY_HIDDEN: CSSProperties = {
21
+ position: 'absolute',
22
+ width: 1,
23
+ height: 1,
24
+ margin: -1,
25
+ padding: 0,
26
+ overflow: 'hidden',
27
+ clip: 'rect(0 0 0 0)',
28
+ whiteSpace: 'nowrap',
29
+ border: 0,
30
+ };
31
+
32
+ /**
33
+ * An amount the server charges, with the list amount struck through when the
34
+ * server charges less. Both are server decimal strings printed as received.
35
+ *
36
+ * Assistive technology reads ONE visually hidden sentence ("Was X, now Y", a
37
+ * plain text node, so it is read in browse mode too) and the visible `<del>` /
38
+ * `<ins>` pair is hidden from it: a deletion's semantics are announced
39
+ * unevenly across screen readers and an `aria-label` on a generic wrapper can
40
+ * be skipped, while a text node cannot. Themes style the pair through
41
+ * `core-cart-item__was` / `core-cart-item__now`; the inline `text-decoration`
42
+ * is the fallback for a theme without those classes (it sets nothing else, so
43
+ * a theme's colour rule still applies).
44
+ */
45
+ function ChargedPrice({ amount, list, currency }: { amount: string; list: string | null; currency: string }): JSX.Element {
46
+ const t = useThemeStrings();
47
+ const charged = formatWireMoney(amount, currency);
48
+
49
+ if (list === null) {
50
+ return <>{charged}</>;
51
+ }
52
+
53
+ const original = formatWireMoney(list, currency);
54
+
55
+ return (
56
+ <>
57
+ <span style={VISUALLY_HIDDEN}>{t('cart.item.discounted', { original, price: charged })}</span>
58
+ <del className="core-cart-item__was" aria-hidden="true">{original}</del>{' '}
59
+ <ins className="core-cart-item__now" aria-hidden="true" style={{ textDecoration: 'none' }}>{charged}</ins>
60
+ </>
61
+ );
62
+ }
63
+
17
64
  /**
18
65
  * The cart page's shared, root design — every theme's shells/cart-shell.tsx
19
66
  * delegates to this (all thin passthroughs today) unless one chooses to
@@ -36,6 +83,8 @@ export function DefaultCartShell({
36
83
  const [noteOpen, setNoteOpen] = useState(false);
37
84
  const [agreed, setAgreed] = useState(false);
38
85
  const relatedRef = useRef<HTMLDivElement>(null);
86
+ // What the server charges for exactly these lines, or null: list prices, as always.
87
+ const serverPricing = resolveCartPricing(useCartServerPricing(), items);
39
88
 
40
89
  const firstSlug = items.find((item) => item.slug)?.slug ?? '';
41
90
  const { products: related } = useRelatedProducts(firstSlug, 6);
@@ -68,7 +117,10 @@ export function DefaultCartShell({
68
117
  <div className="core-cart-page__main">
69
118
  <div className="core-cart-page__items-card">
70
119
  <ul className="core-cart-page__items">
71
- {items.map((item) => (
120
+ {items.map((item) => {
121
+ const linePricing = cartLinePricing(serverPricing, item.id);
122
+
123
+ return (
72
124
  <li key={`${item.shop_id}-${item.id}`} className="core-cart-page__item">
73
125
  {item.image ? (
74
126
  <Image src={item.image} alt={item.title} className="core-cart-page__item-img" />
@@ -80,7 +132,7 @@ export function DefaultCartShell({
80
132
  {visibleLineProperties(item).map((row) => (
81
133
  <span key={row.key} className="core-cart-page__item-price">{`${row.label}: ${row.value}`}</span>
82
134
  ))}
83
- <span className="core-cart-page__item-price">{t('cart.item.each', { price: formatMoney(item.unit_price, currency) })}</span>
135
+ <span className="core-cart-page__item-price">{t('cart.item.each', { price: linePricing ? formatWireMoney(linePricing.unit_price, currency) : formatMoney(item.unit_price, currency) })}</span>
84
136
  </div>
85
137
  <div className="core-cart-page__item-qty">
86
138
  <button type="button" onClick={() => onDecrease(item.id, item.shop_id)} aria-label={t('cart.item.decrease', { title: item.title })}>
@@ -91,14 +143,19 @@ export function DefaultCartShell({
91
143
  <svg width="10" height="10" viewBox="0 0 12 12" fill="none" aria-hidden="true"><path d="M6 2v8M2 6h8" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" /></svg>
92
144
  </button>
93
145
  </div>
94
- <span className="core-cart-page__item-total">{formatMoney(item.unit_price * item.quantity, currency)}</span>
146
+ <span className="core-cart-page__item-total">
147
+ {linePricing ? (
148
+ <ChargedPrice amount={linePricing.line_total} list={linePricing.list_line_total} currency={currency} />
149
+ ) : formatMoney(item.unit_price * item.quantity, currency)}
150
+ </span>
95
151
  <button type="button" className="core-cart-page__item-remove" onClick={() => onRemove(item.id, item.shop_id)} aria-label={t('cart.item.remove', { title: item.title })}>
96
152
  <svg width="16" height="16" viewBox="0 0 20 20" fill="none" aria-hidden="true">
97
153
  <path d="M4 6h12M8 6V4.5A1.5 1.5 0 019.5 3h1A1.5 1.5 0 0112 4.5V6m-6 0v9.5A1.5 1.5 0 007.5 17h5a1.5 1.5 0 001.5-1.5V6" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" />
98
154
  </svg>
99
155
  </button>
100
156
  </li>
101
- ))}
157
+ );
158
+ })}
102
159
  </ul>
103
160
  </div>
104
161
 
@@ -184,7 +241,11 @@ export function DefaultCartShell({
184
241
 
185
242
  <div className="core-cart-page__subtotal">
186
243
  <span>{t('cart.summary.subtotal')}</span>
187
- <strong>{formatMoney(total, currency)} {currency}</strong>
244
+ <strong>
245
+ {serverPricing ? (
246
+ <ChargedPrice amount={serverPricing.total} list={serverPricing.list_total} currency={currency} />
247
+ ) : formatMoney(total, currency)} {currency}
248
+ </strong>
188
249
  </div>
189
250
 
190
251
  <label className="core-cart-page__terms">
@@ -0,0 +1,82 @@
1
+ 'use client';
2
+
3
+ import { useContext, type JSX, type ReactNode } from 'react';
4
+ import { StorefrontContext, useThemeStrings } from '../provider';
5
+ import { useMarkets, type MarketsState } from '../hooks/use-markets';
6
+ import type { StoreMarket } from '../utils/market';
7
+ import './language-switcher.css';
8
+
9
+ /** Props for `MarketSwitcher`. */
10
+ export interface MarketSwitcherProps {
11
+ /** Extra class on the root, to position or restyle the control. */
12
+ className?: string;
13
+ /**
14
+ * Take over the presentation. Called with the markets, the chosen one and
15
+ * `select`; whatever it returns renders instead of the default control.
16
+ * Still renders nothing on a store with no published market.
17
+ */
18
+ children?: (state: MarketsState & { label: string; labelFor: (market: StoreMarket | null) => string; displayName: (market: StoreMarket | null) => string }) => ReactNode;
19
+ }
20
+
21
+ /**
22
+ * The storefront's market control: the store's own currency plus each published
23
+ * market, one native select. Renders nothing outside a storefront or on a store
24
+ * with no published market, so it is safe to place unconditionally. Choosing an
25
+ * option reloads the page with every price in that currency; the choice is
26
+ * explicit and remembered for the store (nothing is guessed from the shopper's
27
+ * location). It reuses the language control's `qn-lang` look and tokens, so it
28
+ * mirrors in right-to-left storefronts.
29
+ *
30
+ * A theme that places this sets `marketSwitcher: 'theme'` in its manifest, so
31
+ * the storefront does not also render its own floating control.
32
+ */
33
+ export function MarketSwitcher(props: MarketSwitcherProps): JSX.Element | null {
34
+ const inStorefront = useContext(StorefrontContext) !== null;
35
+ if (!inStorefront) return null;
36
+ return <MarketSwitcherInner {...props} />;
37
+ }
38
+
39
+ function MarketSwitcherInner({ className, children }: MarketSwitcherProps): JSX.Element | null {
40
+ const t = useThemeStrings();
41
+ const state = useMarkets();
42
+ const { markets, hasMarkets, active, shopCurrency, select } = state;
43
+
44
+ if (!hasMarkets) return null;
45
+
46
+ const label = t('market.label');
47
+ // The store's own currency is its bare ISO code: a localized currency name can differ between the server's ICU and
48
+ // the browser's, and a select whose text differs between the two does not hydrate cleanly.
49
+ const displayName = (market: StoreMarket | null): string => (market ? `${market.name} · ${market.currency}` : shopCurrency);
50
+ const labelFor = (market: StoreMarket | null): string => t('market.named', { name: displayName(market) });
51
+
52
+ if (children) return <>{children({ ...state, label, labelFor, displayName })}</>;
53
+
54
+ const rootClass = ['qn-lang', 'qn-lang--select', 'qn-market', className].filter(Boolean).join(' ');
55
+
56
+ return (
57
+ <div className={rootClass} role="group" aria-label={label} data-qn-market-switcher="" data-variant="select">
58
+ <svg className="qn-lang__icon" aria-hidden="true" viewBox="0 0 24 24" focusable="false">
59
+ <circle cx="12" cy="12" r="9" />
60
+ <path d="M14.5 9.2c-.4-.8-1.4-1.2-2.5-1.2-1.4 0-2.4.7-2.4 1.8 0 2.4 5 1.1 5 3.6 0 1.1-1.1 1.8-2.6 1.8-1.2 0-2.2-.5-2.6-1.4M12 6.5V8m0 8v1.5" />
61
+ </svg>
62
+ <span className="qn-lang__field">
63
+ <select
64
+ className="qn-lang__select"
65
+ aria-label={labelFor(active)}
66
+ value={active ? String(active.id) : ''}
67
+ onChange={(event) => select(event.target.value === '' ? null : Number(event.target.value))}
68
+ >
69
+ <option value="">{displayName(null)}</option>
70
+ {markets.map((market) => (
71
+ <option key={market.id} value={String(market.id)}>
72
+ {displayName(market)}
73
+ </option>
74
+ ))}
75
+ </select>
76
+ <svg className="qn-lang__chevron" aria-hidden="true" viewBox="0 0 10 10" focusable="false">
77
+ <path d="M1 3.5 5 7.5 9 3.5" />
78
+ </svg>
79
+ </span>
80
+ </div>
81
+ );
82
+ }
@@ -0,0 +1,258 @@
1
+ 'use client';
2
+
3
+ import { useCallback, useEffect, useRef, useState } from 'react';
4
+ import { useStorefront, useStorefrontLocale } from '../provider';
5
+ import { ApiRequestError } from '../sdk/client';
6
+ import { useCartStore } from '../stores/cart-store';
7
+ import type { Product, ProductVariant } from '../types/product';
8
+ import type { AddAppBlockLinesResult, AppBlockLine, AppBlockLineOutcome, AppBlockLineStatus } from '../types/app-block';
9
+ import { requiredAddonsSatisfied } from '../utils/addon-selection';
10
+ import { productRequiresVariant } from '../utils/match-variant';
11
+ import { fetchProductBySlug } from './use-products';
12
+
13
+ /** Lines one press may add; the platform read caps at the same number. */
14
+ export const APP_BLOCK_MAX_LINES = 20;
15
+
16
+ type LoadProduct = (slug: string) => Promise<Product | null>;
17
+
18
+ type Loaded = { product: Product | null } | { failed: true };
19
+
20
+ async function load(loadProduct: LoadProduct, slug: string): Promise<Loaded> {
21
+ try {
22
+ return { product: await loadProduct(slug) };
23
+ } catch (caught) {
24
+ // A product that is gone is "unavailable"; any other failure may pass on a retry.
25
+ return caught instanceof ApiRequestError && caught.code === 'not_found' ? { product: null } : { failed: true };
26
+ }
27
+ }
28
+
29
+ function validShape(line: AppBlockLine | null | undefined): line is AppBlockLine {
30
+ return (
31
+ typeof line === 'object' &&
32
+ line !== null &&
33
+ typeof line.slug === 'string' &&
34
+ line.slug !== '' &&
35
+ typeof line.product_id === 'string' &&
36
+ Number.isInteger(line.quantity) &&
37
+ line.quantity >= 1 &&
38
+ line.quantity <= 20
39
+ );
40
+ }
41
+
42
+ /** The variant a line names on a variant product, or the status that stops it. */
43
+ function resolveVariant(product: Product, line: AppBlockLine): ProductVariant | AppBlockLineStatus {
44
+ if (!line.variant_id) {
45
+ return 'variant_required';
46
+ }
47
+
48
+ const variant = product.variants?.find((entry) => entry.id === line.variant_id);
49
+
50
+ // Only `in_stock` is read: the server folds the store's own stock setting into
51
+ // it. `tracking` and `quantity` are raw columns (a store that never enabled
52
+ // tracking sends every variant as tracked with 0 left), and stock is enforced
53
+ // at checkout, not by this helper, so a quantity is never compared with them.
54
+ return !variant || !variant.is_active || variant.inventory?.in_stock === false ? 'unavailable' : variant;
55
+ }
56
+
57
+ /**
58
+ * Whether the server would turn the line away, judged from the product as read.
59
+ * It mirrors the cart write, which adds nothing for a variant product without a
60
+ * valid variant and for a product with a required add-on group. A pack group
61
+ * counts too: the server composes its items, and delivery checkout rejects a
62
+ * line without them, so a bare line is never added. The kit itself cannot see
63
+ * that write (the host app syncs the cart); these are the cases it can know here.
64
+ */
65
+ function classify(product: Product | null, line: AppBlockLine, shopId: string): ProductVariant | AppBlockLineStatus | null {
66
+ if (!product || product.id !== line.product_id || product.shop_id !== shopId || product.status === 'inactive') {
67
+ return 'unavailable';
68
+ }
69
+
70
+ if (productRequiresVariant(product)) {
71
+ return resolveVariant(product, line);
72
+ }
73
+
74
+ if (line.variant_id || product.inventory?.in_stock === false) {
75
+ return 'unavailable';
76
+ }
77
+
78
+ return requiredAddonsSatisfied(product.addons ?? [], new Set()) ? null : 'customise';
79
+ }
80
+
81
+ /**
82
+ * Adds the lines of an add-to-cart app block through the cart store's own
83
+ * `addItemWithAddons`, one line at a time and silently, and reports what
84
+ * happened to each. `loadProduct` resolves a line's product by slug; a hook
85
+ * wraps it for storefront use ({@link useAddAppBlockLines}).
86
+ *
87
+ * The first 20 lines are tried; the rest are `over_limit`. A line that cannot
88
+ * be added is reported and the others are still added. The stored price of a
89
+ * line is whatever the store computes for the product (or variant) alone: the
90
+ * function never reads pricing, offers or anything an app sent beyond the
91
+ * product, variant and quantity.
92
+ */
93
+ export async function addAppBlockLines(
94
+ lines: AppBlockLine[],
95
+ { shopId, loadProduct }: { shopId: string; loadProduct: LoadProduct },
96
+ ): Promise<AddAppBlockLinesResult> {
97
+ const given: Array<AppBlockLine | null | undefined> = Array.isArray(lines) ? lines : [];
98
+ const tried = given.slice(0, APP_BLOCK_MAX_LINES);
99
+ const slugs = [...new Set(tried.filter(validShape).map((line) => line.slug))];
100
+ const loaded = new Map<string, Loaded>();
101
+
102
+ await Promise.all(slugs.map(async (slug) => loaded.set(slug, await load(loadProduct, slug))));
103
+
104
+ const outcomes: AppBlockLineOutcome[] = given.map((line, index) => {
105
+ const base = {
106
+ index,
107
+ product_id: typeof line?.product_id === 'string' ? line.product_id : '',
108
+ variant_id: typeof line?.variant_id === 'string' ? line.variant_id : null,
109
+ title: null as string | null,
110
+ ...(line?.properties && typeof line.properties === 'object' && Object.keys(line.properties).length > 0 ? { properties_dropped: true as const } : {}),
111
+ };
112
+
113
+ if (index >= APP_BLOCK_MAX_LINES) {
114
+ return { ...base, status: 'over_limit' };
115
+ }
116
+
117
+ if (!validShape(line)) {
118
+ return { ...base, status: 'failed' };
119
+ }
120
+
121
+ try {
122
+ return addOne(line, base, loaded.get(line.slug), shopId);
123
+ } catch (caught) {
124
+ // A throw before the store call leaves the cart as it was.
125
+ console.error('[cart] an add-to-cart app block line failed:', caught);
126
+
127
+ return { ...base, status: 'failed' };
128
+ }
129
+ });
130
+
131
+ const added = outcomes.filter((outcome) => outcome.status === 'added').length;
132
+
133
+ return {
134
+ added,
135
+ outcomes,
136
+ complete: outcomes.length > 0 && added === outcomes.length,
137
+ propertiesDropped: outcomes.some((outcome) => outcome.status === 'added' && outcome.properties_dropped === true),
138
+ };
139
+ }
140
+
141
+ function shopUnits(shopId: string): number {
142
+ return useCartStore.getState().items.reduce((sum, entry) => sum + (entry.shop_id === shopId ? entry.quantity : 0), 0);
143
+ }
144
+
145
+ function addOne(line: AppBlockLine, base: Omit<AppBlockLineOutcome, 'status'>, entry: Loaded | undefined, shopId: string): AppBlockLineOutcome {
146
+ if (!entry || 'failed' in entry) {
147
+ return { ...base, status: 'failed' };
148
+ }
149
+
150
+ const product = entry.product;
151
+ const verdict = classify(product, line, shopId);
152
+ const title = product?.title ?? null;
153
+
154
+ if (typeof verdict === 'string') {
155
+ return { ...base, title, status: verdict };
156
+ }
157
+
158
+ const before = shopUnits(shopId);
159
+ let result: ReturnType<ReturnType<typeof useCartStore.getState>['addItemWithAddons']>;
160
+
161
+ try {
162
+ result = useCartStore.getState().addItemWithAddons(product as Product, line.quantity, [], verdict, { silent: true });
163
+ } catch (caught) {
164
+ // The store writes the line before it reports the add (the analytics event
165
+ // comes last), so a throw is judged by what the cart holds, never guessed.
166
+ console.error('[cart] the cart store threw while adding an app block line:', caught);
167
+
168
+ return { ...base, title, status: shopUnits(shopId) >= before + line.quantity ? 'added' : 'failed' };
169
+ }
170
+
171
+ return { ...base, title, status: result === 'added' ? 'added' : result === 'variant_required' ? 'variant_required' : 'customise' };
172
+ }
173
+
174
+ /** What makes two presses the same pack: the same lines, in the same order. */
175
+ function pressSignature(lines: AppBlockLine[]): string {
176
+ return JSON.stringify(
177
+ (Array.isArray(lines) ? lines : []).map((line) =>
178
+ typeof line === 'object' && line !== null ? [line.product_id, line.slug, line.variant_id ?? null, line.quantity] : null,
179
+ ),
180
+ );
181
+ }
182
+
183
+ /**
184
+ * Puts the products of an add-to-cart app block into the shopper's cart through
185
+ * the store's own add action: no app code runs, no app writes to the cart, and
186
+ * no price is touched (each line is priced like the same product added from its
187
+ * page). Call `addLines` from the press handler with `lines` from the block's
188
+ * read, then print ONE notice from the result: "added" only when `complete` is
189
+ * true, else name the lines that were not added from `outcomes` (`customise`
190
+ * and `variant_required` mean the shopper must choose on the product page).
191
+ *
192
+ * `shopId` is the store's id (`product.shop_id`); a line whose product belongs
193
+ * to another store is `unavailable`. While a press is pending, `pending` is
194
+ * true and an `addLines` call with the same lines in the same order returns the
195
+ * pending result and adds nothing, so a double click adds the pack once; a
196
+ * different pack runs on its own. Disable the button on `pending` too.
197
+ *
198
+ * Limits: a line's `properties` are not written to the cart (the store has no
199
+ * entry for them; the outcome says `properties_dropped` and the result
200
+ * `propertiesDropped`), and the products are read fresh on every press.
201
+ *
202
+ * @example
203
+ * const { addLines, pending } = useAddAppBlockLines(shopId);
204
+ * const result = await addLines(read.lines);
205
+ */
206
+ export function useAddAppBlockLines(shopId: string | null | undefined): {
207
+ addLines: (lines: AppBlockLine[]) => Promise<AddAppBlockLinesResult>;
208
+ pending: boolean;
209
+ } {
210
+ const { previewData, vendor } = useStorefront();
211
+ const locale = useStorefrontLocale();
212
+ const [pending, setPending] = useState(false);
213
+ const inFlight = useRef(new Map<string, Promise<AddAppBlockLinesResult>>());
214
+ const mounted = useRef(true);
215
+ const previewProducts = previewData?.products;
216
+ const vendorSlug = vendor.slug;
217
+
218
+ useEffect(() => {
219
+ mounted.current = true;
220
+
221
+ return () => {
222
+ mounted.current = false;
223
+ };
224
+ }, []);
225
+
226
+ const addLines = useCallback(
227
+ (lines: AppBlockLine[]): Promise<AddAppBlockLinesResult> => {
228
+ const signature = pressSignature(lines);
229
+ const running = inFlight.current.get(signature);
230
+
231
+ if (running) {
232
+ return running;
233
+ }
234
+
235
+ const loadProduct: LoadProduct = async (slug) =>
236
+ Array.isArray(previewProducts)
237
+ ? (previewProducts.find((entry) => entry.slug === slug) ?? null)
238
+ : fetchProductBySlug(vendorSlug, slug, locale);
239
+
240
+ setPending(true);
241
+
242
+ const run = addAppBlockLines(lines, { shopId: shopId ?? '', loadProduct }).finally(() => {
243
+ inFlight.current.delete(signature);
244
+
245
+ if (mounted.current) {
246
+ setPending(inFlight.current.size > 0);
247
+ }
248
+ });
249
+
250
+ inFlight.current.set(signature, run);
251
+
252
+ return run;
253
+ },
254
+ [shopId, previewProducts, vendorSlug, locale],
255
+ );
256
+
257
+ return { addLines, pending };
258
+ }
@@ -0,0 +1,33 @@
1
+ 'use client';
2
+
3
+ import type { JSX, ReactNode } from 'react';
4
+ import { createContext, useContext } from 'react';
5
+ import type { CartServerPricing } from '../utils/cart-pricing';
6
+
7
+ const CartServerPricingContext = createContext<CartServerPricing | null>(null);
8
+
9
+ /**
10
+ * Where the host app hands the kit what the server charges for the cart on
11
+ * screen. The storefront mounts it once, above every theme, with the pricing
12
+ * it read from the server for the cart as it stands (or `null` when it has
13
+ * none). A theme never mounts it; it reads the result through `useShopCart()`
14
+ * or `CartPanelController`.
15
+ */
16
+ export function CartServerPricingProvider({
17
+ value,
18
+ children,
19
+ }: {
20
+ value: CartServerPricing | null;
21
+ children: ReactNode;
22
+ }): JSX.Element {
23
+ return <CartServerPricingContext.Provider value={value}>{children}</CartServerPricingContext.Provider>;
24
+ }
25
+
26
+ /**
27
+ * The pricing the host provided, exactly as given, or `null` without a provider.
28
+ * It is NOT checked against any cart lines: prefer `useShopCart(...).pricing`,
29
+ * which only returns it when it covers the lines on screen.
30
+ */
31
+ export function useCartServerPricing(): CartServerPricing | null {
32
+ return useContext(CartServerPricingContext);
33
+ }