Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat(ui): add inline and dialog creation to v3 combobox (#8225)
Andrew Huangcf8f461e6f0a
diff --git a/frontend/src/components/COMPONENT_LIFECYCLE.md b/frontend/src/components/COMPONENT_LIFECYCLE.mdindex 13ffe12fcc..00ae569abc 100644--- a/frontend/src/components/COMPONENT_LIFECYCLE.md+++ b/frontend/src/components/COMPONENT_LIFECYCLE.md@@ -24,7 +24,7 @@ This ledger records lifecycle decisions that aren't obvious from component sourc| Components | Status | Direction || ------------------------------ | ---------- | --------------------------------------------------------------------- || `ReactSelect/FilterableSelect` | Deprecated | Use `Combobox`; keep compatibility available while consumers migrate. |-| `ReactSelect/CreatableSelect` | Blocked | `Combobox` doesn't support inline option creation. |+| `ReactSelect/CreatableSelect` | Deprecated | Use `Combobox` with inline `creation` for values needing no metadata, or dialog `creation` for caller-owned forms and persistence. Keep compatibility for react-select-specific component overrides; migrate consumers separately. |## Updating the ledgerdiff --git a/frontend/src/components/external-migrations/VaultConnectionAndNamespaceFields.tsx b/frontend/src/components/external-migrations/VaultConnectionAndNamespaceFields.tsxindex e67a7dc8ce..462e4d7186 100644--- a/frontend/src/components/external-migrations/VaultConnectionAndNamespaceFields.tsx+++ b/frontend/src/components/external-migrations/VaultConnectionAndNamespaceFields.tsx@@ -20,9 +20,9 @@ import { useGetVaultNamespaces } from "@app/hooks/api/migration/queries";type Props = {appConnections: TAvailableAppConnection[];connectionId: string | null;- onConnectionIdChange: (connectionId: string) => void;+ onConnectionIdChange: (connectionId: string | null) => void;namespace: string | null;- onNamespaceChange: (namespace: string) => void;+ onNamespaceChange: (namespace: string | null) => void;namespaceTooltip: string;namespaceHelpText: string;idPrefix?: string;@@ -94,7 +94,7 @@ export const VaultConnectionAndNamespaceFields = ({<Comboboxid={connectionInputId}value={appConnections.find((connection) => connection.id === connectionId) ?? null}- onValueChange={(connection) => onConnectionIdChange(connection.id)}+ onValueChange={(connection) => onConnectionIdChange(connection?.id ?? null)}options={appConnections}getOptionValue={(option) => option.id}getOptionLabel={(option) => option.name}@@ -132,7 +132,7 @@ export const VaultConnectionAndNamespaceFields = ({<Comboboxid={namespaceInputId}value={namespaces?.find((option) => option.name === namespace) ?? null}- onValueChange={(option) => onNamespaceChange(option.name)}+ onValueChange={(option) => onNamespaceChange(option?.name ?? null)}options={namespaces ?? []}getOptionValue={(option) => option.name}getOptionLabel={(option) => (option.name === "/" ? "root" : option.name)}diff --git a/frontend/src/components/external-migrations/vaultImportSelection.ts b/frontend/src/components/external-migrations/vaultImportSelection.tsindex 5b354e26f3..37a1fa80d2 100644--- a/frontend/src/components/external-migrations/vaultImportSelection.ts+++ b/frontend/src/components/external-migrations/vaultImportSelection.ts@@ -6,8 +6,8 @@ export type VaultImportSelectionState<TSelection> = {};export type VaultImportSelectionAction<TSelection> =- | { type: "connection"; value: string }- | { type: "namespace"; value: string }+ | { type: "connection"; value: string | null }+ | { type: "namespace"; value: string | null }| { type: "mount"; value: string | null }| { type: "selection"; value: TSelection | null };diff --git a/frontend/src/components/secret-syncs/forms/SecretSyncConnectionField.tsx b/frontend/src/components/secret-syncs/forms/SecretSyncConnectionField.tsxindex c1f68b59ba..ce1273f25f 100644--- a/frontend/src/components/secret-syncs/forms/SecretSyncConnectionField.tsx+++ b/frontend/src/components/secret-syncs/forms/SecretSyncConnectionField.tsx@@ -100,6 +100,11 @@ export const SecretSyncConnectionField = ({ onChange: callback }: Props) => {<Comboboxvalue={value}onValueChange={(newValue) => {+ if (!newValue) {+ onChange(null);+ if (callback) callback();+ return;+ }if (newValue.id === "_create") {handlePopUpOpen("addConnection");// store for oauth callback connectionsdiff --git a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/1PasswordSyncFields.tsx b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/1PasswordSyncFields.tsxindex 4f0e0c8ec8..c15906ec0c 100644--- a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/1PasswordSyncFields.tsx+++ b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/1PasswordSyncFields.tsx@@ -70,7 +70,7 @@ export const OnePassSyncFields = () => {isLoading={isVaultsLoading && Boolean(connectionId)}isDisabled={!connectionId}value={vaults?.find((v) => v.id === value) || null}- onValueChange={(option) => onChange(option.id ?? null)}+ onValueChange={(option) => onChange(option?.id ?? null)}options={vaults}placeholder="Select a vault..."getOptionLabel={(option) => option.name}diff --git a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/AzureDevOpsSyncFields.tsx b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/AzureDevOpsSyncFields.tsxindex b30d5d099e..cad4f6c750 100644--- a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/AzureDevOpsSyncFields.tsx+++ b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/AzureDevOpsSyncFields.tsx@@ -69,8 +69,8 @@ export const AzureDevOpsSyncFields = () => {isDisabled={!connectionId}value={projects?.find((v) => v.appId === value) ?? null}onValueChange={(option) => {- onChange(option.appId ?? null);- setValue("destinationConfig.devopsProjectName", option.name ?? "");+ onChange(option?.appId ?? null);+ setValue("destinationConfig.devopsProjectName", option?.name ?? "");}}options={projects}placeholder="Select a project..."diff --git a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/CamundaSyncFields.tsx b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/CamundaSyncFields.tsxindex 80f60d5157..77b0a20253 100644--- a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/CamundaSyncFields.tsx+++ b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/CamundaSyncFields.tsx@@ -71,8 +71,8 @@ export const CamundaSyncFields = () => {isDisabled={!connectionId}value={clusters?.find((cluster) => cluster.uuid === value) ?? null}onValueChange={(option) => {- onChange(option.uuid ?? null);- setValue("destinationConfig.clusterName", option.name ?? "");+ onChange(option?.uuid ?? null);+ setValue("destinationConfig.clusterName", option?.name ?? "");}}options={clusters}placeholder="Select a cluster..."diff --git a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/CloudflarePagesSyncFields.tsx b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/CloudflarePagesSyncFields.tsxindex 71d61e81af..9fb1c3c588 100644--- a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/CloudflarePagesSyncFields.tsx+++ b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/CloudflarePagesSyncFields.tsx@@ -73,7 +73,7 @@ export const CloudflarePagesSyncFields = () => {isDisabled={!connectionId}value={projects.find((project) => project.name === value) ?? null}onValueChange={(option) => {- onChange(option.name ?? null);+ onChange(option?.name ?? null);}}options={projects}placeholder="Select a project..."diff --git a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/CloudflareWorkersSyncFields.tsx b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/CloudflareWorkersSyncFields.tsxindex 1510bb80f9..f0ef119b63 100644--- a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/CloudflareWorkersSyncFields.tsx+++ b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/CloudflareWorkersSyncFields.tsx@@ -56,7 +56,7 @@ export const CloudflareWorkersSyncFields = () => {isDisabled={!connectionId}value={scripts?.find((script) => script.id === value) ?? null}onValueChange={(option) => {- onChange(option.id ?? null);+ onChange(option?.id ?? null);}}options={scripts}placeholder="Select a worker script..."diff --git a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/DatabricksSyncFields.tsx b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/DatabricksSyncFields.tsxindex 31cdc13d4f..200c692416 100644--- a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/DatabricksSyncFields.tsx+++ b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/DatabricksSyncFields.tsx@@ -69,7 +69,7 @@ export const DatabricksSyncFields = () => {isLoading={isSecretScopesPending && Boolean(connectionId)}isDisabled={!connectionId}value={secretScopes.find((scope) => scope.name === value) ?? null}- onValueChange={(option) => onChange(option.name ?? null)}+ onValueChange={(option) => onChange(option?.name ?? null)}options={secretScopes}placeholder="Select a secret scope..."getOptionLabel={(option) => option.name}diff --git a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/GcpSyncFields.tsx b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/GcpSyncFields.tsxindex 300a38126a..b59c6e4456 100644--- a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/GcpSyncFields.tsx+++ b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/GcpSyncFields.tsx@@ -189,7 +189,7 @@ export const GcpSyncFields = () => {onValueChange={(option) => {setValue("destinationConfig.locationId", "");setValue("destinationConfig.userReplicaLocationIds", []);- onChange(option.id);+ onChange(option?.id ?? "");}}options={projects ?? []}placeholder="Select a GCP project..."@@ -281,7 +281,7 @@ export const GcpSyncFields = () => {isLoading={areLocationsPending && Boolean(projectId)}isDisabled={!projectId}value={locations?.find((option) => option.locationId === value) ?? null}- onValueChange={(option) => onChange(option.locationId)}+ onValueChange={(option) => onChange(option?.locationId ?? "")}options={locations ?? []}placeholder="Select a region..."getOptionLabel={(option) => `${option.displayName} (${option.locationId})`}diff --git a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/GitHubSyncFields.tsx b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/GitHubSyncFields.tsxindex 3d3ea94a1c..99be19a96b 100644--- a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/GitHubSyncFields.tsx+++ b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/GitHubSyncFields.tsx@@ -121,9 +121,9 @@ export const GitHubSyncFields = () => {isDisabled={!connectionId}value={organizations.find((org) => org.login === value) ?? null}onValueChange={(option) => {- if (option.login === value) return;+ if (option?.login === value) return;- onChange(option.login);+ onChange(option?.login ?? "");setValue("destinationConfig.selectedRepositoryIds", []);}}options={organizations}@@ -274,7 +274,7 @@ export const GitHubSyncFields = () => {isLoading={isEnvironmentsPending && Boolean(connectionId) && Boolean(currentRepo)}isDisabled={!connectionId || !currentRepo}value={environments.find((env) => env.name === value) ?? null}- onValueChange={(option) => onChange(option.name ?? null)}+ onValueChange={(option) => onChange(option?.name ?? null)}options={environments}placeholder="Select an environment..."getOptionLabel={(option) => option.name}diff --git a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/HCVaultSyncFields.tsx b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/HCVaultSyncFields.tsxindex 00b8007cb5..1747b41789 100644--- a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/HCVaultSyncFields.tsx+++ b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/HCVaultSyncFields.tsx@@ -70,7 +70,7 @@ export const HCVaultSyncFields = () => {isLoading={isMountsLoading && Boolean(connectionId)}isDisabled={!connectionId}value={value ? { label: value, value } : null}- onValueChange={(option) => onChange(option.value)}+ onValueChange={(option) => onChange(option?.value ?? "")}options={mounts?.map((mount) => ({ label: mount, value: mount })) ?? []}placeholder="Select a Secrets Engine Mount..."getOptionLabel={(option) => option.label}diff --git a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/HerokuSyncFields.tsx b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/HerokuSyncFields.tsxindex a0d97eeda2..1586a18a83 100644--- a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/HerokuSyncFields.tsx+++ b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/HerokuSyncFields.tsx@@ -64,8 +64,8 @@ export const HerokuSyncFields = () => {isDisabled={!connectionId}value={apps?.find((app) => app.id === value) ?? null}onValueChange={(option) => {- onChange(option.id ?? "");- setValue("destinationConfig.appName", option.name ?? "");+ onChange(option?.id ?? "");+ setValue("destinationConfig.appName", option?.name ?? "");}}options={apps}placeholder="Select an app..."diff --git a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/HumanitecSyncFields.tsx b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/HumanitecSyncFields.tsxindex d68484eba4..0701383375 100644--- a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/HumanitecSyncFields.tsx+++ b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/HumanitecSyncFields.tsx@@ -71,7 +71,7 @@ export const HumanitecSyncFields = () => {isDisabled={!connectionId}value={organizations?.find((org) => org.id === value) ?? null}onValueChange={(option) => {- onChange(option.id ?? null);+ onChange(option?.id ?? null);setValue("destinationConfig.app", "");setValue("destinationConfig.env", "");}}@@ -118,7 +118,7 @@ export const HumanitecSyncFields = () => {?.apps?.find((app) => app.id === value) ?? null}onValueChange={(option) => {- onChange(option.id ?? null);+ onChange(option?.id ?? null);setValue("destinationConfig.env", "");}}options={@@ -214,7 +214,7 @@ export const HumanitecSyncFields = () => {}isDisabled={!connectionId || !currentApp}value={environments.find((env) => env.id === value) ?? null}- onValueChange={(option) => onChange(option.id ?? null)}+ onValueChange={(option) => onChange(option?.id ?? null)}options={environments}placeholder="Select an env..."getOptionLabel={(option) => option.name}diff --git a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/OCIVaultSyncFields.tsx b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/OCIVaultSyncFields.tsxindex 3a21f2824b..a55c0cdf06 100644--- a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/OCIVaultSyncFields.tsx+++ b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/OCIVaultSyncFields.tsx@@ -91,7 +91,7 @@ export const OCIVaultSyncFields = () => {isDisabled={!connectionId}value={compartments?.find((c) => c.id === value) ?? null}onValueChange={(option) => {- onChange(option.id ?? null);+ onChange(option?.id ?? null);setValue("destinationConfig.vaultOcid", "");setValue("destinationConfig.keyOcid", "");}}@@ -138,7 +138,7 @@ export const OCIVaultSyncFields = () => {isDisabled={!connectionId || !selectedCompartment}value={vaults?.find((v) => v.id === value) || null}onValueChange={(option) => {- onChange(option.id ?? null);+ onChange(option?.id ?? null);setValue("destinationConfig.keyOcid", "");}}options={vaults}@@ -184,7 +184,7 @@ export const OCIVaultSyncFields = () => {isDisabled={!connectionId || !selectedCompartment || !selectedVault}value={keys?.find((v) => v.id === value) ?? null}onValueChange={(option) => {- onChange(option.id ?? null);+ onChange(option?.id ?? null);}}options={keys}placeholder="Select a key..."diff --git a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/RenderSyncFields.tsx b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/RenderSyncFields.tsxindex 0b91d09c65..c92f715b6f 100644--- a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/RenderSyncFields.tsx+++ b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/RenderSyncFields.tsx@@ -130,8 +130,8 @@ export const RenderSyncFields = () => {isDisabled={!connectionId}value={services?.find((service) => service.id === value) ?? null}onValueChange={(option) => {- onChange(option.id ?? null);- setValue("destinationConfig.serviceName", option.name ?? "");+ onChange(option?.id ?? null);+ setValue("destinationConfig.serviceName", option?.name ?? "");}}options={services}placeholder="Select a service..."@@ -171,8 +171,8 @@ export const RenderSyncFields = () => {isDisabled={!connectionId}value={groups?.find((group) => group.id === value) ?? null}onValueChange={(option) => {- onChange(option.id ?? null);- setValue("destinationConfig.environmentGroupName", option.name ?? "");+ onChange(option?.id ?? null);+ setValue("destinationConfig.environmentGroupName", option?.name ?? "");}}options={groups}placeholder="Select an environment group..."diff --git a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/SnowflakeSyncFields.tsx b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/SnowflakeSyncFields.tsxindex 5ed2065bae..24916a8435 100644--- a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/SnowflakeSyncFields.tsx+++ b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/SnowflakeSyncFields.tsx@@ -81,7 +81,7 @@ export const SnowflakeSyncFields = () => {value={databases.find((db) => db.name === value) ?? null}onValueChange={(option) => {setValue("destinationConfig.schema", "");- onChange(option.name ?? "");+ onChange(option?.name ?? "");}}options={databases}placeholder="Select a database..."@@ -124,7 +124,7 @@ export const SnowflakeSyncFields = () => {isLoading={isSchemasPending && Boolean(connectionId) && Boolean(database)}isDisabled={!connectionId || !database}value={schemas.find((schema) => schema.name === value) ?? null}- onValueChange={(option) => onChange(option.name ?? "")}+ onValueChange={(option) => onChange(option?.name ?? "")}options={schemas}placeholder="Select a schema..."getOptionLabel={(option) => option.name}diff --git a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/TeamCitySyncFields.tsx b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/TeamCitySyncFields.tsxindex 2ab8d022f2..d327cc3370 100644--- a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/TeamCitySyncFields.tsx+++ b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/TeamCitySyncFields.tsx@@ -76,7 +76,7 @@ export const TeamCitySyncFields = () => {isDisabled={!connectionId}value={projects?.find((proj) => proj.id === value) ?? null}onValueChange={(option) => {- onChange(option.id ?? null);+ onChange(option?.id ?? null);setValue("destinationConfig.buildConfig", "");}}options={projects}diff --git a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/TerraformCloudSyncFields.tsx b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/TerraformCloudSyncFields.tsxindex 52f645b269..c24739a140 100644--- a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/TerraformCloudSyncFields.tsx+++ b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/TerraformCloudSyncFields.tsx@@ -80,7 +80,7 @@ export const TerraformCloudSyncFields = () => {organizations ? (organizations.find((org) => org.id === value) ?? null) : null}onValueChange={(option) => {- onChange(option.id ?? null);+ onChange(option?.id ?? null);setValue("destinationConfig.variableSetId", "");setValue("destinationConfig.workspaceId", "");setValue("destinationConfig.variableSetName", "");diff --git a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/VercelSyncFields.tsx b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/VercelSyncFields.tsxindex 813f027d7a..875e6d30c4 100644--- a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/VercelSyncFields.tsx+++ b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/VercelSyncFields.tsx@@ -205,6 +205,11 @@ export const VercelSyncFields = () => {isError={Boolean(error)}value={value || null}onValueChange={(id) => {+ if (!id) {+ onChange("");+ setValue("destinationConfig.teamName", "");+ return;+ }const option = teams?.find((team) => team.id === id);if (!option || id === value) return;onChange(id);@@ -366,6 +371,13 @@ export const VercelSyncFields = () => {isDisabled={!connectionId}value={value || null}onValueChange={(id) => {+ if (!id) {+ onChange("");+ setValue("destinationConfig.appName", "");+ setValue("destinationConfig.env", "");+ setValue("destinationConfig.branch", "");+ return;+ }const selected = availableApps.find((app) => app.id === id);if (!selected || id === value) return;onChange(id);@@ -422,7 +434,7 @@ export const VercelSyncFields = () => {: null}onValueChange={(option) => {- const envKey = option.key;+ const envKey = option?.key ?? "";onChange(envKey);setValue("destinationConfig.branch", "");diff --git a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/WindmillSyncFields.tsx b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/WindmillSyncFields.tsxindex f017ca3c55..58dea3b80a 100644--- a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/WindmillSyncFields.tsx+++ b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/WindmillSyncFields.tsx@@ -69,7 +69,7 @@ export const WindmillSyncFields = () => {isLoading={isWorkspacesLoading && Boolean(connectionId)}isDisabled={!connectionId}value={workspaces?.find((workspace) => workspace.name === value) ?? null}- onValueChange={(option) => onChange(option.name ?? null)}+ onValueChange={(option) => onChange(option?.name ?? null)}options={workspaces}placeholder="Select a workspace..."getOptionLabel={(option) => option.name}diff --git a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/shared/AwsRegionSelect.tsx b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/shared/AwsRegionSelect.tsxindex 3f63bd2208..47ca3c8f2e 100644--- a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/shared/AwsRegionSelect.tsx+++ b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/shared/AwsRegionSelect.tsx@@ -24,7 +24,7 @@ export const AwsRegionSelect = ({ id, value, onChange, isError, ...props }: Prop<Comboboxid={id}value={AWS_REGIONS.find((region) => region.slug === value)}- onValueChange={(option) => onChange(option.slug)}+ onValueChange={(option) => onChange(option?.slug ?? "")}options={AWS_REGIONS}isError={isError}placeholder="Select region..."diff --git a/frontend/src/components/v3/generic/Combobox/Combobox.regression.stories.tsx b/frontend/src/components/v3/generic/Combobox/Combobox.regression.stories.tsxnew file mode 100644index 0000000000..8ca18c7f9d--- /dev/null+++ b/frontend/src/components/v3/generic/Combobox/Combobox.regression.stories.tsx@@ -0,0 +1,48 @@+import type { Meta, StoryObj } from "@storybook/react-vite";++import { Combobox } from "./Combobox";+import {+ ComboboxStoryFrame,+ DismissedPendingCreation as DismissedPendingCreationStory,+ OpaqueOptionFields as OpaqueOptionFieldsStory,+ PreserveNewQueryDuringCreation as PreserveNewQueryDuringCreationStory,+ ServerFilteredSelection as ServerFilteredSelectionStory,+ SingleDismissedFailure as SingleDismissedFailureStory,+ UnmountedPendingCreation as UnmountedPendingCreationStory,+ ValidatedCreation as ValidatedCreationStory,+ ViewportEdges as ViewportEdgesStory+} from "./Combobox.stories";++const meta = {+ title: "Generic/Combobox/Regression",+ component: Combobox,+ parameters: {+ layout: "centered",+ docs: { disable: true }+ },+ tags: ["!autodocs"],+ decorators: [+ (Story, context) => (+ <ComboboxStoryFrame fullscreen={context.parameters.layout === "fullscreen"}>+ <Story />+ </ComboboxStoryFrame>+ )+ ],+ globals: {+ backgrounds: { value: "card" }+ }+} satisfies Meta<typeof Combobox>;++export default meta;+type Story = StoryObj;++export const OpaqueOptionFields: Story = { ...OpaqueOptionFieldsStory };+export const ViewportEdges: Story = { ...ViewportEdgesStory };+export const ServerFilteredSelection: Story = { ...ServerFilteredSelectionStory };+export const SingleDismissedFailure: Story = { ...SingleDismissedFailureStory };+export const DismissedPendingCreation: Story = { ...DismissedPendingCreationStory };+export const PreserveNewQueryDuringCreation: Story = {+ ...PreserveNewQueryDuringCreationStory+};+export const UnmountedPendingCreation: Story = { ...UnmountedPendingCreationStory };+export const ValidatedCreation: Story = { ...ValidatedCreationStory };diff --git a/frontend/src/components/v3/generic/Combobox/Combobox.stories.tsx b/frontend/src/components/v3/generic/Combobox/Combobox.stories.tsxindex d8117d9eb4..058cd699eb 100644--- a/frontend/src/components/v3/generic/Combobox/Combobox.stories.tsx+++ b/frontend/src/components/v3/generic/Combobox/Combobox.stories.tsx@@ -1,6 +1,14 @@-import { createContext, type ReactNode, useContext, useEffect, useState } from "react";+import {+ type ComponentType,+ createContext,+ type FormEvent,+ type ReactNode,+ useContext,+ useEffect,+ useState+} from "react";import type { Meta, StoryObj } from "@storybook/react-vite";-import { expect, userEvent, within } from "storybook/test";+import { expect, userEvent, waitFor, within } from "storybook/test";import { useDebounce } from "@app/hooks";@@ -9,12 +17,15 @@ import {Dialog,DialogContent,DialogDescription,+ DialogFooter,DialogHeader,DialogTitle,DialogTrigger} from "../Dialog";import { Field, FieldError, FieldLabel } from "../Field";-import { Combobox, type ComboboxProps } from "./Combobox";+import { Input } from "../Input";+import { TextArea } from "../TextArea";+import { Combobox, type ComboboxDialogCreationRenderProps, type ComboboxProps } from ".";const ENVIRONMENTS = [{ id: "development", name: "Development" },@@ -26,21 +37,25 @@ const ORGANIZATION_ROLES = [{slug: "admin",name: "Admin",+ items: 4,description: "Can manage organization settings, billing, members, and projects."},{slug: "member",name: "Member",+ items: 38,description: "Can access assigned projects but cannot manage the organization."},{slug: "no-access",name: "No Access",+ items: 2,description: "Cannot access the organization until a more permissive role is assigned."},...Array.from({ length: 24 }, (_, index) => ({slug: `custom-role-${index + 1}`,name: `Custom role ${index + 1}`,+ items: index + 1,description:"A custom organization role with a longer description that can wrap onto two lines."}))@@ -58,15 +73,41 @@ const VAULTS = [{ id: "security", name: "Security", items: 7 }] as const;+type TagOption = { id: string; name: string; group: string };++const TAGS: TagOption[] = [+ { id: "production", name: "production", group: "Environment" },+ { id: "staging", name: "staging", group: "Environment" },+ { id: "compliance", name: "compliance", group: "Policy" },+ { id: "rotation-required", name: "rotation-required", group: "Policy" }+];++const sleep = (duration: number) =>+ new Promise<void>((resolve) => {+ window.setTimeout(resolve, duration);+ });++const getTrailingSlot = (input: HTMLElement) => {+ const control = input.closest("[data-slot='combobox-control']") ?? input.parentElement;+ return control?.querySelector("[data-slot='combobox-trailing-slot']");+};++const clickOpenTrailingClear = (input: HTMLElement) => {+ const button = getTrailingSlot(input)?.querySelector("button");+ if (!(button instanceof HTMLButtonElement)) throw new Error("Expected a trailing clear button");+ button.click();+};+const ComboboxStoryPortalContext = createContext<HTMLElement | null>(null);const StoryCombobox = <TOption,>(props: ComboboxProps<TOption>) => {const portalContainer = useContext(ComboboxStoryPortalContext);const { modal } = props;- return <Combobox {...props} portalContainer={modal ? undefined : portalContainer} />;+ const StoryComponent = Combobox as ComponentType<ComboboxProps<TOption>>;+ return <StoryComponent {...props} portalContainer={modal ? undefined : portalContainer} />;};-const ComboboxStoryFrame = ({+export const ComboboxStoryFrame = ({children,fullscreen = false}: {@@ -92,6 +133,18 @@ const ComboboxStoryFrame = ({const meta = {title: "Generic/Combobox",component: Combobox,+ includeStories: [+ "Default",+ "RichOptions",+ "Multiple",+ "ChipLayouts",+ "ServerSearch",+ "InDialog",+ "States",+ "InlineCreation",+ "DialogCreation",+ "GroupedRemoteCreation"+ ],parameters: {layout: "centered"},@@ -119,23 +172,29 @@ type Story = StoryObj;const DefaultRender = () => {const [value, setValue] = useState<(typeof ENVIRONMENTS)[number] | null>(null);+ const [clearCount, setClearCount] = useState(0);return (- <Field>- <FieldLabel htmlFor="combobox-environment">Environment</FieldLabel>- <StoryCombobox- id="combobox-environment"- options={ENVIRONMENTS}- value={value}- onValueChange={setValue}- onClear={() => setValue(null)}- getOptionValue={(option) => option.id}- getOptionLabel={(option) => option.name}- placeholder="Select environment..."- searchPlaceholder="Search environments..."- searchAriaLabel="Search environments"- />- </Field>+ <div>+ <Field>+ <FieldLabel htmlFor="combobox-environment">Environment</FieldLabel>+ <StoryCombobox+ id="combobox-environment"+ options={ENVIRONMENTS}+ value={value}+ onValueChange={(nextValue: (typeof ENVIRONMENTS)[number] | null) => {+ setValue(nextValue);+ if (nextValue === null) setClearCount((current) => current + 1);+ }}+ getOptionValue={(option) => option.id}+ getOptionLabel={(option) => option.name}+ placeholder="Select environment..."+ searchPlaceholder="Search environments..."+ searchAriaLabel="Search environments"+ />+ </Field>+ <p className="sr-only">Clear actions: {clearCount}</p>+ </div>);};@@ -143,10 +202,44 @@ const DefaultRender = () => {* `Combobox` is a searchable object select built on Base UI and styled to match* Infisical's Radix-based controls. It portals its menu, flips near viewport* edges, and limits the scrollable option list to the available space. Selected- * values remain the original option objects for controlled form libraries.+ * values remain the original option objects for controlled form libraries. Single+ * selections are clearable by default and emit `null`; use `onClear` to override+ * that reset or `isClearable={false}` when the domain has no empty state.*/export const Default: Story = {- render: () => <DefaultRender />+ render: () => <DefaultRender />,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const input = canvas.getByRole("combobox", { name: "Environment" });++ await expect(input).toHaveAttribute("placeholder", "Select environment...");+ await expect(getTrailingSlot(input)).toHaveAttribute("data-state", "chevron");+ await userEvent.click(input);+ await expect(input).toHaveAttribute("placeholder", "Select environment...");+ await userEvent.type(input, "prod");+ await expect(input).toHaveValue("prod");+ await userEvent.click(canvas.getByRole("option", { name: "Production" }));+ await expect(input).toHaveValue("Production");+ await expect(getTrailingSlot(input)).toHaveAttribute("data-state", "clear");++ await userEvent.click(canvas.getByRole("button", { name: "Clear selection" }));+ await expect(input).toHaveValue("");+ await expect(getTrailingSlot(input)).toHaveAttribute("data-state", "chevron");++ await userEvent.click(input);+ await userEvent.click(canvas.getByRole("option", { name: "Staging" }));+ await userEvent.click(input);+ await expect(input).toHaveValue("Staging");+ await expect(canvas.getByRole("option", { name: "Development" })).toBeInTheDocument();+ await expect(+ canvas.getByRole("button", { name: "Clear selection", hidden: true })+ ).toBeInTheDocument();+ await userEvent.type(input, "dev");+ await expect(input).toHaveValue("dev");+ clickOpenTrailingClear(input);+ await waitFor(() => expect(input).toHaveValue(""));+ await expect(getTrailingSlot(input)).toHaveAttribute("data-state", "chevron");+ }};const ALL_ORGANIZATIONS = Array.from({ length: 2_000 }, (_, index) => ({@@ -169,7 +262,11 @@ const fetchOrganizations = (search: string) =>});const ServerSearchRender = () => {- const [value, setValue] = useState<(typeof ALL_ORGANIZATIONS)[number] | null>(null);+ const [value, setValue] = useState<(typeof ALL_ORGANIZATIONS)[number] | null>(+ ALL_ORGANIZATIONS[1998]+ );+ const [valueChangeCount, setValueChangeCount] = useState(0);+ const [clearOverrideCount, setClearOverrideCount] = useState(0);const [search, setSearch] = useState("");const [debouncedSearch] = useDebounce(search);const [organizations, setOrganizations] = useState<typeof ALL_ORGANIZATIONS>([]);@@ -191,29 +288,49 @@ const ServerSearchRender = () => {}, [debouncedSearch]);return (- <Field>- <FieldLabel htmlFor="combobox-server-search">Organization</FieldLabel>- <StoryCombobox- id="combobox-server-search"- options={organizations}- value={value}- onValueChange={setValue}- onClear={() => setValue(null)}- onSearchChange={setSearch}- isLoading={isLoading || search !== debouncedSearch}- getOptionValue={(option) => option.id}- getOptionLabel={(option) => option.name}- placeholder="Select organization..."- searchPlaceholder="Search organizations..."- searchAriaLabel="Search organizations"- emptyMessage="No organizations match that search."- listFooter={- totalCount > organizations.length- ? `Showing ${organizations.length} of ${totalCount.toLocaleString()} — type to search the rest`- : null- }- />- </Field>+ <div className="flex flex-col gap-2">+ <Field>+ <FieldLabel htmlFor="combobox-server-search">Organization</FieldLabel>+ <StoryCombobox+ id="combobox-server-search"+ options={organizations}+ value={value}+ onValueChange={(nextValue: (typeof ALL_ORGANIZATIONS)[number]) => {+ setValue(nextValue);+ setValueChangeCount((current) => current + 1);+ }}+ onClear={() => {+ setValue(null);+ setClearOverrideCount((current) => current + 1);+ }}+ onSearchChange={setSearch}+ isLoading={isLoading || search !== debouncedSearch}+ getOptionValue={(option) => option.id}+ getOptionLabel={(option) => option.name}+ placeholder="Select organization..."+ searchPlaceholder="Search organizations..."+ searchAriaLabel="Search organizations"+ emptyMessage="No organizations match that search."+ renderValue={(option) => (+ <span data-testid="server-selected-value" className="font-medium">+ {option.name}+ </span>+ )}+ listFooter={+ totalCount > organizations.length+ ? `Showing ${organizations.length} of ${totalCount.toLocaleString()} — type to search the rest`+ : null+ }+ />+ </Field>+ <p data-testid="server-query" className="text-xs text-muted">+ Remote query: {search || "(empty)"}+ </p>+ <p className="sr-only">Selected organization: {value?.name ?? "none"}</p>+ <p className="sr-only" data-testid="server-callback-counts">+ Value changes: {valueChangeCount}; clear overrides: {clearOverrideCount}+ </p>+ </div>);};@@ -232,7 +349,42 @@ const ServerSearchRender = () => {* Without `onSearchChange` the component would only ever match within those 25.*/export const ServerSearch: Story = {- render: () => <ServerSearchRender />+ parameters: {+ docs: {+ description: {+ story:+ "Caller-owned search renders one fetched page at a time while preserving the controlled selection object even when that saved option is absent from the current page. Debounce the query and keep `isLoading` true across both the debounce and request windows."+ }+ }+ },+ render: () => <ServerSearchRender />,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const input = canvas.getByRole("combobox", { name: "Organization" });++ await expect(input).toHaveValue("Organization 1999");+ await expect(canvas.getByTestId("server-query")).toHaveTextContent("Remote query: (empty)");+ await userEvent.click(input);+ await expect(input).toHaveValue("Organization 1999");+ await expect(canvas.getByTestId("server-selected-value")).toBeInTheDocument();+ await expect(canvas.getByTestId("server-query")).toHaveTextContent("Remote query: (empty)");+ await expect(input).toHaveAttribute("placeholder", "Select organization...");++ await userEvent.type(input, "Organization 2");+ await expect(input).toHaveValue("Organization 2");+ await expect(canvas.queryByTestId("server-selected-value")).not.toBeInTheDocument();+ await expect(canvas.getByTestId("server-query")).toHaveTextContent(+ "Remote query: Organization 2"+ );+ await expect(getTrailingSlot(input)).toHaveAttribute("data-state", "loading");+ await waitFor(() => expect(getTrailingSlot(input)).toHaveAttribute("data-state", "clear"));+ clickOpenTrailingClear(input);+ await waitFor(() => expect(input).toHaveValue(""));+ await expect(canvas.getByTestId("server-query")).toHaveTextContent("Remote query: (empty)");+ await expect(canvas.getByTestId("server-callback-counts")).toHaveTextContent(+ "Value changes: 0; clear overrides: 1"+ );+ }};const RichOptionsRender = () => {@@ -260,6 +412,7 @@ const RichOptionsRender = () => {<p className="text-xs leading-4 break-words whitespace-normal text-muted">{option.description}</p>+ <p className="text-xs text-muted">{option.items} assigned members</p></div>)}/>@@ -325,25 +478,29 @@ const MultipleRender = () => {const [value, setValue] = useState<(typeof PROJECTS)[number][]>(PROJECTS.slice(0, 2));return (- <Field>- <FieldLabel id="combobox-projects-label" htmlFor="combobox-projects">- Projects- </FieldLabel>- <StoryCombobox- id="combobox-projects"- aria-labelledby="combobox-projects-label"- multiple- options={PROJECTS}- value={value}- onValueChange={(options) => setValue(options)}- getOptionValue={(option) => option.id}- getOptionLabel={(option) => option.name}- placeholder="Select projects..."- searchPlaceholder="Search projects..."- searchAriaLabel="Search projects"- clearAriaLabel="Clear all projects"- />- </Field>+ <div>+ <Field>+ <FieldLabel id="combobox-projects-label" htmlFor="combobox-projects">+ Projects+ </FieldLabel>+ <StoryCombobox+ id="combobox-projects"+ aria-labelledby="combobox-projects-label"+ multiple+ isSelectAll+ options={PROJECTS}+ value={value}+ onValueChange={(options) => setValue(options)}+ getOptionValue={(option) => option.id}+ getOptionLabel={(option) => option.name}+ placeholder="Select projects..."+ searchPlaceholder="Search projects..."+ searchAriaLabel="Search projects"+ clearAriaLabel="Clear all projects"+ />+ </Field>+ <p className="sr-only">Selected projects: {value.length}</p>+ </div>);};@@ -353,29 +510,41 @@ const MultipleRender = () => {* search input cleared and focused.*/export const Multiple: Story = {- name: "Multiple: Chips",+ name: "Example: Multiple Selection",render: () => <MultipleRender />,play: async ({ canvasElement }) => {const canvas = within(canvasElement);const combobox = canvas.getByRole("combobox", { name: "Projects" });+ await userEvent.click(+ canvas.getByRole("button", { name: "Remove Project 1 with a long descriptive name" })+ );+ await expect(+ canvas.queryByRole("button", { name: "Remove Project 1 with a long descriptive name" })+ ).not.toBeInTheDocument();+ await expect(canvas.getByRole("button", { name: "Remove Project 2" })).toBeInTheDocument();await userEvent.click(canvas.getByText("Projects"));await userEvent.type(combobox, "Project 3");await expect(combobox).toHaveFocus();await expect(combobox).toHaveAccessibleName("Projects");+ await expect(getTrailingSlot(combobox)).toHaveAttribute("data-state", "clear");+ clickOpenTrailingClear(combobox);+ await expect(canvas.queryByRole("button", { name: /Remove Project/ })).not.toBeInTheDocument();+ await waitFor(() => expect(combobox).toHaveValue(""));+ await expect(getTrailingSlot(combobox)).toHaveAttribute("data-state", "chevron");}};-const SelectAllRender = () => {- const [value, setValue] = useState<(typeof PROJECTS)[number][]>([]);+const SingleLineRender = () => {+ const [value, setValue] = useState<(typeof PROJECTS)[number][]>(PROJECTS.slice(0, 12));return (<Field>- <FieldLabel htmlFor="combobox-select-all-projects">Projects</FieldLabel>+ <FieldLabel htmlFor="combobox-single-line-projects">Projects</FieldLabel><StoryCombobox- id="combobox-select-all-projects"+ id="combobox-single-line-projects"multiple- isSelectAll+ singleLineoptions={PROJECTS}value={value}onValueChange={(options) => setValue(options)}@@ -390,25 +559,15 @@ const SelectAllRender = () => {);};-/**- * `isSelectAll` adds a toggle above the option list that selects every option- * matching the current search, then clears that same set once all are selected.- */-export const SelectAll: Story = {- name: "Multiple: Select All",- render: () => <SelectAllRender />-};--const SingleLineRender = () => {+const OverflowedSelectionsRender = () => {const [value, setValue] = useState<(typeof PROJECTS)[number][]>(PROJECTS.slice(0, 12));return (<Field>- <FieldLabel htmlFor="combobox-single-line-projects">Projects</FieldLabel>+ <FieldLabel htmlFor="combobox-overflow-projects">Projects</FieldLabel><StoryCombobox- id="combobox-single-line-projects"+ id="combobox-overflow-projects"multiple- singleLineoptions={PROJECTS}value={value}onValueChange={(options) => setValue(options)}@@ -417,69 +576,83 @@ const SingleLineRender = () => {placeholder="Select projects..."searchPlaceholder="Search projects..."searchAriaLabel="Search projects"- clearAriaLabel="Clear all projects"/></Field>);};-/**- * Single-line mode keeps the chips and search input on one row. Overflow scrolls- * horizontally with a thin scrollbar while the clear button remains visible at- * the trailing edge.- */-export const SingleLine: Story = {- name: "Multiple: Single Line",+export const ChipLayouts: Story = {+ name: "Example: Chip Layouts",parameters: {docs: {description: {story:- "Use `singleLine` when the control should behave like a text input instead of expanding vertically. Selected chips scroll horizontally with a thin scrollbar, and the clear button stays visible."+ "Use the default wrapped layout when every selection should stay visible within a bounded scroll area. Use `singleLine` when the field must keep text-input height and horizontal overflow is preferable."}}},- render: () => <SingleLineRender />+ render: () => (+ <div className="flex w-80 flex-col gap-6">+ <OverflowedSelectionsRender />+ <SingleLineRender />+ </div>+ )};-const OverflowedSelectionsRender = () => {- const [value, setValue] = useState<(typeof PROJECTS)[number][]>(PROJECTS.slice(0, 12));+const NestedDialogCreationField = () => {+ const [options, setOptions] = useState<string[]>([]);+ const [value, setValue] = useState<string | null>(null);return (<Field>- <FieldLabel htmlFor="combobox-overflow-projects">Projects</FieldLabel>+ <FieldLabel htmlFor="combobox-nested-dialog-tag">Primary tag</FieldLabel><StoryCombobox- id="combobox-overflow-projects"- multiple- options={PROJECTS}+ id="combobox-nested-dialog-tag"+ modal+ options={options}value={value}- onValueChange={(options) => setValue(options)}- getOptionValue={(option) => option.id}- getOptionLabel={(option) => option.name}- placeholder="Select projects..."- searchPlaceholder="Search projects..."- searchAriaLabel="Search projects"+ onValueChange={setValue}+ getOptionValue={(option) => option}+ getOptionLabel={(option) => option}+ placeholder="Select or create a tag..."+ creation={{+ mode: "dialog",+ title: "Create Nested Tag",+ description: "Confirm the tag before adding it to this invitation.",+ renderForm: ({ initialInput, complete, cancel }) => (+ <form+ className="flex flex-col gap-4"+ onSubmit={(event) => {+ event.preventDefault();+ setOptions((current) => [...current, initialInput]);+ setValue(initialInput);+ complete();+ }}+ >+ <Field>+ <FieldLabel htmlFor="nested-dialog-tag-name">Tag name</FieldLabel>+ <Input id="nested-dialog-tag-name" defaultValue={initialInput} autoFocus />+ </Field>+ <DialogFooter>+ <Button variant="ghost" onClick={cancel}>+ Cancel+ </Button>+ <Button type="submit">Create Tag</Button>+ </DialogFooter>+ </form>+ )+ }}/>+ <p className="text-sm text-muted">Created tag: {value ?? "none"}</p></Field>);};-export const OverflowedSelections: Story = {- name: "Multiple: Overflowed Selections",- parameters: {- docs: {- description: {- story:- "A large selection wraps into a bounded, internally scrollable chip area so the form cannot grow without limit. Every chip remains keyboard reachable and removable."- }- }- },- render: () => <OverflowedSelectionsRender />-};-const InDialogRender = () => {const [value, setValue] = useState<(typeof ORGANIZATION_ROLES)[number] | null>(ORGANIZATION_ROLES[1]);+ const [parentSubmitCount, setParentSubmitCount] = useState(0);return (<Dialog>@@ -487,34 +660,44 @@ const InDialogRender = () => {<Button variant="outline">Open Role Picker</Button></DialogTrigger><DialogContent>- <DialogHeader>- <DialogTitle>Invite Organization Member</DialogTitle>- <DialogDescription>Choose the organization role for this member.</DialogDescription>- </DialogHeader>- <Field>- <FieldLabel htmlFor="combobox-dialog-role">Organization role</FieldLabel>- <StoryCombobox- id="combobox-dialog-role"- options={ORGANIZATION_ROLES}- value={value}- onValueChange={setValue}- getOptionValue={(option) => option.slug}- getOptionLabel={(option) => option.name}- getOptionKeywords={(option) => [option.description]}- placeholder="Select role..."- searchPlaceholder="Search roles..."- searchAriaLabel="Search organization roles"- modal- renderOption={(option) => (- <div className="min-w-0">- <p className="truncate">{option.name}</p>- <p className="text-xs leading-4 break-words whitespace-normal text-muted">- {option.description}- </p>- </div>- )}- />- </Field>+ <form+ className="flex flex-col gap-6"+ onSubmit={(event) => {+ event.preventDefault();+ setParentSubmitCount((current) => current + 1);+ }}+ >+ <DialogHeader>+ <DialogTitle>Invite Organization Member</DialogTitle>+ <DialogDescription>Choose the organization role for this member.</DialogDescription>+ </DialogHeader>+ <Field>+ <FieldLabel htmlFor="combobox-dialog-role">Organization role</FieldLabel>+ <StoryCombobox+ id="combobox-dialog-role"+ options={ORGANIZATION_ROLES}+ value={value}+ onValueChange={setValue}+ getOptionValue={(option) => option.slug}+ getOptionLabel={(option) => option.name}+ getOptionKeywords={(option) => [option.description]}+ placeholder="Select role..."+ searchPlaceholder="Search roles..."+ searchAriaLabel="Search organization roles"+ modal+ renderOption={(option) => (+ <div className="min-w-0">+ <p className="truncate">{option.name}</p>+ <p className="text-xs leading-4 break-words whitespace-normal text-muted">+ {option.description}+ </p>+ </div>+ )}+ />+ </Field>+ <NestedDialogCreationField />+ <p role="status">Parent form submits: {parentSubmitCount}</p>+ </form></DialogContent></Dialog>);@@ -526,15 +709,73 @@ export const InDialog: Story = {docs: {description: {story:- "Set `modal` when the combobox is rendered inside a modal Dialog. Base UI then preserves focus containment and scroll access for its body-portalled option list."+ "Set `modal` when the combobox is rendered inside a modal Dialog. Base UI then preserves focus containment and scroll access for its body-portalled option list. A dialog creation form stops its submit event at the shared creation-dialog boundary, so React portal propagation cannot submit an ancestor form."}}},- render: () => <InDialogRender />+ render: () => <InDialogRender />,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);++ await userEvent.click(canvas.getByRole("button", { name: "Open Role Picker" }));+ const parentDialog = await body.findByRole("dialog", { name: "Invite Organization Member" });+ const roleInput = within(parentDialog).getByRole("combobox", { name: "Organization role" });+ const roleClear = within(parentDialog).getByRole("button", { name: "Clear selection" });+ roleClear.focus();+ await expect(roleClear).toHaveFocus();+ await userEvent.keyboard("{Enter}");+ await waitFor(() => expect(roleInput).toHaveValue(""));++ const input = within(parentDialog).getByRole("combobox", { name: "Primary tag" });+ await userEvent.click(input);+ await userEvent.type(input, "Enter tag");+ await userEvent.click(body.getByRole("option", { name: 'Create "Enter tag"' }));+ const creationDialog = await body.findByRole("dialog", { name: "Create Nested Tag" });+ await expect(within(creationDialog).getByLabelText("Tag name")).toHaveValue("Enter tag");+ await userEvent.keyboard("{Enter}");+ await waitFor(() =>+ expect(body.queryByRole("dialog", { name: "Create Nested Tag" })).not.toBeInTheDocument()+ );+ await expect(+ body.getByRole("dialog", { name: "Invite Organization Member" })+ ).toBeInTheDocument();+ await waitFor(() => expect(input).toHaveFocus());+ await expect(input).toHaveValue("Enter tag");+ await expect(within(parentDialog).getByText("Parent form submits: 0")).toBeInTheDocument();+ await userEvent.click(within(parentDialog).getByRole("button", { name: "Clear selection" }));+ await waitFor(() => expect(input).toHaveValue(""));++ await userEvent.click(input);+ await userEvent.clear(input);+ await userEvent.type(input, "Button tag");+ await userEvent.click(body.getByRole("option", { name: 'Create "Button tag"' }));+ const buttonCreationDialog = await body.findByRole("dialog", { name: "Create Nested Tag" });+ await userEvent.click(within(buttonCreationDialog).getByRole("button", { name: "Create Tag" }));+ await waitFor(() =>+ expect(body.queryByRole("dialog", { name: "Create Nested Tag" })).not.toBeInTheDocument()+ );+ await waitFor(() => expect(input).toHaveFocus());+ await expect(input).toHaveValue("Button tag");+ await expect(within(parentDialog).getByText("Created tag: Button tag")).toBeInTheDocument();+ await expect(within(parentDialog).getByText("Parent form submits: 0")).toBeInTheDocument();+ const nestedClear = within(parentDialog).getByRole("button", { name: "Clear selection" });+ nestedClear.focus();+ await expect(nestedClear).toHaveFocus();+ await userEvent.keyboard("{Enter}");+ await waitFor(() => expect(input).toHaveValue(""));+ }};-export const States: Story = {- render: () => (+const StatesRender = () => {+ const [loadingSingleValue, setLoadingSingleValue] = useState<+ (typeof ENVIRONMENTS)[number] | null+ >(ENVIRONMENTS[0]);+ const [loadingMultipleValue, setLoadingMultipleValue] = useState<(typeof PROJECTS)[number][]>(+ PROJECTS.slice(0, 2)+ );++ return (<div className="flex flex-col gap-5"><Field data-invalid="true"><FieldLabel htmlFor="combobox-error">Environment</FieldLabel>@@ -560,6 +801,18 @@ export const States: Story = {isDisabled/></Field>+ <Field>+ <FieldLabel htmlFor="combobox-non-clearable">Required environment</FieldLabel>+ <StoryCombobox+ id="combobox-non-clearable"+ options={ENVIRONMENTS}+ value={ENVIRONMENTS[0]}+ onValueChange={() => undefined}+ getOptionValue={(option) => option.id}+ getOptionLabel={(option) => option.name}+ isClearable={false}+ />+ </Field><Field data-disabled="true"><FieldLabel id="combobox-disabled-projects-label" htmlFor="combobox-disabled-projects">Projects@@ -577,18 +830,54 @@ export const States: Story = {/></Field><Field>- <FieldLabel htmlFor="combobox-loading">Environment</FieldLabel>+ <FieldLabel htmlFor="combobox-loading">Loading environment</FieldLabel><StoryComboboxid="combobox-loading"- options={[]}- onValueChange={() => undefined}+ options={ENVIRONMENTS}+ value={loadingSingleValue}+ onValueChange={setLoadingSingleValue}getOptionValue={(option: (typeof ENVIRONMENTS)[number]) => option.id}getOptionLabel={(option) => option.name}isLoading/></Field>+ <Field>+ <FieldLabel htmlFor="combobox-loading-projects">Loading projects</FieldLabel>+ <StoryCombobox+ id="combobox-loading-projects"+ multiple+ options={PROJECTS}+ value={loadingMultipleValue}+ onValueChange={(nextValue) => setLoadingMultipleValue(nextValue)}+ getOptionValue={(option) => option.id}+ getOptionLabel={(option) => option.name}+ isLoading+ />+ </Field></div>- )+ );+};++export const States: Story = {+ render: () => <StatesRender />,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const disabledSingle = canvasElement.querySelector<HTMLElement>("#combobox-disabled")!;+ const nonClearableSingle = canvas.getByRole("combobox", { name: "Required environment" });+ const disabledMultiple = canvas.getByRole("combobox", { name: "Projects", hidden: true });+ const loadingSingle = canvas.getByRole("combobox", { name: "Loading environment" });+ const loadingMultiple = canvas.getByRole("combobox", { name: "Loading projects" });++ await expect(getTrailingSlot(disabledSingle)).toHaveAttribute("data-state", "chevron");+ await expect(getTrailingSlot(nonClearableSingle)).toHaveAttribute("data-state", "chevron");+ await expect(getTrailingSlot(disabledMultiple)).toHaveAttribute("data-state", "chevron");+ await expect(canvas.queryByRole("button", { name: "Clear selection" })).not.toBeInTheDocument();+ await expect(+ canvas.queryByRole("button", { name: "Clear all selections" })+ ).not.toBeInTheDocument();+ await expect(getTrailingSlot(loadingSingle)).toHaveAttribute("data-state", "loading");+ await expect(getTrailingSlot(loadingMultiple)).toHaveAttribute("data-state", "loading");+ }};const ViewportEdgesRender = () => {@@ -598,7 +887,7 @@ const ViewportEdgesRender = () => {const renderCombobox = (id: string,value: (typeof ORGANIZATION_ROLES)[number] | null,- onValueChange: (option: (typeof ORGANIZATION_ROLES)[number]) => void+ onValueChange: (option: (typeof ORGANIZATION_ROLES)[number] | null) => void) => (<StoryComboboxid={id}@@ -669,7 +958,6 @@ export const ServerFilteredSelection: Story = {options={options}value={value}onValueChange={setValue}- onClear={() => setValue(null)}getOptionValue={(id) => id}getOptionLabel={(id) => id}shouldFilter={false}@@ -679,3 +967,782 @@ export const ServerFilteredSelection: Story = {);}};++const CreatableSingleRender = () => {+ const [options, setOptions] = useState<{ id: string; name: string }[]>([...ENVIRONMENTS]);+ const [value, setValue] = useState<{ id: string; name: string } | null>(null);++ return (+ <Field>+ <FieldLabel htmlFor="combobox-creatable-environment">Environment</FieldLabel>+ <StoryCombobox+ id="combobox-creatable-environment"+ options={options}+ value={value}+ onValueChange={setValue}+ getOptionValue={(option) => option.id}+ getOptionLabel={(option) => option.name}+ placeholder="Select or create an environment..."+ creation={{+ onCreate: (inputValue) => {+ const option = { id: inputValue, name: inputValue };+ setOptions((current) => [...current, option]);+ setValue(option);+ }+ }}+ />+ </Field>+ );+};++const SingleDismissedFailureRender = () => {+ const [attempt, setAttempt] = useState(0);+ const [options, setOptions] = useState<{ id: string; name: string }[]>([]);+ const [value, setValue] = useState<{ id: string; name: string } | null>(null);++ return (+ <div className="flex flex-col gap-4">+ <Field>+ <FieldLabel htmlFor="combobox-single-dismissed-failure">Environment</FieldLabel>+ <StoryCombobox+ id="combobox-single-dismissed-failure"+ options={options}+ value={value}+ onValueChange={setValue}+ getOptionValue={(option) => option.id}+ getOptionLabel={(option) => option.name}+ placeholder="Select or create an environment..."+ creation={{+ onCreate: async (inputValue) => {+ await sleep(500);+ if (attempt === 0) {+ setAttempt(1);+ throw false;+ }+ const option = { id: inputValue, name: inputValue };+ setOptions([option]);+ setValue(option);+ }+ }}+ />+ </Field>+ <Button variant="outline">Continue</Button>+ <p role="status">{value ? `Selected ${value.name}` : "No selection"}</p>+ </div>+ );+};++export const SingleDismissedFailure: Story = {+ name: "Creation: Single Dismissed Failure and Retry",+ parameters: {+ docs: {+ description: {+ story:+ "A rejected single-value creation retains its failed query and inline error after pending work was dismissed. Reopening allows the same query to be retried without restoring focus or opening automatically."+ }+ }+ },+ render: () => <SingleDismissedFailureRender />,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const input = canvas.getByRole("combobox", { name: "Environment" });+ const continueButton = canvas.getByRole("button", { name: "Continue" });++ await userEvent.click(input);+ await userEvent.type(input, "retryable");+ await userEvent.click(canvas.getByRole("option", { name: 'Create "retryable"' }));+ await expect(getTrailingSlot(input)).toHaveAttribute("data-state", "loading");+ await userEvent.keyboard("{Escape}");+ await userEvent.click(continueButton);+ await sleep(600);+ await expect(input).toHaveAttribute("aria-expanded", "false");+ await expect(continueButton).toHaveFocus();++ await userEvent.click(input);+ await expect(await canvas.findByRole("alert")).toHaveTextContent(+ 'Could not create "retryable"'+ );+ await expect(input).toHaveValue("retryable");+ await userEvent.click(canvas.getByRole("option", { name: /Create "retryable"/ }));+ await expect(await canvas.findByText("Selected retryable")).toBeInTheDocument();+ await expect(input).toHaveAttribute("aria-expanded", "false");+ await expect(input).toHaveValue("retryable");+ }+};++const AsyncCreationRender = () => {+ const [options, setOptions] = useState(TAGS);+ const [value, setValue] = useState<TagOption[]>([]);++ return (+ <Field>+ <FieldLabel htmlFor="combobox-async-tags">Tags</FieldLabel>+ <StoryCombobox+ id="combobox-async-tags"+ multiple+ options={options}+ value={value}+ onValueChange={(nextValue) => setValue(nextValue)}+ getOptionValue={(option) => option.id}+ getOptionLabel={(option) => option.name}+ placeholder="Select or create tags..."+ creation={{+ isValid: (inputValue) => /^[a-z][a-z0-9-]*$/.test(inputValue),+ formatLabel: (inputValue) => `Create tag "${inputValue}"`,+ formatPendingLabel: (inputValue) => `Creating tag "${inputValue}"...`,+ formatError: () => "The tag could not be created. Check the slug and try again.",+ onCreate: async (inputValue) => {+ await sleep(350);+ if (inputValue === "reserved") {+ const failure: unknown = false;+ throw failure;+ }++ const option = { id: inputValue, name: inputValue, group: "Custom" };+ setOptions((current) => [...current, option]);+ setValue((current) =>+ current.some((tag) => tag.id === option.id) ? current : [...current, option]+ );+ }+ }}+ />+ </Field>+ );+};++export const InlineCreation: Story = {+ name: "Example: Inline Creation",+ parameters: {+ docs: {+ description: {+ story:+ "Inline creation is the compact path for values that need no extra metadata. The single-select example persists immediately; the multi-select example validates a slug, exposes caller-owned pending and failure copy, and updates controlled options and selections only after persistence succeeds."+ }+ }+ },+ render: () => (+ <div className="flex w-80 flex-col gap-6">+ <CreatableSingleRender />+ <AsyncCreationRender />+ </div>+ ),+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const environmentInput = canvas.getByRole("combobox", { name: "Environment" });+ const tagsInput = canvas.getByRole("combobox", { name: "Tags" });++ await userEvent.click(environmentInput);+ await userEvent.type(environmentInput, "prod");+ await expect(canvas.getByRole("option", { name: "Production" })).toBeInTheDocument();+ await userEvent.click(canvas.getByRole("option", { name: 'Create "prod"' }));+ await expect(environmentInput).toHaveValue("prod");++ await userEvent.click(tagsInput);+ await userEvent.type(tagsInput, "release-ready");+ await userEvent.click(canvas.getByRole("option", { name: 'Create tag "release-ready"' }));+ await expect(+ canvas.getByRole("option", { name: 'Creating tag "release-ready"...' })+ ).toHaveAttribute("aria-disabled", "true");+ await expect(getTrailingSlot(tagsInput)).toHaveAttribute("data-state", "loading");+ await expect(+ canvas.queryByRole("button", { name: "Clear all selections" })+ ).not.toBeInTheDocument();+ await expect(+ await canvas.findByRole("button", { name: "Remove release-ready" })+ ).toBeInTheDocument();+ await expect(getTrailingSlot(tagsInput)).toHaveAttribute("data-state", "clear");++ await userEvent.type(tagsInput, "reserved");+ await userEvent.keyboard("{Enter}{Escape}");+ await sleep(450);+ await userEvent.click(tagsInput);+ await expect(await canvas.findByRole("alert")).toHaveTextContent(+ "The tag could not be created"+ );+ }+};++const AsyncLifecycleRender = () => {+ const [options, setOptions] = useState<TagOption[]>([]);+ const [value, setValue] = useState<TagOption[]>([]);++ return (+ <div className="flex flex-col gap-4">+ <Field>+ <FieldLabel htmlFor="combobox-async-lifecycle">Tags</FieldLabel>+ <StoryCombobox+ id="combobox-async-lifecycle"+ multiple+ options={options}+ value={value}+ onValueChange={(nextValue) => setValue(nextValue)}+ getOptionValue={(option) => option.id}+ getOptionLabel={(option) => option.name}+ placeholder="Select or create tags..."+ creation={{+ onCreate: async (inputValue) => {+ await sleep(500);+ const option = { id: inputValue, name: inputValue, group: "Custom" };+ setOptions((current) => [...current, option]);+ setValue((current) => [...current, option]);+ }+ }}+ />+ </Field>+ <Button variant="outline">Continue</Button>+ </div>+ );+};++export const DismissedPendingCreation: Story = {+ name: "Creation: Dismissed Pending Success",+ parameters: {+ docs: {+ description: {+ story:+ "Dismissing a multi-select while creation is pending keeps focus where the user moved it. Completion updates the caller-owned selection without reopening the popup or stealing focus."+ }+ }+ },+ render: () => <AsyncLifecycleRender />,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const input = canvas.getByRole("combobox", { name: "Tags" });+ const continueButton = canvas.getByRole("button", { name: "Continue" });++ await userEvent.click(input);+ await userEvent.type(input, "deferred");+ await userEvent.click(canvas.getByRole("option", { name: 'Create "deferred"' }));+ await userEvent.keyboard("{Escape}");+ await userEvent.click(continueButton);+ await expect(+ await canvas.findByRole("button", { name: "Remove deferred" })+ ).toBeInTheDocument();+ await expect(input).toHaveAttribute("aria-expanded", "false");+ await expect(continueButton).toHaveFocus();+ }+};++export const PreserveNewQueryDuringCreation: Story = {+ name: "Creation: Preserve New Query During Success",+ parameters: {+ docs: {+ description: {+ story:+ "If the user starts another query while creation is pending, completion selects the caller-created option but does not clear or replace the newer query."+ }+ }+ },+ render: () => <AsyncLifecycleRender />,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const input = canvas.getByRole("combobox", { name: "Tags" });++ await userEvent.click(input);+ await userEvent.type(input, "first-tag");+ await userEvent.click(canvas.getByRole("option", { name: 'Create "first-tag"' }));+ await userEvent.clear(input);+ await userEvent.type(input, "next-query");+ await expect(+ await canvas.findByRole("button", { name: "Remove first-tag" })+ ).toBeInTheDocument();+ await expect(input).toHaveValue("next-query");+ await expect(canvas.getByRole("option", { name: 'Create "next-query"' })).toBeInTheDocument();+ }+};++const UnmountPendingCreationRender = () => {+ const [isVisible, setIsVisible] = useState(true);+ const [value, setValue] = useState<TagOption[]>([]);++ return (+ <div className="flex flex-col gap-4">+ {isVisible && (+ <Field>+ <FieldLabel htmlFor="combobox-unmount-pending">Tags</FieldLabel>+ <StoryCombobox+ id="combobox-unmount-pending"+ multiple+ options={value}+ value={value}+ onValueChange={(nextValue) => setValue(nextValue)}+ getOptionValue={(option) => option.id}+ getOptionLabel={(option) => option.name}+ placeholder="Select or create tags..."+ creation={{+ onCreate: async (inputValue) => {+ await sleep(500);+ setValue((current) => [+ ...current,+ { id: inputValue, name: inputValue, group: "Custom" }+ ]);+ }+ }}+ />+ </Field>+ )}+ <Button variant="outline" onClick={() => setIsVisible(false)}>+ Hide combobox+ </Button>+ <p role="status">{value.length === 1 ? "Created 1 tag" : "Waiting for creation"}</p>+ </div>+ );+};++export const UnmountedPendingCreation: Story = {+ name: "Creation: Unmounted Pending Success",+ parameters: {+ docs: {+ description: {+ story:+ "Unmounting while creation is pending invalidates the Combobox request lifecycle. The caller-owned request can still complete without causing the removed Combobox to update state or steal focus."+ }+ }+ },+ render: () => <UnmountPendingCreationRender />,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const input = canvas.getByRole("combobox", { name: "Tags" });+ const hideButton = canvas.getByRole("button", { name: "Hide combobox" });++ await userEvent.click(input);+ await userEvent.type(input, "unmounted");+ await userEvent.click(canvas.getByRole("option", { name: 'Create "unmounted"' }));+ await userEvent.click(hideButton);+ await expect(canvas.queryByRole("combobox", { name: "Tags" })).not.toBeInTheDocument();+ await expect(await canvas.findByText("Created 1 tag")).toBeInTheDocument();+ await expect(hideButton).toHaveFocus();+ }+};++const ValidatedCreationRender = () => {+ const [value, setValue] = useState<TagOption[]>([]);+ const knownOrganizationEmails = ["[email protected]", "[email protected]"];++ return (+ <Field>+ <FieldLabel htmlFor="combobox-validated-email">Approvers</FieldLabel>+ <StoryCombobox+ id="combobox-validated-email"+ multiple+ options={TAGS}+ value={value}+ onValueChange={(nextValue) => setValue(nextValue)}+ getOptionValue={(option) => option.id}+ getOptionLabel={(option) => option.name}+ placeholder="Select approvers or enter a member email..."+ creation={{+ isValid: (inputValue) =>+ /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(inputValue) &&+ !knownOrganizationEmails.includes(inputValue.toLocaleLowerCase()),+ isDuplicate: (inputValue, option) =>+ option.id.toLocaleLowerCase() === inputValue.toLocaleLowerCase(),+ formatLabel: (inputValue) => `Use member email "${inputValue}"`,+ onCreate: (inputValue) =>+ setValue((current) => [+ ...current,+ { id: inputValue, name: inputValue, group: "Member email" }+ ])+ }}+ />+ </Field>+ );+};++export const ValidatedCreation: Story = {+ name: "Creation: Validation and Domain Duplicates",+ parameters: {+ docs: {+ description: {+ story:+ "`isValid` can close over domain data that is not in the current result page, as invitation and manual-approval forms require. `isDuplicate` overrides the default exact, case-sensitive label comparison when a domain uses another identity rule."+ }+ }+ },+ render: () => <ValidatedCreationRender />,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const input = canvas.getByRole("combobox", { name: "Approvers" });++ await userEvent.click(input);+ await userEvent.type(input, "[email protected]");+ await expect(+ canvas.queryByRole("option", { name: 'Use member email "[email protected]"' })+ ).not.toBeInTheDocument();+ await userEvent.clear(input);+ await userEvent.type(input, "[email protected]");+ await expect(+ canvas.getByRole("option", { name: 'Use member email "[email protected]"' })+ ).toBeInTheDocument();+ }+};++type MetadataTagOption = {+ id: string;+ name: string;+ slug: string;+ description: string;+};++type MetadataTagFormProps = ComboboxDialogCreationRenderProps & {+ onCreate: (option: Omit<MetadataTagOption, "id">) => Promise<void>;+ onPendingChange: (isPending: boolean) => void;+};++const toSlug = (value: string) =>+ value+ .trim()+ .toLocaleLowerCase()+ .replace(/[^a-z0-9]+/g, "-")+ .replace(/^-|-$/g, "");++const MetadataTagForm = ({+ initialInput,+ complete,+ cancel,+ onCreate,+ onPendingChange+}: MetadataTagFormProps) => {+ const [name, setName] = useState(initialInput);+ const [slug, setSlug] = useState(() => toSlug(initialInput));+ const [description, setDescription] = useState("");+ const [isPending, setIsPending] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const isValid = Boolean(name.trim() && /^[a-z][a-z0-9-]*$/.test(slug));++ const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {+ event.preventDefault();+ if (!isValid || isPending) return;++ setError(null);+ setIsPending(true);+ onPendingChange(true);+ try {+ await onCreate({ name: name.trim(), slug, description: description.trim() });+ complete();+ } catch {+ setError("That slug is reserved. Choose another slug and try again.");+ } finally {+ setIsPending(false);+ onPendingChange(false);+ }+ };++ return (+ <form className="flex flex-col gap-4" onSubmit={handleSubmit}>+ <Field>+ <FieldLabel htmlFor="dialog-tag-name">Name</FieldLabel>+ <Input+ id="dialog-tag-name"+ value={name}+ onChange={(event) => setName(event.target.value)}+ autoFocus+ />+ </Field>+ <Field data-invalid={Boolean(slug) && !isValid ? "true" : undefined}>+ <FieldLabel htmlFor="dialog-tag-slug">Slug</FieldLabel>+ <Input+ id="dialog-tag-slug"+ value={slug}+ onChange={(event) => setSlug(event.target.value)}+ aria-invalid={Boolean(slug) && !isValid ? true : undefined}+ />+ {slug && !isValid && <FieldError>Use lowercase letters, numbers, and hyphens.</FieldError>}+ </Field>+ <Field>+ <FieldLabel htmlFor="dialog-tag-description">Description</FieldLabel>+ <TextArea+ id="dialog-tag-description"+ value={description}+ onChange={(event) => setDescription(event.target.value)}+ placeholder="Explain when this tag should be used."+ />+ </Field>+ {error && (+ <p role="alert" className="text-sm text-danger">+ {error}+ </p>+ )}+ <DialogFooter>+ <Button variant="ghost" onClick={cancel} isDisabled={isPending}>+ Cancel+ </Button>+ <Button type="submit" isDisabled={!isValid} isPending={isPending}>+ Create Tag+ </Button>+ </DialogFooter>+ </form>+ );+};++const MetadataOptionDetails = ({ option }: { option: MetadataTagOption }) => (+ <dl+ aria-label={`${option.name} metadata`}+ className="grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-xs"+ >+ <dt className="text-muted">ID</dt>+ <dd>{option.id}</dd>+ <dt className="text-muted">Name</dt>+ <dd>{option.name}</dd>+ <dt className="text-muted">Slug</dt>+ <dd>{option.slug}</dd>+ <dt className="text-muted">Description</dt>+ <dd>{option.description || "No description"}</dd>+ </dl>+);++const renderMetadataOption = (option: MetadataTagOption) => (+ <div className="min-w-0">+ <p className="truncate">{option.name}</p>+ <p className="truncate text-xs text-muted">{option.slug}</p>+ <p className="text-xs leading-4 break-words whitespace-normal text-muted">+ {option.description || "No description"}+ </p>+ </div>+);++function SingleDialogCreationRender({ modal = false }: { modal?: boolean }) {+ const [options, setOptions] = useState<MetadataTagOption[]>([]);+ const [value, setValue] = useState<MetadataTagOption | null>(null);+ const [isPending, setIsPending] = useState(false);++ return (+ <div className="flex flex-col gap-3">+ <Field>+ <FieldLabel htmlFor="combobox-dialog-primary-tag">Primary tag</FieldLabel>+ <StoryCombobox+ id="combobox-dialog-primary-tag"+ modal={modal}+ options={options}+ value={value}+ onValueChange={setValue}+ getOptionValue={(option) => option.id}+ getOptionLabel={(option) => option.name}+ getOptionKeywords={(option) => [option.slug, option.description]}+ renderOption={renderMetadataOption}+ placeholder="Select or create a primary tag..."+ creation={{+ mode: "dialog",+ title: "Create Tag",+ description: "Add a reusable tag with the metadata your team needs.",+ isPending,+ renderForm: (props) => (+ <MetadataTagForm+ {...props}+ onPendingChange={setIsPending}+ onCreate={async (fields) => {+ await sleep(450);+ if (fields.slug === "reserved") throw new Error("Reserved slug");+ const option = { id: `tag-${fields.slug}`, ...fields };+ setOptions((current) => [...current, option]);+ setValue(option);+ }}+ />+ )+ }}+ />+ </Field>+ {value && <MetadataOptionDetails option={value} />}+ </div>+ );+}++const MultipleDialogCreationRender = () => {+ const [options, setOptions] = useState<MetadataTagOption[]>([]);+ const [value, setValue] = useState<MetadataTagOption[]>([]);+ const [isPending, setIsPending] = useState(false);++ return (+ <div className="flex flex-col gap-3">+ <Field>+ <FieldLabel htmlFor="combobox-dialog-additional-tags">Additional tags</FieldLabel>+ <StoryCombobox+ id="combobox-dialog-additional-tags"+ multiple+ options={options}+ value={value}+ onValueChange={setValue}+ getOptionValue={(option) => option.id}+ getOptionLabel={(option) => option.name}+ getOptionKeywords={(option) => [option.slug, option.description]}+ renderOption={renderMetadataOption}+ placeholder="Select or create additional tags..."+ creation={{+ mode: "dialog",+ title: "Create Tag",+ description: "Add a reusable tag with the metadata your team needs.",+ isPending,+ renderForm: (props) => (+ <MetadataTagForm+ {...props}+ onPendingChange={setIsPending}+ onCreate={async (fields) => {+ await sleep(450);+ if (fields.slug === "reserved") throw new Error("Reserved slug");+ const option = { id: `tag-${fields.slug}`, ...fields };+ setOptions((current) => [...current, option]);+ setValue((current) => [...current, option]);+ }}+ />+ )+ }}+ />+ </Field>+ {value.map((option) => (+ <MetadataOptionDetails key={option.id} option={option} />+ ))}+ </div>+ );+};++export const DialogCreation: Story = {+ name: "Example: Dialog Creation",+ parameters: {+ docs: {+ description: {+ story:+ 'Use `creation.mode = "dialog"` when a new option needs metadata beyond the search query. The caller renders and validates the form, persists a complete domain object, updates controlled options and selection, then calls `complete`. Cancel preserves the query for retry; `isPending` blocks Escape, outside click, and close controls until persistence settles.'+ }+ }+ },+ render: () => (+ <div className="flex w-80 flex-col gap-8">+ <SingleDialogCreationRender />+ <MultipleDialogCreationRender />+ </div>+ ),+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);+ const primaryInput = canvas.getByRole("combobox", { name: "Primary tag" });+ const additionalInput = canvas.getByRole("combobox", { name: "Additional tags" });++ await userEvent.click(primaryInput);+ await userEvent.type(primaryInput, "Release workflow");+ await userEvent.click(canvas.getByRole("option", { name: 'Create "Release workflow"' }));+ let dialog = await body.findByRole("dialog", { name: "Create Tag" });+ await expect(within(dialog).getByLabelText("Name")).toHaveValue("Release workflow");+ const slugInput = within(dialog).getByLabelText("Slug");+ const createButton = within(dialog).getByRole("button", { name: "Create Tag" });+ await userEvent.clear(slugInput);+ await expect(createButton).toBeDisabled();+ await userEvent.type(slugInput, "release-workflow");+ await userEvent.click(within(dialog).getByRole("button", { name: "Cancel" }));+ await waitFor(() =>+ expect(body.queryByRole("dialog", { name: "Create Tag" })).not.toBeInTheDocument()+ );+ await waitFor(() => expect(primaryInput).toHaveFocus());+ await expect(primaryInput).toHaveValue("Release workflow");+ await expect(primaryInput).toHaveAttribute("aria-expanded", "true");++ await userEvent.click(canvas.getByRole("option", { name: 'Create "Release workflow"' }));+ dialog = await body.findByRole("dialog", { name: "Create Tag" });+ await userEvent.type(+ within(dialog).getByLabelText("Description"),+ "Coordinates checks before production deployment."+ );+ await userEvent.click(within(dialog).getByRole("button", { name: "Create Tag" }));+ await expect(within(dialog).getByRole("button", { name: "Create Tag" })).toHaveAttribute(+ "aria-busy",+ "true"+ );+ await userEvent.keyboard("{Escape}");+ await expect(body.getByRole("dialog", { name: "Create Tag" })).toBeInTheDocument();+ const primaryMetadata = await canvas.findByLabelText("Release workflow metadata");+ await expect(within(primaryMetadata).getByText("tag-release-workflow")).toBeInTheDocument();+ await expect(+ within(primaryMetadata).getByText("Coordinates checks before production deployment.")+ ).toBeInTheDocument();+ await waitFor(() =>+ expect(body.queryByRole("dialog", { name: "Create Tag" })).not.toBeInTheDocument()+ );+ await waitFor(() => expect(primaryInput).toHaveFocus());+ await expect(primaryInput).toHaveAttribute("aria-expanded", "false");++ await userEvent.click(additionalInput);+ await userEvent.type(additionalInput, "Security review");+ await userEvent.click(canvas.getByRole("option", { name: 'Create "Security review"' }));+ dialog = await body.findByRole("dialog", { name: "Create Tag" });+ await userEvent.clear(within(dialog).getByLabelText("Slug"));+ await userEvent.type(within(dialog).getByLabelText("Slug"), "reserved");+ await userEvent.click(within(dialog).getByRole("button", { name: "Create Tag" }));+ await expect(await within(dialog).findByRole("alert")).toHaveTextContent("slug is reserved");+ await userEvent.clear(within(dialog).getByLabelText("Slug"));+ await userEvent.type(within(dialog).getByLabelText("Slug"), "security-review");+ await userEvent.click(within(dialog).getByRole("button", { name: "Create Tag" }));+ await expect(+ await canvas.findByRole("button", { name: "Remove Security review" })+ ).toBeInTheDocument();+ const additionalMetadata = await canvas.findByLabelText("Security review metadata");+ await expect(within(additionalMetadata).getByText("tag-security-review")).toBeInTheDocument();+ }+};++const GroupedRemoteCreationRender = () => {+ const [query, setQuery] = useState("");+ const [options, setOptions] = useState(TAGS);+ const [value, setValue] = useState<TagOption[]>([]);+ const results = options.filter((option) => option.name.includes(query));++ return (+ <Field>+ <FieldLabel htmlFor="combobox-remote-tags">Remote tags</FieldLabel>+ <StoryCombobox+ id="combobox-remote-tags"+ multiple+ isSelectAll+ options={results}+ value={value}+ onValueChange={(nextValue) => setValue(nextValue)}+ onSearchChange={setQuery}+ includeMissingSelectedOptions={false}+ getOptionValue={(option) => option.id}+ getOptionLabel={(option) => option.name}+ getOptionGroup={(option) => option.group}+ creation={{+ onCreate: (inputValue) => {+ const option = { id: inputValue, name: inputValue, group: "Custom" };+ setOptions((current) => [...current, option]);+ setValue((current) => [...current, option]);+ }+ }}+ />+ </Field>+ );+};++export const GroupedRemoteCreation: Story = {+ name: "Creation: Grouped Remote Results and Select All",+ parameters: {+ docs: {+ description: {+ story:+ "Creation composes with grouped, caller-filtered multi-select results. The internal Create item stays outside domain groups and Select All counts only real options, and successful creation resets the caller-owned query so refreshed results remain visible."+ }+ }+ },+ render: () => <GroupedRemoteCreationRender />,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const input = canvas.getByRole("combobox", { name: "Remote tags" });++ await userEvent.click(input);+ await userEvent.type(input, "prod");+ await expect(canvas.getByRole("button", { name: "Select All (1)" })).toBeInTheDocument();+ await expect(canvas.getByRole("option", { name: 'Create "prod"' })).toBeInTheDocument();+ await userEvent.click(canvas.getByRole("button", { name: "Select All (1)" }));+ await expect(canvas.getByRole("button", { name: "Remove production" })).toBeInTheDocument();+ await expect(canvas.queryByRole("button", { name: "Remove prod" })).not.toBeInTheDocument();++ await userEvent.clear(input);+ await userEvent.type(input, "remote-created");+ const createOption = canvas.getByRole("option", { name: 'Create "remote-created"' });+ await userEvent.keyboard("{ArrowDown}");+ await expect(createOption).toHaveAttribute("data-highlighted");+ await userEvent.keyboard("{Enter}");+ await expect(canvas.getByRole("button", { name: "Remove remote-created" })).toBeInTheDocument();+ await expect(input).toHaveValue("");+ await expect(canvas.getByRole("option", { name: /production/ })).toBeInTheDocument();+ await expect(canvas.getByRole("button", { name: "Select All (5)" })).toBeInTheDocument();+ }+};diff --git a/frontend/src/components/v3/generic/Combobox/Combobox.tsx b/frontend/src/components/v3/generic/Combobox/Combobox.tsxindex 972f6423b8..c27ae71847 100644--- a/frontend/src/components/v3/generic/Combobox/Combobox.tsx+++ b/frontend/src/components/v3/generic/Combobox/Combobox.tsx@@ -1,9 +1,10 @@import * as React from "react";import { Combobox as ComboboxPrimitive } from "@base-ui/react/combobox";-import { CheckIcon, ChevronDownIcon, Loader2Icon, XIcon } from "lucide-react";+import { CheckIcon, ChevronDownIcon, Loader2Icon, PlusIcon, XIcon } from "lucide-react";import { cn } from "../../utils";import { useScrollEdges } from "../../utils/useScrollEdges";+import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "../Dialog";import { getComboboxInputAriaLabel } from "./combobox-accessibility";import {COMBOBOX_CHIP_CLASS,@@ -13,6 +14,7 @@ import {COMBOBOX_CHIPS_INPUT_CLASS,comboboxChipsViewportClass} from "./combobox-chips";+import { type ComboboxCreationContext, getComboboxCreationInput } from "./combobox-creation";import { mergeComboboxItems } from "./combobox-items";import "../../utils/ScrollEdgeFade.css";@@ -21,6 +23,45 @@ type ComboboxRenderOptionState = {isSelected: boolean;};+type ComboboxCreationBaseConfig<TOption> = {+ isValid?: (inputValue: string, context: ComboboxCreationContext<TOption>) => boolean;+ isDuplicate?: (inputValue: string, option: TOption) => boolean;+ formatLabel?: (inputValue: string) => React.ReactNode;+ isDisabled?: boolean;+};++type ComboboxInlineCreationConfig<TOption> = ComboboxCreationBaseConfig<TOption> & {+ mode?: "inline";+ /**+ * Owns domain-option construction, persistence, and controlled options/value+ * updates. Return the persistence promise so the combobox can retain the query+ * on failure and clear it only after success.+ */+ onCreate: (inputValue: string) => void | Promise<void>;+ formatPendingLabel?: (inputValue: string) => React.ReactNode;+ formatError?: (error: unknown, inputValue: string) => React.ReactNode;+ isPending?: boolean;+};++type ComboboxDialogCreationRenderProps = {+ initialInput: string;+ complete: () => void;+ cancel: () => void;+};++type ComboboxDialogCreationConfig<TOption> = ComboboxCreationBaseConfig<TOption> & {+ mode: "dialog";+ title: React.ReactNode;+ description: React.ReactNode;+ renderForm: (props: ComboboxDialogCreationRenderProps) => React.ReactNode;+ /** Prevent dismissing the dialog while caller-owned persistence is pending. */+ isPending?: boolean;+};++type ComboboxCreationConfig<TOption> =+ | ComboboxInlineCreationConfig<TOption>+ | ComboboxDialogCreationConfig<TOption>;+type ComboboxSharedProps<TOption> = {options?: readonly TOption[];getOptionValue: (option: TOption) => string;@@ -35,6 +76,7 @@ type ComboboxSharedProps<TOption> = {renderValue?: (option: TOption) => React.ReactNode;clearAriaLabel?: string;placeholder?: string;+ /** @deprecated Use `searchAriaLabel`. The visible placeholder no longer changes on focus. */searchPlaceholder?: string;searchAriaLabel?: string;emptyMessage?: React.ReactNode | ((inputValue: string) => React.ReactNode);@@ -49,27 +91,56 @@ type ComboboxSharedProps<TOption> = {shouldFilter?: boolean;/** Keep selected values in the option list even when absent from the latest results. */includeMissingSelectedOptions?: boolean;+ /**+ * Adds a validated Create row. Inline mode persists directly from the query;+ * dialog mode delegates metadata, validation, persistence, and controlled+ * option/selection updates to the caller's form.+ */+ creation?: ComboboxCreationConfig<TOption>;+};++type ComboboxInputProps = Omit<+ React.ComponentPropsWithoutRef<"input">,+ "children" | "disabled" | "multiple" | "onChange" | "type" | "value"+>;++type ComboboxSingleValueProps<TOption> = {+ multiple?: false;+ value?: TOption | null;+};++type ComboboxSingleDefaultClearProps<TOption> = ComboboxSingleValueProps<TOption> & {+ isClearable?: true;+ onValueChange: (option: TOption | null) => void;+ onClear?: undefined;+};++type ComboboxSingleOverrideClearProps<TOption> = ComboboxSingleValueProps<TOption> & {+ isClearable?: true;+ onValueChange: (option: TOption) => void;+ onClear: () => void;+};++type ComboboxSingleNonClearableProps<TOption> = ComboboxSingleValueProps<TOption> & {+ isClearable: false;+ onValueChange: (option: TOption) => void;+ onClear?: never;};type ComboboxSingleProps<TOption> = ComboboxSharedProps<TOption> &- Omit<- React.ComponentPropsWithoutRef<"input">,- "children" | "disabled" | "multiple" | "onChange" | "type" | "value"- > & {- multiple?: false;- value?: TOption | null;- onValueChange: (option: TOption) => void;- onClear?: () => void;- };+ ComboboxInputProps &+ (+ | ComboboxSingleDefaultClearProps<TOption>+ | ComboboxSingleOverrideClearProps<TOption>+ | ComboboxSingleNonClearableProps<TOption>+ );type ComboboxMultipleProps<TOption> = ComboboxSharedProps<TOption> &- Omit<- React.ComponentPropsWithoutRef<"input">,- "children" | "disabled" | "multiple" | "onChange" | "type" | "value"- > & {+ ComboboxInputProps & {multiple: true;singleLine?: boolean;isSelectAll?: boolean;+ isClearable?: boolean;value?: readonly TOption[];onValueChange: (options: TOption[]) => void;onClear?: () => void;@@ -77,6 +148,15 @@ type ComboboxMultipleProps<TOption> = ComboboxSharedProps<TOption> &type ComboboxProps<TOption> = ComboboxSingleProps<TOption> | ComboboxMultipleProps<TOption>;+const clearSingleComboboxValue = <TOption,>(props: ComboboxSingleProps<TOption>) => {+ if (props.onClear) {+ props.onClear();+ return;+ }++ if (props.isClearable !== false) props.onValueChange(null);+};+const SINGLE_LIST_MAX_HEIGHT = "min(18.75rem, var(--available-height, 50dvh))";const MULTIPLE_LIST_MAX_HEIGHT = "min(18.75rem, var(--available-height, 50dvh))";@@ -95,6 +175,61 @@ const preventComboboxFormSubmit = (event: React.KeyboardEvent<HTMLInputElement>)if (event.key === "Enter") event.preventDefault();};+const isComboboxTrailingSlotEvent = (event: Event) =>+ event.target instanceof Element &&+ Boolean(event.target.closest("[data-slot='combobox-trailing-slot']"));++const isComboboxCreateItemEvent = (event: Event) =>+ event.target instanceof Element &&+ Boolean(event.target.closest("[data-slot='combobox-create-item']"));++type ComboboxTrailingSlotProps = {+ canClear: boolean;+ clearAriaLabel: string;+ isBusy: boolean;+ className?: string;+ onClear: () => void;+};++const ComboboxTrailingSlot = ({+ canClear,+ clearAriaLabel,+ isBusy,+ className,+ onClear+}: ComboboxTrailingSlotProps) => {+ let state = "chevron";+ if (canClear) state = "clear";+ if (isBusy) state = "loading";++ return (+ <div+ data-slot="combobox-trailing-slot"+ data-state={state}+ className={cn(+ "pointer-events-none flex size-7 shrink-0 items-center justify-center text-accent",+ className+ )}+ >+ {state === "loading" && <Loader2Icon aria-hidden="true" className="size-4 animate-spin" />}+ {state === "clear" && (+ <button+ type="button"+ aria-label={clearAriaLabel}+ onPointerDown={(event) => {+ event.preventDefault();+ }}+ onClick={onClear}+ className="pointer-events-auto flex size-full items-center justify-center rounded-md text-muted outline-none hover:bg-foreground/5 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"+ >+ <XIcon aria-hidden="true" className="size-4" />+ </button>+ )}+ {state === "chevron" && <ChevronDownIcon aria-hidden="true" className="size-4" />}+ </div>+ );+};+const useComboboxItems = <TOption,>(options: readonly TOption[],selectedOptions: readonly TOption[],@@ -107,15 +242,34 @@ const useComboboxItems = <TOption,>([getOptionValue, includeMissingSelectedOptions, options, selectedOptions]);-type ComboboxItem<TOption> = {+type ComboboxOptionItem<TOption> = {+ type: "option";option: TOption;};+type ComboboxCreateItem = {+ type: "create";+ inputValue: string;+};++type ComboboxItem<TOption> = ComboboxOptionItem<TOption> | ComboboxCreateItem;+type ComboboxGroup<TOption> = {+ type: "group";value: string;items: ComboboxItem<TOption>[];+ isCreationGroup?: boolean;};+const isInlineCreationConfig = <TOption,>(+ creation?: ComboboxCreationConfig<TOption>+): creation is ComboboxInlineCreationConfig<TOption> =>+ Boolean(creation && creation.mode !== "dialog");++const isDialogCreationConfig = <TOption,>(+ creation?: ComboboxCreationConfig<TOption>+): creation is ComboboxDialogCreationConfig<TOption> => creation?.mode === "dialog";+const usePrimitiveComboboxItems = <TOption,>(items: readonly TOption[],getOptionValue: (option: TOption) => string,@@ -125,14 +279,17 @@ const usePrimitiveComboboxItems = <TOption,>(// Base UI treats any object with an `items` property as a group. Wrapping every// consumer option keeps provider-specific fields opaque to the primitive and// reserves the grouped shape for groups created explicitly below.- const flatItems = items.map((option) => ({ option }));+ const flatItems: ComboboxOptionItem<TOption>[] = items.map((option) => ({+ type: "option",+ option+ }));const itemsByValue = new Map(flatItems.map((item) => [getOptionValue(item.option), item] as const));if (!getOptionGroup) return { itemsByValue, rootItems: flatItems };- const groupedItems = new Map<string, ComboboxItem<TOption>[]>();+ const groupedItems = new Map<string, ComboboxOptionItem<TOption>[]>();flatItems.forEach((item) => {const group = getOptionGroup(item.option);const groupItems = groupedItems.get(group);@@ -143,6 +300,7 @@ const usePrimitiveComboboxItems = <TOption,>(return {itemsByValue,rootItems: Array.from(groupedItems, ([value, groupItems]) => ({+ type: "group" as const,value,items: groupItems}))@@ -159,6 +317,7 @@ type ComboboxListProps<TOption> = Omit<| "isLoading"| "isOptionDisabled"| "loadingMessage"+ | "creation"| "renderOption"| "renderOptionIndicator">,@@ -169,6 +328,8 @@ type ComboboxListProps<TOption> = Omit<isEmpty: boolean;selectedValues: ReadonlySet<string>;maxHeight: string;+ creationError: { error: unknown; inputValue: string } | null;+ isCreationPending: boolean;};const ComboboxList = <TOption,>({@@ -179,14 +340,59 @@ const ComboboxList = <TOption,>({isLoading,isOptionDisabled,loadingMessage,+ creation,renderOption,renderOptionIndicator,ariaLabel,isEmpty,selectedValues,- maxHeight+ maxHeight,+ creationError,+ isCreationPending}: ComboboxListProps<TOption>) => {+ const inlineCreation = isInlineCreationConfig(creation) ? creation : undefined;+const renderItem = (item: ComboboxItem<TOption>) => {+ if (item.type === "create") {+ const hasCreationError = Boolean(+ inlineCreation && creationError?.inputValue === item.inputValue+ );+ const error = hasCreationError ? creationError?.error : undefined;++ return (+ <ComboboxPrimitive.Item+ key={`create:${item.inputValue}`}+ data-slot="combobox-create-item"+ value={item}+ disabled={creation?.isDisabled || creation?.isPending || isCreationPending}+ className={cn(+ COMBOBOX_ROW_CLASS,+ "px-2 data-[disabled]:cursor-not-allowed data-[disabled]:opacity-65 data-[highlighted]:bg-foreground/5 data-[highlighted]:text-foreground"+ )}+ >+ {isCreationPending ? (+ <Loader2Icon className="size-4 shrink-0 animate-spin text-accent" aria-hidden="true" />+ ) : (+ <PlusIcon className="size-4 shrink-0 text-accent" aria-hidden="true" />+ )}+ <span className="min-w-0 flex-1">+ <span className="block truncate">+ {isCreationPending && inlineCreation+ ? (inlineCreation.formatPendingLabel?.(item.inputValue) ??+ `Creating "${item.inputValue}"...`)+ : (creation?.formatLabel?.(item.inputValue) ?? `Create "${item.inputValue}"`)}+ </span>+ {hasCreationError ? (+ <span role="alert" className="block text-xs whitespace-normal text-danger">+ {inlineCreation?.formatError?.(error, item.inputValue) ??+ `Could not create "${item.inputValue}". Try again.`}+ </span>+ ) : null}+ </span>+ </ComboboxPrimitive.Item>+ );+ }+const { option } = item;const optionValue = getOptionValue(option);const isSelected = selectedValues.has(optionValue);@@ -239,12 +445,12 @@ const ComboboxList = <TOption,>({<ComboboxPrimitive.Groupkey={group.value}items={group.items}+ aria-label={group.isCreationGroup ? "Create option" : undefined}className={cn(- group.value === "" && "border-b border-border pb-1",- group.value === "" && "mb-1"+ !group.isCreationGroup && group.value === "" && "mb-1 border-b border-border pb-1")}>- {group.value !== "" && (+ {!group.isCreationGroup && group.value !== "" && (<ComboboxPrimitive.GroupLabel className="px-2 py-1.5 text-xs font-medium text-muted">{group.value}</ComboboxPrimitive.GroupLabel>@@ -366,46 +572,240 @@ const useComboboxFilter = <TOption,>({[getOptionKeywords, getOptionLabel]);-const SingleCombobox = <TOption,>({- options = [],- value,- onValueChange,- getOptionValue,- getOptionLabel,- getOptionKeywords,- getOptionGroup,- isOptionDisabled,- onSearchChange,- listFooter,- renderOption,- renderOptionIndicator,- renderValue,- onClear,- clearAriaLabel = "Clear selection",- placeholder = "Select an option...",- searchPlaceholder = "Search...",- searchAriaLabel = searchPlaceholder,- emptyMessage = "No options found.",- loadingMessage = "Loading options...",- isDisabled = false,- isLoading = false,- isError = false,- modal = false,- portalContainer: portalContainerProp,- className,- contentClassName,- onInputValueChange,- shouldFilter = true,- includeMissingSelectedOptions = true,- id,- onKeyDown,- ...inputProps-}: ComboboxSingleProps<TOption>) => {+const useComboboxCreation = <TOption,>({+ creation,+ onSuccess+}: {+ creation?: ComboboxInlineCreationConfig<TOption>;+ onSuccess: (inputValue: string) => void;+}) => {+ const pendingRef = React.useRef(false);+ const requestIdRef = React.useRef(0);+ const [state, setState] = React.useState<+ | { status: "idle" }+ | { status: "pending"; inputValue: string }+ | { status: "failed"; inputValue: string; error: unknown }+ >({ status: "idle" });++ React.useEffect(+ () => () => {+ requestIdRef.current += 1;+ pendingRef.current = false;+ },+ []+ );++ const clearError = React.useCallback(() => {+ setState((current) => (current.status === "failed" ? { status: "idle" } : current));+ }, []);++ const create = React.useCallback(+ (inputValue: string) => {+ if (!creation || creation.isDisabled || creation.isPending || pendingRef.current) return;++ const requestId = requestIdRef.current + 1;+ requestIdRef.current = requestId;+ pendingRef.current = true;+ setState({ status: "pending", inputValue });++ Promise.resolve()+ .then(() => creation.onCreate(inputValue))+ .then(+ () => {+ if (requestIdRef.current !== requestId) return;+ pendingRef.current = false;+ setState({ status: "idle" });+ onSuccess(inputValue);+ },+ (error: unknown) => {+ if (requestIdRef.current !== requestId) return;+ pendingRef.current = false;+ setState({ status: "failed", error, inputValue });+ }+ );+ },+ [creation, onSuccess]+ );++ return {+ clearError,+ create,+ creationError:+ state.status === "failed" ? { error: state.error, inputValue: state.inputValue } : null,+ isCreationPending: state.status === "pending" || Boolean(creation?.isPending),+ isCreationActive: () => pendingRef.current,+ pendingInputValue: state.status === "pending" ? state.inputValue : null+ };+};++type ComboboxDialogCreationState<TOption> = {+ creation?: ComboboxDialogCreationConfig<TOption>;+ initialInput: string;+ isOpen: boolean;+ open: (inputValue: string) => void;+ complete: () => void;+ cancel: () => void;+ onOpenChange: (open: boolean) => void;+ onCloseAutoFocus: (event: Event) => void;+};++type ComboboxCreationDialogProps<TOption> = Omit<ComboboxDialogCreationState<TOption>, "open">;++const useComboboxDialogCreation = <TOption,>({+ creation,+ onComplete,+ onClosed+}: {+ creation?: ComboboxCreationConfig<TOption>;+ onComplete: (inputValue: string) => void;+ onClosed: (outcome: "complete" | "cancel") => void;+}): ComboboxDialogCreationState<TOption> => {+ const dialogCreation = isDialogCreationConfig(creation) ? creation : undefined;+ const [initialInput, setInitialInput] = React.useState("");+ const [isOpen, setIsOpen] = React.useState(false);+ const outcomeRef = React.useRef<"complete" | "cancel" | null>(null);++ const open = React.useCallback(+ (inputValue: string) => {+ if (!dialogCreation || dialogCreation.isDisabled || dialogCreation.isPending) return;+ outcomeRef.current = null;+ setInitialInput(inputValue);+ setIsOpen(true);+ },+ [dialogCreation]+ );++ const complete = React.useCallback(() => {+ outcomeRef.current = "complete";+ onComplete(initialInput);+ setIsOpen(false);+ }, [initialInput, onComplete]);++ const cancel = React.useCallback(() => {+ if (dialogCreation?.isPending) return;+ outcomeRef.current = "cancel";+ setIsOpen(false);+ }, [dialogCreation?.isPending]);++ const onOpenChange = React.useCallback(+ (nextOpen: boolean) => {+ if (!nextOpen) cancel();+ },+ [cancel]+ );++ const onCloseAutoFocus = React.useCallback(+ (event: Event) => {+ event.preventDefault();+ const outcome = outcomeRef.current;+ outcomeRef.current = null;+ if (outcome) onClosed(outcome);+ },+ [onClosed]+ );++ return {+ creation: dialogCreation,+ initialInput,+ isOpen,+ open,+ complete,+ cancel,+ onOpenChange,+ onCloseAutoFocus+ };+};++const ComboboxCreationDialog = <TOption,>({+ creation,+ initialInput,+ isOpen,+ complete,+ cancel,+ onOpenChange,+ onCloseAutoFocus+}: ComboboxCreationDialogProps<TOption>) => {+ if (!creation) return null;++ const preventPendingDismissal = (event: Event) => {+ if (creation.isPending) event.preventDefault();+ };++ return (+ <Dialog open={isOpen} onOpenChange={onOpenChange}>+ <DialogContent+ showCloseButton={!creation.isPending}+ onEscapeKeyDown={preventPendingDismissal}+ onPointerDownOutside={preventPendingDismissal}+ onInteractOutside={preventPendingDismissal}+ onCloseAutoFocus={onCloseAutoFocus}+ onSubmit={(event) => event.stopPropagation()}+ >+ <DialogHeader>+ <DialogTitle>{creation.title}</DialogTitle>+ <DialogDescription>{creation.description}</DialogDescription>+ </DialogHeader>+ {creation.renderForm({ initialInput, complete, cancel })}+ </DialogContent>+ </Dialog>+ );+};++const SingleCombobox = <TOption,>(props: ComboboxSingleProps<TOption>) => {+ const {+ options = [],+ value,+ onValueChange,+ getOptionValue,+ getOptionLabel,+ getOptionKeywords,+ getOptionGroup,+ isOptionDisabled,+ onSearchChange,+ listFooter,+ renderOption,+ renderOptionIndicator,+ renderValue,+ onClear,+ clearAriaLabel = "Clear selection",+ placeholder = "Select an option...",+ searchPlaceholder = "Search...",+ searchAriaLabel = searchPlaceholder,+ emptyMessage = "No options found.",+ loadingMessage = "Loading options...",+ isClearable = true,+ isDisabled = false,+ isLoading = false,+ isError = false,+ modal = false,+ portalContainer: portalContainerProp,+ className,+ contentClassName,+ onInputValueChange,+ shouldFilter = true,+ includeMissingSelectedOptions = true,+ creation,+ id,+ onClick,+ onFocus,+ onKeyDown,+ ...inputProps+ } = props;const inputRef = React.useRef<HTMLInputElement | null>(null);const highlightedOptionValueRef = React.useRef<string | null>(null);const [open, setOpen] = React.useState(false);const selectedLabel = value == null ? "" : getOptionLabel(value);const [search, setSearch] = React.useState("");+ const searchRef = React.useRef(search);+ searchRef.current = search;+ const isDialogCreationActiveRef = React.useRef(false);+ const [isEditing, setIsEditingState] = React.useState(false);+ const isEditingRef = React.useRef(isEditing);+ isEditingRef.current = isEditing;+ const setIsEditing = React.useCallback((nextIsEditing: boolean) => {+ isEditingRef.current = nextIsEditing;+ setIsEditingState(nextIsEditing);+ }, []);const selectedOptions = React.useMemo(() => (value == null ? [] : [value]), [value]);// A caller-owned search returns one already-filtered page after a debounce and a round trip.// The local matcher must not filter that page again, a selection missing from it is not a@@ -425,15 +825,18 @@ const SingleCombobox = <TOption,>({getOptionGroup);const selectedItem =- value == null ? null : (itemsByValue.get(getOptionValue(value)) ?? { option: value });+ value == null+ ? null+ : (itemsByValue.get(getOptionValue(value)) ?? ({ type: "option", option: value } as const));const filter = useComboboxFilter({ getOptionKeywords, getOptionLabel });const primitiveFilter = React.useCallback(- (item: ComboboxItem<TOption>, query: string) => filter(item.option, query),+ (item: ComboboxItem<TOption>, query: string) =>+ item.type === "create" || filter(item.option, query),[filter]);const visibleOptions = React.useMemo(- () => items.filter((option) => !isLocalFilterEnabled || filter(option, search)),- [filter, isLocalFilterEnabled, items, search]+ () => items.filter((option) => !isLocalFilterEnabled || !isEditing || filter(option, search)),+ [filter, isEditing, isLocalFilterEnabled, items, search]);const selectableOptions = React.useMemo(() => visibleOptions.filter((option) => !isOptionDisabled?.(option)),@@ -448,161 +851,280 @@ const SingleCombobox = <TOption,>({onSearchChange?.(nextSearch);onInputValueChange?.(nextSearch);};+ const creationInput =+ creation && isEditing+ ? getComboboxCreationInput({+ inputValue: search,+ options,+ selectedOptions,+ getOptionLabel,+ isDuplicate: creation.isDuplicate,+ isValid: creation.isValid+ })+ : null;+ const handleCreationSuccess = React.useCallback(+ (inputValue: string) => {+ if (searchRef.current.trim() !== inputValue) return;+ setOpen(false);+ setIsEditing(false);+ setSearch("");+ onSearchChange?.("");+ onInputValueChange?.("");+ },+ [onInputValueChange, onSearchChange, setIsEditing]+ );+ const handleCreationDialogClosed = React.useCallback((outcome: "complete" | "cancel") => {+ if (outcome === "cancel") setOpen(true);+ window.requestAnimationFrame(() => {+ inputRef.current?.focus();+ isDialogCreationActiveRef.current = false;+ });+ }, []);+ const dialogCreation = useComboboxDialogCreation({+ creation,+ onComplete: handleCreationSuccess,+ onClosed: handleCreationDialogClosed+ });+ const {+ clearError: clearCreationError,+ create: createOption,+ creationError,+ isCreationActive,+ isCreationPending,+ pendingInputValue+ } = useComboboxCreation({+ creation: isInlineCreationConfig(creation) ? creation : undefined,+ onSuccess: handleCreationSuccess+ });+ const handleClear = () => {+ if (!isClearable) return;+ setIsEditing(false);+ updateSearch("");+ clearCreationError();+ clearSingleComboboxValue(props);+ window.requestAnimationFrame(() => inputRef.current?.focus());+ };+ const creationItem: ComboboxCreateItem | null =+ pendingInputValue || creationInput+ ? { type: "create", inputValue: pendingInputValue ?? creationInput! }+ : null;+ const primitiveItems = React.useMemo(() => {+ if (!creationItem) return rootItems;+ if (!getOptionGroup) return [...rootItems, creationItem];+ return [+ ...rootItems,+ {+ type: "group" as const,+ value: "__combobox-creation__",+ items: [creationItem],+ isCreationGroup: true+ }+ ];+ }, [creationItem, getOptionGroup, rootItems]);+ let statusMessage: React.ReactNode = null;+ if (isLoading) statusMessage = loadingMessage;+ else if (isCreationPending) statusMessage = "Creating option...";return (- <ComboboxPrimitive.Root<ComboboxItem<TOption>, false>- items={rootItems}- value={selectedItem}- onValueChange={(nextValue, eventDetails) => {- if (nextValue == null) {- if (eventDetails.reason === "clear-press") {- updateSearch("");- onClear?.();- }- return;- }- onValueChange(nextValue.option);- }}- open={open}- onOpenChange={(nextOpen, eventDetails) => {- setOpen(nextOpen);- if (nextOpen) {- // Clicking into a selected combobox starts from its current label. When- // typing itself opens the popup, preserve the query emitted just before- // this event instead of replacing the user's first keystroke. Consumers- // that search server-side never receive the seeded label (it would be- // sent as a query and match nothing), so their input must stay in step- // with the empty query the parent still holds.- if (eventDetails.reason !== "input-change") {- setSearch(isLocalFilterEnabled ? selectedLabel : "");- }- } else {- highlightedOptionValueRef.current = null;- updateSearch("");- }- }}- onItemHighlighted={(item) => {- highlightedOptionValueRef.current = item ? getOptionValue(item.option) : null;- }}- inputValue={open ? search : selectedLabel}- onInputValueChange={(nextValue, eventDetails) => {- if (eventDetails.reason === "input-change" || eventDetails.reason === "input-clear") {- updateSearch(nextValue);- }- }}- itemToStringLabel={(item) => getOptionLabel(item.option)}- itemToStringValue={(item) => getOptionValue(item.option)}- isItemEqualToValue={(option, selectedOption) =>- getOptionValue(option.option) === getOptionValue(selectedOption.option)- }- filter={isLocalFilterEnabled ? primitiveFilter : null}- disabled={isDisabled}- modal={modal}- autoHighlight={!isSearchOwnedByCaller}- >- <div className="relative w-full">- <ComboboxPrimitive.Input- ref={inputRef}- id={id}- data-slot="combobox-input"- data-invalid={isError}- aria-invalid={isError || undefined}- aria-busy={isLoading || undefined}- placeholder={open ? searchPlaceholder : placeholder}- onKeyDown={(event) => {- onKeyDown?.(event);-- const hasHighlightedOption = selectableOptions.some(- (option) => getOptionValue(option) === highlightedOptionValueRef.current- );+ <>+ <div data-slot="combobox-control" className="relative w-full">+ <ComboboxPrimitive.Root<ComboboxItem<TOption>, false>+ items={primitiveItems}+ value={selectedItem}+ onValueChange={(nextValue, eventDetails) => {+ if (nextValue == null) {+ if (eventDetails.reason === "clear-press") handleClear();+ return;+ }+ if (nextValue.type === "create") {+ eventDetails.cancel();+ if (dialogCreation.creation) {+ isDialogCreationActiveRef.current = true;+ setOpen(false);+ dialogCreation.open(nextValue.inputValue);+ } else {+ createOption(nextValue.inputValue);+ }+ return;+ }+ onValueChange(nextValue.option);+ }}+ open={open}+ onOpenChange={(nextOpen, eventDetails) => {if (- !event.defaultPrevented &&- event.key === "Enter" &&- open &&- !isLoading &&- !isSearchOwnedByCaller &&- !hasHighlightedOption &&- selectableOptions[0]+ !nextOpen &&+ eventDetails.reason === "outside-press" &&+ isComboboxTrailingSlotEvent(eventDetails.event)) {- onValueChange(selectableOptions[0]);- setOpen(false);+ eventDetails.cancel();+ return;+ }+ if (!nextOpen && isCreationActive() && eventDetails.reason === "item-press") {+ setOpen(true);+ return;+ }+ const isOpeningCreationDialog =+ !nextOpen &&+ eventDetails.reason === "item-press" &&+ isDialogCreationConfig(creation) &&+ (isDialogCreationActiveRef.current || isComboboxCreateItemEvent(eventDetails.event));+ setOpen(nextOpen);+ if (!nextOpen && !isCreationActive() && !isOpeningCreationDialog) {+ highlightedOptionValueRef.current = null;+ setIsEditing(false);updateSearch("");+ clearCreationError();}-- preventComboboxFormSubmit(event);}}- className={cn(- "h-9 w-full rounded-md border border-border bg-transparent py-2 pr-9 pl-2.5 text-sm text-foreground transition-[color,box-shadow] outline-none placeholder:text-muted",- "hover:border-foreground/20 focus:border-ring focus:ring-[3px] focus:ring-ring/50",- "data-[disabled]:pointer-events-none data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50 data-[invalid=true]:border-danger data-[invalid=true]:ring-danger/40",- !open && value != null && renderValue && "text-transparent",- className- )}- {...inputProps}- />- {!open && value != null && renderValue && (- <span- className={cn(- "pointer-events-none absolute inset-y-0 right-9 left-2.5 flex min-w-0 items-center truncate text-sm text-foreground",- isDisabled && "opacity-50"- )}- >- {renderValue(value)}- </span>- )}- {value != null && onClear && (- <ComboboxPrimitive.Clear- aria-label={clearAriaLabel}- tabIndex={0}- onClick={() => window.requestAnimationFrame(() => inputRef.current?.focus())}- className={cn(- "absolute top-1/2 right-7 z-10 flex size-7 -translate-y-1/2 items-center justify-center rounded-md text-muted outline-none",- "hover:bg-foreground/5 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[popup-open]:hidden"+ onItemHighlighted={(item) => {+ highlightedOptionValueRef.current =+ item?.type === "option" ? getOptionValue(item.option) : (item?.inputValue ?? null);+ }}+ inputValue={isEditing ? search : selectedLabel}+ onInputValueChange={(nextValue, eventDetails) => {+ if (eventDetails.reason === "input-change" || eventDetails.reason === "input-clear") {+ if (+ eventDetails.reason === "input-clear" &&+ (isCreationActive() || isDialogCreationActiveRef.current)+ )+ return;+ setIsEditing(eventDetails.reason === "input-change");+ updateSearch(nextValue);+ clearCreationError();+ }+ }}+ itemToStringLabel={(item) =>+ item.type === "create" ? item.inputValue : getOptionLabel(item.option)+ }+ itemToStringValue={(item) =>+ item.type === "create" ? `create:${item.inputValue}` : getOptionValue(item.option)+ }+ isItemEqualToValue={(option, selectedOption) =>+ option.type === "option" &&+ selectedOption.type === "option" &&+ getOptionValue(option.option) === getOptionValue(selectedOption.option)+ }+ filter={isLocalFilterEnabled && isEditing ? primitiveFilter : null}+ disabled={isDisabled}+ modal={modal}+ autoHighlight={!isSearchOwnedByCaller}+ >+ <div className="relative w-full">+ <ComboboxPrimitive.Input+ ref={inputRef}+ id={id}+ data-slot="combobox-input"+ data-invalid={isError}+ aria-invalid={isError || undefined}+ aria-busy={isLoading || isCreationPending || undefined}+ placeholder={placeholder}+ onClick={(event) => {+ onClick?.(event);+ if (!event.defaultPrevented && value != null && !isEditingRef.current) {+ event.currentTarget.select();+ }+ }}+ onFocus={(event) => {+ onFocus?.(event);+ if (!event.defaultPrevented && value != null && !isEditingRef.current) {+ event.currentTarget.select();+ }+ }}+ onKeyDown={(event) => {+ onKeyDown?.(event);++ if (+ !event.defaultPrevented &&+ value != null &&+ !isEditingRef.current &&+ ((event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) ||+ event.key === "Backspace" ||+ event.key === "Delete")+ ) {+ setIsEditing(true);+ setSearch("");+ }++ const hasHighlightedOption = highlightedOptionValueRef.current != null;+ if (+ !event.defaultPrevented &&+ event.key === "Enter" &&+ open &&+ !isLoading &&+ !isSearchOwnedByCaller &&+ !hasHighlightedOption &&+ selectableOptions[0]+ ) {+ onValueChange(selectableOptions[0]);+ setOpen(false);+ updateSearch("");+ }++ preventComboboxFormSubmit(event);+ }}+ className={cn(+ "h-9 w-full rounded-md border border-border bg-transparent py-2 pr-9 pl-2.5 text-sm text-foreground transition-[color,box-shadow] outline-none placeholder:text-muted",+ "hover:border-foreground/20 focus:border-ring focus:ring-[3px] focus:ring-ring/50",+ "data-[disabled]:pointer-events-none data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50 data-[invalid=true]:border-danger data-[invalid=true]:ring-danger/40",+ !isEditing && value != null && renderValue && "text-transparent",+ className+ )}+ {...inputProps}+ />+ {!isEditing && value != null && renderValue && (+ <span+ className={cn(+ "pointer-events-none absolute inset-y-0 right-9 left-2.5 flex min-w-0 items-center truncate text-sm text-foreground",+ isDisabled && "opacity-50"+ )}+ >+ {renderValue(value)}+ </span>)}+ {isLoading && <span className="sr-only">{loadingMessage}</span>}+ </div>+ <ComboboxPrimitive.Status className="sr-only">{statusMessage}</ComboboxPrimitive.Status>+ <ComboboxPopup+ anchor={inputRef}+ ariaLabel={searchAriaLabel}+ className={contentClassName}+ portalContainer={portalContainerProp}>- <XIcon className="size-3.5" />- </ComboboxPrimitive.Clear>- )}- {isLoading ? (- <Loader2Icon- className="pointer-events-none absolute top-1/2 right-2 size-4 -translate-y-1/2 animate-spin text-accent"- aria-hidden="true"- />- ) : (- <ChevronDownIcon- className="pointer-events-none absolute top-1/2 right-2 size-4 -translate-y-1/2 text-accent"- aria-hidden="true"- />- )}- {isLoading && <span className="sr-only">{loadingMessage}</span>}- </div>- <ComboboxPrimitive.Status className="sr-only">- {isLoading ? loadingMessage : null}- </ComboboxPrimitive.Status>- <ComboboxPopup- anchor={inputRef}- ariaLabel={searchAriaLabel}- className={contentClassName}- portalContainer={portalContainerProp}- >- <ComboboxList- emptyMessage={typeof emptyMessage === "function" ? emptyMessage(search) : emptyMessage}- loadingMessage={loadingMessage}- isLoading={isLoading}- getOptionValue={getOptionValue}- getOptionLabel={getOptionLabel}- getOptionGroup={getOptionGroup}- isOptionDisabled={isOptionDisabled}- renderOption={renderOption}- renderOptionIndicator={renderOptionIndicator}- ariaLabel={`${searchAriaLabel} suggestions`}- isEmpty={visibleOptions.length === 0}- selectedValues={selectedValues}- maxHeight={SINGLE_LIST_MAX_HEIGHT}+ <ComboboxList+ emptyMessage={+ typeof emptyMessage === "function" ? emptyMessage(search) : emptyMessage+ }+ loadingMessage={loadingMessage}+ creation={creation}+ isLoading={isLoading}+ getOptionValue={getOptionValue}+ getOptionLabel={getOptionLabel}+ getOptionGroup={getOptionGroup}+ isOptionDisabled={isOptionDisabled}+ renderOption={renderOption}+ renderOptionIndicator={renderOptionIndicator}+ ariaLabel={`${searchAriaLabel} suggestions`}+ isEmpty={visibleOptions.length === 0 && !creationItem}+ selectedValues={selectedValues}+ maxHeight={SINGLE_LIST_MAX_HEIGHT}+ creationError={creationError}+ isCreationPending={isCreationPending}+ />+ {listFooter && <ComboboxListFooter>{listFooter}</ComboboxListFooter>}+ </ComboboxPopup>+ </ComboboxPrimitive.Root>+ <ComboboxTrailingSlot+ className="absolute top-1 right-1 z-10"+ isBusy={isLoading || isCreationPending}+ canClear={Boolean(+ isClearable && !isDisabled && (value != null || (isEditing && search.length > 0))+ )}+ clearAriaLabel={clearAriaLabel}+ onClear={handleClear}/>- {listFooter && <ComboboxListFooter>{listFooter}</ComboboxListFooter>}- </ComboboxPopup>- </ComboboxPrimitive.Root>+ </div>+ <ComboboxCreationDialog {...dialogCreation} />+ </>);};@@ -624,6 +1146,7 @@ const MultipleCombobox = <TOption,>({clearAriaLabel = "Clear all selections",singleLine = false,isSelectAll = false,+ isClearable = true,placeholder = "Select options...",searchPlaceholder = "Search...",searchAriaLabel = searchPlaceholder,@@ -639,6 +1162,7 @@ const MultipleCombobox = <TOption,>({onInputValueChange,shouldFilter = true,includeMissingSelectedOptions = true,+ creation,id,"aria-label": ariaLabel,"aria-labelledby": ariaLabelledBy,@@ -651,7 +1175,12 @@ const MultipleCombobox = <TOption,>({singleLine ? "horizontal" : "vertical");const [open, setOpen] = React.useState(false);+ const openRef = React.useRef(open);+ openRef.current = open;const [search, setSearch] = React.useState("");+ const searchRef = React.useRef(search);+ searchRef.current = search;+ const isDialogCreationActiveRef = React.useRef(false);const selectedOptions = React.useMemo(() => [...value], [value]);// A caller-owned search returns one already-filtered page after a debounce and a round trip.// The local matcher must not filter that page again, a selection missing from it is not a@@ -670,12 +1199,17 @@ const MultipleCombobox = <TOption,>({getOptionGroup);const selectedItems = React.useMemo(- () => selectedOptions.map((option) => itemsByValue.get(getOptionValue(option)) ?? { option }),+ () =>+ selectedOptions.map(+ (option) =>+ itemsByValue.get(getOptionValue(option)) ?? ({ type: "option", option } as const)+ ),[getOptionValue, itemsByValue, selectedOptions]);const filter = useComboboxFilter({ getOptionKeywords, getOptionLabel });const primitiveFilter = React.useCallback(- (item: ComboboxItem<TOption>, query: string) => filter(item.option, query),+ (item: ComboboxItem<TOption>, query: string) =>+ item.type === "create" || filter(item.option, query),[filter]);const selectedValues = React.useMemo(@@ -700,6 +1234,80 @@ const MultipleCombobox = <TOption,>({const areAllOptionsSelected =selectAllOptions.length > 0 &&selectAllOptions.every((option) => selectedValues.has(getOptionValue(option)));+ const creationInput = creation+ ? getComboboxCreationInput({+ inputValue: search,+ options,+ selectedOptions,+ getOptionLabel,+ isDuplicate: creation.isDuplicate,+ isValid: creation.isValid+ })+ : null;+ const handleCreationSuccess = React.useCallback(+ (inputValue: string) => {+ if (searchRef.current.trim() !== inputValue) return;+ setSearch("");+ onSearchChange?.("");+ onInputValueChange?.("");+ if (openRef.current) window.requestAnimationFrame(() => inputRef.current?.focus());+ },+ [onInputValueChange, onSearchChange]+ );+ const handleCreationDialogClosed = React.useCallback((outcome: "complete" | "cancel") => {+ if (outcome === "cancel") {+ openRef.current = true;+ setOpen(true);+ }+ window.requestAnimationFrame(() => {+ inputRef.current?.focus();+ isDialogCreationActiveRef.current = false;+ });+ }, []);+ const dialogCreation = useComboboxDialogCreation({+ creation,+ onComplete: handleCreationSuccess,+ onClosed: handleCreationDialogClosed+ });+ const {+ clearError: clearCreationError,+ create: createOption,+ creationError,+ isCreationActive,+ isCreationPending,+ pendingInputValue+ } = useComboboxCreation({+ creation: isInlineCreationConfig(creation) ? creation : undefined,+ onSuccess: handleCreationSuccess+ });+ const handleClear = () => {+ if (!isClearable) return;+ updateSearch("");+ clearCreationError();+ if (onClear) onClear();+ else onValueChange([]);+ window.requestAnimationFrame(() => inputRef.current?.focus());+ };+ const creationItem: ComboboxCreateItem | null =+ pendingInputValue || creationInput+ ? { type: "create", inputValue: pendingInputValue ?? creationInput! }+ : null;+ const primitiveItems = React.useMemo(() => {+ if (!creationItem) return rootItems;+ if (!getOptionGroup) return [...rootItems, creationItem];+ return [+ ...rootItems,+ {+ type: "group" as const,+ value: "__combobox-creation__",+ items: [creationItem],+ isCreationGroup: true+ }+ ];+ }, [creationItem, getOptionGroup, rootItems]);+ let statusMessage: React.ReactNode = null;+ if (isLoading) statusMessage = loadingMessage;+ else if (isCreationPending) statusMessage = "Creating option...";const handleSelectAllToggle = () => {const selectAllValues = new Set(selectAllOptions.map(getOptionValue));@@ -715,171 +1323,216 @@ const MultipleCombobox = <TOption,>({};return (- <ComboboxPrimitive.Root<ComboboxItem<TOption>, true>- multiple- items={rootItems}- value={selectedItems}- onValueChange={(nextValue, eventDetails) => {- if (eventDetails.reason === "item-press") {- eventDetails.cancel();- updateSearch("");- setOpen(true);- window.requestAnimationFrame(() => inputRef.current?.focus());- }+ <>+ <div data-slot="combobox-control" className="relative w-full">+ <ComboboxPrimitive.Root<ComboboxItem<TOption>, true>+ multiple+ items={primitiveItems}+ value={selectedItems}+ onValueChange={(nextValue, eventDetails) => {+ const createItem = nextValue.find((item) => item.type === "create");+ if (createItem) {+ eventDetails.cancel();+ if (dialogCreation.creation) {+ isDialogCreationActiveRef.current = true;+ openRef.current = false;+ setOpen(false);+ dialogCreation.open(createItem.inputValue);+ } else {+ createOption(createItem.inputValue);+ }+ return;+ }- if (eventDetails.reason === "clear-press" && onClear) {- onClear();- return;- }+ if (eventDetails.reason === "item-press") {+ eventDetails.cancel();+ updateSearch("");+ setOpen(true);+ window.requestAnimationFrame(() => inputRef.current?.focus());+ }- onValueChange(nextValue.map((item) => item.option));- }}- open={open}- onOpenChange={(nextOpen) => {- setOpen(nextOpen);- if (!nextOpen) updateSearch("");- }}- inputValue={search}- onInputValueChange={(nextValue, eventDetails) => {- setSearch(nextValue);- if (eventDetails.reason === "input-change" || eventDetails.reason === "input-clear") {- onSearchChange?.(nextValue);- onInputValueChange?.(nextValue);- }- }}- itemToStringLabel={(item) => getOptionLabel(item.option)}- itemToStringValue={(item) => getOptionValue(item.option)}- isItemEqualToValue={(option, selectedOption) =>- getOptionValue(option.option) === getOptionValue(selectedOption.option)- }- filter={isLocalFilterEnabled ? primitiveFilter : null}- disabled={isDisabled}- modal={modal}- autoHighlight={!isSearchOwnedByCaller}- >- <ComboboxPrimitive.Chips- ref={chipsRef}- data-slot="combobox-chips"- data-disabled={isDisabled ? "" : undefined}- data-invalid={isError}- className={cn(- COMBOBOX_CHIPS_CLASS,- singleLine ? "items-center" : "items-start",- value.length > 0 ? "p-1" : "py-1 pr-2 pl-2.5",- className- )}- >- <div- className={comboboxChipsViewportClass(singleLine)}- ref={setViewportRef}- data-scroll-edge-axis={singleLine ? "horizontal" : "vertical"}- data-scrollable-start={scrollEdges.start}- data-scrollable-end={scrollEdges.end}+ if (eventDetails.reason === "clear-press") {+ handleClear();+ return;+ }++ onValueChange(+ nextValue.flatMap((item) => (item.type === "option" ? [item.option] : []))+ );+ }}+ open={open}+ onOpenChange={(nextOpen, eventDetails) => {+ if (+ !nextOpen &&+ eventDetails.reason === "outside-press" &&+ isComboboxTrailingSlotEvent(eventDetails.event)+ ) {+ eventDetails.cancel();+ return;+ }+ if (!nextOpen && isCreationActive() && eventDetails.reason === "item-press") {+ openRef.current = true;+ setOpen(true);+ return;+ }+ const isOpeningCreationDialog =+ !nextOpen &&+ eventDetails.reason === "item-press" &&+ isDialogCreationConfig(creation) &&+ (isDialogCreationActiveRef.current || isComboboxCreateItemEvent(eventDetails.event));+ openRef.current = nextOpen;+ setOpen(nextOpen);+ if (!nextOpen && !isCreationActive() && !isOpeningCreationDialog) {+ updateSearch("");+ clearCreationError();+ }+ }}+ inputValue={search}+ onInputValueChange={(nextValue, eventDetails) => {+ if (+ eventDetails.reason === "input-clear" &&+ (isCreationActive() || isDialogCreationActiveRef.current)+ )+ return;+ setSearch(nextValue);+ if (eventDetails.reason === "input-change" || eventDetails.reason === "input-clear") {+ clearCreationError();+ onSearchChange?.(nextValue);+ onInputValueChange?.(nextValue);+ }+ }}+ itemToStringLabel={(item) =>+ item.type === "create" ? item.inputValue : getOptionLabel(item.option)+ }+ itemToStringValue={(item) =>+ item.type === "create" ? `create:${item.inputValue}` : getOptionValue(item.option)+ }+ isItemEqualToValue={(option, selectedOption) =>+ option.type === "option" &&+ selectedOption.type === "option" &&+ getOptionValue(option.option) === getOptionValue(selectedOption.option)+ }+ filter={isLocalFilterEnabled ? primitiveFilter : null}+ disabled={isDisabled}+ modal={modal}+ autoHighlight={!isSearchOwnedByCaller}>- <ComboboxPrimitive.Value>- {(selectedValue: ComboboxItem<TOption>[]) => (- <>- {selectedValue.map(({ option }) => {- const label = getOptionLabel(option);- return (- <ComboboxPrimitive.Chip- key={getOptionValue(option)}- className={COMBOBOX_CHIP_CLASS}- >- <span className={COMBOBOX_CHIP_LABEL_CLASS}>- {renderValue?.(option) ?? label}- </span>- {!isDisabled && (- <ComboboxPrimitive.ChipRemove- aria-label={`Remove ${label}`}- className={COMBOBOX_CHIP_REMOVE_CLASS}+ <ComboboxPrimitive.Chips+ ref={chipsRef}+ data-slot="combobox-chips"+ data-disabled={isDisabled ? "" : undefined}+ data-invalid={isError}+ className={cn(+ COMBOBOX_CHIPS_CLASS,+ singleLine ? "items-center" : "items-start",+ value.length > 0 ? "p-1 pr-8" : "py-1 pr-8 pl-2.5",+ className+ )}+ >+ <div+ className={comboboxChipsViewportClass(singleLine)}+ ref={setViewportRef}+ data-scroll-edge-axis={singleLine ? "horizontal" : "vertical"}+ data-scrollable-start={scrollEdges.start}+ data-scrollable-end={scrollEdges.end}+ >+ <ComboboxPrimitive.Value>+ {(selectedValue: ComboboxItem<TOption>[]) => (+ <>+ {selectedValue.map((item) => {+ if (item.type === "create") return null;+ const { option } = item;+ const label = getOptionLabel(option);+ return (+ <ComboboxPrimitive.Chip+ key={getOptionValue(option)}+ className={COMBOBOX_CHIP_CLASS}>- <XIcon className="size-3" />- </ComboboxPrimitive.ChipRemove>- )}- </ComboboxPrimitive.Chip>- );+ <span className={COMBOBOX_CHIP_LABEL_CLASS}>+ {renderValue?.(option) ?? label}+ </span>+ {!isDisabled && (+ <ComboboxPrimitive.ChipRemove+ aria-label={`Remove ${label}`}+ className={COMBOBOX_CHIP_REMOVE_CLASS}+ >+ <XIcon className="size-3" />+ </ComboboxPrimitive.ChipRemove>+ )}+ </ComboboxPrimitive.Chip>+ );+ })}+ </>+ )}+ </ComboboxPrimitive.Value>+ <ComboboxPrimitive.Input+ ref={inputRef}+ id={id}+ aria-label={getComboboxInputAriaLabel({+ ariaLabel,+ ariaLabelledBy,+ id,+ searchAriaLabel})}- </>- )}- </ComboboxPrimitive.Value>- <ComboboxPrimitive.Input- ref={inputRef}- id={id}- aria-label={getComboboxInputAriaLabel({- ariaLabel,- ariaLabelledBy,- id,- searchAriaLabel- })}- aria-labelledby={ariaLabelledBy}- aria-invalid={isError || undefined}- aria-busy={isLoading || undefined}- placeholder={value.length === 0 ? placeholder : undefined}- onKeyDown={(event) => {- onKeyDown?.(event);- preventComboboxFormSubmit(event);- }}- className={COMBOBOX_CHIPS_INPUT_CLASS}- {...inputProps}- />- </div>- {value.length > 0 && !isDisabled && (- <ComboboxPrimitive.Clear- aria-label={clearAriaLabel}- tabIndex={0}- className="flex size-6 shrink-0 items-center justify-center rounded-md text-muted outline-none hover:bg-foreground/5 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring data-[disabled]:pointer-events-none data-[disabled]:opacity-50"+ aria-labelledby={ariaLabelledBy}+ aria-invalid={isError || undefined}+ aria-busy={isLoading || isCreationPending || undefined}+ placeholder={value.length === 0 ? placeholder : undefined}+ onKeyDown={(event) => {+ onKeyDown?.(event);+ preventComboboxFormSubmit(event);+ }}+ className={COMBOBOX_CHIPS_INPUT_CLASS}+ {...inputProps}+ />+ </div>+ </ComboboxPrimitive.Chips>+ <ComboboxPrimitive.Status className="sr-only">{statusMessage}</ComboboxPrimitive.Status>+ <ComboboxPopup+ anchor={chipsRef}+ className={contentClassName}+ portalContainer={portalContainerProp}>- <XIcon className="size-3.5" />- </ComboboxPrimitive.Clear>- )}- <span- aria-hidden="true"- className={cn(- "pointer-events-none flex h-6 shrink-0 items-center justify-center text-accent",- value.length > 0 && "mr-1"- )}- >- {isLoading ? (- <Loader2Icon className="size-4 animate-spin" />- ) : (- <ChevronDownIcon className="size-4" />- )}- </span>- </ComboboxPrimitive.Chips>- <ComboboxPrimitive.Status className="sr-only">- {isLoading ? loadingMessage : null}- </ComboboxPrimitive.Status>- <ComboboxPopup- anchor={chipsRef}- className={contentClassName}- portalContainer={portalContainerProp}- >- {selectAllOptions.length > 0 && (- <ComboboxSelectAll- areAllSelected={areAllOptionsSelected}- optionCount={selectAllOptions.length}- onToggle={handleSelectAllToggle}- />- )}- <ComboboxList- emptyMessage={typeof emptyMessage === "function" ? emptyMessage(search) : emptyMessage}- loadingMessage={loadingMessage}- isLoading={isLoading}- getOptionValue={getOptionValue}- getOptionLabel={getOptionLabel}- getOptionGroup={getOptionGroup}- isOptionDisabled={isOptionDisabled}- renderOption={renderOption}- renderOptionIndicator={renderOptionIndicator}- ariaLabel={`${searchAriaLabel} suggestions`}- isEmpty={visibleOptions.length === 0}- selectedValues={selectedValues}- maxHeight={MULTIPLE_LIST_MAX_HEIGHT}+ {selectAllOptions.length > 0 && (+ <ComboboxSelectAll+ areAllSelected={areAllOptionsSelected}+ optionCount={selectAllOptions.length}+ onToggle={handleSelectAllToggle}+ />+ )}+ <ComboboxList+ emptyMessage={+ typeof emptyMessage === "function" ? emptyMessage(search) : emptyMessage+ }+ loadingMessage={loadingMessage}+ creation={creation}+ isLoading={isLoading}+ getOptionValue={getOptionValue}+ getOptionLabel={getOptionLabel}+ getOptionGroup={getOptionGroup}+ isOptionDisabled={isOptionDisabled}+ renderOption={renderOption}+ renderOptionIndicator={renderOptionIndicator}+ ariaLabel={`${searchAriaLabel} suggestions`}+ isEmpty={visibleOptions.length === 0 && !creationItem}+ selectedValues={selectedValues}+ maxHeight={MULTIPLE_LIST_MAX_HEIGHT}+ creationError={creationError}+ isCreationPending={isCreationPending}+ />+ {listFooter && <ComboboxListFooter>{listFooter}</ComboboxListFooter>}+ </ComboboxPopup>+ </ComboboxPrimitive.Root>+ <ComboboxTrailingSlot+ className="absolute top-1 right-1 z-10"+ isBusy={isLoading || isCreationPending}+ canClear={isClearable && !isDisabled && (value.length > 0 || search.length > 0)}+ clearAriaLabel={clearAriaLabel}+ onClear={handleClear}/>- {listFooter && <ComboboxListFooter>{listFooter}</ComboboxListFooter>}- </ComboboxPopup>- </ComboboxPrimitive.Root>+ </div>+ <ComboboxCreationDialog {...dialogCreation} />+ </>);};@@ -889,6 +1542,22 @@ const MultipleCombobox = <TOption,>({* Options are filtered in the browser unless `onSearchChange` is passed, which hands* filtering to the caller so the list can be fetched a page at a time.*/+function Combobox<TOption>(props: ComboboxMultipleProps<TOption>): React.ReactElement;+function Combobox<TOption>(+ props: ComboboxSharedProps<TOption> &+ ComboboxInputProps &+ ComboboxSingleOverrideClearProps<TOption>+): React.ReactElement;+function Combobox<TOption>(+ props: ComboboxSharedProps<TOption> &+ ComboboxInputProps &+ ComboboxSingleNonClearableProps<TOption>+): React.ReactElement;+function Combobox<TOption>(+ props: ComboboxSharedProps<TOption> &+ ComboboxInputProps &+ ComboboxSingleDefaultClearProps<TOption>+): React.ReactElement;function Combobox<TOption>(props: ComboboxProps<TOption>) {const { multiple } = props;if (multiple) return <MultipleCombobox {...props} />;@@ -897,6 +1566,10 @@ function Combobox<TOption>(props: ComboboxProps<TOption>) {export {Combobox,+ type ComboboxCreationConfig,+ type ComboboxDialogCreationConfig,+ type ComboboxDialogCreationRenderProps,+ type ComboboxInlineCreationConfig,type ComboboxMultipleProps,type ComboboxProps,type ComboboxRenderOptionState,diff --git a/frontend/src/components/v3/generic/Combobox/combobox-creation.ts b/frontend/src/components/v3/generic/Combobox/combobox-creation.tsnew file mode 100644index 0000000000..156d59e504--- /dev/null+++ b/frontend/src/components/v3/generic/Combobox/combobox-creation.ts@@ -0,0 +1,32 @@+export type ComboboxCreationContext<TOption> = {+ options: readonly TOption[];+ selectedOptions: readonly TOption[];+};++type GetComboboxCreationInputProps<TOption> = ComboboxCreationContext<TOption> & {+ inputValue: string;+ getOptionLabel: (option: TOption) => string;+ isDuplicate?: (inputValue: string, option: TOption) => boolean;+ isValid?: (inputValue: string, context: ComboboxCreationContext<TOption>) => boolean;+};++export const getComboboxCreationInput = <TOption>({+ inputValue,+ options,+ selectedOptions,+ getOptionLabel,+ isDuplicate,+ isValid+}: GetComboboxCreationInputProps<TOption>) => {+ const trimmedInput = inputValue.trim();+ if (!trimmedInput) return null;++ const context = { options, selectedOptions };+ if (isValid && !isValid(trimmedInput, context)) return null;++ const duplicate = [...options, ...selectedOptions].some((option) =>+ isDuplicate ? isDuplicate(trimmedInput, option) : getOptionLabel(option).trim() === trimmedInput+ );++ return duplicate ? null : trimmedInput;+};diff --git a/frontend/src/components/v3/generic/Combobox/index.ts b/frontend/src/components/v3/generic/Combobox/index.tsindex 59f02ff576..a9afb2eb45 100644--- a/frontend/src/components/v3/generic/Combobox/index.ts+++ b/frontend/src/components/v3/generic/Combobox/index.ts@@ -1,5 +1,9 @@export {Combobox,+ type ComboboxCreationConfig,+ type ComboboxDialogCreationConfig,+ type ComboboxDialogCreationRenderProps,+ type ComboboxInlineCreationConfig,type ComboboxMultipleProps,type ComboboxProps,type ComboboxRenderOptionState,diff --git a/frontend/src/components/v3/generic/ReactSelect/CreatableSelect.stories.tsx b/frontend/src/components/v3/generic/ReactSelect/CreatableSelect.stories.tsxindex cd834c260a..5f8a7e9d5c 100644--- a/frontend/src/components/v3/generic/ReactSelect/CreatableSelect.stories.tsx+++ b/frontend/src/components/v3/generic/ReactSelect/CreatableSelect.stories.tsx@@ -17,10 +17,9 @@ const TAG_OPTIONS: Option[] = [const slugRegex = /^[a-z][a-z0-9-]*$/;/**- * `CreatableSelect` is the v3 react-select-based dropdown that lets users pick- * from existing options *or* create new ones inline. The canonical use is a- * tag input — choose existing tags from the menu, type a new one and hit Enter- * to create it.+ * `CreatableSelect` is the deprecated react-select compatibility path for+ * existing inline-creation consumers. New and migrated code should use+ * `Combobox` with its `creation` config.** Inherits `FilterableSelect`'s state and styling, plus react-select-creatable's* extras for managing inline creation:@@ -30,9 +29,9 @@ const slugRegex = /^[a-z][a-z0-9-]*$/;* length, uniqueness). Return `false` to hide the Create suggestion.* - **`formatCreateLabel(input)`** — customize the suggestion text.*- * Reach for `CreatableSelect` over `FilterableSelect` only when the user- * legitimately needs to add new entries (tags, role names, custom claims).- * For a fixed list, `FilterableSelect` is the right primitive.+ * Keep this component only where a consumer still depends on react-select-specific+ * component overrides. Migrate those customizations to Combobox composition before+ * removing the compatibility path.*/const meta = {title: "Generic/CreatableSelect",@@ -40,7 +39,7 @@ const meta = {parameters: {layout: "centered"},- tags: ["autodocs"],+ tags: ["autodocs", "deprecated"],decorators: [(Story) => (<div className="h-52 w-96">diff --git a/frontend/src/components/v3/generic/ReactSelect/CreatableSelect.tsx b/frontend/src/components/v3/generic/ReactSelect/CreatableSelect.tsxindex f62626e037..58d8eb5bb8 100644--- a/frontend/src/components/v3/generic/ReactSelect/CreatableSelect.tsx+++ b/frontend/src/components/v3/generic/ReactSelect/CreatableSelect.tsx@@ -10,6 +10,10 @@ import {} from "./components";import { getSelectClassNames, selectClassNames, selectStyles } from "./styles";+/**+ * @deprecated Use `Combobox` with its `creation` config. Keep this compatibility+ * path for consumers that still depend on react-select-specific component overrides.+ */export const CreatableSelect = <T,>({isMulti,closeMenuOnSelect,diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAuthMethodModalContent.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAuthMethodModalContent.tsxindex 0d6c572081..bbcf800aed 100644--- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAuthMethodModalContent.tsx+++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAuthMethodModalContent.tsx@@ -411,6 +411,7 @@ export const IdentityAuthMethodModalContent = ({value={selectedAuthMethod}options={authMethodOptions}isDisabled={isSelectedAuthAlreadyConfigured}+ isClearable={false}isError={Boolean(error)}isOptionDisabled={({ isConfigured }) => isConfigured}getOptionLabel={({ label }) => label}diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/VaultKubernetesAuthImportModal.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/VaultKubernetesAuthImportModal.tsxindex fa9cd1d3f2..71a610a305 100644--- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/VaultKubernetesAuthImportModal.tsx+++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/VaultKubernetesAuthImportModal.tsx@@ -59,7 +59,7 @@ const Content = ({ onClose, appConnections, onImport }: ContentProps) => {activeConnectionId);- const handleConnectionChange = (id: string) => {+ const handleConnectionChange = (id: string | null) => {setSelectedConnectionId(id);setSelectedNamespace(null);setSelectedMountPath(null);@@ -68,7 +68,7 @@ const Content = ({ onClose, appConnections, onImport }: ContentProps) => {setShouldFetchRoles(false);};- const handleNamespaceChange = (ns: string) => {+ const handleNamespaceChange = (ns: string | null) => {setSelectedNamespace(ns);setSelectedMountPath(null);setSelectedRole(null);diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/AddSubOrgMemberModal.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/AddSubOrgMemberModal.tsxindex f7d6913c18..ab3d00fea8 100644--- a/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/AddSubOrgMemberModal.tsx+++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/AddSubOrgMemberModal.tsx@@ -159,7 +159,7 @@ export const AddSubOrgMemberModal = ({ popUp, handlePopUpToggle }: Props) => {render={({ field, fieldState: { error } }) => (<Field><FieldLabel htmlFor="add-sub-org-member-users">Emails</FieldLabel>- <Combobox+ <Combobox<{ username: string }>id="add-sub-org-member-users"multipleplaceholder="Add one or more users..."diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/OrganizationRoleField.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/OrganizationRoleField.tsxindex 293558077c..725d084c44 100644--- a/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/OrganizationRoleField.tsx+++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/OrganizationRoleField.tsx@@ -20,8 +20,8 @@ type OrganizationRoleOption = {type OrganizationRoleFieldProps<TOption extends OrganizationRoleOption> = {id: string;options: readonly TOption[];- value?: TOption;- onValueChange: (value: TOption) => void;+ value?: TOption | null;+ onValueChange: (value: TOption | null) => void;isLoading: boolean;isError: boolean;errorMessage?: ReactNode;diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/ProjectRoleSelect.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/ProjectRoleSelect.tsxindex 5c8d81ed58..4d47c892e9 100644--- a/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/ProjectRoleSelect.tsx+++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/ProjectRoleSelect.tsx@@ -65,7 +65,7 @@ export const getSingleSelectedProjectId = (selectedProjects: { id: string }[]) =type Props = {inputId?: string;value?: TProjectRoleOption | null;- onChange: (value: TProjectRoleOption) => void;+ onChange: (value: TProjectRoleOption | null) => void;isError?: boolean;selectedProjects: { id: string }[];fixedRoles?: TProjectRoleOption[];diff --git a/frontend/src/pages/organization/BillingV2Page/components/RootOrgFilter.tsx b/frontend/src/pages/organization/BillingV2Page/components/RootOrgFilter.tsxindex 86788a878e..ef34b4cf80 100644--- a/frontend/src/pages/organization/BillingV2Page/components/RootOrgFilter.tsx+++ b/frontend/src/pages/organization/BillingV2Page/components/RootOrgFilter.tsx@@ -52,6 +52,7 @@ export const RootOrgFilter = ({searchPlaceholder="Search organizations..."searchAriaLabel="Search root organizations"isLoading={isLoading}+ isClearable={false}options={options}value={selectedOrg}getOptionGroup={(option) => (option.id === ALL_ORGS_VALUE ? "" : "Organizations")}diff --git a/frontend/src/pages/pam/PamAccountsPage/components/AssignAccessModal.tsx b/frontend/src/pages/pam/PamAccountsPage/components/AssignAccessModal.tsxindex 746f8589f9..22d7fd387a 100644--- a/frontend/src/pages/pam/PamAccountsPage/components/AssignAccessModal.tsx+++ b/frontend/src/pages/pam/PamAccountsPage/components/AssignAccessModal.tsx@@ -400,6 +400,7 @@ export const AssignAccessModal = ({id="pam-assign-access-role"value={selectedRole}options={resourceRoles ?? []}+ isClearable={false}onValueChange={(opt) => setRoleSlug(opt.slug)}getOptionValue={(opt) => opt.slug}getOptionLabel={(opt) => opt.name}diff --git a/frontend/src/pages/project/RoleDetailsBySlugPage/components/VaultPolicyImportModal.tsx b/frontend/src/pages/project/RoleDetailsBySlugPage/components/VaultPolicyImportModal.tsxindex 807f37dfc3..9a1b43d379 100644--- a/frontend/src/pages/project/RoleDetailsBySlugPage/components/VaultPolicyImportModal.tsx+++ b/frontend/src/pages/project/RoleDetailsBySlugPage/components/VaultPolicyImportModal.tsx@@ -86,7 +86,7 @@ const Content = ({ onClose, appConnections }: ContentProps) => {activeConnectionId);- const handleConnectionChange = (id: string) => {+ const handleConnectionChange = (id: string | null) => {setSelectedConnectionId(id);setSelectedNamespace(null);setSelectedPolicy(null);@@ -96,7 +96,7 @@ const Content = ({ onClose, appConnections }: ContentProps) => {setShouldFetchPolicies(false);};- const handleNamespaceChange = (ns: string) => {+ const handleNamespaceChange = (ns: string | null) => {setSelectedNamespace(ns);setSelectedPolicy(null);};@@ -256,7 +256,7 @@ const Content = ({ onClose, appConnections }: ContentProps) => {value={appConnections.find((connection) => connection.id === selectedConnectionId) ?? null}- onValueChange={(connection) => handleConnectionChange(connection.id)}+ onValueChange={(connection) => handleConnectionChange(connection?.id ?? null)}options={appConnections}getOptionValue={(option) => option.id}getOptionLabel={(option) => option.name}@@ -288,7 +288,7 @@ const Content = ({ onClose, appConnections }: ContentProps) => {<Comboboxid="vault-namespace"value={namespaces?.find((namespace) => namespace.name === selectedNamespace) ?? null}- onValueChange={(namespace) => handleNamespaceChange(namespace.name)}+ onValueChange={(namespace) => handleNamespaceChange(namespace?.name ?? null)}options={namespaces ?? []}getOptionValue={(option) => option.name}getOptionLabel={(option) => (option.name === "/" ? "root" : option.name)}diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/CopySecretsSheet/CopySecretsSheet.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/CopySecretsSheet/CopySecretsSheet.tsxindex 7052e98244..7e37243503 100644--- a/frontend/src/pages/secret-manager/OverviewPage/components/CopySecretsSheet/CopySecretsSheet.tsx+++ b/frontend/src/pages/secret-manager/OverviewPage/components/CopySecretsSheet/CopySecretsSheet.tsx@@ -634,7 +634,7 @@ const CopySecretsSession = ({: undefined}onValueChange={(environment) => {- setSourceEnvironmentSlug(environment.slug);+ setSourceEnvironmentSlug(environment?.slug ?? "");setSelection(null);}}/>@@ -707,7 +707,7 @@ const CopySecretsSession = ({getOptionLabel={({ name }) => name}getOptionValue={({ slug }) => slug}onValueChange={(environment) =>- setDestinationEnvironmentSlug(environment.slug)+ setDestinationEnvironmentSlug(environment?.slug ?? "")}/></Field>diff --git a/frontend/src/pages/secret-manager/SecretApprovalsPage/components/AccessApprovalRequest/components/RequestAccessForm.tsx b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/AccessApprovalRequest/components/RequestAccessForm.tsxindex 61086fba47..7b690f1a64 100644--- a/frontend/src/pages/secret-manager/SecretApprovalsPage/components/AccessApprovalRequest/components/RequestAccessForm.tsx+++ b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/AccessApprovalRequest/components/RequestAccessForm.tsx@@ -627,8 +627,8 @@ export const RequestAccessForm = ({currentProject?.environments?.find(({ slug }) => slug === field.value) ?? null}onValueChange={(environmentOption) => {- if (environmentOption.slug === field.value) return;- field.onChange(environmentOption.slug);+ if (environmentOption?.slug === field.value) return;+ field.onChange(environmentOption?.slug ?? "");// clear alongside the env change so both land in one renderform.setValue("secretPath", "", {shouldValidate: form.formState.isSubmitteddiff --git a/frontend/src/pages/secret-manager/SecretApprovalsPage/components/ApprovalPolicyList/components/AccessPolicyModal.tsx b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/ApprovalPolicyList/components/AccessPolicyModal.tsxindex b0cc90e5ff..c6a03f3d33 100644--- a/frontend/src/pages/secret-manager/SecretApprovalsPage/components/ApprovalPolicyList/components/AccessPolicyModal.tsx+++ b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/ApprovalPolicyList/components/AccessPolicyModal.tsx@@ -680,6 +680,7 @@ const Form = ({<FieldContent><Comboboxmodal+ isClearable={false}aria-label="Policy type"options={Object.values(PolicyType)}value={value ?? null}