xonecas.io
8447
Co

conveyor / commit effc09c

Starter kit: seed the template with the library made in the app

canvas (free cards per project), editor (files and images), library
(pick and add), taskbar (projects, add, forget), running indicator,
titlebar and root, all built with the widget builder.

Co-Authored-By: Claude Opus 5.5

sacenox2026-11-09 effc09c5cff43d40005ea3ddfdb52be6b425c950 parent ad60eef

7 files changed

templates/library/widgets/canvas.rs+166−20
@@ -1,7 +1,9 @@
11 //! A free canvas: new widgets land where they were asked for, and a drag on one (outside its
2-//! own controls) moves it. Root puts it under the title bar.
2+//! own controls) moves it. Its right edge, bottom edge and corner resize it, and a double
3+//! click (or the header's □) maximizes it to the whole canvas. Cards stay inside the canvas
4+//! as it resizes. Root shows one per project, under the title bar.
35 use super::api::*;
4-use rune::{Drag, El, Phase, Tx, el, text, tok};
6+use rune::{Cursor, Drag, El, Phase, Shape, Tx, el, row, text, tok};
57 use std::path::PathBuf;
68
79 pub const WIDGET: Widget = Widget { title: "Canvas", size: (0.0, 0.0), new: |cx| Box::new(Canvas::load(cx)) };
@@ -13,67 +15,211 @@ struct Child {
1315 y: f32,
1416 w: f32,
1517 h: f32,
18+ /// Fills the canvas, keeping its spot and size for when it's restored.
19+ max: bool,
1620 }
1721
22+/// The smallest a card resizes to.
23+const MIN: (f32, f32) = (200.0, 120.0);
24+
25+/// What a drag on a card does: move it, or resize it from an edge or the corner.
26+#[derive(Clone, Copy, PartialEq)]
27+enum Grip { Move, Right, Bottom, Corner }
28+
1829 pub struct Canvas {
1930 children: Vec<Child>,
2031 file: PathBuf,
21- /// Where the dragged child was when the drag started.
32+ /// Where the dragged child was (or its size, when resizing) when the drag started.
2233 grab: Option<(f32, f32)>,
34+ /// The canvas's laid-out size, kept as a "size" file: the app reloads widgets without
35+ /// laying out again, so `on_layout` only speaks when the size changes.
36+ size: (f32, f32),
37+ /// The taskbar's Library toggle hid this desktop's library cards; kept as a "library-hidden" file.
38+ library_hidden: bool,
2339 }
2440
2541 impl Canvas {
26- /// children: one line per child, "kind key x y w h".
42+ /// children: one line per child, "kind key x y w h max".
2743 fn load(cx: &Cx) -> Self {
2844 let file = cx.dir.join("children");
2945 let children = std::fs::read_to_string(&file).unwrap_or_default().lines().filter_map(|l| {
3046 let f: Vec<&str> = l.split(' ').collect();
3147 let n = |i: usize| f.get(i)?.parse::<f32>().ok();
32- Some(Child { kind: f.first()?.to_string(), key: f.get(1)?.to_string(), x: n(2)?, y: n(3)?, w: n(4)?, h: n(5)? })
48+ Some(Child { kind: f.first()?.to_string(), key: f.get(1)?.to_string(), x: n(2)?, y: n(3)?, w: n(4)?, h: n(5)?, max: f.get(6) == Some(&"1") })
3349 }).collect();
34- Canvas { children, file, grab: None }
50+ let library_hidden = cx.dir.join("library-hidden").exists();
51+ let size = std::fs::read_to_string(cx.dir.join("size")).ok().and_then(|s| {
52+ let (w, h) = s.split_once(' ')?;
53+ Some((w.parse().ok()?, h.parse().ok()?))
54+ }).unwrap_or((0.0, 0.0));
55+ Canvas { children, file, grab: None, size, library_hidden }
3556 }
3657
3758 fn save(&self) {
38- let lines: String = self.children.iter().map(|c| format!("{} {} {} {} {} {}\n", c.kind, c.key, c.x, c.y, c.w, c.h)).collect();
59+ let lines: String = self.children.iter().map(|c| format!("{} {} {} {} {} {} {}\n", c.kind, c.key, c.x, c.y, c.w, c.h, c.max as u8)).collect();
3960 let _ = std::fs::write(&self.file, lines);
4061 }
62+
63+ /// Where child `c` shows: its spot, pulled back inside the canvas.
64+ fn fit(&self, c: &Child) -> (f32, f32) {
65+ if self.size.0 <= 0.0 { return (c.x, c.y) }
66+ (c.x.min(self.size.0 - c.w).max(0.0), c.y.min(self.size.1 - c.h).max(0.0))
67+ }
68+
69+ /// Child `c`'s shown rect: the whole canvas when maximized, else its size at its fitted spot.
70+ fn rect(&self, c: &Child) -> (f32, f32, f32, f32) {
71+ if c.max && self.size.0 > 0.0 { return (0.0, 0.0, self.size.0, self.size.1) }
72+ let (x, y) = self.fit(c);
73+ (x, y, c.w, c.h)
74+ }
75+
76+ /// Maximizes the child keyed `key`, or restores it.
77+ pub fn toggle_max(&mut self, key: &str) {
78+ if let Some(c) = self.children.iter_mut().find(|c| c.key == key) { c.max = !c.max }
79+ self.save();
80+ }
81+
82+ /// Adds a `kind` of size `size` with its top-left at `at`.
83+ pub fn add(&mut self, kind: &str, at: (f32, f32), (w, h): (f32, f32)) {
84+ let key = (1..).map(|i| format!("{kind}{i}")).find(|k| !self.children.iter().any(|c| &c.key == k)).unwrap();
85+ self.children.push(Child { kind: kind.into(), key, x: at.0, y: at.1, w, h, max: false });
86+ self.save();
87+ }
88+
89+ /// Whether a `kind` is on the canvas.
90+ pub fn has(&self, kind: &str) -> bool {
91+ self.children.iter().any(|c| c.kind == kind)
92+ }
93+
94+ /// Whether a library card shows here.
95+ pub fn library_shown(&self) -> bool {
96+ !self.library_hidden && self.has("library")
97+ }
98+
99+ /// Hides or shows this desktop's library cards, putting one in the top-left if showing and there's none.
100+ pub fn toggle_library(&mut self) {
101+ let shown = self.library_shown();
102+ if !shown && !self.has("library") { self.add("library", (24.0, 24.0), super::library::WIDGET.size) }
103+ self.library_hidden = shown;
104+ let flag = self.file.with_file_name("library-hidden");
105+ let _ = if shown { std::fs::write(flag, "") } else { std::fs::remove_file(flag) };
106+ }
107+
108+ /// Takes the child keyed `key` off the canvas.
109+ pub fn remove(&mut self, key: &str) {
110+ self.children.retain(|c| c.key != key);
111+ self.save();
112+ }
113+
114+ /// Adds a `kind` beside the child keyed `beside`: to its right if it fits, else to its left,
115+ /// stepping down past anything already there.
116+ pub fn add_beside(&mut self, kind: &str, size: (f32, f32), beside: &str) {
117+ let Some(b) = self.children.iter().find(|c| c.key == beside) else { return };
118+ let (bx, by) = self.fit(b);
119+ let right = bx + b.w + 16.0;
120+ let x = if self.size.0 <= 0.0 || right + size.0 <= self.size.0 { right } else { (bx - 16.0 - size.0).max(0.0) };
121+ let mut y = by;
122+ while self.children.iter().any(|c| c.x == x && c.y == y) { y += 28.0; }
123+ self.add(kind, (x, y), size);
124+ }
41125 }
42126
43127 impl View for Canvas {
44128 fn view(&self, cx: &Cx) -> El {
45129 let t = tok::theme(true);
46- let mut canvas = el().w_full().h_full().fill(t.bg);
130+ let id = cx.id.to_owned();
131+ let mut canvas = el().w_full().h_full().fill(t.bg)
132+ .on_layout(move |h: &mut HostState, r: [f32; 4]| if let Some(c) = get::<Canvas>(h, &id) {
133+ c.size = (r[2], r[3]);
134+ let _ = std::fs::write(c.file.with_file_name("size"), format!("{} {}", r[2], r[3]));
135+ });
47136 if self.children.is_empty() {
48137 canvas = canvas.center().child(text("Ctrl+click anywhere to make a widget").color(t.text_secondary));
49138 }
50- for c in &self.children {
51- canvas = canvas.child(el().key(format!("card-{}", c.key)).w(c.w).h(c.h).absolute(c.x, c.y).radius(10.0).fill(t.card).padding(12.0)
139+ // A discarded build's kinds go away, and come back if it's built again.
140+ // The taskbar's Library toggle hides library cards.
141+ let hidden = |c: &&Child| c.kind == "library" && self.library_hidden;
142+ for c in self.children.iter().filter(|c| cx.kinds().iter().any(|(n, _)| *n == c.kind)).filter(|c| !hidden(c)) {
143+ let (x, y, w, h) = self.rect(c);
144+ let radius = if c.max { 0.0 } else { 10.0 };
145+ let grip = |name: &str, g: Grip, cursor: Cursor| el().key(format!("resize-{name}")).cursor(cursor).on_drag(drag(cx.id, c.key.clone(), g));
146+ let mut card = el().key(format!("card-{}", c.key)).w(w).h(h).absolute(x, y).radius(radius).clip_rounded(radius).fill(t.card).padding(12.0)
52147 .child(cx.child(&c.kind, &c.key))
53- .on_drag(drag(cx.id, c.key.clone())));
148+ .on_drag(drag(cx.id, c.key.clone(), Grip::Move));
149+ if !c.max {
150+ let corner = Shape::new().stroke(vec![[13.0, 5.0], [5.0, 13.0]], 1.5, t.text_secondary).stroke(vec![[13.0, 9.0], [9.0, 13.0]], 1.5, t.text_secondary);
151+ card = card.child(grip("right", Grip::Right, Cursor::ResizeColumn).pin(None, Some(0.0), Some(0.0), Some(16.0)).w(6.0))
152+ .child(grip("bottom", Grip::Bottom, Cursor::ResizeRow).pin(Some(0.0), None, Some(16.0), Some(0.0)).h(6.0))
153+ .child(grip("corner", Grip::Corner, Cursor::Crosshair).pin(None, None, Some(0.0), Some(0.0)).w(16.0).h(16.0).shape(corner));
154+ }
155+ canvas = canvas.child(card);
54156 }
55157 canvas
56158 }
57159
160+ /// The shown desktop tells the taskbar's Library toggle, through the shared "library", whether its library shows.
161+ fn update(&mut self, cx: &Cx) {
162+ let active = cx.id.rsplit_once('.').is_some_and(|(_, k)| k == super::root::desktop(cx));
163+ let v = if self.library_shown() { "shown" } else { "hidden" };
164+ if active && cx.shared("library") != Some(v) { cx.act(move |l| l.share("library", v)) }
165+ }
166+
58167 fn mount(&mut self, kind: &str, at: (f32, f32), cx: &Cx) -> bool {
59168 let (w, h) = cx.kinds().iter().find(|(n, _)| *n == kind).map(|(_, w)| w.size).filter(|s| s.0 > 0.0).unwrap_or((320.0, 240.0));
60- let key = (1..).map(|i| format!("{kind}{i}")).find(|k| !self.children.iter().any(|c| &c.key == k)).unwrap();
61- self.children.push(Child { kind: kind.into(), key, x: at.0, y: at.1, w, h });
62- self.save();
169+ self.add(kind, at, (w, h));
63170 true
64171 }
65172 }
66173
67-fn drag(id: &str, key: String) -> impl Fn(&mut HostState, &mut Drag, &mut Tx) + 'static {
174+/// A □ for a card's header that maximizes the card (instance `cx.id`) to its canvas, or restores it.
175+pub fn maximize(cx: &Cx) -> El {
176+ let t = tok::theme(true);
177+ let id = cx.id.to_owned();
178+ row().key("maximize").w(24.0).h(24.0).center().radius(6.0).role("button").label("Maximize").help("Maximize or restore").hover(t.press)
179+ .child(text("□").font(tok::type_::LABEL).color(t.text_secondary))
180+ .on_press_tx(move |h: &mut HostState, _: &mut Tx| {
181+ let Some((parent, key)) = id.rsplit_once('.') else { return };
182+ if let Some(canvas) = get::<Canvas>(h, parent) { canvas.toggle_max(key) }
183+ })
184+}
185+
186+/// A × for a card's header that takes the card (instance `cx.id`) off its canvas.
187+pub fn close(cx: &Cx, label: &str) -> El {
188+ let t = tok::theme(true);
189+ let id = cx.id.to_owned();
190+ row().key("close").w(24.0).h(24.0).center().radius(6.0).role("button").label(label).help("Close").hover(t.press)
191+ .child(text("×").font(tok::type_::BODY).color(t.text_secondary))
192+ .on_press_tx(move |h: &mut HostState, _: &mut Tx| {
193+ let Some((parent, key)) = id.rsplit_once('.') else { return };
194+ if let Some(canvas) = get::<Canvas>(h, parent) { canvas.remove(key) }
195+ })
196+}
197+
198+/// A drag on card `key`: a double click maximizes or restores it; otherwise `g` moves or resizes it,
199+/// unless it's maximized.
200+fn drag(id: &str, key: String, g: Grip) -> impl Fn(&mut HostState, &mut Drag, &mut Tx) + 'static {
68201 let id = id.to_owned();
69202 move |h: &mut HostState, d: &mut Drag, _: &mut Tx| {
70203 let Some(canvas) = get::<Canvas>(h, &id) else { return };
71- let Some(c) = canvas.children.iter_mut().find(|c| c.key == key) else { return };
204+ let Some(i) = canvas.children.iter().position(|c| c.key == key) else { return };
205+ let ((x, y, _, _), size) = (canvas.rect(&canvas.children[i]), canvas.size);
206+ let c = &mut canvas.children[i];
207+ // Up to the canvas's far edge, once its size is known.
208+ let room = |s: f32, at: f32| if s > 0.0 { s - at } else { f32::INFINITY };
209+ let w = |a: f32| (a + d.dx).min(room(size.0, x)).max(MIN.0);
210+ let h = |b: f32| (b + d.dy).min(room(size.1, y)).max(MIN.1);
72211 match (d.phase, canvas.grab) {
73- (Phase::Down, _) => canvas.grab = Some((c.x, c.y)),
74- (Phase::Move, Some((x, y))) => (c.x, c.y) = ((x + d.dx).max(0.0), (y + d.dy).max(0.0)),
75- (Phase::Up, Some((x, y))) => {
76- if d.cancelled() { (c.x, c.y) = (x, y) }
212+ (Phase::Down, _) if g == Grip::Move && d.clicks == 2 => { canvas.grab = None; canvas.toggle_max(&key) }
213+ _ if c.max => {}
214+ (Phase::Down, _) => { (c.x, c.y) = (x, y); canvas.grab = Some(if g == Grip::Move { (x, y) } else { (c.w, c.h) }) }
215+ (Phase::Move, Some((a, b))) => match g {
216+ Grip::Move => (c.x, c.y) = ((a + d.dx).max(0.0), (b + d.dy).max(0.0)),
217+ Grip::Right => c.w = w(a),
218+ Grip::Bottom => c.h = h(b),
219+ Grip::Corner => (c.w, c.h) = (w(a), h(b)),
220+ },
221+ (Phase::Up, Some((a, b))) => {
222+ if d.cancelled() { if g == Grip::Move { (c.x, c.y) = (a, b) } else { (c.w, c.h) = (a, b) } }
77223 canvas.grab = None;
78224 canvas.save();
79225 }
templates/library/widgets/editor.rs+235−0
@@ -0,0 +1,235 @@
1+//! A floating code editor: the project's files as a tree on the left, the picked file on the
2+//! right. Text edits in place (Ctrl+S or Save writes it); PNG, JPEG and SVG show as images.
3+//! The project is the one whose desktop this card is on.
4+use super::{api::*, canvas};
5+use rune::{El, Family, Image, ImageCache, Key, KeyEvent, ScrollSpec, SurfaceFit, TextEdit, Tx, col, el, oklch, row, text, text_input, tok};
6+use std::{collections::{BTreeSet, HashMap}, path::{Path, PathBuf}, sync::Arc};
7+
8+pub const WIDGET: Widget = Widget { title: "Editor", size: (860.0, 540.0), new: |cx| Box::new(Editor::load(cx)) };
9+
10+/// Files past this (images aside) show a note instead of their contents.
11+const MAX_BYTES: u64 = 2 << 20;
12+
13+enum Content {
14+ None,
15+ /// In `Editor::text`.
16+ Text,
17+ /// Decoding, then decoded.
18+ Loading(Image),
19+ Image(Image),
20+ Note(String),
21+}
22+
23+pub struct Editor {
24+ /// The project's folder, and its listings: (name, is_dir), refreshed every 2 s.
25+ root: PathBuf,
26+ listings: HashMap<PathBuf, Vec<(String, bool)>>,
27+ listed_at: f64,
28+ expanded: BTreeSet<PathBuf>,
29+ file: Option<PathBuf>,
30+ content: Content,
31+ /// The open text, what's on disk, and what the draft file last got.
32+ text: TextEdit,
33+ saved: String,
34+ drafted: String,
35+ images: ImageCache,
36+ dir: PathBuf,
37+}
38+
39+impl Editor {
40+ /// "state": the open file on the first line, then one expanded folder per line. "draft": unsaved text.
41+ fn load(cx: &Cx) -> Self {
42+ let state = std::fs::read_to_string(cx.dir.join("state")).unwrap_or_default();
43+ let mut lines = state.lines().map(PathBuf::from);
44+ let file = lines.next().filter(|p| !p.as_os_str().is_empty());
45+ let mut e = Editor { root: project_dir(cx), listings: HashMap::new(), listed_at: 0.0, expanded: lines.collect(),
46+ file: None, content: Content::None, text: TextEdit::new(""), saved: String::new(), drafted: String::new(), images: ImageCache::new(Arc::new(|| {})), dir: cx.dir.clone() };
47+ let draft = std::fs::read_to_string(e.dir.join("draft"));
48+ if let Some(f) = file { e.open(f) }
49+ if let (Content::Text, Ok(draft)) = (&e.content, draft) { e.text.text = draft }
50+ e
51+ }
52+
53+ fn save_state(&self) {
54+ let open = self.file.as_ref().map(|f| f.display().to_string()).unwrap_or_default();
55+ let lines: String = self.expanded.iter().map(|d| format!("{}\n", d.display())).collect();
56+ let _ = std::fs::write(self.dir.join("state"), format!("{open}\n{lines}"));
57+ }
58+
59+ fn open(&mut self, path: PathBuf) {
60+ let _ = std::fs::remove_file(self.dir.join("draft"));
61+ let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_lowercase();
62+ let size = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0);
63+ let image = matches!(ext.as_str(), "png" | "jpg" | "jpeg" | "svg" | "svgz");
64+ self.content = match if size > MAX_BYTES && !image { Ok(vec![]) } else { std::fs::read(&path) } {
65+ Err(e) => Content::Note(format!("Can't read it: {e}")),
66+ Ok(_) if size > MAX_BYTES && !image => Content::Note(format!("Too large to open here ({})", kb(size))),
67+ Ok(b) if image => Content::Loading(self.images.load(b)),
68+ Ok(b) => match String::from_utf8(b) {
69+ Ok(s) if !s.contains('\0') => { (self.text, self.drafted, self.saved) = (TextEdit::new(s.clone()), s.clone(), s); Content::Text }
70+ _ => Content::Note(format!("Binary file ({})", kb(size))),
71+ },
72+ };
73+ (self.text.anchor, self.text.focus) = (0, 0);
74+ self.file = Some(path);
75+ self.save_state();
76+ }
77+
78+ fn save(&mut self) {
79+ let (Some(f), Content::Text) = (&self.file, &self.content) else { return };
80+ if std::fs::write(f, &self.text.text).is_ok() { self.saved = self.text.text.clone(); }
81+ }
82+
83+ fn toggle(&mut self, dir: PathBuf) {
84+ if !self.expanded.remove(&dir) { self.listings.insert(dir.clone(), list(&dir)); self.expanded.insert(dir); }
85+ self.save_state();
86+ }
87+
88+ fn modified(&self) -> bool {
89+ matches!(self.content, Content::Text) && self.text.text != self.saved
90+ }
91+}
92+
93+impl View for Editor {
94+ fn update(&mut self, cx: &Cx) {
95+ // A decoded image shows at once: the no-op act asks for a render.
96+ if let Content::Loading(i) = &self.content && i.is_ready() { self.content = Content::Image(i.clone()); cx.act(|_| {}) }
97+ let root = project_dir(cx);
98+ if root != self.root || cx.now - self.listed_at > 2.0 { (self.root, self.listed_at) = (root, cx.now); self.listings.clear(); }
99+ for d in std::iter::once(&self.root).chain(self.expanded.iter().filter(|d| d.starts_with(&self.root))) {
100+ if !self.listings.contains_key(d) { self.listings.insert(d.clone(), list(d)); }
101+ }
102+ // Unsaved typing goes to "draft" so a restart keeps it.
103+ if matches!(self.content, Content::Text) && self.text.text != self.drafted {
104+ self.drafted = self.text.text.clone();
105+ let draft = self.dir.join("draft");
106+ let _ = if self.text.text == self.saved { std::fs::remove_file(draft) } else { std::fs::write(draft, &self.text.text) };
107+ }
108+ }
109+
110+ fn view(&self, cx: &Cx) -> El {
111+ let t = tok::theme(true);
112+ let mut tree = col().w_full();
113+ if self.listings.contains_key(&self.root) { tree = self.tree(cx, tree, &self.root, 0) }
114+ else { tree = tree.child(text(format!("No folder at {}", self.root.display())).font(tok::type_::LABEL).color(t.text_secondary).wrap()) }
115+ col().w_full().h_full().gap(8.0)
116+ .child(self.header(cx))
117+ .child(el().w_full().h(1.0).fill(t.separator))
118+ .child(row().w_full().grow(1.0).min_h(0.0).gap(8.0)
119+ .child(col().key("tree").w(220.0).h_full().min_h(0.0).scroll(ScrollSpec { stick_bottom: false }).child(tree))
120+ .child(el().w(1.0).h_full().fill(t.separator))
121+ .child(col().key("content").grow(1.0).min_w(0.0).h_full().min_h(0.0).child(self.content(cx))))
122+ }
123+}
124+
125+impl Editor {
126+ /// The project, the open file's path under it with a dot while modified, a Save button, and ×.
127+ fn header(&self, cx: &Cx) -> El {
128+ let t = tok::theme(true);
129+ let project = cx.data.projects.iter().find(|p| Path::new(&p.path) == self.root).map_or("Editor", |p| p.slug.as_str());
130+ let path = self.file.as_ref().map(|f| rel(&self.root, f)).unwrap_or_default();
131+ let mut h = row().key("header").w_full().center_y().gap(8.0)
132+ .child(text(project).font(tok::type_::TITLE).color(t.text))
133+ .child(text(path).font(tok::type_::LABEL).color(t.text_secondary).truncate().min_w(0.0).shrink());
134+ if self.modified() { h = h.child(text("●").font(tok::type_::LABEL).color(oklch(0.8, 0.14, 80.0))); }
135+ h = h.child(el().grow(1.0));
136+ if let Content::Text = self.content {
137+ let before = self.text.text.get(..self.text.focus).unwrap_or("");
138+ let col_n = before.len() - before.rfind('\n').map_or(0, |i| i + 1) + 1;
139+ h = h.child(text(format!("Ln {}, Col {col_n}", before.matches('\n').count() + 1)).font(tok::type_::LABEL).color(t.text_secondary));
140+ }
141+ if let Content::Image(i) = &self.content && let Some([w, ht]) = i.size() {
142+ h = h.child(text(format!("{w}×{ht}")).font(tok::type_::LABEL).color(t.text_secondary));
143+ }
144+ if self.modified() {
145+ h = h.child(row().key("save").h(24.0).px(10.0).center().radius(6.0).role("button").label("Save").help("Save (Ctrl+S)")
146+ .fill(t.press).hover(t.hover).child(text("Save").font(tok::type_::LABEL).color(t.text))
147+ .on_press_tx(on(cx.id, |e: &mut Editor, _| e.save())));
148+ }
149+ h.child(canvas::maximize(cx)).child(canvas::close(cx, "Close editor"))
150+ }
151+
152+ /// `dir`'s entries at `depth`, folders first, with expanded folders' entries under them.
153+ fn tree(&self, cx: &Cx, mut tree: El, dir: &Path, depth: usize) -> El {
154+ let t = tok::theme(true);
155+ for (name, is_dir) in self.listings.get(dir).into_iter().flatten() {
156+ let path = dir.join(name);
157+ let open = *is_dir && self.expanded.contains(&path);
158+ let picked = self.file.as_ref() == Some(&path);
159+ let glyph = if !is_dir { " " } else if open { "▾" } else { "▸" };
160+ let p = path.clone();
161+ tree = tree.child(row().key(format!("node-{}", rel(&self.root, &path).replace('/', "|"))).w_full().h(24.0)
162+ .pl(6.0 + depth as f32 * 14.0).pr(6.0).gap(6.0).center_y().radius(5.0).role("button").label(name.as_str())
163+ .fill(if picked { t.press } else { t.card }).hover(t.hover)
164+ .on_press_tx(on(cx.id, move |e: &mut Editor, _| if p.is_dir() { e.toggle(p.clone()) } else { e.open(p.clone()) }))
165+ .child(text(glyph).font(tok::type_::LABEL).color(t.text_secondary).w(10.0))
166+ .child(text(name.as_str()).font(tok::type_::LABEL).color(if picked || *is_dir { t.text } else { t.text_secondary }).truncate()));
167+ if open { tree = self.tree(cx, tree, &path, depth + 1) }
168+ }
169+ tree
170+ }
171+
172+ fn content(&self, cx: &Cx) -> El {
173+ let t = tok::theme(true);
174+ let note = |s: &str| col().w_full().h_full().center().child(text(s).color(t.text_secondary));
175+ match &self.content {
176+ Content::None => note("Pick a file on the left"),
177+ Content::Note(s) => note(s),
178+ Content::Loading(_) => note("Loading…"),
179+ Content::Image(i) => match (i.size(), i.error()) {
180+ (_, Some(e)) => note(&format!("Can't show this image: {e}")),
181+ (None, _) => note("Can't show this image"),
182+ (Some([w, h]), _) => col().w_full().h_full().center().child(el().key("image").w_full().h_full()
183+ .max_w(w as f32).max_h(h as f32).pixels_fit(i.pixels(), SurfaceFit::Fit)),
184+ },
185+ Content::Text => col().key("code").w_full().h_full().min_h(0.0).scroll(ScrollSpec { stick_bottom: false })
186+ .child(text_input(&self.text, tok::type_::BODY.family(Family::SystemMono)).w_full().color(t.text)
187+ .on_edit(edit(cx.id, |e: &mut Editor| &mut e.text))
188+ .on_submit(on(cx.id, |e: &mut Editor, _| newline(&mut e.text)))
189+ .on_input_key(keys(cx.id))),
190+ }
191+ }
192+}
193+
194+/// Ctrl+S saves; Tab indents four spaces.
195+fn keys(id: &str) -> impl Fn(&mut HostState, &KeyEvent, &mut Tx) -> bool + 'static {
196+ let id = id.to_owned();
197+ move |h: &mut HostState, k: &KeyEvent, _: &mut Tx| {
198+ let Some(e) = get::<Editor>(h, &id) else { return false };
199+ if k.is_command('s') { e.save(); return true }
200+ if k.key == Key::Tab && !k.mods.shift { e.text.insert(" "); return true }
201+ false
202+ }
203+}
204+
205+/// Return: a line break that keeps the current line's indent.
206+fn newline(edit: &mut TextEdit) {
207+ let before = edit.text.get(..edit.focus.min(edit.anchor)).unwrap_or("");
208+ let line = &before[before.rfind('\n').map_or(0, |i| i + 1)..];
209+ let indent: String = line.chars().take_while(|c| *c == ' ' || *c == '\t').collect();
210+ edit.insert(&format!("\n{indent}"));
211+}
212+
213+/// The folder of the project whose desktop holds this card: `root.canvas-<slug>.<key>`, or the widgets project on `root.canvas`.
214+fn project_dir(cx: &Cx) -> PathBuf {
215+ let desktop = cx.id.rsplit('.').nth(1).unwrap_or("");
216+ let slug = desktop.strip_prefix("canvas-").unwrap_or("widgets");
217+ cx.data.projects.iter().find(|p| p.slug == slug).map(|p| PathBuf::from(&p.path)).unwrap_or_default()
218+}
219+
220+/// A folder's entries, folders first then files, by name; `.git` left out.
221+fn list(dir: &Path) -> Vec<(String, bool)> {
222+ let mut v: Vec<(String, bool)> = std::fs::read_dir(dir).into_iter().flatten().flatten()
223+ .map(|e| (e.file_name().to_string_lossy().into_owned(), e.path().is_dir()))
224+ .filter(|(n, _)| n != ".git").collect();
225+ v.sort_by_key(|(n, d)| (!d, n.to_lowercase()));
226+ v
227+}
228+
229+fn rel(root: &Path, p: &Path) -> String {
230+ p.strip_prefix(root).unwrap_or(p).display().to_string()
231+}
232+
233+fn kb(n: u64) -> String {
234+ if n < 1 << 20 { format!("{:.1} KB", n as f64 / 1024.0) } else { format!("{:.1} MB", n as f64 / 1048576.0) }
235+}
templates/library/widgets/library.rs+51−0
@@ -0,0 +1,51 @@
1+//! The widget library as a floating list: every kind, its file and size. A placeable kind has a
2+//! + that drops a new one on the canvas beside this card, and × closes the card.
3+use super::{api::*, canvas::{self, Canvas}};
4+use rune::{El, ScrollSpec, Tx, col, el, oklch, row, text, tok};
5+
6+pub const WIDGET: Widget = Widget { title: "Library", size: (280.0, 380.0), new: |_| Box::new(Library) };
7+
8+pub struct Library;
9+
10+impl View for Library {
11+ fn view(&self, cx: &Cx) -> El {
12+ let t = tok::theme(true);
13+ let kinds = cx.kinds();
14+ let mut list = col().w_full().gap(2.0);
15+ for (name, w) in kinds { list = list.child(item(cx, name, w)); }
16+ col().w_full().h_full().gap(8.0)
17+ .child(row().key("header").w_full().center_y().gap(8.0)
18+ .child(text("Library").font(tok::type_::TITLE).color(t.text))
19+ .child(el().grow(1.0))
20+ .child(text(format!("{} widgets", kinds.len())).font(tok::type_::LABEL).color(t.text_secondary))
21+ .child(canvas::maximize(cx))
22+ .child(canvas::close(cx, "Close library")))
23+ .child(el().w_full().h(1.0).fill(t.separator))
24+ .child(col().key("kinds").w_full().grow(1.0).min_h(0.0).scroll(ScrollSpec { stick_bottom: false }).child(list))
25+ }
26+}
27+
28+/// One kind: a glyph, its title, `name.rs` and size (or "layout" when it only fills a parent),
29+/// and a + when the canvas can take one.
30+fn item(cx: &Cx, name: &'static str, w: &Widget) -> El {
31+ let t = tok::theme(true);
32+ let placeable = w.size.0 > 0.0 && w.size.1 > 0.0;
33+ let detail = if placeable { format!("{name}.rs · {}×{}", w.size.0, w.size.1) } else { format!("{name}.rs · layout") };
34+ let glyph = text(if placeable { "◆" } else { "▤" }).color(if placeable { oklch(0.72, 0.14, 250.0) } else { t.text_secondary });
35+ let mut r = row().key(format!("kind-{name}")).w_full().h(44.0).px(8.0).gap(10.0).center_y().radius(6.0).hover(t.hover)
36+ .child(glyph)
37+ .child(col().grow(1.0).min_w(0.0).gap(2.0)
38+ .child(text(w.title).font(tok::type_::BODY).color(t.text).truncate())
39+ .child(text(detail).font(tok::type_::LABEL).color(t.text_secondary).truncate()));
40+ if placeable {
41+ let (id, size) = (cx.id.to_owned(), w.size);
42+ r = r.child(row().key(format!("add-{name}")).w(28.0).h(28.0).center().radius(6.0).role("button")
43+ .label(format!("Add {}", w.title)).help(format!("Add {} to the canvas", w.title)).hover(t.press)
44+ .child(text("+").font(tok::type_::TITLE).color(t.text_secondary))
45+ .on_press_tx(move |h: &mut HostState, _: &mut Tx| {
46+ let Some((parent, key)) = id.rsplit_once('.') else { return };
47+ if let Some(canvas) = get::<Canvas>(h, parent) { canvas.add_beside(name, size, key) }
48+ }));
49+ }
50+ r
51+}
templates/library/widgets/root.rs+13−3
@@ -1,5 +1,5 @@
1-//! The whole window: the app draws this widget and nothing else. By default, a title bar over
2-//! a free canvas. Change it into anything: a sidebar and panes, tabs, tiling.
1+//! The whole window: the app draws this widget and nothing else. A title bar, the shared
2+//! "project"'s own canvas (its desktop), and the taskbar along the bottom.
33 use super::api::*;
44 use rune::{El, col};
55
@@ -11,6 +11,16 @@ impl View for Root {
1111 fn view(&self, cx: &Cx) -> El {
1212 col().w_full().h_full()
1313 .child(col().w_full().h(36.0).child(cx.child("titlebar", "titlebar")))
14- .child(col().w_full().grow(1.0).min_h(0.0).child(cx.child("canvas", "canvas")))
14+ .child(col().w_full().grow(1.0).min_h(0.0).child(cx.child("canvas", &desktop(cx))))
15+ .child(col().w_full().h(44.0).child(cx.child("taskbar", "taskbar")))
16+ }
17+}
18+
19+/// The key of the shared "project"'s canvas under root. The widgets project (or none picked) keeps
20+/// the original "canvas".
21+pub fn desktop(cx: &Cx) -> String {
22+ match cx.shared("project") {
23+ Some(p) if p != "widgets" => format!("canvas-{p}"),
24+ _ => "canvas".into(),
1525 }
1626 }
templates/library/widgets/running.rs+43−0
@@ -0,0 +1,43 @@
1+//! A compact running indicator: a conveyor belt that moves while any ticket runs, and how many do.
2+//! Hover lists them. The title bar puts it at its center.
3+use super::api::*;
4+use rune::{El, LineCap, Shape, el, oklch, row, text, tok};
5+
6+pub const WIDGET: Widget = Widget { title: "Running", size: (0.0, 0.0), new: |_| Box::new(Running) };
7+
8+pub struct Running;
9+
10+impl View for Running {
11+ fn view(&self, cx: &Cx) -> El {
12+ let t = tok::theme(true);
13+ let running: Vec<&Ticket> = cx.data.tickets.iter().filter(|k| k.state == "running").collect();
14+ let on = !running.is_empty();
15+ if on { cx.animate(); }
16+ let color = if on { oklch(0.72, 0.14, 250.0) } else { t.text_secondary };
17+ let help = if on { running.iter().map(|k| format!("{} #{} {}", k.project, k.id, k.title)).collect::<Vec<_>>().join("\n") } else { "Nothing running".into() };
18+ let b = row().key("running").h(28.0).px(8.0).gap(6.0).center_y().radius(6.0).hover(t.hover).help(help)
19+ .child(el().key("belt").w(26.0).h(18.0).shape(belt(if on { (cx.now % 600.0) as f32 } else { 0.0 }, color)));
20+ if on { b.child(text(running.len().to_string()).font(tok::type_::LABEL).color(t.text)) } else { b }
21+ }
22+}
23+
24+/// A belt (a stadium with two rollers) carrying packages, in a 26×18 box. `t` seconds moves it.
25+fn belt(t: f32, color: rune::Color) -> Shape {
26+ let (l, r, y, rad) = (7.0, 19.0, 13.0, 3.5);
27+ let arc = |cx: f32, from: f32| (0..=8).map(move |i| { let a = (from + i as f32 * 22.5).to_radians(); [cx + rad * a.cos(), y + rad * a.sin()] });
28+ let stadium: Vec<[f32; 2]> = arc(r, -90.0).chain(arc(l, 90.0)).collect();
29+ let mut s = Shape::new().stroke_with(stadium, true, 1.4, LineCap::Round, color);
30+ for c in [l, r] {
31+ let a = -t * 4.0;
32+ let (dx, dy) = (1.6 * a.cos(), 1.6 * a.sin());
33+ s = s.line([c - dx, y - dy], [c + dx, y + dy], 1.2, LineCap::Round, color);
34+ }
35+ // Packages 10 apart sliding right, cut off where they leave the belt.
36+ let shift = (t * 6.0) % 10.0;
37+ for k in 0..3 {
38+ let x0 = (k as f32 * 10.0 - 7.0 + shift).max(3.5);
39+ let x1 = (k as f32 * 10.0 - 2.0 + shift).min(22.5);
40+ if x1 - x0 > 0.5 { s = s.fill(vec![[x0, 3.5], [x1, 3.5], [x1, 8.5], [x0, 8.5]], color); }
41+ }
42+ s
43+}
templates/library/widgets/taskbar.rs+130−0
@@ -0,0 +1,130 @@
1+//! A taskbar along the bottom of the window: the widgets project pinned first, then every other
2+//! project, and a button that adds one. The library toggle sits beside the widgets project. A press shares "project", and root switches to its canvas.
3+//! A project's × forgets it from the bar: the first press arms it (red), a second within `ARMED` seconds forgets.
4+use super::{api::*, canvas::Canvas};
5+use rune::{El, FileDialogOptions, Tx, el, oklch, row, text, tok};
6+use std::path::PathBuf;
7+
8+pub const WIDGET: Widget = Widget { title: "Taskbar", size: (0.0, 44.0), new: |cx| Box::new(Taskbar::load(cx)) };
9+
10+/// Projects forgotten from the bar (saved, one slug a line), and the × pressed once, with when.
11+pub struct Taskbar { forgotten: Vec<String>, armed: Option<(String, f64)>, file: PathBuf }
12+
13+/// How long a first press on × stays armed.
14+const ARMED: f64 = 3.0;
15+
16+impl Taskbar {
17+ fn load(cx: &Cx) -> Self {
18+ let file = cx.dir.join("forgotten");
19+ let forgotten = std::fs::read_to_string(&file).unwrap_or_default().lines().map(str::to_owned).collect();
20+ Taskbar { forgotten, armed: None, file }
21+ }
22+
23+ fn armed(&self, slug: &str, now: f64) -> bool {
24+ self.armed.as_ref().is_some_and(|(s, at)| s == slug && now - at < ARMED)
25+ }
26+
27+ /// Arms `slug`'s ×, or forgets it if already armed. True when forgotten.
28+ fn press_forget(&mut self, slug: &str) -> bool {
29+ if !self.armed(slug, now()) { self.armed = Some((slug.to_owned(), now())); return false; }
30+ self.armed = None;
31+ self.forgotten.push(slug.to_owned());
32+ let _ = std::fs::write(&self.file, self.forgotten.join("\n"));
33+ true
34+ }
35+
36+ fn remember(&mut self, slug: &str) {
37+ self.forgotten.retain(|s| s != slug);
38+ let _ = std::fs::write(&self.file, self.forgotten.join("\n"));
39+ }
40+}
41+
42+/// The library itself: the project whose tickets build this app.
43+const LIBRARY: &str = "widgets";
44+
45+impl View for Taskbar {
46+ fn view(&self, cx: &Cx) -> El {
47+ let t = tok::theme(true);
48+ let active = cx.shared("project");
49+ let item = |p: &Project| project(cx, p, active == Some(p.slug.as_str()), self.armed(&p.slug, cx.now));
50+ let mut bar = row().w_full().h_full().center_y().gap(4.0).px(8.0).fill(t.card).border_sides([0.0, 1.0, 0.0, 0.0], t.separator);
51+ if let Some(p) = cx.data.projects.iter().find(|p| p.slug == LIBRARY) {
52+ bar = bar.child(item(p)).child(library_toggle(cx)).child(el().w(1.0).h(22.0).mx(4.0).fill(t.separator));
53+ }
54+ for p in cx.data.projects.iter().filter(|p| p.slug != LIBRARY && !self.forgotten.contains(&p.slug)) { bar = bar.child(item(p)); }
55+ bar.child(add_button(cx))
56+ }
57+}
58+
59+/// One project's button: its glyph and name, a badge counting its running and queued tickets (blue while one runs), and an
60+/// underline when it's the shared "project", and a × to forget it (red while `armed`). The widgets project can't be forgotten.
61+fn project(cx: &Cx, p: &Project, active: bool, armed: bool) -> El {
62+ let t = tok::theme(true);
63+ let accent = oklch(0.72, 0.14, 250.0);
64+ let count = |s: &str| cx.data.tickets.iter().filter(|k| k.project == p.slug && k.state == s).count();
65+ let (running, queued) = (count("running"), count("ready"));
66+ let glyph = if p.slug == LIBRARY { "◆" } else { "▣" };
67+ let slug = p.slug.clone();
68+ let mut b = row().key(format!("project-{}", p.slug)).h(34.0).px(10.0).gap(7.0).center_y().radius(6.0)
69+ .role("button").label(&p.slug).help(format!("{}\n{}\n{running} running, {queued} queued", p.slug, p.path)).hover(t.hover)
70+ .on_press_tx(move |h: &mut HostState, _: &mut Tx| share(h, "project", &slug))
71+ .child(text(glyph).color(if active { accent } else { t.text_secondary }))
72+ .child(text(&p.slug).font(tok::type_::LABEL).color(if active { t.text } else { t.text_secondary }));
73+ if p.slots == 0 { b = b.child(text("paused").font(tok::type_::LABEL).color(t.text_secondary)); }
74+ if running + queued > 0 {
75+ b = b.child(row().h(16.0).px(5.0).radius(8.0).center().fill(if running > 0 { accent } else { t.control_off })
76+ .child(text((running + queued).to_string()).font(tok::type_::LABEL).color(if running > 0 { t.bg } else { t.text })));
77+ }
78+ if p.slug != LIBRARY { b = b.child(forget(cx, &p.slug, active, armed)); }
79+ if active { b = b.fill(t.press).child(el().absolute(10.0, 31.0).w(14.0).h(2.0).radius(1.0).fill(accent)); }
80+ b
81+}
82+
83+/// The × on project `slug`'s button: arms on the first press, forgets on the second, and switches to
84+/// the widgets desktop if `slug` is the `active` one.
85+fn forget(cx: &Cx, slug: &str, active: bool, armed: bool) -> El {
86+ let t = tok::theme(true);
87+ let red = oklch(0.65, 0.2, 25.0);
88+ let (id, slug) = (cx.id.to_owned(), slug.to_owned());
89+ let x = row().key(format!("forget-{slug}")).w(18.0).h(18.0).ml(-3.0).mr(-6.0).center().radius(4.0).role("button")
90+ .label(format!("Forget {slug}")).help(if armed { "Press again to forget" } else { "Forget project" }).hover(t.press)
91+ .child(text("×").font(tok::type_::LABEL).color(if armed { t.text } else { t.text_secondary }))
92+ .on_press_tx(move |h: &mut HostState, _: &mut Tx| {
93+ let Some(bar) = get::<Taskbar>(h, &id) else { return };
94+ if bar.press_forget(&slug) && active { share(h, "project", LIBRARY) }
95+ });
96+ if armed { x.fill(red) } else { x }
97+}
98+
99+fn add_button(cx: &Cx) -> El {
100+ let t = tok::theme(true);
101+ let id = cx.id.to_owned();
102+ row().key("add-project").w(34.0).h(34.0).center().radius(6.0).role("button").label("Add project").help("Add project")
103+ .hover(t.hover).child(text("+").font(tok::type_::TITLE).color(t.text_secondary))
104+ .on_press_tx(move |_: &mut HostState, tx: &mut Tx| {
105+ let id = id.clone();
106+ let options = FileDialogOptions { title: "Add project".into(), ..Default::default() };
107+ tx.open_folder(options, move |h: &mut HostState, result, _| {
108+ let Ok(Some(path)) = result else { return };
109+ let name = path.file_name().map(|n| n.to_string_lossy().to_lowercase()).unwrap_or_default();
110+ let slug: String = name.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }).collect();
111+ let slug = slug.trim_matches('-');
112+ if slug.is_empty() { return }
113+ if let Some(bar) = get::<Taskbar>(h, &id) { bar.remember(slug) }
114+ add_project(h, slug, &path);
115+ share(h, "project", slug);
116+ });
117+ })
118+}
119+
120+/// Shows or hides the shown desktop's library cards; the canvas reports back through the shared "library".
121+fn library_toggle(cx: &Cx) -> El {
122+ let t = tok::theme(true);
123+ let shown = cx.shared("library") != Some("hidden");
124+ let canvas = format!("{}.{}", cx.id.rsplit_once('.').map_or("root", |(p, _)| p), super::root::desktop(cx));
125+ let b = row().key("toggle-library").w(34.0).h(34.0).center().radius(6.0).role("button")
126+ .label(if shown { "Hide library" } else { "Show library" }).help(if shown { "Hide library" } else { "Show library" }).hover(t.hover)
127+ .on_press_tx(move |h: &mut HostState, _: &mut Tx| if let Some(c) = get::<Canvas>(h, &canvas) { c.toggle_library() })
128+ .child(text("▤").color(if shown { oklch(0.72, 0.14, 250.0) } else { t.text_secondary }));
129+ if shown { b.fill(t.press) } else { b }
130+}
templates/library/widgets/titlebar.rs+10−8
@@ -1,4 +1,4 @@
1-//! The window's title bar: drag to move it, and its buttons.
1+//! The window's title bar: drag to move it, the running indicator centered, and its buttons.
22 use super::api::*;
33 use rune::{El, Tx, el, row, text, tok};
44
@@ -12,13 +12,15 @@ fn button(key: &'static str, label: &'static str, glyph: &'static str, f: impl F
1212 }
1313
1414 impl View for TitleBar {
15- fn view(&self, _: &Cx) -> El {
15+ fn view(&self, cx: &Cx) -> El {
1616 let t = tok::theme(true);
17- row().w_full().h_full().center_y().fill(t.card).window_drag().pl(14.0)
18- .child(text("Conveyor").font(tok::type_::TITLE).color(t.text))
19- .child(el().grow(1.0))
20- .child(button("min", "Minimize", "_", |_, tx| tx.minimize()))
21- .child(button("max", "Maximize", "□", |_, tx| tx.toggle_maximized()))
22- .child(button("close", "Close", "×", |_, tx| tx.close_window()))
17+ // Equal-growth sides (flex-basis 0, same padding) keep the indicator at the bar's true center.
18+ row().w_full().h_full().center_y().fill(t.card).window_drag()
19+ .child(row().grow(1.0).h_full().center_y().pl(14.0).child(text("Conveyor").font(tok::type_::TITLE).color(t.text)))
20+ .child(cx.child("running", "running"))
21+ .child(row().grow(1.0).h_full().pl(14.0).child(el().grow(1.0))
22+ .child(button("min", "Minimize", "_", |_, tx| tx.minimize()))
23+ .child(button("max", "Maximize", "□", |_, tx| tx.toggle_maximized()))
24+ .child(button("close", "Close", "×", |_, tx| tx.close_window())))
2325 }
2426 }