fix: Upgrade booking-flow eslint config * Upgrade booking-flow eslint config Approved-by: Bianca Widstam
103 lines
2.5 KiB
TypeScript
103 lines
2.5 KiB
TypeScript
import { useEffect, useState } from "react"
|
|
import { z } from "zod"
|
|
|
|
import { BOOKING_WIDGET_STATE } from "@scandic-hotels/common/constants/sessionKeys"
|
|
import { dt } from "@scandic-hotels/common/dt"
|
|
|
|
import { adultsSchema, childAgeSchema, childBedSchema } from "../utils/url"
|
|
|
|
const DEFAULT_ROOMS = [{ adults: 1, childrenInRoom: [] }]
|
|
|
|
const stateSchema = z.object({
|
|
fromDate: z.string(),
|
|
toDate: z.string(),
|
|
rooms: z.array(
|
|
z.object({
|
|
adults: adultsSchema,
|
|
childrenInRoom: z
|
|
.array(
|
|
z.object({
|
|
bed: childBedSchema,
|
|
age: childAgeSchema,
|
|
})
|
|
)
|
|
.optional(),
|
|
})
|
|
),
|
|
})
|
|
|
|
type BookingWidgetState = z.infer<typeof stateSchema>
|
|
|
|
export function useBookingWidgetState() {
|
|
const [bookingState, setBookingState] = useState<BookingWidgetState>({
|
|
fromDate: dt().format("YYYY-MM-DD"),
|
|
toDate: dt().add(1, "day").format("YYYY-MM-DD"),
|
|
rooms: DEFAULT_ROOMS,
|
|
})
|
|
|
|
useEffect(() => {
|
|
const now = dt()
|
|
const stored = getBookingWidgetState()
|
|
if (!stored) {
|
|
return
|
|
}
|
|
const storedFrom = dt(stored.fromDate)
|
|
const storedTo = dt(stored.toDate)
|
|
|
|
const isDateParamValid =
|
|
storedFrom.isValid() &&
|
|
storedTo.isValid() &&
|
|
storedFrom.isSameOrAfter(now, "day") &&
|
|
storedTo.isAfter(storedFrom)
|
|
|
|
if (isDateParamValid && stored.rooms?.length) {
|
|
// eslint-disable-next-line react-hooks/set-state-in-effect
|
|
setBookingState({
|
|
fromDate: storedFrom.format("YYYY-MM-DD"),
|
|
toDate: storedTo.format("YYYY-MM-DD"),
|
|
rooms: stored.rooms,
|
|
})
|
|
}
|
|
}, [])
|
|
return bookingState
|
|
}
|
|
|
|
function getBookingWidgetState(): BookingWidgetState | null {
|
|
if (typeof window === "undefined") {
|
|
return null
|
|
}
|
|
try {
|
|
const savedBookingWidgetState = sessionStorage.getItem(BOOKING_WIDGET_STATE)
|
|
if (savedBookingWidgetState) {
|
|
const stored = JSON.parse(savedBookingWidgetState)
|
|
return stateSchema.parse(stored)
|
|
}
|
|
} catch {
|
|
try {
|
|
sessionStorage.removeItem(BOOKING_WIDGET_STATE)
|
|
} catch {}
|
|
}
|
|
return null
|
|
}
|
|
|
|
export function setBookingWidgetState(state: BookingWidgetState): void {
|
|
if (typeof window === "undefined") {
|
|
return
|
|
}
|
|
try {
|
|
sessionStorage.setItem(
|
|
BOOKING_WIDGET_STATE,
|
|
JSON.stringify(stateSchema.parse(state))
|
|
)
|
|
} catch {}
|
|
}
|
|
|
|
export function clearBookingWidgetState(): void {
|
|
if (typeof window === "undefined") {
|
|
return
|
|
}
|
|
try {
|
|
sessionStorage.removeItem(BOOKING_WIDGET_STATE)
|
|
} catch {}
|
|
}
|