UNPKG

@softr/sdk

Version:

The SDK for building Softr apps on TanStack Start. It lets an app interact with Softr: auth, datasources, workflows and integrations.

356 lines (354 loc) • 11.4 kB
import { logger } from "./logger.js"; import { z } from "zod"; import { Fragment, createContext, createElement, useContext, useMemo, useSyncExternalStore } from "react"; import { rootRouteId, useRouteContext } from "@tanstack/react-router"; //#region src/formatting.ts const DEFAULT_LOCALE = "en-US"; /** The formatting before a request has resolved one. */ function defaultFormatting() { return { dateLocale: DEFAULT_LOCALE, numberLocale: DEFAULT_LOCALE, timeZone: null, fixedDate: null, weekStart: null, language: DEFAULT_LOCALE, rtl: false }; } const localeSettingsSchema = z.object({ dateAndTimeSettings: z.object({ formatSettings: z.object({ type: z.enum(["LOCAL", "FIXED"]), fixedSettings: z.object({ dateFormat: z.enum([ "FRIENDLY", "DD-MM-YYYY", "MM-DD-YYYY", "YYYY-MM-DD" ]).nullish(), dateFormatSeparator: z.enum([ "-", "/", "." ]).nullish(), timeFormat: z.enum(["12", "24"]).nullish(), weekStart: z.literal([ 1, 2, 3, 4, 5, 6, 7 ]).nullish() }).nullish() }), timezoneSettings: z.object({ type: z.enum(["LOCAL", "FIXED"]), fixedTimezone: z.string().nullish() }) }), numberFormattingSettings: z.object({ type: z.enum(["LOCAL", "FIXED"]), fixedLocale: z.string().nullish() }), languageSettings: z.object({ language: z.string().nullish(), rtl: z.boolean() }) }); /** * Combines the app's settings with what the request says about the visitor. * A `FIXED` setting wins. A `LOCAL` one uses the request: `Accept-Language` * for the locale and the `user-timezone` cookie for the zone. */ function resolveFormatting(settings, acceptLanguage, timeZoneCookie) { const language = supportedLocale(settings?.languageSettings.language) ?? DEFAULT_LOCALE; const visitorLocale = firstSupportedLocale(acceptLanguage) ?? language; const format = settings?.dateAndTimeSettings.formatSettings; const fixed = format?.type === "FIXED" ? format.fixedSettings : null; const zone = settings?.dateAndTimeSettings.timezoneSettings; const fixedZone = zone?.type === "FIXED" ? validTimeZone(zone.fixedTimezone) : null; const numbers = settings?.numberFormattingSettings; return { dateLocale: visitorLocale, numberLocale: (numbers?.type === "FIXED" ? supportedLocale(numbers.fixedLocale) : null) ?? visitorLocale, timeZone: fixedZone ?? validTimeZone(timeZoneCookie), fixedDate: fixed?.dateFormat ? { format: fixed.dateFormat, separator: fixed.dateFormatSeparator ?? "-", hour12: fixed.timeFormat === "12" } : null, weekStart: fixed?.dateFormat ? fixed.weekStart ?? 1 : null, language, rtl: settings?.languageSettings.rtl ?? false }; } /** * The day of a date, in the app's format. A timestamp reads in * `formatting.timeZone`, or in UTC while that is unknown. Returns `""` for * `null`, `undefined` or a value that is not a date, so a record's nullable * date field needs no guard. */ function formatDate(value, formatting, options = {}) { return formatDateValue(value, formatting, false, options); } /** * The day and the time of a timestamp, in the app's format and zone. Returns * `""` for `null`, `undefined` or a value that is not a date. In JSX, prefer * `<FormattedDate time />`: on a first visit it waits for the visitor's zone * instead of showing UTC. */ function formatDateTime(value, formatting, options = {}) { return formatDateValue(value, formatting, true, options); } /** A number in the app's number locale. Returns `""` for a value that is not finite. */ function formatNumber(value, formatting, options) { if (!Number.isFinite(value)) return ""; return new Intl.NumberFormat(formatting.numberLocale, options).format(value); } /** * The formatting of this request. On the server and during hydration it is * the one the server resolved. After hydration, a zone the server did not know * yet is filled in from the browser. * * Requires the root route to resolve `getSoftrContext`. */ function useFormatting() { const resolved = useRouteContext({ from: rootRouteId, select: (context) => context.formatting }); const scope = useContext(ScopeContext); const hydrated = useHydrated(); return useMemo(() => { const scoped = { ...resolved, ...scope.timeZone ? { timeZone: scope.timeZone } : {}, ...scope.locale ? { dateLocale: scope.locale, numberLocale: scope.locale, fixedDate: null } : {} }; return scoped.timeZone === null && hydrated ? { ...scoped, timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone } : scoped; }, [ resolved, scope, hydrated ]); } const ScopeContext = createContext({}); /** * Formats every date and number inside it in a zone or a locale the builder names, such as "show * this page in New York time". A known zone renders on the server at once. An inner scope wins over * an outer one. An unknown zone or locale is ignored, because it can come from a record. * * @example * <FormattingScope timeZone="America/New_York"> * <FormattedDate value={event.fields.starts} time /> * </FormattingScope> */ function FormattingScope({ timeZone, locale, children }) { const parent = useContext(ScopeContext); const value = useMemo(() => { const zone = checkedTimeZone(timeZone); const tag = locale === void 0 ? null : supportedLocale(locale); if (locale !== void 0 && tag === null) logger.warn(`FormattingScope ignores the unknown locale "${locale}".`); return { timeZone: zone ?? parent.timeZone, locale: tag ?? parent.locale }; }, [ parent, timeZone, locale ]); return createElement(ScopeContext.Provider, { value }, children); } /** * A date in the app's format, in a `<span>`, safe to render on the server. A * timestamp whose zone is not known yet renders `fallback` until the browser * supplies it, so the visitor never sees a UTC time. A `null` or `undefined` * value renders nothing, so a record's nullable date field needs no guard. * * @example * <FormattedDate value={bug.fields.created} /> * <FormattedDate value={event.fields.starts} time /> */ function FormattedDate({ value, time = false, fallback = null,...options }) { const formatting = useFormatting(); const hydrated = useHydrated(); if (value === null || value === void 0) return null; if (!isCalendarDay(value) && zoneFor(formatting, options) === null) return createElement(Fragment, null, fallback); return createElement("span", { suppressHydrationWarning: true }, !hydrated && typeof document !== "undefined" ? "" : (time ? formatDateTime : formatDate)(value, formatting, options)); } /** * False on the server and while React hydrates, true after. The callbacks live at module level, so React * does not schedule a snapshot check on each render. */ function useHydrated() { return useSyncExternalStore(subscribeNever, snapshotHydrated, snapshotServer); } function subscribeNever() { return () => {}; } function snapshotHydrated() { return true; } function snapshotServer() { return false; } const CALENDAR_DAY = /^\d{4}-\d{2}-\d{2}$/; /** A calendar day such as `2026-10-06` names the same day in every zone, so it needs none. */ function isCalendarDay(value) { return typeof value === "string" && CALENDAR_DAY.test(value); } function formatDateValue(value, formatting, withTime, options) { if (value === null || value === void 0) return ""; const day = isCalendarDay(value); const date = day ? /* @__PURE__ */ new Date(`${value}T00:00:00Z`) : new Date(value); if (Number.isNaN(date.getTime())) return ""; const timeZone = day ? "UTC" : zoneFor(formatting, options) ?? "UTC"; const showTime = withTime && !day; if (options.parts) return new Intl.DateTimeFormat(formatting.dateLocale, { ...options.parts, ...formatting.fixedDate !== null ? { hour12: formatting.fixedDate.hour12 } : {}, timeZone }).format(date); if (formatting.fixedDate !== null) return formatFixed(date, timeZone, showTime, formatting.fixedDate); if (options.dateStyle) return new Intl.DateTimeFormat(formatting.dateLocale, { dateStyle: options.dateStyle, ...showTime ? { timeStyle: "short" } : {}, timeZone }).format(date); return new Intl.DateTimeFormat(formatting.dateLocale, { year: "numeric", month: "numeric", day: "numeric", ...showTime ? { hour: "numeric", minute: "numeric" } : {}, timeZone }).format(date); } const MONTHS = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]; function formatFixed(date, timeZone, showTime, fixed) { const parts = new Intl.DateTimeFormat("en-US", { timeZone, year: "numeric", month: "numeric", day: "numeric", hour: "numeric", minute: "numeric", hourCycle: "h23" }).formatToParts(date); const part = (type) => Number(parts.find((p) => p.type === type)?.value ?? NaN); const [year, month, day, hour, minute] = [ part("year"), part("month"), part("day"), part("hour"), part("minute") ]; const sep = fixed.separator; const text = { FRIENDLY: `${MONTHS[month - 1]} ${ordinal(day)}, ${year}`, "DD-MM-YYYY": [ pad(day), pad(month), year ].join(sep), "MM-DD-YYYY": [ pad(month), pad(day), year ].join(sep), "YYYY-MM-DD": [ year, pad(month), pad(day) ].join(sep) }[fixed.format]; if (!showTime) return text; if (!fixed.hour12) return `${text} ${pad(hour)}:${pad(minute)}`; return `${text} ${pad(hour % 12 === 0 ? 12 : hour % 12)}:${pad(minute)} ${hour < 12 ? "AM" : "PM"}`; } function pad(value) { return String(value).padStart(2, "0"); } function ordinal(day) { if (day % 100 >= 11 && day % 100 <= 13) return `${day}th`; return `${day}${[ "th", "st", "nd", "rd" ][day % 10] ?? "th"}`; } /** The first locale in an `Accept-Language` header that `Intl` supports, by weight. */ function firstSupportedLocale(header) { if (!header) return null; const ranked = header.split(",").map((entry, index) => { const [tag = "", ...params] = entry.trim().split(";"); const q = params.map((p) => p.trim()).find((p) => p.startsWith("q=")); const weight = q === void 0 ? 1 : Number(q.slice(2)); return { tag: tag.trim(), weight: Number.isNaN(weight) ? 0 : weight, index }; }).filter((entry) => entry.tag !== "" && entry.tag !== "*" && entry.weight > 0).sort((a, b) => b.weight - a.weight || a.index - b.index); for (const { tag } of ranked) { const locale = supportedLocale(tag); if (locale !== null) return locale; } return null; } function supportedLocale(tag) { if (!tag) return null; try { return Intl.DateTimeFormat.supportedLocalesOf(tag)[0] ?? null; } catch { return null; } } /** The zone a value reads in: the one the call names, else the formatting's, else `null` while unknown. */ function zoneFor(formatting, options) { return checkedTimeZone(options.timeZone) ?? formatting.timeZone; } /** `validTimeZone` for a zone the app's code names. It warns, so a typo shows in the logs. */ function checkedTimeZone(zone) { if (zone === void 0) return null; const valid = validTimeZone(zone); if (valid === null) logger.warn(`Ignoring the unknown time zone "${zone}".`); return valid; } function validTimeZone(zone) { if (!zone) return null; try { return new Intl.DateTimeFormat("en-US", { timeZone: zone }).resolvedOptions().timeZone; } catch { return null; } } //#endregion export { FormattedDate, FormattingScope, defaultFormatting, formatDate, formatDateTime, formatNumber, localeSettingsSchema, resolveFormatting, useFormatting };