@zappie/foundations 0.9.2 → 0.9.3

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 CHANGED
@@ -1,5 +1,13 @@
1
1
  # @zappie/foundations
2
2
 
3
+ ## 0.9.3
4
+
5
+ ### Patch Changes
6
+
7
+ - ad0e714: New `@zappie/foundations/branch-switch` entry for React Router sites. `createBranchSwitchLoader({ shopAt })` gives the root route a `clientLoader` that reads only the chosen branch's menu in the browser when a link names another branch of the store already loaded, and a `shouldRevalidate` that reloads the shop only for another branch. `useBranchIntent(branch)` starts the menu read on pointer, touch and focus. `useChooseBranch(then)` moves a bag with lines to the branch before `then` navigates. `useReloadingBranch(shop, { location, navigation })` names the branch the shop is reloading for, so you can show your own skeleton. `reloadsShop`, `branchNamed` and `loadedBranchOf` are exported too.
8
+ - Updated dependencies [ad0e714]
9
+ - @zappie/sdk@0.10.3
10
+
3
11
  ## 0.9.2
4
12
 
5
13
  ### Patch Changes
package/README.md CHANGED
@@ -31,11 +31,12 @@ Want ready-made, styled components instead? Copy them into your project from the
31
31
 
32
32
  ## Entry points
33
33
 
34
- | Import | For |
35
- | ------------------------------- | --------------------------------------------------------------- |
36
- | `@zappie/foundations` | Every part |
37
- | `@zappie/foundations/next` | Keeping overlays in step with Back and Forward in a Next.js app |
38
- | `@zappie/foundations/rich-text` | Sanitising and parsing merchant rich text before you render it |
34
+ | Import | For |
35
+ | ----------------------------------- | ----------------------------------------------------------------------- |
36
+ | `@zappie/foundations` | Every part |
37
+ | `@zappie/foundations/next` | Keeping overlays in step with Back and Forward in a Next.js app |
38
+ | `@zappie/foundations/branch-switch` | Choosing a branch in a React Router site without waiting for the server |
39
+ | `@zappie/foundations/rich-text` | Sanitising and parsing merchant rich text before you render it |
39
40
 
40
41
  ## Docs
41
42
 
@@ -110,6 +111,110 @@ then the panel is hidden from assistive technology and takes no keys, presses or
110
111
  scrolls, apart from Escape and an outside press, which close it. Style the panel
111
112
  and `[data-zappie-backdrop]` as usual: both frames match them.
112
113
 
