@zappie/foundations 0.28.4 → 0.29.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 +19 -0
- package/dist/branch-switch/index.d.ts +7 -2
- package/dist/branch-switch/index.js +1 -1
- package/dist/checkout/use-checkout-flow.js +1 -1
- package/dist/fulfilment/schedule.js +1 -1
- package/dist/internal/order-type.js +1 -0
- package/dist/search/index.js +1 -1
- package/dist/version.js +1 -1
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,24 @@
|
|
|
1
1
|
# @zappie/foundations
|
|
2
2
|
|
|
3
|
+
## 0.29.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- ecb9878: Search and Schedule read the menus of the bag's order type, so a pickup-only item is found and its menu's hours count on Pickup. `createBranchSwitchLoader` takes `fulfilment`, which names the order type to read another branch's menu for, as the root loader passes it to `loadStoreAndMenu`.
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- Updated dependencies [ecb9878]
|
|
12
|
+
- @zappie/sdk@0.30.0
|
|
13
|
+
|
|
14
|
+
## 0.28.5
|
|
15
|
+
|
|
16
|
+
### Patch Changes
|
|
17
|
+
|
|
18
|
+
- cf6e683: `useCheckoutFlow()` offers a switch of how the order comes only to modes the checkout offers. An issue's `switch_fulfilment` fix names only those modes, and goes when it names none, so a bag at a dine-in-only branch no longer offers a switch to delivery or pickup. `fix()` on such a switch returns nothing instead of choosing a mode the branch does not take.
|
|
19
|
+
- Updated dependencies [f089b13]
|
|
20
|
+
- @zappie/sdk@0.29.2
|
|
21
|
+
|
|
3
22
|
## 0.28.4
|
|
4
23
|
|
|
5
24
|
### Patch Changes
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Branch, Store, Zappie, Menu } from '@zappie/sdk';
|
|
1
|
+
import { Branch, Store, Zappie, Menu, MenuFulfilment } from '@zappie/sdk';
|
|
2
2
|
import { IntentPreloadHandlers } from '../index.js';
|
|
3
3
|
import 'react';
|
|
4
4
|
|
|
@@ -41,6 +41,11 @@ type BranchSwitchOptions<T extends BranchSwitchShop> = {
|
|
|
41
41
|
serverOnly?(url: URL, shop: T): boolean;
|
|
42
42
|
/** The query parameter that names a branch in a link. Defaults to `branch`. */
|
|
43
43
|
param?: string;
|
|
44
|
+
/**
|
|
45
|
+
* The order type to read the other branch's menu for, as your root loader passes it to
|
|
46
|
+
* `loadStoreAndMenu`. Each type has its own menus. Left out, the branch's default type.
|
|
47
|
+
*/
|
|
48
|
+
fulfilment?(url: URL, shop: T): MenuFulfilment | undefined;
|
|
44
49
|
};
|
|
45
50
|
/** The arguments React Router passes to `shouldRevalidate` that the branch switch reads. */
|
|
46
51
|
type BranchSwitchRevalidateArgs = {
|
|
@@ -124,7 +129,7 @@ declare function reloadsShop(current: URLSearchParams, next: URLSearchParams, lo
|
|
|
124
129
|
* export const shouldRevalidate: ShouldRevalidateFunction = (args) => branchSwitch.shouldRevalidate(args);
|
|
125
130
|
* export const clientLoader = (args: Route.ClientLoaderArgs) => branchSwitch.clientLoader(args);
|
|
126
131
|
*/
|
|
127
|
-
declare function createBranchSwitchLoader<T extends BranchSwitchShop>({ shopAt, serverOnly, param, }?: BranchSwitchOptions<T>): BranchSwitchLoader<T>;
|
|
132
|
+
declare function createBranchSwitchLoader<T extends BranchSwitchShop>({ shopAt, serverOnly, param, fulfilment, }?: BranchSwitchOptions<T>): BranchSwitchLoader<T>;
|
|
128
133
|
/**
|
|
129
134
|
* Pointer, touch and focus handlers that start reading a branch's menu when
|
|
130
135
|
* the shopper reaches for the control that chooses it. The client keeps one
|
|
@@ -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};
|
|
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",fulfilment}={}){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,fulfilment:fulfilment?.(url,current.shop),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};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use client";import{holdsForLater,isHeldQuote}from"@zappie/sdk";import{CheckoutError,createCheckout}from"@zappie/sdk/checkout";import{defaultRegion,prefillFulfilment,rememberAddress,rememberedAddress,watchCheckoutDefaults}from"@zappie/sdk/checkout-defaults";import{createCustomer}from"@zappie/sdk/customer";import{holdPerks}from"@zappie/sdk/loyalty";import{usePendingNavigation}from"@zappie/sdk/navigation/react";import{useCart}from"@zappie/sdk/react";import{redirectToCheckout}from"@zappie/sdk/redirect";import{countEvent,currentSource}from"@zappie/sdk/visits";import{useCallback,useEffect,useMemo,useRef,useState}from"react";import{createCheckoutAttempt}from"./attempt.js";import{businessContactFields,checkoutCustomer,contactProblems,fullPhone,recipientProblems}from"./contact.js";import{fieldSelector,issueSelector}from"./markers.js";import{checkoutOffers}from"./offers.js";import{cartIdentity,paymentNotice,payPath,takePaymentIntent}from"./pay-after-sign-in.js";import{signInOnce}from"./sign-in.js";import{checkoutStatus,firstIssue,isCheckoutFieldIssue,payEnabled}from"./status.js";import{checkoutTiming}from"./timing.js";function readSession(key){try{return window.sessionStorage.getItem(key)}catch{return null}}function writeSession(key,value){try{window.sessionStorage.setItem(key,value)}catch{}}function removeSession(key){try{window.sessionStorage.removeItem(key)}catch{}}var aborted=failure=>failure instanceof Error&&failure.name==="AbortError";var NO_FIELDS=[];var NO_VALUES={};var NO_RECIPIENT={on:false,name:"",phone:""};function profileValues(me){const values={};for(const[key,value]of[["given_name",me.given_name],["family_name",me.family_name],["email",me.email]]){if(value?.trim()){values[key]=value.trim()}}return values}var LISTED_BY_DEFAULT=["delivery","pickup"];var accountOf=person=>person?{name:person.given_name,phone:person.phone_masked}:void 0;function useCheckoutFlow(options){const{branch,menu,contactFields:givenFields=NO_FIELDS,reviewPath="/checkout",dialCode="+234",storageKey="zappie:checkout"}=options;const cart=useCart();const checkout=useMemo(()=>options.checkout??createCheckout(),[options.checkout]);const customer=useMemo(()=>options.customer??createCustomer(),[options.customer]);const owned=options.customer===void 0;const attempt=useMemo(()=>createCheckoutAttempt(),[]);const leaving=usePendingNavigation();const[auth,setAuth]=useState("unknown");const[who,setWho]=useState();const[account,setAccount]=useState();const[profile,setProfile]=useState();const[defaults,setDefaults]=useState();const[phone,setPhoneState]=useState("");const[values,setValues]=useState({});const[recipient,setRecipient]=useState(NO_RECIPIENT);const[shown,setShown]=useState(new Set);const[error,setError]=useState();const[signInRequired,setSignInRequired]=useState(false);const[leavingFor,setLeavingFor]=useState();const[failedKey,setFailedKey]=useState();const[notice,setNotice]=useState();const[defaultsFor,setDefaultsFor]=useState();const payKey=`${storageKey}.pay`;const paying=useRef(void 0);const payRead=useRef(false);useEffect(()=>{if(!payRead.current){payRead.current=true;paying.current=takePaymentIntent(payKey)}},[payKey]);const listed=options.offers??LISTED_BY_DEFAULT;const listedKey=listed.join();const offers=useMemo(()=>{const taken=checkoutOffers(branch,menu);return listed.filter(type=>taken.includes(type))},[branch,menu,listedKey]);const branchId=cart.branchId??branch.id;const fulfilment=cart.fulfilment;const[chosen,setChosen]=useState();const initial=options.initialMode&&offers.includes(options.initialMode)?options.initialMode:offers[0]??"pickup";const mode=chosen??(fulfilment&&offers.includes(fulfilment.type)?fulfilment.type:initial);const asking=options.checkoutFields!==void 0;const storeFieldsKey=asking?JSON.stringify(options.checkoutFields):"";const asked=useMemo(()=>asking?businessContactFields(options.checkoutFields,branchId,mode):givenFields,[asking,storeFieldsKey,branchId,mode,givenFields]);const holds=profile&&profile.of===who?profile.values:NO_VALUES;const held=asked.flatMap(field=>holds[field.key]?[{key:field.key,label:field.label,value:holds[field.key]}]:[]);const heldKey=held.map(entry=>entry.key).join();const contactFields=useMemo(()=>asked.filter(field=>!heldKey.split(",").includes(field.key)),[asked,heldKey]);const[pendingAt,setPendingAt]=useState();const delivery=mode==="delivery"&&fulfilment?.type==="delivery"?fulfilment:void 0;const scheduledFor=mode==="dine_in"?void 0:(fulfilment&&fulfilment.type!=="dine_in"&&fulfilment.type===mode?fulfilment.scheduledFor:void 0)??pendingAt;const latest=useRef(delivery);latest.current=delivery;useEffect(()=>{const ownerKey=`${storageKey}.owner`;const owner=readSession(ownerKey);if(owner&&owner!==who){if(who!==void 0){for(const key of[ownerKey,`${storageKey}.phone`,`${storageKey}.contact`,`${storageKey}.recipient`]){removeSession(key)}}setPhoneState("");setValues({});setRecipient(NO_RECIPIENT);return}if(who){writeSession(ownerKey,who)}setPhoneState(readSession(`${storageKey}.phone`)??"");try{setValues(JSON.parse(readSession(`${storageKey}.contact`)??"{}"))}catch{setValues({})}try{setRecipient({...NO_RECIPIENT,...JSON.parse(readSession(`${storageKey}.recipient`)??"{}")})}catch{setRecipient(NO_RECIPIENT)}},[storageKey,who]);const read=useRef({branch,fulfilment});read.current={branch,fulfilment};useEffect(()=>{const stopDefaults=watchCheckoutDefaults(customer,()=>read.current,next=>{setDefaults(next);setDefaultsFor(customer.state==="authenticated"?customer.customer?.id:customer.state==="anonymous"?null:void 0)});const stopAuth=customer.onChange((state,person)=>{setAuth(state);setAccount(state==="authenticated"?accountOf(person):void 0);setWho(state==="authenticated"?person?.id??void 0:state==="anonymous"?null:void 0)});void customer.session().then(current=>{setAuth(current?"authenticated":"anonymous");setAccount(accountOf(current));setWho(current?.id??null)},()=>{setAuth("anonymous");setAccount(void 0)});return()=>{stopDefaults();stopAuth();if(owned&&"dispose"in customer){customer.dispose()}}},[customer,owned]);const asksAny=asking&&asked.length>0;useEffect(()=>{if(!asksAny||!who){return}let current=true;customer.profile().then(me=>{if(current){setProfile({of:who,values:profileValues(me)})}},()=>void 0);return()=>{current=false}},[asksAny,who,customer]);useEffect(()=>{if(!cart.isHydrated||cart.lines.length===0||mode==="delivery"||fulfilment?.type===mode){return}cart.actions.setFulfilment(mode==="dine_in"?{type:"dine_in",branchId}:{type:"pickup",branchId,...pendingAt?{scheduledFor:pendingAt}:{}})},[branchId,cart.actions,cart.isHydrated,cart.lines.length,fulfilment?.type,mode,pendingAt]);const pendingDelivery=mode==="delivery"&&fulfilment?.type!=="delivery";useEffect(()=>{cart.actions.setPendingFulfilment(pendingDelivery?{type:"delivery",scheduledFor:pendingAt}:null)},[cart.actions,pendingDelivery,pendingAt]);const awaiting=useRef(false);const writeDelivery=useCallback((patch,at=scheduledFor)=>{const current=latest.current;const address=patch.address??current?.address;if(!address?.line1){return false}const regionId=defaultRegion(branch,patch.deliveryRegionId??current?.deliveryRegionId);const next={type:"delivery",branchId,address,...regionId?{deliveryRegionId:regionId}:{},...at?{scheduledFor:at}:{}};latest.current=next;awaiting.current=false;setChosen("delivery");cart.actions.setFulfilment(next);return true},[branch,branchId,cart.actions,scheduledFor]);const prefilled=useRef(void 0);useEffect(()=>{if(!cart.isHydrated||cart.lines.length===0){return}const filled=prefillFulfilment(fulfilment,branch);if(filled&&filled!==fulfilment){cart.actions.setFulfilment(filled);return}if(awaiting.current&&who!==void 0&&mode==="delivery"&&fulfilment?.type!=="delivery"){const known=rememberedAddress({customerId:who})??defaults?.address;if(known){writeDelivery({address:known})}return}const address=defaults?.address;if(mode==="delivery"&&!fulfilment&&address&&prefilled.current!==address){prefilled.current=address;writeDelivery({address})}},[branch,cart.actions,cart.isHydrated,cart.lines.length,defaults?.address,fulfilment,mode,who,writeDelivery]);const quoteKey=JSON.stringify([cart.lines,fulfilment,cart.promoCode]);const quoted=useRef("");useEffect(()=>{if(cart.isHydrated&&cart.lines.length>0&&cart.state.status==="ready"&"ed.current!==quoteKey){quoted.current=quoteKey;void cart.actions.quote().then(()=>{setFailedKey(void 0);setError(current=>current==="quote_failed"?void 0:current)},failure=>{if(!aborted(failure)){setFailedKey(quoteKey);setError("quote_failed")}})}},[cart.actions,cart.isHydrated,cart.lines.length,cart.state.status,quoteKey]);const timing=checkoutTiming(branch,menu,cart.lines,scheduledFor);const quote="quote"in cart.state?cart.state.quote:void 0;const heldQuote=isHeldQuote(quote);const unquotedTime=Boolean(scheduledFor)&&!quote?.fulfilment?.scheduledFor;const issues=useMemo(()=>{const cartIssues=cart.issues.filter(issue2=>!isCheckoutFieldIssue(issue2));return timing.ahead?unquotedTime?cartIssues.filter(issue2=>!holdsForLater(issue2)):cartIssues:cartIssues.map(issue2=>holdsForLater(issue2)?{...issue2,fixes:issue2.fixes.filter(entry=>entry.action!=="schedule")}:issue2)},[cart.issues,timing.ahead,unquotedTime]);const accountPhone=defaults?.phone.fromAccount?defaults.phone.display:void 0;const forOther=mode!=="dine_in"&&recipient.on;const problems=contactProblems(contactFields,values,phone,accountPhone,dialCode);if(forOther){delete problems.phone;Object.assign(problems,recipientProblems(recipient,dialCode))}const quotedField=cart.issues.map(issue2=>isCheckoutFieldIssue(issue2)?issue2.data?.field:void 0).find(field=>typeof field==="string");const contactField=Object.keys(problems)[0]??quotedField;const sending=asking?checkoutCustomer(contactFields,values):null;const sendingKey=JSON.stringify(sending);useEffect(()=>{if(asking){cart.actions.setCustomer(sending)}},[asking,sendingKey,cart.actions]);const contactPhone=forOther?fullPhone(recipient.phone,dialCode):phone.trim()?fullPhone(phone,dialCode):"";const status=checkoutStatus({busy:leaving.pending,hydrated:cart.isHydrated,lines:cart.lines.length,auth,closed:timing.closed,needsAddress:mode==="delivery"&&!delivery?.address.line1,needsTime:mode!=="dine_in"&&timing.needsTime,state:cart.state,quoteFailed:failedKey===quoteKey,signInRequired,contactField});const shopper=()=>customer.state==="authenticated"?customer.customer?.id??void 0:customer.state==="anonymous"?null:void 0;const choose=type=>{setChosen(type);awaiting.current=false;if(type==="delivery"&&fulfilment?.type!=="delivery"){setPendingAt(scheduledFor);const owner=shopper();const known=(owner===void 0?void 0:rememberedAddress({customerId:owner}))??defaults?.address;if(known){writeDelivery({address:known},scheduledFor);return void 0}awaiting.current=true;return{step:"address"}}return void 0};const setDelivery=(change,{remember=true}={})=>{const base=change.address??latest.current?.address;if(!base?.line1){return{step:"address"}}const typed=change.note??change.address?.instructions??latest.current?.address.instructions;const{instructions:_old,...rest}=base;const note=typed?.trim();writeDelivery({address:note?{...rest,instructions:note}:rest,...change.regionId!==void 0?{deliveryRegionId:change.regionId}:{}});const owner=shopper();if(change.address&&remember&&owner!==void 0){rememberAddress(change.address,void 0,owner)}return void 0};const setAddress=(address,options2={})=>{setDelivery({address},options2)};const setRegion=regionId=>latest.current?setDelivery({regionId}):{step:"address"};const setNote=note=>latest.current?setDelivery({note}):{step:"address"};const schedule=at=>{setPendingAt(at??void 0);if(!fulfilment||fulfilment.type==="dine_in"||fulfilment.type!==mode){return}const{scheduledFor:_old,...rest}=fulfilment;cart.actions.setFulfilment(at?{...rest,scheduledFor:at}:rest)};const fix=(issue2,action)=>{setError(void 0);switch(action.action){case"change_address":return{step:"address"};case"choose_region":return{step:"area"};case"schedule":return{step:"time"};case"fill_field":setShown(current=>new Set([...current,action.field]));return{step:"contact",field:action.field,target:fieldSelector(action.field)};case"switch_fulfilment":{const next=action.types.find(type=>type!==mode&&offers.includes(type))??(mode==="delivery"?"pickup":"delivery");return choose(next)}case"choose_option":case"choose_other_option":{const line=cart.lines.find(entry=>entry.id===issue2.lineId);return line?{step:"item",itemId:line.itemId,lineId:line.id}:void 0}default:cart.actions.applyFix(cart.issues.find(entry=>entry.code===issue2.code&&entry.lineId===issue2.lineId&&entry.message===issue2.message)??issue2,action);return void 0}};const signIn=options.signIn??signInOnce;const leaveToSignIn=()=>{setLeavingFor("sign_in");if(quote){writeSession(payKey,JSON.stringify({at:Date.now(),cart:cartIdentity(branchId,cart.lines,cart.promoCode),total:quote.total}))}if(!signIn(payPath(reviewPath))){removeSession(payKey);leaving.end();setError("sign_in_failed")}};const keepRecipient=change=>setRecipient(current=>{const next={...current,...change};writeSession(`${storageKey}.recipient`,JSON.stringify(next));return next});const redirect=options.redirect??(url=>redirectToCheckout(url,window.top??window));const attribution=options.attribution??currentSource;const openPayment=async()=>{setLeavingFor("payment");try{const prepared=attempt({payload:cart.actions.toCheckoutPayload(),branchId,contactPhone,contactName:forOther?recipient.name:"",returnUrl:`${location.origin}/checkout/return`,cancelUrl:`${location.origin}${reviewPath}`,attribution:attribution()});const session=await checkout.open(prepared.request,prepared.key);holdPerks(prepared.request.perk_redemption_ids,session);redirect(session.url)}catch(failure){if(failure instanceof CheckoutError&&failure.apiCode==="customer_required"){setSignInRequired(true);leaveToSignIn();return}leaving.end();if(failure instanceof CheckoutError&&failure.apiCode==="quote_issues"&&failure.param?.startsWith("customer.")){const key=failure.param.slice("customer.".length);setShown(current=>new Set([...current,key]));void cart.actions.quote({force:true}).catch(()=>void 0);return}setError("open_failed")}};const retry=async()=>{setFailedKey(void 0);try{await cart.actions.quote({force:true});setError(void 0)}catch(failure){if(!aborted(failure)){setFailedKey(quoteKey);setError("quote_failed")}}};const issue=status==="fix_issues"?firstIssue(cart.state):void 0;const activate=async()=>{setError(void 0);setNotice(void 0);switch(status){case"address":return{step:"address"};case"area":return{step:"area"};case"time":return{step:"time"};case"fix_issues":{const target=issue??issues[0];return target?{step:"issue",issue:target,target:issueSelector(target)}:void 0}case"phone":case"contact":setShown(current=>new Set([...current,...Object.keys(problems)]));return contactField?{step:"contact",field:contactField,target:fieldSelector(contactField)}:void 0;case"retry":await retry();return void 0;case"sign_in":countEvent("checkout");await leaving.start(leaveToSignIn);return void 0;case"pay":countEvent("checkout");await leaving.start(openPayment);return void 0;default:return void 0}};useEffect(()=>{const intent=paying.current;if(!intent||auth==="unknown"){return}if(auth==="authenticated"&&status!=="empty"&&(defaultsFor!==who||cart.state.status==="ready"||status==="checking"||status==="quoting"||status==="busy")){return}paying.current=void 0;if(auth==="anonymous"){return}const found=paymentNotice(intent,{cart:cartIdentity(branchId,cart.lines,cart.promoCode),total:quote?.total,status,issues});if(found){setNotice(found);return}countEvent("checkout");void leaving.start(openPayment)});return{mode,offers,choose,delivery,setDelivery,setAddress,setRegion,setNote,scheduledFor,schedule,timing,contact:{phone,contactPhone,setPhone:value=>{setPhoneState(value);writeSession(`${storageKey}.phone`,value)},accountPhone,fields:contactFields,held,values,setField:(key,value)=>{setValues(current=>{const next={...current,[key]:value};writeSession(`${storageKey}.contact`,JSON.stringify(next));return next})},recipient:mode==="dine_in"?void 0:{label:mode==="pickup"?"Collected by":"Deliver to",...recipient,setOn:on=>keepRecipient({on}),setName:name=>keepRecipient({name}),setPhone:value=>keepRecipient({phone:value})},problems,shown,show:key=>setShown(current=>current.has(key)?current:new Set([...current,key]))},auth,account,quote,pricing:cart.state.status==="quoting",held:heldQuote?timing.ahead?"time":"opening":void 0,issues,fix,error,clearError:()=>setError(void 0),notice,clearNotice:()=>setNotice(void 0),pay:{status,enabled:payEnabled(status),leavingFor:status==="busy"?leavingFor:void 0,issue,field:status==="phone"||status==="contact"?contactField:void 0,activate}}}export{useCheckoutFlow};
|
|
1
|
+
"use client";import{holdsForLater,isHeldQuote}from"@zappie/sdk";import{CheckoutError,createCheckout}from"@zappie/sdk/checkout";import{defaultRegion,prefillFulfilment,rememberAddress,rememberedAddress,watchCheckoutDefaults}from"@zappie/sdk/checkout-defaults";import{createCustomer}from"@zappie/sdk/customer";import{holdPerks}from"@zappie/sdk/loyalty";import{usePendingNavigation}from"@zappie/sdk/navigation/react";import{useCart}from"@zappie/sdk/react";import{redirectToCheckout}from"@zappie/sdk/redirect";import{countEvent,currentSource}from"@zappie/sdk/visits";import{useCallback,useEffect,useMemo,useRef,useState}from"react";import{createCheckoutAttempt}from"./attempt.js";import{businessContactFields,checkoutCustomer,contactProblems,fullPhone,recipientProblems}from"./contact.js";import{fieldSelector,issueSelector}from"./markers.js";import{checkoutOffers}from"./offers.js";import{cartIdentity,paymentNotice,payPath,takePaymentIntent}from"./pay-after-sign-in.js";import{signInOnce}from"./sign-in.js";import{checkoutStatus,firstIssue,isCheckoutFieldIssue,payEnabled}from"./status.js";import{checkoutTiming}from"./timing.js";function readSession(key){try{return window.sessionStorage.getItem(key)}catch{return null}}function writeSession(key,value){try{window.sessionStorage.setItem(key,value)}catch{}}function removeSession(key){try{window.sessionStorage.removeItem(key)}catch{}}var aborted=failure=>failure instanceof Error&&failure.name==="AbortError";var NO_FIELDS=[];var NO_VALUES={};var NO_RECIPIENT={on:false,name:"",phone:""};function profileValues(me){const values={};for(const[key,value]of[["given_name",me.given_name],["family_name",me.family_name],["email",me.email]]){if(value?.trim()){values[key]=value.trim()}}return values}var LISTED_BY_DEFAULT=["delivery","pickup"];var switchable=(types,mode,offers)=>types.filter(type=>type!==mode&&offers.includes(type));function offeredSwitches(issue,mode,offers){let changed=false;const fixes=issue.fixes.flatMap(entry=>{if(entry.action!=="switch_fulfilment"){return[entry]}const types=switchable(entry.types,mode,offers);if(types.length===entry.types.length){return[entry]}changed=true;return types.length?[{...entry,types}]:[]});return changed?{...issue,fixes}:issue}var accountOf=person=>person?{name:person.given_name,phone:person.phone_masked}:void 0;function useCheckoutFlow(options){const{branch,menu,contactFields:givenFields=NO_FIELDS,reviewPath="/checkout",dialCode="+234",storageKey="zappie:checkout"}=options;const cart=useCart();const checkout=useMemo(()=>options.checkout??createCheckout(),[options.checkout]);const customer=useMemo(()=>options.customer??createCustomer(),[options.customer]);const owned=options.customer===void 0;const attempt=useMemo(()=>createCheckoutAttempt(),[]);const leaving=usePendingNavigation();const[auth,setAuth]=useState("unknown");const[who,setWho]=useState();const[account,setAccount]=useState();const[profile,setProfile]=useState();const[defaults,setDefaults]=useState();const[phone,setPhoneState]=useState("");const[values,setValues]=useState({});const[recipient,setRecipient]=useState(NO_RECIPIENT);const[shown,setShown]=useState(new Set);const[error,setError]=useState();const[signInRequired,setSignInRequired]=useState(false);const[leavingFor,setLeavingFor]=useState();const[failedKey,setFailedKey]=useState();const[notice,setNotice]=useState();const[defaultsFor,setDefaultsFor]=useState();const payKey=`${storageKey}.pay`;const paying=useRef(void 0);const payRead=useRef(false);useEffect(()=>{if(!payRead.current){payRead.current=true;paying.current=takePaymentIntent(payKey)}},[payKey]);const listed=options.offers??LISTED_BY_DEFAULT;const listedKey=listed.join();const offers=useMemo(()=>{const taken=checkoutOffers(branch,menu);return listed.filter(type=>taken.includes(type))},[branch,menu,listedKey]);const branchId=cart.branchId??branch.id;const fulfilment=cart.fulfilment;const[chosen,setChosen]=useState();const initial=options.initialMode&&offers.includes(options.initialMode)?options.initialMode:offers[0]??"pickup";const mode=chosen??(fulfilment&&offers.includes(fulfilment.type)?fulfilment.type:initial);const asking=options.checkoutFields!==void 0;const storeFieldsKey=asking?JSON.stringify(options.checkoutFields):"";const asked=useMemo(()=>asking?businessContactFields(options.checkoutFields,branchId,mode):givenFields,[asking,storeFieldsKey,branchId,mode,givenFields]);const holds=profile&&profile.of===who?profile.values:NO_VALUES;const held=asked.flatMap(field=>holds[field.key]?[{key:field.key,label:field.label,value:holds[field.key]}]:[]);const heldKey=held.map(entry=>entry.key).join();const contactFields=useMemo(()=>asked.filter(field=>!heldKey.split(",").includes(field.key)),[asked,heldKey]);const[pendingAt,setPendingAt]=useState();const delivery=mode==="delivery"&&fulfilment?.type==="delivery"?fulfilment:void 0;const scheduledFor=mode==="dine_in"?void 0:(fulfilment&&fulfilment.type!=="dine_in"&&fulfilment.type===mode?fulfilment.scheduledFor:void 0)??pendingAt;const latest=useRef(delivery);latest.current=delivery;useEffect(()=>{const ownerKey=`${storageKey}.owner`;const owner=readSession(ownerKey);if(owner&&owner!==who){if(who!==void 0){for(const key of[ownerKey,`${storageKey}.phone`,`${storageKey}.contact`,`${storageKey}.recipient`]){removeSession(key)}}setPhoneState("");setValues({});setRecipient(NO_RECIPIENT);return}if(who){writeSession(ownerKey,who)}setPhoneState(readSession(`${storageKey}.phone`)??"");try{setValues(JSON.parse(readSession(`${storageKey}.contact`)??"{}"))}catch{setValues({})}try{setRecipient({...NO_RECIPIENT,...JSON.parse(readSession(`${storageKey}.recipient`)??"{}")})}catch{setRecipient(NO_RECIPIENT)}},[storageKey,who]);const read=useRef({branch,fulfilment});read.current={branch,fulfilment};useEffect(()=>{const stopDefaults=watchCheckoutDefaults(customer,()=>read.current,next=>{setDefaults(next);setDefaultsFor(customer.state==="authenticated"?customer.customer?.id:customer.state==="anonymous"?null:void 0)});const stopAuth=customer.onChange((state,person)=>{setAuth(state);setAccount(state==="authenticated"?accountOf(person):void 0);setWho(state==="authenticated"?person?.id??void 0:state==="anonymous"?null:void 0)});void customer.session().then(current=>{setAuth(current?"authenticated":"anonymous");setAccount(accountOf(current));setWho(current?.id??null)},()=>{setAuth("anonymous");setAccount(void 0)});return()=>{stopDefaults();stopAuth();if(owned&&"dispose"in customer){customer.dispose()}}},[customer,owned]);const asksAny=asking&&asked.length>0;useEffect(()=>{if(!asksAny||!who){return}let current=true;customer.profile().then(me=>{if(current){setProfile({of:who,values:profileValues(me)})}},()=>void 0);return()=>{current=false}},[asksAny,who,customer]);useEffect(()=>{if(!cart.isHydrated||cart.lines.length===0||mode==="delivery"||fulfilment?.type===mode){return}cart.actions.setFulfilment(mode==="dine_in"?{type:"dine_in",branchId}:{type:"pickup",branchId,...pendingAt?{scheduledFor:pendingAt}:{}})},[branchId,cart.actions,cart.isHydrated,cart.lines.length,fulfilment?.type,mode,pendingAt]);const pendingDelivery=mode==="delivery"&&fulfilment?.type!=="delivery";useEffect(()=>{cart.actions.setPendingFulfilment(pendingDelivery?{type:"delivery",scheduledFor:pendingAt}:null)},[cart.actions,pendingDelivery,pendingAt]);const awaiting=useRef(false);const writeDelivery=useCallback((patch,at=scheduledFor)=>{const current=latest.current;const address=patch.address??current?.address;if(!address?.line1){return false}const regionId=defaultRegion(branch,patch.deliveryRegionId??current?.deliveryRegionId);const next={type:"delivery",branchId,address,...regionId?{deliveryRegionId:regionId}:{},...at?{scheduledFor:at}:{}};latest.current=next;awaiting.current=false;setChosen("delivery");cart.actions.setFulfilment(next);return true},[branch,branchId,cart.actions,scheduledFor]);const prefilled=useRef(void 0);useEffect(()=>{if(!cart.isHydrated||cart.lines.length===0){return}const filled=prefillFulfilment(fulfilment,branch);if(filled&&filled!==fulfilment){cart.actions.setFulfilment(filled);return}if(awaiting.current&&who!==void 0&&mode==="delivery"&&fulfilment?.type!=="delivery"){const known=rememberedAddress({customerId:who})??defaults?.address;if(known){writeDelivery({address:known})}return}const address=defaults?.address;if(mode==="delivery"&&!fulfilment&&address&&prefilled.current!==address){prefilled.current=address;writeDelivery({address})}},[branch,cart.actions,cart.isHydrated,cart.lines.length,defaults?.address,fulfilment,mode,who,writeDelivery]);const quoteKey=JSON.stringify([cart.lines,fulfilment,cart.promoCode]);const quoted=useRef("");useEffect(()=>{if(cart.isHydrated&&cart.lines.length>0&&cart.state.status==="ready"&"ed.current!==quoteKey){quoted.current=quoteKey;void cart.actions.quote().then(()=>{setFailedKey(void 0);setError(current=>current==="quote_failed"?void 0:current)},failure=>{if(!aborted(failure)){setFailedKey(quoteKey);setError("quote_failed")}})}},[cart.actions,cart.isHydrated,cart.lines.length,cart.state.status,quoteKey]);const timing=checkoutTiming(branch,menu,cart.lines,scheduledFor);const quote="quote"in cart.state?cart.state.quote:void 0;const heldQuote=isHeldQuote(quote);const unquotedTime=Boolean(scheduledFor)&&!quote?.fulfilment?.scheduledFor;const offersKey=offers.join();const issues=useMemo(()=>{const cartIssues=cart.issues.filter(issue2=>!isCheckoutFieldIssue(issue2)).map(issue2=>offeredSwitches(issue2,mode,offers));return timing.ahead?unquotedTime?cartIssues.filter(issue2=>!holdsForLater(issue2)):cartIssues:cartIssues.map(issue2=>holdsForLater(issue2)?{...issue2,fixes:issue2.fixes.filter(entry=>entry.action!=="schedule")}:issue2)},[cart.issues,timing.ahead,unquotedTime,mode,offersKey]);const accountPhone=defaults?.phone.fromAccount?defaults.phone.display:void 0;const forOther=mode!=="dine_in"&&recipient.on;const problems=contactProblems(contactFields,values,phone,accountPhone,dialCode);if(forOther){delete problems.phone;Object.assign(problems,recipientProblems(recipient,dialCode))}const quotedField=cart.issues.map(issue2=>isCheckoutFieldIssue(issue2)?issue2.data?.field:void 0).find(field=>typeof field==="string");const contactField=Object.keys(problems)[0]??quotedField;const sending=asking?checkoutCustomer(contactFields,values):null;const sendingKey=JSON.stringify(sending);useEffect(()=>{if(asking){cart.actions.setCustomer(sending)}},[asking,sendingKey,cart.actions]);const contactPhone=forOther?fullPhone(recipient.phone,dialCode):phone.trim()?fullPhone(phone,dialCode):"";const status=checkoutStatus({busy:leaving.pending,hydrated:cart.isHydrated,lines:cart.lines.length,auth,closed:timing.closed,needsAddress:mode==="delivery"&&!delivery?.address.line1,needsTime:mode!=="dine_in"&&timing.needsTime,state:cart.state,quoteFailed:failedKey===quoteKey,signInRequired,contactField});const shopper=()=>customer.state==="authenticated"?customer.customer?.id??void 0:customer.state==="anonymous"?null:void 0;const choose=type=>{setChosen(type);awaiting.current=false;if(type==="delivery"&&fulfilment?.type!=="delivery"){setPendingAt(scheduledFor);const owner=shopper();const known=(owner===void 0?void 0:rememberedAddress({customerId:owner}))??defaults?.address;if(known){writeDelivery({address:known},scheduledFor);return void 0}awaiting.current=true;return{step:"address"}}return void 0};const setDelivery=(change,{remember=true}={})=>{const base=change.address??latest.current?.address;if(!base?.line1){return{step:"address"}}const typed=change.note??change.address?.instructions??latest.current?.address.instructions;const{instructions:_old,...rest}=base;const note=typed?.trim();writeDelivery({address:note?{...rest,instructions:note}:rest,...change.regionId!==void 0?{deliveryRegionId:change.regionId}:{}});const owner=shopper();if(change.address&&remember&&owner!==void 0){rememberAddress(change.address,void 0,owner)}return void 0};const setAddress=(address,options2={})=>{setDelivery({address},options2)};const setRegion=regionId=>latest.current?setDelivery({regionId}):{step:"address"};const setNote=note=>latest.current?setDelivery({note}):{step:"address"};const schedule=at=>{setPendingAt(at??void 0);if(!fulfilment||fulfilment.type==="dine_in"||fulfilment.type!==mode){return}const{scheduledFor:_old,...rest}=fulfilment;cart.actions.setFulfilment(at?{...rest,scheduledFor:at}:rest)};const fix=(issue2,action)=>{setError(void 0);switch(action.action){case"change_address":return{step:"address"};case"choose_region":return{step:"area"};case"schedule":return{step:"time"};case"fill_field":setShown(current=>new Set([...current,action.field]));return{step:"contact",field:action.field,target:fieldSelector(action.field)};case"switch_fulfilment":{const next=switchable(action.types,mode,offers)[0];return next?choose(next):void 0}case"choose_option":case"choose_other_option":{const line=cart.lines.find(entry=>entry.id===issue2.lineId);return line?{step:"item",itemId:line.itemId,lineId:line.id}:void 0}default:cart.actions.applyFix(cart.issues.find(entry=>entry.code===issue2.code&&entry.lineId===issue2.lineId&&entry.message===issue2.message)??issue2,action);return void 0}};const signIn=options.signIn??signInOnce;const leaveToSignIn=()=>{setLeavingFor("sign_in");if(quote){writeSession(payKey,JSON.stringify({at:Date.now(),cart:cartIdentity(branchId,cart.lines,cart.promoCode),total:quote.total}))}if(!signIn(payPath(reviewPath))){removeSession(payKey);leaving.end();setError("sign_in_failed")}};const keepRecipient=change=>setRecipient(current=>{const next={...current,...change};writeSession(`${storageKey}.recipient`,JSON.stringify(next));return next});const redirect=options.redirect??(url=>redirectToCheckout(url,window.top??window));const attribution=options.attribution??currentSource;const openPayment=async()=>{setLeavingFor("payment");try{const prepared=attempt({payload:cart.actions.toCheckoutPayload(),branchId,contactPhone,contactName:forOther?recipient.name:"",returnUrl:`${location.origin}/checkout/return`,cancelUrl:`${location.origin}${reviewPath}`,attribution:attribution()});const session=await checkout.open(prepared.request,prepared.key);holdPerks(prepared.request.perk_redemption_ids,session);redirect(session.url)}catch(failure){if(failure instanceof CheckoutError&&failure.apiCode==="customer_required"){setSignInRequired(true);leaveToSignIn();return}leaving.end();if(failure instanceof CheckoutError&&failure.apiCode==="quote_issues"&&failure.param?.startsWith("customer.")){const key=failure.param.slice("customer.".length);setShown(current=>new Set([...current,key]));void cart.actions.quote({force:true}).catch(()=>void 0);return}setError("open_failed")}};const retry=async()=>{setFailedKey(void 0);try{await cart.actions.quote({force:true});setError(void 0)}catch(failure){if(!aborted(failure)){setFailedKey(quoteKey);setError("quote_failed")}}};const issue=status==="fix_issues"?firstIssue(cart.state):void 0;const activate=async()=>{setError(void 0);setNotice(void 0);switch(status){case"address":return{step:"address"};case"area":return{step:"area"};case"time":return{step:"time"};case"fix_issues":{const target=issue??issues[0];return target?{step:"issue",issue:target,target:issueSelector(target)}:void 0}case"phone":case"contact":setShown(current=>new Set([...current,...Object.keys(problems)]));return contactField?{step:"contact",field:contactField,target:fieldSelector(contactField)}:void 0;case"retry":await retry();return void 0;case"sign_in":countEvent("checkout");await leaving.start(leaveToSignIn);return void 0;case"pay":countEvent("checkout");await leaving.start(openPayment);return void 0;default:return void 0}};useEffect(()=>{const intent=paying.current;if(!intent||auth==="unknown"){return}if(auth==="authenticated"&&status!=="empty"&&(defaultsFor!==who||cart.state.status==="ready"||status==="checking"||status==="quoting"||status==="busy")){return}paying.current=void 0;if(auth==="anonymous"){return}const found=paymentNotice(intent,{cart:cartIdentity(branchId,cart.lines,cart.promoCode),total:quote?.total,status,issues});if(found){setNotice(found);return}countEvent("checkout");void leaving.start(openPayment)});return{mode,offers,choose,delivery,setDelivery,setAddress,setRegion,setNote,scheduledFor,schedule,timing,contact:{phone,contactPhone,setPhone:value=>{setPhoneState(value);writeSession(`${storageKey}.phone`,value)},accountPhone,fields:contactFields,held,values,setField:(key,value)=>{setValues(current=>{const next={...current,[key]:value};writeSession(`${storageKey}.contact`,JSON.stringify(next));return next})},recipient:mode==="dine_in"?void 0:{label:mode==="pickup"?"Collected by":"Deliver to",...recipient,setOn:on=>keepRecipient({on}),setName:name=>keepRecipient({name}),setPhone:value=>keepRecipient({phone:value})},problems,shown,show:key=>setShown(current=>current.has(key)?current:new Set([...current,key]))},auth,account,quote,pricing:cart.state.status==="quoting",held:heldQuote?timing.ahead?"time":"opening":void 0,issues,fix,error,clearError:()=>setError(void 0),notice,clearNotice:()=>setNotice(void 0),pay:{status,enabled:payEnabled(status),leavingFor:status==="busy"?leavingFor:void 0,issue,field:status==="phone"||status==="contact"?contactField:void 0,activate}}}export{useCheckoutFlow};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use client";import{useCart,useMenu,useStore,useZappie}from"@zappie/sdk/react";import{forwardRef,useEffect,useMemo,useState}from"react";import{part}from"../internal/slot.js";import{useControllableState}from"../internal/use-controllable-state.js";var windowModule;var windowLoad;var loadRules=()=>windowLoad??(windowLoad=import("./window.js").catch(()=>import("./window.js")).then(module=>windowModule=module).catch(error=>{windowLoad=void 0;throw error}));var Schedule=/*@__PURE__ */forwardRef(function Schedule2({branch,timezone:suppliedTimezone,value,defaultValue=null,onValueChange,intervalMinutes,maxDays,noticeMinutes,menuIds,...props},ref){const client=useZappie();const store=useStore();const menu=useMenu(branch.id,{metadataOnly:true});const
|
|
1
|
+
"use client";import{useCart,useMenu,useStore,useZappie}from"@zappie/sdk/react";import{forwardRef,useEffect,useMemo,useState}from"react";import{bagOrderType}from"../internal/order-type.js";import{part}from"../internal/slot.js";import{useControllableState}from"../internal/use-controllable-state.js";var windowModule;var windowLoad;var loadRules=()=>windowLoad??(windowLoad=import("./window.js").catch(()=>import("./window.js")).then(module=>windowModule=module).catch(error=>{windowLoad=void 0;throw error}));var Schedule=/*@__PURE__ */forwardRef(function Schedule2({branch,timezone:suppliedTimezone,value,defaultValue=null,onValueChange,intervalMinutes,maxDays,noticeMinutes,menuIds,...props},ref){const client=useZappie();const store=useStore();const cart=useCart();const fulfilment=bagOrderType(cart.fulfilment);const menu=useMenu(branch.id,{metadataOnly:true,fulfilment});const ids=(menuIds??cart.lines.map(line=>line.menuId)).join(" ");const[retrying,setRetrying]=useState(false);const[rules,setRules]=useState(windowModule);const[failed,setFailed]=useState(false);useEffect(()=>{if(!rules){loadRules().then(setRules,()=>setFailed(true))}},[]);const menuFailed=!menu.data&&menu.error!==void 0;const status=menu.isLoading||retrying||!rules&&!failed?"loading":menuFailed||failed?"error":"ready";const ready=status==="ready";const timezone=suppliedTimezone??branch.timezone??store.data?.timezone??"UTC";const[now,setNow]=useState(()=>new Date);useEffect(()=>{const timer=setTimeout(()=>setNow(new Date),6e4-Date.now()%6e4);return()=>clearTimeout(timer)},[now]);const[selection,setSelection]=useControllableState({value,defaultValue,onChange:onValueChange});const result=useMemo(()=>rules?.bagWindow(branch,timezone,now,menu.data,ids,{intervalMinutes,maxDays,noticeMinutes}),[rules,branch,timezone,now,menu.data,ids,intervalMinutes,maxDays,noticeMinutes]);const slots=ready&&result?.slots||[];const days=Array.from(new Set(slots.map(slot=>slot.date))).map(date=>({date,slots:slots.filter(slot=>slot.date===date)}));const canAsap=ready&&result.canAsap;const isClosed=ready&&!canAsap&&slots.length===0;const isValid=selection===null?canAsap:slots.some(slot=>slot.value===selection);const retry=()=>{if(failed){location.reload();return}if(retrying||!menuFailed){return}setRetrying(true);void client.menu.get({branch:branch.id,metadataOnly:true,fulfilment}).catch(()=>{}).finally(()=>setRetrying(false))};const setValue=next=>{if(next===null?canAsap:slots.some(slot=>slot.value===next)){setSelection(next)}};return part("div",props,{status,retry,isClosed,blocker:isClosed?result.why():void 0,days,slots,value:selection,setValue,isAsap:selection===null,canAsap,isValid},{role:"group","aria-busy":status==="loading"?true:void 0,"data-status":status,"data-state":isValid?"valid":"invalid","data-invalid":isValid||!ready?void 0:""},ref)});export{Schedule};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var bagOrderType=fulfilment=>fulfilment?.type==="dine_in"?"dineIn":fulfilment?.type;export{bagOrderType};
|
package/dist/search/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use client";import{useCart,useMenu,useZappie}from"@zappie/sdk/react";import{createContext,forwardRef,useContext,useEffect,useMemo}from"react";import{countAnnouncement,useCombobox,withLiveRegion}from"../internal/combobox.js";import{composeRefs,part}from"../internal/slot.js";import{useControllableState}from"../internal/use-controllable-state.js";import{createSearchIndex}from"./engine.js";import{createSearchIndex as createSearchIndex2}from"./engine.js";import{jsx}from"react/jsx-runtime";var Context=/*@__PURE__ */createContext(null);function useSearch(){const ctx=useContext(Context);if(!ctx){throw new Error("Search parts require Search.Root")}return ctx}function Root(props){if(props.source){return jsx(ControlledRoot,{...props,source:props.source})}return jsx(UncontrolledRoot,{...props})}function UncontrolledRoot(props){const cart=useCart();const menu=useMenu(cart.branchId??void 0);const[query,setQuery]=useControllableState({value:props.query,defaultValue:props.defaultQuery??"",onChange:props.onQueryChange});const index=useMemo(()=>menu.data?createSearchIndex(menu.data):()=>[],[menu.data]);const results=useMemo(()=>index(query),[index,query]);return jsx(ControlledRoot,{...props,query,onQueryChange:setQuery,source:{results,isLoading:menu.isLoading,isStale:menu.isStale}})}function ControlledRoot({query,defaultQuery="",onQueryChange,onSelect=()=>{},announcement=countAnnouncement,source,...props}){const client=useZappie();const[value,setValue]=useControllableState({value:query,defaultValue:defaultQuery,onChange:onQueryChange});const results=source.results;const combo=useCombobox(results,onSelect);const setQuery=next=>{setValue(next);combo.setActiveIndex(-1);combo.setOpen(true)};useEffect(()=>{if(!value.trim()){return}const timer=setTimeout(()=>client._internal.emit("search",{query:value,resultCount:results.length}),600);return()=>clearTimeout(timer)},[client,value,results.length]);const state={...combo,query:value,setQuery,results,setComposing:value2=>source.onCompositionChange?.(value2),...source.error?{error:source.error}:{},...source.retry?{retry:source.retry}:{}};return jsx(Context.Provider,{value:state,children:part("div",withLiveRegion(props,combo.isOpen&&value.trim()?announcement(results.length):""),state,{"data-state":source.error?"error":source.isLoading?"loading":source.isStale?"stale":"valid",onBlur:event=>{if(!event.currentTarget.contains(event.relatedTarget)){combo.setOpen(false)}}})})}var Input=/*@__PURE__ */forwardRef(function Input2(props,ref){const state=useSearch();return part("input",props,state,{...state.inputProps,type:"search",onCompositionStart:()=>state.setComposing(true),onCompositionEnd:()=>state.setComposing(false),value:state.query,onChange:event=>state.setQuery(event.target.value)},ref)});var Results=/*@__PURE__ */forwardRef(function Results2(props,ref){const state=useSearch();return part("div",props,state,state.listProps,composeRefs(ref,node=>{if(node?.id&&node.id!==state.listProps.id){state.setListId(node.id)}}))});var Result=/*@__PURE__ */forwardRef(function Result2({index,...props},ref){const state=useSearch();return part("div",props,state,state.getOptionProps(index),composeRefs(ref,node=>{if(node?.id&&node.id!==state.getOptionProps(index).id){state.registerOption(index,node.id)}}))});var Search={Root,Input,Results,Result};export{Search,createSearchIndex2 as createSearchIndex};
|
|
1
|
+
"use client";import{useCart,useMenu,useZappie}from"@zappie/sdk/react";import{createContext,forwardRef,useContext,useEffect,useMemo}from"react";import{countAnnouncement,useCombobox,withLiveRegion}from"../internal/combobox.js";import{bagOrderType}from"../internal/order-type.js";import{composeRefs,part}from"../internal/slot.js";import{useControllableState}from"../internal/use-controllable-state.js";import{createSearchIndex}from"./engine.js";import{createSearchIndex as createSearchIndex2}from"./engine.js";import{jsx}from"react/jsx-runtime";var Context=/*@__PURE__ */createContext(null);function useSearch(){const ctx=useContext(Context);if(!ctx){throw new Error("Search parts require Search.Root")}return ctx}function Root(props){if(props.source){return jsx(ControlledRoot,{...props,source:props.source})}return jsx(UncontrolledRoot,{...props})}function UncontrolledRoot(props){const cart=useCart();const menu=useMenu(cart.branchId??void 0,{fulfilment:bagOrderType(cart.fulfilment)});const[query,setQuery]=useControllableState({value:props.query,defaultValue:props.defaultQuery??"",onChange:props.onQueryChange});const index=useMemo(()=>menu.data?createSearchIndex(menu.data):()=>[],[menu.data]);const results=useMemo(()=>index(query),[index,query]);return jsx(ControlledRoot,{...props,query,onQueryChange:setQuery,source:{results,isLoading:menu.isLoading,isStale:menu.isStale}})}function ControlledRoot({query,defaultQuery="",onQueryChange,onSelect=()=>{},announcement=countAnnouncement,source,...props}){const client=useZappie();const[value,setValue]=useControllableState({value:query,defaultValue:defaultQuery,onChange:onQueryChange});const results=source.results;const combo=useCombobox(results,onSelect);const setQuery=next=>{setValue(next);combo.setActiveIndex(-1);combo.setOpen(true)};useEffect(()=>{if(!value.trim()){return}const timer=setTimeout(()=>client._internal.emit("search",{query:value,resultCount:results.length}),600);return()=>clearTimeout(timer)},[client,value,results.length]);const state={...combo,query:value,setQuery,results,setComposing:value2=>source.onCompositionChange?.(value2),...source.error?{error:source.error}:{},...source.retry?{retry:source.retry}:{}};return jsx(Context.Provider,{value:state,children:part("div",withLiveRegion(props,combo.isOpen&&value.trim()?announcement(results.length):""),state,{"data-state":source.error?"error":source.isLoading?"loading":source.isStale?"stale":"valid",onBlur:event=>{if(!event.currentTarget.contains(event.relatedTarget)){combo.setOpen(false)}}})})}var Input=/*@__PURE__ */forwardRef(function Input2(props,ref){const state=useSearch();return part("input",props,state,{...state.inputProps,type:"search",onCompositionStart:()=>state.setComposing(true),onCompositionEnd:()=>state.setComposing(false),value:state.query,onChange:event=>state.setQuery(event.target.value)},ref)});var Results=/*@__PURE__ */forwardRef(function Results2(props,ref){const state=useSearch();return part("div",props,state,state.listProps,composeRefs(ref,node=>{if(node?.id&&node.id!==state.listProps.id){state.setListId(node.id)}}))});var Result=/*@__PURE__ */forwardRef(function Result2({index,...props},ref){const state=useSearch();return part("div",props,state,state.getOptionProps(index),composeRefs(ref,node=>{if(node?.id&&node.id!==state.getOptionProps(index).id){state.registerOption(index,node.id)}}))});var Search={Root,Input,Results,Result};export{Search,createSearchIndex2 as createSearchIndex};
|
package/dist/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var PACKAGE_VERSION=true?"0.
|
|
1
|
+
var PACKAGE_VERSION=true?"0.29.0":"0.0.0-development";export{PACKAGE_VERSION};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zappie/foundations",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.29.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,
|
|
@@ -101,7 +101,7 @@
|
|
|
101
101
|
"peerDependencies": {
|
|
102
102
|
"react": "^18.2.0 || ^19.0.0",
|
|
103
103
|
"react-dom": "^18.2.0 || ^19.0.0",
|
|
104
|
-
"@zappie/sdk": "^0.
|
|
104
|
+
"@zappie/sdk": "^0.30.0",
|
|
105
105
|
"react-router": "^8.4.0"
|
|
106
106
|
},
|
|
107
107
|
"peerDependenciesMeta": {
|
|
@@ -118,7 +118,7 @@
|
|
|
118
118
|
"@types/google.maps": "^3.66.7",
|
|
119
119
|
"esbuild": "^0.28.2",
|
|
120
120
|
"react-router": "8.5.0",
|
|
121
|
-
"@zappie/sdk": "0.
|
|
121
|
+
"@zappie/sdk": "0.30.0"
|
|
122
122
|
},
|
|
123
123
|
"license": "MIT",
|
|
124
124
|
"homepage": "https://github.com/zappie/storefront-packages#readme",
|