Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions paper-core.lock.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,23 +17,23 @@
"src/lib/saleor/raw.ts": "45e3d30eabf2cca7f726571e3ac5b04c01b68f06319028944ad2dbf5dc4005cd",
"src/lib/storefront/AGENTS.md": "0801d7f64a44b6469dd8d7c353c882db19e77dcf4e01bb06c8dc6b2c5d93016e",
"src/lib/storefront/contract/gallery.ts": "38e03e4d2844fa299330811fb7d6cf0260cd222fc58af3311513ec898d0cc701",
"src/lib/storefront/contract/listing.ts": "3bc1fcc56d1e606daab8d53a178f0d6f5e60a3fbdfc6678884164190049787ac",
"src/lib/storefront/contract/listing.ts": "52409ae95b22ab87eec7cda1cf34b4b5ccb1d0b221acc22438d4597c7b1f6ec1",
"src/lib/storefront/contract/product.ts": "a842b65c6cedaa4a6dbecbf1b213da3c411e6baf8dfb031b6299050a6746401f",
"src/lib/storefront/contract/version.ts": "88020263209f89b26b592ce46c6ff6948096eebdf539bccdfb6725718cf22aae",
"src/lib/storefront/mappers/gallery-images.ts": "ffc2e05b9699ee41d88755e805498ae54377dfaa61e0bba8e42a90558e365f4f",
"src/lib/storefront/mappers/product.ts": "6789b0feb4bc21acb0528f0672c26cdc2f8d2bcebc395c4d0ab2da964f999d2b",
"src/lib/storefront/templates.ts": "6907e0806f157c7faafcd56b4f25574f5ee3185c19842f90d9b1cc779b436ea9",
"src/lib/listing/cacheability.ts": "f461a1e4d9c637de7b09c825874b68f8ab5e24a4dcda394b39ba23906258e655",
"src/lib/listing/invalidate.ts": "982db0da013741b22388fe908d4d28428cabaec4abcedaa08599577fdaaebf8e",
"src/lib/listing/load.ts": "f727fe351237604ce610f9d099862d15c7724994350a706bc84e9385271dd76b",
"src/lib/listing/load.ts": "812faecd45aa9fde0b0fbd05ce34ef655178c602ea9d20dda5f9fd03fcc288ad",
"src/lib/listing/payload.ts": "5ee1a559b1ba2e50b58d5a31585e43c2b7fa216d0e8ddea7f376c6bdd4156c7e",
"src/lib/listing/policy.ts": "0bd21c24318b06fd116cff3f35748abe299e89968073609abed41ae13157e7f8",
"src/lib/listing/policy.ts": "47959a4b8b325660759b196c1285bbc93cf328662fe98f2ebd3f11c41831cbc9",
"src/lib/listing/provider.ts": "28f97d1a2b964ee68a907dcdd1961e74d60f149058c33904ed410b2232bfce8b",
"src/lib/listing/providers/saleor/constraints.ts": "662462b5ff8987e56e7f54ed922af94ff0f0cd26fc9ea4a907918f9af4849c20",
"src/lib/listing/providers/saleor/index.ts": "ccb00383a1c04d6cbb415d978a9fbb2ed6b86b50762d3095230cb9e5e569276e",
"src/lib/listing/providers/saleor/index.ts": "7fca1fef9af2c5375c1a1dc19a14d4f1ccf85ecae02e88ae15ab559b6ed84190",
"src/lib/listing/providers/saleor/sample-facets.ts": "5754db9106d5eae0e9ade7dc131185d9a2ca04a90f655037b8e55c4551ffa531",
"src/lib/listing/providers/saleor/to-card.ts": "746cff6c843ca5bab213413089a84e96157e603902d401394f80190d350eb890",
"src/lib/listing/query.ts": "ab82f321fbeb2dec2be789e1e4c827de48a18df5a0dd6fe1f029697e7cd05382",
"src/lib/listing/query.ts": "a266004dccda06daa713696619f67e685392eac8d9575f792ad9dae940a2b612",
"src/lib/listing/registry.ts": "f83f4fe6b3ea0015e313351b137220a4ce7b66f1978a7b95a706d8688f4241b1",
"src/lib/listing/testing.ts": "0ce9ea9c0f36f88120d1f4e8f9f8d7c87eb978d58c3291edd6ce97c4c601afe5",
"src/app/api/revalidate/route.ts": "ab573a7143b263cd75d1e142175f8e5b6ccf9cc4e694885a0ca58ca319ea60be",
Expand Down
8 changes: 7 additions & 1 deletion src/app/api/listing/route.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import { NextRequest } from "next/server";
import { isStorefrontLocaleSlug } from "@/config/locale";
import { getStorefrontChannelSlugs } from "@/lib/channel-slugs";
import { listingViewFromSearchParams, type ListingSurface } from "@/lib/catalog/listing-query";
import {
LISTING_KNOWN_TOTAL_PARAM,
listingViewFromSearchParams,
parseKnownTotal,
type ListingSurface,
} from "@/lib/catalog/listing-query";
import { loadListingView } from "@/lib/listing/load";

