Гант: свёртывание групп, сводные полосы с вехами, масштаб времени
All checks were successful
ci / test (push) Successful in 18s
ci / deploy (push) Successful in 1m17s

Каждый этап - группа со сводной штрихованной полосой; вехи (колонка
is_milestone, по умолчанию чек-пойнты CP-*) отмечены ромбами с подписями
над полосой и пунктирными направляющими вниз. Группы сворачиваются кликом,
кнопками «Свернуть все / Развернуть все». Масштаб времени (кнопки и
Shift+колесо) меняет только ось, шрифты и интервалы не меняются.
Состояние в адресе: px, collapsed. Параметры px и collapsed у /gantt.svg.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-14 14:51:37 +03:00
parent ea57029bc0
commit 95ddaa4d99
10 changed files with 412 additions and 107 deletions

View File

@@ -9,13 +9,26 @@ export interface GanttOptions {
deps?: boolean;
/** показывать только эти этапы */
stages?: string[] | null;
/** масштаб времени: пикселей на день. Меняет только ось времени, шрифты и интервалы строк остаются прежними */
px?: number;
/** свёрнутые группы (этапы): от них остаётся только сводная полоса */
collapsed?: string[] | null;
}
const LEFT = 420;
const PX = 5; // пикселей на день
/** Ширина левой колонки с названиями; не зависит от масштаба времени. */
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 = 24;
const HEAD = 76;
const STAGE_ROW = 24;
const GROUP_BAR_H = 14; // высота сводной полосы
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`);
@@ -24,11 +37,16 @@ const addDays = (iso: string, days: number): string | null => {
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));
};
/** Порядок этапов: по самому раннему сроку окончания среди шагов с заданным сроком (шаги без срока не тянут этап в начало), затем по появлению. */
export function stageOrder(rows: ProcessRow[], schedule: Schedule): string[] {
const key = new Map<string, number>();
for (const r of rows) {
const s = r.stage ?? "(без этапа)";
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);
@@ -40,134 +58,254 @@ export function stageOrder(rows: ProcessRow[], schedule: Schedule): string[] {
return [...key.entries()].sort((a, b) => a[1] - b[1]).map(([s]) => s);
}
export interface GroupSummary {
stage: string;
/** границы сводной полосы (дни) */
start: number;
end: number;
/** вехи группы: строки с признаком is_milestone, по дате завершения */
milestones: Array<{ row: ProcessRow; day: 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 }))
.sort((a, b) => a.day - b.day || a.row.id.localeCompare(b.row.id, "ru", { numeric: true }));
return { stage, start: Number.isFinite(start) ? start : 0, end: Number.isFinite(end) ? end : 0, milestones };
}
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 };
}
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).filter((s) => !opts.stages?.length || opts.stages.includes(s));
const color = (stage: string) => PALETTE[stages.indexOf(stage) % PALETTE.length] ?? PALETTE[0]!;
const colorIdx = (stage: string) => Math.max(0, stages.indexOf(stage)) % PALETTE.length;
const color = (stage: string) => PALETTE[colorIdx(stage)] ?? PALETTE[0]!;
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 x = (d: number) => GANTT_LEFT + d * px;
// Строки: заголовок этапа, затем его шаги по началу
type Line = { kind: "stage"; stage: string } | { kind: "row"; row: ProcessRow; t: Timing };
const lines: Line[] = [];
for (const stage of stages) {
lines.push({ kind: "stage", stage });
const rs = model.rows
.filter((r) => (r.stage ?? "(без этапа)") === stage)
// Группы: строки этапа по началу
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 }));
for (const x of rs) lines.push({ kind: "row", ...x });
}
const summary = summarizeGroup(stage, rows);
const { labels, levels } = placeLabels(summary.milestones.map((m) => ({ x: x(m.day), row: m.row })));
const headH = 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;
const ys: number[] = [];
for (const l of lines) {
ys.push(y);
if (l.kind === "row") yOf.set(l.row.id, y + ROW / 2);
y += l.kind === "stage" ? STAGE_ROW : ROW;
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 + ROW / 2);
y += ROW;
}
}
g.bottom = y;
}
const height = y + 40;
const days = Math.ceil((schedule.maxDay + 10) / 10) * 10;
const width = LEFT + days * PX + 30;
const x = (d: number) => LEFT + d * PX;
// подписи вех могут выступать за правый край оси
const labelRight = Math.max(0, ...groups.flatMap((g) => g.labels.map((l) => l.x + (l.text.length * CHAR_W) / 2)));
const width = Math.round(Math.max(GANTT_LEFT + days * 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>`);
for (let d = 0; d <= days; d += 7) {
const major = d % 30 === 0 || d % 28 === 0 ? d % 28 === 0 : false;
out.push(`<line x1="${x(d)}" y1="${HEAD - 4}" x2="${x(d)}" y2="${height - 30}" stroke="${major ? "#c9c9c9" : "#eeeeee"}" stroke-width="1"/>`);
// Ось: шаг подписей выбирается так, чтобы подписи не слипались при любом масштабе
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 = 0; 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 = 0; d <= days; d += 30) {
for (let d = 0; 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 out.push(`<text x="${x(d) + 3}" y="${HEAD - 24}" fill="#777" font-size="11">мес. ${d / 30}</text>`);
else if (d % 30 === 0) out.push(`<text x="${x(d) + 3}" y="${HEAD - 24}" fill="#777" font-size="11">мес. ${d / 30}</text>`);
}
// Вертикальные линии чек-поинтов
const cpDays = new Set<number>();
for (const l of lines) if (l.kind === "row" && /^CP-/.test(l.row.id)) cpDays.add(l.t.end);
for (const d of cpDays) out.push(`<line x1="${x(d)}" y1="${HEAD}" x2="${x(d)}" y2="${height - 30}" stroke="#d9a1a1" stroke-width="1" stroke-dasharray="2 4"/>`);
// Подложки групп и направляющие вех
for (const g of groups) {
const c = color(g.stage);
out.push(`<rect x="0" y="${g.top}" width="${width}" height="${g.headH}" fill="${c.fill}" opacity="0.45"/>`);
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"/>`);
}
}
// Зависимости под полосами
// Зависимости под полосами (только между видимыми строками)
if (opts.deps !== false) {
const arrows: string[] = [];
for (const l of lines) {
if (l.kind !== "row") continue;
for (const dep of l.row.dependsOn) {
const dt = schedule.timings.get(dep);
const y1 = yOf.get(dep);
const y2 = yOf.get(l.row.id);
if (!dt || y1 === undefined || y2 === undefined) continue;
const x1 = x(dt.end);
const x2 = x(l.t.start);
const xm = Math.min(x2 - 4, Math.max(x1 + 4, (x1 + x2) / 2));
arrows.push(`<path d="M${x1} ${y1} H${xm} V${y2} H${x2}" fill="none" stroke="#9aa0a6" stroke-width="0.8" marker-end="url(#arr)"/>`);
for (const g of groups) {
for (const { row, t } of g.rows) {
for (const dep of row.dependsOn) {
const dt = schedule.timings.get(dep);
const y1 = yOf.get(dep);
const y2 = yOf.get(row.id);
if (!dt || y1 === undefined || y2 === undefined) continue;
const x1 = x(dt.end);
const x2 = x(t.start);
const xm = Math.min(x2 - 4, Math.max(x1 + 4, (x1 + x2) / 2));
arrows.push(`<path d="M${x1} ${y1} H${xm} V${y2} H${x2}" fill="none" stroke="#9aa0a6" stroke-width="0.8" marker-end="url(#arr)"/>`);
}
}
}
out.push(`<g opacity="0.7">${arrows.join("")}</g>`);
}
// Строки
lines.forEach((l, i) => {
const top = ys[i]!;
if (l.kind === "stage") {
const c = color(l.stage);
out.push(`<rect x="0" y="${top}" width="${width}" height="${STAGE_ROW}" fill="${c.fill}" opacity="0.55"/>`);
out.push(`<text x="12" y="${top + 16}" font-weight="700" fill="${c.stroke}">${esc(l.stage)}</text>`);
return;
// Строки раскрытых групп
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 + ROW / 2;
const warn = conflicts.get(row.id);
const tip = tooltip([
`${row.id} - ${row.actionName ?? ""}${row.isMilestone ? " (веха)" : ""}`,
row.description,
`Ответственный: ${[row.role ? roleName.get(row.role) ?? row.role : null, row.responsibleName].filter(Boolean).join(" / ") || "не указан"}`,
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;
out.push(`<g${t.fromConstraint || t.kind === "recurring" ? "" : ' opacity="0.65"'}>${tip}`);
out.push(`<text x="12" y="${cy + 4}" font-weight="${ms ? 700 : 500}" fill="${warn ? "#b00020" : "#222"}">${esc(row.id)}</text>`);
out.push(`<text x="62" y="${cy + 4}" font-weight="${ms ? 600 : 400}" fill="#222">${esc(truncate(row.actionName ?? row.description ?? "", 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"' : "";
if (t.kind === "recurring") {
out.push(`<rect x="${x(t.start)}" y="${cy - 4}" width="${Math.max(2, (t.end - t.start) * px)}" height="8" rx="3" fill="url(#hatch)" stroke="${c.stroke}" stroke-width="0.8"/>`);
} else {
if (t.end > t.start) {
out.push(`<rect x="${x(t.start)}" y="${cy - 7}" width="${Math.max(3, (t.end - t.start) * px)}" height="14" rx="3" fill="${ms ? c.stroke : c.fill}" fill-opacity="${ms ? 0.55 : 1}" stroke="${stroke}" stroke-width="${warn ? 1.6 : 1.1}"${dash}/>`);
}
if (ms || t.kind === "milestone") {
const px0 = x(t.end);
out.push(`<path d="M${px0} ${cy - 8} L${px0 + 8} ${cy} L${px0} ${cy + 8} L${px0 - 8} ${cy} Z" fill="${ms ? c.stroke : c.fill}" stroke="${stroke}" stroke-width="${ms ? 1.5 : 1}"${dash}/>`);
out.push(`<text x="${px0 + 12}" y="${cy + 4}" fill="#555" font-size="11">день ${t.end}</text>`);
} else {
out.push(`<text x="${x(t.end) + 5}" y="${cy + 4}" fill="#555" font-size="11">${t.start}–${t.end}</text>`);
}
}
out.push("</g>");
}
const { row, t } = l;
const c = color(row.stage ?? "(без этапа)");
const cy = top + ROW / 2;
const warn = conflicts.get(row.id);
}
// Строки групп: название слева (клик сворачивает), сводная полоса с вехами справа
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([
`${row.id} - ${row.actionName ?? ""}`,
row.description,
`Ответственный: ${[row.role ? roleName.get(row.role) ?? row.role : null, row.responsibleName].filter(Boolean).join(" / ") || "не указан"}`,
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,
`${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 ? "Клик - развернуть" : "Клик - свернуть",
]);
const isCp = /^CP-/.test(row.id);
out.push(`<g${t.fromConstraint || t.kind === "recurring" ? "" : ' opacity="0.65"'}>${tip}`);
out.push(`<text x="12" y="${cy + 4}" font-weight="${isCp ? 700 : 500}" fill="${warn ? "#b00020" : "#222"}">${esc(row.id)}</text>`);
out.push(`<text x="62" y="${cy + 4}" font-weight="${isCp ? 600 : 400}" fill="#222">${esc(truncate(row.actionName ?? row.description ?? "", 52))}</text>`);
if (row.questions) out.push(`<circle cx="${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"' : "";
if (t.kind === "milestone") {
const px = x(t.end);
out.push(`<path d="M${px} ${cy - 8} L${px + 8} ${cy} L${px} ${cy + 8} L${px - 8} ${cy} Z" fill="${isCp ? c.stroke : c.fill}" stroke="${stroke}" stroke-width="${isCp ? 1.5 : 1}"${dash}/>`);
if (isCp) out.push(`<text x="${px + 12}" y="${cy + 4}" fill="#555" font-size="11">день ${t.end}</text>`);
} else if (t.kind === "recurring") {
out.push(`<rect x="${x(t.start)}" y="${cy - 4}" width="${Math.max(2, (t.end - t.start) * PX)}" height="8" rx="3" fill="url(#hatch)" stroke="${c.stroke}" stroke-width="0.8"/>`);
} else {
out.push(`<rect x="${x(t.start)}" y="${cy - 7}" width="${Math.max(3, (t.end - t.start) * PX)}" height="14" rx="3" fill="${c.fill}" stroke="${stroke}" stroke-width="${warn ? 1.6 : 1.1}"${dash}/>`);
out.push(`<text x="${x(t.end) + 5}" y="${cy + 4}" fill="#555" font-size="11">${t.start}–${t.end}</text>`);
// зона клика: левая колонка и сама полоса
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"/>`);
out.push(`<text x="10" y="${cy + 5}" font-size="14" fill="${c.stroke}">${g.collapsed ? "▸" : "▾"}</text>`);
out.push(`<text x="28" y="${cy + 5}" font-weight="700" fill="${c.stroke}">${esc(truncate(g.stage, 34))}<tspan dx="6" font-weight="400" fill="#667085">(${g.rows.length})</tspan></text>`);
out.push("</g>");
out.push(`<g>${tip}`);
out.push(`<rect x="${x(s.start)}" y="${barY}" width="${Math.max(2, (s.end - s.start) * px)}" height="${GROUP_BAR_H}" rx="2" fill="url(#gh${colorIdx(g.stage)})" stroke="${c.stroke}" stroke-width="1.2"/>`);
const diamond = (dx: number, size: number) => `<path d="M${dx} ${cy - size} L${dx + size} ${cy} L${dx} ${cy + size} L${dx - size} ${cy} Z" fill="${c.stroke}" stroke="#fff" stroke-width="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) out.push(diamond(x(m.day), 8));
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>");
});
}
// Легенда
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="130" y="${ly - 1}" width="22" height="10" rx="3" fill="#cfe8ff" stroke="#3b7dc4"/><text x="158" y="${ly + 7}">работа</text>` +
`<rect x="212" y="${ly - 1}" width="22" height="10" rx="3" fill="#cfe8ff" stroke="#3b7dc4" stroke-dasharray="4 2"/><text x="240" y="${ly + 7}">срок «не позже / около»</text>` +
`<rect x="400" y="${ly - 1}" width="22" height="10" rx="3" fill="url(#hatch)" stroke="#777"/><text x="428" y="${ly + 7}">повторяется</text>` +
`<rect x="515" y="${ly - 1}" width="22" height="10" rx="3" fill="#fff" stroke="#d32f2f" stroke-width="1.6"/><text x="543" y="${ly + 7}">противоречие в сроках</text>` +
`<circle cx="690" cy="${ly + 4}" r="4" fill="#e6a100"/><text x="700" y="${ly + 7}">есть открытый вопрос (наведите курсор)</text></g>`,
`<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="url(#gh0)" stroke="#3b7dc4"/><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="url(#hatch)" 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></g>`,
);
const hatches = stages
.map((_, i) => {
const c = PALETTE[i % PALETTE.length]!;
return `<pattern id="gh${i}" width="7" height="7" patternUnits="userSpaceOnUse" patternTransform="rotate(45)"><rect width="7" height="7" fill="${c.fill}"/><line x1="0" y1="0" x2="0" y2="7" stroke="${c.stroke}" stroke-width="2.4"/></pattern>`;
})
.join("");
const defs =
`<marker id="arr" viewBox="0 0 6 6" refX="5" refY="3" markerWidth="5" markerHeight="5" orient="auto"><path d="M0 0 L6 3 L0 6 z" fill="#9aa0a6"/></marker>` +
`<pattern id="hatch" width="6" height="6" patternUnits="userSpaceOnUse" patternTransform="rotate(45)"><rect width="6" height="6" fill="#ffffff"/><line x1="0" y1="0" x2="0" y2="6" stroke="#9aa0a6" stroke-width="2"/></pattern>`;
return svgDoc(width, height, defs, out.join("\n"));
`<pattern id="hatch" width="6" height="6" patternUnits="userSpaceOnUse" patternTransform="rotate(45)"><rect width="6" height="6" fill="#ffffff"/><line x1="0" y1="0" x2="0" y2="6" stroke="#9aa0a6" stroke-width="2"/></pattern>` +
hatches +
// запасной шаблон для легенды, если этапов нет
(stages.length ? "" : `<pattern id="gh0" width="7" height="7" patternUnits="userSpaceOnUse" patternTransform="rotate(45)"><rect width="7" height="7" fill="#cfe8ff"/><line x1="0" y1="0" x2="0" y2="7" stroke="#3b7dc4" stroke-width="2.4"/></pattern>`);
return svgDoc(width, height, defs, out.join("\n"), `data-left="${GANTT_LEFT}" data-px="${px}"`);
}