114
+ ## Branch switch
115
+
116
+ Choosing a branch shows that branch's menu without waiting for the server. A
117
+ link to another branch of the store already loaded reads only that branch's
118
+ menu in the browser, and the read starts when the shopper reaches for the
119
+ button. It has its own entry, `@zappie/foundations/branch-switch`, so pages
120
+ that don't use it never load it. Use it in a React Router root route:
121
+
122
+ ```tsx
123
+ import {
124
+ createBranchSwitchLoader,
125
+ useReloadingBranch,
126
+ } from "@zappie/foundations";
127
+
128
+ const branchSwitch = createBranchSwitchLoader<ShopData>({
129
+ // What your loader returns for ?branch=<that branch>. Recompute every field
130
+ // that depends on the branch.
131
+ shopAt: (shop, branch, menu) => ({
132
+ ...shop,
133
+ config: { ...shop.config, branch: branch.id },
134
+ branch,
135
+ menu,
136
+ branchChosen: true,
137
+ mustChoose: false,
138
+ }),
139
+ // Paths your loader redirects go to the server.
140
+ serverOnly: (url, shop) => Boolean(redirectFor(shop.store, url.pathname)),
141
+ });
142
+
143
+ export const shouldRevalidate: ShouldRevalidateFunction = (args) =>
144
+ branchSwitch.shouldRevalidate(args);
145
+ export const clientLoader = (args: Route.ClientLoaderArgs) =>
146
+ branchSwitch.clientLoader(args);
147
+
148
+ export default function App() {
149
+ const shop = useLoaderData<typeof loader>();
150
+ const client = useMemo(() => createZappie(shop.config), [shop.config.branch]);
151
+ branchSwitch.remember(shop, client);
152
+ return <ZappieProvider client={client}>…</ZappieProvider>;
153
+ }
154
+ ```
155
+
156
+ - `createBranchSwitchLoader({ shopAt, serverOnly?, param? })` returns
157
+ `remember`, `shouldRevalidate` and `clientLoader`. Your loader data needs
158
+ `store`, `branch` and, when the shopper chooses a branch, `branchChosen`.
159
+ Without `branchChosen` the loaded branch counts as chosen.
160
+ - `clientLoader` builds the shop with `shopAt` from the shop the root last
161
+ rendered. An unknown branch, a `serverOnly` URL or a failed read calls
162
+ `serverLoader()`. A cancelled navigation throws.
163
+ - `shouldRevalidate` reloads the shop only for a link that names another
164
+ branch. A link without `?branch=` keeps the branch, and so does a link to the
165
+ branch already loaded and chosen. Form submissions keep React Router's rule.
166
+ - `reloadsShop`, `branchNamed` and `loadedBranchOf` are the rules behind them,
167
+ for your own code.
168
+
169
+ Read the menu on intent, and move the bag before you navigate:
170
+
171
+ ```tsx
172
+ import {
173
+ useBranchIntent,
174
+ useChooseBranch,
175
+ } from "@zappie/foundations/branch-switch";
176
+
177
+ function BranchCard({ branch }: { branch: Branch }) {
178
+ const intent = useBranchIntent(branch);
179
+ const navigate = useNavigate();
180
+ const choose = useChooseBranch((next) => {
181
+ rememberBranch(next.id);
182
+ navigate(`/menu?branch=${next.slug}`);
183
+ });
184
+ return (
185
+ <button type="button" {...intent} onClick={() => void choose(branch)}>
186
+ Order from {branch.name}
187
+ </button>
188
+ );
189
+ }
190
+ ```
191
+
192
+ - `useBranchIntent(branch)` returns `{ onPointerEnter, onPointerDown, onFocus }`.
193
+ Each starts the branch's menu read. The client shares one read per branch,
194
+ so the click and the loader reuse it.
195
+ - `useChooseBranch(then)` starts the menu read, moves a bag with lines to the
196
+ branch, and calls `then` once the move is done. Remember the choice and
197
+ navigate in `then`. Keep the branch ID in your cookie: the server then reads
198
+ the store and the menu at once (`loadStoreAndMenu` in `@zappie/sdk/server`).
199
+
200
+ Show your own skeleton while the shop reloads for a branch:
201
+
202
+ ```tsx
203
+ const reloading = useReloadingBranch(shop, {
204
+ location: useLocation(),
205
+ navigation: useNavigation(),
206
+ });
207
+ return reloading?.pathname === "/menu" ? (
208
+ <MenuSkeleton branch={reloading.branch} />
209
+ ) : (
210
+ <Outlet />
211
+ );
212
+ ```
213
+
214
+ `useReloadingBranch(shop, { location, navigation }, param?)` returns
215
+ `{ branch, pathname }` while a navigation reloads the shop for a branch the
216
+ store has, and undefined otherwise.
217
+
113
218
  ## Item form focus
114
219
 
115
220
  When an add fails validation, `ItemForm.Root` focuses the first invalid group
