Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

Fix/timezones picker (#1453)

Anshul sharmaf25cf44fe7b4
diff --git a/packages/form/src/components/Timezone.tsx b/packages/form/src/components/Timezone.tsx
index 631dfe3a2b..17a8122242 100644
--- a/packages/form/src/components/Timezone.tsx
+++ b/packages/form/src/components/Timezone.tsx
@@ -1,5 +1,6 @@
import {
getTimezoneAbbreviations,
+ getTimezoneDisplayName,
getTimezones,
type TimezoneGroup
} from "@carbon/utils";
@@ -17,30 +18,36 @@ type TimezoneProps = Omit<ComboboxProps, "options"> & {
};
/**
- * Searchable timezone picker. Options are flattened to full IANA names with
- * their colloquial abbreviations and current offset —
- * "America/Chicago (CST/CDT, -06:00)" — so search matches by city, region,
- * offset, or the abbreviation people actually type (CST, EST, IST, …). The
- * offset is relative to UTC by definition, so no "UTC" prefix.
+ * One line per zone: "America/New York (GMT-04:00)". `keywords` is searched but
+ * never rendered, so "eastern time", "EST" and "asia kolkata" all find a zone.
*/
const Timezone = ({ options, ...props }: TimezoneProps) => {
const flatOptions = useMemo(() => {
const groups = options?.length ? options : getTimezones();
- return groups.flatMap((group) =>
- group.options.map((option) => {
- const offset = /[+-]\d{2}:\d{2}/.exec(option.label)?.[0];
- const abbreviations = getTimezoneAbbreviations(option.value)
- .filter((a) => a !== option.value)
- .join("/");
- const detail = [abbreviations, offset].filter(Boolean).join(", ");
- return {
- value: option.value,
- label: `${option.value.replace(/_/g, " ")}${
- detail ? ` (${detail})` : ""
- }`
- };
- })
- );
+ return groups
+ .flatMap((group) =>
+ group.options.map((option) => {
+ const offset = /[+-]\d{2}:\d{2}/.exec(option.label)?.[0];
+ const abbreviations = getTimezoneAbbreviations(option.value)
+ .filter((a) => a !== option.value)
+ .join(" ");
+ return {
+ value: option.value,
+ label: `${option.value.replace(/_/g, " ")}${
+ offset ? ` (GMT${offset})` : ""
+ }`,
+ keywords: [
+ option.value,
+ option.value.replace(/[/_]+/g, " "),
+ getTimezoneDisplayName(option.value),
+ abbreviations
+ ]
+ .filter(Boolean)
+ .join(" ")
+ };
+ })
+ )
+ .sort((a, b) => a.label.localeCompare(b.label));
}, [options]);
return <Combobox {...props} options={flatOptions} />;
diff --git a/packages/react/package.json b/packages/react/package.json
index 531b8803eb..97b0bf1e84 100644
--- a/packages/react/package.json
+++ b/packages/react/package.json
@@ -87,7 +87,8 @@
"sonner": "2.0.7",
"tailwind-merge": "catalog:",
"tailwindcss-animate": "catalog:",
- "zustand": "catalog:"
+ "zustand": "catalog:",
+ "match-sorter": "catalog:"
},
"devDependencies": {
"@carbon/config": "workspace:*",
diff --git a/packages/react/src/Combobox.tsx b/packages/react/src/Combobox.tsx
index 10f87c0371..92d84db10f 100644
--- a/packages/react/src/Combobox.tsx
+++ b/packages/react/src/Combobox.tsx
@@ -1,5 +1,6 @@
import { useLingui } from "@lingui/react/macro";
import { useVirtualizer } from "@tanstack/react-virtual";
+import { matchSorter, rankings } from "match-sorter";
import type { ComponentPropsWithoutRef, ReactNode } from "react";
import { forwardRef, useMemo, useRef, useState } from "react";
import { LuCheck, LuPlus, LuSettings2, LuX } from "react-icons/lu";
@@ -19,6 +20,21 @@ import { TruncatedTooltipText } from "./TruncatedTooltipText";
import { cn } from "./utils/cn";
import { reactNodeToString } from "./utils/react";
+export type ComboboxOption = {
+ label: string | JSX.Element;
+ value: string;
+ helper?: string;
+ helperRight?: string;
+ /** Extra search text, matched but never rendered. */
+ keywords?: string;
+};
+
+/** Ranks options against the query. Defaults to `filterComboboxOptions`. */
+export type ComboboxFilter = (
+ options: ComboboxOption[],
+ search: string
+) => ComboboxOption[];
+
export type ComboboxProps = Omit<
ComponentPropsWithoutRef<"button">,
"onChange"
@@ -26,12 +42,8 @@ export type ComboboxProps = Omit<
asButton?: boolean;
size?: "sm" | "md" | "lg";
value?: string;
- options: {
- label: string | JSX.Element;
- value: string;
- helper?: string;
- helperRight?: string;
- }[];
+ options: ComboboxOption[];
+ filter?: ComboboxFilter;
isClearable?: boolean;
isLoading?: boolean;
isReadOnly?: boolean;
@@ -52,6 +64,7 @@ const Combobox = forwardRef<HTMLButtonElement, ComboboxProps>(
size,
value,
options,
+ filter,
isClearable,
isLoading,
isReadOnly,
@@ -176,6 +189,7 @@ const Combobox = forwardRef<HTMLButtonElement, ComboboxProps>(
) : (
<VirtualizedCommand
options={options}
+ filter={filter}
value={value}
onChange={onChange}
itemHeight={itemHeight}
@@ -202,15 +216,46 @@ Combobox.displayName = "Combobox";
export { Combobox };
type VirtualizedCommandProps = {
- options: ComboboxProps["options"];
+ options: ComboboxOption[];
+ filter?: ComboboxFilter;
value?: string;
onChange?: (selected: string) => void;
itemHeight: number;
setOpen: (open: boolean) => void;
};
+const labelOf = (option: ComboboxOption) =>
+ typeof option.label === "string"
+ ? option.label
+ : reactNodeToString(option.label);
+
+/**
+ * Default search. Capped at CONTAINS because match-sorter's fuzzy tier matched
+ * 278 of 419 timezones for "EST"; the joined key lets a query span fields
+ * ("PART-001 Steel Bracket"), which per-key matching alone misses.
+ */
+export function filterComboboxOptions(
+ options: ComboboxOption[],
+ search: string
+): ComboboxOption[] {
+ if (!search) return options;
+ return matchSorter(options, search, {
+ threshold: rankings.CONTAINS,
+ keys: [
+ labelOf,
+ (option) => option.helper ?? "",
+ (option) => option.keywords ?? "",
+ (option) =>
+ [labelOf(option), option.helper, option.keywords]
+ .filter(Boolean)
+ .join(" ")
+ ]
+ });
+}
+
function VirtualizedCommand({
options,
+ filter = filterComboboxOptions,
value,
onChange,
itemHeight,
@@ -220,28 +265,10 @@ function VirtualizedCommand({
const [search, setSearch] = useState("");
const parentRef = useRef<HTMLDivElement>(null);
- const filteredOptions = useMemo(() => {
- if (!search) return options;
- const query = search.toLowerCase();
- // Rank word-boundary hits above mid-word substrings, then earlier hits
- // first — searching "EST" should surface "(EST/EDT, …)" timezones before
- // cities that merely contain "est" (Creston, Bucharest…). Stable sort, so
- // equally-ranked options keep their original order.
- const scored: { option: (typeof options)[number]; score: number }[] = [];
- for (const option of options) {
- const text = (
- typeof option.label === "string"
- ? `${option.label} ${option.helper}`
- : reactNodeToString(option.label)
- ).toLowerCase();
- const index = text.indexOf(query);
- if (index === -1) continue;
- const atWordStart =
- index === 0 || !/[a-z0-9]/.test(text.charAt(index - 1));
- scored.push({ option, score: (atWordStart ? 0 : 100000) + index });
- }
- return scored.sort((a, b) => a.score - b.score).map((s) => s.option);
- }, [options, search]);
+ const filteredOptions = useMemo(
+ () => filter(options, search),
+ [options, search, filter]
+ );
const virtualizer = useVirtualizer({
count: filteredOptions.length,
diff --git a/packages/react/src/index.tsx b/packages/react/src/index.tsx
index 5349229b1b..ed4a5e8b8a 100644
--- a/packages/react/src/index.tsx
+++ b/packages/react/src/index.tsx
@@ -64,8 +64,8 @@ import {
CollapsibleContent,
CollapsibleTrigger
} from "./Collapsible";
-import type { ComboboxProps } from "./Combobox";
-import { Combobox } from "./Combobox";
+import type { ComboboxFilter, ComboboxOption, ComboboxProps } from "./Combobox";
+import { Combobox, filterComboboxOptions } from "./Combobox";
import {
Command,
CommandDialog,
@@ -396,6 +396,7 @@ export {
CollapsibleContent,
CollapsibleTrigger,
Combobox,
+ filterComboboxOptions,
Command,
CommandDialog,
CommandEmpty,
@@ -642,6 +643,8 @@ export type {
ButtonProps,
ChoiceCardOption,
ChoiceSelectOption,
+ ComboboxFilter,
+ ComboboxOption,
ComboboxProps,
CreatableComboboxProps,
CreatableMultiSelectProps,
diff --git a/packages/utils/src/geo.ts b/packages/utils/src/geo.ts
index 4cdb6a92ef..9a694ce44d 100644
--- a/packages/utils/src/geo.ts
+++ b/packages/utils/src/geo.ts
@@ -37,6 +37,31 @@ const timeZoneNameOf = (
return parts.find((p) => p.type === "timeZoneName")?.value ?? "";
};
+const displayNameCache = new Map<string, string>();
+
+/**
+ * A zone's colloquial name ("Eastern Time"), from CLDR. Empty when the runtime
+ * only offers a bare "GMT+05:30", which the offset already covers.
+ */
+export function getTimezoneDisplayName(zone: string): string {
+ const cached = displayNameCache.get(zone);
+ if (cached !== undefined) return cached;
+
+ let name = "";
+ try {
+ const parts = new Intl.DateTimeFormat("en-US", {
+ timeZone: zone,
+ timeZoneName: "longGeneric"
+ }).formatToParts(new Date());
+ const value = parts.find((p) => p.type === "timeZoneName")?.value ?? "";
+ if (!/^(GMT|UTC)([+-]|$)/.test(value)) name = value;
+ } catch {
+ // Unresolvable zone, or an ICU without `longGeneric`.
+ }
+ displayNameCache.set(zone, name);
+ return name;
+}
+
const ABBREVIATION = /^[A-Za-z]{2,6}$/;
const abbreviationCache = new Map<string, string[]>();
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 348b588439..c868be0a10 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -186,6 +186,9 @@ catalogs:
kysely:
specifier: 0.28.15
version: 0.28.15
+ match-sorter:
+ specifier: 8.1.0
+ version: 8.1.0
nanoid:
specifier: 5.1.7
version: 5.1.7
@@ -3157,6 +3160,9 @@ importers:
is-hotkey:
specifier: 0.2.0
version: 0.2.0
+ match-sorter:
+ specifier: 'catalog:'
+ version: 8.1.0
nanoid:
specifier: 'catalog:'
version: 5.1.7
@@ -3247,7 +3253,7 @@ importers:
version: 5.8.3
vitest:
specifier: 'catalog:'
packages/stripe:
dependencies:
@@ -13459,6 +13465,9 @@ packages:
engines: {node: '>= 16'}
hasBin: true
+ resolution: {integrity: sha512-0HX3BHPixkbECX+Vt7nS1vJ6P2twPgGTU3PMXjWrl1eyVCL24tFHeyYN1FN5RKLzve0TyzNI9qntqQGbebnfPQ==}
+
resolution: {integrity: sha512-4vRUvPyxdO8cWULGTh9dZWL2tZK6LDBvj+OGHBER7poH9Qdt7kXEoj20wiz4lQUbUXQZFjPbe5mVDo9nutizCw==}
@@ -15114,6 +15123,9 @@ packages:
engines: {node: '>=16.6.0'}
hasBin: true
+ resolution: {integrity: sha512-8g3/Otx1eJaVD12e31UbJj1YzdtVvzH85HV7t+9MJYk/u3XmkOUJ5Ys9wQrf9PCPK8+xn4ymzqYCiZl6QWKn+A==}
+
resolution: {integrity: sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==}
engines: {node: '>=0.10.0'}
@@ -28001,6 +28013,11 @@ snapshots:
+ dependencies:
+ '@babel/runtime': 7.29.2
+ remove-accents: 0.5.0
+
@@ -30026,6 +30043,8 @@ snapshots:
fs-extra: 11.3.4
minimatch: 10.2.5
+
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index c4c761a750..8c50ac57cc 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -81,6 +81,7 @@ catalog:
isbot: '5'
jose: 6.0.11
kysely: 0.28.15
+ match-sorter: 8.1.0
nanoid: 5.1.7
nanostores: 0.9.5
nodemon: 3.1.14