mirror of
https://github.com/Rain-kl/OpenFlare.git
synced 2026-10-04 15:06:37 +08:00
fix(waf): complete geography match options
Use full country and ISO subdivision data, show localized country names with codes, and add searchable region selection.
This commit is contained in:
@@ -0,0 +1,23 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { countryOptions, regionOptions } from './geo-options';
|
||||
|
||||
describe('geo options', () => {
|
||||
it('contains the complete country list with localized names', () => {
|
||||
expect(countryOptions).toHaveLength(249);
|
||||
expect(countryOptions).toContainEqual(
|
||||
expect.objectContaining({ value: 'CN', label: '中国' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('contains searchable ISO subdivision options', () => {
|
||||
expect(regionOptions.length).toBeGreaterThan(4000);
|
||||
expect(regionOptions).toContainEqual(
|
||||
expect.objectContaining({
|
||||
value: 'CN-BJ',
|
||||
label: expect.stringContaining('Beijing'),
|
||||
searchText: expect.stringContaining('中国'),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
import { allCountries } from 'country-region-data';
|
||||
|
||||
export interface GeoOption {
|
||||
value: string;
|
||||
label: string;
|
||||
searchText: string;
|
||||
}
|
||||
|
||||
const countryCodePattern = /^[A-Z]{2}$/;
|
||||
const regionCodePattern = /^[A-Z0-9]{1,3}$/;
|
||||
const countryDisplayNames = new Intl.DisplayNames(['zh-CN'], {
|
||||
type: 'region',
|
||||
});
|
||||
|
||||
function localizedCountryName(code: string, fallback: string) {
|
||||
const localized = countryDisplayNames.of(code);
|
||||
return !localized || localized === code ? fallback : localized;
|
||||
}
|
||||
|
||||
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}`,
|
||||
},
|
||||
];
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -52,7 +52,7 @@ it('creates any normalized valid geography code', async () => {
|
||||
const onChange = vi.fn();
|
||||
render(<NodeProperties node={node} ipGroups={[]} onChange={onChange} />);
|
||||
fireEvent.click(screen.getByRole('button', { name: '国家代码' }));
|
||||
fireEvent.change(await screen.findByPlaceholderText('输入代码并添加'), {
|
||||
fireEvent.change(await screen.findByPlaceholderText('搜索名称或代码'), {
|
||||
target: { value: 'nz' },
|
||||
});
|
||||
fireEvent.click(screen.getByRole('button', { name: '添加代码' }));
|
||||
@@ -62,3 +62,17 @@ it('creates any normalized valid geography code', async () => {
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('shows localized country names together with their codes', async () => {
|
||||
const node: WAFRuleNode = {
|
||||
id: 'geo',
|
||||
type: 'geo_match',
|
||||
position: { x: 0, y: 0 },
|
||||
config: { countries: [], regions: [] },
|
||||
};
|
||||
render(<NodeProperties node={node} ipGroups={[]} onChange={vi.fn()} />);
|
||||
fireEvent.click(screen.getByRole('button', { name: '国家代码' }));
|
||||
expect(await screen.findByText('中国')).toBeInTheDocument();
|
||||
expect(screen.getByText('CN')).toBeInTheDocument();
|
||||
expect(screen.getByText(/共 249 个国家\/地区/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -28,32 +28,7 @@ import { Separator } from '@/components/ui/separator';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import type { WAFIPGroup, WAFRuleNode } from '@/lib/services/openflare';
|
||||
|
||||
const countries = [
|
||||
'CN',
|
||||
'US',
|
||||
'JP',
|
||||
'SG',
|
||||
'DE',
|
||||
'FR',
|
||||
'GB',
|
||||
'CA',
|
||||
'AU',
|
||||
'BR',
|
||||
'IN',
|
||||
'KR',
|
||||
].map((value) => ({ value, label: value }));
|
||||
const regions = [
|
||||
'CN-BJ',
|
||||
'CN-SH',
|
||||
'CN-GD',
|
||||
'CN-ZJ',
|
||||
'US-CA',
|
||||
'US-NY',
|
||||
'US-TX',
|
||||
'JP-13',
|
||||
'DE-BE',
|
||||
'GB-ENG',
|
||||
].map((value) => ({ value, label: value }));
|
||||
import { countryOptions, regionOptions, type GeoOption } from './geo-options';
|
||||
|
||||
export function NodeProperties({
|
||||
node,
|
||||
@@ -119,6 +94,7 @@ function PropertyFields({
|
||||
options={ipGroups.map((group) => ({
|
||||
value: String(group.id),
|
||||
label: group.name,
|
||||
searchText: `${group.name} ${group.id}`,
|
||||
}))}
|
||||
value={node.config.ip_group_ids.map(String)}
|
||||
onChange={(values) =>
|
||||
@@ -136,7 +112,8 @@ function PropertyFields({
|
||||
<MultiSelect
|
||||
id={`${node.id}-countries`}
|
||||
label='国家代码'
|
||||
options={countries}
|
||||
description={`共 ${countryOptions.length} 个国家/地区,显示国家名与 ISO 代码`}
|
||||
options={countryOptions}
|
||||
value={node.config.countries}
|
||||
creatablePattern={/^[A-Z]{2}$/}
|
||||
onChange={(countries) =>
|
||||
@@ -146,9 +123,11 @@ function PropertyFields({
|
||||
<MultiSelect
|
||||
id={`${node.id}-regions`}
|
||||
label='地区代码'
|
||||
options={regions}
|
||||
description={`共 ${regionOptions.length} 个一级行政区,输入名称或代码搜索`}
|
||||
options={regionOptions}
|
||||
value={node.config.regions}
|
||||
creatablePattern={/^[A-Z]{2}-[A-Z0-9]{1,3}$/}
|
||||
searchRequired
|
||||
onChange={(regions) =>
|
||||
onChange({ ...node, config: { ...node.config, regions } })
|
||||
}
|
||||
@@ -297,28 +276,41 @@ function NumberField({
|
||||
function MultiSelect({
|
||||
id,
|
||||
label,
|
||||
description,
|
||||
options,
|
||||
value,
|
||||
creatablePattern,
|
||||
searchRequired = false,
|
||||
onChange,
|
||||
}: {
|
||||
id: string;
|
||||
label: string;
|
||||
options: { value: string; label: string }[];
|
||||
description?: string;
|
||||
options: GeoOption[];
|
||||
value: string[];
|
||||
creatablePattern?: RegExp;
|
||||
searchRequired?: boolean;
|
||||
onChange: (value: string[]) => void;
|
||||
}) {
|
||||
const [draft, setDraft] = useState('');
|
||||
const normalized = draft.trim().toUpperCase();
|
||||
const visible = [
|
||||
const query = draft.trim().toLocaleLowerCase();
|
||||
const available = [
|
||||
...options,
|
||||
...value
|
||||
.filter(
|
||||
(selected) => !options.some((option) => option.value === selected),
|
||||
)
|
||||
.map((selected) => ({ value: selected, label: selected })),
|
||||
.map((selected) => ({
|
||||
value: selected,
|
||||
label: selected,
|
||||
searchText: selected,
|
||||
})),
|
||||
];
|
||||
const visible = available.filter((option) => {
|
||||
if (!query) return !searchRequired || value.includes(option.value);
|
||||
return option.searchText.toLocaleLowerCase().includes(query);
|
||||
});
|
||||
const canCreate = Boolean(
|
||||
creatablePattern?.test(normalized) && !value.includes(normalized),
|
||||
);
|
||||
@@ -331,57 +323,68 @@ function MultiSelect({
|
||||
{value.length ? `已选择 ${value.length} 项` : '请选择'}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
align='start'
|
||||
className='flex max-h-64 flex-col gap-2 overflow-y-auto'
|
||||
>
|
||||
{creatablePattern && (
|
||||
<PopoverContent align='start' className='flex w-80 flex-col gap-2 p-3'>
|
||||
{(creatablePattern || options.length > 0) && (
|
||||
<div className='flex gap-2'>
|
||||
<Input
|
||||
aria-label={`新建${label}`}
|
||||
placeholder='输入代码并添加'
|
||||
placeholder='搜索名称或代码'
|
||||
value={draft}
|
||||
onChange={(event) => setDraft(event.target.value)}
|
||||
/>
|
||||
<Button
|
||||
size='sm'
|
||||
disabled={!canCreate}
|
||||
onClick={() => {
|
||||
onChange([...value, normalized]);
|
||||
setDraft('');
|
||||
}}
|
||||
>
|
||||
添加代码
|
||||
</Button>
|
||||
{creatablePattern && (
|
||||
<Button
|
||||
size='sm'
|
||||
disabled={!canCreate}
|
||||
onClick={() => {
|
||||
onChange([...value, normalized]);
|
||||
setDraft('');
|
||||
}}
|
||||
>
|
||||
添加代码
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{visible.length === 0 ? (
|
||||
<p className='text-sm text-muted-foreground'>暂无可选项</p>
|
||||
) : (
|
||||
visible.map((option) => (
|
||||
<label
|
||||
key={option.value}
|
||||
className='flex cursor-pointer items-center gap-2 text-sm'
|
||||
>
|
||||
<Checkbox
|
||||
checked={value.includes(option.value)}
|
||||
onCheckedChange={(checked) =>
|
||||
onChange(
|
||||
checked
|
||||
? [...value, option.value]
|
||||
: value.filter((item) => item !== option.value),
|
||||
)
|
||||
}
|
||||
/>
|
||||
<span>{option.label}</span>
|
||||
<span className='ml-auto font-mono text-xs text-muted-foreground'>
|
||||
{option.value}
|
||||
</span>
|
||||
</label>
|
||||
))
|
||||
)}
|
||||
<div className='max-h-56 space-y-1 overflow-y-auto pr-1'>
|
||||
{visible.length === 0 ? (
|
||||
<p className='px-1 py-3 text-sm text-muted-foreground'>
|
||||
{searchRequired && !query
|
||||
? `输入名称或代码搜索 ${options.length} 个选项`
|
||||
: '没有匹配的选项'}
|
||||
</p>
|
||||
) : (
|
||||
visible.map((option) => (
|
||||
<label
|
||||
key={option.value}
|
||||
className='flex min-h-8 cursor-pointer items-center gap-2 rounded-md px-1 text-sm hover:bg-accent'
|
||||
>
|
||||
<Checkbox
|
||||
checked={value.includes(option.value)}
|
||||
onCheckedChange={(checked) =>
|
||||
onChange(
|
||||
checked
|
||||
? [...value, option.value]
|
||||
: value.filter((item) => item !== option.value),
|
||||
)
|
||||
}
|
||||
/>
|
||||
<span
|
||||
className='min-w-0 flex-1 truncate'
|
||||
title={option.label}
|
||||
>
|
||||
{option.label}
|
||||
</span>
|
||||
<span className='font-mono text-xs text-muted-foreground'>
|
||||
{option.value}
|
||||
</span>
|
||||
</label>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
{description && <FieldDescription>{description}</FieldDescription>}
|
||||
</Field>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -51,6 +51,7 @@
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "^1.1.1",
|
||||
"country-region-data": "^4.1.0",
|
||||
"date-fns": "^4.1.0",
|
||||
"echarts": "^6.1.0",
|
||||
"echarts-for-react": "^3.0.6",
|
||||
|
||||
Generated
+8
@@ -122,6 +122,9 @@ importers:
|
||||
cmdk:
|
||||
specifier: ^1.1.1
|
||||
version: 1.1.1(@types/react-dom@19.2.2(@types/react@19.2.2))(@types/react@19.2.2)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
|
||||
country-region-data:
|
||||
specifier: ^4.1.0
|
||||
version: 4.1.0
|
||||
date-fns:
|
||||
specifier: ^4.1.0
|
||||
version: 4.1.0
|
||||
@@ -2399,6 +2402,9 @@ packages:
|
||||
core-js@3.47.0:
|
||||
resolution: {integrity: sha512-c3Q2VVkGAUyupsjRnaNX6u8Dq2vAdzm9iuPj5FW0fRxzlxgq9Q39MDq10IvmQSpLgHQNyQzQmOo6bgGHmH3NNg==}
|
||||
|
||||
country-region-data@4.1.0:
|
||||
resolution: {integrity: sha512-20fGwnpj5Q3HlQTHdMUstpD4pixphymWBj1f9/EonKEvnEDCaq1S3peE1O7NLxHI1zSa6W+5do/u7xS7UVfZtw==}
|
||||
|
||||
crelt@1.0.6:
|
||||
resolution: {integrity: sha512-VQ2MBenTq1fWZUH9DJNGti7kKv6EeAuYr3cLwxUWhIu1baTaXh4Ib5W2CqHVqib4/MqbYGJqiL3Zb8GJZr3l4g==}
|
||||
|
||||
@@ -6670,6 +6676,8 @@ snapshots:
|
||||
core-js@3.47.0:
|
||||
optional: true
|
||||
|
||||
country-region-data@4.1.0: {}
|
||||
|
||||
crelt@1.0.6: {}
|
||||
|
||||
cross-spawn@7.0.6:
|
||||
|
||||
Reference in New Issue
Block a user