Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

optimize timezone dropdown with virtualization and memoization #9896

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { findAvailableTimeZoneOption } from '@/localization/utils/findAvailableT
import { AVAILABLE_TIMEZONE_OPTIONS } from '@/settings/accounts/constants/AvailableTimezoneOptions';

import { Select } from '@/ui/input/components/Select';
import { VirtualizedSelect } from '@/ui/input/components/VirtualizedSelect';

type SettingsAccountsCalendarTimeZoneSelectProps = {
value?: string;
Expand All @@ -13,7 +14,7 @@ export const SettingsAccountsCalendarTimeZoneSelect = ({
value = detectTimeZone(),
onChange,
}: SettingsAccountsCalendarTimeZoneSelectProps) => (
<Select
<VirtualizedSelect
dropdownId="settings-accounts-calendar-time-zone"
dropdownWidth={416}
label="Time zone"
Expand All @@ -22,5 +23,7 @@ export const SettingsAccountsCalendarTimeZoneSelect = ({
options={AVAILABLE_TIMEZONE_OPTIONS}
onChange={onChange}
withSearchInput
itemHeight={40}
maxHeight={300}
/>
);
Original file line number Diff line number Diff line change
@@ -1,18 +1,46 @@
/* eslint-disable @nx/workspace-max-consts-per-file */
import { memoize } from 'lodash';
import { getTimezoneOffset } from 'date-fns-tz';
import { IANA_TIME_ZONES } from '@/localization/constants/IanaTimeZones';
import { formatTimeZoneLabel } from '@/localization/utils/formatTimeZoneLabel';
import { SelectOption } from '@/ui/input/components/Select';

import { AVAILABLE_TIME_ZONE_OPTIONS_BY_LABEL } from '@/settings/accounts/constants/AvailableTimezoneOptionsByLabel';
type TimezoneSelectOption = SelectOption<string> & {
offset: number; // Add the offset property
};

export const AVAILABLE_TIMEZONE_OPTIONS = Object.values(
AVAILABLE_TIME_ZONE_OPTIONS_BY_LABEL,
).sort((optionA, optionB) => {
// eslint-disable-next-line @typescript-eslint/naming-convention
const difference =
getTimezoneOffset(optionA.value) - getTimezoneOffset(optionB.value);
export const createTimeZoneOptions = memoize(() => {
const timeZoneOptionsMap = IANA_TIME_ZONES.reduce<Record<string, TimezoneSelectOption>>(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

logic: memoizing this function won't help with performance since it's only called once at module initialization - the AVAILABLE_TIMEZONE_OPTIONS constant already serves as a cache

(result, ianaTimeZone) => {
const timeZoneLabel = formatTimeZoneLabel(ianaTimeZone);
const timeZoneName = timeZoneLabel.slice(11);

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

style: slicing at index 11 is fragile - consider using a regex or split() to extract the timezone name more reliably

return difference === 0
? // Sort alphabetically if the time zone offsets are the same.
optionA.label.localeCompare(optionB.label)
: // Sort by time zone offset if different.
difference;
if (
timeZoneName.includes('GMT') ||
timeZoneName.includes('UTC') ||
timeZoneName.includes('UCT') ||
timeZoneLabel in result
) {
return result;
}

return {
...result,
[timeZoneLabel]: {
label: timeZoneLabel,
value: ianaTimeZone,
// Pre-calculate offset to avoid doing it during sorting
offset: getTimezoneOffset(ianaTimeZone)
},
};
},
{}
);

return Object.values(timeZoneOptionsMap).sort((a, b) => {
const difference = a.offset - b.offset;
return difference === 0 ? a.label.localeCompare(b.label) : difference;
});

});

export const AVAILABLE_TIMEZONE_OPTIONS = createTimeZoneOptions();
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ const StyledLabel = styled.span`
margin-bottom: ${({ theme }) => theme.spacing(1)};
`;

export const Select = <Value extends SelectValue>({
export const Select = <Value extends SelectValue,>({
className,
disabled: disabledFromProps,
selectSizeVariant,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
import { SelectProps, SelectValue } from '@/ui/input/components/Select';
import { SelectControl } from '@/ui/input/components/SelectControl';
import { SelectHotkeyScope } from '@/ui/input/types/SelectHotkeyScope';
import { Dropdown } from '@/ui/layout/dropdown/components/Dropdown';
import { DropdownMenuItemsContainer } from '@/ui/layout/dropdown/components/DropdownMenuItemsContainer';
import { DropdownMenuSearchInput } from '@/ui/layout/dropdown/components/DropdownMenuSearchInput';
import { DropdownMenuSeparator } from '@/ui/layout/dropdown/components/DropdownMenuSeparator';
import { useDropdown } from '@/ui/layout/dropdown/hooks/useDropdown';
import styled from '@emotion/styled';
import { useVirtualizer } from '@tanstack/react-virtual';
import { useEffect, useMemo, useRef, useState } from 'react';
import { isDefined, MenuItem, MenuItemSelect } from 'twenty-ui';

interface VirtualizedSelectProps<T extends SelectValue> extends Omit<SelectProps<T>, 'dropdownComponents'> {
itemHeight: number;
maxHeight: number;
}

const StyledContainer = styled.div<{ fullWidth?: boolean }>`
width: ${({ fullWidth }) => (fullWidth ? '100%' : 'auto')};
`;

const StyledLabel = styled.span`
color: ${({ theme }) => theme.font.color.light};
display: block;
font-size: ${({ theme }) => theme.font.size.xs};
font-weight: ${({ theme }) => theme.font.weight.semiBold};
margin-bottom: ${({ theme }) => theme.spacing(1)};
`;

const StyledScrollContainer = styled.div<{ maxHeight: number }>`
max-height: ${({ maxHeight }) => maxHeight}px;
overflow-y: auto;
`;

export const VirtualizedSelect = <T extends SelectValue,>({
className = '',
disabled: disabledFromProps,
fullWidth = false,
label = '',
options,
itemHeight,
maxHeight,
value,
onChange,
dropdownId,
dropdownWidth = 176,
selectSizeVariant,
needIconCheck,
onBlur,
callToActionButton,
emptyOption,
withSearchInput,
dropdownWidthAuto,
}: VirtualizedSelectProps<T>) => {
const [searchInputValue, setSearchInputValue] = useState('');
const [isOpen, setIsOpen] = useState(false);
const selectContainerRef = useRef<HTMLDivElement>(null);
const parentRef = useRef<HTMLDivElement>(null);
const { closeDropdown } = useDropdown(dropdownId);

const filteredOptions = useMemo(
() =>
searchInputValue
? options.filter(({ label }) =>
label.toLowerCase().includes(searchInputValue.toLowerCase()),
)
: options,
[options, searchInputValue],
);

const rowVirtualizer = useVirtualizer({
count: filteredOptions.length,
getScrollElement: () => parentRef.current,
estimateSize: () => itemHeight,
overscan: 5,
});
Comment on lines +72 to +77
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

style: overscan value of 5 may be too low for smooth scrolling with variable height items. Consider increasing to 10-20 for better performance


useEffect(() => {
if (isOpen && parentRef.current) {
parentRef.current.scrollTop = 0;
}
}, [isOpen, searchInputValue]);

const selectedOption = options.find((opt) => opt.value === value) || options[0];

const isDisabled =
disabledFromProps ||
(options.length <= 1 &&
!isDefined(callToActionButton) &&
(!isDefined(emptyOption) || selectedOption !== emptyOption));

const dropDownMenuWidth =
dropdownWidthAuto && selectContainerRef.current?.clientWidth
? selectContainerRef.current?.clientWidth
: dropdownWidth;

return (
<StyledContainer
className={className}
fullWidth={fullWidth}
tabIndex={0}
onBlur={onBlur}
ref={selectContainerRef}
>
{!!label && <StyledLabel>{label}</StyledLabel>}
{isDisabled ? (
<SelectControl
selectedOption={selectedOption}
isDisabled={isDisabled}
selectSizeVariant={selectSizeVariant}
/>
) : (
<Dropdown
dropdownId={dropdownId}
dropdownMenuWidth={dropDownMenuWidth}
dropdownPlacement="bottom-start"
onOpen={() => setIsOpen(true)}
onClose={() => {
setIsOpen(false);
setSearchInputValue('');
}}
clickableComponent={
<SelectControl
selectedOption={selectedOption}
isDisabled={isDisabled}
selectSizeVariant={selectSizeVariant}
/>
}
dropdownComponents={
<>
{withSearchInput && (
<>
<DropdownMenuSearchInput
autoFocus
value={searchInputValue}
onChange={(event) => setSearchInputValue(event.target.value)}
/>
<DropdownMenuSeparator />
</>
)}
<StyledScrollContainer ref={parentRef} maxHeight={maxHeight}>
<div
style={{
height: `${rowVirtualizer.getTotalSize()}px`,
width: '100%',
position: 'relative',
}}
>
{rowVirtualizer.getVirtualItems().map((virtualRow) => {
const option = filteredOptions[virtualRow.index];
return (
<div
key={virtualRow.key}
style={{
position: 'absolute',
top: 0,
left: 0,
width: '100%',
transform: `translateY(${virtualRow.start}px)`,
}}
>
<MenuItemSelect
LeftIcon={option.Icon}
text={option.label}
selected={selectedOption.value === option.value}
needIconCheck={needIconCheck}
onClick={() => {
onChange?.(option.value);
onBlur?.();
closeDropdown();
}}
/>
</div>
);
})}
</div>
</StyledScrollContainer>
{callToActionButton && filteredOptions.length > 0 && (
<>
<DropdownMenuSeparator />
<DropdownMenuItemsContainer hasMaxHeight={false} scrollable={false}>
<MenuItem
onClick={callToActionButton.onClick}
LeftIcon={callToActionButton.Icon}
text={callToActionButton.text}
/>
</DropdownMenuItemsContainer>
</>
)}
</>
}
dropdownHotkeyScope={{ scope: SelectHotkeyScope.Select }}
/>
)}
</StyledContainer>
);
};
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { detectTimeZone } from '@/localization/utils/detectTimeZone';
import { findAvailableTimeZoneOption } from '@/localization/utils/findAvailableTimeZoneOption';
import { AVAILABLE_TIMEZONE_OPTIONS } from '@/settings/accounts/constants/AvailableTimezoneOptions';
import { Select } from '@/ui/input/components/Select';
import { createTimeZoneOptions } from '@/settings/accounts/constants/AvailableTimezoneOptions';
import { VirtualizedSelect } from '@/ui/input/components/VirtualizedSelect';
import { useMemo, useState } from 'react';
import { isDefined } from '~/utils/isDefined';


type DateTimeSettingsTimeZoneSelectProps = {
value?: string;
onChange: (nextValue: string) => void;
Expand All @@ -13,27 +15,41 @@ export const DateTimeSettingsTimeZoneSelect = ({
value = detectTimeZone(),
onChange,
}: DateTimeSettingsTimeZoneSelectProps) => {
const [searchQuery, setSearchQuery] = useState('');
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

logic: searchQuery state is defined but setSearchQuery is never used - this may prevent the search functionality from working

const systemTimeZone = detectTimeZone();

const systemTimeZoneOption = findAvailableTimeZoneOption(systemTimeZone);

const filteredOptions = useMemo(() => {
const allOptions = createTimeZoneOptions();
if (!searchQuery) return allOptions;
Comment on lines +23 to +24
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

style: createTimeZoneOptions() is called on every search - should be memoized separately to avoid regenerating the full list repeatedly


const query = searchQuery.toLowerCase();
return allOptions.filter(option =>
option.label.toLowerCase().includes(query)
);
}, [searchQuery]);

const allOptions = useMemo(() => {
const systemOption = {
label: isDefined(systemTimeZoneOption)
? `System settings - ${systemTimeZoneOption.label}`
: 'System settings',
value: 'system',
};
return [systemOption, ...filteredOptions];
}, [filteredOptions, systemTimeZoneOption]);

return (
<Select
<VirtualizedSelect
dropdownId="settings-accounts-calendar-time-zone"
label="Time zone"
dropdownWidthAuto
fullWidth
value={value}
options={[
{
label: isDefined(systemTimeZoneOption)
? `System settings - ${systemTimeZoneOption.label}`
: 'System settings',
value: 'system',
},
...AVAILABLE_TIMEZONE_OPTIONS,
]}
options={allOptions}
onChange={onChange}
itemHeight={40}
maxHeight={300}
withSearchInput
/>
);
Expand Down
Loading