@@ -0,0 +1,168 @@
1
+ import { Store, Branch, Zappie, Menu } from '@zappie/sdk';
2
+ import { IntentPreloadHandlers } from '../index.js';
3
+ import 'react';
4
+
5
+ /**
6
+ * The parts of a site's root loader data the branch switch reads: the store,
7
+ * the branch the shop was loaded for, and whether the shopper chose it. A site
8
+ * without a branch choice leaves `branchChosen` out, and the loaded branch
9
+ * counts as chosen.
10
+ */
11
+ type BranchSwitchShop = {
12
+ store: Store;
13
+ branch?: Branch | undefined;
14
+ branchChosen?: boolean | undefined;
15
+ };
16
+ /** The branch a shop was loaded for, and whether the shopper chose it. */
17
+ type LoadedBranch = {
18
+ id?: string | undefined;
19
+ slug?: string | undefined;
20
+ chosen: boolean;
21
+ };
22
+ /** Settings for `createBranchSwitchLoader`. */
23
+ type BranchSwitchOptions<T extends BranchSwitchShop> = {
24
+ /**
25
+ * The shop at another branch: what your root loader returns for
26
+ * `?branch=<that branch>`, built from the shop already loaded and that
27
+ * branch's menu. Recompute every field that depends on the branch here.
28
+ */
29
+ shopAt(shop: T, branch: Branch, menu: Menu): T;
30
+ /**
31
+ * Return true to send this URL to the server loader anyway, such as a path
32
+ * your loader redirects.
33
+ */
34
+ serverOnly?(url: URL, shop: T): boolean;
35
+ /** The query parameter that names a branch in a link. Defaults to `branch`. */
36
+ param?: string;
37
+ };
38
+ /** The arguments React Router passes to `shouldRevalidate` that the branch switch reads. */
39
+ type BranchSwitchRevalidateArgs = {
40
+ currentUrl: URL;
41
+ nextUrl: URL;
42
+ formMethod?: string | undefined;
43
+ defaultShouldRevalidate: boolean;
44
+ };
45
+ /** The arguments React Router passes to a `clientLoader` that the branch switch reads. */
46
+ type BranchSwitchClientLoaderArgs<S> = {
47
+ request: Request;
48
+ serverLoader: () => Promise<S>;
49
+ };
50
+ /** The root route's `clientLoader` and `shouldRevalidate` for a fast branch switch. */
51
+ type BranchSwitchLoader<T extends BranchSwitchShop> = {
52
+ /**
53
+ * Keep the shop the root rendered and the client it reads with. Call it in
54
+ * the root component on every render, before `ZappieProvider`. It does
55
+ * nothing on the server.
56
+ */
57
+ remember(shop: T, client: Zappie): void;
58
+ /** Reload the shop only for a link to another branch. Form submissions keep React Router's rule. */
59
+ shouldRevalidate(args: BranchSwitchRevalidateArgs): boolean;
60
+ /**
61
+ * A link to another branch of the store already loaded reads only that
62
+ * branch's menu, in the browser, and builds the shop with `shopAt`. Any
63
+ * other link, or a failed read, calls `serverLoader`.
64
+ */
65
+ clientLoader<S>(args: BranchSwitchClientLoaderArgs<S>): Promise<T | S>;
66
+ };
67
+ /** The branch the shop was loaded for, and whether the shopper chose it. */
68
+ declare function loadedBranchOf(shop: BranchSwitchShop): LoadedBranch;
69
+ /**
70
+ * The store's branch a link names, by ID or slug, as `resolveBranch` matches it.
71
+ *
72
+ * @param store - The store, with its branches.
73
+ * @param wanted - The value of the link's branch parameter.
74
+ */
75
+ declare function branchNamed(store: Store, wanted: string | null | undefined): Branch | undefined;
76
+ /**
77
+ * Whether moving from one URL to the next loads the shop again. Only a link
78
+ * that names another branch does. A link without the branch parameter keeps
79
+ * the branch already loaded, and a link to the branch already loaded and
80
+ * chosen reads nothing again.
81
+ *
82
+ * @param current - The current URL's query.
83
+ * @param next - The next URL's query.
84
+ * @param loaded - The branch the shop was loaded for.
85
+ * @param param - The query parameter that names a branch. Defaults to `branch`.
86
+ */
87
+ declare function reloadsShop(current: URLSearchParams, next: URLSearchParams, loaded: LoadedBranch | undefined, param?: string): boolean;
88
+ /**
89
+ * The root route's `clientLoader` and `shouldRevalidate` for choosing a
90
+ * branch without waiting for the server. Moving to another branch of the
91
+ * store already loaded reads only that branch's menu from the browser: one
92
+ * request instead of the server reading the store and then the menu, and none
93
+ * when `useBranchIntent` already read it. Create it once at module scope.
94
+ *
95
+ * @example
96
+ * const branchSwitch = createBranchSwitchLoader<ShopData>({
97
+ * shopAt: (shop, branch, menu) => ({ ...shop, config: { ...shop.config, branch: branch.id }, branch, menu, branchChosen: true, mustChoose: false }),
98
+ * serverOnly: (url, shop) => Boolean(redirectFor(shop.store, url.pathname)),
99
+ * });
100
+ * export const shouldRevalidate: ShouldRevalidateFunction = (args) => branchSwitch.shouldRevalidate(args);
101
+ * export const clientLoader = (args: Route.ClientLoaderArgs) => branchSwitch.clientLoader(args);
102
+ */
103
+ declare function createBranchSwitchLoader<T extends BranchSwitchShop>({ shopAt, serverOnly, param, }: BranchSwitchOptions<T>): BranchSwitchLoader<T>;
104
+ /**
105
+ * Pointer, touch and focus handlers that start reading a branch's menu when
106
+ * the shopper reaches for the control that chooses it. The client keeps one
107
+ * read per branch, so the branch switch picks up this read, or its result,
108
+ * instead of starting another. Spread the result on the control.
109
+ *
110
+ * @example
111
+ * const intent = useBranchIntent(branch);
112
+ * <button {...intent} onClick={() => choose(branch)}>Order from {branch.name}</button>
113
+ *
114
+ * @param branch - The branch the control chooses, or its ID.
115
+ */
116
+ declare function useBranchIntent(branch: Branch | string): IntentPreloadHandlers;
117
+ /**
118
+ * Choose a branch to order from. The branch's menu starts loading at once.
119
+ * A bag with lines from another branch moves there first, and `then` runs
120
+ * once the move is done, so the shopper never lands on a branch whose bag is
121
+ * still moving. Remember the choice and navigate in `then`.
122
+ *
123
+ * @example
124
+ * const choose = useChooseBranch((branch) => {
125
+ * rememberBranch(branch.id);
126
+ * navigate(`/menu?branch=${branch.slug}`);
127
+ * });
128
+ *
129
+ * @param then - What to do once the bag is at the branch.
130
+ * @returns A function that chooses a branch and resolves after `then`.
131
+ */
132
+ declare function useChooseBranch(then: (branch: Branch) => void | Promise<void>): (branch: Branch) => Promise<void>;
133
+ /** The router state `useReloadingBranch` reads: React Router's `useLocation()` and `useNavigation()`. */
134
+ type BranchSwitchRouterState = {
135
+ location: {
136
+ search: string;
137
+ };
138
+ navigation: {
139
+ state: string;
140
+ location?: {
141
+ pathname: string;
142
+ search: string;
143
+ } | undefined;
144
+ };
145
+ };
146
+ /** A branch the shop is reloading for, and the path the shopper is moving to. */
147
+ type ReloadingBranch = {
148
+ branch: Branch;
149
+ pathname: string;
150
+ };
151
+ /**
152
+ * The branch the shop is reloading for while the shopper moves to another
153
+ * branch of the store, so you can show your own skeleton, such as the menu's,
154
+ * from the tap. Undefined while nothing reloads, or the link names a branch
155
+ * the store doesn't have.
156
+ *
157
+ * @example
158
+ * const reloading = useReloadingBranch(shop, { location: useLocation(), navigation: useNavigation() });
159
+ * {reloading?.pathname === "/menu" ? <MenuSkeleton branch={reloading.branch} /> : <Outlet />}
160
+ *
161
+ * @param shop - The shop the root rendered.
162
+ * @param router - The current location and navigation.
163
+ * @param param - The query parameter that names a branch. Defaults to `branch`.
164
+ */
165
+ declare function useReloadingBranch(shop: BranchSwitchShop, { location, navigation }: BranchSwitchRouterState, param?: string): ReloadingBranch | undefined;
166
+
167
+ export { branchNamed, createBranchSwitchLoader, loadedBranchOf, reloadsShop, useBranchIntent, useChooseBranch, useReloadingBranch };
168
+ export type { BranchSwitchClientLoaderArgs, BranchSwitchLoader, BranchSwitchOptions, BranchSwitchRevalidateArgs, BranchSwitchRouterState, BranchSwitchShop, LoadedBranch, ReloadingBranch };
@@ -0,0 +1,126 @@
1
+ "use client";
2
+
3
+ // src/branch-switch/index.ts
4
+ import { useCart, useZappie } from "@zappie/sdk/react";
5
+ import { useMemo } from "react";
6
+ import { useIntentPreload } from "../deferred/index.js";
7
+ function loadedBranchOf(shop) {
8
+ return {
9
+ ...shop.branch ? { id: shop.branch.id, slug: shop.branch.slug } : {},
10
+ chosen: shop.branchChosen ?? true
11
+ };
12
+ }
13
+ function branchNamed(store, wanted) {
14
+ return wanted ? store.branches.find(
15
+ (branch) => branch.id === wanted || branch.slug === wanted
16
+ ) : void 0;
17
+ }
18
+ function reloadsShop(current, next, loaded, param = "branch") {
19
+ const wanted = next.get(param);
20
+ if (wanted === null || wanted === current.get(param)) {
21
+ return false;
22
+ }
23
+ return !(loaded?.chosen && (wanted === loaded.id || wanted === loaded.slug));
24
+ }
25
+ function createBranchSwitchLoader({
26
+ shopAt,
27
+ serverOnly,
28
+ param = "branch"
29
+ }) {
30
+ let live;
31
+ return {
32
+ remember(shop, client) {
33
+ if (typeof window !== "undefined") {
34
+ live = { shop, client };
35
+ }
36
+ },
37
+ shouldRevalidate({
38
+ currentUrl,
39
+ nextUrl,
40
+ formMethod,
41
+ defaultShouldRevalidate
42
+ }) {
43
+ if (formMethod && formMethod.toUpperCase() !== "GET") {
44
+ return defaultShouldRevalidate;
45
+ }
46
+ return reloadsShop(
47
+ currentUrl.searchParams,
48
+ nextUrl.searchParams,
49
+ live && loadedBranchOf(live.shop),
50
+ param
51
+ );
52
+ },
53
+ async clientLoader({ request, serverLoader }) {
54
+ const url = new URL(request.url);
55
+ const current = live;
56
+ const branch = current ? branchNamed(current.shop.store, url.searchParams.get(param)) : void 0;
57
+ if (current && branch && !serverOnly?.(url, current.shop)) {
58
+ try {
59
+ const menu = await current.client.menu.get({
60
+ branch: branch.id,
61
+ signal: request.signal
62
+ });
63
+ return shopAt(current.shop, branch, menu);
64
+ } catch (error) {
65
+ if (request.signal.aborted) {
66
+ throw error;
67
+ }
68
+ }
69
+ }
70
+ return serverLoader();
71
+ }
72
+ };
73
+ }
74
+ var readMenu = (client, branch) => client.menu.get({ branch: typeof branch === "string" ? branch : branch.id });
75
+ function useBranchIntent(branch) {
76
+ const client = useZappie();
77
+ return useIntentPreload(
78
+ useMemo(
79
+ () => ({ preload: () => readMenu(client, branch) }),
80
+ [client, branch]
81
+ )
82
+ );
83
+ }
84
+ function useChooseBranch(then) {
85
+ const client = useZappie();
86
+ const cart = useCart();
87
+ return async (branch) => {
88
+ readMenu(client, branch).catch(() => {
89
+ });
90
+ if (cart.lines.length > 0 && branch.id !== cart.branchId) {
91
+ await cart.actions.moveTo(branch.id);
92
+ }
93
+ await then(branch);
94
+ };
95
+ }
96
+ function useReloadingBranch(shop, { location, navigation }, param = "branch") {
97
+ const next = navigation.state === "loading" ? navigation.location : void 0;
98
+ const pathname = next?.pathname;
99
+ const search = next?.search;
100
+ return useMemo(() => {
101
+ if (pathname === void 0 || search === void 0) {
102
+ return void 0;
103
+ }
104
+ const wanted = new URLSearchParams(search);
105
+ if (!reloadsShop(
106
+ new URLSearchParams(location.search),
107
+ wanted,
108
+ loadedBranchOf(shop),
109
+ param
110
+ )) {
111
+ return void 0;
112
+ }
113
+ const branch = branchNamed(shop.store, wanted.get(param));
114
+ return branch ? { branch, pathname } : void 0;
115
+ }, [shop, location.search, pathname, search, param]);
116
+ }
117
+ export {
118
+ branchNamed,
119
+ createBranchSwitchLoader,
120
+ loadedBranchOf,
121
+ reloadsShop,
122
+ useBranchIntent,
123
+ useChooseBranch,
124
+ useReloadingBranch
125
+ };
126
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,6 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/branch-switch/index.ts"],
4
+ "mappings": "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",
5
+ "names": []
6
+ }
@@ -0,0 +1,91 @@
1
+ import { ComponentType, ReactNode, ReactElement } from 'react';
2
+
3
+ /** Props for a deferred component: its own props plus `open`, which the helper reads and passes on. */
4
+ type DeferredProps<P> = Omit<P, "open"> & {
5
+ /**
6
+ * Load the code if needed and render the component. Before the first open
7
+ * it renders nothing; after it, the component stays mounted and receives
8
+ * `open`, so it can animate out and return focus when it closes.
9
+ */
10
+ open: boolean;
11
+ /** Shown while `open` is true and the code is still loading, for inline parts that should hold their place. */
12
+ fallback?: ReactNode;
13
+ /**
14
+ * Shown while `open` is true and the code failed to load. Call `retry` to load it again.
15
+ * A later `preload()`, such as the next tap on the trigger, also retries and renders on success.
16
+ */
17
+ failed?: (retry: () => void) => ReactNode;
18
+ };
19
+ /** Options for `preloadWhenIdle`. */
20
+ type DeferredIdleOptions = {
21
+ /** Start the load after this many milliseconds even if the browser never goes idle. */
22
+ timeout?: number;
23
+ };
24
+ /**
25
+ * A component whose code loads on demand and renders without suspending.
26
+ * Create it once at module scope with `deferred()`.
27
+ */
28
+ type Deferred<P> = {
29
+ /**
30
+ * Start loading the code. Repeated calls share one load. A failed load is
31
+ * forgotten, so the next call tries again.
32
+ * @returns The loaded component, or the load error.
33
+ */
34
+ preload(): Promise<ComponentType<P>>;
35
+ /**
36
+ * Load the code once the browser is idle. Use it only for small chunks.
37
+ * Does nothing on the server.
38
+ * @returns A function that cancels the scheduled load.
39
+ */
40
+ preloadWhenIdle(options?: DeferredIdleOptions): () => void;
41
+ /**
42
+ * Renders nothing until `open` is first true and the code is in. When
43
+ * `open` turns true it loads the code and renders as soon as it arrives. If
44
+ * the load fails it shows `failed` and renders once a retry or a later
45
+ * `preload()` succeeds. It never suspends. After the first open the component stays mounted and
46
+ * every prop passes through, `open` included, so it can run its own exit.
47
+ */
48
+ Component: (props: DeferredProps<P>) => ReactElement | null;
49
+ };
50
+ /** Event handlers that start loading a deferred component when a shopper reaches for its trigger. */
51
+ type IntentPreloadHandlers = {
52
+ onPointerEnter: () => void;
53
+ onPointerDown: () => void;
54
+ onFocus: () => void;
55
+ };
56
+ /** What a deferred load resolves to: a component, or a module whose default export is one. */
57
+ type DeferredModule = ComponentType<never> | {
58
+ default: ComponentType<never>;
59
+ };
60
+ /** The props of the component a deferred load resolves to. */
61
+ type DeferredModuleProps<T> = T extends {
62
+ default: ComponentType<infer P>;
63
+ } ? P : T extends ComponentType<infer P> ? P : never;
64
+ /**
65
+ * Load a component's code on demand without `React.lazy` or `<Suspense>`.
66
+ * React holds a suspended boundary's first reveal for about 300 ms, so a
67
+ * lazy overlay opens late. A deferred one renders on the frame its code
68
+ * arrives. Pass a module whose default export is the component, or resolve
69
+ * to the component itself.
70
+ *
71
+ * @example
72
+ * const Bag = deferred(() => import("./bag-sheet"));
73
+ * const Finder = deferred(() => import("./finder").then((m) => m.Finder));
74
+ * <Bag.Component open={open} onClose={close} />
75
+ */
76
+ declare function deferred<T extends DeferredModule>(load: () => Promise<T>): Deferred<DeferredModuleProps<T>>;
77
+ /**
78
+ * Start loading a deferred component when the shopper points at, presses or
79
+ * focuses its trigger, so the code is usually in by the click. Spread the
80
+ * result on the trigger.
81
+ *
82
+ * @example
83
+ * const intent = useIntentPreload(Bag);
84
+ * <button {...intent} onClick={openBag}>Bag</button>
85
+ */
86
+ declare function useIntentPreload(target: {
87
+ preload(): Promise<unknown>;
88
+ }): IntentPreloadHandlers;
89
+
90
+ export { deferred as d, useIntentPreload as u };
91
+ export type { Deferred as D, IntentPreloadHandlers as I, DeferredIdleOptions as a, DeferredProps as b };
package/dist/index.d.ts CHANGED
@@ -1,12 +1,13 @@
1
1
  import { P as PartOwnedAttributes, a as PartProps } from './engine-D2iRshfW.js';