const SURFACES = new Set<ListingSurface>(["all", "category", "collection", "search"]);
Expand Down Expand Up @@ -46,6 +51,7 @@ export async function GET(request: NextRequest) {
channel,
slug,
view: listingViewFromSearchParams(url.searchParams),
knownTotal: parseKnownTotal(url.searchParams.get(LISTING_KNOWN_TOTAL_PARAM)),
});

if (!payload) {
Expand Down
5 changes: 4 additions & 1 deletion src/graphql/ProductListByCategoryProducts.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ query ProductListByCategoryProducts(
$sortBy: ProductOrder
$filter: ProductFilterInput
$where: ProductWhereInput
# False when the caller already has the total for these filters. Saleor counts the
# whole filtered set for `totalCount`, so skipping it saves that query.
$withTotal: Boolean = true
) {
category(slug: $slug) {
products(
Expand All @@ -33,7 +36,7 @@ query ProductListByCategoryProducts(
startCursor
endCursor
}
totalCount
totalCount @include(if: $withTotal)
}
}
}
5 changes: 4 additions & 1 deletion src/graphql/ProductListByCollectionProducts.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ query ProductListByCollectionProducts(
$sortBy: ProductOrder
$filter: ProductFilterInput
$where: ProductWhereInput
# False when the caller already has the total for these filters. Saleor counts the
# whole filtered set for `totalCount`, so skipping it saves that query.
$withTotal: Boolean = true
) {
collection(slug: $slug, channel: $channel) {
products(
Expand All @@ -32,7 +35,7 @@ query ProductListByCollectionProducts(
startCursor
endCursor
}
totalCount
totalCount @include(if: $withTotal)
}
}
}
5 changes: 4 additions & 1 deletion src/graphql/ProductListPaginated.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ query ProductListPaginated(
$sortBy: ProductOrder
$filter: ProductFilterInput
$where: ProductWhereInput
# False when the caller already has the total for these filters. Saleor counts the
# whole filtered set for `totalCount`, so skipping it saves that query.
$withTotal: Boolean = true
$search: String
) {
products(
Expand All @@ -21,7 +24,7 @@ query ProductListPaginated(
where: $where
search: $search
) {
totalCount
totalCount @include(if: $withTotal)
edges {
node {
...ProductListItem
Expand Down
32 changes: 32 additions & 0 deletions src/lib/catalog/listing-query.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ import { describe, expect, it } from "vitest";
import {
applyListingSearchParams,
isCanonicalListingView,
listingTotalKey,
listingViewFromSearchParams,
parseKnownTotal,
} from "./listing-query";

describe("isCanonicalListingView", () => {
Expand Down Expand Up @@ -55,3 +57,33 @@ describe("applyListingSearchParams", () => {
expect(target.get("sort")).toBeNull();
});
});

describe("listingTotalKey", () => {
it("ignores sort and paging, which do not change the total", () => {
const base = listingTotalKey({ colors: "blue" });
expect(listingTotalKey({ colors: "blue", sort: "price_asc" })).toBe(base);
expect(listingTotalKey({ colors: "blue", cursor: "WyIxIl0=", direction: "prev" })).toBe(base);
expect(listingTotalKey({ colors: "blue", page: "3" })).toBe(base);
});

it("changes with filters and search text", () => {
const base = listingTotalKey({ colors: "blue" });
expect(listingTotalKey({ colors: "red" })).not.toBe(base);
expect(listingTotalKey({ colors: "blue", sizes: "m" })).not.toBe(base);
expect(listingTotalKey({ colors: "blue", query: "tee" })).not.toBe(base);
expect(listingTotalKey({})).toBe("");
});
});

describe("parseKnownTotal", () => {
it("accepts a non-negative integer", () => {
expect(parseKnownTotal("0")).toBe(0);
expect(parseKnownTotal("1234")).toBe(1234);
});

it("ignores anything else, so the server counts", () => {
for (const raw of [null, "", "-1", "1.5", "12abc", "1e3", "99999999999999999999"]) {
expect(parseKnownTotal(raw)).toBeUndefined();
}
});
});
26 changes: 26 additions & 0 deletions src/lib/catalog/listing-query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,32 @@ export function listingViewKey(params: ListingViewParams): string {
return target.toString();
}

/** Listing params that change the total. Sort, cursor, direction, and page do not. */
const LISTING_TOTAL_KEYS = ["price", "colors", "sizes", "categories", "query"] as const;

/**
* Stable key of the params a total depends on. Two views with the same key have the
* same total, so paging or re-sorting can reuse the one the shopper already has.
*/
export function listingTotalKey(params: ListingViewParams): string {
const target = new URLSearchParams();
const view = listingViewFromRecord(params);
for (const key of LISTING_TOTAL_KEYS) {
const value = view[key];
if (typeof value === "string" && value) target.set(key, value);
}
return target.toString();
}

/** `/api/listing` param carrying the total the client already has for these filters. */
export const LISTING_KNOWN_TOTAL_PARAM = "total";

export function parseKnownTotal(raw: string | null): number | undefined {
if (raw == null || !/^\d+$/.test(raw)) return undefined;
const value = Number(raw);
return Number.isSafeInteger(value) ? value : undefined;
}

/** Append listing + identity keys onto a `/api/listing` URL. */
export function applyListingSearchParams(
target: URLSearchParams,
Expand Down
1 change: 1 addition & 0 deletions src/lib/listing/load.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export async function loadListingView(input: {
channel: string;
slug?: string;
view: ListingViewParams;
knownTotal?: number;
}): Promise<ListingPayload | null> {
const query = listingQueryFromInput(input);
if (!query) return null;
Expand Down
15 changes: 12 additions & 3 deletions src/lib/listing/policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,17 +28,26 @@ async function loadCachedTtl(providerId: string, query: ListingQuery): Promise<L
return getListingProvider(providerId).load(query);
}

function withoutKnownTotal(query: ListingQuery): ListingQuery {
const copy = { ...query };
delete copy.knownTotal;
return copy;
}

/**
* Listing data for one query. The provider is chosen from the surface.
* The query is normalized to the provider's sorts and pagination before the cache key.
* Canonical category, collection, and all-products grids are cached.
* Search, filters, and cursors are live so a provider cannot explode the cache key space.
* A cached entry always carries its own total: `knownTotal` is dropped before the cache
* key, so one shopper's count is never stored for everyone.
*/
export async function loadListing(input: ListingQuery): Promise<ListingResult | null> {
const provider = listingProviderFor(input.surface.kind);
const query = normalizeListingQuery(provider, input);
const mode = listingFetchMode(query, provider);
if (mode === "cached-saleor") return loadCachedSaleor(provider.id, query);
if (mode === "cached-ttl") return loadCachedTtl(provider.id, query);
return provider.load(query);
if (mode === "live") return provider.load(query);
const cacheable = withoutKnownTotal(query);
if (mode === "cached-saleor") return loadCachedSaleor(provider.id, cacheable);
return loadCachedTtl(provider.id, cacheable);
}
24 changes: 24 additions & 0 deletions src/lib/listing/providers/saleor/contract.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,30 @@ describe("saleor listing provider", () => {
expect(JSON.stringify(variables.where)).toContain('"colour"');
});

it("asks Saleor for the total when the caller does not have it", async () => {
const { provider, seen } = capture();
const result = await provider.load(categoryQuery);
expect(seen[0]?.withTotal).toBe(true);
expect(result?.total).toEqual({ value: CATALOG.length, exact: true });
});

it("skips Saleor's count and returns the known total", async () => {
const seen: Array<Record<string, unknown>> = [];
const provider = createSaleorListingProvider(async (input) => {
seen.push(input.variables);
const data = sliceConnection(input.variables);
// Saleor omits `totalCount` when `@include(if: $withTotal)` is false.
return { category: { products: { ...data.category!.products!, totalCount: undefined } } };
});
const result = await provider.load({
...categoryQuery,
page: { mode: "cursor", direction: "next", cursor: "12" },
knownTotal: 42,
});
expect(seen[0]?.withTotal).toBe(false);
expect(result?.total).toEqual({ value: 42, exact: true });
});

it("sends no search argument outside the search surface", async () => {
const { provider, seen } = capture();
await provider.load(categoryQuery);
Expand Down
3 changes: 2 additions & 1 deletion src/lib/listing/providers/saleor/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@ export function createSaleorListingProvider(
...(constraints.filter ? { filter: constraints.filter } : {}),
...(constraints.where ? { where: constraints.where } : {}),
...(search ? { search } : {}),
withTotal: query.knownTotal === undefined,
...graphqlLanguageCodeVariables(query.locale),
},
});
Expand All @@ -217,7 +218,7 @@ export function createSaleorListingProvider(
startCursor: connection?.pageInfo.startCursor,
endCursor: connection?.pageInfo.endCursor,
},
total: { value: connection?.totalCount ?? items.length, exact: true },
total: { value: query.knownTotal ?? connection?.totalCount ?? items.length, exact: true },
resolvedCategories,
} satisfies ListingResult;
},
Expand Down
2 changes: 2 additions & 0 deletions src/lib/listing/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export function listingQueryFromInput(input: {
slug?: string;
view: ListingViewParams;
pageSize?: number;
knownTotal?: number;
}): ListingQuery | null {
const view = listingViewFromRecord(input.view);
const selections: Record<string, string[]> = {};
Expand Down Expand Up @@ -87,5 +88,6 @@ export function listingQueryFromInput(input: {
sort: canonicalSortId(typeof view.sort === "string" ? view.sort : undefined),
page,
pageSize: input.pageSize ?? ProductsPerPage,
...(input.knownTotal !== undefined ? { knownTotal: input.knownTotal } : {}),
};
}
6 changes: 6 additions & 0 deletions src/lib/storefront/contract/listing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,12 @@ export type ListingQuery = {
sort?: SortId;
page: ListingPageRequest;
pageSize: number;
/**
* The total the caller already has for this surface, selections, range, and search
* text. Sort and page do not change it. A provider whose total costs a query (Saleor
* counts the whole filtered set) returns this value instead of counting again.
*/
knownTotal?: number;
};

/** Normalized product shape for listing cards. */
Expand Down
36 changes: 34 additions & 2 deletions src/ui/components/plp/use-listing-query.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
"use client";

import { useEffect, useMemo, useState } from "react";
import { useEffect, useMemo, useRef, useState } from "react";
import { useSearchParams } from "next/navigation";
import {
LISTING_KNOWN_TOTAL_PARAM,
applyListingSearchParams,
listingTotalKey,
listingViewFromSearchParams,
listingViewKey,
type ListingPageInfo,
Expand Down Expand Up @@ -51,6 +53,9 @@ const EMPTY_PAGE_INFO: ListingPageInfo = {
* Canonical URLs use the server-rendered first page. Any listing query fetches
* `/api/listing` and swaps the grid. Hide the grid until that fetch returns so
* a shared `?colors=` link does not flash the unfiltered HTML.
*
* Paging and re-sorting do not change the total, so the request carries the total
* already shown for the same filters and the server skips counting again.
*/
export function useListingQuery({
surface,
Expand All @@ -68,9 +73,16 @@ export function useListingQuery({
const view = useMemo(() => listingViewFromSearchParams(searchParams), [searchParams]);
const viewKey = listingViewKey(view);
const matchesServer = viewKey === initialViewKey;
const totalKey = listingTotalKey(view);
const serverTotalKey = useMemo(
() => listingTotalKey(listingViewFromSearchParams(new URLSearchParams(initialViewKey))),
[initialViewKey],
);

const [cache, setCache] = useState<{ key: string; payload: ListingPayload } | null>(null);
const [errorKey, setErrorKey] = useState<string | null>(null);
// Last total fetched on the client. A ref, so learning it does not refetch the view.
const fetchedTotal = useRef<{ key: string; total: number } | null>(null);

useEffect(() => {
if (matchesServer) return;
Expand All @@ -83,6 +95,13 @@ export function useListingQuery({
slug,
view,
});
const knownTotal =
totalKey === serverTotalKey
? initialTotalCount
: fetchedTotal.current?.key === totalKey
? fetchedTotal.current.total
: undefined;
if (knownTotal !== undefined) params.set(LISTING_KNOWN_TOTAL_PARAM, String(knownTotal));
const ac = new AbortController();
const key = viewKey;

Expand All @@ -92,6 +111,7 @@ export function useListingQuery({
return response.json() as Promise<ListingPayload>;
})
.then((payload) => {
fetchedTotal.current = { key: totalKey, total: payload.totalCount };
setCache({ key, payload });
setErrorKey((current) => (current === key ? null : current));
emitCommerceEvent({
Expand All @@ -108,7 +128,19 @@ export function useListingQuery({
});

return () => ac.abort();
}, [matchesServer, viewKey, surface, locale, channel, slug, view, providerId]);
}, [
matchesServer,
viewKey,
totalKey,
serverTotalKey,
initialTotalCount,
surface,
locale,
channel,
slug,
view,
providerId,
]);

if (matchesServer) {
return {
Expand Down
Loading