@zappie/foundations 0.9.2 → 0.10.0

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,21 @@
1
1
  # @zappie/foundations
2
2
 
3
+ ## 0.10.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 5edf72a: Drawers and sheets from `Overlay` drag to close on phones and touch screens. A sheet moves the way it is attached, down for a bottom sheet and towards its side for a side sheet, follows the finger, fades the backdrop, and closes past a quarter of its size or on a flick, the way the close button does. It springs back otherwise. A list inside scrolls first, a sideways swipe stays with a carousel, and a sheet that fills the screen in the direction it would move, a dialog, and a side drawer under a mouse on a wide screen never drag. Under reduced motion the sheet stays still until it closes. `dragToClose={false}` on `Overlay.Content` turns it off.
8
+
9
+ The sheet has `data-drag-to-close` while it can be dragged and `data-swiping` during a drag, for styling a handle. `useDragToClose` gives a sheet you build yourself the same gesture. The gesture loads with the overlay engine, so the initial entry grows by about 0.3 KB gzip.
10
+
11
+ ## 0.9.3
12
+
13
+ ### Patch Changes
14
+
15
+ - 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.
16
+ - Updated dependencies [ad0e714]
17
+ - @zappie/sdk@0.10.3
18
+
3
19
  ## 0.9.2
4
20
 
5
21
  ### 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,152 @@ 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
