Feat: 新增 AI 翻译选项,可指定需要翻译的语种,以及使用已有翻译版本作为原文

This commit is contained in:
奇趣保罗 2025-11-06 11:45:23 +08:00
parent 9df11bbddf
commit b71de1f5c9
7 changed files with 379 additions and 27 deletions

View File

@ -14,6 +14,7 @@
"@radix-ui/react-checkbox": "^1.3.3",
"@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-dropdown-menu": "^2.1.16",
"@radix-ui/react-separator": "^1.1.8",
"@radix-ui/react-slot": "^1.2.3",
"@tailwindcss/vite": "^4.1.16",
"class-variance-authority": "^0.7.1",

View File

@ -17,6 +17,9 @@ importers:
'@radix-ui/react-dropdown-menu':
specifier: ^2.1.16
version: 2.1.16(@types/react-dom@19.2.2(@types/react@19.2.2))(@types/react@19.2.2)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)
'@radix-ui/react-separator':
specifier: ^1.1.8
version: 1.1.8(@types/react-dom@19.2.2(@types/react@19.2.2))(@types/react@19.2.2)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)
'@radix-ui/react-slot':
specifier: ^1.2.3
version: 1.2.3(@types/react@19.2.2)(react@19.2.0)
@ -642,6 +645,19 @@ packages:
'@types/react-dom':
optional: true
'@radix-ui/react-primitive@2.1.4':
resolution: {integrity: sha512-9hQc4+GNVtJAIEPEqlYqW5RiYdrr8ea5XQ0ZOnD6fgru+83kqT15mq2OCcbe8KnjRZl5vF3ks69AKz3kh1jrhg==}
peerDependencies:
'@types/react': '*'
'@types/react-dom': '*'
react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
peerDependenciesMeta:
'@types/react':
optional: true
'@types/react-dom':
optional: true
'@radix-ui/react-roving-focus@1.1.11':
resolution: {integrity: sha512-7A6S9jSgm/S+7MdtNDSb+IU859vQqJ/QAtcYQcfFC6W8RS4IxIZDldLR0xqCFZ6DCyrQLjLPsxtTNch5jVA4lA==}
peerDependencies:
@ -655,6 +671,19 @@ packages:
'@types/react-dom':
optional: true
'@radix-ui/react-separator@1.1.8':
resolution: {integrity: sha512-sDvqVY4itsKwwSMEe0jtKgfTh+72Sy3gPmQpjqcQneqQ4PFmr/1I0YA+2/puilhggCe2gJcx5EBAYFkWkdpa5g==}
peerDependencies:
'@types/react': '*'
'@types/react-dom': '*'
react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
peerDependenciesMeta:
'@types/react':
optional: true
'@types/react-dom':
optional: true
'@radix-ui/react-slot@1.2.3':
resolution: {integrity: sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A==}
peerDependencies:
@ -664,6 +693,15 @@ packages:
'@types/react':
optional: true
'@radix-ui/react-slot@1.2.4':
resolution: {integrity: sha512-Jl+bCv8HxKnlTLVrcDE8zTMJ09R9/ukw4qBs/oZClOfoQk/cOTbDn+NceXfV7j09YPVQUryJPHurafcSg6EVKA==}
peerDependencies:
'@types/react': '*'
react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
peerDependenciesMeta:
'@types/react':
optional: true
'@radix-ui/react-use-callback-ref@1.1.1':
resolution: {integrity: sha512-FkBMwD+qbGQeMu1cOHnuGB6x4yzPjho8ap5WtbEJ26umhgqVXbhekKUQO+hZEL1vU92a3wHwdp0HAcqAUF5iDg==}
peerDependencies:
@ -2303,6 +2341,15 @@ snapshots:
'@types/react': 19.2.2
'@types/react-dom': 19.2.2(@types/react@19.2.2)
'@radix-ui/react-primitive@2.1.4(@types/react-dom@19.2.2(@types/react@19.2.2))(@types/react@19.2.2)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)':
dependencies:
'@radix-ui/react-slot': 1.2.4(@types/react@19.2.2)(react@19.2.0)
react: 19.2.0
react-dom: 19.2.0(react@19.2.0)
optionalDependencies:
'@types/react': 19.2.2
'@types/react-dom': 19.2.2(@types/react@19.2.2)
'@radix-ui/react-roving-focus@1.1.11(@types/react-dom@19.2.2(@types/react@19.2.2))(@types/react@19.2.2)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)':
dependencies:
'@radix-ui/primitive': 1.1.3
@ -2320,6 +2367,15 @@ snapshots:
'@types/react': 19.2.2
'@types/react-dom': 19.2.2(@types/react@19.2.2)
'@radix-ui/react-separator@1.1.8(@types/react-dom@19.2.2(@types/react@19.2.2))(@types/react@19.2.2)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)':
dependencies:
'@radix-ui/react-primitive': 2.1.4(@types/react-dom@19.2.2(@types/react@19.2.2))(@types/react@19.2.2)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)
react: 19.2.0
react-dom: 19.2.0(react@19.2.0)
optionalDependencies:
'@types/react': 19.2.2
'@types/react-dom': 19.2.2(@types/react@19.2.2)
'@radix-ui/react-slot@1.2.3(@types/react@19.2.2)(react@19.2.0)':
dependencies:
'@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.2)(react@19.2.0)
@ -2327,6 +2383,13 @@ snapshots:
optionalDependencies:
'@types/react': 19.2.2
'@radix-ui/react-slot@1.2.4(@types/react@19.2.2)(react@19.2.0)':
dependencies:
'@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.2)(react@19.2.0)
react: 19.2.0
optionalDependencies:
'@types/react': 19.2.2
'@radix-ui/react-use-callback-ref@1.1.1(@types/react@19.2.2)(react@19.2.0)':
dependencies:
react: 19.2.0

