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 data-title=[actions.map(|_| t.title.as_str())] {
633 @if let Some(a) = actions {
634 span.card-grip title="Drag to reorder" aria-hidden="true" {
635 (crate::ui::icon(crate::ui::Icon::Grip))
636 }
637 form.card-del method="post"
638 action=(format!("/{}/{}/delete-task/{}/{}", a.owner, a.repo, crate::ui::enc_ref(a.rev), a.path)) {
639 (crate::ui::csrf_input(a.csrf))
640 input type="hidden" name="expected_tip" value=(a.tip);
641 input type="hidden" name="section" value=(s.title);
642 input type="hidden" name="title" value=(t.title);
643 button.card-del-btn type="submit" title="Delete task" aria-label="Delete task" { "×" }
644 }
645 }
646 div.title { (render_markdown(&t.title)) }
647 @if !t.details.trim().is_empty() {
648 details {
649 summary { "details" }
650 div.card-details { (render_markdown(&t.details)) }
651 }
652 }
653 }
654 }
655 }
656 }
657 }
658 @if !notes.trim().is_empty() {
659 details.todo-notes {
660 summary { "notes" }
661 div.md-body { (render_markdown(&notes)) }
662 }
663 }
664 @if actions.is_some() { script { (maud::PreEscaped(BOARD_DND_JS)) } }
665 })
666}
667
668/// Drag-and-drop reordering for the board, via a per-card grip handle and
669/// Pointer Events — so it works with mouse, touch, and pen alike (plain HTML5
670/// drag-and-drop never fires on touchscreens). Grab a card's grip, drag within
671/// or across columns; the card reorders live, and on release the new
672/// (section, index) is POSTed to the move endpoint and the page reloads.
673/// Reads the endpoint/tip/csrf from the `.kanban` element's data-attrs.
674const BOARD_DND_JS: &str = r#"
675(function(){
676 var board = document.querySelector('.kanban[data-move-url]');
677 if (!board) return;
678 var url = board.dataset.moveUrl, tip = board.dataset.tip, csrf = board.dataset.csrf;
679 var card = null, fromSection = null, grip = null, pid = null;
680
681 function afterCard(col, y){
682 var cards = [].slice.call(col.querySelectorAll('.card:not(.dragging)'));
683 var best = null, bestOffset = -Infinity;
684 cards.forEach(function(c){
685 var box = c.getBoundingClientRect();
686 var offset = y - box.top - box.height / 2;
687 if (offset < 0 && offset > bestOffset) { bestOffset = offset; best = c; }
688 });
689 return best;
690 }
691 function onMove(e){
692 if (!card) return;
693 e.preventDefault();
694 var under = document.elementFromPoint(e.clientX, e.clientY);
695 var col = (under && under.closest && under.closest('.col')) || card.closest('.col');
696 var after = afterCard(col, e.clientY);
697 if (after == null) col.appendChild(card);
698 else col.insertBefore(card, after);
699 }
700 function onUp(){
701 if (!card) return;
702 grip.removeEventListener('pointermove', onMove);
703 grip.removeEventListener('pointerup', onUp);
704 grip.removeEventListener('pointercancel', onUp);
705 var c = card;
706 card = null;
707 c.classList.remove('dragging');
708 var col = c.closest('.col');
709 var cards = [].slice.call(col.querySelectorAll('.card'));
710 var body = new URLSearchParams();
711 body.set('csrf', csrf);
712 body.set('expected_tip', tip);
713 body.set('from_section', fromSection);
714 body.set('to_section', col.dataset.section);
715 body.set('title', c.dataset.title);
716 body.set('to_index', String(cards.indexOf(c)));
717 fetch(url, {
718 method: 'POST',
719 headers: {'X-CSRF-Token': csrf, 'Content-Type': 'application/x-www-form-urlencoded'},
720 body: body.toString()
721 }).then(function(r){
722 if (!r.ok) throw new Error('move failed (' + r.status + ')');
723 location.reload();
724 }).catch(function(err){ console.error(err); location.reload(); });
725 }
726 board.addEventListener('pointerdown', function(e){
727 var g = e.target.closest('.card-grip');
728 if (!g) return;
729 card = g.closest('.card');
730 if (!card) return;
731 e.preventDefault();
732 grip = g;
733 pid = e.pointerId;
734 fromSection = card.closest('.col').dataset.section;
735 card.classList.add('dragging');
736 grip.setPointerCapture(pid);
737 grip.addEventListener('pointermove', onMove);
738 grip.addEventListener('pointerup', onUp);
739 grip.addEventListener('pointercancel', onUp);
740 });
741})();
742"#;
743
744#[cfg(test)]
745mod tests {
746 use super::*;
747
748 const DOC: &str = "\
749intro prose
750
751# Now
752
753- [ ] first task
754 - a detail line
755 - another `detail`
756- [x] finished task
757
758# Done [x]
759
760- [ ] moved here, checkbox stale
761
762## Implement Navbar
763
764Sticky top bar with the repo switcher.
765
766- shipped behind a flag
767- needs a follow-up for mobile
768
769# Notes
770
771just prose, no tasks
772
773```
774# not a heading
775- [ ] not a task
776```
777";
778
779 #[test]
780 fn parses_sections_tasks_details() {
781 let s = parse(DOC);
782 assert_eq!(s.len(), 4); // preamble + 3 column headings (## is a ticket)
783 assert_eq!(s[0].level, 0);
784 assert_eq!(s[0].prose.trim(), "intro prose");
785
786 assert_eq!(s[1].title, "Now");
787 assert!(!s[1].done);
788 assert_eq!(s[1].tasks.len(), 2);
789 assert_eq!(s[1].tasks[0].title, "first task");
790 assert!(!s[1].tasks[0].done);
791 assert!(!s[1].tasks[0].ticket);
792 assert_eq!(s[1].tasks[0].details, "- a detail line\n- another `detail`");
793 assert!(s[1].tasks[1].done);
794
795 // Done section: heading marker wins over the task's own checkbox.
796 assert_eq!(s[2].title, "Done");
797 assert!(s[2].done);
798 assert_eq!(s[2].tasks.len(), 2); // checkbox task + the ticket
799 assert!(s[2].tasks[0].done);
800 assert!(!s[2].tasks[0].ticket);
801 }
802
803 #[test]
804 fn nested_heading_is_a_ticket() {
805 let s = parse(DOC);
806 let ticket = &s[2].tasks[1];
807 assert!(ticket.ticket);
808 assert_eq!(ticket.title, "Implement Navbar");
809 // Done inherited from the `# Done [x]` section.
810 assert!(ticket.done);
811 assert!(ticket.details.contains("Sticky top bar"));
812 assert!(ticket.details.contains("- needs a follow-up for mobile"));
813 // The body must not leak into a sibling section.
814 assert!(!ticket.details.contains("just prose"));
815 }
816
817 #[test]
818 fn ticket_own_done_marker() {
819 let s = parse("# Backlog\n\n## Fix login [x]\n\nbody\n\n## Add search\n\nbody\n");
820 assert!(!s[1].done); // section is open
821 assert_eq!(s[1].tasks.len(), 2);
822 assert!(s[1].tasks[0].done); // ticket marked done on its own heading
823 assert_eq!(s[1].tasks[0].title, "Fix login");
824 assert!(!s[1].tasks[1].done);
825 }
826
827 #[test]
828 fn todo_md_by_filename() {
829 assert!(is_todo_md("TODO.md"));
830 assert!(is_todo_md("docs/todo.MD"));
831 assert!(!is_todo_md("TODO.txt"));
832 assert!(!is_todo_md("NOT-TODO.md"));
833 }
834
835 #[test]
836 fn board_renders_columns_tickets_and_falls_back() {
837 let board = render_board(DOC, None).expect("has tasks").into_string();
838 assert!(board.contains("kanban"));
839 assert!(board.contains("Now"));
840 assert!(board.contains("first task"));
841 // Tickets render as ordinary cards — no checkbox input, no special
842 // card class. (The DOC text mentions "checkbox", so check elements.)
843 assert!(board.contains("Implement Navbar"));
844 assert!(!board.contains("<input"), "no checkbox clutter: {board}");
845 assert!(!board.contains("ticket\""), "no ticket card class: {board}");
846 assert!(board.contains("just prose"), "notes area kept: {board}");
847 assert!(render_board("# readme\n\nonly prose\n", None).is_none());
848 }
849
850 #[test]
851 fn add_task_appends_ticket_within_section_byte_exactly() {
852 let out = add_task(DOC, "Now", "new ticket", "").unwrap();
853 // Lands as a nested heading after the section's last non-blank line,
854 // padded by a blank line, before the next column heading.
855 assert!(out.contains("- [x] finished task\n\n## new ticket\n\n# Done"));
856 // Round-trip rule: removing the inserted ticket restores the original.
857 assert_eq!(out.replacen("## new ticket\n\n", "", 1), DOC);
858 }
859
860 #[test]
861 fn add_task_with_body_writes_heading_then_description() {
862 let out = add_task("# Now\n# Done\n", "Now", "Title", "Line one\nLine two").unwrap();
863 assert_eq!(out, "# Now\n\n## Title\n\nLine one\nLine two\n# Done\n");
864 // The body becomes the ticket's parsed details.
865 let now = parse(&out).into_iter().find(|s| s.title == "Now").unwrap();
866 let ticket = now.tasks.iter().find(|t| t.title == "Title").unwrap();
867 assert!(ticket.ticket);
868 assert_eq!(ticket.details.trim(), "Line one\nLine two");
869 }
870
871 #[test]
872 fn add_task_ticket_level_tracks_the_column_level() {
873 // Columns at `##` ⇒ tickets nest at `###`.
874 let doc = "## Backlog\n\n### Existing\n\nbody\n";
875 let out = add_task(doc, "Backlog", "New one", "").unwrap();
876 assert!(out.contains("body\n\n### New one"));
877 }
878
879 #[test]
880 fn add_task_to_done_section_inherits_done_no_checkbox() {
881 let out = add_task(DOC, "Done", "tidy up", "").unwrap();
882 assert!(out.contains("## tidy up"));
883 assert!(!out.contains("- [ ] tidy up") && !out.contains("- [x] tidy up"));
884 // Parses as a ticket under the done column, so it reads as done.
885 let done = parse(&out).into_iter().find(|s| s.title == "Done").unwrap();
886 assert!(
887 done.tasks
888 .iter()
889 .any(|t| t.ticket && t.title == "tidy up" && t.done)
890 );
891 }
892
893 #[test]
894 fn add_task_into_empty_section_inserts_blank_then_ticket() {
895 let doc = "# Now\n# Done\n";
896 assert_eq!(
897 add_task(doc, "Now", "first", "").unwrap(),
898 "# Now\n\n## first\n# Done\n"
899 );
900 }
901
902 #[test]
903 fn add_task_rejects_missing_section_blank_title_and_headingless() {
904 assert!(add_task(DOC, "Nonexistent", "x", "").is_none());
905 assert!(add_task(DOC, "Now", " ", "body still rejected").is_none());
906 assert!(add_task("no headings here\n", "Whatever", "x", "").is_none());
907 }
908
909 #[test]
910 fn added_ticket_renders_as_a_board_card() {
911 let out = add_task(DOC, "Now", "Wire uploads", "").unwrap();
912 let board = render_board(&out, None).expect("has tasks").into_string();
913 assert!(board.contains("Wire uploads"));
914 }
915
916 #[test]
917 fn task_sections_lists_column_headings_stripped() {
918 assert_eq!(task_sections(DOC), ["Now", "Done", "Notes"]);
919 assert!(task_sections("# readme\n\nonly prose\n") == ["readme"]);
920 assert!(task_sections("no headings at all\n").is_empty());
921 }
922
923 #[test]
924 fn add_then_remove_task_round_trips() {
925 // Removing a just-added ticket restores the document byte-for-byte.
926 let added = add_task(DOC, "Now", "throwaway", "with a body line").unwrap();
927 assert_eq!(
928 remove_task(&added, "Now", "throwaway").as_deref(),
929 Some(DOC)
930 );
931 }
932
933 #[test]
934 fn remove_task_deletes_ticket_block() {
935 let doc = "# Now\n\n## first\n\nbody one\n\n## second\n\nbody two\n";
936 assert_eq!(
937 remove_task(doc, "Now", "first").unwrap(),
938 "# Now\n\n## second\n\nbody two\n"
939 );
940 // Removing the last ticket leaves the section heading intact.
941 assert_eq!(
942 remove_task(doc, "Now", "second").unwrap(),
943 "# Now\n\n## first\n\nbody one\n"
944 );
945 }
946
947 #[test]
948 fn remove_task_deletes_checkbox_with_its_details() {
949 let doc = "# Now\n\n- [ ] a\n detail of a\n- [x] b\n\n# Done\n";
950 assert_eq!(
951 remove_task(doc, "Now", "a").unwrap(),
952 "# Now\n\n- [x] b\n\n# Done\n"
953 );
954 }
955
956 #[test]
957 fn remove_task_rejects_missing_section_or_task() {
958 assert!(remove_task(DOC, "Nope", "first task").is_none());
959 assert!(remove_task(DOC, "Now", "not a real task").is_none());
960 }
961
962 /// Ticket titles of a section, in order — order is what reordering changes.
963 fn order(text: &str, section: &str) -> Vec<String> {
964 parse(text)
965 .into_iter()
966 .find(|s| s.title == section)
967 .map(|s| s.tasks.into_iter().map(|t| t.title).collect())
968 .unwrap_or_default()
969 }
970
971 #[test]
972 fn move_task_reorders_within_a_section() {
973 let doc = "# Now\n\n## a\n\n## b\n\n## c\n";
974 assert_eq!(
975 order(&move_task(doc, "c", "Now", "Now", 0).unwrap(), "Now"),
976 ["c", "a", "b"]
977 );
978 // to_index past the end appends.
979 assert_eq!(
980 order(&move_task(doc, "a", "Now", "Now", 9).unwrap(), "Now"),
981 ["b", "c", "a"]
982 );
983 }
984
985 #[test]
986 fn move_task_across_sections_preserves_body() {
987 let doc = "# Now\n\n## a\n\nbody of a\n\n# Done\n\n## b\n";
988 let out = move_task(doc, "a", "Now", "Done", 1).unwrap();
989 assert_eq!(order(&out, "Now"), Vec::<String>::new());
990 assert_eq!(order(&out, "Done"), ["b", "a"]);
991 assert!(
992 out.contains("## a\n\nbody of a"),
993 "body travels with the ticket"
994 );
995 }
996
997 #[test]
998 fn move_task_rejects_unknown_task_or_section() {
999 let doc = "# Now\n\n## a\n\n# Done\n";
1000 assert!(move_task(doc, "ghost", "Now", "Done", 0).is_none());
1001 assert!(move_task(doc, "a", "Now", "Nope", 0).is_none());
1002 }
1003}