anvilsign in

collin/anvil

1//! todo-md parsing and kanban rendering.
2//!
3//! Implements the todo-md spec (the `todo-md` repo). A `TODO.md` is split into
4//! sections by the shallowest heading level used (the *column level*):
5//!
6//! - **Sections** — headings at the column level (e.g. every `#`). They become
7//! kanban columns. A heading containing `[x]` marks a done section; every
8//! task in it counts as done.
9//! - **Tasks** come in two forms inside a section:
10//! - **checkbox tasks** — `- [ ]` / `- [x]` list items; lines indented under
11//! them are their details (opaque markdown).
12//! - **tickets** — a heading nested *deeper* than the column level (e.g. a
13//! `## Implement Navbar` under `# Done`). The heading is the ticket title
14//! and everything beneath it, until the next heading, is its detail body.
15//! A ticket is done if its section is done or its own heading carries
16//! `[x]`.
17//! - Prose-only sections render as ordinary markdown below the board.
18//!
19//! This module is the first "custom renderer" for a well-known filename; the
20//! filename → renderer match in `ui::blob` is the registry that routes here.
21
22use maud::{
23 Markup,
24 html,
25};
26
27use crate::ui::render_markdown;
28
29pub struct Section {
30 /// Heading level (1–6); 0 for the implicit preamble section.
31 pub level: u8,
32 /// Heading text with any `[x]` / `✓` done-marker stripped.
33 pub title: String,
34 /// Done section: tasks in it count as done regardless of their checkbox.
35 pub done: bool,
36 pub tasks: Vec<Task>,
37 /// Non-task content of the section, verbatim (used for the notes area).
38 pub prose: String,
39}
40
41pub struct Task {
42 pub done: bool,
43 pub title: String,
44 /// Raw markdown block: a checkbox task's indented lines (dedented one
45 /// level) or a ticket's body beneath its heading.
46 pub details: String,
47 /// True when the task came from a nested heading (a ticket) rather than a
48 /// `- [ ]` checkbox line.
49 pub ticket: bool,
50}
51
52/// Where subsequent non-structural lines accumulate.
53#[derive(Clone, Copy, Eq, PartialEq)]
54enum Mode {
55 /// Section prose (no open task).
56 Prose,
57 /// Indented detail lines of a checkbox task (dedented one level).
58 TaskDetail,
59 /// Body of a ticket — runs until the next heading; verbatim.
60 TicketBody,
61}
62
63/// Whether a path names a `TODO.md` (any directory, any case).
64pub fn is_todo_md(path: &str) -> bool {
65 std::path::Path::new(path)
66 .file_name()
67 .is_some_and(|n| n.eq_ignore_ascii_case("TODO.md"))
68}
69
70/// The shallowest heading level in the document (the column level), or 0 if
71/// there are no headings. Fenced regions are skipped.
72fn column_level(text: &str) -> u8 {
73 let mut in_fence = false;
74 let mut min = 0u8;
75 for line in text.lines() {
76 if line.trim_start().starts_with("```") {
77 in_fence = !in_fence;
78 continue;
79 }
80 if in_fence {
81 continue;
82 }
83 if let Some((level, _)) = heading(line)
84 && (min == 0 || level < min)
85 {
86 min = level;
87 }
88 }
89 min
90}
91
92/// Parse a todo-md document into sections. The preamble (content before the
93/// first heading) becomes a level-0 section with an empty title.
94pub fn parse(text: &str) -> Vec<Section> {
95 let col = column_level(text);
96 let mut sections = vec![Section {
97 level: 0,
98 title: String::new(),
99 done: false,
100 tasks: Vec::new(),
101 prose: String::new(),
102 }];
103 let mut in_fence = false;
104 let mut mode = Mode::Prose;
105
106 for line in text.lines() {
107 let fence_toggle = line.trim_start().starts_with("```");
108 let structural = !in_fence && !fence_toggle;
109 if fence_toggle {
110 in_fence = !in_fence;
111 }
112
113 if structural {
114 if let Some((level, rest)) = heading(line) {
115 let cur = sections.last_mut().expect("never empty");
116 if col != 0 && level > col {
117 // A heading deeper than the column level is a ticket in
118 // the current section.
119 cur.tasks.push(Task {
120 done: cur.done || marked_done(rest),
121 title: strip_marker(rest),
122 details: String::new(),
123 ticket: true,
124 });
125 mode = Mode::TicketBody;
126 } else {
127 sections.push(Section {
128 level,
129 title: strip_marker(rest),
130 done: marked_done(rest),
131 tasks: Vec::new(),
132 prose: String::new(),
133 });
134 mode = Mode::Prose;
135 }
136 continue;
137 }
138
139 // Inside a ticket body only a heading (handled above) ends it;
140 // everything else — prose, checkbox lines, blanks — is body.
141 if mode != Mode::TicketBody {
142 if let Some((done, title)) = task_line(line) {
143 sections.last_mut().expect("never empty").tasks.push(Task {
144 done,
145 title: title.to_string(),
146 details: String::new(),
147 ticket: false,
148 });
149 mode = Mode::TaskDetail;
150 continue;
151 }
152 // A non-indented, non-blank line ends a checkbox task's
153 // details and reverts to section prose.
154 if mode == Mode::TaskDetail && !line.is_empty() && !line.starts_with(" ") {
155 mode = Mode::Prose;
156 }
157 }
158 }
159
160 append_line(sections.last_mut().expect("never empty"), mode, line);
161 }
162
163 for s in &mut sections {
164 if s.done {
165 for t in &mut s.tasks {
166 t.done = true;
167 }
168 }
169 for t in &mut s.tasks {
170 // Drop trailing blank lines swallowed while the task was open.
171 while t.details.ends_with('\n') {
172 t.details.pop();
173 }
174 }
175 }
176 sections
177}
178
179fn append_line(section: &mut Section, mode: Mode, line: &str) {
180 match mode {
181 Mode::Prose => {
182 section.prose.push_str(line);
183 section.prose.push('\n');
184 }
185 Mode::TaskDetail => {
186 let t = section.tasks.last_mut().expect("open task exists");
187 // Dedent one level (2–4 spaces) so details render as their own
188 // markdown rather than a code block.
189 let spaces = line.len() - line.trim_start_matches(' ').len();
190 t.details.push_str(&line[spaces.min(4).min(line.len())..]);
191 t.details.push('\n');
192 }
193 Mode::TicketBody => {
194 let t = section.tasks.last_mut().expect("open ticket exists");
195 t.details.push_str(line);
196 t.details.push('\n');
197 }
198 }
199}
200
201fn heading(line: &str) -> Option<(u8, &str)> {
202 let hashes = line.bytes().take_while(|&b| b == b'#').count();
203 if (1..=6).contains(&hashes) && line[hashes..].starts_with(' ') {
204 Some((hashes as u8, line[hashes..].trim()))
205 } else {
206 None
207 }
208}
209
210/// Whether a heading's text carries a done marker (`[x]`, ASCII; `✓` accepted
211/// for todomd compatibility).
212fn marked_done(heading_rest: &str) -> bool {
213 heading_rest.contains("[x]") || heading_rest.contains("[X]") || heading_rest.contains('✓')
214}
215
216fn strip_marker(heading_rest: &str) -> String {
217 heading_rest
218 .replace("[x]", "")
219 .replace("[X]", "")
220 .replace('✓', "")
221 .trim()
222 .to_string()
223}
224
225fn task_line(line: &str) -> Option<(bool, &str)> {
226 let open = line.strip_prefix("- [ ] ");
227 let done = line.strip_prefix("- [x] ").or(line.strip_prefix("- [X] "));
228 match (open, done) {
229 (Some(rest), _) => Some((false, rest.trim())),
230 (_, Some(rest)) => Some((true, rest.trim())),
231 _ => None,
232 }
233}
234
235/// The **add** operation: append a ticket — a nested heading (`## <title>`,
236/// one level below the column headings) followed by an optional `body` (the
237/// ticket's description) — to the end of the section named `section`, touching
238/// no other byte of the document (the todo-md round-trip rule). A ticket is the
239/// richer card style: it inherits done-ness from its column, so it carries no
240/// checkbox. `body` should already be LF-normalized; its surrounding blank
241/// lines are trimmed. Returns `None` when the title is blank, the document has
242/// no column headings to nest under, or no such section exists.
243pub fn add_task(text: &str, section: &str, title: &str, body: &str) -> Option<String> {
244 let title = title.split_whitespace().collect::<Vec<_>>().join(" ");
245 if title.is_empty() {
246 return None;
247 }
248
249 // `split('\n')` (not `lines()`) so reconstruction is byte-exact.
250 let lines: Vec<&str> = text.split('\n').collect();
251 let col = column_level(text);
252 // A ticket nests one level below the columns; with no headings at all
253 // there's no column to nest it under.
254 if col == 0 {
255 return None;
256 }
257
258 // The target span: [start, end) of the section's body lines.
259 let mut start = None;
260 let mut end = lines.len();
261 let mut in_fence = false;
262 for (i, raw) in lines.iter().enumerate() {
263 let line = raw.trim_end_matches('\r');
264 if line.trim_start().starts_with("```") {
265 in_fence = !in_fence;
266 continue;
267 }
268 if in_fence {
269 continue;
270 }
271 if let Some((level, rest)) = heading(line)
272 && level == col
273 {
274 match start {
275 None if strip_marker(rest) == section => start = Some(i + 1),
276 Some(_) => {
277 end = i;
278 break;
279 }
280 None => {}
281 }
282 }
283 }
284 let start = start?;
285
286 // The ticket block: a blank line (separating it from prior content or the
287 // section heading), the heading, then — if there's a description — a blank
288 // line and the body.
289 let heading = format!("{} {title}", "#".repeat(col as usize + 1));
290 let mut block = vec![String::new(), heading];
291 let body = body.trim();
292 if !body.is_empty() {
293 block.push(String::new());
294 block.extend(body.split('\n').map(str::to_string));
295 }
296
297 // Insert after the section's last non-blank line, or right after the
298 // heading for an empty section.
299 let pos = match (start..end).rev().find(|&i| !lines[i].trim().is_empty()) {
300 Some(i) => i + 1,
301 None => start,
302 };
303 let mut out: Vec<String> = lines.iter().map(|l| l.to_string()).collect();
304 out.splice(pos..pos, block);
305 Some(out.join("\n"))
306}
307
308/// The section names a task can be added to: the column-level headings, in
309/// document order, stripped of any done marker. These are exactly the names
310/// [`add_task`] accepts. Empty when the document has no headings.
311pub fn task_sections(text: &str) -> Vec<String> {
312 let col = column_level(text);
313 if col == 0 {
314 return Vec::new();
315 }
316 let mut in_fence = false;
317 let mut out = Vec::new();
318 for line in text.lines() {
319 if line.trim_start().starts_with("```") {
320 in_fence = !in_fence;
321 continue;
322 }
323 if in_fence {
324 continue;
325 }
326 if let Some((level, rest)) = heading(line)
327 && level == col
328 {
329 out.push(strip_marker(rest));
330 }
331 }
332 out
333}
334
335/// Render a todo-md document as a kanban board (columns = task-bearing
336/// sections) with prose sections as a notes area below. `None` if the file
337/// contains no tasks at all — callers fall back to plain markdown.
338pub fn render_board(text: &str) -> Option<Markup> {
339 let sections = parse(text);
340 if sections.iter().all(|s| s.tasks.is_empty()) {
341 return None;
342 }
343
344 // Prose-only sections (and stray preamble/column prose) become one
345 // markdown notes blob, headings preserved.
346 let mut notes = String::new();
347 for s in &sections {
348 let prose_empty = s.prose.trim().is_empty();
349 if s.tasks.is_empty() && s.level > 0 && prose_empty {
350 continue; // empty section: nothing to show either way
351 }
352 if s.tasks.is_empty() {
353 if s.level > 0 {
354 notes.push_str(&format!("{} {}\n", "#".repeat(s.level as usize), s.title));
355 }
356 if !prose_empty {
357 notes.push_str(&s.prose);
358 notes.push('\n');
359 }
360 }
361 }
362
363 Some(html! {
364 div.kanban {
365 @for s in sections.iter().filter(|s| !s.tasks.is_empty()) {
366 div.col {
367 h3 {
368 @if s.title.is_empty() { "Tasks" } @else { (s.title) }
369 span.count {
370 @if s.done {
371 ({ s.tasks.len().to_string() }) " done"
372 } @else {
373 ({ s.tasks.iter().filter(|t| !t.done).count().to_string() })
374 " open"
375 }
376 }
377 }
378 @for t in &s.tasks {
379 div.card.done[t.done] {
380 div.title { (render_markdown(&t.title)) }
381 @if !t.details.trim().is_empty() {
382 details {
383 summary { "details" }
384 div.card-details { (render_markdown(&t.details)) }
385 }
386 }
387 }
388 }
389 }
390 }
391 }
392 @if !notes.trim().is_empty() {
393 details.todo-notes {
394 summary { "notes" }
395 div.md-body { (render_markdown(&notes)) }
396 }
397 }
398 })
399}
400
401#[cfg(test)]
402mod tests {
403 use super::*;
404
405 const DOC: &str = "\
406intro prose
407
408# Now
409
410- [ ] first task
411 - a detail line
412 - another `detail`
413- [x] finished task
414
415# Done [x]
416
417- [ ] moved here, checkbox stale
418
419## Implement Navbar
420
421Sticky top bar with the repo switcher.
422
423- shipped behind a flag
424- needs a follow-up for mobile
425
426# Notes
427
428just prose, no tasks
429
430```
431# not a heading
432- [ ] not a task
433```
434";
435
436 #[test]
437 fn parses_sections_tasks_details() {
438 let s = parse(DOC);
439 assert_eq!(s.len(), 4); // preamble + 3 column headings (## is a ticket)
440 assert_eq!(s[0].level, 0);
441 assert_eq!(s[0].prose.trim(), "intro prose");
442
443 assert_eq!(s[1].title, "Now");
444 assert!(!s[1].done);
445 assert_eq!(s[1].tasks.len(), 2);
446 assert_eq!(s[1].tasks[0].title, "first task");
447 assert!(!s[1].tasks[0].done);
448 assert!(!s[1].tasks[0].ticket);
449 assert_eq!(s[1].tasks[0].details, "- a detail line\n- another `detail`");
450 assert!(s[1].tasks[1].done);
451
452 // Done section: heading marker wins over the task's own checkbox.
453 assert_eq!(s[2].title, "Done");
454 assert!(s[2].done);
455 assert_eq!(s[2].tasks.len(), 2); // checkbox task + the ticket
456 assert!(s[2].tasks[0].done);
457 assert!(!s[2].tasks[0].ticket);
458 }
459
460 #[test]
461 fn nested_heading_is_a_ticket() {
462 let s = parse(DOC);
463 let ticket = &s[2].tasks[1];
464 assert!(ticket.ticket);
465 assert_eq!(ticket.title, "Implement Navbar");
466 // Done inherited from the `# Done [x]` section.
467 assert!(ticket.done);
468 assert!(ticket.details.contains("Sticky top bar"));
469 assert!(ticket.details.contains("- needs a follow-up for mobile"));
470 // The body must not leak into a sibling section.
471 assert!(!ticket.details.contains("just prose"));
472 }
473
474 #[test]
475 fn ticket_own_done_marker() {
476 let s = parse("# Backlog\n\n## Fix login [x]\n\nbody\n\n## Add search\n\nbody\n");
477 assert!(!s[1].done); // section is open
478 assert_eq!(s[1].tasks.len(), 2);
479 assert!(s[1].tasks[0].done); // ticket marked done on its own heading
480 assert_eq!(s[1].tasks[0].title, "Fix login");
481 assert!(!s[1].tasks[1].done);
482 }
483
484 #[test]
485 fn todo_md_by_filename() {
486 assert!(is_todo_md("TODO.md"));
487 assert!(is_todo_md("docs/todo.MD"));
488 assert!(!is_todo_md("TODO.txt"));
489 assert!(!is_todo_md("NOT-TODO.md"));
490 }
491
492 #[test]
493 fn board_renders_columns_tickets_and_falls_back() {
494 let board = render_board(DOC).expect("has tasks").into_string();
495 assert!(board.contains("kanban"));
496 assert!(board.contains("Now"));
497 assert!(board.contains("first task"));
498 // Tickets render as ordinary cards — no checkbox input, no special
499 // card class. (The DOC text mentions "checkbox", so check elements.)
500 assert!(board.contains("Implement Navbar"));
501 assert!(!board.contains("<input"), "no checkbox clutter: {board}");
502 assert!(!board.contains("ticket\""), "no ticket card class: {board}");
503 assert!(board.contains("just prose"), "notes area kept: {board}");
504 assert!(render_board("# readme\n\nonly prose\n").is_none());
505 }
506
507 #[test]
508 fn add_task_appends_ticket_within_section_byte_exactly() {
509 let out = add_task(DOC, "Now", "new ticket", "").unwrap();
510 // Lands as a nested heading after the section's last non-blank line,
511 // padded by a blank line, before the next column heading.
512 assert!(out.contains("- [x] finished task\n\n## new ticket\n\n# Done"));
513 // Round-trip rule: removing the inserted ticket restores the original.
514 assert_eq!(out.replacen("## new ticket\n\n", "", 1), DOC);
515 }
516
517 #[test]
518 fn add_task_with_body_writes_heading_then_description() {
519 let out = add_task("# Now\n# Done\n", "Now", "Title", "Line one\nLine two").unwrap();
520 assert_eq!(out, "# Now\n\n## Title\n\nLine one\nLine two\n# Done\n");
521 // The body becomes the ticket's parsed details.
522 let now = parse(&out).into_iter().find(|s| s.title == "Now").unwrap();
523 let ticket = now.tasks.iter().find(|t| t.title == "Title").unwrap();
524 assert!(ticket.ticket);
525 assert_eq!(ticket.details.trim(), "Line one\nLine two");
526 }
527
528 #[test]
529 fn add_task_ticket_level_tracks_the_column_level() {
530 // Columns at `##` ⇒ tickets nest at `###`.
531 let doc = "## Backlog\n\n### Existing\n\nbody\n";
532 let out = add_task(doc, "Backlog", "New one", "").unwrap();
533 assert!(out.contains("body\n\n### New one"));
534 }
535
536 #[test]
537 fn add_task_to_done_section_inherits_done_no_checkbox() {
538 let out = add_task(DOC, "Done", "tidy up", "").unwrap();
539 assert!(out.contains("## tidy up"));
540 assert!(!out.contains("- [ ] tidy up") && !out.contains("- [x] tidy up"));
541 // Parses as a ticket under the done column, so it reads as done.
542 let done = parse(&out).into_iter().find(|s| s.title == "Done").unwrap();
543 assert!(
544 done.tasks
545 .iter()
546 .any(|t| t.ticket && t.title == "tidy up" && t.done)
547 );
548 }
549
550 #[test]
551 fn add_task_into_empty_section_inserts_blank_then_ticket() {
552 let doc = "# Now\n# Done\n";
553 assert_eq!(
554 add_task(doc, "Now", "first", "").unwrap(),
555 "# Now\n\n## first\n# Done\n"
556 );
557 }
558
559 #[test]
560 fn add_task_rejects_missing_section_blank_title_and_headingless() {
561 assert!(add_task(DOC, "Nonexistent", "x", "").is_none());
562 assert!(add_task(DOC, "Now", " ", "body still rejected").is_none());
563 assert!(add_task("no headings here\n", "Whatever", "x", "").is_none());
564 }
565
566 #[test]
567 fn added_ticket_renders_as_a_board_card() {
568 let out = add_task(DOC, "Now", "Wire uploads", "").unwrap();
569 let board = render_board(&out).expect("has tasks").into_string();
570 assert!(board.contains("Wire uploads"));
571 }
572
573 #[test]
574 fn task_sections_lists_column_headings_stripped() {
575 assert_eq!(task_sections(DOC), ["Now", "Done", "Notes"]);
576 assert!(task_sections("# readme\n\nonly prose\n") == ["readme"]);
577 assert!(task_sections("no headings at all\n").is_empty());
578 }
579}