xonecas.io
8447
Co

conveyor / files

conveyor / templates / library / widgets / taskbar.rs

9.8 KB
1//! A taskbar on any edge of the window: the widgets project pinned first, then every other project,
2//! and a button that adds one. The dock icon at its end picks the window edge it sits on: top, bottom, left or right.
3//!
4//! A press on a project shares "project", and root switches to its canvas. A project's × forgets it from
5//! the bar: the first press arms it (red), a second within `ARMED` seconds forgets. The edge is shared as "taskbar-edge".
6use super::{api::*, look, ui};
7use rune::{Align, El, FileDialogOptions, Side, Tx, col, el, row, text};
8use std::path::PathBuf;
9
10pub const WIDGET: Widget = Widget { title: "Taskbar", size: (0.0, 44.0), new: |cx| Box::new(Taskbar::load(cx)) };
11
12/// Projects forgotten from the bar (saved, one slug a line), the × pressed once, with when, and
13/// whether the dock menu is open.
14pub struct Taskbar { forgotten: Vec<String>, armed: Option<(String, f64)>, file: PathBuf, menu: bool }
15
16/// The window edge the taskbar sits on.
17#[derive(Clone, Copy, PartialEq)]
18pub enum Edge { Top, Bottom, Left, Right }
19
20/// The bar's height on the top or bottom, and the sidebar's width on the left or right.
21pub const THICK: f32 = 44.0;
22pub const WIDE: f32 = 200.0;
23
24impl Edge {
25    const ALL: [(Edge, &str); 4] = [(Edge::Top, "top"), (Edge::Bottom, "bottom"), (Edge::Left, "left"), (Edge::Right, "right")];
26
27    fn vertical(self) -> bool { matches!(self, Edge::Left | Edge::Right) }
28
29    /// The side of the dock icon its menu opens on: toward the canvas.
30    fn inward(self) -> Side {
31        match self { Edge::Top => Side::Bottom, Edge::Bottom => Side::Top, Edge::Left => Side::Right, Edge::Right => Side::Left }
32    }
33}
34
35/// The edge the taskbar is snapped to: bottom until it's moved.
36pub fn edge(cx: &Cx) -> Edge {
37    cx.shared("taskbar-edge").and_then(|s| Edge::ALL.iter().find(|(_, n)| *n == s)).map_or(Edge::Bottom, |(e, _)| *e)
38}
39
40/// How long a first press on × stays armed.
41const ARMED: f64 = 3.0;
42
43impl Taskbar {
44    fn load(cx: &Cx) -> Self {
45        let file = cx.dir.join("forgotten");
46        let forgotten = std::fs::read_to_string(&file).unwrap_or_default().lines().map(str::to_owned).collect();
47        Taskbar { forgotten, armed: None, file, menu: false }
48    }
49
50    fn armed(&self, slug: &str, now: f64) -> bool {
51        self.armed.as_ref().is_some_and(|(s, at)| s == slug && now - at < ARMED)
52    }
53
54    /// Arms `slug`'s ×, or forgets it if already armed. True when forgotten.
55    fn press_forget(&mut self, slug: &str) -> bool {
56        if !self.armed(slug, now()) { self.armed = Some((slug.to_owned(), now())); return false; }
57        self.armed = None;
58        self.forgotten.push(slug.to_owned());
59        let _ = std::fs::write(&self.file, self.forgotten.join("\n"));
60        true
61    }
62
63    fn remember(&mut self, slug: &str) {
64        self.forgotten.retain(|s| s != slug);
65        let _ = std::fs::write(&self.file, self.forgotten.join("\n"));
66    }
67}
68
69/// The library itself: the project whose tickets build this app.
70const LIBRARY: &str = "widgets";
71
72impl View for Taskbar {
73    fn view(&self, cx: &Cx) -> El {
74        let t = look::of(cx);
75        let active = cx.shared("project");
76        let edge = edge(cx);
77        let v = edge.vertical();
78        let item = |p: &Project| project(cx, p, active == Some(p.slug.as_str()), self.armed(&p.slug, cx.now), v);
79        // The separator line faces the canvas: [top, right, bottom, left].
80        let line = match edge { Edge::Bottom => [1.0, 0.0, 0.0, 0.0], Edge::Top => [0.0, 0.0, 1.0, 0.0], Edge::Left => [0.0, 1.0, 0.0, 0.0], Edge::Right => [0.0, 0.0, 0.0, 1.0] };
81        let mut bar = if v { col().py(8.0).px(6.0) } else { row().center_y().px(8.0) }
82            .w_full().h_full().gap(4.0).fill(t.card).border_sides(line, t.separator);
83        if let Some(p) = cx.data.projects.iter().find(|p| p.slug == LIBRARY) {
84            let sep = if v { el().w_full().h(1.0).my(4.0) } else { el().w(1.0).h(22.0).mx(4.0) };
85            bar = bar.child(item(p)).child(sep.fill(t.separator));
86        }
87        for p in cx.data.projects.iter().filter(|p| p.slug != LIBRARY && !self.forgotten.contains(&p.slug)) { bar = bar.child(item(p)); }
88        bar.child(add_button(cx)).child(el().grow(1.0)).child(dock_button(cx, edge, self.menu))
89            .child(if self.menu { dock_menu(cx, edge) } else { el() })
90    }
91}
92
93/// A window drawn small, with `edge` filled in: the taskbar on that edge.
94fn dock_glyph(t: &look::Look, edge: Edge) -> El {
95    let strip = match edge {
96        Edge::Top => el().absolute(0.0, 0.0).w_full().h(3.0),
97        Edge::Bottom => el().absolute(0.0, 6.0).w_full().h(3.0),
98        Edge::Left => el().absolute(0.0, 0.0).w(4.0).h_full(),
99        Edge::Right => el().absolute(9.0, 0.0).w(4.0).h_full(),
100    };
101    el().w(18.0).h(14.0).radius(3.0).border(1.5, t.text_secondary).padding(1.0).child(el().w_full().h_full().child(strip.radius(1.0).fill(t.text_secondary)))
102}
103
104/// The dock icon at the bar's far end: the edge it's on, opening `dock_menu`.
105fn dock_button(cx: &Cx, edge: Edge, open: bool) -> El {
106    let t = look::of(cx);
107    let b = row().key("move-taskbar").w(34.0).h(34.0).center().radius(6.0).role("button").label("Move taskbar")
108        .help("Move taskbar").hover(t.hover).on_press_tx(on(cx.id, |b: &mut Taskbar, _| b.menu = !b.menu))
109        .child(dock_glyph(&t, edge));
110    if open { b.fill(t.press) } else { b }
111}
112
113/// The four edges beside the dock icon, a check on the current one; a pick or a click outside closes it.
114fn dock_menu(cx: &Cx, edge: Edge) -> El {
115    let (t, id) = (look::of(cx), cx.id.to_owned());
116    let close = |h: &mut HostState, id: &str| if let Some(b) = get::<Taskbar>(h, id) { b.menu = false };
117    let mut list = ui::popover(&t, col().key("dock-menu").w(150.0).padding(4.0).gap(2.0))
118        .anchored_fit("move-taskbar", edge.inward(), Align::End, 4.0)
119        .modal(true, { let id = id.clone(); move |h: &mut HostState| close(h, &id) });
120    for (e, name) in Edge::ALL {
121        let id = id.clone();
122        let title = format!("{}{}", name[..1].to_uppercase(), &name[1..]);
123        list = list.child(row().key(format!("dock-{name}")).w_full().min_h(28.0).px(8.0).gap(10.0).center_y().radius(5.0)
124            .role("button").label(&title).hover(t.hover)
125            .on_press_tx(move |h: &mut HostState, _: &mut Tx| { share(h, "taskbar-edge", name); close(h, &id) })
126            .child(dock_glyph(&t, e)).child(text(title).font(t.label).color(t.text).grow(1.0))
127            .child(text(if e == edge { "✓" } else { "" }).font(t.label).color(t.accent)));
128    }
129    list
130}
131
132/// One project's button: its name, a badge counting its running and queued tickets (blue while one runs), and an
133/// underline when it's the shared "project", and a × to forget it (red while `armed`). The widgets project can't be forgotten.
134/// In a `vertical` sidebar it fills the width, with its badge and × at the right.
135fn project(cx: &Cx, p: &Project, active: bool, armed: bool, vertical: bool) -> El {
136    let t = look::of(cx);
137    let count = |s: &str| cx.data.tickets.iter().filter(|k| k.project == p.slug && k.state == s).count();
138    let (running, queued) = (count("running"), count("ready"));
139    let slug = p.slug.clone();
140    let mut b = row().key(format!("project-{}", p.slug)).h(34.0).px(10.0).gap(7.0).center_y().radius(6.0)
141        .role("button").label(&p.slug).help(format!("{}\n{}\n{running} running, {queued} queued", p.slug, p.path)).hover(t.hover)
142        .on_press_tx(move |h: &mut HostState, _: &mut Tx| share(h, "project", &slug))
143        .child(text(&p.slug).font(t.label).color(if active { t.text } else { t.text_secondary }).truncate().min_w(0.0));
144    if vertical { b = b.w_full().child(el().grow(1.0)); }
145    if p.slots == 0 { b = b.child(text("paused").font(t.label).color(t.text_secondary)); }
146    if running + queued > 0 {
147        b = b.child(row().min_h(16.0).px(5.0).radius(8.0).center().fill(if running > 0 { t.accent } else { t.control_off })
148            .child(text((running + queued).to_string()).font(t.label).color(if running > 0 { t.on_accent } else { t.text })));
149    }
150    if p.slug != LIBRARY { b = b.child(forget(cx, &p.slug, active, armed)); }
151    if active { b = b.fill(t.press).child(el().absolute(10.0, 31.0).w(14.0).h(2.0).radius(1.0).fill(t.accent)); }
152    b
153}
154
155/// The × on project `slug`'s button: arms on the first press, forgets on the second, and switches to
156/// the widgets desktop if `slug` is the `active` one.
157fn forget(cx: &Cx, slug: &str, active: bool, armed: bool) -> El {
158    let t = look::of(cx);
159    let (id, slug) = (cx.id.to_owned(), slug.to_owned());
160    ui::armed(&t, &format!("forget-{slug}"), &format!("Forget {slug}"), armed, "×", move |h: &mut HostState, _: &mut Tx| {
161        let Some(bar) = get::<Taskbar>(h, &id) else { return };
162        if bar.press_forget(&slug) && active { share(h, "project", LIBRARY) }
163    }).min_w(18.0).min_h(18.0).px(0.0).ml(-3.0).mr(-6.0).radius(4.0)
164}
165
166fn add_button(cx: &Cx) -> El {
167    let t = look::of(cx);
168    let id = cx.id.to_owned();
169    row().key("add-project").w(34.0).h(34.0).center().radius(6.0).role("button").label("Add project").help("Add project")
170        .hover(t.hover).child(text("+").font(t.title).color(t.text_secondary))
171        .on_press_tx(move |_: &mut HostState, tx: &mut Tx| {
172            let id = id.clone();
173            let options = FileDialogOptions { title: "Add project".into(), ..Default::default() };
174            tx.open_folder(options, move |h: &mut HostState, result, _| {
175                let Ok(Some(path)) = result else { return };
176                let name = path.file_name().map(|n| n.to_string_lossy().to_lowercase()).unwrap_or_default();
177                let slug: String = name.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }).collect();
178                let slug = slug.trim_matches('-');
179                if slug.is_empty() { return }
180                if let Some(bar) = get::<Taskbar>(h, &id) { bar.remember(slug) }
181                add_project(h, slug, &path);
182                share(h, "project", slug);
183            });
184        })
185}