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/// The inverse of [`add_task`]: delete the task titled `title` from the section
336/// named `section`, touching no other byte (round-trip rule). Handles both a
337/// ticket (a nested `## title` heading and its body, up to the next heading)
338/// and a `- [ ]` checkbox task (its line plus indented detail lines). Returns
339/// `None` if the section or task isn't found. Removes its own trailing blank
340/// lines and collapses the blank seam left behind so spacing stays tidy.
341pub fn remove_task(text: &str, section: &str, title: &str) -> Option<String> {
342 let lines: Vec<&str> = text.split('\n').collect();
343 let col = column_level(text);
344 if col == 0 {
345 return None;
346 }
347
348 // The section body span [start, end), exactly as add_task locates it.
349 let mut start = None;
350 let mut end = lines.len();
351 let mut in_fence = false;
352 for (i, raw) in lines.iter().enumerate() {
353 let line = raw.trim_end_matches('\r');
354 if line.trim_start().starts_with("```") {
355 in_fence = !in_fence;
356 continue;
357 }
358 if in_fence {
359 continue;
360 }
361 if let Some((level, rest)) = heading(line)
362 && level == col
363 {
364 match start {
365 None if strip_marker(rest) == section => start = Some(i + 1),
366 Some(_) => {
367 end = i;
368 break;
369 }
370 None => {}
371 }
372 }
373 }
374 let start = start?;
375
376 // The end of a ticket body: the next heading (any level) or section end.
377 let ticket_body_end = |from: usize| {
378 let mut j = from;
379 let mut f = false;
380 while j < end {
381 let l = lines[j].trim_end_matches('\r');
382 if l.trim_start().starts_with("```") {
383 f = !f;
384 } else if !f && heading(l).is_some() {
385 break;
386 }
387 j += 1;
388 }
389 j
390 };
391
392 // Walk the section body to find the task and its line span [from, to).
393 let mut from = None;
394 let mut to = end;
395 let mut i = start;
396 let mut fence = false;
397 while i < end {
398 let line = lines[i].trim_end_matches('\r');
399 if line.trim_start().starts_with("```") {
400 fence = !fence;
401 i += 1;
402 continue;
403 }
404 if !fence {
405 if let Some((level, rest)) = heading(line) {
406 if level > col {
407 let body_end = ticket_body_end(i + 1);
408 if strip_marker(rest) == title {
409 from = Some(i);
410 to = body_end;
411 break;
412 }
413 i = body_end; // skip a non-matching ticket whole
414 continue;
415 }
416 } else if let Some((_, t)) = task_line(line) {
417 let mut j = i + 1;
418 while j < end && lines[j].starts_with(" ") {
419 j += 1;
420 }
421 if t == title {
422 from = Some(i);
423 to = j;
424 break;
425 }
426 i = j; // skip a non-matching task with its details
427 continue;
428 }
429 }
430 i += 1;
431 }
432 let from = from?;
433
434 // Don't swallow the blank separator before the next item/heading.
435 while to > from && lines[to - 1].trim().is_empty() {
436 to -= 1;
437 }
438
439 let mut out: Vec<String> = lines.iter().map(|l| l.to_string()).collect();
440 out.drain(from..to);
441 // Collapse a double blank left where the block was.
442 if from > 0
443 && from < out.len()
444 && out[from - 1].trim().is_empty()
445 && out[from].trim().is_empty()
446 {
447 out.remove(from);
448 }
449 Some(out.join("\n"))
450}
451
452/// What the board needs to render per-task delete controls: the repo
453/// coordinates, the branch tip (compare-and-swap guard), and a CSRF token.
454/// `None` renders a read-only board.
455pub struct BoardActions<'a> {
456 pub owner: &'a str,
457 pub repo: &'a str,
458 pub rev: &'a str,
459 pub path: &'a str,
460 pub tip: &'a str,
461 pub csrf: &'a str,
462}
463
464/// Render a todo-md document as a kanban board (columns = task-bearing
465/// sections) with prose sections as a notes area below. `None` if the file
466/// contains no tasks at all — callers fall back to plain markdown.
467pub fn render_board(text: &str, actions: Option<&BoardActions>) -> Option<Markup> {
468 let sections = parse(text);
469 if sections.iter().all(|s| s.tasks.is_empty()) {
470 return None;
471 }
472
473 // Prose-only sections (and stray preamble/column prose) become one
474 // markdown notes blob, headings preserved.
475 let mut notes = String::new();
476 for s in &sections {
477 let prose_empty = s.prose.trim().is_empty();
478 if s.tasks.is_empty() && s.level > 0 && prose_empty {
479 continue; // empty section: nothing to show either way
480 }
481 if s.tasks.is_empty() {
482 if s.level > 0 {
483 notes.push_str(&format!("{} {}\n", "#".repeat(s.level as usize), s.title));
484 }
485 if !prose_empty {
486 notes.push_str(&s.prose);
487 notes.push('\n');
488 }
489 }
490 }
491
492 Some(html! {
493 div.kanban {
494 @for s in sections.iter().filter(|s| !s.tasks.is_empty()) {
495 div.col {
496 h3 {
497 @if s.title.is_empty() { "Tasks" } @else { (s.title) }
498 span.count {
499 @if s.done {
500 ({ s.tasks.len().to_string() }) " done"
501 } @else {
502 ({ s.tasks.iter().filter(|t| !t.done).count().to_string() })
503 " open"
504 }
505 }
506 }
507 @for t in &s.tasks {
508 div.card.done[t.done] {
509 @if let Some(a) = actions {
510 form.card-del method="post"
511 action=(format!("/{}/{}/delete-task/{}/{}", a.owner, a.repo, crate::ui::enc_ref(a.rev), a.path)) {
512 (crate::ui::csrf_input(a.csrf))
513 input type="hidden" name="expected_tip" value=(a.tip);
514 input type="hidden" name="section" value=(s.title);
515 input type="hidden" name="title" value=(t.title);
516 button.card-del-btn type="submit" title="Delete task" aria-label="Delete task" { "×" }
517 }
518 }
519 div.title { (render_markdown(&t.title)) }
520 @if !t.details.trim().is_empty() {
521 details {
522 summary { "details" }
523 div.card-details { (render_markdown(&t.details)) }
524 }
525 }
526 }
527 }
528 }
529 }
530 }
531 @if !notes.trim().is_empty() {
532 details.todo-notes {
533 summary { "notes" }
534 div.md-body { (render_markdown(&notes)) }
535 }
536 }
537 })
538}
539
540#[cfg(test)]
541mod tests {
542 use super::*;
543
544 const DOC: &str = "\
545intro prose
546
547# Now
548
549- [ ] first task
550 - a detail line
551 - another `detail`
552- [x] finished task
553
554# Done [x]
555
556- [ ] moved here, checkbox stale
557
558## Implement Navbar
559
560Sticky top bar with the repo switcher.
561
562- shipped behind a flag
563- needs a follow-up for mobile
564
565# Notes
566
567just prose, no tasks
568
569```
570# not a heading
571- [ ] not a task
572```
573";
574
575 #[test]
576 fn parses_sections_tasks_details() {
577 let s = parse(DOC);
578 assert_eq!(s.len(), 4); // preamble + 3 column headings (## is a ticket)
579 assert_eq!(s[0].level, 0);
580 assert_eq!(s[0].prose.trim(), "intro prose");
581
582 assert_eq!(s[1].title, "Now");
583 assert!(!s[1].done);
584 assert_eq!(s[1].tasks.len(), 2);
585 assert_eq!(s[1].tasks[0].title, "first task");
586 assert!(!s[1].tasks[0].done);
587 assert!(!s[1].tasks[0].ticket);
588 assert_eq!(s[1].tasks[0].details, "- a detail line\n- another `detail`");
589 assert!(s[1].tasks[1].done);
590
591 // Done section: heading marker wins over the task's own checkbox.
592 assert_eq!(s[2].title, "Done");
593 assert!(s[2].done);
594 assert_eq!(s[2].tasks.len(), 2); // checkbox task + the ticket
595 assert!(s[2].tasks[0].done);
596 assert!(!s[2].tasks[0].ticket);
597 }
598
599 #[test]
600 fn nested_heading_is_a_ticket() {
601 let s = parse(DOC);
602 let ticket = &s[2].tasks[1];
603 assert!(ticket.ticket);
604 assert_eq!(ticket.title, "Implement Navbar");
605 // Done inherited from the `# Done [x]` section.
606 assert!(ticket.done);
607 assert!(ticket.details.contains("Sticky top bar"));
608 assert!(ticket.details.contains("- needs a follow-up for mobile"));
609 // The body must not leak into a sibling section.
610 assert!(!ticket.details.contains("just prose"));
611 }
612
613 #[test]
614 fn ticket_own_done_marker() {
615 let s = parse("# Backlog\n\n## Fix login [x]\n\nbody\n\n## Add search\n\nbody\n");
616 assert!(!s[1].done); // section is open
617 assert_eq!(s[1].tasks.len(), 2);
618 assert!(s[1].tasks[0].done); // ticket marked done on its own heading
619 assert_eq!(s[1].tasks[0].title, "Fix login");
620 assert!(!s[1].tasks[1].done);
621 }
622
623 #[test]
624 fn todo_md_by_filename() {
625 assert!(is_todo_md("TODO.md"));
626 assert!(is_todo_md("docs/todo.MD"));
627 assert!(!is_todo_md("TODO.txt"));
628 assert!(!is_todo_md("NOT-TODO.md"));
629 }
630
631 #[test]
632 fn board_renders_columns_tickets_and_falls_back() {
633 let board = render_board(DOC, None).expect("has tasks").into_string();
634 assert!(board.contains("kanban"));
635 assert!(board.contains("Now"));
636 assert!(board.contains("first task"));
637 // Tickets render as ordinary cards — no checkbox input, no special
638 // card class. (The DOC text mentions "checkbox", so check elements.)
639 assert!(board.contains("Implement Navbar"));
640 assert!(!board.contains("<input"), "no checkbox clutter: {board}");
641 assert!(!board.contains("ticket\""), "no ticket card class: {board}");
642 assert!(board.contains("just prose"), "notes area kept: {board}");
643 assert!(render_board("# readme\n\nonly prose\n", None).is_none());
644 }
645
646 #[test]
647 fn add_task_appends_ticket_within_section_byte_exactly() {
648 let out = add_task(DOC, "Now", "new ticket", "").unwrap();
649 // Lands as a nested heading after the section's last non-blank line,
650 // padded by a blank line, before the next column heading.
651 assert!(out.contains("- [x] finished task\n\n## new ticket\n\n# Done"));
652 // Round-trip rule: removing the inserted ticket restores the original.
653 assert_eq!(out.replacen("## new ticket\n\n", "", 1), DOC);
654 }
655
656 #[test]
657 fn add_task_with_body_writes_heading_then_description() {
658 let out = add_task("# Now\n# Done\n", "Now", "Title", "Line one\nLine two").unwrap();
659 assert_eq!(out, "# Now\n\n## Title\n\nLine one\nLine two\n# Done\n");
660 // The body becomes the ticket's parsed details.
661 let now = parse(&out).into_iter().find(|s| s.title == "Now").unwrap();
662 let ticket = now.tasks.iter().find(|t| t.title == "Title").unwrap();
663 assert!(ticket.ticket);
664 assert_eq!(ticket.details.trim(), "Line one\nLine two");
665 }
666
667 #[test]
668 fn add_task_ticket_level_tracks_the_column_level() {
669 // Columns at `##` ⇒ tickets nest at `###`.
670 let doc = "## Backlog\n\n### Existing\n\nbody\n";
671 let out = add_task(doc, "Backlog", "New one", "").unwrap();
672 assert!(out.contains("body\n\n### New one"));
673 }
674
675 #[test]
676 fn add_task_to_done_section_inherits_done_no_checkbox() {
677 let out = add_task(DOC, "Done", "tidy up", "").unwrap();
678 assert!(out.contains("## tidy up"));
679 assert!(!out.contains("- [ ] tidy up") && !out.contains("- [x] tidy up"));
680 // Parses as a ticket under the done column, so it reads as done.
681 let done = parse(&out).into_iter().find(|s| s.title == "Done").unwrap();
682 assert!(
683 done.tasks
684 .iter()
685 .any(|t| t.ticket && t.title == "tidy up" && t.done)
686 );
687 }
688
689 #[test]
690 fn add_task_into_empty_section_inserts_blank_then_ticket() {
691 let doc = "# Now\n# Done\n";
692 assert_eq!(
693 add_task(doc, "Now", "first", "").unwrap(),
694 "# Now\n\n## first\n# Done\n"
695 );
696 }
697
698 #[test]
699 fn add_task_rejects_missing_section_blank_title_and_headingless() {
700 assert!(add_task(DOC, "Nonexistent", "x", "").is_none());
701 assert!(add_task(DOC, "Now", " ", "body still rejected").is_none());
702 assert!(add_task("no headings here\n", "Whatever", "x", "").is_none());
703 }
704
705 #[test]
706 fn added_ticket_renders_as_a_board_card() {
707 let out = add_task(DOC, "Now", "Wire uploads", "").unwrap();
708 let board = render_board(&out, None).expect("has tasks").into_string();
709 assert!(board.contains("Wire uploads"));
710 }
711
712 #[test]
713 fn task_sections_lists_column_headings_stripped() {
714 assert_eq!(task_sections(DOC), ["Now", "Done", "Notes"]);
715 assert!(task_sections("# readme\n\nonly prose\n") == ["readme"]);
716 assert!(task_sections("no headings at all\n").is_empty());
717 }
718
719 #[test]
720 fn add_then_remove_task_round_trips() {
721 // Removing a just-added ticket restores the document byte-for-byte.
722 let added = add_task(DOC, "Now", "throwaway", "with a body line").unwrap();
723 assert_eq!(
724 remove_task(&added, "Now", "throwaway").as_deref(),
725 Some(DOC)
726 );
727 }
728
729 #[test]
730 fn remove_task_deletes_ticket_block() {
731 let doc = "# Now\n\n## first\n\nbody one\n\n## second\n\nbody two\n";
732 assert_eq!(
733 remove_task(doc, "Now", "first").unwrap(),
734 "# Now\n\n## second\n\nbody two\n"
735 );
736 // Removing the last ticket leaves the section heading intact.
737 assert_eq!(
738 remove_task(doc, "Now", "second").unwrap(),
739 "# Now\n\n## first\n\nbody one\n"
740 );
741 }
742
743 #[test]
744 fn remove_task_deletes_checkbox_with_its_details() {
745 let doc = "# Now\n\n- [ ] a\n detail of a\n- [x] b\n\n# Done\n";
746 assert_eq!(
747 remove_task(doc, "Now", "a").unwrap(),
748 "# Now\n\n- [x] b\n\n# Done\n"
749 );
750 }
751
752 #[test]
753 fn remove_task_rejects_missing_section_or_task() {
754 assert!(remove_task(DOC, "Nope", "first task").is_none());
755 assert!(remove_task(DOC, "Now", "not a real task").is_none());
756 }
757}