@tansy/theme-storefront 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,24 @@
1
+ # Changelog
2
+
3
+ What changed in each release of `@tansy/theme-storefront`. Releases up to 0.1.0 went out with every other package
4
+ on one version and are described in [tansy's changelog](../../CHANGELOG.md).
5
+
6
+ ## 0.1.1 — 2026-11-22
7
+
8
+ - **Pages change without a reload.** Links between the theme's pages are followed inside the app,
9
+ through the Next router, each move inside a view transition: the header holds still, a product's
10
+ picture flies from its card to its page and back, and the current category chip and the tab bar's
11
+ dot slide to their new place. A page loaded in full, such as another language, still animates in
12
+ browsers with cross-document view transitions. Nothing moves for visitors who ask for less motion.
13
+ - **Tapping a product's picture zooms it** to fill the screen, and back.
14
+ - **The back arrow returns to the page the visitor came from**, as an app's does. From a product,
15
+ that page comes back scrolled to the product's card, and its picture flies back into it. Opened
16
+ from a shared link, it goes to the shop.
17
+ - **On phones:** a tab bar with a menu that rises as a sheet, pictures that swipe, and **Buy now**
18
+ and **Add to cart** pinned to the bottom of a product page.
19
+ - **A Format field** on products (physical, digital, or both), shown as a badge.
20
+ - **Memberships for digital editions:** a **Membership** field on products, a **Library page** at
21
+ `/library` with the plans on offer, and **Library files** that only members of a plan including
22
+ them can see or download. A new `library` option links to it from the header and tab bar.
23
+ - The theme now names `@tansy/payments` as a peer dependency, for its Subscribe button, and
24
+ requires `tansy`, `@tansy/shop` and `@tansy/payments` ^0.1.1.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mohamed Salah
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,13 @@
1
- # Temporary Holding Version
1
+ <!-- Generated by scripts/package-metadata.mjs. Change that script, not this file. -->
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ # @tansy/theme-storefront
4
+
5
+ A storefront look for the shop plugin: soft rounded product cards, a product stage with a size picker and quantity stepper, and a two-column cart.
6
+
7
+ ```bash
8
+ npm install @tansy/theme-storefront
9
+ ```
10
+
11
+ Add it to `tansy.config.ts`. See [the storefront theme documentation](https://github.com/mhmdsalahsebai/tansy/blob/main/docs/themes/storefront.md) for what it adds and the options it takes.
12
+
13
+ A first-party theme for [tansy](https://github.com/mhmdsalahsebai/tansy), a self-hosted, runtime-schema CMS for Next.js. MIT licensed.
package/client.d.ts ADDED
@@ -0,0 +1,81 @@
1
+ import { type ReactNode } from "react";
2
+ import { type VariantOption } from "@tansy/shop/react";
3
+ import { type SiteWords } from "tansy/react";
4
+ /**
5
+ * Follows the theme's links inside the app, through the Next router, so moving between pages swaps
6
+ * the page without loading a new document, each move inside a view transition (`moveTo`): the
7
+ * header holds still, the picture flies and the chip and tab dot slide. Pages loaded in full
8
+ * (another language, a shared link) still get the cross-document transition the layout switches
9
+ * on, named here on `pageswap`.
10
+ * Rendered by the layout on every page, it also leaves the note the back arrow reads.
11
+ */
12
+ export declare function ViewTransitionNames(): null;
13
+ /**
14
+ * Wraps the page beneath the header and tells a running move between pages (`moveTo`) that the new
15
+ * page is in, as soon as the router has put it in the document, so the browser animates to it.
16
+ */
17
+ export declare function PageTransition({ children }: {
18
+ children: ReactNode;
19
+ }): ReactNode;
20
+ /**
21
+ * Searches published products as the visitor types, through the records API. It reads as
22
+ * whoever is looking, so the products collection's list rule still decides what can be found.
23
+ */
24
+ export declare function ProductSearch({ id: anchor, words, currency }: {
25
+ id?: string;
26
+ words?: SiteWords;
27
+ currency: string;
28
+ }): import("react").JSX.Element;
29
+ export interface GalleryImage {
30
+ src: string;
31
+ thumb: string; /** What the image shows, for a reader who can't see it (set beside the file). */
32
+ alt: string;
33
+ }
34
+ /**
35
+ * The product's pictures on a soft stage, with a ring around it. They sit side by side in a
36
+ * track that snaps, so a finger swipes through them as in an app, and arrows, thumbnails or the
37
+ * arrow keys (once the stage has focus) step through them too. The picture showing carries
38
+ * `transitionName`, the name its card in a list has, so moving between them flies it across.
39
+ * Tapping it zooms it to fill the screen, the same picture growing out of the stage, and closing
40
+ * shrinks it back.
41
+ */
42
+ export declare function ProductGallery({ images, transitionName, words }: {
43
+ images: GalleryImage[];
44
+ transitionName?: string;
45
+ words?: SiteWords;
46
+ }): import("react").JSX.Element;
47
+ /**
48
+ * Price, options as chips, a quantity stepper, and two ways to buy: into the cart and stay,
49
+ * or into the cart and straight to it. The cart is the shop plugin's, so checkout prices it
50
+ * again on the server whatever this page showed.
51
+ */
52
+ export declare function BuyBox({ product, price, compareAt, stock, variants, currency, cartHref, words }: {
53
+ product: number;
54
+ price: number | null;
55
+ compareAt: number | null;
56
+ stock: number | null;
57
+ variants?: VariantOption[];
58
+ currency: string;
59
+ cartHref?: string;
60
+ words?: SiteWords;
61
+ }): import("react").JSX.Element;
62
+ /**
63
+ * A back arrow that returns to the page the visitor came from, as an app's does. It goes there as
64
+ * a new move forward rather than back through history, so it gets the same transition as any link,
65
+ * and adds `#` and the card of `card`, the product being left: the browser scrolls that card into
66
+ * view as the page shows, so the list comes back where the visitor was and the product's
67
+ * picture flies back into its own card. The address is worked out once the page has loaded, before
68
+ * this page's own links leave a note of their own. Opened from a shared link or a new tab, it is
69
+ * `href`.
70
+ */
71
+ export declare function BackLink({ href, card, className, children }: {
72
+ href: string;
73
+ card?: number | string;
74
+ className?: string;
75
+ children: ReactNode;
76
+ }): import("react").JSX.Element;
77
+ export declare function ShareButton({ title, words, className }: {
78
+ title: string;
79
+ words?: SiteWords;
80
+ className?: string;
81
+ }): import("react").JSX.Element;
package/client.js ADDED
@@ -0,0 +1,461 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
+ import { usePathname, useRouter, useSearchParams } from "next/navigation";
4
+ import { useEffect, useId, useLayoutEffect, useRef, useState } from "react";
5
+ import { flushSync } from "react-dom";
6
+ import { addToCart } from "@tansy/shop/react";
7
+ import { apiPath, contentLocale, sitePath, siteWords } from "tansy/react";
8
+ import { Bag, Check, ChevronLeft, ChevronRight, Close, Minus, Plus, Search, Send } from "./icons";
9
+ import { cardAnchor, cx, money, text } from "./lib";
10
+ /**
11
+ * The theme's parts that need the browser. Each takes `pickWords(words, "storefront")` from a
12
+ * template, so it speaks the page's language and keeps links in it.
13
+ */
14
+ /* ------------------------------------------------------- view transitions */
15
+ const reducedMotion = () => window.matchMedia("(prefers-reduced-motion: reduce)").matches;
16
+ /**
17
+ * Runs a change to the page as a same-document view transition where the browser has them, with
18
+ * `type` so styles.css can tell it from moving between pages. Browsers that have transitions but
19
+ * not types get it without one.
20
+ */
21
+ function transition(change, type) {
22
+ if (typeof document.startViewTransition !== "function" || reducedMotion())
23
+ return change();
24
+ const update = () => flushSync(change);
25
+ try {
26
+ document.startViewTransition({ update, types: [type] });
27
+ }
28
+ catch {
29
+ document.startViewTransition(update);
30
+ }
31
+ }
32
+ const pathOf = (href) => {
33
+ try {
34
+ return new URL(href, window.location.href).pathname;
35
+ }
36
+ catch {
37
+ return "";
38
+ }
39
+ };
40
+ /**
41
+ * Before a page is left for a product, picks the picture that flies. Pictures that lead to a
42
+ * product carry `data-sf-vt` (the name) and `data-sf-vt-href`. When the same product shows twice,
43
+ * such as in the spotlight and the grid, the one pressed (or else the one most in view) takes the
44
+ * name and the others give it up, since a page may use a name once. The new page names its own.
45
+ */
46
+ function nameFlyingPicture(to, pressed) {
47
+ const path = pathOf(to);
48
+ const pictures = [...document.querySelectorAll("[data-sf-vt-href]")].filter((picture) => pathOf(picture.dataset.sfVtHref ?? "") === path);
49
+ if (!pictures.length)
50
+ return;
51
+ const near = (picture) => pressed && picture.closest("li, article, [data-sf-vt-scope]")?.contains(pressed);
52
+ const inView = (picture) => {
53
+ const box = picture.getBoundingClientRect();
54
+ return Math.max(0, Math.min(box.bottom, window.innerHeight) - Math.max(box.top, 0)) * Math.max(0, Math.min(box.right, window.innerWidth) - Math.max(box.left, 0));
55
+ };
56
+ const chosen = pictures.find(near) ?? pictures.reduce((best, picture) => (inView(picture) > inView(best) ? picture : best));
57
+ const name = chosen.dataset.sfVt ?? "";
58
+ for (const other of document.querySelectorAll("[data-sf-vt]")) {
59
+ if (other !== chosen && other.style.viewTransitionName === name)
60
+ other.style.viewTransitionName = "none";
61
+ }
62
+ chosen.style.viewTransitionName = name;
63
+ }
64
+ /** Set once a link here has been followed without loading a new document. */
65
+ let softNavigated = false;
66
+ /** Ends the view transition of a move between pages, once the new page is in. Set while one runs. */
67
+ let pageIn = null;
68
+ /**
69
+ * The link a click follows inside the app, or null when the browser should load it itself: a
70
+ * new tab, a download, another site, the API (files), another language, or a jump on this page.
71
+ */
72
+ function appLink(event) {
73
+ if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)
74
+ return null;
75
+ const link = event.target?.closest?.("a[href]");
76
+ if (!link || !link.closest(".sf-shell"))
77
+ return null;
78
+ if ((link.target && link.target !== "_self") || link.hasAttribute("download") || link.hasAttribute("hreflang") || link.relList.contains("external"))
79
+ return null;
80
+ if (link.origin !== location.origin || link.pathname.startsWith(apiPath("/")))
81
+ return null;
82
+ if (link.pathname === location.pathname && link.search === location.search && link.hash)
83
+ return null;
84
+ return link;
85
+ }
86
+ /**
87
+ * The Next router, or null where a template is rendered outside one (as tests render them), whose
88
+ * links then load pages as plain links do. `useRouter` throws there, but always reads its context,
89
+ * so catching keeps the hooks in the same order.
90
+ */
91
+ function useAppRouter() {
92
+ try {
93
+ return useRouter();
94
+ }
95
+ catch {
96
+ return null;
97
+ }
98
+ }
99
+ /** How long the old page may stay frozen waiting for the new one before it's let go without an animation. */
100
+ const PAGE_WAIT_MS = 3000;
101
+ /**
102
+ * Moves to `href` through the Next router inside a view transition: the browser takes the old page,
103
+ * the router swaps in the new one without loading a document, and `PageTransition` ends the update
104
+ * once it's in, so the browser animates from one to the other. styles.css says how.
105
+ */
106
+ function moveTo(router, href) {
107
+ if (typeof document.startViewTransition !== "function" || reducedMotion() || document.visibilityState !== "visible")
108
+ return router.push(href);
109
+ pageIn?.();
110
+ let pushed = false;
111
+ const push = () => {
112
+ if (pushed)
113
+ return;
114
+ pushed = true;
115
+ router.push(href);
116
+ };
117
+ const update = () => new Promise((resolve) => {
118
+ const timer = setTimeout(() => { pageIn = null; resolve(); }, PAGE_WAIT_MS);
119
+ pageIn = () => { clearTimeout(timer); pageIn = null; resolve(); };
120
+ push();
121
+ });
122
+ let transition;
123
+ try {
124
+ transition = document.startViewTransition({ update, types: ["sf-page"] });
125
+ }
126
+ catch {
127
+ transition = document.startViewTransition(update);
128
+ }
129
+ // The browser takes the old page on its next frame. Where none comes, the move goes without the animation.
130
+ setTimeout(() => {
131
+ if (pushed)
132
+ return;
133
+ transition.skipTransition();
134
+ push();
135
+ }, 1000);
136
+ }
137
+ /**
138
+ * Follows the theme's links inside the app, through the Next router, so moving between pages swaps
139
+ * the page without loading a new document, each move inside a view transition (`moveTo`): the
140
+ * header holds still, the picture flies and the chip and tab dot slide. Pages loaded in full
141
+ * (another language, a shared link) still get the cross-document transition the layout switches
142
+ * on, named here on `pageswap`.
143
+ * Rendered by the layout on every page, it also leaves the note the back arrow reads.
144
+ */
145
+ export function ViewTransitionNames() {
146
+ const router = useAppRouter();
147
+ useCameFromNote();
148
+ useEffect(() => {
149
+ let pressed = null;
150
+ const prefetched = new Set();
151
+ const press = (event) => { pressed = event.target instanceof Element ? event.target : null; };
152
+ if (!router)
153
+ return;
154
+ const hover = (event) => {
155
+ const link = event.target?.closest?.("a[href]");
156
+ if (!link || link.origin !== location.origin || link.pathname.startsWith(apiPath("/")) || prefetched.has(link.href))
157
+ return;
158
+ prefetched.add(link.href);
159
+ router.prefetch(link.href);
160
+ };
161
+ const click = (event) => {
162
+ const link = appLink(event);
163
+ if (!link)
164
+ return;
165
+ event.preventDefault();
166
+ if (!reducedMotion())
167
+ nameFlyingPicture(link.href, pressed ?? event.target);
168
+ softNavigated = true;
169
+ const href = link.pathname + link.search + link.hash;
170
+ // The page already showing: the router refreshes it in place, with nothing to animate.
171
+ if (link.pathname === location.pathname && link.search === location.search)
172
+ router.push(href);
173
+ else
174
+ moveTo(router, href);
175
+ };
176
+ const swap = (event) => {
177
+ const { viewTransition, activation } = event;
178
+ const to = activation?.entry?.url;
179
+ if (viewTransition && to)
180
+ nameFlyingPicture(to, pressed);
181
+ };
182
+ window.addEventListener("pointerdown", press, true);
183
+ document.addEventListener("mouseover", hover);
184
+ document.addEventListener("click", click);
185
+ window.addEventListener("pageswap", swap);
186
+ return () => {
187
+ window.removeEventListener("pointerdown", press, true);
188
+ document.removeEventListener("mouseover", hover);
189
+ document.removeEventListener("click", click);
190
+ window.removeEventListener("pageswap", swap);
191
+ };
192
+ }, [router]);
193
+ return null;
194
+ }
195
+ /**
196
+ * Wraps the page beneath the header and tells a running move between pages (`moveTo`) that the new
197
+ * page is in, as soon as the router has put it in the document, so the browser animates to it.
198
+ */
199
+ export function PageTransition({ children }) {
200
+ const pathname = usePathname();
201
+ const search = useSearchParams()?.toString();
202
+ useLayoutEffect(() => { pageIn?.(); }, [pathname, search]);
203
+ return children;
204
+ }
205
+ const thumb = (fileId, size = "100x100") => apiPath(`/files/${encodeURIComponent(fileId)}?thumb=${size}`);
206
+ const MIN_LENGTH = 2;
207
+ const WAIT_MS = 250;
208
+ /**
209
+ * Searches published products as the visitor types, through the records API. It reads as
210
+ * whoever is looking, so the products collection's list rule still decides what can be found.
211
+ */
212
+ export function ProductSearch({ id: anchor, words, currency }) {
213
+ const { t, formatNumber } = siteWords(words);
214
+ const id = useId();
215
+ const input = useRef(null);
216
+ const [query, setQuery] = useState("");
217
+ const [results, setResults] = useState(null);
218
+ const [state, setState] = useState("idle");
219
+ const pending = useRef(null);
220
+ async function run(value) {
221
+ pending.current?.abort();
222
+ const terms = value.trim();
223
+ if (terms.length < MIN_LENGTH) {
224
+ setResults(null);
225
+ setState("idle");
226
+ return;
227
+ }
228
+ const controller = new AbortController();
229
+ pending.current = controller;
230
+ setState("busy");
231
+ // Published only, so staff who may list drafts find what visitors find, and every link opens.
232
+ const params = new URLSearchParams({ search: terms, filter: 'status = "published"', perPage: "6", fields: "id,title,price,images", urls: "1" });
233
+ const locale = contentLocale(words);
234
+ if (locale)
235
+ params.set("locale", locale);
236
+ try {
237
+ const response = await fetch(apiPath(`/collections/shop-products/records?${params}`), { signal: controller.signal, headers: { accept: "application/json" } });
238
+ const json = await response.json().catch(() => null);
239
+ if (controller.signal.aborted)
240
+ return;
241
+ if (!response.ok || !Array.isArray(json?.items)) {
242
+ setState("failed");
243
+ setResults(null);
244
+ return;
245
+ }
246
+ setResults(json.items);
247
+ setState("idle");
248
+ }
249
+ catch {
250
+ if (!controller.signal.aborted)
251
+ setState("failed");
252
+ }
253
+ }
254
+ useEffect(() => {
255
+ const timer = setTimeout(() => void run(query), WAIT_MS);
256
+ return () => clearTimeout(timer);
257
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- searches again only when the words typed change
258
+ }, [query]);
259
+ useEffect(() => () => pending.current?.abort(), []);
260
+ // The Search tab links here by its id: arriving that way puts the cursor in the box.
261
+ useEffect(() => {
262
+ if (!anchor)
263
+ return;
264
+ const focus = () => { if (window.location.hash === `#${anchor}`)
265
+ input.current?.focus({ preventScroll: false }); };
266
+ focus();
267
+ window.addEventListener("hashchange", focus);
268
+ return () => window.removeEventListener("hashchange", focus);
269
+ }, [anchor]);
270
+ function submit(event) {
271
+ event.preventDefault();
272
+ void run(query);
273
+ }
274
+ const open = results !== null || state === "failed";
275
+ const status = state === "busy"
276
+ ? t("storefront.searching")
277
+ : state === "failed"
278
+ ? t("storefront.searchFailed")
279
+ : results === null ? "" : results.length ? t("storefront.found", { count: results.length }) : t("storefront.noResults", { query: query.trim() });
280
+ return (_jsxs("div", { id: anchor, className: "sf:relative sf:w-full sf:max-w-xl sf:scroll-mt-24", children: [_jsxs("form", { role: "search", onSubmit: submit, children: [_jsx("label", { className: "sf:sr-only", htmlFor: `${id}-q`, children: t("storefront.searchLabel") }), _jsxs("span", { className: "sf:flex sf:h-14 sf:items-center sf:gap-3 sf:rounded-full sf:border sf:border-line sf:bg-surface sf:ps-5 sf:pe-2 sf:transition sf:focus-within:border-accent sf:focus-within:bg-page sf:focus-within:ring-4 sf:focus-within:ring-accent/15", children: [_jsx(Search, { className: "sf:size-5 sf:shrink-0 sf:text-muted" }), _jsx("input", { ref: input, id: `${id}-q`, type: "search", enterKeyHint: "search", name: "q", autoComplete: "off", maxLength: 200, placeholder: t("storefront.searchPlaceholder"), value: query, onChange: (event) => setQuery(event.target.value), onKeyDown: (event) => { if (event.key === "Escape")
281
+ setQuery(""); }, "aria-controls": `${id}-results`, "aria-describedby": `${id}-status`, className: "sf:h-full sf:min-w-0 sf:flex-1 sf:bg-transparent sf:text-base sf:text-ink sf:outline-none sf:placeholder:text-muted" }), _jsx("button", { type: "submit", className: "sf:inline-flex sf:h-10 sf:shrink-0 sf:items-center sf:rounded-full sf:bg-ink sf:px-5 sf:text-sm sf:font-medium sf:text-page sf:transition sf:hover:bg-accent sf:hover:text-on-accent", children: t("storefront.searchLabel") })] })] }), _jsx("p", { id: `${id}-status`, className: "sf:sr-only", role: "status", "aria-live": "polite", children: status }), _jsx("div", { id: `${id}-results`, hidden: !open, className: "sf:absolute sf:inset-x-0 sf:top-full sf:z-20 sf:mt-2 sf:overflow-hidden sf:rounded-3xl sf:border sf:border-line sf:bg-page sf:p-2 sf:shadow-card", children: results && results.length > 0 ? (_jsx("ul", { children: results.map((product) => {
282
+ const path = text(product.recordPath);
283
+ const image = Array.isArray(product.images) ? text(product.images[0]) : "";
284
+ const price = typeof product.price === "number" ? product.price : null;
285
+ return (_jsx("li", { children: _jsxs("a", { href: path ? sitePath(words, path) : undefined, className: "sf:flex sf:items-center sf:gap-3 sf:rounded-2xl sf:p-2 sf:text-ink sf:no-underline sf:hover:bg-surface sf:focus-visible:bg-surface sf:focus-visible:outline-none", children: [image ? _jsx("img", { src: thumb(image), alt: "", width: 48, height: 48, loading: "lazy", ...(path ? { "data-sf-vt": `sf-product-${product.id}`, "data-sf-vt-href": sitePath(words, path) } : {}), className: "sf-vt-product sf:size-12 sf:rounded-full sf:bg-surface sf:object-cover" }) : _jsx("span", { className: "sf:grid sf:size-12 sf:place-items-center sf:rounded-full sf:bg-surface sf:text-muted", "aria-hidden": "true", children: _jsx(Bag, {}) }), _jsx("span", { className: "sf:min-w-0 sf:flex-1 sf:truncate sf:font-medium", children: text(product.title) }), price !== null && _jsx("span", { className: "sf:text-sm sf:text-muted sf:tabular-nums", children: money(formatNumber, price, currency) })] }) }, product.id));
286
+ }) })) : _jsx("p", { className: "sf:p-3 sf:text-sm sf:text-muted", children: status }) })] }));
287
+ }
288
+ const RoundButton = ({ label, onClick, children }) => (_jsx("button", { type: "button", "aria-label": label, onClick: onClick, className: "sf:grid sf:size-10 sf:place-items-center sf:rounded-full sf:text-ink sf:transition sf:hover:bg-ink sf:hover:text-page sf:focus-visible:outline-2 sf:focus-visible:outline-accent", children: children }));
289
+ /** Smooth unless the visitor asks for less motion. */
290
+ const scrollBehavior = () => (reducedMotion() ? "auto" : "smooth");
291
+ /**
292
+ * The product's pictures on a soft stage, with a ring around it. They sit side by side in a
293
+ * track that snaps, so a finger swipes through them as in an app, and arrows, thumbnails or the
294
+ * arrow keys (once the stage has focus) step through them too. The picture showing carries
295
+ * `transitionName`, the name its card in a list has, so moving between them flies it across.
296
+ * Tapping it zooms it to fill the screen, the same picture growing out of the stage, and closing
297
+ * shrinks it back.
298
+ */
299
+ export function ProductGallery({ images, transitionName, words }) {
300
+ const { t } = siteWords(words);
301
+ const [index, setIndex] = useState(0);
302
+ const [zoomed, setZoomed] = useState(false);
303
+ const track = useRef(null);
304
+ const opener = useRef(null);
305
+ const count = images.length;
306
+ const name = transitionName ?? "sf-zoom";
307
+ function zoom(open) {
308
+ transition(() => setZoomed(open), "sf-zoom");
309
+ if (!open)
310
+ opener.current?.focus({ preventScroll: true });
311
+ }
312
+ // While zoomed: Escape closes, and the page behind holds still.
313
+ useEffect(() => {
314
+ if (!zoomed)
315
+ return;
316
+ const keys = (event) => { if (event.key === "Escape")
317
+ zoom(false); };
318
+ const root = document.documentElement;
319
+ const overflow = root.style.overflow;
320
+ root.style.overflow = "hidden";
321
+ window.addEventListener("keydown", keys);
322
+ return () => { root.style.overflow = overflow; window.removeEventListener("keydown", keys); };
323
+ }, [zoomed]);
324
+ /** Scrolls the track to a picture. The index follows from the scroll, so swiping and stepping agree. */
325
+ function show(at) {
326
+ const slide = track.current?.children[(at + count) % count];
327
+ slide?.scrollIntoView({ behavior: scrollBehavior(), block: "nearest", inline: "center" });
328
+ }
329
+ function onScroll() {
330
+ const element = track.current;
331
+ if (!element || !element.clientWidth)
332
+ return;
333
+ // scrollLeft runs negative right to left, so its size is what counts.
334
+ setIndex(Math.min(count - 1, Math.round(Math.abs(element.scrollLeft) / element.clientWidth)));
335
+ }
336
+ function keys(event) {
337
+ if (count < 2 || (event.key !== "ArrowLeft" && event.key !== "ArrowRight"))
338
+ return;
339
+ event.preventDefault();
340
+ const rtl = getComputedStyle(event.currentTarget).direction === "rtl";
341
+ show(index + ((event.key === "ArrowRight") !== rtl ? 1 : -1));
342
+ }
343
+ return (_jsxs("section", { "aria-label": t("storefront.images"), className: "sf:flex sf:flex-col sf:gap-4", children: [_jsxs("div", { role: count > 1 ? "group" : undefined, "aria-roledescription": count > 1 ? "carousel" : undefined, tabIndex: count > 1 ? 0 : undefined, onKeyDown: keys, className: "sf:group sf:relative sf:isolate sf:aspect-square sf:overflow-hidden sf:rounded-card sf:bg-surface sf:focus-visible:outline-2 sf:focus-visible:outline-offset-4 sf:focus-visible:outline-accent", children: [_jsx("span", { "aria-hidden": "true", className: "sf:absolute sf:top-[58%] sf:left-1/2 sf:-z-10 sf:h-[26%] sf:w-[118%] sf:-translate-x-1/2 sf:-rotate-6 sf:rounded-[50%] sf:border sf:border-ink/15" }), _jsx("span", { "aria-hidden": "true", className: "sf:absolute sf:top-1/2 sf:left-1/2 sf:-z-20 sf:size-[72%] sf:-translate-1/2 sf:rounded-full sf:bg-page/70 sf:blur-2xl" }), count > 0 ? (_jsx("div", { ref: track, onScroll: onScroll, className: "sf-track sf:absolute sf:inset-0 sf:flex sf:snap-x sf:snap-mandatory sf:overflow-x-auto sf:overscroll-x-contain", children: images.map((image, at) => (_jsx("div", { className: "sf:grid sf:size-full sf:shrink-0 sf:snap-center sf:snap-always sf:place-items-center", "aria-hidden": at !== index ? true : undefined, children: _jsx("button", { type: "button", ref: at === index ? opener : undefined, tabIndex: at === index ? 0 : -1, onClick: () => zoom(true), "aria-label": t("storefront.zoomIn"), className: "sf:grid sf:size-full sf:cursor-zoom-in sf:place-items-center sf:focus-visible:outline-none", children: _jsx("img", { src: image.src, alt: image.alt, loading: at === 0 ? "eager" : "lazy", draggable: false, style: at === index && !zoomed ? { viewTransitionName: name } : undefined, className: cx(at === index && "sf-zoom-target", "sf-vt-product sf:size-[82%] sf:object-contain sf:drop-shadow-[0_24px_30px_rgba(0,0,0,0.18)] sf:transition-transform sf:duration-500 sf:ease-out sf:select-none sf:group-hover:scale-[1.03] sf:motion-reduce:transition-none") }) }) }, image.src))) })) : _jsx("div", { className: "sf:grid sf:size-full sf:place-items-center", children: _jsx(Bag, { className: "sf:size-16 sf:text-muted/50", strokeWidth: 1 }) }), count > 1 && (_jsxs(_Fragment, { children: [_jsx("div", { "aria-hidden": "true", className: "sf:pointer-events-none sf:absolute sf:bottom-5 sf:left-1/2 sf:flex sf:-translate-x-1/2 sf:gap-1.5 sf:sm:hidden", children: images.map((image, at) => _jsx("span", { className: cx("sf:h-1.5 sf:rounded-full sf:transition-all sf:duration-300", at === index ? "sf:w-5 sf:bg-ink" : "sf:w-1.5 sf:bg-ink/25") }, image.src)) }), _jsxs("div", { className: "sf:absolute sf:bottom-6 sf:left-1/2 sf:hidden sf:-translate-x-1/2 sf:items-center sf:gap-1 sf:rounded-full sf:border sf:border-line sf:bg-page/80 sf:p-1 sf:shadow-sm sf:backdrop-blur sf:sm:flex", children: [_jsx(RoundButton, { label: t("storefront.previousImage"), onClick: () => show(index - 1), children: _jsx(ChevronLeft, { className: "sf:size-5 sf:rtl:-scale-x-100" }) }), _jsxs("span", { className: "sf:min-w-12 sf:text-center sf:text-sm sf:text-muted sf:tabular-nums", "aria-live": "polite", children: [index + 1, " / ", count] }), _jsx(RoundButton, { label: t("storefront.nextImage"), onClick: () => show(index + 1), children: _jsx(ChevronRight, { className: "sf:size-5 sf:rtl:-scale-x-100" }) })] })] }))] }), zoomed && images[index] && (_jsxs("div", { role: "dialog", "aria-modal": "true", "aria-label": images[index].alt || t("storefront.images"), className: "sf-zoom sf:fixed sf:inset-0 sf:z-[60] sf:grid sf:cursor-zoom-out sf:place-items-center sf:p-4", onClick: () => zoom(false), children: [_jsx("img", { src: images[index].src, alt: images[index].alt, draggable: false, style: { viewTransitionName: name }, className: "sf-zoom-target sf-vt-product sf:max-h-[88dvh] sf:w-full sf:max-w-[min(92vw,56rem)] sf:object-contain sf:select-none" }), _jsx("button", { type: "button", autoFocus: true, onClick: (event) => { event.stopPropagation(); zoom(false); }, "aria-label": t("storefront.closeZoom"), className: "sf-zoom-close sf:fixed sf:end-4 sf:top-4 sf:grid sf:size-11 sf:place-items-center sf:rounded-full sf:border sf:border-line sf:bg-page sf:text-ink sf:shadow-card", children: _jsx(Close, {}) })] })), count > 1 && (_jsx("ul", { className: "sf-chips sf:flex sf:gap-3 sf:overflow-x-auto sf:pb-1", children: images.map((image, at) => (_jsx("li", { className: "sf:shrink-0", children: _jsx("button", { type: "button", onClick: () => show(at), "aria-label": t("storefront.showImage", { number: at + 1 }), "aria-current": at === index ? "true" : undefined, className: cx("sf:block sf:size-20 sf:overflow-hidden sf:rounded-full sf:border-2 sf:bg-surface sf:p-1 sf:transition sf:focus-visible:outline-2 sf:focus-visible:outline-offset-2 sf:focus-visible:outline-accent", at === index ? "sf:border-accent" : "sf:border-transparent sf:opacity-70 sf:hover:opacity-100"), children: _jsx("img", { src: image.thumb, alt: image.alt, loading: "lazy", className: "sf:size-full sf:rounded-full sf:object-cover" }) }) }, image.src))) }))] }));
344
+ }
345
+ /* ----------------------------------------------------------------- buy box */
346
+ function Stepper({ value, max, onChange, id, words }) {
347
+ const { t } = siteWords(words);
348
+ const set = (next) => onChange(Math.max(1, Math.min(max, next)));
349
+ const step = "sf:grid sf:size-11 sf:place-items-center sf:rounded-full sf:text-ink sf:transition sf:hover:bg-page sf:disabled:opacity-35 sf:disabled:hover:bg-transparent sf:focus-visible:outline-2 sf:focus-visible:outline-accent";
350
+ return (_jsxs("div", { className: "sf:inline-flex sf:items-center sf:gap-1 sf:rounded-full sf:bg-surface sf:p-1", children: [_jsx("button", { type: "button", className: step, "aria-label": t("storefront.decrease"), "aria-controls": id, disabled: value <= 1, onClick: () => set(value - 1), children: _jsx(Minus, {}) }), _jsx("input", { id: id, type: "number", inputMode: "numeric", min: 1, max: max, value: value, onChange: (event) => set(Number(event.target.value) || 1), className: "sf:w-10 sf:bg-transparent sf:text-center sf:text-lg sf:font-semibold sf:text-ink sf:tabular-nums sf:outline-none sf:[appearance:textfield] sf:[&::-webkit-inner-spin-button]:appearance-none sf:[&::-webkit-outer-spin-button]:appearance-none" }), _jsx("button", { type: "button", className: step, "aria-label": t("storefront.increase"), "aria-controls": id, disabled: value >= max, onClick: () => set(value + 1), children: _jsx(Plus, {}) })] }));
351
+ }
352
+ /**
353
+ * Price, options as chips, a quantity stepper, and two ways to buy: into the cart and stay,
354
+ * or into the cart and straight to it. The cart is the shop plugin's, so checkout prices it
355
+ * again on the server whatever this page showed.
356
+ */
357
+ export function BuyBox({ product, price, compareAt, stock, variants = [], currency, cartHref = "/cart", words }) {
358
+ const { t, formatNumber } = siteWords(words);
359
+ const id = useId();
360
+ const [variant, setVariant] = useState(variants.find((option) => option.stock !== 0)?.id ?? null);
361
+ const [quantity, setQuantity] = useState(1);
362
+ const [added, setAdded] = useState(false);
363
+ const chosen = variants.find((option) => option.id === variant) ?? null;
364
+ const left = variants.length ? chosen?.stock ?? null : stock;
365
+ const amount = chosen?.price ?? price;
366
+ const soldOut = variants.length ? !chosen || chosen.stock === 0 : stock === 0;
367
+ const max = Math.max(1, Math.min(99, left ?? 99));
368
+ function choose(option) {
369
+ setVariant(option.id);
370
+ setQuantity((current) => Math.min(current, Math.max(1, option.stock ?? 99)));
371
+ setAdded(false);
372
+ }
373
+ function submit(event) {
374
+ event.preventDefault();
375
+ if (soldOut)
376
+ return;
377
+ addToCart(product, chosen?.id ?? null, quantity);
378
+ // A short tap, as an app gives, on phones that can. Only after a real tap, as browsers refuse it otherwise.
379
+ if (navigator.userActivation?.isActive)
380
+ navigator.vibrate?.(12);
381
+ const submitter = event.nativeEvent.submitter;
382
+ if (submitter?.getAttribute("value") === "buy")
383
+ window.location.assign(sitePath(words, cartHref));
384
+ else
385
+ setAdded(true);
386
+ }
387
+ return (_jsxs("form", { onSubmit: submit, className: "sf:flex sf:flex-col sf:gap-7", children: [_jsxs("div", { className: "sf:flex sf:flex-wrap sf:items-end sf:gap-x-4 sf:gap-y-2", children: [amount !== null && _jsx("p", { className: "sf:text-4xl sf:font-semibold sf:tracking-tight sf:text-ink sf:tabular-nums sf:sm:text-5xl", children: money(formatNumber, amount, currency) }), compareAt !== null && amount !== null && compareAt > amount && _jsx("p", { className: "sf:pb-1.5 sf:text-lg sf:text-muted sf:tabular-nums", children: _jsx("s", { children: money(formatNumber, compareAt, currency) }) }), _jsxs("p", { className: cx("sf:ms-auto sf:mb-1.5 sf:inline-flex sf:items-center sf:gap-1.5 sf:rounded-full sf:px-3 sf:py-1 sf:text-sm sf:font-medium", soldOut ? "sf:bg-surface sf:text-muted" : "sf:bg-accent/10 sf:text-accent"), children: [!soldOut && _jsx(Check, { className: "sf:size-4" }), soldOut ? t("storefront.soldOut") : left !== null && left <= 5 ? t("storefront.onlyLeft", { count: left }) : t("storefront.inStock")] })] }), variants.length > 0 && (_jsxs("fieldset", { className: "sf:flex sf:flex-col sf:gap-3", children: [_jsx("legend", { className: "sf:mb-3 sf:text-sm sf:font-medium sf:text-muted", children: t("storefront.options") }), _jsx("div", { className: "sf:flex sf:flex-wrap sf:gap-2", children: variants.map((option) => (_jsxs("label", { className: "sf:relative", children: [_jsx("input", { type: "radio", name: `${id}-variant`, value: option.id, checked: variant === option.id, disabled: option.stock === 0, onChange: () => choose(option), className: "sf:peer sf:sr-only" }), _jsx("span", { className: "sf:inline-flex sf:h-12 sf:min-w-12 sf:cursor-pointer sf:items-center sf:justify-center sf:rounded-full sf:border sf:border-line sf:bg-page sf:px-4 sf:text-sm sf:font-medium sf:text-ink sf:transition sf:select-none sf:hover:border-ink sf:peer-checked:border-accent sf:peer-checked:bg-accent sf:peer-checked:text-on-accent sf:peer-focus-visible:ring-4 sf:peer-focus-visible:ring-accent/25 sf:peer-disabled:cursor-not-allowed sf:peer-disabled:text-muted sf:peer-disabled:line-through sf:peer-disabled:opacity-60 sf:peer-disabled:hover:border-line", children: option.title })] }, option.id))) })] })), !soldOut && (_jsxs("div", { className: "sf:flex sf:items-center sf:gap-4", children: [_jsx("label", { htmlFor: `${id}-quantity`, className: "sf:text-sm sf:font-medium sf:text-muted", children: t("storefront.quantity") }), _jsx(Stepper, { id: `${id}-quantity`, value: Math.min(quantity, max), max: max, onChange: (value) => { setQuantity(value); setAdded(false); }, words: words })] })), _jsxs("div", { className: "sf-buybar sf:grid sf:grid-cols-2 sf:gap-3", children: [_jsx("button", { type: "submit", value: "buy", disabled: soldOut, className: "sf:inline-flex sf:h-14 sf:items-center sf:justify-center sf:rounded-full sf:bg-accent sf:px-6 sf:text-base sf:font-semibold sf:text-on-accent sf:shadow-[0_10px_24px_-10px] sf:shadow-accent sf:transition sf:hover:brightness-110 sf:active:scale-[0.98] sf:disabled:cursor-not-allowed sf:disabled:opacity-50 sf:disabled:shadow-none sf:focus-visible:outline-2 sf:focus-visible:outline-offset-2 sf:focus-visible:outline-accent", children: t("storefront.buyNow") }), _jsx("button", { type: "submit", value: "add", disabled: soldOut, className: "sf:inline-flex sf:h-14 sf:items-center sf:justify-center sf:rounded-full sf:border sf:border-line sf:bg-surface sf:px-6 sf:text-base sf:font-semibold sf:text-ink sf:transition sf:hover:border-ink sf:active:scale-[0.98] sf:disabled:cursor-not-allowed sf:disabled:opacity-50 sf:focus-visible:outline-2 sf:focus-visible:outline-offset-2 sf:focus-visible:outline-accent", children: soldOut ? t("storefront.soldOut") : t("storefront.addToCart") })] }), _jsx("p", { role: "status", className: cx("sf:-mt-3 sf:text-sm sf:text-accent", !added && "sf:sr-only"), children: added && _jsxs(_Fragment, { children: [t("storefront.added"), " ", _jsx("a", { href: sitePath(words, cartHref), className: "sf:font-semibold sf:underline sf:underline-offset-4", children: t("storefront.viewCart") })] }) })] }));
388
+ }
389
+ /* ------------------------------------------------------------------- share */
390
+ /** The browser's share sheet where there is one, and copying the address where there isn't. */
391
+ const CAME_FROM = "sf-came-from";
392
+ const withoutHash = (href) => href.split("#")[0];
393
+ /** Where the visitor followed a link here from, when this page is where it led. */
394
+ function cameFrom() {
395
+ try {
396
+ const kind = performance.getEntriesByType("navigation")[0]?.type;
397
+ const note = JSON.parse(sessionStorage.getItem(CAME_FROM) ?? "null");
398
+ if ((kind !== "navigate" && !softNavigated) || !note || withoutHash(note.to) !== withoutHash(location.href))
399
+ return null;
400
+ const from = new URL(note.from);
401
+ return from.origin === location.origin && withoutHash(from.href) !== withoutHash(location.href) ? withoutHash(from.href) : null;
402
+ }
403
+ catch {
404
+ return null;
405
+ }
406
+ }
407
+ /** Leaves the note `cameFrom` reads whenever a link to another page here is followed. Rendered by the layout, on every page. */
408
+ function useCameFromNote() {
409
+ useEffect(() => {
410
+ const note = (event) => {
411
+ const link = event.target?.closest?.("a[href]");
412
+ if (!link || link.origin !== location.origin || link.target === "_blank" || link.hasAttribute("download"))
413
+ return;
414
+ try {
415
+ sessionStorage.setItem(CAME_FROM, JSON.stringify({ from: location.href, to: link.href }));
416
+ }
417
+ catch {
418
+ // Storage can be off. The back arrow then follows its own link.
419
+ }
420
+ };
421
+ document.addEventListener("click", note, true);
422
+ return () => document.removeEventListener("click", note, true);
423
+ }, []);
424
+ }
425
+ /**
426
+ * A back arrow that returns to the page the visitor came from, as an app's does. It goes there as
427
+ * a new move forward rather than back through history, so it gets the same transition as any link,
428
+ * and adds `#` and the card of `card`, the product being left: the browser scrolls that card into
429
+ * view as the page shows, so the list comes back where the visitor was and the product's
430
+ * picture flies back into its own card. The address is worked out once the page has loaded, before
431
+ * this page's own links leave a note of their own. Opened from a shared link or a new tab, it is
432
+ * `href`.
433
+ */
434
+ export function BackLink({ href, card, className, children }) {
435
+ const [target, setTarget] = useState(href);
436
+ const pathname = usePathname();
437
+ useEffect(() => {
438
+ const from = cameFrom();
439
+ // eslint-disable-next-line react-hooks/set-state-in-effect -- sessionStorage only exists in the browser
440
+ setTarget(from ? (card === undefined ? from : `${from}#${cardAnchor(card)}`) : href);
441
+ }, [card, href, pathname]);
442
+ return _jsx("a", { href: target, className: className, children: children });
443
+ }
444
+ export function ShareButton({ title, words, className }) {
445
+ const { t } = siteWords(words);
446
+ const [copied, setCopied] = useState(false);
447
+ async function share() {
448
+ const url = window.location.href;
449
+ if (typeof navigator.share === "function") {
450
+ await navigator.share({ title, url }).catch(() => null);
451
+ return;
452
+ }
453
+ try {
454
+ await navigator.clipboard.writeText(url);
455
+ setCopied(true);
456
+ setTimeout(() => setCopied(false), 2000);
457
+ }
458
+ catch { /* clipboard blocked: nothing to say */ }
459
+ }
460
+ return (_jsxs(_Fragment, { children: [_jsx("button", { type: "button", onClick: share, "aria-label": t("storefront.share"), className: className, children: copied ? _jsx(Check, {}) : _jsx(Send, {}) }), _jsx("span", { role: "status", className: "sf:sr-only", children: copied ? t("storefront.copied") : "" })] }));
461
+ }
Binary file
@@ -0,0 +1 @@
1
+ Geist by Vercel and basement.studio, under the SIL Open Font License 1.1: https://github.com/vercel/geist-font
package/icons.d.ts ADDED
@@ -0,0 +1,21 @@
1
+ import type { SVGProps } from "react";
2
+ type Props = SVGProps<SVGSVGElement>;
3
+ export declare const ArrowUpRight: (props: Props) => import("react").JSX.Element;
4
+ export declare const ChevronLeft: (props: Props) => import("react").JSX.Element;
5
+ export declare const ChevronRight: (props: Props) => import("react").JSX.Element;
6
+ export declare const ChevronDown: (props: Props) => import("react").JSX.Element;
7
+ export declare const Bag: (props: Props) => import("react").JSX.Element;
8
+ export declare const Store: (props: Props) => import("react").JSX.Element;
9
+ export declare const BookOpen: (props: Props) => import("react").JSX.Element;
10
+ export declare const Download: (props: Props) => import("react").JSX.Element;
11
+ export declare const Lock: (props: Props) => import("react").JSX.Element;
12
+ export declare const Close: (props: Props) => import("react").JSX.Element;
13
+ export declare const User: (props: Props) => import("react").JSX.Element;
14
+ export declare const Search: (props: Props) => import("react").JSX.Element;
15
+ export declare const Send: (props: Props) => import("react").JSX.Element;
16
+ export declare const Globe: (props: Props) => import("react").JSX.Element;
17
+ export declare const Bars: (props: Props) => import("react").JSX.Element;
18
+ export declare const Minus: (props: Props) => import("react").JSX.Element;
19
+ export declare const Plus: (props: Props) => import("react").JSX.Element;
20
+ export declare const Check: (props: Props) => import("react").JSX.Element;
21
+ export {};