LuisSanchez commented on code in PR #36486:
URL: https://github.com/apache/superset/pull/36486#discussion_r2644217514
##########
superset-frontend/packages/superset-ui-core/src/components/TimezoneSelector/index.tsx:
##########
@@ -45,118 +65,183 @@ const offsetsToName = {
'060': ['GMT Standard Time - London', 'British Summer Time'],
};
-export type TimezoneSelectorProps = {
- onTimezoneChange: (value: string) => void;
- timezone?: string | null;
- minWidth?: string;
-};
+let cachedTimezoneOptions: TimezoneOption[] | null = null;
+let computePromise: Promise<TimezoneOption[]> | null = null;
+
+function getOffsetKey(timezoneName: string): string {
+ return (
+ JANUARY_REF.tz(timezoneName).utcOffset().toString() +
+ JULY_REF.tz(timezoneName).utcOffset().toString()
+ );
+}
+
+function getTimezoneDisplayName(
+ timezoneName: string,
+ currentDate: ReturnType<typeof extendedDayjs>,
+): string {
+ const offsetKey = getOffsetKey(timezoneName);
+ const dateInZone = currentDate.tz(timezoneName);
+ const isDSTActive = isDST(dateInZone, timezoneName);
+ const namePair = offsetsToName[offsetKey];
+ return namePair ? (isDSTActive ? namePair[1] : namePair[0]) : timezoneName;
+}
+
+function computeTimezoneOptions(): TimezoneOption[] {
+ const currentDate = extendedDayjs(new Date());
+ const allZones = Intl.supportedValuesOf('timeZone');
+ const seenLabels = new Set<string>();
+ const options: TimezoneOption[] = [];
+
+ for (const zone of allZones) {
+ const offsetKey = getOffsetKey(zone);
+ const displayName = getTimezoneDisplayName(zone, currentDate);
+ const offset = currentDate.tz(zone).format('Z');
+ const label = `GMT ${offset} (${displayName})`;
+
+ if (!seenLabels.has(label)) {
+ seenLabels.add(label);
+ options.push({
+ label,
+ value: zone,
+ offsets: offsetKey,
+ timezoneName: zone,
+ });
+ }
+ }
+
+ cachedTimezoneOptions = options;
+ return options;
+}
+
+function getTimezoneOptionsAsync(): Promise<TimezoneOption[]> {
+ if (cachedTimezoneOptions) {
+ return Promise.resolve(cachedTimezoneOptions);
+ }
+
+ if (computePromise) {
+ return computePromise;
+ }
+
+ // Use queueMicrotask for better performance than setTimeout(0)
+ // Falls back to setTimeout for older browsers
+ computePromise = new Promise<TimezoneOption[]>((resolve, reject) => {
+ const run = () => {
+ try {
+ const result = computeTimezoneOptions();
+ resolve(result);
+ } catch (err) {
+ reject(err);
+ } finally {
+ computePromise = null;
+ }
+ };
+ if (typeof queueMicrotask === 'function') {
+ queueMicrotask(run);
+ } else {
+ setTimeout(run, 0);
+ }
+ });
+
+ return computePromise;
+}
+
+function findMatchingTimezone(
+ timezone: string | null | undefined,
+ options: TimezoneOption[],
+): string {
+ const targetTimezone = timezone || extendedDayjs.tz.guess();
+ const targetOffsetKey = getOffsetKey(targetTimezone);
+ let fallbackValue: string | undefined;
+
+ for (const option of options) {
+ if (
+ option.offsets === targetOffsetKey &&
+ option.timezoneName === targetTimezone
+ ) {
+ return option.value;
+ }
+ if (!fallbackValue && option.offsets === targetOffsetKey) {
+ fallbackValue = option.value;
+ }
+ }
+
+ return fallbackValue || DEFAULT_TIMEZONE.value;
+}
export default function TimezoneSelector({
onTimezoneChange,
timezone,
- minWidth = MIN_SELECT_WIDTH, // smallest size for current values
+ minWidth = MIN_SELECT_WIDTH,
+ placeholder,
...rest
}: TimezoneSelectorProps) {
- const { TIMEZONE_OPTIONS, TIMEZONE_OPTIONS_SORT_COMPARATOR, validTimezone } =
- useMemo(() => {
- const currentDate = extendedDayjs();
- const JANUARY = extendedDayjs.tz('2021-01-01');
- const JULY = extendedDayjs.tz('2021-07-01');
-
- const getOffsetKey = (name: string) =>
- JANUARY.tz(name).utcOffset().toString() +
- JULY.tz(name).utcOffset().toString();
-
- const getTimezoneName = (name: string) => {
- const offsets = getOffsetKey(name);
- return (
- (isDST(currentDate.tz(name), name)
- ? offsetsToName[offsets as keyof typeof offsetsToName]?.[1]
- : offsetsToName[offsets as keyof typeof offsetsToName]?.[0]) ||
name
- );
- };
-
- // TODO: remove this ts-ignore when typescript is upgraded to 5.1
- // @ts-ignore
- const ALL_ZONES: string[] = Intl.supportedValuesOf('timeZone');
-
- const labels = new Set<string>();
- const TIMEZONE_OPTIONS = ALL_ZONES.map(zone => {
- const label = `GMT ${extendedDayjs
- .tz(currentDate, zone)
- .format('Z')} (${getTimezoneName(zone)})`;
-
- if (labels.has(label)) {
- return null; // Skip duplicates
- }
- labels.add(label);
- return {
- label,
- value: zone,
- offsets: getOffsetKey(zone),
- timezoneName: zone,
- };
- }).filter(Boolean) as {
- label: string;
- value: string;
- offsets: string;
- timezoneName: string;
- }[];
-
- const TIMEZONE_OPTIONS_SORT_COMPARATOR = (
- a: (typeof TIMEZONE_OPTIONS)[number],
- b: (typeof TIMEZONE_OPTIONS)[number],
- ) =>
- extendedDayjs.tz(currentDate, a.timezoneName).utcOffset() -
- extendedDayjs.tz(currentDate, b.timezoneName).utcOffset();
-
- // pre-sort timezone options by time offset
- TIMEZONE_OPTIONS.sort(TIMEZONE_OPTIONS_SORT_COMPARATOR);
-
- const matchTimezoneToOptions = (timezone: string) => {
- const offsetKey = getOffsetKey(timezone);
- let fallbackValue: string | undefined;
-
- for (const option of TIMEZONE_OPTIONS) {
- if (
- option.offsets === offsetKey &&
- option.timezoneName === timezone
- ) {
- return option.value;
- }
- if (!fallbackValue && option.offsets === offsetKey) {
- fallbackValue = option.value;
- }
- }
- return fallbackValue || DEFAULT_TIMEZONE.value;
- };
-
- const validTimezone = matchTimezoneToOptions(
- timezone || extendedDayjs.tz.guess(),
- );
-
- return {
- TIMEZONE_OPTIONS,
- TIMEZONE_OPTIONS_SORT_COMPARATOR,
- validTimezone,
- };
- }, [timezone]);
-
- // force trigger a timezone update if provided `timezone` is not invalid
+ const [timezoneOptions, setTimezoneOptions] = useState<
+ TimezoneOption[] | null
+ >(cachedTimezoneOptions);
+ const [isLoadingOptions, setIsLoadingOptions] = useState(false);
+ const hasSetDefaultRef = useRef(false);
+
+ const handleOpenChange = useCallback(
+ (isOpen: boolean) => {
+ if (isOpen && !timezoneOptions && !isLoadingOptions) {
+ setIsLoadingOptions(true);
+ getTimezoneOptionsAsync()
+ .then(setTimezoneOptions)
+ .finally(() => setIsLoadingOptions(false));
+ }
+ },
+ [timezoneOptions, isLoadingOptions],
+ );
+
+ const sortComparator = useMemo(() => {
+ if (!timezoneOptions) return undefined;
+ const currentDate = extendedDayjs();
+ return (a: TimezoneOption, b: TimezoneOption) =>
+ currentDate.tz(a.timezoneName).utcOffset() -
+ currentDate.tz(b.timezoneName).utcOffset();
+ }, [timezoneOptions]);
+
+ const validTimezone = useMemo(() => {
+ if (!timezoneOptions) {
+ return timezone || extendedDayjs.tz.guess();
+ }
+ return findMatchingTimezone(timezone, timezoneOptions);
+ }, [timezone, timezoneOptions]);
+
+ // Preload timezone options on mount and set default value
useEffect(() => {
- if (validTimezone && timezone !== validTimezone) {
- onTimezoneChange(validTimezone);
+ if (!timezoneOptions && !isLoadingOptions) {
+ setIsLoadingOptions(true);
+ getTimezoneOptionsAsync()
+ .then(options => {
+ setTimezoneOptions(options);
+ // Set default value if no timezone is provided and we haven't set
it yet
+ if (!timezone && !hasSetDefaultRef.current) {
+ const defaultTz = findMatchingTimezone(null, options);
+ onTimezoneChange(defaultTz);
+ hasSetDefaultRef.current = true;
+ }
+ })
+ .finally(() => setIsLoadingOptions(false));
+ } else if (timezoneOptions && !timezone && !hasSetDefaultRef.current) {
+ // If options are already available (cached), set default immediately
+ const defaultTz = findMatchingTimezone(null, timezoneOptions);
+ onTimezoneChange(defaultTz);
+ hasSetDefaultRef.current = true;
}
- }, [validTimezone, onTimezoneChange, timezone]);
+ }, [timezoneOptions, isLoadingOptions, timezone, onTimezoneChange]);
return (
<Select
ariaLabel={t('Timezone selector')}
onChange={tz => onTimezoneChange(tz as string)}
- value={validTimezone}
- options={TIMEZONE_OPTIONS}
- sortComparator={TIMEZONE_OPTIONS_SORT_COMPARATOR}
- {...rest}
+ onOpenChange={handleOpenChange}
+ value={timezoneOptions ? validTimezone : undefined}
+ options={timezoneOptions || []}
+ sortComparator={sortComparator}
+ loading={isLoadingOptions}
+ placeholder={isLoadingOptions ? t('Loading timezones...') : placeholder}
+ {...({ placement: 'topLeft', ...rest } as any)}
Review Comment:
Done!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]