@zappie/foundations 0.18.0 → 0.19.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,17 @@
1
1
  # @zappie/foundations
2
2
 
3
+ ## 0.19.0
4
+
5
+ ### Minor Changes
6
+
7
+ - d71cdc5: `@zappie/foundations/branch-switch` now covers every site's branch choice. `useBranchChoice` starts the branch's menu read, moves a bag with lines there, keeps the choice in your branch cookie and goes to the destination with `?branch=` in its address, back to an item with the line kept when the finder was opened from one. `useRememberLinkedBranch` keeps a branch a link names, `rememberBranch` and `atBranch` are the pieces, and `createBranchSwitchLoader`'s `shopAt` defaults to `shopAtBranch`, which sets the branch, its menu and `config.branch` and marks it chosen.
8
+
9
+ `@zappie/foundations/branch-finder` opens your own branch picker or locator from any control. `BranchFinder.Root` holds it and loads its code with `deferred()`, `BranchFinder.Trigger` opens it with a destination, and `useBranchFinder()` opens it from code.
10
+
11
+ `@zappie/foundations/branch-list` is the data behind a branch list. `useHere` asks for the shopper's location only when they tap, `nearestFirst` sorts the branches nearest first, `whereIs` and `kilometres` place and measure them, and `useBranchOffers` reads what each branch sells without its items. `menusLabel` names a branch's menus.
12
+
13
+ The starter keeps the shopper's branch in a cookie, so a page without `?branch=` shows the branch they chose, and its page cache keeps a page apart for each branch. The header's picker opens through `BranchFinder` and chooses with `useBranchChoice`. A new Our branches page lists every branch nearest first once the shopper shares their location, with what each sells and a button to order there.
14
+
3
15
  ## 0.18.0
4
16
 
5
17
  ### Minor Changes
package/README.md CHANGED
@@ -36,6 +36,8 @@ Want ready-made, styled components instead? Copy them into your project from the
36
36
  | `@zappie/foundations` | Every part |
37
37
  | `@zappie/foundations/next` | Keeping overlays in step with Back and Forward in a Next.js app |
38
38
  | `@zappie/foundations/branch-switch` | Choosing a branch in a React Router site without waiting for the server |
39
+ | `@zappie/foundations/branch-finder` | Opening the site's branch picker or locator from any control |
40
+ | `@zappie/foundations/branch-list` | Nearest-first branch lists and what each branch sells |
39
41
  | `@zappie/foundations/checkout` | Checkout behaviour for a bag or a cart page, with no markup |
40
42
  | `@zappie/foundations/loyalty` | The rewards sheet's parts, the bag's rewards row and the claim toast |
41
43
  | `@zappie/foundations/order` | A customer's order details page, as parts or one default layout |
@@ -444,19 +446,9 @@ that don't use it never load it. Use it in a React Router root route:
444
446
  import {
445
447
  createBranchSwitchLoader,
446
448
  useReloadingBranch,
447
- } from "@zappie/foundations";
449
+ } from "@zappie/foundations/branch-switch";
448
450
 
449
451
  const branchSwitch = createBranchSwitchLoader<ShopData>({
450
- // What your loader returns for ?branch=<that branch>. Recompute every field
451
- // that depends on the branch.
452
- shopAt: (shop, branch, menu) => ({
453
- ...shop,
454
- config: { ...shop.config, branch: branch.id },
455
- branch,
456
- menu,
457
- branchChosen: true,
458
- mustChoose: false,
459
- }),
460
452
  // Paths your loader redirects go to the server.
461
453
  serverOnly: (url, shop) => Boolean(redirectFor(shop.store, url.pathname)),
462
454
  });
@@ -474,34 +466,35 @@ export default function App() {
474
466
  }
475
467
  ```
476
468
 
477
- - `createBranchSwitchLoader({ shopAt, serverOnly?, param? })` returns
469
+ - `createBranchSwitchLoader({ shopAt?, serverOnly?, param? })` returns
478
470
  `remember`, `shouldRevalidate` and `clientLoader`. Your loader data needs
479
471
  `store`, `branch` and, when the shopper chooses a branch, `branchChosen`.
480
472
  Without `branchChosen` the loaded branch counts as chosen.
481
473
  - `clientLoader` builds the shop with `shopAt` from the shop the root last
482
474
  rendered. An unknown branch, a `serverOnly` URL or a failed read calls
483
475
  `serverLoader()`. A cancelled navigation throws.
476
+ - `shopAt` is what your loader returns for `?branch=<that branch>`. It
477
+ defaults to `shopAtBranch`, which sets `branch`, `menu` and
478
+ `config.branch`, marks the branch chosen and clears `mustChoose` where your
479
+ shop has them. Pass your own when another field depends on the branch, such
480
+ as a home link per branch.
484
481
  - `shouldRevalidate` reloads the shop only for a link that names another
485
482
  branch. A link without `?branch=` keeps the branch, and so does a link to the
486
483
  branch already loaded and chosen. Form submissions keep React Router's rule.
487
484
  - `reloadsShop`, `branchNamed` and `loadedBranchOf` are the rules behind them,
488
485
  for your own code.
489
486
 
490
- Read the menu on intent, and move the bag before you navigate:
487
+ Choose a branch from a picker, a locator or a card:
491
488
 
492
489
  ```tsx
493
490
  import {
491
+ useBranchChoice,
494
492
  useBranchIntent,
495
- useChooseBranch,
496
493
  } from "@zappie/foundations/branch-switch";
497
494
 
