@zappie/foundations 0.18.0 → 0.20.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 +20 -0
- package/README.md +203 -23
- package/dist/branch-finder/index.d.ts +60 -0
- package/dist/branch-finder/index.js +2 -0
- package/dist/branch-finder/index.js.map +6 -0
- package/dist/branch-list/index.d.ts +100 -0
- package/dist/branch-list/index.js +2 -0
- package/dist/branch-list/index.js.map +6 -0
- package/dist/branch-list/nearest.js +2 -0
- package/dist/branch-list/nearest.js.map +6 -0
- package/dist/branch-list/offers.js +2 -0
- package/dist/branch-list/offers.js.map +6 -0
- package/dist/branch-switch/index.d.ts +101 -7
- package/dist/branch-switch/index.js +1 -1
- package/dist/branch-switch/index.js.map +1 -1
- package/dist/checkout/index.d.ts +5 -18
- package/dist/hours/index.d.ts +237 -0
- package/dist/hours/index.js +2 -0
- package/dist/hours/index.js.map +6 -0
- package/dist/offers-fDZ0bZ0i.d.ts +19 -0
- package/dist/version.js +1 -1
- package/package.json +13 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,25 @@
|
|
|
1
1
|
# @zappie/foundations
|
|
2
2
|
|
|
3
|
+
## 0.20.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 4102e33: `@zappie/foundations/hours` puts a branch's hours into words, in the branch's own time zone, then the store's, then Africa/Lagos. `openStatus` and `useOpenStatus` say whether it is open, closing soon or when it opens next. `opensLabel` and `nextOpening` read the API's next opening and fall back to the hours. `closedForOrders` and `takesOrdersAhead` say whether it takes an order now or for later. `openingHours` groups a week from Sunday, Monday or today, and `branchHours` gives a branch card its status, today's hours and its week. Every label takes your clock style, weekday names and words. `useNow` is the shopper's clock once the page is in the browser.
|
|
8
|
+
|
|
9
|
+
The starter's Our branches page shows each branch's status, whether it takes orders while closed and its week from today.
|
|
10
|
+
|
|
11
|
+
## 0.19.0
|
|
12
|
+
|
|
13
|
+
### Minor Changes
|
|
14
|
+
|
|
15
|
+
- 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.
|
|
16
|
+
|
|
17
|
+
`@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.
|
|
18
|
+
|
|
19
|
+
`@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.
|
|
20
|
+
|
|
21
|
+
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.
|
|
22
|
+
|
|
3
23
|
## 0.18.0
|
|
4
24
|
|
|
5
25
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -36,6 +36,9 @@ 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 |
|
|
41
|
+
| `@zappie/foundations/hours` | Open now, opening labels, closed for orders and a week of hours |
|
|
39
42
|
| `@zappie/foundations/checkout` | Checkout behaviour for a bag or a cart page, with no markup |
|
|
40
43
|
| `@zappie/foundations/loyalty` | The rewards sheet's parts, the bag's rewards row and the claim toast |
|
|
41
44
|
| `@zappie/foundations/order` | A customer's order details page, as parts or one default layout |
|
|
@@ -444,19 +447,9 @@ that don't use it never load it. Use it in a React Router root route:
|
|
|
444
447
|
import {
|
|
445
448
|
createBranchSwitchLoader,
|
|
446
449
|
useReloadingBranch,
|
|
447
|
-
} from "@zappie/foundations";
|
|
450
|
+
} from "@zappie/foundations/branch-switch";
|
|
448
451
|
|
|
449
452
|
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
453
|
// Paths your loader redirects go to the server.
|
|
461
454
|
serverOnly: (url, shop) => Boolean(redirectFor(shop.store, url.pathname)),
|
|
462
455
|
});
|
|
@@ -474,34 +467,35 @@ export default function App() {
|
|
|
474
467
|
}
|
|
475
468
|
```
|
|
476
469
|
|
|
477
|
-
- `createBranchSwitchLoader({ shopAt
|
|
470
|
+
- `createBranchSwitchLoader({ shopAt?, serverOnly?, param? })` returns
|
|
478
471
|
`remember`, `shouldRevalidate` and `clientLoader`. Your loader data needs
|
|
479
472
|
`store`, `branch` and, when the shopper chooses a branch, `branchChosen`.
|
|
480
473
|
Without `branchChosen` the loaded branch counts as chosen.
|
|
481
474
|
- `clientLoader` builds the shop with `shopAt` from the shop the root last
|
|
482
475
|
rendered. An unknown branch, a `serverOnly` URL or a failed read calls
|
|
483
476
|
`serverLoader()`. A cancelled navigation throws.
|
|
477
|
+
- `shopAt` is what your loader returns for `?branch=<that branch>`. It
|
|
478
|
+
defaults to `shopAtBranch`, which sets `branch`, `menu` and
|
|
479
|
+
`config.branch`, marks the branch chosen and clears `mustChoose` where your
|
|
480
|
+
shop has them. Pass your own when another field depends on the branch, such
|
|
481
|
+
as a home link per branch.
|
|
484
482
|
- `shouldRevalidate` reloads the shop only for a link that names another
|
|
485
483
|
branch. A link without `?branch=` keeps the branch, and so does a link to the
|
|
486
484
|
branch already loaded and chosen. Form submissions keep React Router's rule.
|
|
487
485
|
- `reloadsShop`, `branchNamed` and `loadedBranchOf` are the rules behind them,
|
|
488
486
|
for your own code.
|
|
489
487
|
|
|
490
|
-
|
|
488
|
+
Choose a branch from a picker, a locator or a card:
|
|
491
489
|
|
|
492
490
|
```tsx
|
|
493
491
|
import {
|
|
492
|
+
useBranchChoice,
|
|
494
493
|
useBranchIntent,
|
|
495
|
-
useChooseBranch,
|
|
496
494
|
} from "@zappie/foundations/branch-switch";
|
|
497
495
|
|
|
498
496
|
function BranchCard({ branch }: { branch: Branch }) {
|
|
499
497
|
const intent = useBranchIntent(branch);
|
|
500
|
-
const
|
|
501
|
-
const choose = useChooseBranch((next) => {
|
|
502
|
-
rememberBranch(next.id);
|
|
503
|
-
navigate(`/menu?branch=${next.slug}`);
|
|
504
|
-
});
|
|
498
|
+
const choose = useBranchChoice({ cookie: "site_branch", to: "/menu" });
|
|
505
499
|
return (
|
|
506
500
|
<button type="button" {...intent} onClick={() => void choose(branch)}>
|
|
507
501
|
Order from {branch.name}
|
|
@@ -513,10 +507,24 @@ function BranchCard({ branch }: { branch: Branch }) {
|
|
|
513
507
|
- `useBranchIntent(branch)` returns `{ onPointerEnter, onPointerDown, onFocus }`.
|
|
514
508
|
Each starts the branch's menu read. The client shares one read per branch,
|
|
515
509
|
so the click and the loader reuse it.
|
|
516
|
-
- `
|
|
517
|
-
branch,
|
|
518
|
-
|
|
519
|
-
the
|
|
510
|
+
- `useBranchChoice({ cookie?, rememberBy?, to?, param?, then? })` returns
|
|
511
|
+
`choose(branch, destination?)`. It starts the menu read, moves a bag with
|
|
512
|
+
lines to the branch, keeps the choice in `cookie`, and navigates to the
|
|
513
|
+
destination with the branch in its address. The cookie keeps the branch ID
|
|
514
|
+
unless `rememberBy` is `"slug"`. Give the server's `loadStoreAndMenu` (in
|
|
515
|
+
`@zappie/sdk/server`) the same cookie, and the page cache its
|
|
516
|
+
`branchCookie`. Without a destination the shopper goes to `to`, `/` by
|
|
517
|
+
default, or to what `to(branch)` returns. A destination is
|
|
518
|
+
`{ path, state?, replace?, preventScrollReset? }`, so a finder opened from an
|
|
519
|
+
item can go back to it with the line chosen so far. `then(branch,
|
|
520
|
+
destination)` runs once the navigation has started: close the finder there,
|
|
521
|
+
or scroll to the menu. Call it inside the router.
|
|
522
|
+
- `useRememberLinkedBranch(branch, { cookie, rememberBy?, param? })` keeps a
|
|
523
|
+
branch a link names in the cookie, so pages without `?branch=` stay on it.
|
|
524
|
+
- `rememberBranch(cookie, value)` and `atBranch(path, branch, param?)` are the
|
|
525
|
+
pieces, for your own code.
|
|
526
|
+
- `useChooseBranch(then)` only moves the bag and calls `then` once the move is
|
|
527
|
+
done, for a choice that remembers and navigates its own way.
|
|
520
528
|
|
|
521
529
|
Show your own skeleton while the shop reloads for a branch:
|
|
522
530
|
|
|
@@ -536,6 +544,178 @@ return reloading?.pathname === "/menu" ? (
|
|
|
536
544
|
`{ branch, pathname }` while a navigation reloads the shop for a branch the
|
|
537
545
|
store has, and undefined otherwise.
|
|
538
546
|
|
|
547
|
+
## Branch finder
|
|
548
|
+
|
|
549
|
+
`@zappie/foundations/branch-finder` opens the site's own branch picker or
|
|
550
|
+
locator from the header, the hero, an item card or the footer. Its code loads
|
|
551
|
+
with `deferred()`, starts loading when a shopper reaches for a control, and
|
|
552
|
+
mounts on the first open. The finder's look, its list and its frame stay
|
|
553
|
+
yours.
|
|
554
|
+
|
|
555
|
+
```tsx
|
|
556
|
+
import { deferred, OverlayRetry } from "@zappie/foundations";
|
|
557
|
+
import { BranchFinder } from "@zappie/foundations/branch-finder";
|
|
558
|
+
|
|
559
|
+
const finder = deferred(() => import("./ui/branch-dialog"));
|
|
560
|
+
|
|
561
|
+
<BranchFinder.Root
|
|
562
|
+
finder={finder}
|
|
563
|
+
preloadWhenIdle
|
|
564
|
+
failed={(retry, close) => (
|
|
565
|
+
<OverlayRetry
|
|
566
|
+
message="The branch list didn't load."
|
|
567
|
+
retry={retry}
|
|
568
|
+
close={close}
|
|
569
|
+
/>
|
|
570
|
+
)}
|
|
571
|
+
>
|
|
572
|
+
<Header />{" "}
|
|
573
|
+
{/* <BranchFinder.Trigger className="branch">Choose a branch</BranchFinder.Trigger> */}
|
|
574
|
+
<Outlet />
|
|
575
|
+
</BranchFinder.Root>;
|
|
576
|
+
|
|
577
|
+
// app/ui/branch-dialog.tsx
|
|
578
|
+
export default function BranchDialog({
|
|
579
|
+
open,
|
|
580
|
+
onClose,
|
|
581
|
+
then,
|
|
582
|
+
}: BranchFinderProps) {
|
|
583
|
+
const choose = useBranchChoice({
|
|
584
|
+
cookie: "site_branch",
|
|
585
|
+
to: "/menu",
|
|
586
|
+
then: onClose,
|
|
587
|
+
});
|
|
588
|
+
// … each branch calls choose(branch, then)
|
|
589
|
+
}
|
|
590
|
+
```
|
|
591
|
+
|
|
592
|
+
- `BranchFinder.Root` goes around the shell once. It renders `finder` with
|
|
593
|
+
`open`, `onClose` and `then`, the destination the control asked for.
|
|
594
|
+
`preloadWhenIdle` loads its code once the page is idle. `failed` shows while
|
|
595
|
+
open when the code didn't load.
|
|
596
|
+
- `BranchFinder.Trigger` is a button marked
|
|
597
|
+
`data-zappie-overlay-trigger="branch"` with `aria-haspopup="dialog"`. `then`
|
|
598
|
+
is where the shopper goes once they choose, such as the item the card
|
|
599
|
+
shows. Your `onClick` runs first and can cancel with `preventDefault()`. Use
|
|
600
|
+
`asChild` for your own button.
|
|
601
|
+
- `useBranchFinder()` gives `open(then?)` and `close()`. They never change.
|
|
602
|
+
|
|
603
|
+
## Branch list
|
|
604
|
+
|
|
605
|
+
`@zappie/foundations/branch-list` is the data behind a picker or a locator:
|
|
606
|
+
the branches nearest first, and what each one sells. It loads only on the
|
|
607
|
+
pages that use it.
|
|
608
|
+
|
|
609
|
+
```tsx
|
|
610
|
+
import {
|
|
611
|
+
kilometres,
|
|
612
|
+
menusLabel,
|
|
613
|
+
nearestFirst,
|
|
614
|
+
useBranchOffers,
|
|
615
|
+
useHere,
|
|
616
|
+
whereIs,
|
|
617
|
+
} from "@zappie/foundations/branch-list";
|
|
618
|
+
|
|
619
|
+
const { here, locate, locating, refused } = useHere();
|
|
620
|
+
const offers = useBranchOffers(store.branches, { active: open });
|
|
621
|
+
<button type="button" onClick={locate} disabled={locating}>
|
|
622
|
+
Use my location
|
|
623
|
+
</button>;
|
|
624
|
+
{
|
|
625
|
+
nearestFirst(store.branches, here).map((branch) => (
|
|
626
|
+
<BranchCard
|
|
627
|
+
key={branch.id}
|
|
628
|
+
branch={branch}
|
|
629
|
+
menus={offers[branch.id]?.menus}
|
|
630
|
+
/>
|
|
631
|
+
));
|
|
632
|
+
}
|
|
633
|
+
```
|
|
634
|
+
|
|
635
|
+
- `useHere(timeout?)` asks the browser where the shopper is when `locate`
|
|
636
|
+
runs, never before. It gives `here`, `setHere`, `locating`, `refused` and
|
|
637
|
+
`locate`. `refused` is true when the shopper says no, the browser has no
|
|
638
|
+
location or the lookup fails. `setHere` takes a location from elsewhere,
|
|
639
|
+
such as a saved address.
|
|
640
|
+
- `nearestFirst(branches, here)` sorts nearest first, puts a branch with no
|
|
641
|
+
location last and keeps ties in order. Without `here` the order stays.
|
|
642
|
+
- `whereIs(branch)` is the branch's pin, else its pickup point's. A pin at
|
|
643
|
+
0, 0 counts as none. `kilometres(from, to)` is the distance along the
|
|
644
|
+
earth's surface.
|
|
645
|
+
- `useBranchOffers(branches, { active?, typesOf? })` reads each branch's menus
|
|
646
|
+
without their items, once per branch for the page's life. It returns
|
|
647
|
+
`{ menus, types }` by branch ID: the names of menus that have categories, and
|
|
648
|
+
the order types they take, from `checkoutOffers` unless you pass `typesOf`.
|
|
649
|
+
A branch is absent until its answer arrives and stays absent when the read
|
|
650
|
+
fails. An empty `menus` means it has nothing to sell yet.
|
|
651
|
+
- `menusLabel(names)` joins the names with " · ", and reads "Breakfast only"
|
|
652
|
+
for one.
|
|
653
|
+
|
|
654
|
+
## Hours
|
|
655
|
+
|
|
656
|
+
`@zappie/foundations/hours` puts a branch's hours into words: open now and
|
|
657
|
+
closing soon, when it opens next, whether it takes orders, a week of hours and
|
|
658
|
+
a branch card's hours. It reads each branch in its own time zone, then the
|
|
659
|
+
store's (`storeTimezone`), then Africa/Lagos. It loads only on the pages that
|
|
660
|
+
use it.
|
|
661
|
+
|
|
662
|
+
```tsx
|
|
663
|
+
import {
|
|
664
|
+
closedForOrders,
|
|
665
|
+
opensLabel,
|
|
666
|
+
useBranchHours,
|
|
667
|
+
useOpenStatus,
|
|
668
|
+
} from "@zappie/foundations/hours";
|
|
669
|
+
|
|
670
|
+
const status = useOpenStatus(branch, { storeTimezone: store.timezone });
|
|
671
|
+
// undefined on the server, then { isOpen, closingSoon, closedForOrders, label: "Open until 10 pm", ... }
|
|
672
|
+
const hours = useBranchHours(branch, { storeTimezone: store.timezone });
|
|
673
|
+
{
|
|
674
|
+
hours?.week.map((row) => (
|
|
675
|
+
<div key={row.dayLabel} aria-current={row.today && "date"}>
|
|
676
|
+
<dt>{row.dayLabel}</dt>
|
|
677
|
+
<dd>{row.hoursLabel}</dd>
|
|
678
|
+
</div>
|
|
679
|
+
));
|
|
680
|
+
}
|
|
681
|
+
opensLabel(branch, { clock: { hour12: false } }); // "Opens tomorrow at 7:00"
|
|
682
|
+
closedForOrders(branch); // closed, and not taking orders for later
|
|
683
|
+
```
|
|
684
|
+
|
|
685
|
+
- `openStatus(branch, options)` works out the state at `now` from the weekly
|
|
686
|
+
hours, special hours, overnight hours and `closedUntil`. Its label reads
|
|
687
|
+
"Open until 10 pm", "Closes at 10 pm" within `closingSoonMinutes` (30 by
|
|
688
|
+
default), "Opens at 8 am", "Opens tomorrow at 8 am", "Opens Mon at 8 am" or
|
|
689
|
+
"Closed". `closedForOrders` is true when it is closed and takes no orders
|
|
690
|
+
ahead.
|
|
691
|
+
- `opensLabel(branch, options)` and `nextOpening(branch, options)` give when a
|
|
692
|
+
closed branch opens next. `from: "api"`, the default, reads `isOpen`,
|
|
693
|
+
`closedUntil` and `nextChangeAt`, and falls back to the hours when no
|
|
694
|
+
opening is still ahead; `from: "hours"` reads only the hours. Today and
|
|
695
|
+
tomorrow are the branch's local dates.
|
|
696
|
+
- Every label takes `clock` (`hour12`, `padHour`, `minutes`, `period`,
|
|
697
|
+
`space`, `roundLastMinute`), `weekday` (`short` or `long`) and `phrases`,
|
|
698
|
+
whose `{time}` and `{weekday}` fill in: `{ today: "Opens today {time}" }`.
|
|
699
|
+
`formatClock(time, clock)` formats one wall-clock time.
|
|
700
|
+
- `closedForOrders(branch, { lastOrderMinutes? })` is the API's closed and no
|
|
701
|
+
orders ahead. With `lastOrderMinutes`, an open branch that closes within
|
|
702
|
+
them takes no order either, unless it takes orders ahead.
|
|
703
|
+
`takesOrdersAhead(branch, menu, menuIds)` says whether a bag can be timed
|
|
704
|
+
for later, by the branch or a pre-order menu.
|
|
705
|
+
- `openingHours(times, options)` groups a week into runs of days that share
|
|
706
|
+
their hours, from `start` (`sunday`, `monday` or `today`). `closed` names
|
|
707
|
+
the closed days, `everyDay` collapses a week of the same hours, `allDay`
|
|
708
|
+
names midnight to midnight, `today` marks its row, and `dayNames`, `range`
|
|
709
|
+
and `through` set the words.
|
|
710
|
+
- `branchHours(branch, options)` is a branch card's hours: its `status`,
|
|
711
|
+
`today`'s hours with special hours, and its `week` from today.
|
|
712
|
+
- `useNow()` is the time once the page is idle in the browser, then each
|
|
713
|
+
minute and on focus; undefined on the server. `useOpenStatus` and
|
|
714
|
+
`useBranchHours` run on it, so the server's HTML never disagrees with the
|
|
715
|
+
first render.
|
|
716
|
+
|
|
717
|
+
`src/hours/ADOPTING.md` maps each site's own copies onto these.
|
|
718
|
+
|
|
539
719
|
## Item form focus
|
|
540
720
|
|
|
541
721
|
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
|
+
"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,GA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Z,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": ["../../src/branch-list/offers.ts"],
|
|
4
|
+
"mappings": "aAEA,OAAS,cAAiB,oBAC1B,OAAS,UAAW,aAAgB,QACpC,OAAS,mBAAyC,wBAiBlD,IAAM,MAAQ,IAAI,QAElB,SAAS,QAAQ,OAAgB,OAAsC,CACrE,IAAI,MAAQ,MAAM,IAAI,MAAM,EAC5B,GAAI,CAAC,MAAO,CACV,MAAQ,IAAI,IACZ,MAAM,IAAI,OAAQ,KAAK,CACzB,CACA,IAAI,QAAU,MAAM,I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|
+
"names": []
|
|
6
|
+
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
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, }
|
|
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,Y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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
|
}
|
package/dist/checkout/index.d.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
import { CartModule, CartIssue,
|
|
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 {
|
|
438
|
-
export type { CheckoutAccount, CheckoutAttempt, CheckoutAuth, CheckoutContact, CheckoutCustomer, CheckoutDelivery, CheckoutDeliveryChange, CheckoutFlow, CheckoutFlowError, CheckoutFlowOptions, CheckoutIntent,
|
|
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,237 @@
|
|
|
1
|
+
import { OpeningTime, Branch, Menu } from '@zappie/sdk';
|
|
2
|
+
|
|
3
|
+
/** A day of the week, Sunday 0 to Saturday 6, as `OpeningTime.day` counts it. */
|
|
4
|
+
type Weekday = OpeningTime["day"];
|
|
5
|
+
/** The time zone for a branch and a store that name none. */
|
|
6
|
+
declare const DEFAULT_TIMEZONE = "Africa/Lagos";
|
|
7
|
+
/**
|
|
8
|
+
* The time zone a branch's hours are kept in: its own, then the store's, then Africa/Lagos.
|
|
9
|
+
*
|
|
10
|
+
* @param storeTimezone - The store's time zone, for a branch that names none.
|
|
11
|
+
*/
|
|
12
|
+
declare function branchTimezone(branch: Pick<Branch, "timezone">, storeTimezone?: string): string;
|
|
13
|
+
/** The weekday it is at `now` in `timezone`. */
|
|
14
|
+
declare function todayIn(timezone: string, now?: Date): Weekday;
|
|
15
|
+
/**
|
|
16
|
+
* How a time reads. The default is a 12-hour clock in lower case with a space, minutes only when they aren't
|
|
17
|
+
* zero: "9 am", "7:30 pm".
|
|
18
|
+
*/
|
|
19
|
+
type ClockStyle = {
|
|
20
|
+
/** A 12-hour clock with am and pm. Defaults to true. A 24-hour clock always shows its minutes: "7:00", "19:30". */
|
|
21
|
+
hour12?: boolean | undefined;
|
|
22
|
+
/** Pad the hour to two digits: "09:00 AM". Defaults to false. */
|
|
23
|
+
padHour?: boolean | undefined;
|
|
24
|
+
/** `auto` drops zero minutes ("9 am"), `always` keeps them ("9:00 am"). Defaults to `auto`. */
|
|
25
|
+
minutes?: "auto" | "always" | undefined;
|
|
26
|
+
/** `lower` reads "am", `upper` reads "AM". Defaults to `lower`. */
|
|
27
|
+
period?: "lower" | "upper" | undefined;
|
|
28
|
+
/** A space between the time and am or pm. Defaults to true. */
|
|
29
|
+
space?: boolean | undefined;
|
|
30
|
+
/** Read a minute to the hour as the hour, so the API's 16:59 close reads "5 pm". Defaults to false. */
|
|
31
|
+
roundLastMinute?: boolean | undefined;
|
|
32
|
+
};
|
|
33
|
+
/**
|
|
34
|
+
* Format an HH:mm or HH:mm:ss wall-clock time. Returns invalid input unchanged.
|
|
35
|
+
*
|
|
36
|
+
* @example
|
|
37
|
+
* ```ts
|
|
38
|
+
* formatClock("19:30"); // "7:30 pm"
|
|
39
|
+
* formatClock("09:00", { padHour: true, minutes: "always", period: "upper", space: false }); // "09:00AM"
|
|
40
|
+
* formatClock("07:00", { hour12: false }); // "7:00"
|
|
41
|
+
* ```
|
|
42
|
+
*/
|
|
43
|
+
declare function formatClock(time: string, { hour12, padHour, minutes, period, space, roundLastMinute, }?: ClockStyle): string;
|
|
44
|
+
/** When a closed branch opens next, in its own time zone. */
|
|
45
|
+
type NextOpening = {
|
|
46
|
+
at: Date;
|
|
47
|
+
/** Whether that is today or tomorrow in the branch's time zone, or a later day. */
|
|
48
|
+
day: "today" | "tomorrow" | "later";
|
|
49
|
+
weekday: Weekday;
|
|
50
|
+
/** The local wall-clock time, HH:mm. */
|
|
51
|
+
time: string;
|
|
52
|
+
};
|
|
53
|
+
/** The instant to measure from and the store's time zone, for a branch that names none. */
|
|
54
|
+
type HoursOptions = {
|
|
55
|
+
/** Defaults to the current time. */
|
|
56
|
+
now?: Date | undefined;
|
|
57
|
+
/** The store's time zone, for a branch that names none. The branch's own always wins. */
|
|
58
|
+
storeTimezone?: string | undefined;
|
|
59
|
+
};
|
|
60
|
+
/**
|
|
61
|
+
* When a closed branch opens next, or undefined while it is open or when nothing is ahead.
|
|
62
|
+
*
|
|
63
|
+
* `api` (the default) reads the API's answer: open is `branch.isOpen`, and the opening is `closedUntil`, then
|
|
64
|
+
* `nextChangeAt`. It falls back to the hours when the API sends no opening still ahead. `hours` works both out from
|
|
65
|
+
* the weekly hours, special hours and `closedUntil` at `now`, so it keeps up with the clock after the store was read.
|
|
66
|
+
*/
|
|
67
|
+
declare function nextOpening(branch: Branch, { from, now, storeTimezone, }?: HoursOptions & {
|
|
68
|
+
from?: "api" | "hours" | undefined;
|
|
69
|
+
}): NextOpening | undefined;
|
|
70
|
+
/**
|
|
71
|
+
* The words around an opening. `{time}` is the formatted time and `{weekday}` the day's name.
|
|
72
|
+
* The defaults read "Opens at 7 am", "Opens tomorrow at 7 am" and "Opens Thu at 7 am".
|
|
73
|
+
*/
|
|
74
|
+
type OpeningPhrases = {
|
|
75
|
+
today: string;
|
|
76
|
+
tomorrow: string;
|
|
77
|
+
later: string;
|
|
78
|
+
};
|
|
79
|
+
/** How an opening or a status reads. */
|
|
80
|
+
type LabelOptions = {
|
|
81
|
+
clock?: ClockStyle | undefined;
|
|
82
|
+
/** `short` reads "Thu", `long` reads "Thursday". Defaults to `short`. */
|
|
83
|
+
weekday?: "short" | "long" | undefined;
|
|
84
|
+
phrases?: Partial<OpeningPhrases> | undefined;
|
|
85
|
+
};
|
|
86
|
+
/** Put an opening into words, as `opensLabel` does. */
|
|
87
|
+
declare function describeOpening(next: NextOpening, { clock, weekday, phrases }?: LabelOptions): string;
|
|
88
|
+
/**
|
|
89
|
+
* When a closed branch opens next, in words and in its own time zone: "Opens at 7 am", "Opens tomorrow at 7 am",
|
|
90
|
+
* "Opens Thu at 7 am". Undefined while it is open or when nothing is ahead.
|
|
91
|
+
*
|
|
92
|
+
* @example
|
|
93
|
+
* ```ts
|
|
94
|
+
* opensLabel(branch, { clock: { hour12: false } }); // "Opens tomorrow at 7:00"
|
|
95
|
+
* opensLabel(branch, { from: "hours", weekday: "long", phrases: { today: "Opens today {time}" } });
|
|
96
|
+
* ```
|
|
97
|
+
*/
|
|
98
|
+
declare function opensLabel(branch: Branch, options?: HoursOptions & LabelOptions & {
|
|
99
|
+
from?: "api" | "hours" | undefined;
|
|
100
|
+
}): string | undefined;
|
|
101
|
+
/**
|
|
102
|
+
* Whether the branch takes no order at all now: closed, and not taking orders for later either.
|
|
103
|
+
*
|
|
104
|
+
* With `lastOrderMinutes`, an open branch that closes within that many minutes takes no order either, unless it takes
|
|
105
|
+
* orders for later. Open is the API's `branch.isOpen`, and the closing comes from its hours at `now`.
|
|
106
|
+
*/
|
|
107
|
+
declare function closedForOrders(branch: Branch, { lastOrderMinutes, now, storeTimezone, }?: HoursOptions & {
|
|
108
|
+
lastOrderMinutes?: number | undefined;
|
|
109
|
+
}): boolean;
|
|
110
|
+
/**
|
|
111
|
+
* Whether a bag can be timed for later: the branch takes orders ahead, or the bag holds an item from a pre-order
|
|
112
|
+
* menu, which is scheduled on that menu's own terms even at a branch that takes no orders ahead. Either way the
|
|
113
|
+
* branch must take scheduled orders.
|
|
114
|
+
*
|
|
115
|
+
* @param menuIds - The source menus of the bag's lines.
|
|
116
|
+
*/
|
|
117
|
+
declare function takesOrdersAhead(branch: Branch, menu: Menu | undefined, menuIds: readonly string[]): boolean;
|
|
118
|
+
/**
|
|
119
|
+
* The words of a status. `{time}` is the closing time in `open` and `closingSoon`.
|
|
120
|
+
* The defaults read "Open until 10 pm", "Closes at 10 pm" and "Closed".
|
|
121
|
+
*/
|
|
122
|
+
type StatusPhrases = OpeningPhrases & {
|
|
123
|
+
open: string;
|
|
124
|
+
closingSoon: string;
|
|
125
|
+
closed: string;
|
|
126
|
+
};
|
|
127
|
+
/** A branch's state at an instant, worked out from its hours in its own time zone. */
|
|
128
|
+
type HoursStatus = {
|
|
129
|
+
isOpen: boolean;
|
|
130
|
+
/** Whether the branch takes orders for later, so a closed branch can still take one. */
|
|
131
|
+
canOrderAhead: boolean;
|
|
132
|
+
/** Closed now and not taking orders for later. */
|
|
133
|
+
closedForOrders: boolean;
|
|
134
|
+
/** Open, and closing within `closingSoonMinutes`. */
|
|
135
|
+
closingSoon: boolean;
|
|
136
|
+
label: string;
|
|
137
|
+
/** When it opens next, while it is closed. */
|
|
138
|
+
next?: NextOpening;
|
|
139
|
+
/** The next opening or closing found in the hours, for a timer. */
|
|
140
|
+
nextChange?: Date;
|
|
141
|
+
timezone: string;
|
|
142
|
+
};
|
|
143
|
+
/** Options for `openStatus`. */
|
|
144
|
+
type OpenStatusOptions = HoursOptions & Omit<LabelOptions, "phrases"> & {
|
|
145
|
+
phrases?: Partial<StatusPhrases> | undefined;
|
|
146
|
+
/** How near the closing time counts as closing soon. Defaults to 30 minutes. */
|
|
147
|
+
closingSoonMinutes?: number | undefined;
|
|
148
|
+
};
|
|
149
|
+
/**
|
|
150
|
+
* Whether a branch is open at `now` and its next change in words, from its weekly hours, special hours, overnight
|
|
151
|
+
* hours and `closedUntil`, in the branch's own time zone.
|
|
152
|
+
*
|
|
153
|
+
* @example
|
|
154
|
+
* ```ts
|
|
155
|
+
* openStatus(branch, { now, storeTimezone: store.timezone });
|
|
156
|
+
* // { isOpen: true, closingSoon: false, label: "Open until 10 pm", ... }
|
|
157
|
+
* ```
|
|
158
|
+
*/
|
|
159
|
+
declare function openStatus(branch: Branch, { now, storeTimezone, closingSoonMinutes, phrases, ...label }?: OpenStatusOptions): HoursStatus;
|
|
160
|
+
/** One row of a week's hours: a run of days that share their hours. */
|
|
161
|
+
type HoursRow = {
|
|
162
|
+
days: Weekday[];
|
|
163
|
+
dayLabel: string;
|
|
164
|
+
hoursLabel: string;
|
|
165
|
+
/** Set on a run of closed days, when `closed` names them. */
|
|
166
|
+
closed?: true;
|
|
167
|
+
/** Set on the row that holds `today`. */
|
|
168
|
+
today?: true;
|
|
169
|
+
};
|
|
170
|
+
/** How a week's hours are grouped and read. */
|
|
171
|
+
type OpeningHoursOptions = {
|
|
172
|
+
/** The first day: `sunday`, `monday` or `today`. Defaults to `sunday`. `today` needs `today`. */
|
|
173
|
+
start?: "sunday" | "monday" | "today" | undefined;
|
|
174
|
+
/** Today's weekday, from `todayIn`, to start the week on or to mark its row. */
|
|
175
|
+
today?: Weekday | undefined;
|
|
176
|
+
/** Name the closed days with this label ("Closed") instead of leaving them out. */
|
|
177
|
+
closed?: string | undefined;
|
|
178
|
+
/** One row with this label ("Every day") when all seven days share their hours. */
|
|
179
|
+
everyDay?: string | undefined;
|
|
180
|
+
/** Read hours from midnight to 23:5x with this label ("Open all day"). */
|
|
181
|
+
allDay?: string | undefined;
|
|
182
|
+
clock?: ClockStyle | undefined;
|
|
183
|
+
/** Seven day names from Sunday. Defaults to the full English names. */
|
|
184
|
+
dayNames?: readonly string[] | undefined;
|
|
185
|
+
/** Between an opening and a closing time. Defaults to " – ". */
|
|
186
|
+
range?: string | undefined;
|
|
187
|
+
/** Between the first and last day of a run. Defaults to " – ". */
|
|
188
|
+
through?: string | undefined;
|
|
189
|
+
/** Between two sets of hours on one day. Defaults to ", ". */
|
|
190
|
+
separator?: string | undefined;
|
|
191
|
+
};
|
|
192
|
+
/**
|
|
193
|
+
* A week's opening hours grouped into runs of consecutive days that share their hours, from Sunday, Monday or
|
|
194
|
+
* today. Closed days are left out unless `closed` names them, and a week with no open day has no rows.
|
|
195
|
+
*
|
|
196
|
+
* @example
|
|
197
|
+
* ```ts
|
|
198
|
+
* openingHours(branch.openingTimes, { start: "monday", closed: "Closed", everyDay: "Every day" });
|
|
199
|
+
* // [{ days: [1, 2, 3, 4, 5], dayLabel: "Monday – Friday", hoursLabel: "8 am – 10 pm" },
|
|
200
|
+
* // { days: [6, 0], dayLabel: "Saturday – Sunday", hoursLabel: "Closed", closed: true }]
|
|
201
|
+
* ```
|
|
202
|
+
*/
|
|
203
|
+
declare function openingHours(times: readonly OpeningTime[], options?: OpeningHoursOptions): HoursRow[];
|
|
204
|
+
/** A branch's hours for a list of branches: its status, today's hours and its week from today. */
|
|
205
|
+
type BranchHours = {
|
|
206
|
+
status: HoursStatus;
|
|
207
|
+
/** Today's hours in the branch's time zone, with today's special hours. Empty on a closed day. */
|
|
208
|
+
today: string;
|
|
209
|
+
week: HoursRow[];
|
|
210
|
+
};
|
|
211
|
+
/** Options for `branchHours`: `hours` reads today's hours and the week, the rest read the status. */
|
|
212
|
+
type BranchHoursOptions = OpenStatusOptions & {
|
|
213
|
+
hours?: Omit<OpeningHoursOptions, "today"> | undefined;
|
|
214
|
+
};
|
|
215
|
+
/**
|
|
216
|
+
* Everything a branch card shows about hours, in the branch's own time zone: whether it is open at `now` and its next
|
|
217
|
+
* change, today's hours (special hours included), and the week starting today with today's row marked.
|
|
218
|
+
*/
|
|
219
|
+
declare function branchHours(branch: Branch, { hours, ...options }?: BranchHoursOptions): BranchHours;
|
|
220
|
+
/**
|
|
221
|
+
* The time now, once the page is in the browser and idle, then each `every` milliseconds and on window focus.
|
|
222
|
+
* Undefined while the server renders and until then, so hours are worked out on the shopper's clock and the server's
|
|
223
|
+
* HTML never disagrees with the first render.
|
|
224
|
+
*
|
|
225
|
+
* @param every - How often to refresh. Defaults to a minute.
|
|
226
|
+
*/
|
|
227
|
+
declare function useNow(every?: number): Date | undefined;
|
|
228
|
+
/**
|
|
229
|
+
* `openStatus` on the shopper's clock (`useNow`): undefined while the server renders and until the page is idle,
|
|
230
|
+
* then refreshed each minute and on window focus.
|
|
231
|
+
*/
|
|
232
|
+
declare function useOpenStatus(branch: Branch | undefined, options?: Omit<OpenStatusOptions, "now">): HoursStatus | undefined;
|
|
233
|
+
/** `branchHours` on the shopper's clock (`useNow`), undefined until the page is idle in the browser. */
|
|
234
|
+
declare function useBranchHours(branch: Branch, options?: Omit<BranchHoursOptions, "now">): BranchHours | undefined;
|
|
235
|
+
|
|
236
|
+
export { DEFAULT_TIMEZONE, branchHours, branchTimezone, closedForOrders, describeOpening, formatClock, nextOpening, openStatus, openingHours, opensLabel, takesOrdersAhead, todayIn, useBranchHours, useNow, useOpenStatus };
|
|
237
|
+
export type { BranchHours, BranchHoursOptions, ClockStyle, HoursOptions, HoursRow, HoursStatus, LabelOptions, NextOpening, OpenStatusOptions, OpeningHoursOptions, OpeningPhrases, StatusPhrases, Weekday };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{useEffect,useState}from"react";import{canOrderAhead,dateOffset,getOpenStatus,localParts,parseWallClock}from"../status/hours.js";var DEFAULT_TIMEZONE="Africa/Lagos";var LONG_DAYS=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];var SHORT_DAYS=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];var MINUTE=6e4;function branchTimezone(branch,storeTimezone){return branch.timezone??storeTimezone??DEFAULT_TIMEZONE}function todayIn(timezone,now=new Date){return new Date(`${localParts(now,timezone).date}T00:00:00Z`).getUTCDay()}function formatClock(time,{hour12=true,padHour=false,minutes="auto",period="lower",space=true,roundLastMinute=false}={}){const clock=parseWallClock(time);if(!clock){return time}let total=clock.hour24*60+clock.minute;if(roundLastMinute&&clock.minute===59){total=(total+1)%1440}const hour24=Math.floor(total/60);const minute=String(total%60).padStart(2,"0");const hour=String(hour12?hour24%12||12:hour24).padStart(padHour?2:1,"0");if(!hour12){return`${hour}:${minute}`}const half=hour24>=12?"PM":"AM";return`${hour}${minutes==="always"||minute!=="00"?`:${minute}`:""}${space?" ":""}${period==="upper"?half:half.toLowerCase()}`}var pad=value=>String(value).padStart(2,"0");function opening(at,timezone,now){const local=localParts(at,timezone);const today=localParts(now,timezone).date;return{at,day:local.date===today?"today":local.date===dateOffset(today,1)?"tomorrow":"later",weekday:new Date(`${local.date}T00:00:00Z`).getUTCDay(),time:`${pad(local.hour)}:${pad(local.minute)}`}}function nextOpening(branch,{from="api",now=new Date,storeTimezone}={}){const timezone=branchTimezone(branch,storeTimezone);if(from==="api"){if(branch.isOpen){return void 0}const value=branch.closedUntil??branch.nextChangeAt;const at=value?new Date(value):void 0;if(at&&at.getTime()>now.getTime()){return opening(at,timezone,now)}}const state=getOpenStatus(branch,timezone,now);return state.isOpen||!state.nextChange?void 0:opening(state.nextChange,timezone,now)}var OPENING={today:"Opens at {time}",tomorrow:"Opens tomorrow at {time}",later:"Opens {weekday} at {time}"};function describeOpening(next,{clock,weekday="short",phrases}={}){return{...OPENING,...phrases}[next.day].replace("{time}",formatClock(next.time,clock)).replace("{weekday}",(weekday==="long"?LONG_DAYS:SHORT_DAYS)[next.weekday])}function opensLabel(branch,options={}){const next=nextOpening(branch,options);return next&&describeOpening(next,options)}function closedForOrders(branch,{lastOrderMinutes,now=new Date,storeTimezone}={}){const ahead=canOrderAhead(branch);if(!branch.isOpen||ahead||!lastOrderMinutes){return!branch.isOpen&&!ahead}const state=getOpenStatus(branch,branchTimezone(branch,storeTimezone),now);return Boolean(state.isOpen&&state.nextChange&&state.nextChange.getTime()-now.getTime()<=lastOrderMinutes*MINUTE)}function takesOrdersAhead(branch,menu,menuIds){const preorder=menuIds.some(id=>menu?.menus?.find(section=>section.id===id)?.schedule?.preorder);return branch.fulfilment.scheduling&&(preorder||canOrderAhead(branch))}var STATUS={...OPENING,open:"Open until {time}",closingSoon:"Closes at {time}",closed:"Closed"};function openStatus(branch,{now=new Date,storeTimezone,closingSoonMinutes=30,phrases,...label}={}){const timezone=branchTimezone(branch,storeTimezone);const state=getOpenStatus(branch,timezone,now);const words={...STATUS,...phrases};const closingSoon=Boolean(state.isOpen&&state.nextChange&&state.nextChange.getTime()-now.getTime()<=closingSoonMinutes*MINUTE);const next=!state.isOpen&&state.nextChange?opening(state.nextChange,timezone,now):void 0;return{isOpen:state.isOpen,canOrderAhead:state.canOrderAhead,closedForOrders:!state.isOpen&&!state.canOrderAhead,closingSoon,label:state.isOpen?(closingSoon?words.closingSoon:words.open).replace("{time}",state.nextChange?formatClock(opening(state.nextChange,timezone,now).time,label.clock):""):next?describeOpening(next,{...label,phrases:words}):words.closed,...next?{next}:{},...state.nextChange?{nextChange:state.nextChange}:{},timezone}}function dayHours(times,day,{allDay,clock,range=" \u2013 ",separator=", "}){return times.filter(time=>!time.disabled&&time.day===day).sort((a,b)=>a.opens.localeCompare(b.opens)).map(time=>allDay!==void 0&&time.opens.startsWith("00:00")&&/^23:5\d/.test(time.closes)?allDay:`${formatClock(time.opens,clock)}${range}${formatClock(time.closes,clock)}`).join(separator)}function openingHours(times,options={}){const{start="sunday",today,closed,everyDay,dayNames=LONG_DAYS,through=" \u2013 "}=options;const first=start==="monday"?1:start==="today"?today??0:0;const week=Array.from({length:7},(_,index)=>(first+index)%7);const hours=week.map(day=>dayHours(times,day,options));if(!hours.some(Boolean)){return[]}const mark=days=>today!==void 0&&days.includes(today)?{today:true}:{};if(everyDay!==void 0&&hours.every(value=>value===hours[0])){return[{days:week,dayLabel:everyDay,hoursLabel:hours[0],...mark(week)}]}const runs=[];week.forEach((day,index)=>{const value=hours[index]||closed;if(value===void 0){return}const run=runs.at(-1);if(run&&run.last===index-1&&run.hours===value){run.days.push(day);run.last=index}else{runs.push({days:[day],hours:value,last:index})}});return runs.map(({days,hours:value})=>({days,dayLabel:days.length===1?dayNames[days[0]]:`${dayNames[days[0]]}${through}${dayNames[days.at(-1)]}`,hoursLabel:value,...value===closed&&!dayHours(times,days[0],options)?{closed:true}:{},...mark(days)}))}function branchHours(branch,{hours={},...options}={}){const status=openStatus(branch,options);const now=options.now??new Date;const day=todayIn(status.timezone,now);const date=localParts(now,status.timezone).date;const special=branch.specialHours?.find(entry=>entry.date===date);const clock=hours.clock??options.clock;const style={...hours,clock};return{status,today:special?special.closed||!special.opens||!special.closes?"":dayHours([{day,opens:special.opens,closes:special.closes}],day,style):dayHours(branch.openingTimes,day,style),week:openingHours(branch.openingTimes,{start:"today",...style,today:day})}}function useNow(every=MINUTE){const[now,setNow]=useState();useEffect(()=>{const tick=()=>setNow(new Date);const idle=typeof requestIdleCallback==="function"?requestIdleCallback(tick,{timeout:1500}):void 0;const soon=idle===void 0?setTimeout(tick,0):void 0;const timer=setInterval(tick,every);window.addEventListener("focus",tick);return()=>{if(idle!==void 0){cancelIdleCallback(idle)}clearTimeout(soon);clearInterval(timer);window.removeEventListener("focus",tick)}},[every]);return now}function useOpenStatus(branch,options={}){const now=useNow();return branch&&now?openStatus(branch,{...options,now}):void 0}function useBranchHours(branch,options={}){const now=useNow();return now?branchHours(branch,{...options,now}):void 0}export{DEFAULT_TIMEZONE,branchHours,branchTimezone,closedForOrders,describeOpening,formatClock,nextOpening,openStatus,openingHours,opensLabel,takesOrdersAhead,todayIn,useBranchHours,useNow,useOpenStatus};
|
|
2
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/hours/index.ts"],
|
|
4
|
+
"mappings": "AACA,OAAS,UAAW,aAA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appie/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.
|
|
1
|
+
var PACKAGE_VERSION=true?"0.20.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.
|
|
3
|
+
"version": "0.20.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,18 @@
|
|
|
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
|
+
},
|
|
28
|
+
"./hours": {
|
|
29
|
+
"types": "./dist/hours/index.d.ts",
|
|
30
|
+
"import": "./dist/hours/index.js"
|
|
31
|
+
},
|
|
20
32
|
"./schedule": {
|
|
21
33
|
"types": "./dist/schedule/index.d.ts",
|
|
22
34
|
"import": "./dist/schedule/index.js"
|