Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

✨ Add Intl-based date/time localization, wired into (space) (#2512)

Luke Vella26a2f3a391f4
diff --git a/apps/web/src/app/[locale]/(space)/(dashboard)/events/events-infinite-list.tsx b/apps/web/src/app/[locale]/(space)/(dashboard)/events/events-infinite-list.tsx
index e4f65ec6f..bd772cde5 100644
--- a/apps/web/src/app/[locale]/(space)/(dashboard)/events/events-infinite-list.tsx
+++ b/apps/web/src/app/[locale]/(space)/(dashboard)/events/events-infinite-list.tsx
@@ -96,9 +96,9 @@ export function EventsInfiniteList({
<StackedListItem key={event.id}>
<ScheduledEventListItem
eventId={event.id}
- floating={!event.timeZone}
title={event.title}
start={event.start}
+ timeZone={event.timeZone}
end={event.end}
allDay={event.allDay}
invites={event.invites}
diff --git a/apps/web/src/app/[locale]/(space)/layout.tsx b/apps/web/src/app/[locale]/(space)/layout.tsx
index 491b500e3..71d311c38 100644
--- a/apps/web/src/app/[locale]/(space)/layout.tsx
+++ b/apps/web/src/app/[locale]/(space)/layout.tsx
@@ -1,9 +1,12 @@
import { dehydrate, HydrationBoundary } from "@tanstack/react-query";
import { redirect } from "next/navigation";
+import { TimeZoneChangeDetector } from "@/app/[locale]/timezone-change-detector";
import { SessionRefresher } from "@/components/session-refresher";
-import { PreferencesProvider } from "@/contexts/preferences";
import { PayWall } from "@/features/billing/components/pay-wall";
import { SpaceProvider } from "@/features/space/client";
+import { getLocale } from "@/i18n/server/get-locale";
+import { DateTimeProvider } from "@/lib/datetime/client";
+import { LocaleSync } from "@/lib/locale/client";
import { getPathname } from "@/lib/pathname";
import { createPrivateSSRHelper } from "@/trpc/server/create-ssr-helper";
import { buildSafeRedirectUrl } from "@/utils/redirect";
@@ -13,11 +16,13 @@ export default async function Layout({
}: {
children: React.ReactNode;
}) {
+ const locale = await getLocale();
const helpers = await createPrivateSSRHelper();
- await Promise.all([helpers.user.getMe.prefetch()]);
-
- const space = await helpers.spaces.getCurrent.fetch();
+ const [user, space] = await Promise.all([
+ helpers.user.getMe.fetch(),
+ helpers.spaces.getCurrent.fetch(),
+ ]);
if (!space) {
const pathname = await getPathname();
@@ -29,12 +34,18 @@ export default async function Layout({
return (
<HydrationBoundary state={dehydrate(helpers.queryClient)}>
<SessionRefresher />
- <PreferencesProvider>
+ <LocaleSync userLocale={user?.locale} />
+ <TimeZoneChangeDetector initialTimeZone={user?.timeZone} />
+ <DateTimeProvider
+ locale={locale}
+ timeZone={user?.timeZone}
+ timeFormat={user?.timeFormat}
+ >
<SpaceProvider>
{children}
<PayWall />
</SpaceProvider>
- </PreferencesProvider>
+ </DateTimeProvider>
</HydrationBoundary>
);
}
diff --git a/apps/web/src/app/[locale]/(space)/settings/preferences/components/date-time-preferences.tsx b/apps/web/src/app/[locale]/(space)/settings/preferences/components/date-time-preferences.tsx
index 4fb1989c7..957cae9fa 100644
--- a/apps/web/src/app/[locale]/(space)/settings/preferences/components/date-time-preferences.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/preferences/components/date-time-preferences.tsx
@@ -1,4 +1,7 @@
+"use client";
+
import { zodResolver } from "@hookform/resolvers/zod";
+import type { TimeFormat } from "@rallly/database";
import { Button } from "@rallly/ui/button";
import {
Form,
@@ -18,11 +21,13 @@ import { useForm } from "react-hook-form";
import * as z from "zod";
import { TimeFormatPicker } from "@/components/time-format-picker";
import { TimeZoneSelect } from "@/components/time-zone-picker/time-zone-select";
-import { usePreferences } from "@/contexts/preferences";
+import { updateLocalizationAction } from "@/features/user/actions";
import { Trans } from "@/i18n/client";
+import { getLocaleDefaults } from "@/lib/datetime/locales";
import { dayjs } from "@/lib/dayjs";
-import { useTimezone } from "@/lib/timezone/client/context";
-import { useDayjs } from "@/utils/dayjs";
+import { useLocale } from "@/lib/locale/client";
+import { useSafeAction } from "@/lib/safe-action/client";
+import { getBrowserTimeZone } from "@/utils/date-time-utils";
const formSchema = z.object({
timeFormat: z.enum(["hours12", "hours24"]),
@@ -30,17 +35,25 @@ const formSchema = z.object({
weekStart: z.number().min(0).max(6),
});
-export const DateTimePreferences = () => {
- const { timezone } = useTimezone();
- const { timeFormat, weekStart } = useDayjs();
- const { updatePreferences } = usePreferences();
+export const DateTimePreferences = ({
+ initialValues,
+}: {
+ initialValues: {
+ timeFormat?: TimeFormat;
+ timeZone?: string;
+ weekStart?: number;
+ };
+}) => {
+ const updateLocalization = useSafeAction(updateLocalizationAction);
+ const { locale } = useLocale();
+ const localeDefaults = getLocaleDefaults(locale);
const form = useForm({
resolver: zodResolver(formSchema),
defaultValues: {
- timeFormat,
- weekStart,
- timeZone: timezone,
+ timeFormat: initialValues.timeFormat ?? localeDefaults.timeFormat,
+ weekStart: initialValues.weekStart ?? localeDefaults.weekStart,
+ timeZone: initialValues.timeZone ?? getBrowserTimeZone(),
},
});
@@ -50,8 +63,10 @@ export const DateTimePreferences = () => {
<Form {...form}>
<form
onSubmit={handleSubmit(async (data) => {
- updatePreferences(data);
- form.reset(data);
+ const result = await updateLocalization.executeAsync(data);
+ if (!result?.serverError && !result?.validationErrors) {
+ form.reset(data);
+ }
})}
>
<div className="space-y-6">
@@ -107,7 +122,7 @@ export const DateTimePreferences = () => {
field.onChange(Number.parseInt(value, 10));
}}
>
- <SelectTrigger className="w-fit">
+ <SelectTrigger className="w-fit min-w-32">
<SelectValue />
</SelectTrigger>
<SelectContent>
diff --git a/apps/web/src/app/[locale]/(space)/settings/preferences/components/language-preference.tsx b/apps/web/src/app/[locale]/(space)/settings/preferences/components/language-preference.tsx
index ffdec824e..9a5a60a10 100644
--- a/apps/web/src/app/[locale]/(space)/settings/preferences/components/language-preference.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/preferences/components/language-preference.tsx
@@ -1,3 +1,5 @@
+"use client";
+
import { zodResolver } from "@hookform/resolvers/zod";
import { buttonVariants } from "@rallly/ui";
import { Button } from "@rallly/ui/button";
@@ -13,7 +15,6 @@ import Link from "next/link";
import { useForm } from "react-hook-form";
import * as z from "zod";
import { LanguageSelect } from "@/components/poll/language-selector";
-import { useUser } from "@/components/user-provider";
import { Trans } from "@/i18n/client";
import { useLocale } from "@/lib/locale/client";
import { trpc } from "@/trpc/client";
@@ -22,8 +23,11 @@ const formSchema = z.object({
language: z.string(),
});
-export const LanguagePreference = () => {
- const { user } = useUser();
+export const LanguagePreference = ({
+ defaultValue,
+}: {
+ defaultValue?: string;
+}) => {
const { locale, changeLocale } = useLocale();
const updateLocale = trpc.user.updateLocale.useMutation({
onSuccess: (_data, variables) => {
@@ -32,7 +36,7 @@ export const LanguagePreference = () => {
});
const form = useForm({
defaultValues: {
- language: user?.locale ?? locale,
+ language: defaultValue ?? locale,
},
resolver: zodResolver(formSchema),
});
@@ -54,7 +58,7 @@ export const LanguagePreference = () => {
</FormLabel>
<FormControl>
<LanguageSelect
- className="w-fit"
+ className="w-fit min-w-32"
value={field.value}
onChange={field.onChange}
/>
diff --git a/apps/web/src/app/[locale]/(space)/settings/preferences/components/theme-preference.tsx b/apps/web/src/app/[locale]/(space)/settings/preferences/components/theme-preference.tsx
index 7a76e3fec..0085bea5d 100644
--- a/apps/web/src/app/[locale]/(space)/settings/preferences/components/theme-preference.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/preferences/components/theme-preference.tsx
@@ -2,6 +2,7 @@
import { RadioGroup, RadioGroupItem } from "@rallly/ui/radio-group";
import { MonitorIcon, MoonIcon, SunIcon } from "lucide-react";
+import React from "react";
import { useTheme } from "@/features/theme/client";
import { Trans } from "@/i18n/client";
@@ -30,10 +31,15 @@ function ThemeOptionLabel({ children }: { children: React.ReactNode }) {
export function ThemePreference() {
const { theme, setTheme } = useTheme();
+ const [mounted, setMounted] = React.useState(false);
+
+ React.useEffect(() => {
+ setMounted(true);
+ }, []);
return (
<RadioGroup
- value={theme}
+ value={mounted ? theme : undefined}
onValueChange={setTheme}
className="flex flex-wrap gap-2"
>
diff --git a/apps/web/src/app/[locale]/(space)/settings/preferences/page.tsx b/apps/web/src/app/[locale]/(space)/settings/preferences/page.tsx
index 7e1d2eede..77780b3eb 100644
--- a/apps/web/src/app/[locale]/(space)/settings/preferences/page.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/preferences/page.tsx
@@ -1,5 +1,16 @@
import type { Metadata } from "next";
+import { DateTimePreferences } from "@/app/[locale]/(space)/settings/preferences/components/date-time-preferences";
+import { LanguagePreference } from "@/app/[locale]/(space)/settings/preferences/components/language-preference";
+import { ThemePreference } from "@/app/[locale]/(space)/settings/preferences/components/theme-preference";
import type { Params } from "@/app/[locale]/types";
+import {
+ PageSection,
+ PageSectionContent,
+ PageSectionDescription,
+ PageSectionGroup,
+ PageSectionHeader,
+ PageSectionTitle,
+} from "@/app/components/page-layout";
import {
SettingsPage,
SettingsPageContent,
@@ -7,11 +18,18 @@ import {
SettingsPageHeader,
SettingsPageTitle,
} from "@/app/components/settings-layout";
+import { getCurrentUser } from "@/auth/data";
import { Trans } from "@/i18n/client";
import { getTranslation } from "@/i18n/server";
-import { PreferencesPage } from "./preferences-page";
+import { InvalidSessionError } from "@/lib/errors/invalid-session-error";
export default async function Page() {
+ const user = await getCurrentUser();
+
+ if (!user) {
+ throw new InvalidSessionError();
+ }
+
return (
<SettingsPage>
<SettingsPageHeader>
@@ -26,7 +44,64 @@ export default async function Page() {
</SettingsPageDescription>
</SettingsPageHeader>
<SettingsPageContent>
- <PreferencesPage />
+ <PageSectionGroup>
+ <PageSection variant="card">
+ <PageSectionHeader>
+ <PageSectionTitle>
+ <Trans i18nKey="language" defaults="Language" />
+ </PageSectionTitle>
+ <PageSectionDescription>
+ <Trans
+ i18nKey="languageDescription"
+ defaults="Change your preferred language"
+ />
+ </PageSectionDescription>
+ </PageSectionHeader>
+ <PageSectionContent>
+ <LanguagePreference defaultValue={user.locale} />
+ </PageSectionContent>
+ </PageSection>
+
+ <PageSection variant="card">
+ <PageSectionHeader>
+ <PageSectionTitle>
+ <Trans i18nKey="theme" defaults="Theme" />
+ </PageSectionTitle>
+ <PageSectionDescription>
+ <Trans
+ i18nKey="themeDescription"
+ defaults="Choose your preferred appearance"
+ />
+ </PageSectionDescription>
+ </PageSectionHeader>
+ <PageSectionContent>
+ <ThemePreference />
+ </PageSectionContent>
+ </PageSection>
+
+ <PageSection variant="card">
+ <PageSectionHeader>
+ <PageSectionTitle>
+ <Trans i18nKey="dateAndTime" defaults="Date & Time" />
+ </PageSectionTitle>
+ <PageSectionDescription>
+ <Trans
+ i18nKey="dateAndTimeDescription"
+ defaults="Change your preferred date and time settings"
+ />
+ </PageSectionDescription>
+ </PageSectionHeader>
+ <PageSectionContent>
+ <DateTimePreferences
+ initialValues={{
+ timeFormat: user.timeFormat,
+ timeZone: user.timeZone,
+ weekStart: user.weekStart,
+ }}
+ />
+ </PageSectionContent>
+ </PageSection>
+ </PageSectionGroup>
</SettingsPageContent>
</SettingsPage>
);
diff --git a/apps/web/src/app/[locale]/(space)/settings/preferences/preferences-page.tsx b/apps/web/src/app/[locale]/(space)/settings/preferences/preferences-page.tsx
deleted file mode 100644
index 92319361a..000000000
--- a/apps/web/src/app/[locale]/(space)/settings/preferences/preferences-page.tsx
+++ /dev/null
@@ -1,77 +0,0 @@
-"use client";
-
-import dynamic from "next/dynamic";
-import {
- PageSection,
- PageSectionContent,
- PageSectionDescription,
- PageSectionGroup,
- PageSectionHeader,
- PageSectionTitle,
-} from "@/app/components/page-layout";
-import { Trans } from "@/i18n/client";
-import { DateTimePreferences } from "./components/date-time-preferences";
-import { LanguagePreference } from "./components/language-preference";
-import { ThemePreference } from "./components/theme-preference";
-
-export const PreferencesPage = dynamic(
- () => Promise.resolve({ default: PreferencesPageInner }),
- { ssr: false },
-);
-
-function PreferencesPageInner() {
- return (
- <PageSectionGroup>
- <PageSection variant="card">
- <PageSectionHeader>
- <PageSectionTitle>
- <Trans i18nKey="language" defaults="Language" />
- </PageSectionTitle>
- <PageSectionDescription>
- <Trans
- i18nKey="languageDescription"
- defaults="Change your preferred language"
- />
- </PageSectionDescription>
- </PageSectionHeader>
- <PageSectionContent>
- <LanguagePreference />
- </PageSectionContent>
- </PageSection>
-
- <PageSection variant="card">
- <PageSectionHeader>
- <PageSectionTitle>
- <Trans i18nKey="theme" defaults="Theme" />
- </PageSectionTitle>
- <PageSectionDescription>
- <Trans
- i18nKey="themeDescription"
- defaults="Choose your preferred appearance"
- />
- </PageSectionDescription>
- </PageSectionHeader>
- <PageSectionContent>
- <ThemePreference />
- </PageSectionContent>
- </PageSection>
-
- <PageSection variant="card">
- <PageSectionHeader>
- <PageSectionTitle>
- <Trans i18nKey="dateAndTime" defaults="Date & Time" />
- </PageSectionTitle>
- <PageSectionDescription>
- <Trans
- i18nKey="dateAndTimeDescription"
- defaults="Change your preferred date and time settings"
- />
- </PageSectionDescription>
- </PageSectionHeader>
- <PageSectionContent>
- <DateTimePreferences />
- </PageSectionContent>
- </PageSection>
- </PageSectionGroup>
- );
-}
diff --git a/apps/web/src/app/[locale]/timezone-change-detector.test.tsx b/apps/web/src/app/[locale]/timezone-change-detector.test.tsx
index 785ae3cc7..830d24e5a 100644
--- a/apps/web/src/app/[locale]/timezone-change-detector.test.tsx
+++ b/apps/web/src/app/[locale]/timezone-change-detector.test.tsx
@@ -9,10 +9,17 @@ vi.mock("@/utils/date-time-utils", () => ({
getBrowserTimeZone: () => mockTimeZone,
}));
+const { mockExecute } = vi.hoisted(() => ({ mockExecute: vi.fn() }));
+vi.mock("@/features/user/actions", () => ({ updateLocalizationAction: {} }));
+vi.mock("@/lib/safe-action/client", () => ({
+ useSafeAction: () => ({ execute: mockExecute }),
+}));
+
describe("TimeZoneChangeDetector", () => {
beforeEach(() => {
localStorage.clear();
mockTimeZone = "America/New_York";
+ mockExecute.mockClear();
});
afterEach(() => {
@@ -32,27 +39,25 @@ describe("TimeZoneChangeDetector", () => {
expect(screen.getByText("Timezone Change Detected")).toBeInTheDocument();
});
- it("accepting timezone change calls onTimeZoneChange and updates localStorage", async () => {
+ it("accepting the change updates the localization and localStorage", async () => {
const user = userEvent.setup();
- const mockOnTimeZoneChange = vi.fn();
localStorage.setItem("previousTimeZone", "Fake/Timezone");
- render(<TimeZoneChangeDetector onTimeZoneChange={mockOnTimeZoneChange} />);
+ render(<TimeZoneChangeDetector />);
await user.click(screen.getByText("Yes, update my timezone"));
- expect(mockOnTimeZoneChange).toHaveBeenCalledWith("America/New_York");
+ expect(mockExecute).toHaveBeenCalledWith({ timeZone: "America/New_York" });
expect(localStorage.getItem("previousTimeZone")).toBe("America/New_York");
});
- it("declining timezone change updates localStorage without calling onTimeZoneChange", async () => {
+ it("declining the change updates localStorage without updating localization", async () => {
const user = userEvent.setup();
- const mockOnTimeZoneChange = vi.fn();
localStorage.setItem("previousTimeZone", "Fake/Timezone");
- render(<TimeZoneChangeDetector onTimeZoneChange={mockOnTimeZoneChange} />);
+ render(<TimeZoneChangeDetector />);
await user.click(screen.getByText("No, keep the current timezone"));
- expect(mockOnTimeZoneChange).not.toHaveBeenCalled();
+ expect(mockExecute).not.toHaveBeenCalled();
expect(localStorage.getItem("previousTimeZone")).toBe("America/New_York");
});
diff --git a/apps/web/src/app/[locale]/timezone-change-detector.tsx b/apps/web/src/app/[locale]/timezone-change-detector.tsx
index bd4dc5b6f..5475798e8 100644
--- a/apps/web/src/app/[locale]/timezone-change-detector.tsx
+++ b/apps/web/src/app/[locale]/timezone-change-detector.tsx
@@ -1,3 +1,5 @@
+"use client";
+
import { Button } from "@rallly/ui/button";
import {
Dialog,
@@ -7,21 +9,23 @@ import {
DialogTitle,
} from "@rallly/ui/dialog";
import React, { useState } from "react";
+import { updateLocalizationAction } from "@/features/user/actions";
import { Trans } from "@/i18n/client";
+import { useSafeAction } from "@/lib/safe-action/client";
import { getBrowserTimeZone } from "@/utils/date-time-utils";
import { safeLocalStorage } from "@/utils/local-storage";
export function TimeZoneChangeDetector({
initialTimeZone,
- onTimeZoneChange,
}: {
initialTimeZone?: string;
- onTimeZoneChange?: (timeZone: string) => void;
}) {
const [open, setOpen] = useState(false);
const currentTimeZone = getBrowserTimeZone();
+ const updateLocalization = useSafeAction(updateLocalizationAction);
+
const [previousTimeZone, setPreviousTimeZone] = useState(() => {
const cachedPreviousTimeZone = safeLocalStorage.getItem("previousTimeZone");
if (cachedPreviousTimeZone) {
@@ -65,7 +69,9 @@ export function TimeZoneChangeDetector({
variant="primary"
onClick={() => {
safeLocalStorage.setItem("previousTimeZone", currentTimeZone);
- onTimeZoneChange?.(currentTimeZone);
+ updateLocalization.execute({
+ timeZone: currentTimeZone,
+ });
setOpen(false);
}}
>
diff --git a/apps/web/src/components/clock.tsx b/apps/web/src/components/clock.tsx
index 8d761b7cd..c73cbfa9b 100644
--- a/apps/web/src/components/clock.tsx
+++ b/apps/web/src/components/clock.tsx
@@ -23,7 +23,7 @@ import { Trans } from "@/i18n/client";
import { dayjs } from "@/lib/dayjs";
import { useDayjs } from "@/utils/dayjs";
-export const TimePreferences = () => {
+const TimePreferences = () => {
const { updatePreferences } = usePreferences();
const { timeFormat, timeZone } = useDayjs();
@@ -55,7 +55,7 @@ export const TimePreferences = () => {
);
};
-export const Clock = ({ className }: { className?: string }) => {
+const Clock = ({ className }: { className?: string }) => {
const { timeZone, timeFormat } = useDayjs();
const timeZoneDisplayFormat = soft(timeZone)[0];
const now = spacetime.now(timeZone);
@@ -75,23 +75,7 @@ export const Clock = ({ className }: { className?: string }) => {
);
};
-export const TimesShownIn = () => {
- const { timeZone } = useDayjs();
- return (
- <ClockPreferences>
- <Button type="button" variant="ghost">
- <GlobeIcon data-icon="inline-start" />
- <Trans
- i18nKey="cityTime"
- defaults="{city} Time"
- values={{ city: getCityFromTimezoneId(timeZone) }}
- />
- </Button>
- </ClockPreferences>
- );
-};
-
-export const ClockPreferences = ({ children }: React.PropsWithChildren) => {
+const ClockPreferences = ({ children }: React.PropsWithChildren) => {
return (
<Dialog modal={false}>
<DialogTrigger asChild>{children}</DialogTrigger>
@@ -115,3 +99,19 @@ export const ClockPreferences = ({ children }: React.PropsWithChildren) => {
</Dialog>
);
};
+
+export const TimesShownIn = () => {
+ const { timeZone } = useDayjs();
+ return (
+ <ClockPreferences>
+ <Button type="button" variant="ghost">
+ <GlobeIcon data-icon="inline-start" />
+ <Trans
+ i18nKey="cityTime"
+ defaults="{city} Time"
+ values={{ city: getCityFromTimezoneId(timeZone) }}
+ />
+ </Button>
+ </ClockPreferences>
+ );
+};
diff --git a/apps/web/src/contexts/preferences.tsx b/apps/web/src/contexts/preferences.tsx
index dae3e6a4f..11c6f4f9d 100644
--- a/apps/web/src/contexts/preferences.tsx
+++ b/apps/web/src/contexts/preferences.tsx
@@ -4,7 +4,6 @@ import type { TimeFormat } from "@rallly/database";
import React from "react";
import { useLocalStorage } from "react-use";
import * as z from "zod";
-import { TimeZoneChangeDetector } from "@/app/[locale]/timezone-change-detector";
import { useRequiredContext } from "@/components/use-required-context";
import { LocaleSync, useLocale } from "@/lib/locale/client";
import { trpc } from "@/trpc/client";
@@ -95,12 +94,6 @@ export const PreferencesProvider = ({
}}
>
{children}
- <TimeZoneChangeDetector
- initialTimeZone={preferences.timeZone}
- onTimeZoneChange={(timeZone) => {
- updatePreferences({ timeZone });
- }}
- />
<LocaleSync userLocale={user?.locale} />
</DayjsProvider>
</PreferencesContext.Provider>
diff --git a/apps/web/src/features/scheduled-event/components/event-date-time.tsx b/apps/web/src/features/scheduled-event/components/event-date-time.tsx
new file mode 100644
index 000000000..02e998fe7
--- /dev/null
+++ b/apps/web/src/features/scheduled-event/components/event-date-time.tsx
@@ -0,0 +1,77 @@
+"use client";
+
+import { Trans } from "@/i18n/client";
+import { CalendarDate } from "@/lib/datetime/calendar-date";
+import type { DateInput, DatePreset } from "@/lib/datetime/format";
+import { Time, TimeRange } from "@/lib/datetime/time";
+
+/**
+ * Raw scheduling fields as stored on a scheduled event. `timeZone` is
+ * required so callers can't drop the null (floating) case: null means the
+ * stored wall time is shown as-is to everyone; a set zone means a fixed
+ * instant shown in the viewer's time zone.
+ */
+type SchedulingFields = {
+ allDay: boolean;
+ timeZone: string | null;
+};
+
+export function EventDate({
+ value,
+ allDay,
+ timeZone,
+ preset = "dateLong",
+ className,
+}: SchedulingFields & {
+ value: DateInput;
+ preset?: DatePreset;
+ className?: string;
+}) {
+ if (allDay) {
+ return <CalendarDate value={value} preset={preset} className={className} />;
+ }
+ if (timeZone === null) {
+ return (
+ <Time
+ value={value}
+ preset={preset}
+ timeZone="UTC"
+ showTimeZone={false}
+ className={className}
+ />
+ );
+ }
+ return <Time value={value} preset={preset} className={className} />;
+}
+
+export function EventTimeRange({
+ start,
+ end,
+ allDay,
+ timeZone,
+ className,
+}: SchedulingFields & {
+ start: DateInput;
+ end: DateInput;
+ className?: string;
+}) {
+ if (allDay) {
+ return (
+ <span className={className}>
+ <Trans i18nKey="allDay" defaults="All day" />
+ </span>
+ );
+ }
+ if (timeZone === null) {
+ return (
+ <TimeRange
+ start={start}
+ end={end}
+ timeZone="UTC"
+ showTimeZone={false}
+ className={className}
+ />
+ );
+ }
+ return <TimeRange start={start} end={end} className={className} />;
+}
diff --git a/apps/web/src/features/scheduled-event/components/scheduled-event-list.tsx b/apps/web/src/features/scheduled-event/components/scheduled-event-list.tsx
index 2c3e2898c..99cba4726 100644
--- a/apps/web/src/features/scheduled-event/components/scheduled-event-list.tsx
+++ b/apps/web/src/features/scheduled-event/components/scheduled-event-list.tsx
@@ -27,9 +27,12 @@ import { MoreVerticalIcon } from "lucide-react";
import { CopyLinkButton } from "@/components/copy-link-button";
import { OptimizedAvatarImage } from "@/components/optimized-avatar-image";
import { StackedList } from "@/components/stacked-list";
+import {
+ EventDate,
+ EventTimeRange,
+} from "@/features/scheduled-event/components/event-date-time";
import { isScheduledEventEnabled } from "@/features/scheduled-event/constants";
import { Trans, useTranslation } from "@/i18n/client";
-import { FormattedDateTime } from "@/lib/timezone/client/formatted-date-time";
import { trpc } from "@/trpc/client";
export const ScheduledEventList = StackedList;
@@ -41,7 +44,7 @@ export function ScheduledEventListItem({
end,
allDay,
invites,
- floating: isFloating,
+ timeZone,
status,
createdBy,
}: {
@@ -50,9 +53,9 @@ export function ScheduledEventListItem({
status: ScheduledEventStatus;
start: Date;
end: Date;
+ timeZone: string | null;
allDay: boolean;
invites: { id: string; inviteeName: string; inviteeImage?: string }[];
- floating: boolean;
createdBy: { name: string; image?: string };
}) {
const { t } = useTranslation();
@@ -62,6 +65,7 @@ export function ScheduledEventListItem({
dialog.dismiss();
},
});
+
return (
<div className="flex w-full gap-6">
<div className="flex flex-1 flex-col gap-y-1 lg:flex-row-reverse lg:justify-end lg:gap-x-4">
@@ -115,33 +119,18 @@ export function ScheduledEventListItem({
</div>
</div>
</div>
- <div className="flex items-center whitespace-nowrap text-sm lg:min-w-40">
+ <div className="flex items-center whitespace-nowrap text-sm lg:min-w-48">
<div>
- <div>
- <FormattedDateTime
- date={start}
- floating={isFloating}
- format="LL"
- />
+ <div className="font-medium">
+ <EventDate value={start} allDay={allDay} timeZone={timeZone} />
</div>
- <div className="mt-1 text-muted-foreground">
- {allDay ? (
- <Trans i18nKey="allDay" defaults="All day" />
- ) : (
- <div className="flex items-center gap-x-1">
- <FormattedDateTime
- date={start}
- floating={isFloating}
- format="LT"
- />
- <span>-</span>
- <FormattedDateTime
- date={end}
- floating={isFloating}
- format="LT"
- />
- </div>
- )}
+ <div className="text-muted-foreground">
+ <EventTimeRange
+ start={start}
+ end={end}
+ allDay={allDay}
+ timeZone={timeZone}
+ />
</div>
</div>
</div>
diff --git a/apps/web/src/features/user/actions.ts b/apps/web/src/features/user/actions.ts
index 30e524675..120571507 100644
--- a/apps/web/src/features/user/actions.ts
+++ b/apps/web/src/features/user/actions.ts
@@ -1,14 +1,12 @@
"use server";
import { subject } from "@casl/ability";
import { prisma } from "@rallly/database";
+import { headers } from "next/headers";
import * as z from "zod";
-import {
- updateUserImage,
- updateUserLocalization,
- updateUserName,
-} from "@/features/user/mutations";
+import { updateUserImage, updateUserName } from "@/features/user/mutations";
+import authLib from "@/lib/auth";
+import { timeFormatSchema, weekStartSchema } from "@/lib/datetime/schema";
import { AppError } from "@/lib/errors";
-import { timeFormatSchema, weekStartSchema } from "@/lib/localization/schema";
import {
adminActionClient,
authActionClient,
@@ -40,12 +38,14 @@ export const updateLocalizationAction = authActionClient
weekStart: weekStartSchema.optional(),
}),
)
- .action(async ({ ctx, parsedInput }) => {
- await updateUserLocalization({
- userId: ctx.user.id,
- timeZone: parsedInput.timeZone,
- timeFormat: parsedInput.timeFormat,
- weekStart: parsedInput.weekStart,
+ .action(async ({ parsedInput }) => {
+ await authLib.api.updateUser({
+ body: {
+ timeZone: parsedInput.timeZone,
+ timeFormat: parsedInput.timeFormat,
+ weekStart: parsedInput.weekStart,
+ },
+ headers: await headers(),
});
});
diff --git a/apps/web/src/features/user/data.ts b/apps/web/src/features/user/data.ts
index 14479b9e6..5c7215892 100644
--- a/apps/web/src/features/user/data.ts
+++ b/apps/web/src/features/user/data.ts
@@ -10,7 +10,7 @@ export const createUserDTO = (user: User): UserDTO => ({
email: user.email,
role: user.role,
banned: user.banned,
- timeZone: user.timeZone ?? undefined,
+ timeZone: user.timeZone || undefined,
timeFormat: user.timeFormat ?? undefined,
locale: user.locale ?? undefined,
weekStart: user.weekStart ?? undefined,
@@ -34,7 +34,7 @@ const createGuestDTO = (session: {
banned: false,
isGuest: true,
locale: session.locale,
- timeZone: session.timeZone,
+ timeZone: session.timeZone || undefined,
});
export const getUser = async (id: string) => {
diff --git a/apps/web/src/features/user/mutations.ts b/apps/web/src/features/user/mutations.ts
index fd905124b..7595c132b 100644
--- a/apps/web/src/features/user/mutations.ts
+++ b/apps/web/src/features/user/mutations.ts
@@ -77,30 +77,6 @@ export async function updateUserImage({
revalidateTag(userProfileTag(userId), "max");
}
-// Localization is written directly via Prisma (not Better-Auth): the cookie is
-// the SSR source of truth, so the session cache doesn't need refreshing here.
-// Undefined fields are no-ops in Prisma, giving patch semantics.
-export async function updateUserLocalization({
- userId,
- timeZone,
- timeFormat,
- weekStart,
-}: {
- userId: string;
- timeZone?: string;
- timeFormat?: TimeFormat;
- weekStart?: number;
-}) {
- await prisma.user.update({
- where: { id: userId },
- data: {
- timeZone,
- timeFormat,
- weekStart,
- },
- });
-}
-
export async function setActiveSpace({
userId,
spaceId,
diff --git a/apps/web/src/lib/auth.ts b/apps/web/src/lib/auth.ts
index 7d72c0ff8..f0961e7eb 100644
--- a/apps/web/src/lib/auth.ts
+++ b/apps/web/src/lib/auth.ts
@@ -226,6 +226,16 @@ export const authLib = betterAuth({
type: "string",
input: true,
},
+ timeFormat: {
+ type: "string",
+ input: true,
+ required: false,
+ },
+ weekStart: {
+ type: "number",
+ input: true,
+ required: false,
+ },
},
},
secondaryStorage: kv
@@ -506,7 +516,9 @@ export const getSession = cache(async () => {
isGuest: !!session.user.isAnonymous,
image: session.user.image,
locale: session.user.locale ?? undefined,
- timeZone: session.user.timeZone ?? undefined,
+ timeZone: session.user.timeZone || undefined,
+ timeFormat: session.user.timeFormat ?? undefined,
+ weekStart: session.user.weekStart ?? undefined,
},
expires: session.session.expiresAt.toISOString(),
updatedAt: session.session.updatedAt.toISOString(),
diff --git a/apps/web/src/lib/datetime/calendar-date.tsx b/apps/web/src/lib/datetime/calendar-date.tsx
new file mode 100644
index 000000000..408a97c22
--- /dev/null
+++ b/apps/web/src/lib/datetime/calendar-date.tsx
@@ -0,0 +1,26 @@
+"use client";
+
+import { useDateTimeConfig } from "@/lib/datetime/client";
+import type { DateInput, DatePreset } from "@/lib/datetime/format";
+import { formatDate } from "@/lib/datetime/format";
+import { toISODate } from "./utils";
+
+export type CalendarDateProps = {
+ value: DateInput;
+ preset?: DatePreset;
+ className?: string;
+};
+
+/** A zone-less calendar date (all-day events, stored as UTC midnight). */
+export function CalendarDate({
+ value,
+ preset = "dateLong",
+ className,
+}: CalendarDateProps) {
+ const { locale } = useDateTimeConfig();
+ return (
+ <time dateTime={toISODate(value)} className={className}>
+ {formatDate(value, { preset, locale })}
+ </time>
+ );
+}
diff --git a/apps/web/src/lib/datetime/client.tsx b/apps/web/src/lib/datetime/client.tsx
new file mode 100644
index 000000000..ca35a228e
--- /dev/null
+++ b/apps/web/src/lib/datetime/client.tsx
@@ -0,0 +1,65 @@
+"use client";
+
+import type { TimeFormat } from "@rallly/database";
+import { defaultLocale } from "@rallly/languages";
+import { useParams } from "next/navigation";
+import React from "react";
+import { normalizeTimeZone } from "@/lib/datetime/utils";
+import { getBrowserTimeZone } from "@/utils/date-time-utils";
+
+type DateTimeConfig = {
+ locale?: string;
+ timeZone?: string;
+ timeFormat?: TimeFormat;
+};
+
+const DateTimeContext = React.createContext<DateTimeConfig | undefined>(
+ undefined,
+);
+
+// Merges with any parent provider so a nested provider can override a single
+// field (e.g. a time zone switcher) without restating the rest. Falls back to
+// the browser zone when no zone is known; detected in an effect so the server
+// and first client render match.
+export function DateTimeProvider({
+ locale,
+ timeZone,
+ timeFormat,
+ children,
+}: DateTimeConfig & { children: React.ReactNode }) {
+ const parent = React.useContext(DateTimeContext);
+ const [browserTimeZone, setBrowserTimeZone] = React.useState<string>();
+
+ React.useEffect(() => {
+ setBrowserTimeZone(getBrowserTimeZone());
+ }, []);
+
+ const value = React.useMemo(
+ () => ({
+ locale: locale ?? parent?.locale,
+ // Stored zones can be empty or corrupt; parent and browser zones are
+ // already normalized.
+ timeZone:
+ normalizeTimeZone(timeZone) ?? parent?.timeZone ?? browserTimeZone,
+ timeFormat: timeFormat ?? parent?.timeFormat,
+ }),
+ [locale, timeZone, timeFormat, parent, browserTimeZone],
+ );
+
+ return (
+ <DateTimeContext.Provider value={value}>
+ {children}
+ </DateTimeContext.Provider>
+ );
+}
+
+export function useDateTimeConfig() {
+ const config = React.useContext(DateTimeContext);
+ const params = useParams<{ locale?: string }>();
+
+ return {
+ locale: config?.locale ?? params?.locale ?? defaultLocale,
+ timeZone: config?.timeZone,
+ timeFormat: config?.timeFormat,
+ };
+}
diff --git a/apps/web/src/lib/datetime/format.test.ts b/apps/web/src/lib/datetime/format.test.ts
new file mode 100644
index 000000000..061f29d06
--- /dev/null
+++ b/apps/web/src/lib/datetime/format.test.ts
@@ -0,0 +1,181 @@
+import type { TimeFormat } from "@rallly/database";
+import { describe, expect, it } from "vitest";
+import {
+ formatDate,
+ formatDateTime,
+ formatDateTimeRange,
+ formatRelativeTime,
+} from "@/lib/datetime/format";
+
+// Fri 26 Jun 2026, in UTC.
+const at = (hour: number, minute = 0) =>
+ new Date(Date.UTC(2026, 5, 26, hour, minute));
+
+const ctx = (locale: string, timeFormat?: TimeFormat, timeZone = "UTC") => ({
+ locale,
+ timeFormat,
+ timeZone,
+});
+
+describe("formatDateTime", () => {
+ it("formats 24-hour time", () => {
+ expect(
+ formatDateTime(at(13), { preset: "time", ...ctx("en", "hours24") }),
+ ).toBe("13:00");
+ });
+
+ it("formats 12-hour time", () => {
+ const out = formatDateTime(at(13), {
+ preset: "time",
+ ...ctx("en", "hours12"),
+ });
+ expect(out).toMatch(/\bPM\b/i);
+ expect(out).not.toContain("13");
+ });
+
+ it("falls back to the locale default when no time format is set", () => {
+ expect(formatDateTime(at(13), { preset: "time", ...ctx("en") })).toMatch(
+ /\bPM\b/i,
+ );
+ expect(formatDateTime(at(13), { preset: "time", ...ctx("de") })).toContain(
+ "13",
+ );
+ });
+
+ it("applies the 12-hour override on a 24-hour-default locale (de)", () => {
+ const out = formatDateTime(at(13), {
+ preset: "time",
+ ...ctx("de", "hours12"),
+ });
+ expect(out).not.toContain("13");
+ });
+
+ it("places the meridiem before the time for Chinese 12-hour", () => {
+ expect(
+ formatDateTime(at(13), { preset: "time", ...ctx("zh", "hours12") }),
+ ).toBe("下午1:00");
+ });
+
+ it("preserves the locale separator under override (Finnish period)", () => {
+ expect(
+ formatDateTime(at(15, 30), { preset: "time", ...ctx("fi", "hours24") }),
+ ).toBe("15.30");
+ });
+
+ it("produces different output for hours12 vs hours24 (override applied)", () => {
+ expect(
+ formatDateTime(at(13), { preset: "time", ...ctx("en", "hours12") }),
+ ).not.toBe(
+ formatDateTime(at(13), { preset: "time", ...ctx("en", "hours24") }),
+ );
+ });
+
+ it("converts to the given timezone", () => {
+ // 13:00 UTC = 09:00 America/New_York (EDT) in June.
+ expect(
+ formatDateTime(at(13), {
+ preset: "time",
+ ...ctx("en", "hours24", "America/New_York"),
+ }),
+ ).toBe("09:00");
+ });
+
+ it("formats a weekday", () => {
+ expect(
+ formatDateTime(at(13), { preset: "weekday", ...ctx("en", "hours24") }),
+ ).toBe("Friday");
+ });
+
+ it("formats a datetime with both date and time parts", () => {
+ const out = formatDateTime(at(13), {
+ preset: "datetime",
+ ...ctx("en", "hours24"),
+ });
+ expect(out).toContain("2026");
+ expect(out).toContain("13:00");
+ });
+
+ it("applies the timezone to the datetime preset", () => {
+ // 13:00 UTC = 09:00 America/New_York; the date+time preset must honor it.
+ const out = formatDateTime(at(13), {
+ preset: "datetime",
+ ...ctx("en", "hours24", "America/New_York"),
+ });
+ expect(out).toContain("09:00");
+ expect(out).not.toContain("13:00");
+ });
+
+ it("date preset omits the time", () => {
+ const out = formatDateTime(at(13), {
+ preset: "date",
+ ...ctx("en", "hours24"),
+ });
+ expect(out).toContain("2026");
+ expect(out).not.toContain("13:00");
+ });
+
+ it("appends the timezone name when showTimeZone is set", () => {
+ const out = formatDateTime(at(13), {
+ preset: "time",
+ ...ctx("en", "hours24", "America/New_York"),
+ showTimeZone: true,
+ });
+ expect(out).toContain("EDT");
+ });
+
+ it("accepts ISO strings and timestamps", () => {
+ expect(
+ formatDateTime(at(13).toISOString(), {
+ preset: "time",
+ ...ctx("en", "hours24"),
+ }),
+ ).toBe("13:00");
+ expect(
+ formatDateTime(at(13).getTime(), {
+ preset: "time",
+ ...ctx("en", "hours24"),
+ }),
+ ).toBe("13:00");
+ });
+});
+
+describe("formatDateTimeRange", () => {
+ it("formats a time range", () => {
+ const out = formatDateTimeRange(at(13), at(14), {
+ preset: "time",
+ ...ctx("en", "hours24"),
+ });
+ expect(out).toContain("13:00");
+ expect(out).toContain("14:00");
+ });
+});
+
+describe("formatDate", () => {
+ it("formats a UTC-midnight value as the stored calendar date", () => {
+ // Midnight UTC is the previous day in every zone west of UTC; formatDate
+ // must ignore the viewer's zone entirely.
+ const utcMidnight = new Date(Date.UTC(2026, 5, 26));
+ expect(formatDate(utcMidnight, { locale: "en" })).toBe("June 26, 2026");
+ });
+
+ it("supports date presets", () => {
+ const utcMidnight = new Date(Date.UTC(2026, 5, 26));
+ expect(formatDate(utcMidnight, { preset: "weekday", locale: "en" })).toBe(
+ "Friday",
+ );
+ });
+});
+
+describe("formatRelativeTime", () => {
+ // Relative to the real current time, so derive the input from `Date.now()` to
+ // keep these deterministic.
+ const twoHoursAgo = () => new Date(Date.now() - 2 * 60 * 60 * 1000);
+
+ it("formats relative time", () => {
+ expect(formatRelativeTime(twoHoursAgo(), "en")).toBe("2 hours ago");
+ });
+
+ it("localizes relative time", () => {
+ expect(formatRelativeTime(twoHoursAgo(), "de")).toBe("vor 2 Stunden");
+ });
+});
diff --git a/apps/web/src/lib/datetime/format.ts b/apps/web/src/lib/datetime/format.ts
new file mode 100644
index 000000000..a73194a2f
--- /dev/null
+++ b/apps/web/src/lib/datetime/format.ts
@@ -0,0 +1,142 @@
+import type { TimeFormat } from "@rallly/database";
+
+export type DateInput = Date | string | number;
+
+export type DatePreset = "date" | "dateLong" | "weekday";
+
+export type DateTimePreset = DatePreset | "time" | "datetime";
+
+export type FormatDateTimeOptions = {
+ preset?: DateTimePreset;
+ locale: string;
+ timeFormat?: TimeFormat;
+ timeZone?: string;
+ showTimeZone?: boolean;
+};
+
+function toDate(value: DateInput): Date {
+ return value instanceof Date ? value : new Date(value);
+}
+
+const formatters = new Map<string, Intl.DateTimeFormat>();
+
+function getCachedIntlDateFormatter({
+ preset = "datetime",
+ locale,
+ timeFormat,
+ timeZone,
+ showTimeZone,
+}: FormatDateTimeOptions) {
+ const options = {
+ ...presetOptions(preset, timeFormat),
+ // An empty string is an invalid IANA zone and throws; treat it as "unset".
+ timeZone: timeZone || undefined,
+ timeZoneName: showTimeZone ? ("short" as const) : undefined,
+ };
+ const key = `${locale}|${JSON.stringify(options)}`;
+ let f = formatters.get(key);
+ if (!f) {
+ f = new Intl.DateTimeFormat(locale, options);
+ formatters.set(key, f);
+ }
+ return f;
+}
+
+function presetOptions(
+ preset: DateTimePreset,
+ timeFormat?: TimeFormat,
+): Intl.DateTimeFormatOptions {
+ // Leave hour12 undefined when there's no preference so the locale decides.
+ const hour12 = timeFormat ? timeFormat === "hours12" : undefined;
+ switch (preset) {
+ case "time":
+ return {
+ hour: hour12 === false ? "2-digit" : "numeric",
+ minute: "2-digit",
+ hour12,
+ };
+ case "date":
+ return {
+ year: "numeric",
+ month: "short",
+ day: "numeric",
+ };
+ case "dateLong":
+ return {
+ year: "numeric",
+ month: "long",
+ day: "numeric",
+ };
+ case "weekday":
+ return { weekday: "long" };
+ case "datetime":
+ return {
+ year: "numeric",
+ month: "short",
+ day: "numeric",
+ hour: hour12 === false ? "2-digit" : "numeric",
+ minute: "2-digit",
+ hour12,
+ };
+ }
+}
+
+export function formatDateTime(
+ value: DateInput,
+ options: FormatDateTimeOptions,
+): string {
+ return getCachedIntlDateFormatter(options).format(toDate(value));
+}
+
+export function formatDateTimeRange(
+ start: DateInput,
+ end: DateInput,
+ options: FormatDateTimeOptions,
+): string {
+ return getCachedIntlDateFormatter(options).formatRange(
+ toDate(start),
+ toDate(end),
+ );
+}
+
+// All-day values are stored as UTC midnight, so they always format in UTC.
+export function formatDate(
+ value: DateInput,
+ options: { preset?: DatePreset; locale: string },
+): string {
+ return formatDateTime(value, {
+ preset: options.preset ?? "dateLong",
+ locale: options.locale,
+ timeZone: "UTC",
+ });
+}
+
+const relativeFormatters = new Map<string, Intl.RelativeTimeFormat>();
+
+// Largest-first; each entry is how many of the unit make up the next one.
+const DIVISIONS: [Intl.RelativeTimeFormatUnit, number][] = [
+ ["second", 60],
+ ["minute", 60],
+ ["hour", 24],
+ ["day", 7],
+ ["week", 4.34524],
+ ["month", 12],
+ ["year", Number.POSITIVE_INFINITY],
+];
+
+export function formatRelativeTime(value: DateInput, locale: string): string {
+ let rtf = relativeFormatters.get(locale);
+ if (!rtf) {
+ rtf = new Intl.RelativeTimeFormat(locale, { numeric: "auto" });
+ relativeFormatters.set(locale, rtf);
+ }
+
+ let amount = (toDate(value).getTime() - Date.now()) / 1000;
+ for (const [unit, perNext] of DIVISIONS) {
+ if (Math.abs(amount) < perNext) {
+ return rtf.format(Math.round(amount), unit);
+ }
+ amount /= perNext;
+ }
+ return rtf.format(Math.round(amount), "year");
+}
diff --git a/apps/web/src/lib/datetime/locales.test.ts b/apps/web/src/lib/datetime/locales.test.ts
new file mode 100644
index 000000000..c8b89d3c9
--- /dev/null
+++ b/apps/web/src/lib/datetime/locales.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it } from "vitest";
+import { getLocaleDefaults } from "@/lib/datetime/locales";
+
+// Tripwire: these lock the CLDR-derived defaults so an ICU/Node upgrade that
+// shifts one fails loudly.
+describe("getLocaleDefaults", () => {
+ it("uses a 12-hour clock and Sunday week start for en (US)", () => {
+ expect(getLocaleDefaults("en")).toEqual({
+ timeFormat: "hours12",
+ weekStart: 0,
+ });
+ });
+
+ it("uses a 24-hour clock and Monday week start for en-GB", () => {
+ expect(getLocaleDefaults("en-GB")).toEqual({
+ timeFormat: "hours24",
+ weekStart: 1,
+ });
+ });
+
+ it("uses a 24-hour clock and Monday week start for de", () => {
+ expect(getLocaleDefaults("de")).toEqual({
+ timeFormat: "hours24",
+ weekStart: 1,
+ });
+ });
+
+ it("trusts CLDR's Sunday week start for Portugal (pt)", () => {
+ expect(getLocaleDefaults("pt")).toEqual({
+ timeFormat: "hours24",
+ weekStart: 0,
+ });
+ });
+});
diff --git a/apps/web/src/lib/datetime/locales.ts b/apps/web/src/lib/datetime/locales.ts
new file mode 100644
index 000000000..629489e96
--- /dev/null
+++ b/apps/web/src/lib/datetime/locales.ts
@@ -0,0 +1,37 @@
+import type { TimeFormat } from "@rallly/database";
+
+type LocaleDefaults = {
+ weekStart: number;
+ timeFormat: TimeFormat;
+};
+
+type WeekInfo = { firstDay: number };
+
+// `getWeekInfo()` (spec) / `.weekInfo` (older engines) isn't in every TS lib yet.
+function getWeekInfo(locale: string): WeekInfo {
+ const l = new Intl.Locale(locale) as Intl.Locale & {
+ getWeekInfo?: () => WeekInfo;
+ weekInfo?: WeekInfo;
+ };
+ return l.getWeekInfo?.() ?? l.weekInfo ?? { firstDay: 1 };
+}
+
+const cache = new Map<string, LocaleDefaults>();
+
+export function getLocaleDefaults(locale: string): LocaleDefaults {
+ let defaults = cache.get(locale);
+ if (!defaults) {
+ const hourCycle = new Intl.DateTimeFormat(locale, {
+ hour: "numeric",
+ }).resolvedOptions().hourCycle;
+ const timeFormat: TimeFormat =
+ hourCycle === "h11" || hourCycle === "h12" ? "hours12" : "hours24";
+
+ // `firstDay` is 1..7 (Mon..Sun); map to JS 0..6 (Sun..Sat).
+ const weekStart = getWeekInfo(locale).firstDay % 7;
+
+ defaults = { weekStart, timeFormat };
+ cache.set(locale, defaults);
+ }
+ return defaults;
+}
diff --git a/apps/web/src/lib/datetime/relative-time.tsx b/apps/web/src/lib/datetime/relative-time.tsx
new file mode 100644
index 000000000..e7b28132b
--- /dev/null
+++ b/apps/web/src/lib/datetime/relative-time.tsx
@@ -0,0 +1,22 @@
+"use client";
+
+import { useDateTimeConfig } from "@/lib/datetime/client";
+import type { DateInput } from "@/lib/datetime/format";
+import { formatRelativeTime } from "@/lib/datetime/format";
+import { toISO } from "./utils";
+
+export type RelativeTimeProps = {
+ value: DateInput;
+ /** Override the viewer's locale. */
+ locale?: string;
+ className?: string;
+};
+
+export function RelativeTime({ value, locale, className }: RelativeTimeProps) {
+ const config = useDateTimeConfig();
+ return (
+ <time dateTime={toISO(value)} className={className}>
+ {formatRelativeTime(value, locale ?? config.locale)}
+ </time>
+ );
+}
diff --git a/apps/web/src/lib/datetime/schema.ts b/apps/web/src/lib/datetime/schema.ts
new file mode 100644
index 000000000..b414316bf
--- /dev/null
+++ b/apps/web/src/lib/datetime/schema.ts
@@ -0,0 +1,5 @@
+import * as z from "zod";
+
+export const timeFormatSchema = z.enum(["hours12", "hours24"]);
+
+export const weekStartSchema = z.coerce.number().int().min(0).max(6);
diff --git a/apps/web/src/lib/datetime/time.tsx b/apps/web/src/lib/datetime/time.tsx
new file mode 100644
index 000000000..3a80bdc7a
--- /dev/null
+++ b/apps/web/src/lib/datetime/time.tsx
@@ -0,0 +1,94 @@
+"use client";
+
+import { useDateTimeConfig } from "@/lib/datetime/client";
+import type { DateInput, DateTimePreset } from "@/lib/datetime/format";
+import { formatDateTime, formatDateTimeRange } from "@/lib/datetime/format";
+import { toISO } from "./utils";
+
+export type TimeProps = {
+ value: DateInput;
+ preset?: DateTimePreset;
+ /** Display zone (e.g. a venue's zone). Omit to show the viewer's local time. */
+ timeZone?: string;
+ /** Overrides the default rule: show the zone when it isn't the viewer's. */
+ showTimeZone?: boolean;
+ className?: string;
+};
+
+export function Time({
+ value,
+ preset = "datetime",
+ timeZone,
+ showTimeZone,
+ className,
+}: TimeProps) {
+ const config = useDateTimeConfig();
+ const displayTimeZone = timeZone ?? config.timeZone;
+
+ // The viewer's zone isn't known until the provider detects it on the
+ // client; render a non-breaking space (preserves the line height) rather
+ // than a time that may be wrong.
+ if (!displayTimeZone) {
+ return (
+ <time dateTime={toISO(value)} className={className}>
+ {" "}
+ </time>
+ );
+ }
+
+ return (
+ <time dateTime={toISO(value)} className={className}>
+ {formatDateTime(value, {
+ preset,
+ locale: config.locale,
+ timeFormat: config.timeFormat,
+ timeZone: displayTimeZone,
+ showTimeZone:
+ showTimeZone ?? Boolean(timeZone && timeZone !== config.timeZone),
+ })}
+ </time>
+ );
+}
+
+export type TimeRangeProps = {
+ start: DateInput;
+ end: DateInput;
+ preset?: DateTimePreset;
+ /** Display zone (e.g. a venue's zone). Omit to show the viewer's local time. */
+ timeZone?: string;
+ /** Overrides the default rule: show the zone when it isn't the viewer's. */
+ showTimeZone?: boolean;
+ className?: string;
+};
+
+export function TimeRange({
+ start,
+ end,
+ preset = "time",
+ timeZone,
+ showTimeZone,
+ className,
+}: TimeRangeProps) {
+ const config = useDateTimeConfig();
+ const displayTimeZone = timeZone ?? config.timeZone;
+
+ // The viewer's zone isn't known until the provider detects it on the
+ // client; render a non-breaking space (preserves the line height) rather
+ // than a time that may be wrong.
+ if (!displayTimeZone) {
+ return <span className={className}>{" "}</span>;
+ }
+
+ return (
+ <span className={className}>
+ {formatDateTimeRange(start, end, {
+ preset,
+ locale: config.locale,
+ timeFormat: config.timeFormat,
+ timeZone: displayTimeZone,
+ showTimeZone:
+ showTimeZone ?? Boolean(timeZone && timeZone !== config.timeZone),
+ })}
+ </span>
+ );
+}
diff --git a/apps/web/src/lib/datetime/utils.test.ts b/apps/web/src/lib/datetime/utils.test.ts
new file mode 100644
index 000000000..3848ae596
--- /dev/null
+++ b/apps/web/src/lib/datetime/utils.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, it } from "vitest";
+import { normalizeTimeZone } from "./utils";
+
+describe("normalizeTimeZone", () => {
+ it("returns a valid IANA zone unchanged", () => {
+ expect(normalizeTimeZone("Europe/Malta")).toBe("Europe/Malta");
+ expect(normalizeTimeZone("UTC")).toBe("UTC");
+ });
+
+ it("treats empty and nullish values as unset", () => {
+ expect(normalizeTimeZone("")).toBeUndefined();
+ expect(normalizeTimeZone(null)).toBeUndefined();
+ expect(normalizeTimeZone(undefined)).toBeUndefined();
+ });
+
+ it("treats invalid zone names as unset instead of throwing", () => {
+ expect(normalizeTimeZone("Not/AZone")).toBeUndefined();
+ expect(normalizeTimeZone("garbage")).toBeUndefined();
+ });
+});
diff --git a/apps/web/src/lib/datetime/utils.ts b/apps/web/src/lib/datetime/utils.ts
new file mode 100644
index 000000000..7a4132811
--- /dev/null
+++ b/apps/web/src/lib/datetime/utils.ts
@@ -0,0 +1,30 @@
+import type { DateInput } from "@/lib/datetime/format";
+
+function toDate(value: DateInput) {
+ return value instanceof Date ? value : new Date(value);
+}
+
+export function toISO(value: DateInput) {
+ return toDate(value).toISOString();
+}
+
+export function toISODate(value: DateInput) {
+ return toDate(value).toISOString().slice(0, 10);
+}
+
+/**
+ * Returns the given zone if it's a valid IANA identifier, otherwise
+ * undefined. Guards against empty strings and corrupt stored values, which
+ * would make Intl.DateTimeFormat throw.
+ */
+export function normalizeTimeZone(timeZone: string | undefined | null) {
+ if (!timeZone) {
+ return undefined;
+ }
+ try {
+ new Intl.DateTimeFormat(undefined, { timeZone });
+ return timeZone;
+ } catch {
+ return undefined;
+ }
+}
diff --git a/apps/web/src/lib/dayjs.ts b/apps/web/src/lib/dayjs.ts
index 3159a37d8..3c08cd76e 100644
--- a/apps/web/src/lib/dayjs.ts
+++ b/apps/web/src/lib/dayjs.ts
@@ -11,7 +11,6 @@ import minMax from "dayjs/plugin/minMax";
import relativeTime from "dayjs/plugin/relativeTime";
import timezone from "dayjs/plugin/timezone";
import toArray from "dayjs/plugin/toArray";
-import updateLocale from "dayjs/plugin/updateLocale";
import utc from "dayjs/plugin/utc";
dayjs.extend(utc);
@@ -27,6 +26,5 @@ dayjs.extend(localizedFormat);
dayjs.extend(minMax);
dayjs.extend(relativeTime);
dayjs.extend(toArray);
-dayjs.extend(updateLocale);
export { dayjs };
diff --git a/apps/web/src/lib/localization/boundary.tsx b/apps/web/src/lib/localization/boundary.tsx
deleted file mode 100644
index 3af2718d2..000000000
--- a/apps/web/src/lib/localization/boundary.tsx
+++ /dev/null
@@ -1,15 +0,0 @@
-import type React from "react";
-import { LocalizationProvider } from "@/lib/localization/context";
-import { getLocalization } from "@/lib/localization/server";
-
-export async function LocalizationBoundary({
- children,
-}: {
- children?: React.ReactNode;
-}) {
- const initial = await getLocalization();
-
- return (
- <LocalizationProvider initial={initial}>{children}</LocalizationProvider>
- );
-}
diff --git a/apps/web/src/lib/localization/constants.ts b/apps/web/src/lib/localization/constants.ts
deleted file mode 100644
index c95354d7d..000000000
--- a/apps/web/src/lib/localization/constants.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-// Locale reuses the existing `rallly_locale` cookie (see `@/lib/locale/constants`).
-// Each preference gets its own cookie so the async timezone detector can't
-// read-merge-write-clobber a concurrent change to a different preference.
-export const TIMEZONE_COOKIE = "rallly_timezone";
-export const TIME_FORMAT_COOKIE = "rallly_time_format";
-export const WEEK_START_COOKIE = "rallly_week_start";
diff --git a/apps/web/src/lib/localization/context.tsx b/apps/web/src/lib/localization/context.tsx
deleted file mode 100644
index de7aa1abb..000000000
--- a/apps/web/src/lib/localization/context.tsx
+++ /dev/null
@@ -1,70 +0,0 @@
-"use client";
-
-import type { TimeFormat } from "@rallly/database";
-import React from "react";
-import { useRequiredContext } from "@/components/use-required-context";
-import {
- setTimeFormatCookie,
- setTimeZoneCookie,
- setWeekStartCookie,
-} from "@/lib/localization/cookies";
-import type { Localization } from "@/lib/localization/schema";
-
-type LocalizationContextValue = Localization & {
- setTimeZone: (timeZone: string) => void;
- setTimeFormat: (timeFormat: TimeFormat) => void;
- setWeekStart: (weekStart: number) => void;
-};
-
-const LocalizationContext =
- React.createContext<LocalizationContextValue | null>(null);
-
-LocalizationContext.displayName = "LocalizationContext";
-
-export function LocalizationProvider({
- children,
- initial,
-}: {
- children?: React.ReactNode;
- initial: Localization;
-}) {
- const [state, setState] = React.useState(initial);
-
- // Each setter updates local state instantly, then persists to the cookie
- // (next-request SSR / cross-device read). No DB write — that happens only on
- // an explicit save in the "Language & Region" settings — and no router.refresh.
- const setTimeZone = React.useCallback((timeZone: string) => {
- setState((prev) => ({ ...prev, timeZone }));
- setTimeZoneCookie(timeZone);
- }, []);
-
- const setTimeFormat = React.useCallback((timeFormat: TimeFormat) => {
- setState((prev) => ({ ...prev, timeFormat }));
- setTimeFormatCookie(timeFormat);
- }, []);
-
- const setWeekStart = React.useCallback((weekStart: number) => {
- setState((prev) => ({ ...prev, weekStart }));
- setWeekStartCookie(weekStart);
- }, []);
-
- const value = React.useMemo(
- () => ({ ...state, setTimeZone, setTimeFormat, setWeekStart }),
- [state, setTimeZone, setTimeFormat, setWeekStart],
- );
-
- return (
- <LocalizationContext.Provider value={value}>
- {children}
- </LocalizationContext.Provider>
- );
-}
-
-export function useLocalization() {
- return useRequiredContext(LocalizationContext);
-}
-
-// Timezone is its own concern → thin selector.
-export function useTimeZone() {
- return useLocalization().timeZone;
-}
diff --git a/apps/web/src/lib/localization/cookies.ts b/apps/web/src/lib/localization/cookies.ts
deleted file mode 100644
index 3594d72a0..000000000
--- a/apps/web/src/lib/localization/cookies.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-"use client";
-
-import type { TimeFormat } from "@rallly/database";
-import Cookies from "js-cookie";
-import {
- TIME_FORMAT_COOKIE,
- TIMEZONE_COOKIE,
- WEEK_START_COOKIE,
-} from "@/lib/localization/constants";
-
-const cookieOptions = {
- path: "/",
- domain: process.env.NEXT_PUBLIC_COOKIE_DOMAIN,
- expires: 400,
-};
-
-export function setTimeZoneCookie(timeZone: string) {
- Cookies.set(TIMEZONE_COOKIE, timeZone, cookieOptions);
-}
-
-export function setTimeFormatCookie(timeFormat: TimeFormat) {
- Cookies.set(TIME_FORMAT_COOKIE, timeFormat, cookieOptions);
-}
-
-export function setWeekStartCookie(weekStart: number) {
- Cookies.set(WEEK_START_COOKIE, String(weekStart), cookieOptions);
-}
diff --git a/apps/web/src/lib/localization/locale-defaults.ts b/apps/web/src/lib/localization/locale-defaults.ts
deleted file mode 100644
index 6df403b58..000000000
--- a/apps/web/src/lib/localization/locale-defaults.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import type { TimeFormat } from "@rallly/database";
-import type { SupportedLocale } from "@rallly/languages";
-
-type LocaleDefaults = {
- weekStart: number;
- timeFormat: TimeFormat;
-};
-
-// Default time format / week start per locale. Server-safe (no dayjs imports)
-// so `getLocalization()` can resolve fallbacks.
-const localeDefaults: Record<SupportedLocale, LocaleDefaults> = {
- en: { weekStart: 1, timeFormat: "hours12" },
- "en-GB": { weekStart: 1, timeFormat: "hours24" },
- es: { weekStart: 1, timeFormat: "hours24" },
- da: { weekStart: 1, timeFormat: "hours24" },
- de: { weekStart: 1, timeFormat: "hours24" },
- fi: { weekStart: 1, timeFormat: "hours24" },
- fr: { weekStart: 1, timeFormat: "hours24" },
- it: { weekStart: 1, timeFormat: "hours24" },
- sv: { weekStart: 1, timeFormat: "hours24" },
- cs: { weekStart: 1, timeFormat: "hours24" },
- pl: { weekStart: 1, timeFormat: "hours24" },
- pt: { weekStart: 1, timeFormat: "hours24" },
- "pt-BR": { weekStart: 0, timeFormat: "hours24" },
- ru: { weekStart: 1, timeFormat: "hours24" },
- nl: { weekStart: 1, timeFormat: "hours24" },
- no: { weekStart: 1, timeFormat: "hours24" },
- hu: { weekStart: 1, timeFormat: "hours24" },
- zh: { weekStart: 1, timeFormat: "hours24" },
-};
-
-export function getLocaleDefaults(locale: string): LocaleDefaults {
- return localeDefaults[locale as SupportedLocale] ?? localeDefaults.en;
-}
diff --git a/apps/web/src/lib/localization/schema.ts b/apps/web/src/lib/localization/schema.ts
deleted file mode 100644
index 4bf394dff..000000000
--- a/apps/web/src/lib/localization/schema.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import type { TimeFormat } from "@rallly/database";
-import * as z from "zod";
-
-export const timeFormatSchema = z.enum(["hours12", "hours24"]);
-
-// Coerces a cookie string ("0".."6") into a numeric weekday index.
-export const weekStartSchema = z.coerce.number().int().min(0).max(6);
-
-export type Localization = {
- locale: string;
- timeZone?: string;
- timeFormat: TimeFormat;
- weekStart: number;
-};
diff --git a/apps/web/src/lib/localization/server.test.ts b/apps/web/src/lib/localization/server.test.ts
deleted file mode 100644
index cc4998430..000000000
--- a/apps/web/src/lib/localization/server.test.ts
+++ /dev/null
@@ -1,125 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-vi.mock("server-only", () => ({}));
-
-// Make `cache()` a pass-through so each call re-runs (no request-scoped memo).
-vi.mock("react", async (importOriginal) => {
- const actual = await importOriginal<typeof import("react")>();
- return { ...actual, cache: (fn: unknown) => fn };
-});
-
-const cookieStore = new Map<string, string>();
-const mockGetLocale = vi.fn<() => Promise<string>>();
-const mockGetCurrentUser = vi.fn();
-
-vi.mock("next/headers", () => ({
- cookies: async () => ({
- get: (name: string) =>
- cookieStore.has(name) ? { value: cookieStore.get(name) } : undefined,
- }),
-}));
-
-vi.mock("@/i18n/server/get-locale", () => ({
- getLocale: () => mockGetLocale(),
-}));
-
-vi.mock("@/auth/data", () => ({
- getCurrentUser: () => mockGetCurrentUser(),
-}));
-
-import {
- TIME_FORMAT_COOKIE,
- TIMEZONE_COOKIE,
- WEEK_START_COOKIE,
-} from "@/lib/localization/constants";
-import { getLocalization } from "@/lib/localization/server";
-
-beforeEach(() => {
- cookieStore.clear();
- mockGetLocale.mockReset().mockResolvedValue("en");
- mockGetCurrentUser.mockReset().mockResolvedValue(null);
-});
-
-describe("getLocalization", () => {
- it("uses cookie values and skips the DB when all cookies are present", async () => {
- cookieStore.set(TIMEZONE_COOKIE, "America/New_York");
- cookieStore.set(TIME_FORMAT_COOKIE, "hours24");
- cookieStore.set(WEEK_START_COOKIE, "3");
-
- const localization = await getLocalization();
-
- expect(localization).toEqual({
- locale: "en",
- timeZone: "America/New_York",
- timeFormat: "hours24",
- weekStart: 3,
- });
- expect(mockGetCurrentUser).not.toHaveBeenCalled();
- });
-
- it("falls back to the logged-in user's DB values when cookies are absent", async () => {
- mockGetCurrentUser.mockResolvedValue({
- timeZone: "Europe/Paris",
- timeFormat: "hours24",
- weekStart: 0,
- });
-
- const localization = await getLocalization();
-
- expect(localization).toEqual({
- locale: "en",
- timeZone: "Europe/Paris",
- timeFormat: "hours24",
- weekStart: 0,
- });
- });
-
- it("falls back to locale defaults for guests/anonymous (timeZone undefined)", async () => {
- mockGetCurrentUser.mockResolvedValue(null);
-
- const localization = await getLocalization();
-
- // `en` defaults: weekStart 1, timeFormat hours12.
- expect(localization).toEqual({
- locale: "en",
- timeZone: undefined,
- timeFormat: "hours12",
- weekStart: 1,
- });
- });
-
- it("hits the DB when only some cookies are present", async () => {
- cookieStore.set(TIMEZONE_COOKIE, "America/New_York");
- mockGetCurrentUser.mockResolvedValue({
- timeZone: "Europe/Paris",
- timeFormat: "hours24",
- weekStart: 0,
- });
-
- const localization = await getLocalization();
-
- // timeZone comes from the cookie; the rest from the DB.
- expect(localization).toEqual({
- locale: "en",
- timeZone: "America/New_York",
- timeFormat: "hours24",
- weekStart: 0,
- });
- expect(mockGetCurrentUser).toHaveBeenCalledTimes(1);
- });
-
- it("ignores invalid cookie values and falls back", async () => {
- cookieStore.set(TIMEZONE_COOKIE, "America/New_York");
- cookieStore.set(TIME_FORMAT_COOKIE, "bogus");
- cookieStore.set(WEEK_START_COOKIE, "99");
-
- const localization = await getLocalization();
-
- expect(localization).toEqual({
- locale: "en",
- timeZone: "America/New_York",
- timeFormat: "hours12",
- weekStart: 1,
- });
- });
-});
diff --git a/apps/web/src/lib/localization/server.ts b/apps/web/src/lib/localization/server.ts
deleted file mode 100644
index 093107706..000000000
--- a/apps/web/src/lib/localization/server.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-import "server-only";
-
-import { cookies } from "next/headers";
-import { cache } from "react";
-import { getCurrentUser } from "@/auth/data";
-import { getLocale } from "@/i18n/server/get-locale";
-import {
- TIME_FORMAT_COOKIE,
- TIMEZONE_COOKIE,
- WEEK_START_COOKIE,
-} from "@/lib/localization/constants";
-import { getLocaleDefaults } from "@/lib/localization/locale-defaults";
-import type { Localization } from "@/lib/localization/schema";
-import { timeFormatSchema, weekStartSchema } from "@/lib/localization/schema";
-
-/**
- * Resolves the viewer's localization for SSR.
- *
- * Each value falls back cookie → DB → locale default. The DB lookup is
- * short-circuited: `getCurrentUser()` only runs when a cookie is missing, so
- * anonymous/cookie-present viewers cost zero DB reads. `timeZone` has no locale
- * default and stays undefined for guests/anonymous viewers (resolved client-side).
- */
-export const getLocalization = cache(async (): Promise<Localization> => {
- const [cookieStore, locale] = await Promise.all([cookies(), getLocale()]);
-
- const timeZoneCookie = cookieStore.get(TIMEZONE_COOKIE)?.value;
- const timeFormatCookie = timeFormatSchema.safeParse(
- cookieStore.get(TIME_FORMAT_COOKIE)?.value,
- );
- const weekStartCookie = weekStartSchema.safeParse(
- cookieStore.get(WEEK_START_COOKIE)?.value,
- );
-
- const needsDbFallback =
- !timeZoneCookie || !timeFormatCookie.success || !weekStartCookie.success;
-
- const user = needsDbFallback ? await getCurrentUser() : null;
-
- const defaults = getLocaleDefaults(locale);
-
- return {
- locale,
- timeZone: timeZoneCookie ?? user?.timeZone ?? undefined,
- timeFormat:
- (timeFormatCookie.success ? timeFormatCookie.data : undefined) ??
- user?.timeFormat ??
- defaults.timeFormat,
- weekStart:
- (weekStartCookie.success ? weekStartCookie.data : undefined) ??
- user?.weekStart ??
- defaults.weekStart,
- };
-});
diff --git a/apps/web/src/lib/timezone/client/context.tsx b/apps/web/src/lib/timezone/client/context.tsx
deleted file mode 100644
index 93f9723cb..000000000
--- a/apps/web/src/lib/timezone/client/context.tsx
+++ /dev/null
@@ -1,12 +0,0 @@
-"use client";
-
-import { useUser } from "@/components/user-provider";
-import { getBrowserTimeZone } from "@/utils/date-time-utils";
-
-export const useTimezone = () => {
- const { user } = useUser();
-
- return {
- timezone: user?.timeZone ?? getBrowserTimeZone(),
- };
-};
diff --git a/apps/web/src/lib/timezone/client/formatted-date-time.tsx b/apps/web/src/lib/timezone/client/formatted-date-time.tsx
deleted file mode 100644
index 32abd2eb3..000000000
--- a/apps/web/src/lib/timezone/client/formatted-date-time.tsx
+++ /dev/null
@@ -1,47 +0,0 @@
-"use client";
-
-import type { ConfigType } from "dayjs";
-import * as React from "react";
-
-import { dayjs } from "@/lib/dayjs";
-
-import { useFormattedDateTime } from "@/lib/timezone/hooks/use-formatted-date-time";
-
-interface FormattedDateTimeProps extends React.HTMLAttributes<HTMLSpanElement> {
- /** The date/time to format (Accepts Date, ISO string, Unix timestamp, Dayjs object). */
- date: ConfigType | null | undefined;
- /** A dayjs format string (e.g., "YYYY-MM-DD HH:mm", "h:mm A"). Defaults to a locale-aware format. */
- format?: string;
- /** If true, formats the time without applying the context timezone. Defaults to false. */
- floating?: boolean;
- /** Optional locale string (e.g., "en-US", "fr-FR"). Defaults to browser/system locale. */
- locale?: string;
-}
-
-/**
- * Component to render a formatted date/time string based on the current timezone context.
- *
- * Uses the `useFormattedDateTime` hook internally.
- */
-export const FormattedDateTime = React.forwardRef<
- HTMLTimeElement,
- FormattedDateTimeProps
->(({ date, format, floating, locale, ...props }, ref) => {
- const formattedDate = useFormattedDateTime(date, {
- format,
- floating,
- locale,
- });
-
- return (
- <time
- dateTime={date ? dayjs(date).toISOString() : new Date().toISOString()}
- ref={ref}
- {...props}
- >
- {formattedDate}
- </time>
- );
-});
-
-FormattedDateTime.displayName = "FormattedDateTime";
diff --git a/apps/web/src/lib/timezone/hooks/use-formatted-date-time.ts b/apps/web/src/lib/timezone/hooks/use-formatted-date-time.ts
deleted file mode 100644
index 6635b749a..000000000
--- a/apps/web/src/lib/timezone/hooks/use-formatted-date-time.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-import type { ConfigType } from "dayjs";
-
-import { dayjs } from "@/lib/dayjs";
-import { useTimezone } from "@/lib/timezone/client/context";
-
-interface UseFormattedDateTimeOptions {
- /** A dayjs format string (e.g., "YYYY-MM-DD HH:mm", "h:mm A"). Defaults to a locale-aware format. */
- format?: string;
- /** If true, formats the time without applying the context timezone. Defaults to false. */
- floating?: boolean;
- /** Optional locale string (e.g., "en-US", "fr-FR"). Defaults to browser/system locale. */
- locale?: string;
-}
-
-/**
- * Hook to format a date/time value based on the current timezone context.
- *
- * @param date The date/time to format (Accepts Date, ISO string, Unix timestamp, Dayjs object).
- * @param options Formatting options including format string, floating flag, and locale.
- * @returns The formatted date/time string.
- */
-export const useFormattedDateTime = (
- date: ConfigType | null | undefined,
- options: UseFormattedDateTimeOptions = {},
-): string => {
- const { timezone } = useTimezone();
- const { format, floating = false, locale } = options;
-
- if (!date) {
- return "";
- }
-
- let dayjsInstance = dayjs(date);
-
- // Apply locale if provided
- if (locale) {
- dayjsInstance = dayjsInstance.locale(locale);
- }
-
- // Apply timezone unless floating is true
- if (!floating) {
- dayjsInstance = dayjsInstance.tz(timezone);
- }
- // For floating times, we might still want to ensure consistency,
- // especially if the input could be a Z-suffixed ISO string.
- // Converting to UTC first standardizes it before formatting without tz.
- else {
- dayjsInstance = dayjsInstance.utc();
- }
-
- return dayjsInstance.format(format ?? "LLLL");
-};
diff --git a/apps/web/vitest.config.mts b/apps/web/vitest.config.mts
index b2f4ff38e..860f41324 100644
--- a/apps/web/vitest.config.mts
+++ b/apps/web/vitest.config.mts
@@ -11,6 +11,9 @@ export default defineConfig({
exclude: ["**/node_modules/**", "**/*.spec.ts"],
setupFiles: ["./src/test/setup.ts"],
css: true,
+ // Non-UTC, non-integer offset so code that omits an explicit timeZone fails
+ // loudly instead of passing by luck on a UTC runner.
+ env: { TZ: "Asia/Kathmandu" },
},
resolve: {
alias: {