View File

@ -1,6 +1,14 @@
import { memo, useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Checkbox } from "@/components/ui/checkbox";
import {
DropdownMenu,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
} from "@/components/ui/dropdown-menu";
import {
Dialog,
DialogContent,
@ -9,6 +17,7 @@ import {
DialogTitle,
} from "@/components/ui/dialog";
import { requestTranslations } from "@/lib/ai";
import { ButtonGroup } from "../ui/button-group";
type Props = {
open: boolean;
@ -16,13 +25,21 @@ type Props = {
languages: string[];
paths: string[];
prompt: string | undefined;
onConfirm: (result: Record<string, Record<string, string>>) => Promise<void> | void;
initialSelectedLanguages?: string[];
getExistingByPath?: (path: string) => Record<string, string>;
onConfirm: (
result: Record<string, Record<string, string>>,
options: { overwrite: boolean; selectedLanguages: string[] }
) => Promise<void> | void;
};
function AiTranslateModalImpl({ open, onOpenChange, languages, paths, prompt, onConfirm }: Props) {
function AiTranslateModalImpl({ open, onOpenChange, languages, paths, prompt, initialSelectedLanguages, getExistingByPath, onConfirm }: Props) {
const [inputsByKey, setInputsByKey] = useState<Record<string, string>>({});
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [selectedLangs, setSelectedLangs] = useState<string[]>([]);
const [overwrite, setOverwrite] = useState(false);
const [existingCache, setExistingCache] = useState<Record<string, { lang: string; text: string }[]>>({});
const MAX_ITEMS = 50;
const overLimit = paths.length > MAX_ITEMS;
@ -31,10 +48,28 @@ function AiTranslateModalImpl({ open, onOpenChange, languages, paths, prompt, on
const init: Record<string, string> = {};
for (const p of paths) init[p] = inputsByKey[p] ?? "";
setInputsByKey(init);
// 初始化默认勾选语言
const initSelected = (initialSelectedLanguages && initialSelectedLanguages.length > 0)
? initialSelectedLanguages
: languages;
setSelectedLangs(initSelected);
setOverwrite(false);
setExistingCache({});
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open, paths.join("|")]);
function loadExistingForPath(path: string) {
if (existingCache[path]) return;
const map = getExistingByPath?.(path) ?? {};
const arr = Object.entries(map)
.map(([lang, text]) => ({ lang, text }))
.filter((it) => typeof it.text === "string" && it.text.trim() !== "");
setExistingCache((old) => ({ ...old, [path]: arr }));
}
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (overLimit) {
@ -50,11 +85,15 @@ function AiTranslateModalImpl({ open, onOpenChange, languages, paths, prompt, on
setError("当前项目暂无目标语言");
return;
}
if (selectedLangs.length === 0) {
setError("请选择目标语言");
return;
}
setLoading(true);
setError(null);
try {
const result = await requestTranslations({ items, languages, prompt });
await onConfirm(result);
const result = await requestTranslations({ items, languages: selectedLangs, prompt });
await onConfirm(result, { overwrite, selectedLanguages: selectedLangs });
setInputsByKey({});
onOpenChange(false);
} catch (e) {
@ -78,27 +117,114 @@ function AiTranslateModalImpl({ open, onOpenChange, languages, paths, prompt, on
<DialogHeader>
<DialogTitle>{`AI 翻译 — 已选 ${paths.length}`}</DialogTitle>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-3">
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-4 max-h-[50vh] overflow-auto pr-1">
{paths.map((p) => (
<div key={p} className="flex flex-col gap-2">
<div className="truncate font-mono text-xs text-muted-foreground">{p}</div>
<div className="truncate font-mono text-xs text-muted-foreground">
{p}
</div>
<ButtonGroup className="w-full">
<Input
className="grow"
value={inputsByKey[p] ?? ""}
onChange={(e) => setInputsByKey((old) => ({ ...old, [p]: e.target.value }))}
onChange={(e) =>
setInputsByKey((old) => ({ ...old, [p]: e.target.value }))
}
placeholder="请输入原文本"
aria-label={`原文 ${p}`}
/>
<DropdownMenu
onOpenChange={(open) => {
if (open) loadExistingForPath(p);
}}
>
<DropdownMenuTrigger asChild>
<Button
type="button"
variant="outline"
aria-label="使用已有翻译"
>
使
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent
align="end"
className="max-w-96 whitespace-normal wrap-break-word"
>
{(existingCache[p]?.length ?? 0) === 0 ? (
<DropdownMenuItem disabled></DropdownMenuItem>
) : (
(existingCache[p] || []).map((opt) => (
<>
<DropdownMenuLabel>
{opt.lang}
</DropdownMenuLabel>
<DropdownMenuItem
key={`${p}:${opt.lang}`}
onClick={() =>
setInputsByKey((old) => ({
...old,
[p]: opt.text,
}))
}
title={opt.text}
>
<span className="truncate block">{opt.text}</span>
</DropdownMenuItem>
</>
))
)}
</DropdownMenuContent>
</DropdownMenu>
</ButtonGroup>
</div>
))}
</div>
<div className="space-y-2">
<div className="text-xs text-muted-foreground">
{languages.join(", ") || "无"}
</div>
<div className="flex flex-wrap gap-3">
{languages.map((lang) => {
const checked = selectedLangs.includes(lang);
return (
<label
key={lang}
className="inline-flex items-center gap-2 select-none"
>
<Checkbox
checked={checked}
onCheckedChange={(v) => {
setSelectedLangs((old) => {
const set = new Set(old);
if (v) set.add(lang);
else set.delete(lang);
return Array.from(set);
});
}}
/>
<span className="text-sm">{lang}</span>
</label>
);
})}
</div>
</div>
<label className="inline-flex items-center gap-2 select-none">
<Checkbox
checked={overwrite}
onCheckedChange={(v) => setOverwrite(!!v)}
/>
<span className="text-sm"></span>
</label>
{(error || overLimit) && (
<div className="text-sm text-red-600" role="alert">{error}</div>
<div className="text-sm text-red-600" role="alert">
{error}
</div>
)}
<DialogFooter>
<Button
type="button"

View File

@ -0,0 +1,83 @@
import { Slot } from "@radix-ui/react-slot";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
import { Separator } from "@/components/ui/separator";
const buttonGroupVariants = cva(
"flex w-fit items-stretch [&>*]:focus-visible:z-10 [&>*]:focus-visible:relative [&>[data-slot=select-trigger]:not([class*='w-'])]:w-fit [&>input]:flex-1 has-[select[aria-hidden=true]:last-child]:[&>[data-slot=select-trigger]:last-of-type]:rounded-r-md has-[>[data-slot=button-group]]:gap-2",
{
variants: {
orientation: {
horizontal:
"[&>*:not(:first-child)]:rounded-l-none [&>*:not(:first-child)]:border-l-0 [&>*:not(:last-child)]:rounded-r-none",
vertical:
"flex-col [&>*:not(:first-child)]:rounded-t-none [&>*:not(:first-child)]:border-t-0 [&>*:not(:last-child)]:rounded-b-none",
},
},
defaultVariants: {
orientation: "horizontal",
},
}
);
function ButtonGroup({
className,
orientation,
...props
}: React.ComponentProps<"div"> & VariantProps<typeof buttonGroupVariants>) {
return (
<div
role="group"
data-slot="button-group"
data-orientation={orientation}
className={cn(buttonGroupVariants({ orientation }), className)}
{...props}
/>
);
}
function ButtonGroupText({
className,
asChild = false,
...props
}: React.ComponentProps<"div"> & {
asChild?: boolean;
}) {
const Comp = asChild ? Slot : "div";
return (
<Comp
className={cn(
"bg-muted flex items-center gap-2 rounded-md border px-4 text-sm font-medium shadow-xs [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
/>
);
}
function ButtonGroupSeparator({
className,
orientation = "vertical",
...props
}: React.ComponentProps<typeof Separator>) {
return (
<Separator
data-slot="button-group-separator"
orientation={orientation}
className={cn(
"bg-input relative !m-0 self-stretch data-[orientation=vertical]:h-auto",
className
)}
{...props}
/>
);
}
export {
ButtonGroup,
ButtonGroupSeparator,
ButtonGroupText,
buttonGroupVariants,
};

View File

@ -153,7 +153,7 @@ function DropdownMenuLabel({
data-slot="dropdown-menu-label"
data-inset={inset}
className={cn(
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8 opacity-50",
className
)}
{...props}

View File

@ -0,0 +1,26 @@
import * as React from "react"
import * as SeparatorPrimitive from "@radix-ui/react-separator"
import { cn } from "@/lib/utils"
function Separator({
className,
orientation = "horizontal",
decorative = true,
...props
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
return (
<SeparatorPrimitive.Root
data-slot="separator"
decorative={decorative}
orientation={orientation}
className={cn(
"bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
className
)}
{...props}
/>
)
}
export { Separator }

View File

@ -139,7 +139,44 @@ export default function Editor() {
onError: (m) => setPageError(m),
});
const tableWidth = useMemo(() => (languages.length * 200) + 36 + 60 + 200, [languages.length]);
const tableWidth = useMemo(() => (languages.length * 200) + 36 + 60 + 300, [languages.length]);
function computeSuggestedLanguages(pathsInput: string[]): string[] {
if (languages.length === 0 || pathsInput.length === 0) return [];
const missing = new Set<string>();
for (const lang of languages) {
const langMap = valuesByLang[lang] || {};
let hasMissing = false;
for (const p of pathsInput) {
const val = langMap[p];
if (typeof val !== "string" || val.trim() === "") {
hasMissing = true;
break;
}
}
if (hasMissing) missing.add(lang);
}
const arr = Array.from(missing);
return arr.length > 0 ? arr : languages; // 如无缺失则默认全选
}
const getExistingByPath = useCallback((path: string) => {
const result: Record<string, string> = {};
for (const lang of languages) {
const text = valuesByLang[lang]?.[path];
if (typeof text === "string" && text.trim() !== "") {
result[lang] = text;
}
}
return result;
}, [languages, valuesByLang]);
const virtuosoComponents = useMemo(() => ({
Table: ({ style, ...props }: React.TableHTMLAttributes<HTMLTableElement>) => <table className="min-w-full text-sm table-fixed" {...props} style={{ ...style, width: tableWidth }} />,
@ -166,7 +203,7 @@ export default function Editor() {
}}
/>
</th>
<th style={{ width: 200 }} className="text-left px-3 py-2"></th>
<th style={{ width: 300 }} className="text-left px-3 py-2"></th>
{languages.map((lang) => (
<th key={lang} style={{ width: 200 }} className="text-left px-3 py-2">{lang}</th>
))}
@ -194,7 +231,7 @@ export default function Editor() {
}}
/>
</td>
<td className="px-3 py-2 font-mono">
<td className="px-3 py-2 font-mono wrap-break-word">
<button type="button" className="w-full text-left min-h-8 leading-8 px-2 rounded hover:bg-accent" onClick={handleCopy} title="点击复制">
{entry.path}
</button>
@ -287,7 +324,7 @@ export default function Editor() {
</td>
</>
);
}, [languages, inline, projectId, structure, setStructure, setValuesByLang, copy]);
}, [languages, inline, projectId, structure, setStructure, setValuesByLang, copy, selected]);
useEffect(() => {
if (!projectId || languages.length === 0) return;
@ -477,17 +514,25 @@ export default function Editor() {
onOpenChange={(v) => setAiModal((cur) => (cur ? { ...cur, open: v } : cur))}
languages={languages}
paths={aiModal?.path ? [aiModal.path] : []}
initialSelectedLanguages={aiModal?.path ? computeSuggestedLanguages([aiModal.path]) : []}
getExistingByPath={getExistingByPath}
prompt={project?.preferences?.aiPrompt}
onConfirm={async (translations) => {
onConfirm={async (translations, options) => {
if (!projectId || !aiModal) return;
const updates: Record<string, Record<string, string>> = {};
try {
const targetLangs = options?.selectedLanguages ?? languages;
await Promise.all(
languages.map(async (lang) => {
targetLangs.map(async (lang) => {
const prev = valuesByLang[lang] ?? {};
const next = { ...prev } as Record<string, string>;
const langMap = translations[lang] || {};
for (const [k, v] of Object.entries(langMap)) next[k] = v;
for (const [k, v] of Object.entries(langMap)) {
const existing = prev[k];
const isFilled = typeof existing === "string" && existing.trim() !== "";
if (!options?.overwrite && isFilled) continue; // 仅填充缺失
next[k] = v as string;
}
updates[lang] = next;
await upsertLanguageTranslations(projectId, lang, next);
})
@ -506,17 +551,25 @@ export default function Editor() {
onOpenChange={setAiBulkOpen}
languages={languages}
paths={Array.from(selected)}
initialSelectedLanguages={computeSuggestedLanguages(Array.from(selected))}
getExistingByPath={getExistingByPath}
prompt={project?.preferences?.aiPrompt}
onConfirm={async (translations) => {
onConfirm={async (translations, options) => {
if (!projectId || selected.size === 0) return;
try {
const updatesByLang: Record<string, Record<string, string>> = {};
const targetLangs = options?.selectedLanguages ?? languages;
await Promise.all(
languages.map(async (lang) => {
targetLangs.map(async (lang) => {
const prev = valuesByLang[lang] ?? {};
const next = { ...prev } as Record<string, string>;
const langMap = translations[lang] || {};
for (const [k, v] of Object.entries(langMap)) next[k] = v;
for (const [k, v] of Object.entries(langMap)) {
const existing = prev[k];
const isFilled = typeof existing === "string" && existing.trim() !== "";
if (!options?.overwrite && isFilled) continue; // 仅填充缺失
next[k] = v as string;
}
updatesByLang[lang] = next;
await upsertLanguageTranslations(projectId, lang, next);
})