diff --git a/.env.example b/.env.example index fa5a4ca1..b1b05f8d 100644 --- a/.env.example +++ b/.env.example @@ -13,7 +13,6 @@ WEAVERSE_PROJECT_ID="" # PUBLIC_STOREFRONT_ID="" # PUBLIC_CHECKOUT_DOMAIN=".myshopify.com" # PUBLIC_CUSTOMER_ACCOUNT_API_CLIENT_ID="" -# PUBLIC_CUSTOMER_ACCOUNT_API_URL="https://shopify.com//account/customer/api" # SHOP_ID="" # Optional Weaverse configuration diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8753fa31..6a350440 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -27,15 +27,26 @@ jobs: run: npm ci --engine-strict --no-audit --no-fund - name: Static checks run: npm run check - - name: Generate GraphQL types - run: npm run codegen - name: Check types run: npm run typecheck + - name: Check combined-listing targets + run: node --test tests/combined-listing-target.unit.test.mjs + - name: Check authenticated cart handoff and Studio schema regressions + run: | + npx --no-install vite-node tests/cart-checkout-handoff.unit.test.ts + npx --no-install vite-node tests/weaverse-csp.unit.test.ts + npx --no-install vite-node tests/layout-fragments.unit.test.ts + npx --no-install vite-node tests/customer-auth-migration.unit.test.ts + npx --no-install vite-node tests/featured-collections-schema.unit.test.ts - name: Check Themivo wishlist regressions run: | npx --no-install vite-node tests/themivo-wishlist.unit.test.ts npx --no-install vite-node tests/themivo-products.unit.test.ts npx --no-install vite-node tests/themivo-appearance.unit.test.ts + - name: Check private wishlist analytics + run: | + npx --no-install playwright install --with-deps chromium + node --test tests/private-wishlist-analytics.browser.mjs - name: Check localization run: npm run locale:check && npm run i18n:test - name: Check sanitizer regressions diff --git a/.github/workflows/node22-support.yml b/.github/workflows/node22-support.yml index bdc312d0..32da4646 100644 --- a/.github/workflows/node22-support.yml +++ b/.github/workflows/node22-support.yml @@ -40,12 +40,10 @@ jobs: - name: Install from the committed lockfile run: npm ci --engine-strict --no-audit --no-fund - name: Verify the resolved dependency graph - run: npm ls @shopify/mini-oxygen sanitize-html @shopify/cli @graphql-codegen/cli vite-node body-parser undici vite esbuild framer-motion motion-dom motion-utils --all + run: npm ls @shopify/mini-oxygen sanitize-html @shopify/cli vite-node body-parser undici vite esbuild framer-motion motion-dom motion-utils --all # Repository scripts must resolve the tested local CLI. - name: Verify onboarding uses the pinned local CLI run: node -e "const assert = require('node:assert/strict'); const pinned = require('./package.json').devDependencies['@shopify/cli']; const resolved = require('./node_modules/@shopify/cli/package.json').version; console.log({pinned, resolved}); assert.equal(resolved, pinned, 'Onboarding must resolve the local pinned CLI, not a fetched one');" - - name: Generate GraphQL types - run: npm run codegen - name: Check types run: npm run typecheck - name: Check localization diff --git a/.gitignore b/.gitignore index 09cd245b..d685a8fa 100644 --- a/.gitignore +++ b/.gitignore @@ -24,3 +24,7 @@ pnpm-lock.yaml /scripts/get_weaverse_page.mjs /scripts/search_shopify_docs.mjs /scripts/search_weaverse_docs.mjs + +# Hydrogen GraphQL schema environments +storefront-graphql-env.d.ts +customer-account-graphql-env.d.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index c4a174f6..ca4202da 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,34 @@ # @weaverse/aspen +## Unreleased + +### Hydrogen 2026.10 and Weaverse v6 + +- Updated the storefront foundation to Hydrogen 2026.10 and Weaverse v6 while + retaining Aspen's page sections, theme settings, navigation and commerce UI. +- Migrated product selection, cart handlers, customer account queries, analytics + and section data loading to the new APIs. Preserved Aspen's queued cart + updates, inventory checks, discounts, gift cards and order notes. +- Reconciled cart buyer identity after Customer Account authorization, refresh + and logout; signed-out mutations explicitly clear old customer tokens, and + failed logout detachment expires the cart cookie. Account login redirects keep + order keys and other page parameters while stripping React Router metadata. + Temporary account refresh failures retain customer identity and allow cart + mutations to be retried. +- Moved collection browsing to Hydrogen's collection store. Existing filter and + sort links redirect to the new URL format; pagination supports forward and + backward navigation. Default collection ordering, combined category/facet + selections and missing-collection cursor recovery are preserved. +- Preserved locale-aware price formatting, translated merchant content, SEO, + image rendering and Studio component settings. +- Local development uses Vite/MiniOxygen, with HTTPS available through + `npm run dev:https`. Builds use React Router; `npm run typecheck` now checks + GraphQL documents as well as TypeScript. Node requirements remain + `^22.18.0 || ^24.11.0`. +- See [migration and verification notes](docs/hydrogen-2026-10-migration.md) + for deployment verification. A published release remains outstanding. + + ## 2026.11.12 This release brings together the Aspen updates since `v2026.6.12`, with a diff --git a/CLAUDE.md b/CLAUDE.md index 077b2d8e..3c65c9ee 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -5,14 +5,14 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co ## Development Commands ### Core Development -- `npm run dev` - Start development server on port 3456 with codegen -- `npm run dev:ca` - Start dev server with a tunnel and push its domain for the Customer Account API OAuth flow -- `npm run build` - Build for production with codegen +- `npm run dev` - Start Vite/MiniOxygen on port 3456 +- `npm run dev:ca` - Alias for local HTTPS development +- `npm run build` - Build the React Router client and Oxygen worker - `npm run preview` - Preview production build - `npm run start` - Start production server - `npm run typecheck` - Generate React Router types and run TypeScript type checking -- `npm run routes-check` - Verify all standard Shopify routes are configured -- `npm run codegen` - Generate GraphQL types and schema +- `npm run dev:https` - Start local HTTPS for Customer Account OAuth +- `npm run deploy` - Deploy the built client and worker to Oxygen ### Code Quality - `npm run check` - Run Oxfmt and Oxlint through `vp check` @@ -32,8 +32,8 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co This is a **Shopify Hydrogen storefront** built with **React Router v7** (not Remix) and integrated with **Weaverse** for visual page building. Key architectural decisions: ### Framework Stack -- **Hydrogen 2026.4** - Shopify's React framework for commerce -- **React Router 7.16** - Programmatic route configuration (NOT Remix - see import rules below) +- **Hydrogen 2026.10** - Shopify's React framework for commerce +- **React Router 7.18** - Programmatic route configuration (NOT Remix - see import rules below) - **Weaverse** - Visual page builder with component system - **Vite** - Build tool and dev server - **Vite+** - Oxlint and Oxfmt, without changing the Vite build @@ -83,10 +83,10 @@ import { useLoaderData, Link, Form } from '@remix-run/react'; ### GraphQL & Data Fetching - **Storefront API** for product/collection data -- **Generated types** in `storefront-api.generated.d.ts` (DO NOT edit directly) +- **Typed documents** use `gql()`; infer data from documents in `app/graphql/` - **Fragments** defined in `app/graphql/fragments.ts` - **Queries** in `app/graphql/queries.ts` -- **Regenerate types** with `npm run codegen` after schema changes +- **Validate documents** with `npm run typecheck` after GraphQL changes ### Testing Setup - **Playwright** for end-to-end testing @@ -127,7 +127,7 @@ export let schema = createSchema({ - `app/routes.ts` is the source of truth for the React Router route tree - Route modules live in `app/routes/` and must be explicitly referenced by `app/routes.ts` - Route filenames keep the established locale-aware naming convention, such as `($locale).products.$productHandle.tsx` -- Run `npm run routes-check` after changing the route tree +- Run `npm run typecheck` after changing the route tree ### Code Quality Standards - **TypeScript**: Strict mode disabled, but use types where beneficial @@ -154,7 +154,7 @@ Required environment variables: ### Updating GraphQL Schema 1. Modify queries in `app/graphql/` -2. Run `npm run codegen` +2. Run `npm run typecheck` 3. Update TypeScript types as needed ### Adding Theme Settings @@ -171,3 +171,15 @@ Required environment variables: - **Shopify Oxygen**: Native Hydrogen deployment platform - **Build command**: `npm run build` - **Environment**: Ensure all env vars are configured + +## Hydrogen 2026.10 migration contracts + +- Build request context in `app/.server/context.ts`; `server.ts` composes Shopify + handlers, React Router, session commit and response headers. +- Import Weaverse React Router APIs from `@weaverse/hydrogen/react-router`. +- Run Storefront queries with `storefront.graphql(gql(...), {variables, cache})`; + use `unwrapStorefront` where query errors should reach the route boundary. +- Aspen's queued cart UI and native `/cart` forms use the app-owned cart gateway; + `CartLibrarySync` refreshes Hydrogen's store after these custom mutations. +- Keep saved section types/settings, merchant content, responsive markup and + locale/currency behavior compatible. See `docs/hydrogen-2026-10-migration.md`. diff --git a/README.md b/README.md index 68a08dfc..3e2e1d6b 100644 --- a/README.md +++ b/README.md @@ -20,11 +20,11 @@ _Aspen is a sophisticated Shopify theme crafted specifically for home furniture ![Weaverse + Hydrogen + Shopify](https://cdn.shopify.com/s/files/1/0838/0052/3057/files/weaverse-x-hydrogen-x-shopify.png?v=1755245801) - React Router v7 -- Hydrogen 2026.4 +- Hydrogen 2026.10 - Oxygen - Shopify CLI - Vite+ checks (Oxlint and Oxfmt) -- GraphQL generator +- Typed GraphQL documents with gql.tada - TypeScript and JavaScript flavors - Tailwind CSS v4 (via Vite) - Radix UI components @@ -85,6 +85,8 @@ Aspen uses parallel data loading for optimal performance. Every route loads Weav ```ts:routes/($locale)._index.tsx import { data } from 'react-router'; +import { CACHE_DEFAULT } from '~/utils/cache'; +import { unwrapStorefront } from '~/utils/storefront'; import { type LoaderFunctionArgs } from 'react-router'; export async function loader({ context }: LoaderFunctionArgs) { @@ -92,7 +94,7 @@ export async function loader({ context }: LoaderFunctionArgs) { // Parallel data loading for best performance const [collections, weaverseData] = await Promise.all([ - storefront.query(COLLECTIONS_QUERY), + storefront.graphql(COLLECTIONS_QUERY, {cache: CACHE_DEFAULT}).then(unwrapStorefront), weaverse.loadPage({ type: 'INDEX' }), ]); @@ -105,43 +107,17 @@ export async function loader({ context }: LoaderFunctionArgs) { `weaverse` is a `WeaverseClient` instance that has been injected into the app context by Weaverse. It provides a set of methods to interact with the Weaverse API. -```ts:app/lib/context.ts -// app/lib/context.ts - -const hydrogenContext = createHydrogenContext( - { - env, - request, - cache, - waitUntil, - session, - i18n: getLocaleFromRequest(request), - cart: { - queryFragment: CART_QUERY_FRAGMENT, - }, - }, - {}, -); - -const weaverse = new WeaverseClient({ - ...hydrogenContext, - request, - cache, - themeSchema, - components, -}); - -Object.assign(hydrogenContext, { weaverse }); - -return hydrogenContext; -``` +The request-scoped clients are created in `app/.server/context.ts`. `server.ts` +composes Shopify handlers with React Router and applies the session and response +headers. See [migration notes](docs/hydrogen-2026-10-migration.md) for the new +request lifecycle. ### Rendering page content Weaverse pages is rendered using `` component. ```tsx:app/weaverse/index.tsx -import { WeaverseHydrogenRoot } from '@weaverse/hydrogen'; +import { WeaverseHydrogenRoot } from '@weaverse/hydrogen/react-router'; import { GenericError } from '~/components/generic-error'; import { components } from './components'; @@ -182,7 +158,7 @@ export async function loader({request, context}: RouteLoaderArgs) { And then you can use it in your components with `useThemeSettings` hook. ```tsx:app/weaverse/components/logo.tsx -import { useThemeSettings } from '@weaverse/hydrogen'; +import { useThemeSettings } from '@weaverse/hydrogen/react-router'; function Logo() { let {logo} = useThemeSettings(); @@ -198,7 +174,7 @@ function Logo() { The `App` component is wrapped with `withWeaverse` HoC in order to SSR the theme settings. ```tsx:root.tsx -import { withWeaverse } from '@weaverse/hydrogen'; +import { withWeaverse } from '@weaverse/hydrogen/react-router'; function App() { return ( @@ -215,16 +191,16 @@ export default withWeaverse(App); To create a section, you need to create a new file in [`app/sections`](app/sections) directory and register it in [`app/weaverse/components.ts`](app/weaverse/components.ts) file. -**Important:** All Weaverse sections must use `forwardRef` and extend `HydrogenComponentProps`. +**Important:** All Weaverse sections must use `forwardRef` and extend `WeaverseComponentProps`. ```tsx:app/sections/video/index.tsx -import type { - HydrogenComponentProps, +import { + type WeaverseComponentProps, createSchema, -} from '@weaverse/hydrogen'; +} from '@weaverse/hydrogen/react-router'; import { forwardRef } from 'react'; -interface VideoProps extends HydrogenComponentProps { +interface VideoProps extends WeaverseComponentProps { heading: string; description: string; videoUrl: string; @@ -300,16 +276,16 @@ What if your component needs to fetch data from Shopify API or any third-party A Just export a `loader` function from your component: ```tsx:app/sections/video/index.tsx (loader example) -import type { ComponentLoaderArgs } from '@weaverse/hydrogen'; - -export const loader = async ({ weaverse, data }: ComponentLoaderArgs) => { - const result = await weaverse.storefront.query( - HOMEPAGE_SEO_QUERY, - { - variables: { handle: data.collection.handle || 'frontpage' }, - }, - ); - return result.data; +import type { WeaverseComponentLoaderArgs } from '@weaverse/hydrogen/react-router'; +import { CACHE_DEFAULT } from '~/utils/cache'; +import { unwrapStorefront } from '~/utils/storefront'; + +export const loader = async ({ weaverse, data }: WeaverseComponentLoaderArgs) => { + // HOMEPAGE_SEO_QUERY is a gql() document from @shopify/hydrogen. + return weaverse.storefront.graphql(HOMEPAGE_SEO_QUERY, { + variables: {handle: data.collection.handle}, + cache: CACHE_DEFAULT, + }).then(unwrapStorefront); }; ``` @@ -320,7 +296,7 @@ Don't forget to register your new section in `app/weaverse/components.ts`: ```typescript import * as Video from "~/sections/video"; -export const components: HydrogenComponent[] = [ +export const components: WeaverseComponent[] = [ // ... existing components Video, ]; @@ -345,7 +321,7 @@ app/ └── weaverse/ # Weaverse configuration Key configuration files: -- codegen.ts # GraphQL code generation +- app/graphql/ # Typed gql() documents - react-router.config.ts # React Router configuration - vite.config.ts # Vite bundler and Vite+ static checks ``` @@ -363,8 +339,7 @@ Before committing, always run: ```bash npm run check # Check lint and formatting npm run check:fix # Format and apply safe lint fixes -npm run typecheck # Check TypeScript types -npm run codegen # Update GraphQL types +npm run typecheck # Validate TypeScript and GraphQL documents ``` ## References diff --git a/app/.server/cart-gateway.ts b/app/.server/cart-gateway.ts new file mode 100644 index 00000000..e738b4ee --- /dev/null +++ b/app/.server/cart-gateway.ts @@ -0,0 +1,282 @@ +import { + Cache, + type CartUpdatePayload, + createCartCookie, + getCartId, + gql, +} from "@shopify/hydrogen"; +import type { + CartBuyerIdentityInput, + CartInput, +} from "@shopify/hydrogen/storefront-api-types"; +import type { CartApiQueryFragment } from "~/graphql/storefront-types"; +import { CART_FRAGMENT, cartHandlers } from "./cart"; +import type { Storefront } from "./storefront"; + +export type CartMutationResult = { + cart?: CartApiQueryFragment | null; + userErrors?: Array<{ message: string; code?: string; field?: string[] }>; + errors?: Array<{ message: string }>; +}; +const BUYER = gql( + `mutation AspenCartBuyer($cartId: ID!, $buyerIdentity: CartBuyerIdentityInput!) { + cartBuyerIdentityUpdate(cartId: $cartId, buyerIdentity: $buyerIdentity) { + cart { + ...CartFragment + } + userErrors { + message + code + field + } + } +}`, + [CART_FRAGMENT], +); +const GIFT_ADD = gql( + `mutation AspenCartGiftAdd($cartId: ID!, $codes: [String!]!) { + cartGiftCardCodesAdd(cartId: $cartId, giftCardCodes: $codes) { + cart { + ...CartFragment + } + userErrors { + message + code + field + } + } +}`, + [CART_FRAGMENT], +); +const GIFT_REMOVE = gql( + `mutation AspenCartGiftRemove($cartId: ID!, $ids: [ID!]!) { + cartGiftCardCodesRemove(cartId: $cartId, appliedGiftCardIds: $ids) { + cart { + ...CartFragment + } + userErrors { + message + code + field + } + } +}`, + [CART_FRAGMENT], +); +const CREATE = gql( + `mutation AspenCartCreate($input: CartInput!) { + cartCreate(input: $input) { + cart { + ...CartFragment + } + userErrors { + message + code + field + } + } +}`, + [CART_FRAGMENT], +); + +/** Server gateway for Aspen's application-owned cart actions and permalinks. */ +export function createAspenCart({ + request, + storefront, + getCustomerAccessToken, +}: { + request: Request; + storefront: Storefront; + /** null is signed out; undefined is a transient account failure. */ + getCustomerAccessToken: () => Promise; +}) { + let id = getCartId(request); + function setCartId(cartId: string) { + id = cartId; + return new Headers({ "Set-Cookie": createCartCookie(cartId) }); + } + function withCheckoutHandoff( + cart: CartApiQueryFragment | null, + customerAccessToken: string | null | undefined, + ) { + if (!cart?.checkoutUrl || !customerAccessToken) { + return cart; + } + const checkoutUrl = new URL(cart.checkoutUrl); + checkoutUrl.searchParams.set("logged_in", "true"); + return { ...cart, checkoutUrl: checkoutUrl.toString() }; + } + // Mutation carts become the UI baseline without a root loader revalidation. + function mutationResult( + result: CartMutationResult, + customerAccessToken: string | null | undefined, + ): CartMutationResult { + if (!result.cart) { + return result; + } + return { + ...result, + cart: withCheckoutHandoff(result.cart, customerAccessToken), + }; + } + async function get() { + const headers = new Headers(request.headers); + const otherCookies = (headers.get("Cookie") || "") + .split(";") + .filter((cookie) => !cookie.trim().startsWith("cart=")); + if (id) otherCookies.push(`cart=${id.replace("gid://shopify/Cart/", "")}`); + headers.set("Cookie", otherCookies.join(";")); + const result = await cartHandlers.get({ + request: new Request(request.url, { headers }), + storefrontClient: storefront, + }); + if (result.data.errors?.length) + throw new Error(result.data.errors[0].message); + const cart = result.data.cart as CartApiQueryFragment | null; + return withCheckoutHandoff( + cart, + cart?.checkoutUrl ? await getCustomerAccessToken() : null, + ); + } + async function syncBuyerIdentity( + buyerIdentity: CartBuyerIdentityInput, + ): Promise { + const result = await storefront.graphql(BUYER, { + variables: { cartId: id, buyerIdentity }, + }); + return { ...result.data?.cartBuyerIdentityUpdate, errors: result.errors }; + } + async function updateBuyerIdentity( + buyerIdentity: CartBuyerIdentityInput, + ): Promise { + if (!id) return { cart: null, userErrors: [] }; + const token = await getCustomerAccessToken(); + return mutationResult(await syncBuyerIdentity(buyerIdentity), token); + } + async function getBuyerIdentity(): Promise< + CartBuyerIdentityInput | undefined + > { + const token = await getCustomerAccessToken(); + if (token === undefined) return undefined; + return { + countryCode: storefront.i18n.country, + customerAccessToken: token, + }; + } + function accountUnavailable(): CartMutationResult { + return { errors: [{ message: "errors.generic" }] }; + } + async function create(input: CartInput): Promise { + const buyerIdentity = await getBuyerIdentity(); + if (!buyerIdentity) return accountUnavailable(); + const result = await storefront.graphql(CREATE, { + variables: { + input: { + ...input, + buyerIdentity: { + ...buyerIdentity, + ...input.buyerIdentity, + }, + }, + }, + }); + if (result.data?.cartCreate?.cart?.id) id = result.data.cartCreate.cart.id; + return mutationResult( + { ...result.data?.cartCreate, errors: result.errors }, + buyerIdentity.customerAccessToken, + ); + } + async function mutate( + body: Record, + ): Promise { + const buyerIdentity = await getBuyerIdentity(); + if (!buyerIdentity) return accountUnavailable(); + // Keep market/customer binding current on writes, including cross-market + // navigation and sign-in/out; Shopify does not infer these from the URL. + if (id) { + const synced = await syncBuyerIdentity(buyerIdentity); + const missingCart = + synced.userErrors?.length && + synced.userErrors.every( + (error) => + error.code === "INVALID" && error.field?.includes("cartId"), + ); + if (body.intent === "add" && missingCart && !synced.errors?.length) + id = undefined; + else if (synced.userErrors?.length || synced.errors?.length) + return mutationResult(synced, buyerIdentity.customerAccessToken); + } + const headers = new Headers(request.headers); + headers.set("Content-Type", "application/json"); + const otherCookies = (headers.get("Cookie") || "") + .split(";") + .filter((cookie) => !cookie.trim().startsWith("cart=")); + if (id) otherCookies.push(`cart=${id.replace("gid://shopify/Cart/", "")}`); + headers.set("Cookie", otherCookies.join(";")); + const created = !id; + const result = await cartHandlers.post({ + storefrontClient: storefront, + request: new Request(new URL("/api/cart", request.url), { + method: "POST", + headers, + body: JSON.stringify(body), + }), + }); + if (result.type === "error") + return { userErrors: [{ message: result.error.message }] }; + if (result.type !== "json") throw new Error("Unexpected cart redirect"); + let payload = result.data as CartMutationResult; + if (payload.cart?.id) { + id = payload.cart.id; + if (created && body.intent === "add") { + const synced = await syncBuyerIdentity(buyerIdentity); + if (synced.cart) payload = { ...payload, cart: synced.cart }; + } + } + // Reuse the token resolved before writes; a later lookup can fail after + // Shopify has already applied the mutation. + return mutationResult(payload, buyerIdentity.customerAccessToken); + } + return { + get, + getCartId: () => id, + setCartId, + create, + updateBuyerIdentity, + addLines: (lines: CartUpdatePayload["lines"]) => + mutate({ intent: "add", lines }), + updateLines: (lines: CartUpdatePayload["lines"]) => + mutate({ intent: "update", lines }), + removeLines: (lineIds: string[]) => + mutate({ + intent: "remove", + // The JSON handler infers removal from zero-quantity lines. + lines: lineIds.map((id) => ({ id, quantity: 0 })), + }), + updateDiscountCodes: (discountCodes: string[]) => + mutate({ intent: "discount-update", discountCodes }), + updateNote: (note: string) => mutate({ intent: "note-update", note }), + async addGiftCardCodes(codes: string[]): Promise { + if (!id) return { cart: null, userErrors: [] }; + const token = await getCustomerAccessToken(); + const r = await storefront.graphql(GIFT_ADD, { + variables: { cartId: id, codes }, + }); + return mutationResult( + { ...r.data?.cartGiftCardCodesAdd, errors: r.errors }, + token, + ); + }, + async removeGiftCardCodes(ids: string[]): Promise { + if (!id) return { cart: null, userErrors: [] }; + const token = await getCustomerAccessToken(); + const r = await storefront.graphql(GIFT_REMOVE, { + variables: { cartId: id, ids }, + }); + return mutationResult( + { ...r.data?.cartGiftCardCodesRemove, errors: r.errors }, + token, + ); + }, + }; +} diff --git a/app/.server/cart.ts b/app/.server/cart.ts new file mode 100644 index 00000000..db24fc94 --- /dev/null +++ b/app/.server/cart.ts @@ -0,0 +1,246 @@ +import { createCartServerHandlers, gql } from "@shopify/hydrogen"; +import { getCustomerSession } from "./customer-account"; + +export const CART_FRAGMENT = gql(`fragment CartFragment on Cart { + updatedAt + id + appliedGiftCards { + id + lastCharacters + amountUsed { + amount + currencyCode + } + } + checkoutUrl + totalQuantity + buyerIdentity { + countryCode + customer { + id + email + firstName + lastName + displayName + } + email + phone + } + lines(first: 250) { + nodes { + ...AspenCartLine + ...AspenCartLineComponent + } + } + cost { + subtotalAmount { + amount + currencyCode + } + totalAmount { + amount + currencyCode + } + } + note + attributes { + key + value + } + discountCodes { + code + applicable + } +} + +fragment AspenCartLine on CartLine { + id + quantity + attributes { + key + value + } + discountAllocations { + discountedAmount { + amount + currencyCode + } + ... on CartCodeDiscountAllocation { + code + } + ... on CartAutomaticDiscountAllocation { + title + } + ... on CartCustomDiscountAllocation { + title + } + } + cost { + totalAmount { + amount + currencyCode + } + amountPerQuantity { + amount + currencyCode + } + compareAtAmountPerQuantity { + amount + currencyCode + } + } + sellingPlanAllocation { + sellingPlan { + id + name + description + recurringDeliveries + options { + name + value + } + } + } + merchandise { + ... on ProductVariant { + id + availableForSale + quantityAvailable + currentlyNotInStock + quantityRule { + minimum + maximum + increment + } + compareAtPrice { + amount + currencyCode + } + price { + amount + currencyCode + } + requiresShipping + title + image { + id + url + altText + width + height + } + product { + handle + title + id + vendor + } + selectedOptions { + name + value + } + } + } +} + +fragment AspenCartLineComponent on ComponentizableCartLine { + id + quantity + attributes { + key + value + } + discountAllocations { + discountedAmount { + amount + currencyCode + } + ... on CartCodeDiscountAllocation { + code + } + ... on CartAutomaticDiscountAllocation { + title + } + ... on CartCustomDiscountAllocation { + title + } + } + cost { + totalAmount { + amount + currencyCode + } + amountPerQuantity { + amount + currencyCode + } + compareAtAmountPerQuantity { + amount + currencyCode + } + } + merchandise { + ... on ProductVariant { + id + availableForSale + quantityAvailable + currentlyNotInStock + quantityRule { + minimum + maximum + increment + } + compareAtPrice { + amount + currencyCode + } + price { + amount + currencyCode + } + requiresShipping + title + image { + id + url + altText + width + height + } + product { + handle + title + id + vendor + } + selectedOptions { + name + value + } + requiresComponents + components(first: 10) { + nodes { + productVariant { + id + title + product { + handle + } + } + quantity + } + } + } + } +}`); +export const cartHandlers = createCartServerHandlers({ + fragment: CART_FRAGMENT, +}); + +/** Reuse the account session so /api/cart preserves authenticated checkout. */ +export function getCartHandlers(env: Env) { + return createCartServerHandlers({ + fragment: CART_FRAGMENT, + customerSession: getCustomerSession(env)?.session, + }); +} diff --git a/app/.server/context.ts b/app/.server/context.ts new file mode 100644 index 00000000..0cd35e5f --- /dev/null +++ b/app/.server/context.ts @@ -0,0 +1,65 @@ +import { WeaverseClient } from "@weaverse/hydrogen/react-router"; +import { loadStoreLocalization } from "~/utils/localization.server"; +import { components } from "~/weaverse/components"; +import { getThemeSchema } from "~/weaverse/schema.server"; +import { createAspenCart } from "./cart-gateway"; +import { createCustomerAccount } from "./customer-account"; +import { AppSession } from "./session"; +import { createRequestStorefront } from "./storefront"; + +export async function createAppLoadContext( + request: Request, + env: Env, + executionContext: ExecutionContext, +) { + if (!env.SESSION_SECRET) + throw new Error("SESSION_SECRET environment variable is not set"); + const waitUntil = executionContext.waitUntil.bind(executionContext); + const [cache, session] = await Promise.all([ + caches.open("hydrogen"), + AppSession.init(request, [env.SESSION_SECRET]), + ]); + const storedCountry = session.get("marketCountry"); + const storefront = createRequestStorefront({ + request, + env, + cache, + waitUntil, + marketCountry: + typeof storedCountry === "string" ? storedCountry : undefined, + }); + const customerAccount = createCustomerAccount({ + env, + request, + session, + storefront, + }); + const localization = await loadStoreLocalization(storefront, request); + const cart = createAspenCart({ + request, + storefront, + getCustomerAccessToken: customerAccount.getCartAccessToken, + }); + const weaverse = new WeaverseClient({ + storefront, + locale: localization.selectedLocale, + env, + cache, + waitUntil, + request, + customerAccount, + themeSchema: getThemeSchema(localization), + components, + }); + return { + env, + cache, + waitUntil, + session, + storefront, + customerAccount, + localization, + cart, + weaverse, + }; +} diff --git a/app/.server/customer-account.ts b/app/.server/customer-account.ts new file mode 100644 index 00000000..5dbd1364 --- /dev/null +++ b/app/.server/customer-account.ts @@ -0,0 +1,327 @@ +import { + createShopifyRouteHandler, + type ShopifyRouteHandlerContext, +} from "@shopify/hydrogen"; +import { + type AnyCustomerAccountDocument, + type CustomerAccountClient, + type CustomerAccountGqlRestParam, + type CustomerSession, + createCustomerAccountClient, + createCustomerAccountServerHandlers, + createCustomerSession, +} from "@shopify/hydrogen/customer-account"; +import { redirectDocument } from "react-router"; +import type { AppSession } from "~/.server/session"; +import { resolveRequestLocale, type Storefront } from "~/.server/storefront"; +import { + CUSTOMER_ACCESS_TOKEN_PATH, + customerAccountLoginPath, +} from "~/utils/customer-account"; +import { + stripLocalePrefix as delocalizePath, + prefixPathWithLocale as localizePath, +} from "~/utils/locale"; +import { EXPIRED_CART_COOKIE, syncCustomerCart } from "./customer-cart"; + +const CUSTOMER_ACCOUNT_HANDLER_PATH = + /^\/account\/(login|authorize|refresh|logout)$/; + +// Reused across requests in the same isolate, so concurrent token refreshes +// for one customer share a single request to Shopify. +let cached: + | { + key: string; + session: CustomerSession; + handlers: ReturnType; + } + | undefined; + +/** + * The shop's customer session, or `undefined` when Customer Accounts are not + * configured. `createCustomerSession` throws on a missing shop ID or client + * ID, and a storefront without accounts must keep serving pages. + */ +export function getCustomerSession(env: Env) { + if (!hasCustomerAccounts(env)) return undefined; + const key = `${env.SHOP_ID}:${env.PUBLIC_CUSTOMER_ACCOUNT_API_CLIENT_ID}`; + if (cached?.key !== key) { + const session = createCustomerSession({ + shopId: env.SHOP_ID, + customerAccountApiClientId: env.PUBLIC_CUSTOMER_ACCOUNT_API_CLIENT_ID, + }); + const handlers = createCustomerAccountServerHandlers({ + customerSession: session, + // A sign-in that carries no `return_to` lands on the account page. + defaultPostLoginRedirectPathname: "/account", + }); + cached = { key, session, handlers }; + } + return cached; +} + +let warnedInvalidShopId = false; + +/** Whether this storefront has Customer Accounts configured. */ +export function hasCustomerAccounts(env: Env) { + if (!env.SHOP_ID || !env.PUBLIC_CUSTOMER_ACCOUNT_API_CLIENT_ID) return false; + // `createCustomerSession` throws on a non-numeric shop ID; a misconfigured + // value must disable accounts, not take every page down with a 500. + if (!/^\d+$/.test(env.SHOP_ID)) { + if (!warnedInvalidShopId) { + warnedInvalidShopId = true; + console.warn( + `[customer-account] SHOP_ID must be the numeric shop ID; got "${env.SHOP_ID}". Customer Accounts are disabled.`, + ); + } + return false; + } + return true; +} + +/** + * The header's `` web component needs the customer's access + * token. It is fetched after hydration from this private, uncacheable + * endpoint and never rendered into the HTML, which stays anonymous so Oxygen + * can full-page cache it. Answers `null` when nobody is signed in or Customer + * Accounts are not configured. + */ +function customerAccessTokenHandler(customerSession?: CustomerSession) { + return createShopifyRouteHandler( + CUSTOMER_ACCESS_TOKEN_PATH, + "GET", + async ({ + sessionManager, + requestContext, + }: Pick< + ShopifyRouteHandlerContext, + "sessionManager" | "requestContext" + >) => { + const customerAccessToken = customerSession + ? await customerSession + .getOrRefreshAccessToken(sessionManager, requestContext) + .catch(() => undefined) + : undefined; + return { + type: "json", + data: { customerAccessToken: customerAccessToken ?? null }, + headers: { "Cache-Control": "private, no-store" }, + }; + }, + ); +} + +/** + * Aspen's Customer Account route handlers for `handleShopifyRoutes`: + * Hydrogen's `/account/login`, `/account/authorize`, `/account/refresh` and + * `/account/logout` (fixed and unprefixed; link to them with plain + * ``/`
`, never the router's ``/``), plus the header's + * access-token endpoint. Without Customer Accounts only the token endpoint is + * registered, answering `null`. + */ +export function getCustomerAccountHandlers(env: Env) { + const customer = getCustomerSession(env); + const accessToken = customerAccessTokenHandler(customer?.session); + if (!customer) return { accessToken }; + const { session, handlers } = customer; + function reconcile( + path: string, + method: string, + handler: ( + context: Parameters[0], + ) => ReturnType, + detach = false, + ) { + return createShopifyRouteHandler( + path, + method, + async (context: ShopifyRouteHandlerContext) => { + const result = await handler(context); + if (result.type !== "redirect") return result; + const token = detach + ? null + : await session.getAccessToken( + context.sessionManager, + context.requestContext, + ); + // A transient refresh leaves a refreshable session and its cart untouched. + if ( + !detach && + !token && + (await session.isLoggedIn( + context.sessionManager, + context.requestContext, + )) + ) + return result; + const synced = await syncCustomerCart( + context.request, + context.storefrontClient, + token ?? null, + ); + if (!synced && !token) { + const headers = new Headers(result.headers); + headers.append("Set-Cookie", EXPIRED_CART_COOKIE); + return { ...result, headers }; + } + return result; + }, + ); + } + return { + ...handlers, + authorize: reconcile("/account/authorize", "GET", handlers.authorize), + refresh: reconcile("/account/refresh", "GET", handlers.refresh), + logout: reconcile("/account/logout", "POST", handlers.logout, true), + accessToken, + }; +} + +/** + * The options of `customerAccount.graphql()`: the client's own, minus the + * access token the wrapper attaches. Optional when the document has no + * required variables. + */ +type GraphqlOptions = Omit< + CustomerAccountGqlRestParam[0], + "accessToken" +>; +type GraphqlRestParam = + object extends GraphqlOptions + ? [options?: GraphqlOptions] + : [options: GraphqlOptions]; + +/** + * The Customer Account API as Aspen's account routes use it. + * + * `graphql` attaches the customer's access token, refreshing it when needed + * (the refreshed tokens reach the browser because `server.ts` commits the + * session on every response). Without a session it throws a redirect to the + * login handler with a localized `return_to`, so a shopper bounced from + * `/fr-fr/account` signs in and comes back to the French market. + */ +export function createCustomerAccount({ + env, + request, + session, + storefront, +}: { + env: Env; + request: Request; + session: AppSession; + storefront: Storefront; +}) { + const requestContext = storefront.requestContext; + // The canonical market (public language), for URLs. `storefront.i18n` + // carries Shopify's provider language instead. + const market = resolveRequestLocale(request); + const customerSession = getCustomerSession(env)?.session; + let client: CustomerAccountClient | undefined; + + async function getAccessToken() { + return customerSession?.getOrRefreshAccessToken(session, requestContext); + } + + /** A null token means signed out; undefined means a refreshable session is unavailable. */ + async function getCartAccessToken(): Promise { + const token = await getAccessToken(); + if (token) return token; + return customerSession && + (await customerSession.isLoggedIn(session, requestContext)) + ? undefined + : null; + } + + /** + * Hydrogen's login handler lives at the unprefixed `/account/login`, so the + * market rides in `return_to` and `locale`. The redirect reloads the + * document: answering a `.data` request, a plain redirect would make React + * Router route `/account/login` client-side into the account catch-all + * instead of reaching the handler. + * + * `return_to` drops React Router's single-fetch `.data` suffix and `/_root` + * segment and a trailing slash, so it round-trips as a real page path. + */ + function loginRedirect() { + const url = new URL(request.url); + const path = url.pathname + .replace(/\/(?:_root|_)\.data$/, "/") + .replace(/\.data$/, "") + .replace(/\/_root$/, "/") + .replace(/(.+)\/$/, "$1"); + // Returning to a handler path (reached via a client-side `` that + // should have been a plain ``) would start another sign-in. + url.searchParams.delete("_routes"); + url.searchParams.delete("_data"); + const returnTo = CUSTOMER_ACCOUNT_HANDLER_PATH.test(delocalizePath(path)) + ? "/account" + : path + url.search; + return redirectDocument(customerAccountLoginPath(returnTo, market)); + } + + async function requireAccessToken() { + const accessToken = await getAccessToken(); + if (!accessToken) throw loginRedirect(); + return accessToken; + } + + return { + i18n: storefront.i18n, + async isLoggedIn() { + return customerSession + ? customerSession.isLoggedIn(session, requestContext) + : false; + }, + getAccessToken, + getCartAccessToken, + /** Throws a localized login redirect when the shopper has no session. */ + async handleAuthStatus() { + await requireAccessToken(); + }, + async graphql( + doc: Doc, + ...[options]: GraphqlRestParam + ) { + const accessToken = await requireAccessToken(); + client ??= createCustomerAccountClient({ + shopId: env.SHOP_ID, + requestContext, + }); + // `GraphqlRestParam` is the client's parameter minus `accessToken`; + // TypeScript cannot re-derive that for a generic `Doc`. + const rest = [ + { ...options, accessToken }, + ] as CustomerAccountGqlRestParam; + return client.graphql(doc, ...rest); + }, + /** + * Signs the shopper out without a form post and returns them to their + * market's home page: clears the customer session (committed by + * `server.ts`) and redirects through Shopify's logout when the session + * held an ID token. Used when the session turns out to be unusable. + * + * Shopify redirects to the home URL after clearing its own session, so + * every market's home URL must be registered as an allowed logout URI in + * the Customer Account API settings. + */ + async logout() { + const home = localizePath("/", market); + const destination = customerSession + ? await customerSession.logout(session, requestContext, { + postLogoutRedirectUri: home, + }) + : home; + const detached = await syncCustomerCart(request, storefront, null); + return redirectDocument( + destination, + detached + ? undefined + : { + headers: { "Set-Cookie": EXPIRED_CART_COOKIE }, + }, + ); + }, + }; +} + +export type CustomerAccount = ReturnType; diff --git a/app/.server/customer-cart.ts b/app/.server/customer-cart.ts new file mode 100644 index 00000000..1b9842eb --- /dev/null +++ b/app/.server/customer-cart.ts @@ -0,0 +1,38 @@ +import { + getCartId, + gql, + type ShopifyRouteHandlerContext, +} from "@shopify/hydrogen"; + +const BUYER_IDENTITY = + gql(`mutation AspenCustomerCartIdentity($cartId: ID!, $buyerIdentity: CartBuyerIdentityInput!) { + cartBuyerIdentityUpdate(cartId: $cartId, buyerIdentity: $buyerIdentity) { + cart { id } + userErrors { message } + } +}`); + +/** App-owned cart gateway also reconciles account changes made by native handlers. */ +export async function syncCustomerCart( + request: Request, + storefront: ShopifyRouteHandlerContext["storefrontClient"], + customerAccessToken: string | null, +): Promise { + const cartId = getCartId(request); + if (!cartId) return true; + try { + const result = await storefront.graphql(BUYER_IDENTITY, { + variables: { cartId, buyerIdentity: { customerAccessToken } }, + }); + return ( + !result.errors?.length && + !!result.data?.cartBuyerIdentityUpdate?.cart && + !result.data.cartBuyerIdentityUpdate.userErrors.length + ); + } catch { + return false; + } +} + +// Same cookie name/path as Hydrogen's cart cookie. Preserve other response cookies. +export const EXPIRED_CART_COOKIE = "cart=; Path=/; SameSite=Lax; Max-Age=0"; diff --git a/app/.server/market-redirect.ts b/app/.server/market-redirect.ts new file mode 100644 index 00000000..f8de5c25 --- /dev/null +++ b/app/.server/market-redirect.ts @@ -0,0 +1,107 @@ +import { + stripLocalePrefix as delocalizePath, + prefixPathWithLocale as localizePath, +} from "~/utils/locale"; +import { resolveRequestLocale as resolveLocaleFromRequest } from "./storefront"; + +/** Looks a redirect up in Shopify; `null` when none matches. */ +type LookupRedirect = (request: Request) => Promise; + +const SINGLE_FETCH_DATA_SUFFIX = ".data"; +const SINGLE_FETCH_ROOT_SEGMENT = "_root.data"; +const SINGLE_FETCH_TRAILING_SLASH_SEGMENT = "_.data"; + +/** + * The document path behind a React Router single-fetch request, and whether + * the request was one (a client-side navigation). + * + * `/collections/all.data` → `/collections/all`, `/_root.data` → `/`, and + * `/collections/_.data` → `/collections/` (a trailing-slash URL). + */ +function parseSingleFetchPathname(pathname: string) { + if (!pathname.endsWith(SINGLE_FETCH_DATA_SUFFIX)) { + return { pathname, isSoftNavigation: false }; + } + if (pathname.endsWith(`/${SINGLE_FETCH_TRAILING_SLASH_SEGMENT}`)) { + return { + pathname: pathname.slice(0, -SINGLE_FETCH_TRAILING_SLASH_SEGMENT.length), + isSoftNavigation: true, + }; + } + if (pathname.endsWith(`/${SINGLE_FETCH_ROOT_SEGMENT}`)) { + const prefix = pathname.slice(0, -SINGLE_FETCH_ROOT_SEGMENT.length); + return { pathname: prefix || "/", isSoftNavigation: true }; + } + return { + pathname: pathname.slice(0, -SINGLE_FETCH_DATA_SUFFIX.length), + isSoftNavigation: true, + }; +} + +/** + * Resolves a Shopify URL redirect for a request that the app answered with 404, + * keeping the shopper in the market they were already shopping. + * + * - **Markets.** Shopify stores URL redirects on market-neutral paths and + * `handleShopifyRedirects` matches the request path verbatim, so a localized + * URL never matches: `/collections/all` redirects on the default market + * while `/de-de/collections/all` 404s. The lookup is therefore delocalized + * and the target relocalized. + * - **Client-side navigations.** Hydrogen 2026.10 only matches document paths, + * while a `` to a redirected URL fetches `/old-path.data`. The lookup + * uses the document path, and a matched redirect is answered the way + * classic Hydrogen's `storefrontRedirect` did: `204` with + * `X-Remix-Redirect`, which React Router follows client-side. + * + * `lookup` is injected so this decision can be exercised without Shopify: it is + * `handleShopifyRedirects` bound to the storefront client in `server.ts`. + * Resolves `null` when the 404 should stand. + */ +export async function marketAwareRedirect( + request: Request, + lookup: LookupRedirect, +): Promise { + const locale = resolveLocaleFromRequest(request); + const url = new URL(request.url); + const { pathname, isSoftNavigation } = parseSingleFetchPathname(url.pathname); + const neutralPath = delocalizePath(pathname); + + // The default market's document paths are already neutral, so the plain + // lookup is both correct and one fewer `Request` allocation. + const lookupUrl = new URL(url); + lookupUrl.pathname = neutralPath; + const redirected = await lookup( + lookupUrl.pathname === url.pathname + ? request + : new Request(lookupUrl, request), + ); + const location = redirected?.headers.get("Location"); + if (!redirected || !location) { + return null; + } + + const target = new URL(location, url); + // An off-origin target is Shopify's own (checkout, admin); relocalizing it + // would rewrite someone else's URL. + const destination = + target.origin === url.origin + ? localizePath(target.pathname, locale) + target.search + target.hash + : target.toString(); + + // `Headers` overwrites on `set`; spreading into an object literal would + // append a second value and produce a comma-joined header. + const headers = new Headers(redirected.headers); + if (isSoftNavigation) { + headers.delete("Location"); + headers.set("X-Remix-Redirect", destination); + headers.set("X-Remix-Status", String(redirected.status)); + return new Response(null, { status: 204, headers }); + } + headers.set( + "Location", + target.origin === url.origin + ? new URL(destination, url).toString() + : destination, + ); + return new Response(null, { status: redirected.status, headers }); +} diff --git a/app/.server/session.ts b/app/.server/session.ts new file mode 100644 index 00000000..21ce064d --- /dev/null +++ b/app/.server/session.ts @@ -0,0 +1,88 @@ +import type { WritableCustomerSessionManager } from "@shopify/hydrogen/customer-account"; +import { + createCookieSessionStorage, + type Session, + type SessionStorage, +} from "react-router"; + +/** + * The signed cookie session that Customer Account handlers read and write. + * + * It implements Hydrogen's session-manager contract on top of React Router's + * cookie storage. The cookie is signed, not encrypted, and holds only the + * customer's OAuth state and tokens. It is committed once per response in + * `server.ts`, and only when something changed, so an anonymous page never + * gets a `Set-Cookie` that would make it uncacheable. + */ +export class AppSession implements WritableCustomerSessionManager { + isPending = false; + readonly #storage: SessionStorage; + readonly #session: Session; + readonly #origin: string; + + constructor(storage: SessionStorage, session: Session, origin: string) { + this.#storage = storage; + this.#session = session; + this.#origin = origin; + } + + static async init(request: Request, secrets: string[]) { + const storage = createCookieSessionStorage({ + cookie: { + name: "session", + httpOnly: true, + path: "/", + sameSite: "lax", + // Customer Account OAuth only runs over HTTPS; plain-HTTP local dev + // still needs a readable cookie for the rest of the session. + secure: new URL(request.url).protocol === "https:", + secrets, + }, + }); + const session = await storage + .getSession(request.headers.get("Cookie")) + .catch(() => storage.getSession()); + + return new AppSession(storage, session, new URL(request.url).origin); + } + + get(key: string) { + return this.getSessionItem(key); + } + + set(key: string, value: unknown) { + this.setSessionItem(key, value); + } + + unset(key: string) { + this.removeSessionItem(key); + } + + destroy() { + return this.#storage.destroySession(this.#session); + } + + getSessionOrigin() { + return this.#origin; + } + + getSessionItem(key: string) { + return this.#session.get(key); + } + + setSessionItem(key: string, value: unknown) { + this.isPending = true; + this.#session.set(key, value); + } + + removeSessionItem(key: string) { + this.isPending = true; + this.#session.unset(key); + } + + async commit() { + if (!this.isPending) return; + this.isPending = false; + return { "Set-Cookie": await this.#storage.commitSession(this.#session) }; + } +} diff --git a/app/.server/sitemap.ts b/app/.server/sitemap.ts new file mode 100644 index 00000000..e36b8d86 --- /dev/null +++ b/app/.server/sitemap.ts @@ -0,0 +1,319 @@ +import { gql } from "@shopify/hydrogen"; +import type { Storefront } from "~/.server/storefront"; +import { qualifyArticleSitemapItems } from "~/utils/blog-sitemap.server"; +import { CACHE_DEFAULT } from "~/utils/cache"; +import { unwrapStorefront } from "~/utils/storefront"; + +/** + * Local port of classic Hydrogen's `getSitemapIndex` / `getSitemap` (removed in + * Hydrogen 2026.10). Same queries, same XML byte for byte and same headers; + * queries run through `storefront.graphql` with the cache classic used + * implicitly (`CACHE_DEFAULT`). Options Aspen never passed (`types`, + * `customChildSitemaps`, `getChangeFreq`) are not ported, and `articles` pages + * are rendered by Aspen's own articles sitemap (see `routes/seo/sitemap-page`). + */ + +const SITEMAP_INDEX_PREFIX = ` + +`; +const SITEMAP_INDEX_SUFFIX = ` +`; +const SITEMAP_PREFIX = ` +`; +const SITEMAP_SUFFIX = ""; +const SITEMAP_HEADERS = { + "Content-Type": "application/xml", + "Cache-Control": `max-age=${60 * 60 * 24}`, +}; + +/** Resource types, in the order classic listed them in the index. */ +const SITEMAP_TYPES = [ + "products", + "pages", + "collections", + "metaObjects", + "articles", + "blogs", +] as const; + +export async function getSitemapIndex({ + storefront, + request, +}: { + storefront: Storefront; + request: Request; +}) { + let data = unwrapStorefront( + await storefront.graphql(SITEMAP_INDEX_QUERY, { cache: CACHE_DEFAULT }), + ); + let baseUrl = new URL(request.url).origin; + let body = + SITEMAP_INDEX_PREFIX + + SITEMAP_TYPES.map((type) => { + let resource = data[type]; + if (!resource) { + throw new Error( + `[h2:sitemap:error] No data found for type ${type}. Check types passed to \`getSitemapIndex\``, + ); + } + return getSitemapLinks(type, resource.pagesCount?.count ?? 0, baseUrl); + }).join("\n") + + SITEMAP_INDEX_SUFFIX; + return new Response(body, { headers: SITEMAP_HEADERS }); +} + +type GetLinkArgs = { + type: string; + baseUrl: string; + handle?: string; + locale?: string; +}; + +type SitemapItem = { handle: string; updatedAt?: string; type?: string }; + +export async function getSitemap({ + storefront, + request, + params, + getLink, + locales = [], + noItemsFallback = "/", +}: { + storefront: Storefront; + request: Request; + params: { type?: string; page?: string }; + /** Builds each resource URL (and its `hreflang` alternates when `locales` is set). */ + getLink: (args: GetLinkArgs) => string; + /** `hreflang` values to emit `xhtml:link` alternates for. */ + locales?: string[]; + /** Path listed when the page has no items. */ + noItemsFallback?: string; +}) { + if (!(params.type && params.page)) { + throw new Response("No data found", { status: 404 }); + } + let type = params.type; + let items = await fetchSitemapItems( + storefront, + type, + Number.parseInt(params.page, 10), + ); + if (!items) { + throw new Response("Not found", { status: 404 }); + } + let baseUrl = new URL(request.url).origin; + let body = ""; + if (items.length) { + body = + SITEMAP_PREFIX + + items + .map((item) => + renderUrlTag({ + url: getLink({ + type: item.type ?? type, + baseUrl, + handle: item.handle, + }), + type: item.type ?? type, + getLink, + updatedAt: item.updatedAt, + handle: item.handle, + locales, + baseUrl, + }), + ) + .join("\n") + + SITEMAP_SUFFIX; + } else { + body = `${SITEMAP_PREFIX} + ${baseUrl + noItemsFallback} +${SITEMAP_SUFFIX}`; + } + return new Response(body, { headers: SITEMAP_HEADERS }); +} + +/** The page's items, or `undefined` for an unknown resource type. */ +async function fetchSitemapItems( + storefront: Storefront, + type: string, + page: number, +): Promise { + let options = { variables: { page }, cache: CACHE_DEFAULT }; + switch (type) { + case "articles": + return qualifyArticleSitemapItems( + storefront, + unwrapStorefront( + await storefront.graphql(ARTICLE_SITEMAP_QUERY, options), + ).sitemap.resources?.items ?? [], + ); + case "products": + return ( + unwrapStorefront( + await storefront.graphql(PRODUCT_SITEMAP_QUERY, options), + ).sitemap.resources?.items ?? [] + ); + case "collections": + return ( + unwrapStorefront( + await storefront.graphql(COLLECTION_SITEMAP_QUERY, options), + ).sitemap.resources?.items ?? [] + ); + case "pages": + return ( + unwrapStorefront(await storefront.graphql(PAGE_SITEMAP_QUERY, options)) + .sitemap.resources?.items ?? [] + ); + case "blogs": + return ( + unwrapStorefront(await storefront.graphql(BLOG_SITEMAP_QUERY, options)) + .sitemap.resources?.items ?? [] + ); + case "metaObjects": + return ( + unwrapStorefront( + await storefront.graphql(METAOBJECT_SITEMAP_QUERY, options), + ).sitemap.resources?.items ?? [] + ); + default: + return; + } +} + +function getSitemapLinks(resource: string, count: number, baseUrl: string) { + let links = ""; + for (let i = 1; i <= count; i++) { + links += ` ${baseUrl}/sitemap/${resource}/${i}.xml +`; + } + return links; +} + +function renderUrlTag({ + url, + updatedAt, + locales, + type, + getLink, + baseUrl, + handle, +}: { + url: string; + updatedAt?: string; + locales: string[]; + type: string; + getLink: (args: GetLinkArgs) => string; + baseUrl: string; + handle: string; +}) { + return ` + ${url} + ${updatedAt ? `${updatedAt}` : ""} + weekly +${locales + .map((locale) => + renderAlternateTag(getLink({ type, baseUrl, handle, locale }), locale), + ) + .join("\n")} + + `.trim(); +} + +function renderAlternateTag(url: string, locale: string) { + return ` `; +} + +const SITEMAP_INDEX_QUERY = gql(`query SitemapIndex { + products: sitemap(type: PRODUCT) { + pagesCount { + count + } + } + collections: sitemap(type: COLLECTION) { + pagesCount { + count + } + } + articles: sitemap(type: ARTICLE) { + pagesCount { + count + } + } + pages: sitemap(type: PAGE) { + pagesCount { + count + } + } + blogs: sitemap(type: BLOG) { + pagesCount { + count + } + } + metaObjects: sitemap(type: METAOBJECT) { + pagesCount { + count + } + } +}`); + +const PRODUCT_SITEMAP_QUERY = gql(`query SitemapProducts($page: Int!) { + sitemap(type: PRODUCT) { + resources(page: $page) { + items { + handle + updatedAt + } + } + } +}`); + +const COLLECTION_SITEMAP_QUERY = gql(`query SitemapCollections($page: Int!) { + sitemap(type: COLLECTION) { + resources(page: $page) { + items { + handle + updatedAt + } + } + } +}`); + +const PAGE_SITEMAP_QUERY = gql(`query SitemapPages($page: Int!) { + sitemap(type: PAGE) { + resources(page: $page) { + items { + handle + updatedAt + } + } + } +}`); + +const BLOG_SITEMAP_QUERY = gql(`query SitemapBlogs($page: Int!) { + sitemap(type: BLOG) { + resources(page: $page) { + items { + handle + updatedAt + } + } + } +}`); + +const METAOBJECT_SITEMAP_QUERY = gql(`query SitemapMetaobjects($page: Int!) { + sitemap(type: METAOBJECT) { + resources(page: $page) { + items { + handle + updatedAt + ... on SitemapResourceMetaobject { + type + } + } + } + } +}`); + +const ARTICLE_SITEMAP_QUERY = gql( + `query SitemapArticles($page: Int!) { sitemap(type: ARTICLE) { resources(page: $page) { items { ... on SitemapResourceInterface { handle updatedAt } } } } }`, +); diff --git a/app/.server/storefront.ts b/app/.server/storefront.ts new file mode 100644 index 00000000..cde258bd --- /dev/null +++ b/app/.server/storefront.ts @@ -0,0 +1,144 @@ +import { + type CacheInstance, + type CachingStrategy, + createShopifyRequestContext, + createStorefrontClient, + type PublicStorefrontClient, + type RequestScopedPrivateStorefrontClient, + type ShopifyRequestContext, +} from "@shopify/hydrogen"; +import type { I18nLocale as Locale } from "~/types/locale"; +import { getRequestI18n } from "~/utils/localization.server"; + +const resolveLocale = (pathname: string): Locale => + getRequestI18n(new Request(new URL(pathname, "https://aspen.local"))); + +// The bare client types default their per-call options to `{}`, which drops +// `cache` from `graphql()`. Every Aspen query passes one, so carry it here. +type StorefrontCallOptions = { cache?: CachingStrategy }; + +/** The request's market, with Shopify's provider language as `language`. */ +export type StorefrontI18n = Locale & { pathPrefix: string }; + +export type Storefront = ( + | RequestScopedPrivateStorefrontClient + | PublicStorefrontClient +) & { i18n: StorefrontI18n }; + +/** + * Paths Hydrogen's request handlers own. They are matched exactly and never + * carry a market prefix, so the market comes from the page that called them. + */ +const UNPREFIXED_HANDLER_PATH = /^\/(api\/|account\/(login|logout|refresh)$)/; + +/** + * The market a request is served in. + * + * Page requests carry the market in their path. Hydrogen-owned endpoints + * (`/api/cart`, `/api/predictive-search`, the Customer Account login and + * logout) are always unprefixed, so for those the market is read from the + * same-origin `Referer` instead, as Aspen's `/cart` action already did. A + * missing or foreign `Referer` falls back to the default market. + */ +export function resolveRequestLocale(request: Request): Locale { + const url = new URL(request.url); + if (!UNPREFIXED_HANDLER_PATH.test(url.pathname)) { + return resolveLocale(url.pathname); + } + // A login link carries the shopper's page in `return_to`, which survives + // the redirects into `/account/login` more reliably than the `Referer`. + if (url.pathname === "/account/login") { + const returnTo = url.searchParams.get("return_to"); + if (returnTo?.startsWith("/") && !returnTo.startsWith("//")) { + return resolveLocale(new URL(returnTo, url).pathname); + } + } + const referer = request.headers.get("Referer"); + if (!referer) return resolveLocale("/"); + try { + const source = new URL(referer); + return resolveLocale(source.origin === url.origin ? source.pathname : "/"); + } catch { + return resolveLocale("/"); + } +} + +// Oxygen sets `oxygen-buyer-ip`; the others cover local dev behind a proxy. +const BUYER_IP_HEADERS = [ + "oxygen-buyer-ip", + "cf-connecting-ip", + "x-forwarded-for", +] as const; +const DEVELOPMENT_BUYER_IP = "127.0.0.1"; + +function getBuyerIp(headers: Headers): string | undefined { + for (const header of BUYER_IP_HEADERS) { + const ip = headers.get(header)?.split(",")[0]?.trim(); + if (ip) return ip; + } + return process.env.NODE_ENV === "production" + ? undefined + : DEVELOPMENT_BUYER_IP; +} + +/** + * The request-scoped Storefront API client. + * + * Oxygen injects `PRIVATE_STOREFRONT_API_TOKEN` for a linked storefront; the + * private client then forwards the buyer's IP for Shopify's bot protection. + * Without a private token, or without a trusted buyer IP, the public token is + * used, so a merchant running Aspen locally with only the public token keeps a + * working store. + */ +export function createRequestStorefront({ + request, + env, + cache, + waitUntil, + marketCountry, +}: { + request: Request; + marketCountry?: string; + env: Env; + cache: CacheInstance; + waitUntil: ExecutionContext["waitUntil"]; +}): Storefront { + const resolved = resolveRequestLocale(request); + const locale = getRequestI18n( + new Request(new URL(resolved.pathPrefix || "/", request.url)), + marketCountry, + ); + const buyerIp = getBuyerIp(request.headers); + const config = { + storeDomain: env.PUBLIC_STORE_DOMAIN, + storefrontId: env.PUBLIC_STOREFRONT_ID || undefined, + cache, + waitUntil, + }; + + if (env.PRIVATE_STOREFRONT_API_TOKEN && buyerIp) { + return createStorefrontClient({ + type: "private", + requestContext: createShopifyRequestContext({ + request, + i18n: locale, + buyerIp, + }), + config: { + ...config, + privateStorefrontToken: env.PRIVATE_STOREFRONT_API_TOKEN, + }, + }) as Storefront; + } + + return createStorefrontClient({ + type: "public", + requestContext: createShopifyRequestContext({ request, i18n: locale }), + config: { + ...config, + publicStorefrontToken: env.PUBLIC_STOREFRONT_API_TOKEN || undefined, + }, + }) as Storefront; +} + +export type StorefrontRequestContext = ShopifyRequestContext; diff --git a/app/components/background-image.tsx b/app/components/background-image.tsx index d91d7a93..56e25c45 100644 --- a/app/components/background-image.tsx +++ b/app/components/background-image.tsx @@ -1,8 +1,11 @@ -import { Image } from "@shopify/hydrogen"; -import type { InspectorGroup, WeaverseImage } from "@weaverse/hydrogen"; -import { useTranslation } from "@weaverse/hydrogen"; +import type { + InspectorGroup, + WeaverseImage, +} from "@weaverse/hydrogen/react-router"; +import { useTranslation } from "@weaverse/hydrogen/react-router"; import type { VariantProps } from "class-variance-authority"; import { cva } from "class-variance-authority"; +import { Image } from "~/components/shopify-image"; const variants = cva("absolute inset-0 z-[-1] h-full w-full", { variants: { diff --git a/app/components/cart/cart-action-form.tsx b/app/components/cart/cart-action-form.tsx new file mode 100644 index 00000000..69604287 --- /dev/null +++ b/app/components/cart/cart-action-form.tsx @@ -0,0 +1,68 @@ +import type { ReactNode } from "react"; +import { type FetcherWithComponents, useFetcher } from "react-router"; + +// Aspen's queued cart controls use a shared form envelope on the app-owned +// /cart action. Keep that envelope while executing mutations with the new +// Hydrogen handlers; this also preserves native form submissions. +type FormInputs = Record & { + lines?: Array<{ id?: string; merchandiseId?: string; quantity?: number }>; +}; +export function CartForm({ + children, + action, + inputs, + route, + fetcherKey, +}: { + children: + | ReactNode + | ((fetcher: FetcherWithComponents) => ReactNode); + action?: string; + inputs?: FormInputs; + route?: string; + fetcherKey?: string; +}) { + const fetcher = useFetcher({ key: fetcherKey }); + return ( + + {(action || inputs) && ( + + )} + {typeof children === "function" ? children(fetcher) : children} + + ); +} +CartForm.INPUT_NAME = "cartFormInput"; +CartForm.ACTIONS = { + AttributesUpdateInput: "AttributesUpdateInput", + BuyerIdentityUpdate: "BuyerIdentityUpdate", + Create: "Create", + DiscountCodesUpdate: "DiscountCodesUpdate", + GiftCardCodesAdd: "GiftCardCodesAdd", + GiftCardCodesRemove: "GiftCardCodesRemove", + LinesAdd: "LinesAdd", + LinesRemove: "LinesRemove", + LinesUpdate: "LinesUpdate", + NoteUpdate: "NoteUpdate", +} as const; +CartForm.getFormInput = ( + form: FormData, +): { action?: string; inputs: FormInputs } => { + const envelope = form.get(CartForm.INPUT_NAME); + const raw: unknown = envelope ? JSON.parse(String(envelope)) : {}; + if (!raw || typeof raw !== "object" || Array.isArray(raw)) + throw new Error("Invalid cart form"); + const parsed = raw as { action?: string; inputs?: FormInputs }; + const inputs: FormInputs = { ...parsed.inputs }; + for (const key of new Set(form.keys())) { + if (key === CartForm.INPUT_NAME) continue; + const values = form.getAll(key); + const value = values.length > 1 ? values : values[0]; + inputs[key] = value === "on" ? true : value === "off" ? false : value; + } + return { action: parsed.action, inputs }; +}; diff --git a/app/components/cart/cart-baseline.ts b/app/components/cart/cart-baseline.ts index ab0f07c0..347e1e4d 100644 --- a/app/components/cart/cart-baseline.ts +++ b/app/components/cart/cart-baseline.ts @@ -1,5 +1,5 @@ import type { Fetcher } from "react-router"; -import type { CartApiQueryFragment } from "storefront-api.generated"; +import type { CartApiQueryFragment } from "~/graphql/storefront-types"; import type { CartMutationResponse } from "./cart-types"; let freshestFetcherCart: CartApiQueryFragment | null = null; diff --git a/app/components/cart/cart-best-sellers.tsx b/app/components/cart/cart-best-sellers.tsx index 16a013df..ce8ac249 100644 --- a/app/components/cart/cart-best-sellers.tsx +++ b/app/components/cart/cart-best-sellers.tsx @@ -3,14 +3,14 @@ import type { Product, ProductSortKeys, } from "@shopify/hydrogen/storefront-api-types"; -import { useTranslation } from "@weaverse/hydrogen"; +import { useTranslation } from "@weaverse/hydrogen/react-router"; import clsx from "clsx"; import { useEffect, useId, useMemo, useRef, useState } from "react"; -import type { ProductCardFragment } from "storefront-api.generated"; import { ArrowButton } from "~/components/arrow-button"; import { Link } from "~/components/link"; import { ProductCard } from "~/components/product/product-card"; import { Skeleton } from "~/components/skeleton"; +import type { ProductCardFragment } from "~/graphql/storefront-types"; import { usePrefixPathWithLocale } from "~/hooks/use-prefix-path-with-locale"; import { useTranslatedText } from "~/hooks/use-translated-text"; diff --git a/app/components/cart/cart-code-form.tsx b/app/components/cart/cart-code-form.tsx index 9b7b3bb7..2c6c1ba0 100644 --- a/app/components/cart/cart-code-form.tsx +++ b/app/components/cart/cart-code-form.tsx @@ -1,8 +1,8 @@ -import { CartForm } from "@shopify/hydrogen"; -import { useTranslation } from "@weaverse/hydrogen"; +import { useTranslation } from "@weaverse/hydrogen/react-router"; import { useId, useRef, useState } from "react"; import { useFetcher } from "react-router"; import { Button } from "~/components/button"; +import { CartForm } from "~/components/cart/cart-action-form"; import { usePrefixPathWithLocale } from "~/hooks/use-prefix-path-with-locale"; import { CART_CODE_APPLY_ACTION, uppercaseCartCode } from "~/utils/cart-code"; import { getCartMutationError } from "~/utils/cart-error"; diff --git a/app/components/cart/cart-library-sync.tsx b/app/components/cart/cart-library-sync.tsx new file mode 100644 index 00000000..2751bff3 --- /dev/null +++ b/app/components/cart/cart-library-sync.tsx @@ -0,0 +1,27 @@ +import { useEffect, useRef } from "react"; +import { useFetchers } from "react-router"; +import { CartAnalytics } from "~/components/root/analytics-views"; +import { useCartActions } from "./cart-store"; + +/** Reconcile app-owned queued mutations with Hydrogen's cart and analytics store. */ +export function CartLibrarySync() { + const fetchers = useFetchers(); + const { refresh } = useCartActions(); + const seen = useRef(new WeakSet()); + useEffect(() => { + let changed = false; + for (const f of fetchers) { + if ( + f.state === "submitting" || + !f.data || + typeof f.data !== "object" || + seen.current.has(f.data) + ) + continue; + seen.current.add(f.data); + if ("cart" in f.data) changed = true; + } + if (changed) refresh(); + }, [fetchers, refresh]); + return ; +} diff --git a/app/components/cart/cart-line-item.tsx b/app/components/cart/cart-line-item.tsx index f5979348..96e89bd2 100644 --- a/app/components/cart/cart-line-item.tsx +++ b/app/components/cart/cart-line-item.tsx @@ -1,11 +1,11 @@ import { Tag, X } from "@phosphor-icons/react"; -import { Money } from "@shopify/hydrogen"; -import { useTranslation } from "@weaverse/hydrogen"; +import { useTranslation } from "@weaverse/hydrogen/react-router"; import clsx from "clsx"; -import type { CartApiQueryFragment } from "storefront-api.generated"; import { Image } from "~/components/image"; import { Link } from "~/components/link"; +import { Money } from "~/components/money"; import { SubscriptionLineItem } from "~/components/subscriptions/subscription-line-item"; +import type { CartApiQueryFragment } from "~/graphql/storefront-types"; import { calculateAspectRatio } from "~/utils/image"; import { toggleCartDrawer } from "../layout/cart-drawer"; import { CartLineQuantityAdjust } from "./cart-line-qty-adjust"; diff --git a/app/components/cart/cart-line-qty-adjust.tsx b/app/components/cart/cart-line-qty-adjust.tsx index 6f147ff6..c9d1e0fd 100644 --- a/app/components/cart/cart-line-qty-adjust.tsx +++ b/app/components/cart/cart-line-qty-adjust.tsx @@ -1,4 +1,4 @@ -import { useTranslation } from "@weaverse/hydrogen"; +import { useTranslation } from "@weaverse/hydrogen/react-router"; import { cn } from "~/utils/cn"; import type { CartLine } from "./cart-types"; import { CART_DRAWER_QUANTITY_SIZE_CLASS } from "./drawer-frame"; diff --git a/app/components/cart/cart-main.tsx b/app/components/cart/cart-main.tsx index c6dcf451..5790a96e 100644 --- a/app/components/cart/cart-main.tsx +++ b/app/components/cart/cart-main.tsx @@ -1,11 +1,11 @@ import * as Dialog from "@radix-ui/react-dialog"; -import { Money } from "@shopify/hydrogen"; -import { useTranslation } from "@weaverse/hydrogen"; +import { useTranslation } from "@weaverse/hydrogen/react-router"; import clsx from "clsx"; import { useRef, useState } from "react"; import useScroll from "react-use/esm/useScroll"; -import type { CartApiQueryFragment } from "storefront-api.generated"; import { Link } from "~/components/link"; +import { Money } from "~/components/money"; +import type { CartApiQueryFragment } from "~/graphql/storefront-types"; import { useTranslatedThemeSettings } from "~/hooks/use-translated-theme-settings"; import { getCartMutationError } from "~/utils/cart-error"; import { CartBestSellers } from "./cart-best-sellers"; diff --git a/app/components/cart/cart-page-note.tsx b/app/components/cart/cart-page-note.tsx index 0631e933..d4359273 100644 --- a/app/components/cart/cart-page-note.tsx +++ b/app/components/cart/cart-page-note.tsx @@ -1,5 +1,4 @@ -import { CartForm, Image } from "@shopify/hydrogen"; -import { useTranslation } from "@weaverse/hydrogen"; +import { useTranslation } from "@weaverse/hydrogen/react-router"; import { AnimatePresence, motion, @@ -9,6 +8,8 @@ import { import { type ReactNode, useEffect, useId, useRef, useState } from "react"; import { useFetcher } from "react-router"; import { Button } from "~/components/button"; +import { CartForm } from "~/components/cart/cart-action-form"; +import { Image } from "~/components/shopify-image"; import { usePrefixPathWithLocale } from "~/hooks/use-prefix-path-with-locale"; import { getCartMutationError } from "~/utils/cart-error"; import { CART_ACTION_DESKTOP_HOVER } from "./cart-action-styles"; diff --git a/app/components/cart/cart-store.ts b/app/components/cart/cart-store.ts new file mode 100644 index 00000000..894e0733 --- /dev/null +++ b/app/components/cart/cart-store.ts @@ -0,0 +1,20 @@ +import type { CartDataFromHandlers } from "@shopify/hydrogen"; +import { createCartComponents } from "@shopify/hydrogen/react"; +import type { cartHandlers } from "~/.server/cart"; + +/** The cart as Aspen's cart query returns it (Hydrogen's fields + `CartFragment`). */ +export type CartData = CartDataFromHandlers; +export type CartLineData = CartData["lines"]["nodes"][number]; + +/** + * Hydrogen's cart store bindings, typed with Aspen's cart fragment. + * + * `CartProvider` is rendered once in `app/root.tsx` without server + * `initialData`, so documents stay anonymous and full-page cacheable; the + * store loads `/api/cart` after hydration. + */ +export const { + CartProvider, + useCart: useLibraryCart, + useCartActions, +} = createCartComponents(); diff --git a/app/components/cart/cart-summary-actions.tsx b/app/components/cart/cart-summary-actions.tsx index 4eaa324f..9d6f6e2c 100644 --- a/app/components/cart/cart-summary-actions.tsx +++ b/app/components/cart/cart-summary-actions.tsx @@ -1,12 +1,12 @@ import { XIcon } from "@phosphor-icons/react"; import * as Dialog from "@radix-ui/react-dialog"; -import { CartForm } from "@shopify/hydrogen"; -import { useTranslation } from "@weaverse/hydrogen"; +import { useTranslation } from "@weaverse/hydrogen/react-router"; import { AnimatePresence, motion } from "framer-motion"; import { useEffect, useState } from "react"; import { useFetcher } from "react-router"; -import type { CartApiQueryFragment } from "storefront-api.generated"; import { Button } from "~/components/button"; +import { CartForm } from "~/components/cart/cart-action-form"; +import type { CartApiQueryFragment } from "~/graphql/storefront-types"; import { usePrefixPathWithLocale } from "~/hooks/use-prefix-path-with-locale"; import { uppercaseCartCode } from "~/utils/cart-code"; import { getCartMutationError } from "~/utils/cart-error"; diff --git a/app/components/cart/cart-summary.tsx b/app/components/cart/cart-summary.tsx index afba9580..5716436c 100644 --- a/app/components/cart/cart-summary.tsx +++ b/app/components/cart/cart-summary.tsx @@ -1,13 +1,14 @@ import { Tag, Truck, X } from "@phosphor-icons/react"; -import { CartForm, Money } from "@shopify/hydrogen"; -import { useTranslation } from "@weaverse/hydrogen"; +import { useTranslation } from "@weaverse/hydrogen/react-router"; import clsx from "clsx"; import { useFetcher } from "react-router"; -import type { CartApiQueryFragment } from "storefront-api.generated"; import { Button } from "~/components/button"; +import { CartForm } from "~/components/cart/cart-action-form"; import { Link } from "~/components/link"; import { LoyaltyPointsHint } from "~/components/loyalty/loyalty-points-hint"; +import { Money } from "~/components/money"; import { ProgressBar } from "~/components/progress-bar"; +import type { CartApiQueryFragment } from "~/graphql/storefront-types"; import { usePrefixPathWithLocale } from "~/hooks/use-prefix-path-with-locale"; import { useTranslatedThemeSettings } from "~/hooks/use-translated-theme-settings"; import { getCartMutationError } from "~/utils/cart-error"; diff --git a/app/components/cart/cart-sync.tsx b/app/components/cart/cart-sync.tsx index 221e0cd2..fe6f4892 100644 --- a/app/components/cart/cart-sync.tsx +++ b/app/components/cart/cart-sync.tsx @@ -1,7 +1,7 @@ -import { CartForm } from "@shopify/hydrogen"; import { useEffect, useRef } from "react"; import { type Fetcher, useFetcher, useFetchers } from "react-router"; -import type { CartApiQueryFragment } from "storefront-api.generated"; +import { CartForm } from "~/components/cart/cart-action-form"; +import type { CartApiQueryFragment } from "~/graphql/storefront-types"; import { usePrefixPathWithLocale } from "~/hooks/use-prefix-path-with-locale"; import { CART_ERROR_KEYS } from "~/utils/cart-error"; import { diff --git a/app/components/cart/cart-types.ts b/app/components/cart/cart-types.ts index 28b6ef5c..774460a0 100644 --- a/app/components/cart/cart-types.ts +++ b/app/components/cart/cart-types.ts @@ -1,4 +1,4 @@ -import type { CartApiQueryFragment } from "storefront-api.generated"; +import type { CartApiQueryFragment } from "~/graphql/storefront-types"; export type CartLayout = "page" | "drawer"; @@ -15,3 +15,8 @@ export type CartMutationResponse = { errors?: Array<{ message?: string }>; userErrors?: Array<{ message?: string }>; }; + +export type OptimisticCartLineInput = + import("@shopify/hydrogen/storefront-api-types").CartLineInput & { + selectedVariant?: import("~/graphql/queries").ProductQuery["product"]["selectedOrFirstAvailableVariant"]; + }; diff --git a/app/components/cart/optimistic-cart.ts b/app/components/cart/optimistic-cart.ts index 09104386..853830da 100644 --- a/app/components/cart/optimistic-cart.ts +++ b/app/components/cart/optimistic-cart.ts @@ -1,6 +1,7 @@ -import { CartForm, type OptimisticCartLineInput } from "@shopify/hydrogen"; import type { Fetcher } from "react-router"; -import type { CartApiQueryFragment } from "storefront-api.generated"; +import { CartForm } from "~/components/cart/cart-action-form"; +import type { OptimisticCartLineInput } from "~/components/cart/cart-types"; +import type { CartApiQueryFragment } from "~/graphql/storefront-types"; import { isCompletedCartAdd } from "./cart-baseline"; import { getOptimisticLineQuantity } from "./cart-line-quantity"; import type { @@ -311,7 +312,10 @@ export function applyOptimisticMutations( captureCompletedLineUpdates( baseline, fetcher, - inputs.lines ?? [], + (inputs.lines ?? []).filter( + (line): line is typeof line & { id: string } => + typeof line.id === "string", + ), adjustedQuantities, ) ) { diff --git a/app/components/cart/store.ts b/app/components/cart/store.ts index 8aa5303b..35b84119 100644 --- a/app/components/cart/store.ts +++ b/app/components/cart/store.ts @@ -1,7 +1,7 @@ -import type { OptimisticCartLineInput } from "@shopify/hydrogen"; import { type Fetcher, useFetchers } from "react-router"; -import type { CartApiQueryFragment } from "storefront-api.generated"; import { create } from "zustand"; +import type { OptimisticCartLineInput } from "~/components/cart/cart-types"; +import type { CartApiQueryFragment } from "~/graphql/storefront-types"; import { resolveBaselineCart } from "./cart-baseline"; import { getLineQuantityRules, diff --git a/app/components/collection/browse.tsx b/app/components/collection/browse.tsx new file mode 100644 index 00000000..1f87932a --- /dev/null +++ b/app/components/collection/browse.tsx @@ -0,0 +1,106 @@ +import type { CollectionState, ProductFilter } from "@shopify/hydrogen"; +import { + CollectionProvider, + useCollection, + useCollectionActions, +} from "@shopify/hydrogen/react"; +import { createContext, type ReactNode, useContext } from "react"; +import { useNavigate, useSearchParams } from "react-router"; + +/** + * Hydrogen 2026.10.2 writes category filters as `filter.p.category`, but + * `parseCollectionParams` doesn't read that key, so the store would drop them + * on its next URL sync. Pilot keeps them out of the store and in the URL. + */ +const CATEGORY_PARAM = "filter.p.category"; + +/** Category filters from the `filter.p.category` URL params. */ +export function parseCategoryFilters( + searchParams: URLSearchParams, +): ProductFilter[] { + return searchParams + .getAll(CATEGORY_PARAM) + .map((id) => ({ category: { id } })); +} + +/** + * Hydrogen's collection store for a product listing: filters and sort live in + * the URL (`filter.p.*`/`filter.v.*`, `sort_by`), changes navigate client-side, + * and `useCollection().status` reads `loading` until the loader catches up. + * Pages are not part of the store: `Pagination` keeps the `after`/`before` + * cursors, which the store drops on every filter or sort change. + */ +export function CollectionBrowseProvider({ + handle, + dataSearch, + children, +}: { + handle: string; + /** The search string the loader queried products for. */ + dataSearch: string; + children: ReactNode; +}) { + const navigate = useNavigate(); + const [searchParams] = useSearchParams(); + const storeSearch = new URLSearchParams(searchParams); + storeSearch.delete(CATEGORY_PARAM); + + return ( + { + const next = new URLSearchParams(search); + for (const id of searchParams.getAll(CATEGORY_PARAM)) { + next.append(CATEGORY_PARAM, id); + } + navigate({ search: `?${next}` }, { preventScrollReset: true }); + }} + > + {children} + + ); +} + +/** The store's filters plus the category filters it can't hold. */ +export function useActiveFilters(): ProductFilter[] { + const filters = useCollection((state) => state.filters); + const [searchParams] = useSearchParams(); + return [...filters, ...parseCategoryFilters(searchParams)]; +} + +/** Adds or removes a category filter in the URL, from the first page. */ +export function useToggleCategoryFilter() { + const navigate = useNavigate(); + const [searchParams] = useSearchParams(); + + return function toggleCategoryFilter(id: string) { + const next = new URLSearchParams(searchParams); + const ids = next.getAll(CATEGORY_PARAM); + next.delete(CATEGORY_PARAM); + for (const value of ids.includes(id) + ? ids.filter((v) => v !== id) + : [...ids, id]) { + next.append(CATEGORY_PARAM, value); + } + next.delete("after"); + next.delete("before"); + navigate({ search: `?${next}` }, { preventScrollReset: true }); + }; +} + +const BrowseContext = createContext< + (ReturnType & CollectionState) | null +>(null); +function BrowseBridge({ children }: { children: ReactNode }) { + const state = useCollection(); + const actions = useCollectionActions(); + return ( + + {children} + + ); +} +export function useOptionalCollectionBrowse() { + return useContext(BrowseContext); +} diff --git a/app/components/customer/account-details.tsx b/app/components/customer/account-details.tsx index 12a992ac..ef402a76 100644 --- a/app/components/customer/account-details.tsx +++ b/app/components/customer/account-details.tsx @@ -1,6 +1,6 @@ -import { useTranslation } from "@weaverse/hydrogen"; -import type { CustomerDetailsFragment } from "customer-account-api.generated"; +import { useTranslation } from "@weaverse/hydrogen/react-router"; import type { HTMLAttributes } from "react"; +import type { CustomerDetailsFragment } from "~/graphql/customer-types"; import { useTranslatedText } from "~/hooks/use-translated-text"; import { cn } from "~/utils/cn"; import { AccountPopup } from "./account-popup"; diff --git a/app/components/customer/account-popup.tsx b/app/components/customer/account-popup.tsx index 5fc46dbc..e93ac985 100644 --- a/app/components/customer/account-popup.tsx +++ b/app/components/customer/account-popup.tsx @@ -1,11 +1,11 @@ import { XIcon } from "@phosphor-icons/react"; import * as Dialog from "@radix-ui/react-dialog"; import type { CustomerAddress } from "@shopify/hydrogen/customer-account-api-types"; -import { useTranslation } from "@weaverse/hydrogen"; -import type { CustomerDetailsFragment } from "customer-account-api.generated"; +import { useTranslation } from "@weaverse/hydrogen/react-router"; import { type ReactNode, useEffect, useState } from "react"; import { createPath, useFetcher } from "react-router"; import { useHrefWithLocale } from "~/components/link"; +import type { CustomerDetailsFragment } from "~/graphql/customer-types"; import { translateError } from "~/utils/translated-error"; export function AccountPopup({ @@ -124,9 +124,9 @@ function AccountPopupContent({ autoComplete: "address-level1", }, { - name: "territoryCode", + name: "countryCode", label: "account.countryCode", - value: address?.territoryCode, + value: address?.countryCode, autoComplete: "country", }, { @@ -204,7 +204,7 @@ function AccountPopupContent({ "lastName", "address1", "city", - "territoryCode", + "countryCode", "zip", ].includes(field.name) } diff --git a/app/components/customer/address-book.tsx b/app/components/customer/address-book.tsx index efe14096..94c3fce4 100644 --- a/app/components/customer/address-book.tsx +++ b/app/components/customer/address-book.tsx @@ -1,8 +1,8 @@ import type { CustomerAddress } from "@shopify/hydrogen/customer-account-api-types"; -import { useTranslation } from "@weaverse/hydrogen"; -import type { CustomerDetailsFragment } from "customer-account-api.generated"; +import { useTranslation } from "@weaverse/hydrogen/react-router"; import type { HTMLAttributes } from "react"; import { Form } from "react-router"; +import type { CustomerDetailsFragment } from "~/graphql/customer-types"; import { useTranslatedText } from "~/hooks/use-translated-text"; import { cn } from "~/utils/cn"; import { AccountPopup } from "./account-popup"; diff --git a/app/components/customer/edit-address-form.tsx b/app/components/customer/edit-address-form.tsx index 687f2b17..6176e80b 100644 --- a/app/components/customer/edit-address-form.tsx +++ b/app/components/customer/edit-address-form.tsx @@ -2,7 +2,7 @@ import { CheckIcon } from "@phosphor-icons/react"; import * as Checkbox from "@radix-ui/react-checkbox"; import * as Dialog from "@radix-ui/react-dialog"; import { flattenConnection } from "@shopify/hydrogen"; -import { useTranslation } from "@weaverse/hydrogen"; +import { useTranslation } from "@weaverse/hydrogen/react-router"; import clsx from "clsx"; import { Form, @@ -139,14 +139,14 @@ export function AccountEditAddressForm() { /> + HeadingProps & Partial >((props, ref) => { const translateText = useTranslatedText(); diff --git a/app/components/image.tsx b/app/components/image.tsx index 884f1d8a..e054317d 100644 --- a/app/components/image.tsx +++ b/app/components/image.tsx @@ -1,7 +1,7 @@ -import { Image as HydrogenImage } from "@shopify/hydrogen"; import type { Image as ImageType } from "@shopify/hydrogen/storefront-api-types"; import type React from "react"; import { forwardRef, useEffect, useRef, useState } from "react"; +import { Image as HydrogenImage } from "~/components/shopify-image"; import { cn } from "~/utils/cn"; type Crop = "center" | "top" | "bottom" | "left" | "right"; diff --git a/app/components/layout/cart-drawer.tsx b/app/components/layout/cart-drawer.tsx index faa7556c..5d65cd0a 100644 --- a/app/components/layout/cart-drawer.tsx +++ b/app/components/layout/cart-drawer.tsx @@ -1,7 +1,7 @@ import { ShoppingBagIcon } from "@phosphor-icons/react"; import * as Dialog from "@radix-ui/react-dialog"; -import { useAnalytics } from "@shopify/hydrogen"; -import { useTranslation } from "@weaverse/hydrogen"; + +import { useTranslation } from "@weaverse/hydrogen/react-router"; import { Cart } from "~/components/cart/cart"; import { useCart, useCartStore } from "~/components/cart/store"; import { AnimatedDrawer } from "../animate-drawer"; @@ -28,7 +28,8 @@ export function useCartDrawerState() { export function CartDrawer() { const { t } = useTranslation(); const cart = useCart(); - const { publish } = useAnalytics(); + const publish = (event: string, data: unknown) => + window.dataLayer?.push({ event, data }); const { isOpen, closeCartDrawer } = useCartDrawerState(); return ( diff --git a/app/components/layout/country-selector.tsx b/app/components/layout/country-selector.tsx index 2fe5e841..bb9c7cfe 100644 --- a/app/components/layout/country-selector.tsx +++ b/app/components/layout/country-selector.tsx @@ -1,6 +1,6 @@ import { CaretDownIcon, CheckCircleIcon } from "@phosphor-icons/react"; import * as Popover from "@radix-ui/react-popover"; -import { useTranslation } from "@weaverse/hydrogen"; +import { useTranslation } from "@weaverse/hydrogen/react-router"; import { useState } from "react"; import ReactCountryFlag from "react-country-flag"; import { Link } from "react-router"; diff --git a/app/components/layout/country-selector/use-localization-selector.ts b/app/components/layout/country-selector/use-localization-selector.ts index af5e4836..3a317d1c 100644 --- a/app/components/layout/country-selector/use-localization-selector.ts +++ b/app/components/layout/country-selector/use-localization-selector.ts @@ -1,5 +1,5 @@ -import { CartForm } from "@shopify/hydrogen"; import { useFetcher, useLocation, useRouteLoaderData } from "react-router"; +import { CartForm } from "~/components/cart/cart-action-form"; import { usePrefixPathWithLocale } from "~/hooks/use-prefix-path-with-locale"; import type { RootLoader } from "~/root"; import type { CurrencyOption, I18nLocale } from "~/types/locale"; diff --git a/app/components/layout/desktop-menu.tsx b/app/components/layout/desktop-menu.tsx index c64643c1..fb1bc2d9 100644 --- a/app/components/layout/desktop-menu.tsx +++ b/app/components/layout/desktop-menu.tsx @@ -1,6 +1,9 @@ import { ArrowRightIcon } from "@phosphor-icons/react"; import * as NavigationMenu from "@radix-ui/react-navigation-menu"; -import { useThemeSettings, useTranslation } from "@weaverse/hydrogen"; +import { + useThemeSettings, + useTranslation, +} from "@weaverse/hydrogen/react-router"; import clsx from "clsx"; import { useEffect, useState } from "react"; import { useLocation, useNavigate } from "react-router"; diff --git a/app/components/layout/filter-search-page.tsx b/app/components/layout/filter-search-page.tsx index b929bf00..2aaeac12 100644 --- a/app/components/layout/filter-search-page.tsx +++ b/app/components/layout/filter-search-page.tsx @@ -7,7 +7,7 @@ import type { Filter, ProductFilter, } from "@shopify/hydrogen/storefront-api-types"; -import { useTranslation } from "@weaverse/hydrogen"; +import { useTranslation } from "@weaverse/hydrogen/react-router"; import clsx from "clsx"; import { useRef, useState } from "react"; import { @@ -17,9 +17,9 @@ import { useRouteLoaderData, useSearchParams, } from "react-router"; -import type { CollectionQuery } from "storefront-api.generated"; import { OPTIONS_AS_SWATCH } from "~/components/product/product-option-values"; import { ScrollArea } from "~/components/scroll-area"; +import type { CollectionQuery } from "~/graphql/storefront-types"; import { useClosestWeaverseItem } from "~/hooks/use-closest-weaverse-item"; import type { RootLoader } from "~/root"; import type { CollectionFiltersData } from "~/sections/collection-filters"; diff --git a/app/components/layout/footer.tsx b/app/components/layout/footer.tsx index 958cf782..f9f4616d 100644 --- a/app/components/layout/footer.tsx +++ b/app/components/layout/footer.tsx @@ -7,8 +7,10 @@ import { TwitterLogo, } from "@phosphor-icons/react"; import * as Accordion from "@radix-ui/react-accordion"; -import { Image } from "@shopify/hydrogen"; -import { useThemeSettings, useTranslation } from "@weaverse/hydrogen"; +import { + useThemeSettings, + useTranslation, +} from "@weaverse/hydrogen/react-router"; import clsx from "clsx"; import type React from "react"; import { useEffect, useState } from "react"; @@ -16,6 +18,7 @@ import type { FetcherWithComponents } from "react-router"; import { useFetcher } from "react-router"; import { Link } from "~/components/link"; import { AspenWordmark } from "~/components/logo"; +import { Image } from "~/components/shopify-image"; import { useFooterRichText } from "~/hooks/use-footer-rich-text"; import { useGlobalThemeText } from "~/hooks/use-global-theme-text"; import { useShopMenu } from "~/hooks/use-shop-menu"; diff --git a/app/components/layout/header.tsx b/app/components/layout/header.tsx index a100112a..c16bd072 100644 --- a/app/components/layout/header.tsx +++ b/app/components/layout/header.tsx @@ -1,5 +1,8 @@ import { UserIcon } from "@phosphor-icons/react"; -import { useThemeSettings, useTranslation } from "@weaverse/hydrogen"; +import { + useThemeSettings, + useTranslation, +} from "@weaverse/hydrogen/react-router"; import { cva } from "class-variance-authority"; import clsx from "clsx"; import { Suspense, useState } from "react"; diff --git a/app/components/layout/mobile-menu.tsx b/app/components/layout/mobile-menu.tsx index 286930f9..9ee2d230 100644 --- a/app/components/layout/mobile-menu.tsx +++ b/app/components/layout/mobile-menu.tsx @@ -6,7 +6,7 @@ import { } from "@phosphor-icons/react"; import * as Collapsible from "@radix-ui/react-collapsible"; import * as Dialog from "@radix-ui/react-dialog"; -import { useTranslation } from "@weaverse/hydrogen"; +import { useTranslation } from "@weaverse/hydrogen/react-router"; import { AnimatePresence, motion, useReducedMotion } from "framer-motion"; import { type Ref, useEffect, useRef, useState } from "react"; import { Image } from "~/components/image"; diff --git a/app/components/layout/predictive-search/PopularSearch.tsx b/app/components/layout/predictive-search/PopularSearch.tsx index 4986c600..a0a8f6cf 100644 --- a/app/components/layout/predictive-search/PopularSearch.tsx +++ b/app/components/layout/predictive-search/PopularSearch.tsx @@ -1,4 +1,4 @@ -import { useTranslation } from "@weaverse/hydrogen"; +import { useTranslation } from "@weaverse/hydrogen/react-router"; import { useEffect, useMemo, useState } from "react"; import Link from "~/components/link"; import { cn } from "~/utils/cn"; diff --git a/app/components/layout/predictive-search/search-desktop/index.tsx b/app/components/layout/predictive-search/search-desktop/index.tsx index f27b4ac8..5dbf5ece 100644 --- a/app/components/layout/predictive-search/search-desktop/index.tsx +++ b/app/components/layout/predictive-search/search-desktop/index.tsx @@ -1,7 +1,7 @@ import { CircleNotchIcon, MagnifyingGlassIcon } from "@phosphor-icons/react"; import * as Dialog from "@radix-ui/react-dialog"; import * as VisuallyHidden from "@radix-ui/react-visually-hidden"; -import { useTranslation } from "@weaverse/hydrogen"; +import { useTranslation } from "@weaverse/hydrogen/react-router"; import clsx from "clsx"; import { AnimatePresence, motion, useReducedMotion } from "framer-motion"; import { diff --git a/app/components/layout/predictive-search/search-desktop/predictive-search-result.tsx b/app/components/layout/predictive-search/search-desktop/predictive-search-result.tsx index f1a8adee..8c9b05f0 100644 --- a/app/components/layout/predictive-search/search-desktop/predictive-search-result.tsx +++ b/app/components/layout/predictive-search/search-desktop/predictive-search-result.tsx @@ -1,8 +1,8 @@ -import { Money } from "@shopify/hydrogen"; import type { MoneyV2 } from "@shopify/hydrogen/storefront-api-types"; -import { useTranslation } from "@weaverse/hydrogen"; +import { useTranslation } from "@weaverse/hydrogen/react-router"; import { Image } from "~/components/image"; import { Link } from "~/components/link"; +import { Money } from "~/components/money"; import { ProductCardRating } from "~/components/product/product-card-rating"; import { SwatchFill, swatchFrameClassName } from "~/components/product/swatch"; import { CompareAtPrice } from "~/components/product/variant-prices"; diff --git a/app/components/layout/predictive-search/search-mobile/index.tsx b/app/components/layout/predictive-search/search-mobile/index.tsx index 3a800b7c..caaa0f54 100644 --- a/app/components/layout/predictive-search/search-mobile/index.tsx +++ b/app/components/layout/predictive-search/search-mobile/index.tsx @@ -1,7 +1,7 @@ import { CircleNotchIcon, MagnifyingGlass, X } from "@phosphor-icons/react"; import * as Dialog from "@radix-ui/react-dialog"; import * as VisuallyHidden from "@radix-ui/react-visually-hidden"; -import { useTranslation } from "@weaverse/hydrogen"; +import { useTranslation } from "@weaverse/hydrogen/react-router"; import clsx from "clsx"; import { AnimatePresence, motion } from "framer-motion"; import { useEffect, useRef, useState } from "react"; diff --git a/app/components/layout/predictive-search/search-mobile/predictive-search-result.tsx b/app/components/layout/predictive-search/search-mobile/predictive-search-result.tsx index 4682b7df..ed8e0810 100644 --- a/app/components/layout/predictive-search/search-mobile/predictive-search-result.tsx +++ b/app/components/layout/predictive-search/search-mobile/predictive-search-result.tsx @@ -1,5 +1,5 @@ import type { MoneyV2 } from "@shopify/hydrogen/storefront-api-types"; -import { useTranslation } from "@weaverse/hydrogen"; +import { useTranslation } from "@weaverse/hydrogen/react-router"; import { Image } from "~/components/image"; import { Link } from "~/components/link"; import { ProductCardRating } from "~/components/product/product-card-rating"; diff --git a/app/components/layout/scrolling-announcement.tsx b/app/components/layout/scrolling-announcement.tsx index f350fa48..64111d43 100644 --- a/app/components/layout/scrolling-announcement.tsx +++ b/app/components/layout/scrolling-announcement.tsx @@ -4,7 +4,7 @@ import { TwitterLogo, YoutubeLogo, } from "@phosphor-icons/react"; -import { useTranslation } from "@weaverse/hydrogen"; +import { useTranslation } from "@weaverse/hydrogen/react-router"; import { cva } from "class-variance-authority"; import { type CSSProperties, useEffect, useRef } from "react"; import type { Swiper as SwiperClass } from "swiper"; diff --git a/app/components/link.tsx b/app/components/link.tsx index 045879f2..f46abb83 100644 --- a/app/components/link.tsx +++ b/app/components/link.tsx @@ -1,9 +1,9 @@ import { createSchema, - type HydrogenComponentProps, type InspectorGroup, useThemeSettings, -} from "@weaverse/hydrogen"; + type WeaverseComponentProps, +} from "@weaverse/hydrogen/react-router"; import { cva, type VariantProps } from "class-variance-authority"; import { forwardRef, type HTMLAttributes } from "react"; import { @@ -91,7 +91,7 @@ export interface LinkData export interface LinkProps extends HTMLAttributes, - Partial>, + Partial>, LinkData {} export function useHrefWithLocale(href: LinkProps["to"]) { diff --git a/app/components/logo.tsx b/app/components/logo.tsx index b649139e..f203a56f 100644 --- a/app/components/logo.tsx +++ b/app/components/logo.tsx @@ -1,7 +1,10 @@ -import { Image } from "@shopify/hydrogen"; -import { useThemeSettings, useTranslation } from "@weaverse/hydrogen"; +import { + useThemeSettings, + useTranslation, +} from "@weaverse/hydrogen/react-router"; import clsx from "clsx"; import { Link } from "~/components/link"; +import { Image } from "~/components/shopify-image"; import { useShopMenu } from "~/hooks/use-shop-menu"; export function Logo() { diff --git a/app/components/loyalty/loyalty-points-hint.tsx b/app/components/loyalty/loyalty-points-hint.tsx index a458da44..fc494c76 100644 --- a/app/components/loyalty/loyalty-points-hint.tsx +++ b/app/components/loyalty/loyalty-points-hint.tsx @@ -1,4 +1,4 @@ -import { useTranslation } from "@weaverse/hydrogen"; +import { useTranslation } from "@weaverse/hydrogen/react-router"; import { Suspense } from "react"; import { Await, useRouteLoaderData } from "react-router"; import { Link } from "~/components/link"; diff --git a/app/components/money.tsx b/app/components/money.tsx new file mode 100644 index 00000000..053184ed --- /dev/null +++ b/app/components/money.tsx @@ -0,0 +1,107 @@ +import { formatMoney, type MoneyV2 } from "@shopify/hydrogen"; +import type { + ComponentPropsWithoutRef, + ElementType, + JSX, + ReactNode, +} from "react"; +import { useLocale } from "~/hooks/use-locale"; +import type { I18nLocale as Locale } from "~/types/locale"; + +type MoneyData = Partial; + +/** + * Formats `money` the way `locale`'s market writes prices: `1.234,56 €` in + * de-DE, `¥1,235` in ja-JP, `$1,234.56` in the default en-US market. + * + * Uses {@link priceLocaleFor} (a BCP-47 tag), not `language`: the provider + * code can be script-specific (`ZH_CN`), which makes `Intl` throw. English + * markets abroad follow their country: `/en-de` also renders `1.234,56 €`. + */ +export function formatMarketMoney(money: MoneyData, locale: Locale) { + return formatMoney( + { amount: money.amount ?? "", currencyCode: money.currencyCode ?? "" }, + { locale: `${locale.language.toLowerCase()}-${locale.country}` }, + ); +} + +/** + * Drop-in replacement for classic hydrogen-react's `useMoney()`, built on + * Hydrogen's `formatMoney()` with the current market's locale. Exposes the + * same fields Pilot reads (`localizedString`, `withoutTrailingZeros`, + * `withoutTrailingZerosAndCurrency`, `currencySymbol`, `amount`, `parts`, ...). + * + * The market is read from the URL, like `usePrefixPathWithLocale`: the server + * and the client see the same path, so both render the same string. + */ +export function useMoney(money: MoneyData) { + return formatMarketMoney(money, useLocale()); +} + +type MoneyPropsBase = { + /** Element or component to render as the wrapper. Defaults to `div`. */ + as?: T; + /** A Storefront / Customer Account API `MoneyV2`. */ + data: MoneyData; + /** Remove the currency symbol from the output. */ + withoutCurrency?: boolean; + /** Remove trailing zeros (`$10.00` → `$10`) from whole amounts. */ + withoutTrailingZeros?: boolean; + /** A `UnitPriceMeasurement`; renders `{separator}{referenceUnit}` after the price. */ + measurement?: { referenceUnit?: string | null }; + /** Separator between the price and the measurement. Defaults to `/`. */ + measurementSeparator?: ReactNode; +}; + +export type MoneyProps = MoneyPropsBase & + Omit, keyof MoneyPropsBase>; + +/** + * Drop-in replacement for classic hydrogen-react's ``: same props, same + * wrapper element and same rendered text. + */ +export function Money({ + data, + as, + withoutCurrency, + withoutTrailingZeros, + measurement, + measurementSeparator = "/", + ...passthroughProps +}: MoneyProps): JSX.Element { + if (!isMoney(data)) { + throw new Error( + ` needs a valid 'data' prop that has 'amount' and 'currencyCode'`, + ); + } + let money = useMoney(data); + let Wrapper: ElementType = as ?? "div"; + let output = money.localizedString; + if (withoutCurrency && withoutTrailingZeros) { + output = money.withoutTrailingZerosAndCurrency; + } else if (withoutCurrency) { + output = money.amount; + } else if (withoutTrailingZeros) { + output = money.withoutTrailingZeros; + } + return ( + + {output} + {measurement?.referenceUnit && ( + <> + {measurementSeparator} + {measurement.referenceUnit} + + )} + + ); +} + +function isMoney(money: MoneyData): money is MoneyV2 { + return ( + typeof money.amount === "string" && + !!money.amount && + typeof money.currencyCode === "string" && + !!money.currencyCode + ); +} diff --git a/app/components/nav-link.tsx b/app/components/nav-link.tsx index 0dc61cd1..d07c1075 100644 --- a/app/components/nav-link.tsx +++ b/app/components/nav-link.tsx @@ -1,4 +1,4 @@ -import { useThemeSettings } from "@weaverse/hydrogen"; +import { useThemeSettings } from "@weaverse/hydrogen/react-router"; import { forwardRef } from "react"; import { NavLink as RemixNavLink, diff --git a/app/components/newsletter-popup.tsx b/app/components/newsletter-popup.tsx index 8cc060de..003789a8 100644 --- a/app/components/newsletter-popup.tsx +++ b/app/components/newsletter-popup.tsx @@ -1,7 +1,10 @@ import { XIcon } from "@phosphor-icons/react"; import * as Dialog from "@radix-ui/react-dialog"; import * as VisuallyHidden from "@radix-ui/react-visually-hidden"; -import { useThemeSettings, useTranslation } from "@weaverse/hydrogen"; +import { + useThemeSettings, + useTranslation, +} from "@weaverse/hydrogen/react-router"; import { useEffect, useState } from "react"; import { useFetcher, useLocation, useRouteLoaderData } from "react-router"; import { Button } from "~/components/button"; diff --git a/app/components/overlay.tsx b/app/components/overlay.tsx index f36f321f..d05e9e69 100644 --- a/app/components/overlay.tsx +++ b/app/components/overlay.tsx @@ -1,4 +1,4 @@ -import type { InspectorGroup } from "@weaverse/hydrogen"; +import type { InspectorGroup } from "@weaverse/hydrogen/react-router"; import type { CSSProperties } from "react"; import { cn } from "~/utils/cn"; diff --git a/app/components/pagination.tsx b/app/components/pagination.tsx new file mode 100644 index 00000000..a01b5d6e --- /dev/null +++ b/app/components/pagination.tsx @@ -0,0 +1,377 @@ +/** + * Local port of classic Hydrogen's `` (`@shopify/hydrogen@2026.4`, MIT). + * Hydrogen 2026.10 no longer exports it, and its collection store owns filters and sort, + * not pages. The port is near-literal: history-state page accumulation (infinite scroll, + * load previous/more) and the render-prop API behave as before. Cursor URLs use the + * `?after=`/`?before=` params that Hydrogen's collection helpers clear on a browse change. + * + * `useMemo` is kept on purpose (exception to the no-useMemo rule): `NextLink`/`PreviousLink` + * are components created per render, and without a stable identity React would remount the + * anchor on every render, resetting the infinite-scroll `useInView` ref. + */ +import { flattenConnection } from "@shopify/hydrogen"; +import { + createElement, + type FC, + type ForwardRefExoticComponent, + forwardRef, + type RefAttributes, + useEffect, + useMemo, + useRef, + useState, +} from "react"; +import { + Link, + type LinkProps, + useLocation, + useNavigate, + useNavigation, +} from "react-router"; + +declare global { + interface Window { + __hydrogenHydrated?: boolean; + } +} + +type Maybe = T | null; + +type PageInfo = { + startCursor?: Maybe; + endCursor?: Maybe; + hasNextPage: boolean; + hasPreviousPage: boolean; +}; + +type Connection = + | { nodes: Array; pageInfo: PageInfo } + | { edges: Array<{ node: NodesType }>; pageInfo: PageInfo }; + +type PaginationState = { + pagination?: { + [key: string]: { + nodes: Array; + pageInfo?: PageInfo | null; + }; + }; +}; + +type PaginationLink = ForwardRefExoticComponent< + Omit & RefAttributes +>; + +interface PaginationInfo { + /** The paginated array of nodes. You should map over and render this array. */ + nodes: Array; + /** Navigates to the next page of paginated data (renders nothing when there is none). */ + NextLink: PaginationLink; + /** Navigates to the previous page of paginated data (renders nothing when there is none). */ + PreviousLink: PaginationLink; + /** The URL to the previous page of paginated data. */ + previousPageUrl: string; + /** The URL to the next page of paginated data. */ + nextPageUrl: string; + /** True if the cursor has next paginated data */ + hasNextPage: boolean; + /** True if the cursor has previous paginated data */ + hasPreviousPage: boolean; + /** True if we are in the process of fetching another page of data */ + isLoading: boolean; + /** Pass as `` to append the next page to the already-loaded nodes. */ + state: { + nodes: Array; + pageInfo: { + endCursor: Maybe | undefined; + startCursor: Maybe | undefined; + hasPreviousPage: boolean; + }; + }; +} + +type PaginationProps = { + /** A paginated connection with `pageInfo` (`hasPreviousPage`, `hasNextPage`, `startCursor`, `endCursor`). */ + connection: Connection; + /** A render prop that includes pagination data and helpers. */ + children: FC>; + /** Avoids URL param conflicts when using multiple `Pagination` components on a single page. */ + namespace?: string; +}; + +export function Pagination({ + connection, + children = () => { + console.warn(" requires children to work properly"); + return null; + }, + namespace = "", +}: PaginationProps): ReturnType { + const [isLoading, setIsLoading] = useState(false); + const transition = useNavigation(); + const location = useLocation(); + + // Reset loading state once the transition state is idle + useEffect(() => { + if (transition.state === "idle") { + setIsLoading(false); + } + }, [transition.state]); + + const { + endCursor, + hasNextPage, + hasPreviousPage, + nextPageUrl, + nodes, + previousPageUrl, + startCursor, + } = usePagination(connection, namespace); + + const state = useMemo( + () => ({ + ...location.state, + pagination: { + ...location.state?.pagination, + [namespace]: { + pageInfo: { endCursor, hasPreviousPage, hasNextPage, startCursor }, + nodes, + }, + }, + }), + [ + endCursor, + hasNextPage, + hasPreviousPage, + startCursor, + nodes, + namespace, + location.state, + ], + ); + + const NextLink = useMemo( + () => + forwardRef>( + function PaginationNextLink(props, ref) { + return hasNextPage + ? createElement(Link, { + preventScrollReset: true, + ...props, + to: nextPageUrl, + state, + replace: true, + ref, + onClick: () => setIsLoading(true), + }) + : null; + }, + ), + [hasNextPage, nextPageUrl, state], + ); + + const PreviousLink = useMemo( + () => + forwardRef>( + function PaginationPreviousLink(props, ref) { + return hasPreviousPage + ? createElement(Link, { + preventScrollReset: true, + ...props, + to: previousPageUrl, + state, + replace: true, + ref, + onClick: () => setIsLoading(true), + }) + : null; + }, + ), + [hasPreviousPage, previousPageUrl, state], + ); + + return children({ + state, + hasNextPage, + hasPreviousPage, + isLoading, + nextPageUrl, + nodes, + previousPageUrl, + NextLink, + PreviousLink, + }); +} + +function getParamsWithoutPagination( + paramsString?: string, + state?: PaginationState, +) { + const params = new URLSearchParams(paramsString); + const activeNamespaces = Object.keys(state?.pagination || {}); + for (const namespace of activeNamespaces) { + const namespacePrefix = namespace === "" ? "" : `${namespace}_`; + params.delete(`${namespacePrefix}after`); + params.delete(`${namespacePrefix}before`); + } + return params.toString(); +} + +function makeError(prop: string): never { + throw new Error( + `The Pagination component requires \`${prop}\` to be a part of your query. See the guide on how to setup your query to include \`${prop}\`: https://shopify.dev/docs/custom-storefronts/hydrogen/data-fetching/pagination#setup-the-paginated-query`, + ); +} + +/** + * Cumulative pagination logic for a connection (classic `usePagination`). + * Hydration is detected with the same `window.__hydrogenHydrated` flag as classic + * Hydrogen, so the first client render matches the server render. + */ +function usePagination( + connection: Connection, + namespace = "", +) { + if (!connection.pageInfo) { + makeError("pageInfo"); + } + if (typeof connection.pageInfo.startCursor === "undefined") { + makeError("pageInfo.startCursor"); + } + if (typeof connection.pageInfo.endCursor === "undefined") { + makeError("pageInfo.endCursor"); + } + if (typeof connection.pageInfo.hasNextPage === "undefined") { + makeError("pageInfo.hasNextPage"); + } + if (typeof connection.pageInfo.hasPreviousPage === "undefined") { + makeError("pageInfo.hasPreviousPage"); + } + + const transition = useNavigation(); + const navigate = useNavigate(); + const { state, search, pathname } = useLocation() as { + state?: PaginationState; + search: string; + pathname: string; + }; + + const afterParam = namespace ? `${namespace}_after` : "after"; + const beforeParam = namespace ? `${namespace}_before` : "before"; + const isPrevious = new URLSearchParams(search).has(beforeParam); + + const nodes = useMemo(() => { + if ( + !globalThis?.window?.__hydrogenHydrated || + !state?.pagination?.[namespace]?.nodes + ) { + return flattenConnection(connection) as NodesType[]; + } + if (isPrevious) { + return [ + ...(flattenConnection(connection) as NodesType[]), + ...(state.pagination[namespace].nodes || []), + ]; + } + return [ + ...(state.pagination[namespace].nodes || []), + ...(flattenConnection(connection) as NodesType[]), + ]; + }, [state, connection, namespace, isPrevious]); + + const currentPageInfo = useMemo(() => { + const hydrogenHydrated = globalThis?.window?.__hydrogenHydrated; + const stateInfo = state?.pagination?.[namespace]?.pageInfo; + let pageStartCursor = + !hydrogenHydrated || stateInfo?.startCursor === undefined + ? connection.pageInfo.startCursor + : stateInfo.startCursor; + let pageEndCursor = + !hydrogenHydrated || stateInfo?.endCursor === undefined + ? connection.pageInfo.endCursor + : stateInfo.endCursor; + let previousPageExists = + !hydrogenHydrated || stateInfo?.hasPreviousPage === undefined + ? connection.pageInfo.hasPreviousPage + : stateInfo.hasPreviousPage; + let nextPageExists = + !hydrogenHydrated || stateInfo?.hasNextPage === undefined + ? connection.pageInfo.hasNextPage + : stateInfo.hasNextPage; + + if (state?.pagination?.[namespace]?.nodes) { + if (isPrevious) { + pageStartCursor = connection.pageInfo.startCursor; + previousPageExists = connection.pageInfo.hasPreviousPage; + } else { + pageEndCursor = connection.pageInfo.endCursor; + nextPageExists = connection.pageInfo.hasNextPage; + } + } + + return { + startCursor: pageStartCursor, + endCursor: pageEndCursor, + hasPreviousPage: previousPageExists, + hasNextPage: nextPageExists, + }; + }, [ + isPrevious, + state, + namespace, + connection.pageInfo.hasNextPage, + connection.pageInfo.hasPreviousPage, + connection.pageInfo.startCursor, + connection.pageInfo.endCursor, + ]); + + // Keep track of the current URL state, to compare whenever the URL changes + const urlRef = useRef({ + params: getParamsWithoutPagination(search, state), + pathname, + }); + + useEffect(() => { + window.__hydrogenHydrated = true; + }, []); + + useEffect(() => { + const currentParams = getParamsWithoutPagination(search, state); + const pathChanged = pathname !== urlRef.current.pathname; + const nonPaginationParamsChanged = currentParams !== urlRef.current.params; + if ( + // Only clean up if the base URL or non-pagination params change + (pathChanged || nonPaginationParamsChanged) && + // And we're not on the initial load + !(transition.state === "idle" && !transition.location) + ) { + urlRef.current = { pathname, params: currentParams }; + navigate(`${pathname}?${currentParams}`, { + replace: true, + preventScrollReset: true, + state: { nodes: undefined, pageInfo: undefined }, + }); + } + // Classic Hydrogen runs this only when the URL or history state changes. + // oxlint-disable-next-line react/exhaustive-deps + }, [pathname, search, state]); + + const previousPageUrl = useMemo(() => { + const params = new URLSearchParams(search); + params.delete(afterParam); + if (currentPageInfo.startCursor) { + params.set(beforeParam, currentPageInfo.startCursor); + } + return `?${params.toString()}`; + }, [search, currentPageInfo.startCursor, afterParam, beforeParam]); + + const nextPageUrl = useMemo(() => { + const params = new URLSearchParams(search); + params.delete(beforeParam); + if (currentPageInfo.endCursor) { + params.set(afterParam, currentPageInfo.endCursor); + } + return `?${params.toString()}`; + }, [search, currentPageInfo.endCursor, afterParam, beforeParam]); + + return { ...currentPageInfo, previousPageUrl, nextPageUrl, nodes }; +} diff --git a/app/components/paragraph.tsx b/app/components/paragraph.tsx index 61971f30..ba86cbc2 100644 --- a/app/components/paragraph.tsx +++ b/app/components/paragraph.tsx @@ -1,4 +1,7 @@ -import { createSchema, type HydrogenComponentProps } from "@weaverse/hydrogen"; +import { + createSchema, + type WeaverseComponentProps, +} from "@weaverse/hydrogen/react-router"; import type { VariantProps } from "class-variance-authority"; import { cva } from "class-variance-authority"; import { forwardRef } from "react"; @@ -6,7 +9,7 @@ import { useTranslatedText } from "~/hooks/use-translated-text"; import { cn } from "~/utils/cn"; export interface ParagraphProps - extends VariantProps, Partial { + extends VariantProps, Partial { as?: "p" | "div"; content: string; color?: string; diff --git a/app/components/product-media/external-video.tsx b/app/components/product-media/external-video.tsx new file mode 100644 index 00000000..16ba4207 --- /dev/null +++ b/app/components/product-media/external-video.tsx @@ -0,0 +1,51 @@ +import type { ComponentPropsWithRef } from "react"; + +type ExternalVideoProps = Omit, "src"> & { + /** A Storefront API `ExternalVideo` (`embedUrl`, plus `id`/`alt`). */ + data: { id?: string | null; alt?: string | null; embedUrl?: string | null }; + /** Extra embed URL params (e.g. YouTube `autoplay`). */ + options?: Record; +}; + +/** + * Local port of classic hydrogen-react's `` (removed in + * Hydrogen 2026.10): renders the YouTube/Vimeo embed iframe with the same + * attributes and defaults. + */ +export function ExternalVideo({ + data, + options, + id = data.id ?? undefined, + frameBorder = "0", + allow = "accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture", + allowFullScreen = true, + loading = "lazy", + ...passthroughProps +}: ExternalVideoProps) { + if (!data.embedUrl) { + throw new Error(" requires the 'embedUrl' property"); + } + let finalUrl = data.embedUrl; + if (options) { + let urlObject = new URL(data.embedUrl); + for (let [key, value] of Object.entries(options)) { + if (typeof value === "undefined") { + continue; + } + urlObject.searchParams.set(key, value.toString()); + } + finalUrl = urlObject.toString(); + } + return ( +