xonecas.io
8447
Co

conveyor / files

conveyor / templates / library / widgets / board.rs

8.5 KB
1//! A kanban board of the tickets of the project whose desktop this is: a column per state with
2//! counts, and cards with #id, title and time in that state. Drag a card to move it (never into
3//! or out of running), type at the top of draft to write a new one, and click a card to open it.
4use super::{api::*, look, canvas::{self, Canvas}, ui};
5use std::path::PathBuf;
6use rune::{Drag, El, Phase, ScrollSpec, TextEdit, Tx, col, el, row, text};
7
8pub const WIDGET: Widget = Widget { title: "Board", size: (1100.0, 520.0), new: |cx| Box::new(Board::load(cx)) };
9
10pub const STATES: [&str; 7] = ["draft", "ready", "running", "review", "parked", "failed", "done"];
11
12pub struct Board {
13    /// The quick-add field at the top of draft.
14    add: TextEdit,
15    /// The board's rect, then each column's, in window points from layout. Kept as a "layout"
16    /// file: the app reloads widgets without laying out again, so `on_layout` only speaks when
17    /// they move, and a rebuilt board would place the dragged card from (0, 0).
18    rects: [[f32; 4]; 8],
19    file: PathBuf,
20    /// The card being dragged: its ticket, the pointer in window points, and where on the card it was grabbed.
21    drag: Option<Dragged>,
22}
23
24#[derive(Clone, Copy)]
25struct Dragged { id: u32, at: [f32; 2], grab: [f32; 2], w: f32, moved: bool }
26
27impl Board {
28    fn load(cx: &Cx) -> Self {
29        let file = cx.dir.join("layout");
30        let mut rects = [[0.0; 4]; 8];
31        for (r, l) in rects.iter_mut().zip(std::fs::read_to_string(&file).unwrap_or_default().lines()) {
32            for (v, n) in r.iter_mut().zip(l.split(' ')) { *v = n.parse().unwrap_or(0.0) }
33        }
34        Board { add: TextEdit::default(), rects, file, drag: None }
35    }
36
37    /// Rect `i` (0 the board, then the columns) was laid out at `r`.
38    fn laid(&mut self, i: usize, r: [f32; 4]) {
39        self.rects[i] = r;
40        let _ = std::fs::write(&self.file, self.rects.iter().map(|r| format!("{} {} {} {}\n", r[0], r[1], r[2], r[3])).collect::<String>());
41    }
42
43    /// The column under window point `p`.
44    fn col_at(&self, p: [f32; 2]) -> Option<&'static str> {
45        self.rects[1..].iter().position(|r| p[0] >= r[0] && p[0] < r[0] + r[2] && p[1] >= r[1] && p[1] < r[1] + r[3]).map(|i| STATES[i])
46    }
47
48    /// Where the dragged card would land: a column it can move to, or none.
49    fn target(&self, from: &str) -> Option<&'static str> {
50        let d = self.drag.filter(|d| d.moved)?;
51        self.col_at(d.at).filter(|s| *s != from && *s != "running" && from != "running")
52    }
53}
54
55impl View for Board {
56    fn view(&self, cx: &Cx) -> El {
57        let t = look::of(cx);
58        let project = super::root::project_of(cx.id);
59        let tickets: Vec<&Ticket> = cx.data.tickets.iter().filter(|k| k.project == project).collect();
60        let dragged = self.drag.and_then(|d| tickets.iter().find(|k| k.id == d.id).copied());
61        let target = dragged.and_then(|k| self.target(&k.state));
62        let mut cols = row().key("columns").w_full().grow(1.0).min_h(0.0).gap(8.0);
63        for (i, state) in STATES.iter().enumerate() {
64            let mut cards: Vec<&Ticket> = tickets.iter().filter(|k| k.state == *state).copied().collect();
65            cards.sort_by_key(|k| std::cmp::Reverse(k.since));
66            let id = cx.id.to_owned();
67            let mut list = col().w_full().gap(6.0);
68            if *state == "draft" { list = list.child(quick_add(cx, &self.add, project)); }
69            for k in &cards { list = list.child(card(cx, k, dragged.is_some_and(|d| d.id == k.id))); }
70            cols = cols.child(col().key(format!("col-{state}")).grow(1.0).min_w(0.0).h_full().gap(8.0).padding(6.0).radius(8.0)
71                .fill(if target == Some(state) { t.press } else { t.bg })
72                .on_layout(move |h: &mut HostState, r: [f32; 4]| if let Some(b) = get::<Board>(h, &id) { b.laid(i + 1, r) })
73                .child(row().key(format!("head-{state}")).w_full().px(4.0).gap(6.0).center_y()
74                    .child(text(*state).font(t.label).color(t.text).truncate().min_w(0.0))
75                    .child(el().grow(1.0))
76                    .child(text(cards.len().to_string()).font(t.label).color(t.text_secondary)))
77                .child(col().w_full().grow(1.0).min_h(0.0).scroll(ScrollSpec { stick_bottom: false }).child(list)));
78        }
79        let id = cx.id.to_owned();
80        let mut board = col().w_full().h_full().gap(8.0)
81            .on_layout(move |h: &mut HostState, r: [f32; 4]| if let Some(b) = get::<Board>(h, &id) { b.laid(0, r) })
82            .child(row().key("header").w_full().center_y().gap(8.0)
83                .child(text("Board").font(t.title).color(t.text))
84                .child(text(project).font(t.label).color(t.text_secondary))
85                .child(el().grow(1.0))
86                .child(text(format!("{} tickets", tickets.len())).font(t.label).color(t.text_secondary))
87                .child(canvas::maximize(cx))
88                .child(canvas::close(cx, "Close board")))
89            .child(el().w_full().h(1.0).fill(t.separator))
90            .child(cols);
91        // The dragged card follows the pointer.
92        if let (Some(d), Some(k)) = (self.drag.filter(|d| d.moved), dragged) {
93            let (x, y) = (d.at[0] - d.grab[0] - self.rects[0][0], d.at[1] - d.grab[1] - self.rects[0][1]);
94            board = board.child(face(&look::of(cx), k, cx.now).w(d.w).absolute(x, y).opacity(0.9).border(1.0, t.accent));
95        }
96        board
97    }
98}
99
100/// The field atop draft: Enter writes a new draft titled with what was typed.
101fn quick_add(cx: &Cx, edit_: &TextEdit, project: &str) -> El {
102    let t = look::of(cx);
103    let (id, project) = (cx.id.to_owned(), project.to_owned());
104    ui::field(&t, edit_, t.label, "New draft…").key("quick-add").single_line().fill(t.card)
105        .on_edit(edit(cx.id, |b: &mut Board| &mut b.add))
106        .on_submit(move |h: &mut HostState, _: &mut Tx| {
107            let Some(b) = get::<Board>(h, &id) else { return };
108            let words = b.add.text.trim().to_owned();
109            b.add.clear();
110            if !words.is_empty() { new_ticket(h, &project, &words, &words, "draft", &[]) }
111        })
112}
113
114/// A ticket's card: drag it to another column, or click it to open the ticket beside the board.
115fn card(cx: &Cx, k: &Ticket, dragged: bool) -> El {
116    let (id, ticket, from) = (cx.id.to_owned(), k.id, k.state.clone());
117    face(&look::of(cx), k, cx.now).key(format!("card-{}", k.id)).w_full().role("button").label(format!("#{} {}", k.id, k.title)).hover(look::of(cx).hover)
118        .opacity(if dragged { 0.35 } else { 1.0 })
119        .on_drag(move |h: &mut HostState, d: &mut Drag, _: &mut Tx| {
120            let Some(b) = get::<Board>(h, &id) else { return };
121            match d.phase {
122                Phase::Down => b.drag = Some(Dragged { id: ticket, at: d.window_point(), grab: [d.x, d.y], w: d.w, moved: false }),
123                Phase::Move => if let Some(g) = &mut b.drag { g.at = d.window_point(); g.moved |= d.dx.abs() + d.dy.abs() > 4.0 },
124                Phase::Up => {
125                    let to = if d.cancelled() { None } else { b.target(&from) };
126                    let clicked = b.drag.take().is_some_and(|g| !g.moved) && !d.cancelled();
127                    let project = super::root::project_of(&id).to_owned();
128                    if let Some(to) = to { set_state(h, &project, ticket, to) }
129                    if clicked { open(h, &id, ticket) }
130                }
131            }
132        })
133}
134
135/// What a card shows: #id, the time in its state, and its title.
136fn face(t: &look::Look, k: &Ticket, now: f64) -> El {
137    col().gap(4.0).padding(8.0).radius(6.0).fill(t.card)
138        .child(row().w_full().gap(6.0).flex_wrap()
139            .child(text(format!("#{}", k.id)).font(t.label).color(t.text_secondary))
140            .child(el().grow(1.0))
141            .child(text(ago(now, k.since)).font(t.label).color(t.text_secondary)))
142        .child(text(&k.title).font(t.label).color(t.text).w_full().wrap().max_lines(3))
143}
144
145/// Opens ticket `ticket` in a card beside board `board` on its canvas, or brings it to the front.
146fn open(h: &mut HostState, board: &str, ticket: u32) {
147    let Some((parent, key)) = board.rsplit_once('.') else { return };
148    if let Some(c) = get::<Canvas>(h, parent) { c.open_beside("ticket", &format!("ticket-{ticket}"), super::ticket::WIDGET.size, key) }
149}
150
151/// How long ago Unix time `at` was: 40s, 12m, 3h, 5d.
152pub fn ago(now: f64, at: u64) -> String {
153    let s = (now as u64).saturating_sub(at);
154    match s {
155        0..60 => format!("{s}s"),
156        60..3600 => format!("{}m", s / 60),
157        3600..86400 => format!("{}h", s / 3600),
158        _ => format!("{}d", s / 86400),
159    }
160}