app: draw champion portraits, a 16:9 player and draggable scroll bars

Cards and the review header showed two initials where a champion
portrait belongs. Data Dragon is fetched from a worker thread and cached
under the user's cache directory, so the first sight of a champion puts
its face on the card and later runs read it from disk; offline, the tile
keeps its initials on the champion's colour.

The review screen put the clip in a small box above two list columns.
The clip now fills the window at 16:9 and the highlights and timeline
open beside it on demand, so nothing shrinks the video by default and
every event still marks the scrubber.

Scroll bars were a thumb drawn over the cards that could not be
dragged. They now sit in a strip the content leaves free, stay visible
while the list overflows, and scroll the viewport when dragged.
This commit is contained in:
vhaudiquet committed 2026-11-16 18:24:39 +01:00
1 parent 3d0cad3312
commit 227aecb8f6
10 files changed
+500 -181

No files matched your search

+29 -7
View File
@@ -9,6 +9,7 @@ use rune::{Cx, El, Key, KeyEvent, Tx, col, el, row, text};
use crate::history::{self, QueueCategory, Timeline};
use crate::ipc::{self, Daemon};
use crate::os;
use crate::portraits;
use crate::screens;
use crate::settings::{AudioSource, AudioSourceType, Settings};
use crate::ui::{self, Paint, body, heading};
@@ -114,6 +115,7 @@ pub struct App {
pub games_loaded: bool,
pub filter: Option<QueueCategory>,
pub review: screens::review::Review,
pub portraits: Option<portraits::Portraits>,
pub scroll: ui::ScrollBar,
pub highlights_scroll: ui::ScrollBar,
pub events_scroll: ui::ScrollBar,
@@ -150,6 +152,7 @@ impl App {
games_loaded: false,
filter: None,
review: screens::review::Review::default(),
portraits: None,
scroll: ui::ScrollBar::new(),
highlights_scroll: ui::ScrollBar::new(),
events_scroll: ui::ScrollBar::new(),
@@ -303,6 +306,7 @@ fn hide_window() {
/// `AppSpec::setup`: keep the waker and put the tray icon up.
pub fn setup(app: &mut App, waker: rune::Waker) {
app.waker = Some(waker.clone());
app.portraits = Some(portraits::Portraits::new(waker.clone()));
app.daemon.set_waker(waker.clone());
app.refresh_settings();
app.refresh_games();
@@ -698,7 +702,7 @@ pub fn view(app: &App, cx: &mut Cx<App>) -> El {
main = main.child(notice(p, banner));
}
main = main.child(content);
let mut window = col()
let window = col()
.key("window")
.w_full()
.h_full()
@@ -706,13 +710,23 @@ pub fn view(app: &App, cx: &mut Cx<App>) -> El {
.child(titlebar(p, app))
.child(main)
.child(statusbar(p, app));
window = match app.screen {
match app.screen {
Screen::Review => window
.child(app.highlights_scroll.thumb(p, "highlights-thumb"))
.child(app.events_scroll.thumb(p, "events-thumb")),
_ => window.child(app.scroll.thumb(p, "scroll-thumb")),
};
window
.child(
app.highlights_scroll
.thumb(p, "highlights-thumb", "highlight-scroller"),
)
.child(app.events_scroll.thumb(p, "events-thumb", "event-scroller")),
_ => window.child(app.scroll.thumb(
p,
"scroll-thumb",
if app.screen == Screen::Settings {
"scroller"
} else {
"list-scroller"
},
)),
}
}
/// Whether this is a headless run (`--snap out.png`, `--tree`, …) rather than a window.
@@ -753,6 +767,14 @@ pub fn demo_review(app: &mut App) {
}
app.review.game = app.games.first().map(|game| game.recording_id.clone());
app.review.error = Some("Sample recording: no clip on disk.".to_string());
// Snapshot hook: draw a real clip when one is handed in.
if let Ok(path) = std::env::var("LR_DEMO_VIDEO") {
let player = rune::Player::file(&path);
player.set_looping(false);
app.review.player = Some(player);
app.review.error = None;
}
if let Some(game) = app.games.first() {
app.review.highlights =
crate::highlight::compute(game, game.summoner().as_deref(), Default::default());
+5
View File
@@ -11,6 +11,7 @@ mod highlight;
mod history;
mod ipc;
mod os;
mod portraits;
mod screens;
mod settings;
mod ui;
@@ -62,6 +63,10 @@ fn main() {
app.settings_tab = app::SettingsTab::Daemon;
}),
("review", |app| app::demo_review(app)),
("details", |app| {
app::demo_review(app);
app.review.show_details = true;
}),
("many", |app| {
app.screen = app::Screen::History;
app.games = (0..30).flat_map(|_| crate::history::sample()).collect();
+196
View File
@@ -0,0 +1,196 @@
//! Champion portraits, fetched from Data Dragon and cached on disk.
//!
//! Rune decodes images but has no HTTP client on native, so the bytes come down here first. A
//! portrait is drawn as soon as it is on disk, and the app redraws when a download lands.
use std::collections::{HashMap, HashSet};
use std::io::Read;
use std::path::PathBuf;
use std::sync::mpsc::{Receiver, Sender, channel};
use std::sync::{Arc, Mutex};
use std::time::Duration;
/// Riot's public asset CDN.
const HOST: &str = "https://ddragon.leagueoflegends.com";
/// The champion list: Data Dragon ids ("Kaisa") by display name ("Kai'Sa"), for one patch.
#[derive(Clone, serde::Deserialize, serde::Serialize)]
struct Catalog {
version: String,
ids: HashMap<String, String>,
}
/// Where the portraits and the champion list are cached.
fn cache_dir() -> PathBuf {
directories::ProjectDirs::from("com", "leaguerecorder", "leaguerecorder")
.map(|dirs| dirs.cache_dir().join("portraits"))
.unwrap_or_else(|| PathBuf::from("./portraits"))
}
/// Champion portraits drawn from the cache, with the missing ones fetched in the background.
pub struct Portraits {
dir: PathBuf,
images: rune::ImageCache,
catalog: Arc<Mutex<Option<Catalog>>>,
asked: Mutex<HashSet<String>>,
tx: Sender<String>,
}
impl Portraits {
pub fn new(waker: rune::Waker) -> Self {
let dir = cache_dir();
let _ = std::fs::create_dir_all(&dir);
let catalog = Arc::new(Mutex::new(read_catalog(&dir)));
let (tx, rx) = channel();
let worker = Worker {
dir: dir.clone(),
catalog: catalog.clone(),
wake: waker.clone(),
};
let spawned = std::thread::Builder::new()
.name("portraits".into())
.spawn(move || worker.run(rx));
if spawned.is_err() {
eprintln!("portrait downloads are unavailable");
}
Self {
dir,
images: rune::ImageCache::new(waker),
catalog,
asked: Mutex::new(HashSet::new()),
tx,
}
}
/// The portrait for a champion's display name at `size` points, once it is on disk. A
/// missing one is queued and the app redraws when it arrives.
pub fn image(&self, champion: &str, size: f32, scale: f32) -> Option<rune::Image> {
let champion = champion.trim();
if champion.is_empty() {
return None;
}
let path = {
let catalog = self.catalog.lock().unwrap();
let Some(catalog) = catalog.as_ref() else {
drop(catalog);
self.ask(champion);
return None;
};
let id = catalog.ids.get(champion)?;
self.dir.join(format!("{id}.png"))
};
if !path.is_file() {
self.ask(champion);
return None;
}
Some(self.images.file(&path, size, scale))
}
fn ask(&self, champion: &str) {
if self.asked.lock().unwrap().insert(champion.to_string()) {
let _ = self.tx.send(champion.to_string());
}
}
}
/// The cache's background thread: the champion list first, then one portrait at a time.
struct Worker {
dir: PathBuf,
catalog: Arc<Mutex<Option<Catalog>>>,
wake: rune::Waker,
}
impl Worker {
fn run(self, rx: Receiver<String>) {
if self.catalog.lock().unwrap().is_none() {
match self.ensure_catalog() {
Some(catalog) => {
*self.catalog.lock().unwrap() = Some(catalog);
(self.wake)();
}
None => eprintln!("champion list unavailable; drawing initials instead"),
}
}
while let Ok(name) = rx.recv() {
self.download(&name);
}
}
/// The cached champion list, or a fresh one written next to the portraits.
fn ensure_catalog(&self) -> Option<Catalog> {
if let Some(catalog) = read_catalog(&self.dir) {
return Some(catalog);
}
let catalog = fetch_catalog()?;
let text = serde_json::to_vec(&catalog).ok()?;
let path = self.dir.join("catalog.json");
let _ = std::fs::write(path.with_extension("part"), text);
let _ = std::fs::rename(path.with_extension("part"), &path);
Some(catalog)
}
fn download(&self, champion: &str) {
let (id, version) = {
let catalog = self.catalog.lock().unwrap();
let Some(catalog) = catalog.as_ref() else {
return;
};
let Some(id) = catalog.ids.get(champion).cloned() else {
return;
};
(id, catalog.version.clone())
};
let path = self.dir.join(format!("{id}.png"));
if path.is_file() {
return;
}
let url = format!("{HOST}/cdn/{version}/img/champion/{id}.png");
let Some(bytes) = get(&url) else {
return;
};
if bytes.is_empty() {
return;
}
let part = path.with_extension("part");
if std::fs::write(&part, bytes).is_ok() && std::fs::rename(&part, &path).is_ok() {
(self.wake)();
}
}
}
fn read_catalog(dir: &std::path::Path) -> Option<Catalog> {
let bytes = std::fs::read(dir.join("catalog.json")).ok()?;
serde_json::from_slice(&bytes).ok()
}
/// The champion list of the latest patch: display names to Data Dragon ids.
fn fetch_catalog() -> Option<Catalog> {
let versions: Vec<String> =
serde_json::from_slice(&get(&format!("{HOST}/api/versions.json"))?).ok()?;
let version = versions.into_iter().next()?;
let url = format!("{HOST}/cdn/{version}/data/en_US/champion.json");
let data: serde_json::Value = serde_json::from_slice(&get(&url)?).ok()?;
let mut ids = HashMap::new();
for (id, champion) in data.get("data")?.as_object()? {
if let Some(name) = champion.get("name").and_then(|name| name.as_str()) {
ids.insert(name.to_string(), id.clone());
}
}
(!ids.is_empty()).then_some(Catalog { version, ids })
}
fn get(url: &str) -> Option<Vec<u8>> {
let mut response = ureq::get(url)
.config()
.timeout_global(Some(Duration::from_secs(20)))
.build()
.call()
.ok()?;
let mut bytes = Vec::new();
response
.body_mut()
.as_reader()
.read_to_end(&mut bytes)
.ok()?;
Some(bytes)
}
+13 -47
View File
@@ -1,7 +1,7 @@
//! Match history: the timelines on disk, newest first, filtered by queue.
//!
//! The card reads like `GameHistory.vue`: result banner, champion, queue, KDA, per-minute
//! stats, items are not shown because the app has no Data Dragon image cache yet.
//! The card reads like `GameHistory.vue`: result banner, champion portrait, queue, KDA and
//! per-minute stats. Items are not shown: the timeline does not carry them.
use rune::tok::{radius, space, type_};
use rune::{Color, El, col, el, row, text};
@@ -41,7 +41,8 @@ pub fn view(app: &App, p: Paint) -> El {
.filter(|(_, g)| app.filter.is_none_or(|f| g.category() == f))
.collect();
let mut list = col().key("games").w_full().gap(space::S2);
// The scroll bar gets its own strip at the end, clear of the cards.
let mut list = col().key("games").w_full().gap(space::S2).pr(14.0);
if !app.games_loaded {
list = list.child(
text("Loading match history…")
@@ -64,7 +65,7 @@ pub fn view(app: &App, p: Paint) -> El {
));
} else {
for (index, game) in filtered {
list = list.child(game_card(p, game, index));
list = list.child(game_card(app, p, game, index));
}
}
@@ -113,8 +114,8 @@ pub fn view(app: &App, p: Paint) -> El {
)
.child(
app.scroll.follow(
"list-scroller",
col()
.key("list-scroller")
.w_full()
.grow(1.0)
.min_h(0.0)
@@ -147,7 +148,7 @@ fn empty(p: Paint, title: &str, detail: &str) -> El {
)
}
fn game_card(p: Paint, game: &Timeline, index: usize) -> El {
fn game_card(app: &App, p: Paint, game: &Timeline, index: usize) -> El {
let outcome = game.outcome();
let ink = outcome_color(p, outcome);
let champion = game.champion().unwrap_or_else(|| "Unknown champion".into());
@@ -242,7 +243,12 @@ fn game_card(p: Paint, game: &Timeline, index: usize) -> El {
.key("identity")
.gap(space::S3)
.center_y()
.child(portrait(p, game.champion().as_deref()))
.child(ui::champion_portrait(
app,
p,
game.champion().as_deref(),
52.0,
))
.child(
col()
.key("identity-labels")
@@ -312,43 +318,3 @@ fn stat(p: Paint, value: &str, label: &str) -> El {
)
.child(text(label).key("label").font(body(10.5)).color(p.muted()))
}
/// A square champion tile. There is no Data Dragon image cache yet, so the tile carries the
/// champion's initials on a colour derived from the name: the same champion always gets the
/// same tile.
fn portrait(p: Paint, champion: Option<&str>) -> El {
let name = champion.unwrap_or_default();
let hue = name
.bytes()
.fold(2166136261u32, |hash, byte| {
hash.wrapping_mul(16777619) ^ byte as u32
})
.rem_euclid(360) as f32;
let (fill, ink) = if name.is_empty() {
(p.t.control_off, p.muted())
} else {
(rune::oklch(0.36, 0.075, hue), rune::oklch(0.94, 0.02, hue))
};
el().key("portrait")
.size(52.0, 52.0)
.radius(radius::MD)
.fill(fill)
.border(p.hair, ink.alpha(0.18))
.a11y_hidden()
.child(text(initials(name)).font(heading(17.0)).color(ink).center())
}
/// Up to two letters from the champion's name: `Kai'Sa` is KS, `Jinx` is J.
fn initials(name: &str) -> String {
let letters: Vec<char> = name
.split(|c: char| !c.is_alphanumeric())
.filter(|word| !word.is_empty())
.filter_map(|word| word.chars().next())
.take(2)
.collect();
if letters.is_empty() {
"?".into()
} else {
letters.into_iter().collect()
}
}
+139 -104
View File
@@ -18,6 +18,7 @@ pub struct Review {
pub time: f64,
pub duration: f64,
pub scrubber_width: f32,
pub show_details: bool,
pub highlights: Vec<Highlight>,
pub export: Option<Receiver<Result<String, String>>>,
pub export_note: Option<String>,
@@ -169,6 +170,12 @@ pub fn view(app: &App, p: Paint) -> El {
app.screen = Screen::History;
},
))
.child(ui::champion_portrait(
app,
p,
game.champion().as_deref(),
26.0,
))
.child(
text(game.champion().unwrap_or_else(|| "Unknown champion".into()))
.key("champion")
@@ -199,6 +206,41 @@ pub fn view(app: &App, p: Paint) -> El {
.color(p.muted()),
);
// The player takes the window: the clip is why the screen exists. The details column
// opens beside it on demand, so a closed panel leaves the clip the whole width.
let body = row()
.key("review-body")
.w_full()
.grow(1.0)
.min_h(0.0)
.gap(space::S3)
.child(
col()
.key("player")
.grow(1.0)
.min_w(0.0)
.min_h(0.0)
.gap(space::S2)
.child(video_stage(app, p))
.child(transport(app, p))
.child(scrubber(app, p, game)),
);
let body = if app.review.show_details {
body.child(
col()
.key("details")
.w(380.0)
.min_w(320.0)
.h_full()
.min_h(0.0)
.gap(space::S2)
.child(highlights(app, p, game))
.child(events(app, p, game)),
)
} else {
body
};
col()
.key("review")
.w_full()
@@ -206,111 +248,103 @@ pub fn view(app: &App, p: Paint) -> El {
.padding(space::S6)
.gap(space::S3)
.child(header)
.child(video_stage(app, p))
.child(scrubber(app, p, game))
.child(
row()
.key("review-body")
.w_full()
.grow(1.0)
.min_h(0.0)
.gap(space::S3)
.child(highlights(app, p, game))
.child(events(app, p, game)),
)
.child(body)
}
/// The clip itself: the largest 16:9 box that fits, on black, with a message when there is no
/// file to play.
fn video_stage(app: &App, p: Paint) -> El {
let mut stage = el()
let stage = el()
.key("stage")
.w_full()
.grow(1.0)
.min_h(0.0)
.radius(radius::LG)
.fill(rune::Color::BLACK)
.clip_soft(radius::LG);
.radius(radius::LG)
.clip_soft(radius::LG)
.center();
if let Some(player) = &app.review.player {
stage = stage.child(
match &app.review.player {
Some(player) => stage.child(
el().key("video")
.w_full()
.h_full()
.video(player, SurfaceFit::Fit),
);
} else {
stage = stage.child(
col()
.key("stage-empty")
.w_full()
.h_full()
.center()
.gap(6.0)
.child(
text(
app.review
.error
.clone()
.unwrap_or_else(|| "Loading the clip…".into()),
)
.key("stage-message")
.font(body(13.0))
.color(p.muted()),
),
);
}
col()
.key("stage-column")
.w_full()
.grow(1.0)
.min_h(0.0)
.gap(space::S2)
.child(stage)
.child(
row()
.key("transport")
.w_full()
.center_y()
.gap(space::S3)
.child(ui::button(
p,
"play-pause",
if playing(app) { "Pause" } else { "Play" },
false,
|app: &mut App| {
app.review.playback();
},
))
.child(ui::button(p, "rewind", "-10 s", false, |app: &mut App| {
let at = app.review.time - 10.0;
app.review.seek(at);
}))
.child(ui::button(p, "advance", "+10 s", false, |app: &mut App| {
let at = app.review.time + 10.0;
app.review.seek(at);
}))
.child(
text(format!(
"{} / {}",
format::clock(app.review.time),
format::clock(app.review.duration)
))
.key("time")
.font(type_::MONO_CAPTION)
.color(p.muted()),
.aspect_fit(16.0 / 9.0)
.video(player, SurfaceFit::Fill),
),
None => stage.child(
col().key("stage-empty").center().gap(6.0).child(
text(
app.review
.error
.clone()
.unwrap_or_else(|| "Loading the clip…".into()),
)
.child(el().grow(1.0))
.child(
text(
app.review.export_note.clone().unwrap_or_else(|| {
format!("{} highlights", app.review.highlights.len())
}),
)
.key("export-note")
.font(body(11.5))
.color(p.muted()),
),
.key("stage-message")
.font(body(13.0))
.color(p.muted()),
),
),
}
}
/// Play/pause, the ten-second steps and the clock, with the highlights toggle on the other
/// side: the list is one press away, not a column that always takes the clip's width.
fn transport(app: &App, p: Paint) -> El {
let count = app.review.highlights.len();
let bar = row()
.key("transport")
.w_full()
.center_y()
.gap(space::S2)
.child(ui::button(
p,
"play-pause",
if playing(app) { "Pause" } else { "Play" },
false,
|app: &mut App| {
app.review.playback();
},
))
.child(ui::button(p, "rewind", "-10 s", false, |app: &mut App| {
let at = app.review.time - 10.0;
app.review.seek(at);
}))
.child(ui::button(p, "advance", "+10 s", false, |app: &mut App| {
let at = app.review.time + 10.0;
app.review.seek(at);
}))
.child(
text(format!(
"{} / {}",
format::clock(app.review.time),
format::clock(app.review.duration)
))
.key("time")
.font(type_::MONO_CAPTION)
.color(p.muted()),
)
.child(el().grow(1.0));
let bar = match &app.review.export_note {
Some(note) => bar.child(
text(note.clone())
.key("export-note")
.font(body(11.5))
.color(p.muted()),
),
None => bar,
};
bar.child(ui::button(
p,
"toggle-details",
&if app.review.show_details {
"Hide details".to_string()
} else {
format!("Highlights · {count}")
},
false,
|app: &mut App| {
app.review.show_details = !app.review.show_details;
},
))
}
fn playing(app: &App) -> bool {
@@ -551,8 +585,9 @@ fn highlights(app: &App, p: Paint, game: &Timeline) -> El {
col()
.key("highlights-panel")
.w(360.0)
.h_full()
.w_full()
.grow(1.0)
.min_h(0.0)
.gap(space::S2)
.child(
text("Highlights")
@@ -562,20 +597,20 @@ fn highlights(app: &App, p: Paint, game: &Timeline) -> El {
)
.child(
app.highlights_scroll.follow(
"highlight-scroller",
col()
.key("highlight-scroller")
.w_full()
.grow(1.0)
.min_h(0.0)
.scroll(rune::ScrollSpec {
stick_bottom: false,
})
.child(list),
.child(list.pr(14.0)),
),
)
}
fn events(app: &App, p: Paint, game: &Timeline) -> El {
fn events(_app: &App, p: Paint, game: &Timeline) -> El {
let interesting = |kind: &str| {
matches!(
kind,
@@ -640,9 +675,9 @@ fn events(app: &App, p: Paint, game: &Timeline) -> El {
col()
.key("events-panel")
.grow(1.0)
.min_w(240.0)
.h_full()
.w_full()
.grow(1.5)
.min_h(0.0)
.gap(space::S2)
.child(
text("Timeline")
@@ -651,16 +686,16 @@ fn events(app: &App, p: Paint, game: &Timeline) -> El {
.color(p.muted()),
)
.child(
app.events_scroll.follow(
_app.events_scroll.follow(
"event-scroller",
col()
.key("event-scroller")
.w_full()
.grow(1.0)
.min_h(0.0)
.scroll(rune::ScrollSpec {
stick_bottom: false,
})
.child(list),
.child(list.pr(14.0)),
),
)
}
+4 -2
View File
@@ -222,11 +222,13 @@ pub fn view(app: &App, p: Paint) -> El {
let kit = rune_kit::Kit::neutral(app.dark);
let mut layer = Vec::new();
// The scroll bar gets its own strip at the end, clear of the cards.
let content = col()
.key("tab-content")
.w_full()
.gap(space::S6)
.pb(space::S6);
.pb(space::S6)
.pr(14.0);
let content = match app.settings_tab {
SettingsTab::General => general(app, p, &kit, &mut layer, content),
SettingsTab::Recording => recording(app, p, &kit, &mut layer, content),
@@ -288,8 +290,8 @@ pub fn view(app: &App, p: Paint) -> El {
.child(tabs(p, app))
.child(
app.scroll.follow(
"scroller",
col()
.key("scroller")
.w_full()
.grow(1.0)
.min_h(0.0)
+99 -13
View File
@@ -11,6 +11,7 @@ pub struct Paint {
pub accent: Color,
pub dark: bool,
pub hair: f32,
pub scale: f32,
}
impl Paint {
@@ -20,6 +21,7 @@ impl Paint {
accent: tok::accent(0, dark),
dark,
hair: 1.0 / scale,
scale,
}
}
@@ -346,8 +348,70 @@ pub fn dot(color: Color) -> El {
.a11y_hidden()
}
/// A scroll viewport's scrollbar. The viewport reports where it is; the thumb follows in the
/// same frame, so a drag scrolls the list and the bar together.
/// A square champion portrait at `size` points: the Data Dragon file once it is on disk,
/// initials on a colour derived from the name until then (and offline).
pub fn champion_portrait(app: &App, p: Paint, champion: Option<&str>, size: f32) -> El {
let name = champion.unwrap_or_default();
let hue = name
.bytes()
.fold(2166136261u32, |hash, byte| {
hash.wrapping_mul(16777619) ^ byte as u32
})
.rem_euclid(360) as f32;
let (fill, ink) = if name.is_empty() {
(p.t.control_off, p.muted())
} else {
(rune::oklch(0.36, 0.075, hue), rune::oklch(0.94, 0.02, hue))
};
let radius = (size * 0.14).max(2.0);
let tile = el()
.key("portrait")
.size(size, size)
.radius(radius)
.fill(fill)
.border(p.hair, ink.alpha(0.18))
.a11y_hidden();
match app
.portraits
.as_ref()
.and_then(|portraits| portraits.image(name, size, p.scale))
{
Some(image) => tile.child(
el().key("portrait-image")
.w_full()
.h_full()
.radius(radius)
.pixels(image.pixels()),
),
None => tile.child(
text(initials(name))
.font(heading(size * 0.33))
.color(ink)
.center(),
),
}
}
/// Up to two letters from the champion's name: `Kai'Sa` is KS, `Jinx` is J.
fn initials(name: &str) -> String {
let letters: Vec<char> = name
.split(|c: char| !c.is_alphanumeric())
.filter(|word| !word.is_empty())
.filter_map(|word| word.chars().next())
.take(2)
.collect();
if letters.is_empty() {
"?".into()
} else {
letters.into_iter().collect()
}
}
/// A scroll viewport's scroll bar: a thumb in a strip of its own at the viewport's end edge,
/// shown whenever the content overflows, and dragged to scroll.
///
/// The screen lays the thumb where the viewport's strip is (the content leaves it room), so it
/// never draws over a card. `follow` takes where the viewport is, `thumb` draws it.
pub struct ScrollBar {
area: rune::Live<[f32; 4]>,
thumb: rune::Live<[f32; 4]>,
@@ -369,35 +433,57 @@ impl ScrollBar {
}
}
/// Make this viewport's scrolling move the thumb.
pub fn follow(&self, viewport: El) -> El {
/// Make this viewport's scrolling move the thumb, and its key one a drag can scroll to.
pub fn follow(&self, key: &'static str, viewport: El) -> El {
let reported = self.area.clone();
let area = self.area.clone();
let last = self.last.clone();
let on_layout_last = self.last.clone();
let on_layout_thumb = self.thumb.clone();
let thumb = self.thumb.clone();
let layout_thumb = self.thumb.clone();
let last = self.last.clone();
let layout_last = self.last.clone();
viewport
.on_layout_tx(move |_app: &mut App, rect, tx| {
reported.set(rect);
place(&on_layout_thumb, rect, on_layout_last.get());
place(&layout_thumb, rect, layout_last.get());
tx.live_only();
})
.on_scroll_offset(move |at: rune::ScrollPos| {
last.set(at);
place(&thumb, area.get(), at);
})
.key(key)
}
/// The thumb, drawn over the window. `key` must differ per bar on one screen.
pub fn thumb(&self, p: Paint, key: &str) -> El {
pub fn thumb(&self, p: Paint, key: &'static str, viewport: &'static str) -> El {
let last = self.last.clone();
let area = self.area.clone();
el().key(key)
.absolute(0.0, 0.0)
.size(6.0, 0.0)
.radius(3.0)
.fill(p.t.text_secondary.alpha(0.5))
.size(10.0, 0.0)
.radius(5.0)
.fill(p.t.text_secondary.alpha(0.45))
.hover(p.t.text_secondary.alpha(0.8))
.live_rect(&self.thumb)
.a11y_hidden()
.on_drag_any(move |d: &mut rune::Drag, tx: &mut rune::Tx| {
tx.live_only();
let at = last.get();
let max = at.max[1];
let [_, _, _, area_h] = area.get();
let travel = (area_h - d.h).max(1.0);
if max <= 0.5 || area_h <= 1.0 {
return;
}
match d.phase {
rune::Phase::Down => d.data = at.offset[1],
rune::Phase::Move => {
let y = (d.data + d.dy * max / travel).clamp(0.0, max);
tx.scroll_to(viewport, 0.0, y);
}
rune::Phase::Up => {}
}
})
}
}
@@ -410,5 +496,5 @@ fn place(thumb: &rune::Live<[f32; 4]>, [x, y, w, h]: [f32; 4], at: rune::ScrollP
}
let height = (h * at.viewport[1] / content).clamp(28.0, h);
let progress = (at.offset[1] / at.max[1]).clamp(0.0, 1.0);
thumb.set([x + w - 9.0, y + progress * (h - height), 6.0, height]);
thumb.set([x + w - 12.0, y + progress * (h - height), 10.0, height]);
}