Files
UHD_Media_Tool/apps/web/app/components/settings/path-mappings.tsx
T
rootandClaude Opus 5.5 52402864d6 style(copy): punctuation rules and site-wide fix with a CI check (QA U11)
- glossary: 10 punctuation rules (full-width in Chinese, CJK/Latin spacing,
  full-width parens around Chinese, single ellipsis, 「」 quotes, period rules)
- scripts/check-copy-punctuation.mjs: checks string literals, templates and JSX
  text (not comments, types, keys, match/compare strings); --fix, --strict,
  --by-file; wired into deno task ci as check:copy in warn mode
- --fix applied to web, server and contracts; files other lanes were editing
  (subscriptions, sites, browser, agent, auth/account, inventory) left for them
- tests updated for the changed messages

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-09-28 20:09:29 +08:00

230 lines
8.5 KiB
TypeScript

import { type PathMapping, PathMappingCreate } from "@umt/contracts";
import { LoaderCircle, Plus, ShieldCheck, Trash2 } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";
import { libraryRoots, pathMappings } from "~/api/instances.ts";
import { ConfirmDialog } from "~/components/console/confirm-dialog.tsx";
import { DetailSection } from "~/components/console/detail-sheet.tsx";
import { zodFieldErrors } from "~/components/console/form-field.tsx";
import { StatusBadge } from "~/components/console/status-badge.tsx";
import { Button } from "~/components/ui/button.tsx";
import { errorMessage } from "~/lib/api.ts";
import { healthLabel } from "~/lib/labels.ts";
import { FieldControl, type FormValues, num, str } from "./resource-section.tsx";
// 实例抽屉里的路径映射:只列本实例的映射,可新增、校验、删除。
// 对方看到的路径前缀 → 本进程可访问的前缀;前缀越长越优先,同长按优先级。
const EMPTY: FormValues = { remotePrefix: "", localPrefix: "", libraryRootId: "none", priority: "0" };
export function PathMappingsPanel({
viewKind,
instanceId,
}: {
viewKind: "downloader" | "media_server";
instanceId: string;
}) {
const list = pathMappings.useList();
const create = pathMappings.useCreate();
const remove = pathMappings.useRemove();
const verify = pathMappings.useVerify();
const roots = libraryRoots.useList();
const [adding, setAdding] = useState(false);
const [v, setV] = useState<FormValues>(EMPTY);
const [errors, setErrors] = useState<Record<string, string>>({});
const [deleting, setDeleting] = useState<PathMapping | null>(null);
const rows = (list.data?.items ?? []).filter((m) =>
viewKind === "downloader" ? m.downloaderInstanceId === instanceId : m.mediaServerInstanceId === instanceId,
);
const rootOpts = [
{ value: "none", label: "不关联" },
...(roots.data?.items ?? []).map((d) => ({ value: d.id, label: d.name })),
];
const rootName = (id: string | null) => roots.data?.items.find((r) => r.id === id)?.name;
const submit = async (e: React.FormEvent) => {
e.preventDefault();
const root = str(v.libraryRootId);
const parsed = PathMappingCreate.safeParse({
viewKind,
downloaderInstanceId: viewKind === "downloader" ? instanceId : null,
mediaServerInstanceId: viewKind === "media_server" ? instanceId : null,
remotePrefix: str(v.remotePrefix),
localPrefix: str(v.localPrefix),
libraryRootId: root && root !== "none" ? root : null,
priority: num(v.priority) ?? 0,
enabled: true,
});
if (!parsed.success) {
const fe = zodFieldErrors(parsed.error.issues);
if (fe.localPrefix) fe.localPrefix = "填以 / 开头的绝对路径";
if (fe.remotePrefix) fe.remotePrefix = "必填";
setErrors(fe);
return;
}
setErrors({});
try {
await create.mutateAsync(parsed.data as never);
toast.success("路径映射已添加");
setV(EMPTY);
setAdding(false);
} catch (err) {
toast.error(errorMessage(err, "添加失败"));
}
};
return (
<DetailSection
title="路径映射"
actions={
adding ? null : (
<Button variant="outline" size="xs" onClick={() => setAdding(true)}>
<Plus />
添加映射
</Button>
)
}
>
<p className="mb-2 text-meta text-muted-foreground">
把{viewKind === "downloader" ? "下载器" : "媒体服务器"}
看到的路径换成本服务能访问的路径。前缀越长越优先,同长比优先级。
</p>
{list.isPending ? (
<p className="text-caption text-muted-foreground">加载中…</p>
) : rows.length === 0 ? (
<p className="text-caption text-muted-foreground">还没有映射,路径两边一致时不用加。</p>
) : (
<ul className="divide-y divide-border/60 rounded-lg border border-border/60">
{rows.map((m) => {
const h = healthLabel(m.verifyStatus);
return (
<li key={m.id} className="flex items-center gap-2 px-3 py-2">
<div className="min-w-0 flex-1 font-mono text-meta">
<p className="truncate">{m.remotePrefix}</p>
<p className="truncate text-muted-foreground">→ {m.localPrefix}</p>
{rootName(m.libraryRootId) ? (
<p className="font-sans text-muted-foreground">库根:{rootName(m.libraryRootId)}</p>
) : null}
</div>
<StatusBadge tone={h.tone}>{h.label}</StatusBadge>
<Button
variant="ghost"
size="icon-sm"
aria-label="校验映射"
title="校验"
disabled={verify.isPending}
onClick={async () => {
try {
const r = await verify.mutateAsync(m.id);
if (r.verifyStatus === "ok") toast.success("映射可用");
else toast.error(String(r.verifyDetail?.message ?? "本地前缀不可访问"));
} catch (err) {
toast.error(errorMessage(err, "校验失败"));
}
}}
>
<ShieldCheck />
</Button>
<Button
variant="ghost"
size="icon-sm"
aria-label="删除映射"
className="hover:text-destructive"
onClick={() => setDeleting(m)}
>
<Trash2 />
</Button>
</li>
);
})}
</ul>
)}
{adding ? (
<form
onSubmit={submit}
noValidate
className="mt-3 grid gap-x-3 gap-y-1 rounded-lg border border-border/60 p-3 sm:grid-cols-2"
>
<FieldControl
spec={{
name: "remotePrefix",
label: "对方路径前缀",
kind: "text",
required: true,
placeholder: "/downloads",
wide: true,
}}
value={v.remotePrefix}
error={errors.remotePrefix}
onChange={(x) => setV((s) => ({ ...s, remotePrefix: x }))}
disabled={create.isPending}
/>
<FieldControl
spec={{
name: "localPrefix",
label: "本地路径前缀",
kind: "text",
required: true,
placeholder: "/mnt/cache/downloads",
wide: true,
}}
value={v.localPrefix}
error={errors.localPrefix}
onChange={(x) => setV((s) => ({ ...s, localPrefix: x }))}
disabled={create.isPending}
/>
<FieldControl
spec={{ name: "libraryRootId", label: "关联库根", kind: "select", options: rootOpts }}
value={v.libraryRootId}
onChange={(x) => setV((s) => ({ ...s, libraryRootId: x }))}
disabled={create.isPending}
/>
<FieldControl
spec={{ name: "priority", label: "优先级", kind: "number", hint: "数字大的优先" }}
value={v.priority}
error={errors.priority}
onChange={(x) => setV((s) => ({ ...s, priority: x }))}
disabled={create.isPending}
/>
<div className="flex gap-2 sm:col-span-2">
<Button type="submit" size="sm" disabled={create.isPending}>
{create.isPending ? <LoaderCircle className="animate-spin" /> : null}
添加
</Button>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => {
setAdding(false);
setErrors({});
}}
>
取消
</Button>
</div>
</form>
) : null}
<ConfirmDialog
open={!!deleting}
onOpenChange={(o) => !o && setDeleting(null)}
title="删除路径映射?"
description="依赖这条映射的路径换算会失效,磁盘文件不动。"
confirmLabel="删除映射"
destructive
onConfirm={async () => {
if (!deleting) return;
try {
await remove.mutateAsync(deleting.id);
toast.success("路径映射已删除");
} catch (err) {
toast.error(errorMessage(err, "删除失败"));
throw err;
}
}}
/>
</DetailSection>
);
}