Skip to content

Commit fc21c8b

Browse files
authored
Merge pull request #25 from Weaverse/fix/cart-performance
fix(cart): stabilize add quantities and align drawer styling
2 parents dd0c400 + b2d64f7 commit fc21c8b

9 files changed

Lines changed: 285 additions & 6 deletions

‎app/components/cart/animate-bottom-sheet.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ export function AnimatedBottomSheet({ open, children }) {
3030
className={clsx(
3131
"fixed inset-y-0 right-0 z-[60] bg-black/50",
3232
CART_DRAWER_WIDTH_CLASS,
33+
CART_DRAWER_RADIUS_CLASS,
3334
)}
3435
style={{ opacity: "var(--cart-sheet-progress)" }}
3536
/>

‎app/components/cart/cart-baseline.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,15 @@ import type { CartMutationResponse } from "./cart-types";
55
let freshestFetcherCart: CartApiQueryFragment | null = null;
66
let cartMutationEpoch = 0;
77
let recordedMutationCarts = new WeakSet<object>();
8+
let completedCartAdds = new WeakSet<FormData>();
9+
10+
export function recordCompletedCartAdd(formData: FormData) {
11+
completedCartAdds.add(formData);
12+
}
13+
14+
export function isCompletedCartAdd(formData: FormData) {
15+
return completedCartAdds.has(formData);
16+
}
817

918
export function getTimestampMs(dateString: string | undefined): number {
1019
return dateString ? new Date(dateString).getTime() : 0;
@@ -81,6 +90,7 @@ export function resolveBaselineCart(
8190
}
8291

8392
export function resetCartBaselineForTests() {
93+
completedCartAdds = new WeakSet();
8494
freshestFetcherCart = null;
8595
cartMutationEpoch = 0;
8696
recordedMutationCarts = new WeakSet<object>();

‎app/components/cart/cart-main.tsx‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -426,7 +426,11 @@ export function CartEmpty({
426426
{buttonStartShopping && (
427427
<Link
428428
to={layout === "page" ? "/products" : ""}
429-
className={clsx(layout === "drawer" ? "w-full" : "min-w-48")}
429+
variant="primary"
430+
className={clsx(
431+
"uppercase",
432+
layout === "drawer" ? "w-full" : "min-w-48",
433+
)}
430434
onClick={onClose}
431435
>
432436
{buttonStartShopping}

‎app/components/cart/cart-sync.tsx‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
getTimestampMs,
1212
hasCartResponseErrors,
1313
recordCartMutation,
14+
recordCompletedCartAdd,
1415
} from "./cart-baseline";
1516
import type { CartMutationResponse } from "./cart-types";
1617
import { useCartStore } from "./store";
@@ -31,6 +32,15 @@ function getFormInput(fetcher: Fetcher<unknown>) {
3132

3233
function syncFetcherResponse(fetcher: Fetcher<unknown>) {
3334
const response = fetcher.data as CartMutationResponse | undefined;
35+
const formInput = getFormInput(fetcher);
36+
if (
37+
response &&
38+
fetcher.formData &&
39+
formInput?.action === CartForm.ACTIONS.LinesAdd
40+
) {
41+
// The owner can receive its result before useFetchers leaves submitting.
42+
recordCompletedCartAdd(fetcher.formData);
43+
}
3444
const token = fetcher.formData?.get("cartStageToken");
3545
if (typeof token === "string" && response) {
3646
useCartStore.getState().clearPendingAdd(token);
@@ -44,7 +54,6 @@ function syncFetcherResponse(fetcher: Fetcher<unknown>) {
4454
}
4555
}
4656

47-
const formInput = getFormInput(fetcher);
4857
if (formInput?.action !== CartForm.ACTIONS.LinesUpdate) {
4958
return;
5059
}

‎app/components/cart/optimistic-cart.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { CartForm, type OptimisticCartLineInput } from "@shopify/hydrogen";
22
import type { Fetcher } from "react-router";
33
import type { CartApiQueryFragment } from "storefront-api.generated";
4+
import { isCompletedCartAdd } from "./cart-baseline";
45
import { getOptimisticLineQuantity } from "./cart-line-quantity";
56
import type {
67
CartLine,
@@ -281,6 +282,11 @@ export function applyOptimisticMutations(
281282
}
282283

283284
if (action === CartForm.ACTIONS.LinesAdd) {
285+
// A store update can render against an older Router fetcher snapshot.
286+
// Do not replay an add whose owner already received its action result.
287+
if (isCompletedCartAdd(fetcher.formData)) {
288+
continue;
289+
}
284290
const lines = ((inputs.lines ?? []) as OptimisticCartLineInput[]).filter(
285291
(line) => !staged.handled.has(cartLineIdentity(line)),
286292
);

‎app/components/product/add-to-cart-button.tsx‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ export function AddToCartButton({
5555
const { t } = useTranslation();
5656
const cartRoute = usePrefixPathWithLocale("/cart");
5757
const pendingToken = useRef<string | null>(null);
58+
const [stageToken, setStageToken] = useState("");
5859
const submitted = useRef(false);
5960
const [submittedLines, setSubmittedLines] = useState<
6061
OptimisticCartLineInput[] | null
@@ -94,6 +95,7 @@ export function AddToCartButton({
9495
setSubmittedLines(lines);
9596
submitted.current = true;
9697
pendingToken.current = useCartStore.getState().stagePendingAdd(lines);
98+
setStageToken(pendingToken.current ?? "");
9799
const tokenInput = (event.target as HTMLFormElement).elements.namedItem(
98100
"cartStageToken",
99101
);
@@ -124,7 +126,8 @@ export function AddToCartButton({
124126
submitted={submitted}
125127
onSettled={handleSettled}
126128
>
127-
<input type="hidden" name="cartStageToken" defaultValue="" />
129+
{/* Preserve the token when staging the add rerenders this form. */}
130+
<input type="hidden" name="cartStageToken" value={stageToken} />
128131
<input
129132
type="hidden"
130133
name="analytics"
Lines changed: 174 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,174 @@
1+
import assert from "node:assert/strict";
2+
import test from "node:test";
3+
import { fileURLToPath } from "node:url";
4+
import { chromium, expect } from "@playwright/test";
5+
import { build } from "esbuild";
6+
7+
const root = fileURLToPath(new URL("../", import.meta.url));
8+
// Exercise the real form, store and Router lifecycle, including a slow loader
9+
// after the action completes. Only translations and the server are fixtures.
10+
const bundle = await build({
11+
stdin: {
12+
resolveDir: root,
13+
loader: "tsx",
14+
contents: `
15+
import React, {useLayoutEffect} from 'react';
16+
import {createRoot} from 'react-dom/client';
17+
import {createMemoryRouter,RouterProvider,useLoaderData} from 'react-router';
18+
import {CartForm} from '@shopify/hydrogen';
19+
import {useProductQuantity} from './app/hooks/use-product-quantity';
20+
import {AddToCartButton} from './app/components/product/add-to-cart-button';
21+
import {CartStoreSync} from './app/components/cart/cart-sync';
22+
import {useCart,useCartStore} from './app/components/cart/store';
23+
import {buildOptimisticAddCart} from './app/components/cart/optimistic-cart';
24+
const variant={id:'gid://shopify/ProductVariant/7',availableForSale:true,quantityAvailable:7,price:{amount:'10',currencyCode:'USD'},product:{id:'product-1',handle:'chair',title:'Chair'},selectedOptions:[]};
25+
const input=quantity=>({merchandiseId:variant.id,selectedVariant:variant,quantity});
26+
function makeCart(quantity,sequence) {
27+
const cart=buildOptimisticAddCart([input(quantity)]);
28+
return {...cart,id:'cart-1',updatedAt:new Date(Date.UTC(2026,10,16,0,0,sequence)).toISOString(),isOptimistic:false,lines:{...cart.lines,nodes:cart.lines.nodes.map(line=>({...line,id:'line-1',isOptimistic:false}))}};
29+
}
30+
function Fixture({quantity:requested}) {
31+
const {quantity,setQuantity}=useProductQuantity(variant);
32+
const {cart:initialCart}=useLoaderData();
33+
const cart=useCart();
34+
const total=cart?.totalQuantity ?? 0;
35+
const lineQuantity=cart?.lines.nodes[0]?.quantity ?? 0;
36+
useLayoutEffect(()=>{window.quantities.push({total,lineQuantity});},[total,lineQuantity]);
37+
return <><CartStoreSync initialCart={initialCart}/><button onClick={()=>setQuantity(requested)}>Select quantity</button><output data-test='cart-quantity'>{lineQuantity}</output><AddToCartButton data-test='add' cartOpenTiming='manual' lines={[input(quantity)]}>Add to cart</AddToCartButton></>;
38+
}
39+
window.start=({existing,quantity,reject})=>{
40+
let currentCart=existing ? makeCart(existing,0) : null;
41+
let firstLoad=true, sequence=0;
42+
useCartStore.setState({serverCart:currentCart,isResolved:true});
43+
useCartStore.setState({inventoryPolicies:new Map([[variant.id,'DENY']])});
44+
window.quantities=[];window.requests=[];window.loaders=[];
45+
const router=createMemoryRouter([
46+
{id:'root',path:'/',element:<Fixture quantity={quantity}/>,loader:()=>{
47+
if(firstLoad){firstLoad=false;return {cart:currentCart};}
48+
return new Promise(resolve=>window.loaders.push(()=>resolve({cart:currentCart})));
49+
}},
50+
{path:'/cart',action:async({request})=>{
51+
const formData=await request.formData();
52+
const {inputs}=CartForm.getFormInput(formData);
53+
window.requests.push({quantity:inputs.lines[0].quantity,token:formData.get('cartStageToken')});
54+
await new Promise(resolve=>{window.finishAction=resolve;});
55+
if(reject) return {userErrors:[{message:'Rejected'}]};
56+
currentCart=makeCart((currentCart?.totalQuantity ?? 0)+inputs.lines[0].quantity,++sequence);
57+
return {cart:currentCart};
58+
}},
59+
]);
60+
window.router=router;
61+
createRoot(document.getElementById('root')).render(<RouterProvider router={router}/>);
62+
};
63+
`,
64+
},
65+
bundle: true,
66+
write: false,
67+
format: "iife",
68+
jsx: "automatic",
69+
alias: { "~": `${root}app` },
70+
plugins: [
71+
{
72+
name: "translation-only",
73+
setup(builder) {
74+
builder.onResolve({ filter: /^@weaverse\/hydrogen$/ }, () => ({
75+
path: "translation",
76+
namespace: "fixture",
77+
}));
78+
builder.onLoad({ filter: /.*/, namespace: "fixture" }, () => ({
79+
loader: "js",
80+
contents: "export const useTranslation=()=>({t:key=>key});",
81+
}));
82+
},
83+
},
84+
],
85+
});
86+
87+
for (const scenario of [
88+
{ existing: 0, quantity: 5, reject: false },
89+
{ existing: 0, quantity: 7, reject: false },
90+
{ existing: 1, quantity: 2, reject: false },
91+
{ existing: 2, quantity: 3, reject: true },
92+
]) {
93+
test(`add quantities never double during revalidation: ${JSON.stringify(scenario)}`, async () => {
94+
const browser = await chromium.launch();
95+
try {
96+
const page = await browser.newPage();
97+
await page.setContent('<div id="root"></div>');
98+
await page.addScriptTag({ content: bundle.outputFiles[0].text });
99+
await page.evaluate((options) => window.start(options), scenario);
100+
const quantity = page.locator('[data-test="cart-quantity"]');
101+
const add = page.locator('[data-test="add"]');
102+
await expect(quantity).toHaveText(String(scenario.existing));
103+
const tokens = [];
104+
let existing = scenario.existing;
105+
// A second submission on the same mounted form must get its own token.
106+
for (
107+
let attempt = 0;
108+
attempt < (scenario.quantity > 3 ? 1 : 2);
109+
attempt += 1
110+
) {
111+
await page
112+
.getByRole("button", { name: "Select quantity", exact: true })
113+
.click();
114+
await expect(add).toBeEnabled();
115+
await add.click();
116+
await expect(quantity).toHaveText(String(existing + scenario.quantity));
117+
await expect(add).toBeDisabled();
118+
await expect
119+
.poll(() => page.evaluate(() => window.requests.length))
120+
.toBe(attempt + 1);
121+
await page.evaluate(() => window.finishAction());
122+
await expect
123+
.poll(() => page.evaluate(() => window.loaders.length))
124+
.toBe(1);
125+
const accepted = scenario.reject
126+
? existing
127+
: existing + scenario.quantity;
128+
// Check while revalidation is held, not just after the eventual idle state.
129+
await expect(quantity).toHaveText(String(accepted));
130+
const trace = await page.evaluate(() => window.quantities);
131+
assert.ok(
132+
trace.every(
133+
(frame) =>
134+
frame.total === frame.lineQuantity &&
135+
[existing, existing + scenario.quantity].includes(frame.total),
136+
),
137+
JSON.stringify(trace),
138+
);
139+
const request = await page.evaluate(() => window.requests.at(-1));
140+
assert.equal(request.quantity, scenario.quantity);
141+
assert.ok(
142+
request.token,
143+
"The submitted form must retain its stage token",
144+
);
145+
assert.ok(
146+
!tokens.includes(request.token),
147+
"Each add needs a fresh token",
148+
);
149+
tokens.push(request.token);
150+
await page.evaluate(() => {
151+
for (const finish of window.loaders.splice(0)) {
152+
finish();
153+
}
154+
});
155+
await expect
156+
.poll(() =>
157+
page.evaluate(() =>
158+
Array.from(window.router.state.fetchers.values()).every(
159+
(fetcher) => fetcher.state === "idle",
160+
),
161+
),
162+
)
163+
.toBe(true);
164+
await expect(quantity).toHaveText(String(accepted));
165+
existing = accepted;
166+
await page.evaluate(() => {
167+
window.quantities = [];
168+
});
169+
}
170+
} finally {
171+
await browser.close();
172+
}
173+
});
174+
}

‎tests/cart-dialog-animation.browser.mjs‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -281,13 +281,30 @@ test("All cart action sheets share the cart bounds and token-based square-right
281281
.filter((element) => getComputedStyle(element).zIndex === "60")
282282
.map((element) => {
283283
const rect = element.getBoundingClientRect();
284-
return { x: rect.x, width: rect.width };
284+
const style = getComputedStyle(element);
285+
return {
286+
x: rect.x,
287+
width: rect.width,
288+
topLeft: style.borderTopLeftRadius,
289+
bottomLeft: style.borderBottomLeftRadius,
290+
topRight: style.borderTopRightRadius,
291+
bottomRight: style.borderBottomRightRadius,
292+
};
285293
}),
286294
);
287295
assert.deepEqual(
288296
overlayBounds,
289-
[{ x: cartBounds.x, width: cartBounds.width }],
290-
`${width}px ${name}: nested backdrop must stay within the cart frame`,
297+
[
298+
{
299+
x: cartBounds.x,
300+
width: cartBounds.width,
301+
topLeft: "18px",
302+
bottomLeft: "18px",
303+
topRight: "0px",
304+
bottomRight: "0px",
305+
},
306+
],
307+
`${width}px ${name}: nested backdrop must match the cart frame and corners`,
291308
);
292309
await page.keyboard.press("Escape");
293310
await expect(dialog).toHaveCount(0);

0 commit comments

Comments
 (0)