498
495
  function BranchCard({ branch }: { branch: Branch }) {
499
496
  const intent = useBranchIntent(branch);
500
- const navigate = useNavigate();
501
- const choose = useChooseBranch((next) => {
502
- rememberBranch(next.id);
503
- navigate(`/menu?branch=${next.slug}`);
504
- });
497
+ const choose = useBranchChoice({ cookie: "site_branch", to: "/menu" });
505
498
  return (
506
499
  <button type="button" {...intent} onClick={() => void choose(branch)}>
507
500
  Order from {branch.name}
@@ -513,10 +506,24 @@ function BranchCard({ branch }: { branch: Branch }) {
513
506
  - `useBranchIntent(branch)` returns `{ onPointerEnter, onPointerDown, onFocus }`.
514
507
  Each starts the branch's menu read. The client shares one read per branch,
515
508
  so the click and the loader reuse it.
516
- - `useChooseBranch(then)` starts the menu read, moves a bag with lines to the
517
- branch, and calls `then` once the move is done. Remember the choice and
518
- navigate in `then`. Keep the branch ID in your cookie: the server then reads
519
- the store and the menu at once (`loadStoreAndMenu` in `@zappie/sdk/server`).
509
+ - `useBranchChoice({ cookie?, rememberBy?, to?, param?, then? })` returns
510
+ `choose(branch, destination?)`. It starts the menu read, moves a bag with
511
+ lines to the branch, keeps the choice in `cookie`, and navigates to the
512
+ destination with the branch in its address. The cookie keeps the branch ID
513
+ unless `rememberBy` is `"slug"`. Give the server's `loadStoreAndMenu` (in
514
+ `@zappie/sdk/server`) the same cookie, and the page cache its
515
+ `branchCookie`. Without a destination the shopper goes to `to`, `/` by
516
+ default, or to what `to(branch)` returns. A destination is
517
+ `{ path, state?, replace?, preventScrollReset? }`, so a finder opened from an
518
+ item can go back to it with the line chosen so far. `then(branch,
519
+ destination)` runs once the navigation has started: close the finder there,
520
+ or scroll to the menu. Call it inside the router.
521
+ - `useRememberLinkedBranch(branch, { cookie, rememberBy?, param? })` keeps a
522
+ branch a link names in the cookie, so pages without `?branch=` stay on it.
523
+ - `rememberBranch(cookie, value)` and `atBranch(path, branch, param?)` are the
524
+ pieces, for your own code.
525
+ - `useChooseBranch(then)` only moves the bag and calls `then` once the move is
526
+ done, for a choice that remembers and navigates its own way.
520
527
 
521
528
  Show your own skeleton while the shop reloads for a branch:
522
529
 
@@ -536,6 +543,113 @@ return reloading?.pathname === "/menu" ? (
536
543
  `{ branch, pathname }` while a navigation reloads the shop for a branch the
537
544
  store has, and undefined otherwise.
538
545
 
546
+ ## Branch finder
547
+
548
+ `@zappie/foundations/branch-finder` opens the site's own branch picker or
549
+ locator from the header, the hero, an item card or the footer. Its code loads
550
+ with `deferred()`, starts loading when a shopper reaches for a control, and
551
+ mounts on the first open. The finder's look, its list and its frame stay
552
+ yours.
553
+
554
+ ```tsx
555
+ import { deferred, OverlayRetry } from "@zappie/foundations";
556
+ import { BranchFinder } from "@zappie/foundations/branch-finder";
557
+
558
+ const finder = deferred(() => import("./ui/branch-dialog"));
559
+
560
+ <BranchFinder.Root
561
+ finder={finder}
562
+ preloadWhenIdle
563
+ failed={(retry, close) => (
564
+ <OverlayRetry
565
+ message="The branch list didn't load."
566
+ retry={retry}
567
+ close={close}
568
+ />
569
+ )}
570
+ >
571
+ <Header />{" "}
572
+ {/* <BranchFinder.Trigger className="branch">Choose a branch</BranchFinder.Trigger> */}
573
+ <Outlet />
574
+ </BranchFinder.Root>;
575
+
576
+ // app/ui/branch-dialog.tsx
577
+ export default function BranchDialog({
578
+ open,
579
+ onClose,
580
+ then,
581
+ }: BranchFinderProps) {
582
+ const choose = useBranchChoice({
583
+ cookie: "site_branch",
584
+ to: "/menu",
585
+ then: onClose,
586
+ });
587
+ // … each branch calls choose(branch, then)
588
+ }
589
+ ```
590
+
591
+ - `BranchFinder.Root` goes around the shell once. It renders `finder` with
592
+ `open`, `onClose` and `then`, the destination the control asked for.
593
+ `preloadWhenIdle` loads its code once the page is idle. `failed` shows while
594
+ open when the code didn't load.
595
+ - `BranchFinder.Trigger` is a button marked
596
+ `data-zappie-overlay-trigger="branch"` with `aria-haspopup="dialog"`. `then`
597
+ is where the shopper goes once they choose, such as the item the card
598
+ shows. Your `onClick` runs first and can cancel with `preventDefault()`. Use
599
+ `asChild` for your own button.
600
+ - `useBranchFinder()` gives `open(then?)` and `close()`. They never change.
601
+
602
+ ## Branch list
603
+
604
+ `@zappie/foundations/branch-list` is the data behind a picker or a locator:
605
+ the branches nearest first, and what each one sells. It loads only on the
606
+ pages that use it.
607
+
608
+ ```tsx
609
+ import {
610
+ kilometres,
611
+ menusLabel,
612
+ nearestFirst,
613
+ useBranchOffers,
614
+ useHere,
615
+ whereIs,
616
+ } from "@zappie/foundations/branch-list";
617
+
618
+ const { here, locate, locating, refused } = useHere();
619
+ const offers = useBranchOffers(store.branches, { active: open });
620
+ <button type="button" onClick={locate} disabled={locating}>
621
+ Use my location
622
+ </button>;
623
+ {
624
+ nearestFirst(store.branches, here).map((branch) => (
625
+ <BranchCard
626
+ key={branch.id}
627
+ branch={branch}
628
+ menus={offers[branch.id]?.menus}
629
+ />
630
+ ));
631
+ }
632
+ ```
633
+
634
+ - `useHere(timeout?)` asks the browser where the shopper is when `locate`
635
+ runs, never before. It gives `here`, `setHere`, `locating`, `refused` and
636
+ `locate`. `refused` is true when the shopper says no, the browser has no
637
+ location or the lookup fails. `setHere` takes a location from elsewhere,
638
+ such as a saved address.
639
+ - `nearestFirst(branches, here)` sorts nearest first, puts a branch with no
640
+ location last and keeps ties in order. Without `here` the order stays.
641
+ - `whereIs(branch)` is the branch's pin, else its pickup point's. A pin at
642
+ 0, 0 counts as none. `kilometres(from, to)` is the distance along the
643
+ earth's surface.
644
+ - `useBranchOffers(branches, { active?, typesOf? })` reads each branch's menus
645
+ without their items, once per branch for the page's life. It returns
646
+ `{ menus, types }` by branch ID: the names of menus that have categories, and
647
+ the order types they take, from `checkoutOffers` unless you pass `typesOf`.
648
+ A branch is absent until its answer arrives and stays absent when the read
649
+ fails. An empty `menus` means it has nothing to sell yet.
650
+ - `menusLabel(names)` joins the names with " · ", and reads "Breakfast only"
651
+ for one.
652
+
539
653
  ## Item form focus
540
654
 
541
655
  When an add fails validation, `ItemForm.Root` focuses the first invalid group
@@ -0,0 +1,60 @@
1
+ import { P as PartOwnedAttributes } from '../slot-CHfqzPTd.js';
2
+ import { PartProps } from '../index.js';
3
+ import * as react from 'react';
4
+ import { ReactNode } from 'react';
5
+ import { BranchDestination } from '../branch-switch/index.js';
6
+ import { Deferred } from '../index.js';
7
+ import '@zappie/sdk';
8
+
9
+ /** What the site's finder receives: whether it is open, how to close it, and where the choice goes. */
10
+ type BranchFinderProps = {
11
+ open: boolean;
12
+ onClose: () => void;
13
+ /** Where the shopper goes once they choose. Absent for the finder's default, such as the menu. */
14
+ then?: BranchDestination | undefined;
15
+ };
16
+ /** The controls from `useBranchFinder()`. */
17
+ type BranchFinderControls = {
18
+ /** Open the finder. `then` is where the shopper goes once they choose. */
19
+ open: (then?: BranchDestination) => void;
20
+ /** Close the finder. */
21
+ close: () => void;
22
+ };
23
+ /** Open and close the branch finder, inside `BranchFinder.Root`. The controls never change. */
24
+ declare function useBranchFinder(): BranchFinderControls;
25
+ /**
26
+ * Holds the branch finder, so the header, the hero, item cards and the footer
27
+ * can each open it. It renders the site's finder, loaded with `deferred()`,
28
+ * once it first opens, and keeps it mounted after so it can run its exit.
29
+ */
30
+ declare function Root({ finder, preloadWhenIdle, failed, children, }: {
31
+ /** The site's finder: its picker or locator dialog, loaded with `deferred()`. */
32
+ finder: Deferred<BranchFinderProps>;
33
+ /** Load the finder's code once the page is idle, so a tap paints it at once. */
34
+ preloadWhenIdle?: boolean | undefined;
35
+ /** Shown while open when the finder's code didn't load. */
36
+ failed?: ((retry: () => void, close: () => void) => ReactNode) | undefined;
37
+ children: ReactNode;
38
+ }): react.JSX.Element;
39
+ /** Props for `BranchFinder.Trigger`: a button's props, and where the shopper goes once they choose. */
40
+ type BranchFinderTriggerProps = PartProps<BranchFinderControls> & {
41
+ then?: BranchDestination | undefined;
42
+ };
43
+ /**
44
+ * The branch finder's plumbing: `Root` goes around the shell once and renders
45
+ * the site's finder, `Trigger` opens it from any control, and
46
+ * `useBranchFinder()` opens it from code. The finder itself, its look and its
47
+ * list, stays the site's.
48
+ */
49
+ declare const BranchFinder: {
50
+ Root: typeof Root;
51
+ Trigger: react.ForwardRefExoticComponent<Omit<react.AllHTMLAttributes<HTMLElement>, PartOwnedAttributes> & {
52
+ asChild?: boolean;
53
+ children?: ReactNode | ((state: BranchFinderControls) => ReactNode);
54
+ } & {
55
+ then?: BranchDestination | undefined;
56
+ } & react.RefAttributes<HTMLElement>>;
57
+ };
58
+
59
+ export { BranchDestination, BranchFinder, useBranchFinder };
60
+ export type { BranchFinderControls, BranchFinderProps, BranchFinderTriggerProps };
@@ -0,0 +1,2 @@
1
+ "use client";import{createContext,forwardRef,useCallback,useContext,useEffect,useMemo,useState}from"react";import{useIntentPreload}from"../deferred/index.js";import{part}from"../internal/slot.js";import{jsx,jsxs}from"react/jsx-runtime";var Controls=/*@__PURE__ */createContext(null);function useShared(){const value=useContext(Controls);if(!value){throw new Error("BranchFinder parts require BranchFinder.Root")}return value}function useBranchFinder(){return useShared()}function Root({finder,preloadWhenIdle,failed,children}){const[state,setState]=useState({open:false});const open=useCallback(then=>setState({open:true,then}),[]);const close=useCallback(()=>setState(current=>({...current,open:false})),[]);const value=useMemo(()=>({open,close,finder}),[open,close,finder]);useEffect(()=>preloadWhenIdle?finder.preloadWhenIdle():void 0,[finder,preloadWhenIdle]);return jsxs(Controls.Provider,{value,children:[children,jsx(finder.Component,{open:state.open,onClose:close,then:state.then,...failed?{failed}:{}})]})}var Trigger=/*@__PURE__ */forwardRef(function Trigger2({then,...props},ref){const shared=useShared();const intent=useIntentPreload(shared.finder);return part("button",props,shared,{type:"button","aria-haspopup":"dialog","data-zappie-overlay-trigger":"branch",...intent,onClick:()=>shared.open(then)},ref)});var BranchFinder={Root,Trigger};export{BranchFinder,useBranchFinder};
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,6 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/branch-finder/index.tsx"],
4
+ "mappings": "aACA,OACE,cACA,WACA,YACA,WACA,UACA,QACA,aAEK,QAEP,OAAS,qBAAuC,uBAChD,OAAS,SAA4B,sBAyEjC,OAEE,IAFF,6BApDJ,IAAM,SAAW,eAAgB,cAA6B,IAAI,EAElE,SAAS,WAAoB,CAC3B,MAAM,MAAQ,WAAW,QAAQ,EACjC,GAAI,CAAC,MAAO,CACV,MAAM,IAAI,MAAM,8CAA8C,CAChE,CACA,OAAO,KACT,CAGO,SAAS,iBAAwC,CACtD,OAAO,UAAU,CACnB,CAOA,SAAS,KAAK,CACZ,OACA,gBACA,OACA,QACF,EAQG,CACD,KAAM,CAAC,MAAO,QAAQ,EAAI,SAGvB,CAAE,KAAM,KAAM,CAAC,EAClB,MAAM,KAAO,YACV,MAA6B,SAAS,CAAE,KAAM,KAAM,IAAK,CAAC,EAC3D,CAAC,CACH,EACA,MAAM,MAAQ,YACZ,IAAM,SAAU,UAAa,CAAE,GAAG,QAAS,KAAM,KAAM,EAAE,EACzD,CAAC,CACH,EACA,MAAM,MAAQ,QAAQ,KAAO,CAAE,KAAM,MAAO,MAAO,GAAI,CAAC,KAAM,MAAO,MAAM,CAAC,EAC5E,UACE,IAAO,gBAAkB,OAAO,gBAAgB,EAAI,OACpD,CAAC,OAAQ,eAAe,CAC1B,EACA,OACE,KAAC,SAAS,SAAT,CAAkB,MAChB,mBACD,IAAC,OAAO,UAAP,CACC,KAAM,MAAM,KACZ,QAAS,MACT,KAAM,MAAM,KACX,GAAI,OAAS,CAAE,MAAO,EAAI,CAAC,EAC9B,GACF,CAEJ,CAaA,IAAM,QAAU,eAAgB,WAG9B,SAASA,SAAQ,CAAE,KAAM,GAAG,KAAM,EAAG,IAAK,CAC1C,MAAM,OAAS,UAAU,EACzB,MAAM,OAAS,iBAAiB,OAAO,MAAM,EAC7C,OAAO,KACL,SACA,MACA,OACA,CACE,KAAM,SACN,gBAAiB,SACjB,8BAA+B,SAC/B,GAAG,OACH,QAAS,IAAM,OAAO,KAAK,IAAI,CACjC,EACA,GACF,CACF,CAAC,EAQM,IAAM,aAAe,CAAE,KAAM,OAAQ",
5
+ "names": ["Trigger"]
6
+ }
@@ -0,0 +1,100 @@
1
+ import { Branch, Menu } from '@zappie/sdk';
2
+ import { CheckoutMode } from '../checkout/index.js';
3
+
4
+ /** A point on the map, in degrees. */
5
+ type Coordinates = {
6
+ lat: number;
7
+ lng: number;
8
+ };
9
+ /**
10
+ * How far apart two points are, in kilometres along the earth's surface.
11
+ *
12
+ * @param from - One point.
13
+ * @param to - The other point.
14
+ */
15
+ declare function kilometres(from: Coordinates, to: Coordinates): number;
16
+ /**
17
+ * Where a branch is on the map: its own pin, else its pickup point's. A pin
18
+ * never set, at 0, 0, is no location.
19
+ *
20
+ * @param branch - The branch.
21
+ */
22
+ declare function whereIs(branch: Pick<Branch, "coordinates" | "pickupAddress">): Coordinates | undefined;
23
+ /**
24
+ * The branches nearest first from where the shopper is. A branch with no
25
+ * location goes last, and branches the same distance away keep their order.
26
+ * Without a location the order stays as it was. It always returns a new array.
27
+ *
28
+ * @param branches - The branches, in the store's order.
29
+ * @param here - Where the shopper is, or undefined.
30
+ */
31
+ declare function nearestFirst<T extends Pick<Branch, "coordinates" | "pickupAddress">>(branches: readonly T[], here: Coordinates | undefined): T[];
32
+ /** Where the shopper is, from `useHere()`. */
33
+ type Here = {
34
+ /** Where the shopper is, once known. */
35
+ here: Coordinates | undefined;
36
+ /** Set it from elsewhere, such as a signed-in shopper's saved address. */
37
+ setHere: (here: Coordinates | undefined) => void;
38
+ /** True while the browser looks up where the shopper is. */
39
+ locating: boolean;
40
+ /** True when the shopper refused, the browser has no location or the lookup failed. */
41
+ refused: boolean;
42
+ /** Ask the browser where the shopper is: the "Use my location" button. */
43
+ locate: () => void;
44
+ };
45
+ /**
46
+ * "Use my location": where the shopper is, once they allow the browser to
47
+ * say. Nothing is asked until `locate` runs, so call it from a button.
48
+ *
49
+ * @example
50
+ * const { here, locate, locating, refused } = useHere();
51
+ * const sorted = nearestFirst(store.branches, here);
52
+ * <button type="button" onClick={locate} disabled={locating}>Use my location</button>
53
+ * {refused && <p>We couldn't find where you are.</p>}
54
+ *
55
+ * @param timeout - How long the lookup may take, in milliseconds. Defaults to 8 seconds.
56
+ */
57
+ declare function useHere(timeout?: number): Here;
58
+
59
+ /** What a branch sells: the names of its menus and the order types they take. */
60
+ type BranchOffer<T = CheckoutMode> = {
61
+ menus: string[];
62
+ types: T[];
63
+ };
64
+ /** Settings for `useBranchOffers`. */
65
+ type BranchOffersOptions<T> = {
66
+ /** Read the menus. Pass false until the finder or the list shows. Defaults to true. */
67
+ active?: boolean | undefined;
68
+ /**
69
+ * The order types a branch's menus take. Defaults to `checkoutOffers`:
70
+ * delivery, pickup and in venue, as the branch and its menus allow.
71
+ */
72
+ typesOf?: ((branch: Branch, menu: Menu) => T[]) | undefined;
73
+ };
74
+ /**
75
+ * Each branch's menus and the order types they take, read once the finder or
76
+ * the branch list shows. Only the menus' names are read, not their items. A
77
+ * menu with no categories doesn't count. A branch is absent until its answer
78
+ * arrives, and stays absent when the read fails, so nothing shows on a guess.
79
+ * A branch whose `menus` is empty has nothing to sell yet.
80
+ *
81
+ * @example
82
+ * const offers = useBranchOffers(store.branches, { active: open });
83
+ * const offer = offers[branch.id];
84
+ * {offer && <p>{menusLabel(offer.menus)}</p>}
85
+ *
86
+ * @param branches - The branches to read.
87
+ * @param options - Whether to read yet, and how to list order types.
88
+ * @returns Each branch's offer, by branch ID.
89
+ */
90
+ declare function useBranchOffers<T = CheckoutMode>(branches: readonly Branch[], { active, typesOf }?: BranchOffersOptions<T>): Record<string, BranchOffer<T>>;
91
+ /**
92
+ * A branch's menus as the merchant names them, joined with " · ", and
93
+ * "<name> only" when it sells one.
94
+ *
95
+ * @param names - The menus' names, from `useBranchOffers`.
96
+ */
97
+ declare function menusLabel(names: readonly string[]): string;
98
+
99
+ export { kilometres, menusLabel, nearestFirst, useBranchOffers, useHere, whereIs };
100
+ export type { BranchOffer, BranchOffersOptions, Coordinates, Here };
@@ -0,0 +1,2 @@
1
+ import{kilometres,nearestFirst,useHere,whereIs}from"./nearest.js";import{menusLabel,useBranchOffers}from"./offers.js";export{kilometres,menusLabel,nearestFirst,useBranchOffers,useHere,whereIs};
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,6 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/branch-list/index.ts"],
4
+ "mappings": "AAAA,OAAS,WAAY,aAAc,QAAS,YAAe,eAE3D,OAAS,WAAY,oBAAuB",
5
+ "names": []
6
+ }
@@ -0,0 +1,2 @@
1
+ "use client";import{useCallback,useState}from"react";var placed=point=>point&&(point.lat!==0||point.lng!==0)?point:void 0;function kilometres(from,to){const radians=Math.PI/180;const a=Math.sin((to.lat-from.lat)*radians/2)**2+Math.cos(from.lat*radians)*Math.cos(to.lat*radians)*Math.sin((to.lng-from.lng)*radians/2)**2;return 2*6371*Math.asin(Math.sqrt(a))}function whereIs(branch){return placed(branch.coordinates)??placed(branch.pickupAddress?.coordinates)}function nearestFirst(branches,here){if(!here){return[...branches]}const away=branch=>{const at=whereIs(branch);return at?kilometres(here,at):Infinity};return branches.map(branch=>({branch,distance:away(branch)})).sort((left,right)=>left.distance===right.distance?0:left.distance-right.distance).map(({branch})=>branch)}function useHere(timeout=8e3){const[here,setHere]=useState();const[locating,setLocating]=useState(false);const[refused,setRefused]=useState(false);const locate=useCallback(()=>{if(!navigator.geolocation){setRefused(true);return}setLocating(true);navigator.geolocation.getCurrentPosition(position=>{setHere({lat:position.coords.latitude,lng:position.coords.longitude});setRefused(false);setLocating(false)},()=>{setRefused(true);setLocating(false)},{timeout})},[timeout]);return{here,setHere,locating,refused,locate}}export{kilometres,nearestFirst,useHere,whereIs};
2
+ //# sourceMappingURL=nearest.js.map
@@ -0,0 +1,6 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/branch-list/nearest.ts"],
4
+ "mappings": "aAEA,OAAS,YAAa,aAAgB,QAKtC,IAAM,OAAU,OACd,QAAU,MAAM,MAAQ,GAAK,MAAM,MAAQ,GAAK,MAAQ,OAQnD,SAAS,WAAW,KAAmB,GAAyB,CACrE,MAAM,QAAU,KAAK,GAAK,IAC1B,MAAM,EACJ,KAAK,KAAM,GAAG,IAAM,KAAK,KAAO,QAAW,CAAC,GAAK,EACjD,KAAK,IAAI,KAAK,IAAM,OAAO,EACzB,KAAK,IAAI,GAAG,IAAM,OAAO,EACzB,KAAK,KAAM,GAAG,IAAM,KAAK,KAAO,QAAW,CAAC,GAAK,EACrD,MAAO,GAAI,KAAO,KAAK,KAAK,KAAK,KAAK,CAAC,CAAC,CAC1C,CAQO,SAAS,QACd,OACyB,CACzB,OACE,OAAO,OAAO,WAAW,GAAK,OAAO,OAAO,eAAe,WAAW,CAE1E,CAUO,SAAS,aAEd,SAAwB,KAAoC,CAC5D,GAAI,CAAC,KAAM,CACT,MAAO,CAAC,GAAG,QAAQ,CACrB,CACA,MAAM,KAAQ,QAAc,CAC1B,MAAM,GAAK,QAAQ,MAAM,EACzB,OAAO,GAAK,WAAW,KAAM,EAAE,EAAI,QACrC,EACA,OAAO,SACJ,IAAK,SAAY,CAAE,OAAQ,SAAU,KAAK,MAAM,CAAE,EAAE,EACpD,KAAK,CAAC,KAAM,QACX,KAAK,WAAa,MAAM,SAAW,EAAI,KAAK,SAAW,MAAM,QAC/D,EACC,IAAI,CAAC,CAAE,MAAO,IAAM,MAAM,CAC/B,CA4BO,SAAS,QAAQ,QAAU,IAAY,CAC5C,KAAM,CAAC,KAAM,OAAO,EAAI,SAAsB,EAC9C,KAAM,CAAC,SAAU,WAAW,EAAI,SAAS,KAAK,EAC9C,KAAM,CAAC,QAAS,UAAU,EAAI,SAAS,KAAK,EAC5C,MAAM,OAAS,YAAY,IAAM,CAC/B,GAAI,CAAC,UAAU,YAAa,CAC1B,WAAW,IAAI,EACf,MACF,CACA,YAAY,IAAI,EAChB,UAAU,YAAY,mBACnB,UAAa,CACZ,QAAQ,CACN,IAAK,SAAS,OAAO,SACrB,IAAK,SAAS,OAAO,SACvB,CAAC,EACD,WAAW,KAAK,EAChB,YAAY,KAAK,CACnB,EACA,IAAM,CACJ,WAAW,IAAI,EACf,YAAY,KAAK,CACnB,EACA,CAAE,OAAQ,CACZ,CACF,EAAG,CAAC,OAAO,CAAC,EACZ,MAAO,CAAE,KAAM,QAAS,SAAU,QAAS,MAAO,CACpD",
5
+ "names": []
6
+ }
@@ -0,0 +1,2 @@
1
+ "use client";import{useZappie}from"@zappie/sdk/react";import{useEffect,useState}from"react";import{checkoutOffers}from"../checkout/offers.js";var reads=new WeakMap;function menusOf(client,branch){let known=reads.get(client);if(!known){known=new Map;reads.set(client,known)}let pending=known.get(branch.id);if(!pending){pending=client.menu.get({branch:branch.id,metadataOnly:true}).then(menu=>({...menu,menus:(menu.menus??[]).filter(section=>section.categoryIds.length>0)})).catch(()=>null);known.set(branch.id,pending)}return pending}function useBranchOffers(branches,{active=true,typesOf}={}){const client=useZappie();const[menus,setMenus]=useState({});useEffect(()=>{if(!active){return}let live=true;for(const branch of branches){void menusOf(client,branch).then(menu=>{if(live&&menu){setMenus(current=>current[branch.id]?current:{...current,[branch.id]:menu})}})}return()=>{live=false}},[client,branches,active]);const types=typesOf??checkoutOffers;const offers={};for(const branch of branches){const menu=menus[branch.id];if(menu){offers[branch.id]={menus:(menu.menus??[]).map(section=>section.name),types:types(branch,menu)}}}return offers}function menusLabel(names){return names.length===1?`${names[0]} only`:names.join(" \xB7 ")}export{menusLabel,useBranchOffers};
2
+ //# sourceMappingURL=offers.js.map
@@ -0,0 +1,6 @@
1
+ {
2
+ "version": 3,
3
+ "sources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M,OAAO,EAAE,EAC5B,GAAI,KAAM,CACR,OAAO,OAAO,EAAE,EAAI,CAClB,OAAQ,KAAK,OAAS,CAAC,GAAG,IAAK,SAAY,QAAQ,IAAI,EACvD,MAAO,MAAM,OAAQ,IAAI,CAC3B,CACF,CACF,CACA,OAAO,MACT,CAQO,SAAS,WAAW,MAAkC,CAC3D,OAAO,MAAM,SAAW,EAAI,GAAG,MAAM,CAAC,CAAC,QAAU,MAAM,KAAK,QAAK,CACnE",
5
+ "names": []
6
+ }
@@ -1,4 +1,4 @@
1
- import { Store, Branch, Zappie, Menu } from '@zappie/sdk';
1
+ import { Branch, Store, Zappie, Menu } from '@zappie/sdk';
2
2
  import { IntentPreloadHandlers } from '../index.js';
