@zappie/foundations 0.28.1 → 0.28.4
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 +27 -0
- package/dist/account/index.js +0 -1
- package/dist/account/zappie-account.js +0 -1
- package/dist/attribution/powered-by-zappie.js +0 -1
- package/dist/bag/index.d.ts +4 -0
- package/dist/bag/index.js +0 -1
- package/dist/bag/param.js +0 -1
- package/dist/bag/server.js +0 -1
- package/dist/branch-finder/index.d.ts +2 -0
- package/dist/branch-finder/index.js +0 -1
- package/dist/branch-list/index.d.ts +4 -0
- package/dist/branch-list/index.js +0 -1
- package/dist/branch-list/nearest.js +0 -1
- package/dist/branch-list/offers.js +0 -1
- package/dist/branch-map/colors.js +0 -1
- package/dist/branch-map/delivery-map.js +0 -1
- package/dist/branch-map/delivery-runtime.js +0 -1
- package/dist/branch-map/fit.js +0 -1
- package/dist/branch-map/geometry.js +0 -1
- package/dist/branch-map/index.js +0 -1
- package/dist/branch-map/loader.js +0 -1
- package/dist/branch-map/markers.js +0 -1
- package/dist/branch-map/runtime.js +0 -1
- package/dist/branch-map/use-map-runtime.js +0 -1
- package/dist/branch-switch/index.d.ts +20 -0
- package/dist/branch-switch/index.js +0 -1
- package/dist/cart/index.js +0 -1
- package/dist/checkout/attempt.js +0 -1
- package/dist/checkout/contact.js +0 -1
- package/dist/checkout/index.d.ts +108 -22
- package/dist/checkout/index.js +0 -1
- package/dist/checkout/markers.js +0 -1
- package/dist/checkout/offers.js +0 -1
- package/dist/checkout/pay-after-sign-in.js +0 -1
- package/dist/checkout/sign-in.js +0 -1
- package/dist/checkout/status.js +0 -1
- package/dist/checkout/timing.js +0 -1
- package/dist/checkout/use-checkout-flow.js +1 -2
- package/dist/{core-Cd-_zlQx.d.ts → core-Dd6qKwNT.d.ts} +4 -0
- package/dist/{countries-BLeLfxnY.d.ts → countries-B4B4-e2j.d.ts} +9 -1
- package/dist/deferred/index.js +0 -1
- package/dist/deferred/retry.js +0 -1
- package/dist/fulfilment/address-picker.js +0 -1
- package/dist/fulfilment/branch-picker.js +0 -1
- package/dist/fulfilment/schedule.js +0 -1
- package/dist/fulfilment/switch.js +0 -1
- package/dist/fulfilment/window.js +1 -2
- package/dist/hours/index.d.ts +16 -0
- package/dist/hours/index.js +0 -1
- package/dist/{index-B1mCF3ft.d.ts → index-iwUrGm5U.d.ts} +3 -0
- package/dist/index.d.ts +82 -8
- package/dist/index.js +0 -1
- package/dist/internal/combobox.js +0 -1
- package/dist/internal/data-attrs.js +0 -1
- package/dist/internal/ids.js +0 -1
- package/dist/internal/labelled-control.js +0 -1
- package/dist/internal/slot.js +0 -1
- package/dist/internal/use-controllable-state.js +0 -1
- package/dist/item-form/index.js +0 -1
- package/dist/item-form/option-group.js +0 -1
- package/dist/item-form/options.js +0 -1
- package/dist/item-form/quantity.js +0 -1
- package/dist/item-form/root.js +0 -1
- package/dist/item-sheet/index.d.ts +1 -0
- package/dist/item-sheet/index.js +0 -1
- package/dist/loyalty/index.d.ts +4 -0
- package/dist/loyalty/index.js +0 -1
- package/dist/media/image.js +0 -1
- package/dist/money.js +0 -1
- package/dist/next.js +0 -1
- package/dist/{offers-fDZ0bZ0i.d.ts → offers-BVmFttDd.d.ts} +7 -1
- package/dist/order/index.d.ts +36 -1
- package/dist/order/index.js +0 -1
- package/dist/order/model.js +0 -1
- package/dist/order/use-customer-order.js +0 -1
- package/dist/otp/input.js +0 -1
- package/dist/overlay/deferred-host.js +0 -1
- package/dist/overlay/drag-to-close.js +0 -1
- package/dist/overlay/drag.js +0 -1
- package/dist/overlay/engine.js +0 -1
- package/dist/overlay/history.js +0 -1
- package/dist/overlay/load.js +0 -1
- package/dist/overlay/react.js +0 -1
- package/dist/payment/methods.js +0 -1
- package/dist/phone/combobox.js +0 -1
- package/dist/phone/core.js +0 -1
- package/dist/phone/countries.d.ts +1 -1
- package/dist/phone/countries.js +0 -1
- package/dist/phone/country-data.js +0 -1
- package/dist/phone/index.d.ts +5 -2
- package/dist/phone/index.js +0 -1
- package/dist/phone/load.js +0 -1
- package/dist/phone/picker.js +0 -1
- package/dist/phone/use-phone-field.js +0 -1
- package/dist/rich-text/banners.js +0 -1
- package/dist/rich-text/browser.js +0 -1
- package/dist/rich-text/core.js +0 -1
- package/dist/rich-text/index.d.ts +1 -1
- package/dist/rich-text/index.js +0 -1
- package/dist/rich-text/string.js +0 -1
- package/dist/schedule/index.d.ts +1 -1
- package/dist/schedule/index.js +0 -1
- package/dist/search/engine.js +0 -1
- package/dist/search/index.js +0 -1
- package/dist/site/at-table.js +0 -1
- package/dist/site/category-spy.js +0 -1
- package/dist/site/closed.js +0 -1
- package/dist/site/customer/checkout-return.js +0 -1
- package/dist/site/customer/gate.js +0 -1
- package/dist/site/customer/index.d.ts +9 -1
- package/dist/site/customer/index.js +0 -1
- package/dist/site/index.d.ts +1 -1
- package/dist/site/index.js +0 -1
- package/dist/site/page-views.js +0 -1
- package/dist/site/server/closed.js +0 -1
- package/dist/site/server/context.js +0 -1
- package/dist/site/server/document.js +0 -1
- package/dist/site/server/index.d.ts +12 -3
- package/dist/site/server/index.js +0 -1
- package/dist/site/title.js +0 -1
- package/dist/status/contact.js +0 -1
- package/dist/status/hours.js +1 -2
- package/dist/status/open-status.js +0 -1
- package/dist/{title-CgphFqNB.d.ts → title-uNmu5FUl.d.ts} +2 -0
- package/dist/version.js +1 -2
- package/dist/{window-BtvnXLww.d.ts → window-ClzBXJAe.d.ts} +6 -0
- package/package.json +4 -4
- package/dist/account/index.js.map +0 -6
- package/dist/account/zappie-account.js.map +0 -6
- package/dist/attribution/powered-by-zappie.js.map +0 -6
- package/dist/bag/index.js.map +0 -6
- package/dist/bag/param.js.map +0 -6
- package/dist/bag/server.js.map +0 -6
- package/dist/branch-finder/index.js.map +0 -6
- package/dist/branch-list/index.js.map +0 -6
- package/dist/branch-list/nearest.js.map +0 -6
- package/dist/branch-list/offers.js.map +0 -6
- package/dist/branch-map/colors.js.map +0 -6
- package/dist/branch-map/delivery-map.js.map +0 -6
- package/dist/branch-map/delivery-runtime.js.map +0 -6
- package/dist/branch-map/fit.js.map +0 -6
- package/dist/branch-map/geometry.js.map +0 -6
- package/dist/branch-map/index.js.map +0 -6
- package/dist/branch-map/loader.js.map +0 -6
- package/dist/branch-map/markers.js.map +0 -6
- package/dist/branch-map/runtime.js.map +0 -6
- package/dist/branch-map/use-map-runtime.js.map +0 -6
- package/dist/branch-switch/index.js.map +0 -6
- package/dist/cart/index.js.map +0 -6
- package/dist/checkout/attempt.js.map +0 -6
- package/dist/checkout/contact.js.map +0 -6
- package/dist/checkout/index.js.map +0 -6
- package/dist/checkout/markers.js.map +0 -6
- package/dist/checkout/offers.js.map +0 -6
- package/dist/checkout/pay-after-sign-in.js.map +0 -6
- package/dist/checkout/sign-in.js.map +0 -6
- package/dist/checkout/status.js.map +0 -6
- package/dist/checkout/timing.js.map +0 -6
- package/dist/checkout/use-checkout-flow.js.map +0 -6
- package/dist/deferred/index.js.map +0 -6
- package/dist/deferred/retry.js.map +0 -6
- package/dist/fulfilment/address-picker.js.map +0 -6
- package/dist/fulfilment/branch-picker.js.map +0 -6
- package/dist/fulfilment/schedule.js.map +0 -6
- package/dist/fulfilment/switch.js.map +0 -6
- package/dist/fulfilment/window.js.map +0 -6
- package/dist/hours/index.js.map +0 -6
- package/dist/index.js.map +0 -6
- package/dist/internal/combobox.js.map +0 -6
- package/dist/internal/data-attrs.js.map +0 -6
- package/dist/internal/ids.js.map +0 -6
- package/dist/internal/labelled-control.js.map +0 -6
- package/dist/internal/slot.js.map +0 -6
- package/dist/internal/use-controllable-state.js.map +0 -6
- package/dist/item-form/index.js.map +0 -6
- package/dist/item-form/option-group.js.map +0 -6
- package/dist/item-form/options.js.map +0 -6
- package/dist/item-form/quantity.js.map +0 -6
- package/dist/item-form/root.js.map +0 -6
- package/dist/item-sheet/index.js.map +0 -6
- package/dist/loyalty/index.js.map +0 -6
- package/dist/media/image.js.map +0 -6
- package/dist/money.js.map +0 -6
- package/dist/next.js.map +0 -6
- package/dist/order/index.js.map +0 -6
- package/dist/order/model.js.map +0 -6
- package/dist/order/use-customer-order.js.map +0 -6
- package/dist/otp/input.js.map +0 -6
- package/dist/overlay/deferred-host.js.map +0 -6
- package/dist/overlay/drag-to-close.js.map +0 -6
- package/dist/overlay/drag.js.map +0 -6
- package/dist/overlay/engine.js.map +0 -6
- package/dist/overlay/history.js.map +0 -6
- package/dist/overlay/load.js.map +0 -6
- package/dist/overlay/react.js.map +0 -6
- package/dist/payment/methods.js.map +0 -6
- package/dist/phone/combobox.js.map +0 -6
- package/dist/phone/core.js.map +0 -6
- package/dist/phone/countries.js.map +0 -6
- package/dist/phone/country-data.js.map +0 -6
- package/dist/phone/index.js.map +0 -6
- package/dist/phone/load.js.map +0 -6
- package/dist/phone/picker.js.map +0 -6
- package/dist/phone/use-phone-field.js.map +0 -6
- package/dist/rich-text/banners.js.map +0 -6
- package/dist/rich-text/browser.js.map +0 -6
- package/dist/rich-text/core.js.map +0 -6
- package/dist/rich-text/index.js.map +0 -6
- package/dist/rich-text/string.js.map +0 -6
- package/dist/schedule/index.js.map +0 -6
- package/dist/search/engine.js.map +0 -6
- package/dist/search/index.js.map +0 -6
- package/dist/site/at-table.js.map +0 -6
- package/dist/site/category-spy.js.map +0 -6
- package/dist/site/closed.js.map +0 -6
- package/dist/site/customer/checkout-return.js.map +0 -6
- package/dist/site/customer/gate.js.map +0 -6
- package/dist/site/customer/index.js.map +0 -6
- package/dist/site/index.js.map +0 -6
- package/dist/site/page-views.js.map +0 -6
- package/dist/site/server/closed.js.map +0 -6
- package/dist/site/server/context.js.map +0 -6
- package/dist/site/server/document.js.map +0 -6
- package/dist/site/server/index.js.map +0 -6
- package/dist/site/title.js.map +0 -6
- package/dist/status/contact.js.map +0 -6
- package/dist/status/hours.js.map +0 -6
- package/dist/status/open-status.js.map +0 -6
- package/dist/version.js.map +0 -6
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,32 @@
|
|
|
1
1
|
# @zappie/foundations
|
|
2
2
|
|
|
3
|
+
## 0.28.4
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- f9cc0ca: Ship no `.js.map` files. They held no source, so they only made the download bigger. Type declarations and their TSDoc still ship, so editor hovers are unchanged.
|
|
8
|
+
- 6c550cd: The quote now carries the API's `fill_field` fix as `{ action: "fill_field", field }`. `useCheckoutFlow`'s `fix` opens the contact step at that field, and the kit checkout page offers no button for it. A quote issue takes its option group from the API's `data.group_id` into `groupId`, so a problem the cart and the quote both report shows once. A quote whose checkout reason is newer than the SDK is read without that reason instead of failing. `WireIssue` loses `group_id`, which the API never sent.
|
|
9
|
+
- c7a941b: Document every member of the public types and the meaning of every value of their string unions.
|
|
10
|
+
- Updated dependencies [f9cc0ca]
|
|
11
|
+
- Updated dependencies [6c550cd]
|
|
12
|
+
- Updated dependencies [61d813f]
|
|
13
|
+
- Updated dependencies [c7a941b]
|
|
14
|
+
- @zappie/sdk@0.29.0
|
|
15
|
+
|
|
16
|
+
## 0.28.3
|
|
17
|
+
|
|
18
|
+
### Patch Changes
|
|
19
|
+
|
|
20
|
+
- 8f44616: The docs reference now carries each parameter's description, marks a parameter with a default as optional, and lists a string union's values with their meanings.
|
|
21
|
+
- Updated dependencies [8f44616]
|
|
22
|
+
- @zappie/sdk@0.28.2
|
|
23
|
+
|
|
24
|
+
## 0.28.2
|
|
25
|
+
|
|
26
|
+
### Patch Changes
|
|
27
|
+
|
|
28
|
+
- 2cf8cba: `canOrderAhead` is false for a branch with no opening day, whatever its order-ahead days, so a site offers no later slot the quote would refuse. The API reads a branch with no hours as closed.
|
|
29
|
+
|
|
3
30
|
## 0.28.1
|
|
4
31
|
|
|
5
32
|
### Patch Changes
|
package/dist/account/index.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
1
|
import{forwardRef}from"react";import{part}from"../internal/slot.js";var AccountNotConfiguredError=class extends Error{constructor(){super("Account authentication requires SDK auth (Open Storefronts PRD 13)");this.code="not_configured";this.name="AccountNotConfiguredError"}};async function signIn(_options){throw new AccountNotConfiguredError}async function signOut(_options){throw new AccountNotConfiguredError}var SignIn=/*@__PURE__ */forwardRef(function SignIn2(props,ref){return part("div",props,{signIn,status:"not_configured"},{"data-state":"invalid"},ref)});var SignOut=/*@__PURE__ */forwardRef(function SignOut2(props,ref){return part("div",props,{signOut,status:"not_configured"},{"data-state":"invalid"},ref)});var CustomerPart=/*@__PURE__ */forwardRef(function Customer(props,ref){return part("div",props,{customer:null,status:"not_configured"},{"data-state":"invalid"},ref)});var Account={SignIn,SignOut,Customer:CustomerPart};export{Account,AccountNotConfiguredError};
|
|
2
|
-
//# sourceMappingURL=index.js.map
|
|
@@ -1,2 +1 @@
|
|
|
1
1
|
import{accountsUrl}from"@zappie/sdk/account";import{forwardRef,useEffect,useState}from"react";import{part}from"../internal/slot.js";var LOOPBACK=new Set(["localhost","127.0.0.1","[::1]","::1"]);function zappieEnvironment(host){const name=host.trim().toLowerCase().replace(/\.$/,"");return LOOPBACK.has(name)||name.endsWith(".localhost")||name.endsWith(".workers.dev")||name.endsWith(".zappie-sites.dev")||name.includes(".stg.")?"staging":"production"}function zappieAccountUrl(page){const back=new URL(page);return accountsUrl("/account",zappieEnvironment(back.hostname),{returnTo:back})}function useZappieAccountUrl(returnTo){const[url,setUrl]=useState(()=>accountsUrl("/account"));useEffect(()=>{setUrl(zappieAccountUrl(new URL(returnTo??"",window.location.href)))},[returnTo]);return url}var ZappieAccountLink=/*@__PURE__ */forwardRef(function ZappieAccountLink2({returnTo,...props},ref){const href=useZappieAccountUrl(returnTo);return part("a",{...props,children:props.children??"Your Zappie account"},{href},{href,"data-zappie-account":""},ref)});export{ZappieAccountLink,useZappieAccountUrl,zappieAccountUrl,zappieEnvironment};
|
|
2
|
-
//# sourceMappingURL=zappie-account.js.map
|
|
@@ -1,2 +1 @@
|
|
|
1
1
|
import{jsx}from"react/jsx-runtime";var ZAPPIE_ATTRIBUTION_URL="https://zappie.ai";var ZAPPIE_ATTRIBUTION_TEXT="Powered by Zappie";function PoweredByZappie({style,...props}){const size=style?.fontSize??"1em";return jsx("a",{...props,style:{color:"inherit",...style,fontSize:`max(${typeof size=="number"?size+"px":size}, var(--z-text-sm, .875rem), 11px)`},href:ZAPPIE_ATTRIBUTION_URL,target:"_blank",rel:"noopener","data-zappie-attribution":"",children:ZAPPIE_ATTRIBUTION_TEXT})}export{PoweredByZappie,ZAPPIE_ATTRIBUTION_TEXT,ZAPPIE_ATTRIBUTION_URL};
|
|
2
|
-
//# sourceMappingURL=powered-by-zappie.js.map
|
package/dist/bag/index.d.ts
CHANGED
|
@@ -116,9 +116,13 @@ declare const Bag: {
|
|
|
116
116
|
};
|
|
117
117
|
/** A line just added, from `useAddToBag()`. `undo` takes it out again, or back to its quantity before. */
|
|
118
118
|
type AddedNotice = {
|
|
119
|
+
/** Always `added`. It tells this notice apart from a refusal in `CartNoticeValue`. */
|
|
119
120
|
kind: "added";
|
|
121
|
+
/** A number that rises with each notice, so the newer of an add and a refusal wins. */
|
|
120
122
|
id: number;
|
|
123
|
+
/** The cart line the add made or joined, as it stood just after the add. */
|
|
121
124
|
line: CartLine;
|
|
125
|
+
/** Takes the line out again, or puts it back to its quantity before the add, and clears the notice. */
|
|
122
126
|
undo: () => void;
|
|
123
127
|
};
|
|
124
128
|
/** What `CartNotice` shows: a change the server refused and the cart put back, or a line just added. */
|
package/dist/bag/index.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
1
|
"use client";import{useCart,useCartNotice,useZappie}from"@zappie/sdk/react";import{createContext,forwardRef,Fragment,useCallback,useContext,useEffect,useMemo,useRef,useState,useSyncExternalStore}from"react";import{useLocation,useNavigate}from"react-router";import{part}from"../internal/slot.js";import{DeferredHost,loadBody}from"../overlay/deferred-host.js";import{Overlay}from"../overlay/react.js";import{BAG_PARAM}from"./param.js";import{jsx,jsxs}from"react/jsx-runtime";var PAY_PARAM="zappie_pay";var MARK="__zappieBag";function hasBagParam(url){const query=typeof url==="string"?new URL(url===""||/^(\?|\/|[a-z][a-z\d+.-]*:)/i.test(url)?url:`?${url}`,"https://bag.invalid").searchParams:url instanceof URL?url.searchParams:url;return query.has(BAG_PARAM)}function revealBagColumn(id,query){const column=document.getElementById(id);if(!column||query&&!window.matchMedia(query).matches){return false}const box=column.getBoundingClientRect();if(box.top>=window.innerHeight||box.bottom<=0){column.scrollIntoView({block:"nearest",behavior:window.matchMedia("(prefers-reduced-motion: reduce)").matches?"auto":"smooth"})}return true}var Controls=/*@__PURE__ */createContext(null);var Open=/*@__PURE__ */createContext(false);function useShared(){const value=useContext(Controls);if(!value){throw new Error("Bag parts require Bag.Root")}return value}function useBag(){return useShared()}function useBagOpen(){return useContext(Open)}var ignore=()=>{};var marked=state=>!!state?.[MARK];function pageOf(href){const url=new URL(href,window.location.href);url.searchParams.delete(BAG_PARAM);return url.pathname+url.search}function write(push){const url=new URL(window.location.href);url.searchParams.set(BAG_PARAM,"open");const history=Object.getPrototypeOf(window.history);history[push?"pushState":"replaceState"].call(window.history,{...window.history.state,[MARK]:1},"",url.href)}function Root({body,preload=[],inline,children}){const[open,setOpen]=useState(false);const location=useLocation();const navigate=useNavigate();const opener=useRef(null);const latest=useRef({open,inline,location,preload,page:location.pathname,closing:[]});Object.assign(latest.current,{inline,location,preload});const controls=useMemo(()=>{const set=value=>{latest.current.open=value;setOpen(value)};const show=()=>{if(latest.current.open||latest.current.inline?.()){return}opener.current=document.activeElement instanceof HTMLElement?document.activeElement:null;set(true);write(true)};const close=()=>new Promise(resolve=>{if(latest.current.open){set(false)}if(marked(window.history.state)){latest.current.closing.push(resolve);window.history.back()}else{resolve()}});return{open:show,close,toggle:()=>{if(latest.current.open){void close()}else{show()}},preload:()=>{loadBody(body).catch(ignore);for(const part2 of latest.current.preload){part2.preload().catch(ignore)}},body,opener}},[body]);useEffect(()=>{const onPop=event=>{const{location:location2,open:open2,closing}=latest.current;const bag=marked(event.state)&&hasBagParam(window.location.href);if(pageOf(window.location.href)===pageOf(location2.pathname+location2.search)&&(bag||open2||closing.length>0)){event.stopImmediatePropagation();latest.current.open=bag;setOpen(bag);latest.current.closing=[];closing.forEach(resolve=>resolve())}};window.addEventListener("popstate",onPop,true);return()=>window.removeEventListener("popstate",onPop,true)},[]);useEffect(()=>{const state=latest.current;const query=new URLSearchParams(location.search);if(query.get(BAG_PARAM)!=="open"){if(state.page!==location.pathname&&state.open){state.open=false;setOpen(false)}state.page=location.pathname;return}state.page=location.pathname;const again=marked(window.history.state);query.delete(BAG_PARAM);query.delete(PAY_PARAM);const shown=!state.inline?.();state.open=shown;setOpen(shown);void Promise.resolve(navigate(location.pathname+(query.size?`?${query}`:"")+location.hash,{replace:true,preventScrollReset:true,state:location.state})).then(()=>{if(latest.current.open){write(!again)}})},[location.key]);useEffect(()=>{if(typeof window.requestIdleCallback==="function"){const handle2=window.requestIdleCallback(controls.preload);return()=>window.cancelIdleCallback(handle2)}const handle=window.setTimeout(controls.preload,1);return()=>window.clearTimeout(handle)},[controls]);return jsx(Controls.Provider,{value:controls,children:jsx(Open.Provider,{value:open,children})})}function Content({presentation="sheet",failed,...props}){const{body,close,opener,open:show,preload}=useShared();const open=useBagOpen();const cart=useCart();const lines=cart.isHydrated?cart.lines.length:void 0;const before=useRef(lines);useEffect(()=>{if(lines!==void 0&&(before.current??lines)<lines){preload()}before.current=lines},[lines,preload]);const navigation=useMemo(()=>({isOpen:open,open:show,close:()=>void close(),trigger:opener}),[open,show,close,opener]);return jsx(DeferredHost,{body,param:BAG_PARAM,id:"open",navigation,presentation,failed,props,children:jsx(body.Component,{open:true,close,empty:cart.isHydrated&&cart.lines.length===0})})}var Trigger=/*@__PURE__ */forwardRef(function Trigger2(props,ref){const bag=useShared();return part("button",props,bag,{type:"button","aria-haspopup":"dialog","aria-expanded":useBagOpen(),"data-zappie-overlay-trigger":"bag",onPointerEnter:bag.preload,onPointerDown:bag.preload,onFocus:bag.preload,onClick:bag.open},ref)});var Bag={Root,Content,Trigger,Title:Overlay.Title,Close:Overlay.Close};var stores=new WeakMap;function storeFor(cart){let store=stores.get(cart);if(!store){store={value:null,listeners:new Set};stores.set(cart,store)}return store}function put(store,value){store.value=value;store.listeners.forEach(listener=>listener())}var sequence=0;function useAddToBag(){const{cart}=useZappie();const{actions}=useCart();return useCallback((item,input,options)=>{const before=new Map(cart.lines.map(entry=>[entry.id,entry]));const line=actions.add(item,input,options);const was=before.get(line.id);const store=storeFor(cart);put(store,{kind:"added",id:++sequence,line,undo:()=>{if(was){actions.update(line.id,{quantity:was.quantity})}else{actions.remove(line.id)}put(store,null)}});return line},[cart,actions])}function useCartNoticeValue(){const{cart}=useZappie();const refused=useCartNotice();const store=storeFor(cart);const subscribe=useCallback(listener=>{store.listeners.add(listener);return()=>{store.listeners.delete(listener)}},[store]);const added=useSyncExternalStore(subscribe,()=>store.value,()=>null);const[seen,setSeen]=useState({at:0});if(refused.notice&&refused.notice.id!==seen.id){setSeen({id:refused.notice.id,at:++sequence})}const notice=refused.notice&&(!added||seen.at>added.id)?{kind:"refused",...refused.notice,id:seen.at}:added;const{dismiss:dismissRefused}=refused;const dismiss=useCallback(()=>{dismissRefused();put(store,null)},[dismissRefused,store]);return{notice,dismiss}}var HIDDEN={position:"absolute",width:1,height:1,overflow:"hidden",clipPath:"inset(50%)",whiteSpace:"nowrap"};function CartNotice({duration=6e3,announce=notice=>`${notice.line.name} added to your bag.`,className,children=notice=>notice.kind==="refused"?notice.message:null}){const{notice,dismiss}=useCartNoticeValue();const ref=useRef(null);const[held,setHeld]=useState(false);const id=notice?.id;useEffect(()=>{setHeld(false);const node=ref.current;if(id===void 0||!node){return}node.showPopover?.();const hold=()=>setHeld(true);const release=()=>setHeld(false);const onKey=event=>{if(event.key==="Escape"){dismiss()}};const listeners=[["pointerenter",hold],["pointerleave",release],["focusin",hold],["focusout",release],["keydown",onKey]];for(const[type,listener]of listeners){node.addEventListener(type,listener)}return()=>{for(const[type,listener]of listeners){node.removeEventListener(type,listener)}}},[id,dismiss]);useEffect(()=>{if(id===void 0||held){return}const timer=setTimeout(dismiss,duration);return()=>clearTimeout(timer)},[id,held,duration,dismiss]);const shown=notice?children(notice,dismiss):null;return jsxs(Fragment,{children:[jsx("p",{role:"status",style:HIDDEN,"data-zappie-cart-announcer":"",children:notice?.kind==="added"?announce(notice):""}),notice&&shown!=null&&shown!==false&&jsx("div",{ref,popover:"manual",className,"data-zappie-cart-notice":notice.kind==="refused"?notice.code:"added",children:shown},notice.id)]})}export{BAG_PARAM,Bag,CartNotice,PAY_PARAM,hasBagParam,revealBagColumn,useAddToBag,useBag,useBagOpen,useCartNoticeValue};
|
|
2
|
-
//# sourceMappingURL=index.js.map
|
package/dist/bag/param.js
CHANGED
package/dist/bag/server.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
1
|
import{safeRedirect}from"@zappie/sdk/redirect";import{BAG_PARAM}from"./param.js";function openBagAt(request,{to="/"}={}){const target=new URL(to,"https://bag.invalid");new URL(request.url).searchParams.forEach((value,key)=>target.searchParams.set(key,value));target.searchParams.set(BAG_PARAM,"open");return new Response(null,{status:302,headers:{Location:safeRedirect(target.pathname+target.search,`${target.pathname}?${BAG_PARAM}=open`),"X-Robots-Tag":"noindex"}})}export{openBagAt};
|
|
2
|
-
//# sourceMappingURL=server.js.map
|
|
@@ -8,7 +8,9 @@ import '@zappie/sdk';
|
|
|
8
8
|
|
|
9
9
|
/** What the site's finder receives: whether it is open, how to close it, and where the choice goes. */
|
|
10
10
|
type BranchFinderProps = {
|
|
11
|
+
/** Whether the finder is open. It stays mounted after it closes, so it can run its exit. */
|
|
11
12
|
open: boolean;
|
|
13
|
+
/** Closes the finder. */
|
|
12
14
|
onClose: () => void;
|
|
13
15
|
/** Where the shopper goes once they choose. Absent for the finder's default, such as the menu. */
|
|
14
16
|
then?: BranchDestination | undefined;
|
|
@@ -1,2 +1 @@
|
|
|
1
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
|
|
@@ -3,7 +3,9 @@ import { CheckoutMode } from '../checkout/index.js';
|
|
|
3
3
|
|
|
4
4
|
/** A point on the map, in degrees. */
|
|
5
5
|
type Coordinates = {
|
|
6
|
+
/** Latitude, in degrees. */
|
|
6
7
|
lat: number;
|
|
8
|
+
/** Longitude, in degrees. */
|
|
7
9
|
lng: number;
|
|
8
10
|
};
|
|
9
11
|
/**
|
|
@@ -58,7 +60,9 @@ declare function useHere(timeout?: number): Here;
|
|
|
58
60
|
|
|
59
61
|
/** What a branch sells: the names of its menus and the order types they take. */
|
|
60
62
|
type BranchOffer<T = CheckoutMode> = {
|
|
63
|
+
/** The names of the branch's menus that have at least one category. Empty when it has nothing to sell yet. */
|
|
61
64
|
menus: string[];
|
|
65
|
+
/** The order types those menus take, such as delivery, pickup and in venue. */
|
|
62
66
|
types: T[];
|
|
63
67
|
};
|
|
64
68
|
/** Settings for `useBranchOffers`. */
|
|
@@ -1,2 +1 @@
|
|
|
1
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
|
|
@@ -1,2 +1 @@
|
|
|
1
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
|
|
@@ -1,2 +1 @@
|
|
|
1
1
|
var DEFAULT_COLORS={accent:"#111111",accentForeground:"#ffffff"};var COLOR_PROBE_STYLE={color:"var(--map-accent, currentColor)",backgroundColor:"var(--map-accent-foreground, #ffffff)",borderColor:"var(--delivery-map-route, #163300)"};function readColors(probe){if(!probe||typeof getComputedStyle!=="function"){return DEFAULT_COLORS}const style=getComputedStyle(probe);return{accent:style.color||DEFAULT_COLORS.accent,accentForeground:style.backgroundColor||DEFAULT_COLORS.accentForeground,route:style.borderTopColor||void 0}}export{COLOR_PROBE_STYLE,DEFAULT_COLORS,readColors};
|
|
2
|
-
//# sourceMappingURL=colors.js.map
|
|
@@ -1,2 +1 @@
|
|
|
1
1
|
"use client";import{useEffect,useRef}from"react";import{COLOR_PROBE_STYLE,readColors}from"./colors.js";import{validCoordinates}from"./geometry.js";import{useMapRuntime}from"./use-map-runtime.js";import{jsx,jsxs}from"react/jsx-runtime";var loadDeliveryMap=(target,key,signal)=>import("./delivery-runtime.js").then(({createDeliveryMap})=>createDeliveryMap(target,key,signal));function DeliveryMap({branch,shopper,route,browserKey,pinImageUrl,onLoadError,renderLoadError,...props}){const probe=useRef(null);const origin=validCoordinates(branch.coordinates)?branch.coordinates:void 0;const destination=validCoordinates(shopper)?shopper:void 0;const mappable=!!origin&&!!destination;const{element,runtime,failure,retry}=useMapRuntime(browserKey,mappable,loadDeliveryMap,onLoadError);const failed=failure!==void 0;const coordinates=branch.coordinates;useEffect(()=>{if(runtime&&validCoordinates(coordinates)&&validCoordinates(shopper)){runtime.update({branch:coordinates,shopper,route,pinImageUrl,colors:readColors(probe.current)})}},[runtime,coordinates,shopper,route,pinImageUrl]);if(!browserKey){return null}return jsxs("div",{...props,"data-delivery-map":"",children:[jsx("span",{ref:probe,hidden:true,style:COLOR_PROBE_STYLE}),jsx("div",{hidden:failed||!mappable,ref:element,"data-delivery-map-canvas":"",style:{height:"100%"}}),failure&&renderLoadError?renderLoadError({error:failure.error,retry}):failed||!mappable?jsx("p",{role:"status",children:"Map location unavailable"}):null]})}export{DeliveryMap};
|
|
2
|
-
//# sourceMappingURL=delivery-map.js.map
|
|
@@ -1,2 +1 @@
|
|
|
1
1
|
import{pointBounds}from"./fit.js";import{loadMaps}from"./loader.js";import{DEFAULT_COLORS,markerOverlayClass,paintMarker}from"./markers.js";var DELIVERY_ROUTE={color:"#163300",opacity:.6,weight:5};var DELIVERY_LOGO_SIZE=36;function deliveryPath(update){const via=(update.route??[]).filter(point=>Number.isFinite(point.lat)&&Number.isFinite(point.lng));return via.length>=2?via:[update.branch,update.shopper]}function deliveryBounds(update){return pointBounds([update.branch,update.shopper,...deliveryPath(update)])}async function createDeliveryMap(element,key,signal){const maps=await loadMaps(key);signal.throwIfAborted();const map=new maps.Map(element,{center:{lat:0,lng:0},zoom:12,gestureHandling:"none",disableDefaultUI:true,keyboardShortcuts:false,clickableIcons:false});const Marker=markerOverlayClass(maps);let branchPin;let shopperPin;let line;let framed;let last;const pin=(key2,position)=>{const node=document.createElement("div");node.setAttribute("aria-hidden","true");node.dataset.deliveryMapPin=key2;const marker=new Marker(key2,position,node);marker.setMap(map);return marker};const frame=update=>{map.fitBounds(deliveryBounds(update))};const resize=typeof ResizeObserver==="function"?new ResizeObserver(()=>{if(last){frame(last)}}):void 0;resize?.observe(element);return{update(update){last=update;const colors=update.colors??DEFAULT_COLORS;branchPin??(branchPin=pin("branch",update.branch));branchPin.setPosition(update.branch);if(update.pinImageUrl){paintMarker(branchPin.element,{kind:"logo",size:DELIVERY_LOGO_SIZE,imageUrl:update.pinImageUrl,shadow:"sm",lift:DELIVERY_LOGO_SIZE/2},colors)}else{paintMarker(branchPin.element,{kind:"dot",selected:true},colors)}branchPin.element.style.cursor="default";shopperPin??(shopperPin=pin("shopper",update.shopper));shopperPin.setPosition(update.shopper);paintMarker(shopperPin.element,{kind:"house",color:"#ffffff",lift:16},colors);line??(line=new maps.Polyline({map}));line.setOptions({path:deliveryPath(update),strokeColor:update.colors?.route??DELIVERY_ROUTE.color,strokeOpacity:DELIVERY_ROUTE.opacity,strokeWeight:DELIVERY_ROUTE.weight,clickable:false});const key2=JSON.stringify(deliveryBounds(update));if(key2!==framed){framed=key2;frame(update)}},destroy(){resize?.disconnect();branchPin?.setMap(null);shopperPin?.setMap(null);line?.setMap(null);maps.event.clearInstanceListeners(map);element.replaceChildren()}}}export{DELIVERY_LOGO_SIZE,DELIVERY_ROUTE,createDeliveryMap,deliveryBounds,deliveryPath};
|
|
2
|
-
//# sourceMappingURL=delivery-runtime.js.map
|
package/dist/branch-map/fit.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
1
|
import{nearestBranch}from"@zappie/sdk/branches";import{validCoordinates,visibleBranches}from"./geometry.js";var OVERVIEW_PADDING=64;var ROUTE_PADDING={top:88,right:88,bottom:88,left:88};var COMPACT_ROUTE_PADDING={top:72,right:52,bottom:36,left:52};var SINGLE_POINT_ZOOM=14;var COMPACT_SINGLE_POINT_ZOOM=13;function focusedBranch(branches,selectedId,shopper){const visible=visibleBranches(branches);const selected=visible.find(branch=>branch.id===selectedId);if(selected||!validCoordinates(shopper)){return selected}const nearest=nearestBranch(visible,shopper);return nearest&&visible.find(branch=>branch.id===nearest.id)}function clusterSize(count){return count<10?40:count<50?48:56}function pointBounds(points){if(!points.length){return void 0}const wrapped=lng=>(lng+360)%360;const longitudes=points.map(point=>point.lng).sort((a,b)=>wrapped(a)-wrapped(b));let gap=-1;let start=0;for(let index=0;index<longitudes.length;index++){const next=wrapped(longitudes[(index+1)%longitudes.length])+(index===longitudes.length-1?360:0);if(next-wrapped(longitudes[index])>gap){gap=next-wrapped(longitudes[index]);start=(index+1)%longitudes.length}}return{north:Math.max(...points.map(point=>point.lat)),south:Math.min(...points.map(point=>point.lat)),west:longitudes[start],east:longitudes[(start+longitudes.length-1)%longitudes.length]}}function branchBounds(branches,location){const points=visibleBranches(branches).map(branch=>branch.coordinates);if(validCoordinates(location)){points.push(location)}return pointBounds(points)}function fitPlan({branches,shopper,focused,maxZoom,compact=false}){const location=validCoordinates(shopper)?shopper:void 0;const points=location&&focused?[location,focused.coordinates]:[...location?[location]:[],...visibleBranches(branches).map(branch=>branch.coordinates)];if(!points.length){return void 0}const route=!!(location&&focused);if(points.length===1){return{kind:"center",center:points[0],zoom:Math.min(maxZoom,compact?COMPACT_SINGLE_POINT_ZOOM:SINGLE_POINT_ZOOM)}}return{kind:"bounds",bounds:pointBounds(points),padding:route?compact?COMPACT_ROUTE_PADDING:ROUTE_PADDING:OVERVIEW_PADDING,maxZoom}}export{COMPACT_ROUTE_PADDING,COMPACT_SINGLE_POINT_ZOOM,OVERVIEW_PADDING,ROUTE_PADDING,SINGLE_POINT_ZOOM,branchBounds,clusterSize,fitPlan,focusedBranch,pointBounds};
|
|
2
|
-
//# sourceMappingURL=fit.js.map
|
package/dist/branch-map/index.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
1
|
"use client";import{useEffect,useRef}from"react";import{COLOR_PROBE_STYLE,readColors}from"./colors.js";import{validCoordinates,visibleBranches}from"./geometry.js";import{useMapRuntime}from"./use-map-runtime.js";import{DeliveryMap}from"./delivery-map.js";import{jsx,jsxs}from"react/jsx-runtime";var loadBranchMap=mapTypeControl=>(target,key,signal)=>import("./runtime.js").then(({createMap})=>createMap(target,key,signal,{mapTypeControl}));function BranchMap({branches,selectedBranchId,onSelect,shopperLocation,browserKey,maxZoom,pinImageUrl,mapTypeControl=false,pinLabel,compact=false,onLoadError,renderLoadError,...props}){const probe=useRef(null);const hasCoordinates=visibleBranches(branches).length>0;const{element,runtime,failure,retry}=useMapRuntime(browserKey,hasCoordinates,loadBranchMap(mapTypeControl),onLoadError);const failed=failure!==void 0;const effectiveMaxZoom=maxZoom??(validCoordinates(shopperLocation)?15:14);useEffect(()=>{runtime?.update(branches,selectedBranchId,onSelect,shopperLocation,{maxZoom:effectiveMaxZoom,pinImageUrl,mapTypeControl,pinLabel,compact,colors:readColors(probe.current)})},[runtime,branches,selectedBranchId,onSelect,shopperLocation,effectiveMaxZoom,pinImageUrl,mapTypeControl,pinLabel,compact]);if(!browserKey){return null}const unavailable=branches.filter(branch=>!visibleBranches([branch]).length);return jsxs("div",{...props,"data-branch-map":"",children:[jsx("span",{ref:probe,hidden:true,style:COLOR_PROBE_STYLE}),jsx("div",{hidden:failed||!hasCoordinates,ref:element,"data-branch-map-canvas":"",style:{height:"100%"}}),failure&&renderLoadError?renderLoadError({error:failure.error,retry}):failed||!hasCoordinates?jsx("p",{role:"status",children:"Map location unavailable"}):null,unavailable.map(branch=>jsxs("button",{type:"button","aria-pressed":branch.id===selectedBranchId,onClick:()=>onSelect(branch),children:[branch.name,": Map location unavailable"]},branch.id)),runtime&&validCoordinates(shopperLocation)?jsx("button",{type:"button",onClick:()=>runtime.locate(shopperLocation),children:"Use my current location"}):null]})}export{BranchMap,DeliveryMap};
|
|
2
|
-
//# sourceMappingURL=index.js.map
|
|
@@ -1,2 +1 @@
|
|
|
1
1
|
var pending;function loadMaps(key){if(globalThis.google?.maps?.Map){return Promise.resolve(google.maps)}if(pending){return pending}pending=new Promise((resolve,reject)=>{const script=document.createElement("script");const callback=`__zappieMaps${Date.now()}`;const scope=globalThis;const cleanup=()=>{clearTimeout(timeout);delete scope[callback]};const fail=()=>{cleanup();script.remove();pending=void 0;reject(new Error("Map location unavailable"))};const timeout=setTimeout(fail,15e3);scope[callback]=()=>{cleanup();resolve(google.maps)};script.async=true;script.src=`https://maps.googleapis.com/maps/api/js?${new URLSearchParams({key,loading:"async",callback,v:"weekly"})}`;script.onerror=fail;document.head.appendChild(script)});return pending}export{loadMaps};
|
|
2
|
-
//# sourceMappingURL=loader.js.map
|
|
@@ -1,2 +1 @@
|
|
|
1
1
|
var __typeError=msg=>{throw TypeError(msg)};var __accessCheck=(obj,member,msg)=>member.has(obj)||__typeError("Cannot "+msg);var __privateGet=(obj,member,getter)=>(__accessCheck(obj,member,"read from private field"),getter?getter.call(obj):member.get(obj));var __privateAdd=(obj,member,value)=>member.has(obj)?__typeError("Cannot add the same private member more than once"):member instanceof WeakSet?member.add(obj):member.set(obj,value);var __privateSet=(obj,member,value,setter)=>(__accessCheck(obj,member,"write to private field"),setter?setter.call(obj,value):member.set(obj,value),value);import{DEFAULT_COLORS}from"./colors.js";var SHADOW_SM="0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)";var SHADOW_MD="0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)";var MARKER_BOX=40;var LABEL_GAP=4;var LOGO_RADIUS="var(--branch-map-logo-radius,var(--z-radius-pill,9999px))";function branchMarker(imageUrl,focused){return imageUrl?{kind:"logo",size:focused?40:32,imageUrl,shadow:focused?"md":"sm"}:{kind:"dot",selected:focused}}var SVG_NAMESPACE="http://www.w3.org/2000/svg";function houseIcon(){const svg=document.createElementNS(SVG_NAMESPACE,"svg");for(const[name,value]of Object.entries({width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true"})){svg.setAttribute(name,value)}svg.style.display="block";for(const data of[["path","d","M15 22a1 1 0 0 1-1-1v-4a1 1 0 0 1 .445-.832l3-2a1 1 0 0 1 1.11 0l3 2A1 1 0 0 1 22 17v4a1 1 0 0 1-1 1z"],["path","d","M18 10a8 8 0 0 0-16 0c0 4.993 5.539 10.193 7.399 11.799a1 1 0 0 0 .601.2"],["path","d","M18 22v-3"],["circle","cx","10"]]){const child=document.createElementNS(SVG_NAMESPACE,data[0]);child.setAttribute(data[1],data[2]);if(data[0]==="circle"){child.setAttribute("cy","10");child.setAttribute("r","3")}svg.appendChild(child)}return svg}function paintMarker(element,spec,colors){const{left,top}=element.style;try{paint(element,spec,colors)}finally{element.style.left=left;element.style.top=top}}function paint(element,spec,colors){element.dataset.marker=spec.kind;if(spec.kind==="logo"){const lift=spec.lift??MARKER_BOX/2;element.style.cssText=`position:absolute;box-sizing:border-box;transform:translate(-50%,calc(-50% - ${lift}px));width:${spec.size}px;height:${spec.size}px;padding:0;border-radius:${LOGO_RADIUS};overflow:hidden;border:2px solid white;background:white;box-shadow:${spec.shadow==="md"?SHADOW_MD:SHADOW_SM};cursor:pointer;transition:width 150ms cubic-bezier(0.4,0,0.2,1),height 150ms cubic-bezier(0.4,0,0.2,1)`;let image=element.querySelector("img");if(!image){element.replaceChildren();image=document.createElement("img");image.alt="";image.decoding="async";image.draggable=false;image.onerror=()=>{image.style.visibility="hidden"};element.appendChild(image)}image.style.cssText=`display:block;width:100%;height:100%;border-radius:${LOGO_RADIUS};object-fit:cover`;if(image.getAttribute("src")!==spec.imageUrl){image.src=spec.imageUrl}return}if(spec.kind==="dot"){element.replaceChildren();element.style.cssText=`position:absolute;transform:translate(-50%,-100%);width:var(--branch-map-pin-size,24px);height:var(--branch-map-pin-size,24px);border-radius:var(--branch-map-pin-radius,var(--z-radius-pill,50%));border:2px solid var(--branch-map-pin-border,currentColor);background:var(${spec.selected?"--branch-map-pin-selected":"--branch-map-pin"},currentColor);cursor:pointer`;return}element.style.cssText=`position:absolute;box-sizing:border-box;transform:translate(-50%,calc(-50% - ${spec.lift??MARKER_BOX/2}px));width:32px;height:32px;padding:4px;border-radius:var(--branch-map-marker-radius,var(--z-radius-sm,4px));border:2px solid white;background:${colors.accent};color:${spec.color};box-shadow:${SHADOW_MD}`;if(!element.firstChild){element.appendChild(houseIcon())}}function paintLabel(element,options){const{left,top}=element.style;element.style.cssText=`position:absolute;box-sizing:border-box;transform:translate(-50%,calc(-100% - ${options.offset}));white-space:nowrap;pointer-events:none;padding:4px 8px;border-radius:var(--branch-map-label-radius,var(--z-radius-sm,8px));font-size:12px;line-height:16px;font-weight:500;${options.capitalize?"text-transform:capitalize;":""}background:var(--branch-map-label-background,white);color:var(--branch-map-label-color,#111);border:2px solid var(--branch-map-label-border,${options.colors.accent});box-shadow:${SHADOW_MD}`;element.style.left=left;element.style.top=top}function labelOffset(spec){return spec.kind==="dot"?`var(--branch-map-pin-size,24px) + ${LABEL_GAP}px`:`${MARKER_BOX+LABEL_GAP}px`}function markerOverlayClass(maps){var _position,_pane,_a;return _a=class extends maps.OverlayView{constructor(key,position,element){super();__privateAdd(this,_position);__privateAdd(this,_pane);this.key=key;this.element=element;__privateSet(this,_position,position);this.label=document.createElement("span");this.label.setAttribute("aria-hidden","true")}getPosition(){return new maps.LatLng(__privateGet(this,_position))}getVisible(){return true}setPosition(position){__privateSet(this,_position,position);if(this.getMap()){this.draw()}}setLabel(text){this.label.textContent=text??"";if(!text){this.label.remove()}else if(__privateGet(this,_pane)&&!this.label.isConnected){__privateGet(this,_pane).appendChild(this.label)}}onAdd(){__privateSet(this,_pane,this.getPanes()?.overlayMouseTarget);__privateGet(this,_pane)?.appendChild(this.element);if(this.label.textContent){__privateGet(this,_pane)?.appendChild(this.label)}maps.OverlayView.preventMapHitsAndGesturesFrom(this.element)}draw(){const point=this.getProjection()?.fromLatLngToDivPixel(new maps.LatLng(__privateGet(this,_position)));if(point){for(const node of[this.element,this.label]){node.style.left=`${point.x}px`;node.style.top=`${point.y}px`}}}onRemove(){__privateSet(this,_pane,void 0);this.element.remove();this.label.remove()}},_position=new WeakMap,_pane=new WeakMap,_a}export{DEFAULT_COLORS,branchMarker,labelOffset,markerOverlayClass,paintLabel,paintMarker};
|
|
2
|
-
//# sourceMappingURL=markers.js.map
|
|
@@ -1,2 +1 @@
|
|
|
1
1
|
import{MarkerClusterer}from"@googlemaps/markerclusterer";import{clusterSize,fitPlan,focusedBranch}from"./fit.js";import{validCoordinates,visibleBranches}from"./geometry.js";import{loadMaps}from"./loader.js";import{branchMarker,DEFAULT_COLORS,labelOffset,markerOverlayClass,paintLabel,paintMarker}from"./markers.js";var clusterable=marker=>marker;var ROUTE_OPACITY=.7;var ROUTE_WEIGHT=4;var CLUSTER_EXPAND_PADDING=56;var CLUSTER_EXPAND_MAX_ZOOM=21;var CLUSTER_EXPAND_MAX_ATTEMPTS=6;function clusterIcon(count,colors){const size=clusterSize(count);const svg=`<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 ${size} ${size}"><circle cx="${size/2}" cy="${size/2}" r="${size/2-3}" fill="${colors.accent}" stroke="#ffffff" stroke-width="3"/></svg>`;return{size,url:`data:image/svg+xml;base64,${btoa(svg)}`,label:{text:String(count),color:colors.accentForeground,fontSize:"13px",fontWeight:"600"}}}async function createMap(element,key,signal,options){const maps=await loadMaps(key);signal.throwIfAborted();const map=new maps.Map(element,{center:{lat:0,lng:0},zoom:12,mapTypeControl:options.mapTypeControl,streetViewControl:false});const Marker=markerOverlayClass(maps);const pins=new Map;let shopperPin;let route;let clusterer;let clusterColors;let clustered;let fitListener;let stopExpanding;let fitted;let lastSelected;let select=()=>{};const fit=plan=>{fitListener?.remove();fitListener=void 0;if(plan.kind==="center"){map.panTo(plan.center);map.setZoom(plan.zoom);return}map.fitBounds(plan.bounds,plan.padding);fitListener=maps.event.addListenerOnce(map,"idle",()=>{fitListener=void 0;const zoom=map.getZoom();if(typeof zoom==="number"&&zoom>plan.maxZoom){map.setZoom(plan.maxZoom)}})};const ensureClusterer=colors=>{const key2=`${colors.accent}|${colors.accentForeground}`;if(clusterer&&clusterColors===key2){return clusterer}clusterer?.clearMarkers(true);clusterer?.setMap(null);clusterColors=key2;clustered=void 0;clusterer=new MarkerClusterer({map,renderer:{render:({count,position})=>{const icon=clusterIcon(count,colors);return new maps.Marker({position,icon:{url:icon.url,scaledSize:new maps.Size(icon.size,icon.size)},label:icon.label,zIndex:999})}}});return clusterer};const expandTo=marker=>{stopExpanding?.();const active=clusterer;if(!active){return}let attempts=0;let cancelled=false;let idle;const expand=()=>{if(cancelled){return}active.render();const cluster=active.clusters?.find(candidate=>candidate.markers?.includes(clusterable(marker)));if(!cluster||cluster.count<=1){return}if(attempts===0&&cluster.bounds){map.fitBounds(cluster.bounds,CLUSTER_EXPAND_PADDING)}else{const zoom=map.getZoom();if(typeof zoom!=="number"||zoom>=CLUSTER_EXPAND_MAX_ZOOM){return}map.setZoom(Math.min(zoom+2,CLUSTER_EXPAND_MAX_ZOOM))}attempts+=1;if(attempts<CLUSTER_EXPAND_MAX_ATTEMPTS){idle=maps.event.addListenerOnce(map,"idle",expand)}};expand();stopExpanding=()=>{cancelled=true;idle?.remove();stopExpanding=void 0}};return{update(branches,selected,onSelect,location,options2){select=onSelect;const colors=options2?.colors??DEFAULT_COLORS;map.setOptions({mapTypeControl:options2?.mapTypeControl??false});const visible=visibleBranches(branches);const shopper=validCoordinates(location)?location:void 0;const focused=focusedBranch(visible,selected,shopper);for(const[id,pin]of pins){if(!visible.some(branch=>branch.id===id)){pin.marker.setMap(null);pins.delete(id)}}for(const branch of visible){let pin=pins.get(branch.id);if(!pin){const button2=document.createElement("button");button2.type="button";button2.dataset.branchMapPin="";const id=branch.id;button2.onclick=()=>{const current=pins.get(id);if(current){select(current.branch)}};pin={marker:new Marker(branch.id,branch.coordinates,button2),branch};pin.marker.label.dataset.branchMapPinLabel="";pins.set(branch.id,pin)}pin.branch=branch;pin.marker.setPosition(branch.coordinates);const isFocused=branch.id===focused?.id;const spec=branchMarker(options2?.pinImageUrl,isFocused);const button=pin.marker.element;button.setAttribute("aria-label",branch.name);button.setAttribute("aria-pressed",String(branch.id===selected));button.dataset.selected=String(branch.id===selected);button.dataset.focused=String(isFocused);paintMarker(button,spec,colors);const showLabel=options2?.pinLabel==="all"||options2?.pinLabel==="selected"&&isFocused;pin.marker.setLabel(showLabel?branch.name:void 0);pin.marker.label.dataset.selected=String(branch.id===selected);paintLabel(pin.marker.label,{offset:labelOffset(spec),capitalize:true,colors})}const active=ensureClusterer(colors);const markerSet=[...pins.keys()].join("\n");if(markerSet!==clustered){clustered=markerSet;active.clearMarkers(true);active.addMarkers([...pins.values()].map(({marker:marker2})=>clusterable(marker2)))}if(shopper){if(!shopperPin){const house=document.createElement("div");house.setAttribute("role","img");house.setAttribute("aria-label","Your location");house.dataset.branchMapShopper="";shopperPin=new Marker("shopper",shopper,house);shopperPin.setLabel("You");shopperPin.setMap(map)}shopperPin.setPosition(shopper);paintMarker(shopperPin.element,{kind:"house",color:colors.accentForeground},colors);paintLabel(shopperPin.label,{offset:labelOffset({kind:"house",color:""}),capitalize:false,colors})}else{shopperPin?.setMap(null);shopperPin=void 0}if(shopper&&focused){route??(route=new maps.Polyline({map}));route.setOptions({path:[shopper,focused.coordinates],strokeColor:colors.accent,strokeOpacity:ROUTE_OPACITY,strokeWeight:ROUTE_WEIGHT,clickable:false})}else{route?.setMap(null);route=void 0}const plan=fitPlan({branches:visible,shopper,focused,maxZoom:options2?.maxZoom??14,compact:options2?.compact??false});const frame=JSON.stringify(plan??null);const previous=lastSelected;lastSelected=selected;if(frame!==fitted){fitted=frame;if(plan){fit(plan)}}else{const target=visible.find(branch=>branch.id===selected);if(target&&selected!==previous&&!shopper&&!options2?.compact){map.panTo(target.coordinates)}}const marker=selected?pins.get(selected)?.marker:void 0;if(marker&&selected!==previous){expandTo(marker)}},locate(location){map.panTo(location)},destroy(){fitListener?.remove();stopExpanding?.();clusterer?.clearMarkers(true);clusterer?.setMap(null);for(const{marker}of pins.values()){marker.setMap(null);marker.element.onclick=null}pins.clear();shopperPin?.setMap(null);route?.setMap(null);maps.event.clearInstanceListeners(map);element.replaceChildren()}}}export{clusterIcon,createMap};
|
|
2
|
-
//# sourceMappingURL=runtime.js.map
|
|
@@ -1,2 +1 @@
|
|
|
1
1
|
import{useEffect,useRef,useState}from"react";function useMapRuntime(browserKey,enabled,load,onLoadError){const element=useRef(null);const[runtime,setRuntime]=useState();const[failure,setFailure]=useState();const[attempt,setAttempt]=useState(0);const loader=useRef(load);const reportError=useRef(onLoadError);useEffect(()=>{loader.current=load;reportError.current=onLoadError},[load,onLoadError]);useEffect(()=>{if(!browserKey||!element.current||!enabled){return}let disposed=false;const controller=new AbortController;let instance;const target=element.current;setFailure(void 0);void loader.current(target,browserKey,controller.signal).then(map=>{instance=map;if(disposed){map.destroy()}else{setRuntime(map)}}).catch(error=>{if(!disposed){setFailure({error});reportError.current?.(error)}});return()=>{disposed=true;controller.abort();instance?.destroy();setRuntime(void 0)}},[browserKey,enabled,attempt]);return{element,runtime,failure,retry:()=>setAttempt(count=>count+1)}}export{useMapRuntime};
|
|
2
|
-
//# sourceMappingURL=use-map-runtime.js.map
|
|
@@ -9,14 +9,20 @@ import 'react';
|
|
|
9
9
|
* counts as chosen.
|
|
10
10
|
*/
|
|
11
11
|
type BranchSwitchShop = {
|
|
12
|
+
/** The store, with its branches. A link's branch parameter is matched against them. */
|
|
12
13
|
store: Store;
|
|
14
|
+
/** The branch the shop was loaded for. Left out when the shop has no branch yet. */
|
|
13
15
|
branch?: Branch | undefined;
|
|
16
|
+
/** Whether the shopper chose the loaded branch. Left out, it counts as chosen. */
|
|
14
17
|
branchChosen?: boolean | undefined;
|
|
15
18
|
};
|
|
16
19
|
/** The branch a shop was loaded for, and whether the shopper chose it. */
|
|
17
20
|
type LoadedBranch = {
|
|
21
|
+
/** The loaded branch's ID. Left out when the shop has no branch. */
|
|
18
22
|
id?: string | undefined;
|
|
23
|
+
/** The loaded branch's slug. Left out when the shop has no branch. */
|
|
19
24
|
slug?: string | undefined;
|
|
25
|
+
/** Whether the shopper chose the branch. While false, a link to the same branch still reloads the shop. */
|
|
20
26
|
chosen: boolean;
|
|
21
27
|
};
|
|
22
28
|
/** Settings for `createBranchSwitchLoader`. */
|
|
@@ -38,14 +44,20 @@ type BranchSwitchOptions<T extends BranchSwitchShop> = {
|
|
|
38
44
|
};
|
|
39
45
|
/** The arguments React Router passes to `shouldRevalidate` that the branch switch reads. */
|
|
40
46
|
type BranchSwitchRevalidateArgs = {
|
|
47
|
+
/** The URL the shopper is on. */
|
|
41
48
|
currentUrl: URL;
|
|
49
|
+
/** The URL the shopper is moving to. */
|
|
42
50
|
nextUrl: URL;
|
|
51
|
+
/** The HTTP method of a form submission. Left out for a link. Any method but `GET` keeps React Router's rule. */
|
|
43
52
|
formMethod?: string | undefined;
|
|
53
|
+
/** What React Router would decide on its own. Returned as it is for a form submission that isn't `GET`. */
|
|
44
54
|
defaultShouldRevalidate: boolean;
|
|
45
55
|
};
|
|
46
56
|
/** The arguments React Router passes to a `clientLoader` that the branch switch reads. */
|
|
47
57
|
type BranchSwitchClientLoaderArgs<S> = {
|
|
58
|
+
/** The request for the page. Its URL names the branch, and its signal cancels the menu read. */
|
|
48
59
|
request: Request;
|
|
60
|
+
/** Runs the route's server loader. Called for any link that isn't to another branch, or when the menu read fails. */
|
|
49
61
|
serverLoader: () => Promise<S>;
|
|
50
62
|
};
|
|
51
63
|
/** The root route's `clientLoader` and `shouldRevalidate` for a fast branch switch. */
|
|
@@ -173,9 +185,13 @@ declare function atBranch(path: string, branch: string, param?: string): string;
|
|
|
173
185
|
* passes the item's path and the line chosen so far in `state`.
|
|
174
186
|
*/
|
|
175
187
|
type BranchDestination = {
|
|
188
|
+
/** The path to go to, such as `/menu`. The branch parameter is added to its query. */
|
|
176
189
|
path: string;
|
|
190
|
+
/** Router state to pass with the navigation, such as the line chosen so far. */
|
|
177
191
|
state?: unknown;
|
|
192
|
+
/** Replace the current history entry instead of adding one. Defaults to false. */
|
|
178
193
|
replace?: boolean;
|
|
194
|
+
/** Keep the scroll position instead of scrolling to the top. Defaults to false. */
|
|
179
195
|
preventScrollReset?: boolean;
|
|
180
196
|
};
|
|
181
197
|
/** Settings for `useBranchChoice`. */
|
|
@@ -226,9 +242,11 @@ declare function useRememberLinkedBranch(branch: Pick<Branch, "id" | "slug"> | u
|
|
|
226
242
|
}): void;
|
|
227
243
|
/** The router state `useReloadingBranch` reads: React Router's `useLocation()` and `useNavigation()`. */
|
|
228
244
|
type BranchSwitchRouterState = {
|
|
245
|
+
/** The current location, from `useLocation()`. Only its query is read. */
|
|
229
246
|
location: {
|
|
230
247
|
search: string;
|
|
231
248
|
};
|
|
249
|
+
/** The navigation in progress, from `useNavigation()`. A branch reloads only while `state` is `loading`. */
|
|
232
250
|
navigation: {
|
|
233
251
|
state: string;
|
|
234
252
|
location?: {
|
|
@@ -239,7 +257,9 @@ type BranchSwitchRouterState = {
|
|
|
239
257
|
};
|
|
240
258
|
/** A branch the shop is reloading for, and the path the shopper is moving to. */
|
|
241
259
|
type ReloadingBranch = {
|
|
260
|
+
/** The branch the link names. */
|
|
242
261
|
branch: Branch;
|
|
262
|
+
/** The path the shopper is moving to, without the query. */
|
|
243
263
|
pathname: string;
|
|
244
264
|
};
|
|
245
265
|
/**
|
|
@@ -1,2 +1 @@
|
|
|
1
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
|
-
//# sourceMappingURL=index.js.map
|
package/dist/cart/index.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
1
|
"use client";import{useCart,useCartCatalogue,useZappie}from"@zappie/sdk/react";import{createContext,forwardRef,useContext,useEffect,useState}from"react";import{part}from"../internal/slot.js";import{Quantity}from"../item-form/quantity.js";import{jsx}from"react/jsx-runtime";var Context=/*@__PURE__ */createContext(null);function useContextValue(){const value=useContext(Context);if(!value){throw new Error("Cart parts require Cart.Root")}return value}function Root(props){const state=useCart();return jsx(Context.Provider,{value:state,children:part("div",props,state,{"data-state":!state.isHydrated?"loading":state.issues.some(issue=>issue.severity==="blocking")?"invalid":"valid"})})}var Line=/*@__PURE__ */forwardRef(function Line2({line,...props},ref){const cart=useContextValue();const item=useCartCatalogue()?.items[line.itemId];const current=cart.lines.find(candidate=>candidate.id===line.id);if(!current){return null}const quote="quote"in cart.state?cart.state.quote:void 0;const total=quote?.lines.find(candidate=>candidate.lineId===line.id)?.total??null;const context={line:current,item,total,pending:!quote,edit:patch=>cart.actions.update(line.id,patch),remove:()=>cart.actions.remove(line.id)};return part("div",props,context,{"data-zappie-cart-line":line.id,"aria-busy":!quote||void 0,"data-invalid":cart.issues.some(issue=>issue.lineId===line.id&&issue.severity==="blocking")?"":void 0},ref)});function CartQuantity({lineId,...props}){const cart=useContextValue();const line=cart.lines.find(candidate=>candidate.id===lineId);const item=useCartCatalogue()?.items[line?.itemId??""];if(!line){return null}const step=item?.quantity.step??1;const min=Math.ceil((item?.quantity.min??1)/step)*step;return jsx(Quantity.Root,{...props,value:line.quantity,min,max:Math.min(item?.quantity.max??99,99),step,onValueChange:quantity=>cart.actions.update(lineId,{quantity})})}var Remove=/*@__PURE__ */forwardRef(function Remove2({lineId,...props},ref){const cart=useContextValue();return part("button",props,{},{type:"button",onClick:()=>cart.actions.remove(lineId)},ref)});var Empty=/*@__PURE__ */forwardRef(function Empty2(props,ref){const cart=useContextValue();return cart.isHydrated&&!cart.lines.length?part("div",props,{},{},ref):null});var Issues=/*@__PURE__ */forwardRef(function Issues2(props,ref){const cart=useContextValue();return part("div",props,{issues:cart.issues,applyFix:cart.actions.applyFix},{"aria-live":"polite","data-state":cart.issues.length?"invalid":"valid"},ref)});var Cart={Root,Line,Quantity:CartQuantity,Remove,Empty,Issues};var Totals=/*@__PURE__ */forwardRef(function Totals2(props,ref){const cart=useCart();const client=useZappie();const[failure,setFailure]=useState(null);const[expired,setExpired]=useState(false);const quote="quote"in cart.state?cart.state.quote:void 0;useEffect(()=>client.on("quote_failed",({code})=>setFailure(code==="network_error"||code==="timeout"?"offline":"stale")),[client]);useEffect(()=>{if(cart.state.status==="quoting"||quote){setFailure(null)}setExpired(Boolean(quote&&Date.parse(quote.expiresAt)<=Date.now()));if(!quote){return}const timeout=setTimeout(()=>setExpired(true),Math.max(0,Math.min(2147483647,Date.parse(quote.expiresAt)-Date.now())));return()=>clearTimeout(timeout)},[quote,cart.state.status]);const pending=cart.state.status==="ready"&&!quote&&cart.lines.length>0;const status=failure==="offline"?"offline":cart.state.status==="quoting"||!cart.isHydrated?"loading":failure==="stale"||expired?"stale":pending?"loading":!quote?"stale":"ready";return part("div",props,{quote,status},{"aria-live":"polite","aria-busy":status==="loading","data-state":status==="ready"?"valid":status==="offline"?"stale":status},ref)});export{Cart,Totals};
|
|
2
|
-
//# sourceMappingURL=index.js.map
|
package/dist/checkout/attempt.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
1
|
import{checkoutFulfilment}from"@zappie/sdk/checkout";function fulfilment(payload){const value=checkoutFulfilment(payload.fulfilment);if(value.type==="dine_in"){throw new Error("Checkout sessions don't take in-venue orders yet")}const scheduled=value.scheduled_for!==void 0?{scheduled_for:value.scheduled_for}:{};if(value.type==="pickup"){return{type:"pickup",...scheduled}}return{type:"delivery",...value.address!==void 0?{address:value.address}:{},...value.delivery_region_id!==void 0?{delivery_region_id:value.delivery_region_id}:{},...value.instructions!==void 0?{instructions:value.instructions}:{},...scheduled}}function createCheckoutAttempt(){let current;return input=>{const{payload,attribution}=input;const phone=input.contactPhone.trim().replace(/\s+/g,"");const name=input.contactName?.trim()??"";const digest=JSON.stringify({payload,phone,name});if(current?.digest===digest){return current.attempt}const request={branch_id:input.branchId,menu_version:payload.menu_version,lines:payload.lines,fulfilment:fulfilment(payload),...phone?{contact_phone:phone}:{},...name?{contact_name:name}:{},...payload.promo_code?{promo_code:payload.promo_code}:{},...payload.perk_redemption_ids?{perk_redemption_ids:payload.perk_redemption_ids}:{},...attribution.source?{source:attribution.source}:{},...attribution.campaign?{campaign:attribution.campaign}:{},return_url:input.returnUrl,cancel_url:input.cancelUrl};current={digest,attempt:{key:crypto.randomUUID(),request}};return current.attempt}}export{createCheckoutAttempt};
|
|
2
|
-
//# sourceMappingURL=attempt.js.map
|
package/dist/checkout/contact.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
1
|
import{isContactPhoneValid}from"@zappie/sdk/checkout";function fullPhone(typed,dialCode="+234"){const value=typed.trim().replace(/\s+/g,"");if(!value){return""}return value.startsWith("+")?value:`${dialCode}${value.replace(/^0/,"")}`}var emailPattern=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function contactProblems(fields,values,phone,accountPhone,dialCode="+234"){const problems={};if(!phone.trim()){if(!accountPhone){problems.phone="missing"}}else if(!isContactPhoneValid(fullPhone(phone,dialCode))){problems.phone="invalid"}for(const field of fields){const value=values[field.key]?.trim()??"";if(!value){if(field.required){problems[field.key]="missing"}}else if(field.type==="email"&&!emailPattern.test(value)||field.type==="tel"&&!isContactPhoneValid(value)){problems[field.key]="invalid"}}return problems}function recipientProblems(recipient,dialCode="+234"){const problems={};if(!recipient.on){return problems}const name=recipient.name.trim();if(!name){problems.recipient_name="missing"}else if(name.length>100){problems.recipient_name="invalid"}if(!recipient.phone.trim()){problems.recipient_phone="missing"}else if(!isContactPhoneValid(fullPhone(recipient.phone,dialCode))){problems.recipient_phone="invalid"}return problems}var BUILT_IN=["given_name","family_name","email"];function businessContactFields(fields,branchId,mode){if(mode!=="pickup"&&mode!=="delivery"){return[]}return(fields??[]).flatMap(field=>BUILT_IN.includes(field.key)&&field.appliesTo.fulfilment.includes(mode)&&(field.appliesTo.branchIds.length===0||field.appliesTo.branchIds.includes(branchId))?[{key:field.key,label:field.label,type:field.type==="email"?"email":"text",required:field.required}]:[])}function checkoutCustomer(fields,values){const customer={};for(const field of fields){const value=values[field.key]?.trim();if(value&&BUILT_IN.includes(field.key)){customer[field.key]=value}}return Object.keys(customer).length?customer:null}export{businessContactFields,checkoutCustomer,contactProblems,fullPhone,recipientProblems};
|
|
2
|
-
//# sourceMappingURL=contact.js.map
|