Files
kandev/apps/web/app/office/projects/create-project-dialog.tsx
T
2026-08-26 14:13:35 +00:00

364 lines
12 KiB
TypeScript

"use client";
import { useState, useCallback } from "react";
import { toast } from "@/lib/toast/sonner";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@kandev/ui/dialog";
import { Button } from "@kandev/ui/button";
import { Input } from "@kandev/ui/input";
import { Label } from "@kandev/ui/label";
import { Textarea } from "@kandev/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@kandev/ui/select";
import { useAppStore } from "@/components/state-provider";
import { selectOfficeAgentProfiles } from "@/lib/state/slices/office/selectors";
import { useRepositories } from "@/hooks/domains/workspace/use-repositories";
import { createProject } from "@/lib/api/domains/office-api";
import type { AgentProfile } from "@/lib/state/slices/office/types";
import { ProjectRepositoryPicker } from "./project-repository-picker";
import { RepoChip } from "./repo-chip";
import { useTranslation } from "react-i18next";
const COLOR_OPTIONS = [
"#ef4444",
"#f97316",
"#eab308",
"#22c55e",
"#06b6d4",
"#3b82f6",
"#8b5cf6",
"#ec4899",
];
type CreateProjectDialogProps = {
open: boolean;
onOpenChange: (open: boolean) => void;
workspaceId: string;
};
function ColorPicker({ color, onChange }: { color: string; onChange: (c: string) => void }) {
const { t } = useTranslation();
return (
<div className="space-y-2">
<Label>{t("office:color")}</Label>
<div className="flex gap-2">
{COLOR_OPTIONS.map((c) => (
<button
key={c}
type="button"
className={`h-6 w-6 rounded-sm cursor-pointer transition-all ${
color === c ? "ring-2 ring-offset-2 ring-primary" : ""
}`}
style={{ backgroundColor: c }}
onClick={() => onChange(c)}
/>
))}
</div>
</div>
);
}
function ReposField({
workspaceId,
repos,
onAddRepo,
onRemoveRepo,
}: {
workspaceId: string;
repos: string[];
onAddRepo: (repo: string) => void;
onRemoveRepo: (r: string) => void;
}) {
const { t } = useTranslation();
const { repositories } = useRepositories(workspaceId);
return (
<div className="space-y-2">
<Label>{t("office:repositories")}</Label>
<p className="text-xs text-muted-foreground">{t("office:gitUrlsOrLocalPathsWhereShort")}</p>
<div className="flex flex-wrap items-center gap-2" data-testid="project-repo-chips">
{repos.map((repo) => (
<RepoChip
key={repo}
value={repo}
workspaceRepos={repositories}
onRemove={() => onRemoveRepo(repo)}
/>
))}
<ProjectRepositoryPicker
workspaceId={workspaceId}
repositories={repositories}
exclude={repos}
onSelect={onAddRepo}
/>
</div>
</div>
);
}
// `labelKey`, not `label` — module scope freezes a `t()` at the boot locale.
// The `id`s are the persisted executor-type values. The workspace's own executor
// metadata wins when loaded, and those labels are workspace data.
const FALLBACK_EXECUTOR_TYPES = [
{ id: "local_pc", labelKey: "office:localStandalone" },
{ id: "local_docker", labelKey: "office:localDocker" },
{ id: "sprites", labelKey: "office:spritesRemoteSandbox" },
{ id: "remote_docker", labelKey: "office:remoteDocker" },
];
function ExecutorField({
executorType,
dockerImage,
executorTypes,
onExecutorTypeChange,
onDockerImageChange,
}: {
executorType: string;
dockerImage: string;
executorTypes: Array<{ id: string; label: string }>;
onExecutorTypeChange: (v: string) => void;
onDockerImageChange: (v: string) => void;
}) {
const { t } = useTranslation();
return (
<div className="space-y-2">
<Label>{t("office:executorType")}</Label>
<p className="text-xs text-muted-foreground">{t("office:howAgentSessionsRunInheritUses")}</p>
<Select value={executorType} onValueChange={onExecutorTypeChange}>
<SelectTrigger className="cursor-pointer">
<SelectValue placeholder={t("office:inheritFromWorkspace")} />
</SelectTrigger>
<SelectContent>
<SelectItem value="inherit" className="cursor-pointer">
{t("office:inheritFromWorkspace")}
</SelectItem>
{executorTypes.map((et) => (
<SelectItem key={et.id} value={et.id} className="cursor-pointer">
{et.label}
</SelectItem>
))}
</SelectContent>
</Select>
{(executorType === "local_docker" || executorType === "remote_docker") && (
<Input
placeholder={t("office:dockerImageWithExample")}
value={dockerImage}
onChange={(e) => onDockerImageChange(e.target.value)}
className="mt-2"
/>
)}
</div>
);
}
type ProjectFormState = {
name: string;
description: string;
color: string;
repos: string[];
leadAgentId: string;
executorType: string;
dockerImage: string;
};
const INITIAL_PROJECT_STATE: ProjectFormState = {
name: "",
description: "",
color: COLOR_OPTIONS[5],
repos: [],
leadAgentId: "",
executorType: "",
dockerImage: "",
};
function useProjectForm(workspaceId: string, onClose: () => void) {
const { t } = useTranslation();
const addProject = useAppStore((s) => s.addProject);
const [form, setForm] = useState<ProjectFormState>(INITIAL_PROJECT_STATE);
const [submitting, setSubmitting] = useState(false);
const update = useCallback(
(patch: Partial<ProjectFormState>) => setForm((prev) => ({ ...prev, ...patch })),
[],
);
const handleAddRepo = useCallback(
(repo: string) => {
const trimmed = repo.trim();
if (trimmed && !form.repos.includes(trimmed)) {
update({ repos: [...form.repos, trimmed] });
}
},
[form.repos, update],
);
const handleRemoveRepo = useCallback(
(repo: string) => update({ repos: form.repos.filter((r) => r !== repo) }),
[form.repos, update],
);
const handleCreate = useCallback(async () => {
if (!form.name.trim()) return;
setSubmitting(true);
try {
const result = await createProject(workspaceId, {
name: form.name.trim(),
description: form.description,
color: form.color,
repositories: form.repos,
leadAgentProfileId: form.leadAgentId || undefined,
executorConfig: form.executorType
? { type: form.executorType, image: form.dockerImage || undefined }
: undefined,
});
if (result) addProject(workspaceId, result);
onClose();
setForm(INITIAL_PROJECT_STATE);
toast.success(t("office:projectCreated"));
} catch (err) {
toast.error(err instanceof Error ? err.message : t("office:failedToCreateProject"));
} finally {
setSubmitting(false);
}
}, [form, workspaceId, addProject, onClose]);
return { form, update, submitting, handleAddRepo, handleRemoveRepo, handleCreate };
}
function ProjectFormBody({
form,
agents,
executorTypes,
workspaceId,
onUpdate,
onAddRepo,
onRemoveRepo,
}: {
form: ProjectFormState;
agents: AgentProfile[];
executorTypes: Array<{ id: string; label: string }>;
workspaceId: string;
onUpdate: (patch: Partial<ProjectFormState>) => void;
onAddRepo: (repo: string) => void;
onRemoveRepo: (r: string) => void;
}) {
const { t } = useTranslation();
return (
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="project-name">{t("office:name")}</Label>
<Input
id="project-name"
placeholder={t("office:projectName")}
value={form.name}
onChange={(e) => onUpdate({ name: e.target.value })}
autoFocus
/>
</div>
<div className="space-y-2">
<Label htmlFor="project-desc">{t("office:description")}</Label>
<Textarea
id="project-desc"
placeholder={t("office:projectDescription")}
value={form.description}
onChange={(e) => onUpdate({ description: e.target.value })}
className="min-h-[80px]"
/>
</div>
<ColorPicker color={form.color} onChange={(c) => onUpdate({ color: c })} />
<ReposField
workspaceId={workspaceId}
repos={form.repos}
onAddRepo={onAddRepo}
onRemoveRepo={onRemoveRepo}
/>
<div className="space-y-2">
<Label>{t("office:leadAgent")}</Label>
<p className="text-xs text-muted-foreground">
{t("office:theAgentResponsibleForManagingThis")}
</p>
<Select value={form.leadAgentId} onValueChange={(v) => onUpdate({ leadAgentId: v })}>
<SelectTrigger className="cursor-pointer">
<SelectValue placeholder={t("office:selectAgentOptional")} />
</SelectTrigger>
<SelectContent>
<SelectItem value="none" className="cursor-pointer">
{t("office:none")}
</SelectItem>
{agents.map((a) => (
<SelectItem key={a.id} value={a.id} className="cursor-pointer">
{a.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<ExecutorField
executorType={form.executorType}
dockerImage={form.dockerImage}
executorTypes={executorTypes}
onExecutorTypeChange={(v) => onUpdate({ executorType: v })}
onDockerImageChange={(v) => onUpdate({ dockerImage: v })}
/>
</div>
);
}
export function CreateProjectDialog({ open, onOpenChange, workspaceId }: CreateProjectDialogProps) {
const { t } = useTranslation();
const agents = useAppStore(selectOfficeAgentProfiles);
const meta = useAppStore((s) => s.office.meta);
const executorTypes =
meta?.executorTypes.map((e) => ({ id: e.id, label: e.label })) ??
FALLBACK_EXECUTOR_TYPES.map((e) => ({ id: e.id, label: t(e.labelKey) }));
const { form, update, submitting, handleAddRepo, handleRemoveRepo, handleCreate } =
useProjectForm(workspaceId, () => onOpenChange(false));
// ProjectRepositoryPicker renders its popover inline. Paint clipping keeps
// that wide popover from creating a horizontal scroll range on the dialog.
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent
data-testid="create-project-dialog"
data-layout="contained"
className="max-h-[calc(100dvh-2rem)] max-w-[calc(100vw-2rem)] grid-rows-[auto_minmax(0,1fr)_auto] overflow-clip sm:max-w-lg"
>
<DialogHeader>
<DialogTitle>{t("office:newProject")}</DialogTitle>
</DialogHeader>
<div
data-testid="create-project-dialog-body"
className="min-h-0 min-w-0 overflow-x-hidden overflow-y-auto overscroll-contain"
>
<ProjectFormBody
form={form}
agents={agents}
executorTypes={executorTypes}
workspaceId={workspaceId}
onUpdate={update}
onAddRepo={handleAddRepo}
onRemoveRepo={handleRemoveRepo}
/>
</div>
<div
data-testid="create-project-dialog-footer"
className="flex flex-col justify-end gap-2 border-t border-border pt-4 sm:flex-row"
>
<Button
variant="ghost"
onClick={() => onOpenChange(false)}
className="min-h-11 w-full cursor-pointer sm:min-h-9 sm:w-auto"
>
{t("common:cancel")}
</Button>
<Button
onClick={handleCreate}
disabled={!form.name.trim() || submitting}
className="min-h-11 w-full cursor-pointer sm:min-h-9 sm:w-auto"
>
{submitting ? t("office:creating") : t("office:createProject")}
</Button>
</div>
</DialogContent>
</Dialog>
);
}