3
3
  import 'react';
4
4
 
@@ -25,8 +25,9 @@ type BranchSwitchOptions<T extends BranchSwitchShop> = {
25
25
  * The shop at another branch: what your root loader returns for
26
26
  * `?branch=<that branch>`, built from the shop already loaded and that
27
27
  * branch's menu. Recompute every field that depends on the branch here.
28
+ * Defaults to `shopAtBranch`.
28
29
  */
29
- shopAt(shop: T, branch: Branch, menu: Menu): T;
30
+ shopAt?(shop: T, branch: Branch, menu: Menu): T;
30
31
  /**
31
32
  * Return true to send this URL to the server loader anyway, such as a path
32
33
  * your loader redirects.
@@ -64,6 +65,18 @@ type BranchSwitchLoader<T extends BranchSwitchShop> = {
64
65
  */
65
66
  clientLoader<S>(args: BranchSwitchClientLoaderArgs<S>): Promise<T | S>;
66
67
  };
68
+ /**
69
+ * The shop at another branch, for the loader data most sites keep: the branch
70
+ * and its menu, `config.branch` set to the branch's ID, `branchChosen` true
71
+ * and `mustChoose` false where the shop has them. Every other field stays.
72
+ * It is `createBranchSwitchLoader`'s default `shopAt`. Write your own when
73
+ * another field depends on the branch.
74
+ *
75
+ * @param shop - The shop already loaded.
76
+ * @param branch - The branch the link names.
77
+ * @param menu - That branch's menu.
78
+ */
79
+ declare function shopAtBranch<T extends BranchSwitchShop>(shop: T, branch: Branch, menu: Menu): T;
67
80
  /** The branch the shop was loaded for, and whether the shopper chose it. */
