"use client"; import { useMemo, useState } from "react"; import { zodResolver } from "@hookform/resolvers/zod"; import { useForm } from "react-hook-form"; import { Info } from "lucide-react"; import { z } from "zod"; import { Button } from "@/components/ui/button"; import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form"; import { Input } from "@/components/ui/input"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { Textarea } from "@/components/ui/textarea"; import type { ConnectInstancePayload, ImportInstancePayload, } from "@/types/instance"; import { stripBucketPrefix } from "@/lib/normalize-oss-endpoint"; import { connectInstanceBaseSchema, editInstanceFormSchema, withCredentialModeRules, } from "@/schemas/instance"; import { useLocaleRevalidation } from "@/hooks/use-locale-revalidation"; import { useI18n } from "@/i18n/i18n-context"; import type { TranslateFn } from "@/i18n/i18n-context"; // Localized name-field overrides shared by connect/edit. The pattern and the // reserved-"default" rule stay identical to the canonical schema; only the // error messages are swapped for i18n. Field structure and length limits are // inherited from the base schema so this form cannot drift from the server. function localizedNameField(t: TranslateFn) { return z .string() .trim() .regex(/^[a-z0-9-]{1,32}$/, t("instance.validation.namePattern")) .refine((v) => v !== "default", t("instance.validation.nameReserved")); } function buildConnectFormSchema(t: TranslateFn) { return withCredentialModeRules( connectInstanceBaseSchema.extend({ name: localizedNameField(t), // Form-side URL-shape overrides (the base only enforces non-empty). otsEndpoint: z .string() .trim() .url(t("instance.validation.otsEndpointUrl")), otsInstanceName: z .string() .trim() .min( 1, t("instance.validation.required", { label: t("instance.validation.labelOtsInstanceName"), }), ) .max(128), ossEndpoint: z .string() .trim() .url(t("instance.validation.ossEndpointUrl")) .optional() .or(z.literal("")), }), ); } function buildEditFormSchema(t: TranslateFn) { return editInstanceFormSchema .innerType() .extend({ name: localizedNameField(t), otsEndpoint: z .string() .trim() .min( 1, t("instance.validation.required", { label: t("instance.validation.labelOtsEndpoint"), }), ) .max(256), otsInstanceName: z .string() .trim() .min( 1, t("instance.validation.required", { label: t("instance.validation.labelOtsInstanceName"), }), ) .max(128), }) .refine( (v) => { const hasId = Boolean(v.accessKeyId && v.accessKeyId.length > 0); const hasSecret = Boolean( v.accessKeySecret && v.accessKeySecret.length > 0, ); return hasId === hasSecret; }, { message: t("instance.validation.akSkPairUpdate"), path: ["accessKeySecret"], }, ); } function buildTokenFormSchema(t: TranslateFn) { return z.object({ token: z .string() .trim() .min(10, t("instance.validation.tokenTooShort")) .max(4096), }); } function buildRegionOptions(t: TranslateFn) { return [ { value: "cn-beijing", label: t("instance.regions.cn-beijing") }, { value: "cn-hangzhou", label: t("instance.regions.cn-hangzhou") }, { value: "cn-shanghai", label: t("instance.regions.cn-shanghai") }, { value: "cn-shenzhen", label: t("instance.regions.cn-shenzhen") }, { value: "__custom__", label: t("instance.regions.custom") }, ] as const; } export interface ConnectInstanceFormProps { mode: "create" | "edit"; defaultValues?: Partial; /** * Edit-mode hint: masked AccessKey ID surfaced as the input placeholder. * The form never prefills the actual field with the masked value because * submitting it would overwrite the live credential with stars on the * server. Ignored in create mode. */ accessKeyIdPlaceholder?: string; /** * Edit-mode hint: masked AccessKey Secret surfaced as the input * placeholder so users can see "something is set" without exposing it. */ accessKeySecretPlaceholder?: string; /** * Edit-mode hint: masked API Key surfaced as the input placeholder. */ apiKeyPlaceholder?: string; onSubmit: ( values: ConnectInstancePayload | ImportInstancePayload, ) => Promise; busy?: boolean; lockName?: boolean; submitLabel?: string; } type Tab = "manual" | "token"; export function ConnectInstanceForm({ mode, defaultValues, accessKeyIdPlaceholder, accessKeySecretPlaceholder, apiKeyPlaceholder, onSubmit, busy, lockName, submitLabel, }: ConnectInstanceFormProps) { const { t } = useI18n(); const [tab, setTab] = useState("manual"); const isEdit = mode === "edit"; const regionOptions = useMemo(() => buildRegionOptions(t), [t]); const initialRegion = defaultValues?.region ?? "cn-hangzhou"; const initialRegionIsPreset = useMemo( () => regionOptions.some((opt) => opt.value === initialRegion), [initialRegion, regionOptions], ); const [regionMode, setRegionMode] = useState( initialRegionIsPreset ? initialRegion : "__custom__", ); // The two modes need different validation: // - create: every field required (connectFormSchema). // - edit: AK/SK optional but pair-locked, and every other endpoint // field still validated (editInstanceFormSchema). Submitting // with both blank means "keep the existing credential". // The resolver typing differs between the two schemas because of the // `.refine` overload on the edit variant; the cast below keeps the // FormValues shape (ConnectInstancePayload) intact at the call sites. const resolver = useMemo( () => zodResolver( // eslint-disable-next-line @typescript-eslint/no-explicit-any (isEdit ? buildEditFormSchema(t) : buildConnectFormSchema(t)) as any, // eslint-disable-next-line @typescript-eslint/no-explicit-any ) as any, [isEdit, t], ); const manualForm = useForm({ resolver, defaultValues: { name: defaultValues?.name ?? "", // Never seed AK/SK in edit mode: the dialog only has access to // masked values (e.g. "LTAI****t2j2"), and prefilling them would // round-trip the stars back to the server on save and brick the // instance. The masked string is shown as a placeholder instead so // users still get the "something is set" affordance. accessKeyId: isEdit ? "" : (defaultValues?.accessKeyId ?? ""), accessKeySecret: isEdit ? "" : (defaultValues?.accessKeySecret ?? ""), // Same masked-placeholder treatment as AK/SK in edit mode. apiKey: isEdit ? "" : (defaultValues?.apiKey ?? ""), otsEndpoint: defaultValues?.otsEndpoint ?? "", otsInstanceName: defaultValues?.otsInstanceName ?? "", ossEndpoint: defaultValues?.ossEndpoint ?? "", ossBucketName: defaultValues?.ossBucketName ?? "", region: initialRegion, }, }); const tokenResolver = useMemo( () => zodResolver(buildTokenFormSchema(t)), [t], ); const tokenForm = useForm<{ token: string }>({ resolver: tokenResolver, defaultValues: { token: "" }, }); // Resolvers above rebuild from `t`, but react-hook-form keeps each error's // message string frozen at validation time; re-run validation on already // errored fields so their text follows the active locale. useLocaleRevalidation(manualForm); useLocaleRevalidation(tokenForm); async function handleManualSubmit(values: ConnectInstancePayload) { let ossEndpoint = values.ossEndpoint?.trim() || undefined; const ossBucketName = values.ossBucketName?.trim() || undefined; if (ossEndpoint && ossBucketName) { ossEndpoint = stripBucketPrefix(ossEndpoint, ossBucketName); } const normalized: ConnectInstancePayload = { ...values, ossEndpoint, ossBucketName, }; await onSubmit(normalized); } async function handleTokenSubmit(values: { token: string }) { const payload: ImportInstancePayload = { token: values.token.trim() }; await onSubmit(payload); } const showTokenTab = mode === "create"; return ( setTab(v as Tab)} className="w-full" > {showTokenTab && ( {t("instance.form.tabManual")} {t("instance.form.tabToken")} )}
( {t("instance.form.nameLabel")} {t("instance.form.nameDesc")} )} /> ( {t("instance.form.regionLabel")} {regionMode === "__custom__" ? (
) : ( )}
)} />
( {t("instance.form.accessKeyIdLabel")} {isEdit && ( {t("instance.form.akSkPairHint")} )} )} /> ( {t("instance.form.accessKeySecretLabel")} )} />
( {t("instance.form.apiKeyLabel")} {t("instance.form.apiKeyDesc")} )} />
( {t("instance.form.otsEndpointLabel")} )} /> ( {t("instance.form.otsInstanceNameLabel")} )} />
{t("instance.form.ossInfoHint")}
( {t("instance.form.ossEndpointLabel")} )} /> ( {t("instance.form.ossBucketLabel")} )} />
{showTokenTab && (
( {t("instance.form.tokenLabel")}