feat(locale): complete admin locale management

This commit is contained in:
2026-09-11 22:49:01 +08:00
parent 9b8d9c7391
commit c987d9c0b1
4 changed files with 112 additions and 51 deletions
+97 -39
View File
@@ -2,8 +2,11 @@ import { createFileRoute } from '@tanstack/react-router'
import { PERM, requirePermission } from '@/auth/permissions'
import { useCan } from '@/auth/store'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { useState } from 'react'
import { Plus, Trash2 } from 'lucide-react'
import { useEffect, useState } from 'react'
import { Pencil, Plus, Trash2 } from 'lucide-react'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { toast } from 'sonner'
import type { ColumnDef } from '@tanstack/react-table'
import type { LocaleRow } from '@/api/types'
@@ -36,6 +39,7 @@ function LocalesPage() {
const queryClient = useQueryClient()
const locales = useQuery({ queryKey: ['locales'], queryFn: fetchLocales })
const [dialogOpen, setDialogOpen] = useState(false)
const [editing, setEditing] = useState<LocaleRow | null>(null)
const refresh = () => queryClient.invalidateQueries({ queryKey: ['locales'] })
@@ -78,9 +82,22 @@ function LocalesPage() {
},
{
header: '操作',
cell: ({ row }) =>
canDelete ? (
<ConfirmDialog
cell: ({ row }) => (
<div className="flex items-center gap-1">
{canUpdate && (
<Button
variant="ghost"
size="icon-sm"
aria-label="编辑"
onClick={() => {
setEditing(row.original)
setDialogOpen(true)
}}
>
<Pencil className="size-4" />
</Button>
)}
{canDelete && <ConfirmDialog
trigger={
<Button variant="ghost" size="icon-sm" aria-label="删除">
<Trash2 className="size-4 text-destructive" />
@@ -90,10 +107,10 @@ function LocalesPage() {
confirmLabel="删除"
destructive
onConfirm={() => remove(row.original)}
/>
) : (
<span className="text-xs text-muted-foreground"></span>
),
/>}
{!canUpdate && !canDelete && <span className="text-xs text-muted-foreground"></span>}
</div>
),
},
]
@@ -104,7 +121,10 @@ function LocalesPage() {
description="平台支持的界面/内容语言"
actions={
canCreate && (
<Button onClick={() => setDialogOpen(true)}>
<Button onClick={() => {
setEditing(null)
setDialogOpen(true)
}}>
<Plus className="size-4" />
</Button>
@@ -117,37 +137,70 @@ function LocalesPage() {
loading={locales.isPending}
emptyText="暂无语言"
/>
<CreateLocaleDialog
<LocaleDialog
open={dialogOpen}
onOpenChange={setDialogOpen}
onCreated={() => void refresh()}
locale={editing}
onSaved={() => void refresh()}
/>
</div>
)
}
function CreateLocaleDialog({
const localeSchema = z.object({
code: z.string().trim().min(2, '请输入语言代码').max(10).regex(
/^[A-Za-z]{2,3}(?:[-_][A-Za-z]{4})?(?:[-_](?:[A-Za-z]{2}|[0-9]{3}))?$/,
'请输入有效的 BCP-47 语言代码',
),
name: z.string().trim().min(1, '请输入名称').max(50),
native_name: z.string().trim().min(1, '请输入本地名称').max(50),
sort_order: z.number().int().min(0),
is_active: z.boolean(),
})
type LocaleFormValues = z.infer<typeof localeSchema>
function LocaleDialog({
open,
onOpenChange,
onCreated,
locale,
onSaved,
}: {
open: boolean
onOpenChange: (open: boolean) => void
onCreated: () => void
locale: LocaleRow | null
onSaved: () => void
}) {
const [draft, setDraft] = useState({ code: '', name: '', native_name: '' })
const [busy, setBusy] = useState(false)
const form = useForm<LocaleFormValues>({
resolver: zodResolver(localeSchema),
defaultValues: { code: '', name: '', native_name: '', sort_order: 0, is_active: true },
})
const submit = async () => {
useEffect(() => {
if (!open) return
form.reset({
code: locale?.code ?? '',
name: locale?.name ?? '',
native_name: locale?.native_name ?? '',
sort_order: locale?.sort_order ?? 0,
is_active: locale?.is_active ?? true,
})
}, [form, locale, open])
const submit = async (values: LocaleFormValues) => {
setBusy(true)
try {
await createLocale({ ...draft, is_active: true })
toast.success(`已添加语言 ${draft.code}`)
setDraft({ code: '', name: '', native_name: '' })
onCreated()
if (locale) {
await updateLocale(locale.code, values)
} else {
await createLocale(values)
}
toast.success(locale ? `已更新语言 ${locale.code}` : `已添加语言 ${values.code}`)
onSaved()
onOpenChange(false)
} catch (error) {
handleApiError(error)
handleApiError(error, form.setError)
} finally {
setBusy(false)
}
@@ -157,43 +210,48 @@ function CreateLocaleDialog({
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-sm">
<DialogHeader>
<DialogTitle></DialogTitle>
<DialogTitle>{locale ? `编辑语言 ${locale.code}` : '添加语言'}</DialogTitle>
</DialogHeader>
<div className="grid gap-4">
<form className="grid gap-4" onSubmit={form.handleSubmit(submit)}>
<div className="grid gap-1.5">
<Label></Label>
<Input
className="font-mono"
placeholder="zh-CN"
value={draft.code}
onChange={(e) => setDraft((d) => ({ ...d, code: e.target.value }))}
disabled={!!locale}
{...form.register('code')}
/>
{form.formState.errors.code && <p className="text-xs text-destructive">{form.formState.errors.code.message}</p>}
</div>
<div className="grid gap-1.5">
<Label></Label>
<Input
placeholder="Simplified Chinese"
value={draft.name}
onChange={(e) => setDraft((d) => ({ ...d, name: e.target.value }))}
{...form.register('name')}
/>
{form.formState.errors.name && <p className="text-xs text-destructive">{form.formState.errors.name.message}</p>}
</div>
<div className="grid gap-1.5">
<Label></Label>
<Input
placeholder="简体中文"
value={draft.native_name}
onChange={(e) => setDraft((d) => ({ ...d, native_name: e.target.value }))}
{...form.register('native_name')}
/>
{form.formState.errors.native_name && <p className="text-xs text-destructive">{form.formState.errors.native_name.message}</p>}
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>
</Button>
<Button onClick={submit} disabled={busy || !draft.code || !draft.name || !draft.native_name}>
{busy ? '添加中…' : '添加'}
</Button>
</DialogFooter>
<div className="grid gap-1.5">
<Label></Label>
<Input type="number" {...form.register('sort_order', { valueAsNumber: true })} />
</div>
<div className="flex items-center justify-between">
<Label></Label>
<Switch checked={form.watch('is_active')} onCheckedChange={(value) => form.setValue('is_active', value)} />
</div>
<DialogFooter>
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}></Button>
<Button type="submit" disabled={busy}>{busy ? '保存中…' : '保存'}</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
)