Гант: группы, порядок и цвета как в презентации, сплошная заливка, шапка группы с ролями; тест; docs
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
import type { ProcessModel, ProcessRow } from "./model.js";
|
||||
import type { Schedule, Timing } from "./schedule.js";
|
||||
import { PALETTE, esc, svgDoc, tooltip, truncate } from "./svg.js";
|
||||
import { esc, svgDoc, tooltip, truncate } from "./svg.js";
|
||||
|
||||
export interface GanttOptions {
|
||||
/** дата kick-off (YYYY-MM-DD) - если задана, на оси подписываются календарные даты */
|
||||
@@ -26,6 +26,7 @@ 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;
|
||||
@@ -44,7 +45,24 @@ export const clampPx = (px: number | undefined): number => {
|
||||
return Math.min(GANTT_MAX_PX, Math.max(GANTT_MIN_PX, v));
|
||||
};
|
||||
|
||||
/** Порядок этапов: по самому раннему сроку окончания среди шагов с заданным сроком (шаги без срока не тянут этап в начало), затем по появлению. */
|
||||
/** Группы презентации «Pre-construction»: порядок сверху вниз и цвета (сплошная полоса / светлый тон для примерных сроков). */
|
||||
export const STAGE_STYLES: ReadonlyArray<{ stage: string; fill: string; stroke: string }> = [
|
||||
{ stage: "Договоры", stroke: "#7a808f", fill: "#dde0e6" },
|
||||
{ stage: "Архитектура", stroke: "#3f9a78", fill: "#d4ece3" },
|
||||
{ stage: "Спецификации", stroke: "#3f7ea6", fill: "#d3e4ef" },
|
||||
{ stage: "Пермит", stroke: "#d8622f", fill: "#f7d9cc" },
|
||||
{ stage: "Финансы", stroke: "#d4982f", fill: "#f5e6c8" },
|
||||
{ stage: "Закупки", stroke: "#6f93ab", fill: "#dbe6ee" },
|
||||
{ stage: "Стройка", stroke: "#1f7a52", fill: "#cfe6da" },
|
||||
];
|
||||
const OTHER_STYLES: ReadonlyArray<{ fill: string; stroke: string }> = [
|
||||
{ stroke: "#8a6bb5", fill: "#e5dcf1" },
|
||||
{ stroke: "#b44b7c", fill: "#f5cfe0" },
|
||||
{ stroke: "#2f9a8f", fill: "#c9f0ec" },
|
||||
{ stroke: "#a39a1c", fill: "#f3efb0" },
|
||||
];
|
||||
|
||||
/** Порядок этапов: сначала группы презентации в её порядке, остальные - по самому раннему сроку окончания среди шагов с заданным сроком (шаги без срока не тянут этап в начало), затем по появлению. */
|
||||
export function stageOrder(rows: ProcessRow[], schedule: Schedule): string[] {
|
||||
const key = new Map<string, number>();
|
||||
for (const r of rows) {
|
||||
@@ -57,7 +75,15 @@ export function stageOrder(rows: ProcessRow[], schedule: Schedule): string[] {
|
||||
const v = t.fromConstraint ? t.end : t.end + 0.5; // выведенные сроки чуть слабее заданных
|
||||
key.set(s, Math.min(key.get(s) ?? Infinity, v));
|
||||
}
|
||||
return [...key.entries()].sort((a, b) => a[1] - b[1]).map(([s]) => s);
|
||||
const known = (s: string) => STAGE_STYLES.findIndex((x) => x.stage === s);
|
||||
return [...key.entries()]
|
||||
.sort((a, b) => {
|
||||
const ka = known(a[0]);
|
||||
const kb = known(b[0]);
|
||||
if (ka >= 0 || kb >= 0) return (ka >= 0 ? ka : Infinity) - (kb >= 0 ? kb : Infinity) || a[1] - b[1];
|
||||
return a[1] - b[1];
|
||||
})
|
||||
.map(([s]) => s);
|
||||
}
|
||||
|
||||
export interface GroupSummary {
|
||||
@@ -120,8 +146,9 @@ export function renderGantt(model: ProcessModel, schedule: Schedule, opts: Gantt
|
||||
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 colorIdx = (stage: string) => Math.max(0, stages.indexOf(stage)) % PALETTE.length;
|
||||
const color = (stage: string) => PALETTE[colorIdx(stage)] ?? PALETTE[0]!;
|
||||
const others = stages.filter((s) => !STAGE_STYLES.some((x) => x.stage === s));
|
||||
const color = (stage: string): { fill: string; stroke: string } =>
|
||||
STAGE_STYLES.find((x) => x.stage === stage) ?? OTHER_STYLES[Math.max(0, others.indexOf(stage)) % OTHER_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]);
|
||||
@@ -136,7 +163,7 @@ export function renderGantt(model: ProcessModel, schedule: Schedule, opts: Gantt
|
||||
.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 = GROUP_PAD + levels * LABEL_STEP + GROUP_BAR_H + GROUP_PAD;
|
||||
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 };
|
||||
});
|
||||
|
||||
@@ -187,7 +214,9 @@ export function renderGantt(model: ProcessModel, schedule: Schedule, opts: Gantt
|
||||
// Подложки групп и направляющие вех
|
||||
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"/>`);
|
||||
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"/>`);
|
||||
@@ -258,7 +287,7 @@ export function renderGantt(model: ProcessModel, schedule: Schedule, opts: Gantt
|
||||
out.push(`<text x="${tx}" y="${top + ROW - 3}" text-anchor="${anchor}" font-size="9" letter-spacing="0.5" fill="#777">${esc(row.id)}</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="url(#hatch)" stroke="${c.stroke}" stroke-width="0.8"/>`);
|
||||
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 {
|
||||
@@ -266,7 +295,7 @@ export function renderGantt(model: ProcessModel, schedule: Schedule, opts: Gantt
|
||||
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}" fill-opacity="${ms ? 0.8 : 1}" stroke="${stroke}" stroke-width="${warn ? 1.6 : 1.1}"${dash}/>`);
|
||||
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 {
|
||||
@@ -306,11 +335,13 @@ export function renderGantt(model: ProcessModel, schedule: Schedule, opts: Gantt
|
||||
]);
|
||||
// зона клика: левая колонка и сама полоса
|
||||
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>`);
|
||||
const people = [...new Set(g.rows.map(({ row }) => (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}`);
|
||||
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"/>`);
|
||||
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="${c.stroke}" 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));
|
||||
@@ -327,25 +358,14 @@ export function renderGantt(model: ProcessModel, schedule: Schedule, opts: Gantt
|
||||
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="url(#gh0)" stroke="#3b7dc4"/><text x="108" 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="url(#hatch)" stroke="#777"/><text x="558" 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></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="6" markerHeight="6" orient="auto"><path d="M0 0 L6 3 L0 6 z" fill="#444"/></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>` +
|
||||
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>`);
|
||||
const defs = `<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>`;
|
||||
return svgDoc(width, height, defs, out.join("\n"), `data-left="${GANTT_LEFT}" data-px="${px}"`);
|
||||
}
|
||||
|
||||
@@ -182,6 +182,19 @@ describe("Гант: группы, вехи, свёртывание, масшта
|
||||
expect(narrow).toMatch(/font-weight="600" fill="#[0-9a-f]{6}">Работа<[/]text>/); // не влезло - подпись над полосой
|
||||
});
|
||||
|
||||
it("группы презентации: порядок и цвета фиксированы, заливка сплошная (без штриховки)", () => {
|
||||
const rows = ["Стройка", "Пермит", "Договоры", "Финансы", "Свой этап", "Спецификации", "Архитектура", "Закупки"].map((s, i) => row({ id: "S-" + i, stage: s, date_constraint: "день " + (10 + i) }));
|
||||
const m: ProcessModel = { ...model, rows };
|
||||
const sc = computeSchedule(m.rows);
|
||||
expect(stageOrder(m.rows, sc)).toEqual(["Договоры", "Архитектура", "Спецификации", "Пермит", "Финансы", "Закупки", "Стройка", "Свой этап"]);
|
||||
const svg = renderGantt(m, sc, {});
|
||||
expect(svg).toContain("#7a808f"); // Договоры
|
||||
expect(svg).toContain("#d8622f"); // Пермит
|
||||
expect(svg).toContain("#1f7a52"); // Стройка
|
||||
expect(svg).not.toContain("<pattern");
|
||||
expect(svg).not.toContain("url(#hatch)");
|
||||
});
|
||||
|
||||
it("масштаб времени меняет только ось: ширина растёт, шрифты и высота остаются", () => {
|
||||
const a = renderGantt(ms, sch, { px: 5 });
|
||||
const b = renderGantt(ms, sch, { px: 20 });
|
||||
|
||||
Reference in New Issue
Block a user