Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,71 +1,112 @@
import { Switch } from "@/components/ui/switch";
import { Button, Input } from "@unkey/ui";
import { trpc } from "@/lib/trpc/client";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { EnvVarInputs } from "./components/env-var-inputs";
import { EnvVarSaveActions } from "./components/env-var-save-actions";
import { EnvVarSecretSwitch } from "./components/env-var-secret-switch";
import { type EnvVar, type EnvVarFormData, EnvVarFormSchema } from "./types";

type AddEnvVarRowProps = {
value: { key: string; value: string; isSecret: boolean };
onChange: (value: { key: string; value: string; isSecret: boolean }) => void;
onSave: () => void;
projectId: string;
getExistingEnvVar: (key: string, excludeId?: string) => EnvVar | undefined;
onCancel: () => void;
};

export function AddEnvVarRow({ value, onChange, onSave, onCancel }: AddEnvVarRowProps) {
const handleSave = () => {
if (!value.key.trim() || !value.value.trim()) {
return;
export function AddEnvVarRow({ projectId, getExistingEnvVar, onCancel }: AddEnvVarRowProps) {
const trpcUtils = trpc.useUtils();

// TODO: Add mutation when available
// const upsertMutation = trpc.deploy.project.envs.upsert.useMutation();

const {
register,
handleSubmit,
watch,
setValue,
formState: { errors, isValid, isSubmitting },
} = useForm<EnvVarFormData>({
resolver: zodResolver(
EnvVarFormSchema.superRefine((data, ctx) => {
const existing = getExistingEnvVar(data.key);
if (existing) {
ctx.addIssue({
code: "custom",
message: "Variable name already exists",
path: ["key"],
});
}
}),
),
defaultValues: {
key: "",
value: "",
type: "env",
},
});

const watchedType = watch("type");

const handleSave = async (_formData: EnvVarFormData) => {
try {
// TODO: Call tRPC upsert when available
// await upsertMutation.mutateAsync({
// projectId,
// ...formData
// });

// Mock successful save for now
await new Promise((resolve) => setTimeout(resolve, 500));

// Invalidate to refresh data
await trpcUtils.deploy.project.envs.getEnvs.invalidate({ projectId });

onCancel(); // Close the add form
} catch (error) {
console.error("Failed to add env var:", error);
}
};

const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === "Enter" && isValid && !isSubmitting) {
handleSubmit(handleSave)();
} else if (e.key === "Escape") {
onCancel();
}
onSave();
};

return (
<div className="w-full flex px-4 py-3 bg-gray-2 border-b border-gray-4 last:border-b-0">
<div className="w-fit flex gap-2 items-center">
<Input
value={value.key}
onChange={(e) => onChange({ ...value, key: e.target.value })}
placeholder="Variable name"
className="min-h-[32px] text-xs w-48"
<form onSubmit={handleSubmit(handleSave)} className="w-full flex items-center gap-2 h-12">
<EnvVarInputs
register={register}
errors={errors}
isSecret={watchedType === "secret"}
onKeyDown={handleKeyDown}
autoFocus
/>
<span className="text-gray-9 text-xs px-1">=</span>
<Input
value={value.value}
onChange={(e) => onChange({ ...value, value: e.target.value })}
placeholder="Variable value"
className="min-h-[32px] text-xs flex-1"
type={value.isSecret ? "password" : "text"}
/>
</div>
<div className="flex items-center gap-2 ml-auto">
<div className="flex items-center gap-2">
<span className="text-xs text-gray-9">Secret</span>
<Switch
className="
h-4 w-8
data-[state=checked]:bg-success-9
data-[state=checked]:ring-2
data-[state=checked]:ring-successA-5
data-[state=unchecked]:bg-gray-3
data-[state=unchecked]:ring-2
data-[state=unchecked]:ring-grayA-3
[&>span]:h-3.5 [&>span]:w-3.5
"
thumbClassName="h-[14px] w-[14px] data-[state=unchecked]:bg-grayA-9 data-[state=checked]:bg-white"
checked={value.isSecret}
onCheckedChange={(checked) => onChange({ ...value, isSecret: checked })}
<div className="flex items-center gap-2 ml-auto">
<EnvVarSecretSwitch
isSecret={watchedType === "secret"}
onCheckedChange={(checked) =>
setValue("type", checked ? "secret" : "env", {
shouldDirty: true,
shouldValidate: true,
})
}
disabled={isSubmitting}
/>
<EnvVarSaveActions
isSubmitting={isSubmitting}
save={{
disabled: !isValid || isSubmitting,
}}
cancel={{
disabled: isSubmitting,
onClick: onCancel,
}}
/>
</div>
<Button
variant="outline"
className="text-xs"
onClick={handleSave}
disabled={!value.key.trim() || !value.value.trim()}
>
Save
</Button>
<Button variant="outline" onClick={onCancel} className="text-xs">
Cancel
</Button>
</div>
</form>
</div>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
import { trpc } from "@/lib/trpc/client";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { type EnvVar, type EnvVarFormData, EnvVarFormSchema } from "../types";
import { EnvVarInputs } from "./env-var-inputs";
import { EnvVarSaveActions } from "./env-var-save-actions";
import { EnvVarSecretSwitch } from "./env-var-secret-switch";

type EnvVarFormProps = {
initialData: EnvVarFormData;
projectId: string;
getExistingEnvVar: (key: string, excludeId?: string) => EnvVar | undefined;
onSuccess: () => void;
onCancel: () => void;
excludeId?: string;
autoFocus?: boolean;
decrypted?: boolean;
className?: string;
};

export function EnvVarForm({
initialData,
projectId,
getExistingEnvVar,
onSuccess,
onCancel,
excludeId,
decrypted,
autoFocus = false,
className = "w-full flex px-4 py-3 bg-gray-2 border-b border-gray-4 last:border-b-0",
}: EnvVarFormProps) {
const trpcUtils = trpc.useUtils();

// TODO: Add mutations when available
// const upsertMutation = trpc.deploy.project.envs.upsert.useMutation();

const {
register,
handleSubmit,
watch,
setValue,
formState: { errors, isValid, isSubmitting },
} = useForm<EnvVarFormData>({
resolver: zodResolver(
EnvVarFormSchema.superRefine((data, ctx) => {
const existing = getExistingEnvVar(data.key, excludeId);
if (existing) {
ctx.addIssue({
code: "custom",
message: "Variable name already exists",
path: ["key"],
});
}
}),
),
defaultValues: initialData,
});

const watchedType = watch("type");

const handleSave = async (_formData: EnvVarFormData) => {
try {
// TODO: Call tRPC upsert when available
// await upsertMutation.mutateAsync({
// projectId,
// id: excludeId, // Will be undefined for new entries
// ...formData
// });

// Mock successful save for now
await new Promise((resolve) => setTimeout(resolve, 500));

// Invalidate to refresh data
await trpcUtils.deploy.project.envs.getEnvs.invalidate({ projectId });

onSuccess();
} catch (error) {
console.error("Failed to save env var:", error);
throw error; // Re-throw to let form handle the error state
}
};

const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === "Enter" && isValid && !isSubmitting) {
handleSubmit(handleSave)();
} else if (e.key === "Escape") {
onCancel();
}
};

return (
<div className={className}>
<form onSubmit={handleSubmit(handleSave)} className="w-full flex items-center gap-2">
<EnvVarInputs
register={register}
errors={errors}
isSecret={watchedType === "secret"}
decrypted={decrypted}
onKeyDown={handleKeyDown}
autoFocus={autoFocus}
/>
<div className="flex items-center gap-2 ml-auto">
<EnvVarSecretSwitch
isSecret={watchedType === "secret"}
onCheckedChange={(checked) =>
setValue("type", checked ? "secret" : "env", {
shouldDirty: true,
shouldValidate: true,
})
}
disabled={isSubmitting}
/>
<EnvVarSaveActions
isSubmitting={isSubmitting}
save={{
disabled: !isValid || isSubmitting,
}}
cancel={{
disabled: isSubmitting,
onClick: onCancel,
}}
/>
</div>
</form>
</div>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { cn } from "@/lib/utils";
import { Input } from "@unkey/ui";
import { forwardRef } from "react";
import type { FieldErrors, UseFormRegister } from "react-hook-form";
import type { EnvVarFormData } from "../types";

type EnvVarInputsProps = {
register: UseFormRegister<EnvVarFormData>;
errors: FieldErrors<EnvVarFormData>;
isSecret: boolean;
onKeyDown?: (e: React.KeyboardEvent) => void;
decrypted?: boolean;
autoFocus?: boolean;
};

export const EnvVarInputs = forwardRef<HTMLDivElement, EnvVarInputsProps>(
({ register, errors, isSecret, onKeyDown, autoFocus = false, decrypted }, ref) => {
return (
<div ref={ref} className="w-fit flex gap-2 items-center">
<div className="w-[108px]">
<Input
{...register("key")}
onKeyDown={onKeyDown}
placeholder="Variable name"
className={cn(
"min-h-[32px] text-xs w-[108px] font-mono",
errors.key && "border-red-6 focus:border-red-7",
)}
autoFocus={autoFocus}
autoComplete="off"
spellCheck={false}
autoCapitalize="none"
aria-invalid={Boolean(errors.key)}
/>
</div>
<span className="text-gray-9 text-xs px-1">=</span>
<Input
{...register("value")}
onKeyDown={onKeyDown}
placeholder="Variable value"
className={cn(
"min-h-[32px] text-xs flex-1 font-mono",
errors.value && "border-red-6 focus:border-red-7",
)}
type={isSecret && !decrypted ? "password" : "text"}
autoComplete={isSecret ? "new-password" : "off"}
spellCheck={false}
autoCapitalize="none"
aria-invalid={Boolean(errors.value)}
/>
</div>
);
},
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { Button } from "@unkey/ui";

export const EnvVarSaveActions = ({
save,
cancel,
isSubmitting,
}: {
isSubmitting: boolean;
save: {
disabled: boolean;
};
cancel: {
disabled: boolean;
onClick: () => void;
};
}) => {
return (
<>
<Button
type="submit"
variant="outline"
className="text-xs"
disabled={save.disabled}
loading={isSubmitting}
>
Save
</Button>
<Button
type="button"
variant="outline"
disabled={cancel.disabled}
onClick={cancel.onClick}
className="text-xs"
>
Cancel
</Button>
</>
);
};
Loading