Files
MikrotikManager/tests/e2e/network-map-visual.spec.ts
T
Denozordec 876a61f705
Docker images / prepare-release (push) Successful in 14s
Docker images / backend-test (push) Successful in 12m24s
Docker images / frontend-image (push) Successful in 2m21s
Docker images / updater-image (push) Successful in 41s
Docker images / netflow-agent-image (push) Successful in 32s
Docker images / backend-image (push) Successful in 1m52s
Docker images / publish-release (push) Successful in 17s
Docker images / notify-webhook (push) Successful in 2s
fix(network-map): перенести визуализацию карты из утверждённого прототипа
2026-12-03 11:36:21 +07:00

152 lines
11 KiB
TypeScript

import { mkdir, writeFile } from "node:fs/promises"
import path from "node:path"
import { expect, test } from "@playwright/test"
import { serveMapVisual } from "./fixtures/network-map-visual"
// The approved atlas has 63px device cards, 13px names and 15px row gutters.
// Measure screen coordinates: inspecting SVG attributes alone misses a compressed viewBox.
for (const width of [998, 1320, 320, 390]) {
for (const dense of [false, true]) {
const theme = (width === 998 || width === 390) === !dense ? "dark" : "light"
const size = dense ? "dense" : "ordinary"
test(`Карта сети: физический масштаб и подписи ${width} · ${size} · ${theme}`, async ({ page }, info) => {
await page.setViewportSize({ width, height: width < 500 ? 1040 : 915 })
await page.emulateMedia({ colorScheme: theme, reducedMotion: "reduce" })
await page.addInitScript(scheme => localStorage.setItem("rl-theme", scheme), theme)
await serveMapVisual(page, dense)
await page.goto("/network-map")
const map = page.getByRole("group", { name: "Интерактивная карта сети" })
await expect(map.getByRole("button", { name: "Устройство msk-gw01", exact: true })).toBeVisible()
await expect(map.getByRole("button", { name: "Сервис YouTube", exact: true })).toBeVisible()
await expect(map.getByRole("button", { name: /^Остальные сервисы \(2\)/ })).toBeVisible()
await expect(page.locator("html")).toHaveClass(new RegExp(theme))
await page.evaluate(() => document.fonts.ready)
if (width < 500) {
const lane = page.getByRole("combobox", { name: "Перейти к колонке" })
await lane.selectOption("access-nodes")
await expect(lane).toHaveValue("access-nodes")
await lane.blur()
} else {
await expect(page.getByRole("button", { name: "Боковое меню" })).toHaveAttribute("aria-expanded", "true")
}
const sizes = await map.evaluate(svg => {
const position = (element: Element) => {
const r = element.getBoundingClientRect()
return { x:r.x,y:r.y,w:r.width,h:r.height }
}
const buttons = Array.from(svg.querySelectorAll("g[role=button]"))
const measure = (label: string, word: string, box: string) => {
const node = buttons.find(n => n.getAttribute("aria-label") === label)
const plate = node?.querySelector('[data-map-box="'+box+'"]')
const name = Array.from(node?.querySelectorAll<SVGTextElement>("text") ?? []).find(n => n.textContent?.includes(word))
if (!plate || !name) throw Error("Нет подписанной карточки " + label)
const matrix = name.getScreenCTM()!
return {...position(plate), font:parseFloat(getComputedStyle(name).fontSize)*Math.hypot(matrix.a,matrix.b)}
}
const host = position(svg)
const gateway = measure("Устройство msk-gw01", "msk-gw01","card")
const otherGateway = measure("Устройство msk-gw02", "msk-gw02","card")
const service = measure("Сервис YouTube","YouTube","dest")
const visibleDevice = Array.from(svg.querySelectorAll('[data-map-box="card"]')).map(position)
.filter(card=>card.x+card.w>host.x && card.x<host.x+host.w && card.y+card.h>host.y && card.y<host.y+host.h)
const span = visibleDevice.length ? Math.max(...visibleDevice.map(c=>c.y+c.h))-Math.min(...visibleDevice.map(c=>c.y)) : 0
return {host,gateway,service,span,rowPitch:Math.abs(otherGateway.y-gateway.y), overflow:document.documentElement.scrollWidth-innerWidth}
})
const stage = process.env.MAP_VISUAL_STAGE
if (stage === "before" || stage === "after") {
const folder = path.resolve("work/map-release-preview",stage)
const name = [width,size,theme].join("-")
await mkdir(folder,{recursive:true})
await page.screenshot({path:path.join(folder,name+".png"),animations:"disabled",style:"nextjs-portal { visibility:hidden !important }"})
await writeFile(info.outputPath("geometry.json"),JSON.stringify(sizes,null,2))
}
expect(sizes.overflow, "Горизонтальный скролл принадлежит полотну").toBeLessThanOrEqual(1)
// The reference uses 938px for its six minimum column widths. Surplus space is shared evenly.
const expectedGatewayWidth=Math.min(157,140+Math.max(0,sizes.host.w-938)/6)
expect(Math.abs(sizes.gateway.w-expectedGatewayWidth),"Физическая ширина карточки JH из эталона").toBeLessThanOrEqual(3)
expect(Math.abs(sizes.gateway.h-63),"Физическая высота карточки JH из эталона").toBeLessThanOrEqual(2)
expect(Math.abs(sizes.gateway.font-13),"Размер имени при открытии").toBeLessThanOrEqual(.5)
expect(Math.abs(sizes.service.font-13),"Размер имени сервиса при открытии").toBeLessThanOrEqual(.5)
expect(sizes.service.w/sizes.gateway.w,"Пропорция ширины сервиса и устройства").toBeGreaterThan(0.9)
expect(sizes.service.w/sizes.gateway.w).toBeLessThan(1.35)
expect(sizes.service.h/sizes.gateway.h,"Сервис рисуется полноценной карточкой").toBeGreaterThan(0.85)
expect(sizes.rowPitch,"Между московскими JH остаётся зазор").toBeGreaterThanOrEqual(sizes.gateway.h+8)
const gateway=map.getByRole("button",{name:"Устройство msk-gw01",exact:true})
const roleTile=gateway.locator('[data-role-tile="JH"]')
await expect(roleTile).toHaveAttribute("width","29")
await expect(gateway.locator('[data-country-flag="RU"]')).toHaveCount(1)
await expect(gateway.locator('[data-rate-dir="rx"]')).toContainText("132")
await expect(gateway.locator('[data-rate-dir="tx"]')).toContainText("86")
const youtube=map.getByRole("button",{name:"Сервис YouTube",exact:true})
await expect(youtube.locator('[data-service-brand="YouTube"]')).toHaveCount(1)
await expect(youtube.locator('[data-service-share]')).toHaveCount(1)
await expect(map.locator('[data-map-lane]')).toHaveCount(6)
const nodes=map.locator('g[data-node-kind=device]')
await expect(nodes).toHaveCount(dense ? 9 : 10)
if (dense) {
const hiddenJhs=map.getByRole("button",{name:/^Раскрыть группу.*NSK.*Узлы доступа/i})
await expect(hiddenJhs).toHaveAttribute("aria-expanded","false")
await expect(hiddenJhs).toContainText(/(?:отказ|проблем)\S*\s*·?\s*1/i)
}
const intersections=await map.evaluate(root=>{
const nodes=[...root.querySelectorAll('[data-map-box="card"],[data-map-box="group"],[data-map-box="dest"],[data-map-box="wan"],[data-map-box="access"]')].map(e=>({
name:e.closest('[role=button]')?.getAttribute("aria-label") ?? e.getAttribute("data-map-box"),box:e.getBoundingClientRect()
}))
return nodes.flatMap(({name,box:a},i)=>nodes.slice(i+1).filter(({box:b})=>
Math.min(a.right,b.right)-Math.max(a.left,b.left)>2 && Math.min(a.bottom,b.bottom)-Math.max(a.top,b.top)>2
).map(n=>[name,n.name]))
})
expect(intersections,"Карточки и заголовки групп имеют непересекающиеся области нажатия").toEqual([])
if (width >= 998) {
expect(sizes.span,"Узлы занимают по высоте минимум три ряда карточек").toBeGreaterThan(260)
}
})
}
}
for (const width of [320,1320]) {
test(`Карта сети: расположение карточки назначения и возврат к категории · ${width}`, async ({page})=>{
await page.setViewportSize({width,height:width===320 ? 1040 : 915})
await serveMapVisual(page)
await page.goto("/network-map")
const map=page.getByRole("group",{name:"Интерактивная карта сети"})
const details=page.getByRole("complementary",{name:"Детали объекта карты"})
await page.getByRole("button",{name:"Категории",exact:true}).click()
const category=map.getByRole("button",{name:"Категория CDN",exact:true})
if(width===320)await page.getByRole("combobox",{name:"Перейти к колонке"}).selectOption("destinations")
await category.press("Enter")
await expect(details.getByRole("heading",{name:"CDN",exact:true})).toBeVisible()
await details.getByRole("button",{name:/^Cloudflare/}).click()
await expect(details.getByRole("heading",{name:"Cloudflare",exact:true})).toBeVisible()
const bounds=await details.boundingBox(),canvas=await map.boundingBox()
if (!bounds || !canvas) throw Error("Нет карты или карточки выбранного сервиса")
if (width===320) expect(bounds.y).toBeGreaterThanOrEqual(canvas.y+canvas.height-2)
else expect(bounds.x).toBeGreaterThanOrEqual(canvas.x+canvas.width-2)
expect(bounds.height,"Панель не схлопнулась после включения contain:size").toBeGreaterThan(220)
const scroll=await details.evaluate(aside=>{
const body=Array.from(aside.querySelectorAll<HTMLElement>("div")).find(el=>el.classList.contains("flex-1") && getComputedStyle(el).overflowY==="auto")
if (!body) return null
const max=body.scrollHeight-body.clientHeight
body.scrollTop=max
const reached=body.scrollTop
body.scrollTop=0
return {client:body.clientHeight,max,reached}
})
expect(scroll).not.toBeNull()
expect(scroll!.client).toBeGreaterThan(70)
expect(scroll!.reached).toBeGreaterThanOrEqual(scroll!.max-1)
if(width===1320 && process.env.MAP_VISUAL_STAGE==="after"){
await page.screenshot({path:path.resolve("work/map-release-preview/after/1320-service-inspector.png"),animations:"disabled",style:"nextjs-portal { visibility:hidden !important }"})
}
expect(await page.evaluate(()=>document.documentElement.scrollWidth-innerWidth)).toBeLessThanOrEqual(1)
await details.getByRole("button",{name:"Назад к предыдущему объекту"}).click()
await expect(details.getByRole("heading",{name:"CDN",exact:true})).toBeVisible()
const workbench=page.getByRole("region",{name:"Рабочая панель карты"})
await workbench.getByRole("tab",{name:/^Назначения/}).click()
await expect(workbench.locator("table")).toBeVisible()
expect((await map.boundingBox())!.height,"Раскрытая диагностика не обрезает холст").toBeGreaterThanOrEqual(canvas.height-2)
})
}