Merge master

This commit is contained in:
Linus Flood
2024-11-28 13:37:45 +01:00
225 changed files with 4488 additions and 3192 deletions
-189
View File
@@ -1,189 +0,0 @@
import merge from "deepmerge"
import { produce } from "immer"
import { useContext } from "react"
import { create, useStore } from "zustand"
import { createJSONStorage, persist } from "zustand/middleware"
import { bedTypeSchema } from "@/components/HotelReservation/EnterDetails/BedType/schema"
import { breakfastStoreSchema } from "@/components/HotelReservation/EnterDetails/Breakfast/schema"
import {
guestDetailsSchema,
signedInDetailsSchema,
} from "@/components/HotelReservation/EnterDetails/Details/schema"
import { DetailsContext } from "@/contexts/Details"
import { arrayMerge } from "@/utils/merge"
import { StepEnum } from "@/types/enums/step"
import type { DetailsState, InitialState } from "@/types/stores/details"
export const detailsStorageName = "details-storage"
export function createDetailsStore(
initialState: InitialState,
isMember: boolean
) {
if (typeof window !== "undefined") {
/**
* We need to initialize the store from sessionStorage ourselves
* since `persist` does it first after render and therefore
* we cannot use the data as `defaultValues` for our forms.
* RHF caches defaultValues on mount.
*/
const detailsStorageUnparsed = sessionStorage.getItem(detailsStorageName)
if (detailsStorageUnparsed) {
const detailsStorage: Record<
"state",
Pick<DetailsState, "data">
> = JSON.parse(detailsStorageUnparsed)
initialState = merge(detailsStorage.state.data, initialState, {
arrayMerge,
})
}
}
return create<DetailsState>()(
persist(
(set) => ({
actions: {
setIsSubmittingDisabled(isSubmittingDisabled) {
return set(
produce((state: DetailsState) => {
state.isSubmittingDisabled = isSubmittingDisabled
})
)
},
setTotalPrice(totalPrice) {
return set(
produce((state: DetailsState) => {
state.totalPrice = totalPrice
})
)
},
toggleSummaryOpen() {
return set(
produce((state: DetailsState) => {
state.isSummaryOpen = !state.isSummaryOpen
})
)
},
updateBedType(bedType) {
return set(
produce((state: DetailsState) => {
state.isValid["select-bed"] = true
state.data.bedType = bedType
})
)
},
updateBreakfast(breakfast) {
return set(
produce((state: DetailsState) => {
state.isValid.breakfast = true
state.data.breakfast = breakfast
})
)
},
updateDetails(data) {
return set(
produce((state: DetailsState) => {
state.isValid.details = true
state.data.countryCode = data.countryCode
state.data.dateOfBirth = data.dateOfBirth
state.data.email = data.email
state.data.firstName = data.firstName
state.data.join = data.join
state.data.lastName = data.lastName
if (data.join) {
state.data.membershipNo = undefined
} else {
state.data.membershipNo = data.membershipNo
}
state.data.phoneNumber = data.phoneNumber
state.data.zipCode = data.zipCode
})
)
},
},
data: merge(
{
bedType: undefined,
breakfast: undefined,
countryCode: "",
dateOfBirth: "",
email: "",
firstName: "",
join: false,
lastName: "",
membershipNo: "",
phoneNumber: "",
termsAccepted: false,
zipCode: "",
},
initialState
),
isSubmittingDisabled: false,
isSummaryOpen: false,
isValid: {
[StepEnum.selectBed]: false,
[StepEnum.breakfast]: false,
[StepEnum.details]: false,
[StepEnum.payment]: false,
},
totalPrice: {
euro: { currency: "", amount: 0 },
local: { currency: "", amount: 0 },
},
}),
{
name: detailsStorageName,
onRehydrateStorage(prevState) {
return function (state) {
if (state) {
const validatedBedType = bedTypeSchema.safeParse(state.data)
if (validatedBedType.success !== state.isValid["select-bed"]) {
state.isValid["select-bed"] = validatedBedType.success
}
const validatedBreakfast = breakfastStoreSchema.safeParse(
state.data
)
if (validatedBreakfast.success !== state.isValid.breakfast) {
state.isValid.breakfast = validatedBreakfast.success
}
const detailsSchema = isMember
? signedInDetailsSchema
: guestDetailsSchema
const validatedDetails = detailsSchema.safeParse(state.data)
if (validatedDetails.success !== state.isValid.details) {
state.isValid.details = validatedDetails.success
}
const mergedState = merge(state.data, prevState.data, {
arrayMerge,
})
state.data = mergedState
}
}
},
partialize(state) {
return {
data: state.data,
}
},
storage: createJSONStorage(() => sessionStorage),
}
)
)
}
export function useDetailsStore<T>(selector: (store: DetailsState) => T) {
const store = useContext(DetailsContext)
if (!store) {
throw new Error("useDetailsStore must be used within DetailsProvider")
}
return useStore(store, selector)
}
+227
View File
@@ -0,0 +1,227 @@
import isEqual from "lodash.isequal"
import { z } from "zod"
import { Lang } from "@/constants/languages"
import { breakfastPackageSchema } from "@/server/routers/hotels/output"
import { getLang } from "@/i18n/serverContext"
import type { BookingData } from "@/types/components/hotelReservation/enterDetails/bookingData"
import { RoomPackageCodeEnum } from "@/types/components/hotelReservation/selectRate/roomFilter"
import { CurrencyEnum } from "@/types/enums/currency"
import { StepEnum } from "@/types/enums/step"
import type { DetailsState, RoomRate } from "@/types/stores/enter-details"
import type { SafeUser } from "@/types/user"
export function langToCurrency() {
const lang = getLang()
switch (lang) {
case Lang.da:
return CurrencyEnum.DKK
case Lang.de:
case Lang.en:
case Lang.fi:
return CurrencyEnum.EUR
case Lang.no:
return CurrencyEnum.NOK
case Lang.sv:
return CurrencyEnum.SEK
default:
throw new Error(`Unexpected lang: ${lang}`)
}
}
export function extractGuestFromUser(user: NonNullable<SafeUser>) {
return {
countryCode: user.address.countryCode?.toString(),
email: user.email,
firstName: user.firstName,
lastName: user.lastName,
join: false,
membershipNo: user.membership?.membershipNumber,
phoneNumber: user.phoneNumber ?? "",
}
}
export function navigate(step: StepEnum, searchParams: string) {
window.history.pushState({ step }, "", `${step}?${searchParams}`)
}
export function checkIsSameBooking(prev: BookingData, next: BookingData) {
return isEqual(prev, next)
}
export function add(...nums: (number | string | undefined)[]) {
return nums.reduce((total: number, num) => {
if (typeof num === "undefined") {
num = 0
}
total = total + parseInt(`${num}`)
return total
}, 0)
}
export function subtract(...nums: (number | string | undefined)[]) {
return nums.reduce((total: number, num, idx) => {
if (typeof num === "undefined") {
num = 0
}
if (idx === 0) {
return parseInt(`${num}`)
}
total = total - parseInt(`${num}`)
if (total < 0) {
return 0
}
return total
}, 0)
}
export function getInitialRoomPrice(roomRate: RoomRate, isMember: boolean) {
if (isMember && roomRate.memberRate) {
return {
euro: {
currency: CurrencyEnum.EUR,
price: roomRate.memberRate.requestedPrice?.pricePerStay ?? 0,
},
local: {
currency: roomRate.memberRate.localPrice.currency,
price: roomRate.memberRate.localPrice.pricePerStay,
},
}
}
return {
euro: {
currency: CurrencyEnum.EUR,
price: roomRate.publicRate.requestedPrice?.pricePerStay ?? 0,
},
local: {
currency: roomRate.publicRate.localPrice.currency,
price: roomRate.publicRate.localPrice.pricePerStay,
},
}
}
export function getInitialTotalPrice(roomRate: RoomRate, isMember: boolean) {
if (isMember && roomRate.memberRate) {
return {
euro: {
currency: CurrencyEnum.EUR,
price: roomRate.memberRate.requestedPrice?.pricePerStay ?? 0,
},
local: {
currency: roomRate.memberRate.localPrice.currency,
price: roomRate.memberRate.localPrice.pricePerStay,
},
}
}
return {
euro: {
currency: CurrencyEnum.EUR,
price: roomRate.publicRate.requestedPrice?.pricePerStay ?? 0,
},
local: {
currency: roomRate.publicRate.localPrice.currency,
price: roomRate.publicRate.localPrice.pricePerStay,
},
}
}
export function calcTotalMemberPrice(state: DetailsState) {
if (!state.roomRate.memberRate) {
return {
roomPrice: state.roomPrice,
totalPrice: state.totalPrice,
}
}
return calcTotalPrice({
breakfast: state.breakfast,
packages: state.packages,
roomPrice: state.roomPrice,
totalPrice: state.totalPrice,
...state.roomRate.memberRate,
})
}
export function calcTotalPublicPrice(state: DetailsState) {
return calcTotalPrice({
breakfast: state.breakfast,
packages: state.packages,
roomPrice: state.roomPrice,
totalPrice: state.totalPrice,
...state.roomRate.publicRate,
})
}
export function calcTotalPrice(
state: Pick<
DetailsState,
"breakfast" | "packages" | "roomPrice" | "totalPrice"
> &
DetailsState["roomRate"]["publicRate"]
) {
const roomAndTotalPrice = {
roomPrice: state.roomPrice,
totalPrice: state.totalPrice,
}
if (state.requestedPrice?.pricePerStay) {
roomAndTotalPrice.roomPrice.euro = {
currency: CurrencyEnum.EUR,
price: state.requestedPrice.pricePerStay,
}
let totalPriceEuro = state.requestedPrice.pricePerStay
if (state.breakfast) {
totalPriceEuro = add(
totalPriceEuro,
state.breakfast.requestedPrice.totalPrice
)
}
if (state.packages) {
totalPriceEuro = state.packages.reduce((total, pkg) => {
if (pkg.requestedPrice.totalPrice) {
total = add(total, pkg.requestedPrice.totalPrice)
}
return total
}, totalPriceEuro)
}
roomAndTotalPrice.totalPrice.euro = {
currency: CurrencyEnum.EUR,
price: totalPriceEuro,
}
}
const roomPriceLocal = state.localPrice
roomAndTotalPrice.roomPrice.local = {
currency: roomPriceLocal.currency,
price: roomPriceLocal.pricePerStay,
}
let totalPriceLocal = roomPriceLocal.pricePerStay
if (state.breakfast) {
totalPriceLocal = add(
totalPriceLocal,
state.breakfast.localPrice.totalPrice
)
}
if (state.packages) {
totalPriceLocal = state.packages.reduce((total, pkg) => {
if (pkg.localPrice.totalPrice) {
total = add(total, pkg.localPrice.totalPrice)
}
return total
}, totalPriceLocal)
}
roomAndTotalPrice.totalPrice.local = {
currency: roomPriceLocal.currency,
price: totalPriceLocal,
}
return roomAndTotalPrice
}
+485
View File
@@ -0,0 +1,485 @@
import deepmerge from "deepmerge"
import { produce } from "immer"
import { useContext } from "react"
import { create, useStore } from "zustand"
import { createJSONStorage, persist } from "zustand/middleware"
import { bedTypeSchema } from "@/components/HotelReservation/EnterDetails/BedType/schema"
import { breakfastStoreSchema } from "@/components/HotelReservation/EnterDetails/Breakfast/schema"
import {
guestDetailsSchema,
signedInDetailsSchema,
} from "@/components/HotelReservation/EnterDetails/Details/schema"
import { DetailsContext } from "@/contexts/Details"
import { arrayMerge } from "@/utils/merge"
import {
add,
calcTotalMemberPrice,
calcTotalPublicPrice,
checkIsSameBooking,
extractGuestFromUser,
getInitialRoomPrice,
getInitialTotalPrice,
langToCurrency,
navigate,
} from "./helpers"
import { CurrencyEnum } from "@/types/enums/currency"
import { StepEnum } from "@/types/enums/step"
import type {
DetailsState,
FormValues,
InitialState,
} from "@/types/stores/enter-details"
import type { SafeUser } from "@/types/user"
const defaultGuestState = {
countryCode: "",
dateOfBirth: "",
email: "",
firstName: "",
join: false,
lastName: "",
membershipNo: "",
phoneNumber: "",
zipCode: "",
}
export const detailsStorageName = "details-storage"
export function createDetailsStore(
initialState: InitialState,
currentStep: StepEnum,
searchParams: string,
user: SafeUser
) {
const isMember = !!user
const isBrowser = typeof window !== "undefined"
// Spread is done on purpose since we want
// a copy of initialState and not alter the
// original
const formValues: FormValues = {
bedType: initialState.bedType,
booking: initialState.booking,
breakfast: undefined,
guest: isMember
? deepmerge(defaultGuestState, extractGuestFromUser(user))
: defaultGuestState,
}
if (isBrowser) {
/**
* We need to initialize the store from sessionStorage ourselves
* since `persist` does it first after render and therefore
* we cannot use the data as `defaultValues` for our forms.
* RHF caches defaultValues on mount.
*/
const detailsStorageUnparsed = sessionStorage.getItem(detailsStorageName)
if (detailsStorageUnparsed) {
const detailsStorage: Record<"state", FormValues> = JSON.parse(
detailsStorageUnparsed
)
const isSameBooking = checkIsSameBooking(
detailsStorage.state.booking,
initialState.booking
)
if (isSameBooking) {
if (!initialState.bedType && detailsStorage.state.bedType) {
formValues.bedType = detailsStorage.state.bedType
}
if ("breakfast" in detailsStorage.state) {
formValues.breakfast = detailsStorage.state.breakfast
}
if ("guest" in detailsStorage.state) {
if (!user) {
formValues.guest = deepmerge(
defaultGuestState,
detailsStorage.state.guest,
{ arrayMerge }
)
}
}
}
}
}
const initialRoomPrice = getInitialRoomPrice(initialState.roomRate, isMember)
const initialTotalPrice = getInitialTotalPrice(
initialState.roomRate,
isMember
)
if (initialState.packages) {
initialState.packages.forEach((pkg) => {
initialTotalPrice.euro.price = add(
initialTotalPrice.euro.price,
pkg.requestedPrice.totalPrice
)
initialTotalPrice.local.price = add(
initialTotalPrice.local.price,
pkg.localPrice.totalPrice
)
})
}
return create<DetailsState>()(
persist(
(set) => ({
actions: {
completeStep() {
return set(
produce((state: DetailsState) => {
const currentStepIndex = state.steps.indexOf(state.currentStep)
const nextStep = state.steps[currentStepIndex + 1]
state.currentStep = nextStep
navigate(nextStep, searchParams)
})
)
},
navigate(step: StepEnum) {
return set(
produce((state) => {
state.currentStep = step
navigate(step, searchParams)
})
)
},
setIsSubmittingDisabled(isSubmittingDisabled) {
return set(
produce((state: DetailsState) => {
state.isSubmittingDisabled = isSubmittingDisabled
})
)
},
setStep(step: StepEnum) {
return set(
produce((state: DetailsState) => {
state.currentStep = step
})
)
},
setTotalPrice(totalPrice) {
return set(
produce((state: DetailsState) => {
state.totalPrice.euro = totalPrice.euro
state.totalPrice.local = totalPrice.local
})
)
},
toggleSummaryOpen() {
return set(
produce((state: DetailsState) => {
state.isSummaryOpen = !state.isSummaryOpen
})
)
},
updateBedType(bedType) {
return set(
produce((state: DetailsState) => {
state.isValid["select-bed"] = true
state.bedType = bedType
const currentStepIndex = state.steps.indexOf(state.currentStep)
const nextStep = state.steps[currentStepIndex + 1]
state.currentStep = nextStep
navigate(nextStep, searchParams)
})
)
},
updateBreakfast(breakfast) {
return set(
produce((state: DetailsState) => {
state.isValid.breakfast = true
const stateTotalEuroPrice = state.totalPrice.euro?.price || 0
const stateTotalLocalPrice = state.totalPrice.local.price
const addToTotalPrice =
(state.breakfast === undefined ||
state.breakfast === false) &&
!!breakfast
const subtractFromTotalPrice =
(state.breakfast === undefined || state.breakfast) &&
breakfast === false
if (addToTotalPrice) {
const breakfastTotalEuroPrice = parseInt(
breakfast.requestedPrice.totalPrice
)
const breakfastTotalPrice = parseInt(
breakfast.localPrice.totalPrice
)
state.totalPrice = {
euro: {
currency: CurrencyEnum.EUR,
price: stateTotalEuroPrice + breakfastTotalEuroPrice,
},
local: {
currency: breakfast.localPrice.currency,
price: stateTotalLocalPrice + breakfastTotalPrice,
},
}
}
if (subtractFromTotalPrice) {
let currency =
state.totalPrice.local.currency ?? langToCurrency()
let currentBreakfastTotalPrice = 0
let currentBreakfastTotalEuroPrice = 0
if (state.breakfast) {
currentBreakfastTotalPrice = parseInt(
state.breakfast.localPrice.totalPrice
)
currentBreakfastTotalEuroPrice = parseInt(
state.breakfast.requestedPrice.totalPrice
)
currency = state.breakfast.localPrice.currency
}
let euroPrice =
stateTotalEuroPrice - currentBreakfastTotalEuroPrice
if (euroPrice < 0) {
euroPrice = 0
}
let localPrice =
stateTotalLocalPrice - currentBreakfastTotalPrice
if (localPrice < 0) {
localPrice = 0
}
state.totalPrice = {
euro: {
currency: CurrencyEnum.EUR,
price: euroPrice,
},
local: {
currency,
price: localPrice,
},
}
}
state.breakfast = breakfast
const currentStepIndex = state.steps.indexOf(state.currentStep)
const nextStep = state.steps[currentStepIndex + 1]
state.currentStep = nextStep
navigate(nextStep, searchParams)
})
)
},
updateDetails(data) {
return set(
produce((state: DetailsState) => {
state.isValid.details = true
state.guest.countryCode = data.countryCode
state.guest.dateOfBirth = data.dateOfBirth
state.guest.email = data.email
state.guest.firstName = data.firstName
state.guest.join = data.join
state.guest.lastName = data.lastName
if (data.join) {
state.guest.membershipNo = undefined
} else {
state.guest.membershipNo = data.membershipNo
}
state.guest.phoneNumber = data.phoneNumber
state.guest.zipCode = data.zipCode
if (data.join || data.membershipNo || isMember) {
const memberPrice = calcTotalMemberPrice(state)
state.roomPrice = memberPrice.roomPrice
state.totalPrice = memberPrice.totalPrice
} else {
const publicPrice = calcTotalPublicPrice(state)
state.roomPrice = publicPrice.roomPrice
state.totalPrice = publicPrice.totalPrice
}
const currentStepIndex = state.steps.indexOf(state.currentStep)
const nextStep = state.steps[currentStepIndex + 1]
state.currentStep = nextStep
navigate(nextStep, searchParams)
})
)
},
},
bedType: initialState.bedType ?? undefined,
booking: initialState.booking,
breakfast: undefined,
currentStep,
formValues,
guest: isMember
? deepmerge(defaultGuestState, extractGuestFromUser(user))
: defaultGuestState,
isSubmittingDisabled: false,
isSummaryOpen: false,
isValid: {
[StepEnum.selectBed]: false,
[StepEnum.breakfast]: false,
[StepEnum.details]: false,
[StepEnum.payment]: false,
},
packages: initialState.packages,
roomPrice: initialRoomPrice,
roomRate: initialState.roomRate,
steps: [
StepEnum.selectBed,
StepEnum.breakfast,
StepEnum.details,
StepEnum.payment,
],
totalPrice: initialTotalPrice,
}),
{
name: detailsStorageName,
merge(persistedState, currentState) {
if (
persistedState &&
Object.prototype.hasOwnProperty.call(persistedState, "booking")
) {
const isSameBooking = checkIsSameBooking(
// @ts-expect-error - persistedState cannot be typed
persistedState.booking,
currentState.booking
)
if (!isSameBooking) {
return deepmerge(persistedState, currentState, { arrayMerge })
}
}
return deepmerge(currentState, persistedState ?? {}, { arrayMerge })
},
onRehydrateStorage(initState) {
return function (state) {
if (state) {
if (
(state.guest.join || state.guest.membershipNo || isMember) &&
state.roomRate.memberRate
) {
const memberPrice = calcTotalMemberPrice(state)
state.roomPrice = memberPrice.roomPrice
state.totalPrice = memberPrice.totalPrice
} else {
const publicPrice = calcTotalPublicPrice(state)
state.roomPrice = publicPrice.roomPrice
state.totalPrice = publicPrice.totalPrice
}
/**
* TODO:
* - when included in rate, can packages still be received?
* - no hotels yet with breakfast included in the rate so
* impossible to build for atm.
*
* checking against initialState since that means the
* hotel doesn't offer breakfast
*
* matching breakfast first so the steps array is altered
* before the bedTypes possible step altering
*/
if (initialState.breakfast === false) {
state.steps = state.steps.filter(
(step) => step === StepEnum.breakfast
)
if (state.currentStep === StepEnum.breakfast) {
state.currentStep = state.steps[1]
}
}
if (initialState.bedType) {
if (state.currentStep === StepEnum.selectBed) {
state.currentStep = state.steps[1]
}
}
const isSameBooking = checkIsSameBooking(
initState.booking,
state.booking
)
const validateBooking = isSameBooking ? state : initState
const validPaths = [StepEnum.selectBed]
const validatedBedType = bedTypeSchema.safeParse(validateBooking)
if (validatedBedType.success) {
state.isValid["select-bed"] = true
validPaths.push(state.steps[1])
}
const validatedBreakfast =
breakfastStoreSchema.safeParse(validateBooking)
if (validatedBreakfast.success) {
state.isValid.breakfast = true
validPaths.push(StepEnum.details)
}
const detailsSchema = isMember
? signedInDetailsSchema
: guestDetailsSchema
const validatedDetails = detailsSchema.safeParse(
validateBooking.guest
)
// Need to add the breakfast check here too since
// when a member comes into the flow, their data is
// already added and valid, and thus to avoid showing a
// step the user hasn't been on yet as complete
if (state.isValid.breakfast && validatedDetails.success) {
state.isValid.details = true
validPaths.push(StepEnum.payment)
}
if (!validPaths.includes(state.currentStep)) {
state.currentStep = validPaths.at(-1)!
}
if (currentStep !== state.currentStep) {
const stateCurrentStep = state.currentStep
setTimeout(() => {
navigate(stateCurrentStep, searchParams)
})
}
if (isSameBooking) {
state = deepmerge<DetailsState>(initState, state, {
arrayMerge,
})
} else {
state = deepmerge<DetailsState>(state, initState, {
arrayMerge,
})
}
}
}
},
partialize(state) {
return {
bedType: state.bedType,
booking: state.booking,
breakfast: state.breakfast,
guest: state.guest,
totalPrice: state.totalPrice,
}
},
storage: createJSONStorage(() => sessionStorage),
}
)
)
}
export function useEnterDetailsStore<T>(selector: (store: DetailsState) => T) {
const store = useContext(DetailsContext)
if (!store) {
throw new Error("useEnterDetailsStore must be used within DetailsProvider")
}
return useStore(store, selector)
}
-1
View File
@@ -21,7 +21,6 @@ export const useHotelFilterStore = create<HotelFilterState>((set) => ({
: [...state.activeFilters, filterId]
return { activeFilters: newFilters }
}),
resultCount: 0,
setResultCount: (count) => set({ resultCount: count }),
}))
-156
View File
@@ -1,156 +0,0 @@
"use client"
import merge from "deepmerge"
import { produce } from "immer"
import { AppRouterInstance } from "next/dist/shared/lib/app-router-context.shared-runtime"
import { useContext } from "react"
import { create, useStore } from "zustand"
import { bedTypeSchema } from "@/components/HotelReservation/EnterDetails/BedType/schema"
import { breakfastStoreSchema } from "@/components/HotelReservation/EnterDetails/Breakfast/schema"
import {
guestDetailsSchema,
signedInDetailsSchema,
} from "@/components/HotelReservation/EnterDetails/Details/schema"
import { StepsContext } from "@/contexts/Steps"
import { detailsStorageName as detailsStorageName } from "./details"
import { StepEnum } from "@/types/enums/step"
import type { DetailsState } from "@/types/stores/details"
import type { StepState } from "@/types/stores/steps"
export function createStepsStore(
currentStep: StepEnum,
isMember: boolean,
noBedChoices: boolean,
noBreakfast: boolean,
searchParams: string,
push: AppRouterInstance["push"]
) {
const isBrowser = typeof window !== "undefined"
const steps = [
StepEnum.selectBed,
StepEnum.breakfast,
StepEnum.details,
StepEnum.payment,
]
/**
* TODO:
* - when included in rate, can packages still be received?
* - no hotels yet with breakfast included in the rate so
* impossible to build for atm.
*
* matching breakfast first so the steps array is altered
* before the bedTypes possible step altering
*/
if (noBreakfast) {
steps.splice(1, 1)
if (currentStep === StepEnum.breakfast) {
currentStep = steps[1]
push(`${currentStep}?${searchParams}`)
}
}
if (noBedChoices) {
if (currentStep === StepEnum.selectBed) {
currentStep = steps[1]
push(`${currentStep}?${searchParams}`)
}
}
const detailsStorageUnparsed = isBrowser
? sessionStorage.getItem(detailsStorageName)
: null
if (detailsStorageUnparsed) {
const detailsStorage: Record<
"state",
Pick<DetailsState, "data">
> = JSON.parse(detailsStorageUnparsed)
const validPaths = [StepEnum.selectBed]
const validatedBedType = bedTypeSchema.safeParse(detailsStorage.state.data)
if (validatedBedType.success) {
validPaths.push(steps[1])
}
const validatedBreakfast = breakfastStoreSchema.safeParse(
detailsStorage.state.data
)
if (validatedBreakfast.success) {
validPaths.push(StepEnum.details)
}
const detailsSchema = isMember ? signedInDetailsSchema : guestDetailsSchema
const validatedDetails = detailsSchema.safeParse(detailsStorage.state.data)
if (validatedDetails.success) {
validPaths.push(StepEnum.payment)
}
if (!validPaths.includes(currentStep) && isBrowser) {
// We will always have at least one valid path
currentStep = validPaths.pop()!
push(`${currentStep}?${searchParams}`)
}
}
const initalData = {
currentStep,
steps,
}
return create<StepState>()((set) =>
merge(
{
currentStep: StepEnum.selectBed,
steps: [],
completeStep() {
return set(
produce((state: StepState) => {
const currentStepIndex = state.steps.indexOf(state.currentStep)
const nextStep = state.steps[currentStepIndex + 1]
state.currentStep = nextStep
window.history.pushState(
{ step: nextStep },
"",
nextStep + window.location.search
)
})
)
},
navigate(step: StepEnum) {
return set(
produce((state) => {
state.currentStep = step
window.history.pushState(
{ step },
"",
step + window.location.search
)
})
)
},
setStep(step: StepEnum) {
return set(
produce((state: StepState) => {
state.currentStep = step
})
)
},
},
initalData
)
)
}
export function useStepsStore<T>(selector: (store: StepState) => T) {
const store = useContext(StepsContext)
if (!store) {
throw new Error(`useStepsStore must be used within StepsProvider`)
}
return useStore(store, selector)
}