2
2
  import { Presentation, SwipeDirection } from './overlay/engine.js';
3
3
  import * as react from 'react';
4
- import { HTMLAttributes, ReactNode, ComponentType, ReactElement, KeyboardEvent as KeyboardEvent$1, ImgHTMLAttributes, ChangeEvent, ClipboardEvent } from 'react';
4
+ import { HTMLAttributes, ReactNode, KeyboardEvent as KeyboardEvent$1, ImgHTMLAttributes, ChangeEvent, ClipboardEvent } from 'react';
5
5
  import { ZappieEnvironment } from '@zappie/sdk/services';
6
6
  import * as _zappie_sdk from '@zappie/sdk';
7
7
  import { Branch as Branch$1, CartLine, Money as Money$1, CartLineInput, CartIssue, CartFix, Quote, DeliveryAddress, MenuSchedule, CartFulfilment, OptionGroup as OptionGroup$1, Item, Choice as Choice$1, MoneyFormatOptions, PaymentMethodKind, Category, Menu, Store, OpeningTime } from '@zappie/sdk';
8
8
  import { Coordinates } from '@zappie/sdk/branches';
9
9
  import { useCart } from '@zappie/sdk/react';
10
+ export { D as Deferred, a as DeferredIdleOptions, b as DeferredProps, I as IntentPreloadHandlers, d as deferred, u as useIntentPreload } from './index-B1NMxq0i.js';
10
11
  import { C as CloseOptions, O as OverlayQuery } from './history-BlytQinP.js';
