Files
supabase/apps/studio/components/interfaces/UserDropdown.tsx
T
Jordi Enric d8bb0ade65 feat(studio): add timezone picker to user dropdown (#45517)
## Problem

The dashboard renders all timestamps in the browser's local timezone.
When debugging app issues, users often want to see logs and timestamps
in a different timezone (e.g. their app's deployment region) without
changing their OS clock.

## Fix

- New Timezone submenu in the user-avatar dropdown, sitting next to the
existing Theme picker. Search-as-you-type combobox over the full IANA
catalog plus an Auto detect option.
- Selection persists in localStorage (`supabase-ui-timezone`) and
survives `clearLocalStorage()`. No backend schema change.
- New `lib/datetime.tsx` exposes pure timezone-aware formatters
(`formatDateTime`, `formatDate`, `formatTime`, `formatFromNow`,
`toTimezone`) plus a `TimezoneProvider` and matching React hooks
(`useTimezone`, `useFormatDateTime`, ...). The pure functions take `tz`
explicitly so they're easy to unit test (17 vitest cases covering DST
transitions, multi-tz formatting, unix-micro/Date inputs, invalid-tz
fallback).
- The selected timezone propagates to every existing `<TimestampInfo>`
in Studio via a new `TimestampInfoProvider` context exported from
`ui-patterns`. No per-callsite changes needed for those ~20+ surfaces.
- The `UnifiedLogs` date column migrates off `date-fns` to the new
`useFormatDateTime` hook (the rest of the date-fns callers stay as-is,
since they're either internal range math or non-display).
- `ALL_TIMEZONES` (~600 entries) moves out of `PITR.constants.ts` into a
shared `lib/constants/timezones.ts`. PITR keeps a re-export shim so its
callers don't move. New `TIMEZONES_BY_IANA` dedupes the catalog by
primary IANA name (the original list contains both PDT and PST rows for
`America/Los_Angeles`, etc.) and `findTimezoneByIana` provides reverse
lookup.
- Telemetry: `timezone_picker_clicked` PostHog event with
`previousTimezone`, `nextTimezone`, `isAutoDetected` properties.

Notes for reviewers:
- Bare `dayjs(x).format(...)` calls (~157 files) intentionally still
render in browser-local time. Surfaces opt in by switching to the new
wrappers, so this PR is the abstraction plus logs adoption; broader
migration is a follow-up.
- Two `// prettier-ignore` lines (`apps/studio/pages/_app.tsx`,
`apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.fields.tsx`)
work around a pre-existing local-tooling issue where
`prettier-plugin-sql-cst` strips angle-bracket type arguments under
certain conditions. Project's pinned prettier (3.8.1) does not strip;
the issue surfaces with a globally-installed prettier. Worth tracking
separately.
- Hydration: `guessLocalTimezone()` and `useLocalStorageQuery` are
client-only. Studio is mostly CSR via the Pages Router, but any SSR'd
`<TimestampInfo>` may briefly render in the server's tz before client
hydration. Existing behavior already had this mismatch with `.local()`;
this PR does not regress it.
- Backend timestamps round-tripped through query params and mutations
stay UTC. The picker is display-only.

## How to test

- Run `pnpm dev:studio`, sign in.
- Open the user avatar dropdown (top right). Hover Timezone.
- Search for "tokyo", pick `(UTC+09:00) Osaka, Sapporo, Tokyo`.
- Open any project, navigate to Logs (e.g. `Project > Logs > Edge
Functions`). Hover a log row's timestamp; the popover should show UTC,
the chosen tz (`Asia/Tokyo`), and the relative time. Visible cell text
should be in JST.
- Visit any page that uses `<TimestampInfo>` (Database > Backups,
Project Pause state, Edge Function details). Same tooltip should reflect
Asia/Tokyo.
- Refresh the page; timezone is still Asia/Tokyo.
- Reopen the picker, choose Auto detect; timestamps revert to browser
local.
- Run `pnpm --filter studio test lib/datetime.test.ts`. 17 tests should
pass.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* Timezone selector added to the user menu with auto-detect and manual
override
* App-wide timezone provider and hooks plus a shared timezone catalog
for consistent timezone-aware display
* Timestamp components accept an optional timezone prop and respect user
preference (persisted)

* **Bug Fixes / Improvements**
* Logs and timestamp displays now use the new timezone formatting hooks

* **Tests**
  * Added comprehensive datetime and timezone catalog tests

* **Telemetry**
  * Telemetry event added for timezone picker interactions
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-05-06 14:52:36 +02:00

177 lines
6.1 KiB
TypeScript

import { useFlag } from 'common'
import { FlaskConical, Loader2, ScrollText, Settings } from 'lucide-react'
import { useTheme } from 'next-themes'
import Link from 'next/link'
import { useRouter } from 'next/router'
import {
cn,
DropdownMenu,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
singleThemes,
Theme,
} from 'ui'
import { ButtonTooltip } from '../ui/ButtonTooltip'
import { useFeaturePreviewModal } from './App/FeaturePreview/FeaturePreviewContext'
import { TimezoneDropdown } from './UserDropdown/TimezoneDropdown'
import { ProfileImage } from '@/components/ui/ProfileImage'
import { useIsFeatureEnabled } from '@/hooks/misc/useIsFeatureEnabled'
import { IS_PLATFORM } from '@/lib/constants'
import { useProfileNameAndPicture } from '@/lib/profile'
import { useTrack } from '@/lib/telemetry/track'
import { useAppStateSnapshot } from '@/state/app-state'
export function UserDropdown({
triggerClassName,
contentClassName,
}: {
triggerClassName?: string
contentClassName?: string
}) {
const router = useRouter()
const { theme, setTheme } = useTheme()
const appStateSnapshot = useAppStateSnapshot()
const profileShowEmailEnabled = useIsFeatureEnabled('profile:show_email')
const timezonePickerEnabled = useFlag('timezonePicker')
const { username, avatarUrl, primaryEmail, isLoading } = useProfileNameAndPicture()
const { toggleFeaturePreviewModal } = useFeaturePreviewModal()
const track = useTrack()
return (
<DropdownMenu
onOpenChange={(open) => {
if (open) track('header_user_dropdown_opened')
}}
>
<DropdownMenuTrigger asChild className={cn('border shrink-0 px-3', triggerClassName)}>
<ButtonTooltip
type="default"
className="[&>span]:flex px-0 py-0 rounded-full overflow-hidden h-8 w-8"
tooltip={{ content: { text: 'Account settings' } }}
>
{isLoading ? (
<div className="w-full h-full flex items-center justify-center">
<Loader2 className="animate-spin text-foreground-lighter" size={16} />
</div>
) : (
<ProfileImage alt={username} src={avatarUrl} className="w-8 h-8 rounded-md" />
)}
</ButtonTooltip>
</DropdownMenuTrigger>
<DropdownMenuContent side="bottom" align="end" className={contentClassName}>
{IS_PLATFORM && (
<>
<div className="px-2 py-1 flex flex-col gap-0 text-sm">
{!!username ? (
<>
<span title={username} className="w-full text-left text-foreground truncate">
{username}
</span>
{primaryEmail !== username && profileShowEmailEnabled && (
<span
title={primaryEmail}
className="w-full text-left text-foreground-light text-xs truncate"
>
{primaryEmail}
</span>
)}
</>
) : (
<span title={primaryEmail} className="w-full text-left text-foreground truncate">
{primaryEmail}
</span>
)}
</div>
<DropdownMenuSeparator />
<DropdownMenuGroup>
<DropdownMenuItem className="flex gap-2 cursor-pointer" asChild>
<Link
href="/account/me"
onClick={() => {
if (router.pathname !== '/account/me') {
appStateSnapshot.setLastRouteBeforeVisitingAccountPage(router.asPath)
}
}}
>
<Settings size={14} strokeWidth={1.5} className="text-foreground-lighter" />
Account preferences
</Link>
</DropdownMenuItem>
<DropdownMenuItem
className="flex gap-2 cursor-pointer"
onClick={() => toggleFeaturePreviewModal(true)}
// onSelect={() => toggleFeaturePreviewModal(true)}
>
<FlaskConical size={14} strokeWidth={1.5} className="text-foreground-lighter" />
Feature previews
</DropdownMenuItem>
<DropdownMenuItem className="flex gap-2 cursor-pointer" asChild>
<Link
href="https://supabase.com/changelog"
target="_blank"
rel="noopener noreferrer"
>
<ScrollText size={14} strokeWidth={1.5} className="text-foreground-lighter" />
Changelog
</Link>
</DropdownMenuItem>
<DropdownMenuSeparator />
</DropdownMenuGroup>
</>
)}
<DropdownMenuGroup>
<DropdownMenuLabel>Theme</DropdownMenuLabel>
<DropdownMenuRadioGroup
value={theme}
onValueChange={(value) => {
setTheme(value)
}}
>
{singleThemes.map((theme: Theme) => (
<DropdownMenuRadioItem
key={theme.value}
value={theme.value}
className="cursor-pointer"
>
{theme.name}
</DropdownMenuRadioItem>
))}
</DropdownMenuRadioGroup>
</DropdownMenuGroup>
{timezonePickerEnabled && (
<>
<DropdownMenuSeparator />
<DropdownMenuGroup>
<TimezoneDropdown />
</DropdownMenuGroup>
</>
)}
{IS_PLATFORM && (
<>
<DropdownMenuSeparator />
<DropdownMenuGroup>
<DropdownMenuItem
className="cursor-pointer"
onSelect={() => {
router.push('/logout')
}}
>
Log out
</DropdownMenuItem>
</DropdownMenuGroup>
</>
)}
</DropdownMenuContent>
</DropdownMenu>
)
}