xonecas.io
8447
Co

conveyor / files

conveyor / templates / library / widgets / ticket.rs

15.3 KB
1//! One ticket, opened from a board: its title and body (editable while it isn't running; Save
2//! rewrites it), attached files, its conversation with times, and what its state allows next.
3//! The body while running and the conversation are rendered as Markdown.
4//! In review it shows the branch's diff stat, and Explore opens the branch in an editor beside it; parked, the block and its recommendation. With no
5//! ticket to show, it's a form that writes a new one, with files dropped on it attached.
6use super::{api::*, look, board::ago, canvas, ui};
7use rune::{El, FileDialogOptions, ScrollSpec, TextEdit, TextStyle, Tx, col, el, row, text};
8use std::{path::PathBuf, sync::{Arc, Mutex}};
9
10pub const WIDGET: Widget = Widget { title: "Ticket", size: (480.0, 620.0), new: |cx| Box::new(TicketCard::load(cx)) };
11
12pub struct TicketCard {
13    title: TextEdit,
14    body: TextEdit,
15    /// The title and body as conveyor last had them: the fields follow them until edited.
16    base: (String, String),
17    /// Unsaved edits, kept as a "draft" file (title, a line break, body) across reloads.
18    draft: PathBuf,
19    /// `git diff --stat HEAD...t-<id>`, run when the ticket entered review at this time.
20    diff: Arc<Mutex<Option<String>>>,
21    diff_for: u64,
22    /// The new ticket's attachments, one path a line in the "files" file.
23    files: Vec<PathBuf>,
24    files_at: PathBuf,
25}
26
27/// The ticket this card shows: its key is `ticket-<id>` on the project's desktop.
28fn ticket<'a>(cx: &'a Cx) -> Option<&'a Ticket> {
29    let id: u32 = cx.id.rsplit('.').next()?.strip_prefix("ticket-")?.parse().ok()?;
30    let project = super::root::project_of(cx.id);
31    cx.data.tickets.iter().find(|k| k.project == project && k.id == id)
32}
33
34impl TicketCard {
35    fn load(cx: &Cx) -> Self {
36        let draft = cx.dir.join("draft");
37        let (title, body) = std::fs::read_to_string(&draft).ok().and_then(|s| s.split_once('\n').map(|(a, b)| (a.to_owned(), b.to_owned())))
38            .or_else(|| ticket(cx).map(|k| (k.title.clone(), k.body.clone()))).unwrap_or_default();
39        let base = ticket(cx).map(|k| (k.title.clone(), k.body.clone())).unwrap_or_default();
40        let files_at = cx.dir.join("files");
41        let files = std::fs::read_to_string(&files_at).unwrap_or_default().lines().map(PathBuf::from).collect();
42        TicketCard { title: TextEdit::new(title), body: TextEdit::new(body), base, draft, diff: Arc::default(), diff_for: 0, files, files_at }
43    }
44
45    fn set_files(&mut self, files: Vec<PathBuf>) {
46        self.files = files;
47        let lines: Vec<String> = self.files.iter().map(|f| f.to_string_lossy().into_owned()).collect();
48        let _ = std::fs::write(&self.files_at, lines.join("\n"));
49    }
50
51    fn modified(&self) -> bool {
52        (self.title.text.as_str(), self.body.text.as_str()) != (self.base.0.as_str(), self.base.1.as_str())
53    }
54}
55
56impl View for TicketCard {
57    fn update(&mut self, cx: &Cx) {
58        let k = ticket(cx);
59        if let Some(k) = k && (k.title.as_str(), k.body.as_str()) != (self.base.0.as_str(), self.base.1.as_str()) {
60            if !self.modified() { (self.title, self.body) = (TextEdit::new(k.title.clone()), TextEdit::new(k.body.clone())) }
61            self.base = (k.title.clone(), k.body.clone());
62        }
63        let draft = format!("{}\n{}", self.title.text, self.body.text);
64        if !self.modified() { let _ = std::fs::remove_file(&self.draft); }
65        else if std::fs::read_to_string(&self.draft).ok().as_deref() != Some(&draft) { let _ = std::fs::write(&self.draft, draft); }
66        let Some(k) = k else { return };
67        if k.state == "review" && self.diff_for != k.since {
68            self.diff_for = k.since;
69            let (out, path, branch) = (self.diff.clone(), cx.data.projects.iter().find(|p| p.slug == k.project).map(|p| p.path.clone()).unwrap_or_default(), format!("HEAD...refs/conveyor/t-{}", k.id));
70            *out.lock().unwrap() = None;
71            std::thread::spawn(move || {
72                let r = std::process::Command::new("git").args(["diff", "--stat", &branch]).current_dir(&path).output();
73                let s = match r {
74                    Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim_end().to_owned(),
75                    Ok(o) => String::from_utf8_lossy(&o.stderr).trim_end().to_owned(),
76                    Err(e) => format!("git: {e}"),
77                };
78                *out.lock().unwrap() = Some(if s.is_empty() { "No changes".into() } else { s });
79            });
80        }
81    }
82
83    fn view(&self, cx: &Cx) -> El {
84        let t = look::of(cx);
85        let Some(k) = ticket(cx) else { return self.form(cx) };
86        let running = k.state == "running";
87        let label = |s: &str| text(s).font(t.label).color(t.text_secondary);
88        let field = |e: &TextEdit| ui::field(&t, e, t.body, "");
89        let mut body = col().w_full().gap(10.0);
90        body = if running {
91            body.child(text(&k.title).font(t.title).color(t.text).w_full().wrap())
92                .child(ui::markdown(&t, &k.body, t.body, t.text).key("body"))
93                .child(label("Running: editing waits until it settles"))
94        } else {
95            body.child(field(&self.title).key("title").single_line().on_edit(edit(cx.id, |c: &mut TicketCard| &mut c.title)))
96                .child(field(&self.body).key("body").min_h(120.0).on_edit(edit(cx.id, |c: &mut TicketCard| &mut c.body)))
97        };
98        if !k.files.is_empty() {
99            let mut files = col().key("files").w_full().gap(2.0).child(label("Files"));
100            for f in &k.files {
101                let path = f.clone();
102                let name = std::path::Path::new(f).file_name().map_or(f.clone(), |n| n.to_string_lossy().into_owned());
103                files = files.child(row().key(format!("file-{name}")).w_full().px(6.0).py(4.0).radius(5.0).role("button").label(name.as_str()).help(f.as_str()).hover(t.hover)
104                    .on_press_tx(move |_: &mut HostState, _: &mut Tx| { let _ = std::process::Command::new(if cfg!(target_os = "macos") { "open" } else { "xdg-open" }).arg(&path).spawn(); })
105                    .child(text(format!("▤ {name}")).font(t.label).color(t.text).truncate()));
106            }
107            body = body.child(files);
108        }
109        if k.state == "review" {
110            let diff = self.diff.lock().unwrap().clone().unwrap_or_else(|| "…".into());
111            body = body.child(col().key("diff").w_full().gap(4.0).padding(8.0).radius(6.0).fill(t.bg)
112                .child(row().w_full().center_y().gap(8.0)
113                    .child(text(format!("Branch t-{}", k.id)).font(t.label).color(t.text))
114                    .child(el().grow(1.0))
115                    .child(explore(cx, k.id)))
116                .child(text(diff).font(t.mono).color(t.text_secondary).w_full().wrap()));
117        }
118        if k.state == "parked" && let Some(b) = k.thread.iter().rev().find(|a| a.kind == "block") {
119            body = body.child(col().key("block").w_full().gap(4.0).padding(8.0).radius(6.0).fill(t.bg).border(1.0, t.warn)
120                .child(text("Blocked").font(t.label).color(t.warn))
121                .child(text(&b.text).font(t.label).color(t.text).w_full().wrap())
122                .child(label("Answer it in the body, then Ready")));
123        }
124        // The conversation reads a step above body text, with open line spacing, each entry on its own card.
125        let read = { let size = t.body.size * 15.0 / 13.0; TextStyle { size, line_height: size * 1.5, ..t.body } };
126        let mut thread = col().key("thread").w_full().gap(10.0).child(label("Conversation"));
127        for (i, a) in k.thread.iter().enumerate() {
128            thread = thread.child(col().key(format!("entry-{i}")).w_full().gap(6.0).px(14.0).py(10.0).radius(8.0).fill(t.bg)
129                .child(row().w_full().center_y().gap(6.0)
130                    .child(row().px(8.0).py(2.0).radius(8.0).fill(t.press).child(text(&a.kind).font(t.label).color(t.text)))
131                    .child(el().grow(1.0)).child(label(&ago(cx.now, a.at))))
132                .child(ui::markdown(&t, &a.text, read, t.text).key("text")));
133        }
134        col().w_full().h_full().gap(10.0)
135            .child(row().key("header").w_full().center_y().gap(8.0)
136                .child(text(format!("#{}", k.id)).font(t.title).color(t.text))
137                .child(row().px(8.0).py(2.0).radius(8.0).fill(t.press).child(text(&k.state).font(t.label).color(t.text)))
138                .child(label(&ago(cx.now, k.since)))
139                .child(el().grow(1.0))
140                .child(canvas::maximize(cx))
141                .child(canvas::close(cx, "Close ticket")))
142            .child(el().w_full().h(1.0).fill(t.separator))
143            .child(col().key("content").w_full().grow(1.0).min_h(0.0).scroll(ScrollSpec { stick_bottom: false }).child(body.child(thread)))
144            .child(self.actions(cx, k))
145    }
146}
147
148impl TicketCard {
149    /// Save while edited, and the moves the ticket's state allows.
150    fn actions(&self, cx: &Cx, k: &Ticket) -> El {
151        let mut bar = row().key("actions").w_full().gap(8.0).child(el().grow(1.0));
152        if k.state != "running" && self.modified() { bar = bar.child(button(cx, k, "save", "Save", None, true, false)) }
153        // A parked ticket goes back once its body has the answer: it differs from what the agent was given.
154        let answered = k.thread.iter().rev().find(|a| a.kind == "prompt").is_none_or(|p| p.text.trim() != self.body.text.trim());
155        match k.state.as_str() {
156            "draft" => bar.child(button(cx, k, "ready", "Ready", Some("ready"), true, true)),
157            "failed" => bar.child(button(cx, k, "retry", "Ready to retry", Some("ready"), true, true)),
158            "parked" => bar.child(button(cx, k, "ready", "Ready", Some("ready"), answered, true)),
159            "review" => bar.child(button(cx, k, "back", "Back to draft", Some("draft"), true, false)).child(button(cx, k, "done", "Done", Some("done"), true, true)),
160            _ => bar,
161        }
162    }
163}
164
165impl TicketCard {
166    /// The new ticket form, for this desktop's project: title, body, attachments, Draft or Ready.
167    fn form(&self, cx: &Cx) -> El {
168        let t = look::of(cx);
169        let project = super::root::project_of(cx.id);
170        let field = |e: &TextEdit, hint: &str| ui::field(&t, e, t.body, hint);
171        let mut files = col().key("files").w_full().gap(2.0)
172            .child(row().w_full().center_y().gap(8.0)
173                .child(text("Files").font(t.label).color(t.text_secondary))
174                .child(el().grow(1.0))
175                .child(attach(cx)));
176        if self.files.is_empty() { files = files.child(text("Drop files here to attach them").font(t.label).color(t.text_secondary)) }
177        for (i, f) in self.files.iter().enumerate() {
178            let name = f.file_name().map_or(f.to_string_lossy(), |n| n.to_string_lossy()).into_owned();
179            files = files.child(row().key(format!("file-{name}")).w_full().center_y().gap(6.0).px(6.0).py(4.0).radius(5.0).help(f.to_string_lossy().as_ref())
180                .child(text(format!("▤ {name}")).font(t.label).color(t.text).truncate().grow(1.0))
181                .child(ui::icon(&t, "remove", "×", "Remove", on(cx.id, move |c: &mut TicketCard, _| { let mut f = c.files.clone(); f.remove(i); c.set_files(f) }))));
182        }
183        let some = !self.title.text.trim().is_empty() || !self.body.text.trim().is_empty();
184        let id = cx.id.to_owned();
185        col().key("new-ticket").w_full().h_full().gap(10.0)
186            .on_drop_files(move |h: &mut HostState, dropped: &[PathBuf], _: &mut Tx| {
187                let Some(c) = get::<TicketCard>(h, &id) else { return };
188                let mut f = c.files.clone();
189                f.extend(dropped.iter().filter(|p| !c.files.contains(p)).cloned());
190                c.set_files(f);
191            })
192            .child(row().key("header").w_full().center_y().gap(8.0)
193                .child(text("New ticket").font(t.title).color(t.text))
194                .child(text(project).font(t.label).color(t.text_secondary))
195                .child(el().grow(1.0))
196                .child(canvas::maximize(cx))
197                .child(canvas::close(cx, "Close")))
198            .child(el().w_full().h(1.0).fill(t.separator))
199            .child(field(&self.title, "Title").key("title").single_line().on_edit(edit(cx.id, |c: &mut TicketCard| &mut c.title)))
200            .child(field(&self.body, "What should happen…").key("body").grow(1.0).min_h(120.0).on_edit(edit(cx.id, |c: &mut TicketCard| &mut c.body)))
201            .child(files)
202            .child(row().key("actions").w_full().gap(8.0).child(el().grow(1.0))
203                .child(create(cx, "draft", "Save draft", some))
204                .child(create(cx, "ready", "Ready", some)))
205    }
206}
207
208/// Opens ticket `ticket`'s branch in an editor card beside this one, or brings it to the front.
209fn explore(cx: &Cx, ticket: u32) -> El {
210    let id = cx.id.to_owned();
211    ui::button(&look::of(cx), "explore", "Explore in editor", true, move |h: &mut HostState, _: &mut Tx| {
212        let Some((parent, key)) = id.rsplit_once('.') else { return };
213        if let Some(c) = get::<canvas::Canvas>(h, parent) { c.open_beside("editor", &format!("branch-{ticket}"), super::editor::WIDGET.size, key) }
214    }).help(format!("Browse #{ticket}'s work read-only, its changed files lit"))
215}
216
217/// Opens the system's file dialog and attaches the chosen file to the new ticket.
218fn attach(cx: &Cx) -> El {
219    let id = cx.id.to_owned();
220    ui::icon(&look::of(cx), "attach", "+ Attach", "Attach file", move |_: &mut HostState, tx: &mut Tx| {
221        let id = id.clone();
222        tx.open_file(FileDialogOptions { title: "Attach file".into(), ..Default::default() }, move |h: &mut HostState, result, _| {
223            let Ok(Some(path)) = result else { return };
224            let Some(c) = get::<TicketCard>(h, &id) else { return };
225            if !c.files.contains(&path) { let mut f = c.files.clone(); f.push(path); c.set_files(f) }
226        });
227    })
228}
229
230/// Writes the form as a new ticket in `state` and clears it. Untitled, it takes the body's first line.
231fn create(cx: &Cx, state: &'static str, label: &str, on: bool) -> El {
232    let (id, project) = (cx.id.to_owned(), super::root::project_of(cx.id).to_owned());
233    let make = if state == "ready" { ui::primary } else { ui::button };
234    make(&look::of(cx), state, label, on, move |h: &mut HostState, _: &mut Tx| {
235        let Some(c) = get::<TicketCard>(h, &id) else { return };
236        let body = c.body.text.trim().to_owned();
237        let title = Some(c.title.text.trim()).filter(|s| !s.is_empty()).unwrap_or_else(|| body.lines().next().unwrap_or("")).to_owned();
238        let files = c.files.clone();
239        (c.title, c.body) = (TextEdit::default(), TextEdit::default());
240        c.set_files(Vec::new());
241        new_ticket(h, &project, &title, &body, state, &files);
242    })
243}
244
245/// A button that saves any edits, then moves the ticket to `to`; the `main` one in the accent. Dimmed and inert unless `on`.
246fn button(cx: &Cx, k: &Ticket, key: &str, label: &str, to: Option<&'static str>, on: bool, main: bool) -> El {
247    let (id, project, ticket) = (cx.id.to_owned(), k.project.clone(), k.id);
248    let make = if main { ui::primary } else { ui::button };
249    make(&look::of(cx), key, label, on, move |h: &mut HostState, _: &mut Tx| {
250        let Some(c) = get::<TicketCard>(h, &id) else { return };
251        let edits = c.modified().then(|| (c.title.text.trim().to_owned(), c.body.text.clone()));
252        if let Some((title, body)) = edits { edit_ticket(h, &project, ticket, &title, &body) }
253        if let Some(to) = to { set_state(h, &project, ticket, to) }
254    })
255}