UNPKG

@intility/bifrost-react

Version:

React library for Intility's design system, Bifrost.

66 lines (65 loc) 1.87 kB
import { c as _c } from "react-compiler-runtime"; import { useCallback } from "react"; import useLocale from "./useLocale.js"; // cache each formatter as it is created const formattersCache = {}; function getDateFormatter(locale, options) { // is this actually less expensive than creating a new formatter? const key = JSON.stringify({ locale, options }); let formatter = formattersCache[key]; if (!formatter || typeof formatter.format !== "function") { formatter = new Intl.DateTimeFormat(locale, options); formattersCache[key] = formatter; } return formatter; } /** * Context-aware date and time formatter using locale and options from the * current Bifrost context unless specified * * @returns A function that formats a date and/or time * * @see https://bifrost.intility.com/react/useDateTimeFormatter * * @example * const dateTimeFormatter = useDateTimeFormatter(); * * // "04/03/2024" * const formattedDate = dateTimeFormatter({ * show: "date", * date: "2024-03-04T10:23:11.408Z", * }); */ export default function useDateTimeFormatter() { const $ = _c(2); const { dateOptions } = useLocale(); let t0; if ($[0] !== dateOptions) { t0 = function dateTimeFormatter(t1) { let { date, show, locale, options } = t1; date = typeof date === "string" ? new Date(date) : date; show = show ?? "date"; locale = locale ?? dateOptions.locale; options = options ?? (show === "date" ? dateOptions.date : show === "time" ? dateOptions.time : { ...dateOptions.time, ...dateOptions.date }); return show === "date" ? getDateFormatter(locale, options).format(date) : getDateFormatter(locale, options).format(date).replace(",", ""); }; $[0] = dateOptions; $[1] = t0; } else { t0 = $[1]; } return t0; }