@usequeek/theme-kit 0.1.28 → 0.1.30
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 +82 -0
- package/apps/storefront-events.ts +277 -0
- package/client.ts +3 -0
- package/components/cart/cart-panel-controller.tsx +5 -1
- package/components/cart/default-cart-shell.tsx +68 -7
- package/hooks/use-add-app-block-lines.ts +258 -0
- package/hooks/use-cart-server-pricing.tsx +33 -0
- package/hooks/use-products.ts +20 -5
- package/hooks/use-shop-cart.ts +15 -1
- package/index.ts +2 -0
- package/locales/en.default.json +2 -1
- package/package.json +1 -1
- package/stores/cart-store.ts +39 -16
- package/types/app-block.ts +86 -0
- package/types/vendor.ts +7 -1
- package/utils/cart-pricing.ts +115 -0
- package/utils/format.ts +45 -0
- package/apps/analytics-events.ts +0 -32
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
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
|
|
3
|
+
import { roundAmount } from '../utils/format';
|
|
4
|
+
import { gtagPush } from './gtag';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The one place a storefront announces a shopping event.
|
|
8
|
+
*
|
|
9
|
+
* trackStorefrontEvent('product_added_to_cart', { currency, value, items });
|
|
10
|
+
*
|
|
11
|
+
* Code that emits an event never calls a provider SDK. Providers subscribe:
|
|
12
|
+
* the Google Analytics subscriber is registered below, once, as soon as this
|
|
13
|
+
* module loads; the host registers any other provider with `onStorefrontEvent`.
|
|
14
|
+
*
|
|
15
|
+
* The bus is synchronous. A subscriber that throws is isolated: the page and
|
|
16
|
+
* the other subscribers carry on. With no `window` (server render) an event is
|
|
17
|
+
* a no-op, so emitting is always safe.
|
|
18
|
+
*
|
|
19
|
+
* No customer field travels on the bus: product ids, names, prices, quantities,
|
|
20
|
+
* value, currency, the order number and `paid` only. That is enforced at runtime,
|
|
21
|
+
* not just in the types: every event is rebuilt from its known keys before any
|
|
22
|
+
* subscriber sees it, so an extra key on the payload or on an item (line text,
|
|
23
|
+
* an email, a phone) never reaches a subscriber or `dataLayer`.
|
|
24
|
+
*
|
|
25
|
+
* Register subscribers on the client (an effect, or client module load), never
|
|
26
|
+
* in a server render body: on the server `onStorefrontEvent` is a no-op.
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
export interface StorefrontEventItem {
|
|
30
|
+
item_id: string;
|
|
31
|
+
item_name: string;
|
|
32
|
+
/** The unit price actually charged, after discounts. Providers sum price * quantity as revenue. */
|
|
33
|
+
price: number;
|
|
34
|
+
quantity: number;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface StorefrontEventMap {
|
|
38
|
+
product_viewed: { currency: string; value: number; items: StorefrontEventItem[] };
|
|
39
|
+
/** Scrubbed by the bus before any subscriber sees it (see `scrubSearchTerm`). */
|
|
40
|
+
search_submitted: { search_term: string };
|
|
41
|
+
product_added_to_cart: { currency: string; value: number; items: StorefrontEventItem[] };
|
|
42
|
+
checkout_started: { currency: string; value: number; num_items: number; items: StorefrontEventItem[] };
|
|
43
|
+
checkout_completed: {
|
|
44
|
+
/** The human order number, never the order UUID. */
|
|
45
|
+
order_no: string;
|
|
46
|
+
currency: string;
|
|
47
|
+
/** The order's grand total (what the customer paid), tax and shipping included. */
|
|
48
|
+
value: number;
|
|
49
|
+
/** False for an order still awaiting online payment. */
|
|
50
|
+
paid: boolean;
|
|
51
|
+
items: StorefrontEventItem[];
|
|
52
|
+
/** Items after discounts, excluding tax and shipping. GA4 `purchase.value` uses it
|
|
53
|
+
* when finite, otherwise the sum of price * quantity of `items`. */
|
|
54
|
+
subtotal?: number;
|
|
55
|
+
/** Tax and shipping amounts of the order, when known. GA4 takes them as separate parameters. */
|
|
56
|
+
tax?: number;
|
|
57
|
+
shipping?: number;
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export type StorefrontEventName = keyof StorefrontEventMap;
|
|
62
|
+
|
|
63
|
+
export type StorefrontEvent = {
|
|
64
|
+
[K in StorefrontEventName]: { name: K; data: StorefrontEventMap[K] };
|
|
65
|
+
}[StorefrontEventName];
|
|
66
|
+
|
|
67
|
+
/** A handler may be async; a rejection is caught and logged like a throw. */
|
|
68
|
+
export type StorefrontEventHandler = (event: StorefrontEvent) => void | Promise<unknown>;
|
|
69
|
+
|
|
70
|
+
const SEARCH_TERM_MAX_LENGTH = 100;
|
|
71
|
+
const SEARCH_TERM_MAX_DIGITS = 6;
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Cleans a shopper's search text before it can reach any provider. Returns
|
|
75
|
+
* `null` when the event must be dropped entirely: empty, an `@` (or `%40`)
|
|
76
|
+
* anywhere (an email address), or 7 or more digits IN TOTAL anywhere in the
|
|
77
|
+
* text (a phone, card or order number; "in total" rather than "consecutive" is
|
|
78
|
+
* the stricter rule, so `0803 123 4567` and `08-03-12-34-567` are both dropped).
|
|
79
|
+
* The text is NFKC-normalised first, so full-width `@`, small `﹫`, superscript
|
|
80
|
+
* and circled digits count as what they look like. The checks run on the full
|
|
81
|
+
* trimmed text, then the result is capped at 100 characters.
|
|
82
|
+
*/
|
|
83
|
+
export function scrubSearchTerm(raw: unknown): string | null {
|
|
84
|
+
if (typeof raw !== 'string') {
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const trimmed = raw.normalize('NFKC').trim();
|
|
89
|
+
|
|
90
|
+
if (trimmed === '' || trimmed.includes('@') || /%40/i.test(trimmed)) {
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
if ((trimmed.match(/\p{N}/gu) ?? []).length > SEARCH_TERM_MAX_DIGITS) {
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const capped = Array.from(trimmed).slice(0, SEARCH_TERM_MAX_LENGTH).join('').trim();
|
|
99
|
+
|
|
100
|
+
return capped === '' ? null : capped;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const handlers = new Set<StorefrontEventHandler>();
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Subscribes to every storefront event. Returns the unsubscribe function.
|
|
107
|
+
* Without a `window` (server render) nothing is stored and the unsubscribe is a no-op.
|
|
108
|
+
*/
|
|
109
|
+
export function onStorefrontEvent(handler: StorefrontEventHandler): () => void {
|
|
110
|
+
if (typeof window === 'undefined') {
|
|
111
|
+
return () => {};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
handlers.add(handler);
|
|
115
|
+
|
|
116
|
+
return () => {
|
|
117
|
+
handlers.delete(handler);
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function normalizeItems(items: unknown): StorefrontEventItem[] {
|
|
122
|
+
if (!Array.isArray(items)) {
|
|
123
|
+
return [];
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
return items.map((item: Partial<StorefrontEventItem> | null) => ({
|
|
127
|
+
item_id: String(item?.item_id ?? ''),
|
|
128
|
+
item_name: String(item?.item_name ?? ''),
|
|
129
|
+
price: Number(item?.price),
|
|
130
|
+
quantity: Number(item?.quantity),
|
|
131
|
+
}));
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Rebuilds an event from its known keys only, so nothing extra reaches a subscriber. */
|
|
135
|
+
function normalizeEvent<K extends StorefrontEventName>(name: K, data: StorefrontEventMap[K]): StorefrontEvent | null {
|
|
136
|
+
const raw = (data ?? {}) as Record<string, unknown>;
|
|
137
|
+
|
|
138
|
+
switch (name) {
|
|
139
|
+
case 'search_submitted': {
|
|
140
|
+
const term = scrubSearchTerm(raw.search_term);
|
|
141
|
+
|
|
142
|
+
return term === null ? null : { name: 'search_submitted', data: { search_term: term } };
|
|
143
|
+
}
|
|
144
|
+
case 'product_viewed':
|
|
145
|
+
case 'product_added_to_cart':
|
|
146
|
+
return {
|
|
147
|
+
name,
|
|
148
|
+
data: {
|
|
149
|
+
currency: String(raw.currency ?? ''),
|
|
150
|
+
value: roundAmount(Number(raw.value)),
|
|
151
|
+
items: normalizeItems(raw.items),
|
|
152
|
+
},
|
|
153
|
+
} as StorefrontEvent;
|
|
154
|
+
case 'checkout_started':
|
|
155
|
+
return {
|
|
156
|
+
name: 'checkout_started',
|
|
157
|
+
data: {
|
|
158
|
+
currency: String(raw.currency ?? ''),
|
|
159
|
+
value: roundAmount(Number(raw.value)),
|
|
160
|
+
num_items: Number(raw.num_items),
|
|
161
|
+
items: normalizeItems(raw.items),
|
|
162
|
+
},
|
|
163
|
+
};
|
|
164
|
+
case 'checkout_completed': {
|
|
165
|
+
const extras = (key: 'subtotal' | 'tax' | 'shipping'): Partial<Record<typeof key, number>> =>
|
|
166
|
+
typeof raw[key] === 'number' ? { [key]: roundAmount(raw[key] as number) } : {};
|
|
167
|
+
|
|
168
|
+
return {
|
|
169
|
+
name: 'checkout_completed',
|
|
170
|
+
data: {
|
|
171
|
+
order_no: String(raw.order_no ?? ''),
|
|
172
|
+
currency: String(raw.currency ?? ''),
|
|
173
|
+
value: roundAmount(Number(raw.value)),
|
|
174
|
+
paid: raw.paid === true,
|
|
175
|
+
items: normalizeItems(raw.items),
|
|
176
|
+
...extras('subtotal'),
|
|
177
|
+
...extras('tax'),
|
|
178
|
+
...extras('shipping'),
|
|
179
|
+
},
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
default:
|
|
183
|
+
return null;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function logSubscriberError(name: string, error: unknown): void {
|
|
188
|
+
if (process.env.NODE_ENV !== 'production') {
|
|
189
|
+
console.error('[storefront-events] a subscriber threw on', name, error);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export function trackStorefrontEvent<K extends StorefrontEventName>(name: K, data: StorefrontEventMap[K]): void {
|
|
194
|
+
if (typeof window === 'undefined') {
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const event = normalizeEvent(name, data);
|
|
199
|
+
|
|
200
|
+
if (event === null) {
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
for (const handler of [...handlers]) {
|
|
205
|
+
try {
|
|
206
|
+
const result = handler(event);
|
|
207
|
+
|
|
208
|
+
if (result && typeof (result as Promise<unknown>).catch === 'function') {
|
|
209
|
+
(result as Promise<unknown>).catch((error: unknown) => logSubscriberError(name, error));
|
|
210
|
+
}
|
|
211
|
+
} catch (error) {
|
|
212
|
+
logSubscriberError(name, error);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
const finite = (value: number): boolean => Number.isFinite(value);
|
|
218
|
+
|
|
219
|
+
/** `{ value }` when it is a real number, nothing otherwise: GA gets no `NaN`. */
|
|
220
|
+
const valueParam = (value: number): { value: number } | Record<string, never> => (finite(value) ? { value } : {});
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Google Analytics 4. Not gated on consent here: Consent Mode (see
|
|
224
|
+
* analytics.tsx) decides whether gtag.js transmits anything for a denied
|
|
225
|
+
* visitor, so events are pushed unconditionally and Google's library filters.
|
|
226
|
+
*
|
|
227
|
+
* `purchase.value` follows Google's reference: the sum of price * quantity of
|
|
228
|
+
* the items (after discounts), excluding shipping and tax, which go in their own
|
|
229
|
+
* parameters. The event's `subtotal` is used when given; the payload `value`
|
|
230
|
+
* (grand total) is never sent to GA as the purchase value.
|
|
231
|
+
*/
|
|
232
|
+
function googleAnalyticsSubscriber(event: StorefrontEvent): void {
|
|
233
|
+
switch (event.name) {
|
|
234
|
+
case 'product_viewed':
|
|
235
|
+
gtagPush('event', 'view_item', { currency: event.data.currency, ...valueParam(event.data.value), items: event.data.items });
|
|
236
|
+
return;
|
|
237
|
+
case 'search_submitted':
|
|
238
|
+
gtagPush('event', 'search', { search_term: event.data.search_term });
|
|
239
|
+
return;
|
|
240
|
+
case 'product_added_to_cart':
|
|
241
|
+
gtagPush('event', 'add_to_cart', { currency: event.data.currency, ...valueParam(event.data.value), items: event.data.items });
|
|
242
|
+
return;
|
|
243
|
+
case 'checkout_started':
|
|
244
|
+
gtagPush('event', 'begin_checkout', { currency: event.data.currency, ...valueParam(event.data.value), items: event.data.items });
|
|
245
|
+
return;
|
|
246
|
+
case 'checkout_completed': {
|
|
247
|
+
const { order_no, currency, items, subtotal, tax, shipping } = event.data;
|
|
248
|
+
const value =
|
|
249
|
+
typeof subtotal === 'number' && finite(subtotal)
|
|
250
|
+
? subtotal
|
|
251
|
+
: roundAmount(items.reduce((sum, item) => sum + item.price * item.quantity, 0));
|
|
252
|
+
|
|
253
|
+
gtagPush('event', 'purchase', {
|
|
254
|
+
transaction_id: order_no,
|
|
255
|
+
...valueParam(value),
|
|
256
|
+
currency,
|
|
257
|
+
...(typeof tax === 'number' && finite(tax) ? { tax } : {}),
|
|
258
|
+
...(typeof shipping === 'number' && finite(shipping) ? { shipping } : {}),
|
|
259
|
+
items,
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
let googleAnalyticsRegistered = false;
|
|
266
|
+
|
|
267
|
+
/** Idempotent; runs once at module load so GA is live whenever the bus is used. */
|
|
268
|
+
export function registerGoogleAnalyticsSubscriber(): void {
|
|
269
|
+
if (googleAnalyticsRegistered) {
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
googleAnalyticsRegistered = true;
|
|
274
|
+
handlers.add(googleAnalyticsSubscriber);
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
registerGoogleAnalyticsSubscriber();
|
package/client.ts
CHANGED
|
@@ -27,6 +27,7 @@ export * from './components/checkout/default-checkout-shell';
|
|
|
27
27
|
export * from './components/checkout/checkout-contact';
|
|
28
28
|
export * from './components/checkout/policy-links';
|
|
29
29
|
export * from './apps/follow-card';
|
|
30
|
+
export * from './apps/storefront-events';
|
|
30
31
|
export * from './apps/subscribe-form';
|
|
31
32
|
export * from './api/collections';
|
|
32
33
|
export * from './api/orders';
|
|
@@ -35,6 +36,8 @@ export * from './hooks/use-locales';
|
|
|
35
36
|
export * from './hooks/use-auth';
|
|
36
37
|
export * from './hooks/use-cart';
|
|
37
38
|
export * from './hooks/use-shop-cart';
|
|
39
|
+
export * from './hooks/use-add-app-block-lines';
|
|
40
|
+
export * from './hooks/use-cart-server-pricing';
|
|
38
41
|
export * from './hooks/use-products';
|
|
39
42
|
export * from './hooks/use-product-detail';
|
|
40
43
|
export * from './hooks/use-product-sections';
|
|
@@ -9,12 +9,15 @@ 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
11
|
import { normalizeCurrencyCode } from '../../utils/format';
|
|
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;
|
|
@@ -46,7 +49,7 @@ export function CartPanelController({
|
|
|
46
49
|
const router = useRouter();
|
|
47
50
|
const isOpen = useCartPanelStore((state) => state.isOpen);
|
|
48
51
|
const closePanel = useCartPanelStore((state) => state.close);
|
|
49
|
-
const { items, total, setQuantity, removeItem } = useShopCart(vendor.id);
|
|
52
|
+
const { items, total, pricing, setQuantity, removeItem } = useShopCart(vendor.id);
|
|
50
53
|
|
|
51
54
|
useEffect(() => {
|
|
52
55
|
if (!isOpen) return;
|
|
@@ -71,6 +74,7 @@ export function CartPanelController({
|
|
|
71
74
|
isOpen,
|
|
72
75
|
items,
|
|
73
76
|
total,
|
|
77
|
+
pricing,
|
|
74
78
|
// Store-wide display uses the vendor's currency; item rows carry their own.
|
|
75
79
|
// List-level meta.currency is never read (platform default, wrong per store).
|
|
76
80
|
currency: normalizeCurrencyCode(vendor.currency),
|
|
@@ -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">
|
|
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>
|
|
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">
|