import { useEffect, useRef, useState } from "react"; import { ChevronDown, KeyRound, MoreHorizontal, ShieldAlert, Type as TypeIcon, UserRound, X, } from "lucide-react"; import type { CompanySecret, UserSecretDefinition } from "@paperclipai/shared"; import { cn } from "@/lib/utils"; import { ANALYTICS_NO_CAPTURE_CLASS } from "@/lib/analytics/privacy"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; import { Popover, PopoverAnchor, PopoverContent } from "@/components/ui/popover"; import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; import { SecretPicker } from "./SecretPicker"; import { CreateSecretPopover, ConvertToSecretPopover } from "./CreateSecretPopover"; import { isSensitiveEnv } from "./sensitive"; import { computeRowHealth, computeUserSecretRowHealth, planSourceSwitch, secretNameFromKey, type EnvRow, type NameIssue, type RowSource, } from "./model"; const nameInputClass = "w-full rounded-md border border-border px-2.5 py-1.5 bg-transparent outline-none text-sm font-mono placeholder:text-muted-foreground/40 focus-visible:ring-2 focus-visible:ring-ring/40"; const valueTextInputClass = "min-w-0 flex-1 bg-transparent px-2 py-1.5 text-sm font-mono outline-none placeholder:text-muted-foreground/40"; type SecretPopoverState = { mode: "create" | "store"; name: string; value: string } | null; export interface EnvironmentVariableDirtyFields { name: boolean; value: boolean; } export interface EnvironmentVariableRowProps { row: EnvRow; isLast: boolean; secrets: readonly CompanySecret[]; userSecretDefinitions?: readonly UserSecretDefinition[]; recentlyUsedSecrets?: readonly CompanySecret[]; disabled?: boolean; nameIssue: NameIssue | null; showNameIssue: boolean; dirtyFields: EnvironmentVariableDirtyFields; onPatch: (patch: Partial) => void; onRemove: () => void; onNameBlur: () => void; /** Handle a multi-line dotenv paste into the (empty) name field. Returns true if consumed. */ onNamePaste: (text: string) => boolean; /** Enter pressed in the value of the last row — append a fresh row and focus it. */ onEnterInValueLast: () => void; onCreateSecret: (name: string, value: string) => Promise; onToast: (message: string) => void; /** Parent-driven focus request for this row (append flow, source switch). */ focusRequest: "name" | "value" | null; onFocusConsumed: () => void; } export function EnvironmentVariableRow({ row, isLast, secrets, userSecretDefinitions, recentlyUsedSecrets, disabled, nameIssue, showNameIssue, dirtyFields, onPatch, onRemove, onNameBlur, onNamePaste, onEnterInValueLast, onCreateSecret, onToast, focusRequest, onFocusConsumed, }: EnvironmentVariableRowProps) { const nameInputRef = useRef(null); const valueInputRef = useRef(null); const valueCellRef = useRef(null); const [secretPopover, setSecretPopover] = useState(null); const [versionOpen, setVersionOpen] = useState(false); const [undoPrev, setUndoPrev] = useState(null); const health = computeRowHealth(row, secrets) ?? computeUserSecretRowHealth(row, userSecretDefinitions); const boundSecret = row.source === "secret" ? secrets.find((s) => s.id === row.secretId) ?? null : null; const userSecretsEnabled = (userSecretDefinitions?.length ?? 0) > 0; const sensitive = row.source === "text" && !row.sensitiveDismissed && isSensitiveEnv(row.name, row.textValue); // Consume parent focus requests (append / source-switch flows). useEffect(() => { if (!focusRequest) return; if (focusRequest === "name") { nameInputRef.current?.focus(); } else if (row.source === "text") { valueInputRef.current?.focus(); } else if (row.source === "secret") { // Focusing the combobox trigger opens SearchableSelect (non-pointer focus). valueCellRef.current?.querySelector("[role=combobox]")?.focus(); } else { valueCellRef.current?.querySelector("select,input")?.focus(); } onFocusConsumed(); }, [focusRequest, onFocusConsumed, row.source]); // Auto-expire the 5s "Undo" affordance after a Secret→Text switch (§6.3). useEffect(() => { if (!undoPrev) return; const handle = window.setTimeout(() => setUndoPrev(null), 5000); return () => window.clearTimeout(handle); }, [undoPrev]); function switchSource(next: RowSource) { if (next === "user_secret") { if (row.source === "user_secret") return; onPatch({ source: "user_secret", secretId: "", version: "latest" }); window.setTimeout(() => valueCellRef.current?.querySelector("select,input")?.focus(), 0); return; } const plan = planSourceSwitch(row, next); switch (plan.kind) { case "noop": return; case "open-store": { // Defer to the next macrotask so the source DropdownMenu fully closes // (and Radix returns focus to its trigger) before we open the anchored // store-as-secret popover. Opening synchronously inside the menu-item's // onSelect lets the menu's focus-return land as a `focusOutside` / // `interactOutside` on the just-opened popover, which Radix would // immediately dismiss — the same nested open-while-closing race as the // ⋯ path and the picker's + Create item (PAP-12476/12477/12478). const { name, value } = plan; window.setTimeout(() => setSecretPopover({ mode: "store", name, value }), 0); return; } case "to-secret": onPatch({ source: "secret", userSecretKey: "", required: true }); // Auto-open the picker. window.setTimeout(() => { valueCellRef.current?.querySelector("[role=combobox]")?.focus(); }, 0); return; case "to-text": if (plan.undoFrom) setUndoPrev(plan.undoFrom); onPatch({ source: "text", secretId: "", userSecretKey: "", required: true, version: "latest" }); window.setTimeout(() => valueInputRef.current?.focus(), 0); return; } } async function submitSecretPopover(name: string, value: string) { const created = await onCreateSecret(name, value); onPatch({ source: "secret", secretId: created.id, userSecretKey: "", required: true, version: "latest", textValue: "", }); onToast(`Secret ${created.name} created`); setSecretPopover(null); } function openStoreAsSecret() { const name = secretNameFromKey(row.name) || "secret"; const { textValue } = row; window.setTimeout(() => setSecretPopover({ mode: "store", name, value: textValue }), 0); } const sourceLabel = row.source === "text" ? "Text value" : row.source === "secret" ? "Organization secret reference" : "User secret reference"; const nameErrorId = `${row.id}-name-error`; const healthId = `${row.id}-health`; const isDirty = dirtyFields.name || dirtyFields.value; const versions = boundSecret ? Math.max(0, boundSecret.latestVersion) : 0; const versionTagLabel = row.version === "latest" ? "latest" : `v${row.version}`; const versionPinned = row.version !== "latest"; return (
{/* Name cell — mobile col 1 / desktop col 1 */}
onPatch({ name: event.target.value })} onBlur={onNameBlur} onPaste={(event) => { if (row.name) return; const text = event.clipboardData.getData("text"); if (onNamePaste(text)) event.preventDefault(); }} onKeyDown={(event) => { if (event.key === "Enter") { event.preventDefault(); if (row.source === "text") valueInputRef.current?.focus(); else valueCellRef.current?.querySelector("[role=combobox],select,input")?.focus(); } }} />
{/* Value cell — mobile full-width line 2 / desktop col 2 */}
{ if (!open) setSecretPopover(null); }} >
{/* Source switch (inside the field) */} {sourceLabel} switchSource("text")}> Text value Store the value inline as plain text. switchSource("secret")}> Organization secret Resolve a stored organization secret at run start. switchSource("user_secret")}> User secret Resolve the responsible user's own value at run start. {row.source === "text" ? ( <> onPatch({ textValue: event.target.value })} onKeyDown={(event) => { if (event.key === "Enter" && isLast) { event.preventDefault(); onEnterInValueLast(); } }} /> {sensitive ? (
) : null} ) : row.source === "secret" ? (
onPatch({ secretId: id, version: "latest" })} onCreateNew={(query) => setSecretPopover({ mode: "create", name: secretNameFromKey(query) || query.trim(), value: "" }) } triggerClassName={cn( "rounded-none border-0 bg-transparent shadow-none focus-visible:ring-0", boundSecret && boundSecret.status === "active" && "pr-24 has-[>svg]:!pr-24", )} /> {boundSecret && boundSecret.status === "active" ? ( {Array.from({ length: versions }, (_, idx) => versions - idx) .filter((v) => v > 0) .map((v) => ( ))} ) : null}
) : (
{userSecretsEnabled ? ( ) : ( onPatch({ userSecretKey: event.target.value })} /> )}
)}
{ // Keep the create/store popover open when the dismissal // originates from inside the value cell — i.e. the picker's // combobox trigger or the source-switch dropdown trigger, both // anchored here. Those controls close by returning focus to // themselves; because the value cell is this popover's *anchor* // (outside its content), Radix reads that focus-return as a // `focusOutside` and would dismiss the just-opened popover. // // The picker's close animation can delay its focus-return past // any single macrotask, so the `setTimeout(0)` open-defers // (SearchableSelect / switchSource) cannot reliably win the race // (PAP-12492). Guarding the interaction here makes the create / // store popover survive that focus-return deterministically, // independent of timing. Dismissals from anywhere *outside* the // value cell (real outside clicks, Escape) are untouched. const target = event.detail.originalEvent.target as Node | null; if (target && valueCellRef.current?.contains(target)) { event.preventDefault(); } }} > {secretPopover?.mode === "store" ? ( s.name)} onCancel={() => setSecretPopover(null)} onSubmit={submitSecretPopover} /> ) : secretPopover?.mode === "create" ? ( s.name)} onCancel={() => setSecretPopover(null)} onSubmit={submitSecretPopover} /> ) : null}
{/* Inline secret-health message */} {health ? (

{health.message}

) : null} {/* 5s undo after Secret→Text */} {undoPrev ? (

Reverted to text —{" "}

) : null}
{showNameIssue && nameIssue ? (

{nameIssue.message}

) : null} {/* Actions cell — mobile col 2 line 1 / desktop col 3 */}
{row.source === "text" && !sensitive && (row.name.trim() || row.textValue) ? ( { // Defer to the next macrotask so this menu fully closes (and // Radix returns focus to the ⋯ trigger, which sits outside the // row's Popover) before we open the anchored store-as-secret // popover. Opening synchronously lets the menu's focus-return // land as a `focusOutside` on the just-opened popover, which // Radix would immediately dismiss — the same nested open-while- // closing race as the picker's + Create item (PAP-12476/12477). window.setTimeout(openStoreAsSecret, 0); }} > Store as secret… ) : null}
); }