Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
✨ Add timezone cookie and segment-scoped datetime config (#2515)
Luke Vellaa899c0a80379
diff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.jsonindex 2be53466e..9732ca603 100644--- a/apps/web/public/locales/en/app.json+++ b/apps/web/public/locales/en/app.json@@ -645,9 +645,9 @@"themeSystem": "System","timeFormat": "Time format","timeZone": "Time zone",- "timeZoneChangeDetectorMessage": "Your timezone has changed to <b>{currentTimeZone}</b>. Do you want to update your preferences?",- "timeZoneChangeDetectorTitle": "Timezone Change Detected","timezoneInputPlaceholder": "Search timezone…",+ "timeZoneMismatchDialogMessage": "It looks like you are in <b>{currentTimeZone}</b> but your timezone is set to <b>{homeTimeZone}</b>. Do you want to update it?",+ "timeZoneMismatchDialogTitle": "Timezone Mismatch Detected","timeZoneSelect__noOption": "No option found","title": "Title","titlePlaceholder": "Monthly Meetup",diff --git a/apps/web/src/app/[locale]/(space)/layout.tsx b/apps/web/src/app/[locale]/(space)/layout.tsxindex 71d311c38..4b4f6d05a 100644--- a/apps/web/src/app/[locale]/(space)/layout.tsx+++ b/apps/web/src/app/[locale]/(space)/layout.tsx@@ -1,10 +1,9 @@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 { PayWall } from "@/features/billing/components/pay-wall";import { SpaceProvider } from "@/features/space/client";-import { getLocale } from "@/i18n/server/get-locale";+import { TimeZoneMismatchDialog } from "@/features/user/components/timezone-mismatch-dialog";import { DateTimeProvider } from "@/lib/datetime/client";import { LocaleSync } from "@/lib/locale/client";import { getPathname } from "@/lib/pathname";@@ -16,7 +15,6 @@ export default async function Layout({}: {children: React.ReactNode;}) {- const locale = await getLocale();const helpers = await createPrivateSSRHelper();const [user, space] = await Promise.all([@@ -35,12 +33,8 @@ export default async function Layout({<HydrationBoundary state={dehydrate(helpers.queryClient)}><SessionRefresher /><LocaleSync userLocale={user?.locale} />- <TimeZoneChangeDetector initialTimeZone={user?.timeZone} />- <DateTimeProvider- locale={locale}- timeZone={user?.timeZone}- timeFormat={user?.timeFormat}- >+ <TimeZoneMismatchDialog homeTimeZone={user?.timeZone} />+ <DateTimeProvider timeZone={user?.timeZone} timeFormat={user?.timeFormat}><SpaceProvider>{children}<PayWall />diff --git a/apps/web/src/app/[locale]/layout.tsx b/apps/web/src/app/[locale]/layout.tsxindex 1e7064161..05c83c5f7 100644--- a/apps/web/src/app/[locale]/layout.tsx+++ b/apps/web/src/app/[locale]/layout.tsx@@ -15,6 +15,7 @@ import { getInstanceBrandingConfig } from "@/features/branding/queries";import { ThemeProvider } from "@/features/theme/client";import { I18nProvider } from "@/i18n/client";import { initI18next } from "@/i18n/i18n";+import { TimeZoneSync } from "@/lib/datetime/timezone-sync";import { FeatureFlagsProvider } from "@/lib/feature-flags/client";import { featureFlagConfig } from "@/lib/feature-flags/config";import { TRPCProvider } from "@/trpc/client/provider";@@ -81,7 +82,9 @@ export default async function Root({<LazyMotion features={domAnimation}><SkipNavLink /><PostHogPageView />- <TooltipProvider>{children}</TooltipProvider>+ <TimeZoneSync>+ <TooltipProvider>{children}</TooltipProvider>+ </TimeZoneSync></LazyMotion></TRPCProvider></I18nProvider>diff --git a/apps/web/src/app/[locale]/timezone-change-detector.test.tsx b/apps/web/src/app/[locale]/timezone-change-detector.test.tsxdeleted file mode 100644index 830d24e5a..000000000--- a/apps/web/src/app/[locale]/timezone-change-detector.test.tsx+++ /dev/null@@ -1,68 +0,0 @@-import userEvent from "@testing-library/user-event";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { render, screen } from "@/test/test-utils";--import { TimeZoneChangeDetector } from "./timezone-change-detector";--let mockTimeZone = "America/New_York";-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(() => {- localStorage.clear();- });-- it("does not show modal on initial load with no previous timezone", () => {- render(<TimeZoneChangeDetector />);- expect(- screen.queryByText("Timezone Change Detected"),- ).not.toBeInTheDocument();- });-- it("shows modal if stored timezone differs from current", () => {- localStorage.setItem("previousTimeZone", "Fake/Timezone");- render(<TimeZoneChangeDetector />);- expect(screen.getByText("Timezone Change Detected")).toBeInTheDocument();- });-- it("accepting the change updates the localization and localStorage", async () => {- const user = userEvent.setup();- localStorage.setItem("previousTimeZone", "Fake/Timezone");-- render(<TimeZoneChangeDetector />);- await user.click(screen.getByText("Yes, update my timezone"));-- expect(mockExecute).toHaveBeenCalledWith({ timeZone: "America/New_York" });- expect(localStorage.getItem("previousTimeZone")).toBe("America/New_York");- });-- it("declining the change updates localStorage without updating localization", async () => {- const user = userEvent.setup();- localStorage.setItem("previousTimeZone", "Fake/Timezone");-- render(<TimeZoneChangeDetector />);- await user.click(screen.getByText("No, keep the current timezone"));-- expect(mockExecute).not.toHaveBeenCalled();- expect(localStorage.getItem("previousTimeZone")).toBe("America/New_York");- });-- it("stores current timezone on first visit", () => {- render(<TimeZoneChangeDetector />);- 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.tsxdeleted file mode 100644index 5475798e8..000000000--- a/apps/web/src/app/[locale]/timezone-change-detector.tsx+++ /dev/null@@ -1,99 +0,0 @@-"use client";--import { Button } from "@rallly/ui/button";-import {- Dialog,- DialogContent,- DialogFooter,- DialogHeader,- 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,-}: {- initialTimeZone?: string;-}) {- const [open, setOpen] = useState(false);-- const currentTimeZone = getBrowserTimeZone();-- const updateLocalization = useSafeAction(updateLocalizationAction);-- const [previousTimeZone, setPreviousTimeZone] = useState(() => {- const cachedPreviousTimeZone = safeLocalStorage.getItem("previousTimeZone");- if (cachedPreviousTimeZone) {- return cachedPreviousTimeZone;- }-- const timeZone = initialTimeZone ?? currentTimeZone;-- safeLocalStorage.setItem("previousTimeZone", timeZone);-- return timeZone;- });-- React.useEffect(() => {- if (previousTimeZone !== currentTimeZone) {- setOpen(true);- }- }, [previousTimeZone, currentTimeZone]);-- return (- <Dialog open={open} onOpenChange={setOpen}>- <DialogContent size="lg">- <DialogHeader>- <DialogTitle>- <Trans- i18nKey="timeZoneChangeDetectorTitle"- defaults="Timezone Change Detected"- />- </DialogTitle>- </DialogHeader>- <p className="text-muted-foreground text-sm leading-relaxed">- <Trans- i18nKey="timeZoneChangeDetectorMessage"- defaults="Your timezone has changed to <b>{currentTimeZone}</b>. Do you want to update your preferences?"- components={{ b: <b className="font-medium text-foreground" /> }}- values={{ currentTimeZone }}- />- </p>- <DialogFooter>- <Button- variant="primary"- onClick={() => {- safeLocalStorage.setItem("previousTimeZone", currentTimeZone);- updateLocalization.execute({- timeZone: currentTimeZone,- });- setOpen(false);- }}- >- <Trans- i18nKey="yesUpdateTimezone"- defaults="Yes, update my timezone"- />- </Button>- <Button- onClick={() => {- setPreviousTimeZone(currentTimeZone);- safeLocalStorage.setItem("previousTimeZone", currentTimeZone);- setOpen(false);- }}- >- <Trans- i18nKey="noKeepCurrentTimezone"- defaults="No, keep the current timezone"- />- </Button>- </DialogFooter>- </DialogContent>- </Dialog>- );-}diff --git a/apps/web/src/features/user/components/timezone-mismatch-dialog.test.tsx b/apps/web/src/features/user/components/timezone-mismatch-dialog.test.tsxnew file mode 100644index 000000000..1c0eb8b3f--- /dev/null+++ b/apps/web/src/features/user/components/timezone-mismatch-dialog.test.tsx@@ -0,0 +1,120 @@+import userEvent from "@testing-library/user-event";+import Cookies from "js-cookie";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { TIME_ZONE_COOKIE_NAME } from "@/lib/datetime/constants";+import { TimeZoneSync } from "@/lib/datetime/timezone-sync";+import { act, render, screen } from "@/test/test-utils";++import { TimeZoneMismatchDialog } from "./timezone-mismatch-dialog";++let mockTimeZone = "America/New_York";+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 }),+}));++function renderDialog(props: { homeTimeZone?: string } = {}) {+ return render(+ <TimeZoneSync>+ <TimeZoneMismatchDialog {...props} />+ </TimeZoneSync>,+ );+}++describe("TimeZoneMismatchDialog", () => {+ beforeEach(() => {+ mockTimeZone = "America/New_York";+ mockExecute.mockClear();+ });++ afterEach(() => {+ Cookies.remove(TIME_ZONE_COOKIE_NAME);+ });++ it("does not show on a first visit (no cookie), but records the zone", () => {+ renderDialog({ homeTimeZone: "Europe/Malta" });+ expect(+ screen.queryByText("Timezone Mismatch Detected"),+ ).not.toBeInTheDocument();+ expect(Cookies.get(TIME_ZONE_COOKIE_NAME)).toBe("America/New_York");+ });++ it("does not show when the zone has not changed, even if it differs from the home zone", () => {+ // The settings scenario: the user deliberately set a different home zone.+ Cookies.set(TIME_ZONE_COOKIE_NAME, "America/New_York");+ renderDialog({ homeTimeZone: "Europe/Malta" });+ expect(+ screen.queryByText("Timezone Mismatch Detected"),+ ).not.toBeInTheDocument();+ });++ it("shows when the viewer moved to a zone that is not their home zone", () => {+ Cookies.set(TIME_ZONE_COOKIE_NAME, "Asia/Tokyo");+ renderDialog({ homeTimeZone: "Europe/Malta" });+ expect(screen.getByText("Timezone Mismatch Detected")).toBeInTheDocument();+ expect(Cookies.get(TIME_ZONE_COOKIE_NAME)).toBe("America/New_York");+ });++ it("does not show when the viewer moved back to their home zone", () => {+ Cookies.set(TIME_ZONE_COOKIE_NAME, "Asia/Tokyo");+ renderDialog({ homeTimeZone: "America/New_York" });+ expect(+ screen.queryByText("Timezone Mismatch Detected"),+ ).not.toBeInTheDocument();+ });++ it("does not show when there is no home timezone", () => {+ Cookies.set(TIME_ZONE_COOKIE_NAME, "Asia/Tokyo");+ renderDialog();+ expect(+ screen.queryByText("Timezone Mismatch Detected"),+ ).not.toBeInTheDocument();+ });++ it("updating syncs the account zone", async () => {+ const user = userEvent.setup();+ Cookies.set(TIME_ZONE_COOKIE_NAME, "Asia/Tokyo");+ renderDialog({ homeTimeZone: "Europe/Malta" });++ await user.click(screen.getByText("Yes, update my timezone"));++ expect(mockExecute).toHaveBeenCalledWith({ timeZone: "America/New_York" });+ });++ it("shows when the zone changes while the tab is open and regains focus", async () => {+ Cookies.set(TIME_ZONE_COOKIE_NAME, "America/New_York");+ renderDialog({ homeTimeZone: "America/New_York" });+ expect(+ screen.queryByText("Timezone Mismatch Detected"),+ ).not.toBeInTheDocument();++ // Laptop reopened in a new zone: no remount, just a focus event.+ mockTimeZone = "Asia/Tokyo";+ act(() => {+ window.dispatchEvent(new Event("focus"));+ });++ expect(+ await screen.findByText("Timezone Mismatch Detected"),+ ).toBeInTheDocument();+ expect(Cookies.get(TIME_ZONE_COOKIE_NAME)).toBe("Asia/Tokyo");+ });++ it("declining closes without updating the account", async () => {+ const user = userEvent.setup();+ Cookies.set(TIME_ZONE_COOKIE_NAME, "Asia/Tokyo");+ renderDialog({ homeTimeZone: "Europe/Malta" });++ await user.click(screen.getByText("No, keep the current timezone"));++ expect(mockExecute).not.toHaveBeenCalled();+ expect(+ screen.queryByText("Timezone Mismatch Detected"),+ ).not.toBeInTheDocument();+ });+});diff --git a/apps/web/src/features/user/components/timezone-mismatch-dialog.tsx b/apps/web/src/features/user/components/timezone-mismatch-dialog.tsxnew file mode 100644index 000000000..ca43274f2--- /dev/null+++ b/apps/web/src/features/user/components/timezone-mismatch-dialog.tsx@@ -0,0 +1,101 @@+"use client";++import { Button } from "@rallly/ui/button";+import {+ Dialog,+ DialogContent,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@rallly/ui/dialog";+import React from "react";+import { updateLocalizationAction } from "@/features/user/actions";+import { Trans } from "@/i18n/client";+import { useTimeZoneChange } from "@/lib/datetime/timezone-sync";+import { useSafeAction } from "@/lib/safe-action/client";++/**+ * Offers to update the account's home time zone when TimeZoneSync detects+ * that the viewer has moved since their last visit. Consuming the change+ * event (rather than comparing zones directly) means a standing mismatch the+ * user created deliberately — picking a different home zone in settings, or+ * declining this prompt before — never re-prompts; only an actual move does.+ */+export function TimeZoneMismatchDialog({+ homeTimeZone,+}: {+ homeTimeZone?: string;+}) {+ const change = useTimeZoneChange();++ const [prompt, setPrompt] = React.useState<{ currentTimeZone: string }>();++ const updateLocalization = useSafeAction(updateLocalizationAction);++ React.useEffect(() => {+ if (change && homeTimeZone && change.currentTimeZone !== homeTimeZone) {+ setPrompt({ currentTimeZone: change.currentTimeZone });+ change.acknowledge();+ }+ }, [change, homeTimeZone]);++ if (!prompt) {+ return null;+ }++ return (+ <Dialog+ open={true}+ onOpenChange={(open) => {+ if (!open) {+ setPrompt(undefined);+ }+ }}+ >+ <DialogContent size="lg">+ <DialogHeader>+ <DialogTitle>+ <Trans+ i18nKey="timeZoneMismatchDialogTitle"+ defaults="Timezone Mismatch Detected"+ />+ </DialogTitle>+ </DialogHeader>+ <p className="text-muted-foreground text-sm leading-relaxed">+ <Trans+ i18nKey="timeZoneMismatchDialogMessage"+ defaults="It looks like you are in <b>{currentTimeZone}</b> but your timezone is set to <b>{homeTimeZone}</b>. Do you want to update it?"+ components={{ b: <b className="font-medium text-foreground" /> }}+ values={{ currentTimeZone: prompt.currentTimeZone, homeTimeZone }}+ />+ </p>+ <DialogFooter>+ <Button+ variant="primary"+ onClick={() => {+ updateLocalization.execute({+ timeZone: prompt.currentTimeZone,+ });+ setPrompt(undefined);+ }}+ >+ <Trans+ i18nKey="yesUpdateTimezone"+ defaults="Yes, update my timezone"+ />+ </Button>+ <Button+ onClick={() => {+ setPrompt(undefined);+ }}+ >+ <Trans+ i18nKey="noKeepCurrentTimezone"+ defaults="No, keep the current timezone"+ />+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/apps/web/src/lib/datetime/constants.ts b/apps/web/src/lib/datetime/constants.tsnew file mode 100644index 000000000..dcee07a7a--- /dev/null+++ b/apps/web/src/lib/datetime/constants.ts@@ -0,0 +1,2 @@+export const TIME_ZONE_COOKIE_NAME = "rallly_time_zone";+export const TIME_FORMAT_COOKIE_NAME = "rallly_time_format";diff --git a/apps/web/src/lib/datetime/server.ts b/apps/web/src/lib/datetime/server.tsnew file mode 100644index 000000000..ddd06747d--- /dev/null+++ b/apps/web/src/lib/datetime/server.ts@@ -0,0 +1,26 @@+import "server-only";++import { cookies } from "next/headers";+import {+ TIME_FORMAT_COOKIE_NAME,+ TIME_ZONE_COOKIE_NAME,+} from "@/lib/datetime/constants";+import { normalizeTimeFormat, normalizeTimeZone } from "@/lib/datetime/utils";++/**+ * Device-scoped datetime config for public pages: the viewer's current zone+ * and their per-device format choice. Authenticated segments seed their+ * provider from the user's stored preferences instead. No zone means the+ * viewer's first ever request — components render times client-side once the+ * zone is known.+ */+export async function getDeviceDateTimeConfig() {+ const cookieStore = await cookies();++ return {+ timeZone: normalizeTimeZone(cookieStore.get(TIME_ZONE_COOKIE_NAME)?.value),+ timeFormat: normalizeTimeFormat(+ cookieStore.get(TIME_FORMAT_COOKIE_NAME)?.value,+ ),+ };+}diff --git a/apps/web/src/lib/datetime/timezone-sync.tsx b/apps/web/src/lib/datetime/timezone-sync.tsxnew file mode 100644index 000000000..b5b40cbb8--- /dev/null+++ b/apps/web/src/lib/datetime/timezone-sync.tsx@@ -0,0 +1,84 @@+"use client";++import Cookies from "js-cookie";+import React from "react";+import { TIME_ZONE_COOKIE_NAME } from "@/lib/datetime/constants";+import { getBrowserTimeZone } from "@/utils/date-time-utils";++type TimeZoneChange = {+ previousTimeZone: string;+ currentTimeZone: string;+ /** Consume the change so no other surface prompts for it again. */+ acknowledge: () => void;+};++const TimeZoneChangeContext = React.createContext<TimeZoneChange | null>(null);++/**+ * Keeps the timeZone cookie in sync with the browser-detected zone and+ * exposes the change event through context. Detection must happen here: this+ * is the only place that sees the previous and current zone atomically —+ * consumers (e.g. TimeZoneMismatchDialog) may mount before or after the sync+ * runs depending on streaming and navigation, so they read the event from+ * context instead of the cookie. The cookie always means "the viewer's+ * current zone"; preference actions never write it.+ */+export function TimeZoneSync({ children }: { children: React.ReactNode }) {+ const [change, setChange] = React.useState<{+ previousTimeZone: string;+ currentTimeZone: string;+ } | null>(null);++ React.useEffect(() => {+ // Also re-check when the tab regains focus: long-lived tabs are how most+ // zone changes arrive (laptop reopened after travel), with no remount.+ const syncTimeZone = () => {+ if (document.visibilityState === "hidden") {+ return;+ }++ const currentTimeZone = getBrowserTimeZone();+ const previousTimeZone = Cookies.get(TIME_ZONE_COOKIE_NAME);++ if (previousTimeZone === currentTimeZone) {+ return;+ }++ Cookies.set(TIME_ZONE_COOKIE_NAME, currentTimeZone, {+ path: "/",+ expires: 365,+ sameSite: "lax",+ domain: process.env.NEXT_PUBLIC_COOKIE_DOMAIN,+ });++ // A first visit sets the cookie without announcing a change.+ if (previousTimeZone) {+ setChange({ previousTimeZone, currentTimeZone });+ }+ };++ syncTimeZone();+ window.addEventListener("focus", syncTimeZone);+ document.addEventListener("visibilitychange", syncTimeZone);+ return () => {+ window.removeEventListener("focus", syncTimeZone);+ document.removeEventListener("visibilitychange", syncTimeZone);+ };+ }, []);++ const value = React.useMemo(+ () => (change ? { ...change, acknowledge: () => setChange(null) } : null),+ [change],+ );++ return (+ <TimeZoneChangeContext.Provider value={value}>+ {children}+ </TimeZoneChangeContext.Provider>+ );+}++/** The unacknowledged zone change for this session, if any. */+export function useTimeZoneChange() {+ return React.useContext(TimeZoneChangeContext);+}diff --git a/apps/web/src/lib/datetime/utils.ts b/apps/web/src/lib/datetime/utils.tsindex 7a4132811..b8cbb752a 100644--- a/apps/web/src/lib/datetime/utils.ts+++ b/apps/web/src/lib/datetime/utils.ts@@ -1,3 +1,4 @@+import type { TimeFormat } from "@rallly/database";import type { DateInput } from "@/lib/datetime/format";function toDate(value: DateInput) {@@ -28,3 +29,10 @@ export function normalizeTimeZone(timeZone: string | undefined | null) {return undefined;}}++/** Narrows a stored value to a TimeFormat; anything else means "unset". */+export function normalizeTimeFormat(+ value: string | undefined | null,+): TimeFormat | undefined {+ return value === "hours12" || value === "hours24" ? value : undefined;+}