fix topology of cards
This commit is contained in:
+33
-61
@@ -3,18 +3,17 @@ import { Background } from '@vue-flow/background'
|
||||
import { Controls } from '@vue-flow/controls'
|
||||
import { useVueFlow, VueFlow, type Edge, type Node, type NodeMouseEvent, type NodeTypesObject } from '@vue-flow/core'
|
||||
import { MiniMap } from '@vue-flow/minimap'
|
||||
import { computed, markRaw, nextTick, onBeforeUnmount, onMounted, ref, watch, type Ref } from 'vue'
|
||||
import { ApiError, getGraph, getProfiles, resetPositions, savePositions } from './api'
|
||||
import { computed, markRaw, nextTick, onBeforeUnmount, onMounted, provide, ref, watch, type Ref } from 'vue'
|
||||
import { ApiError, getGraph, resetPositions, savePositions } from './api'
|
||||
import BlueprintNode from './components/BlueprintNode.vue'
|
||||
import NodeCard from './components/NodeCard.vue'
|
||||
import { applyView, toFlow } from './flow'
|
||||
import { highlightFor, rowSelId } from './highlight'
|
||||
import { autoLayout } from './layout'
|
||||
import { buildReach, highlightFor, type Reach } from './reach'
|
||||
import type { GraphResponse, Positions, ProfileItem } from './types'
|
||||
import type { GraphResponse, Positions, Warning } from './types'
|
||||
|
||||
const nodeTypes = { bp: markRaw(BlueprintNode) } as unknown as NodeTypesObject
|
||||
const nodeTypes = { bp: markRaw(BlueprintNode), card: markRaw(NodeCard) } as unknown as NodeTypesObject
|
||||
|
||||
const profiles = ref<ProfileItem[]>([])
|
||||
const profileKey = ref('')
|
||||
const current = ref<GraphResponse | null>(null)
|
||||
const nodes = ref([]) as Ref<Node[]>
|
||||
const edges = ref([]) as Ref<Edge[]>
|
||||
@@ -29,8 +28,7 @@ const saveState = ref<'idle' | 'saving' | 'saved' | 'error'>('idle')
|
||||
let autoPos: Positions = {}
|
||||
const { fitView, getNodes } = useVueFlow()
|
||||
|
||||
const reach = computed<Map<string, Reach>>(() => (current.value ? buildReach(current.value.graph) : new Map()))
|
||||
const warnings = computed(() => current.value?.graph.warnings ?? [])
|
||||
const warnings = computed<Warning[]>(() => current.value?.graph.warnings ?? [])
|
||||
const meta = computed(() => current.value?.meta)
|
||||
const metaText = computed(() => {
|
||||
if (!meta.value) return ''
|
||||
@@ -41,9 +39,15 @@ const saveText = computed(
|
||||
() => ({ idle: '', saving: 'сохраняю раскладку…', saved: 'раскладка сохранена', error: 'не удалось сохранить раскладку' })[saveState.value],
|
||||
)
|
||||
|
||||
// клик по строке карточки: подсветить все хосты, которые через неё идут
|
||||
provide('selectRow', (nodeId: string, key: string) => {
|
||||
const id = rowSelId(nodeId, key)
|
||||
selected.value = selected.value === id ? null : id
|
||||
})
|
||||
|
||||
function refreshView() {
|
||||
if (!current.value) return
|
||||
const hl = highlightFor(selected.value, reach.value)
|
||||
const hl = highlightFor(selected.value, current.value.graph)
|
||||
const v = applyView(nodes.value, edges.value, hl, hideShadowed.value)
|
||||
nodes.value = v.nodes
|
||||
edges.value = v.edges
|
||||
@@ -51,29 +55,26 @@ function refreshView() {
|
||||
watch([selected, hideShadowed], refreshView)
|
||||
|
||||
function fit(delay = 80) {
|
||||
nextTick(() => window.setTimeout(() => fitView({ padding: 0.12 }), delay))
|
||||
nextTick(() => window.setTimeout(() => fitView({ padding: 0.1 }), delay))
|
||||
}
|
||||
|
||||
async function load(opts: { force?: boolean; keep?: boolean } = {}) {
|
||||
loading.value = true
|
||||
try {
|
||||
const data = await getGraph(profileKey.value || undefined, opts.force)
|
||||
const switched = data.profile.uuid !== current.value?.profile.uuid
|
||||
const keep = !!opts.keep && !switched
|
||||
const existing: Positions = keep
|
||||
const data = await getGraph(opts.force)
|
||||
const existing: Positions = opts.keep
|
||||
? Object.fromEntries(getNodes.value.map((n) => [n.id, { x: n.position.x, y: n.position.y }]))
|
||||
: {}
|
||||
|
||||
current.value = data
|
||||
profileKey.value = data.profile.uuid
|
||||
autoPos = autoLayout(data.graph)
|
||||
const flow = toFlow(data.graph, { ...data.positions, ...existing }, autoPos)
|
||||
if (selected.value && !flow.nodes.some((n) => n.id === selected.value)) selected.value = null
|
||||
const known = new Set(flow.nodes.map((n) => n.id))
|
||||
if (selected.value && !selected.value.startsWith('row|') && !known.has(selected.value)) selected.value = null
|
||||
nodes.value = flow.nodes
|
||||
edges.value = flow.edges
|
||||
error.value = null
|
||||
refreshView()
|
||||
if (!keep) fit()
|
||||
if (!opts.keep) fit()
|
||||
} catch (e) {
|
||||
error.value = e instanceof ApiError ? (e.status === 401 ? 'Нужна авторизация: обнови страницу и введи логин/пароль' : e.message) : String(e)
|
||||
} finally {
|
||||
@@ -81,11 +82,6 @@ async function load(opts: { force?: boolean; keep?: boolean } = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
async function onProfileChange() {
|
||||
selected.value = null
|
||||
await load()
|
||||
}
|
||||
|
||||
function onNodeClick({ node }: NodeMouseEvent) {
|
||||
selected.value = selected.value === node.id ? null : node.id
|
||||
}
|
||||
@@ -101,7 +97,7 @@ function scheduleSave() {
|
||||
)
|
||||
saveState.value = 'saving'
|
||||
try {
|
||||
await savePositions(current.value.profile.uuid, positions)
|
||||
await savePositions(current.value.positionsKey, positions)
|
||||
saveState.value = 'saved'
|
||||
} catch {
|
||||
saveState.value = 'error'
|
||||
@@ -112,7 +108,7 @@ function scheduleSave() {
|
||||
async function resetLayout() {
|
||||
if (!current.value) return
|
||||
try {
|
||||
await resetPositions(current.value.profile.uuid)
|
||||
await resetPositions(current.value.positionsKey)
|
||||
nodes.value = nodes.value.map((n) => ({ ...n, position: autoPos[n.id] ?? n.position }))
|
||||
saveState.value = 'idle'
|
||||
fit()
|
||||
@@ -121,23 +117,10 @@ async function resetLayout() {
|
||||
}
|
||||
}
|
||||
|
||||
// --- предупреждения ---
|
||||
function warningTarget(w: string): string | null {
|
||||
let m = w.match(/^rule #(\d+)/)
|
||||
if (m) return `rule:${m[1]}`
|
||||
m = w.match(/^outbound (\S+)/)
|
||||
if (m) return `out:${m[1]}`
|
||||
m = w.match(/^balancer (\S+):/)
|
||||
if (m) return `bal:${m[1]}`
|
||||
m = w.match(/^хост (.+?): /)
|
||||
if (m) return current.value?.graph.nodes.find((n) => n.type === 'host' && n.label === m![1])?.id ?? null
|
||||
return null
|
||||
}
|
||||
function focusWarning(w: string) {
|
||||
const id = warningTarget(w)
|
||||
if (!id) return
|
||||
selected.value = id
|
||||
nextTick(() => fitView({ nodes: [id], padding: 0.6, maxZoom: 1, duration: 300 }))
|
||||
function focusWarning(w: Warning) {
|
||||
if (!w.target) return
|
||||
selected.value = w.target
|
||||
nextTick(() => fitView({ nodes: [w.target as string], padding: 0.5, maxZoom: 1, duration: 300 }))
|
||||
}
|
||||
|
||||
// --- автообновление ---
|
||||
@@ -151,24 +134,13 @@ onBeforeUnmount(() => {
|
||||
window.clearTimeout(saveTimer)
|
||||
})
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
profiles.value = await getProfiles()
|
||||
} catch (e) {
|
||||
error.value = e instanceof ApiError ? e.message : String(e)
|
||||
return
|
||||
}
|
||||
await load()
|
||||
})
|
||||
onMounted(() => load())
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="app">
|
||||
<header class="bar">
|
||||
<h1>Remnawave · маршруты</h1>
|
||||
<select v-model="profileKey" :disabled="loading || profiles.length < 2" @change="onProfileChange">
|
||||
<option v-for="p in profiles" :key="p.uuid" :value="p.uuid">{{ p.name }} ({{ p.rules }} правил)</option>
|
||||
</select>
|
||||
<button :disabled="loading" @click="load({ force: true, keep: true })">Обновить</button>
|
||||
<button :disabled="!current" @click="resetLayout">Сбросить раскладку</button>
|
||||
<button :disabled="!current" @click="fit(0)">Вписать</button>
|
||||
@@ -209,16 +181,16 @@ onMounted(async () => {
|
||||
<button @click="showWarnings = false">×</button>
|
||||
</div>
|
||||
<ul>
|
||||
<li v-for="w in warnings" :key="w" :class="{ link: warningTarget(w) }" @click="focusWarning(w)">{{ w }}</li>
|
||||
<li v-for="w in warnings" :key="w.text" :class="{ link: w.target }" @click="focusWarning(w)">{{ w.text }}</li>
|
||||
</ul>
|
||||
</aside>
|
||||
|
||||
<div class="legend">
|
||||
<span><i class="l route" /> маршрут хоста (vlessRoute)</span>
|
||||
<span><i class="l target" /> правило → выход</span>
|
||||
<span><i class="l link" /> мост → нода</span>
|
||||
<span><i class="l dead" /> мёртвое ребро: правило недостижимо или нода не работает</span>
|
||||
<span class="hint">клик по узлу подсвечивает путь, по пустому месту сбрасывает</span>
|
||||
<span><i class="l host" /> хост → строка правила</span>
|
||||
<span><i class="l target" /> правило → outbound/балансер</span>
|
||||
<span><i class="l link" /> outbound → инбаунд ноды-приёмника</span>
|
||||
<span><i class="l dead" /> мёртвое: нода не работает</span>
|
||||
<span class="hint">клик по хосту, ноде, блоку или строке подсвечивает путь, по пустому месту сбрасывает</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+6
-14
@@ -1,4 +1,4 @@
|
||||
import type { GraphResponse, Positions, ProfileItem } from './types'
|
||||
import type { GraphResponse, Positions } from './types'
|
||||
|
||||
export class ApiError extends Error {
|
||||
constructor(message: string, public status: number) {
|
||||
@@ -26,22 +26,14 @@ async function request<T>(url: string, init?: RequestInit): Promise<T> {
|
||||
return r.status === 204 ? (undefined as T) : r.json()
|
||||
}
|
||||
|
||||
export const getProfiles = () =>
|
||||
request<{ profiles: ProfileItem[] }>('/api/profiles').then((d) => d.profiles)
|
||||
export const getGraph = (refresh = false) =>
|
||||
request<GraphResponse>(`/api/graph${refresh ? '?refresh=1' : ''}`)
|
||||
|
||||
export function getGraph(profile?: string, refresh = false) {
|
||||
const q = new URLSearchParams()
|
||||
if (profile) q.set('profile', profile)
|
||||
if (refresh) q.set('refresh', '1')
|
||||
return request<GraphResponse>(`/api/graph?${q}`)
|
||||
}
|
||||
|
||||
export const savePositions = (uuid: string, positions: Positions) =>
|
||||
request<{ saved: number }>(`/api/positions/${uuid}`, {
|
||||
export const savePositions = (key: string, positions: Positions) =>
|
||||
request<{ saved: number }>(`/api/positions/${key}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ positions }),
|
||||
})
|
||||
|
||||
export const resetPositions = (uuid: string) =>
|
||||
request<void>(`/api/positions/${uuid}`, { method: 'DELETE' })
|
||||
export const resetPositions = (key: string) => request<void>(`/api/positions/${key}`, { method: 'DELETE' })
|
||||
|
||||
@@ -1,45 +1,31 @@
|
||||
<script setup lang="ts">
|
||||
import { Handle, Position } from '@vue-flow/core'
|
||||
import { computed } from 'vue'
|
||||
import { bpHandles } from '../handles'
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const props = defineProps<{ id: string; data: Record<string, any> }>()
|
||||
const d = computed(() => props.data)
|
||||
|
||||
const KIND: Record<string, string> = {
|
||||
host: 'HOST', inbound: 'INBOUND', rule: 'RULE', balancer: 'BALANCER',
|
||||
outbound: 'OUTBOUND', node: 'NODE', unresolved: '???',
|
||||
}
|
||||
const kind = computed<string>(() => d.value.kind)
|
||||
const hasIn = computed(() => kind.value !== 'host')
|
||||
const hasOut = computed(() => !['node', 'unresolved'].includes(kind.value))
|
||||
|
||||
const title = computed(() => (kind.value === 'rule' ? `#${d.value.index}` : d.value.label))
|
||||
const cond = computed(() => String(d.value.label ?? '').replace(/^#\d+\s*/, ''))
|
||||
|
||||
function tone(name?: string, targetKind?: string) {
|
||||
if (targetKind === 'balancer') return 'violet'
|
||||
if (name === 'BLOCK') return 'red'
|
||||
if (name === 'DIRECT') return 'green'
|
||||
return 'blue'
|
||||
}
|
||||
const handles = computed(() => bpHandles(kind.value, d.value))
|
||||
const KIND: Record<string, string> = { host: 'HOST', balancer: 'BALANCER', outbound: 'OUTBOUND' }
|
||||
const list = (v?: string[]) => (v && v.length ? v.join(', ') : '—')
|
||||
const tone = computed(() => (/^BLOCK/.test(d.value.label) ? 'red' : d.value.protocol === 'freedom' ? 'green' : 'blue'))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="bp" :class="[`k-${kind}`, { off: d.disabled || d.state === 'disabled' }]">
|
||||
<Handle v-if="hasIn" id="in" type="target" :position="Position.Left" />
|
||||
<Handle v-if="hasOut" id="out" type="source" :position="Position.Right" />
|
||||
<template v-if="kind === 'rule'">
|
||||
<Handle id="prev" type="target" :position="Position.Top" />
|
||||
<Handle id="next" type="source" :position="Position.Bottom" />
|
||||
</template>
|
||||
|
||||
<div class="bp" :class="[`k-${kind}`, { off: d.disabled }]">
|
||||
<Handle
|
||||
v-for="h in handles"
|
||||
:id="h.id"
|
||||
:key="h.id"
|
||||
:type="h.type"
|
||||
:position="h.type === 'target' ? Position.Left : Position.Right"
|
||||
/>
|
||||
<div class="hd">
|
||||
<span class="kind">{{ KIND[kind] }}</span>
|
||||
<span class="title" :title="String(title)">{{ title }}</span>
|
||||
<span v-if="kind === 'node'" class="pill" :class="`st-${d.state}`">{{ d.state }}</span>
|
||||
<span v-if="kind === 'outbound' && d.ip" class="pill" :class="d.alive ? 'st-online' : 'st-offline'">
|
||||
<span class="title" :title="d.label">{{ d.label }}</span>
|
||||
<span v-if="kind === 'outbound'" class="pill" :class="d.alive ? 'st-online' : 'st-offline'">
|
||||
{{ d.alive ? 'up' : 'down' }}
|
||||
</span>
|
||||
</div>
|
||||
@@ -49,83 +35,52 @@ const list = (v?: string[]) => (v && v.length ? v.join(', ') : '—')
|
||||
<div class="row"><span class="k">адрес</span>{{ d.address }}<template v-if="d.port">:{{ d.port }}</template></div>
|
||||
<div class="row">
|
||||
<span class="pill blue">{{ d.vlessRouteId != null ? `route ${d.vlessRouteId}` : 'без route' }}</span>
|
||||
<span v-if="d.inboundTag" class="pill teal">{{ d.inboundTag }}</span>
|
||||
<span v-if="d.disabled" class="pill st-disabled">disabled</span>
|
||||
<span v-if="d.exitAlive === false" class="pill st-offline">выход не работает</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template v-else-if="kind === 'inbound'">
|
||||
<div class="row">{{ d.protocol }}<template v-if="d.port"> :{{ d.port }}</template></div>
|
||||
</template>
|
||||
|
||||
<template v-else-if="kind === 'rule'">
|
||||
<div class="cond" :title="cond">{{ cond }}</div>
|
||||
<div class="row">
|
||||
<span class="arrow">→</span>
|
||||
<span class="pill" :class="tone(d.target, d.targetKind)">{{ d.target }}</span>
|
||||
<span v-if="d.shadowed" class="pill st-offline" title="выше есть catch-all, правило не сработает">недостижимо</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template v-else-if="kind === 'balancer'">
|
||||
<div class="row"><span class="k">стратегия</span>{{ d.strategy ?? '—' }}</div>
|
||||
<div class="row">
|
||||
<span class="k">живых</span>{{ d.aliveMembers?.length ?? 0 }} / {{ d.members?.length ?? 0 }}
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template v-else-if="kind === 'outbound'">
|
||||
<div class="row">{{ d.protocol }}<template v-if="d.ip"> · {{ d.ip }}</template></div>
|
||||
</template>
|
||||
|
||||
<template v-else-if="kind === 'node'">
|
||||
<div class="row">
|
||||
<span v-if="d.country" class="pill gray">{{ d.country }}</span>
|
||||
<span v-if="d.netbird" class="pill teal">NetBird</span>
|
||||
</div>
|
||||
<div class="row"><span class="k">мост</span>{{ list(d.mgmt) }}</div>
|
||||
<div class="row"><span class="k">выход</span>{{ list(d.exit) }}</div>
|
||||
<div v-if="d.inbound?.length" class="row"><span class="k">вход</span>{{ list(d.inbound) }}</div>
|
||||
<div v-if="d.reserve?.length" class="row"><span class="k">резерв</span>{{ d.reserve.length }}</div>
|
||||
<div class="row"><span class="k">живых</span>{{ d.aliveMembers?.length ?? 0 }} / {{ d.members?.length ?? 0 }}</div>
|
||||
</template>
|
||||
|
||||
<template v-else>
|
||||
<div class="row">адрес не найден ни в одной карточке ноды</div>
|
||||
<div class="row">
|
||||
<span class="pill" :class="tone">{{ d.protocol }}</span>
|
||||
<template v-if="d.address">{{ d.address }}<template v-if="d.port">:{{ d.port }}</template></template>
|
||||
<template v-else-if="d.owner"><span class="k">выход</span>{{ list(d.exit) }}</template>
|
||||
</div>
|
||||
<div v-if="d.destName" class="row"><span class="k">→ нода</span>{{ d.destName }}</div>
|
||||
<div class="row" :title="(d.users ?? []).join(', ')">
|
||||
<span class="k">используют</span><span class="users">{{ list(d.users) }}</span>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.bp { width: 250px; background: #1b2130; border: 1px solid #323d55; border-radius: 8px;
|
||||
box-shadow: 0 4px 14px rgb(0 0 0 / 35%); font-size: 12px; color: #d6deeb; overflow: visible; }
|
||||
.hd { display: flex; align-items: center; gap: 8px; padding: 6px 10px; border-radius: 7px 7px 0 0;
|
||||
background: var(--hd, #2a3550); }
|
||||
.bp { width: 250px; background: #1b2130; border: 1px solid #323d55; border-radius: 8px; font-size: 12px;
|
||||
color: #d6deeb; box-shadow: 0 4px 14px rgb(0 0 0 / 35%); }
|
||||
.hd { display: flex; align-items: center; gap: 8px; padding: 6px 10px; border-radius: 7px 7px 0 0; background: var(--hd, #2a3550); }
|
||||
.kind { font-size: 9px; letter-spacing: .08em; opacity: .75; font-weight: 600; }
|
||||
.title { font-weight: 600; flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.bd { padding: 7px 10px 9px; display: flex; flex-direction: column; gap: 5px; }
|
||||
.row { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; line-height: 1.35; }
|
||||
.k { color: #7f8ba3; min-width: 52px; }
|
||||
.cond { color: #aab6cc; display: -webkit-box; -webkit-line-clamp: 2; line-clamp: 2; -webkit-box-orient: vertical;
|
||||
overflow: hidden; word-break: break-word; }
|
||||
.arrow { color: #7f8ba3; }
|
||||
.users { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 150px; }
|
||||
.pill { padding: 1px 7px; border-radius: 10px; font-size: 10.5px; background: #2b3550; color: #cdd7ea; white-space: nowrap; }
|
||||
.pill.blue { background: #1e3a66; color: #9cc4ff; }
|
||||
.pill.green { background: #17402f; color: #7ee2b0; }
|
||||
.pill.red { background: #4a1f26; color: #ff9aa5; }
|
||||
.pill.violet { background: #392a63; color: #c8b3ff; }
|
||||
.pill.teal { background: #14403f; color: #6fe0d6; }
|
||||
.pill.gray { background: #2b3243; color: #aab6cc; }
|
||||
.st-online { background: #17402f; color: #7ee2b0; }
|
||||
.st-offline { background: #4a1f26; color: #ff9aa5; }
|
||||
.st-disabled { background: #343a48; color: #9aa6bd; }
|
||||
.st-connecting { background: #4a3a14; color: #ffd27a; }
|
||||
.k-host { --hd: #1f3b66; }
|
||||
.k-inbound { --hd: #14504f; }
|
||||
.k-rule { --hd: #3b2f66; }
|
||||
.k-balancer { --hd: #5a2f66; }
|
||||
.k-outbound { --hd: #2d4a2f; }
|
||||
.k-node { --hd: #5a4320; }
|
||||
.k-unresolved { --hd: #6b2431; }
|
||||
.off { opacity: .6; }
|
||||
</style>
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
<script setup lang="ts">
|
||||
import { Handle, Position } from '@vue-flow/core'
|
||||
import { computed, inject } from 'vue'
|
||||
import { H } from '../handles'
|
||||
import type { Row, Section } from '../types'
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const props = defineProps<{ id: string; data: Record<string, any> }>()
|
||||
const d = computed(() => props.data)
|
||||
const selectRow = inject<(nodeId: string, key: string) => void>('selectRow', () => {})
|
||||
|
||||
const hl = computed(() => d.value.hl as { active: string[]; pass: string[] } | null)
|
||||
const active = computed(() => new Set(hl.value?.active ?? []))
|
||||
const pass = computed(() => new Set(hl.value?.pass ?? []))
|
||||
const state = (key: string) => (!hl.value ? '' : active.value.has(key) ? 'r-active' : pass.value.has(key) ? 'r-pass' : 'r-dim')
|
||||
|
||||
const sections = computed(() => (d.value.sections ?? []) as Section[])
|
||||
const rows = (s: Section) => (d.value.hideShadowed ? s.rows.filter((r) => !r.shadowed) : s.rows)
|
||||
const tone = (r: Row) =>
|
||||
r.targetKind === 'balancer' ? 'violet' : r.target === 'BLOCK' ? 'red' : r.target === 'DIRECT' ? 'green' : 'blue'
|
||||
// пометка «общее» нужна, только если в секции есть и правила конкретного инбаунда
|
||||
const mixed = (s: Section) => s.rows.some((r) => !r.common)
|
||||
const list = (v?: string[]) => (v && v.length ? v.join(', ') : '—')
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="card" :class="{ off: d.state === 'disabled' }">
|
||||
<div class="hd">
|
||||
<Handle :id="H.head" type="target" :position="Position.Left" />
|
||||
<span class="kind">NODE</span>
|
||||
<span class="name" :title="d.label">{{ d.label }}</span>
|
||||
<span class="pill" :class="`st-${d.state}`">{{ d.state }}</span>
|
||||
</div>
|
||||
<div class="meta">
|
||||
<div class="line">
|
||||
<span v-if="d.profile" class="pill violet" title="профиль ноды">{{ d.profile.name }}</span>
|
||||
<span v-else class="pill gray">нет профиля</span>
|
||||
<span v-if="d.country" class="pill gray">{{ d.country }}</span>
|
||||
<span v-if="d.netbird" class="pill teal">NetBird</span>
|
||||
</div>
|
||||
<div class="line dim">мост {{ list(d.mgmt) }} · выход {{ list(d.exit) }}</div>
|
||||
</div>
|
||||
|
||||
<div v-if="!sections.length" class="empty">нет активных инбаундов</div>
|
||||
<div v-for="s in sections" :key="s.uuid" class="sec">
|
||||
<div class="inb" :class="state(`inb:${s.uuid}`)" @click.stop="selectRow(id, `inb:${s.uuid}`)">
|
||||
<Handle :id="H.inb(s.uuid)" type="target" :position="Position.Left" />
|
||||
<span class="tag">{{ s.tag }}</span>
|
||||
<span class="proto">{{ s.protocol }}<template v-if="s.port"> :{{ s.port }}</template></span>
|
||||
</div>
|
||||
<div
|
||||
v-for="r in rows(s)"
|
||||
:key="r.key"
|
||||
class="row"
|
||||
:class="[state(`${s.uuid}:${r.key}`), { shadowed: r.shadowed, dflt: r.default }]"
|
||||
@click.stop="selectRow(id, `${s.uuid}:${r.key}`)"
|
||||
>
|
||||
<Handle :id="H.rin(s.uuid, r.key)" type="target" :position="Position.Left" />
|
||||
<span class="idx">{{ r.default ? '↳' : `#${r.index}` }}</span>
|
||||
<span class="cond" :title="r.label">{{ r.label }}</span>
|
||||
<span v-if="r.common && !r.default && mixed(s)" class="common" title="общее правило профиля (без inboundTag)">общее</span>
|
||||
<span v-if="r.shadowed" class="pill red" title="выше есть catch-all, правило не сработает">недостижимо</span>
|
||||
<span v-else class="pill" :class="tone(r)">{{ r.target }}</span>
|
||||
<Handle v-if="r.hasEdge" :id="H.rout(s.uuid, r.key)" type="source" :position="Position.Right" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.card { width: 340px; background: #1b2130; border: 1px solid #323d55; border-radius: 8px; font-size: 12px;
|
||||
color: #d6deeb; box-shadow: 0 4px 14px rgb(0 0 0 / 35%); padding-bottom: 8px; }
|
||||
.hd { position: relative; height: 34px; display: flex; align-items: center; gap: 8px; padding: 0 10px;
|
||||
background: #5a4320; border-radius: 7px 7px 0 0; }
|
||||
.kind { font-size: 9px; letter-spacing: .08em; opacity: .75; font-weight: 600; }
|
||||
.name { font-weight: 600; flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.meta { height: 42px; padding: 5px 10px 0; display: flex; flex-direction: column; gap: 4px; }
|
||||
.line { display: flex; gap: 6px; align-items: center; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.line.dim { color: #7f8ba3; font-size: 11px; }
|
||||
.empty { height: 28px; padding: 4px 10px; color: #7f8ba3; }
|
||||
.sec { margin-top: 10px; }
|
||||
.sec:first-of-type { margin-top: 0; }
|
||||
.inb { position: relative; height: 30px; display: flex; align-items: center; gap: 8px; padding: 0 10px;
|
||||
background: #14504f; cursor: pointer; }
|
||||
.tag { font-weight: 600; flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.proto { color: #9fd9d3; font-size: 11px; }
|
||||
.row { position: relative; height: 27px; display: flex; align-items: center; gap: 7px; padding: 0 10px;
|
||||
border-bottom: 1px solid #262f45; cursor: pointer; }
|
||||
.row:hover, .inb:hover { filter: brightness(1.15); }
|
||||
.idx { color: #7f8ba3; min-width: 26px; font-variant-numeric: tabular-nums; }
|
||||
.cond { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: #c3cde0; }
|
||||
.common { font-size: 9.5px; color: #7f8ba3; border: 1px solid #323d55; border-radius: 8px; padding: 0 5px; }
|
||||
.dflt .cond { color: #7f8ba3; font-style: italic; }
|
||||
.shadowed { background: #2a1c24; }
|
||||
.shadowed .cond { text-decoration: line-through; color: #8a6a74; }
|
||||
.r-active { background: #1e3a66; }
|
||||
.r-pass { opacity: .5; }
|
||||
.r-dim { opacity: .25; }
|
||||
.inb.r-active { background: #1b7a76; }
|
||||
.pill { padding: 1px 7px; border-radius: 10px; font-size: 10.5px; background: #2b3550; color: #cdd7ea; white-space: nowrap; }
|
||||
.pill.blue { background: #1e3a66; color: #9cc4ff; }
|
||||
.pill.green { background: #17402f; color: #7ee2b0; }
|
||||
.pill.red { background: #4a1f26; color: #ff9aa5; }
|
||||
.pill.violet { background: #392a63; color: #c8b3ff; }
|
||||
.pill.teal { background: #14403f; color: #6fe0d6; }
|
||||
.pill.gray { background: #2b3243; color: #aab6cc; }
|
||||
.st-online { background: #17402f; color: #7ee2b0; }
|
||||
.st-offline { background: #4a1f26; color: #ff9aa5; }
|
||||
.st-disabled { background: #343a48; color: #9aa6bd; }
|
||||
.st-connecting { background: #4a3a14; color: #ffd27a; }
|
||||
.off { opacity: .65; }
|
||||
</style>
|
||||
+20
-33
@@ -1,59 +1,46 @@
|
||||
import type { Edge, Node } from '@vue-flow/core'
|
||||
import type { Highlight } from './reach'
|
||||
import type { Highlight } from './highlight'
|
||||
import type { Graph, Positions } from './types'
|
||||
|
||||
const LABELLED = new Set(['link', 'route', 'fallback'])
|
||||
const LABELLED = new Set(['host', 'link', 'fallback', 'member'])
|
||||
|
||||
/** Граф бэкенда -> узлы и рёбра Vue Flow (без подсветки). */
|
||||
export function toFlow(graph: Graph, positions: Positions, auto: Positions): { nodes: Node[]; edges: Edge[] } {
|
||||
const targetOf = new Map(graph.edges.filter((e) => e.kind === 'target').map((e) => [e.source, e.target]))
|
||||
|
||||
const nodes: Node[] = graph.nodes.map((n) => {
|
||||
const data: Record<string, unknown> = { ...n.data, kind: n.type, label: n.label }
|
||||
if (n.type === 'rule') {
|
||||
const t = targetOf.get(n.id)
|
||||
if (t) {
|
||||
data.target = t.replace(/^(out|bal):/, '')
|
||||
data.targetKind = t.startsWith('bal:') ? 'balancer' : 'outbound'
|
||||
}
|
||||
}
|
||||
return { id: n.id, type: 'bp', position: positions[n.id] ?? auto[n.id] ?? { x: 0, y: 0 }, data }
|
||||
})
|
||||
|
||||
const nodes: Node[] = graph.nodes.map((n) => ({
|
||||
id: n.id,
|
||||
type: n.type === 'node' ? 'card' : 'bp',
|
||||
position: positions[n.id] ?? auto[n.id] ?? { x: 0, y: 0 },
|
||||
data: { ...n.data, kind: n.type, label: n.label },
|
||||
}))
|
||||
const edges: Edge[] = graph.edges.map((e) => ({
|
||||
id: e.id,
|
||||
source: e.source,
|
||||
target: e.target,
|
||||
sourceHandle: e.kind === 'fallthrough' ? 'next' : 'out',
|
||||
targetHandle: e.kind === 'fallthrough' ? 'prev' : 'in',
|
||||
sourceHandle: e.sourceHandle,
|
||||
targetHandle: e.targetHandle,
|
||||
label: LABELLED.has(e.kind) ? e.label ?? undefined : undefined,
|
||||
data: { kind: e.kind, dead: !!e.data.dead },
|
||||
data: { kind: e.kind, dead: e.data.dead },
|
||||
}))
|
||||
return { nodes, edges }
|
||||
}
|
||||
|
||||
/** Классы подсветки и скрытие. Позиции не трогает. */
|
||||
/** Подсветка и скрытие недостижимых строк. Позиции не трогает. */
|
||||
export function applyView(nodes: Node[], edges: Edge[], hl: Highlight | null, hideShadowed: boolean) {
|
||||
const hidden = new Set(nodes.filter((n) => hideShadowed && n.data.shadowed).map((n) => n.id))
|
||||
|
||||
const outNodes = nodes.map((n) => {
|
||||
const cls: string[] = []
|
||||
if (n.data.shadowed) cls.push('shadowed')
|
||||
if (hl) cls.push(hl.active.has(n.id) ? 'active' : hl.pass.has(n.id) ? 'pass' : 'dim')
|
||||
return { ...n, hidden: hidden.has(n.id), class: cls.join(' ') }
|
||||
const data = { ...n.data, hideShadowed }
|
||||
if (n.type === 'card') {
|
||||
const r = hl?.rows.get(n.id)
|
||||
data.hl = hl ? { active: [...(r?.active ?? [])], pass: [...(r?.pass ?? [])] } : null
|
||||
}
|
||||
const cls = hl ? (hl.nodes.has(n.id) ? 'active' : 'dim') : ''
|
||||
return { ...n, data, class: cls }
|
||||
})
|
||||
|
||||
const outEdges = edges.map((e) => {
|
||||
const cls = [`kind-${e.data.kind}`]
|
||||
if (e.data.dead) cls.push('dead')
|
||||
const lit = !!hl?.edges.has(e.id)
|
||||
if (hl) cls.push(lit ? 'active' : 'dim')
|
||||
return {
|
||||
...e,
|
||||
hidden: hidden.has(e.source) || hidden.has(e.target),
|
||||
animated: lit,
|
||||
class: cls.join(' '),
|
||||
}
|
||||
return { ...e, animated: lit, class: cls.join(' ') }
|
||||
})
|
||||
return { nodes: outNodes, edges: outEdges }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { Section } from './types'
|
||||
|
||||
/** Идентификаторы портов. Бэкенд пишет их в рёбра, карточки рисуют по тем же правилам. */
|
||||
export const H = {
|
||||
head: 'head',
|
||||
inb: (uuid: string) => `inb:${uuid}`,
|
||||
rin: (uuid: string, key: string) => `rin:${uuid}:${key}`,
|
||||
rout: (uuid: string, key: string) => `rout:${uuid}:${key}`,
|
||||
}
|
||||
|
||||
export interface HandleDef {
|
||||
id: string
|
||||
type: 'source' | 'target'
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
export function cardHandles(data: Record<string, any>): HandleDef[] {
|
||||
const out: HandleDef[] = [{ id: H.head, type: 'target' }]
|
||||
for (const s of (data.sections ?? []) as Section[]) {
|
||||
out.push({ id: H.inb(s.uuid), type: 'target' })
|
||||
for (const r of s.rows) {
|
||||
out.push({ id: H.rin(s.uuid, r.key), type: 'target' })
|
||||
if (r.hasEdge) out.push({ id: H.rout(s.uuid, r.key), type: 'source' })
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
export function bpHandles(kind: string, data: Record<string, any>): HandleDef[] {
|
||||
if (kind === 'host') return [{ id: 'out', type: 'source' }]
|
||||
if (kind === 'balancer') return [{ id: 'in', type: 'target' }, { id: 'out', type: 'source' }]
|
||||
return [{ id: 'in', type: 'target' }, ...(data.destName ? [{ id: 'out', type: 'source' as const }] : [])]
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { Graph } from './types'
|
||||
|
||||
export interface Highlight {
|
||||
hostIds: string[]
|
||||
nodes: Set<string>
|
||||
edges: Set<string>
|
||||
/** по картам нод: активные и "проверенные, но не подошедшие" строки */
|
||||
rows: Map<string, { active: Set<string>; pass: Set<string> }>
|
||||
}
|
||||
|
||||
export const rowSelId = (nodeId: string, key: string) => `row|${nodeId}|${key}`
|
||||
|
||||
/** Выбранный хост, строка, блок или нода -> объединённый путь всех хостов, которые через них идут. */
|
||||
export function highlightFor(selected: string | null, g: Graph): Highlight | null {
|
||||
if (!selected) return null
|
||||
const hosts = Object.keys(g.paths)
|
||||
let ids: string[]
|
||||
const nodes = new Set<string>()
|
||||
if (selected.startsWith('host:')) {
|
||||
ids = [selected]
|
||||
} else if (selected.startsWith('row|')) {
|
||||
const [, nodeId, key] = selected.split('|')
|
||||
ids = hosts.filter((h) => g.paths[h].rows[nodeId]?.active.includes(key))
|
||||
nodes.add(nodeId)
|
||||
} else {
|
||||
ids = hosts.filter((h) => g.paths[h].nodes.includes(selected))
|
||||
nodes.add(selected)
|
||||
}
|
||||
|
||||
const edges = new Set<string>()
|
||||
const rows = new Map<string, { active: Set<string>; pass: Set<string> }>()
|
||||
for (const h of ids) {
|
||||
const p = g.paths[h]
|
||||
p.nodes.forEach((n) => nodes.add(n))
|
||||
p.edges.forEach((e) => edges.add(e))
|
||||
for (const [nodeId, r] of Object.entries(p.rows)) {
|
||||
const cur = rows.get(nodeId) ?? { active: new Set<string>(), pass: new Set<string>() }
|
||||
r.active.forEach((k) => cur.active.add(k))
|
||||
r.pass.forEach((k) => cur.pass.add(k))
|
||||
rows.set(nodeId, cur)
|
||||
}
|
||||
}
|
||||
for (const r of rows.values()) r.active.forEach((k) => r.pass.delete(k)) // активная для одного хоста не "проходная"
|
||||
return { hostIds: ids, nodes, edges, rows }
|
||||
}
|
||||
+89
-41
@@ -1,53 +1,101 @@
|
||||
import type { GNode, Graph, NodeKind, Positions } from './types'
|
||||
import type { GNode, Graph, Positions, Section } from './types'
|
||||
|
||||
export const COL_X: Record<NodeKind, number> = {
|
||||
host: 0,
|
||||
inbound: 330,
|
||||
rule: 660,
|
||||
balancer: 1040,
|
||||
outbound: 1380,
|
||||
node: 1720,
|
||||
unresolved: 1720,
|
||||
}
|
||||
export const NODE_HEIGHT: Record<NodeKind, number> = {
|
||||
host: 90, inbound: 76, rule: 84, balancer: 104, outbound: 80, node: 150, unresolved: 64,
|
||||
}
|
||||
const GAP = 24
|
||||
export const WIDTH: Record<string, number> = { host: 250, node: 340, balancer: 250, outbound: 250 }
|
||||
const GAP_X = 150
|
||||
const GAP_Y = 26
|
||||
// размеры частей карточки ноды (CSS держит их фиксированными)
|
||||
const HEAD = 76, INB = 30, ROW = 27, SEC_GAP = 10, PAD = 8
|
||||
|
||||
/** Раскладка колонками: правила по порядку, остальное выравнивается по связанным узлам. */
|
||||
const sections = (n: GNode) => (n.data.sections ?? []) as Section[]
|
||||
|
||||
export function heightOf(n: GNode): number {
|
||||
if (n.type === 'host') return 96
|
||||
if (n.type === 'balancer') return 104
|
||||
if (n.type === 'outbound') return 112
|
||||
const secs = sections(n)
|
||||
const body = secs.length ? secs.reduce((a, s) => a + INB + s.rows.length * ROW + SEC_GAP, 0) : 28
|
||||
return HEAD + body + PAD
|
||||
}
|
||||
|
||||
/** Вертикальный центр порта внутри карточки (для выравнивания связанных блоков). */
|
||||
export function handleCenter(n: GNode, handle: string): number {
|
||||
if (n.type !== 'node') return heightOf(n) / 2
|
||||
if (handle === 'head') return HEAD / 2
|
||||
let y = HEAD
|
||||
for (const s of sections(n)) {
|
||||
if (handle === `inb:${s.uuid}`) return y + INB / 2
|
||||
const i = s.rows.findIndex((r) => handle === `rin:${s.uuid}:${r.key}` || handle === `rout:${s.uuid}:${r.key}`)
|
||||
if (i >= 0) return y + INB + i * ROW + ROW / 2
|
||||
y += INB + s.rows.length * ROW + SEC_GAP
|
||||
}
|
||||
return heightOf(n) / 2
|
||||
}
|
||||
|
||||
/**
|
||||
* Колонки по длиннейшему пути от хостов: хост -> нода -> балансер/outbound -> нода-приёмник...
|
||||
* Внутри колонки блоки выравниваются по связанным портам.
|
||||
*/
|
||||
export function autoLayout(g: Graph): Positions {
|
||||
const y = new Map<string, number>()
|
||||
const pos: Positions = {}
|
||||
const byId = new Map(g.nodes.map((n) => [n.id, n]))
|
||||
const layer = new Map(g.nodes.map((n) => [n.id, 0]))
|
||||
for (let i = 0; i < 40; i++) {
|
||||
let changed = false
|
||||
for (const e of g.edges) {
|
||||
const l = (layer.get(e.source) ?? 0) + 1
|
||||
if (l > (layer.get(e.target) ?? 0)) {
|
||||
layer.set(e.target, l)
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if (!changed) break
|
||||
}
|
||||
|
||||
const place = (kinds: NodeKind[], desired: (n: GNode) => number) => {
|
||||
const items = g.nodes
|
||||
.filter((n) => kinds.includes(n.type))
|
||||
.map((n) => ({ n, d: desired(n) }))
|
||||
.sort((a, b) => a.d - b.d)
|
||||
const layers = [...new Set(layer.values())].sort((a, b) => a - b)
|
||||
const colX = new Map<number, number>()
|
||||
let x = 0
|
||||
for (const L of layers) {
|
||||
colX.set(L, x)
|
||||
x += Math.max(...g.nodes.filter((n) => layer.get(n.id) === L).map((n) => WIDTH[n.type])) + GAP_X
|
||||
}
|
||||
|
||||
const top = new Map<string, number>()
|
||||
const mean = (xs: number[]) => (xs.length ? xs.reduce((a, b) => a + b, 0) / xs.length : 0)
|
||||
|
||||
const place = (items: GNode[], desiredCenter: (n: GNode) => number) => {
|
||||
const sorted = items
|
||||
.map((n) => ({ n, c: desiredCenter(n) }))
|
||||
.sort((a, b) => a.c - b.c || a.n.label.localeCompare(b.n.label))
|
||||
let cursor = -Infinity
|
||||
for (const { n, d } of items) {
|
||||
const yy = Math.max(d, cursor)
|
||||
y.set(n.id, yy)
|
||||
pos[n.id] = { x: COL_X[n.type], y: yy }
|
||||
cursor = yy + NODE_HEIGHT[n.type] + GAP
|
||||
for (const { n, c } of sorted) {
|
||||
const t = Math.max(c - heightOf(n) / 2, cursor)
|
||||
top.set(n.id, t)
|
||||
cursor = t + heightOf(n) + GAP_Y
|
||||
}
|
||||
}
|
||||
|
||||
const mean = (ids: string[]) => {
|
||||
const ys = ids.map((i) => y.get(i)).filter((v): v is number => v !== undefined)
|
||||
return ys.length ? ys.reduce((a, b) => a + b, 0) / ys.length : 0
|
||||
for (const L of layers) {
|
||||
place(
|
||||
g.nodes.filter((n) => layer.get(n.id) === L && n.type !== 'host'),
|
||||
(n) =>
|
||||
mean(
|
||||
g.edges
|
||||
.filter((e) => e.target === n.id && top.has(e.source))
|
||||
.map((e) => top.get(e.source)! + handleCenter(byId.get(e.source)!, e.sourceHandle)),
|
||||
),
|
||||
)
|
||||
}
|
||||
const sourcesOf = (id: string, kinds: string[]) =>
|
||||
g.edges.filter((e) => e.target === id && kinds.includes(e.kind)).map((e) => e.source)
|
||||
// хосты в последнюю очередь: напротив строки, на которой садится их нитка
|
||||
place(
|
||||
g.nodes.filter((n) => n.type === 'host'),
|
||||
(n) =>
|
||||
mean(
|
||||
g.edges
|
||||
.filter((e) => e.source === n.id && top.has(e.target))
|
||||
.map((e) => top.get(e.target)! + handleCenter(byId.get(e.target)!, e.targetHandle)),
|
||||
),
|
||||
)
|
||||
|
||||
place(['rule'], (n) => (n.data.index ?? 0) * (NODE_HEIGHT.rule + GAP))
|
||||
place(['balancer'], (n) => mean(sourcesOf(n.id, ['target'])))
|
||||
place(['outbound'], (n) => mean(sourcesOf(n.id, ['target', 'member', 'fallback'])))
|
||||
place(['node', 'unresolved'], (n) => mean(sourcesOf(n.id, ['link'])))
|
||||
place(['host'], (n) => {
|
||||
const last = (n.data.trace as string[] | undefined)?.at(-1)
|
||||
return (last ? y.get(last) ?? 0 : 0) + (n.data.vlessRouteId ?? 99) * 0.001
|
||||
})
|
||||
place(['inbound'], (n) => mean(g.edges.filter((e) => e.target === n.id).map((e) => e.source)))
|
||||
const pos: Positions = {}
|
||||
for (const n of g.nodes) pos[n.id] = { x: colX.get(layer.get(n.id) ?? 0) ?? 0, y: top.get(n.id) ?? 0 }
|
||||
return pos
|
||||
}
|
||||
|
||||
+4
-10
@@ -35,7 +35,7 @@ button:disabled, select:disabled { opacity: .5; cursor: default; }
|
||||
max-width: 60%; padding: 6px 10px; background: #151b2bd9; border: 1px solid #263149; border-radius: 6px;
|
||||
color: #aab6cc; font-size: 11.5px; }
|
||||
.legend .l { display: inline-block; width: 22px; height: 0; border-top: 2px solid; vertical-align: middle; margin-right: 4px; }
|
||||
.legend .l.route { border-color: #60a5fa; border-top-style: dashed; }
|
||||
.legend .l.host { border-color: #60a5fa; border-top-style: dashed; }
|
||||
.legend .l.target { border-color: #a78bfa; }
|
||||
.legend .l.link { border-color: #34d399; }
|
||||
.legend .l.dead { border-color: #ef4444; border-top-style: dashed; }
|
||||
@@ -47,17 +47,11 @@ button:disabled, select:disabled { opacity: .5; cursor: default; }
|
||||
.vue-flow__handle-top, .vue-flow__handle-bottom { width: 9px; height: 9px; background: #5b6a86; }
|
||||
.vue-flow__node { transition: opacity .15s; }
|
||||
.vue-flow__node.dim { opacity: .2; }
|
||||
.vue-flow__node.pass { opacity: .5; }
|
||||
.vue-flow__node.active .bp { border-color: #6ea8ff; box-shadow: 0 0 0 1px #6ea8ff, 0 4px 18px rgb(80 140 255 / 35%); }
|
||||
.vue-flow__node.shadowed .bp { border-style: dashed; border-color: #8a3a46; }
|
||||
.vue-flow__node.shadowed { opacity: .8; }
|
||||
.vue-flow__node.shadowed.dim { opacity: .15; }
|
||||
.vue-flow__node.selected .bp { border-color: #6ea8ff; }
|
||||
.vue-flow__node.active .card, .vue-flow__node.active .bp { border-color: #6ea8ff; box-shadow: 0 0 0 1px #6ea8ff, 0 4px 18px rgb(80 140 255 / 30%); }
|
||||
.vue-flow__node.selected .card, .vue-flow__node.selected .bp { border-color: #6ea8ff; }
|
||||
|
||||
.vue-flow__edge-path { stroke: #4b5568; stroke-width: 1.6; transition: opacity .15s; }
|
||||
.vue-flow__edge.kind-flow .vue-flow__edge-path { stroke: #94a3b8; }
|
||||
.vue-flow__edge.kind-route .vue-flow__edge-path { stroke: #60a5fa; stroke-dasharray: 6 4; }
|
||||
.vue-flow__edge.kind-fallthrough .vue-flow__edge-path { stroke: #4b5568; stroke-width: 1.2; }
|
||||
.vue-flow__edge.kind-host .vue-flow__edge-path { stroke: #60a5fa; stroke-dasharray: 6 4; }
|
||||
.vue-flow__edge.kind-target .vue-flow__edge-path { stroke: #a78bfa; }
|
||||
.vue-flow__edge.kind-member .vue-flow__edge-path { stroke: #c084fc; }
|
||||
.vue-flow__edge.kind-fallback .vue-flow__edge-path { stroke: #f59e0b; stroke-dasharray: 4 4; }
|
||||
|
||||
+40
-13
@@ -1,5 +1,5 @@
|
||||
export type NodeKind = 'host' | 'inbound' | 'rule' | 'balancer' | 'outbound' | 'node' | 'unresolved'
|
||||
export type EdgeKind = 'flow' | 'route' | 'fallthrough' | 'target' | 'member' | 'fallback' | 'link'
|
||||
export type NodeKind = 'host' | 'node' | 'balancer' | 'outbound'
|
||||
export type EdgeKind = 'host' | 'target' | 'member' | 'fallback' | 'link'
|
||||
|
||||
export interface GNode {
|
||||
id: string
|
||||
@@ -12,16 +12,51 @@ export interface GNode {
|
||||
export interface GEdge {
|
||||
id: string
|
||||
source: string
|
||||
sourceHandle: string
|
||||
target: string
|
||||
targetHandle: string
|
||||
kind: EdgeKind
|
||||
label: string | null
|
||||
data: { dead?: boolean }
|
||||
data: { dead: boolean }
|
||||
}
|
||||
|
||||
export interface Row {
|
||||
key: string
|
||||
index: number | null
|
||||
label: string
|
||||
common: boolean
|
||||
shadowed: boolean
|
||||
default: boolean
|
||||
vlessRoute: number[]
|
||||
targetKind: 'outbound' | 'balancer'
|
||||
target: string
|
||||
hasEdge: boolean
|
||||
}
|
||||
|
||||
export interface Section {
|
||||
uuid: string
|
||||
tag: string
|
||||
port: number | null
|
||||
protocol: string | null
|
||||
rows: Row[]
|
||||
}
|
||||
|
||||
export interface PathInfo {
|
||||
nodes: string[]
|
||||
edges: string[]
|
||||
rows: Record<string, { active: string[]; pass: string[] }>
|
||||
}
|
||||
|
||||
export interface Warning {
|
||||
text: string
|
||||
target: string | null
|
||||
}
|
||||
|
||||
export interface Graph {
|
||||
nodes: GNode[]
|
||||
edges: GEdge[]
|
||||
warnings: string[]
|
||||
warnings: Warning[]
|
||||
paths: Record<string, PathInfo>
|
||||
}
|
||||
|
||||
export interface Meta {
|
||||
@@ -35,16 +70,8 @@ export interface Meta {
|
||||
export type Positions = Record<string, { x: number; y: number }>
|
||||
|
||||
export interface GraphResponse {
|
||||
profile: { uuid: string; name: string }
|
||||
graph: Graph
|
||||
positionsKey: string
|
||||
positions: Positions
|
||||
meta: Meta
|
||||
}
|
||||
|
||||
export interface ProfileItem {
|
||||
uuid: string
|
||||
name: string
|
||||
inbounds: number
|
||||
rules: number
|
||||
nodes: string[]
|
||||
}
|
||||
|
||||
Vendored
+1
-1235
File diff suppressed because one or more lines are too long
@@ -1,105 +1,125 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { applyView, toFlow } from '../src/flow'
|
||||
import { autoLayout, COL_X, NODE_HEIGHT } from '../src/layout'
|
||||
import { buildReach, highlightFor } from '../src/reach'
|
||||
import { bpHandles, cardHandles } from '../src/handles'
|
||||
import { highlightFor, rowSelId } from '../src/highlight'
|
||||
import { autoLayout, heightOf, WIDTH } from '../src/layout'
|
||||
import type { Graph } from '../src/types'
|
||||
import raw from './fixtures/graph.json'
|
||||
|
||||
const graph = raw as unknown as Graph
|
||||
const RU = 'node:n-ru'
|
||||
const FI = 'node:n-2'
|
||||
|
||||
describe('handles: карточки рисуют ровно те порты, к которым привязаны рёбра', () => {
|
||||
const nodes = new Map(graph.nodes.map((n) => [n.id, n]))
|
||||
const portsOf = (id: string) => {
|
||||
const n = nodes.get(id)!
|
||||
const defs = n.type === 'node' ? cardHandles(n.data) : bpHandles(n.type, n.data)
|
||||
return { source: new Set(defs.filter((h) => h.type === 'source').map((h) => h.id)), target: new Set(defs.filter((h) => h.type === 'target').map((h) => h.id)) }
|
||||
}
|
||||
it('у каждого ребра есть исходящий и входящий порт', () => {
|
||||
for (const e of graph.edges) {
|
||||
expect(portsOf(e.source).source.has(e.sourceHandle), `${e.id} (source)`).toBe(true)
|
||||
expect(portsOf(e.target).target.has(e.targetHandle), `${e.id} (target)`).toBe(true)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('autoLayout', () => {
|
||||
const pos = autoLayout(graph)
|
||||
const nodes = new Map(graph.nodes.map((n) => [n.id, n]))
|
||||
|
||||
it('даёт позицию каждому узлу', () => {
|
||||
it('даёт позицию каждому блоку', () => {
|
||||
for (const n of graph.nodes) expect(pos[n.id], n.id).toBeDefined()
|
||||
})
|
||||
|
||||
it('узлы одной колонки не перекрываются', () => {
|
||||
const byCol = new Map<number, { y: number; h: number; id: string }[]>()
|
||||
for (const n of graph.nodes) {
|
||||
const x = COL_X[n.type]
|
||||
byCol.set(x, [...(byCol.get(x) ?? []), { y: pos[n.id].y, h: NODE_HEIGHT[n.type], id: n.id }])
|
||||
}
|
||||
for (const items of byCol.values()) {
|
||||
items.sort((a, b) => a.y - b.y)
|
||||
for (let i = 1; i < items.length; i++) {
|
||||
expect(items[i].y, `${items[i - 1].id} / ${items[i].id}`).toBeGreaterThanOrEqual(items[i - 1].y + items[i - 1].h)
|
||||
it('блоки одной колонки не перекрываются', () => {
|
||||
const cols = new Map<number, string[]>()
|
||||
for (const n of graph.nodes) cols.set(pos[n.id].x, [...(cols.get(pos[n.id].x) ?? []), n.id])
|
||||
for (const ids of cols.values()) {
|
||||
const sorted = ids.sort((a, b) => pos[a].y - pos[b].y)
|
||||
for (let i = 1; i < sorted.length; i++) {
|
||||
const prev = nodes.get(sorted[i - 1])!
|
||||
expect(pos[sorted[i]].y, `${sorted[i - 1]} / ${sorted[i]}`).toBeGreaterThanOrEqual(pos[sorted[i - 1]].y + heightOf(prev))
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('правила идут сверху вниз по порядку', () => {
|
||||
const ys = graph.nodes.filter((n) => n.type === 'rule').sort((a, b) => a.data.index - b.data.index).map((n) => pos[n.id].y)
|
||||
expect([...ys].sort((a, b) => a - b)).toEqual(ys)
|
||||
it('поток идёт слева направо: источник каждого ребра левее приёмника', () => {
|
||||
for (const e of graph.edges) {
|
||||
expect(pos[e.source].x + WIDTH[nodes.get(e.source)!.type], e.id).toBeLessThan(pos[e.target].x)
|
||||
}
|
||||
})
|
||||
|
||||
it('хост стоит напротив строки, на которую садится его нитка', () => {
|
||||
const h3 = graph.edges.find((e) => e.source === 'host:h3')!
|
||||
const hostY = pos['host:h3'].y + heightOf(nodes.get('host:h3')!) / 2
|
||||
const ruY = pos[RU].y
|
||||
expect(h3.targetHandle).toBe('rin:inb-bridge:8')
|
||||
// правило #8 лежит ниже шапки карточки; хост не должен висеть выше карточки
|
||||
expect(hostY).toBeGreaterThan(ruY)
|
||||
})
|
||||
})
|
||||
|
||||
describe('reach / highlight', () => {
|
||||
const reach = buildReach(graph)
|
||||
|
||||
it('хост с route 3 доходит до BRIDGE_3 и FI-01, пропуская правила 6 и 7', () => {
|
||||
const r = reach.get('host:h3')!
|
||||
expect(r.nodes.has('out:BRIDGE_3')).toBe(true)
|
||||
expect(r.nodes.has('node:FI-01')).toBe(true)
|
||||
expect(r.nodes.has('out:BRIDGE_4')).toBe(false)
|
||||
expect([...r.pass].sort()).toEqual(['rule:6', 'rule:7'])
|
||||
expect(r.nodes.has('rule:8')).toBe(true)
|
||||
expect(r.pass.has('rule:8')).toBe(false)
|
||||
describe('highlight', () => {
|
||||
it('хост: путь через обе ноды, проверенные строки приглушены', () => {
|
||||
const hl = highlightFor('host:h3', graph)!
|
||||
expect(hl.hostIds).toEqual(['host:h3'])
|
||||
expect(hl.nodes.has(RU) && hl.nodes.has(FI)).toBe(true)
|
||||
const ru = hl.rows.get(RU)!
|
||||
expect(ru.active.has('inb-bridge:8')).toBe(true)
|
||||
expect([...ru.pass].sort()).toEqual(['inb-bridge:6', 'inb-bridge:7'])
|
||||
expect(hl.rows.get(FI)!.active.has('inb:inb-def-ss')).toBe(true)
|
||||
})
|
||||
|
||||
it('хост с route 8 упирается в catch-all и никогда не видит SoundCloud-правила', () => {
|
||||
const r = reach.get('host:h8')!
|
||||
expect(r.nodes.has('rule:13')).toBe(true)
|
||||
expect(r.nodes.has('rule:14')).toBe(false)
|
||||
expect(r.nodes.has('bal:BRIDGE_AUTO')).toBe(true)
|
||||
it('строка: подсвечиваются только хосты, которых она касается', () => {
|
||||
expect(highlightFor(rowSelId(RU, 'inb-bridge:8'), graph)!.hostIds).toEqual(['host:h3'])
|
||||
expect(highlightFor(rowSelId(RU, 'inb-bridge:13'), graph)!.hostIds.sort()).toEqual(['host:h8', 'host:hn'])
|
||||
})
|
||||
|
||||
it('хост другого профиля отсутствует', () => {
|
||||
expect(reach.has('host:hx')).toBe(false)
|
||||
it('нода-приёмник: и мост, и прямое подключение', () => {
|
||||
const ids = highlightFor(FI, graph)!.hostIds
|
||||
expect(ids).toContain('host:hd')
|
||||
expect(ids).toContain('host:h3')
|
||||
expect(ids).toContain('host:h7') // через балансер
|
||||
expect(ids).not.toContain('host:nonexistent')
|
||||
})
|
||||
|
||||
it('клик по ноде подсвечивает хосты, которые на неё выходят', () => {
|
||||
const hl = highlightFor('node:FI-01', reach)!
|
||||
expect(hl.hostIds.sort()).toEqual(['host:h3', 'host:h7', 'host:h8', 'host:hn'])
|
||||
expect(hl.active.has('node:FI-01')).toBe(true)
|
||||
it('недостижимая строка не подсвечивает хостов', () => {
|
||||
expect(highlightFor(rowSelId(RU, 'inb-bridge:14'), graph)!.hostIds).toEqual([])
|
||||
})
|
||||
|
||||
it('клик по недостижимому правилу не подсвечивает ни одного хоста', () => {
|
||||
expect(highlightFor('rule:14', reach)!.hostIds).toEqual([])
|
||||
})
|
||||
|
||||
it('клик по DIRECT подсвечивает все хосты профиля', () => {
|
||||
expect(highlightFor('out:DIRECT', reach)!.hostIds).toHaveLength(4)
|
||||
it('без выбора подсветки нет', () => {
|
||||
expect(highlightFor(null, graph)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('toFlow / applyView', () => {
|
||||
const flow = toFlow(graph, {}, autoLayout(graph))
|
||||
|
||||
it('правило знает свою цель, цепочка идёт через нижний/верхний порт', () => {
|
||||
expect(flow.nodes.find((n) => n.id === 'rule:8')!.data.target).toBe('BRIDGE_3')
|
||||
expect(flow.nodes.find((n) => n.id === 'rule:13')!.data.targetKind).toBe('balancer')
|
||||
const ft = flow.edges.find((e) => e.id.includes('fallthrough'))!
|
||||
expect([ft.sourceHandle, ft.targetHandle]).toEqual(['next', 'prev'])
|
||||
it('нода рисуется карточкой, остальное простыми блоками', () => {
|
||||
expect(flow.nodes.filter((n) => n.type === 'card')).toHaveLength(graph.nodes.filter((n) => n.type === 'node').length)
|
||||
expect(flow.nodes.find((n) => n.id === 'host:h3')!.type).toBe('bp')
|
||||
})
|
||||
|
||||
it('сохранённая позиция важнее автоматической', () => {
|
||||
const f = toFlow(graph, { 'rule:0': { x: 1, y: 2 } }, autoLayout(graph))
|
||||
expect(f.nodes.find((n) => n.id === 'rule:0')!.position).toEqual({ x: 1, y: 2 })
|
||||
const f = toFlow(graph, { [RU]: { x: 1, y: 2 } }, autoLayout(graph))
|
||||
expect(f.nodes.find((n) => n.id === RU)!.position).toEqual({ x: 1, y: 2 })
|
||||
})
|
||||
|
||||
it('hideShadowed скрывает недостижимые правила и их рёбра', () => {
|
||||
const v = applyView(flow.nodes, flow.edges, null, true)
|
||||
expect(v.nodes.filter((n) => n.hidden).length).toBe(8)
|
||||
expect(v.edges.filter((e) => e.hidden).length).toBeGreaterThan(8)
|
||||
})
|
||||
|
||||
it('подсветка: остальное приглушается, позиции не меняются', () => {
|
||||
const hl = highlightFor('host:h3', buildReach(graph))
|
||||
it('подсветка: остальное приглушается, карточки получают строки, позиции не меняются', () => {
|
||||
const hl = highlightFor('host:h3', graph)
|
||||
const v = applyView(flow.nodes, flow.edges, hl, false)
|
||||
expect(v.nodes.find((n) => n.id === 'host:h3')!.class).toContain('active')
|
||||
expect(v.nodes.find((n) => n.id === 'host:h7')!.class).toContain('dim')
|
||||
expect(v.nodes.find((n) => n.id === 'rule:6')!.class).toContain('pass')
|
||||
expect(v.nodes.find((n) => n.id === 'host:h3')!.class).toBe('active')
|
||||
expect(v.nodes.find((n) => n.id === 'host:h7')!.class).toBe('dim')
|
||||
expect(v.nodes.find((n) => n.id === RU)!.data.hl.active).toContain('inb-bridge:8')
|
||||
expect(v.edges.filter((e) => e.animated).length).toBe(hl!.edges.size)
|
||||
expect(v.nodes.map((n) => n.position)).toEqual(flow.nodes.map((n) => n.position))
|
||||
})
|
||||
|
||||
it('hideShadowed и пустая подсветка пробрасываются в карточки', () => {
|
||||
const v = applyView(flow.nodes, flow.edges, null, true)
|
||||
expect(v.nodes.find((n) => n.id === RU)!.data.hideShadowed).toBe(true)
|
||||
expect(v.nodes.find((n) => n.id === RU)!.data.hl).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user