11
12
  import { SelectionControl } from '@zappie/sdk/options';
12
13
  import '@base-ui/react/dialog';
@@ -310,93 +311,6 @@ declare const Totals: react.ForwardRefExoticComponent<Omit<react.AllHTMLAttribut
310
311
  children?: react.ReactNode | ((state: TotalsState) => react.ReactNode);
311
312
  } & react.RefAttributes<HTMLElement>>;
312
313
 
313
- /** Props for a deferred component: its own props plus `open`, which the helper reads and passes on. */
314
- type DeferredProps<P> = Omit<P, "open"> & {
315
- /**
316
- * Load the code if needed and render the component. Before the first open
317
- * it renders nothing; after it, the component stays mounted and receives
318
- * `open`, so it can animate out and return focus when it closes.
319
- */
320
- open: boolean;
321
- /** Shown while `open` is true and the code is still loading, for inline parts that should hold their place. */
322
- fallback?: ReactNode;
323
- /**
324
- * Shown while `open` is true and the code failed to load. Call `retry` to load it again.
325
- * A later `preload()`, such as the next tap on the trigger, also retries and renders on success.
326
- */
327
- failed?: (retry: () => void) => ReactNode;
328
- };
329
- /** Options for `preloadWhenIdle`. */
330
- type DeferredIdleOptions = {
331
- /** Start the load after this many milliseconds even if the browser never goes idle. */
332
- timeout?: number;
333
- };
334
- /**
335
- * A component whose code loads on demand and renders without suspending.
336
- * Create it once at module scope with `deferred()`.
337
- */
338
- type Deferred<P> = {
339
- /**
340
- * Start loading the code. Repeated calls share one load. A failed load is
341
- * forgotten, so the next call tries again.
342
- * @returns The loaded component, or the load error.
343
- */
344
- preload(): Promise<ComponentType<P>>;
345
- /**
346
- * Load the code once the browser is idle. Use it only for small chunks.
347
- * Does nothing on the server.
348
- * @returns A function that cancels the scheduled load.
349
- */
350
- preloadWhenIdle(options?: DeferredIdleOptions): () => void;
351
- /**
352
- * Renders nothing until `open` is first true and the code is in. When
353
- * `open` turns true it loads the code and renders as soon as it arrives. If
354
- * the load fails it shows `failed` and renders once a retry or a later
355
- * `preload()` succeeds. It never suspends. After the first open the component stays mounted and
356
- * every prop passes through, `open` included, so it can run its own exit.
357
- */
358
- Component: (props: DeferredProps<P>) => ReactElement | null;
359
- };
360
- /** Event handlers that start loading a deferred component when a shopper reaches for its trigger. */
361
- type IntentPreloadHandlers = {
362
- onPointerEnter: () => void;
363
- onPointerDown: () => void;
364
- onFocus: () => void;
365
- };
366
- /** What a deferred load resolves to: a component, or a module whose default export is one. */
367
- type DeferredModule = ComponentType<never> | {
368
- default: ComponentType<never>;
369
- };
370
- /** The props of the component a deferred load resolves to. */
371
- type DeferredModuleProps<T> = T extends {
372
- default: ComponentType<infer P>;
373
- } ? P : T extends ComponentType<infer P> ? P : never;
374
- /**
375
- * Load a component's code on demand without `React.lazy` or `<Suspense>`.
376
- * React holds a suspended boundary's first reveal for about 300 ms, so a
377
- * lazy overlay opens late. A deferred one renders on the frame its code
378
- * arrives. Pass a module whose default export is the component, or resolve
379
- * to the component itself.
380
- *
381
- * @example
382
- * const Bag = deferred(() => import("./bag-sheet"));
383
- * const Finder = deferred(() => import("./finder").then((m) => m.Finder));
384
- * <Bag.Component open={open} onClose={close} />
385
- */
386
- declare function deferred<T extends DeferredModule>(load: () => Promise<T>): Deferred<DeferredModuleProps<T>>;
387
- /**
388
- * Start loading a deferred component when the shopper points at, presses or
389
- * focuses its trigger, so the code is usually in by the click. Spread the
390
- * result on the trigger.
391
- *
392
- * @example
393
- * const intent = useIntentPreload(Bag);
394
- * <button {...intent} onClick={openBag}>Bag</button>
395
- */
396
- declare function useIntentPreload(target: {
397
- preload(): Promise<unknown>;
398
- }): IntentPreloadHandlers;
399
-
400
314
  declare function useCombobox<T>(results: readonly T[], onSelect: (item: T) => void): {
401
315
  setListId: react.Dispatch<react.SetStateAction<string>>;
402
316
  registerOption: (index: number, id: string) => void;
@@ -1201,5 +1115,5 @@ declare const OpenStatus: react.ForwardRefExoticComponent<Omit<react.AllHTMLAttr
1201
1115
  /** The installed @zappie/foundations version. */
1202
1116
  declare const FOUNDATIONS_VERSION: string;
1203
1117
 
1204
- export { Account, AccountNotConfiguredError, Address, Branch, BranchMap, Cart, Choice, DeliveryMap, FOUNDATIONS_VERSION, Fulfilment, Image, ItemForm, ItemNote, Money, OpenStatus, OptionGroup, Otp, Overlay, PartProps, PaymentMethods, Quantity, Schedule, Search, Totals, ZappieAccountLink, canOrderAhead, contactLinks, createSearchIndex, deferred, formatOpeningHours, formatWallClock, getOpenStatus, parseWallClock, preloadOverlay, scheduleSlots, useControllableState, useIntentPreload, useOverlay, useZappieAccountUrl, zappieAccountUrl, zappieEnvironment, zappieSupportUrl };
1205
- export type { ActiveGroup, AddressState, AddressSuggestion, BranchMapLoadErrorState, BranchMapProps, ContactLink, Customer, Deferred, DeferredIdleOptions, DeferredProps, DeliveryMapProps, ImageProps, IntentPreloadHandlers, ItemFormContext, ItemFormInvalidGroup, ItemFormProps, MapLoadErrorState, NoteState, PaymentMethod, QuantityProps, QuantityState, ScheduleSlot, ScheduleState, ScheduleStatus, SearchResult, SearchSource, SearchState, SignInOptions, TotalsState, ZappieSupportContext };
1118
+ export { Account, AccountNotConfiguredError, Address, Branch, BranchMap, Cart, Choice, DeliveryMap, FOUNDATIONS_VERSION, Fulfilment, Image, ItemForm, ItemNote, Money, OpenStatus, OptionGroup, Otp, Overlay, PartProps, PaymentMethods, Quantity, Schedule, Search, Totals, ZappieAccountLink, canOrderAhead, contactLinks, createSearchIndex, formatOpeningHours, formatWallClock, getOpenStatus, parseWallClock, preloadOverlay, scheduleSlots, useControllableState, useOverlay, useZappieAccountUrl, zappieAccountUrl, zappieEnvironment, zappieSupportUrl };
1119
+ export type { ActiveGroup, AddressState, AddressSuggestion, BranchMapLoadErrorState, BranchMapProps, ContactLink, Customer, DeliveryMapProps, ImageProps, ItemFormContext, ItemFormInvalidGroup, ItemFormProps, MapLoadErrorState, NoteState, PaymentMethod, QuantityProps, QuantityState, ScheduleSlot, ScheduleState, ScheduleStatus, SearchResult, SearchSource, SearchState, SignInOptions, TotalsState, ZappieSupportContext };
package/dist/version.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // src/version.ts
2
- var PACKAGE_VERSION = true ? "0.9.2" : "0.0.0-development";
2
+ var PACKAGE_VERSION = true ? "0.9.3" : "0.0.0-development";
3
3
  export {
4
4
  PACKAGE_VERSION
5
5
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zappie/foundations",
3
- "version": "0.9.2",
3
+ "version": "0.9.3",
4
4
  "description": "UI-less React primitives for Zappie storefronts: behaviour, state and accessibility without styles.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -13,6 +13,10 @@
13
13
  "types": "./dist/next.d.ts",
14
14
  "import": "./dist/next.js"
15
15
  },
16
+ "./branch-switch": {
17
+ "types": "./dist/branch-switch/index.d.ts",
18
+ "import": "./dist/branch-switch/index.js"
19
+ },
16
20
  "./rich-text": {
17
21
  "types": "./dist/rich-text/index.d.ts",
18
22
  "import": "./dist/rich-text/index.js"
@@ -33,7 +37,7 @@
33
37
  "dependencies": {
34
38
  "@base-ui/react": "^1.9.0",
35
39
  "@googlemaps/markerclusterer": "^2.6.2",
36
- "@zappie/sdk": "^0.10.1"
40
+ "@zappie/sdk": "^0.10.3"
37
41
  },
38
42
  "peerDependencies": {
39
43
  "react": "^18.2.0 || ^19.0.0",