fix(i18n): use English runtime text and localize system UI

This commit is contained in:
Arthur Koba
2026-10-25 19:44:15 +03:00
parent ada0550571
commit 65a96670d5
289 changed files with 8092 additions and 3426 deletions
@@ -1,3 +1,4 @@
import { getFormattingLocale } from '@/i18n/format';
export type AccessLogTab = 'overview' | 'ips' | 'list';
export type SearchDraft = {
@@ -66,7 +67,7 @@ export function parseSortValue(value: string) {
}
export function formatCompactNumber(value: number) {
return new Intl.NumberFormat('zh-CN', {
return new Intl.NumberFormat(getFormattingLocale(), {
notation: value >= 10000 ? 'compact' : 'standard',
maximumFractionDigits: 1,
}).format(value);
+19 -17
View File
@@ -1,8 +1,8 @@
'use client';
// Copyright 2026 Arctel.net
// SPDX-License-Identifier: Apache-2.0
'use client';
import * as React from 'react';
import { useTranslations } from 'next-intl';
import { Code } from 'lucide-react';
@@ -22,6 +22,8 @@ import { TableTab } from './tabs/table-tab';
import { ControlsTab } from './tabs/controls-tab';
export default function HeaderDemoPage() {
const rt = useTranslations('runtime');
const t = useTranslations('admin.demo');
const [activeTab, setActiveTab] = React.useState('dashboard');
@@ -59,7 +61,8 @@ export default function HeaderDemoPage() {
{t('rules.structureFocus.description')}
</li>
<li>
<strong>{t('rules.containerAlignment.title')}</strong>:使用{' '}
<strong>{t('rules.containerAlignment.title')}</strong>
{rt('use_1b3d699e')}{' '}
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
flex items-center gap-2
</code>{' '}
@@ -67,22 +70,23 @@ export default function HeaderDemoPage() {
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
py-6 px-1
</code>{' '}
(或{' '}
{rt('or_07d4e3c0')}{' '}
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
py-6
</code>
) {t('rules.containerAlignment.description2')}
</li>
<li>
<strong>{t('rules.iconPresentation.title')}</strong>:直接将
Lucide 图标组件嵌套于标题容器中,应用{' '}
<strong>{t('rules.iconPresentation.title')}</strong>
{rt('place_the_lucide_icon_directly_inside_the_104f794c')}{' '}
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
size-5 text-primary
</code>{' '}
{t('rules.iconPresentation.description')}
</li>
<li>
<strong>{t('rules.textStyle.title')}</strong>:文本使用且仅使用{' '}
<strong>{t('rules.textStyle.title')}</strong>
{rt('use_only_5e12eecb')}{' '}
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
{'h1 className="text-2xl font-semibold tracking-tight"'}
</code>
@@ -93,10 +97,8 @@ export default function HeaderDemoPage() {
{t('rules.textStyle.description2')}
</li>
<li>
<strong>{t('rules.tabsModular.title')}</strong>:凡是带有多个
Tab 页切换的页面,**禁止**将所有 Tab
的渲染代码堆积在同一个物理页面主文件内。每个 Tab 页对应的
Content 必须单独拆分为独立组件文件(如{' '}
<strong>{t('rules.tabsModular.title')}</strong>
{rt('for_pages_with_multiple_tabs_keep_each_5f721959')}{' '}
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
tabs/events-tab.tsx
</code>{' '}
@@ -107,8 +109,8 @@ export default function HeaderDemoPage() {
{t('rules.tabsModular.description2')}
</li>
<li>
<strong>{t('rules.complexityDriven.title')}</strong>:不仅是
Tabs 切换,当一个页面代码行数超过 600
<strong>{t('rules.complexityDriven.title')}</strong>
{rt('beyond_tabs_when_a_page_exceeds_600_d152cfdc')}
{t('rules.complexityDriven.description')}{' '}
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
app/(main)/admin/database/components/
@@ -121,19 +123,19 @@ export default function HeaderDemoPage() {
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
/admin/database
</code>
) 的{' '}
{rt('message_18ab4763')}{' '}
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
table-browser.tsx
</code>
、
{rt('list_separator')}
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
cache-manager.tsx
</code>{' '}
与{' '}
{rt('and_de1d5dd0')}{' '}
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
sql-console.tsx
</code>
。
{rt('sentence_end')}
</li>
</ul>
</div>
@@ -1,8 +1,8 @@
'use client';
// Copyright 2026 Arctel.net
// SPDX-License-Identifier: Apache-2.0
'use client';
import * as React from 'react';
import { useTranslations } from 'next-intl';
import { Code } from 'lucide-react';
@@ -26,6 +26,8 @@ import { Checkbox } from '@/components/ui/checkbox';
import { Button } from '@/components/ui/button';
export function ControlsTab() {
const rt = useTranslations('runtime');
const t = useTranslations('admin.demo.controls');
const [formData, setFormData] = React.useState({
name: '',
@@ -166,78 +168,71 @@ export function ControlsTab() {
{t('spec.unifiedHeight')}
</p>
<p>
输入框 (
{rt('inputs_fabee312')}
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
Input
</code>
) 与下拉选择器 (
{rt('and_selectors_e4875cdf')}
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
SelectTrigger
</code>
) 的高度应统一限制为小号高度{' '}
{rt('should_share_the_compact_height_f1fe2218')}{' '}
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
h-8
</code>
,字体大小使用{' '}
{rt('with_font_size_e7c29991')}{' '}
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
text-xs
</code>
,并使用{' '}
{rt('and_use_ca398a12')}{' '}
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
shadow-none
</code>{' '}
去除原生的重叠阴影。
{rt('to_remove_overlapping_native_shadows_dd65b475')}
</p>
<p className='font-semibold text-foreground text-[11px] pt-1'>
{t('spec.checkboxAlignment')}
</p>
<p>
Checkbox 应在左侧垂直偏上对齐,使用容器{' '}
{rt('align_checkboxes_toward_the_top_left_using_092dcef0')}{' '}
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
flex items-start gap-2.5
</code>{' '}
排列。Checkbox 组件本身添加{' '}
{rt('add_bf15da3a')}{' '}
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
mt-0.5
</code>
,从而在多行描述文本的情况下依然保持良好的顶对齐,避免出现居中对齐导致的凌乱感。
{rt('to_the_checkbox_so_multiline_descriptions_stay_1bb85c4b')}
</p>
<p className='font-semibold text-foreground text-[11px] pt-1'>
{t('spec.buttonStrategy')}
</p>
<p>
普通主表单及新增/保存按钮,一律使用默认 Primary 按钮或次要{' '}
{rt('use_the_default_primary_or_secondary_db7513e5')}{' '}
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
{'variant="secondary"'}
</code>{' '}
按钮,小号高度统一采用{' '}
{rt('button_for_forms_and_create_save_actions_a657dba8')}{' '}
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
h-8 text-xs
</code>
。线框按钮必须带有{' '}
{rt('outline_buttons_must_include_the_66ace005')}{' '}
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
border-dashed shadow-none
</code>{' '}
类。
{rt('class_43eff5ff')}
</p>
</div>
<div className='bg-background/80 p-3 rounded border border-border/40 font-mono text-[10px] space-y-2 overflow-x-auto'>
<div>{`// 1. Label 与 Input 对齐`}</div>
<div>{`<div className="space-y-1.5">
<Label htmlFor="id" className="text-xs font-medium text-foreground">标题</Label>
<Input id="id" className="h-8 text-xs shadow-none" />
</div>`}</div>
<div className='pt-2'>{`// 2. Checkbox 顶对齐`}</div>
<div>{`<div className="flex items-start gap-2.5">
<Checkbox id="c" className="mt-0.5" />
<div className="grid gap-1">
<label htmlFor="c" className="text-xs font-medium leading-none">标题</label>
<p className="text-[10px] text-muted-foreground">多行说明内容</p>
</div>
</div>`}</div>
<div>{rt('1_align_label_and_input_32d4558d')}</div>
<div>{rt.raw('div_classname_space_y_1_5_label_32230ad7')}</div>
<div className='pt-2'>
{rt('2_align_checkbox_to_the_top_bdf68ad8')}
</div>
<div>{rt.raw('div_classname_flex_items_start_gap_2_ccf0d526')}</div>
</div>
</CardContent>
</Card>
@@ -1,8 +1,8 @@
'use client';
// Copyright 2026 Arctel.net
// SPDX-License-Identifier: Apache-2.0
'use client';
import * as React from 'react';
import { useTranslations } from 'next-intl';
import { Code, Cpu, Database, HardDrive } from 'lucide-react';
@@ -10,6 +10,8 @@ import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Progress } from '@/components/ui/progress';
export function DashboardTab() {
const rt = useTranslations('runtime');
const t = useTranslations('admin.demo.dashboard');
return (
<div className='space-y-6'>
@@ -129,17 +131,9 @@ export function DashboardTab() {
</li>
</ul>
<pre className='text-[11px] font-mono text-muted-foreground overflow-x-auto p-3 bg-background rounded border border-border/40 leading-relaxed'>
{`<Card className="border-dashed shadow-none">
<CardHeader className="flex flex-row items-center justify-between pb-2">
<span className="text-xs font-medium text-muted-foreground">指标标题</span>
<Cpu className="size-4 text-primary" />
</CardHeader>
<CardContent className="space-y-2">
<div className="text-2xl font-semibold tracking-tight">42.8 %</div>
<Progress value={42.8} className="h-1.5" />
<p className="text-[10px] text-muted-foreground">状态说明小字</p>
</CardContent>
</Card>`}
{rt.raw(
'card_classname_border_dashed_shadow_none_cardheader_35727acf',
)}
</pre>
</CardContent>
</Card>
@@ -1,8 +1,8 @@
'use client';
// Copyright 2026 Arctel.net
// SPDX-License-Identifier: Apache-2.0
'use client';
import * as React from 'react';
import { useTranslations } from 'next-intl';
import { Code, Edit, ListFilter, Plus, Search, Trash2 } from 'lucide-react';
@@ -20,6 +20,8 @@ import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
export function TableTab() {
const rt = useTranslations('runtime');
const t = useTranslations('admin.demo.table');
const mockTableData = [
{
@@ -193,7 +195,7 @@ export function TableTab() {
border border-dashed shadow-none rounded-lg overflow-hidden
bg-background
</code>
。
{rt('sentence_end')}
</li>
<li>
{t('spec.headerBg')}
@@ -204,7 +206,7 @@ export function TableTab() {
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
text-xs font-semibold
</code>
。
{rt('sentence_end')}
</li>
<li>
{t('spec.cellDivider')}
@@ -215,14 +217,14 @@ export function TableTab() {
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
hover:bg-muted/10 transition-colors
</code>
。
{rt('sentence_end')}
</li>
<li>
{t('spec.monoFont')}
<code className='bg-muted px-1 py-0.5 rounded font-mono'>
font-mono text-xs
</code>
。
{rt('sentence_end')}
</li>
<li>
{t('spec.badgeStyle')}
@@ -233,27 +235,7 @@ export function TableTab() {
</li>
</ul>
<pre className='text-[11px] font-mono text-muted-foreground overflow-x-auto p-3 bg-background rounded border border-border/40 leading-relaxed'>
{`<div className="border border-dashed shadow-none rounded-lg overflow-hidden bg-background">
<Table>
<TableHeader className="bg-muted/40">
<TableRow className="border-dashed hover:bg-transparent">
<TableHead className="text-xs font-semibold">编号</TableHead>
<TableHead className="text-xs font-semibold">状态</TableHead>
</TableRow>
</TableHeader>
<TableBody>
<TableRow className="border-dashed hover:bg-muted/10 transition-colors">
<TableCell className="font-mono text-xs">ID-1001</TableCell>
<TableCell>
<Badge variant="outline" className="text-[10px] bg-emerald-500/10 border-emerald-500/20 text-emerald-600 rounded-full py-0 px-2">
<span className="size-1 bg-emerald-500 rounded-full mr-1.5 shrink-0" />
成功
</Badge>
</TableCell>
</TableRow>
</TableBody>
</Table>
</div>`}
{rt.raw('div_classname_border_border_dashed_shadow_none_b430b520')}
</pre>
</CardContent>
</Card>
@@ -1,5 +1,6 @@
'use client';
import { getFormattingLocale } from '@/i18n/format';
import * as React from 'react';
import { useTranslations } from 'next-intl';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
@@ -72,7 +73,7 @@ function getFileIcon(mimeType: string, className = 'size-8') {
}
function formatDate(dateStr: string) {
return new Date(dateStr).toLocaleString('zh-CN', {
return new Date(dateStr).toLocaleString(getFormattingLocale(), {
year: 'numeric',
month: '2-digit',
day: '2-digit',
@@ -50,6 +50,12 @@ const categoryMap: Record<string, string> = {
其他: 'others',
};
// The API retains persisted category keys; labels always follow the UI locale.
function categoryTranslationKey(name: string) {
const key = categoryMap[name] || 'others';
return `stats.cat${key.charAt(0).toUpperCase()}${key.slice(1)}`;
}
function useStatsChartConfig() {
const t = useTranslations('admin.files');
return {
@@ -158,11 +164,11 @@ export function FileStats() {
stats.categories.forEach((cat) => {
if (cat.count > maxCount) {
maxCount = cat.count;
maxCountName = cat.name;
maxCountName = t(categoryTranslationKey(cat.name));
}
if (cat.size > maxSize) {
maxSize = cat.size;
maxSizeName = cat.name;
maxSizeName = t(categoryTranslationKey(cat.name));
}
});
@@ -17,6 +17,7 @@ limitations under the License.
'use client';
import { useCallback, useEffect, useState } from 'react';
import { isLogStorageDisabledMessage } from './log-storage-error';
import {
BarChart3,
Globe,
@@ -117,7 +118,7 @@ export function AccessAnalytics() {
const errorInstance =
err instanceof Error ? err : new Error(t('fetchFailed'));
const errMsg = errorInstance.message || '';
if (errMsg.includes('ClickHouse') || errMsg.includes('未启用')) {
if (isLogStorageDisabledMessage(errMsg)) {
setClickhouseDisabled(true);
} else {
setError(errorInstance);
@@ -17,6 +17,7 @@ limitations under the License.
'use client';
import { useMemo, useState } from 'react';
import { isLogStorageDisabledMessage } from './log-storage-error';
import { useQuery } from '@tanstack/react-query';
import { toast } from 'sonner';
import { format } from 'date-fns';
@@ -94,7 +95,7 @@ function statusVariant(status: number) {
function isClickhouseDisabledError(error: Error) {
const errMsg = error.message || '';
return errMsg.includes('ClickHouse') || errMsg.includes('未启用');
return isLogStorageDisabledMessage(errMsg);
}
export function AccessLogs() {
@@ -0,0 +1,13 @@
import { getRuntimeTranslator } from '@/i18n/runtime';
export function isLogStorageDisabledMessage(message: string): boolean {
const normalized = message.toLowerCase();
return (
message.includes('ClickHouse') ||
(['en', 'zh-CN'] as const).some((locale) =>
normalized.includes(
getRuntimeTranslator(locale)('disabled_f95ea7f4').toLowerCase(),
),
)
);
}
@@ -1,8 +1,8 @@
'use client';
// Copyright 2026 Arctel.net
// SPDX-License-Identifier: Apache-2.0
'use client';
import * as React from 'react';
import { useTranslations } from 'next-intl';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
@@ -81,6 +81,8 @@ import type {
import { PushService } from '@/lib/services/push';
export function EventsTab() {
const rt = useTranslations('runtime');
const t = useTranslations('admin.push.events');
const queryClient = useQueryClient();
const [deleteTarget, setDeleteTarget] = React.useState<PushEvent | null>(
@@ -706,11 +708,11 @@ export function EventsTab() {
</div>
<div className='space-y-1.5'>
<div className='flex justify-between items-center'>
<div className='flex flex-col gap-1 sm:flex-row sm:items-center sm:justify-between'>
<Label className='text-xs font-semibold'>
{t('contentTemplate')}
</Label>
<span className='text-[10px] text-muted-foreground font-mono flex items-center'>
<span className='text-[10px] text-muted-foreground font-mono'>
{newEventType === 'task'
? t('taskTemplateVars')
: t('eventTemplateVars')}
@@ -721,7 +723,11 @@ export function EventsTab() {
onChange={(e) => setNewEventTemplate(e.target.value)}
rows={6}
className='text-xs font-mono'
placeholder='{"title": "管理员登录提醒", "content": "管理员 {{user.username}} ...", "level": "INFO"}'
placeholder={rt.raw(
newEventType === 'task'
? 'task_notification_template_example'
: 'title_administrator_login_alert_content_administrator_user_6f32cf7c',
)}
/>
</div>
@@ -886,11 +892,11 @@ export function EventsTab() {
</div>
<div className='space-y-1.5'>
<div className='flex justify-between items-center'>
<div className='flex flex-col gap-1 sm:flex-row sm:items-center sm:justify-between'>
<Label className='text-xs font-semibold'>
{t('contentTemplate')}
</Label>
<span className='text-[10px] text-muted-foreground font-mono flex items-center'>
<span className='text-[10px] text-muted-foreground font-mono'>
{selectedEvent.task_type
? t('taskTemplateVars')
: t('eventTemplateVars')}
@@ -901,7 +907,11 @@ export function EventsTab() {
onChange={(e) => setEventTemplate(e.target.value)}
rows={6}
className='text-xs font-mono'
placeholder='{"title": "管理员登录提醒", "content": "管理员 {{user.username}} ...", "level": "INFO"}'
placeholder={rt.raw(
selectedEvent.task_type
? 'task_notification_template_example'
: 'title_administrator_login_alert_content_administrator_user_6f32cf7c',
)}
/>
</div>
</div>
@@ -1,8 +1,8 @@
'use client';
// Copyright 2026 Arctel.net
// SPDX-License-Identifier: Apache-2.0
'use client';
import * as React from 'react';
import { useTranslations } from 'next-intl';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
@@ -62,6 +62,8 @@ import type {
import { PushService } from '@/lib/services/push';
export function SettingsTab() {
const rt = useTranslations('runtime');
const t = useTranslations('admin.push.settings');
const queryClient = useQueryClient();
const [deleteTarget, setDeleteTarget] = React.useState<PushChannel | null>(
@@ -606,7 +608,7 @@ export function SettingsTab() {
toast.success(t('loadedFeishuTemplate'));
}}
>
飞书 Webhook
{rt('lark_webhook_c2e0b312')}
</Button>
<Button
variant='outline'
@@ -623,7 +625,9 @@ export function SettingsTab() {
msgtype: 'markdown',
markdown: {
title: '$title',
text: '### $title\n$content\n\n[查看详情]($url)',
text: rt(
'title_content_view_details_url_7af4b7d5',
),
},
},
null,
@@ -633,7 +637,7 @@ export function SettingsTab() {
toast.success(t('loadedDingTalkTemplate'));
}}
>
钉钉群机器人
{rt('dingtalk_group_bot_5d8efec9')}
</Button>
<Button
variant='outline'
@@ -649,8 +653,9 @@ export function SettingsTab() {
{
msgtype: 'markdown',
markdown: {
content:
'### $title\n$content\n\n[查看详情]($url)',
content: rt(
'title_content_view_details_url_7af4b7d5',
),
},
},
null,
@@ -660,7 +665,7 @@ export function SettingsTab() {
toast.success(t('loadedWeChatTemplate'));
}}
>
企业微信群机器人
{rt('wecom_group_bot_138ea7a8')}
</Button>
<Button
variant='outline'
+20 -5
View File
@@ -1,7 +1,8 @@
'use client';
import * as React from 'react';
import { useTranslations } from 'next-intl';
import { useLocale, useTranslations } from 'next-intl';
import { localizeConfigDescription } from '@/i18n/builtin-metadata';
import { Input } from '@/components/ui/input';
import { Switch } from '@/components/ui/switch';
import {
@@ -52,6 +53,7 @@ function SystemConfigDetailPanel({
saving: boolean;
}) {
const t = useTranslations('admin.system');
const locale = useLocale();
return (
<ManageDetailPanel isEmpty={!config} onSave={onSave} saving={saving}>
<div className='grid grid-cols-1 gap-0'>
@@ -138,8 +140,16 @@ function SystemConfigDetailPanel({
type='text'
value={
editData.description !== undefined
? editData.description
: config?.description || ''
? localizeConfigDescription(
config?.key ?? '',
editData.description,
locale,
)
: localizeConfigDescription(
config?.key ?? '',
config?.description || '',
locale,
)
}
placeholder={t('optionalDescription')}
onChange={(e) => {
@@ -205,6 +215,7 @@ function SystemConfigDetailPanel({
*/
export function SystemConfigs() {
const t = useTranslations('admin.system');
const locale = useLocale();
const {
systemConfigs: configs,
systemConfigsLoading: loading,
@@ -309,9 +320,13 @@ export function SystemConfigs() {
cell: (item) => (
<span
className='truncate max-w-[200px] inline-block text-muted-foreground'
title={item.description}
title={localizeConfigDescription(
item.key,
item.description,
locale,
)}
>
{item.description}
{localizeConfigDescription(item.key, item.description, locale)}
</span>
),
width: '200px',
@@ -47,7 +47,6 @@ import { Badge } from '@/components/ui/badge';
import { cn } from '@/lib/utils';
import { format } from 'date-fns';
import { zhCN } from 'date-fns/locale';
import { Calendar } from '@/components/ui/calendar';
import {
Popover,
@@ -177,7 +176,6 @@ function DatePickerWithTime({
mode='single'
selected={date}
onSelect={handleDateSelect}
locale={zhCN}
/>
</PopoverContent>
</Popover>
@@ -1,5 +1,6 @@
'use client';
import { getFormattingLocale } from '@/i18n/format';
import { useTranslations } from 'next-intl';
import { RankChart } from '@/components/data/rank-chart';
@@ -16,7 +17,7 @@ function buildNodeRankItems(
const leftValue = selector(left);
const rightValue = selector(right);
if (leftValue === rightValue) {
return left.name.localeCompare(right.name, 'zh-CN');
return left.name.localeCompare(right.name, getFormattingLocale());
}
return rightValue - leftValue;
})
@@ -1,5 +1,6 @@
'use client';
import { getFormattingLocale } from '@/i18n/format';
import ReactEChartsCore from 'echarts-for-react/lib/core';
import type { EChartsCoreOption } from 'echarts/core';
import * as echarts from 'echarts/core';
@@ -506,7 +507,7 @@ export function WorldStageMap({
) {
return [
`<div style="font-weight:600;margin-bottom:6px;">${payload.name ?? data.name}</div>`,
`<div>${t('sourceRequests', { count: data.value.toLocaleString('zh-CN') })}</div>`,
`<div>${t('sourceRequests', { count: data.value.toLocaleString(getFormattingLocale()) })}</div>`,
].join('');
}
@@ -522,8 +523,8 @@ export function WorldStageMap({
`<div style="font-weight:600;margin-bottom:6px;">${data.name}</div>`,
`<div>${locationLine}</div>`,
`<div>${t('requestsErrors', {
requests: data.requestCount.toLocaleString('zh-CN'),
errors: data.errorCount.toLocaleString('zh-CN'),
requests: data.requestCount.toLocaleString(getFormattingLocale()),
errors: data.errorCount.toLocaleString(getFormattingLocale()),
})}</div>`,
`<div>${t('eventsStatus', {
events: data.activeEventCount,
@@ -1,3 +1,6 @@
'use client';
import { useTranslations } from 'next-intl';
import type { LucideIcon } from 'lucide-react';
import {
@@ -13,6 +16,8 @@ interface PlaceholderPageProps {
}
export function PlaceholderPage({ title, icon: Icon }: PlaceholderPageProps) {
const rt = useTranslations('runtime');
return (
<div className='py-6 px-1 space-y-6'>
<div className='flex items-center gap-2'>
@@ -22,8 +27,12 @@ export function PlaceholderPage({ title, icon: Icon }: PlaceholderPageProps) {
<Card>
<CardHeader>
<CardTitle className='text-base'>开发中</CardTitle>
<CardDescription>该功能正在迁移开发中,敬请期待。</CardDescription>
<CardTitle className='text-base'>
{rt('under_development_78c33fbf')}
</CardTitle>
<CardDescription>
{rt('this_feature_is_being_migrated_and_developed_61ebaf78')}
</CardDescription>
</CardHeader>
</Card>
</div>
@@ -1,5 +1,6 @@
'use client';
import { getFormattingLocale } from '@/i18n/format';
import { useMemo, useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { Loader2, Trash2 } from 'lucide-react';
@@ -652,7 +653,9 @@ export function NodeObservability({
hint={
topSourceCountry
? t('obs.requestTimes', {
count: topSourceCountry.value.toLocaleString('zh-CN'),
count: topSourceCountry.value.toLocaleString(
getFormattingLocale(),
),
})
: t('obs.noSourceDist')
}
@@ -1,3 +1,4 @@
import { getFormattingLocale } from '@/i18n/format';
import type {
ApplyResult,
NodeItem,
@@ -255,7 +256,7 @@ export function formatMetricCount(value?: number | null) {
if (value === undefined || value === null || !Number.isFinite(value)) {
return '—';
}
return value.toLocaleString('zh-CN');
return value.toLocaleString(getFormattingLocale());
}
export function formatBytesPerSecond(value?: number | null, windowSeconds = 1) {
@@ -79,6 +79,8 @@ function systemConfigMap(configs: SystemConfig[]) {
}
export function RelayNodeDetail({ node }: { node: NodeItem }) {
const rt = useTranslations('runtime');
const t = useTranslations('nodes');
const tc = useTranslations('common');
const router = useRouter();
@@ -116,7 +118,9 @@ export function RelayNodeDetail({ node }: { node: NodeItem }) {
'relay_frps_web_ui_port',
{
value: String(portNum),
description: portCfg?.description || 'FRPS 内置 Web 管理界面端口',
description:
portCfg?.description ||
rt('port_for_the_built_in_frps_web_cfab540f'),
},
);
},
@@ -1,3 +1,4 @@
import { runtimeText } from '@/i18n/runtime';
import type {
ProxyRouteConfigSection,
ProxyRouteCustomHeader,
@@ -154,7 +155,8 @@ const limitRatePattern = /^\d+(?:[kKmM])?$/;
export function getErrorMessage(error: unknown, fallback?: string) {
return error instanceof Error
? error.message
: (fallback ?? '请求失败,请稍后重试。');
: (fallback ??
runtimeText('request_failed_please_try_again_later_8977b79a'));
}
export function linesFromTextarea(value: string) {
@@ -1,5 +1,6 @@
'use client';
import { getFormattingLocale } from '@/i18n/format';
import { Gauge } from 'lucide-react';
import { useTranslations } from 'next-intl';
@@ -31,9 +32,11 @@ function toAvgRpsItems(items: DistributionItem[] | undefined, hours: number) {
function formatRps(value: number) {
if (!Number.isFinite(value)) return '—';
if (value >= 100) {
return value.toLocaleString('zh-CN', { maximumFractionDigits: 1 });
return value.toLocaleString(getFormattingLocale(), {
maximumFractionDigits: 1,
});
}
return value.toLocaleString('zh-CN', {
return value.toLocaleString(getFormattingLocale(), {
maximumFractionDigits: 3,
minimumFractionDigits: 0,
});
@@ -1,5 +1,6 @@
'use client';
import { getFormattingLocale } from '@/i18n/format';
import { useCallback, useMemo, useRef } from 'react';
import type { EChartsOption } from 'echarts';
import type { EChartsType } from 'echarts/core';
@@ -48,7 +49,7 @@ function formatAxisTime(value: string, hours: number) {
function formatRps(value: number) {
if (!Number.isFinite(value)) return '—';
if (value >= 100) return formatCompactNumber(value);
return value.toLocaleString('zh-CN', {
return value.toLocaleString(getFormattingLocale(), {
maximumFractionDigits: 2,
minimumFractionDigits: 0,
});
+19 -8
View File
@@ -1,7 +1,10 @@
import { runtimeText } from '@/i18n/runtime';
import type { WAFIPGroup, WAFIPGroupPayload } from '@/lib/services/openflare';
export function getErrorMessage(error: unknown, fallback?: string) {
return error instanceof Error ? error.message : (fallback ?? '操作失败');
return error instanceof Error
? error.message
: (fallback ?? runtimeText('operation_failed_0c3b4cf7'));
}
export function listToText(items: string[] | undefined) {
@@ -17,7 +20,9 @@ export function parseTextareaList(text: string) {
export function parseAutomaticConfig(
text: string,
invalidMessage = '自动配置必须是 JSON 对象。',
invalidMessage = runtimeText(
'automatic_configuration_must_be_a_json_object_90ba17a4',
),
): Record<string, unknown> {
const parsed = JSON.parse(text || '{}') as unknown;
if (!parsed || Array.isArray(parsed) || typeof parsed !== 'object') {
@@ -28,12 +33,16 @@ export function parseAutomaticConfig(
export const automaticPresetRules = [
{
name: '单 IP 404 高频扫描',
get name() {
return runtimeText('high_frequency_404_scan_from_one_ip_f7d27ffb');
},
labelKey: 'presets.scan404' as const,
expr: 'request_count > 100 && StatusRatio(404) >= 0.8',
},
{
name: '单 IP 直连访问异常',
get name() {
return runtimeText('abnormal_direct_access_from_one_ip_732dbeee');
},
labelKey: 'presets.directAccess' as const,
expr: 'ip_host_count > 50 && ip_host_ratio > 0.5',
},
@@ -75,7 +84,7 @@ export function formatIPGroupBanRemaining(
): string {
const reference = now ?? new Date();
if (ttlSeconds <= 0) {
return t ? t('ban.permanent') : '永久';
return t ? t('ban.permanent') : runtimeText('permanent_3e71ccc8');
}
const capturedDate = new Date(capturedAt);
if (Number.isNaN(capturedDate.getTime())) {
@@ -83,7 +92,7 @@ export function formatIPGroupBanRemaining(
}
const expireDate = new Date(capturedDate.getTime() + ttlSeconds * 1000);
if (expireDate.getTime() <= reference.getTime()) {
return t ? t('ban.expired') : '已过期';
return t ? t('ban.expired') : runtimeText('expired_2fe0e333');
}
const diffMins = Math.round(
(expireDate.getTime() - reference.getTime()) / (60 * 1000),
@@ -91,10 +100,12 @@ export function formatIPGroupBanRemaining(
if (diffMins < 60) {
return t
? t('ban.minutesLater', { count: diffMins })
: `${diffMins} 分钟后`;
: runtimeText('in_value0_minutes_fd2a5b53', { value0: diffMins });
}
const hours = Math.round(diffMins / 60);
return t ? t('ban.hoursLater', { count: hours }) : `${hours} 小时后`;
return t
? t('ban.hoursLater', { count: hours })
: runtimeText('in_value0_hours_5ca37144', { value0: hours });
}
export function getIPGroupViewEntries(
@@ -2,6 +2,7 @@ import type { EdgeChange, Node, NodeChange } from '@xyflow/react';
import type { WAFRuleGraph, WAFRuleNode } from '@/lib/services/openflare';
import { wouldCreateCycle } from './graph-validation';
import { getRuntimeTranslator } from '@/i18n/runtime';
export type GraphErrorTarget = { kind: 'node' | 'edge'; id: string };
@@ -109,9 +110,9 @@ export function findGraphErrorTarget(
}
const messages = collectMessages(payload);
for (const message of messages) {
const nodeId = findMessageId(message, '节点', nodeIds);
const nodeId = findMessageId(message, 'node', nodeIds);
if (nodeId) return { kind: 'node', id: nodeId };
const edgeId = findMessageId(message, '边', edgeIds);
const edgeId = findMessageId(message, 'edge', edgeIds);
if (edgeId) return { kind: 'edge', id: edgeId };
}
return undefined;
@@ -132,16 +133,22 @@ function collectMessages(value: unknown): string[] {
function findMessageId(
message: string,
prefix: '节点' | '边',
prefix: 'node' | 'edge',
ids: string[],
): string | undefined {
const token = prefix === '边' ? '边(?:\\s+ID)?' : '节点';
const tokenKey = prefix === 'edge' ? 'edge_099db313' : 'node_2410d860';
return [...ids]
.sort((a, b) => b.length - a.length)
.find((id) =>
new RegExp(`${token}\\s+${escapeRegExp(id)}(?=$|[\\s,。,::的])`).test(
message,
),
(['en', 'zh-CN'] as const).some((locale) => {
const t = getRuntimeTranslator(locale);
const token = `${escapeRegExp(t(tokenKey))}(?:\\s+ID)?`;
const pattern = t
.raw('value0_s_value1_s_40960c98')
.replace('{value0}', token)
.replace('{value1}', escapeRegExp(id));
return new RegExp(pattern, 'i').test(message);
}),
);
}
@@ -1,8 +1,22 @@
import { describe, expect, it } from 'vitest';
import { countryOptions, regionOptions } from './geo-options';
import { createGeoOptions } from './geo-options';
const { countryOptions, regionOptions } = createGeoOptions('zh-CN');
describe('geo options', () => {
it('uses English country names when requested without changing country codes', () => {
const english = createGeoOptions('en');
expect(english.countryOptions).toContainEqual(
expect.objectContaining({ value: 'CN', label: 'China' }),
);
expect(english.regionOptions).toContainEqual(
expect.objectContaining({
value: 'CN-BJ',
searchText: expect.stringContaining('China'),
}),
);
});
it('contains the complete country list with localized names', () => {
expect(countryOptions).toHaveLength(249);
expect(countryOptions).toContainEqual(
@@ -8,46 +8,50 @@ export interface GeoOption {
const countryCodePattern = /^[A-Z]{2}$/;
const regionCodePattern = /^[A-Z0-9]{1,3}$/;
const countryDisplayNames = new Intl.DisplayNames(['zh-CN'], {
type: 'region',
});
export function createGeoOptions(locale: string) {
const countryDisplayNames = new Intl.DisplayNames([locale], {
type: 'region',
});
function localizedCountryName(code: string, fallback: string) {
const localized = countryDisplayNames.of(code);
return !localized || localized === code ? fallback : localized;
function localizedCountryName(code: string, fallback: string) {
const localized = countryDisplayNames.of(code);
return !localized || localized === code ? fallback : localized;
}
const countryOptions: GeoOption[] = allCountries
.filter(([, code]) => countryCodePattern.test(code))
.map(([englishName, code]) => {
const label = localizedCountryName(code, englishName);
return {
value: code,
label,
searchText: `${label} ${englishName} ${code}`,
};
})
.sort((left, right) => left.label.localeCompare(right.label, locale));
const regionOptions: GeoOption[] = allCountries.flatMap(
([englishCountryName, countryCode, regions]) => {
const countryName = localizedCountryName(countryCode, englishCountryName);
return regions.flatMap(([regionName, shortCode]) => {
const normalizedShortCode = shortCode?.toUpperCase();
if (
!normalizedShortCode ||
!regionCodePattern.test(normalizedShortCode)
) {
return [];
}
const value = `${countryCode}-${normalizedShortCode}`;
return [
{
value,
label: `${regionName} · ${countryName}`,
searchText: `${regionName} ${countryName} ${englishCountryName} ${value}`,
},
];
});
},
);
return { countryOptions, regionOptions };
}
export const countryOptions: GeoOption[] = allCountries
.filter(([, code]) => countryCodePattern.test(code))
.map(([englishName, code]) => {
const label = localizedCountryName(code, englishName);
return {
value: code,
label,
searchText: `${label} ${englishName} ${code}`,
};
})
.sort((left, right) => left.label.localeCompare(right.label, 'zh-CN'));
export const regionOptions: GeoOption[] = allCountries.flatMap(
([englishCountryName, countryCode, regions]) => {
const countryName = localizedCountryName(countryCode, englishCountryName);
return regions.flatMap(([regionName, shortCode]) => {
const normalizedShortCode = shortCode?.toUpperCase();
if (
!normalizedShortCode ||
!regionCodePattern.test(normalizedShortCode)
) {
return [];
}
const value = `${countryCode}-${normalizedShortCode}`;
return [
{
value,
label: `${regionName} · ${countryName}`,
searchText: `${regionName} ${countryName} ${englishCountryName} ${value}`,
},
];
});
},
);
@@ -1,3 +1,4 @@
import { runtimeText } from '@/i18n/runtime';
import type { WAFRuleGraph, WAFRuleNode } from '@/lib/services/openflare';
import { UA_BROWSER_LABELS, UA_OS_LABELS } from './ua-options';
@@ -39,25 +40,33 @@ export function validateGraph(graph: WAFRuleGraph): GraphIssue[] {
const issues: GraphIssue[] = [];
const nodeMap = new Map(graph.nodes.map((node) => [node.id, node]));
if (graph.schema_version !== 1)
issues.push({ code: 'schema', message: '规则图 schema_version 必须为 1' });
issues.push({
code: 'schema',
message: runtimeText('rule_graph_schema_version_must_be_1_ea9a1161'),
});
if (
graph.nodes.length > 128 ||
graph.edges.length > 256 ||
new TextEncoder().encode(JSON.stringify(graph)).length > 256 * 1024
)
issues.push({ code: 'size_limit', message: '规则图超过大小限制' });
issues.push({
code: 'size_limit',
message: runtimeText('rule_graph_exceeds_the_size_limit_337651b9'),
});
const nodeIds = new Set<string>();
for (const node of graph.nodes) {
if (!node.id.trim())
issues.push({
code: 'empty_id',
message: '节点 ID 不能为空',
message: runtimeText('node_id_must_not_be_empty_51a5de58'),
nodeId: node.id,
});
if (nodeIds.has(node.id))
issues.push({
code: 'duplicate_node_id',
message: `节点 ID ${node.id} 重复`,
message: runtimeText('duplicate_node_id_value0_621230af', {
value0: node.id,
}),
nodeId: node.id,
});
nodeIds.add(node.id);
@@ -74,20 +83,22 @@ export function validateGraph(graph: WAFRuleGraph): GraphIssue[] {
if (!edge.id.trim())
issues.push({
code: 'empty_id',
message: '连线 ID 不能为空',
message: runtimeText('edge_id_must_not_be_empty_bc8f69cb'),
edgeId: edge.id,
});
if (edgeIds.has(edge.id))
issues.push({
code: 'duplicate_edge_id',
message: `连线 ID ${edge.id} 重复`,
message: runtimeText('duplicate_edge_id_value0_0a9d1c7c', {
value0: edge.id,
}),
edgeId: edge.id,
});
edgeIds.add(edge.id);
if (nodeMap.get(edge.target)?.type === 'start')
issues.push({
code: 'start_incoming',
message: '开始节点不能有入边',
message: runtimeText('the_start_node_must_not_have_incoming_50a07b17'),
edgeId: edge.id,
nodeId: edge.target,
});
@@ -95,12 +106,12 @@ export function validateGraph(graph: WAFRuleGraph): GraphIssue[] {
if (graph.nodes.filter((node) => node.type === 'start').length !== 1)
issues.push({
code: 'start_count',
message: '规则图必须恰好有一个开始节点',
message: runtimeText('the_rule_graph_must_contain_exactly_one_7dfbc027'),
});
if (graph.nodes.filter((node) => node.type === 'allow').length !== 1)
issues.push({
code: 'allow_count',
message: '规则图必须恰好有一个通过节点',
message: runtimeText('the_rule_graph_must_contain_exactly_one_0036eb82'),
});
for (const edge of graph.edges) {
@@ -112,7 +123,10 @@ export function validateGraph(graph: WAFRuleGraph): GraphIssue[] {
) {
issues.push({
code: 'invalid_edge',
message: `连线 ${edge.id} 的端点或出口无效`,
message: runtimeText(
'edge_value0_has_an_invalid_endpoint_or_9d84eb7e',
{ value0: edge.id },
),
edgeId: edge.id,
});
}
@@ -125,13 +139,19 @@ export function validateGraph(graph: WAFRuleGraph): GraphIssue[] {
if (outgoing.length === 0)
issues.push({
code: 'missing_handle',
message: `节点 ${node.id} 的 ${handle} 出口未连接`,
message: runtimeText(
'node_value0_output_value1_is_not_connected_c3038e81',
{ value0: node.id, value1: handle },
),
nodeId: node.id,
});
if (outgoing.length > 1)
issues.push({
code: 'duplicate_handle',
message: `节点 ${node.id} 的 ${handle} 出口只能连接一次`,
message: runtimeText(
'node_value0_output_value1_can_only_be_903e54ce',
{ value0: node.id, value1: handle },
),
nodeId: node.id,
});
}
@@ -151,7 +171,10 @@ export function validateGraph(graph: WAFRuleGraph): GraphIssue[] {
if (!reachable.has(node.id))
issues.push({
code: 'unreachable',
message: `节点 ${node.id} 无法从开始节点到达`,
message: runtimeText(
'node_value0_is_unreachable_from_the_start_086531dc',
{ value0: node.id },
),
nodeId: node.id,
});
const terminals = graph.nodes
@@ -162,18 +185,27 @@ export function validateGraph(graph: WAFRuleGraph): GraphIssue[] {
if (!canTerminate.has(node.id))
issues.push({
code: 'non_terminating',
message: `节点 ${node.id} 无法抵达终止节点`,
message: runtimeText(
'node_value0_cannot_reach_a_terminal_node_8de2ff6e',
{ value0: node.id },
),
nodeId: node.id,
});
if (hasCycle(graph))
issues.push({ code: 'cycle', message: '规则图不能包含循环' });
issues.push({
code: 'cycle',
message: runtimeText('the_rule_graph_must_not_contain_cycles_fd6fe797'),
});
return issues;
}
function validateNodeConfig(node: WAFRuleNode): string | undefined {
if (node.type === 'ip_match') {
if (node.config.ips.some((value) => !isIP(value)))
return `节点 ${node.id} 包含无效 IP`;
return runtimeText(
'node_value0_contains_an_invalid_ip_address_1873ab94',
{ value0: node.id },
);
if (
node.config.cidrs.some((value) => {
const parts = value.split('/');
@@ -186,9 +218,13 @@ function validateNodeConfig(node: WAFRuleNode): string | undefined {
);
})
)
return `节点 ${node.id} 包含无效 CIDR`;
return runtimeText('node_value0_contains_an_invalid_cidr_00c880d9', {
value0: node.id,
});
if (node.config.ip_group_ids.some((id) => !Number.isInteger(id) || id <= 0))
return `节点 ${node.id} 包含无效 IP 组`;
return runtimeText('node_value0_contains_an_invalid_ip_group_589219a5', {
value0: node.id,
});
}
if (
node.type === 'geo_match' &&
@@ -197,7 +233,10 @@ function validateNodeConfig(node: WAFRuleNode): string | undefined {
(code) => !/^[A-Z]{2}-[A-Z0-9]{1,3}$/.test(code),
))
)
return `节点 ${node.id} 包含无效地域代码`;
return runtimeText(
'node_value0_contains_an_invalid_geography_code_1a9f469b',
{ value0: node.id },
);
if (
node.type === 'pow' &&
(!['fast', 'slow'].includes(node.config.algorithm) ||
@@ -205,37 +244,61 @@ function validateNodeConfig(node: WAFRuleNode): string | undefined {
!isIntegerInRange(node.config.session_ttl, 60) ||
!isIntegerInRange(node.config.challenge_ttl, 30))
)
return `节点 ${node.id} 的 PoW 配置超出范围`;
return runtimeText('node_value0_has_pow_settings_outside_the_9fd2a4cb', {
value0: node.id,
});
if (
node.type === 'block' &&
(!isIntegerInRange(node.config.status_code, 400, 599) ||
new TextEncoder().encode(node.config.response_body).length > 16 * 1024)
)
return `节点 ${node.id} 的阻止响应配置无效`;
return runtimeText(
'node_value0_has_invalid_block_response_settings_ae4c35ca',
{ value0: node.id },
);
if (node.type === 'ua_check') {
if (!['and', 'or'].includes(node.config.match_mode))
return `节点 ${node.id} 的匹配模式必须为 and 或 or`;
return runtimeText('node_value0_match_mode_must_be_and_242c1ae7', {
value0: node.id,
});
if (node.config.browsers.some((label) => !UA_BROWSER_LABELS.has(label)))
return `节点 ${node.id} 包含无效浏览器标签`;
return runtimeText(
'node_value0_contains_an_invalid_browser_tag_4d0e6740',
{ value0: node.id },
);
if (node.config.operating_systems.some((label) => !UA_OS_LABELS.has(label)))
return `节点 ${node.id} 包含无效操作系统标签`;
return runtimeText(
'node_value0_contains_an_invalid_operating_system_45bea1fb',
{ value0: node.id },
);
if (node.config.custom_ua_patterns.length > 32)
return `节点 ${node.id} 的自定义 UA 正则不能超过 32 条`;
return runtimeText('node_value0_allows_at_most_32_custom_497938c6', {
value0: node.id,
});
for (const pattern of node.config.custom_ua_patterns) {
if (!pattern.trim()) return `节点 ${node.id} 的自定义 UA 正则不能为空`;
if (!pattern.trim())
return runtimeText('node_value0_custom_ua_pattern_must_not_a72718be', {
value0: node.id,
});
if (new TextEncoder().encode(pattern).length > 256)
return `节点 ${node.id} 的自定义 UA 正则过长`;
return runtimeText('node_value0_custom_ua_pattern_is_too_c2c83c0e', {
value0: node.id,
});
try {
void new RegExp(pattern);
} catch {
return `节点 ${node.id} 的自定义 UA 正则无效`;
return runtimeText('node_value0_has_an_invalid_custom_ua_c47ffd0d', {
value0: node.id,
});
}
}
if (
node.config.block_custom_ua &&
node.config.custom_ua_patterns.length === 0
)
return `节点 ${node.id} 开启屏蔽自定义 UA 时至少需要一条正则`;
return runtimeText('node_value0_requires_at_least_one_pattern_6114bb93', {
value0: node.id,
});
}
return undefined;
}
@@ -1,29 +1,38 @@
import { describe, expect, it } from 'vitest';
import { getRuntimeTranslator } from '@/i18n/runtime';
import {
createRuleNode,
displayNodeTitle,
NODE_TYPE_LABELS,
parseAddableNodeType,
} from './node-factory';
describe('displayNodeTitle', () => {
it('uses trimmed label when present', () => {
expect(
displayNodeTitle({
type: 'ip_match',
label: ' 办公室 ',
}),
displayNodeTitle(
{
type: 'ip_match',
label: ' 办公室 ',
},
getRuntimeTranslator('en'),
),
).toBe('办公室');
});
it('falls back to type default when label empty', () => {
expect(
displayNodeTitle({
type: 'block',
label: ' ',
}),
).toBe(NODE_TYPE_LABELS.block);
displayNodeTitle(
{
type: 'block',
label: ' ',
},
getRuntimeTranslator('en'),
),
).toBe('Block');
expect(
displayNodeTitle({ type: 'block' }, getRuntimeTranslator('zh-CN')),
).toBe('阻止');
});
});
@@ -7,22 +7,25 @@ export type AddableNodeType = Extract<
'ip_match' | 'geo_match' | 'ua_check' | 'security_check' | 'pow' | 'block'
>;
export const NODE_TYPE_LABELS: Record<WAFRuleNode['type'], string> = {
start: '开始',
ip_match: 'IP 匹配',
geo_match: '地域匹配',
ua_check: 'UA 检查',
security_check: '安全防护',
pow: 'PoW 挑战',
allow: '通过',
block: '阻止',
};
export const NODE_TYPE_LABEL_KEYS = {
start: 'start_d2bb025a',
ip_match: 'ip_match_43f4b6d4',
geo_match: 'geography_match_9acb08c4',
ua_check: 'ua_check_b56dac23',
security_check: 'security_checks_e09822e6',
pow: 'pow_challenge_3c043088',
allow: 'allow_1e9f2561',
block: 'block_2a366d09',
} as const satisfies Record<WAFRuleNode['type'], string>;
export function displayNodeTitle(
node: Pick<WAFRuleNode, 'type' | 'label'>,
translate: (
key: (typeof NODE_TYPE_LABEL_KEYS)[WAFRuleNode['type']],
) => string,
): string {
const custom = node.label?.trim();
return custom || NODE_TYPE_LABELS[node.type];
return custom || translate(NODE_TYPE_LABEL_KEYS[node.type]);
}
export function createRuleNode(
@@ -1,3 +1,4 @@
import { useTranslations } from 'next-intl';
import {
Ban,
Fingerprint,
@@ -10,7 +11,7 @@ import {
import { Button } from '@/components/ui/button';
import {
NODE_TYPE_LABELS,
NODE_TYPE_LABEL_KEYS,
WAF_NODE_DRAG_MIME,
type AddableNodeType,
} from './node-factory';
@@ -25,6 +26,7 @@ const items = [
] satisfies { type: AddableNodeType; icon: typeof Fingerprint }[];
export function NodeLibrary() {
const rt = useTranslations('runtime');
return (
<div className='flex items-center gap-2'>
{items.map(({ type, icon: Icon }) => (
@@ -42,7 +44,7 @@ export function NodeLibrary() {
}}
>
<Icon data-icon='inline-start' />
{NODE_TYPE_LABELS[type]}
{rt(NODE_TYPE_LABEL_KEYS[type])}
</Button>
))}
</div>
@@ -1,6 +1,6 @@
import { CircleHelp, Settings2 } from 'lucide-react';
import { useTranslations } from 'next-intl';
import { useState } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { useMemo, useState } from 'react';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
@@ -35,8 +35,8 @@ import {
} from '@/components/ui/tooltip';
import type { WAFIPGroup, WAFRuleNode } from '@/lib/services/openflare';
import { countryOptions, regionOptions, type GeoOption } from './geo-options';
import { NODE_TYPE_LABELS } from './node-factory';
import { createGeoOptions, type GeoOption } from './geo-options';
import { NODE_TYPE_LABEL_KEYS } from './node-factory';
import { UA_BROWSER_OPTIONS, UA_OS_OPTIONS } from './ua-options';
export function NodeProperties({
@@ -78,6 +78,14 @@ function PropertyFields({
onChange: (node: WAFRuleNode) => void;
}) {
const t = useTranslations('waf.editor');
const locale = useLocale();
const { countryOptions, regionOptions } = useMemo(
() =>
node.type === 'geo_match'
? createGeoOptions(locale)
: { countryOptions: [], regionOptions: [] },
[locale, node.type],
);
if (node.type === 'start' || node.type === 'allow')
return (
<p className='text-sm text-muted-foreground'>{t('systemNodeNoConfig')}</p>
@@ -518,13 +526,14 @@ function DisplayNameField({
onChange: (node: WAFRuleNode) => void;
}) {
const t = useTranslations('waf.editor');
const rt = useTranslations('runtime');
return (
<Field>
<FieldLabel htmlFor={`${node.id}-label`}>{t('displayName')}</FieldLabel>
<Input
id={`${node.id}-label`}
value={node.label ?? ''}
placeholder={NODE_TYPE_LABELS[node.type]}
placeholder={rt(NODE_TYPE_LABEL_KEYS[node.type])}
onChange={(event) => onChange({ ...node, label: event.target.value })}
/>
</Field>
@@ -1,4 +1,5 @@
import { Handle, Position, type NodeProps } from '@xyflow/react';
import { useTranslations } from 'next-intl';
import {
Ban,
Fingerprint,
@@ -42,10 +43,11 @@ const outputHandles: Partial<Record<WAFRuleNode['type'], string[]>> = {
};
export function RuleNode({ data, selected }: NodeProps) {
const rt = useTranslations('runtime');
const value = data as RuleFlowNodeData;
const { rule, issues } = value;
const { icon: Icon } = meta[rule.type];
const title = displayNodeTitle(rule);
const title = displayNodeTitle(rule, rt);
return (
<div
className={cn(
@@ -1,3 +1,4 @@
import { runtimeText } from '@/i18n/runtime';
export const UA_BROWSER_OPTIONS = [
{ value: 'Chrome', label: 'Chrome' },
{ value: 'Safari', label: 'Safari' },
@@ -5,7 +6,12 @@ export const UA_BROWSER_OPTIONS = [
{ value: 'Edge', label: 'Edge' },
{ value: 'Opera', label: 'Opera' },
{ value: 'Chromium', label: 'Chromium' },
{ value: 'WeChat', label: '微信' },
{
value: 'WeChat',
get label() {
return runtimeText('wechat_81b430b6');
},
},
{ value: 'Postman', label: 'Postman' },
{ value: 'CLI', label: 'CLI' },
{ value: 'Bot', label: 'Bot' },
@@ -219,8 +219,8 @@ function EditorContent() {
<ArrowLeft className='size-3.5' />
{t('back')}
</Button>
<div className='flex items-center justify-between gap-4'>
<div className='flex min-w-0 items-center gap-2'>
<div className='flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between'>
<div className='flex min-w-0 flex-wrap items-center gap-2'>
<GitBranch className='size-5 text-primary' />
<h1 className='text-2xl font-semibold tracking-tight'>
{ruleQuery.data.name}
@@ -235,7 +235,7 @@ function EditorContent() {
</Badge>
{dirty && <Badge variant='secondary'>{t('unsaved')}</Badge>}
</div>
<div className='flex shrink-0 items-center gap-2'>
<div className='flex flex-wrap items-center gap-2 xl:shrink-0'>
<div className='flex items-center gap-2'>
<Switch
id='rule-enabled'
@@ -1,5 +1,6 @@
'use client';
import { getFormattingLocale } from '@/i18n/format';
import { useMemo, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Activity, HardDrive, Users } from 'lucide-react';
@@ -31,13 +32,13 @@ function formatAxisLabel(iso: string, range: ZoneStatsRange) {
return '';
}
if (range === '24h') {
return date.toLocaleTimeString('en-US', {
return date.toLocaleTimeString(getFormattingLocale(), {
hour: 'numeric',
minute: undefined,
hour12: true,
});
}
return date.toLocaleDateString('en-GB', {
return date.toLocaleDateString(getFormattingLocale(), {
day: 'numeric',
month: 'short',
});
@@ -54,7 +55,10 @@ function formatWindowLabel(startedAt?: string, endedAt?: string) {
}
const fmt = (value: Date) =>
value
.toLocaleDateString('en-GB', { day: 'numeric', month: 'long' })
.toLocaleDateString(getFormattingLocale(), {
day: 'numeric',
month: 'long',
})
.toUpperCase();
return `${fmt(start)} — ${fmt(end)}`;
}
@@ -1,3 +1,4 @@
import { runtimeText } from '@/i18n/runtime';
import type {
TlsCertificateFileImportPayload,
TlsCertificateItem,
@@ -17,7 +18,8 @@ export type TranslateFn = (
export function getErrorMessage(error: unknown, fallback?: string) {
return error instanceof Error
? error.message
: (fallback ?? '请求失败,请稍后重试。');
: (fallback ??
runtimeText('request_failed_please_try_again_later_8977b79a'));
}
export function getMatchTypeMeta(domain: string): {
@@ -25,8 +27,8 @@ export function getMatchTypeMeta(domain: string): {
tone: StatusTone;
} {
return domain.startsWith('*.')
? { label: '通配符', tone: 'warning' }
: { label: '精确匹配', tone: 'info' };
? { label: runtimeText('wildcard_c6b0739e'), tone: 'warning' }
: { label: runtimeText('exact_match_391fe725'), tone: 'info' };
}
export function getCertificateStatus(
@@ -57,7 +59,10 @@ export function getCertificateStatus(
export function buildCertificateLabel(certificate: TlsCertificateItem) {
return certificate.not_after
? `${certificate.name}(到期:${formatDateTime(certificate.not_after)})`
? runtimeText('value0_expires_value1_7d8600f8', {
value0: certificate.name,
value1: formatDateTime(certificate.not_after),
})
: certificate.name;
}