chore(SW-3397) Moved Confirmation component with Header to booking-flow package * chore(SW-3397) Moved Confirmation component with Header to booking-flow package * chore(SW-3397): Optimised code Approved-by: Anton Gunnarsson
69 lines
1.9 KiB
TypeScript
69 lines
1.9 KiB
TypeScript
"use client"
|
|
import { createEvent, type EventAttributes } from "ics"
|
|
import { useIntl } from "react-intl"
|
|
|
|
import { dt } from "@scandic-hotels/common/dt"
|
|
import { logger } from "@scandic-hotels/common/logger"
|
|
import { toast } from "@scandic-hotels/design-system/Toast"
|
|
|
|
import useLang from "../../hooks/useLang"
|
|
|
|
import type { RouterOutput } from "@scandic-hotels/trpc/client"
|
|
|
|
type AddToCalendarProps = {
|
|
checkInDate: NonNullable<
|
|
RouterOutput["booking"]["get"]
|
|
>["booking"]["checkInDate"]
|
|
event: EventAttributes
|
|
hotelName: NonNullable<RouterOutput["booking"]["get"]>["hotel"]["name"]
|
|
renderButton: (onPress: () => Promise<void>) => React.ReactNode
|
|
}
|
|
|
|
export function AddToCalendar({
|
|
checkInDate,
|
|
event,
|
|
hotelName,
|
|
renderButton,
|
|
}: AddToCalendarProps) {
|
|
const lang = useLang()
|
|
const intl = useIntl()
|
|
|
|
async function downloadBooking() {
|
|
try {
|
|
const d = dt(checkInDate).locale(lang).format("YYYY-MM-DD")
|
|
const filename = `${hotelName.toLowerCase().split(" ").join("_")}-${d}.ics`
|
|
|
|
createEvent(event, (error, value) => {
|
|
if (error) {
|
|
logger.error("ICS Error:", error)
|
|
toast.error(
|
|
intl.formatMessage({
|
|
defaultMessage: "Failed to add to calendar",
|
|
})
|
|
)
|
|
return
|
|
}
|
|
|
|
const file = new File([value], filename, { type: "text/calendar" })
|
|
const url = URL.createObjectURL(file)
|
|
const anchor = document.createElement("a")
|
|
anchor.href = url
|
|
anchor.download = filename
|
|
document.body.appendChild(anchor)
|
|
anchor.click()
|
|
document.body.removeChild(anchor)
|
|
URL.revokeObjectURL(url)
|
|
})
|
|
} catch (error) {
|
|
logger.error("Download error:", error)
|
|
toast.error(
|
|
intl.formatMessage({
|
|
defaultMessage: "Failed to add to calendar",
|
|
})
|
|
)
|
|
}
|
|
}
|
|
|
|
return renderButton(downloadBooking)
|
|
}
|