diff --git a/CLAUDE.md b/CLAUDE.md index ae16b58..a4207f9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -131,9 +131,9 @@ ESM-пакет, Node 22+. SDK — `@modelcontextprotocol/sdk` (`McpServer` + `St **Спринты: доска — это активный спринт.** Вкладки agile-проекта: `tasks-project` (доска), `tasks-project-backlog`, `tasks-project-releases` и `tasks-project-map`. Доска показывает только задачи с `sprintId` активного спринта; без активного спринта — пустое состояние, сетки нет. Планирование (перенос между спринтами и бэклогом, старт, завершение) живёт только на вкладке «Бэклог». Связь задачи со спринтом — одно поле `Task.sprintId`, независимое от эпика и колонки. У задачи в спринте всегда есть колонка: сервер ставит первую колонку проекта, если её нет (`TaskService` и `ProjectTaskService.moveTask`). Задача, созданная на доске, создаётся с `sprintId` активного спринта. Активный спринт в проекте один — это держит и сервис, и уникальный частичный индекс `IDX_sprint_one_active`. `GET /projects/:id/sprints` отдаёт и закрытые (для подписи «(закрыт)» у задачи), экраны фильтруют их сами. -**Карта спринта.** `/tasks/project/:projectId/map?sprint=:sprintId` показывает выбранный спринт, по умолчанию активный. `buildSprintMap` — чистая проекция текущих сущностей, не исторический отчёт: task→story→epic→sprint, пустые назначенные истории и задачи без группы не теряются. Прогресс не зависит от collapse и не подменяет workflow истории. Раскладка в `sprint-map-layout.ts`, SVG-связи и HTML-карточки в `SprintMapCanvas`; состояние веток хранится отдельно по проекту/спринту. Страница атомарно применяет актуальный снимок загрузки. Новая задача явно получает выбранный sprintId, выпущенный релиз не наследуется; новый эпик создаётся с первой историей. `use-sprint-map-create` сохраняет промежуточные ID для повтора назначения без дублей. Закрытый спринт запрещает добавление через карту; существующие редакторы сохраняют свои ограничения. +**Карта спринта.** `/tasks/project/:projectId/map?sprint=:sprintId` показывает выбранный спринт, по умолчанию активный. `buildSprintMap` — чистая проекция текущих сущностей, не исторический отчёт: task→story→epic→sprint, пустые назначенные истории и задачи без группы не теряются. Прогресс не зависит от collapse и не подменяет workflow истории. Двусторонняя mind map в `sprint-map-layout.ts`: спринт в центре, стороны эпиков балансируются по полному размеру веток и не зависят от collapse, потомки располагаются наружу, связи имеют общие ортогональные стволы; карточки горизонтальны и не перекрываются. Уровни детализации в `SprintMapCanvas` задают обзор эпиков/историй/задач, новый scope начинает с эпиков и сохраняет вложенные ветки свёрнутыми при последовательном раскрытии. SVG-связи и HTML-карточки в `SprintMapCanvas`; состояние веток хранится отдельно по проекту/спринту. Страница атомарно применяет актуальный снимок загрузки. Новая задача явно получает выбранный sprintId, выпущенный релиз не наследуется; новый эпик создаётся с первой историей. `use-sprint-map-create` сохраняет промежуточные ID для повтора назначения без дублей. Закрытый спринт запрещает добавление через карту; существующие редакторы сохраняют свои ограничения. -**Зависимости задач.** Таблица `task_dependencies` хранит пару `taskId` (зависимая задача) / `dependencyId` (предшественник), оба FK с CASCADE. `GET /api/tasks/dependencies/graph` читает граф владельца; `PUT /api/tasks/:id/dependencies` принимает `{ dependencyIds: string[] }` и возвращает канонический набор только этой задачи. Проверки владельца, frozen-source, self/duplicates и циклов вместе с заменой выполняются в одной `withSqliteAccess`-транзакции, иначе встречные запросы создадут цикл. `Task` API и workflow не меняются: ожидание вычисляется из текущего `completed` предшественников. `TaskDependencies` общий для страницы/preview: добавление/удаление сохраняется сразу, ошибка откатывает отображение, повтор применяет исходное действие к актуальным связям. Во время запроса действия заблокированы; смена задачи сбрасывает локальное состояние. Graph store сериализует записи одной задачи, объединяет ответы разных задач и отвергает снимки старой ревизии. Карта проецирует скрытые концы на видимого предка; реальные имена и внешние ссылки остаются в панели. Не включать зависимости в иерархию/прогресс. Контракт и проверки: [task-dependencies](docs/tasks/task-dependencies.md). +**Зависимости задач.** Таблица `task_dependencies` хранит пару `taskId` (зависимая задача) / `dependencyId` (предшественник), оба FK с CASCADE. `GET /api/tasks/dependencies/graph` читает граф владельца; `PUT /api/tasks/:id/dependencies` принимает `{ dependencyIds: string[] }` и возвращает канонический набор только этой задачи. Проверки владельца, frozen-source, self/duplicates и циклов вместе с заменой выполняются в одной `withSqliteAccess`-транзакции, иначе встречные запросы создадут цикл. `Task` API и workflow не меняются: ожидание вычисляется из текущего `completed` предшественников. `TaskDependencies` общий для страницы/preview: добавление/удаление сохраняется сразу, ошибка откатывает отображение, повтор применяет исходное действие к актуальным связям. Во время запроса действия заблокированы; смена задачи сбрасывает локальное состояние. Graph store сериализует записи одной задачи, объединяет ответы разных задач и отвергает снимки старой ревизии. Маршрутизатор зависимостей обходит прямоугольники видимых карточек, включая горизонтальные участки, и возвращает bounds всех направлений для fit. Карта проецирует скрытые концы на видимого предка; реальные имена и внешние ссылки остаются в панели. Не включать зависимости в иерархию/прогресс. Контракт и проверки: [task-dependencies](docs/tasks/task-dependencies.md). **Релизы: срез по дате выпуска, не по доске.** Третья вкладка agile-проекта — `tasks-project-releases`. Связь — одно поле `Task.releaseId`, независимое от эпика, колонки и спринта; колонку релиз не трогает и на доске не фильтрует. В выпущенный (`released`) релиз задачу назначить нельзя, а «В релиз…» для эпика или истории (`POST …/releases/:id/assign-group`) не забирает задачи из выпущенных релизов — история выпуска не переписывается. Выпуск (`POST …/:id/release`) переносит только незавершённые задачи. diff --git a/README.md b/README.md index e6495f7..bb46ff0 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ - **🌍 Корректные таймзоны и локали.** Все операции с датами уважают IANA-таймзону пользователя; даты в БД хранятся в UTC и сдвигаются к wall-clock пользователя на границе домена. Календарь, локаль и первый день недели — из настроек пользователя. - **🗓 Богатый UI задач.** Inbox, проекты со списками и board-колонками, повторяющиеся задачи, календарь с drag-create по сетке часов, Pomodoro-таймер, два независимых drag-and-drop-движка (кастомный на PointerEvents + vuedraggable). Agile-проекты включают эпики, истории, спринты и релизы; историю можно перенести в спринт целиком с задачами через меню или drag-and-drop. Стрелки ↑/↓ прямо на доске меняют порядок эпиков и историй внутри эпика; порядок сохраняется после перезагрузки. На доске отображаются группы текущего спринта. Историю или целый эпик можно вернуть в бэклог через меню или MCP `remove_group_from_sprint`: структура сохраняется, задачи других спринтов не меняются. Описание задачи поддерживает Markdown и кликабельные ссылки; исходный текст редактируется по кнопке «Редактировать» с явным сохранением или отменой. Задачи (`/tasks/:taskId`), истории и эпики (`/tasks/project/:projectId/group/:groupId`) открываются на отдельных страницах по постоянным ссылкам. Из карточки можно скопировать ссылку или открыть страницу в новой вкладке; после входа сохраняется исходный адрес. Быстрый просмотр с доски использует тот же редактор. Истории на доске сворачиваются отдельной стрелкой; состояние сохраняется в браузере, добавление задачи раскрывает историю. - **Спринты и истории.** Настраиваемые статусы историй, блокеры и зависимости, бэклог с планированием по бюджету времени, предложения состава через MCP и сохранённые итоги спринтов. [Инструменты планирования](alfy-mcp/README.md#объяснимое-планирование). -- **Карта спринта.** Вкладка «Карта» строит турнирную сетку задач → историй → эпиков → выбранного спринта. Ветки сворачиваются, поиск раскрывает скрытый путь, полотно поддерживает масштабирование и перемещение. Прогресс считает только задачи выбранного спринта; статус истории и метки релизов показаны отдельно. Из карты доступны быстрый просмотр, постоянные ссылки и создание дочерних элементов. +- **Карта спринта.** Вкладка «Карта» показывает mind map: выбранный спринт в центре, эпики расходятся влево и вправо, истории и задачи продолжают ветки наружу. Уровни «Эпики / Истории / Задачи» управляют детализацией; новый спринт открывается компактным обзором эпиков. Ветки сворачиваются, поиск раскрывает скрытый путь, полотно поддерживает масштабирование и перемещение. Прогресс считает только задачи выбранного спринта; статус истории и метки релизов показаны отдельно. Из карты доступны быстрый просмотр, постоянные ссылки и создание дочерних элементов. - **Зависимости задач.** В карточке задачи поле «Зависит от» задаёт предшественников, включая свои задачи из других спринтов и проектов. Карта показывает направленные пунктирные связи и количество незавершённых предшественников. Завершение предшественников снимает ожидание, статус зависимой задачи остаётся прежним. [Как пользоваться](alfy-bot-frontend/README.md#зависимости-задач). - **🔔 Уведомления.** Web-push (VAPID) с подписками на устройство. diff --git a/alfy-bot-frontend/README.md b/alfy-bot-frontend/README.md index 7c08a15..e47ad8f 100644 --- a/alfy-bot-frontend/README.md +++ b/alfy-bot-frontend/README.md @@ -22,6 +22,12 @@ На активной доске **Фокус** показывает ближайшие действия, блокеры и загрузку. При завершении спринта можно распределить остаток, записать итоги и улучшение. **Бэклог → Итоги** хранит исходный и итоговый состав; для старых спринтов отмечает неполную историю. Минуты — оценки объёма, а задачи без оценки показаны отдельно. +## Карта спринта + +Во вкладке **Карта** спринт расположен в центре. Эпики расходятся влево и вправо, истории и задачи продолжают ветки с общими стволами. Сторона эпика сохраняется при сворачивании. Новый спринт открывается обзором эпиков с прогрессом; раскрытие эпика показывает истории, затем можно раскрыть задачи. Кнопки **Эпики / Истории / Задачи** меняют детализацию всей карты. Выбранные свёрнутые ветки сохраняются для проекта и спринта. + +Поиск раскрывает путь к задаче и приближает её. **Вся карта** возвращает общий обзор, **На весь экран** разворачивает полотно. Карточки открывают общий быстрый просмотр и постоянные страницы; прогресс учитывает только выбранный спринт. + ## Зависимости задач Чтобы видеть, что мешает начать задачу, откройте её страницу или быстрый просмотр, в блоке **Зависит от** найдите задачу по названию, ключу (`DEP-12`) или номеру (`12`, `#12`) и выберите её. Добавление сохраняется сразу; крестик рядом с задачей удаляет связь. При ошибке остаётся сохранённый набор связей и доступна кнопка повторного сохранения. Например, «Опубликовать демо» зависит от «Свести треки»: пока сведение не выполнено, публикация показывает ожидание. 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/src/features/projects/lib/sprint-map-layout.ts b/alfy-bot-frontend/src/features/projects/lib/sprint-map-layout.ts index 19640ed..af7a338 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,76 @@ export interface MapEdge { path: string } -const columns: Record = { task: 0, story: 1, epic: 2, ungrouped: 2, sprint: 3 } +interface BranchNode { + node: SprintMapNode + children: BranchNode[] + span: number + weight: number +} + +function collectBranch(node: SprintMapNode, collapsed: ReadonlySet): BranchNode { + const allChildren = node.children.map(child => collectBranch(child, collapsed)) + const children = collapsed.has(node.key) ? [] : allChildren + return { + node, + children, + weight: Math.max(1, allChildren.reduce((sum, child) => sum + child.weight, 0)), + span: Math.max(MAP_NODE_HEIGHT, children.reduce((sum, child) => sum + child.span, 0) + Math.max(0, children.length - 1) * MAP_ROW_GAP), + } +} + +function forestSpan(nodes: BranchNode[]): number { + return nodes.reduce((sum, node) => sum + node.span, 0) + Math.max(0, nodes.length - 1) * MAP_ROW_GAP +} -/** Раскладывает видимые ветки по уровням в пикселях; свёрнутые узлы сохраняют исходные данные и занимают место одной карточки. */ +function branchPath(child: PositionedMapNode, parent: PositionedMapNode, side: number): string { + const startX = side > 0 ? child.x : child.x + child.width + const endX = side > 0 ? parent.x + parent.width : parent.x + const trunkX = (startX + endX) / 2 + return `M${startX} ${child.y + child.height / 2} H${trunkX} V${parent.y + parent.height / 2} H${endX}` +} + +/** Размещает спринт в центре, распределяет полные ветки по сторонам и соединяет их общими ортогональными стволами; координаты и размеры заданы в пикселях, сворачивание не меняет исходные узлы и стороны веток. */ 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 + const tree = collectBranch(root, collapsed) + const sides = [{ direction: 1, weight: 0, branches: [] as BranchNode[] }, { direction: -1, weight: 0, branches: [] as BranchNode[] }] + for (const branch of tree.children) { + const side = sides[0]!.weight <= sides[1]!.weight ? sides[0]! : sides[1]! + side.branches.push(branch) + side.weight += branch.weight + } + const nodes: PositionedMapNode[] = [{ node: root, x: -MAP_NODE_WIDTH / 2, y: -MAP_NODE_HEIGHT / 2, width: MAP_NODE_WIDTH, height: MAP_NODE_HEIGHT }] + const connections: { child: PositionedMapNode, parent: PositionedMapNode, side: number }[] = [] - 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, - } + function place(branch: BranchNode, parent: PositionedMapNode, side: number, depth: number, top: number) { + const positioned = { node: branch.node, x: side * depth * (MAP_NODE_WIDTH + MAP_COLUMN_GAP) - MAP_NODE_WIDTH / 2, y: top + branch.span / 2 - MAP_NODE_HEIGHT / 2, 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}` }) + connections.push({ child: positioned, parent, side }) + let childTop = top + for (const child of branch.children) { + place(child, positioned, side, depth + 1, childTop) + childTop += child.span + MAP_ROW_GAP } - 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, + for (const side of sides) { + let top = -forestSpan(side.branches) / 2 + for (const branch of side.branches) { + place(branch, nodes[0]!, side.direction, 1, top) + top += branch.span + MAP_ROW_GAP + } + } + const halfWidth = Math.max(...nodes.map(node => Math.abs(node.x + node.width / 2) + node.width / 2)) + MAP_PADDING + const halfHeight = Math.max(...nodes.map(node => Math.abs(node.y + node.height / 2) + node.height / 2)) + MAP_PADDING + for (const node of nodes) { + node.x += halfWidth + node.y += halfHeight } + const edges = connections.map(({ child, parent, side }) => ({ from: child.node.key, to: parent.node.key, path: branchPath(child, parent, side) })) + return { nodes, edges, width: halfWidth * 2, height: halfHeight * 2 } } 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..84af683 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) - +
+ +
@@ -217,7 +237,9 @@ 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 @@