From a64b0e47a18c54d960291763aa4ec843f10ff9e7 Mon Sep 17 00:00:00 2001 From: "i.seliverstov" Date: Thu, 5 Nov 2026 16:01:18 +0500 Subject: [PATCH 1/7] docs: plan radial sprint map redesign --- docs/tasks/radial-sprint-map.md | 46 +++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 docs/tasks/radial-sprint-map.md diff --git a/docs/tasks/radial-sprint-map.md b/docs/tasks/radial-sprint-map.md new file mode 100644 index 0000000..57f2796 --- /dev/null +++ b/docs/tasks/radial-sprint-map.md @@ -0,0 +1,46 @@ +# Радиальная карта спринта + +**Status:** executing +**Branch:** codex/radial-sprint-map +**Worktree:** /Users/v/projects/Alfy/.worktrees/radial-sprint-map +**Base:** 278625d (main) +**Mode:** hands-off +**Goal:** Пользователь обозревает большой спринт как радиальное дерево, раскрывает нужную ветку и видит задачи/готовность без вытянутой турнирной сетки. Useless if: подписи накладываются, обзор скрывает работу без раскрытия, зависимости проходят под карточками, поиск/collapse/fullscreen перестают работать. + +## Context +- Пользователь считает растущую турнирную сетку неудобной и прямо просит радиальное отображение. +- Существующая карта уже имеет общий редактор, зависимости, сохранённые свёрнутые ветки и fullscreen; меняется визуальная проекция, не данные. + +## Design +Спринт в центре, эпики на первом кольце, истории и задачи на следующих. Горизонтальные карточки сохраняют название, статус, готовность и действия. Угловые сектора пропорциональны числу видимых листьев; радиусы учитывают размеры карточек и угловые расстояния. Уровни детализации «Эпики / Истории / Задачи» дают быстрый обзор и раскрытие без потери данных. Новые scope начинают с обзора историй, сохранённые ветки сохраняются; поиск раскрывает путь и возвращает читаемый масштаб. + +Выбрана полноценная радиальная раскладка с адаптивными кольцами; простое вращение старой сетки сохраняет вытянутый размер. Свободное force-расположение потребовало бы нестабильных позиций и нового движка. Связи иерархии идут между краями карточек, зависимости сохраняют пунктир/наконечники и обходят видимые карточки. API, состав спринта и прогресс неизменны. +TDD: yes — детерминированная геометрия, отсутствие наложений, обход препятствий, детализация и поиск; качество проверяется в браузере на малом и большом спринте. + +### Invariants +- IV1 — спринт в центре, глубина дерева растёт по радиусу, подписи горизонтальны, видимые карточки не перекрываются. +- IV2 — сворачивание/детализация/поиск не меняют состав или прогресс; скрытая работа раскрывается и доступна по ссылкам. +- IV3 — зависимости направлены, не проходят сквозь карточки, скрытые/внешние концы остаются доступны в панели. +- IV4 — fullscreen, preview, постоянные ссылки, создание, клавиатура и narrow viewport сохраняют работу. + +## Plan +### PH1 — Радиальная геометрия +- features/projects/lib/sprint-map-layout.ts и tests/features/projects/lib/sprint-map-layout.spec.ts: заменить колонки кольцами, сектора по видимому дереву, адаптивный радиус, bounds, связи с краёв карточек. Проверить 0/1/100+ задач, несбалансированные ветви, collapse и детерминизм. Commit: feat(canvas): arrange sprint work in radial rings. +### PH2 — Маршруты зависимостей +- features/projects/lib/sprint-map-dependencies.ts, дополнительные routing helpers при необходимости, tests/features/projects/lib/sprint-map-dependencies.spec.ts: обработка произвольных x/y, обход всех видимых карточек и bounds всех направлений, включая loop collapsed endpoints и пересекающиеся связи. Commit: fix(canvas): route dependencies around radial nodes. +### PH3 — Обзор и интеграция +- SprintMapCanvas.vue, SprintMapNode.vue, use-sprint-map-viewport.ts, ProjectMapView.vue и связанные UI tests: потребить геометрию/bounds, уровни детализации, initial story overview, тексты, fullscreen и focus. README/CLAUDE/task: актуальное поведение и доказательства. Commit: feat(canvas): add radial sprint overview controls. + +### Interfaces +- IF1 — layoutSprintMap(root,collapsed) -> {nodes:PositionedMapNode[],edges:MapEdge[],width,height}; PositionedMapNode и MapEdge сохраняют существующие поля; x/y — левый верхний угол горизонтальной карточки. Root center равен width/2,height/2; все карточки внутри padding. Сектора/радиусы — внутренние детали layout. +- IF2 — deriveSprintMapDependencies(input) сохраняет waiting, links, minX и добавляет bounds:{minX,minY,maxX,maxY}, включающие линии/порты/маркеры; при отсутствии путей bounds нулевые. Canvas объединяет layout bounds с bounds зависимостей; viewport.fit принимает optional x/y origin. + +### Interface graph +- PH1 -> IF1 @ alfy-bot-frontend/src/features/projects/lib/sprint-map-layout.ts alfy-bot-frontend/tests/features/projects/lib/sprint-map-layout.spec.ts +- PH2 IF1 -> IF2 @ alfy-bot-frontend/src/features/projects/lib/sprint-map-dependencies.ts alfy-bot-frontend/src/features/projects/lib/sprint-map-dependency-routing.ts alfy-bot-frontend/tests/features/projects/lib/sprint-map-dependencies.spec.ts +- PH3 IF1, IF2 -> @ alfy-bot-frontend/src/features/projects/ui/SprintMapCanvas.vue alfy-bot-frontend/src/features/projects/ui/SprintMapNode.vue alfy-bot-frontend/src/features/projects/lib/use-sprint-map-viewport.ts alfy-bot-frontend/src/views/ProjectMapView.vue alfy-bot-frontend/tests/features/projects/ui/SprintMapCanvas.spec.ts alfy-bot-frontend/tests/views/ProjectMapView.spec.ts README.md CLAUDE.md alfy-bot-frontend/README.md docs/tasks/radial-sprint-map.md + +## Conclusion +### Hands-off decisions +- udesign/uplan: радиальная раскладка и быстрые уровни детализации, новый scope по историям — прямое исправление жалобы на рост полотна, сохранённое раскрытие не теряется; план auto-approved. +- git-worktrees: отдельный codex/radial-sprint-map от main 278625d, собственный npm ci; локальный preview использует существующий изолированный dev API 3019, прод пока не изменяется. From 550f0f67030f33b5403c7ab7ee85597c1d730862 Mon Sep 17 00:00:00 2001 From: "i.seliverstov" Date: Thu, 5 Nov 2026 16:13:44 +0500 Subject: [PATCH 2/7] feat(canvas): arrange sprint work in radial rings --- .../projects/lib/sprint-map-layout.ts | 177 ++++++++++++--- .../projects/lib/sprint-map-layout.spec.ts | 211 ++++++++++++++++-- 2 files changed, 333 insertions(+), 55 deletions(-) diff --git a/alfy-bot-frontend/src/features/projects/lib/sprint-map-layout.ts b/alfy-bot-frontend/src/features/projects/lib/sprint-map-layout.ts index 19640ed..9f8a107 100644 --- a/alfy-bot-frontend/src/features/projects/lib/sprint-map-layout.ts +++ b/alfy-bot-frontend/src/features/projects/lib/sprint-map-layout.ts @@ -20,51 +20,156 @@ export interface MapEdge { path: string } -const columns: Record = { task: 0, story: 1, epic: 2, ungrouped: 2, sprint: 3 } +interface RadialNode { + node: SprintMapNode + children: RadialNode[] + leaves: number + angle: number + x: number + y: number +} + +const GEOMETRY_EPSILON = 0.0000001 +const MAP_RING_GAP = Math.hypot(MAP_NODE_WIDTH, MAP_NODE_HEIGHT) + MAP_ROW_GAP + +interface Point { x: number, y: number } +type CubicCurve = [Point, Point, Point] +interface EdgeGeometry { start: Point, curves: CubicCurve[] } + +function axisInterval(direction: number, center: number, clearance: number): [number, number] | null { + if (Math.abs(direction) < GEOMETRY_EPSILON) + return Math.abs(center) < clearance ? [-Infinity, Infinity] : null + const first = (center - clearance) / direction + const second = (center + clearance) / direction + return [Math.min(first, second), Math.max(first, second)] +} + +function collisionInterval(node: RadialNode, inner: RadialNode): [number, number] | null { + const x = axisInterval(Math.cos(node.angle), inner.x, MAP_NODE_WIDTH + MAP_ROW_GAP) + const y = axisInterval(Math.sin(node.angle), inner.y, MAP_NODE_HEIGHT + MAP_ROW_GAP) + if (!x || !y) + return null + const start = Math.max(x[0], y[0]) + const end = Math.min(x[1], y[1]) + return start < end ? [start, end] : null +} + +function ringRadius(ring: RadialNode[], inner: RadialNode[], previousRadius: number): number { + let radius = previousRadius + MAP_RING_GAP + ring.forEach((node, index) => { + for (const other of ring.slice(index + 1)) { + const x = Math.abs(Math.cos(node.angle) - Math.cos(other.angle)) + const y = Math.abs(Math.sin(node.angle) - Math.sin(other.angle)) + radius = Math.max(radius, Math.min((MAP_NODE_WIDTH + MAP_ROW_GAP) / x, (MAP_NODE_HEIGHT + MAP_ROW_GAP) / y)) + } + }) + const intervals = ring.flatMap(node => inner.map(other => collisionInterval(node, other)).filter((interval): interval is [number, number] => interval !== null)) + intervals.sort((a, b) => a[0] - b[0]) + for (const [start, end] of intervals) { + if (radius < start) + break + if (radius <= end) + radius = end + GEOMETRY_EPSILON + } + return radius + GEOMETRY_EPSILON +} + +function radialPoint(center: Point, radius: number, angle: number): Point { + return { x: center.x + radius * Math.cos(angle), y: center.y + radius * Math.sin(angle) } +} -/** Раскладывает видимые ветки по уровням в пикселях; свёрнутые узлы сохраняют исходные данные и занимают место одной карточки. */ +function borderRadius(angle: number): number { + return Math.min(MAP_NODE_WIDTH / 2 / Math.abs(Math.cos(angle)), MAP_NODE_HEIGHT / 2 / Math.abs(Math.sin(angle))) +} + +function straightCurve(start: Point, end: Point): CubicCurve { + const dx = (end.x - start.x) / 3 + const dy = (end.y - start.y) / 3 + return [{ x: start.x + dx, y: start.y + dy }, { x: end.x - dx, y: end.y - dy }, end] +} + +function edgeGeometry(child: RadialNode, parent: RadialNode): EdgeGeometry { + const center = { x: 0, y: 0 } + const childRadius = Math.hypot(child.x, child.y) + const parentRadius = Math.hypot(parent.x, parent.y) + const parentAngle = parentRadius === 0 ? child.angle : parent.angle + const start = radialPoint(center, childRadius - borderRadius(child.angle), child.angle) + const end = radialPoint(center, parentRadius + borderRadius(parentAngle), parentAngle) + if (parentRadius === 0) + return { start, curves: [straightCurve(start, end)] } + + const radius = (childRadius + parentRadius) / 2 + const first = radialPoint(center, radius, child.angle) + const curves: CubicCurve[] = [straightCurve(start, first)] + const steps = Math.ceil(Math.abs(parentAngle - child.angle) / (Math.PI / 8)) + let angle = child.angle + for (let step = 1; step <= steps; step++) { + const nextAngle = child.angle + (parentAngle - child.angle) * step / steps + const a = radialPoint(center, radius, angle) + const b = radialPoint(center, radius, nextAngle) + const tangent = 4 / 3 * Math.tan((nextAngle - angle) / 4) * radius + curves.push([{ x: a.x - tangent * Math.sin(angle), y: a.y + tangent * Math.cos(angle) }, { x: b.x + tangent * Math.sin(nextAngle), y: b.y - tangent * Math.cos(nextAngle) }, b]) + angle = nextAngle + } + curves.push(straightCurve(radialPoint(center, radius, parentAngle), end)) + return { start, curves } +} + +function edgePath(geometry: EdgeGeometry, center: Point): string { + const coordinates = (point: Point) => `${point.x + center.x} ${point.y + center.y}` + return `M${coordinates(geometry.start)}${geometry.curves.map(curve => ` C${curve.map(coordinates).join(' ')}`).join('')}` +} + +/** Размещает видимые узлы на кольцах по глубине дерева в пикселях; центр спринта совпадает с центром полотна, карточки разделены отступом и сохраняют исходные данные. */ export function layoutSprintMap(root: SprintMapNode, collapsed: ReadonlySet): { nodes: PositionedMapNode[] edges: MapEdge[] width: number height: number } { - const nodes: PositionedMapNode[] = [] - const edges: MapEdge[] = [] - let nextY = MAP_PADDING - - function place(node: SprintMapNode): PositionedMapNode { - const positioned: PositionedMapNode = { - node, - x: MAP_PADDING + columns[node.kind] * (MAP_NODE_WIDTH + MAP_COLUMN_GAP), - y: nextY, - width: MAP_NODE_WIDTH, - height: MAP_NODE_HEIGHT, - } - nodes.push(positioned) - const children = collapsed.has(node.key) ? [] : node.children.map(place) - const first = children[0] - const [last] = children.slice(-1) - if (first && last) - positioned.y = (first.y + last.y) / 2 - else - nextY += MAP_NODE_HEIGHT + MAP_ROW_GAP - - for (const child of children) { - const startX = child.x + child.width - const startY = child.y + child.height / 2 - const endY = positioned.y + positioned.height / 2 - const bendX = positioned.x - MAP_COLUMN_GAP / 2 - edges.push({ from: child.node.key, to: node.key, path: `M${startX} ${startY} H${bendX} V${endY} H${positioned.x}` }) + const rings: RadialNode[][] = [] + const radialNodes: RadialNode[] = [] + + function collect(node: SprintMapNode, depth: number): RadialNode { + const entry: RadialNode = { node, children: [], leaves: 1, angle: 0, x: 0, y: 0 } + radialNodes.push(entry) + const ring = rings[depth] ??= [] + ring.push(entry) + entry.children = collapsed.has(node.key) ? [] : node.children.map(child => collect(child, depth + 1)) + entry.leaves = Math.max(1, entry.children.reduce((total, child) => total + child.leaves, 0)) + return entry + } + + function assignSectors(node: RadialNode, start: number, span: number) { + node.angle = start + span / 2 + let childStart = start + for (const child of node.children) { + const childSpan = span * child.leaves / node.leaves + assignSectors(child, childStart, childSpan) + childStart += childSpan } - return positioned } - place(root) - return { - nodes, - edges, - width: MAP_PADDING * 2 + 4 * MAP_NODE_WIDTH + 3 * MAP_COLUMN_GAP, - height: nextY - MAP_ROW_GAP + MAP_PADDING, + const rootEntry = collect(root, 0) + assignSectors(rootEntry, -Math.PI / 2, Math.PI * 2) + const inner = [rootEntry] + let previousRadius = 0 + for (const ring of rings.slice(1)) { + const radius = ringRadius(ring, inner, previousRadius) + for (const node of ring) { + node.x = radius * Math.cos(node.angle) + node.y = radius * Math.sin(node.angle) + } + inner.push(...ring) + previousRadius = radius } + + const connections = radialNodes.flatMap(parent => parent.children.map(child => ({ from: child.node.key, to: parent.node.key, geometry: edgeGeometry(child, parent) }))) + const edgePoints = connections.flatMap(({ geometry }) => [geometry.start, ...geometry.curves.flat()]) + const halfWidth = Math.max(...radialNodes.map(node => Math.abs(node.x) + MAP_NODE_WIDTH / 2), ...edgePoints.map(point => Math.abs(point.x))) + MAP_PADDING + const halfHeight = Math.max(...radialNodes.map(node => Math.abs(node.y) + MAP_NODE_HEIGHT / 2), ...edgePoints.map(point => Math.abs(point.y))) + MAP_PADDING + const nodes = radialNodes.map(({ node, x, y }) => ({ node, x: x + halfWidth - MAP_NODE_WIDTH / 2, y: y + halfHeight - MAP_NODE_HEIGHT / 2, width: MAP_NODE_WIDTH, height: MAP_NODE_HEIGHT })) + const center = { x: halfWidth, y: halfHeight } + const edges = connections.map(({ from, to, geometry }) => ({ from, to, path: edgePath(geometry, center) })) + return { nodes, edges, width: halfWidth * 2, height: halfHeight * 2 } } diff --git a/alfy-bot-frontend/tests/features/projects/lib/sprint-map-layout.spec.ts b/alfy-bot-frontend/tests/features/projects/lib/sprint-map-layout.spec.ts index 3fb3e92..60f1745 100644 --- a/alfy-bot-frontend/tests/features/projects/lib/sprint-map-layout.spec.ts +++ b/alfy-bot-frontend/tests/features/projects/lib/sprint-map-layout.spec.ts @@ -1,6 +1,7 @@ import type { SprintMapNode } from '@/features/projects/lib/sprint-map' +import type { PositionedMapNode } from '@/features/projects/lib/sprint-map-layout' import { describe, expect, it } from 'vitest' -import { layoutSprintMap, MAP_COLUMN_GAP, MAP_NODE_HEIGHT, MAP_NODE_WIDTH, MAP_PADDING, MAP_ROW_GAP } from '@/features/projects/lib/sprint-map-layout' +import { layoutSprintMap, MAP_NODE_HEIGHT, MAP_NODE_WIDTH, MAP_PADDING, MAP_ROW_GAP } from '@/features/projects/lib/sprint-map-layout' function node(kind: SprintMapNode['kind'], id: string, children: SprintMapNode[] = []): SprintMapNode { return { key: `${kind}:${id}`, kind, sourceId: id, title: id, statusLabel: '', statusCategory: 'open', statusColor: null, total: 4, done: 2, outsideCount: 0, blockedReason: null, releases: [], children } @@ -10,21 +11,153 @@ function tree() { return node('sprint', 's', [node('epic', 'e', [node('story', 'a', [node('task', '1'), node('task', '2')]), node('story', 'b', [node('task', '3')]), node('task', 'direct')]), node('ungrouped', 'u', [node('task', '4')])]) } +function radius(item: PositionedMapNode, width: number, height: number) { + return Math.hypot(item.x + item.width / 2 - width / 2, item.y + item.height / 2 - height / 2) +} + +function expectSeparated(result: ReturnType) { + result.nodes.forEach((item, index) => { + expect(item).toMatchObject({ width: MAP_NODE_WIDTH, height: MAP_NODE_HEIGHT }) + expect(item.x).toBeGreaterThanOrEqual(MAP_PADDING - 0.000001) + expect(item.y).toBeGreaterThanOrEqual(MAP_PADDING - 0.000001) + expect(item.x + item.width).toBeLessThanOrEqual(result.width - MAP_PADDING + 0.000001) + expect(item.y + item.height).toBeLessThanOrEqual(result.height - MAP_PADDING + 0.000001) + for (const other of result.nodes.slice(index + 1)) { + const gapX = Math.abs(item.x - other.x) - MAP_NODE_WIDTH + const gapY = Math.abs(item.y - other.y) - MAP_NODE_HEIGHT + expect(Math.max(gapX, gapY), `${item.node.key} / ${other.node.key}`).toBeGreaterThanOrEqual(MAP_ROW_GAP - 0.000001) + } + }) +} + +function onBorder(point: number[], item: PositionedMapNode) { + const [x = 0, y = 0] = point + const horizontal = Math.abs(x - item.x) < 0.000001 || Math.abs(x - item.x - item.width) < 0.000001 + const vertical = Math.abs(y - item.y) < 0.000001 || Math.abs(y - item.y - item.height) < 0.000001 + expect(horizontal || vertical).toBe(true) + expect(x).toBeGreaterThanOrEqual(item.x - 0.000001) + expect(x).toBeLessThanOrEqual(item.x + item.width + 0.000001) + expect(y).toBeGreaterThanOrEqual(item.y - 0.000001) + expect(y).toBeLessThanOrEqual(item.y + item.height + 0.000001) +} + +function segmentCrossesCard(start: number[], end: number[], card: PositionedMapNode): boolean { + let enter = 0 + let exit = 1 + const bounds = [[card.x, card.x + card.width], [card.y, card.y + card.height]] + for (let axis = 0; axis < 2; axis++) { + const origin = start[axis]! + const delta = end[axis]! - origin + const [min = 0, max = 0] = bounds[axis]! + if (Math.abs(delta) < 0.0000001) { + if (origin <= min || origin >= max) + return false + continue + } + const first = (min - origin) / delta + const second = (max - origin) / delta + enter = Math.max(enter, Math.min(first, second)) + exit = Math.min(exit, Math.max(first, second)) + } + return enter < exit +} + +function expectEdgesInsideBounds(result: ReturnType) { + for (const edge of result.edges) { + const coordinates = edge.path.match(/-?\d+(?:\.\d+)?(?:e[+-]?\d+)?/gi)!.map(Number) + for (let index = 0; index < coordinates.length; index += 2) { + expect(coordinates[index], `${edge.from} x`).toBeGreaterThanOrEqual(MAP_PADDING - 0.000001) + expect(coordinates[index], `${edge.from} x`).toBeLessThanOrEqual(result.width - MAP_PADDING + 0.000001) + expect(coordinates[index + 1], `${edge.from} y`).toBeGreaterThanOrEqual(MAP_PADDING - 0.000001) + expect(coordinates[index + 1], `${edge.from} y`).toBeLessThanOrEqual(result.height - MAP_PADDING + 0.000001) + } + } +} + +function expectEdgesOutsideCards(result: ReturnType) { + const intersections = new Set() + for (const edge of result.edges) { + const coordinates = edge.path.match(/-?\d+(?:\.\d+)?(?:e[+-]?\d+)?/gi)!.map(Number) + let x = coordinates[0]! + let y = coordinates[1]! + for (let index = 2; index < coordinates.length; index += 6) { + const [ax = 0, ay = 0, bx = 0, by = 0, cx = 0, cy = 0] = coordinates.slice(index, index + 6) + let previous = [x, y] + for (let sample = 1; sample <= 64; sample++) { + const t = sample / 64 + const pointX = (1 - t) ** 3 * x + 3 * (1 - t) ** 2 * t * ax + 3 * (1 - t) * t ** 2 * bx + t ** 3 * cx + const pointY = (1 - t) ** 3 * y + 3 * (1 - t) ** 2 * t * ay + 3 * (1 - t) * t ** 2 * by + t ** 3 * cy + for (const card of result.nodes) { + if (card.node.key === edge.from || card.node.key === edge.to) + continue + if (segmentCrossesCard(previous, [pointX, pointY], card)) + intersections.add(`${edge.from} → ${edge.to} intersects ${card.node.key}`) + } + previous = [pointX, pointY] + } + x = cx + y = cy + } + } + expect([...intersections]).toEqual([]) +} + describe('layoutSprintMap', () => { - it('размещает уровни слева направо и соединяет детей с родителями', () => { + it('включает дуги редких веток в симметричные границы полотна с отступом', () => { + for (const count of [2, 3, 5, 24]) { + const root = node('sprint', 's', [node('epic', 'e', [node('story', 'a', Array.from({ length: count }, (_, index) => node('task', `${index}`)))])]) + const result = layoutSprintMap(root, new Set()) + expect(result.nodes[0]).toMatchObject({ x: result.width / 2 - MAP_NODE_WIDTH / 2, y: result.height / 2 - MAP_NODE_HEIGHT / 2 }) + expectEdgesInsideBounds(result) + } + }) + + it('ведёт иерархию широкой одиночной ветки вокруг центральных карточек', () => { + const root = node('sprint', 's', [node('epic', 'e', [node('story', 'a', Array.from({ length: 24 }, (_, index) => node('task', `${index}`)))])]) + expectEdgesOutsideCards(layoutSprintMap(root, new Set())) + }) + + it('располагает спринт в центре и семантическую глубину дерева на общих кольцах', () => { const result = layoutSprintMap(tree(), new Set()) + const byKey = new Map(result.nodes.map(item => [item.node.key, item])) expect(result.nodes).toHaveLength(10) - const columns = { task: 0, story: 1, epic: 2, ungrouped: 2, sprint: 3 } - for (const item of result.nodes) { - expect(item.x).toBe(MAP_PADDING + columns[item.node.kind] * (MAP_NODE_WIDTH + MAP_COLUMN_GAP)) - expect(item).toMatchObject({ width: MAP_NODE_WIDTH, height: MAP_NODE_HEIGHT }) - expect(item.y).toBeGreaterThanOrEqual(MAP_PADDING) - expect(item.x + item.width).toBeLessThanOrEqual(result.width - MAP_PADDING) - expect(item.y + item.height).toBeLessThanOrEqual(result.height - MAP_PADDING) + expect(byKey.get('sprint:s')).toMatchObject({ x: result.width / 2 - MAP_NODE_WIDTH / 2, y: result.height / 2 - MAP_NODE_HEIGHT / 2 }) + const rings = [['sprint:s'], ['epic:e', 'ungrouped:u'], ['story:a', 'story:b', 'task:direct', 'task:4'], ['task:1', 'task:2', 'task:3']] + let previousRadius = -1 + for (const keys of rings) { + const distances = keys.map(key => radius(byKey.get(key)!, result.width, result.height)) + distances.forEach(distance => expect(distance).toBeCloseTo(distances[0]!, 6)) + expect(distances[0]).toBeGreaterThan(previousRadius) + previousRadius = distances[0]! + } + expectSeparated(result) + }) + + it('распределяет соседние ветки по непрерывным секторам пропорционально видимым листьям', () => { + const root = node('sprint', 's', [node('epic', 'large', Array.from({ length: 3 }, (_, index) => node('task', `${index}`))), node('epic', 'small')]) + const result = layoutSprintMap(root, new Set()) + const angle = (key: string) => { + const item = result.nodes.find(item => item.node.key === key)! + return Math.atan2(item.y + item.height / 2 - result.height / 2, item.x + item.width / 2 - result.width / 2) } + expect(angle('epic:large')).toBeCloseTo(Math.PI / 4, 6) + expect(angle('epic:small')).toBeCloseTo(-3 * Math.PI / 4, 6) + expect(angle('task:0')).toBeCloseTo(-Math.PI / 4, 6) + expect(angle('task:1')).toBeCloseTo(Math.PI / 4, 6) + expect(angle('task:2')).toBeCloseTo(3 * Math.PI / 4, 6) + }) + + it('соединяет края карточек детей и родителей без стрелок', () => { + const result = layoutSprintMap(tree(), new Set()) expect(result.edges).toHaveLength(9) expect(result.edges.find(edge => edge.from === 'task:1')).toMatchObject({ to: 'story:a' }) - expect(result.edges.every(edge => /^M[\d .-]+ H[\d .-]+ V[\d .-]+ H[\d .-]+$/.test(edge.path))).toBe(true) + for (const edge of result.edges) { + expect(edge.path).toMatch(/^M[-\d.e ]+(?: C[-\d.e ]+)+$/i) + const coordinates = edge.path.match(/-?\d+(?:\.\d+)?(?:e[+-]?\d+)?/gi)!.map(Number) + onBorder(coordinates.slice(0, 2), result.nodes.find(item => item.node.key === edge.from)!) + onBorder(coordinates.slice(-2), result.nodes.find(item => item.node.key === edge.to)!) + expect(coordinates.every(Number.isFinite)).toBe(true) + } }) it('сворачивает потомков и уплотняет карту без изменения данных и прогресса', () => { @@ -32,34 +165,74 @@ describe('layoutSprintMap', () => { const before = JSON.stringify(root) const result = layoutSprintMap(root, new Set(['epic:e'])) expect(result.nodes.map(item => item.node.key).sort()).toEqual(['sprint:s', 'epic:e', 'ungrouped:u', 'task:4'].sort()) - expect(result.height).toBeLessThan(layoutSprintMap(root, new Set()).height) + expect(result.width * result.height).toBeLessThan(layoutSprintMap(root, new Set()).width * layoutSprintMap(root, new Set()).height) expect(result.nodes.find(item => item.node.key === 'epic:e')?.node).toMatchObject({ done: 2, total: 4 }) expect(JSON.stringify(root)).toBe(before) }) - it('не перекрывает карточки одного уровня при любых свёрнутых ветках', () => { + it('не перекрывает любые пары карточек при всех комбинациях свёрнутых веток', () => { const root = tree() const branches = ['sprint:s', 'epic:e', 'story:a', 'story:b', 'ungrouped:u'] for (let mask = 0; mask < 2 ** branches.length; mask++) { const collapsed = new Set(branches.filter((_, index) => mask & (1 << index))) const result = layoutSprintMap(root, collapsed) expect(result.nodes.length).toBeGreaterThan(0) - for (const item of result.nodes) { - for (const other of result.nodes) { - if (item.node.key !== other.node.key && item.x === other.x) - expect(Math.abs(item.y - other.y)).toBeGreaterThanOrEqual(MAP_NODE_HEIGHT + MAP_ROW_GAP) - } - } + expectSeparated(result) + expectEdgesOutsideCards(result) + expectEdgesInsideBounds(result) expect(layoutSprintMap(root, collapsed)).toEqual(result) } }) - it('показывает пустой или свёрнутый спринт одной карточкой', () => { + it('размещает 120 задач без наложений и сохраняет компактный обзор историй', () => { + const stories: string[] = [] + const root = node('sprint', 'large', Array.from({ length: 6 }, (_, epic) => node('epic', `${epic}`, Array.from({ length: 4 }, (_, story) => { + const id = `${epic}-${story}` + stories.push(`story:${id}`) + return node('story', id, Array.from({ length: 5 }, (_, task) => node('task', `${id}-${task}`))) + })))) + const expanded = layoutSprintMap(root, new Set()) + const overview = layoutSprintMap(root, new Set(stories)) + expect(expanded.nodes).toHaveLength(151) + expect(overview.nodes).toHaveLength(31) + expectSeparated(expanded) + expectSeparated(overview) + expectEdgesOutsideCards(expanded) + expectEdgesOutsideCards(overview) + expectEdgesInsideBounds(expanded) + expectEdgesInsideBounds(overview) + expect(Math.max(expanded.width, expanded.height)).toBeLessThan(16000) + expect(Math.max(overview.width, overview.height)).toBeLessThan(4000) + expect(overview.width * overview.height).toBeLessThan(expanded.width * expanded.height / 4) + }) + + it('разводит узкие соседние сектора несбалансированного дерева на разных глубинах', () => { + const root = node('sprint', 'unbalanced', [node('epic', 'large', [node('story', 'many', Array.from({ length: 110 }, (_, index) => node('task', `${index}`))), node('story', 'small', [node('task', 'single')])]), node('epic', 'empty'), node('task', 'direct')]) + for (const collapsed of [new Set(), new Set(['story:many']), new Set(['epic:large'])]) { + const result = layoutSprintMap(root, collapsed) + expectSeparated(result) + expectEdgesOutsideCards(result) + expectEdgesInsideBounds(result) + } + }) + + it('поддерживает спринты без задач и с одной прямой задачей', () => { + for (const children of [[], [node('task', 'only')]]) { + const result = layoutSprintMap(node('sprint', 's', children), new Set()) + expect(result.nodes).toHaveLength(children.length + 1) + expect(result.edges).toHaveLength(children.length) + expectSeparated(result) + } + }) + + it('показывает пустой или свёрнутый спринт одной центральной карточкой', () => { for (const root of [node('sprint', 's'), tree()]) { const result = layoutSprintMap(root, new Set(['sprint:s'])) expect(result.nodes).toHaveLength(1) expect(result.edges).toEqual([]) + expect(result.width).toBe(MAP_NODE_WIDTH + 2 * MAP_PADDING) expect(result.height).toBe(MAP_NODE_HEIGHT + 2 * MAP_PADDING) + expect(result.nodes[0]).toMatchObject({ x: MAP_PADDING, y: MAP_PADDING }) } }) }) From 3649603a81b60f655cc31ccbc3f06dcfd9ae83bf Mon Sep 17 00:00:00 2001 From: "i.seliverstov" Date: Thu, 5 Nov 2026 16:13:44 +0500 Subject: [PATCH 3/7] fix(canvas): route dependencies around radial nodes --- .../projects/lib/sprint-map-dependencies.ts | 40 +--- .../lib/sprint-map-dependency-routing.ts | 212 ++++++++++++++++++ .../lib/sprint-map-dependencies.spec.ts | 93 +++++++- 3 files changed, 302 insertions(+), 43 deletions(-) create mode 100644 alfy-bot-frontend/src/features/projects/lib/sprint-map-dependency-routing.ts diff --git a/alfy-bot-frontend/src/features/projects/lib/sprint-map-dependencies.ts b/alfy-bot-frontend/src/features/projects/lib/sprint-map-dependencies.ts index c6aa84b..ff6dcc7 100644 --- a/alfy-bot-frontend/src/features/projects/lib/sprint-map-dependencies.ts +++ b/alfy-bot-frontend/src/features/projects/lib/sprint-map-dependencies.ts @@ -1,7 +1,9 @@ import type { SprintMapNode } from './sprint-map' +import type { SprintMapDependencyBounds } from './sprint-map-dependency-routing' import type { PositionedMapNode } from './sprint-map-layout' import type { TaskDependencyEdge } from '@/features/tasks/model/task-dependencies' import type { Task } from '@/features/tasks/model/types' +import { routeSprintMapDependencies } from './sprint-map-dependency-routing' export interface SprintMapDependency extends TaskDependencyEdge { predecessor: Task | null @@ -38,41 +40,8 @@ function taskEndpoints(root: SprintMapNode, visibleNodes: PositionedMapNode[]) { return endpoints } -function routeDependencies(links: SprintMapDependency[], visibleNodes: PositionedMapNode[]): number { - const lanes: { start: number, end: number, x: number }[] = [] - let minX = 0 - for (const link of links) { - if (!link.from || !link.to) - continue - const source = { x: link.from.x - 9, y: link.from.y + link.from.height * 2 / 3 } - const target = { x: link.to.x - 11, y: link.to.y + link.to.height / 3 } - const interval = { start: Math.min(source.y, target.y) - 12, end: Math.max(source.y, target.y) + 12 } - let laneX = Math.min(link.from.x, link.to.x) - 40 - while (true) { - const obstacle = visibleNodes.find(item => laneX >= item.x - 12 && laneX <= item.x + item.width + 12 && interval.start <= item.y + item.height && interval.end >= item.y) - if (obstacle) { - laneX = obstacle.x - 24 - continue - } - if (lanes.some(item => Math.abs(item.x - laneX) < 18 && interval.start <= item.end && interval.end >= item.start)) { - laneX -= 18 - continue - } - break - } - lanes.push({ ...interval, x: laneX }) - const direction = target.y >= source.y ? 1 : -1 - const radius = Math.min(12, Math.abs(target.y - source.y) / 2) - link.sourcePort = source - link.targetPort = target - link.path = `M${source.x} ${source.y} H${laneX + radius} Q${laneX} ${source.y} ${laneX} ${source.y + direction * radius} V${target.y - direction * radius} Q${laneX} ${target.y} ${laneX + radius} ${target.y} H${target.x}` - minX = Math.min(minX, laneX - 16) - } - return minX -} - /** Вычисляет ожидание по текущим задачам и направляет связи от предшественников к видимым узлам; внешние задачи остаются в списке без добавления в дерево. */ -export function deriveSprintMapDependencies(input: SprintMapDependencyInput): { waiting: Map, links: SprintMapDependency[], minX: number } { +export function deriveSprintMapDependencies(input: SprintMapDependencyInput): { waiting: Map, links: SprintMapDependency[], minX: number, bounds: SprintMapDependencyBounds } { const tasks = new Map(input.tasks.map(task => [task.id, task])) const endpoints = taskEndpoints(input.root, input.visibleNodes) const waiting = new Map() @@ -103,5 +72,6 @@ export function deriveSprintMapDependencies(input: SprintMapDependencyInput): { }) } links.sort((a, b) => a.dependencyId.localeCompare(b.dependencyId) || a.taskId.localeCompare(b.taskId)) - return { waiting, links, minX: routeDependencies(links, input.visibleNodes) } + const bounds = routeSprintMapDependencies(links, input.visibleNodes) + return { waiting, links, minX: Math.min(0, bounds.minX), bounds } } diff --git a/alfy-bot-frontend/src/features/projects/lib/sprint-map-dependency-routing.ts b/alfy-bot-frontend/src/features/projects/lib/sprint-map-dependency-routing.ts new file mode 100644 index 0000000..470b4c0 --- /dev/null +++ b/alfy-bot-frontend/src/features/projects/lib/sprint-map-dependency-routing.ts @@ -0,0 +1,212 @@ +import type { PositionedMapNode } from './sprint-map-layout' + +interface Point { x: number, y: number } +interface Rectangle { left: number, top: number, right: number, bottom: number } +interface Endpoint { port: Point, anchor: Point } +interface RoutedLink { + from: PositionedMapNode | null + to: PositionedMapNode | null + sourcePort: Point | null + targetPort: Point | null + path: string | null +} +interface QueueEntry { index: number, distance: number, priority: number } + +export interface SprintMapDependencyBounds { + minX: number + minY: number + maxX: number + maxY: number +} + +function rectangle(node: PositionedMapNode, clearance: number): Rectangle { + return { left: node.x - clearance, top: node.y - clearance, right: node.x + node.width + clearance, bottom: node.y + node.height + clearance } +} + +function crosses(a: Point, b: Point, obstacle: Rectangle) { + return a.y === b.y + ? a.y > obstacle.top && a.y < obstacle.bottom && Math.max(a.x, b.x) > obstacle.left && Math.min(a.x, b.x) < obstacle.right + : a.x > obstacle.left && a.x < obstacle.right && Math.max(a.y, b.y) > obstacle.top && Math.min(a.y, b.y) < obstacle.bottom +} + +function endpoint(node: PositionedMapNode, nodes: PositionedMapNode[], source: boolean, lane: number): Endpoint | null { + const offset = source ? 9 : 11 + const y = node.y + node.height * (source ? 2 / 3 : 1 / 3) + const x = node.x + node.width * (source ? 2 / 3 : 1 / 3) + const obstacles = nodes.filter(item => item !== node).map(item => rectangle(item, 7)) + for (const distance of [28 + lane * 8, 28]) { + const candidates = [ + { port: { x: node.x - offset, y }, anchor: { x: node.x - distance, y } }, + { port: { x: node.x + node.width + offset, y }, anchor: { x: node.x + node.width + distance, y } }, + { port: { x, y: node.y - offset }, anchor: { x, y: node.y - distance } }, + { port: { x, y: node.y + node.height + offset }, anchor: { x, y: node.y + node.height + distance } }, + ] + for (const candidate of candidates) { + if (obstacles.every(item => !crosses(candidate.port, candidate.anchor, item))) + return candidate + } + } + return null +} + +function push(queue: QueueEntry[], entry: QueueEntry) { + let index = queue.length + queue.push(entry) + while (index > 0) { + const parent = (index - 1) >> 1 + if (queue[parent]!.priority <= entry.priority) + break + queue[index] = queue[parent]! + index = parent + } + queue[index] = entry +} + +function pop(queue: QueueEntry[]): QueueEntry { + const result = queue[0]! + const last = queue.pop()! + if (!queue.length) + return result + let index = 0 + while (index * 2 + 1 < queue.length) { + let child = index * 2 + 1 + if (child + 1 < queue.length && queue[child + 1]!.priority < queue[child]!.priority) + child++ + if (queue[child]!.priority >= last.priority) + break + queue[index] = queue[child]! + index = child + } + queue[index] = last + return result +} + +function findRoute(source: Endpoint, target: Endpoint, nodes: PositionedMapNode[], clearance: number): Point[] | null { + const start = source.anchor + const end = target.anchor + const obstacles = nodes.map(item => rectangle(item, clearance)) + const xs = [...new Set([start.x, end.x, ...obstacles.flatMap(item => [item.left, item.right])])].sort((a, b) => a - b) + const ys = [...new Set([start.y, end.y, ...obstacles.flatMap(item => [item.top, item.bottom])])].sort((a, b) => a - b) + const width = xs.length + const count = width * ys.length + const xIndices = new Map(xs.map((value, index) => [value, index])) + const yIndices = new Map(ys.map((value, index) => [value, index])) + const horizontal = new Uint8Array(count) + const vertical = new Uint8Array(count) + for (const obstacle of obstacles) { + const left = xIndices.get(obstacle.left)! + const right = xIndices.get(obstacle.right)! + const top = yIndices.get(obstacle.top)! + const bottom = yIndices.get(obstacle.bottom)! + for (let row = top + 1; row < bottom; row++) + horizontal.fill(1, row * width + left, row * width + right) + for (let row = top; row < bottom; row++) + vertical.fill(1, row * width + left + 1, row * width + right) + } + const first = yIndices.get(start.y)! * width + xIndices.get(start.x)! + const last = yIndices.get(end.y)! * width + xIndices.get(end.x)! + const distances = new Float64Array(count).fill(Number.POSITIVE_INFINITY) + const previous = new Int32Array(count).fill(-1) + const queue: QueueEntry[] = [] + distances[first] = 0 + push(queue, { index: first, distance: 0, priority: Math.abs(start.x - end.x) + Math.abs(start.y - end.y) }) + while (queue.length) { + const current = pop(queue) + if (current.distance !== distances[current.index]) + continue + if (current.index === last) { + const path: Point[] = [] + for (let index = last; index !== -1; index = previous[index]!) + path.push({ x: xs[index % width]!, y: ys[Math.floor(index / width)]! }) + return path.reverse() + } + const column = current.index % width + const row = Math.floor(current.index / width) + const neighbors = [ + column > 0 && !horizontal[current.index - 1] ? current.index - 1 : -1, + row > 0 && !vertical[current.index - width] ? current.index - width : -1, + row + 1 < ys.length && !vertical[current.index] ? current.index + width : -1, + column + 1 < width && !horizontal[current.index] ? current.index + 1 : -1, + ] + for (const neighbor of neighbors) { + if (neighbor < 0) + continue + const horizontalMove = Math.floor(neighbor / width) === row + if (current.index === first && horizontalMove === (source.port.y === source.anchor.y)) + continue + if (neighbor === last && horizontalMove === (target.port.y === target.anchor.y)) + continue + const x = xs[neighbor % width]! + const y = ys[Math.floor(neighbor / width)]! + const distance = current.distance + Math.abs(xs[column]! - x) + Math.abs(ys[row]! - y) + if (distance >= distances[neighbor]!) + continue + distances[neighbor] = distance + previous[neighbor] = current.index + push(queue, { index: neighbor, distance, priority: distance + Math.abs(x - end.x) + Math.abs(y - end.y) }) + } + } + return null +} + +function simplify(points: Point[]) { + const result: Point[] = [] + for (const point of points) { + const lastIndex = result.length - 1 + const last = result[lastIndex] + if (last?.x === point.x && last.y === point.y) + continue + const before = result[result.length - 2] + if (before && last && ((before.x === last.x && last.x === point.x) || (before.y === last.y && last.y === point.y))) + result.pop() + result.push(point) + } + return result +} + +function roundedPath(points: Point[]) { + let path = `M${points[0]!.x} ${points[0]!.y}` + const line = (from: Point, to: Point) => from.x === to.x ? ` V${to.y}` : ` H${to.x}` + for (let index = 1; index < points.length; index++) { + const previous = points[index - 1]! + const point = points[index]! + const next = points[index + 1] + if (!next) { + path += line(previous, point) + continue + } + const radius = Math.min(6, (Math.abs(previous.x - point.x) + Math.abs(previous.y - point.y)) / 2, (Math.abs(next.x - point.x) + Math.abs(next.y - point.y)) / 2) + const before = { x: point.x + Math.sign(previous.x - point.x) * radius, y: point.y + Math.sign(previous.y - point.y) * radius } + const after = { x: point.x + Math.sign(next.x - point.x) * radius, y: point.y + Math.sign(next.y - point.y) * radius } + path += `${line(previous, before)} Q${point.x} ${point.y} ${after.x} ${after.y}` + } + return path +} + +/** Прокладывает направленные ортогональные связи вне видимых карточек и возвращает их границы в пикселях с запасом для маркеров. */ +export function routeSprintMapDependencies(links: RoutedLink[], nodes: PositionedMapNode[]): SprintMapDependencyBounds { + let bounds: SprintMapDependencyBounds | null = null + links.forEach((link, index) => { + if (!link.from || !link.to) + return + const source = endpoint(link.from, nodes, true, index) + const target = endpoint(link.to, nodes, false, index) + if (!source || !target) + return + const route = findRoute(source, target, nodes, 12) ?? findRoute(source, target, nodes, 4) + if (!route) + return + const points = simplify([source.port, source.anchor, ...route, target.anchor, target.port]) + link.sourcePort = source.port + link.targetPort = target.port + link.path = roundedPath(points) + for (const point of points) { + bounds ??= { minX: point.x - 16, minY: point.y - 16, maxX: point.x + 16, maxY: point.y + 16 } + bounds.minX = Math.min(bounds.minX, point.x - 16) + bounds.minY = Math.min(bounds.minY, point.y - 16) + bounds.maxX = Math.max(bounds.maxX, point.x + 16) + bounds.maxY = Math.max(bounds.maxY, point.y + 16) + } + }) + return bounds ?? { minX: 0, minY: 0, maxX: 0, maxY: 0 } +} diff --git a/alfy-bot-frontend/tests/features/projects/lib/sprint-map-dependencies.spec.ts b/alfy-bot-frontend/tests/features/projects/lib/sprint-map-dependencies.spec.ts index 1163d9d..3fc4ccc 100644 --- a/alfy-bot-frontend/tests/features/projects/lib/sprint-map-dependencies.spec.ts +++ b/alfy-bot-frontend/tests/features/projects/lib/sprint-map-dependencies.spec.ts @@ -1,9 +1,42 @@ import type { SprintMapNode } from '@/features/projects/lib/sprint-map' +import type { PositionedMapNode } from '@/features/projects/lib/sprint-map-layout' import type { Task } from '@/features/tasks/model/types' import { describe, expect, it } from 'vitest' import { deriveSprintMapDependencies } from '@/features/projects/lib/sprint-map-dependencies' import { layoutSprintMap } from '@/features/projects/lib/sprint-map-layout' +function positioned(id: string, x: number, y: number, width = 264, height = 156): PositionedMapNode { + return { node: node('task', id), x, y, width, height } +} + +function samplePath(path: string): { x: number, y: number }[] { + const points: { x: number, y: number }[] = [] + let current = { x: 0, y: 0 } + for (const match of path.matchAll(/([MHVQ])([^MHVQ]+)/g)) { + const values = match[2]!.trim().split(/[ ,]+/).map(Number) + const start = current + if (match[1] === 'M') { + current = { x: values[0]!, y: values[1]! } + points.push(current) + continue + } + const end = match[1] === 'Q' ? { x: values[2]!, y: values[3]! } : { x: match[1] === 'H' ? values[0]! : current.x, y: match[1] === 'V' ? values[0]! : current.y } + for (let step = 1; step <= 100; step++) { + const t = step / 100 + points.push(match[1] === 'Q' + ? { x: (1 - t) ** 2 * start.x + 2 * (1 - t) * t * values[0]! + t ** 2 * end.x, y: (1 - t) ** 2 * start.y + 2 * (1 - t) * t * values[1]! + t ** 2 * end.y } + : { x: start.x + (end.x - start.x) * t, y: start.y + (end.y - start.y) * t }) + } + current = end + } + return points +} + +function expectClearPath(path: string, nodes: PositionedMapNode[]) { + for (const point of samplePath(path)) + expect(nodes.some(item => point.x > item.x && point.x < item.x + item.width && point.y > item.y && point.y < item.y + item.height)).toBe(false) +} + function node(kind: SprintMapNode['kind'], id: string, children: SprintMapNode[] = []): SprintMapNode { return { key: `${kind}:${id}`, kind, sourceId: id, title: id, statusLabel: '', statusCategory: 'open', statusColor: null, done: 0, total: kind === 'task' ? 1 : 2, outsideCount: 0, blockedReason: null, releases: [], children } } @@ -20,6 +53,47 @@ function derive(selectedTaskId: string | null, showAll: boolean, collapsed = new } describe('связи карты', () => { + it('обходит препятствие на горизонтальной ножке в произвольной раскладке', () => { + const visibleNodes = [positioned('a', 500, 0), positioned('b', 500, 400), positioned('obstacle', 430, 80, 30)] + const result = deriveSprintMapDependencies({ root, visibleNodes, tasks, dependencies, selectedTaskId: 'b', showAll: false }) + expectClearPath(result.links[0]!.path!, visibleNodes) + }) + + it('меняет сторону порта, когда соседняя карточка закрывает левый выход', () => { + const visibleNodes = [positioned('a', 500, 0), positioned('b', 500, 400), positioned('obstacle', 225, 0)] + const result = deriveSprintMapDependencies({ root, visibleNodes, tasks, dependencies, selectedTaskId: 'b', showAll: false }) + const link = result.links[0]! + expectClearPath(link.path!, visibleNodes) + expect(link.sourcePort!.x).toBeGreaterThan(link.from!.x + link.from!.width) + }) + + it('возвращает границы путей и маркеров по обеим осям', () => { + const visibleNodes = [positioned('a', -20, -100), positioned('b', 400, -100)] + const result = deriveSprintMapDependencies({ root, visibleNodes, tasks, dependencies, selectedTaskId: 'b', showAll: false }) + for (const point of samplePath(result.links[0]!.path!)) { + expect(point.x).toBeGreaterThanOrEqual(result.bounds.minX + 6) + expect(point.y).toBeGreaterThanOrEqual(result.bounds.minY + 6) + expect(point.x).toBeLessThanOrEqual(result.bounds.maxX - 6) + expect(point.y).toBeLessThanOrEqual(result.bounds.maxY - 6) + } + expect(result.minX).toBe(result.bounds.minX) + expect(derive(null, false).bounds).toEqual({ minX: 0, minY: 0, maxX: 0, maxY: 0 }) + }) + + it('сохраняет обход карточек для нескольких связей на карте из ста задач', () => { + const ids = Array.from({ length: 100 }, (_, index) => `task-${index}`) + const largeRoot = node('sprint', 'large', ids.map(id => node('task', id))) + const visibleNodes = ids.map((id, index) => positioned(id, (index % 10) * 330, Math.floor(index / 10) * 210)) + const edges = [9, 24, 57, 80, 99].map(index => ({ dependencyId: ids[0]!, taskId: ids[index]! })) + const input = { root: largeRoot, visibleNodes, tasks: ids.map(id => ({ ...tasks[0]!, id })), dependencies: edges, selectedTaskId: ids[0]!, showAll: false } + const result = deriveSprintMapDependencies(input) + expect(result.links).toHaveLength(edges.length) + for (const link of result.links) { + expect(link.path).toBeTruthy() + expectClearPath(link.path!, visibleNodes) + } + expect(deriveSprintMapDependencies({ ...input, visibleNodes: [...visibleNodes].reverse(), dependencies: [...edges].reverse() }).links.map(link => link.path)).toEqual(result.links.map(link => link.path)) + }) it('считает ожидание без изменения дерева и скрывает линии до выбора', () => { const snapshot = JSON.stringify(root) const result = derive(null, false) @@ -72,7 +146,8 @@ describe('связи карты', () => { }) it('оставляет наконечник и начало вне карточек, подходит к цели горизонтально', () => { - const link = derive('b', false).links[0]! + const visibleNodes = [positioned('a', 500, 0), positioned('b', 500, 400)] + const link = deriveSprintMapDependencies({ root, visibleNodes, tasks, dependencies, selectedTaskId: 'b', showAll: false }).links[0]! expect(link.sourcePort!.x).toBeLessThan(link.from!.x - 5) expect(link.targetPort!.x).toBeLessThan(link.to!.x - 5) expect(link.path).toMatch(/H[-\d.]+$/) @@ -87,9 +162,10 @@ describe('связи карты', () => { const edges = ['b', 'c', 'd', 'e'].map(taskId => ({ taskId, dependencyId: 'a' })) const input = { root: multiRoot, visibleNodes: layoutSprintMap(multiRoot, new Set()).nodes, tasks: multiTasks, dependencies: edges, selectedTaskId: null, showAll: true } const result = deriveSprintMapDependencies(input) - const lanes = result.links.map(link => link.path!.match(/H([-\d.]+)/)![1]) - expect(new Set(lanes).size).toBe(4) - expect(result.minX).toBeLessThan(0) + expect(new Set(result.links.map(link => link.path)).size).toBe(4) + for (const link of result.links) + expectClearPath(link.path!, input.visibleNodes) + expect(result.minX).toBe(Math.min(0, result.bounds.minX)) expect(deriveSprintMapDependencies({ ...input, dependencies: [...edges].reverse() }).links.map(link => link.path)).toEqual(result.links.map(link => link.path)) }) @@ -103,9 +179,10 @@ describe('связи карты', () => { ]) const visibleNodes = layoutSprintMap(obstacleRoot, new Set(['story:first', 'story:last'])).nodes const result = deriveSprintMapDependencies({ root: obstacleRoot, visibleNodes, tasks: [...sources, ...targets, 'middle'].map(id => ({ ...tasks[0]!, id })), dependencies: sources.map((id, index) => ({ dependencyId: id, taskId: targets[index]! })), selectedTaskId: null, showAll: true }) - const obstacle = visibleNodes.find(item => item.node.key === 'task:middle')! - const rails = result.links.map(link => Number(link.path!.match(/Q([-\d.]+) /)![1])) - expect(rails.every(x => x < obstacle.x - 12 || x > obstacle.x + obstacle.width + 12)).toBe(true) - expect(new Set(rails).size).toBe(5) + for (const link of result.links) { + expect(link.path).toBeTruthy() + expectClearPath(link.path!, visibleNodes) + } + expect(new Set(result.links.map(link => link.path)).size).toBe(5) }) }) From cb8cfbc853a61367254e6d80c54f85c88756996a Mon Sep 17 00:00:00 2001 From: "i.seliverstov" Date: Thu, 5 Nov 2026 16:13:45 +0500 Subject: [PATCH 4/7] feat(canvas): add radial sprint overview controls --- .../projects/lib/use-sprint-map-viewport.ts | 4 +- .../features/projects/ui/SprintMapCanvas.vue | 48 ++++++++++++----- .../features/projects/ui/SprintMapNode.vue | 4 +- .../src/views/ProjectMapView.vue | 2 +- .../projects/ui/SprintMapCanvas.spec.ts | 52 +++++++++++++++---- 5 files changed, 82 insertions(+), 28 deletions(-) diff --git a/alfy-bot-frontend/src/features/projects/lib/use-sprint-map-viewport.ts b/alfy-bot-frontend/src/features/projects/lib/use-sprint-map-viewport.ts index 6a7c9ee..df8c8b3 100644 --- a/alfy-bot-frontend/src/features/projects/lib/use-sprint-map-viewport.ts +++ b/alfy-bot-frontend/src/features/projects/lib/use-sprint-map-viewport.ts @@ -1,7 +1,7 @@ import type { Ref } from 'vue' import { computed, onBeforeUnmount, onMounted, ref } from 'vue' -interface MapBounds { width: number, height: number, x?: number } +interface MapBounds { width: number, height: number, x?: number, y?: number } interface MapPoint { x: number, y: number } /** Управляет масштабом и положением полотна в пикселях контейнера, не изменяя узлы карты. */ @@ -39,7 +39,7 @@ export function useSprintMapViewport(element: Ref) { measure() scale.value = Math.max(Number.EPSILON, Math.min(1, (size.value.width - 40) / bounds.width, (size.value.height - 40) / bounds.height)) minScale.value = Math.min(0.08, scale.value) - focus({ x: (bounds.x ?? 0) + bounds.width / 2, y: bounds.height / 2 }) + focus({ x: (bounds.x ?? 0) + bounds.width / 2, y: (bounds.y ?? 0) + bounds.height / 2 }) } function initialize(bounds: MapBounds, root: MapPoint) { diff --git a/alfy-bot-frontend/src/features/projects/ui/SprintMapCanvas.vue b/alfy-bot-frontend/src/features/projects/ui/SprintMapCanvas.vue index b2ea1aa..ef82e86 100644 --- a/alfy-bot-frontend/src/features/projects/ui/SprintMapCanvas.vue +++ b/alfy-bot-frontend/src/features/projects/ui/SprintMapCanvas.vue @@ -3,7 +3,7 @@ import type { SprintMapNode } from '../lib/sprint-map' import type { TaskDependencyEdge } from '@/features/tasks/model/task-dependencies' import type { Task } from '@/features/tasks/model/types' import { useScrollLock, useStorage } from '@vueuse/core' -import { ChevronsLeftRight, GitBranch, Maximize, Maximize2, Minimize2, Minus, Plus, Search, X } from 'lucide-vue-next' +import { GitBranch, Maximize, Maximize2, Minimize2, Minus, Plus, Search, X } from 'lucide-vue-next' import { FocusScope } from 'reka-ui' import { computed, nextTick, onMounted, ref, useId, watch } from 'vue' import { Button } from '@/components/ui/button' @@ -28,12 +28,22 @@ const showAllDependencies = ref(false) const dependencyArrowId = `dependency-arrow-${useId()}` const stored = useStorage>('alfy-sprint-map-collapsed', {}, undefined, { flush: 'sync' }) const scope = computed(() => `${props.projectId}/${props.root.key}`) -const collapsed = computed(() => new Set(Array.isArray(stored.value?.[scope.value]) ? stored.value[scope.value] : [])) +const collapsed = computed(() => new Set(Array.isArray(stored.value?.[scope.value]) ? stored.value[scope.value] : keysForLevel('epics'))) const layout = computed(() => layoutSprintMap(props.root, collapsed.value)) const allNodes = computed(() => flattenSprintMap(props.root)) const matches = computed(() => query.value.trim() ? allNodes.value.filter(node => node.title.toLocaleLowerCase().includes(query.value.trim().toLocaleLowerCase())) : []) const dependencyGraph = computed(() => deriveSprintMapDependencies({ root: props.root, visibleNodes: layout.value.nodes, tasks: props.tasks, dependencies: props.dependencies, selectedTaskId: dependencySelection.value, showAll: showAllDependencies.value })) -const mapBounds = computed(() => ({ x: dependencyGraph.value.minX, width: layout.value.width - dependencyGraph.value.minX, height: layout.value.height })) +const mapBounds = computed(() => { + const { minX, minY, maxX, maxY } = dependencyGraph.value.bounds + const x = Math.min(0, minX) + const y = Math.min(0, minY) + return { x, y, width: Math.max(layout.value.width, maxX) - x, height: Math.max(layout.value.height, maxY) - y } +}) +const detailLevels = [{ id: 'epics', label: 'Эпики', aria: 'Показать эпики' }, { id: 'stories', label: 'Истории', aria: 'Показать истории' }, { id: 'tasks', label: 'Задачи', aria: 'Раскрыть всё' }] as const +const selectedLevel = computed(() => detailLevels.find((level) => { + const keys = keysForLevel(level.id) + return keys.length === collapsed.value.size && keys.every(key => collapsed.value.has(key)) +})?.id) const dependencyTitle = computed(() => props.tasks.find(task => task.id === dependencySelection.value)?.title ?? null) const viewport = useSprintMapViewport(surface) const { scale, minScale, dragging, transform } = viewport @@ -128,9 +138,19 @@ function fit() { viewport.fit(mapBounds.value) } -function expandAll() { - saveCollapsed(new Set()) - nextTick(fit) +function keysForLevel(level: 'epics' | 'stories' | 'tasks'): string[] { + if (level === 'tasks') + return [] + if (level === 'epics') + return allNodes.value.filter(node => node.key !== props.root.key && node.children.length).map(node => node.key) + return allNodes.value.filter(node => node.children.length && (node.kind === 'story' || node.kind === 'ungrouped' || (node.kind === 'epic' && node.children.every(child => child.kind === 'task')))).map(node => node.key) +} + +async function setDetailLevel(level: 'epics' | 'stories' | 'tasks') { + saveCollapsed(new Set(keysForLevel(level))) + query.value = '' + await nextTick() + fit() } async function add(node: SprintMapNode) { @@ -140,9 +160,7 @@ async function add(node: SprintMapNode) { } function initialize() { - const root = layout.value.nodes.find(item => item.node.key === props.root.key) - if (root) - viewport.initialize(mapBounds.value, { x: root.x + root.width / 2, y: root.y + root.height / 2 }) + fit() } watch(scope, async () => { @@ -162,7 +180,7 @@ onMounted(initialize) ref="container" class="flex min-h-0 flex-1 flex-col overflow-hidden border-border bg-background" :class="fullscreen ? 'fixed inset-0 z-40 h-dvh w-full' : 'rounded-xl border'" :role="fullscreen ? 'dialog' : 'region'" :aria-modal="fullscreen || undefined" - aria-label="Турнирная карта спринта" @keydown.esc="onEscape" + aria-label="Радиальная карта спринта" @keydown.esc="onEscape" >
@@ -198,9 +216,11 @@ onMounted(initialize) - +
+ +
@@ -240,7 +260,7 @@ onMounted(initialize)
- Задачи → истории → эпики → спринт + Спринт в центре · Эпики → истории → задачи Спринт закрыт · просмотр
diff --git a/alfy-bot-frontend/src/features/projects/ui/SprintMapNode.vue b/alfy-bot-frontend/src/features/projects/ui/SprintMapNode.vue index 48cfe24..3c27a27 100644 --- a/alfy-bot-frontend/src/features/projects/ui/SprintMapNode.vue +++ b/alfy-bot-frontend/src/features/projects/ui/SprintMapNode.vue @@ -1,6 +1,6 @@