Coverage for app / documents / visuals / mermaid / gantt.py: 91%
373 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
1"""``gantt``.
3Read as Mermaid's ``ganttDb`` reads it: ``title``, ``dateFormat`` (dayjs
4tokens; ISO 8601 accepted beside it), ``axisFormat`` (d3 directives),
5``tickInterval``, ``excludes`` / ``includes`` (weekends, weekday names,
6dates), ``inclusiveEndDates``, ``weekday``, ``section`` and tasks:
7``Name : [done|active|crit|milestone, …] [id,] [start,] end`` where a start
8is a date or ``after id …`` (the latest end) and an end a date, a duration
9(``3d``, ``1w``, ``12h``) or ``until id …`` (the earliest start). A task
10with no start follows the one before it. Tasks may name later tasks; one
11that waits on itself, or names no task, is refused with its line. A
12duration skips excluded days, as Mermaid's ``fixTaskDates`` does. There is
13no "today" line: a PDF has no today.
15Drawn in Mermaid's default theme, with its dates above and below (the top
16axis is also each part's header when a long chart is split across pages).
17"""
19from __future__ import annotations
21import re
22from dataclasses import dataclass, field
23from datetime import datetime, timedelta
25from reportlab.lib.colors import Color, HexColor
27from ..registry import Layout
28from ..text import ellipsize, measure
29from ..theme import Theme
30from . import look
31from .base import Diagram, MermaidSyntaxError, Statement, register_diagram
32from .canvas import Canvas, block_size
33from .compound import MAX_EDGES, MAX_NODES
34from .dates import DAYS, DateFormat, add_months, duration_end, strftime
35from .labels import clean, fit
37TAGS = ("done", "active", "crit", "milestone")
38_TICK = re.compile(r"^([1-9]\d*)(millisecond|second|minute|hour|day|week|month)$")
39_TASK = re.compile(r"^(?P<name>[^:]+?)\s*:\s*(?P<data>.*)$")
40_WEEKDAYS = {name.lower(): i for i, name in enumerate(DAYS)}
42#: Sizes, in points.
43WIDTH = 520.0
44ROW = 20.0
45BAR = 14.0
46AXIS = 18.0
47MARGIN = 6.0
48LABEL_COLUMN = 140.0
49DAY = timedelta(days=1)
51TASK_FILL = HexColor("#8a90dd")
52TASK_STROKE = HexColor("#534fbc")
53ACTIVE_FILL = HexColor("#bfc7ff")
54DONE_FILL = HexColor("#d3d3d3")
55DONE_STROKE = HexColor("#808080")
56CRIT_FILL = HexColor("#ff0000")
57CRIT_STROKE = HexColor("#ff8888")
58GRID = HexColor("#d3d3d3")
59EXCLUDED = HexColor("#eeeeee")
60#: Mermaid's four section bands, each at its CSS opacity.
61SECTION_BANDS: tuple[tuple[Color | None, float], ...] = (
62 (HexColor("#6666ff"), 0.10),
63 (None, 0.0),
64 (HexColor("#fff400"), 0.20),
65 (None, 0.0),
66)
67#: Tick steps tried, smallest first: (count, unit).
68_STEPS: tuple[tuple[int, str], ...] = (
69 (1, "hour"), (3, "hour"), (6, "hour"), (12, "hour"), (1, "day"), (2, "day"),
70 (1, "week"), (2, "week"), (1, "month"), (3, "month"), (6, "month"),
71 (12, "month"), (24, "month"), (60, "month"), (120, "month"),
72) # fmt: skip
73MAX_TICKS = 10
76@dataclass
77class Task:
78 name: str
79 id: str
80 section: int | None
81 tags: set[str]
82 start: str | None
83 end: str
84 line: int
85 index: int
88@dataclass
89class Placed:
90 task: Task
91 start: datetime
92 end: datetime
95@dataclass
96class Exclusions:
97 weekends: bool = False
98 weekdays: set[int] = field(default_factory=set)
99 dates: set[str] = field(default_factory=set)
100 included: set[str] = field(default_factory=set)
102 def excluded(self, day: datetime) -> bool:
103 key = day.date().isoformat()
104 if key in self.included:
105 return False
106 return (
107 (self.weekends and day.weekday() >= 5)
108 or day.weekday() in self.weekdays
109 or key in self.dates
110 )
112 def any(self) -> bool:
113 return self.weekends or bool(self.weekdays) or bool(self.dates)
116@register_diagram
117class GanttDiagram(Diagram):
118 keywords = ("gantt",)
119 noun = "a Gantt chart"
121 def __init__(self) -> None:
122 self.title = None
123 self.date_format = DateFormat("YYYY-MM-DD")
124 self.axis_format: str | None = None
125 self.tick: tuple[int, str] | None = None
126 self.exclusions = Exclusions()
127 self.inclusive = False
128 self.week_starts = 6 # Sunday, as d3's weeks
129 self.sections: list[str] = []
130 self.tasks: list[Task] = []
131 self.placed: list[Placed] = []
133 @classmethod
134 def parse(cls, header: Statement, statements: list[Statement]) -> GanttDiagram:
135 diagram = cls()
136 pending_excludes: list[tuple[str, int]] = []
137 for statement in statements:
138 text, line = statement.text, statement.line
139 first, _, rest = text.partition(" ")
140 rest = rest.strip()
141 if first == "title":
142 diagram.title = rest or None
143 elif first == "dateFormat":
144 diagram.date_format = DateFormat(rest)
145 elif first == "axisFormat":
146 diagram.axis_format = rest or None
147 elif first == "tickInterval":
148 m = _TICK.match(rest)
149 if not m:
150 raise MermaidSyntaxError(
151 line, "tickInterval is a count and a unit, as 1week"
152 )
153 diagram.tick = (int(m.group(1)), m.group(2))
154 elif first in ("excludes", "includes"):
155 pending_excludes.append((text, line))
156 elif first == "inclusiveEndDates":
157 diagram.inclusive = True
158 elif first == "weekday":
159 if rest.lower() not in _WEEKDAYS:
160 raise MermaidSyntaxError(line, "weekday names a day of the week")
161 diagram.week_starts = _WEEKDAYS[rest.lower()]
162 elif first == "section":
163 diagram.sections.append(rest)
164 if len(diagram.sections) > MAX_NODES:
165 raise MermaidSyntaxError(
166 None, f"it has more than {MAX_NODES} sections"
167 )
168 elif first in (
169 "todayMarker",
170 "topAxis",
171 "displayMode",
172 "weekend",
173 "click",
174 ) or first.startswith(("accTitle", "accDescr")):
175 continue
176 else:
177 diagram._task(text, line)
178 # Exclusions are dates in the format: read once the format is known.
179 for text, line in pending_excludes:
180 diagram._exclusions(text, line)
181 if not diagram.tasks:
182 raise MermaidSyntaxError(None, "it has no tasks")
183 diagram._resolve()
184 return diagram
186 def _task(self, text: str, line: int) -> None:
187 m = _TASK.match(text)
188 if not m:
189 raise MermaidSyntaxError(line, "a task is written 'name : start, end'")
190 parts = [p.strip() for p in m.group("data").split(",")]
191 tags: set[str] = set()
192 while parts and parts[0] in TAGS:
193 tags.add(parts.pop(0))
194 if parts and parts[0] == "vert":
195 parts.pop(0)
196 tags.add("milestone")
197 index = len(self.tasks)
198 if len(parts) == 1:
199 tid, start, end = f"task{index + 1}", None, parts[0]
200 elif len(parts) == 2:
201 tid, start, end = f"task{index + 1}", parts[0], parts[1]
202 elif len(parts) == 3:
203 tid, start, end = parts[0], parts[1], parts[2]
204 else:
205 raise MermaidSyntaxError(
206 line, "a task has at most an id, a start and an end after its tags"
207 )
208 if not end:
209 raise MermaidSyntaxError(line, "a task's end or duration is missing")
210 if start is None and index == 0:
211 raise MermaidSyntaxError(line, "the first task needs a start")
212 section = len(self.sections) - 1 if self.sections else None
213 self.tasks.append(
214 Task(m.group("name"), tid, section, tags, start, end, line, index)
215 )
216 if len(self.tasks) > MAX_EDGES:
217 raise MermaidSyntaxError(None, f"it has more than {MAX_EDGES} tasks")
219 def _exclusions(self, text: str, line: int) -> None:
220 first, _, rest = text.partition(" ")
221 for word in re.split(r"[,\s]+", rest.strip()):
222 if not word:
223 continue
224 lowered = word.lower()
225 if first == "excludes" and lowered == "weekends":
226 self.exclusions.weekends = True
227 elif first == "excludes" and lowered in _WEEKDAYS:
228 self.exclusions.weekdays.add(_WEEKDAYS[lowered])
229 else:
230 day = self.date_format.parse(word)
231 if day is None:
232 raise MermaidSyntaxError(
233 line, f"'{word[:40]}' is not a date in the dateFormat"
234 )
235 target = (
236 self.exclusions.dates
237 if first == "excludes"
238 else self.exclusions.included
239 )
240 target.add(day.date().isoformat())
242 # ── times ─────────────────────────────────────────────────────────────
244 def _date(self, text: str, line: int) -> datetime:
245 day = self.date_format.parse(text)
246 if day is None:
247 raise MermaidSyntaxError(
248 line,
249 f"'{text[:40]}' is not a date in the dateFormat ({self.date_format.text})",
250 )
251 return day
253 def _resolve(self) -> None:
254 by_id = {task.id: task for task in self.tasks}
255 starts: dict[int, datetime] = {}
256 ends: dict[int, datetime] = {}
257 visiting: set[int] = set()
259 def named(text: str, keyword: str, task: Task) -> list[Task]:
260 ids = text[len(keyword) :].split()
261 if not ids:
262 raise MermaidSyntaxError(task.line, f"'{keyword}' names no task")
263 out = []
264 for tid in ids:
265 if tid not in by_id:
266 raise MermaidSyntaxError(
267 task.line,
268 f"'{keyword}' names '{tid[:40]}', which no task has as its id",
269 )
270 out.append(by_id[tid])
271 return out
273 def start_of(task: Task) -> datetime:
274 if task.index in starts:
275 return starts[task.index]
276 if task.index in visiting:
277 raise MermaidSyntaxError(
278 task.line, "tasks wait on each other in a circle"
279 )
280 visiting.add(task.index)
281 if task.start is None:
282 value = end_of(self.tasks[task.index - 1])
283 elif task.start.startswith("after ") or task.start == "after":
284 value = max(end_of(t) for t in named(task.start, "after", task))
285 else:
286 value = self._date(task.start, task.line)
287 visiting.discard(task.index)
288 starts[task.index] = value
289 return value
291 def end_of(task: Task) -> datetime:
292 if task.index in ends:
293 return ends[task.index]
294 start = start_of(task)
295 if task.index in visiting:
296 raise MermaidSyntaxError(
297 task.line, "tasks wait on each other in a circle"
298 )
299 visiting.add(task.index)
300 manual = False
301 if task.end.startswith("until ") or task.end == "until":
302 value = min(start_of(t) for t in named(task.end, "until", task))
303 else:
304 value = duration_end(start, task.end)
305 if value is None:
306 value = self._date(task.end, task.line)
307 manual = True
308 if self.inclusive:
309 value += DAY
310 if not manual and self.exclusions.any():
311 value = self._skip_excluded(start, value)
312 visiting.discard(task.index)
313 ends[task.index] = value
314 return value
316 for task in self.tasks:
317 start, end = start_of(task), end_of(task)
318 if end < start:
319 end = start
320 self.placed.append(Placed(task, start, end))
322 def _skip_excluded(self, start: datetime, end: datetime) -> datetime:
323 """Mermaid's ``fixTaskDates``: each excluded day before the end
324 pushes the end a day later."""
325 invalid = False
326 shown = end
327 day = start
328 steps = 0
329 while day <= end and steps < 3660:
330 if not invalid:
331 shown = end
332 invalid = self.exclusions.excluded(day)
333 if invalid:
334 end += DAY
335 day += DAY
336 steps += 1
337 return shown
339 # ── drawing ───────────────────────────────────────────────────────────
341 def layout(self, theme: Theme) -> Layout:
342 font, bold, size = theme.regular, theme.bold, look.FONT_SIZE
343 small = look.SMALL_SIZE
344 titles = [
345 fit(s, bold, size, LABEL_COLUMN - 12, 3) if s else [] for s in self.sections
346 ]
347 label_w = max((block_size(t, bold, size)[0] for t in titles if t), default=0.0)
348 column = min(label_w + 16.0, LABEL_COLUMN) if label_w else 10.0
349 left, right = column + 6.0, WIDTH - 14.0
350 lo = min(p.start for p in self.placed)
351 hi = max(p.end for p in self.placed)
352 if hi <= lo:
353 hi = lo + DAY
354 span = (hi - lo).total_seconds()
356 def x(at: datetime) -> float:
357 return left + (at - lo).total_seconds() / span * (right - left)
359 rows_top = MARGIN + AXIS + 4.0
360 rows_bottom = rows_top + ROW * len(self.placed)
361 height = rows_bottom + 4.0 + AXIS + MARGIN
362 canvas = Canvas(WIDTH, height)
363 header = Canvas(WIDTH, AXIS + 6.0)
365 # Section bands, with their titles in the left column.
366 runs: list[tuple[int | None, int, int]] = []
367 for i, placed in enumerate(self.placed):
368 if runs and runs[-1][0] == placed.task.section:
369 runs[-1] = (runs[-1][0], runs[-1][1], i + 1)
370 else:
371 runs.append((placed.task.section, i, i + 1))
372 for section, first, last in runs:
373 if section is None:
374 continue
375 color, alpha = SECTION_BANDS[section % len(SECTION_BANDS)]
376 top, bottom = rows_top + first * ROW, rows_top + last * ROW
377 if color is not None:
378 canvas.rect(
379 0,
380 top,
381 WIDTH,
382 bottom - top,
383 fill=color,
384 stroke=None,
385 width=0,
386 fill_opacity=alpha,
387 )
388 lines = titles[section]
389 if lines:
390 canvas.lines(
391 column / 2 + 2,
392 (top + bottom) / 2,
393 lines,
394 font=bold,
395 size=size,
396 color=look.TEXT,
397 )
399 # Excluded days, the grid and the dates.
400 if self.exclusions.any() and span <= 400 * 86400:
401 day = lo.replace(hour=0, minute=0, second=0, microsecond=0)
402 while day < hi:
403 if self.exclusions.excluded(day):
404 x0, x1 = max(x(day), left), min(x(day + DAY), right)
405 if x1 > x0:
406 canvas.rect(
407 x0,
408 rows_top,
409 x1 - x0,
410 rows_bottom - rows_top,
411 fill=EXCLUDED,
412 stroke=None,
413 width=0,
414 )
415 day += DAY
416 ticks = self._ticks(lo, hi)
417 pattern = self.axis_format or "%Y-%m-%d"
418 shown_right = float("-inf")
419 for tick in ticks:
420 tx = x(tick)
421 canvas.line(tx, rows_top - 2, tx, rows_bottom + 2, color=GRID, width=0.5)
422 label = strftime(tick, pattern)
423 w = measure(label, font, small)
424 if tx - w / 2 < shown_right + 6:
425 continue
426 shown_right = tx + w / 2
427 for target, y in (
428 (canvas, MARGIN + AXIS - 5),
429 (canvas, rows_bottom + 4 + AXIS - 6),
430 (header, AXIS - 3),
431 ):
432 target.text(tx, y, label, font=font, size=small, color=look.TEXT)
433 for target, y in (
434 (canvas, rows_top - 2),
435 (canvas, rows_bottom + 2),
436 (header, AXIS + 2),
437 ):
438 target.line(left, y, right, y, color=look.LINE, width=0.6)
440 # Tasks.
441 for i, placed in enumerate(self.placed):
442 self._task_bar(canvas, placed, x, rows_top + i * ROW, left, right, theme)
444 breaks = tuple(rows_top + ROW * k for k in range(1, len(self.placed)))
445 return Layout(
446 canvas.drawing(), WIDTH, height, breaks=breaks, header=header.drawing()
447 )
449 def _ticks(self, lo: datetime, hi: datetime) -> list[datetime]:
450 steps = [self.tick] if self.tick else list(_STEPS)
451 units = {"millisecond": "ms", "second": "s", "minute": "m"}
452 for count, unit in steps:
453 ticks = list(self._tick_dates(lo, hi, count, units.get(unit, unit)))
454 if len(ticks) <= (60 if self.tick else MAX_TICKS):
455 return ticks
456 return list(self._tick_dates(lo, hi, *_STEPS[-1]))
458 def _tick_dates(self, lo: datetime, hi: datetime, count: int, unit: str):
459 if unit in ("ms", "s", "m", "hour"):
460 step = {"ms": timedelta(milliseconds=count), "s": timedelta(seconds=count),
461 "m": timedelta(minutes=count), "hour": timedelta(hours=count)}[unit] # fmt: skip
462 at = (
463 lo.replace(minute=0, second=0, microsecond=0)
464 if unit == "hour"
465 else lo.replace(microsecond=0)
466 )
467 elif unit == "day":
468 step = timedelta(days=count)
469 at = lo.replace(hour=0, minute=0, second=0, microsecond=0)
470 elif unit == "week":
471 step = timedelta(weeks=count)
472 at = lo.replace(hour=0, minute=0, second=0, microsecond=0)
473 at -= timedelta(days=(at.weekday() - self.week_starts) % 7)
474 else:
475 at = lo.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
476 at = add_months(at, -((at.month - 1) % count))
477 while at < lo:
478 at = add_months(at, count)
479 while at <= hi:
480 yield at
481 at = add_months(at, count)
482 return
483 while at < lo:
484 at += step
485 made = 0
486 while at <= hi and made < 400:
487 yield at
488 at += step
489 made += 1
491 def _task_bar(
492 self,
493 canvas,
494 placed: Placed,
495 x,
496 top: float,
497 left: float,
498 right: float,
499 theme: Theme,
500 ) -> None:
501 font, size = theme.regular, look.FONT_SIZE
502 tags = placed.task.tags
503 fill, stroke = TASK_FILL, TASK_STROKE
504 text_color = look.WHITE
505 if "active" in tags:
506 fill, text_color = ACTIVE_FILL, look.TEXT
507 if "done" in tags:
508 fill, stroke, text_color = DONE_FILL, DONE_STROKE, look.TEXT
509 if "crit" in tags:
510 stroke = CRIT_STROKE
511 if not ({"active", "done"} & tags):
512 fill, text_color = CRIT_FILL, look.WHITE
513 name = " ".join(clean(placed.task.name))
514 y = top + (ROW - BAR) / 2
515 x0, x1 = x(placed.start), x(placed.end)
516 if "milestone" in tags:
517 cx, cy, r = (x0 + x1) / 2, y + BAR / 2, BAR / 2
518 canvas.polygon(
519 [(cx, cy - r), (cx + r, cy), (cx, cy + r), (cx - r, cy)],
520 fill=fill,
521 stroke=stroke,
522 width=0.8,
523 )
524 width = measure(name, font, size)
525 after, before = right + 10 - (cx + r + 4), (cx - r - 4) - (left - 4)
526 if width <= after or after >= before:
527 shown = ellipsize(name, font, size, max(after, 20.0))
528 canvas.text(
529 cx + r + 4,
530 cy + size * 0.35,
531 shown,
532 font=font,
533 size=size,
534 color=look.TEXT,
535 anchor="start",
536 )
537 else:
538 shown = ellipsize(name, font, size, max(before, 20.0))
539 canvas.text(
540 cx - r - 4,
541 cy + size * 0.35,
542 shown,
543 font=font,
544 size=size,
545 color=look.TEXT,
546 anchor="end",
547 )
548 return
549 x1 = max(x1, x0 + 2.0)
550 canvas.rect(
551 x0, y, x1 - x0, BAR, radius=2.0, fill=fill, stroke=stroke, width=0.8
552 )
553 width = measure(name, font, size)
554 baseline = y + BAR / 2 + size * 0.35
555 if width + 8 <= x1 - x0:
556 canvas.text(
557 (x0 + x1) / 2, baseline, name, font=font, size=size, color=text_color
558 )
559 elif x1 + 4 + width <= right + 10:
560 canvas.text(
561 x1 + 4,
562 baseline,
563 name,
564 font=font,
565 size=size,
566 color=look.TEXT,
567 anchor="start",
568 )
569 elif x0 - 4 - width >= left - 4:
570 canvas.text(
571 x0 - 4,
572 baseline,
573 name,
574 font=font,
575 size=size,
576 color=look.TEXT,
577 anchor="end",
578 )
579 else:
580 room = max(right - x1 - 4, x0 - left - 4)
581 shown = ellipsize(name, font, size, max(room, 30.0))
582 if right - x1 >= x0 - left:
583 canvas.text(
584 x1 + 4,
585 baseline,
586 shown,
587 font=font,
588 size=size,
589 color=look.TEXT,
590 anchor="start",
591 )
592 else:
593 canvas.text(
594 x0 - 4,
595 baseline,
596 shown,
597 font=font,
598 size=size,
599 color=look.TEXT,
600 anchor="end",
601 )