@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/dist/hours/index.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
1
|
import{useEffect,useState}from"react";import{canOrderAhead,dateOffset,getOpenStatus,localParts,parseWallClock}from"../status/hours.js";var DEFAULT_TIMEZONE="Africa/Lagos";var LONG_DAYS=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];var SHORT_DAYS=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];var MINUTE=6e4;function branchTimezone(branch,storeTimezone){return branch.timezone??storeTimezone??DEFAULT_TIMEZONE}function todayIn(timezone,now=new Date){return new Date(`${localParts(now,timezone).date}T00:00:00Z`).getUTCDay()}function formatClock(time,{hour12=true,padHour=false,minutes="auto",period="lower",space=true,roundLastMinute=false}={}){const clock=parseWallClock(time);if(!clock){return time}let total=clock.hour24*60+clock.minute;if(roundLastMinute&&clock.minute===59){total=(total+1)%1440}const hour24=Math.floor(total/60);const minute=String(total%60).padStart(2,"0");const hour=String(hour12?hour24%12||12:hour24).padStart(padHour?2:1,"0");if(!hour12){return`${hour}:${minute}`}const half=hour24>=12?"PM":"AM";return`${hour}${minutes==="always"||minute!=="00"?`:${minute}`:""}${space?" ":""}${period==="upper"?half:half.toLowerCase()}`}var pad=value=>String(value).padStart(2,"0");function opening(at,timezone,now){const local=localParts(at,timezone);const today=localParts(now,timezone).date;return{at,day:local.date===today?"today":local.date===dateOffset(today,1)?"tomorrow":"later",weekday:new Date(`${local.date}T00:00:00Z`).getUTCDay(),time:`${pad(local.hour)}:${pad(local.minute)}`}}function nextOpening(branch,{from="api",now=new Date,storeTimezone}={}){const timezone=branchTimezone(branch,storeTimezone);if(from==="api"){if(branch.isOpen){return void 0}const value=branch.closedUntil??branch.nextChangeAt;const at=value?new Date(value):void 0;if(at&&at.getTime()>now.getTime()){return opening(at,timezone,now)}}const state=getOpenStatus(branch,timezone,now);return state.isOpen||!state.nextChange?void 0:opening(state.nextChange,timezone,now)}var OPENING={today:"Opens at {time}",tomorrow:"Opens tomorrow at {time}",later:"Opens {weekday} at {time}"};function describeOpening(next,{clock,weekday="short",phrases}={}){return{...OPENING,...phrases}[next.day].replace("{time}",formatClock(next.time,clock)).replace("{weekday}",(weekday==="long"?LONG_DAYS:SHORT_DAYS)[next.weekday])}function opensLabel(branch,options={}){const next=nextOpening(branch,options);return next&&describeOpening(next,options)}function closedForOrders(branch,{lastOrderMinutes,now=new Date,storeTimezone}={}){const ahead=canOrderAhead(branch);if(!branch.isOpen||ahead||!lastOrderMinutes){return!branch.isOpen&&!ahead}const state=getOpenStatus(branch,branchTimezone(branch,storeTimezone),now);return Boolean(state.isOpen&&state.nextChange&&state.nextChange.getTime()-now.getTime()<=lastOrderMinutes*MINUTE)}function takesOrdersAhead(branch,menu,menuIds){const preorder=menuIds.some(id=>menu?.menus?.find(section=>section.id===id)?.schedule?.preorder);return branch.fulfilment.scheduling&&(preorder||canOrderAhead(branch))}var STATUS={...OPENING,open:"Open until {time}",closingSoon:"Closes at {time}",closed:"Closed"};function openStatus(branch,{now=new Date,storeTimezone,closingSoonMinutes=30,phrases,...label}={}){const timezone=branchTimezone(branch,storeTimezone);const state=getOpenStatus(branch,timezone,now);const words={...STATUS,...phrases};const closingSoon=Boolean(state.isOpen&&state.nextChange&&state.nextChange.getTime()-now.getTime()<=closingSoonMinutes*MINUTE);const next=!state.isOpen&&state.nextChange?opening(state.nextChange,timezone,now):void 0;return{isOpen:state.isOpen,canOrderAhead:state.canOrderAhead,closedForOrders:!state.isOpen&&!state.canOrderAhead,closingSoon,label:state.isOpen?(closingSoon?words.closingSoon:words.open).replace("{time}",state.nextChange?formatClock(opening(state.nextChange,timezone,now).time,label.clock):""):next?describeOpening(next,{...label,phrases:words}):words.closed,...next?{next}:{},...state.nextChange?{nextChange:state.nextChange}:{},timezone}}function dayHours(times,day,{allDay,clock,range=" \u2013 ",separator=", "}){return times.filter(time=>!time.disabled&&time.day===day).sort((a,b)=>a.opens.localeCompare(b.opens)).map(time=>allDay!==void 0&&time.opens.startsWith("00:00")&&/^23:5\d/.test(time.closes)?allDay:`${formatClock(time.opens,clock)}${range}${formatClock(time.closes,clock)}`).join(separator)}function openingHours(times,options={}){const{start="sunday",today,closed,everyDay,dayNames=LONG_DAYS,through=" \u2013 "}=options;const first=start==="monday"?1:start==="today"?today??0:0;const week=Array.from({length:7},(_,index)=>(first+index)%7);const hours=week.map(day=>dayHours(times,day,options));if(!hours.some(Boolean)){return[]}const mark=days=>today!==void 0&&days.includes(today)?{today:true}:{};if(everyDay!==void 0&&hours.every(value=>value===hours[0])){return[{days:week,dayLabel:everyDay,hoursLabel:hours[0],...mark(week)}]}const runs=[];week.forEach((day,index)=>{const value=hours[index]||closed;if(value===void 0){return}const run=runs.at(-1);if(run&&run.last===index-1&&run.hours===value){run.days.push(day);run.last=index}else{runs.push({days:[day],hours:value,last:index})}});return runs.map(({days,hours:value})=>({days,dayLabel:days.length===1?dayNames[days[0]]:`${dayNames[days[0]]}${through}${dayNames[days.at(-1)]}`,hoursLabel:value,...value===closed&&!dayHours(times,days[0],options)?{closed:true}:{},...mark(days)}))}function branchHours(branch,{hours={},...options}={}){const status=openStatus(branch,options);const now=options.now??new Date;const day=todayIn(status.timezone,now);const date=localParts(now,status.timezone).date;const special=branch.specialHours?.find(entry=>entry.date===date);const clock=hours.clock??options.clock;const style={...hours,clock};return{status,today:special?special.closed||!special.opens||!special.closes?"":dayHours([{day,opens:special.opens,closes:special.closes}],day,style):dayHours(branch.openingTimes,day,style),week:openingHours(branch.openingTimes,{start:"today",...style,today:day})}}function useNow(every=MINUTE){const[now,setNow]=useState();useEffect(()=>{const tick=()=>setNow(new Date);const idle=typeof requestIdleCallback==="function"?requestIdleCallback(tick,{timeout:1500}):void 0;const soon=idle===void 0?setTimeout(tick,0):void 0;const timer=setInterval(tick,every);window.addEventListener("focus",tick);return()=>{if(idle!==void 0){cancelIdleCallback(idle)}clearTimeout(soon);clearInterval(timer);window.removeEventListener("focus",tick)}},[every]);return now}function useOpenStatus(branch,options={}){const now=useNow();return branch&&now?openStatus(branch,{...options,now}):void 0}function useBranchHours(branch,options={}){const now=useNow();return now?branchHours(branch,{...options,now}):void 0}export{DEFAULT_TIMEZONE,branchHours,branchTimezone,closedForOrders,describeOpening,formatClock,nextOpening,openStatus,openingHours,opensLabel,takesOrdersAhead,todayIn,useBranchHours,useNow,useOpenStatus};
|
|
2
|
-
//# sourceMappingURL=index.js.map
|
|
@@ -50,8 +50,11 @@ type Deferred<P> = {
|
|
|
50
50
|
};
|
|
51
51
|
/** Event handlers that start loading a deferred component when a shopper reaches for its trigger. */
|
|
52
52
|
type IntentPreloadHandlers = {
|
|
53
|
+
/** Starts the load when a mouse or pen moves over the trigger. */
|
|
53
54
|
onPointerEnter: () => void;
|
|
55
|
+
/** Starts the load when the trigger is pressed, which covers a tap on a touch screen. */
|
|
54
56
|
onPointerDown: () => void;
|
|
57
|
+
/** Starts the load when the trigger gets focus, such as from the keyboard. */
|
|
55
58
|
onFocus: () => void;
|
|
56
59
|
};
|
|
57
60
|
/** What a deferred load resolves to: a component, or a module whose default export is one. */
|
package/dist/index.d.ts
CHANGED
|
@@ -6,9 +6,9 @@ import * as _zappie_sdk from '@zappie/sdk';
|
|
|
6
6
|
import { Branch as Branch$1, CartLine, Money as Money$1, CartLineInput, CartIssue, CartFix, Quote, DeliveryAddress, CartFulfilment, OptionGroup as OptionGroup$1, Item, Choice as Choice$1, MoneyFormatOptions, PaymentMethodKind, Category, Menu, Store, OpeningTime } from '@zappie/sdk';
|
|
7
7
|
import { Coordinates } from '@zappie/sdk/branches';
|
|
8
8
|
import { useCart } from '@zappie/sdk/react';
|
|
9
|
-
export { D as Deferred, a as DeferredIdleOptions, b as DeferredProps, I as IntentPreloadHandlers, d as deferred, u as useIntentPreload } from './index-
|
|
10
|
-
import { S as ScheduleBlock, a as ScheduleSlot } from './window-
|
|
11
|
-
export { b as ScheduleDay, c as ScheduleMenu, d as ScheduleOptions } from './window-
|
|
9
|
+
export { D as Deferred, a as DeferredIdleOptions, b as DeferredProps, I as IntentPreloadHandlers, d as deferred, u as useIntentPreload } from './index-iwUrGm5U.js';
|
|
10
|
+
import { S as ScheduleBlock, a as ScheduleSlot } from './window-ClzBXJAe.js';
|
|
11
|
+
export { b as ScheduleDay, c as ScheduleMenu, d as ScheduleOptions } from './window-ClzBXJAe.js';
|
|
12
12
|
export { a as Overlay, u as useOverlay } from './react-C1KQB_W3.js';
|
|
13
13
|
import { SelectionControl } from '@zappie/sdk/options';
|
|
14
14
|
import './overlay/engine.js';
|
|
@@ -17,8 +17,11 @@ import './history-BlytQinP.js';
|
|
|
17
17
|
|
|
18
18
|
/** Account stubs that do not read credentials or host authentication. */
|
|
19
19
|
type Customer = {
|
|
20
|
+
/** The customer's ID. */
|
|
20
21
|
id: string;
|
|
22
|
+
/** The customer's first name. Left out when the account has none. */
|
|
21
23
|
givenName?: string;
|
|
24
|
+
/** The customer's phone number with most digits hidden, for display. */
|
|
22
25
|
phoneMasked: string;
|
|
23
26
|
};
|
|
24
27
|
/**
|
|
@@ -26,15 +29,20 @@ type Customer = {
|
|
|
26
29
|
* The current Account sign-in stub rejects with AccountNotConfiguredError.
|
|
27
30
|
*/
|
|
28
31
|
type SignInOptions = {
|
|
32
|
+
/** Where the shopper goes after signing in. Reserved. The stub ignores it. */
|
|
29
33
|
returnTo?: string;
|
|
34
|
+
/** Whether to ask the shopper to sign in: `none` or `login`. Reserved. The stub ignores it, so neither value has an effect yet. */
|
|
30
35
|
prompt?: "none" | "login";
|
|
36
|
+
/** How the sign-in opens: `popup`, `redirect` or `auto`. Reserved. The stub ignores it, so no value has an effect yet. */
|
|
31
37
|
display?: "popup" | "redirect" | "auto";
|
|
38
|
+
/** The access to ask for: `openid`, `phone`, `profile`, `addresses`, `orders:read`, `offline_access`, `cart` or `wallet`. Reserved. The stub ignores it. */
|
|
32
39
|
scopes?: ("openid" | "phone" | "profile" | "addresses" | "orders:read" | "offline_access" | "cart" | "wallet")[];
|
|
33
40
|
};
|
|
34
41
|
/**
|
|
35
42
|
* An error from Account sign-in and sign-out when authentication is not configured.
|
|
36
43
|
*/
|
|
37
44
|
declare class AccountNotConfiguredError extends Error {
|
|
45
|
+
/** Always `not_configured`, so you can tell this error apart without `instanceof`. */
|
|
38
46
|
readonly code = "not_configured";
|
|
39
47
|
constructor();
|
|
40
48
|
}
|
|
@@ -220,11 +228,17 @@ declare function BranchMap({ branches, selectedBranchId, onSelect, shopperLocati
|
|
|
220
228
|
* The current quantity, bounds, step, disabled state and value setter exposed by a quantity control.
|
|
221
229
|
*/
|
|
222
230
|
type QuantityState = {
|
|
231
|
+
/** The quantity now. */
|
|
223
232
|
value: number;
|
|
233
|
+
/** Set the quantity. It snaps to the nearest step from `min` and stays within the bounds. Ignored while disabled or for a value that isn't finite. */
|
|
224
234
|
setValue: (value: number) => void;
|
|
235
|
+
/** The lowest quantity. Defaults to 1. */
|
|
225
236
|
min: number;
|
|
237
|
+
/** The highest quantity. Defaults to 99. */
|
|
226
238
|
max: number;
|
|
239
|
+
/** How much each change moves the quantity. Defaults to 1. */
|
|
227
240
|
step: number;
|
|
241
|
+
/** Whether the control is turned off, so the quantity can't change. Defaults to false. */
|
|
228
242
|
disabled: boolean;
|
|
229
243
|
};
|
|
230
244
|
/**
|
|
@@ -319,7 +333,14 @@ declare const Cart: {
|
|
|
319
333
|
* The quote and its display status: loading, stale, ready or offline.
|
|
320
334
|
*/
|
|
321
335
|
type TotalsState = {
|
|
336
|
+
/** The cart's latest quote, with its totals. Undefined until the first quote arrives. */
|
|
322
337
|
quote?: Quote | undefined;
|
|
338
|
+
/**
|
|
339
|
+
* How far you can trust `quote`. `loading` while the cart is quoting, before it has loaded from storage, or while a
|
|
340
|
+
* cart with lines waits for its first quote. `stale` when the last quote failed for a reason other than the network,
|
|
341
|
+
* when the quote has passed its `expiresAt`, or when there is no quote. `ready` when the quote is current.
|
|
342
|
+
* `offline` when the last quote failed with a network error or a timeout.
|
|
343
|
+
*/
|
|
323
344
|
status: "loading" | "stale" | "ready" | "offline";
|
|
324
345
|
};
|
|
325
346
|
/**
|
|
@@ -400,8 +421,11 @@ declare function useCombobox<T>(results: readonly T[], onSelect: (item: T) => vo
|
|
|
400
421
|
* A labelled address suggestion with an ID and the delivery address selected by the shopper.
|
|
401
422
|
*/
|
|
402
423
|
type AddressSuggestion = {
|
|
424
|
+
/** Your ID for the suggestion, from your search. */
|
|
403
425
|
id: string;
|
|
426
|
+
/** The words the list shows. Choosing the suggestion puts them in the field. */
|
|
404
427
|
label: string;
|
|
428
|
+
/** The delivery address the suggestion stands for, passed to `onSelect`. */
|
|
405
429
|
address: DeliveryAddress;
|
|
406
430
|
};
|
|
407
431
|
/**
|
|
@@ -473,7 +497,13 @@ declare const Branch: {
|
|
|
473
497
|
* Whether the branch's menu hours have loaded. `loading` and `error` say nothing about whether the
|
|
474
498
|
* branch is open.
|
|
475
499
|
*/
|
|
476
|
-
type ScheduleStatus =
|
|
500
|
+
type ScheduleStatus =
|
|
501
|
+
/** The menu hours or the scheduling rules are still loading, or a retry is running. */
|
|
502
|
+
"loading"
|
|
503
|
+
/** The menu hours or the scheduling rules failed to load. */
|
|
504
|
+
| "error"
|
|
505
|
+
/** The hours and the rules are known. */
|
|
506
|
+
| "ready";
|
|
477
507
|
/**
|
|
478
508
|
* Available days and slots, the selected time and controls for choosing ASAP or a scheduled time.
|
|
479
509
|
*
|
|
@@ -494,13 +524,18 @@ type ScheduleState = {
|
|
|
494
524
|
isClosed: boolean;
|
|
495
525
|
/** Why nothing can be ordered when `isClosed` is true, naming the menu that blocks the bag when one does. */
|
|
496
526
|
blocker?: ScheduleBlock | undefined;
|
|
527
|
+
/** The slots grouped by their local date, `YYYY-MM-DD`, earliest first. Only days with a slot appear. Empty until `ready`. */
|
|
497
528
|
days: {
|
|
498
529
|
date: string;
|
|
499
530
|
slots: ScheduleSlot[];
|
|
500
531
|
}[];
|
|
532
|
+
/** Every slot the bag can be ordered for, earliest first. Empty until `ready`. */
|
|
501
533
|
slots: ScheduleSlot[];
|
|
534
|
+
/** The chosen slot's `value`, an RFC 3339 instant in UTC, or null for ASAP. */
|
|
502
535
|
value: string | null;
|
|
536
|
+
/** Choose a slot by its `value`, or null for ASAP. A value that isn't a slot, or ASAP while `canAsap` is false, is ignored. */
|
|
503
537
|
setValue: (value: string | null) => void;
|
|
538
|
+
/** Whether ASAP is chosen, that is `value` is null. */
|
|
504
539
|
isAsap: boolean;
|
|
505
540
|
/**
|
|
506
541
|
* True when the hours are known, the branch takes an order now and every menu in the bag is
|
|
@@ -510,6 +545,7 @@ type ScheduleState = {
|
|
|
510
545
|
* branch takes orders ahead. `isOpen` is read with the store, so pass the latest branch.
|
|
511
546
|
*/
|
|
512
547
|
canAsap: boolean;
|
|
548
|
+
/** Whether the choice can be ordered: ASAP while `canAsap` is true, or a slot still in `slots`. */
|
|
513
549
|
isValid: boolean;
|
|
514
550
|
};
|
|
515
551
|
/**
|
|
@@ -575,11 +611,17 @@ type ActiveGroup = OptionGroup$1;
|
|
|
575
611
|
* The current item selection, preview prices, validation issues and actions supplied to item form parts.
|
|
576
612
|
*/
|
|
577
613
|
type ItemFormContext = {
|
|
614
|
+
/** The item the form adds. */
|
|
578
615
|
item: Item;
|
|
616
|
+
/** The item's option groups that apply to the selection now, with their effective rules. Unavailable groups are left out. */
|
|
579
617
|
groups: ActiveGroup[];
|
|
618
|
+
/** How many the shopper is adding. Defaults to the item's minimum quantity. */
|
|
580
619
|
quantity: number;
|
|
620
|
+
/** Set the quantity. Clears an earlier failure and the `added` status. */
|
|
581
621
|
setQuantity: (quantity: number) => void;
|
|
622
|
+
/** The estimated price of one, with the chosen variant and options. The quote has the final price. */
|
|
582
623
|
unitPrice: Money$1;
|
|
624
|
+
/** `unitPrice` times the quantity, as an estimate. Zero while the quantity is not a whole number from 0 to 99. */
|
|
583
625
|
total: Money$1;
|
|
584
626
|
/** Every issue the shopper should see, shown once they try to add. */
|
|
585
627
|
issues: CartIssue[];
|
|
@@ -588,10 +630,19 @@ type ItemFormContext = {
|
|
|
588
630
|
* no menu here, or a quantity out of range. No group shows these, so show them by Add.
|
|
589
631
|
*/
|
|
590
632
|
itemIssues: CartIssue[];
|
|
633
|
+
/** Whether the selection passes the cart's checks and the last add didn't fail. */
|
|
591
634
|
canAdd: boolean;
|
|
635
|
+
/**
|
|
636
|
+
* Add the line to the cart, or update it through `onCommit`. Returns the line, or null when it fails
|
|
637
|
+
* the checks, the cart refuses it or a branch is required. On a failure the issues show and the
|
|
638
|
+
* first invalid group gets focus.
|
|
639
|
+
*/
|
|
592
640
|
add: () => CartLine | null;
|
|
641
|
+
/** Where the form stands. `incomplete` means the selection fails the cart's checks. `valid` means it passes. `added` means it was just added, until the selection changes. */
|
|
593
642
|
status: "incomplete" | "valid" | "added";
|
|
643
|
+
/** The line as chosen so far, with the menu filled in as the cart would file it. */
|
|
594
644
|
value: CartLineInput;
|
|
645
|
+
/** Replace the selection. The item's ID always stays the form's. Clears an earlier failure and the `added` status. */
|
|
595
646
|
setValue: (value: CartLineInput) => void;
|
|
596
647
|
/** True while Add asks for a branch instead of adding. See `branchRequired` on ItemForm.Root. */
|
|
597
648
|
branchRequired: boolean;
|
|
@@ -600,11 +651,13 @@ type ItemFormContext = {
|
|
|
600
651
|
* An option group that failed validation when the shopper tried to add, with its element and issues.
|
|
601
652
|
*/
|
|
602
653
|
type ItemFormInvalidGroup = {
|
|
654
|
+
/** The option group's ID. */
|
|
603
655
|
groupId: string;
|
|
604
656
|
/** The item's option group, or undefined for a group the template rendered from its own model. */
|
|
605
657
|
group: ActiveGroup | undefined;
|
|
606
658
|
/** The group's rendered element, or undefined when the group is not on screen. */
|
|
607
659
|
element: HTMLElement | undefined;
|
|
660
|
+
/** The issues that belong to this group. */
|
|
608
661
|
issues: CartIssue[];
|
|
609
662
|
};
|
|
610
663
|
/**
|
|
@@ -740,9 +793,11 @@ declare const OptionGroup: react.ForwardRefExoticComponent<Omit<react.AllHTMLAtt
|
|
|
740
793
|
* The item note as it stands, its limit and a setter, exposed by ItemNote.
|
|
741
794
|
*/
|
|
742
795
|
type NoteState = {
|
|
796
|
+
/** The note as it stands. Empty when the line has none. */
|
|
743
797
|
value: string;
|
|
744
798
|
/** Set the note. Text past the limit is cut. An empty note removes it. */
|
|
745
799
|
setValue: (note: string) => void;
|
|
800
|
+
/** The most characters a note can have, `ITEM_NOTE_MAX_LENGTH`. */
|
|
746
801
|
maxLength: number;
|
|
747
802
|
/** How many characters are left. */
|
|
748
803
|
remaining: number;
|
|
@@ -844,7 +899,15 @@ declare const Otp: {
|
|
|
844
899
|
};
|
|
845
900
|
|
|
846
901
|
/** The way a sheet leaves the screen when it is dragged. */
|
|
847
|
-
type DragDirection =
|
|
902
|
+
type DragDirection =
|
|
903
|
+
/** Off the bottom edge, as a bottom sheet leaves. */
|
|
904
|
+
"down"
|
|
905
|
+
/** Off the top edge, as a top sheet leaves. */
|
|
906
|
+
| "up"
|
|
907
|
+
/** Off the left edge, as a left side sheet leaves. */
|
|
908
|
+
| "left"
|
|
909
|
+
/** Off the right edge, as a right side sheet leaves. */
|
|
910
|
+
| "right";
|
|
848
911
|
|
|
849
912
|
/** Options for `useDragToClose`. */
|
|
850
913
|
type DragToCloseOptions = {
|
|
@@ -902,8 +965,11 @@ declare function preloadOverlay(): void;
|
|
|
902
965
|
* A payment-method choice with optional disabled state and an explanatory reason.
|
|
903
966
|
*/
|
|
904
967
|
type PaymentMethod = {
|
|
968
|
+
/** The method this choice selects. */
|
|
905
969
|
value: PaymentMethodKind;
|
|
970
|
+
/** Whether the shopper can't choose it. Its radio is disabled. Defaults to false. */
|
|
906
971
|
disabled?: boolean;
|
|
972
|
+
/** Why the method can't be chosen, read out as its radio's description. Left out when there is nothing to explain. */
|
|
907
973
|
reason?: string;
|
|
908
974
|
};
|
|
909
975
|
type PaymentState = {
|
|
@@ -975,11 +1041,17 @@ type SearchState = ReturnType<typeof useCombobox<SearchResult>> & {
|
|
|
975
1041
|
* Externally supplied search results and optional loading, error, retry and composition controls.
|
|
976
1042
|
*/
|
|
977
1043
|
type SearchSource = {
|
|
1044
|
+
/** The results to list for the query now, in the order to show them. */
|
|
978
1045
|
results: SearchResult[];
|
|
1046
|
+
/** Whether results are loading. The root gets `data-state="loading"` while true. */
|
|
979
1047
|
isLoading?: boolean;
|
|
1048
|
+
/** Whether the results are from an earlier read while a newer one loads. The root gets `data-state="stale"` while true. */
|
|
980
1049
|
isStale?: boolean;
|
|
1050
|
+
/** A message to show when the search failed. The root gets `data-state="error"` while it is set. */
|
|
981
1051
|
error?: string;
|
|
1052
|
+
/** Runs the search again after an error. Passed through to the search state. */
|
|
982
1053
|
retry?: () => void;
|
|
1054
|
+
/** Called with true when the shopper starts composing text with an input method, and false when they finish. */
|
|
983
1055
|
onCompositionChange?: (composing: boolean) => void;
|
|
984
1056
|
};
|
|
985
1057
|
type RootProps = Omit<PartProps<SearchState>, "onSelect"> & {
|
|
@@ -1015,8 +1087,11 @@ declare const Search: {
|
|
|
1015
1087
|
|
|
1016
1088
|
/** A way to reach a branch, as a link a shopper can open. */
|
|
1017
1089
|
type ContactLink = {
|
|
1090
|
+
/** The kind of link. `phone` calls the branch's phone. `message` opens the branch's messaging link. */
|
|
1018
1091
|
type: "phone" | "message";
|
|
1092
|
+
/** The link's words: "Call" or "Send a message". */
|
|
1019
1093
|
label: string;
|
|
1094
|
+
/** The URL to open: `tel:` and the phone's digits for a call, or the branch's messaging link. */
|
|
1020
1095
|
href: string;
|
|
1021
1096
|
};
|
|
1022
1097
|
/**
|
|
@@ -1086,10 +1161,9 @@ declare function formatOpeningHours(times: OpeningTime[]): {
|
|
|
1086
1161
|
}[];
|
|
1087
1162
|
/**
|
|
1088
1163
|
* Whether a branch takes orders for a later slot, so a shopper can still order while it is closed.
|
|
1089
|
-
* It needs scheduling and a positive `orderAheadDays
|
|
1090
|
-
* `orderAheadDays` follows its scheduling capability alone.
|
|
1164
|
+
* It needs scheduling, hours and a positive `orderAheadDays`, or none from a source without them.
|
|
1091
1165
|
*
|
|
1092
|
-
* @param branch - The branch whose scheduling and order-ahead days apply.
|
|
1166
|
+
* @param branch - The branch whose scheduling, hours and order-ahead days apply.
|
|
1093
1167
|
*/
|
|
1094
1168
|
declare function canOrderAhead(branch: Branch$1): boolean;
|
|
1095
1169
|
type OpenStatusState = {
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
1
|
"use client";import{PACKAGE_VERSION}from"./version.js";import{Account,AccountNotConfiguredError}from"./account/index.js";import{useZappieAccountUrl,ZappieAccountLink,zappieAccountUrl,zappieEnvironment}from"./account/zappie-account.js";import{PoweredByZappie,ZAPPIE_ATTRIBUTION_TEXT,ZAPPIE_ATTRIBUTION_URL}from"./attribution/powered-by-zappie.js";import{BranchMap,DeliveryMap}from"./branch-map/index.js";import{Cart,Totals}from"./cart/index.js";import{deferred,useIntentPreload}from"./deferred/index.js";import{OverlayRetry}from"./deferred/retry.js";import{Address}from"./fulfilment/address-picker.js";import{Branch}from"./fulfilment/branch-picker.js";import{Schedule}from"./fulfilment/schedule.js";import{Fulfilment}from"./fulfilment/switch.js";import{useControllableState}from"./internal/use-controllable-state.js";export*from"./item-form/index.js";import{Image}from"./media/image.js";import{Money}from"./money.js";import{Otp}from"./otp/input.js";import{useDragToClose}from"./overlay/drag-to-close.js";import{preloadOverlay}from"./overlay/load.js";import{Overlay,useOverlay}from"./overlay/react.js";import{PaymentMethods}from"./payment/methods.js";import{createSearchIndex,Search}from"./search/index.js";import{contactLinks,zappieSupportUrl}from"./status/contact.js";import{canOrderAhead,formatOpeningHours,formatWallClock,getOpenStatus,parseWallClock}from"./status/hours.js";import{OpenStatus}from"./status/open-status.js";var FOUNDATIONS_VERSION=PACKAGE_VERSION;export{Account,AccountNotConfiguredError,Address,Branch,BranchMap,Cart,DeliveryMap,FOUNDATIONS_VERSION,Fulfilment,Image,Money,OpenStatus,Otp,Overlay,OverlayRetry,PaymentMethods,PoweredByZappie,Schedule,Search,Totals,ZAPPIE_ATTRIBUTION_TEXT,ZAPPIE_ATTRIBUTION_URL,ZappieAccountLink,canOrderAhead,contactLinks,createSearchIndex,deferred,formatOpeningHours,formatWallClock,getOpenStatus,parseWallClock,preloadOverlay,useControllableState,useDragToClose,useIntentPreload,useOverlay,useZappieAccountUrl,zappieAccountUrl,zappieEnvironment,zappieSupportUrl};
|
|
2
|
-
//# sourceMappingURL=index.js.map
|
|
@@ -1,2 +1 @@
|
|
|
1
1
|
import{useEffect,useState}from"react";import{usePartId}from"./ids.js";import{Fragment,jsx,jsxs}from"react/jsx-runtime";function useCombobox(results,onSelect){const id=usePartId();const[activeIndex,setActiveIndex]=useState(-1);const[isOpen,setOpen]=useState(false);const[listId,setListId]=useState(`${id}-list`);const[optionIds,setOptionIds]=useState({});useEffect(()=>setActiveIndex(-1),[results.length]);const registerOption=(index,id2)=>setOptionIds(previous=>previous[index]===id2?previous:{...previous,[index]:id2});const active=activeIndex<results.length?activeIndex:-1;const optionId=index=>optionIds[index]??`${id}-option-${index}`;const activeId=isOpen&&active>=0?optionId(active):void 0;useEffect(()=>{if(activeId){document.getElementById(activeId)?.scrollIntoView?.({block:"nearest"})}},[activeId]);const select=index=>{const item=results[index];if(item!==void 0){onSelect(item);setOpen(false);setActiveIndex(-1)}};return{setListId,registerOption,activeIndex:active,setActiveIndex,isOpen,setOpen,select,inputProps:{role:"combobox","aria-autocomplete":"list","aria-expanded":isOpen,"aria-controls":listId,"aria-activedescendant":activeId,onKeyDown:event=>{if(event.nativeEvent.isComposing||event.keyCode===229){return}if(event.key==="Escape"){event.preventDefault();setOpen(false);setActiveIndex(-1)}else if(event.key==="ArrowDown"||event.key==="ArrowUp"){event.preventDefault();setOpen(true);setActiveIndex(results.length?active<0?event.key==="ArrowDown"?0:results.length-1:(active+(event.key==="ArrowDown"?1:-1)+results.length)%results.length:-1)}else if(event.key==="Enter"&&isOpen&&active>=0){event.preventDefault();select(active)}},onFocus:()=>setOpen(true)},listProps:{id:listId,role:"listbox",hidden:!isOpen},getOptionProps:index=>({id:optionId(index),role:"option","aria-selected":active===index,"data-selected":active===index?"":void 0,onMouseDown:event=>event.preventDefault(),onPointerDown:event=>event.stopPropagation(),onTouchStart:event=>event.stopPropagation(),onClick:()=>select(index)})}}var visuallyHidden={position:"absolute",width:1,height:1,margin:-1,padding:0,border:0,overflow:"hidden",clip:"rect(0 0 0 0)",whiteSpace:"nowrap"};function countAnnouncement(count){return count===0?"No results":`${count} result${count===1?"":"s"} available`}function LiveRegion({message}){return jsx("span",{role:"status","aria-live":"polite","aria-atomic":"true","data-zappie-live":"",style:visuallyHidden,children:message})}function withLiveRegion(props,message){if(props.asChild){return props}const children=props.children;return{...props,children:state=>jsxs(Fragment,{children:[typeof children==="function"?children(state):children,jsx(LiveRegion,{message})]})}}export{LiveRegion,countAnnouncement,useCombobox,withLiveRegion};
|
|
2
|
-
//# sourceMappingURL=combobox.js.map
|
package/dist/internal/ids.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
1
|
import{Children,cloneElement,Fragment,isValidElement}from"react";import{part}from"./slot.js";import{jsxs}from"react/jsx-runtime";function labelledControl(props,state,defaults,control,ref){const{asChild,children,...dom}=props;const content=typeof children==="function"?children(state):children;if(asChild){const child=Children.only(content);if(!isValidElement(child)){throw new Error("asChild requires one React element")}return part("label",{...dom,asChild:true,children:cloneElement(child,void 0,control,child.props.children)},state,defaults,ref)}return part("label",{...dom,children:jsxs(Fragment,{children:[control,content]})},state,defaults,ref)}export{labelledControl};
|
|
2
|
-
//# sourceMappingURL=labelled-control.js.map
|
package/dist/internal/slot.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
1
|
import{Children,cloneElement,createElement,isValidElement}from"react";function composeRefs(...refs){let cleanups=[];return value=>{for(const cleanup of cleanups){cleanup()}cleanups=[];if(value===null){return}for(const ref of refs){if(typeof ref==="function"){const cleanup=ref(value);cleanups.push(typeof cleanup==="function"?cleanup:()=>ref(null))}else if(ref){ref.current=value;cleanups.push(()=>{ref.current=null})}}}}function mergeProps(base,consumer){const result={...base,...consumer};if(typeof base.className==="string"&&typeof consumer.className==="string"){result.className=`${base.className} ${consumer.className}`}if(base.style&&consumer.style&&typeof base.style==="object"&&typeof consumer.style==="object"){result.style={...base.style,...consumer.style}}for(const key of Object.keys(base)){if(/^on[A-Z]/.test(key)&&typeof base[key]==="function"&&typeof consumer[key]==="function"){result[key]=event=>{consumer[key](event);if(!event.defaultPrevented){base[key](event)}}}}return result}function part(tag,props,state,defaults={},ref){const{asChild,children,...dom}=props;const content=typeof children==="function"?children(state):children;const merged=mergeProps(defaults,dom);if(asChild||(tag==="input"||tag==="textarea")&&typeof children==="function"){const child=Children.only(content);if(!isValidElement(child)){throw new Error("asChild requires one React element")}const element=child;const descriptor=Object.getOwnPropertyDescriptor(element,"ref");const childRef=element.props.ref??(descriptor&&"value"in descriptor?descriptor.value:void 0);return cloneElement(element,{...mergeProps(merged,element.props),ref:composeRefs(ref,childRef)})}return createElement(tag,{...merged,ref},content)}function partId(props){if(props.id){return props.id}if(props.asChild&&isValidElement(props.children)){const id=props.children.props.id;return typeof id==="string"?id:void 0}return void 0}export{composeRefs,mergeProps,part,partId};
|
|
2
|
-
//# sourceMappingURL=slot.js.map
|
|
@@ -1,2 +1 @@
|
|
|
1
1
|
import{useCallback,useRef,useState}from"react";function useControllableState({value,defaultValue,onChange}){const[internal,setInternal]=useState(defaultValue);const current=value===void 0?internal:value;const latest=useRef({current,onChange,controlled:value!==void 0});latest.current={current,onChange,controlled:value!==void 0};const set=useCallback(next=>{const snapshot=latest.current;const resolved=typeof next==="function"?next(snapshot.current):next;if(Object.is(resolved,snapshot.current)){return}if(!snapshot.controlled){latest.current.current=resolved;setInternal(resolved)}snapshot.onChange?.(resolved)},[]);return[current,set]}export{useControllableState};
|
|
2
|
-
//# sourceMappingURL=use-controllable-state.js.map
|
package/dist/item-form/index.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
1
|
import{Add,Options}from"./options.js";import{Root}from"./root.js";import{Choice,OptionGroup}from"./option-group.js";import{ItemNote}from"./options.js";import{Quantity}from"./quantity.js";var ItemForm={Root,Options,Add};export{Choice,ItemForm,ItemNote,OptionGroup,Quantity};
|
|
2
|
-
//# sourceMappingURL=index.js.map
|
|
@@ -1,2 +1 @@
|
|
|
1
1
|
"use client";import{canChoose,choiceQuantityMax,atLimit as groupAtLimit,groupRoom,LIMIT_REACHED_HINT,selectionControl,selectionCount}from"@zappie/sdk/options";import{cloneElement,createContext,forwardRef,Fragment,isValidElement,memo,useContext,useMemo,useRef}from"react";import{flag}from"../internal/data-attrs.js";import{usePartId}from"../internal/ids.js";import{labelledControl}from"../internal/labelled-control.js";import{composeRefs,part}from"../internal/slot.js";import{GroupRegistry,useItemForm}from"./root.js";import{jsx,jsxs}from"react/jsx-runtime";var Context=/*@__PURE__ */createContext(null);function useGroup(){const value=useContext(Context);if(!value){throw new Error("Choice and OptionGroup.Input require OptionGroup")}return value}var Group=/*@__PURE__ */forwardRef(function OptionGroup({group:supplied,requiredNote="Required",limitHint:hintText,"aria-describedby":describedBy,children,...props},ref){const ctx=useItemForm();const registry=useContext(GroupRegistry);const group=ctx.groups.find(candidate=>candidate.id===supplied.id)??supplied;const mine=ctx.value.choices?.filter(choice=>choice.groupId===group.id)??[];const selected=mine.map(choice=>choice.choiceId);const quantities=Object.fromEntries(mine.map(choice=>[choice.choiceId,choice.quantity??1]));const invalid=ctx.issues.some(issue=>issue.groupId===group.id);const input=ctx.value.inputs?.[group.id]??"";const latest=useRef({ctx,group});latest.current={ctx,group};const actions=useMemo(()=>{const write=(id,quantity)=>{const{ctx:ctx2,group:group2}=latest.current;const previous=ctx2.value.choices??[];const isThis=candidate=>candidate.groupId===group2.id&&candidate.choiceId===id;const choice=group2.choices.find(candidate=>candidate.id===id);if(!choice||!Number.isInteger(quantity)||quantity>0&&!canChoose(group2,previous,id)){return}const choices=previous.filter(candidate=>!isThis(candidate)&&(quantity<=0||candidate.groupId!==group2.id||group2.selection.max!==1));if(quantity>0){choices.push({groupId:group2.id,choiceId:id,quantity:Math.max(choice.quantity?.min??1,Math.min(choiceQuantityMax(group2,previous,id),quantity))})}const inputs={...ctx2.value.inputs};delete inputs[group2.id];ctx2.setValue({...ctx2.value,choices,inputs})};return{toggle:id=>{const{ctx:ctx2,group:group2}=latest.current;const chosen=ctx2.value.choices?.some(candidate=>candidate.groupId===group2.id&&candidate.choiceId===id);if(!chosen||selectionControl(group2)!=="radio"){write(id,chosen?0:group2.choices.find(candidate=>candidate.id===id)?.quantity?.min??1)}},setQuantity:write,setInput:value=>{const{ctx:ctx2,group:group2}=latest.current;ctx2.setValue({...ctx2.value,choices:(ctx2.value.choices??[]).filter(choice=>choice.groupId!==group2.id),inputs:{...ctx2.value.inputs,[group2.id]:value.slice(0,group2.input?.maxLength??500)}})}}},[]);const selectionKey=JSON.stringify(quantities);const control=selectionControl(group);const count=selectionCount(group,mine);const full=group.kind==="select"&&groupAtLimit(group,mine);const heldBack=full&&group.choices.some(choice=>choice.isAvailable&&!selected.includes(choice.id));const text=heldBack&&(hintText||LIMIT_REACHED_HINT)||void 0;const limitHint=hintText===false?void 0:text;const hintId=usePartId();const name=usePartId();const state=useMemo(()=>({group,selected,quantities,invalid,input,control,count,room:groupRoom(group,mine),atLimit:full,limitHint:text,hintId:limitHint&&hintId,mine,name,...actions}),[group,selectionKey,invalid,input,hintText,hintId,name,actions]);const radio=group.kind==="select"&&control==="radio";const noteId=usePartId();const note=group.required&&group.kind==="select"&&!radio&&requiredNote;const content=typeof children==="function"?children(state):children;const child=props.asChild&&isValidElement(content)?content:void 0;const own=describedBy??child?.props["aria-describedby"];const description=[note&¬eId,limitHint&&hintId,own].filter(Boolean).join(" ")||void 0;const hint=limitHint?jsx("p",{id:hintId,role:"status","data-zappie-limit-hint":"",children:limitHint}):null;return jsxs(Context.Provider,{value:state,children:[note&&jsx("span",{id:noteId,hidden:true,children:note}),part("div",child?{...props,children:cloneElement(child,{"aria-describedby":description},child.props.children,hint)}:{...props,children:jsxs(Fragment,{children:[content,hint]})},state,{role:radio?"radiogroup":"group",tabIndex:-1,"aria-label":group.name,"aria-required":radio?group.required:void 0,"aria-describedby":description,"data-zappie-required":group.required?"true":void 0,"aria-invalid":invalid||void 0,"data-invalid":flag(invalid),"data-state":invalid?"invalid":"valid","data-limit-reached":flag(full),"data-zappie-option-group":group.id},composeRefs(ref,node=>{if(node){registry.set(group.id,node)}else{registry.delete(group.id)}}))]})});var ChoiceView=/*@__PURE__ */memo(forwardRef(function ChoiceView2({choice,selected,control,limitReached,hintId,name,quantity,max,toggleChoice,setChoiceQuantity,disabled:held,...props},ref){const toggle=()=>toggleChoice(choice.id);const unavailable=!choice.isAvailable||Boolean(held);const state={choice,selected,disabled:unavailable||limitReached,limitReached,control,toggle,quantity,min:choice.quantity?.min??1,max,setQuantity:next=>setChoiceQuantity(choice.id,next)};const input=jsx("input",{type:control,name,value:choice.id,checked:selected,disabled:unavailable,"aria-disabled":limitReached||void 0,"aria-describedby":limitReached?hintId:void 0,"data-zappie-choice-input":"",onChange:toggle});return labelledControl(props,state,{"data-selected":flag(selected),"data-sold-out":flag(unavailable),"data-disabled":flag(unavailable||limitReached),"data-limit-reached":flag(limitReached),"data-control":control,"data-state":selected?"checked":"unchecked","data-zappie-option":choice.id},input,ref)}));var Choice=/*@__PURE__ */forwardRef(function Choice2(props,ref){const ctx=useGroup();const id=props.choice.id;const selected=ctx.selected.includes(id);const limitReached=props.choice.isAvailable&&!canChoose(ctx.group,ctx.mine,id);return jsx(ChoiceView,{...props,ref,selected,control:ctx.control,limitReached,hintId:ctx.hintId,name:ctx.name,quantity:ctx.quantities[id]??0,max:choiceQuantityMax(ctx.group,ctx.mine,id),toggleChoice:ctx.toggle,setChoiceQuantity:ctx.setQuantity})});var Input=/*@__PURE__ */forwardRef(function Input2(props,ref){const ctx=useGroup();const id=usePartId(props.id);const toggle=ctx.group.kind==="toggle";return part("input",props,ctx,{id,type:toggle?"checkbox":ctx.group.kind==="select"?"text":ctx.group.kind,value:toggle?void 0:ctx.input,checked:toggle?ctx.input==="true":void 0,required:ctx.group.required,"aria-label":ctx.group.name,"aria-invalid":ctx.invalid||void 0,"data-invalid":flag(ctx.invalid),maxLength:ctx.group.input?.maxLength??500,placeholder:ctx.group.input?.placeholder,onChange:event=>ctx.setInput(toggle?String(event.target.checked):event.target.value)},ref)});var OptionGroup2=/*@__PURE__ */Object.assign(Group,{Input});export{Choice,OptionGroup2 as OptionGroup};
|
|
2
|
-
//# sourceMappingURL=option-group.js.map
|
|
@@ -1,2 +1 @@
|
|
|
1
1
|
import{ITEM_NOTE_MAX_LENGTH}from"@zappie/sdk/options";import{forwardRef,useMemo}from"react";import{flag}from"../internal/data-attrs.js";import{part}from"../internal/slot.js";import{useItemForm}from"./root.js";var Options=/*@__PURE__ */forwardRef(function Options2(props,ref){return part("div",props,useItemForm(),{},ref)});var Add=/*@__PURE__ */forwardRef(function Add2(props,ref){const context=useItemForm();return part("button",props,context,{type:"button",onClick:context.add,"data-zappie-action":"add-to-cart","data-branch-required":flag(context.branchRequired)},ref)});var ItemNote=/*@__PURE__ */forwardRef(function ItemNote2(props,ref){const context=useItemForm();const value=context.value.note??"";const{setValue:setLine,value:line}=context;const state=useMemo(()=>({value,setValue:note=>{const next={...line};const text=note.slice(0,ITEM_NOTE_MAX_LENGTH);if(text){next.note=text}else{delete next.note}setLine(next)},maxLength:ITEM_NOTE_MAX_LENGTH,remaining:ITEM_NOTE_MAX_LENGTH-value.length}),[value,line,setLine]);return part("textarea",props,state,{value,maxLength:ITEM_NOTE_MAX_LENGTH,"data-zappie-item-note":"",onChange:event=>state.setValue(event.target.value)},ref)});export{Add,ItemNote,Options};
|
|
2
|
-
//# sourceMappingURL=options.js.map
|
|
@@ -1,2 +1 @@
|
|
|
1
1
|
"use client";import{createContext,forwardRef,useCallback,useContext,useMemo}from"react";import{flag}from"../internal/data-attrs.js";import{part}from"../internal/slot.js";import{useControllableState}from"../internal/use-controllable-state.js";import{jsx}from"react/jsx-runtime";var Context=/*@__PURE__ */createContext(null);function useQuantity(){const context=useContext(Context);if(!context){throw new Error("Quantity parts require Quantity.Root")}return context}function Root({value,defaultValue,onValueChange,min=1,max=99,step=1,disabled=false,...props}){if(!Number.isFinite(min)||!Number.isFinite(max)||!Number.isFinite(step)||step<=0||min>max){throw new RangeError("Quantity requires finite ordered bounds and a positive step")}const[current,set]=useControllableState({value,defaultValue:defaultValue??min,onChange:onValueChange});const setValue=useCallback(next=>{if(!disabled&&Number.isFinite(next)){const last=min+Math.floor((max-min)/step)*step;set(Math.max(min,Math.min(last,min+Math.round((next-min)/step)*step)))}},[min,max,step,disabled,set]);const state=useMemo(()=>({value:current,setValue,min,max,step,disabled}),[current,setValue,min,max,step,disabled]);return jsx(Context.Provider,{value:state,children:part("div",props,state,{"data-disabled":flag(disabled)})})}function button(direction){return forwardRef(function QuantityButton(props,ref){const ctx=useQuantity();const disabled=ctx.disabled||(direction<0?ctx.value<=ctx.min:ctx.value+ctx.step>ctx.max);return part("button",props,ctx,{type:"button",disabled,"aria-disabled":disabled,"data-disabled":flag(disabled),onClick:()=>ctx.setValue(ctx.value+direction*ctx.step)},ref)})}var Value=/*@__PURE__ */forwardRef(function Value2(props,ref){const ctx=useQuantity();return part("input",props,ctx,{type:"text",inputMode:"numeric",role:"spinbutton",value:String(ctx.value),disabled:ctx.disabled,"aria-valuenow":ctx.value,"aria-valuemin":ctx.min,"aria-valuemax":ctx.max,onChange:event=>{if(event.target.value.trim()){ctx.setValue(Number(event.target.value))}},onKeyDown:event=>{const next={ArrowUp:ctx.value+ctx.step,ArrowDown:ctx.value-ctx.step,Home:ctx.min,End:ctx.max}[event.key];if(next!==void 0){event.preventDefault();ctx.setValue(next)}}},ref)});var Quantity={Root,Value,Increment:button(1),Decrement:button(-1)};export{Quantity};
|
|
2
|
-
//# sourceMappingURL=quantity.js.map
|
package/dist/item-form/root.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
1
|
"use client";import{previewItem,withDefaultMenu,ZappieCartError}from"@zappie/sdk";import{useCart,useCartCatalogue,useZappie}from"@zappie/sdk/react";import{createContext,useCallback,useContext,useMemo,useRef,useState}from"react";import{part}from"../internal/slot.js";import{useControllableState}from"../internal/use-controllable-state.js";import{jsx}from"react/jsx-runtime";var ItemFormStateContext=/*@__PURE__ */createContext(null);function useItemForm(){const value=useContext(ItemFormStateContext);if(!value){throw new Error("ItemForm parts require ItemForm.Root")}return value}var GroupRegistry=/*@__PURE__ */createContext(null);var ungrouped=issues=>issues.filter(issue=>!issue.groupId);function Root({item,value,defaultValue,onValueChange,defaultQuantity,onAdded,onCommit,onInvalid,branchRequired=false,onBranchRequired,menuId,...props}){const client=useZappie();const{actions}=useCart();const menu=useCartCatalogue();const[input,setInput]=useControllableState({value,defaultValue:{...defaultValue,itemId:item.id,quantity:defaultQuantity??defaultValue?.quantity??item.quantity.min},onChange:onValueChange});const registry=useRef(new Map);const[added,setAdded]=useState(false);const[attempted,setAttempted]=useState(false);const[failure,setFailure]=useState(null);const normalized=useMemo(()=>{const line={...input,itemId:item.id};if(line.menuId===void 0&&menuId!==void 0){line.menuId=menuId}return menu?withDefaultMenu(menu,line):line},[input,item.id,menuId,menu]);const preview=useMemo(()=>previewItem(item,normalized),[item,normalized]);const validation=useMemo(()=>client.cart.validate(normalized),[client,normalized,menu]);const issues=failure??(attempted&&!validation.ok?validation.issues:[]);const setValue=useCallback(next=>{setAdded(false);setFailure(null);setInput({...next,itemId:item.id})},[setInput,item.id]);const setQuantity=useCallback(quantity=>setValue({...normalized,quantity}),[setValue,normalized]);const focusIssue=useCallback(errors=>{const ids=new Set([...registry.current.keys(),...preview.groups.map(group=>group.id)]);const invalid=[...ids].flatMap(groupId=>{const issues2=errors.filter(issue=>issue.groupId===groupId);return issues2.length?[{groupId,group:preview.groups.find(group=>group.id===groupId),element:registry.current.get(groupId),issues:issues2}]:[]});invalid[0]?.element?.focus({preventScroll:true});onInvalid?.(invalid,ungrouped(errors))},[preview.groups,onInvalid]);const add=useCallback(()=>{if(branchRequired){onBranchRequired?.(normalized);return null}const result=client.cart.validate(normalized);if(!result.ok){setAttempted(true);setFailure(result.issues);focusIssue(result.issues);return null}try{const line=onCommit?onCommit(normalized):actions.add(item,normalized);setAttempted(false);setAdded(true);onAdded?.(line);return line}catch(error){if(error instanceof ZappieCartError){setAttempted(true);setFailure([...error.issues]);focusIssue([...error.issues]);return null}throw error}},[client,actions,normalized,item,onAdded,onCommit,focusIssue,branchRequired,onBranchRequired]);const context=useMemo(()=>({item,...preview,quantity:normalized.quantity??item.quantity.min,setQuantity,issues,itemIssues:ungrouped(issues),canAdd:validation.ok&&!failure,add,status:added?"added":validation.ok?"valid":"incomplete",value:normalized,setValue,branchRequired}),[item,preview,normalized,setQuantity,issues,validation.ok,failure,add,added,setValue,branchRequired]);return jsx(ItemFormStateContext.Provider,{value:context,children:jsx(GroupRegistry.Provider,{value:registry.current,children:part("div",props,context,{"data-zappie-item":item.id,"data-state":issues.length?"invalid":"valid","data-sold-out":item.isAvailable?void 0:""})})})}export{GroupRegistry,ItemFormStateContext,Root,useItemForm};
|
|
2
|
-
//# sourceMappingURL=root.js.map
|
|
@@ -119,6 +119,7 @@ declare const ItemSheet: {
|
|
|
119
119
|
};
|
|
120
120
|
/** What the item page keeps in the history state while the shopper chooses a branch from Add. */
|
|
121
121
|
type KeptLine = {
|
|
122
|
+
/** The line as the shopper chose it so far: the item, its options and quantity. */
|
|
122
123
|
line: CartLineInput;
|
|
123
124
|
};
|
|
124
125
|
/** The line kept in a history state, when the state holds one for this item. */
|
package/dist/item-sheet/index.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
1
|
"use client";import{createContext,forwardRef,useContext,useEffect,useMemo,useRef,useState}from"react";import{flushSync}from"react-dom";import{UNSAFE_DataRouterDataContext as DataContext,Link,UNSAFE_LocationContext as LocationContext,matchPath,useLocation,useNavigate,useOutlet}from"react-router";import{part}from"../internal/slot.js";import{DeferredHost,loadBody}from"../overlay/deferred-host.js";import{Overlay}from"../overlay/react.js";import{jsx}from"react/jsx-runtime";var SheetContext=/*@__PURE__ */createContext(null);function useItemSheet(){const value=useContext(SheetContext);if(!value){throw new Error("ItemSheet parts require ItemSheet.Root")}return value}var ignore=()=>{};var load=loadBody;function cardFor(itemId,card){return card?.isConnected&&card.dataset.zappieItemLink===itemId?card:itemId?document.querySelector(`[data-zappie-item-link="${CSS.escape(itemId)}"]`):null}function returnFocusToCard(itemId){cardFor(itemId)?.focus({preventScroll:true})}function Root({sheet,href,closeTo="/",path="/item/:id",children}){const{pathname}=useLocation();const navigate=useNavigate();const routed=matchPath(path,pathname)?.params.id;const[tapped,setTapped]=useState();const[leaving,setLeaving]=useState();const pending=useRef(void 0);const latest=useRef({navigate,href,closeTo,routed});latest.current={navigate,href,closeTo,routed};const card=useRef(void 0);useEffect(()=>{if(routed){setTapped(void 0);pending.current=void 0;if(routed===leaving){setLeaving(void 0);void latest.current.navigate(-1)}}},[routed]);useEffect(()=>{const start=()=>load(sheet).catch(ignore);if(typeof window.requestIdleCallback==="function"){const handle2=window.requestIdleCallback(start);return()=>window.cancelIdleCallback(handle2)}const handle=window.setTimeout(start,1);return()=>window.clearTimeout(handle)},[sheet]);const itemId=(routed!==leaving?routed:void 0)??tapped;const actions=useMemo(()=>({href:id=>latest.current.href(id),preload:()=>{load(sheet).catch(ignore)},open:id=>{setLeaving(void 0);flushSync(()=>setTapped(id));const step={frame:requestAnimationFrame(()=>{step.timer=window.setTimeout(()=>{step.sent=id;void latest.current.navigate(latest.current.href(id),{preventScrollReset:true})})})};pending.current=step},close:()=>{const{navigate:navigate2,closeTo:closeTo2,routed:routed2}=latest.current;const step=pending.current;if(!routed2){pending.current=void 0;if(step?.sent){setLeaving(step.sent)}else if(step){cancelAnimationFrame(step.frame);window.clearTimeout(step.timer)}setTapped(void 0)}else if((window.history.state?.idx??0)>0){void navigate2(-1)}else{void navigate2(typeof closeTo2==="string"?closeTo2:closeTo2(routed2),{replace:true,preventScrollReset:true})}}}),[sheet]);const value=useMemo(()=>({...actions,itemId,routed:!!routed,sheet,card}),[actions,itemId,routed,sheet]);return jsx(SheetContext.Provider,{value,children})}function Page(){const{routed}=useItemSheet();const live={outlet:useOutlet(),location:useContext(LocationContext),data:useContext(DataContext)};const[kept,setKept]=useState(live);if(!routed&&(kept.outlet!==live.outlet||kept.location!==live.location||kept.data!==live.data)){setKept(live)}const{outlet,location,data}=routed?kept:live;return jsx(LocationContext.Provider,{value:location,children:jsx(DataContext.Provider,{value:data,children:outlet})})}function Content({presentation="drawer",fallback,failed,...props}){const{itemId,close,sheet,card}=useItemSheet();const[last,setLast]=useState(itemId);if(itemId&&itemId!==last){setLast(itemId)}const open=!!itemId;const navigation=useMemo(()=>({isOpen:open,open:ignore,close,trigger:{get current(){return cardFor(last,card.current)}}}),[open,close,last,card]);if(!last){return null}return jsx(DeferredHost,{body:sheet,param:"item",id:last,navigation,presentation,eager:!!fallback,failed,props,children:jsx(sheet.Component,{open:true,itemId:last,close,fallback:fallback?.(last),failed:retry=>failed(retry,close)},last)})}var Trigger=/*@__PURE__ */forwardRef(function Trigger2({itemId,prefetch="viewport",...props},ref){const state=useItemSheet();const href=state.href(itemId);return part(props.asChild?"a":Link,props,state,{...props.asChild?{href}:{to:href,prefetch},"data-zappie-item-link":itemId,"data-zappie-overlay-trigger":"item",onPointerEnter:state.preload,onPointerDown:state.preload,onFocus:state.preload,onClick:event=>{if(event.button===0&&!(event.metaKey||event.ctrlKey||event.shiftKey||event.altKey)){event.preventDefault();state.card.current=event.currentTarget;state.open(itemId)}}},ref)});var ItemSheet={Root,Page,Content,Trigger,Title:Overlay.Title,Close:Overlay.Close};function keptLine(state,itemId){const line=state?.line;return line&&typeof line==="object"&&line.itemId===itemId?line:void 0}function restoreLine(item,line){const groups=new Map(item.optionGroups.map(group=>[group.id,group]));const chosen=line.choices??[];const asked=Object.entries(line.inputs??{});const choices=chosen.filter(entry=>groups.get(entry.groupId)?.choices.some(choice=>choice.id===entry.choiceId&&choice.isAvailable));const inputs=asked.filter(([groupId])=>groups.has(groupId));return{value:{itemId:item.id,quantity:Math.min(Math.max(line.quantity??item.quantity.min,item.quantity.min),item.quantity.max??Infinity),...choices.length>0?{choices}:{},...inputs.length>0?{inputs:Object.fromEntries(inputs)}:{},...line.note?{note:line.note}:{}},dropped:choices.length!==chosen.length||inputs.length!==asked.length}}export{ItemSheet,keptLine,restoreLine,returnFocusToCard,useItemSheet};
|
|
2
|
-
//# sourceMappingURL=index.js.map
|
package/dist/loyalty/index.d.ts
CHANGED
|
@@ -28,10 +28,13 @@ declare function useRewardsRow(options?: {
|
|
|
28
28
|
};
|
|
29
29
|
/** A perk in the bag's totals: its discount from the quote, or a free item at zero. */
|
|
30
30
|
type PerkLine = {
|
|
31
|
+
/** The redemption that holds the perk on this cart. Pass it to `remove` to take the perk off. */
|
|
31
32
|
redemptionId: string;
|
|
33
|
+
/** What the line reads: the quote's discount label for a discount, the perk's name for a free item. */
|
|
32
34
|
name: string;
|
|
33
35
|
/** Negative for a discount, zero for a free item. */
|
|
34
36
|
amount: Money;
|
|
37
|
+
/** What the perk gives. `discount` takes money off the total, from the quote. `free_item` adds an item at no cost. */
|
|
35
38
|
kind: "discount" | "free_item";
|
|
36
39
|
};
|
|
37
40
|
/**
|
|
@@ -69,6 +72,7 @@ declare function Root({ branchId, open, ...props }: PartProps<RewardsContext> &
|
|
|
69
72
|
}): react.JSX.Element;
|
|
70
73
|
/** One perk's state for its card and button. */
|
|
71
74
|
type PerkState = {
|
|
75
|
+
/** The perk itself, as the loyalty programme lists it. */
|
|
72
76
|
perk: Perk;
|
|
73
77
|
/** What it gives, in words. */
|
|
74
78
|
reward: string;
|
package/dist/loyalty/index.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
1
|
"use client";import{format,money}from"@zappie/sdk";import{signInAgain,useCartPerks,useClaimPoints,useLoyalty,usePerks,useStoreCredit}from"@zappie/sdk/loyalty/react";import{useCart}from"@zappie/sdk/react";import{createContext,forwardRef,useContext,useEffect}from"react";import{part}from"../internal/slot.js";import{jsx}from"react/jsx-runtime";var wire=value=>money(value.amount_minor,value.currency);function rewardLabel(reward){if(reward.type==="free_item"){return"Free item"}if(reward.amount_off){return`${format.money(wire(reward.amount_off))} off`}return`${reward.percent_off??0}% off`}function useRewardsRow(options={}){const cart=useCart();const loyalty=useLoyalty(options.signedIn===false?{enabled:false}:{});return{visible:options.signedIn!==false&&loyalty.enabled&&cart.fulfilment?.type!=="dine_in",points:loyalty.points,status:loyalty.status}}function usePerkLines(){const cart=useCart();const perks=useCartPerks();const quote="quote"in cart.state?cart.state.quote:void 0;const lines=[];for(const perk of cart.perks){const discount=quote?.discounts.find(line=>line.redemptionId===perk.redemptionId);if(discount){lines.push({redemptionId:perk.redemptionId,name:discount.label,amount:discount.amount,kind:"discount"})}else if(perk.reward==="free_item"&"e){lines.push({redemptionId:perk.redemptionId,name:perk.name,amount:money(0,quote.total.currency),kind:"free_item"})}}return{lines,remove:perks.remove,busy:perks.busy,error:perks.error}}var Context=/*@__PURE__ */createContext(null);function useRewards(){const value=useContext(Context);if(!value){throw new Error("Rewards parts require Rewards.Root")}return value}function rewardsErrorMessage(error){return error instanceof Error?error.message:void 0}function Root({branchId,open=true,...props}){const cart=useCart();const branch=branchId??cart.branchId;const loyalty=useLoyalty();const perks=usePerks(open?branch:void 0);const credit=useStoreCredit(open?branch:void 0);const actions=useCartPerks();const value={status:loyalty.status,points:loyalty.points,perks:perks.perks,perksStatus:perks.status,applied:cart.perks,storeCredit:credit.enabled&&credit.balance&&credit.balance.amount_minor>0?wire(credit.balance):void 0,busy:actions.busy,error:actions.error,clearError:actions.clearError,apply:actions.apply,remove:actions.remove};return jsx(Context.Provider,{value,children:part("div",props,value,{"data-state":loyalty.status,"aria-busy":loyalty.status==="loading"||void 0})})}var Points=/*@__PURE__ */forwardRef(function Points2(props,ref){const{points}=useRewards();return part("data",{...props,children:props.children??(points===void 0?"":`${points.toLocaleString("en")} pts`)},{points},{value:points===void 0?void 0:String(points)},ref)});var StoreCredit=/*@__PURE__ */forwardRef(function StoreCredit2(props,ref){const{storeCredit}=useRewards();return storeCredit?part("div",{...props,children:props.children??format.money(storeCredit)},{balance:storeCredit},{},ref):null});var List=/*@__PURE__ */forwardRef(function List2(props,ref){const{perks,perksStatus}=useRewards();return perks.length?part("ul",props,{perks},{"aria-busy":perksStatus==="loading"||void 0},ref):null});var PerkContext=/*@__PURE__ */createContext(null);var PerkPart=/*@__PURE__ */forwardRef(function PerkPart2({perk,...props},ref){const rewards=useRewards();const applied=rewards.applied.find(p=>p.perkId===perk.id);const state={perk,reward:rewardLabel(perk.reward),applied,affordable:(rewards.points??0)>=perk.points_cost,busy:rewards.busy===perk.id||applied!==void 0&&rewards.busy===applied.redemptionId,locked:rewards.busy!==void 0};return jsx(PerkContext.Provider,{value:state,children:part("li",props,state,{"data-state":applied?"applied":state.affordable?"available":"unaffordable"},ref)})});var Action=/*@__PURE__ */forwardRef(function Action2(props,ref){const rewards=useRewards();const state=useContext(PerkContext);if(!state){throw new Error("Rewards.Action requires Rewards.Perk")}const{perk,applied,affordable,busy,locked}=state;const label=applied?"Remove":affordable?"Redeem":"Not enough points";return part("button",{...props,children:props.children??label},{...state,label},{type:"button","aria-label":applied?`Remove ${perk.name} and get ${applied.pointsSpent||perk.points_cost} points back`:affordable?`Redeem ${perk.name} for ${perk.points_cost} points`:`${perk.name} costs ${perk.points_cost} points. Not enough points`,"aria-busy":busy||void 0,disabled:!applied&&!affordable||locked,"data-state":busy?"busy":applied?"applied":"idle",onClick:()=>void(applied?rewards.remove(applied.redemptionId):rewards.apply(perk))},ref)});var Empty=/*@__PURE__ */forwardRef(function Empty2(props,ref){const{perks,perksStatus}=useRewards();return perksStatus==="ready"&&!perks.length?part("p",{...props,children:props.children??"No rewards available yet"},{},{},ref):null});var ErrorPart=/*@__PURE__ */forwardRef(function ErrorPart2(props,ref){const{error,clearError}=useRewards();const message=rewardsErrorMessage(error);return message?part("p",{...props,children:props.children??message},{message,dismiss:clearError},{role:"alert"},ref):null});var SignInAgain=/*@__PURE__ */forwardRef(function SignInAgain2(props,ref){const{status}=useRewards();return status==="scope_required"?part("button",{...props,children:props.children??"Sign in again to use your rewards"},{},{type:"button",onClick:()=>signInAgain()},ref):null});var Rewards={Root,Points,StoreCredit,List,Perk:PerkPart,Action,Empty,Error:ErrorPart,SignInAgain};function useClaimToast(orderId,options){const claim=useClaimPoints(orderId,options);const points=claim.pointsEarned;return{points,message:points===void 0?void 0:`You earned ${points.toLocaleString("en")} ${points===1?"point":"points"}`,dismiss:claim.dismiss}}var ClaimToast=/*@__PURE__ */forwardRef(function ClaimToast2({orderId,paid,durationMs=6e3,...props},ref){const toast=useClaimToast(orderId,{paid});const{message,dismiss}=toast;useEffect(()=>{if(message===void 0){return}const timer=setTimeout(dismiss,durationMs);return()=>clearTimeout(timer)},[message,durationMs]);return message===void 0?null:part("div",{...props,children:props.children??message},{message,points:toast.points,dismiss},{role:"status","aria-live":"polite"},ref)});export{ClaimToast,Rewards,rewardLabel,rewardsErrorMessage,useClaimToast,usePerkLines,useRewardsRow};
|
|
2
|
-
//# sourceMappingURL=index.js.map
|
package/dist/media/image.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
1
|
import{canResize,resized,srcSet}from"@zappie/sdk/template";import{canResizeUpload,isUpload,uploadResized,uploadSrcSet}from"@zappie/sdk/uploads";import{useCallback,useState}from"react";import{jsx}from"react/jsx-runtime";function Image({src,sizes="100vw",priority=false,quality,mode="resize",resizeHosts,alt,onError,...props}){const[failed,setFailed]=useState(null);const upload=isUpload(src);const responsive=mode==="resize"&&failed!==src&&(upload?canResizeUpload(src):canResize(src,resizeHosts));const checkLoaded=useCallback(image=>{if(responsive&&image?.complete&&image.naturalWidth===0){setFailed(src)}},[responsive,src]);return jsx("img",{...props,ref:checkLoaded,alt,src:!responsive?src:upload?uploadResized(src,960,quality):resized(src,960,quality,resizeHosts),...responsive?{srcSet:upload?uploadSrcSet(src,quality):srcSet(src,quality,resizeHosts),sizes}:{},loading:priority?"eager":"lazy",decoding:priority?"sync":"async",...priority?{fetchPriority:"high"}:{},onError:event=>{if(responsive){setFailed(src)}onError?.(event)}})}export{Image};
|
|
2
|
-
//# sourceMappingURL=image.js.map
|
package/dist/money.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
1
|
import{format}from"@zappie/sdk";import{forwardRef}from"react";import{part}from"./internal/slot.js";var Money=/*@__PURE__ */forwardRef(function Money2({value,formatOptions,...props},ref){const formatted=format.money(value,formatOptions);return part("data",{...props,children:props.children??formatted},{formatted},{value:String(value.amountMinor)},ref)});export{Money};
|
|
2
|
-
//# sourceMappingURL=money.js.map
|
package/dist/next.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
1
|
"use client";import{useEffect}from"react";import{LOCATION_EVENT}from"./overlay/history.js";var subscribers=0;var uninstall;function installShallowHistory(){if(typeof window==="undefined"){return()=>{}}if(subscribers++===0){let previous={base:"",pathname:"",shallow:false};const record=()=>{previous={base:window.history.state?.__zappieBase??window.location.pathname,pathname:window.location.pathname,shallow:Boolean(window.history.state?.__zappieBase)}};record();const onPop=event=>{const base=event.state?.__zappieBase??window.location.pathname;if((Boolean(event.state?.__zappieBase)||previous.shallow)&&base===previous.base&&window.location.pathname===previous.pathname){event.stopImmediatePropagation();record();window.dispatchEvent(new Event(LOCATION_EVENT));return}record()};window.addEventListener("popstate",onPop,true);window.addEventListener(LOCATION_EVENT,record);uninstall=()=>{window.removeEventListener("popstate",onPop,true);window.removeEventListener(LOCATION_EVENT,record)}}let released=false;return()=>{if(!released){released=true;if(--subscribers===0){uninstall?.()}}}}function useNextOverlayBridge(){useEffect(installShallowHistory,[])}export{LOCATION_EVENT as OVERLAY_LOCATION_EVENT,installShallowHistory,useNextOverlayBridge};
|
|
2
|
-
//# sourceMappingURL=next.js.map
|
|
@@ -5,7 +5,13 @@ import { Branch, Menu } from '@zappie/sdk';
|
|
|
5
5
|
* Name the in-venue mode with `inVenueLabel(branch)` from `@zappie/sdk/display`: "Walk-in" at a
|
|
6
6
|
* retail branch, "Dine-in" otherwise.
|
|
7
7
|
*/
|
|
8
|
-
type CheckoutMode =
|
|
8
|
+
type CheckoutMode =
|
|
9
|
+
/** The order is delivered to the shopper's address. */
|
|
10
|
+
"delivery"
|
|
11
|
+
/** The shopper collects the order from the branch. */
|
|
12
|
+
| "pickup"
|
|
13
|
+
/** The order is placed and served in the venue. */
|
|
14
|
+
| "dine_in";
|
|
9
15
|
/**
|
|
10
16
|
* The modes the branch takes and its menus serve, in the order delivery, pickup, in venue. A
|
|
11
17
|
* menu that lists no modes serves every mode the branch takes.
|
package/dist/order/index.d.ts
CHANGED
|
@@ -10,7 +10,14 @@ import { ReorderResult } from '@zappie/sdk/customer/reorder';
|
|
|
10
10
|
declare const orderMoney: (value: Money$1) => Money;
|
|
11
11
|
/** One row of an order's totals. */
|
|
12
12
|
type OrderTotalRow = {
|
|
13
|
+
/**
|
|
14
|
+
* What the row is. `subtotal` is the order's subtotal. `charge` is one of the business's charges
|
|
15
|
+
* other than delivery. `delivery` is the delivery charge or fee. `discount` is one discount.
|
|
16
|
+
* `total` is the order's total. `paid` is what the customer has paid, only when above zero.
|
|
17
|
+
* `due` is what is still owed, only when above zero.
|
|
18
|
+
*/
|
|
13
19
|
kind: "subtotal" | "charge" | "delivery" | "discount" | "total" | "paid" | "due";
|
|
20
|
+
/** The words to show, such as "Subtotal" or "Total". A charge or discount carries the label the API gave it. */
|
|
14
21
|
label: string;
|
|
15
22
|
/** Negative for a discount. Zero for a waived charge. */
|
|
16
23
|
amount: Money;
|
|
@@ -45,10 +52,20 @@ declare function currentStep(order: CustomerOrder): {
|
|
|
45
52
|
declare function orderTime(iso: string, timeZone?: string): string;
|
|
46
53
|
|
|
47
54
|
/** Where reading an order stands. */
|
|
48
|
-
type CustomerOrderStatus =
|
|
55
|
+
type CustomerOrderStatus =
|
|
56
|
+
/** The first read hasn't landed yet and no order was passed in. */
|
|
57
|
+
"loading"
|
|
58
|
+
/** The order is read and `order` holds it. */
|
|
59
|
+
| "ready"
|
|
60
|
+
/** The API answered 404: the order is someone else's or doesn't exist. */
|
|
61
|
+
| "not_found"
|
|
62
|
+
/** The last read failed for another reason. `retry` reads it again. */
|
|
63
|
+
| "error";
|
|
49
64
|
/** An order as `useCustomerOrder` reads and follows it. */
|
|
50
65
|
type CustomerOrderState = {
|
|
66
|
+
/** The order as last read or pushed live. Undefined until the first read lands, unless the server passed one in. */
|
|
51
67
|
order: CustomerOrder | undefined;
|
|
68
|
+
/** Where reading the order stands. */
|
|
52
69
|
status: CustomerOrderStatus;
|
|
53
70
|
/** The last read's failure, while `status` is `not_found` or `error`. */
|
|
54
71
|
error: unknown;
|
|
@@ -86,23 +103,41 @@ declare function Root({ customer, orderId, initialOrder, ...props }: PartProps<O
|
|
|
86
103
|
}): react.JSX.Element;
|
|
87
104
|
/** The state `Order.Status` passes to a render function. */
|
|
88
105
|
type OrderStatusState = {
|
|
106
|
+
/**
|
|
107
|
+
* The order's status once it is read. Before that, `loading` while the first read is on its way,
|
|
108
|
+
* `not_found` when the order is someone else's or doesn't exist, and `error` when reading it failed.
|
|
109
|
+
*/
|
|
89
110
|
status: CustomerOrder["status"] | "loading" | "not_found" | "error";
|
|
111
|
+
/** The current step's title, or a loading or failure message before the order is read. */
|
|
90
112
|
title: string;
|
|
113
|
+
/** The current step's description. Empty before the order is read and when the step has none. */
|
|
91
114
|
description: string;
|
|
92
115
|
};
|
|
93
116
|
/** The state `Order.Timeline` passes to a render function. */
|
|
94
117
|
type OrderTimelineState = {
|
|
118
|
+
/** Every step the order has taken, oldest first. The last one is the current step. */
|
|
95
119
|
steps: OrderTimelineStep[];
|
|
120
|
+
/** The step that comes next. Null once the order has ended and during the rider's steps. */
|
|
96
121
|
next: CustomerOrder["next_step"];
|
|
97
122
|
};
|
|
98
123
|
/** One fact about how the order reaches the customer. */
|
|
99
124
|
type OrderFulfilmentRow = {
|
|
125
|
+
/**
|
|
126
|
+
* Which fact the row holds, also its `data-kind`. `type` is Delivery or Pickup. `address` is
|
|
127
|
+
* where a delivery goes, or the branch's address for a pickup. `note` is the delivery note.
|
|
128
|
+
* `scheduled` is the time the order is scheduled for. `ready` is when the business expects it
|
|
129
|
+
* ready. `eta` is the minutes until it arrives or is ready. `contact` is the contact phone.
|
|
130
|
+
* `branch` is the branch's name. A row whose value the order doesn't have is left out.
|
|
131
|
+
*/
|
|
100
132
|
kind: "type" | "address" | "note" | "scheduled" | "ready" | "eta" | "contact" | "branch";
|
|
133
|
+
/** The words to show beside the value, such as "Deliver to" or "Ready by". */
|
|
101
134
|
label: string;
|
|
135
|
+
/** The fact in words. Times are in the branch's time zone, such as "25 Nov, 14:05". */
|
|
102
136
|
value: string;
|
|
103
137
|
};
|
|
104
138
|
/** What an order action's render function gets. */
|
|
105
139
|
type OrderActionState = {
|
|
140
|
+
/** Whether the action is running. A press while it runs does nothing. */
|
|
106
141
|
busy: boolean;
|
|
107
142
|
/** The last failure, in the API's words. */
|
|
108
143
|
error: string | undefined;
|
package/dist/order/index.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
1
|
"use client";import{format}from"@zappie/sdk";import{addReorderToCart}from"@zappie/sdk/customer/reorder";import{useStore,useZappie}from"@zappie/sdk/react";import{canShareReceipt}from"@zappie/sdk/receipts";import{redirectToCheckout}from"@zappie/sdk/redirect";import{createContext,forwardRef,useContext,useRef,useState}from"react";import{part}from"../internal/slot.js";import{ClaimToast}from"../loyalty/index.js";import{currentStep,orderMoney,orderTime,orderTotals}from"./model.js";import{useCustomerOrder}from"./use-customer-order.js";import{currentStep as currentStep2,orderEnded,orderMoney as orderMoney2,orderTime as orderTime2,orderTotals as orderTotals2}from"./model.js";import{useCustomerOrder as useCustomerOrder2}from"./use-customer-order.js";import{Fragment,jsx,jsxs}from"react/jsx-runtime";var Context=/*@__PURE__ */createContext(null);function useOrderContext(){const value=useContext(Context);if(!value){throw new Error("Order parts require Order.Root")}return value}function useOrder(){return useOrderContext().order}var money=value=>format.money(orderMoney(value));function Root({customer,orderId,initialOrder,...props}){const state=useCustomerOrder(customer,orderId,initialOrder?{initialOrder}:{});const store=useStore().data;const branch=store?.branches.find(b=>b.id===state.order?.branch_id);const value={...state,customer,branch,timeZone:branch?.timezone??store?.timezone};return jsx(Context.Provider,{value,children:part("div",props,value,{"data-state":state.status,"aria-busy":state.status==="loading"||void 0})})}function withOrder(name,render){const Part=forwardRef((props,ref)=>{const context=useOrderContext();return context.order?render(context.order,context,props,ref):null});Part.displayName=`Order.${name}`;return Part}var Reference=/*@__PURE__ */withOrder("Reference",(order,_,props,ref)=>part("span",{...props,children:props.children??order.reference},{reference:order.reference},{},ref));var Status=/*@__PURE__ */forwardRef(function Status2(props,ref){const{order,status}=useOrderContext();const state=order?{status:order.status,...currentStep(order)}:{status,title:status==="not_found"?"We couldn't find this order.":status==="error"?"We couldn't load this order. Try again.":"Loading your order",description:""};return part("p",{...props,children:props.children??state.title},state,{role:"status","aria-live":"polite","data-status":state.status},ref)});var Timeline=/*@__PURE__ */withOrder("Timeline",(order,{timeZone},props,ref)=>{const steps=order.timeline;const next=order.next_step;return part("ol",{...props,children:props.children??[...steps.map((step,index)=>{const current=index===steps.length-1;return jsxs("li",{"data-state":current?"current":"done","data-step":step.step,"aria-current":current?"step":void 0,children:[jsx("span",{"data-part":"title",children:step.title})," ",jsx("time",{dateTime:step.at,children:orderTime(step.at,timeZone)}),step.description?jsx("span",{"data-part":"description",children:step.description}):null]},`${step.step}:${step.at}:${index}`)}),next?jsxs("li",{"data-state":"next","data-step":next.step,children:[jsx("span",{"data-part":"title",children:next.title})," ",jsx("span",{"data-part":"label",children:"Next"}),next.description?jsx("span",{"data-part":"description",children:next.description}):null]},"next"):null]},{steps,next},{"aria-label":"Order progress"},ref)});var Fulfilment=/*@__PURE__ */withOrder("Fulfilment",(order,{branch,timeZone},props,ref)=>{const delivery=order.fulfilment==="delivery";const facts=[["type","Fulfilment",delivery?"Delivery":"Pickup"],["address",delivery?"Deliver to":"Pick up from",delivery?order.dropoff_address?.line1:branch?.address],["note","Delivery note",order.delivery_instructions],["scheduled","Scheduled for",order.scheduled_at&&orderTime(order.scheduled_at,timeZone)],["ready","Ready by",order.ready_at&&orderTime(order.ready_at,timeZone)],["eta",delivery?"Arrives in":"Ready in",order.eta_minutes===void 0?void 0:`About ${order.eta_minutes} min`],["contact","Contact phone",order.contact_phone],["branch","Branch",branch?.name]];const rows=facts.flatMap(([kind,label,value])=>value?[{kind,label,value}]:[]);return part("dl",{...props,children:props.children??rows.map(row=>jsxs("div",{"data-kind":row.kind,children:[jsx("dt",{children:row.label}),jsxs("dd",{children:[row.value,row.kind==="branch"&&branch?.phone?jsxs(Fragment,{children:[" ",jsxs("a",{href:`tel:${branch.phone.replace(/[^\d+]/g,"")}`,children:["Call ",branch.name]})]}):null]})]},row.kind))},{rows,branch},{},ref)});function LineDetail({line}){const groups=new Map;for(const choice of line.choices){const name=(choice.quantity>1?`${choice.quantity} \xD7 `:"")+choice.name+(choice.price.amount_minor>0?` (+${money(choice.price)})`:"");groups.set(choice.group_name,[...groups.get(choice.group_name)??[],name])}const details=[...[...groups].map(([group,names])=>["choice",group,names.join(", ")]),...line.texts.map(text=>["text",text.group_name,text.value]),...line.charges.map(charge=>["charge",charge.label,`${money(charge.amount)}${charge.included?" included":""}`])];return jsxs(Fragment,{children:[details.length?jsx("dl",{"data-part":"details",children:details.map(([kind,label,value],index)=>jsxs("div",{"data-kind":kind,children:[jsx("dt",{children:label}),jsx("dd",{children:value})]},`${kind}:${label}:${index}`))}):null,line.notes?jsxs("p",{"data-part":"note",children:["Note: ",line.notes]}):null]})}var Lines=/*@__PURE__ */withOrder("Lines",(order,_,props,ref)=>{const voided=order.voided_lines;const row=(line,index,removed)=>{const head=jsxs(Fragment,{children:[jsxs("span",{"data-part":"quantity",children:[line.quantity," \xD7"]})," ",jsx("span",{"data-part":"name",children:line.name})," ",jsx("data",{"data-part":"total",value:String(line.total.amount_minor),children:money(line.total)})]});return jsxs("li",{"data-state":removed?"voided":void 0,children:[removed?jsxs(Fragment,{children:[jsx("s",{children:head})," ",jsx("span",{"data-part":"label",children:"Removed"})]}):head,jsx(LineDetail,{line})]},`${removed?"v":"l"}:${line.item_id}:${index}`)};return part("ul",{...props,children:props.children??[...order.lines.map((line,index)=>row(line,index,false)),...voided.map((line,index)=>row(line,index,true))]},{lines:order.lines,voided},{"aria-label":"Items"},ref)});var Totals=/*@__PURE__ */withOrder("Totals",(order,_,props,ref)=>{const rows=orderTotals(order);return part("dl",{...props,children:props.children??rows.map((row,index)=>jsxs("div",{"data-kind":row.kind,"data-note":row.note,children:[jsxs("dt",{children:[row.label,row.promoCode?` (${row.promoCode})`:"",row.note==="included"?" (included)":""]}),jsx("dd",{children:row.note==="waived"?"Waived":jsx("data",{value:String(row.amount.amountMinor),children:format.money(row.amount)})})]},`${row.kind}:${index}`))},{rows},{},ref)});var Payments=/*@__PURE__ */withOrder("Payments",(order,{timeZone},props,ref)=>order.payments.length?part("ul",{...props,children:props.children??order.payments.map((payment,index)=>jsxs("li",{"data-state":payment.status,children:[jsx("span",{"data-part":"method",children:payment.method})," ",jsx("data",{value:String(payment.amount.amount_minor),children:money(payment.amount)})," ",jsx("time",{dateTime:payment.paid_at,children:orderTime(payment.paid_at,timeZone)}),payment.status==="refunded"?jsx("span",{"data-part":"label",children:" Refunded"}):null]},`${payment.paid_at}:${index}`))},{payments:order.payments},{"aria-label":"Payments"},ref):null);var message=(error,fallback)=>error instanceof Error&&error.message?error.message:fallback;function useAction(){const[busy,setBusy]=useState(false);const[error,setError]=useState();const running=useRef(false);const run=async(action,fallback)=>{if(running.current){return}running.current=true;setBusy(true);setError(void 0);try{await action()}catch(failure){setError(message(failure,fallback))}finally{running.current=false;setBusy(false)}};return{busy,error,run}}function actionButton(props,ref,state,label,onClick,extra={}){return jsxs(Fragment,{children:[part("button",{...props,children:props.children??label},state,{type:"button","aria-busy":state.busy||void 0,"aria-disabled":state.busy||void 0,"data-state":state.busy?"busy":"idle",onClick:()=>{if(!state.busy){onClick()}},...extra},ref),state.error?jsx("span",{role:"alert",children:state.error}):null]})}var Receipt=/*@__PURE__ */forwardRef(function Receipt2(props,ref){const{order,customer}=useOrderContext();const[file,setFile]=useState();if(!order){return null}const share=event=>{if(!canShareReceipt()){return}event.preventDefault();(file?Promise.resolve(file):customer.receipt(order.id)).then(value=>{setFile(value);return navigator.share({files:[value]})}).catch(()=>void 0)};return part("a",{...props,children:props.children??(file?"Share receipt":"Download receipt")},{shared:Boolean(file)},{href:customer.receiptUrl(order.id),download:"",onClick:share},ref)});var PayBalance=/*@__PURE__ */withOrder("PayBalance",(order,{customer},props,ref)=>order.amount_due.amount_minor>0?jsx(PayButton,{order,customer,props,forward:ref}):null);function PayButton({order,customer,props,forward}){const action=useAction();const keys=useRef(new Map);const due=`${order.id}:${order.amount_due.amount_minor}`;return actionButton(props,forward,action,`Pay ${money(order.amount_due)}`,()=>void action.run(async()=>{if(!keys.current.has(due)){keys.current.set(due,crypto.randomUUID())}const payment=await customer.payBalance(order.id,{idempotencyKey:keys.current.get(due)});redirectToCheckout(payment.url)},"We couldn't start the payment. Try again."))}var OrderAgain=/*@__PURE__ */forwardRef(function OrderAgain2({onReorder,...props},ref){const{order,customer}=useOrderContext();const zappie=useZappie();const action=useAction();const[result,setResult]=useState();if(!order){return null}const notice=result?reorderNotice(result):"";return jsxs(Fragment,{children:[actionButton(props,ref,{...action,result},"Order again",()=>void action.run(async()=>{const next=await addReorderToCart(zappie,await customer.reorder(order.id));setResult(next);onReorder?.(next)},"We couldn't add these items to your bag. Try again.")),jsx("span",{role:"status","data-part":"notice",children:notice})]})});function reorderNotice(result){const count=result.added.reduce((n,line)=>n+line.quantity,0);const added=count?`Added ${count} ${count===1?"item":"items"} to your bag.`:"None of these items can be ordered right now.";const names=result.dropped.map(line=>line.name);return names.length&&count?`${added} ${listNames(names)} ${names.length===1?"isn't":"aren't"} available any more.`:added}function listNames(names){return names.length>1?`${names.slice(0,-1).join(", ")} and ${names.at(-1)}`:names[0]}var Actions=/*@__PURE__ */forwardRef(function Actions2({loyalty,onReorder,...props},ref){const{order}=useOrderContext();return order?part("div",{...props,children:props.children??jsxs(Fragment,{children:[jsx(PayBalance,{}),jsx(Receipt,{}),jsx(OrderAgain,{...onReorder?{onReorder}:{}}),loyalty?jsx(ClaimToast,{orderId:order.id,paid:order.paid}):null]})},{},{role:"group","aria-label":"Order actions"},ref):null});var Order={Root,Reference,Status,Timeline,Fulfilment,Lines,Totals,Payments,Actions,Receipt,PayBalance,OrderAgain};function OrderDetails({customer,orderId,initialOrder,loyalty,onReorder,...props}){return jsx(Root,{customer,orderId,...initialOrder?{initialOrder}:{},...props,children:props.children??jsxs(Fragment,{children:[jsxs("header",{"data-part":"header",children:[jsxs("h1",{children:["Order ",jsx(Reference,{})]}),jsx(Status,{})]}),jsx("section",{"aria-label":"Progress",children:jsx(Timeline,{})}),jsx("section",{"aria-label":"Fulfilment",children:jsx(Fulfilment,{})}),jsx("section",{"aria-label":"Items",children:jsx(Lines,{})}),jsxs("section",{"aria-label":"Totals",children:[jsx(Totals,{}),jsx(Payments,{})]}),jsx(Actions,{...loyalty?{loyalty}:{},...onReorder?{onReorder}:{}})]})})}export{Order,OrderDetails,currentStep2 as currentStep,orderEnded,orderMoney2 as orderMoney,orderTime2 as orderTime,orderTotals2 as orderTotals,reorderNotice,useCustomerOrder2 as useCustomerOrder,useOrder};
|
|
2
|
-
//# sourceMappingURL=index.js.map
|