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/// Where a ticket body ends: the next heading (any level) or `end`. Fenced
336/// regions are skipped so a `#` inside a code block doesn't end it.
337fn ticket_body_end(lines: &[&str], end: usize, from: usize) -> usize {
338 let mut j = from;
339 let mut f = false;
340 while j < end {
341 let l = lines[j].trim_end_matches('\r');
342 if l.trim_start().starts_with("```") {
343 f = !f;
344 } else if !f && heading(l).is_some() {
345 break;
346 }
347 j += 1;
348 }
349 j
350}
351
352/// Body line span `[start, end)` of the column-level section named `section`
353/// (the lines after its heading, up to the next column heading or EOF).
354fn find_section_body(lines: &[&str], col: u8, section: &str) -> Option<(usize, usize)> {
355 let mut start = None;
356 let mut end = lines.len();
357 let mut in_fence = false;
358 for (i, raw) in lines.iter().enumerate() {
359 let line = raw.trim_end_matches('\r');
360 if line.trim_start().starts_with("```") {
361 in_fence = !in_fence;
362 continue;
363 }
364 if in_fence {
365 continue;
366 }
367 if let Some((level, rest)) = heading(line)
368 && level == col
369 {
370 match start {
371 None if strip_marker(rest) == section => start = Some(i + 1),
372 Some(_) => {
373 end = i;
374 break;
375 }
376 None => {}
377 }
378 }
379 }
380 start.map(|s| (s, end))
381}
382
383/// The line span `[from, to)` of the task titled `title` within a section body
384/// `[start, end)` — a ticket (heading + body) or a checkbox line (+ indented
385/// details). Trailing blank lines are excluded so the span is the task's own
386/// content. `None` if not found.
387fn find_task_block(
388 lines: &[&str],
389 col: u8,
390 start: usize,
391 end: usize,
392 title: &str,
393) -> Option<(usize, usize)> {
394 let mut from = None;
395 let mut to = end;
396 let mut i = start;
397 let mut fence = false;
398 while i < end {
399 let line = lines[i].trim_end_matches('\r');
400 if line.trim_start().starts_with("```") {
401 fence = !fence;
402 i += 1;
403 continue;
404 }
405 if !fence {
406 if let Some((level, rest)) = heading(line) {
407 if level > col {
408 let body_end = ticket_body_end(lines, end, i + 1);
409 if strip_marker(rest) == title {
410 from = Some(i);
411 to = body_end;
412 break;
413 }
414 i = body_end;
415 continue;
416 }
417 } else if let Some((_, t)) = task_line(line) {
418 let mut j = i + 1;
419 while j < end && lines[j].starts_with(" ") {
420 j += 1;
421 }
422 if t == title {
423 from = Some(i);
424 to = j;
425 break;
426 }
427 i = j;
428 continue;
429 }
430 }
431 i += 1;
432 }
433 let from = from?;
434 while to > from && lines[to - 1].trim().is_empty() {
435 to -= 1;
436 }
437 Some((from, to))
438}
439
440/// The start line of the `n`-th (0-based) task within `[start, end)`, or `None`
441/// if there are fewer than `n + 1` tasks (caller appends at the section end).
442fn nth_task_start(lines: &[&str], col: u8, start: usize, end: usize, n: usize) -> Option<usize> {
443 let mut count = 0;
444 let mut i = start;
445 let mut fence = false;
446 while i < end {
447 let line = lines[i].trim_end_matches('\r');
448 if line.trim_start().starts_with("```") {
449 fence = !fence;
450 i += 1;
451 continue;
452 }
453 if !fence {
454 if let Some((level, _)) = heading(line) {
455 if level > col {
456 if count == n {
457 return Some(i);
458 }
459 count += 1;
460 i = ticket_body_end(lines, end, i + 1);
461 continue;
462 }
463 } else if task_line(line).is_some() {
464 if count == n {
465 return Some(i);
466 }
467 count += 1;
468 let mut j = i + 1;
469 while j < end && lines[j].starts_with(" ") {
470 j += 1;
471 }
472 i = j;
473 continue;
474 }
475 }
476 i += 1;
477 }
478 None
479}
480
481/// The inverse of [`add_task`]: delete the task titled `title` from the section
482/// named `section`, touching no other byte (round-trip rule). Handles both a
483/// ticket (a nested `## title` heading and its body, up to the next heading)
484/// and a `- [ ]` checkbox task (its line plus indented detail lines). Returns
485/// `None` if the section or task isn't found. Removes its own trailing blank
486/// lines and collapses the blank seam left behind so spacing stays tidy.
487pub fn remove_task(text: &str, section: &str, title: &str) -> Option<String> {
488 let lines: Vec<&str> = text.split('\n').collect();
489 let col = column_level(text);
490 if col == 0 {
491 return None;
492 }
493 let (start, end) = find_section_body(&lines, col, section)?;
494 let (from, to) = find_task_block(&lines, col, start, end, title)?;
495
496 let mut out: Vec<String> = lines.iter().map(|l| l.to_string()).collect();
497 out.drain(from..to);
498 if from > 0
499 && from < out.len()
500 && out[from - 1].trim().is_empty()
501 && out[from].trim().is_empty()
502 {
503 out.remove(from);
504 }
505 Some(out.join("\n"))
506}
507
508/// Move the task titled `title` from `from_section` to position `to_index`
509/// (0-based, among that section's tasks) of `to_section` — the same section to
510/// reorder, or a different one to move between columns. The task's own block is
511/// preserved verbatim; only its placement (and the surrounding blank-line
512/// spacing) changes. `None` if the task or either section isn't found.
513pub fn move_task(
514 text: &str,
515 title: &str,
516 from_section: &str,
517 to_section: &str,
518 to_index: usize,
519) -> Option<String> {
520 let lines: Vec<&str> = text.split('\n').collect();
521 let col = column_level(text);
522 if col == 0 {
523 return None;
524 }
525
526 // Cut the task's block out of its source section.
527 let (fs, fe) = find_section_body(&lines, col, from_section)?;
528 let (from, to) = find_task_block(&lines, col, fs, fe, title)?;
529 let block: Vec<String> = lines[from..to].iter().map(|l| l.to_string()).collect();
530
531 let mut out: Vec<String> = lines.iter().map(|l| l.to_string()).collect();
532 out.drain(from..to);
533 if from > 0
534 && from < out.len()
535 && out[from - 1].trim().is_empty()
536 && out[from].trim().is_empty()
537 {
538 out.remove(from);
539 }
540
541 // Re-locate the target section in the post-removal document and splice the
542 // block in, keeping one blank line on each side.
543 let refs: Vec<&str> = out.iter().map(|s| s.as_str()).collect();
544 let (ts, te) = find_section_body(&refs, col, to_section)?;
545 match nth_task_start(&refs, col, ts, te, to_index) {
546 Some(at) => {
547 let mut ins = block;
548 ins.push(String::new()); // blank between the moved block and the task below it
549 out.splice(at..at, ins);
550 }
551 None => {
552 // Append after the section's last non-blank line.
553 let mut at = te;
554 while at > ts && refs[at - 1].trim().is_empty() {
555 at -= 1;
556 }
557 let mut ins = vec![String::new()];
558 ins.extend(block);
559 out.splice(at..at, ins);
560 }
561 }
562 Some(out.join("\n"))
563}
564
565/// What the board needs to render per-task delete controls: the repo
566/// coordinates, the branch tip (compare-and-swap guard), and a CSRF token.
567/// `None` renders a read-only board.
568pub struct BoardActions<'a> {
569 pub owner: &'a str,
570 pub repo: &'a str,
571 pub rev: &'a str,
572 pub path: &'a str,
573 pub tip: &'a str,
574 pub csrf: &'a str,
575}
576
577/// Render a todo-md document as a kanban board (columns = task-bearing
578/// sections) with prose sections as a notes area below. `None` if the file
579/// contains no tasks at all — callers fall back to plain markdown.
580pub fn render_board(text: &str, actions: Option<&BoardActions>) -> Option<Markup> {
581 let sections = parse(text);
582 if sections.iter().all(|s| s.tasks.is_empty()) {
583 return None;
584 }
585
586 // Prose-only sections (and stray preamble/column prose) become one
587 // markdown notes blob, headings preserved.
588 let mut notes = String::new();
589 for s in &sections {
590 let prose_empty = s.prose.trim().is_empty();
591 if s.tasks.is_empty() && s.level > 0 && prose_empty {
592 continue; // empty section: nothing to show either way
593 }
594 if s.tasks.is_empty() {
595 if s.level > 0 {
596 notes.push_str(&format!("{} {}\n", "#".repeat(s.level as usize), s.title));
597 }
598 if !prose_empty {
599 notes.push_str(&s.prose);
600 notes.push('\n');
601 }
602 }
603 }
604
605 let move_url = actions.map(|a| {
606 format!(
607 "/{}/{}/move-task/{}/{}",
608 a.owner,
609 a.repo,
610 crate::ui::enc_ref(a.rev),
611 a.path
612 )
613 });
614 Some(html! {
615 div.kanban data-move-url=[move_url.as_deref()]
616 data-tip=[actions.map(|a| a.tip)] data-csrf=[actions.map(|a| a.csrf)] {
617 @for s in sections.iter().filter(|s| !s.tasks.is_empty()) {
618 div.col data-section=[actions.map(|_| s.title.as_str())] {
619 h3 {
620 @if s.title.is_empty() { "Tasks" } @else { (s.title) }
621 span.count {
622 @if s.done {
623 ({ s.tasks.len().to_string() }) " done"
624 } @else {
625 ({ s.tasks.iter().filter(|t| !t.done).count().to_string() })
626 " open"
627 }
628 }
629 }
630 @for t in &s.tasks {
631 div.card.done[t.done]
632 draggable=[actions.map(|_| "true")]
633 data-title=[actions.map(|_| t.title.as_str())] {
634 @if let Some(a) = actions {
635 form.card-del method="post"
636 action=(format!("/{}/{}/delete-task/{}/{}", a.owner, a.repo, crate::ui::enc_ref(a.rev), a.path)) {
637 (crate::ui::csrf_input(a.csrf))
638 input type="hidden" name="expected_tip" value=(a.tip);
639 input type="hidden" name="section" value=(s.title);
640 input type="hidden" name="title" value=(t.title);
641 button.card-del-btn type="submit" title="Delete task" aria-label="Delete task" { "×" }
642 }
643 }
644 div.title { (render_markdown(&t.title)) }
645 @if !t.details.trim().is_empty() {
646 details {
647 summary { "details" }
648 div.card-details { (render_markdown(&t.details)) }
649 }
650 }
651 }
652 }
653 }
654 }
655 }
656 @if !notes.trim().is_empty() {
657 details.todo-notes {
658 summary { "notes" }
659 div.md-body { (render_markdown(&notes)) }
660 }
661 }
662 @if actions.is_some() { script { (maud::PreEscaped(BOARD_DND_JS)) } }
663 })
664}
665
666/// Drag-and-drop reordering for the board: drag a card within or across
667/// columns; on drop, POST the new (section, index) to the move endpoint and
668/// reload. Reads the endpoint/tip/csrf from the `.kanban` element's data-attrs.
669const BOARD_DND_JS: &str = r#"
670(function(){
671 var board = document.querySelector('.kanban[data-move-url]');
672 if (!board) return;
673 var url = board.dataset.moveUrl, tip = board.dataset.tip, csrf = board.dataset.csrf;
674 var dragged = null, fromSection = null;
675
676 board.addEventListener('dragstart', function(e){
677 var card = e.target.closest('.card');
678 if (!card) return;
679 dragged = card;
680 fromSection = card.closest('.col').dataset.section;
681 setTimeout(function(){ card.classList.add('dragging'); }, 0);
682 e.dataTransfer.effectAllowed = 'move';
683 });
684 board.addEventListener('dragend', function(){
685 if (dragged) dragged.classList.remove('dragging');
686 dragged = null;
687 });
688 function afterCard(col, y){
689 var cards = [].slice.call(col.querySelectorAll('.card:not(.dragging)'));
690 var best = null, bestOffset = -Infinity;
691 cards.forEach(function(c){
692 var box = c.getBoundingClientRect();
693 var offset = y - box.top - box.height / 2;
694 if (offset < 0 && offset > bestOffset) { bestOffset = offset; best = c; }
695 });
696 return best;
697 }
698 board.addEventListener('dragover', function(e){
699 if (!dragged) return;
700 var col = e.target.closest('.col');
701 if (!col) return;
702 e.preventDefault();
703 var after = afterCard(col, e.clientY);
704 if (after == null) col.appendChild(dragged);
705 else col.insertBefore(dragged, after);
706 });
707 board.addEventListener('drop', function(e){
708 if (!dragged) return;
709 e.preventDefault();
710 var col = dragged.closest('.col');
711 var cards = [].slice.call(col.querySelectorAll('.card'));
712 var body = new URLSearchParams();
713 body.set('csrf', csrf);
714 body.set('expected_tip', tip);
715 body.set('from_section', fromSection);
716 body.set('to_section', col.dataset.section);
717 body.set('title', dragged.dataset.title);
718 body.set('to_index', String(cards.indexOf(dragged)));
719 fetch(url, {
720 method: 'POST',
721 headers: {'X-CSRF-Token': csrf, 'Content-Type': 'application/x-www-form-urlencoded'},
722 body: body.toString()
723 }).then(function(r){
724 if (!r.ok) throw new Error('move failed (' + r.status + ')');
725 location.reload();
726 }).catch(function(err){ console.error(err); location.reload(); });
727 });
728})();
729"#;
730
731#[cfg(test)]
732mod tests {
733 use super::*;
734
735 const DOC: &str = "\
736intro prose
737
738# Now
739
740- [ ] first task
741 - a detail line
742 - another `detail`
743- [x] finished task
744
745# Done [x]
746
747- [ ] moved here, checkbox stale
748
749## Implement Navbar
750
751Sticky top bar with the repo switcher.
752
753- shipped behind a flag
754- needs a follow-up for mobile
755
756# Notes
757
758just prose, no tasks
759
760```
761# not a heading
762- [ ] not a task
763```
764";
765
766 #[test]
767 fn parses_sections_tasks_details() {
768 let s = parse(DOC);
769 assert_eq!(s.len(), 4); // preamble + 3 column headings (## is a ticket)
770 assert_eq!(s[0].level, 0);
771 assert_eq!(s[0].prose.trim(), "intro prose");
772
773 assert_eq!(s[1].title, "Now");
774 assert!(!s[1].done);
775 assert_eq!(s[1].tasks.len(), 2);
776 assert_eq!(s[1].tasks[0].title, "first task");
777 assert!(!s[1].tasks[0].done);
778 assert!(!s[1].tasks[0].ticket);
779 assert_eq!(s[1].tasks[0].details, "- a detail line\n- another `detail`");
780 assert!(s[1].tasks[1].done);
781
782 // Done section: heading marker wins over the task's own checkbox.
783 assert_eq!(s[2].title, "Done");
784 assert!(s[2].done);
785 assert_eq!(s[2].tasks.len(), 2); // checkbox task + the ticket
786 assert!(s[2].tasks[0].done);
787 assert!(!s[2].tasks[0].ticket);
788 }
789
790 #[test]
791 fn nested_heading_is_a_ticket() {
792 let s = parse(DOC);
793 let ticket = &s[2].tasks[1];
794 assert!(ticket.ticket);
795 assert_eq!(ticket.title, "Implement Navbar");
796 // Done inherited from the `# Done [x]` section.
797 assert!(ticket.done);
798 assert!(ticket.details.contains("Sticky top bar"));
799 assert!(ticket.details.contains("- needs a follow-up for mobile"));
800 // The body must not leak into a sibling section.
801 assert!(!ticket.details.contains("just prose"));
802 }
803
804 #[test]
805 fn ticket_own_done_marker() {
806 let s = parse("# Backlog\n\n## Fix login [x]\n\nbody\n\n## Add search\n\nbody\n");
807 assert!(!s[1].done); // section is open
808 assert_eq!(s[1].tasks.len(), 2);
809 assert!(s[1].tasks[0].done); // ticket marked done on its own heading
810 assert_eq!(s[1].tasks[0].title, "Fix login");
811 assert!(!s[1].tasks[1].done);
812 }
813
814 #[test]
815 fn todo_md_by_filename() {
816 assert!(is_todo_md("TODO.md"));
817 assert!(is_todo_md("docs/todo.MD"));
818 assert!(!is_todo_md("TODO.txt"));
819 assert!(!is_todo_md("NOT-TODO.md"));
820 }
821
822 #[test]
823 fn board_renders_columns_tickets_and_falls_back() {
824 let board = render_board(DOC, None).expect("has tasks").into_string();
825 assert!(board.contains("kanban"));
826 assert!(board.contains("Now"));
827 assert!(board.contains("first task"));
828 // Tickets render as ordinary cards — no checkbox input, no special
829 // card class. (The DOC text mentions "checkbox", so check elements.)
830 assert!(board.contains("Implement Navbar"));
831 assert!(!board.contains("<input"), "no checkbox clutter: {board}");
832 assert!(!board.contains("ticket\""), "no ticket card class: {board}");
833 assert!(board.contains("just prose"), "notes area kept: {board}");
834 assert!(render_board("# readme\n\nonly prose\n", None).is_none());
835 }
836
837 #[test]
838 fn add_task_appends_ticket_within_section_byte_exactly() {
839 let out = add_task(DOC, "Now", "new ticket", "").unwrap();
840 // Lands as a nested heading after the section's last non-blank line,
841 // padded by a blank line, before the next column heading.
842 assert!(out.contains("- [x] finished task\n\n## new ticket\n\n# Done"));
843 // Round-trip rule: removing the inserted ticket restores the original.
844 assert_eq!(out.replacen("## new ticket\n\n", "", 1), DOC);
845 }
846
847 #[test]
848 fn add_task_with_body_writes_heading_then_description() {
849 let out = add_task("# Now\n# Done\n", "Now", "Title", "Line one\nLine two").unwrap();
850 assert_eq!(out, "# Now\n\n## Title\n\nLine one\nLine two\n# Done\n");
851 // The body becomes the ticket's parsed details.
852 let now = parse(&out).into_iter().find(|s| s.title == "Now").unwrap();
853 let ticket = now.tasks.iter().find(|t| t.title == "Title").unwrap();
854 assert!(ticket.ticket);
855 assert_eq!(ticket.details.trim(), "Line one\nLine two");
856 }
857
858 #[test]
859 fn add_task_ticket_level_tracks_the_column_level() {
860 // Columns at `##` ⇒ tickets nest at `###`.
861 let doc = "## Backlog\n\n### Existing\n\nbody\n";
862 let out = add_task(doc, "Backlog", "New one", "").unwrap();
863 assert!(out.contains("body\n\n### New one"));
864 }
865
866 #[test]
867 fn add_task_to_done_section_inherits_done_no_checkbox() {
868 let out = add_task(DOC, "Done", "tidy up", "").unwrap();
869 assert!(out.contains("## tidy up"));
870 assert!(!out.contains("- [ ] tidy up") && !out.contains("- [x] tidy up"));
871 // Parses as a ticket under the done column, so it reads as done.
872 let done = parse(&out).into_iter().find(|s| s.title == "Done").unwrap();
873 assert!(
874 done.tasks
875 .iter()
876 .any(|t| t.ticket && t.title == "tidy up" && t.done)
877 );
878 }
879
880 #[test]
881 fn add_task_into_empty_section_inserts_blank_then_ticket() {
882 let doc = "# Now\n# Done\n";
883 assert_eq!(
884 add_task(doc, "Now", "first", "").unwrap(),
885 "# Now\n\n## first\n# Done\n"
886 );
887 }
888
889 #[test]
890 fn add_task_rejects_missing_section_blank_title_and_headingless() {
891 assert!(add_task(DOC, "Nonexistent", "x", "").is_none());
892 assert!(add_task(DOC, "Now", " ", "body still rejected").is_none());
893 assert!(add_task("no headings here\n", "Whatever", "x", "").is_none());
894 }
895
896 #[test]
897 fn added_ticket_renders_as_a_board_card() {
898 let out = add_task(DOC, "Now", "Wire uploads", "").unwrap();
899 let board = render_board(&out, None).expect("has tasks").into_string();
900 assert!(board.contains("Wire uploads"));
901 }
902
903 #[test]
904 fn task_sections_lists_column_headings_stripped() {
905 assert_eq!(task_sections(DOC), ["Now", "Done", "Notes"]);
906 assert!(task_sections("# readme\n\nonly prose\n") == ["readme"]);
907 assert!(task_sections("no headings at all\n").is_empty());
908 }
909
910 #[test]
911 fn add_then_remove_task_round_trips() {
912 // Removing a just-added ticket restores the document byte-for-byte.
913 let added = add_task(DOC, "Now", "throwaway", "with a body line").unwrap();
914 assert_eq!(
915 remove_task(&added, "Now", "throwaway").as_deref(),
916 Some(DOC)
917 );
918 }
919
920 #[test]
921 fn remove_task_deletes_ticket_block() {
922 let doc = "# Now\n\n## first\n\nbody one\n\n## second\n\nbody two\n";
923 assert_eq!(
924 remove_task(doc, "Now", "first").unwrap(),
925 "# Now\n\n## second\n\nbody two\n"
926 );
927 // Removing the last ticket leaves the section heading intact.
928 assert_eq!(
929 remove_task(doc, "Now", "second").unwrap(),
930 "# Now\n\n## first\n\nbody one\n"
931 );
932 }
933
934 #[test]
935 fn remove_task_deletes_checkbox_with_its_details() {
936 let doc = "# Now\n\n- [ ] a\n detail of a\n- [x] b\n\n# Done\n";
937 assert_eq!(
938 remove_task(doc, "Now", "a").unwrap(),
939 "# Now\n\n- [x] b\n\n# Done\n"
940 );
941 }
942
943 #[test]
944 fn remove_task_rejects_missing_section_or_task() {
945 assert!(remove_task(DOC, "Nope", "first task").is_none());
946 assert!(remove_task(DOC, "Now", "not a real task").is_none());
947 }
948
949 /// Ticket titles of a section, in order — order is what reordering changes.
950 fn order(text: &str, section: &str) -> Vec<String> {
951 parse(text)
952 .into_iter()
953 .find(|s| s.title == section)
954 .map(|s| s.tasks.into_iter().map(|t| t.title).collect())
955 .unwrap_or_default()
956 }
957
958 #[test]
959 fn move_task_reorders_within_a_section() {
960 let doc = "# Now\n\n## a\n\n## b\n\n## c\n";
961 assert_eq!(
962 order(&move_task(doc, "c", "Now", "Now", 0).unwrap(), "Now"),
963 ["c", "a", "b"]
964 );
965 // to_index past the end appends.
966 assert_eq!(
967 order(&move_task(doc, "a", "Now", "Now", 9).unwrap(), "Now"),
968 ["b", "c", "a"]
969 );
970 }
971
972 #[test]
973 fn move_task_across_sections_preserves_body() {
974 let doc = "# Now\n\n## a\n\nbody of a\n\n# Done\n\n## b\n";
975 let out = move_task(doc, "a", "Now", "Done", 1).unwrap();
976 assert_eq!(order(&out, "Now"), Vec::<String>::new());
977 assert_eq!(order(&out, "Done"), ["b", "a"]);
978 assert!(
979 out.contains("## a\n\nbody of a"),
980 "body travels with the ticket"
981 );
982 }
983
984 #[test]
985 fn move_task_rejects_unknown_task_or_section() {
986 let doc = "# Now\n\n## a\n\n# Done\n";
987 assert!(move_task(doc, "ghost", "Now", "Done", 0).is_none());
988 assert!(move_task(doc, "a", "Now", "Nope", 0).is_none());
989 }
990}