68
81
  declare function loadedBranchOf(shop: BranchSwitchShop): LoadedBranch;
69
82
  /**
@@ -94,13 +107,12 @@ declare function reloadsShop(current: URLSearchParams, next: URLSearchParams, lo
94
107
  *
95
108
  * @example
96
109
  * const branchSwitch = createBranchSwitchLoader<ShopData>({
97
- * shopAt: (shop, branch, menu) => ({ ...shop, config: { ...shop.config, branch: branch.id }, branch, menu, branchChosen: true, mustChoose: false }),
98
110
  * serverOnly: (url, shop) => Boolean(redirectFor(shop.store, url.pathname)),
99
111
  * });
100
112
  * export const shouldRevalidate: ShouldRevalidateFunction = (args) => branchSwitch.shouldRevalidate(args);
101
113
  * export const clientLoader = (args: Route.ClientLoaderArgs) => branchSwitch.clientLoader(args);
102
114
  */
103
- declare function createBranchSwitchLoader<T extends BranchSwitchShop>({ shopAt, serverOnly, param, }: BranchSwitchOptions<T>): BranchSwitchLoader<T>;
115
+ declare function createBranchSwitchLoader<T extends BranchSwitchShop>({ shopAt, serverOnly, param, }?: BranchSwitchOptions<T>): BranchSwitchLoader<T>;
104
116
  /**
105
117
  * Pointer, touch and focus handlers that start reading a branch's menu when
106
118
  * the shopper reaches for the control that chooses it. The client keeps one
@@ -120,9 +132,12 @@ declare function useBranchIntent(branch: Branch | string): IntentPreloadHandlers
120
132
  * once the move is done, so the shopper never lands on a branch whose bag is
121
133
  * still moving. Remember the choice and navigate in `then`.
122
134
  *
135
+ * `useBranchChoice` does this, then remembers the branch and navigates. Use
136
+ * this one for anything else.
137
+ *
123
138
  * @example
124
139
  * const choose = useChooseBranch((branch) => {
125
- * rememberBranch(branch.id);
140
+ * rememberBranch("site_branch", branch.id);
126
141
  * navigate(`/menu?branch=${branch.slug}`);
127
142
  * });
128
143
  *
@@ -130,6 +145,85 @@ declare function useBranchIntent(branch: Branch | string): IntentPreloadHandlers
130
145
  * @returns A function that chooses a branch and resolves after `then`.
131
146
  */
