Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

Improve UI

Blue Mouse64f975cc7750
diff --git a/web/app/ui/TimezonePicker.tsx b/web/app/ui/TimezonePicker.tsx
index 935ba77fc..66b77686b 100644
--- a/web/app/ui/TimezonePicker.tsx
+++ b/web/app/ui/TimezonePicker.tsx
@@ -1,5 +1,10 @@
+/* oxlint-disable jsx-a11y/no-redundant-roles jsx-a11y/prefer-tag-over-role */
import { Transition } from '@headlessui/react'
-import { CaretUpDownIcon, CheckIcon, GlobeIcon } from '@phosphor-icons/react'
+import {
+ CaretUpDownIcon,
+ CheckIcon,
+ MagnifyingGlassIcon,
+} from '@phosphor-icons/react'
import cx from 'clsx'
import {
Fragment,
@@ -12,24 +17,15 @@ import {
} from 'react'
import { useTranslation } from 'react-i18next'
-import _find from 'lodash/find'
-import _includes from 'lodash/includes'
-import _reduce from 'lodash/reduce'
-
import timezones from '~/lib/constants/timezones'
import { Text } from '~/ui/Text'
interface TimezoneOption {
value: string
label: string
- displayName: string
- cityName: string
offsetLabel: string
offset: number
- abbrev?: string
- altName?: string
- genericName?: string
- regionName?: string
+ searchLabel: string
}
const getTimezoneOffsetMinutes = (
@@ -70,23 +66,6 @@ const getTimezoneOffsetMinutes = (
}
}
-const getTimezoneName = (
- timeZone: string,
- timeZoneName: Intl.DateTimeFormatOptions['timeZoneName'],
- date: Date,
-): string | undefined => {
- try {
- return new Intl.DateTimeFormat('en-US', {
- timeZone,
- timeZoneName,
- })
- .formatToParts(date)
- .find((part) => part.type === 'timeZoneName')?.value
- } catch {
- return undefined
- }
-}
-
const formatOffset = (offsetMinutes: number): string => {
const sign = offsetMinutes < 0 ? '-' : ''
const absolute = Math.abs(offsetMinutes)
@@ -98,6 +77,12 @@ const formatOffset = (offsetMinutes: number): string => {
: `${sign}${hours}`
}
+const formatOffsetLabel = (offsetMinutes: number): string => {
+ const offset = formatOffset(offsetMinutes)
+
+ return `GMT${offset.startsWith('-') ? offset : `+${offset}`}`
+}
+
const isValidTimezone = (timeZone: string, date: Date): boolean => {
try {
new Intl.DateTimeFormat('en-US', { timeZone }).format(date)
@@ -107,63 +92,34 @@ const isValidTimezone = (timeZone: string, date: Date): boolean => {
}
}
-const getTimezoneCityName = (timeZone: string): string => {
+const getTimezoneLabel = (timeZone: string): string => {
if (timeZone === 'GMT') {
return 'UTC'
}
- const cityName = timeZone.split('/').at(-1) || timeZone
+ const parts = timeZone.split('/')
+ const area = parts.at(0)
+ const city = parts.at(-1)?.replace(/_/g, ' ') || timeZone
- return cityName.replace(/_/g, ' ')
-}
-
-const getTimezoneRegionName = (timeZoneName?: string): string | undefined => {
- if (!timeZoneName || timeZoneName.startsWith('GMT')) {
- return undefined
- }
-
- const withoutStandard = timeZoneName.replace(
- /\s+(Standard|Daylight) Time$/,
- '',
- )
-
- if (withoutStandard !== timeZoneName) {
- return withoutStandard
- }
-
- const withoutTime = timeZoneName.replace(/\s+Time$/, '')
-
- return withoutTime.split(/\s+/).length > 1 ? withoutTime : timeZoneName
+ return area ? `${area} - ${city}` : city
}
const buildOptions = (date = new Date()) =>
- _reduce(
- Object.entries(timezones),
- (selectOptions: TimezoneOption[], zone) => {
- const offsetMinutes = getTimezoneOffsetMinutes(zone[0], date)
- const hr = formatOffset(offsetMinutes)
- const offsetLabel = `GMT${_includes(hr, '-') ? hr : `+${hr}`}`
- const label = `(${offsetLabel}) ${zone[1]}`
- const cityName = getTimezoneCityName(zone[0])
- const genericName = getTimezoneName(zone[0], 'longGeneric', date)
-
- selectOptions.push({
- value: zone[0],
+ Object.entries(timezones)
+ .map(([value, description]) => {
+ const offset = getTimezoneOffsetMinutes(value, date)
+ const offsetLabel = formatOffsetLabel(offset)
+ const label = getTimezoneLabel(value)
+
+ return {
+ value,
label,
- displayName: zone[1],
- cityName,
+ offset,
offsetLabel,
- offset: offsetMinutes / 60,
- abbrev: getTimezoneName(zone[0], 'short', date),
- altName: getTimezoneName(zone[0], 'long', date),
- genericName,
- regionName: getTimezoneRegionName(genericName),
- })
-
- return selectOptions
- },
- [],
- ).sort((a, b) => a.offset - b.offset)
+ searchLabel: `${value} ${description} ${label} ${offsetLabel}`,
+ }
+ })
+ .sort((a, b) => a.offset - b.offset)
const buildCustomOption = (
timeZone: string,
@@ -173,23 +129,16 @@ const buildCustomOption = (
return null
}
- const offsetMinutes = getTimezoneOffsetMinutes(timeZone, date)
- const hr = formatOffset(offsetMinutes)
- const offsetLabel = `GMT${_includes(hr, '-') ? hr : `+${hr}`}`
- const cityName = getTimezoneCityName(timeZone)
- const genericName = getTimezoneName(timeZone, 'longGeneric', date)
+ const offset = getTimezoneOffsetMinutes(timeZone, date)
+ const offsetLabel = formatOffsetLabel(offset)
+ const label = getTimezoneLabel(timeZone)
return {
value: timeZone,
- label: `(${offsetLabel}) ${cityName}`,
- displayName: cityName,
- cityName,
+ label,
offsetLabel,
- offset: offsetMinutes / 60,
- abbrev: getTimezoneName(timeZone, 'short', date),
- altName: getTimezoneName(timeZone, 'long', date),
- genericName,
- regionName: getTimezoneRegionName(genericName),
+ offset,
+ searchLabel: `${timeZone} ${label} ${offsetLabel}`,
}
}
@@ -215,29 +164,8 @@ const formatTimezoneTime = (date: Date, timeZone?: string | null): string =>
hour12: true,
})
-const formatTimezoneDate = (date: Date, timeZone?: string | null): string =>
- formatInTimezone(date, timeZone, {
- month: 'short',
- day: 'numeric',
- })
-
-const formatTimezoneDateTime = (date: Date, timeZone?: string | null): string =>
- `${formatTimezoneTime(date, timeZone)}, ${formatTimezoneDate(date, timeZone)}`
-
-const getTimezonePlaceLabel = (option: TimezoneOption): string => {
- if (option.value === 'GMT') {
- return option.displayName
- }
-
- if (option.regionName && option.regionName !== option.cityName) {
- return `${option.cityName} - ${option.regionName}`
- }
-
- return option.displayName
-}
-
const getSelectedTimezoneLabel = (option: TimezoneOption | null): string =>
- option ? `${getTimezonePlaceLabel(option)} (${option.offsetLabel})` : ''
+ option ? `${option.label} (${option.offsetLabel})` : ''
interface TimezoneSelectProps {
value:
@@ -253,10 +181,12 @@ const TimezoneSelect = ({ value, onChange }: TimezoneSelectProps) => {
const { t } = useTranslation('common')
const [now, setNow] = useState(() => new Date())
const [isOpen, setIsOpen] = useState(false)
+ const [isKeyboardMotion, setIsKeyboardMotion] = useState(false)
const [searchValue, setSearchValue] = useState('')
const [activeIndex, setActiveIndex] = useState(0)
const containerRef = useRef<HTMLDivElement>(null)
const inputRef = useRef<HTMLInputElement>(null)
+ const pointerDownRef = useRef(false)
const listboxId = useId()
const optionsCacheKey = new Date(
now.getFullYear(),
@@ -283,27 +213,27 @@ const TimezoneSelect = ({ value, onChange }: TimezoneSelectProps) => {
): TimezoneOption | null => {
if (typeof zone === 'object' && zone.value && zone.label) {
return (
- _find(options, (tz) => tz.value === zone.value) ?? {
+ options.find((tz) => tz.value === zone.value) ??
+ buildCustomOption(zone.value, optionsReferenceDate) ?? {
value: zone.value,
label: zone.label,
- displayName: zone.label,
- cityName: getTimezoneCityName(zone.value),
offsetLabel: 'GMT+0',
offset: 0,
+ searchLabel: `${zone.value} ${zone.label}`,
}
)
}
if (typeof zone === 'string') {
return (
- _find(options, (tz) => tz.value === zone) ??
+ options.find((tz) => tz.value === zone) ??
buildCustomOption(zone, optionsReferenceDate)
)
}
if (zone.value && !zone.label) {
return (
- _find(options, (tz) => tz.value === zone.value) ??
+ options.find((tz) => tz.value === zone.value) ??
buildCustomOption(zone.value, optionsReferenceDate)
)
}
@@ -327,18 +257,7 @@ const TimezoneSelect = ({ value, onChange }: TimezoneSelectProps) => {
}
return options.filter((option) =>
- [
- option.value,
- option.label,
- option.displayName,
- option.cityName,
- option.offsetLabel,
- option.abbrev,
- option.altName,
- option.genericName,
- option.regionName,
- getTimezonePlaceLabel(option),
- ]
+ [option.value, option.label, option.offsetLabel, option.searchLabel]
.filter(Boolean)
.join(' ')
.toLocaleLowerCase()
@@ -347,21 +266,31 @@ const TimezoneSelect = ({ value, onChange }: TimezoneSelectProps) => {
}, [options, searchValue])
const selectedLabel = getSelectedTimezoneLabel(selectedTimezone)
-
- const closeDropdown = () => {
+ const activeOptionId =
+ isOpen && filteredOptions[activeIndex]
+ ? `${listboxId}-option-${activeIndex}`
+ : undefined
+
+ const closeDropdown = (interaction: 'keyboard' | 'pointer' = 'pointer') => {
+ setIsKeyboardMotion(interaction === 'keyboard')
+ pointerDownRef.current = false
setIsOpen(false)
setSearchValue('')
}
- const openDropdown = () => {
+ const openDropdown = (interaction: 'keyboard' | 'pointer' = 'pointer') => {
+ setIsKeyboardMotion(interaction === 'keyboard')
setSearchValue('')
setActiveIndex(selectedIndex >= 0 ? selectedIndex : 0)
setIsOpen(true)
}
- const handleSelect = (item: TimezoneOption) => {
+ const handleSelect = (
+ item: TimezoneOption,
+ interaction: 'keyboard' | 'pointer' = 'pointer',
+ ) => {
onChange(keyExtractor(item))
- closeDropdown()
+ closeDropdown(interaction)
inputRef.current?.focus()
}
@@ -379,6 +308,8 @@ const TimezoneSelect = ({ value, onChange }: TimezoneSelectProps) => {
) {
setIsOpen(false)
setSearchValue('')
+ setIsKeyboardMotion(false)
+ pointerDownRef.current = false
}
}
@@ -414,7 +345,7 @@ const TimezoneSelect = ({ value, onChange }: TimezoneSelectProps) => {
const handleSearchKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
if (event.key === 'Escape') {
event.preventDefault()
- closeDropdown()
+ closeDropdown('keyboard')
inputRef.current?.focus()
return
}
@@ -438,7 +369,7 @@ const TimezoneSelect = ({ value, onChange }: TimezoneSelectProps) => {
const activeOption = filteredOptions[activeIndex]
if (activeOption) {
- handleSelect(activeOption)
+ handleSelect(activeOption, 'keyboard')
}
}
}
@@ -447,7 +378,7 @@ const TimezoneSelect = ({ value, onChange }: TimezoneSelectProps) => {
if (event.key === 'ArrowDown') {
event.preventDefault()
if (!isOpen) {
- openDropdown()
+ openDropdown('keyboard')
return
}
@@ -462,14 +393,16 @@ const TimezoneSelect = ({ value, onChange }: TimezoneSelectProps) => {
const handleFocus = () => {
if (!isOpen) {
- openDropdown()
+ openDropdown(pointerDownRef.current ? 'pointer' : 'keyboard')
}
+
+ pointerDownRef.current = false
}
return (
<div ref={containerRef} className='relative w-full'>
<div className='relative'>
- <GlobeIcon
+ <MagnifyingGlassIcon
className='pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-gray-400 dark:text-gray-500'
aria-hidden='true'
/>
@@ -478,21 +411,25 @@ const TimezoneSelect = ({ value, onChange }: TimezoneSelectProps) => {
type='text'
value={isOpen ? searchValue : selectedLabel}
onFocus={handleFocus}
+ onPointerDown={() => {
+ pointerDownRef.current = true
+ }}
onChange={(event) => {
if (!isOpen) {
+ setIsKeyboardMotion(true)
setIsOpen(true)
}
setSearchValue(event.target.value)
}}
onKeyDown={handleInputKeyDown}
+ role='combobox'
aria-label={t('profileSettings.timezone')}
+ aria-expanded={isOpen}
+ aria-haspopup='listbox'
aria-controls={listboxId}
- aria-activedescendant={
- isOpen && filteredOptions[activeIndex]
- ? `${listboxId}-option-${activeIndex}`
- : undefined
- }
+ aria-autocomplete='list'
+ aria-activedescendant={activeOptionId}
placeholder={t('profileSettings.timezoneSearchPlaceholder')}
className='block w-full rounded-md border-0 bg-white py-2 pr-8 pl-9 text-sm text-gray-900 ring-1 ring-gray-300 transition-shadow duration-150 ease-out ring-inset placeholder:text-gray-400 hover:ring-gray-400 focus:ring-2 focus:ring-slate-900 focus:outline-hidden dark:bg-slate-950 dark:text-gray-50 dark:ring-slate-700/80 dark:placeholder:text-gray-500 dark:hover:ring-slate-600 dark:focus:ring-slate-300'
/>
@@ -507,18 +444,35 @@ const TimezoneSelect = ({ value, onChange }: TimezoneSelectProps) => {
<Transition
show={isOpen}
as={Fragment}
- enter='transition ease-out duration-150'
- enterFrom='opacity-0 -translate-y-0.5'
+ enter={cx(
+ 'transition-[opacity,transform] ease-out-quint',
+ isKeyboardMotion
+ ? 'duration-0'
+ : 'duration-150 motion-reduce:transition-opacity',
+ )}
+ enterFrom={cx(
+ 'opacity-0',
+ !isKeyboardMotion && '-translate-y-0.5 motion-reduce:translate-y-0',
+ )}
enterTo='opacity-100 translate-y-0'
- leave='transition ease-in duration-100'
+ leave={cx(
+ 'transition-[opacity,transform] ease-out-quint',
+ isKeyboardMotion
+ ? 'duration-0'
+ : 'duration-100 motion-reduce:transition-opacity',
+ )}
leaveFrom='opacity-100 translate-y-0'
- leaveTo='opacity-0 -translate-y-0.5'
+ leaveTo={cx(
+ 'opacity-0',
+ !isKeyboardMotion && '-translate-y-0.5 motion-reduce:translate-y-0',
+ )}
>
- <div className='absolute z-50 mt-1 w-full min-w-[200px] overflow-hidden rounded-md bg-white text-sm ring-1 ring-gray-200 focus:outline-hidden dark:bg-slate-950 dark:ring-slate-800'>
+ <div className='absolute z-50 mt-1.5 w-full min-w-[240px] overflow-hidden rounded-md bg-white text-sm ring-1 ring-gray-200 focus:outline-hidden dark:bg-slate-950 dark:ring-slate-800'>
<div
id={listboxId}
+ role='listbox'
aria-label={t('profileSettings.timezone')}
- className='max-h-80 overflow-auto py-1'
+ className='max-h-80 overflow-auto py-1.5'
>
{filteredOptions.length ? (
filteredOptions.map((option, index) => {
@@ -530,14 +484,17 @@ const TimezoneSelect = ({ value, onChange }: TimezoneSelectProps) => {
id={`${listboxId}-option-${index}`}
key={option.value}
type='button'
- aria-pressed={selected}
+ role='option'
+ aria-selected={selected}
+ tabIndex={-1}
onMouseEnter={() => setActiveIndex(index)}
onClick={() => handleSelect(option)}
className={cx(
- 'mx-1 flex w-[calc(100%-0.5rem)] cursor-pointer items-center gap-2 rounded-md px-3 py-2 text-left transition-colors duration-100 ease-out select-none',
+ 'mx-1 flex w-[calc(100%-0.5rem)] transform-gpu cursor-pointer items-center gap-2 rounded-md px-3 py-2 text-left transition-[background-color,color,transform] duration-100 ease-out select-none active:scale-[0.99] motion-reduce:transition-colors motion-reduce:active:scale-100',
{
'bg-gray-100 text-gray-900 dark:bg-slate-800 dark:text-white':
- active || selected,
+ active,
+ 'text-gray-900 dark:text-white': selected && !active,
'text-gray-700 dark:text-gray-50': !active && !selected,
},
)}
@@ -546,21 +503,29 @@ const TimezoneSelect = ({ value, onChange }: TimezoneSelectProps) => {
<Text
as='span'
size='sm'
- weight='semibold'
- colour='primary'
- suppressHydrationWarning
+ weight={selected ? 'semibold' : 'normal'}
+ colour='inherit'
>
- {formatTimezoneDateTime(now, option.value)}
+ {option.label}
</Text>
<Text as='span' size='sm' colour='secondary'>
{' '}
- - {option.offsetLabel}, {getTimezonePlaceLabel(option)}
+ ({option.offsetLabel})
</Text>
</span>
+ <Text
+ as='span'
+ size='sm'
+ colour='secondary'
+ className='hidden shrink-0 tabular-nums sm:inline'
+ suppressHydrationWarning
+ >
+ {formatTimezoneTime(now, option.value)}
+ </Text>
{selected ? (
<CheckIcon
weight='bold'
- className='mt-0.5 size-4 shrink-0 text-slate-900 dark:text-slate-100'
+ className='size-4 shrink-0 text-slate-900 dark:text-slate-100'
aria-hidden='true'
/>
) : null}