Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

improvement(frontend): migrate multi-app connection pickers to Combobox (#8859)

Andrew Huang5b9d39aa3ecd
diff --git a/frontend/src/components/app-connections/index.ts b/frontend/src/components/app-connections/index.ts
index 7ced7c9079..8e8ecf1294 100644
--- a/frontend/src/components/app-connections/index.ts
+++ b/frontend/src/components/app-connections/index.ts
@@ -1 +1,2 @@
export * from "./AppConnectionOption";
+export * from "./useAppConnectionCreation";
diff --git a/frontend/src/components/app-connections/useAppConnectionCreation.tsx b/frontend/src/components/app-connections/useAppConnectionCreation.tsx
new file mode 100644
index 0000000000..da125a9e6a
--- /dev/null
+++ b/frontend/src/components/app-connections/useAppConnectionCreation.tsx
@@ -0,0 +1,184 @@
+import { ReactNode, useEffect, useRef, useState } from "react";
+import { ChevronRightIcon } from "lucide-react";
+
+import {
+ Button,
+ ComboboxDialogCreationConfig,
+ DialogFooter,
+ DiscardChangesAlertDialog,
+ Item,
+ ItemActions,
+ ItemContent,
+ ItemDescription,
+ ItemGroup,
+ ItemMedia,
+ ItemTitle
+} from "@app/components/v3";
+import { ProviderIcon } from "@app/components/v3/platform/ProviderIcon";
+import { ProjectPermissionSub, useProject, useProjectPermission } from "@app/context";
+import { ProjectPermissionAppConnectionActions } from "@app/context/ProjectPermissionContext/types";
+import { APP_CONNECTION_MAP } from "@app/helpers/appConnections";
+import { useDiscardChangesGuard } from "@app/hooks";
+import { TAppConnection } from "@app/hooks/api/appConnections";
+import { AppConnection } from "@app/hooks/api/appConnections/enums";
+import { AppConnectionForm } from "@app/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm";
+
+type Props = {
+ apps: AppConnection[];
+ onCreated: (connection: TAppConnection) => void;
+ onOpen?: VoidFunction;
+ onClose?: VoidFunction;
+};
+
+const CreationLifecycle = ({
+ onOpen,
+ onClose,
+ children
+}: {
+ onOpen: VoidFunction;
+ onClose: VoidFunction;
+ children: ReactNode;
+}) => {
+ const callbacksRef = useRef({ onOpen, onClose });
+ callbacksRef.current = { onOpen, onClose };
+
+ useEffect(() => {
+ callbacksRef.current.onOpen();
+ return () => callbacksRef.current.onClose();
+ }, []);
+
+ return children;
+};
+
+export const useAppConnectionCreation = <TOption,>({
+ apps,
+ onCreated,
+ onOpen,
+ onClose
+}: Props): ComboboxDialogCreationConfig<TOption> | undefined => {
+ const { currentProject } = useProject();
+ const { permission } = useProjectPermission();
+ const [selectedApp, setSelectedApp] = useState<AppConnection | null>(null);
+ const [isDirty, setIsDirty] = useState(false);
+ const [isPending, setIsPending] = useState(false);
+ const cancelRef = useRef<VoidFunction>(() => {});
+ const attemptRef = useRef(0);
+
+ const { confirmDiscard, isDiscardDialogOpen, requestDiscard, setIsDiscardDialogOpen } =
+ useDiscardChangesGuard({
+ isDirty,
+ onDiscard: () => {
+ attemptRef.current += 1;
+ setIsDirty(false);
+ cancelRef.current();
+ }
+ });
+
+ const requestCancel = (cancel: VoidFunction) => {
+ cancelRef.current = cancel;
+ requestDiscard();
+ };
+
+ if (
+ !apps.length ||
+ !permission.can(
+ ProjectPermissionAppConnectionActions.Create,
+ ProjectPermissionSub.AppConnections
+ )
+ )
+ return undefined;
+
+ const app = apps.length === 1 ? apps[0] : selectedApp;
+ const label =
+ apps.length === 1
+ ? `Create ${APP_CONNECTION_MAP[apps[0]].name} Connection`
+ : "Create Connection";
+ const attempt = attemptRef.current;
+
+ return {
+ mode: "dialog",
+ title: app ? `Create ${APP_CONNECTION_MAP[app].name} Connection` : label,
+ description: app
+ ? "The new connection is selected once it is created."
+ : "Choose the type of connection to create.",
+ emptyLabel: label,
+ formatLabel: () => label,
+ isPending,
+ onDismiss: requestCancel,
+ renderForm: ({ complete, cancel }) => (
+ <CreationLifecycle
+ onOpen={() => onOpen?.()}
+ onClose={() => {
+ setSelectedApp(null);
+ setIsDirty(false);
+ onClose?.();
+ }}
+ >
+ {app ? (
+ <AppConnectionForm
+ key={app}
+ app={app}
+ layout="dialog"
+ projectId={currentProject.id}
+ projectType={currentProject.type}
+ onDirtyChange={setIsDirty}
+ onPendingChange={setIsPending}
+ onComplete={(connection) => {
+ if (attempt !== attemptRef.current) return;
+ setIsDirty(false);
+ setIsDiscardDialogOpen(false);
+ onCreated(connection);
+ complete();
+ }}
+ onCancel={() => requestCancel(cancel)}
+ />
+ ) : (
+ <>
+ <ItemGroup>
+ {apps.map((option) => {
+ const { name, image, description } = APP_CONNECTION_MAP[option];
+ return (
+ <Item
+ key={option}
+ asChild
+ variant="outline"
+ className="cursor-pointer text-left hover:bg-foreground/5"
+ >
+ <button type="button" onClick={() => setSelectedApp(option)}>
+ <ItemMedia>
+ <ProviderIcon
+ icon={image}
+ alt={`${name} logo`}
+ className="size-6 object-contain"
+ />
+ </ItemMedia>
+ <ItemContent>
+ <ItemTitle>{name}</ItemTitle>
+ {description && <ItemDescription>{description}</ItemDescription>}
+ </ItemContent>
+ <ItemActions>
+ <ChevronRightIcon className="size-4 text-muted" />
+ </ItemActions>
+ </button>
+ </Item>
+ );
+ })}
+ </ItemGroup>
+ <DialogFooter>
+ <Button variant="ghost" onClick={() => requestCancel(cancel)}>
+ Cancel
+ </Button>
+ </DialogFooter>
+ </>
+ )}
+ <DiscardChangesAlertDialog
+ open={isDiscardDialogOpen}
+ onOpenChange={setIsDiscardDialogOpen}
+ onDiscard={confirmDiscard}
+ title="Discard Connection Setup?"
+ description="Your progress configuring this connection will be lost."
+ />
+ </CreationLifecycle>
+ )
+ };
+};
diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncConnectionField.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncConnectionField.tsx
index 62442db86d..5d46d85112 100644
--- a/frontend/src/components/pki-syncs/forms/PkiSyncConnectionField.tsx
+++ b/frontend/src/components/pki-syncs/forms/PkiSyncConnectionField.tsx
@@ -1,16 +1,17 @@
-import { useState } from "react";
import { Controller, useFormContext } from "react-hook-form";
-import { SingleValue } from "react-select";
import { useRouterState } from "@tanstack/react-router";
import { Info } from "lucide-react";
-import { AppConnectionOption } from "@app/components/app-connections";
import {
+ AppConnectionOptionContent,
+ useAppConnectionCreation
+} from "@app/components/app-connections";
+import {
+ Combobox,
Field,
FieldDescription,
FieldError,
FieldLabel,
- FilterableSelect,
Tooltip,
TooltipContent,
TooltipTrigger
@@ -19,10 +20,11 @@ import { ProjectPermissionSub, useProject, useProjectPermission } from "@app/con
import { ProjectPermissionAppConnectionActions } from "@app/context/ProjectPermissionContext/types";
import { APP_CONNECTION_MAP } from "@app/helpers/appConnections";
import { getPkiSyncConnectionApps, PKI_SYNC_CONNECTION_MAP } from "@app/helpers/pkiSyncs";
-import { usePopUp } from "@app/hooks";
-import { useListAvailableAppConnectionsForApps } from "@app/hooks/api/appConnections";
+import {
+ TAvailableAppConnection,
+ useListAvailableAppConnectionsForApps
+} from "@app/hooks/api/appConnections";
import { AppConnection } from "@app/hooks/api/appConnections/enums";
-import { AddAppConnectionModal } from "@app/pages/organization/AppConnections/AppConnectionsPage/components";
import { TPkiSyncForm } from "./schemas/pki-sync-schema";
@@ -30,6 +32,9 @@ type Props = {
onChange?: VoidFunction;
};
+type TConnectionOption = Partial<TAvailableAppConnection> &
+ Pick<TAvailableAppConnection, "id" | "name"> & { app?: AppConnection };
+
const LDAP_TARGET_FIELDS = [
"host",
"port",
@@ -42,9 +47,6 @@ export const PkiSyncConnectionField = ({ onChange: callback }: Props) => {
const { permission } = useProjectPermission();
const { control, watch, setValue } = useFormContext<TPkiSyncForm>();
- const { popUp, handlePopUpToggle, handlePopUpOpen } = usePopUp(["addConnection"] as const);
- const [appToCreate, setAppToCreate] = useState<AppConnection | null>(null);
-
const destination = watch("destination");
const app = PKI_SYNC_CONNECTION_MAP[destination];
const apps = getPkiSyncConnectionApps(destination);
@@ -88,92 +90,70 @@ export const PkiSyncConnectionField = ({ onChange: callback }: Props) => {
const appNames = apps.map((accepted) => APP_CONNECTION_MAP[accepted].name).join(" or ");
+ const creation = useAppConnectionCreation<TConnectionOption>({
+ apps,
+ onCreated: (connection) => {
+ setValue("connection", connection, { shouldDirty: true });
+ clearLdapTargetFields(connection.app);
+ if (callback) callback();
+ },
+ onOpen: () =>
+ localStorage.setItem(
+ "pkiSyncFormData",
+ JSON.stringify({ ...watch(), returnUrl: getPkiSyncReturnUrl() })
+ ),
+ onClose: () => localStorage.removeItem("pkiSyncFormData")
+ });
+
return (
- <>
- <Controller
- control={control}
- name="connection"
- render={({ field: { value, onChange }, fieldState: { error } }) => (
- <Field className="mb-4">
- <FieldLabel>
- {connectionLabel}
- <Tooltip>
- <TooltipTrigger asChild>
- <Info />
- </TooltipTrigger>
- <TooltipContent className="max-w-sm">
- App Connections can be created from the Project Settings page.
- </TooltipContent>
- </Tooltip>
- </FieldLabel>
- <FilterableSelect
- value={value}
- onChange={(newValue) => {
- const selected = newValue as SingleValue<{
- id: string;
- name: string;
- app?: AppConnection;
- }>;
- if (selected?.id?.startsWith("_create")) {
- setAppToCreate(selected.app ?? app);
- handlePopUpOpen("addConnection");
- onChange(null);
- const formData = { ...watch(), returnUrl: getPkiSyncReturnUrl() };
- localStorage.setItem("pkiSyncFormData", JSON.stringify(formData));
- if (callback) callback();
- return;
- }
-
- onChange(newValue);
- clearLdapTargetFields((newValue as SingleValue<{ app?: AppConnection }>)?.app);
- if (callback) callback();
- }}
- isLoading={isPending}
- options={[
- ...(canCreateConnection
- ? apps.map((creatable) => ({
- id: `_create:${creatable}`,
- name: `Create ${APP_CONNECTION_MAP[creatable].name} Connection`,
- app: creatable
- }))
- : []),
- ...availableConnections
- ]}
- groupBy={apps.length > 1 ? "app" : null}
- getGroupHeaderLabel={(groupApp: AppConnection) => APP_CONNECTION_MAP[groupApp].name}
- placeholder="Select connection..."
- getOptionLabel={(option) => option.name}
- getOptionValue={(option) => option.id}
- components={{ Option: AppConnectionOption }}
- isError={Boolean(error)}
- />
- {!isPending && !availableConnections.length && !canCreateConnection ? (
- <FieldDescription className="text-warning">
- You do not have access to any {appNames} Connections. Contact an admin to create
- one.
- </FieldDescription>
- ) : (
- <FieldError errors={[error]} />
- )}
- </Field>
- )}
- />
- <AddAppConnectionModal
- isOpen={popUp.addConnection.isOpen}
- onOpenChange={(isOpen) => {
- localStorage.removeItem("pkiSyncFormData");
- handlePopUpToggle("addConnection", isOpen);
- }}
- projectType={currentProject.type}
- projectId={currentProject.id}
- app={appToCreate ?? app}
- onComplete={(connection) => {
- if (connection) {
- setValue("connection", connection);
- clearLdapTargetFields(connection.app);
- }
- }}
- />
- </>
+ <Controller
+ control={control}
+ name="connection"
+ render={({ field: { value, onChange, ref }, fieldState: { error } }) => (
+ <Field className="mb-4">
+ <FieldLabel htmlFor="pki-sync-connection">
+ {connectionLabel}
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Info />
+ </TooltipTrigger>
+ <TooltipContent className="max-w-sm">
+ App Connections can be created from the Project Settings page.
+ </TooltipContent>
+ </Tooltip>
+ </FieldLabel>
+ <Combobox<TConnectionOption>
+ id="pki-sync-connection"
+ ref={ref}
+ value={availableConnections.find((option) => option.id === value?.id) ?? value ?? null}
+ onValueChange={(newValue) => {
+ onChange(newValue);
+ clearLdapTargetFields(newValue.app);
+ if (callback) callback();
+ }}
+ isClearable={false}
+ isLoading={isPending}
+ options={availableConnections}
+ getOptionGroup={
+ apps.length > 1 ? (option) => APP_CONNECTION_MAP[option.app ?? app].name : undefined
+ }
+ getOptionKeywords={(option) => [option.id]}
+ placeholder="Select connection..."
+ getOptionLabel={(option) => option.name}
+ getOptionValue={(option) => option.id}
+ renderOption={(option) => <AppConnectionOptionContent data={option} />}
+ creation={creation}
+ isError={Boolean(error)}
+ />
+ {!isPending && !availableConnections.length && !canCreateConnection ? (
+ <FieldDescription className="text-warning">
+ You do not have access to any {appNames} Connections. Contact an admin to create one.
+ </FieldDescription>
+ ) : (
+ <FieldError errors={[error]} />
+ )}
+ </Field>
+ )}
+ />
);
};
diff --git a/frontend/src/components/secret-rotations-v2/forms/SecretRotationV2ConnectionField.tsx b/frontend/src/components/secret-rotations-v2/forms/SecretRotationV2ConnectionField.tsx
index 7de3ba50a2..f6aa162d2f 100644
--- a/frontend/src/components/secret-rotations-v2/forms/SecretRotationV2ConnectionField.tsx
+++ b/frontend/src/components/secret-rotations-v2/forms/SecretRotationV2ConnectionField.tsx
@@ -1,18 +1,14 @@
-import { useMemo, useState } from "react";
+import { useMemo } from "react";
import { Controller, useFormContext } from "react-hook-form";
-import { SingleValue } from "react-select";
import { subject } from "@casl/ability";
import { InfoIcon } from "lucide-react";
-import { AppConnectionOption } from "@app/components/app-connections";
-import { FieldLabelWithTooltip } from "@app/components/secret-rotations-v2/forms/shared";
import {
- Alert,
- AlertDescription,
- Field,
- FieldFeedback,
- FilterableSelect
-} from "@app/components/v3";
+ AppConnectionOptionContent,
+ useAppConnectionCreation
+} from "@app/components/app-connections";
+import { FieldLabelWithTooltip } from "@app/components/secret-rotations-v2/forms/shared";
+import { Alert, AlertDescription, Combobox, Field, FieldFeedback } from "@app/components/v3";
import { ProjectPermissionSub, useProject, useProjectPermission } from "@app/context";
import {
ProjectPermissionAppConnectionActions,
@@ -23,10 +19,11 @@ import {
getSecretRotationConnectionApps,
SECRET_ROTATION_CONNECTION_MAP
} from "@app/helpers/secretRotationsV2";
-import { usePopUp } from "@app/hooks";
-import { useListAvailableAppConnectionsForApps } from "@app/hooks/api/appConnections";
+import {
+ TAvailableAppConnection,
+ useListAvailableAppConnectionsForApps
+} from "@app/hooks/api/appConnections";
import { AppConnection } from "@app/hooks/api/appConnections/enums";
-import { AddAppConnectionModal } from "@app/pages/organization/AppConnections/AppConnectionsPage/components";
import { TSecretRotationV2Form } from "./schemas";
@@ -35,13 +32,13 @@ type Props = {
isUpdate: boolean;
};
+type TConnectionOption = Partial<TAvailableAppConnection> &
+ Pick<TAvailableAppConnection, "id" | "name"> & { app?: AppConnection };
+
export const SecretRotationV2ConnectionField = ({ onChange: callback, isUpdate }: Props) => {
const { permission } = useProjectPermission();
const { control, watch, setValue } = useFormContext<TSecretRotationV2Form>();
- const { popUp, handlePopUpToggle, handlePopUpOpen } = usePopUp(["addConnection"] as const);
- const [appToCreate, setAppToCreate] = useState<AppConnection | null>(null);
-
const rotationType = watch("type");
const environment = watch("environment");
const secretPath = watch("secretPath");
@@ -80,10 +77,26 @@ export const SecretRotationV2ConnectionField = ({ onChange: callback, isUpdate }
const appNames = apps.map((accepted) => APP_CONNECTION_MAP[accepted].name).join(" or ");
+ const creation = useAppConnectionCreation<TConnectionOption>({
+ apps,
+ onCreated: (connection) => {
+ setValue("connection", connection, { shouldValidate: true, shouldDirty: true });
+ if (callback) callback();
+ },
+ onOpen: () =>
+ localStorage.setItem(
+ "secretRotationFormData",
+ JSON.stringify(watch(), (key, serializedValue) =>
+ key === "temporaryParameters" ? undefined : serializedValue
+ )
+ ),
+ onClose: () => localStorage.removeItem("secretRotationFormData")
+ });
+
return (
<>
<Controller
- render={({ field: { value, onChange, onBlur }, fieldState: { error } }) => (
+ render={({ field: { value, onChange, onBlur, ref }, fieldState: { error } }) => (
<Field data-invalid={Boolean(error)}>
<FieldLabelWithTooltip
htmlFor="secret-rotation-connection"
@@ -91,53 +104,28 @@ export const SecretRotationV2ConnectionField = ({ onChange: callback, isUpdate }
>
{connectionLabel}
</FieldLabelWithTooltip>
- <FilterableSelect
- inputId="secret-rotation-connection"
- value={value ?? null}
+ <Combobox<TConnectionOption>
+ id="secret-rotation-connection"
+ ref={ref}
+ value={allowedConnections.find((option) => option.id === value?.id) ?? value ?? null}
onBlur={onBlur}
- onChange={(newValue) => {
- const selected = newValue as SingleValue<{
- id: string;
- name: string;
- app?: AppConnection;
- }>;
- if (selected?.id?.startsWith("_create")) {
- setAppToCreate(selected.app ?? app);
- handlePopUpOpen("addConnection");
- localStorage.setItem(
- "secretRotationFormData",
- JSON.stringify(watch(), (key, serializedValue) =>
- key === "temporaryParameters" ? undefined : serializedValue
- )
- );
- if (callback) callback();
- return;
- }
-
+ onValueChange={(newValue) => {
onChange(newValue);
if (callback) callback();
}}
+ isClearable={false}
isLoading={isPending}
- options={[
- ...(canCreateConnection
- ? apps.map((creatable) => ({
- id: `_create:${creatable}`,
- name:
- apps.length > 1
- ? `Create ${APP_CONNECTION_MAP[creatable].name} Connection`
- : "Create Connection",
- app: creatable
- }))
- : []),
- ...allowedConnections
- ]}
- groupBy={apps.length > 1 ? "app" : null}
- getGroupHeaderLabel={(groupApp: AppConnection) => APP_CONNECTION_MAP[groupApp].name}
+ options={allowedConnections}
+ getOptionGroup={
+ apps.length > 1 ? (option) => APP_CONNECTION_MAP[option.app ?? app].name : undefined
+ }
+ getOptionKeywords={(option) => [option.id]}
isDisabled={isUpdate}
placeholder="Select connection..."
getOptionLabel={(option) => option.name}
getOptionValue={(option) => option.id}
- components={{ Option: AppConnectionOption }}
+ renderOption={(option) => <AppConnectionOptionContent data={option} />}
+ creation={creation}
isError={Boolean(error)}
aria-describedby="secret-rotation-connection-feedback"
/>
@@ -176,21 +164,6 @@ export const SecretRotationV2ConnectionField = ({ onChange: callback, isUpdate }
</AlertDescription>
</Alert>
)}
- <AddAppConnectionModal
- isOpen={popUp.addConnection.isOpen}
- onOpenChange={(isOpen) => {
- localStorage.removeItem("secretRotationFormData");
- handlePopUpToggle("addConnection", isOpen);
- }}
- projectType={currentProject.type}
- projectId={currentProject.id}
- app={appToCreate ?? app}
- onComplete={(connection) => {
- if (connection) {
- setValue("connection", connection, { shouldValidate: true, shouldDirty: true });
- }
- }}
- />
</>
);
};