132
147
  declare function useChooseBranch(then: (branch: Branch) => void | Promise<void>): (branch: Branch) => Promise<void>;
148
+ /**
149
+ * Keep the shopper's branch in a cookie for 30 days, for pages whose links
150
+ * don't name it. Give the server's `loadStoreAndMenu` or `resolveBranch` the
151
+ * same cookie name. Keep the branch ID, not its slug: the server then reads
152
+ * the store and the menu at once.
153
+ *
154
+ * @param cookie - The cookie's name, such as `site_branch`.
155
+ * @param branch - The branch's ID or slug.
156
+ */
157
+ declare function rememberBranch(cookie: string, branch: string): void;
158
+ /**
159
+ * A path with its branch parameter set to the branch, keeping its other
160
+ * parameters and its hash.
161
+ *
162
+ * @example
163
+ * atBranch("/menu?category=drinks", "lekki"); // "/menu?category=drinks&branch=lekki"
164
+ *
165
+ * @param path - The path, with or without a query.
166
+ * @param branch - The branch's slug or ID.
167
+ * @param param - The query parameter that names a branch. Defaults to `branch`.
168
+ */
169
+ declare function atBranch(path: string, branch: string, param?: string): string;
170
+ /**
171
+ * Where a shopper goes once they choose a branch: a path, which gets the
172
+ * branch parameter, and how to navigate there. A finder opened from an item
173
+ * passes the item's path and the line chosen so far in `state`.
174
+ */
175
+ type BranchDestination = {
176
+ path: string;
177
+ state?: unknown;
178
+ replace?: boolean;
179
+ preventScrollReset?: boolean;
180
+ };
181
+ /** Settings for `useBranchChoice`. */
182
+ type BranchChoiceOptions = {
183
+ /** The cookie that keeps the choice. Leave it out when the site keeps none. */
184
+ cookie?: string | undefined;
185
+ /** What the cookie keeps: the branch's `id` (the default, which the server reads fastest) or its `slug`. */
186
+ rememberBy?: "id" | "slug" | undefined;
187
+ /**
188
+ * Where the shopper goes when the choice names no destination: a path, `/`
189
+ * by default, or a function of the branch.
190
+ */
191
+ to?: string | ((branch: Branch) => BranchDestination) | undefined;
192
+ /** The query parameter that names a branch. Defaults to `branch`. */
193
+ param?: string | undefined;
194
+ /** Runs once the navigation has started, such as scrolling to the menu or closing the finder. */
195
+ then?: ((branch: Branch, destination: BranchDestination) => void) | undefined;
196
+ };
197
+ /** Choose a branch, and optionally where to go once the bag is there. Resolves once the navigation has started. */
198
+ type ChooseBranch = (branch: Branch, destination?: BranchDestination) => Promise<void>;
199
+ /**
200
+ * Choose a branch and go there: what every branch finder does. The branch's
201
+ * menu starts loading at once, a bag with lines from another branch moves
202
+ * there first, the cookie keeps the choice, and the shopper lands on the
203
+ * destination with the branch in its address. `then` runs once the
204
+ * navigation has started. Call it inside the router.
205
+ *
206
+ * @example
207
+ * const choose = useBranchChoice({ cookie: "site_branch", to: "/menu" });
208
+ * <button onClick={() => void choose(branch)}>Order from {branch.name}</button>
209
+ * // Back to the item the finder was opened from, with the line kept:
210
+ * void choose(branch, { path: location.pathname, state: { line } });
211
+ *
212
+ * @param options - The cookie, the default destination, the query parameter and what to do after.
213
+ * @returns A function that chooses a branch, with an optional destination.
214
+ */
215
+ declare function useBranchChoice({ cookie, rememberBy, to, param, then, }?: BranchChoiceOptions): ChooseBranch;
216
+ /**
217
+ * Keep a branch a link names: when the address names the branch the shop is
218
+ * showing, the cookie keeps it, so later pages without the parameter stay on
219
+ * it. Call it once, in the root or the header.
220
+ *
221
+ * @param branch - The branch the shop is showing.
222
+ * @param options - The cookie, what it keeps and the query parameter.
223
+ */
224
+ declare function useRememberLinkedBranch(branch: Pick<Branch, "id" | "slug"> | undefined, { cookie, rememberBy, param, }: Pick<BranchChoiceOptions, "rememberBy" | "param"> & {
225
+ cookie: string;
226
+ }): void;
133
227
  /** The router state `useReloadingBranch` reads: React Router's `useLocation()` and `useNavigation()`. */
