mirror of
https://github.com/Rain-kl/OpenFlare.git
synced 2026-10-03 23:06:36 +08:00
feat: add geo_manual_override to NodeItem and NodeMutationPayload
fix: update default GeoIPProvider to ipinfo in settings feat: implement WorldStageMap component for visualizing node health on a world map feat: create NodeEditorModal for editing node details with manual geo location options docs: update app-config documentation to reflect changes in GeoIPProvider default value
This commit is contained in:
@@ -2,11 +2,8 @@
|
||||
|
||||
import Link from 'next/link';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useForm, useWatch } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { RankChart } from '@/components/data/rank-chart';
|
||||
import { TrendChart } from '@/components/data/trend-chart';
|
||||
@@ -31,9 +28,9 @@ import {
|
||||
requestNodeAgentUpdate,
|
||||
updateNode,
|
||||
} from '@/features/nodes/api/nodes';
|
||||
import { NodeEditorModal } from '@/features/nodes/components/node-editor-modal';
|
||||
import type {
|
||||
NodeAgentReleaseInfo,
|
||||
NodeMutationPayload,
|
||||
NodeObservability,
|
||||
} from '@/features/nodes/types';
|
||||
import {
|
||||
@@ -43,7 +40,6 @@ import {
|
||||
ResourceField,
|
||||
ResourceInput,
|
||||
SecondaryButton,
|
||||
ToggleField,
|
||||
} from '@/features/shared/components/resource-primitives';
|
||||
import type { ReleaseChannel } from '@/features/update/types';
|
||||
import { formatDateTime, formatRelativeTime } from '@/lib/utils/date';
|
||||
@@ -62,17 +58,6 @@ import {
|
||||
|
||||
const nodesQueryKey = ['nodes'];
|
||||
|
||||
const nodeSchema = z.object({
|
||||
name: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1, '请输入节点名')
|
||||
.max(128, '节点名不能超过 128 个字符'),
|
||||
auto_update_enabled: z.boolean(),
|
||||
});
|
||||
|
||||
type NodeFormValues = z.infer<typeof nodeSchema>;
|
||||
|
||||
type FeedbackState = {
|
||||
tone: 'info' | 'success' | 'danger';
|
||||
message: string;
|
||||
@@ -80,32 +65,10 @@ type FeedbackState = {
|
||||
|
||||
type HealthEventFilter = 'all' | 'active' | 'resolved';
|
||||
|
||||
const defaultValues: NodeFormValues = {
|
||||
name: '',
|
||||
auto_update_enabled: false,
|
||||
};
|
||||
|
||||
function getErrorMessage(error: unknown) {
|
||||
return error instanceof Error ? error.message : '请求失败,请稍后重试。';
|
||||
}
|
||||
|
||||
function toPayload(
|
||||
values: NodeFormValues,
|
||||
currentNode?: {
|
||||
geo_name?: string;
|
||||
geo_latitude?: number | null;
|
||||
geo_longitude?: number | null;
|
||||
} | null,
|
||||
): NodeMutationPayload {
|
||||
return {
|
||||
name: values.name.trim(),
|
||||
auto_update_enabled: values.auto_update_enabled,
|
||||
geo_name: currentNode?.geo_name ?? '',
|
||||
geo_latitude: currentNode?.geo_latitude ?? null,
|
||||
geo_longitude: currentNode?.geo_longitude ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
async function copyToClipboard(value: string) {
|
||||
await navigator.clipboard.writeText(value);
|
||||
}
|
||||
@@ -303,16 +266,6 @@ export function NodeDetailPage({ nodeId }: { nodeId: string }) {
|
||||
const [healthEventFilter, setHealthEventFilter] =
|
||||
useState<HealthEventFilter>('all');
|
||||
|
||||
const form = useForm<NodeFormValues>({
|
||||
resolver: zodResolver(nodeSchema),
|
||||
defaultValues,
|
||||
});
|
||||
|
||||
const watchedAutoUpdate = useWatch({
|
||||
control: form.control,
|
||||
name: 'auto_update_enabled',
|
||||
});
|
||||
|
||||
const nodesQuery = useQuery({
|
||||
queryKey: nodesQueryKey,
|
||||
queryFn: getNodes,
|
||||
@@ -364,27 +317,12 @@ export function NodeDetailPage({ nodeId }: { nodeId: string }) {
|
||||
}
|
||||
}, [serverUrl]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!node || isEditorOpen) {
|
||||
return;
|
||||
}
|
||||
|
||||
form.reset({
|
||||
name: node.name,
|
||||
auto_update_enabled: node.auto_update_enabled,
|
||||
});
|
||||
}, [form, isEditorOpen, node]);
|
||||
|
||||
const saveMutation = useMutation({
|
||||
mutationFn: async (values: NodeFormValues) =>
|
||||
updateNode(Number(nodeId), toPayload(values, node)),
|
||||
mutationFn: async (payload: Parameters<typeof updateNode>[1]) =>
|
||||
updateNode(Number(nodeId), payload),
|
||||
onSuccess: async (updatedNode) => {
|
||||
setFeedback({ tone: 'success', message: '节点已更新。' });
|
||||
setIsEditorOpen(false);
|
||||
form.reset({
|
||||
name: updatedNode.name,
|
||||
auto_update_enabled: updatedNode.auto_update_enabled,
|
||||
});
|
||||
await queryClient.invalidateQueries({ queryKey: nodesQueryKey });
|
||||
},
|
||||
onError: (error) => {
|
||||
@@ -445,11 +383,6 @@ export function NodeDetailPage({ nodeId }: { nodeId: string }) {
|
||||
},
|
||||
});
|
||||
|
||||
const handleSubmit = form.handleSubmit((values) => {
|
||||
setFeedback(null);
|
||||
saveMutation.mutate(values);
|
||||
});
|
||||
|
||||
const handleDelete = () => {
|
||||
if (!node) {
|
||||
return;
|
||||
@@ -1697,59 +1630,19 @@ export function NodeDetailPage({ nodeId }: { nodeId: string }) {
|
||||
onClose={() => setIsTargetSnapshotOpen(false)}
|
||||
/>
|
||||
|
||||
<AppModal
|
||||
<NodeEditorModal
|
||||
isOpen={isEditorOpen}
|
||||
node={node}
|
||||
isSubmitting={saveMutation.isPending}
|
||||
onClose={() => setIsEditorOpen(false)}
|
||||
title="编辑"
|
||||
title="编辑节点"
|
||||
description="更新模式和节点名都在详情页维护。"
|
||||
footer={
|
||||
<div className="flex flex-wrap justify-end gap-3">
|
||||
<SecondaryButton
|
||||
type="button"
|
||||
onClick={() => setIsEditorOpen(false)}
|
||||
disabled={saveMutation.isPending}
|
||||
>
|
||||
取消
|
||||
</SecondaryButton>
|
||||
<PrimaryButton
|
||||
type="submit"
|
||||
form="node-detail-editor-form"
|
||||
disabled={saveMutation.isPending}
|
||||
>
|
||||
{saveMutation.isPending ? '保存中...' : '保存修改'}
|
||||
</PrimaryButton>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<form
|
||||
id="node-detail-editor-form"
|
||||
className="space-y-5"
|
||||
onSubmit={handleSubmit}
|
||||
>
|
||||
<ResourceField
|
||||
label="节点名"
|
||||
hint="示例:shanghai-edge-1"
|
||||
error={form.formState.errors.name?.message}
|
||||
>
|
||||
<ResourceInput
|
||||
placeholder="shanghai-edge-1"
|
||||
{...form.register('name')}
|
||||
/>
|
||||
</ResourceField>
|
||||
|
||||
<ToggleField
|
||||
label="启用自动更新"
|
||||
description="开启后 Agent 心跳返回会提示节点自动执行自更新。"
|
||||
checked={watchedAutoUpdate}
|
||||
onChange={(checked) =>
|
||||
form.setValue('auto_update_enabled', checked, {
|
||||
shouldDirty: true,
|
||||
shouldValidate: true,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</form>
|
||||
</AppModal>
|
||||
submitLabel="保存修改"
|
||||
onSubmit={(payload) => {
|
||||
setFeedback(null);
|
||||
saveMutation.mutate(payload);
|
||||
}}
|
||||
/>
|
||||
|
||||
<AppModal
|
||||
isOpen={isAgentUpdateModalOpen}
|
||||
|
||||
@@ -0,0 +1,438 @@
|
||||
'use client';
|
||||
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useMemo, useEffect } from 'react';
|
||||
import { useForm, useWatch } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { AppModal } from '@/components/ui/app-modal';
|
||||
import worldGeoJson from '@/features/dashboard/data/world-geo.json';
|
||||
import type { NodeItem, NodeMutationPayload } from '@/features/nodes/types';
|
||||
import {
|
||||
PrimaryButton,
|
||||
ResourceField,
|
||||
ResourceInput,
|
||||
ResourceSelect,
|
||||
SecondaryButton,
|
||||
ToggleField,
|
||||
} from '@/features/shared/components/resource-primitives';
|
||||
|
||||
type GeoJsonGeometry = {
|
||||
type: string;
|
||||
coordinates: unknown;
|
||||
};
|
||||
|
||||
type GeoJsonFeature = {
|
||||
geometry?: GeoJsonGeometry;
|
||||
properties?: {
|
||||
name?: string;
|
||||
};
|
||||
};
|
||||
|
||||
type RegionOption = {
|
||||
label: string;
|
||||
latitude: number;
|
||||
longitude: number;
|
||||
};
|
||||
|
||||
const nodeEditorSchema = z
|
||||
.object({
|
||||
name: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1, '请输入节点名')
|
||||
.max(128, '节点名不能超过 128 个字符'),
|
||||
ip: z.string().trim().max(64, '节点 IP 不能超过 64 个字符'),
|
||||
auto_update_enabled: z.boolean(),
|
||||
geo_manual_override: z.boolean(),
|
||||
geo_region: z.string(),
|
||||
geo_name: z.string().trim().max(128, '位置名不能超过 128 个字符'),
|
||||
geo_latitude: z.string().trim(),
|
||||
geo_longitude: z.string().trim(),
|
||||
})
|
||||
.superRefine((values, ctx) => {
|
||||
if (!values.geo_manual_override) {
|
||||
return;
|
||||
}
|
||||
|
||||
const hasLatitude = values.geo_latitude !== '';
|
||||
const hasLongitude = values.geo_longitude !== '';
|
||||
|
||||
if (hasLatitude !== hasLongitude) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['geo_latitude'],
|
||||
message: '纬度和经度需要同时填写',
|
||||
});
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['geo_longitude'],
|
||||
message: '纬度和经度需要同时填写',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (hasLatitude) {
|
||||
const latitude = Number(values.geo_latitude);
|
||||
if (Number.isNaN(latitude) || latitude < -90 || latitude > 90) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['geo_latitude'],
|
||||
message: '纬度必须在 -90 到 90 之间',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (hasLongitude) {
|
||||
const longitude = Number(values.geo_longitude);
|
||||
if (Number.isNaN(longitude) || longitude < -180 || longitude > 180) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['geo_longitude'],
|
||||
message: '经度必须在 -180 到 180 之间',
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
type NodeEditorValues = z.infer<typeof nodeEditorSchema>;
|
||||
|
||||
const defaultValues: NodeEditorValues = {
|
||||
name: '',
|
||||
ip: '',
|
||||
auto_update_enabled: false,
|
||||
geo_manual_override: false,
|
||||
geo_region: '',
|
||||
geo_name: '',
|
||||
geo_latitude: '',
|
||||
geo_longitude: '',
|
||||
};
|
||||
|
||||
function collectPoints(value: unknown, points: Array<[number, number]>) {
|
||||
if (!Array.isArray(value)) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
value.length >= 2 &&
|
||||
typeof value[0] === 'number' &&
|
||||
typeof value[1] === 'number'
|
||||
) {
|
||||
points.push([value[0], value[1]]);
|
||||
return;
|
||||
}
|
||||
for (const item of value) {
|
||||
collectPoints(item, points);
|
||||
}
|
||||
}
|
||||
|
||||
function getRegionCenter(feature: GeoJsonFeature) {
|
||||
const points: Array<[number, number]> = [];
|
||||
collectPoints(feature.geometry?.coordinates, points);
|
||||
if (points.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let minLongitude = Number.POSITIVE_INFINITY;
|
||||
let maxLongitude = Number.NEGATIVE_INFINITY;
|
||||
let minLatitude = Number.POSITIVE_INFINITY;
|
||||
let maxLatitude = Number.NEGATIVE_INFINITY;
|
||||
|
||||
for (const [longitude, latitude] of points) {
|
||||
minLongitude = Math.min(minLongitude, longitude);
|
||||
maxLongitude = Math.max(maxLongitude, longitude);
|
||||
minLatitude = Math.min(minLatitude, latitude);
|
||||
maxLatitude = Math.max(maxLatitude, latitude);
|
||||
}
|
||||
|
||||
return {
|
||||
longitude: Number(((minLongitude + maxLongitude) / 2).toFixed(4)),
|
||||
latitude: Number(((minLatitude + maxLatitude) / 2).toFixed(4)),
|
||||
};
|
||||
}
|
||||
|
||||
function buildRegionOptions() {
|
||||
const features = ((worldGeoJson as { features?: GeoJsonFeature[] }).features ??
|
||||
[]) as GeoJsonFeature[];
|
||||
const options = new Map<string, RegionOption>();
|
||||
|
||||
for (const feature of features) {
|
||||
const label = feature.properties?.name?.trim();
|
||||
if (!label || options.has(label)) {
|
||||
continue;
|
||||
}
|
||||
const center = getRegionCenter(feature);
|
||||
if (!center) {
|
||||
continue;
|
||||
}
|
||||
options.set(label, {
|
||||
label,
|
||||
latitude: center.latitude,
|
||||
longitude: center.longitude,
|
||||
});
|
||||
}
|
||||
|
||||
return Array.from(options.values()).sort((a, b) =>
|
||||
a.label.localeCompare(b.label),
|
||||
);
|
||||
}
|
||||
|
||||
function buildFormValues(node?: Partial<NodeItem> | null): NodeEditorValues {
|
||||
if (!node) {
|
||||
return defaultValues;
|
||||
}
|
||||
|
||||
return {
|
||||
name: node.name ?? '',
|
||||
ip: node.ip ?? '',
|
||||
auto_update_enabled: node.auto_update_enabled ?? false,
|
||||
geo_manual_override: node.geo_manual_override ?? false,
|
||||
geo_region: node.geo_manual_override ? node.geo_name ?? '' : '',
|
||||
geo_name: node.geo_name ?? '',
|
||||
geo_latitude:
|
||||
node.geo_latitude === undefined || node.geo_latitude === null
|
||||
? ''
|
||||
: String(node.geo_latitude),
|
||||
geo_longitude:
|
||||
node.geo_longitude === undefined || node.geo_longitude === null
|
||||
? ''
|
||||
: String(node.geo_longitude),
|
||||
};
|
||||
}
|
||||
|
||||
function toPayload(values: NodeEditorValues): NodeMutationPayload {
|
||||
if (!values.geo_manual_override) {
|
||||
return {
|
||||
name: values.name.trim(),
|
||||
ip: values.ip.trim(),
|
||||
auto_update_enabled: values.auto_update_enabled,
|
||||
geo_manual_override: false,
|
||||
geo_name: '',
|
||||
geo_latitude: null,
|
||||
geo_longitude: null,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
name: values.name.trim(),
|
||||
ip: values.ip.trim(),
|
||||
auto_update_enabled: values.auto_update_enabled,
|
||||
geo_manual_override: true,
|
||||
geo_name: values.geo_name.trim(),
|
||||
geo_latitude:
|
||||
values.geo_latitude.trim() === '' ? null : Number(values.geo_latitude),
|
||||
geo_longitude:
|
||||
values.geo_longitude.trim() === '' ? null : Number(values.geo_longitude),
|
||||
};
|
||||
}
|
||||
|
||||
export function NodeEditorModal({
|
||||
isOpen,
|
||||
node,
|
||||
isSubmitting,
|
||||
title,
|
||||
description,
|
||||
submitLabel,
|
||||
onClose,
|
||||
onSubmit,
|
||||
}: {
|
||||
isOpen: boolean;
|
||||
node?: Partial<NodeItem> | null;
|
||||
isSubmitting: boolean;
|
||||
title: string;
|
||||
description: string;
|
||||
submitLabel: string;
|
||||
onClose: () => void;
|
||||
onSubmit: (payload: NodeMutationPayload) => void;
|
||||
}) {
|
||||
const form = useForm<NodeEditorValues>({
|
||||
resolver: zodResolver(nodeEditorSchema),
|
||||
defaultValues,
|
||||
});
|
||||
|
||||
const watchedAutoUpdate = useWatch({
|
||||
control: form.control,
|
||||
name: 'auto_update_enabled',
|
||||
});
|
||||
const watchedGeoManualOverride = useWatch({
|
||||
control: form.control,
|
||||
name: 'geo_manual_override',
|
||||
});
|
||||
const regionOptions = useMemo(() => buildRegionOptions(), []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen) {
|
||||
return;
|
||||
}
|
||||
form.reset(buildFormValues(node));
|
||||
}, [form, isOpen, node]);
|
||||
|
||||
const handleSubmit = form.handleSubmit((values) => {
|
||||
onSubmit(toPayload(values));
|
||||
});
|
||||
|
||||
return (
|
||||
<AppModal
|
||||
isOpen={isOpen}
|
||||
onClose={onClose}
|
||||
title={title}
|
||||
description={description}
|
||||
footer={
|
||||
<div className="flex flex-wrap justify-end gap-3">
|
||||
<SecondaryButton
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
取消
|
||||
</SecondaryButton>
|
||||
<PrimaryButton
|
||||
type="submit"
|
||||
form="node-editor-form"
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
{isSubmitting ? '保存中...' : submitLabel}
|
||||
</PrimaryButton>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<form id="node-editor-form" className="space-y-5" onSubmit={handleSubmit}>
|
||||
<ResourceField
|
||||
label="节点名"
|
||||
hint="示例:shanghai-edge-1"
|
||||
error={form.formState.errors.name?.message}
|
||||
>
|
||||
<ResourceInput
|
||||
placeholder="shanghai-edge-1"
|
||||
{...form.register('name')}
|
||||
/>
|
||||
</ResourceField>
|
||||
|
||||
<ResourceField
|
||||
label="节点 IP"
|
||||
hint="可手动维护节点当前对外 IP;留空则等待 Agent 注册或心跳自动回填。"
|
||||
error={form.formState.errors.ip?.message}
|
||||
>
|
||||
<ResourceInput placeholder="203.0.113.10" {...form.register('ip')} />
|
||||
</ResourceField>
|
||||
|
||||
<ToggleField
|
||||
label="启用自动更新"
|
||||
description="开启后 Agent 心跳返回会提示节点自动执行自更新。"
|
||||
checked={watchedAutoUpdate}
|
||||
onChange={(checked) =>
|
||||
form.setValue('auto_update_enabled', checked, {
|
||||
shouldDirty: true,
|
||||
shouldValidate: true,
|
||||
})
|
||||
}
|
||||
/>
|
||||
|
||||
<ToggleField
|
||||
label="手动指定地图地区"
|
||||
description="关闭时,节点会根据当前 IP 自动解析归属地;开启后使用你手动选择的地区与坐标。"
|
||||
checked={watchedGeoManualOverride}
|
||||
onChange={(checked) => {
|
||||
form.setValue('geo_manual_override', checked, {
|
||||
shouldDirty: true,
|
||||
shouldValidate: true,
|
||||
});
|
||||
if (!checked) {
|
||||
form.setValue('geo_region', '', { shouldDirty: true });
|
||||
form.setValue('geo_name', '', { shouldDirty: true });
|
||||
form.setValue('geo_latitude', '', { shouldDirty: true });
|
||||
form.setValue('geo_longitude', '', { shouldDirty: true });
|
||||
}
|
||||
}}
|
||||
/>
|
||||
|
||||
{watchedGeoManualOverride ? (
|
||||
<ResourceField
|
||||
label="地区选择"
|
||||
hint="选择后会自动填充位置名与地图坐标,你也可以继续微调。"
|
||||
>
|
||||
<ResourceSelect
|
||||
value={form.watch('geo_region')}
|
||||
onChange={(event) => {
|
||||
const regionName = event.target.value;
|
||||
form.setValue('geo_region', regionName, {
|
||||
shouldDirty: true,
|
||||
});
|
||||
const selectedRegion = regionOptions.find(
|
||||
(item) => item.label === regionName,
|
||||
);
|
||||
if (!selectedRegion) {
|
||||
return;
|
||||
}
|
||||
form.setValue('geo_name', selectedRegion.label, {
|
||||
shouldDirty: true,
|
||||
shouldValidate: true,
|
||||
});
|
||||
form.setValue('geo_latitude', String(selectedRegion.latitude), {
|
||||
shouldDirty: true,
|
||||
shouldValidate: true,
|
||||
});
|
||||
form.setValue(
|
||||
'geo_longitude',
|
||||
String(selectedRegion.longitude),
|
||||
{
|
||||
shouldDirty: true,
|
||||
shouldValidate: true,
|
||||
},
|
||||
);
|
||||
}}
|
||||
>
|
||||
<option value="">请选择地区</option>
|
||||
{regionOptions.map((option) => (
|
||||
<option key={option.label} value={option.label}>
|
||||
{option.label}
|
||||
</option>
|
||||
))}
|
||||
</ResourceSelect>
|
||||
</ResourceField>
|
||||
) : null}
|
||||
|
||||
<ResourceField
|
||||
label="地图位置名"
|
||||
hint={
|
||||
watchedGeoManualOverride
|
||||
? '可在自动填充后继续修改,例如使用更贴近业务的展示名称。'
|
||||
: '自动解析模式下,该字段会由系统根据节点 IP 回填。'
|
||||
}
|
||||
error={form.formState.errors.geo_name?.message}
|
||||
>
|
||||
<ResourceInput
|
||||
placeholder="Shanghai"
|
||||
disabled={!watchedGeoManualOverride}
|
||||
{...form.register('geo_name')}
|
||||
/>
|
||||
</ResourceField>
|
||||
|
||||
<div className="grid gap-5 md:grid-cols-2">
|
||||
<ResourceField
|
||||
label="纬度"
|
||||
hint="范围 -90 到 90,例如上海约为 31.2304"
|
||||
error={form.formState.errors.geo_latitude?.message}
|
||||
>
|
||||
<ResourceInput
|
||||
placeholder="31.2304"
|
||||
disabled={!watchedGeoManualOverride}
|
||||
{...form.register('geo_latitude')}
|
||||
/>
|
||||
</ResourceField>
|
||||
|
||||
<ResourceField
|
||||
label="经度"
|
||||
hint="范围 -180 到 180,例如上海约为 121.4737"
|
||||
error={form.formState.errors.geo_longitude?.message}
|
||||
>
|
||||
<ResourceInput
|
||||
placeholder="121.4737"
|
||||
disabled={!watchedGeoManualOverride}
|
||||
{...form.register('geo_longitude')}
|
||||
/>
|
||||
</ResourceField>
|
||||
</div>
|
||||
</form>
|
||||
</AppModal>
|
||||
);
|
||||
}
|
||||
@@ -2,18 +2,14 @@
|
||||
|
||||
import Link from 'next/link';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useForm, useWatch } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { EmptyState } from '@/components/feedback/empty-state';
|
||||
import { ErrorState } from '@/components/feedback/error-state';
|
||||
import { InlineMessage } from '@/components/feedback/inline-message';
|
||||
import { LoadingState } from '@/components/feedback/loading-state';
|
||||
import { PageHeader } from '@/components/layout/page-header';
|
||||
import { AppModal } from '@/components/ui/app-modal';
|
||||
import { AppCard } from '@/components/ui/app-card';
|
||||
import { StatusBadge } from '@/components/ui/status-badge';
|
||||
import { getConfigVersions } from '@/features/config-versions/api/config-versions';
|
||||
@@ -23,14 +19,11 @@ import {
|
||||
getNodes,
|
||||
updateNode,
|
||||
} from '@/features/nodes/api/nodes';
|
||||
import type { NodeMutationPayload } from '@/features/nodes/types';
|
||||
import { NodeEditorModal } from '@/features/nodes/components/node-editor-modal';
|
||||
import type { NodeItem, NodeMutationPayload } from '@/features/nodes/types';
|
||||
import {
|
||||
DangerButton,
|
||||
PrimaryButton,
|
||||
ResourceField,
|
||||
ResourceInput,
|
||||
SecondaryButton,
|
||||
ToggleField,
|
||||
} from '@/features/shared/components/resource-primitives';
|
||||
import { formatDateTime, formatRelativeTime } from '@/lib/utils/date';
|
||||
import {
|
||||
@@ -53,105 +46,22 @@ const supportedRiskFilters = [
|
||||
|
||||
type NodeRiskFilter = (typeof supportedRiskFilters)[number];
|
||||
|
||||
const nodeSchema = z.object({
|
||||
name: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1, '请输入节点名')
|
||||
.max(128, '节点名不能超过 128 个字符'),
|
||||
auto_update_enabled: z.boolean(),
|
||||
geo_name: z.string().trim().max(128, '位置名不能超过 128 个字符'),
|
||||
geo_latitude: z.string().trim(),
|
||||
geo_longitude: z.string().trim(),
|
||||
}).superRefine((values, ctx) => {
|
||||
const hasLatitude = values.geo_latitude !== '';
|
||||
const hasLongitude = values.geo_longitude !== '';
|
||||
|
||||
if (hasLatitude !== hasLongitude) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['geo_latitude'],
|
||||
message: '纬度和经度需要同时填写',
|
||||
});
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['geo_longitude'],
|
||||
message: '纬度和经度需要同时填写',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (hasLatitude) {
|
||||
const latitude = Number(values.geo_latitude);
|
||||
if (Number.isNaN(latitude) || latitude < -90 || latitude > 90) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['geo_latitude'],
|
||||
message: '纬度必须在 -90 到 90 之间',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (hasLongitude) {
|
||||
const longitude = Number(values.geo_longitude);
|
||||
if (Number.isNaN(longitude) || longitude < -180 || longitude > 180) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['geo_longitude'],
|
||||
message: '经度必须在 -180 到 180 之间',
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
type NodeFormValues = z.infer<typeof nodeSchema>;
|
||||
|
||||
type FeedbackState = {
|
||||
tone: 'info' | 'success' | 'danger';
|
||||
message: string;
|
||||
};
|
||||
|
||||
const defaultValues: NodeFormValues = {
|
||||
name: '',
|
||||
auto_update_enabled: false,
|
||||
geo_name: '',
|
||||
geo_latitude: '',
|
||||
geo_longitude: '',
|
||||
};
|
||||
|
||||
function getErrorMessage(error: unknown) {
|
||||
return error instanceof Error ? error.message : '请求失败,请稍后重试。';
|
||||
}
|
||||
|
||||
function toPayload(values: NodeFormValues): NodeMutationPayload {
|
||||
return {
|
||||
name: values.name.trim(),
|
||||
auto_update_enabled: values.auto_update_enabled,
|
||||
geo_name: values.geo_name.trim(),
|
||||
geo_latitude:
|
||||
values.geo_latitude.trim() === '' ? null : Number(values.geo_latitude),
|
||||
geo_longitude:
|
||||
values.geo_longitude.trim() === '' ? null : Number(values.geo_longitude),
|
||||
};
|
||||
}
|
||||
|
||||
export function NodesPage() {
|
||||
const searchParams = useSearchParams();
|
||||
const queryClient = useQueryClient();
|
||||
const [feedback, setFeedback] = useState<FeedbackState | null>(null);
|
||||
const [editingNodeId, setEditingNodeId] = useState<number | null>(null);
|
||||
const [editingNode, setEditingNode] = useState<NodeItem | null>(null);
|
||||
const [isEditorOpen, setIsEditorOpen] = useState(false);
|
||||
|
||||
const form = useForm<NodeFormValues>({
|
||||
resolver: zodResolver(nodeSchema),
|
||||
defaultValues,
|
||||
});
|
||||
|
||||
const watchedAutoUpdate = useWatch({
|
||||
control: form.control,
|
||||
name: 'auto_update_enabled',
|
||||
});
|
||||
|
||||
const nodesQuery = useQuery({
|
||||
queryKey: nodesQueryKey,
|
||||
queryFn: getNodes,
|
||||
@@ -165,20 +75,18 @@ export function NodesPage() {
|
||||
});
|
||||
|
||||
const saveMutation = useMutation({
|
||||
mutationFn: async (values: NodeFormValues) => {
|
||||
const payload = toPayload(values);
|
||||
return editingNodeId
|
||||
? updateNode(editingNodeId, payload)
|
||||
mutationFn: async (payload: NodeMutationPayload) => {
|
||||
return editingNode
|
||||
? updateNode(editingNode.id, payload)
|
||||
: createNode(payload);
|
||||
},
|
||||
onSuccess: async () => {
|
||||
setFeedback({
|
||||
tone: 'success',
|
||||
message: editingNodeId ? '节点已更新。' : '节点已创建。',
|
||||
message: editingNode ? '节点已更新。' : '节点已创建。',
|
||||
});
|
||||
setEditingNodeId(null);
|
||||
setEditingNode(null);
|
||||
setIsEditorOpen(false);
|
||||
form.reset(defaultValues);
|
||||
await queryClient.invalidateQueries({ queryKey: nodesQueryKey });
|
||||
},
|
||||
onError: (error) => {
|
||||
@@ -190,8 +98,7 @@ export function NodesPage() {
|
||||
mutationFn: deleteNode,
|
||||
onSuccess: async () => {
|
||||
setFeedback({ tone: 'success', message: '节点已删除。' });
|
||||
setEditingNodeId(null);
|
||||
form.reset(defaultValues);
|
||||
setEditingNode(null);
|
||||
await queryClient.invalidateQueries({ queryKey: nodesQueryKey });
|
||||
},
|
||||
onError: (error) => {
|
||||
@@ -247,41 +154,19 @@ export function NodesPage() {
|
||||
|
||||
const handleReset = () => {
|
||||
setFeedback(null);
|
||||
setEditingNodeId(null);
|
||||
setEditingNode(null);
|
||||
setIsEditorOpen(false);
|
||||
form.reset(defaultValues);
|
||||
};
|
||||
|
||||
const handleCreate = () => {
|
||||
setFeedback(null);
|
||||
setEditingNodeId(null);
|
||||
form.reset(defaultValues);
|
||||
setEditingNode(null);
|
||||
setIsEditorOpen(true);
|
||||
};
|
||||
|
||||
const handleEdit = (
|
||||
nodeId: number,
|
||||
name: string,
|
||||
autoUpdateEnabled: boolean,
|
||||
geoName: string,
|
||||
geoLatitude?: number | null,
|
||||
geoLongitude?: number | null,
|
||||
) => {
|
||||
const handleEdit = (node: NodeItem) => {
|
||||
setFeedback(null);
|
||||
setEditingNodeId(nodeId);
|
||||
form.reset({
|
||||
name,
|
||||
auto_update_enabled: autoUpdateEnabled,
|
||||
geo_name: geoName,
|
||||
geo_latitude:
|
||||
geoLatitude === undefined || geoLatitude === null
|
||||
? ''
|
||||
: String(geoLatitude),
|
||||
geo_longitude:
|
||||
geoLongitude === undefined || geoLongitude === null
|
||||
? ''
|
||||
: String(geoLongitude),
|
||||
});
|
||||
setEditingNode(node);
|
||||
setIsEditorOpen(true);
|
||||
};
|
||||
|
||||
@@ -297,12 +182,6 @@ export function NodesPage() {
|
||||
setFeedback(null);
|
||||
deleteMutation.mutate(nodeId);
|
||||
};
|
||||
|
||||
const handleSubmit = form.handleSubmit((values) => {
|
||||
setFeedback(null);
|
||||
saveMutation.mutate(values);
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="space-y-6">
|
||||
@@ -487,16 +366,7 @@ export function NodesPage() {
|
||||
</Link>
|
||||
<SecondaryButton
|
||||
type="button"
|
||||
onClick={() =>
|
||||
handleEdit(
|
||||
node.id,
|
||||
node.name,
|
||||
node.auto_update_enabled,
|
||||
node.geo_name,
|
||||
node.geo_latitude,
|
||||
node.geo_longitude,
|
||||
)
|
||||
}
|
||||
onClick={() => handleEdit(node)}
|
||||
className="px-3 py-2 text-xs"
|
||||
>
|
||||
编辑
|
||||
@@ -520,98 +390,19 @@ export function NodesPage() {
|
||||
)}
|
||||
</AppCard>
|
||||
</div>
|
||||
<AppModal
|
||||
<NodeEditorModal
|
||||
isOpen={isEditorOpen}
|
||||
node={editingNode}
|
||||
isSubmitting={saveMutation.isPending}
|
||||
title={editingNode ? '编辑节点' : '新增节点'}
|
||||
onClose={handleReset}
|
||||
title={editingNodeId ? '编辑节点' : '新增节点'}
|
||||
description="预创建节点后可在详情页查看专属 Token、部署命令与更新控制。"
|
||||
footer={
|
||||
<div className="flex flex-wrap justify-end gap-3">
|
||||
<SecondaryButton
|
||||
type="button"
|
||||
onClick={handleReset}
|
||||
disabled={saveMutation.isPending}
|
||||
>
|
||||
取消
|
||||
</SecondaryButton>
|
||||
<PrimaryButton
|
||||
type="submit"
|
||||
form="node-editor-form"
|
||||
disabled={saveMutation.isPending}
|
||||
>
|
||||
{saveMutation.isPending
|
||||
? '保存中...'
|
||||
: editingNodeId
|
||||
? '保存修改'
|
||||
: '新增节点'}
|
||||
</PrimaryButton>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<form
|
||||
id="node-editor-form"
|
||||
className="space-y-5"
|
||||
onSubmit={handleSubmit}
|
||||
>
|
||||
<ResourceField
|
||||
label="节点名"
|
||||
hint="示例:shanghai-edge-1"
|
||||
error={form.formState.errors.name?.message}
|
||||
>
|
||||
<ResourceInput
|
||||
placeholder="shanghai-edge-1"
|
||||
{...form.register('name')}
|
||||
/>
|
||||
</ResourceField>
|
||||
|
||||
<ToggleField
|
||||
label="启用自动更新"
|
||||
description="开启后 Agent 心跳返回会提示节点自动执行自更新。"
|
||||
checked={watchedAutoUpdate}
|
||||
onChange={(checked) =>
|
||||
form.setValue('auto_update_enabled', checked, {
|
||||
shouldDirty: true,
|
||||
shouldValidate: true,
|
||||
})
|
||||
}
|
||||
/>
|
||||
|
||||
<ResourceField
|
||||
label="地图位置名"
|
||||
hint="示例:Shanghai / Tokyo / Frankfurt,可用于总览世界板标注。"
|
||||
error={form.formState.errors.geo_name?.message}
|
||||
>
|
||||
<ResourceInput
|
||||
placeholder="Shanghai"
|
||||
{...form.register('geo_name')}
|
||||
/>
|
||||
</ResourceField>
|
||||
|
||||
<div className="grid gap-5 md:grid-cols-2">
|
||||
<ResourceField
|
||||
label="纬度"
|
||||
hint="范围 -90 到 90,例如上海约为 31.2304"
|
||||
error={form.formState.errors.geo_latitude?.message}
|
||||
>
|
||||
<ResourceInput
|
||||
placeholder="31.2304"
|
||||
{...form.register('geo_latitude')}
|
||||
/>
|
||||
</ResourceField>
|
||||
|
||||
<ResourceField
|
||||
label="经度"
|
||||
hint="范围 -180 到 180,例如上海约为 121.4737"
|
||||
error={form.formState.errors.geo_longitude?.message}
|
||||
>
|
||||
<ResourceInput
|
||||
placeholder="121.4737"
|
||||
{...form.register('geo_longitude')}
|
||||
/>
|
||||
</ResourceField>
|
||||
</div>
|
||||
</form>
|
||||
</AppModal>
|
||||
submitLabel={editingNode ? '保存修改' : '新增节点'}
|
||||
onSubmit={(payload) => {
|
||||
setFeedback(null);
|
||||
saveMutation.mutate(payload);
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ export interface NodeItem {
|
||||
geo_name: string;
|
||||
geo_latitude?: number | null;
|
||||
geo_longitude?: number | null;
|
||||
geo_manual_override: boolean;
|
||||
agent_token: string;
|
||||
auto_update_enabled: boolean;
|
||||
update_requested: boolean;
|
||||
@@ -39,10 +40,12 @@ export interface NodeBootstrapToken {
|
||||
|
||||
export interface NodeMutationPayload {
|
||||
name: string;
|
||||
ip: string;
|
||||
auto_update_enabled: boolean;
|
||||
geo_name: string;
|
||||
geo_latitude?: number | null;
|
||||
geo_longitude?: number | null;
|
||||
geo_manual_override: boolean;
|
||||
}
|
||||
|
||||
export interface NodeAgentReleaseInfo {
|
||||
|
||||
Reference in New Issue
Block a user