Files
khb_microservices/packages/khbuild_process_viz/src/gantt.ts

462 lines
29 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { describeResponsible, type ProcessModel, type ProcessRow, type StageRow } from "./model.js";
import type { Schedule, Timing } from "./schedule.js";
import { esc, svgDoc, tooltip, truncate } from "./svg.js";
export interface GanttOptions {
/** дата kick-off (YYYY-MM-DD) - если задана, на оси подписываются календарные даты */
kickoff?: string | null;
/** рисовать стрелки зависимостей */
deps?: boolean;
/** показывать только эти этапы */
stages?: string[] | null;
/** масштаб времени: пикселей на день. Меняет только ось времени, шрифты и интервалы строк остаются прежними */
px?: number;
/** свёрнутые группы (этапы): от них остаётся только сводная полоса */
collapsed?: string[] | null;
}
/** Ширина левой колонки с названиями; не зависит от масштаба времени. */
export const GANTT_LEFT = 420;
export const GANTT_DEFAULT_PX = 5;
export const GANTT_MIN_PX = 0.5;
export const GANTT_MAX_PX = 40;
const ROW = 36; // строка шага: подпись над полосой, полоса, id справа снизу
const BAR_CY = 21; // центр полосы от верха строки
const BAR_H = 14;
const HEAD = 76;
const GROUP_BAR_H = 14; // высота сводной полосы
const GROUP_HEAD_MIN = 40; // в шапке группы помещаются название и роли
const GROUP_PAD = 8; // отступ сверху и снизу в строке группы
const LABEL_STEP = 13; // шаг подписей вех по вертикали
const MAX_LABEL_LEVELS = 4;
const CHAR_W = 6.1; // ширина символа подписи (шрифт 11px)
const NO_STAGE = "(без этапа)";
const addDays = (iso: string, days: number): string | null => {
const d = new Date(`${iso}T00:00:00Z`);
if (Number.isNaN(d.getTime())) return null;
d.setUTCDate(d.getUTCDate() + days);
return d.toISOString().slice(0, 10);
};
export const clampPx = (px: number | undefined): number => {
const v = typeof px === "number" && Number.isFinite(px) ? px : GANTT_DEFAULT_PX;
return Math.min(GANTT_MAX_PX, Math.max(GANTT_MIN_PX, v));
};
/** Цвета этапов без заданных в справочнике (`color_fill`, `color_stroke`): по кругу. */
const FALLBACK_STYLES: ReadonlyArray<{ fill: string; stroke: string }> = [
{ stroke: "#8a6bb5", fill: "#e5dcf1" },
{ stroke: "#b44b7c", fill: "#f5cfe0" },
{ stroke: "#2f9a8f", fill: "#c9f0ec" },
{ stroke: "#a39a1c", fill: "#f3efb0" },
];
/** Порядок этапов: сначала этапы с `ord` в справочнике (по возрастанию), остальные - по самому раннему сроку окончания среди шагов с заданным сроком (шаги без срока не тянут этап в начало), затем по появлению. */
export function stageOrder(rows: ProcessRow[], schedule: Schedule, stageRefs: StageRow[] = []): string[] {
const key = new Map<string, number>();
for (const r of rows) {
const s = r.stage ?? NO_STAGE;
const t = schedule.timings.get(r.id);
if (!t || t.kind === "recurring") {
if (!key.has(s)) key.set(s, Infinity);
continue;
}
const v = t.fromConstraint ? t.end : t.end + 0.5; // выведенные сроки чуть слабее заданных
key.set(s, Math.min(key.get(s) ?? Infinity, v));
}
const ordOf = (s: string): number => stageRefs.find((r) => r.name === s)?.ord ?? Infinity;
return [...key.entries()]
.sort((a, b) => {
const oa = ordOf(a[0]);
const ob = ordOf(b[0]);
return oa === ob ? a[1] - b[1] : oa - ob;
})
.map(([s]) => s);
}
export interface GroupSummary {
stage: string;
/** границы сводной полосы (дни) */
start: number;
end: number;
/** вехи группы: строки с признаком is_milestone, по дате завершения */
milestones: Array<{ row: ProcessRow; day: number; deadline: number | null }>;
/** отрезки, где в группе идут активности (объединение интервалов работ); между ними полоса прерывается */
segments: Array<[number, number]>;
}
/**
* Границы группы считаются по шагам с реальным сроком: повторяющиеся шаги (они тянутся на весь проект) и шаги без срока
* (выведенные нули без зависимостей) границы не растягивают. Если таких шагов нет, берутся все.
*/
export function summarizeGroup(stage: string, rows: Array<{ row: ProcessRow; t: Timing }>): GroupSummary {
const real = rows.filter(({ t }) => t.kind !== "recurring" && (t.fromConstraint || t.end > t.start));
const base = real.length ? real : rows;
const start = Math.min(...base.map(({ t }) => t.start));
const end = Math.max(...base.map(({ t }) => t.end));
const milestones = rows
.filter(({ row, t }) => row.isMilestone && t.kind !== "recurring")
.map(({ row, t }) => ({ row, day: t.end, deadline: t.deadline }))
.sort((a, b) => a.day - b.day || a.row.id.localeCompare(b.row.id, "ru", { numeric: true }));
// Сводная полоса показывает занятость: отрезки работ объединяются, там где активностей нет - разрыв, дальше полоса продолжается.
// Если в группе нет ни одной работы с длительностью (только вехи), рисуется один сплошной отрезок от начала до конца.
const tasks = rows
.filter(({ t }) => t.kind === "task")
.map(({ t }) => [t.start, t.end] as [number, number])
.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
const segments: Array<[number, number]> = [];
for (const [a, b] of tasks) {
const last = segments.at(-1);
if (last && a <= last[1]) last[1] = Math.max(last[1], b);
else segments.push([a, b]);
}
const s0 = Number.isFinite(start) ? start : 0;
const e0 = Number.isFinite(end) ? end : 0;
return { stage, start: s0, end: e0, milestones, segments: segments.length ? segments : [[s0, e0]] };
}
interface PlacedLabel { x: number; level: number; text: string; row: ProcessRow }
/** Раскладывает подписи вех над полосой: сначала длинная подпись (id и название), потом короткая (id), на минимально возможном уровне. */
export function placeLabels(items: Array<{ x: number; row: ProcessRow }>): { labels: PlacedLabel[]; levels: number } {
const taken: Array<Array<[number, number]>> = [];
const labels: PlacedLabel[] = [];
const fits = (level: number, a: number, b: number) => (taken[level] ?? []).every(([l, r]) => b + 6 <= l || a - 6 >= r);
for (const it of items) {
const long = `${it.row.id} · ${truncate(it.row.actionName ?? "", 24)}`;
const candidates = [long, it.row.id];
let placed = false;
for (let level = 0; level < MAX_LABEL_LEVELS && !placed; level++) {
for (const text of candidates) {
const w = text.length * CHAR_W;
if (!fits(level, it.x - w / 2, it.x + w / 2)) continue;
(taken[level] ??= []).push([it.x - w / 2, it.x + w / 2]);
labels.push({ x: it.x, level, text, row: it.row });
placed = true;
break;
}
}
if (!placed) {
// места нет даже на верхнем уровне: коротко на верхнем уровне поверх остальных
const level = MAX_LABEL_LEVELS - 1;
(taken[level] ??= []).push([it.x - 15, it.x + 15]);
labels.push({ x: it.x, level, text: it.row.id, row: it.row });
}
}
return { labels, levels: labels.length ? Math.max(...labels.map((l) => l.level)) + 1 : 0 };
}
/** Зависимости, которые следуют из цепочки других зависимостей (A→B, если B достижим из A через другие шаги): на Ганте не рисуются, смысл графа не меняется. Ключ - `от>к`. */
/** Часть имени CSS-класса из id шага (точка в CP-4.5 и т. п. заменяется). */
const safeId = (id: string): string => id.replace(/[^A-Za-z0-9]/g, "_");
export function redundantDependencies(rows: ProcessRow[]): Set<string> {
const ids = new Set(rows.map((r) => r.id));
const succ = new Map<string, string[]>();
for (const r of rows) for (const d of r.dependsOn) if (ids.has(d)) succ.set(d, [...(succ.get(d) ?? []), r.id]);
const reachable = (from: string, to: string): boolean => {
const stack = [from];
const seen = new Set<string>();
while (stack.length) {
const cur = stack.pop()!;
for (const next of succ.get(cur) ?? []) {
if (cur === from && next === to) continue;
if (next === to) return true;
if (!seen.has(next)) {
seen.add(next);
stack.push(next);
}
}
}
return false;
};
const out = new Set<string>();
for (const r of rows) for (const d of r.dependsOn) if (ids.has(d) && reachable(d, r.id)) out.add(`${d}>${r.id}`);
return out;
}
export function renderGantt(model: ProcessModel, schedule: Schedule, opts: GanttOptions = {}): string {
const px = clampPx(opts.px);
const collapsedSet = new Set(opts.collapsed ?? []);
const stages = stageOrder(model.rows, schedule, model.stages).filter((s) => !opts.stages?.length || opts.stages.includes(s));
const stageColor = new Map(model.stages.filter((r) => r.fill && r.stroke).map((r) => [r.name, { fill: r.fill!, stroke: r.stroke! }]));
const others = stages.filter((s) => !stageColor.has(s));
const color = (stage: string): { fill: string; stroke: string } =>
stageColor.get(stage) ?? FALLBACK_STYLES[Math.max(0, others.indexOf(stage)) % FALLBACK_STYLES.length]!;
const roleName = new Map(model.roles.map((r) => [r.id, r.person ?? r.id]));
const conflicts = new Map<string, string[]>();
for (const w of schedule.warnings) conflicts.set(w.id, [...(conflicts.get(w.id) ?? []), w.message]);
const minDay = Math.min(0, ...[...schedule.timings.values()].filter((t) => t.kind !== "recurring").map((t) => t.start));
const x = (d: number) => GANTT_LEFT + (d - minDay) * px;
// Группы: строки этапа по началу
interface Group { stage: string; rows: Array<{ row: ProcessRow; t: Timing }>; summary: GroupSummary; collapsed: boolean; labels: PlacedLabel[]; levels: number; headH: number; top: number; bottom: number }
const groups: Group[] = stages.map((stage) => {
const rows = model.rows
.filter((r) => (r.stage ?? NO_STAGE) === stage)
.map((r) => ({ row: r, t: schedule.timings.get(r.id)! }))
.sort((a, b) => a.t.start - b.t.start || a.t.end - b.t.end || a.row.id.localeCompare(b.row.id, "ru", { numeric: true }));
const summary = summarizeGroup(stage, rows);
const { labels, levels } = placeLabels(summary.milestones.map((m) => ({ x: x(m.day), row: m.row })));
const headH = Math.max(GROUP_HEAD_MIN, GROUP_PAD + levels * LABEL_STEP + GROUP_BAR_H + GROUP_PAD);
return { stage, rows, summary, collapsed: collapsedSet.has(stage), labels, levels, headH, top: 0, bottom: 0 };
});
// Вертикальная раскладка
const yOf = new Map<string, number>();
const rowTop = new Map<string, number>();
let y = HEAD;
for (const g of groups) {
g.top = y;
y += g.headH;
if (!g.collapsed) {
for (const { row } of g.rows) {
rowTop.set(row.id, y);
yOf.set(row.id, y + BAR_CY);
y += ROW;
}
}
g.bottom = y;
}
const height = y + 40;
const days = Math.ceil((schedule.maxDay + 10) / 10) * 10;
// подписи вех могут выступать за правый край оси
const labelRight = Math.max(
0,
...groups.flatMap((g) => g.labels.map((l) => l.x + (l.text.length * CHAR_W) / 2)),
...groups.flatMap((g) => (g.collapsed ? [] : g.rows.map(({ row, t }) => x(Math.max(t.start, t.end)) + 14 + (row.actionName ?? row.description ?? "").length * CHAR_W))),
);
const width = Math.round(Math.max(GANTT_LEFT + (days - minDay) * px + 30, labelRight + 16));
const out: string[] = [];
out.push(`<text x="12" y="24" font-size="16" font-weight="600" fill="#222">Диаграмма Ганта процесса (${esc(model.set)}): дни от первой встречи с архитектором</text>`);
// Ось: шаг подписей выбирается так, чтобы подписи не слипались при любом масштабе
const steps = [1, 2, 5, 7, 14, 30, 60, 90, 180];
const tick = steps.find((s) => s * px >= 64) ?? 180;
const gridStep = steps.find((s) => s * px >= 8) ?? 7;
for (let d = Math.ceil(minDay / gridStep) * gridStep; d <= days; d += gridStep) {
out.push(`<line x1="${x(d)}" y1="${HEAD - 4}" x2="${x(d)}" y2="${height - 30}" stroke="${d % tick === 0 ? "#c9c9c9" : "#eeeeee"}" stroke-width="1"/>`);
}
for (let d = Math.ceil(minDay / tick) * tick; d <= days; d += tick) {
out.push(`<line x1="${x(d)}" y1="${HEAD - 18}" x2="${x(d)}" y2="${height - 30}" stroke="#bdbdbd" stroke-width="1.2"/>`);
out.push(`<text x="${x(d) + 3}" y="${HEAD - 38}" fill="#444" font-weight="600">день ${d}</text>`);
const date = opts.kickoff ? addDays(opts.kickoff, d) : null;
if (date) out.push(`<text x="${x(d) + 3}" y="${HEAD - 24}" fill="#777" font-size="11">${date}</text>`);
else if (d % 30 === 0) out.push(`<text x="${x(d) + 3}" y="${HEAD - 24}" fill="#777" font-size="11">мес. ${d / 30}</text>`);
}
// Подложки групп и направляющие вех
for (const g of groups) {
const c = color(g.stage);
const gi = groups.indexOf(g);
out.push(`<rect x="0" y="${g.top}" width="${width}" height="${g.bottom - g.top}" fill="${gi % 2 === 0 ? "#f1f1ee" : "#ffffff"}"/>`);
out.push(`<rect x="0" y="${g.top}" width="6" height="${g.bottom - g.top}" fill="${c.stroke}"/>`);
if (!g.collapsed && g.rows.length) {
const xs = new Set<number>([g.summary.start, ...g.summary.milestones.map((m) => m.day)]);
for (const d of xs) out.push(`<line x1="${x(d)}" y1="${g.top + g.headH - GROUP_PAD}" x2="${x(d)}" y2="${g.bottom}" stroke="${c.stroke}" stroke-width="1" stroke-dasharray="4 4" opacity="0.7"/>`);
}
}
// Зависимости под полосами. Если группа свёрнута, от неё остаются вехи: стрелки идут между ромбами сводных полос.
const groupOf = new Map<string, Group>();
for (const g of groups) for (const { row } of g.rows) groupOf.set(row.id, g);
const anchor = (id: string): { xs: number; xe: number; y: number } | null => {
const tm = schedule.timings.get(id);
const g = groupOf.get(id);
if (!tm || !g) return null;
if (!g.collapsed) {
const yy = yOf.get(id);
return yy === undefined ? null : { xs: x(tm.start), xe: x(tm.end), y: yy };
}
const m = g.summary.milestones.find((mm) => mm.row.id === id);
return m ? { xs: x(m.day), xe: x(m.day), y: g.top + GROUP_PAD + g.levels * LABEL_STEP + GROUP_BAR_H / 2 } : null;
};
const ghostMarks: string[] = []; // контурные ромбы вех на строках зависимых шагов (рисуются поверх строк)
const vlines: string[] = [];
const vlIds = new Set<string>(); // вехи, у которых есть контурные ромбы (вертикаль показывается при наведении)
if (opts.deps !== false) {
const arrows: string[] = [];
const ghostLines: string[] = [];
const redundant = redundantDependencies(model.rows);
for (const g of groups) {
for (const { row } of g.rows) {
for (const dep of row.dependsOn) {
if (redundant.has(`${dep}>${row.id}`)) continue;
const from = anchor(dep);
const to = anchor(row.id);
if (!from || !to) continue;
const x1 = from.xe;
const x2 = to.xs;
const depRow = model.rows.find((r) => r.id === dep);
const label = `${dep} -> ${row.id} ${depRow?.actionName ?? ""} -> ${row.actionName ?? ""}`;
if (depRow?.isMilestone) {
// зависимость от вехи: вместо вертикали через весь план - контурный ромб вехи на строке зависимого шага, стрелка идёт от него
const gc = color(groupOf.get(dep)!.stage).stroke;
const gy = to.y;
const sid = safeId(dep);
vlIds.add(sid);
vlines.push(`<line class="vl vl-${sid}" x1="${x1}" y1="${from.y}" x2="${x1}" y2="${gy}" stroke="${gc}" stroke-width="1.6"/>`);
const ghost = `<path class="ms ms-${sid}" d="M${x1} ${gy - 7} L${x1 + 7} ${gy} L${x1} ${gy + 7} L${x1 - 7} ${gy} Z" fill="#fff" stroke="${gc}" stroke-width="1.6"/>`;
const several = row.dependsOn.filter((d) => model.rows.find((r) => r.id === d)?.isMilestone && !redundant.has(`${d}>${row.id}`)).length > 1;
const gl = `<text x="${x1 - 11}" y="${gy + 3}" text-anchor="end" font-size="9" fill="${gc}">${esc(several ? dep : truncate(`${dep} ${depRow.actionName ?? ""}`, 40))}</text>`; // несколько вех на одной строке: только id, чтобы подписи не налезали
const x2e = row.isMilestone ? x2 - 10 : x2; // у вехи-цели стрелка заканчивается перед ромбом, иначе остриё закрыто ромбом
const lp = x2e > x1 + 7 ? `M${x1 + 7} ${gy} H${x2e}` : x2e < x1 - 7 ? `M${x1 - 7} ${gy} H${x2e}` : ""; // назад - если шаг начинается раньше вехи (противоречие)
if (lp) ghostLines.push(`<g class="dep">${tooltip([label])}<path class="dl" d="${lp}" fill="none" stroke="#666" stroke-width="1.1" marker-end="url(#arrg)"/><path d="${lp}" fill="none" stroke="transparent" stroke-width="8" pointer-events="stroke"/></g>`);
ghostMarks.push(`<g>${tooltip([label])}${ghost}${gl}</g>`);
continue;
}
const d = x2 >= x1 ? `M${x1} ${from.y} V${to.y} H${x2}` : `M${x1} ${from.y} H${x1 + 6} V${to.y} H${x2}`;
arrows.push(`<g class="dep">${tooltip([label])}<path class="dl" d="${d}" fill="none" stroke="#444" stroke-width="1.1" marker-end="url(#arr)"/><path d="${d}" fill="none" stroke="transparent" stroke-width="8" pointer-events="stroke"/></g>`);
}
}
}
// слои снизу вверх: линии от контурных вех (почти фон), обычные зависимости, контурные ромбы с подписями (поверх линий)
out.push(`<g opacity="0.75">${ghostLines.join("")}${arrows.join("")}</g>`);
}
// Строки раскрытых групп
for (const g of groups) {
if (g.collapsed) continue;
const c = color(g.stage);
for (const { row, t } of g.rows) {
const top = rowTop.get(row.id)!;
const cy = top + BAR_CY;
const warn = conflicts.get(row.id);
const tip = tooltip([
`${row.id} - ${row.actionName ?? ""}${row.isMilestone ? " (веха)" : ""}`,
row.description,
`Ответственный: ${describeResponsible(row, model)}`,
row.systemToBe ? `Система: ${row.systemToBe}` : null,
row.dateConstraint ? `Срок: ${row.dateConstraint}` : `Срок выведен из зависимостей: день ${t.start}${t.end !== t.start ? "–" + t.end : ""}`,
row.duration ? `Длительность: ${row.duration}` : null,
row.dependsOn.length ? `После: ${row.dependsOn.join(", ")}` : null,
...(warn ?? []).map((w) => `⚠ ${w}`),
row.questions ? `Вопрос: ${row.questions}` : null,
]);
const ms = row.isMilestone;
const name = row.actionName ?? row.description ?? "";
out.push(`<g>${tip}`);
out.push(`<text class="sel" x="12" y="${cy + 4}" font-weight="${ms ? 700 : 500}" fill="${warn ? "#b00020" : "#222"}">${esc(row.id)}</text>`);
out.push(`<text class="sel" x="62" y="${cy + 4}" font-weight="${ms ? 600 : 400}" fill="#222">${esc(truncate(name, 52))}</text>`);
if (row.questions) out.push(`<circle cx="${GANTT_LEFT - 14}" cy="${cy}" r="4" fill="#e6a100"><title>${esc(row.questions)}</title></circle>`);
const stroke = warn ? "#d32f2f" : c.stroke;
const dash = t.approx ? ' stroke-dasharray="4 2"' : "";
const textW = name.length * CHAR_W;
const idText = (tx: number, anchor: "start" | "end") =>
out.push(`<text x="${tx}" y="${top + ROW - 3}" text-anchor="${anchor}" font-size="9" letter-spacing="0.5" fill="#777">${esc(row.id)}${row.duration ? ` · ${esc(row.duration)}` : ""}</text>`);
if (t.kind === "recurring") {
const w = Math.max(2, (t.end - t.start) * px);
out.push(`<rect x="${x(t.start)}" y="${cy - 4}" width="${w}" height="8" rx="3" fill="${c.stroke}" fill-opacity="0.35" stroke="${c.stroke}" stroke-width="0.8"/>`);
out.push(`<text x="${x(t.start) + 2}" y="${cy - 9}" font-size="11" font-weight="600" fill="${c.stroke}">${esc(name)}</text>`);
idText(x(t.end), "end");
} else {
const hasBar = t.end > t.start;
const w = Math.max(3, (t.end - t.start) * px);
const solid = !t.approx;
if (hasBar) {
out.push(`<rect x="${x(t.start)}" y="${cy - BAR_H / 2}" width="${w}" height="${BAR_H}" rx="3" fill="${solid ? c.stroke : c.fill}" stroke="${stroke}" stroke-width="${warn ? 1.6 : 1.1}"${dash}/>`);
if (name) {
if (textW + 8 <= w) out.push(`<text x="${x(t.start) + 5}" y="${cy + 4}" font-size="11" font-weight="600" fill="${solid ? "#fff" : "#222"}">${esc(name)}</text>`);
else {
out.push(`<text x="${x(t.start)}" y="${cy - BAR_H / 2 - 3}" font-size="11" font-weight="600" fill="${c.stroke}">${esc(name)}</text>`);
}
}
}
if (ms || t.kind === "milestone") {
const px0 = x(t.end);
const late = t.deadline !== null && t.end > t.deadline;
if (t.deadline !== null && t.end !== t.deadline) out.push(`<line x1="${px0}" y1="${cy}" x2="${x(t.deadline)}" y2="${cy}" stroke="#d32f2f" stroke-width="1" stroke-dasharray="3 3"/>`);
out.push(`<path class="ms ms-${safeId(row.id)}" d="M${px0} ${cy - 8} L${px0 + 8} ${cy} L${px0} ${cy + 8} L${px0 - 8} ${cy} Z" fill="#1f1f1f" stroke="${late ? "#d32f2f" : "#fff"}" stroke-width="${late ? 2.5 : 1.2}"/>`);
if (!hasBar && name) {
out.push(`<text x="${px0 + 12}" y="${cy + 4}" font-size="11" font-weight="600" fill="${c.stroke}">${esc(name)}</text>`);
}
idText(px0 + 10, "start");
} else {
if (!hasBar && name) {
out.push(`<text x="${x(t.end) + 6}" y="${cy + 4}" font-size="11" font-weight="600" fill="${c.stroke}">${esc(name)}</text>`);
}
idText(hasBar ? x(t.end) : x(t.end) + 6, hasBar ? "end" : "start");
}
}
if (t.deadline !== null) {
const rx = x(t.deadline);
out.push(`<line x1="${rx}" y1="${cy - 12}" x2="${rx}" y2="${cy + 12}" stroke="#d32f2f" stroke-width="3" pointer-events="none"><title>${esc(`Крайний срок: день ${t.deadline}`)}</title></line>`);
}
out.push("</g>");
}
}
// Строки групп: название слева (клик сворачивает), сводная полоса с вехами справа
for (const g of groups) {
const c = color(g.stage);
const s = g.summary;
const barY = g.top + GROUP_PAD + g.levels * LABEL_STEP;
const cy = barY + GROUP_BAR_H / 2;
const tip = tooltip([
`${g.stage}: ${g.rows.length} шаг(ов), дни ${s.start}–${s.end}`,
s.milestones.length ? "Вехи:" : "Вех в группе нет (признак is_milestone)",
...s.milestones.map((m) => ` день ${m.day}: ${m.row.id} - ${m.row.actionName ?? ""}`),
g.collapsed ? "Клик - развернуть" : "Клик - свернуть",
]);
// зона клика: левая колонка и сама полоса
out.push(`<g data-toggle="${esc(g.stage)}" style="cursor:pointer">${tip}<rect x="0" y="${g.top}" width="${GANTT_LEFT - 24}" height="${g.headH}" fill="#000" fill-opacity="0"/>`);
const personOf = new Map(model.responsible.map((r) => [r.id, r.person ?? r.id]));
const people = [
...new Set(
g.rows
.flatMap(({ row }) => (row.responsible.length ? row.responsible.map((id) => personOf.get(id) ?? id) : [row.role ? roleName.get(row.role) ?? row.role : null]))
.filter((v): v is string => !!v),
),
];
out.push(`<text x="14" y="${g.top + 19}" font-size="13" fill="${c.stroke}">${g.collapsed ? "▸" : "▾"}</text>`);
out.push(`<text x="32" y="${g.top + 19}" font-size="14" font-weight="700" fill="#222">${esc(truncate(g.stage, 30))}<tspan dx="6" font-size="11" font-weight="400" fill="#667085">(${g.rows.length})</tspan></text>`);
if (people.length) out.push(`<text x="32" y="${g.top + 34}" font-size="11" fill="#667085">${esc(truncate(people.join(" · "), 44))}</text>`);
out.push("</g>");
out.push(`<g>${tip}`);
for (const [a, b] of s.segments) {
out.push(`<rect x="${x(a)}" y="${barY}" width="${Math.max(2, (b - a) * px)}" height="${GROUP_BAR_H}" rx="2" fill="${c.stroke}" stroke="${c.stroke}" stroke-width="1.2"/>`);
}
const diamond = (dx: number, size: number, late = false, id?: string) => `<path${id ? ` class="ms ms-${safeId(id)}"` : ""} d="M${dx} ${cy - size} L${dx + size} ${cy} L${dx} ${cy + size} L${dx - size} ${cy} Z" fill="${c.stroke}" stroke="${late ? "#d32f2f" : "#fff"}" stroke-width="${late ? 2.5 : 1}"/>`;
const markDays = new Set(s.milestones.map((m) => m.day));
if (!markDays.has(s.start)) out.push(diamond(x(s.start), 6));
if (!markDays.has(s.end)) out.push(diamond(x(s.end), 6));
for (const m of s.milestones) {
if (m.deadline !== null && m.day !== m.deadline) out.push(`<line x1="${x(m.day)}" y1="${cy}" x2="${x(m.deadline)}" y2="${cy}" stroke="#d32f2f" stroke-width="1" stroke-dasharray="3 3"/>`);
out.push(diamond(x(m.day), 8, m.deadline !== null && m.day > m.deadline, m.row.id));
}
for (const m of s.milestones) {
if (m.deadline === null) continue;
const rx = x(m.deadline);
out.push(`<line x1="${rx}" y1="${cy - 12}" x2="${rx}" y2="${cy + 12}" stroke="#d32f2f" stroke-width="3" pointer-events="none"><title>${esc(`Крайний срок: ${m.row.id}, день ${m.deadline}`)}</title></line>`);
}
for (const l of g.labels) {
const ly = barY - 4 - l.level * LABEL_STEP;
out.push(`<text x="${l.x}" y="${ly}" text-anchor="middle" font-size="11" font-weight="600" fill="${c.stroke}">${esc(l.text)}</text>`);
}
out.push("</g>");
}
// Легенда
out.push(`<g>${vlines.join("")}</g>`);
out.push(`<g>${ghostMarks.join("")}</g>`);
const ly = height - 20;
out.push(
`<g font-size="11" fill="#444"><path d="M14 ${ly - 4} l6 6 l-6 6 l-6 -6 z" fill="#777"/><text x="26" y="${ly + 7}">веха</text>` +
`<rect x="72" y="${ly - 1}" width="30" height="10" rx="2" fill="#3f7ea6" stroke="#3f7ea6"/><text x="108" y="${ly + 7}">группа (сводная полоса)</text>` +
`<rect x="260" y="${ly - 1}" width="22" height="10" rx="3" fill="#cfe8ff" stroke="#3b7dc4"/><text x="288" y="${ly + 7}">работа</text>` +
`<rect x="342" y="${ly - 1}" width="22" height="10" rx="3" fill="#cfe8ff" stroke="#3b7dc4" stroke-dasharray="4 2"/><text x="370" y="${ly + 7}">срок «не позже / около»</text>` +
`<rect x="530" y="${ly - 1}" width="22" height="10" rx="3" fill="#777" fill-opacity="0.35" stroke="#777"/><text x="558" y="${ly + 7}">повторяется</text>` +
`<rect x="645" y="${ly - 1}" width="22" height="10" rx="3" fill="#fff" stroke="#d32f2f" stroke-width="1.6"/><text x="673" y="${ly + 7}">противоречие в сроках</text>` +
`<circle cx="820" cy="${ly + 4}" r="4" fill="#e6a100"/><text x="830" y="${ly + 7}">есть открытый вопрос (наведите курсор)</text>` +
`<line x1="1085" y1="${ly - 3}" x2="1085" y2="${ly + 11}" stroke="#d32f2f" stroke-width="3"/><text x="1094" y="${ly + 7}">крайний срок</text></g>`,
);
const hoverCss = `.vl{opacity:0;pointer-events:none}.dep:hover .dl{stroke:#e91e63;stroke-width:3}` + [...vlIds].map((i) => `svg:has(.ms-${i}:hover) .vl-${i}{opacity:1}`).join("");
const defs = `<style>${hoverCss}</style><marker id="arr" viewBox="0 0 6 6" refX="5" refY="3" markerWidth="6" markerHeight="6" orient="auto"><path d="M0 0 L6 3 L0 6 z" fill="#444"/></marker><marker id="arrg" viewBox="0 0 6 6" refX="5" refY="3" markerWidth="6" markerHeight="6" orient="auto"><path d="M0 0 L6 3 L0 6 z" fill="#666"/></marker>`;
return svgDoc(width, height, defs, out.join("\n"), `data-left="${GANTT_LEFT}" data-px="${px}"`);
}