134
228
  type BranchSwitchRouterState = {
135
229
  location: {
@@ -164,5 +258,5 @@ type ReloadingBranch = {
164
258
  */
165
259
  declare function useReloadingBranch(shop: BranchSwitchShop, { location, navigation }: BranchSwitchRouterState, param?: string): ReloadingBranch | undefined;
166
260
 
167
- export { branchNamed, createBranchSwitchLoader, loadedBranchOf, reloadsShop, useBranchIntent, useChooseBranch, useReloadingBranch };
168
- export type { BranchSwitchClientLoaderArgs, BranchSwitchLoader, BranchSwitchOptions, BranchSwitchRevalidateArgs, BranchSwitchRouterState, BranchSwitchShop, LoadedBranch, ReloadingBranch };
261
+ export { atBranch, branchNamed, createBranchSwitchLoader, loadedBranchOf, reloadsShop, rememberBranch, shopAtBranch, useBranchChoice, useBranchIntent, useChooseBranch, useReloadingBranch, useRememberLinkedBranch };
262
+ export type { BranchChoiceOptions, BranchDestination, BranchSwitchClientLoaderArgs, BranchSwitchLoader, BranchSwitchOptions, BranchSwitchRevalidateArgs, BranchSwitchRouterState, BranchSwitchShop, ChooseBranch, LoadedBranch, ReloadingBranch };
@@ -1,2 +1,2 @@
1
- "use client";import{useCart,useZappie}from"@zappie/sdk/react";import{useMemo}from"react";import{useIntentPreload}from"../deferred/index.js";function loadedBranchOf(shop){return{...shop.branch?{id:shop.branch.id,slug:shop.branch.slug}:{},chosen:shop.branchChosen??true}}function branchNamed(store,wanted){return wanted?store.branches.find(branch=>branch.id===wanted||branch.slug===wanted):void 0}function reloadsShop(current,next,loaded,param="branch"){const wanted=next.get(param);if(wanted===null||wanted===current.get(param)){return false}return!(loaded?.chosen&&(wanted===loaded.id||wanted===loaded.slug))}function createBranchSwitchLoader({shopAt,serverOnly,param="branch"}){let live;return{remember(shop,client){if(typeof window!=="undefined"){live={shop,client}}},shouldRevalidate({currentUrl,nextUrl,formMethod,defaultShouldRevalidate}){if(formMethod&&formMethod.toUpperCase()!=="GET"){return defaultShouldRevalidate}return reloadsShop(currentUrl.searchParams,nextUrl.searchParams,live&&loadedBranchOf(live.shop),param)},async clientLoader({request,serverLoader}){const url=new URL(request.url);const current=live;const branch=current?branchNamed(current.shop.store,url.searchParams.get(param)):void 0;if(current&&branch&&!serverOnly?.(url,current.shop)){try{const menu=await current.client.menu.get({branch:branch.id,signal:request.signal});return shopAt(current.shop,branch,menu)}catch(error){if(request.signal.aborted){throw error}}}return serverLoader()}}}var readMenu=(client,branch)=>client.menu.get({branch:typeof branch==="string"?branch:branch.id});function useBranchIntent(branch){const client=useZappie();return useIntentPreload(useMemo(()=>({preload:()=>readMenu(client,branch)}),[client,branch]))}function useChooseBranch(then){const client=useZappie();const cart=useCart();return async branch=>{readMenu(client,branch).catch(()=>{});if(cart.lines.length>0&&branch.id!==cart.branchId){await cart.actions.moveTo(branch.id)}await then(branch)}}function useReloadingBranch(shop,{location,navigation},param="branch"){const next=navigation.state==="loading"?navigation.location:void 0;const pathname=next?.pathname;const search=next?.search;return useMemo(()=>{if(pathname===void 0||search===void 0){return void 0}const wanted=new URLSearchParams(search);if(!reloadsShop(new URLSearchParams(location.search),wanted,loadedBranchOf(shop),param)){return void 0}const branch=branchNamed(shop.store,wanted.get(param));return branch?{branch,pathname}:void 0},[shop,location.search,pathname,search,param])}export{branchNamed,createBranchSwitchLoader,loadedBranchOf,reloadsShop,useBranchIntent,useChooseBranch,useReloadingBranch};
1
+ "use client";import{useCart,useZappie}from"@zappie/sdk/react";import{useEffect,useMemo}from"react";import{useLocation,useNavigate}from"react-router";import{useIntentPreload}from"../deferred/index.js";function shopAtBranch(shop,branch,menu){const fields=shop;return{...shop,...fields.config?{config:{...fields.config,branch:branch.id}}:{},branch,menu,branchChosen:true,..."mustChoose"in fields?{mustChoose:false}:{}}}function loadedBranchOf(shop){return{...shop.branch?{id:shop.branch.id,slug:shop.branch.slug}:{},chosen:shop.branchChosen??true}}function branchNamed(store,wanted){return wanted?store.branches.find(branch=>branch.id===wanted||branch.slug===wanted):void 0}function reloadsShop(current,next,loaded,param="branch"){const wanted=next.get(param);if(wanted===null||wanted===current.get(param)){return false}return!(loaded?.chosen&&(wanted===loaded.id||wanted===loaded.slug))}function createBranchSwitchLoader({shopAt=shopAtBranch,serverOnly,param="branch"}={}){let live;return{remember(shop,client){if(typeof window!=="undefined"){live={shop,client}}},shouldRevalidate({currentUrl,nextUrl,formMethod,defaultShouldRevalidate}){if(formMethod&&formMethod.toUpperCase()!=="GET"){return defaultShouldRevalidate}return reloadsShop(currentUrl.searchParams,nextUrl.searchParams,live&&loadedBranchOf(live.shop),param)},async clientLoader({request,serverLoader}){const url=new URL(request.url);const current=live;const branch=current?branchNamed(current.shop.store,url.searchParams.get(param)):void 0;if(current&&branch&&!serverOnly?.(url,current.shop)){try{const menu=await current.client.menu.get({branch:branch.id,signal:request.signal});return shopAt(current.shop,branch,menu)}catch(error){if(request.signal.aborted){throw error}}}return serverLoader()}}}var readMenu=(client,branch)=>client.menu.get({branch:typeof branch==="string"?branch:branch.id});function useBranchIntent(branch){const client=useZappie();return useIntentPreload(useMemo(()=>({preload:()=>readMenu(client,branch)}),[client,branch]))}function useChooseBranch(then){const move=useMoveToBranch();return async branch=>{await move(branch);await then(branch)}}function useMoveToBranch(){const client=useZappie();const cart=useCart();return async branch=>{readMenu(client,branch).catch(()=>{});if(cart.lines.length>0&&branch.id!==cart.branchId){await cart.actions.moveTo(branch.id)}}}var COOKIE_MAX_AGE=2592e3;function rememberBranch(cookie,branch){document.cookie=`${cookie}=${encodeURIComponent(branch)}; path=/; max-age=${COOKIE_MAX_AGE}; samesite=lax`}function atBranch(path,branch,param="branch"){const url=new URL(path,"https://site.invalid");url.searchParams.set(param,branch);return`${url.pathname}${url.search}${url.hash}`}function useBranchChoice({cookie,rememberBy,to="/",param,then}={}){const navigate=useNavigate();const move=useMoveToBranch();return async(branch,destination)=>{await move(branch);if(cookie){rememberBranch(cookie,rememberBy==="slug"?branch.slug:branch.id)}const where=destination??(typeof to==="string"?{path:to}:to(branch));void navigate(atBranch(where.path,branch.slug,param),{state:where.state,replace:where.replace??false,preventScrollReset:where.preventScrollReset??false});then?.(branch,where)}}function useRememberLinkedBranch(branch,{cookie,rememberBy,param="branch"}){const named=new URLSearchParams(useLocation().search).get(param);const id=branch?.id;const slug=branch?.slug;useEffect(()=>{if(named&&id&&slug&&(named===id||named===slug)){rememberBranch(cookie,rememberBy==="slug"?slug:id)}},[named,id,slug,cookie,rememberBy])}function useReloadingBranch(shop,{location,navigation},param="branch"){const next=navigation.state==="loading"?navigation.location:void 0;const pathname=next?.pathname;const search=next?.search;return useMemo(()=>{if(pathname===void 0||search===void 0){return void 0}const wanted=new URLSearchParams(search);if(!reloadsShop(new URLSearchParams(location.search),wanted,loadedBranchOf(shop),param)){return void 0}const branch=branchNamed(shop.store,wanted.get(param));return branch?{branch,pathname}:void 0},[shop,location.search,pathname,search,param])}export{atBranch,branchNamed,createBranchSwitchLoader,loadedBranchOf,reloadsShop,rememberBranch,shopAtBranch,useBranchChoice,useBranchIntent,useChooseBranch,useReloadingBranch,useRememberLinkedBranch};
2
2
  //# sourceMappingURL=index.js.map
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/branch-switch/index.ts"],
4
- "mappings": "aAEA,OAAS,QAAS,cAAiB,oBACnC,OAAS,YAAe,QACxB,OAAS,qBAAoD,uBAuEtD,SAAS,eAAe,KAAsC,CACnE,MAAO,CACL,GAAI,KAAK,OAAS,CAAE,GAAI,KAAK,OAAO,GAAI,KAAM,KAAK,OAAO,IAAK,EAAI,CAAC,EACpE,OAAQ,KAAK,cAAgB,IAC/B,CACF,CAQO,SAAS,YACd,MACA,OACoB,CACpB,OAAO,OACH,MAAM,SAAS,KACZ,QAAW,OAAO,KAAO,QAAU,OAAO,OAAS,MACtD,EACA,MACN,CAaO,SAAS,YACd,QACA,KACA,OACA,MAAQ,SACC,CACT,MAAM,OAAS,KAAK,IAAI,KAAK,EAC7B,GAAI,SAAW,MAAQ,SAAW,QAAQ,IAAI,KAAK,EAAG,CACpD,MAAO,MACT,CACA,MAAO,EAAE,QAAQ,SAAW,SAAW,OAAO,IAAM,SAAW,OAAO,MACxE,CAiBO,SAAS,yBAAqD,CACnE,OACA,WACA,MAAQ,QACV,EAAkD,CAChD,IAAI,KACJ,MAAO,CACL,SAAS,KAAM,OAAQ,CACrB,GAAI,OAAO,SAAW,YAAa,CACjC,KAAO,CAAE,KAAM,MAAO,CACxB,CACF,EACA,iBAAiB,CACf,WACA,QACA,WACA,uBACF,EAAG,CACD,GAAI,YAAc,WAAW,YAAY,IAAM,MAAO,CACpD,OAAO,uBACT,CACA,OAAO,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oBAAsB,KAClD,CAAC,EACD,OAAO,OAAQ,KAAK,CACtB,CACF,CAUO,SAAS,wBACd,OACA,CACE,OACA,WACA,MAAQ,QACV,EACM,CACN,MAAM,MAAQ,IAAI,gBAAgB,YAAY,EAAE,MAAM,EAAE,IAAI,KAAK,EACjE,MAAM,GAAK,QAAQ,GACnB,MAAM,KAAO,QAAQ,KACrB,UAAU,IAAM,CACd,GAAI,OAAS,IAAM,OAAS,QAAU,IAAM,QAAU,MAAO,CAC3D,eAAe,OAAQ,aAAe,OAAS,KAAO,EAAE,CAC1D,CACF,EAAG,CAAC,MAAO,GAAI,KAAM,OAAQ,UAAU,CAAC,CAC1C,CA4BO,SAAS,mBACd,KACA,CAAE,SAAU,UAAW,EACvB,MAAQ,SACqB,CAC7B,MAAM,KAAO,WAAW,QAAU,UAAY,WAAW,SAAW,OACpE,MAAM,SAAW,MAAM,SACvB,MAAM,OAAS,MAAM,OACrB,OAAO,QAAQ,IAAM,CACnB,GAAI,WAAa,QAAa,SAAW,OAAW,CAClD,OAAO,MACT,CACA,MAAM,OAAS,IAAI,gBAAgB,MAAM,EACzC,GACE,CAAC,YACC,IAAI,gBAAgB,SAAS,MAAM,EACnC,OACA,eAAe,IAAI,EACnB,KACF,EACA,CACA,OAAO,MACT,CACA,MAAM,OAAS,YAAY,KAAK,MAAO,OAAO,IAAI,KAAK,CAAC,EACxD,OAAO,OAAS,CAAE,OAAQ,QAAS,EAAI,MACzC,EAAG,CAAC,KAAM,SAAS,OAAQ,SAAU,OAAQ,KAAK,CAAC,CACrD",
5
5
  "names": []
6
6
  }
@@ -1,5 +1,7 @@
1
- import { CartModule, CartIssue, Branch, Menu, CartState, Money, CartLine, CartFulfilment, DeliveryAddress, Quote, CartFix } from '@zappie/sdk';
1
+ import { CartModule, CartIssue, CartState, Money, Branch, Menu, CartLine, CartFulfilment, DeliveryAddress, Quote, CartFix } from '@zappie/sdk';
2
2
  import { CheckoutRequest, CheckoutClient } from '@zappie/sdk/checkout';
3
+ import { C as CheckoutMode } from '../offers-fDZ0bZ0i.js';
4
+ export { c as checkoutOffers } from '../offers-fDZ0bZ0i.js';
3
5
  import { CustomerClient } from '@zappie/sdk/customer';
4
6
 
5
7
  type Payload = ReturnType<CartModule["toCheckoutPayload"]>;
@@ -97,21 +99,6 @@ declare function fieldMarker(key: string): FieldMarker;
97
99
  */
98
100
  declare function fieldSelector(key: string): string;
99
101
 
100
- /**
101
- * How the order reaches the shopper: delivered, picked up, or placed in the venue (`dine_in`).
102
- * Name the in-venue mode with `inVenueLabel(branch)` from `@zappie/sdk/display`: "Walk-in" at a
103
- * retail branch, "Dine-in" otherwise.
104
- */
105
- type CheckoutMode = "delivery" | "pickup" | "dine_in";
106
- /**
107
- * The modes the branch takes and its menus serve, in the order delivery, pickup, in venue. A
108
- * menu that lists no modes serves every mode the branch takes.
109
- *
110
- * @param branch - The cart's branch.
111
- * @param menu - The branch's menu, whose source menus can each list the modes they serve.
112
- */
113
- declare function checkoutOffers(branch: Branch, menu?: Menu | undefined): CheckoutMode[];
114
-
115
102
  /**
116
103
  * What the one Pay button does now, in precedence order: the first that applies wins.
117
104
  *
@@ -434,5 +421,5 @@ type CheckoutFlow = {
434
421
  */
435
422
  declare function useCheckoutFlow(options: CheckoutFlowOptions): CheckoutFlow;
436
423
 
437
- export { checkoutOffers, checkoutStatus, checkoutTiming, contactProblems, createCheckoutAttempt, fieldMarker, fieldSelector, firstIssue, fullPhone, issueMarker, issueSelector, mustSchedule, payEnabled, signInOnce, useCheckoutFlow };
438
- export type { CheckoutAccount, CheckoutAttempt, CheckoutAuth, CheckoutContact, CheckoutCustomer, CheckoutDelivery, CheckoutDeliveryChange, CheckoutFlow, CheckoutFlowError, CheckoutFlowOptions, CheckoutIntent, CheckoutMode, CheckoutNotice, CheckoutPay, CheckoutStatus, CheckoutStatusInput, CheckoutTiming, ContactField, ContactProblem, ContactValues, FieldMarker, IssueMarker };
424
+ export { CheckoutMode, checkoutStatus, checkoutTiming, contactProblems, createCheckoutAttempt, fieldMarker, fieldSelector, firstIssue, fullPhone, issueMarker, issueSelector, mustSchedule, payEnabled, signInOnce, useCheckoutFlow };
425
+ export type { CheckoutAccount, CheckoutAttempt, CheckoutAuth, CheckoutContact, CheckoutCustomer, CheckoutDelivery, CheckoutDeliveryChange, CheckoutFlow, CheckoutFlowError, CheckoutFlowOptions, CheckoutIntent, CheckoutNotice, CheckoutPay, CheckoutStatus, CheckoutStatusInput, CheckoutTiming, ContactField, ContactProblem, ContactValues, FieldMarker, IssueMarker };
@@ -0,0 +1,19 @@
1
+ import { Branch, Menu } from '@zappie/sdk';
2
+
3
+ /**
4
+ * How the order reaches the shopper: delivered, picked up, or placed in the venue (`dine_in`).
5
+ * Name the in-venue mode with `inVenueLabel(branch)` from `@zappie/sdk/display`: "Walk-in" at a
6
+ * retail branch, "Dine-in" otherwise.
7
+ */
8
+ type CheckoutMode = "delivery" | "pickup" | "dine_in";
9
+ /**
10
+ * The modes the branch takes and its menus serve, in the order delivery, pickup, in venue. A
11
+ * menu that lists no modes serves every mode the branch takes.
12
+ *
13
+ * @param branch - The cart's branch.
14
+ * @param menu - The branch's menu, whose source menus can each list the modes they serve.
15
+ */
16
+ declare function checkoutOffers(branch: Branch, menu?: Menu | undefined): CheckoutMode[];
17
+
18
+ export { checkoutOffers as c };
19
+ export type { CheckoutMode as C };
package/dist/version.js CHANGED
@@ -1,2 +1,2 @@
1
- var PACKAGE_VERSION=true?"0.18.0":"0.0.0-development";export{PACKAGE_VERSION};
1
+ var PACKAGE_VERSION=true?"0.19.0":"0.0.0-development";export{PACKAGE_VERSION};
2
2
  //# sourceMappingURL=version.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zappie/foundations",
3
- "version": "0.18.0",
3
+ "version": "0.19.0",
4
4
  "description": "UI-less React primitives for Zappie storefronts: behaviour, state and accessibility without styles.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -17,6 +17,14 @@
17
17
  "types": "./dist/branch-switch/index.d.ts",
18
18
  "import": "./dist/branch-switch/index.js"
19
19
  },
20
+ "./branch-finder": {
21
+ "types": "./dist/branch-finder/index.d.ts",
22
+ "import": "./dist/branch-finder/index.js"
23
+ },
24
+ "./branch-list": {
25
+ "types": "./dist/branch-list/index.d.ts",
26
+ "import": "./dist/branch-list/index.js"
27
+ },
20
28
  "./schedule": {
21
29
  "types": "./dist/schedule/index.d.ts",
22
30
  "import": "./dist/schedule/index.js"