xonecas.io
8447
Co

conveyor / commit 4d3f967

The library template ships the polished widgets

A new library starts from the widgets built up through tickets: tiles,
themes, a code editor with Markdown preview and commits, the branch view
and the keychain. Ctrl+O widget search replaces the Library card.

Co-Authored-By: Claude Opus 5.5

sacenox2026-11-16 4d3f967a1f585ed77a55d9aa3c364eff1b2a93f2 parent 29aac31

22 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

templates/library/widgets/board.rs+44−28
@@ -1,20 +1,22 @@
11 //! A kanban board of the tickets of the project whose desktop this is: a column per state with
22 //! counts, and cards with #id, title and time in that state. Drag a card to move it (never into
33 //! or out of running), type at the top of draft to write a new one, and click a card to open it.
4-use super::{api::*, canvas::{self, Canvas}};
5-use rune::{Drag, El, Phase, ScrollSpec, TextEdit, Tx, col, el, oklch, row, text, text_input, tok};
4+use super::{api::*, look, canvas::{self, Canvas}, ui};
5+use std::path::PathBuf;
6+use rune::{Drag, El, Phase, ScrollSpec, TextEdit, Tx, col, el, row, text};
67
7-pub const WIDGET: Widget = Widget { title: "Board", size: (1100.0, 520.0), new: |_| Box::new(Board::default()) };
8+pub const WIDGET: Widget = Widget { title: "Board", size: (1100.0, 520.0), new: |cx| Box::new(Board::load(cx)) };
89
910 pub const STATES: [&str; 7] = ["draft", "ready", "running", "review", "parked", "failed", "done"];
1011
11-#[derive(Default)]
1212 pub struct Board {
1313 /// The quick-add field at the top of draft.
1414 add: TextEdit,
15- /// The board's and each column's rect in window points, from layout.
16- rect: [f32; 4],
17- cols: [[f32; 4]; 7],
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,
1820 /// The card being dragged: its ticket, the pointer in window points, and where on the card it was grabbed.
1921 drag: Option<Dragged>,
2022 }
@@ -23,9 +25,24 @@ pub struct Board {
2325 struct Dragged { id: u32, at: [f32; 2], grab: [f32; 2], w: f32, moved: bool }
2426
2527 impl 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+
2643 /// The column under window point `p`.
2744 fn col_at(&self, p: [f32; 2]) -> Option<&'static str> {
28- self.cols.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])
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])
2946 }
3047
3148 /// Where the dragged card would land: a column it can move to, or none.
@@ -37,7 +54,7 @@ impl Board {
3754
3855 impl View for Board {
3956 fn view(&self, cx: &Cx) -> El {
40- let t = tok::theme(true);
57+ let t = look::of(cx);
4158 let project = super::root::project_of(cx.id);
4259 let tickets: Vec<&Ticket> = cx.data.tickets.iter().filter(|k| k.project == project).collect();
4360 let dragged = self.drag.and_then(|d| tickets.iter().find(|k| k.id == d.id).copied());
@@ -52,28 +69,29 @@ impl View for Board {
5269 for k in &cards { list = list.child(card(cx, k, dragged.is_some_and(|d| d.id == k.id))); }
5370 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)
5471 .fill(if target == Some(state) { t.press } else { t.bg })
55- .on_layout(move |h: &mut HostState, r: [f32; 4]| if let Some(b) = get::<Board>(h, &id) { b.cols[i] = r })
72+ .on_layout(move |h: &mut HostState, r: [f32; 4]| if let Some(b) = get::<Board>(h, &id) { b.laid(i + 1, r) })
5673 .child(row().key(format!("head-{state}")).w_full().px(4.0).gap(6.0).center_y()
57- .child(text(*state).font(tok::type_::LABEL).color(t.text))
74+ .child(text(*state).font(t.label).color(t.text).truncate().min_w(0.0))
5875 .child(el().grow(1.0))
59- .child(text(cards.len().to_string()).font(tok::type_::LABEL).color(t.text_secondary)))
76+ .child(text(cards.len().to_string()).font(t.label).color(t.text_secondary)))
6077 .child(col().w_full().grow(1.0).min_h(0.0).scroll(ScrollSpec { stick_bottom: false }).child(list)));
6178 }
6279 let id = cx.id.to_owned();
6380 let mut board = col().w_full().h_full().gap(8.0)
64- .on_layout(move |h: &mut HostState, r: [f32; 4]| if let Some(b) = get::<Board>(h, &id) { b.rect = r })
81+ .on_layout(move |h: &mut HostState, r: [f32; 4]| if let Some(b) = get::<Board>(h, &id) { b.laid(0, r) })
6582 .child(row().key("header").w_full().center_y().gap(8.0)
66- .child(text("Board").font(tok::type_::TITLE).color(t.text))
67- .child(text(project).font(tok::type_::LABEL).color(t.text_secondary))
83+ .child(text("Board").font(t.title).color(t.text))
84+ .child(text(project).font(t.label).color(t.text_secondary))
6885 .child(el().grow(1.0))
69- .child(text(format!("{} tickets", tickets.len())).font(tok::type_::LABEL).color(t.text_secondary))
86+ .child(text(format!("{} tickets", tickets.len())).font(t.label).color(t.text_secondary))
7087 .child(canvas::maximize(cx))
7188 .child(canvas::close(cx, "Close board")))
89+ .child(el().w_full().h(1.0).fill(t.separator))
7290 .child(cols);
7391 // The dragged card follows the pointer.
7492 if let (Some(d), Some(k)) = (self.drag.filter(|d| d.moved), dragged) {
75- let (x, y) = (d.at[0] - d.grab[0] - self.rect[0], d.at[1] - d.grab[1] - self.rect[1]);
76- board = board.child(face(k, cx.now).w(d.w).absolute(x, y).opacity(0.9).border(1.0, oklch(0.72, 0.14, 250.0)));
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));
7795 }
7896 board
7997 }
@@ -81,10 +99,9 @@ impl View for Board {
8199
82100 /// The field atop draft: Enter writes a new draft titled with what was typed.
83101 fn quick_add(cx: &Cx, edit_: &TextEdit, project: &str) -> El {
84- let t = tok::theme(true);
102+ let t = look::of(cx);
85103 let (id, project) = (cx.id.to_owned(), project.to_owned());
86- text_input(edit_, tok::type_::LABEL).key("quick-add").single_line().w_full().px(8.0).py(6.0).radius(6.0).fill(t.card).color(t.text)
87- .placeholder("New draft…", t.text_secondary)
104+ ui::field(&t, edit_, t.label, "New draft…").key("quick-add").single_line().fill(t.card)
88105 .on_edit(edit(cx.id, |b: &mut Board| &mut b.add))
89106 .on_submit(move |h: &mut HostState, _: &mut Tx| {
90107 let Some(b) = get::<Board>(h, &id) else { return };
@@ -97,7 +114,7 @@ fn quick_add(cx: &Cx, edit_: &TextEdit, project: &str) -> El {
97114 /// A ticket's card: drag it to another column, or click it to open the ticket beside the board.
98115 fn card(cx: &Cx, k: &Ticket, dragged: bool) -> El {
99116 let (id, ticket, from) = (cx.id.to_owned(), k.id, k.state.clone());
100- face(k, cx.now).key(format!("card-{}", k.id)).w_full().role("button").label(format!("#{} {}", k.id, k.title)).hover(tok::theme(true).hover)
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)
101118 .opacity(if dragged { 0.35 } else { 1.0 })
102119 .on_drag(move |h: &mut HostState, d: &mut Drag, _: &mut Tx| {
103120 let Some(b) = get::<Board>(h, &id) else { return };
@@ -116,14 +133,13 @@ fn card(cx: &Cx, k: &Ticket, dragged: bool) -> El {
116133 }
117134
118135 /// What a card shows: #id, the time in its state, and its title.
119-fn face(k: &Ticket, now: f64) -> El {
120- let t = tok::theme(true);
136+fn face(t: &look::Look, k: &Ticket, now: f64) -> El {
121137 col().gap(4.0).padding(8.0).radius(6.0).fill(t.card)
122- .child(row().w_full().gap(6.0)
123- .child(text(format!("#{}", k.id)).font(tok::type_::LABEL).color(t.text_secondary))
138+ .child(row().w_full().gap(6.0).flex_wrap()
139+ .child(text(format!("#{}", k.id)).font(t.label).color(t.text_secondary))
124140 .child(el().grow(1.0))
125- .child(text(ago(now, k.since)).font(tok::type_::LABEL).color(t.text_secondary)))
126- .child(text(&k.title).font(tok::type_::LABEL).color(t.text).w_full().wrap().max_lines(3))
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))
127143 }
128144
129145 /// Opens ticket `ticket` in a card beside board `board` on its canvas, or brings it to the front.
templates/library/widgets/branch.rs+71−0
@@ -0,0 +1,71 @@
1+//! A ticket's branch (`t-<id>`) of a project's repo as a folder to browse: the files at its tip
2+//! (`git archive`), extracted again when the tip moves, and the files it changes against HEAD.
3+//! The repo and its checkout are left alone.
4+use std::{collections::BTreeSet, path::{Path, PathBuf}, process::{Command, Stdio}, sync::{Arc, Mutex}};
5+
6+/// How often the branch's tip is checked, in seconds.
7+const EVERY: f64 = 5.0;
8+
9+#[derive(Default)]
10+struct State { rev: String, changed: BTreeSet<PathBuf>, error: Option<String>, busy: bool }
11+
12+pub struct Snapshot {
13+ pub ticket: u32,
14+ /// Where the branch's files are.
15+ pub tree: PathBuf,
16+ state: Arc<Mutex<State>>,
17+ seen: String,
18+ checked: f64,
19+}
20+
21+impl Snapshot {
22+ pub fn new(project: &str, ticket: u32) -> Self {
23+ let tree = std::env::temp_dir().join("conveyor-branches").join(format!("{project}-t{ticket}"));
24+ Snapshot { ticket, tree, state: Arc::default(), seen: String::new(), checked: f64::MIN }
25+ }
26+
27+ /// Checks the tip of the branch in `repo` every few seconds, extracting it again off the UI
28+ /// thread when it moved. True once, when a new tip's files are in `tree`.
29+ pub fn poll(&mut self, now: f64, repo: &Path) -> bool {
30+ let mut s = self.state.lock().unwrap();
31+ if s.rev != self.seen { self.seen = s.rev.clone(); return true }
32+ if s.busy || now - self.checked < EVERY { return false }
33+ (self.checked, s.busy) = (now, true);
34+ let (state, repo, tree, branch) = (self.state.clone(), repo.to_owned(), self.tree.clone(), format!("t-{}", self.ticket));
35+ std::thread::spawn(move || {
36+ let had = state.lock().unwrap().rev.clone();
37+ let r = refresh(&repo, &branch, &tree, &had);
38+ let mut s = state.lock().unwrap();
39+ match r {
40+ Ok(Some((rev, changed))) => (s.rev, s.changed, s.error) = (rev, changed, None),
41+ Ok(None) => s.error = None,
42+ Err(e) => s.error = Some(e),
43+ }
44+ s.busy = false;
45+ });
46+ false
47+ }
48+
49+ pub fn ready(&self) -> bool { !self.seen.is_empty() }
50+ pub fn error(&self) -> Option<String> { self.state.lock().unwrap().error.clone() }
51+ /// Whether `path` is a file the branch changes, or a folder holding one.
52+ pub fn changed(&self, path: &Path) -> bool { self.state.lock().unwrap().changed.iter().any(|c| c.starts_with(path)) }
53+}
54+
55+/// The branch's tip and changed files when its tip isn't `had`, after extracting it to `tree`.
56+fn refresh(repo: &Path, branch: &str, tree: &Path, had: &str) -> Result<Option<(String, BTreeSet<PathBuf>)>, String> {
57+ let git = |args: &[&str]| Command::new("git").args(args).current_dir(repo).output().ok().filter(|o| o.status.success())
58+ .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_owned());
59+ let rev = git(&["rev-parse", "--verify", "--quiet", &format!("{branch}^{{commit}}")]).ok_or(format!("No branch {branch}"))?;
60+ if rev == had { return Ok(None) }
61+ let next = tree.with_extension("new");
62+ let _ = std::fs::remove_dir_all(&next);
63+ std::fs::create_dir_all(&next).map_err(|e| e.to_string())?;
64+ let mut archive = Command::new("git").args(["archive", &rev]).current_dir(repo).stdout(Stdio::piped()).spawn().map_err(|e| format!("git: {e}"))?;
65+ let tar = Command::new("tar").arg("-x").arg("-C").arg(&next).stdin(archive.stdout.take().unwrap()).status().map_err(|e| format!("tar: {e}"))?;
66+ if !archive.wait().is_ok_and(|s| s.success()) || !tar.success() { return Err(format!("Can't extract {branch}")) }
67+ let _ = std::fs::remove_dir_all(tree);
68+ std::fs::rename(&next, tree).map_err(|e| e.to_string())?;
69+ let changed = git(&["diff", "--name-only", &format!("HEAD...{rev}")]).unwrap_or_default().lines().map(|l| tree.join(l)).collect();
70+ Ok(Some((rev, changed)))
71+}
templates/library/widgets/canvas.rs+154−40
@@ -1,9 +1,15 @@
11 //! A free canvas: new widgets land where they were asked for, and a drag on one (outside its
22 //! 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.
5-use super::api::*;
6-use rune::{Cursor, Drag, El, Phase, Shape, Tx, el, row, text, tok};
3+//! click (or the header's □) maximizes it to the whole canvas. A click on a card brings it to the front. Cards stay inside the canvas
4+//! as it resizes. Cards are frosted glass, as the theme sets it: see-through over a blur, with a shadow.
5+//! Tiled (the title bar's toggle, shared as "canvas-layout"), cards fill the canvas i3-style with
6+//! gaps instead: drag any gap between two cards to resize just those along it, and drag a card onto
7+//! another to split just that one (near an edge) or swap with it (the middle), or to the canvas's
8+//! edge to take that whole side, with the spot it will take lit up.
9+//! Root shows one per project, under the title bar, over the project's background image when the
10+//! title bar's button picked one.
11+use super::{api::*, look, tiles::Tiles, ui};
12+use rune::{Cursor, Drag, El, Image, Phase, Shape, SurfaceFit, Tx, el, text};
713 use std::path::PathBuf;
814
915 pub const WIDGET: Widget = Widget { title: "Canvas", size: (0.0, 0.0), new: |cx| Box::new(Canvas::load(cx)) };
@@ -34,8 +40,27 @@ pub struct Canvas {
3440 /// The canvas's laid-out size, kept as a "size" file: the app reloads widgets without
3541 /// laying out again, so `on_layout` only speaks when the size changes.
3642 size: (f32, f32),
43+ /// Whether the canvas tiles its cards. Set in `update`.
44+ tiled: bool,
45+ /// The tiled layout, kept in step with the cards shown, tiled or not.
46+ tiles: Tiles,
47+ /// When tiled, the card being dragged to another tile, how far it has moved, and where the pointer is.
48+ lift: Option<(String, (f32, f32), (f32, f32))>,
49+ /// When tiled, the layout as it was when a gap's drag started.
50+ held: Option<Tiles>,
51+ /// The project's background image, with the path it came from. Set in `update`.
52+ bg: Option<(String, Image)>,
3753 }
3854
55+/// The shared value that says how canvases lay out their cards: "tile", or anything else for floating.
56+pub const LAYOUT: &str = "canvas-layout";
57+
58+/// Whether canvases tile their cards.
59+pub fn tiled(cx: &Cx) -> bool { cx.shared(LAYOUT) == Some("tile") }
60+
61+/// The shared value that holds `project`'s background image path; empty or unset for none.
62+pub fn background(project: &str) -> String { format!("background-{project}") }
63+
3964 impl Canvas {
4065 /// children: one line per child, "kind key x y w h max".
4166 fn load(cx: &Cx) -> Self {
@@ -49,7 +74,8 @@ impl Canvas {
4974 let (w, h) = s.split_once(' ')?;
5075 Some((w.parse().ok()?, h.parse().ok()?))
5176 }).unwrap_or((0.0, 0.0));
52- Canvas { children, file, grab: None, size }
77+ let tiles = Tiles::load(&cx.dir.join("layout"));
78+ Canvas { children, file, grab: None, size, tiled: false, tiles, lift: None, held: None, bg: None }
5379 }
5480
5581 fn save(&self) {
@@ -63,9 +89,11 @@ impl Canvas {
6389 (c.x.min(self.size.0 - c.w).max(0.0), c.y.min(self.size.1 - c.h).max(0.0))
6490 }
6591
66- /// Child `c`'s shown rect: the whole canvas when maximized, else its size at its fitted spot.
67- fn rect(&self, c: &Child) -> (f32, f32, f32, f32) {
92+ /// Child `c`'s shown rect: the whole canvas when maximized, its tile among `tiles` when tiled,
93+ /// else its size at its fitted spot.
94+ fn rect(&self, c: &Child, tiles: Option<&Tiles>) -> (f32, f32, f32, f32) {
6895 if c.max && self.size.0 > 0.0 { return (0.0, 0.0, self.size.0, self.size.1) }
96+ if let Some(r) = tiles.filter(|_| self.size.0 > 0.0).and_then(|t| t.rect(&c.key, self.size)) { return r }
6997 let (x, y) = self.fit(c);
7098 (x, y, c.w, c.h)
7199 }
@@ -100,22 +128,35 @@ impl Canvas {
100128 self.save();
101129 }
102130
103- /// Adds a `kind` beside the child keyed `beside`: to its right if it fits, else against the
104- /// canvas's right edge, stepping down past anything already there.
105- pub fn add_beside(&mut self, kind: &str, size: (f32, f32), beside: &str) {
106- if let Some(at) = self.spot_beside(size, beside) { self.add(kind, at, size) }
107- }
108-
109131 /// Brings the card keyed `key` to the front, or adds a `kind` keyed `key` beside the child keyed `beside`.
110132 pub fn open_beside(&mut self, kind: &str, key: &str, size: (f32, f32), beside: &str) {
111133 if let Some(i) = self.children.iter().position(|c| c.key == key) {
112- let c = self.children.remove(i);
113- self.children.push(c);
134+ self.raise(i);
114135 return self.save();
115136 }
116137 if let Some(at) = self.spot_beside(size, beside) { self.add_keyed(kind, key.into(), at, size) }
117138 }
118139
140+ /// Moves child `i` to the end, drawn over the others; returns its new index.
141+ fn raise(&mut self, i: usize) -> usize {
142+ let c = self.children.remove(i);
143+ self.children.push(c);
144+ self.children.len() - 1
145+ }
146+
147+ /// The cards shown: a discarded build's kinds go away, and come back if it's built again.
148+ fn shown(&self, cx: &Cx) -> Vec<&Child> {
149+ let kinds = cx.kinds();
150+ self.children.iter().filter(|c| kinds.iter().any(|(n, _)| *n == c.kind)).collect()
151+ }
152+
153+ /// The tiled layout of the cards shown.
154+ fn tiling(&self, cx: &Cx) -> Tiles {
155+ let mut tiles = self.tiles.clone();
156+ tiles.sync(&self.shown(cx).iter().map(|c| c.key.clone()).collect::<Vec<_>>(), self.size);
157+ tiles
158+ }
159+
119160 /// Where a card of `size` goes beside the child keyed `beside`.
120161 fn spot_beside(&self, size: (f32, f32), beside: &str) -> Option<(f32, f32)> {
121162 let b = self.children.iter().find(|c| c.key == beside)?;
@@ -129,26 +170,49 @@ impl Canvas {
129170 }
130171
131172 impl View for Canvas {
173+ fn update(&mut self, cx: &Cx) {
174+ self.tiled = tiled(cx);
175+ let keys: Vec<String> = self.shown(cx).iter().map(|c| c.key.clone()).collect();
176+ if self.tiles.sync(&keys, self.size) { self.tiles.save() }
177+ // Root keys a project's canvas "canvas-<slug>"; the widgets project's is plain "canvas".
178+ let project = cx.id.rsplit('.').next().and_then(|k| k.strip_prefix("canvas-")).unwrap_or("widgets");
179+ let path = cx.shared(&background(project)).unwrap_or("");
180+ if self.bg.as_ref().map(|b| b.0.as_str()) != Some(path) {
181+ self.bg = (!path.is_empty()).then(|| (path.to_owned(), cx.images().file(path, 2048.0, 2.0)));
182+ }
183+ }
184+
132185 fn view(&self, cx: &Cx) -> El {
133- let t = tok::theme(true);
186+ let t = look::of(cx);
134187 let id = cx.id.to_owned();
135188 let mut canvas = el().w_full().h_full().fill(t.bg)
136189 .on_layout(move |h: &mut HostState, r: [f32; 4]| if let Some(c) = get::<Canvas>(h, &id) {
137190 c.size = (r[2], r[3]);
138191 let _ = std::fs::write(c.file.with_file_name("size"), format!("{} {}", r[2], r[3]));
139192 });
193+ if let Some((_, i)) = &self.bg && i.size().is_some() {
194+ canvas = canvas.child(el().key("background").absolute(0.0, 0.0).w_full().h_full().pixels_fit(i.pixels(), SurfaceFit::Fill));
195+ }
140196 if self.children.is_empty() {
141- canvas = canvas.center().child(text("Ctrl+click anywhere to make a widget").color(t.text_secondary));
197+ canvas = canvas.center().child(text("Ctrl+click anywhere to make a widget").font(t.body).color(t.text_secondary));
142198 }
143- // A discarded build's kinds go away, and come back if it's built again.
144- for c in self.children.iter().filter(|c| cx.kinds().iter().any(|(n, _)| *n == c.kind)) {
145- let (x, y, w, h) = self.rect(c);
199+ // From `cx`, not `self.tiled`: a toggle can render before the next `update`.
200+ let tiles = tiled(cx).then(|| self.tiling(cx));
201+ let mut shown = self.shown(cx);
202+ // Tiles don't overlap, so only a maximized one, or the one being dragged, draws over the rest.
203+ let lifted = |c: &Child| self.lift.as_ref().filter(|l| l.0 == c.key).map(|l| l.1);
204+ if tiles.is_some() { shown.sort_by_key(|c| (c.max, lifted(c).is_some())) }
205+ let any_max = shown.iter().any(|c| c.max);
206+ for c in shown {
207+ let (x, y, w, h) = self.rect(c, tiles.as_ref());
208+ let (x, y) = lifted(c).map_or((x, y), |(dx, dy)| (x + dx, y + dy));
146209 let radius = if c.max { 0.0 } else { 10.0 };
147210 let grip = |name: &str, g: Grip, cursor: Cursor| el().key(format!("resize-{name}")).cursor(cursor).on_drag(drag(cx.id, c.key.clone(), g));
148- 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)
149- .child(cx.child(&c.kind, &c.key))
211+ // The shadow sits on the card; the rounded clip on its content, or it would clip the shadow too.
212+ let mut card = t.glass(el().key(format!("card-{}", c.key)).w(w).h(h).absolute(x, y).radius(radius))
213+ .child(el().w_full().h_full().clip_rounded(radius).padding(12.0).child(cx.child(&c.kind, &c.key)))
150214 .on_drag(drag(cx.id, c.key.clone(), Grip::Move));
151- if !c.max {
215+ if !c.max && tiles.is_none() {
152216 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);
153217 card = card.child(grip("right", Grip::Right, Cursor::ResizeColumn).pin(None, Some(0.0), Some(0.0), Some(16.0)).w(6.0))
154218 .child(grip("bottom", Grip::Bottom, Cursor::ResizeRow).pin(Some(0.0), None, Some(16.0), Some(0.0)).h(6.0))
@@ -156,6 +220,19 @@ impl View for Canvas {
156220 }
157221 canvas = canvas.child(card);
158222 }
223+ let Some(tiles) = tiles.filter(|_| !any_max && self.size.0 > 0.0) else { return canvas };
224+ // The spot a dragged card will take, lit up over the rest.
225+ if let Some((key, _, p)) = &self.lift {
226+ let hint = tiles.target(key, *p, self.size).and_then(|(on, zone)| tiles.hint(key, on.as_deref(), zone, self.size));
227+ if let Some((x, y, w, h)) = hint {
228+ canvas = canvas.child(el().key("drop-hint").absolute(x, y).w(w).h(h).radius(10.0).fill(t.accent.alpha(0.18)).border(2.0, t.accent));
229+ }
230+ return canvas;
231+ }
232+ for (a, b, ax, (x, y, w, h)) in tiles.gaps(self.size) {
233+ let cursor = if ax == 0 { Cursor::ResizeColumn } else { Cursor::ResizeRow };
234+ canvas = canvas.child(el().key(format!("gap-{a}-{b}")).absolute(x, y).w(w).h(h).cursor(cursor).on_drag(gap(cx.id, a, b, ax)));
235+ }
159236 canvas
160237 }
161238
@@ -168,36 +245,40 @@ impl View for Canvas {
168245
169246 /// A □ for a card's header that maximizes the card (instance `cx.id`) to its canvas, or restores it.
170247 pub fn maximize(cx: &Cx) -> El {
171- let t = tok::theme(true);
172248 let id = cx.id.to_owned();
173- row().key("maximize").w(24.0).h(24.0).center().radius(6.0).role("button").label("Maximize").help("Maximize or restore").hover(t.press)
174- .child(text("□").font(tok::type_::LABEL).color(t.text_secondary))
175- .on_press_tx(move |h: &mut HostState, _: &mut Tx| {
176- let Some((parent, key)) = id.rsplit_once('.') else { return };
177- if let Some(canvas) = get::<Canvas>(h, parent) { canvas.toggle_max(key) }
178- })
249+ ui::icon(&look::of(cx), "maximize", "□", "Maximize or restore", move |h: &mut HostState, _: &mut Tx| {
250+ let Some((parent, key)) = id.rsplit_once('.') else { return };
251+ if let Some(canvas) = get::<Canvas>(h, parent) { canvas.toggle_max(key) }
252+ })
179253 }
180254
181255 /// A × for a card's header that takes the card (instance `cx.id`) off its canvas.
182256 pub fn close(cx: &Cx, label: &str) -> El {
183- let t = tok::theme(true);
184257 let id = cx.id.to_owned();
185- row().key("close").w(24.0).h(24.0).center().radius(6.0).role("button").label(label).help("Close").hover(t.press)
186- .child(text("×").font(tok::type_::BODY).color(t.text_secondary))
187- .on_press_tx(move |h: &mut HostState, _: &mut Tx| {
188- let Some((parent, key)) = id.rsplit_once('.') else { return };
189- if let Some(canvas) = get::<Canvas>(h, parent) { canvas.remove(key) }
190- })
258+ ui::icon(&look::of(cx), "close", "×", label, move |h: &mut HostState, _: &mut Tx| {
259+ let Some((parent, key)) = id.rsplit_once('.') else { return };
260+ if let Some(canvas) = get::<Canvas>(h, parent) { canvas.remove(key) }
261+ })
262+}
263+
264+/// A drag for a part of a card (instance `cx.id`) that takes presses itself, such as a header in a
265+/// focusable widget: it moves the card as a drag on the card does.
266+pub fn mover(cx: &Cx) -> impl Fn(&mut HostState, &mut Drag, &mut Tx) + 'static {
267+ let (parent, key) = cx.id.rsplit_once('.').unwrap_or(("", cx.id));
268+ drag(parent, key.to_owned(), Grip::Move)
191269 }
192270
193-/// A drag on card `key`: a double click maximizes or restores it; otherwise `g` moves or resizes it,
271+/// A drag on card `key`: a press brings it to the front, a double click maximizes or restores it; otherwise `g` moves or resizes it,
194272 /// unless it's maximized.
195273 fn drag(id: &str, key: String, g: Grip) -> impl Fn(&mut HostState, &mut Drag, &mut Tx) + 'static {
196274 let id = id.to_owned();
197275 move |h: &mut HostState, d: &mut Drag, _: &mut Tx| {
198276 let Some(canvas) = get::<Canvas>(h, &id) else { return };
199- let Some(i) = canvas.children.iter().position(|c| c.key == key) else { return };
200- let ((x, y, _, _), size) = (canvas.rect(&canvas.children[i]), canvas.size);
277+ let Some(mut i) = canvas.children.iter().position(|c| c.key == key) else { return };
278+ if canvas.tiled && !(d.phase == Phase::Down && d.clicks == 2) { return swap(canvas, i, d) }
279+ // A press anywhere on a card brings it to the front.
280+ if d.phase == Phase::Down { i = canvas.raise(i) }
281+ let ((x, y, _, _), size) = (canvas.rect(&canvas.children[i], None), canvas.size);
201282 let c = &mut canvas.children[i];
202283 // Up to the canvas's far edge, once its size is known.
203284 let room = |s: f32, at: f32| if s > 0.0 { s - at } else { f32::INFINITY };
@@ -222,3 +303,36 @@ fn drag(id: &str, key: String, g: Grip) -> impl Fn(&mut HostState, &mut Drag, &m
222303 }
223304 }
224305 }
306+
307+/// A drag on tile `i` of a tiled canvas: the card follows the pointer, and dropped on another tile,
308+/// splits it or takes its place.
309+fn swap(canvas: &mut Canvas, i: usize, d: &Drag) {
310+ let c = &canvas.children[i];
311+ if c.max { return }
312+ let Some((x, y, _, _)) = canvas.tiles.rect(&c.key, canvas.size) else { return };
313+ let (key, p) = (c.key.clone(), (x + d.start_x + d.dx, y + d.start_y + d.dy));
314+ match d.phase {
315+ Phase::Down | Phase::Move => canvas.lift = Some((key, (d.dx, d.dy), p)),
316+ Phase::Up => {
317+ canvas.lift = None;
318+ if d.cancelled() { return }
319+ let Some((on, zone)) = canvas.tiles.target(&key, p, canvas.size) else { return };
320+ canvas.tiles.drop(&key, on.as_deref(), zone, canvas.size);
321+ canvas.tiles.save();
322+ }
323+ }
324+}
325+
326+/// A drag on the gap between card `a` and card `b` after it along axis `ax`: moves that gap.
327+fn gap(id: &str, a: String, b: String, ax: usize) -> impl Fn(&mut HostState, &mut Drag, &mut Tx) + 'static {
328+ let id = id.to_owned();
329+ move |h: &mut HostState, d: &mut Drag, _: &mut Tx| {
330+ let Some(canvas) = get::<Canvas>(h, &id) else { return };
331+ if d.phase == Phase::Down { canvas.held = Some(canvas.tiles.clone()) }
332+ let Some(mut tiles) = canvas.held.clone() else { return };
333+ let moved = if d.cancelled() { 0.0 } else if ax == 0 { d.dx } else { d.dy };
334+ tiles.slide(&a, &b, ax, moved, canvas.size);
335+ canvas.tiles = tiles;
336+ if d.phase == Phase::Up { canvas.held = None; canvas.tiles.save() }
337+ }
338+}
templates/library/widgets/code_lang.rs+45−0
@@ -0,0 +1,45 @@
1+//! A file's language, from its name and extension, and its highlights: rune_kit's scanners for
2+//! the languages they know, and `code_scan` and `code_markdown` for the other common ones.
3+use super::{code_markdown, code_scan};
4+use rune_kit::syntax::{self, Highlight, Highlighter};
5+use std::{path::Path, rc::Rc};
6+
7+/// The language `path` is written in, as a name `scan` knows: empty when there's none.
8+pub fn of(path: &Path) -> String {
9+ let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("").to_ascii_lowercase();
10+ let ext = name.rsplit_once('.').map_or("", |(_, e)| e);
11+ match (name.as_str(), ext) {
12+ ("makefile" | "gnumakefile", _) => "make",
13+ ("dockerfile" | "containerfile", _) => "dockerfile",
14+ ("cargo.lock" | "uv.lock" | "poetry.lock" | "pipfile", _) => "toml",
15+ ("gemfile" | "rakefile" | "podfile" | "vagrantfile", _) => "ruby",
16+ ("pkgbuild" | ".bashrc" | ".zshrc" | ".profile" | ".bash_profile" | ".env", _) | (_, "env") => "sh",
17+ (".gitignore" | ".gitattributes" | ".gitconfig" | ".editorconfig" | ".npmrc" | ".dockerignore", _) => "ini",
18+ (_, "md" | "markdown" | "mdx") => "md",
19+ (_, "desktop" | "service" | "properties" | "conf" | "cfg") => "ini",
20+ (_, "cc" | "cpp" | "cxx" | "hpp" | "hh" | "hxx" | "ino") => "cpp",
21+ (_, "kts") => "kt",
22+ (_, "sc") => "scala",
23+ (_, "rake" | "gemspec") => "ruby",
24+ (_, "scss" | "sass" | "less") => "css",
25+ (_, "vue" | "svelte" | "astro") => "html",
26+ (_, "jsonl" | "geojson" | "webmanifest") => "json",
27+ (_, "fish") => "sh",
28+ (_, e) => e,
29+ }.to_owned()
30+}
31+
32+/// `code`'s highlights as `lang` (a name from `of`, or a Markdown fence's), cached.
33+pub fn highlight(lang: &str, code: &str) -> Rc<[Highlight]> {
34+ Highlighter::new(|lang, code| scan(lang, code)).highlight(Some(lang), code)
35+}
36+
37+/// `code`'s highlights as `lang`, uncached.
38+pub fn scan(lang: Option<&str>, code: &str) -> Vec<Highlight> {
39+ let name = lang.unwrap_or("").to_ascii_lowercase();
40+ match (name.as_str(), code_scan::spec(&name)) {
41+ ("md" | "markdown", _) => code_markdown::scan(code),
42+ (_, Some(s)) => { let mut out = Vec::new(); code_scan::scan(s, code, 0, code.len(), &mut out); out }
43+ _ => syntax::builtin(lang, code),
44+ }
45+}
templates/library/widgets/code_markdown.rs+60−0
@@ -0,0 +1,60 @@
1+//! Markdown source colouring: headings, quotes, list markers, inline code, bold, links, and
2+//! fenced code blocks in their own language.
3+use super::{code_lang, code_scan::push};
4+use rune_kit::syntax::{Highlight, Syntax};
5+
6+pub fn scan(code: &str) -> Vec<Highlight> {
7+ let mut out = Vec::new();
8+ // Where the open fence's code starts, its language and its marker.
9+ let mut fence: Option<(usize, &str, &str)> = None;
10+ let mut at = 0;
11+ for line in code.split('\n') {
12+ let (start, t) = (at, line.trim_start());
13+ let lead = start + line.len() - t.len();
14+ at += line.len() + 1;
15+ let whole = start..start + line.trim_end().len();
16+ if let Some((body, lang, mark)) = fence {
17+ if t.starts_with(mark) {
18+ out.extend(code_lang::scan(Some(lang), &code[body..start]).into_iter().map(|(r, p)| (r.start + body..r.end + body, p)));
19+ push(&mut out, whole, Syntax::Comment);
20+ fence = None;
21+ }
22+ } else if let Some(mark) = ["```", "~~~"].into_iter().find(|m| t.starts_with(m)) {
23+ fence = Some((at.min(code.len()), t[3..].split_whitespace().next().unwrap_or(""), mark));
24+ push(&mut out, whole, Syntax::Comment);
25+ } else if t.starts_with('#') {
26+ push(&mut out, whole, Syntax::Keyword);
27+ } else if t.starts_with('>') {
28+ push(&mut out, whole, Syntax::Comment);
29+ } else {
30+ let digits = t.bytes().take_while(u8::is_ascii_digit).count();
31+ let marker = if ["- ", "* ", "+ "].iter().any(|m| t.starts_with(m)) { 1 } else if digits > 0 && t[digits..].starts_with(". ") { digits + 1 } else { 0 };
32+ if marker > 0 { push(&mut out, lead..lead + marker, Syntax::Punctuation) }
33+ inline(code, lead + marker, whole.end, &mut out);
34+ }
35+ }
36+ if let Some((body, lang, _)) = fence {
37+ out.extend(code_lang::scan(Some(lang), &code[body..]).into_iter().map(|(r, p)| (r.start + body..r.end + body, p)));
38+ }
39+ out
40+}
41+
42+/// `code`, `**bold**` and `[links](url)` in `code[from..to]`, one line.
43+fn inline(code: &str, from: usize, to: usize, out: &mut Vec<Highlight>) {
44+ let b = code.as_bytes();
45+ let close = |from: usize, pat: &str| code[from..to].find(pat).map(|p| from + p + pat.len());
46+ let mut i = from;
47+ while i < to {
48+ let found = match b[i] {
49+ b'`' => close(i + 1, "`").map(|e| (e, Syntax::String)),
50+ b'*' if b.get(i + 1) == Some(&b'*') => close(i + 2, "**").map(|e| (e, Syntax::Type)),
51+ b'[' => close(i + 1, "]").map(|e| (e, Syntax::Function)),
52+ b'(' if i > from && b[i - 1] == b']' => close(i + 1, ")").map(|e| (e, Syntax::Property)),
53+ _ => None,
54+ };
55+ match found {
56+ Some((e, k)) => { push(out, i..e, k); i = e }
57+ None => i += 1,
58+ }
59+ }
60+}
templates/library/widgets/code_scan.rs+153−0
@@ -0,0 +1,153 @@
1+//! A table-driven code scanner for the languages rune_kit's own scanners don't know: each
2+//! language is a list of keywords, types, constants, comment markers and quotes.
3+use rune_kit::syntax::{Highlight, Paint, Syntax};
4+use std::ops::Range;
5+
6+pub struct Spec {
7+ /// Space-separated word lists.
8+ keywords: &'static [&'static str],
9+ types: &'static str,
10+ consts: &'static str,
11+ line: &'static [&'static str],
12+ block: Option<(&'static str, &'static str)>,
13+ quotes: &'static [u8],
14+ /// Bytes that may start a word as well as letters: a word they start is a property
15+ /// (`$var`, `@field`, `@Annotation`) unless it is a keyword (`#include`, `.PHONY`).
16+ starts: &'static [u8],
17+ /// Whether a word before `=` is a key, as in config files.
18+ keys: bool,
19+}
20+
21+const NONE: Spec = Spec { keywords: &[], types: "", consts: "true false null", line: &["//"], block: Some(("/*", "*/")), quotes: b"\"'", starts: b"", keys: false };
22+
23+const C: &str = "auto break case const continue default do else enum extern for goto if inline register restrict return sizeof static struct switch typedef union volatile while \
24+ #include #define #undef #if #ifdef #ifndef #elif #else #endif #pragma #error";
25+const C_TYPES: &str = "void char short int long float double signed unsigned bool size_t ssize_t int8_t int16_t int32_t int64_t uint8_t uint16_t uint32_t uint64_t";
26+const CPP: &str = "class namespace template typename public private protected virtual override final new delete this using operator friend try catch throw \
27+ noexcept constexpr consteval explicit mutable static_cast dynamic_cast reinterpret_cast const_cast decltype concept requires co_await co_return co_yield";
28+
29+/// The scanner for `lang` (a canonical or fence name), if this module has one.
30+pub fn spec(lang: &str) -> Option<&'static Spec> {
31+ Some(match lang {
32+ "c" | "h" => &Spec { keywords: &[C], types: C_TYPES, consts: "NULL true false", starts: b"#", ..NONE },
33+ "cpp" | "c++" | "cc" | "hpp" => &Spec { keywords: &[C, CPP], types: C_TYPES, consts: "NULL nullptr true false", starts: b"#", ..NONE },
34+ "cs" | "csharp" | "c#" => &Spec {
35+ keywords: &["abstract as base break case catch checked class const continue default delegate do else enum event explicit extern finally fixed \
36+ for foreach goto if implicit in interface internal is lock namespace new operator out override params private protected public readonly ref \
37+ return sealed sizeof stackalloc static struct switch this throw try typeof unchecked unsafe using virtual volatile while async await var get \
38+ set init record where yield"],
39+ types: "bool byte char decimal double float int long object sbyte short string uint ulong ushort void dynamic", starts: b"#", ..NONE },
40+ "java" => &Spec {
41+ keywords: &["abstract assert break case catch class const continue default do else enum extends final finally for goto if implements import \
42+ instanceof interface native new package private protected public return static strictfp super switch synchronized this throw throws \
43+ transient try volatile while var record sealed permits yield"],
44+ types: "boolean byte char double float int long short void", starts: b"@", ..NONE },
45+ "kotlin" | "kt" | "kts" => &Spec {
46+ keywords: &["as break class continue do else for fun if in interface is object package return super this throw try typealias typeof val var \
47+ when while by catch constructor finally get import init set where abstract annotation companion const data enum external final infix \
48+ inline inner internal lateinit open operator out override private protected public reified sealed suspend tailrec vararg"],
49+ starts: b"@", ..NONE },
50+ "scala" => &Spec {
51+ keywords: &["abstract case catch class def do else enum export extends final finally for given if implicit import lazy match new object \
52+ override package private protected return sealed super then this throw trait try type using val var while with yield"],
53+ ..NONE },
54+ "dart" => &Spec {
55+ keywords: &["abstract as assert async await break case catch class const continue covariant default deferred do else enum export extends \
56+ extension external factory final finally for get hide if implements import in interface is late library mixin new on operator part \
57+ required rethrow return sealed set show static super switch sync this throw try typedef var when while with yield"],
58+ types: "void int double num bool dynamic", starts: b"@", ..NONE },
59+ "php" => &Spec {
60+ keywords: &["abstract and array as break callable case catch class clone const continue declare default do echo else elseif empty \
61+ enddeclare endfor endforeach endif endswitch endwhile enum extends final finally fn for foreach function global goto if implements \
62+ include include_once instanceof insteadof interface isset list match namespace new or print private protected public readonly require \
63+ require_once return static switch throw trait try unset use var while xor yield"],
64+ consts: "true false null TRUE FALSE NULL", line: &["//", "#"], quotes: b"\"'`", starts: b"$", ..NONE },
65+ "ruby" | "rb" => &Spec {
66+ keywords: &["BEGIN END alias and begin break case class def do else elsif end ensure for if in module next not or redo rescue retry return \
67+ self super then undef unless until when while yield require require_relative include extend attr_accessor attr_reader attr_writer \
68+ private protected public raise lambda proc puts"],
69+ consts: "true false nil", line: &["#"], block: Some(("=begin", "=end")), quotes: b"\"'`", starts: b"@$", ..NONE },
70+ "lua" => &Spec {
71+ keywords: &["and break do else elseif end for function goto if in local not or repeat return then until while"],
72+ consts: "true false nil", line: &["--"], block: Some(("--[[", "]]")), ..NONE },
73+ "zig" => &Spec {
74+ keywords: &["addrspace align allowzero and anyframe anytype asm async await break callconv catch comptime const continue defer else enum \
75+ errdefer error export extern fn for if inline linksection noalias noinline nosuspend opaque or orelse packed pub resume return struct \
76+ suspend switch test threadlocal try union unreachable usingnamespace var volatile while"],
77+ types: "i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 isize usize f16 f32 f64 f128 bool void type anyerror noreturn comptime_int comptime_float",
78+ consts: "true false null undefined", block: None, starts: b"@", ..NONE },
79+ "make" | "makefile" | "mk" => &Spec {
80+ keywords: &["ifeq ifneq ifdef ifndef else endif include define endef export unexport override vpath .PHONY .DEFAULT .SUFFIXES"],
81+ consts: "", line: &["#"], block: None, starts: b"$.", ..NONE },
82+ "dockerfile" | "docker" | "containerfile" => &Spec {
83+ keywords: &["FROM RUN CMD LABEL MAINTAINER EXPOSE ENV ADD COPY ENTRYPOINT VOLUME USER WORKDIR ARG ONBUILD STOPSIGNAL HEALTHCHECK SHELL AS"],
84+ consts: "", line: &["#"], block: None, starts: b"$", ..NONE },
85+ "toml" => &Spec { consts: "true false inf nan", line: &["#"], block: None, keys: true, ..NONE },
86+ "ini" | "conf" | "cfg" => &Spec { consts: "true false yes no on off", line: &["#", ";"], block: None, keys: true, ..NONE },
87+ _ => return None,
88+ })
89+}
90+
91+/// Adds `r` as `k`, joined to the last range when they touch and match.
92+pub fn push(out: &mut Vec<Highlight>, r: Range<usize>, k: Syntax) {
93+ if let Some((last, Paint::Kind(lk))) = out.last_mut() && last.end == r.start && *lk == k { last.end = r.end; return }
94+ out.push((r, Paint::Kind(k)));
95+}
96+
97+/// `s`'s highlights of `code[from..to]`. Config files colour a line starting with `[` as a section.
98+pub fn scan(s: &Spec, code: &str, from: usize, to: usize, out: &mut Vec<Highlight>) {
99+ let b = code.as_bytes();
100+ let has = |list: &str, w: &str| list.split_ascii_whitespace().any(|k| k == w);
101+ let word = |c: u8| c.is_ascii_alphanumeric() || c == b'_';
102+ let mut i = from;
103+ while i < to {
104+ let (start, c, rest) = (i, b[i], &b[i..to]);
105+ let kind = if let Some((open, close)) = s.block.filter(|(open, _)| rest.starts_with(open.as_bytes())) {
106+ i = find(b, i + open.len(), to, close.as_bytes()).map_or(to, |e| e + close.len());
107+ Syntax::Comment
108+ } else if s.line.iter().any(|p| rest.starts_with(p.as_bytes())) {
109+ i = find(b, i, to, b"\n").unwrap_or(to);
110+ Syntax::Comment
111+ } else if s.keys && c == b'[' && (i == 0 || b[i - 1] == b'\n') {
112+ i = find(b, i, to, b"\n").unwrap_or(to);
113+ Syntax::Type
114+ } else if s.quotes.contains(&c) {
115+ i = string_end(b, i, to, c);
116+ Syntax::String
117+ } else if c.is_ascii_digit() {
118+ while i < to && (word(b[i]) || b[i] == b'.') { i += 1 }
119+ Syntax::Number
120+ } else if word(c) || s.starts.contains(&c) {
121+ i += 1;
122+ while i < to && (word(b[i]) || b[i] == b'-' && s.keys) { i += 1 }
123+ let w = &code[start..i];
124+ let after = b[i..to].iter().position(|&c| c != b' ' && c != b'\t').map(|p| (b[i + p], b.get(i + p + 1).copied()));
125+ if s.keywords.iter().any(|l| has(l, w)) { Syntax::Keyword }
126+ else if has(s.consts, w) { Syntax::Number }
127+ else if !word(c) { Syntax::Property }
128+ else if s.keys && matches!(after, Some((b'=', n)) if n != Some(b'=')) { Syntax::Property }
129+ else if has(s.types, w) { Syntax::Type }
130+ else if w.len() > 1 && w.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_') { Syntax::Number }
131+ else if c.is_ascii_uppercase() { Syntax::Type }
132+ else if matches!(after, Some((b'(', _))) { Syntax::Function }
133+ else { continue }
134+ } else {
135+ i += 1;
136+ if b"{}[]()<>=+-*/%!&|^~?:;,.".contains(&c) { Syntax::Punctuation } else { continue }
137+ };
138+ push(out, start..i, kind);
139+ }
140+}
141+
142+/// Where the string opening at `i` ends: after its closing quote, or at its line's end. A
143+/// tripled quote (`"""`) runs to its tripled close across lines.
144+fn string_end(b: &[u8], i: usize, to: usize, q: u8) -> usize {
145+ if b[i..to].starts_with(&[q; 3]) { return find(b, i + 3, to, &[q; 3]).map_or(to, |e| e + 3) }
146+ let mut j = i + 1;
147+ while j < to && b[j] != q && b[j] != b'\n' { j += if b[j] == b'\\' { 2 } else { 1 } }
148+ if j < to && b[j] == q { j + 1 } else { j.min(to) }
149+}
150+
151+fn find(b: &[u8], from: usize, to: usize, pat: &[u8]) -> Option<usize> {
152+ b.get(from..to)?.windows(pat.len()).position(|w| w == pat).map(|p| from + p)
153+}
templates/library/widgets/code_theme.rs+42−0
@@ -0,0 +1,42 @@
1+//! Colour schemes for code: Molokai, Nord, Jellybeans and Kanagawa, each a background, a text
2+//! colour and a token colour per kind of syntax. The pick is the shared value "code_theme".
3+use super::api::Cx;
4+use rune::{Color, color::hex};
5+use rune_kit::syntax::{Syntax, SyntaxTheme};
6+
7+pub struct Scheme {
8+ pub name: &'static str,
9+ bg: &'static str,
10+ fg: &'static str,
11+ /// Keyword, string, number, comment, type, function, property, punctuation, inserted, deleted, parameter.
12+ tokens: [&'static str; 11],
13+}
14+
15+const KINDS: [Syntax; 11] = [Syntax::Keyword, Syntax::String, Syntax::Number, Syntax::Comment, Syntax::Type, Syntax::Function,
16+ Syntax::Property, Syntax::Punctuation, Syntax::Inserted, Syntax::Deleted, Syntax::Parameter];
17+
18+pub const ALL: [Scheme; 4] = [
19+ Scheme { name: "Molokai", bg: "#1b1d1e", fg: "#f8f8f2",
20+ tokens: ["#f92672", "#e6db74", "#ae81ff", "#7e8e91", "#66d9ef", "#a6e22e", "#fd971f", "#c4c5b5", "#a6e22e", "#f92672", "#fd971f"] },
21+ Scheme { name: "Nord", bg: "#2e3440", fg: "#d8dee9",
22+ tokens: ["#81a1c1", "#a3be8c", "#b48ead", "#616e88", "#8fbcbb", "#88c0d0", "#ebcb8b", "#eceff4", "#a3be8c", "#bf616a", "#d8dee9"] },
23+ Scheme { name: "Jellybeans", bg: "#151515", fg: "#e8e8d3",
24+ tokens: ["#8197bf", "#99ad6a", "#cf6a4c", "#888888", "#ffb964", "#fad07a", "#c6b6ee", "#8fbfdc", "#99ad6a", "#dd5f5f", "#e8e8d3"] },
25+ Scheme { name: "Kanagawa", bg: "#1f1f28", fg: "#dcd7ba",
26+ tokens: ["#957fb8", "#98bb6c", "#d27e99", "#727169", "#7aa89f", "#7e9cd8", "#e6c384", "#9cabca", "#76946a", "#c34043", "#b8b4d0"] },
27+];
28+
29+impl Scheme {
30+ pub fn bg(&self) -> Color { hex(self.bg).unwrap_or(Color::BLACK) }
31+ pub fn fg(&self) -> Color { hex(self.fg).unwrap_or(Color::WHITE) }
32+
33+ pub fn syntax(&self) -> SyntaxTheme {
34+ KINDS.iter().zip(self.tokens).fold(SyntaxTheme::neutral(true), |s, (k, c)| s.with(*k, hex(c).unwrap_or(Color::WHITE)))
35+ }
36+}
37+
38+/// The picked scheme, Molokai until one is picked.
39+pub fn of(cx: &Cx) -> &'static Scheme {
40+ let name = cx.shared("code_theme").unwrap_or("");
41+ ALL.iter().find(|s| s.name == name).unwrap_or(&ALL[0])
42+}
templates/library/widgets/editor.rs+218−41
@@ -1,8 +1,13 @@
11 //! 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};
2+//! right, with line numbers and the caret's line lit; long lines wrap. Text edits in place (Ctrl+S anywhere in the card, or Save, writes it), and Commit
3+//! commits the picked changed files with a message. Code is coloured by its language in the
4+//! picked scheme (Molokai, Nord, Jellybeans or Kanagawa); PNG, JPEG and SVG show as images, and
5+//! Preview toggles a Markdown file between its source and the rendered page.
6+//! The project is the one whose desktop this card is on. Opened from a ticket in review (keyed
7+//! `branch-<id>`), it browses that ticket's branch instead, read-only, its changed files lit.
8+use super::{api::*, look, branch::Snapshot, canvas, code_lang, code_theme, git_commit::{self, Commit}, ui};
9+use rune::{Align, Color, El, Image, ImageCache, Key, KeyEvent, Keybind, Live, ScrollPos, ScrollSpec, Side, Span, SurfaceFit, TextEdit, TextStyle, Tx, col, el, row, text, text_input};
10+use rune_kit::syntax::Syntax;
611 use std::{collections::{BTreeSet, HashMap}, path::{Path, PathBuf}, rc::Rc};
712
813 pub const WIDGET: Widget = Widget { title: "Editor", size: (860.0, 540.0), new: |cx| Box::new(Editor::load(cx)) };
@@ -34,6 +39,25 @@ pub struct Editor {
3439 drafted: String,
3540 images: Rc<ImageCache>,
3641 dir: PathBuf,
42+ /// The colour scheme dropdown shows.
43+ menu: bool,
44+ /// The code view's scroll (offset y, viewport height), the offset the caret last followed,
45+ /// and the caret a scroll last put down with the column it keeps.
46+ scroll: Live<[f32; 2]>,
47+ scrolled: f32,
48+ goal: Option<(usize, usize)>,
49+ /// The width the code wraps at, from its last layout (0 until then: no wrapping).
50+ width: f32,
51+ /// Why the last save failed, until a save works or another file opens.
52+ error: Option<String>,
53+ /// The ticket branch this card browses instead of the project's folder, read-only, and the
54+ /// selection that typing there goes back to.
55+ branch: Option<Snapshot>,
56+ held: (usize, usize),
57+ /// The Commit dropdown's message, picked files and git runs.
58+ commit: Commit,
59+ /// Markdown files show rendered instead of their source; kept as the "preview" file.
60+ preview: bool,
3761 }
3862
3963 impl Editor {
@@ -42,8 +66,12 @@ impl Editor {
4266 let state = std::fs::read_to_string(cx.dir.join("state")).unwrap_or_default();
4367 let mut lines = state.lines().map(PathBuf::from);
4468 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: cx.images(), dir: cx.dir.clone() };
69+ let branch = cx.id.rsplit('.').next().and_then(|k| k.strip_prefix("branch-")?.parse().ok())
70+ .map(|id| Snapshot::new(super::root::project_of(cx.id), id));
71+ let mut e = Editor { root: branch.as_ref().map_or_else(|| project_dir(cx), |b| b.tree.clone()), listings: HashMap::new(), listed_at: 0.0, expanded: lines.collect(),
72+ file: None, content: Content::None, text: TextEdit::new(""), saved: String::new(), drafted: String::new(), images: cx.images(), dir: cx.dir.clone(), menu: false,
73+ scroll: Live::new([0.0; 2]), scrolled: 0.0, goal: None, width: 0.0, error: None, branch, held: (0, 0), commit: Commit::load(&cx.dir),
74+ preview: cx.dir.join("preview").exists() };
4775 let draft = std::fs::read_to_string(e.dir.join("draft"));
4876 if let Some(f) = file { e.open(f) }
4977 if let (Content::Text, Ok(draft)) = (&e.content, draft) { e.text.text = draft }
@@ -70,14 +98,17 @@ impl Editor {
7098 _ => Content::Note(format!("Binary file ({})", kb(size))),
7199 },
72100 };
73- (self.text.anchor, self.text.focus) = (0, 0);
101+ (self.text.anchor, self.text.focus, self.error) = (0, 0, None);
74102 self.file = Some(path);
75103 self.save_state();
76104 }
77105
78106 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(); }
107+ let (Some(f), Content::Text, None) = (&self.file, &self.content, &self.branch) else { return };
108+ match std::fs::write(f, &self.text.text) {
109+ Ok(()) => { (self.saved, self.error) = (self.text.text.clone(), None); let _ = std::fs::remove_file(self.dir.join("draft")); }
110+ Err(e) => self.error = Some(format!("Can't save: {e}")),
111+ }
81112 }
82113
83114 fn toggle(&mut self, dir: PathBuf) {
@@ -85,6 +116,41 @@ impl Editor {
85116 self.save_state();
86117 }
87118
119+ /// A scroll that leaves the caret behind takes it along: to the first line still showing when
120+ /// scrolling down, the last when scrolling up, at the column it had.
121+ fn follow(&mut self, mono: TextStyle) {
122+ let line = mono.line_px();
123+ let [off, height] = self.scroll.get();
124+ let down = off > self.scrolled;
125+ if off == self.scrolled { return }
126+ self.scrolled = off;
127+ let e = &mut self.text;
128+ let starts: Vec<usize> = std::iter::once(0).chain(e.text.match_indices('\n').map(|(i, _)| i + 1)).collect();
129+ let at = starts.partition_point(|&s| s <= e.focus) - 1;
130+ let tops = tops(&e.text, mono, self.width);
131+ let (first, last) = (((off - 8.0) / line).ceil().max(0.0) as usize, ((off + height - 8.0) / line).floor() as usize);
132+ let first = tops.partition_point(|&r| r < first).min(starts.len() - 1);
133+ let last = tops.partition_point(|&r| r < last).saturating_sub(1).max(first).min(starts.len() - 1);
134+ let to = if down && at < first { first.min(last) } else if !down && at > last { last } else { return };
135+ let column = match self.goal { Some((f, c)) if f == e.focus => c, _ => e.text[starts[at]..e.focus].chars().count() };
136+ let end = starts.get(to + 1).map_or(e.text.len(), |&s| s - 1);
137+ let focus = e.text[starts[to]..end].char_indices().nth(column).map_or(end, |(i, _)| starts[to] + i);
138+ if e.anchor == e.focus { e.anchor = focus }
139+ e.focus = focus;
140+ self.goal = Some((focus, column));
141+ }
142+
143+ fn toggle_preview(&mut self) {
144+ self.preview = !self.preview;
145+ let f = self.dir.join("preview");
146+ let _ = if self.preview { std::fs::write(f, "") } else { std::fs::remove_file(f) };
147+ }
148+
149+ /// The open file is Markdown text, and it shows rendered.
150+ fn previewing(&self) -> bool {
151+ self.preview && matches!(self.content, Content::Text) && self.file.as_deref().is_some_and(is_markdown)
152+ }
153+
88154 fn modified(&self) -> bool {
89155 matches!(self.content, Content::Text) && self.text.text != self.saved
90156 }
@@ -94,84 +160,121 @@ impl View for Editor {
94160 fn update(&mut self, cx: &Cx) {
95161 // A decoded image shows at once: the no-op act asks for a render.
96162 if let Content::Loading(i) = &self.content && i.is_ready() { self.content = Content::Image(i.clone()); cx.act(|_| {}) }
97- let root = project_dir(cx);
163+ // A branch's new tip: its files replace the old ones, the open one included.
164+ if self.branch.as_mut().is_some_and(|b| b.poll(cx.now, &project_dir(cx))) {
165+ self.listed_at = 0.0;
166+ if let Some(f) = self.file.clone() { self.open(f) }
167+ }
168+ let root = self.branch.as_ref().map_or_else(|| project_dir(cx), |b| b.tree.clone());
98169 if root != self.root || cx.now - self.listed_at > 2.0 { (self.root, self.listed_at) = (root, cx.now); self.listings.clear(); }
99170 for d in std::iter::once(&self.root).chain(self.expanded.iter().filter(|d| d.starts_with(&self.root))) {
100171 if !self.listings.contains_key(d) { self.listings.insert(d.clone(), list(d)); }
101172 }
173+ // A branch is read-only: typing is undone before it shows, while the caret and selection move freely.
174+ if self.branch.is_some() {
175+ if self.text.text != self.saved { self.text.text = self.saved.clone(); (self.text.anchor, self.text.focus) = self.held }
176+ self.held = (self.text.anchor, self.text.focus);
177+ }
102178 // Unsaved typing goes to "draft" so a restart keeps it.
103179 if matches!(self.content, Content::Text) && self.text.text != self.drafted {
104180 self.drafted = self.text.text.clone();
105181 let draft = self.dir.join("draft");
106182 let _ = if self.text.text == self.saved { std::fs::remove_file(draft) } else { std::fs::write(draft, &self.text.text) };
107183 }
184+ self.commit.update(cx, &self.root);
108185 }
109186
110187 fn view(&self, cx: &Cx) -> El {
111- let t = tok::theme(true);
188+ let t = look::of(cx);
112189 let mut tree = col().w_full();
113190 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)
191+ else if let Some(b) = self.branch.as_ref().filter(|b| !b.ready()) {
192+ tree = tree.child(text(b.error().unwrap_or(format!("Getting branch t-{}…", b.ticket))).font(t.label).color(t.text_secondary).wrap())
193+ } else { tree = tree.child(text(format!("No folder at {}", self.root.display())).font(t.label).color(t.text_secondary).wrap()) }
194+ let id = cx.id.to_owned();
195+ // Focusable with a key handler, so Ctrl+S saves from the tree and header as well as the code.
196+ col().w_full().h_full().gap(8.0).focusable(true)
197+ .on_key(move |h: &mut HostState, k: &KeyEvent, tx: &mut Tx| save_key().matches_tx(k, tx) && get::<Editor>(h, &id).map(|e| e.save()).is_some())
116198 .child(self.header(cx))
117199 .child(el().w_full().h(1.0).fill(t.separator))
118200 .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))
201+ .child(col().key("tree").w_frac(0.25).min_w(120.0).h_full().min_h(0.0).scroll(ScrollSpec { stick_bottom: false }).child(tree))
120202 .child(el().w(1.0).h_full().fill(t.separator))
121203 .child(col().key("content").grow(1.0).min_w(0.0).h_full().min_h(0.0).child(self.content(cx))))
204+ // Last, so it draws over the code.
205+ .child(if self.menu { scheme_menu(cx) } else { el() })
206+ .child(git_commit::menu(&t, cx, &self.commit, |e: &mut Editor| &mut e.commit,
207+ on(cx.id, |e: &mut Editor, _| { e.save(); e.commit.run(&e.root) })))
122208 }
123209 }
124210
125211 impl Editor {
126- /// The project, the open file's path under it with a dot while modified, a Save button, and ×.
212+ /// The project, the open file's path under it with a dot while modified, why a save failed,
213+ /// a Save button (Saved, greyed, while the file matches the disk), Commit, and ×.
127214 fn header(&self, cx: &Cx) -> El {
128- let t = tok::theme(true);
215+ let t = look::of(cx);
129216 let project = cx.data.projects.iter().find(|p| Path::new(&p.path) == self.root).map_or("Editor", |p| p.slug.as_str());
130217 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)
Cut short: this commit's diff is over 1000 lines.
templates/library/widgets/git_commit.rs+177−0
Cut short: this commit's diff is over 1000 lines.
templates/library/widgets/keychain.rs+122−0
Cut short: this commit's diff is over 1000 lines.
templates/library/widgets/library.rs+0−51
Cut short: this commit's diff is over 1000 lines.
templates/library/widgets/look.rs+142−0
Cut short: this commit's diff is over 1000 lines.
templates/library/widgets/root.rs+19−5
Cut short: this commit's diff is over 1000 lines.
templates/library/widgets/running.rs+15−8
Cut short: this commit's diff is over 1000 lines.
templates/library/widgets/status.rs+71−42
Cut short: this commit's diff is over 1000 lines.
templates/library/widgets/taskbar.rs+103−36
Cut short: this commit's diff is over 1000 lines.
templates/library/widgets/theme.rs+301−0
Cut short: this commit's diff is over 1000 lines.
templates/library/widgets/ticket.rs+135−38
Cut short: this commit's diff is over 1000 lines.
templates/library/widgets/tiles.rs+205−0
Cut short: this commit's diff is over 1000 lines.
templates/library/widgets/titlebar.rs+71−21
Cut short: this commit's diff is over 1000 lines.
templates/library/widgets/ui.rs+66−0
Cut short: this commit's diff is over 1000 lines.
templates/library/widgets/widget_menu.rs+88−23
Cut short: this commit's diff is over 1000 lines.