+ ## Drag to close
115
+
116
+ On a phone or touch screen, a drawer or sheet from `Overlay` closes when it is
117
+ dragged off the screen. It moves the way it is attached: a sheet at the bottom
118
+ of the screen drags down, a sheet at a side drags towards that side. It follows
119
+ the finger and the backdrop fades. Let go past a quarter of the sheet, or flick
120
+ it, and it closes the way the close button does. Otherwise it springs back.
121
+
122
+ - A list inside the sheet scrolls first, and the sheet drags only once the list
123
+ is back at the top. A sideways swipe, such as on a carousel, stays with the
124
+ carousel. Fields and anything marked `data-no-drag` never start a drag.
125
+ - A sheet that fills the screen in the direction it would move, such as a
126
+ full-height sheet, does not drag. Neither does a dialog, nor a side drawer
127
+ under a mouse on a wide screen.
128
+ - Under reduced motion the sheet stays still while the finger moves and still
129
+ closes when it is let go.
130
+ - `dragToClose={false}` on `Overlay.Content` turns it off. `swipeDirection` on
131
+ `Overlay.Root` fixes the direction.
132
+
133
+ The sheet has `data-drag-to-close` (its direction) while it can be dragged and
134
+ `data-swiping` during a drag, so you can show a handle only when it works:
135
+
136
+ ```css
137
+ .sheet-handle {
138
+ display: none;
139
+ }
140
+ [data-drag-to-close="down"] .sheet-handle {
141
+ display: block;
142
+ }
143
+ ```
144
+
145
+ For a sheet you build yourself, `useDragToClose` does the same:
146
+
147
+ ```tsx
148
+ const dragRef = useDragToClose({ onClose: close, enabled: isOpen });
149
+ return isOpen ? (
150
+ <div ref={dragRef} role="dialog" aria-modal>
151
+ …
152
+ </div>
153
+ ) : null;
154
+ ```
155
+
156
+ ## Branch switch
157
+
158
+ Choosing a branch shows that branch's menu without waiting for the server. A
159
+ link to another branch of the store already loaded reads only that branch's
160
+ menu in the browser, and the read starts when the shopper reaches for the
161
+ button. It has its own entry, `@zappie/foundations/branch-switch`, so pages
162
+ that don't use it never load it. Use it in a React Router root route:
163
+
164
+ ```tsx
165
+ import {
166
+ createBranchSwitchLoader,
167
+ useReloadingBranch,
168
+ } from "@zappie/foundations";
169
+
170
+ const branchSwitch = createBranchSwitchLoader<ShopData>({
171
+ // What your loader returns for ?branch=<that branch>. Recompute every field
172
+ // that depends on the branch.
173
+ shopAt: (shop, branch, menu) => ({
174
+ ...shop,
175
+ config: { ...shop.config, branch: branch.id },
176
+ branch,
177
+ menu,
178
+ branchChosen: true,
179
+ mustChoose: false,
180
+ }),
181
+ // Paths your loader redirects go to the server.
182
+ serverOnly: (url, shop) => Boolean(redirectFor(shop.store, url.pathname)),
183
+ });
184
+
185
+ export const shouldRevalidate: ShouldRevalidateFunction = (args) =>
186
+ branchSwitch.shouldRevalidate(args);
187
+ export const clientLoader = (args: Route.ClientLoaderArgs) =>
188
+ branchSwitch.clientLoader(args);
189
+
190
+ export default function App() {
191
+ const shop = useLoaderData<typeof loader>();
192
+ const client = useMemo(() => createZappie(shop.config), [shop.config.branch]);
193
+ branchSwitch.remember(shop, client);
194
+ return <ZappieProvider client={client}>…</ZappieProvider>;
195
+ }
196
+ ```
197
+
198
+ - `createBranchSwitchLoader({ shopAt, serverOnly?, param? })` returns
199
+ `remember`, `shouldRevalidate` and `clientLoader`. Your loader data needs
200
+ `store`, `branch` and, when the shopper chooses a branch, `branchChosen`.
201
+ Without `branchChosen` the loaded branch counts as chosen.
202
+ - `clientLoader` builds the shop with `shopAt` from the shop the root last
203
+ rendered. An unknown branch, a `serverOnly` URL or a failed read calls
204
+ `serverLoader()`. A cancelled navigation throws.
205
+ - `shouldRevalidate` reloads the shop only for a link that names another
206
+ branch. A link without `?branch=` keeps the branch, and so does a link to the
207
+ branch already loaded and chosen. Form submissions keep React Router's rule.
208
+ - `reloadsShop`, `branchNamed` and `loadedBranchOf` are the rules behind them,
209
+ for your own code.
210
+
211
+ Read the menu on intent, and move the bag before you navigate:
212
+
213
+ ```tsx
214
+ import {
215
+ useBranchIntent,
216
+ useChooseBranch,
217
+ } from "@zappie/foundations/branch-switch";
218
+
219
+ function BranchCard({ branch }: { branch: Branch }) {
220
+ const intent = useBranchIntent(branch);
221
+ const navigate = useNavigate();
222
+ const choose = useChooseBranch((next) => {
223
+ rememberBranch(next.id);
224
+ navigate(`/menu?branch=${next.slug}`);
225
+ });
226
+ return (
227
+ <button type="button" {...intent} onClick={() => void choose(branch)}>
228
+ Order from {branch.name}
229
+ </button>
230
+ );
231
+ }
232
+ ```
233
+
234
+ - `useBranchIntent(branch)` returns `{ onPointerEnter, onPointerDown, onFocus }`.
235
+ Each starts the branch's menu read. The client shares one read per branch,
236
+ so the click and the loader reuse it.
237
+ - `useChooseBranch(then)` starts the menu read, moves a bag with lines to the
238
+ branch, and calls `then` once the move is done. Remember the choice and
239
+ navigate in `then`. Keep the branch ID in your cookie: the server then reads
240
+ the store and the menu at once (`loadStoreAndMenu` in `@zappie/sdk/server`).
241
+
242
+ Show your own skeleton while the shop reloads for a branch:
243
+
244
+ ```tsx
245
+ const reloading = useReloadingBranch(shop, {
246
+ location: useLocation(),
247
+ navigation: useNavigation(),
248
+ });
249
+ return reloading?.pathname === "/menu" ? (
250
+ <MenuSkeleton branch={reloading.branch} />
251
+ ) : (
252
+ <Outlet />
253
+ );
254
+ ```
255
+
256
+ `useReloadingBranch(shop, { location, navigation }, param?)` returns
257
+ `{ branch, pathname }` while a navigation reloads the shop for a branch the
258
+ store has, and undefined otherwise.
259
+
113
260
  ## Item form focus
114
261
 
115
262
  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
+ }
@@ -18,6 +18,10 @@ type SurfaceProps = {
18
18
  open: boolean;
19
19
  presentation: Presentation;
20
20
  swipeDirection: SwipeDirection;
21
+ /** Drag drawers and sheets off the screen to close them, on phones. */
22
+ dragToClose: boolean;
23
+ /** The drag's direction, when the Root names one. Otherwise the edge the panel is attached to. */
24
+ dragDirection?: SwipeDirection | undefined;
21
25
  /** Ids the trigger points at; caller-supplied ids win. */
22
26
  contentId: string;
23
27
  titleId?: string | undefined;
@@ -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 };