S013: controls, menus, dialogs, toasts and gallery
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
parent
0062a4a9d1
commit
8b487050e1
21 changed files with 3952 additions and 16 deletions
|
|
@ -13,14 +13,14 @@ Every control in M3 Expressive form, so screens are only assembly. FEATURES 9.4
|
|||
- ~/Projects/Mulberry/src/ui/widgets.rs (buttons, menus)
|
||||
|
||||
## Steps
|
||||
- [ ] Buttons (five kinds, sizes), icon buttons that morph on press, toggle buttons, connected button group whose neighbours give way, split button, FAB and FAB menu, floating toolbar
|
||||
- [ ] Text field, number with unit, search, combo, slider, range, switch, checkbox, radio, chips, segmented control with sliding selection, tabs
|
||||
- [ ] Menus and submenus that keep to the window, context menus, tooltips with shortcuts
|
||||
- [ ] Dialogs of fixed widths, side sheet, confirm; Enter, Escape, focus trap and focus return
|
||||
- [ ] Toasts with action and undo, stacked, pause on hover
|
||||
- [ ] Progress-free states for each: hover, press, focus ring, disabled, error, loading after 300 ms
|
||||
- [ ] Gallery screen behind `--gallery`, shots of every control in light, dark and hovered
|
||||
- [ ] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S013: …`, push
|
||||
- [x] Buttons (five kinds, sizes), icon buttons that morph on press, toggle buttons, connected button group whose neighbours give way, split button, FAB and FAB menu, floating toolbar
|
||||
- [x] Text field, number with unit, search, combo, slider, range, switch, checkbox, radio, chips, segmented control with sliding selection, tabs
|
||||
- [x] Menus and submenus that keep to the window, context menus, tooltips with shortcuts
|
||||
- [x] Dialogs of fixed widths, side sheet, confirm; Enter, Escape, focus trap and focus return
|
||||
- [x] Toasts with action and undo, stacked, pause on hover
|
||||
- [x] Progress-free states for each: hover, press, focus ring, disabled, error, loading after 300 ms
|
||||
- [x] Gallery screen behind `--gallery`, shots of every control in light, dark and hovered
|
||||
- [x] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S013: …`, push
|
||||
|
||||
## End criteria
|
||||
- `nice cargo test -j 2 -p medlar --test widgets` green: hover, press, keyboard, focus return, popups inside the window
|
||||
|
|
|
|||
|
|
@ -24,7 +24,7 @@ Tracker: https://claude.ai/artifact/XouimfVJS6FYVKskGJ8s7H
|
|||
|
||||
## 03 Interface
|
||||
|
||||
- [ ] [S013](03%20Interface/S013-controls.md) Controls, dialogs and toasts
|
||||
- [x] [S013](03%20Interface/S013-controls.md) Controls, dialogs and toasts
|
||||
- [ ] [S014](03%20Interface/S014-wavy-parts-shapes.md) Wavy bars, parts map, shapes and speed graph
|
||||
- [ ] [S015](03%20Interface/S015-main-window.md) Main window and list
|
||||
- [ ] [S016](03%20Interface/S016-add-dialog.md) Add dialog, batch and duplicates
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@
|
|||
use crate::desktop::{Sources, Watch};
|
||||
use crate::motion;
|
||||
use crate::theme::Theme;
|
||||
use crate::ui::gallery;
|
||||
use crate::{fonts, icons, tokens};
|
||||
use eframe::egui::{self, Align2, Context, Ui, ViewportBuilder};
|
||||
use medlar_core::paths::Paths;
|
||||
|
|
@ -68,13 +69,19 @@ impl App {
|
|||
}
|
||||
}
|
||||
|
||||
impl eframe::App for App {
|
||||
/// The app and which of its screens the window shows.
|
||||
struct Window {
|
||||
app: App,
|
||||
show: fn(&mut App, &mut Ui),
|
||||
}
|
||||
|
||||
impl eframe::App for Window {
|
||||
fn ui(&mut self, ui: &mut Ui, _: &mut eframe::Frame) {
|
||||
self.show(ui);
|
||||
(self.show)(&mut self.app, ui);
|
||||
}
|
||||
|
||||
fn clear_color(&self, _: &egui::Visuals) -> [f32; 4] {
|
||||
self.theme.surface.to_normalized_gamma_f32()
|
||||
self.app.theme.surface.to_normalized_gamma_f32()
|
||||
}
|
||||
|
||||
/// Only the window's place and size are remembered.
|
||||
|
|
@ -85,6 +92,15 @@ impl eframe::App for App {
|
|||
|
||||
/// Opens the window and returns when it is closed.
|
||||
pub fn run() -> ExitCode {
|
||||
open(App::show)
|
||||
}
|
||||
|
||||
/// Opens a window with every control instead (`--gallery`).
|
||||
pub fn run_gallery() -> ExitCode {
|
||||
open(|app, ui| app.frame(ui, gallery::show))
|
||||
}
|
||||
|
||||
fn open(show: fn(&mut App, &mut Ui)) -> ExitCode {
|
||||
let paths = Paths::detect();
|
||||
if let Err(e) = paths.create() {
|
||||
eprintln!("{}: {e}", paths.config.display());
|
||||
|
|
@ -110,7 +126,7 @@ pub fn run() -> ExitCode {
|
|||
persistence_path: Some(paths.data.join("window.ron")),
|
||||
..Default::default()
|
||||
};
|
||||
let made = eframe::run_native(APP_ID, options, Box::new(move |cc| Ok(Box::new(App::new(&cc.egui_ctx, settings, Sources::detect())))));
|
||||
let made = eframe::run_native(APP_ID, options, Box::new(move |cc| Ok(Box::new(Window { app: App::new(&cc.egui_ctx, settings, Sources::detect()), show }))));
|
||||
if let Err(e) = made {
|
||||
eprintln!("{}", tr!("app.no_window", why = e));
|
||||
return ExitCode::FAILURE;
|
||||
|
|
|
|||
|
|
@ -9,5 +9,6 @@ pub mod icons;
|
|||
pub mod motion;
|
||||
pub mod theme;
|
||||
pub mod tokens;
|
||||
pub mod ui;
|
||||
|
||||
pub use app::run;
|
||||
pub use app::{run, run_gallery};
|
||||
|
|
|
|||
|
|
@ -5,5 +5,8 @@ fn main() -> ExitCode {
|
|||
if args.is_empty() {
|
||||
return medlar_app::run();
|
||||
}
|
||||
if args == ["--gallery"] {
|
||||
return medlar_app::run_gallery();
|
||||
}
|
||||
medlar_cli::run(args.into_iter())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -53,6 +53,18 @@ pub mod size {
|
|||
pub const CONTROL: f32 = 40.0;
|
||||
pub const HAIRLINE: f32 = 1.0;
|
||||
pub const FOCUS_RING: f32 = 2.0;
|
||||
/// The big button, the FAB, and a slider's handle.
|
||||
pub const LARGE: f32 = 56.0;
|
||||
pub const SWITCH: [f32; 2] = [52.0, 32.0];
|
||||
/// A row of a menu.
|
||||
pub const ROW: f32 = 36.0;
|
||||
pub const MENU_MIN: f32 = 176.0;
|
||||
pub const MENU_MAX: f32 = 336.0;
|
||||
pub const DIALOG_S: f32 = 360.0;
|
||||
pub const DIALOG_M: f32 = 480.0;
|
||||
pub const DIALOG_L: f32 = 640.0;
|
||||
pub const SHEET: f32 = 360.0;
|
||||
pub const TOAST: f32 = 440.0;
|
||||
pub const WINDOW: [f32; 2] = [1080.0, 720.0];
|
||||
pub const WINDOW_MIN: [f32; 2] = [480.0, 360.0];
|
||||
}
|
||||
|
|
@ -63,6 +75,19 @@ pub mod state {
|
|||
pub const PRESS: f32 = 0.12;
|
||||
pub const DRAG: f32 = 0.16;
|
||||
pub const DISABLED: f32 = 0.38;
|
||||
/// The fill of a disabled control.
|
||||
pub const DISABLED_FILL: f32 = 0.12;
|
||||
}
|
||||
|
||||
/// Waits, in seconds.
|
||||
pub mod time {
|
||||
/// A spinner shows only after this.
|
||||
pub const LOADING: f64 = 0.3;
|
||||
/// A pointer rests this long before a submenu opens or closes, so it can cross other rows on its way.
|
||||
pub const SUBMENU: f64 = 0.18;
|
||||
pub const TOAST: f64 = 5.0;
|
||||
/// A toast with a button stays longer.
|
||||
pub const TOAST_ACTION: f64 = 9.0;
|
||||
}
|
||||
|
||||
/// Resting surfaces have no shadow. Menus, dialogs and toasts have this one.
|
||||
|
|
|
|||
289
crates/app/src/ui/dialog.rs
Normal file
289
crates/app/src/ui/dialog.rs
Normal file
|
|
@ -0,0 +1,289 @@
|
|||
//! Dialogs and the side sheet. Call `show` every frame: they come and go by themselves, hold the focus while open and
|
||||
//! give it back.
|
||||
|
||||
use super::widgets::{Button, Kind, cr, enter_taken, key_down};
|
||||
use crate::fonts;
|
||||
use crate::motion::{forget, spring_from};
|
||||
use crate::theme::Theme;
|
||||
use crate::tokens::spring::{DEFAULT, EFFECT};
|
||||
use crate::tokens::{self, elevation, radius, space, text};
|
||||
use eframe::egui::{
|
||||
Align, Area, Color32, Context, FocusDirection, Id, Key, Layout, LayerId, Order, Rect, RichText, ScrollArea, Sense, Shape, Ui, UiBuilder, Vec2,
|
||||
accesskit::Role, pos2, vec2,
|
||||
};
|
||||
use medlar_core::tr;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
pub enum Answer {
|
||||
Main,
|
||||
Cancel,
|
||||
}
|
||||
|
||||
/// Is a dialog or sheet open? Shortcuts of the view wait until none is.
|
||||
pub fn any_open(ctx: &Context) -> bool {
|
||||
ctx.memory(|m| m.top_modal_layer().is_some())
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct State {
|
||||
open: bool,
|
||||
born: u64,
|
||||
/// Has the focus back at the end.
|
||||
back: Option<Id>,
|
||||
/// Had the focus last in here.
|
||||
inside: Option<Id>,
|
||||
}
|
||||
|
||||
/// What an overlay's content knows about itself.
|
||||
struct Shown {
|
||||
/// 0 to 1, may overshoot.
|
||||
v: f32,
|
||||
open: bool,
|
||||
/// On top, and not just opened by the key that is down.
|
||||
keys: bool,
|
||||
scrim_clicked: bool,
|
||||
}
|
||||
|
||||
/// A layer over everything else: scrim, coming and going, focus.
|
||||
fn overlay<R>(ctx: &Context, id: Id, name: &str, open: bool, draw: impl FnOnce(&mut Ui, Shown) -> R) -> Option<R> {
|
||||
let pass = ctx.cumulative_pass_nr();
|
||||
let mut s = ctx.data(|d| d.get_temp::<State>(id)).unwrap_or_default();
|
||||
if open && !s.open {
|
||||
s = State { open, born: pass, back: ctx.memory(|m| m.focused()), inside: None };
|
||||
ctx.memory_mut(|m| m.stop_text_input());
|
||||
} else if !open && s.open {
|
||||
s.open = false;
|
||||
ctx.memory_mut(|m| match s.back {
|
||||
Some(back) => m.request_focus(back),
|
||||
None => m.stop_text_input(),
|
||||
});
|
||||
ctx.request_repaint();
|
||||
}
|
||||
let v = spring_from((id, "shown"), 0.0, f32::from(open), DEFAULT);
|
||||
let fade = spring_from((id, "fade"), 0.0, f32::from(open), EFFECT).clamp(0.0, 1.0);
|
||||
if !open && fade < 0.01 {
|
||||
ctx.data_mut(|d| d.remove::<State>(id));
|
||||
forget((id, "shown"));
|
||||
forget((id, "fade"));
|
||||
return None;
|
||||
}
|
||||
let layer = LayerId::new(Order::Middle, id);
|
||||
let top = ctx.memory(|m| m.top_modal_layer() == Some(layer));
|
||||
if open {
|
||||
ctx.memory_mut(|m| m.set_modal_layer(layer));
|
||||
if s.inside.is_none() && pass < s.born + 8 {
|
||||
ctx.request_repaint();
|
||||
if top && ctx.memory(|m| m.focused().is_none()) {
|
||||
ctx.memory_mut(|m| m.move_focus(FocusDirection::Next));
|
||||
}
|
||||
}
|
||||
}
|
||||
let window = ctx.content_rect();
|
||||
let area = Area::new(id).order(Order::Middle).fixed_pos(window.min).constrain(false).fade_in(false).enabled(open).role(Role::Dialog).accessible_name(name);
|
||||
let out = area.show(ctx, |ui| {
|
||||
ui.set_opacity(fade);
|
||||
let scrim = ui.allocate_rect(window, Sense::CLICK | Sense::DRAG);
|
||||
ui.painter().rect_filled(window, 0.0, Color32::from_black_alpha((255.0 * elevation::SCRIM) as u8));
|
||||
// A sizing pass is drawn nowhere and answers nothing.
|
||||
draw(ui, Shown { v, open, keys: top && open && pass > s.born, scrim_clicked: scrim.clicked() })
|
||||
});
|
||||
if open && top {
|
||||
let focused = ctx.memory(|m| m.focused());
|
||||
if let Some(r) = focused.and_then(|f| ctx.read_response(f)) {
|
||||
if r.layer_id == layer {
|
||||
s.inside = focused;
|
||||
} else if !ctx.memory(|m| m.is_above_modal_layer(r.layer_id)) {
|
||||
// The arrow keys found a control behind the scrim.
|
||||
ctx.memory_mut(|m| match s.inside {
|
||||
Some(inside) => m.request_focus(inside),
|
||||
None => m.stop_text_input(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
ctx.data_mut(|d| d.insert_temp(id, s));
|
||||
Some(out.inner)
|
||||
}
|
||||
|
||||
/// A dialog of one of the fixed widths (`tokens::size::DIALOG_*`).
|
||||
pub struct Dialog<'a> {
|
||||
id: Id,
|
||||
title: &'a str,
|
||||
body: &'a str,
|
||||
width: f32,
|
||||
main: &'a str,
|
||||
cancel: Option<&'a str>,
|
||||
danger: bool,
|
||||
enabled: bool,
|
||||
busy: bool,
|
||||
}
|
||||
|
||||
impl<'a> Dialog<'a> {
|
||||
/// `main` is the verb on the main button.
|
||||
pub fn new(id: &str, title: &'a str, main: &'a str) -> Self {
|
||||
Dialog {
|
||||
id: Id::unique(("dialog", id)),
|
||||
title,
|
||||
body: "",
|
||||
width: tokens::size::DIALOG_M,
|
||||
main,
|
||||
cancel: None,
|
||||
danger: false,
|
||||
enabled: true,
|
||||
busy: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// A small one that only asks. `danger` is for what can't be taken back: Cancel has the focus then.
|
||||
pub fn confirm(id: &str, title: &'a str, body: &'a str, main: &'a str, danger: bool) -> Self {
|
||||
Dialog { body, danger, width: tokens::size::DIALOG_S, ..Dialog::new(id, title, main) }
|
||||
}
|
||||
|
||||
pub fn body(mut self, body: &'a str) -> Self {
|
||||
self.body = body;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn width(mut self, width: f32) -> Self {
|
||||
self.width = width;
|
||||
self
|
||||
}
|
||||
|
||||
/// Another word than "Cancel".
|
||||
pub fn cancel(mut self, cancel: &'a str) -> Self {
|
||||
self.cancel = Some(cancel);
|
||||
self
|
||||
}
|
||||
|
||||
/// Can the main action be done?
|
||||
pub fn enabled(mut self, enabled: bool) -> Self {
|
||||
self.enabled = enabled;
|
||||
self
|
||||
}
|
||||
|
||||
/// The main action is running.
|
||||
pub fn busy(mut self, busy: bool) -> Self {
|
||||
self.busy = busy;
|
||||
self
|
||||
}
|
||||
|
||||
/// The caller sets `open` to false when it gets an answer. `content` is drawn while it goes away, too.
|
||||
pub fn show(self, ctx: &Context, t: &Theme, open: bool, content: impl FnOnce(&mut Ui)) -> Option<Answer> {
|
||||
overlay(ctx, self.id, self.title, open, |ui, shown| self.draw(ui, t, shown, content))?
|
||||
}
|
||||
|
||||
fn draw(self, ui: &mut Ui, t: &Theme, shown: Shown, content: impl FnOnce(&mut Ui)) -> Option<Answer> {
|
||||
let ctx = ui.ctx().clone();
|
||||
let (pad, gap) = (space::XL, space::L);
|
||||
let room = ctx.content_rect().shrink(space::L);
|
||||
let width = self.width.min(room.width());
|
||||
let key = self.id.with("height");
|
||||
let known = ctx.data(|d| d.get_temp::<f32>(key));
|
||||
let height = known.unwrap_or(room.height()).min(room.height());
|
||||
if known.is_none() {
|
||||
// Its height comes out of this pass.
|
||||
ui.set_opacity(0.0);
|
||||
ctx.request_repaint();
|
||||
}
|
||||
let rect = on_pixels(Rect::from_center_size(room.center() + vec2(0.0, (1.0 - shown.v) * space::XL), vec2(width, height)), &ctx);
|
||||
let back = ui.painter().add(Shape::Noop);
|
||||
ui.interact(rect, self.id.with("ground"), Sense::CLICK | Sense::DRAG);
|
||||
let inner = Rect::from_min_size(rect.min + Vec2::splat(pad), vec2(width - 2.0 * pad, room.height() - 2.0 * pad));
|
||||
let mut ui = ui.new_child(UiBuilder::new().max_rect(inner).layout(Layout::top_down(Align::Min)));
|
||||
let ui = &mut ui;
|
||||
ui.spacing_mut().item_spacing = vec2(space::S, 0.0);
|
||||
ui.label(RichText::new(self.title).font(fonts::semi(text::TITLE)).color(t.on_surface));
|
||||
if !self.body.is_empty() {
|
||||
ui.add_space(space::S);
|
||||
ui.label(RichText::new(self.body).font(fonts::ui(text::BODY)).color(t.on_variant));
|
||||
}
|
||||
ui.add_space(gap);
|
||||
let footer = tokens::size::CONTROL + gap;
|
||||
let max = (inner.bottom() - ui.cursor().top() - footer).max(tokens::size::CONTROL);
|
||||
let used = scroll(ui, max, true, content);
|
||||
if used > 0.0 {
|
||||
ui.add_space(gap);
|
||||
}
|
||||
let mut answer = None;
|
||||
let row = Rect::from_min_size(pos2(inner.left(), ui.cursor().top()), vec2(inner.width(), tokens::size::CONTROL));
|
||||
ui.scope_builder(UiBuilder::new().max_rect(row).layout(Layout::right_to_left(Align::Center)), |ui| {
|
||||
let live = self.enabled && !self.busy;
|
||||
let main = Button::new(self.main).danger(self.danger).enabled(self.enabled).busy(self.busy).show(ui, t);
|
||||
let word = self.cancel.map_or_else(|| tr!("dialog.cancel"), str::to_string);
|
||||
let cancel = Button::new(&word).kind(Kind::Text).show(ui, t);
|
||||
if self.danger && shown.open && !shown.keys {
|
||||
cancel.request_focus();
|
||||
}
|
||||
if main.clicked() || shown.keys && live && key_down(&ctx, Key::Enter) && !enter_taken(&ctx) {
|
||||
answer = Some(Answer::Main);
|
||||
}
|
||||
if cancel.clicked() || shown.keys && key_down(&ctx, Key::Escape) {
|
||||
answer = Some(Answer::Cancel);
|
||||
}
|
||||
});
|
||||
let height = (ui.min_rect().height() + 2.0 * pad).min(room.height());
|
||||
if known != Some(height) {
|
||||
ctx.data_mut(|d| d.insert_temp(key, height));
|
||||
ctx.request_repaint();
|
||||
}
|
||||
let drawn = Rect::from_min_size(rect.min, vec2(width, height));
|
||||
let corner = cr(radius::XL);
|
||||
let shape = Shape::Vec(vec![elevation::floating(t.dark).as_shape(drawn, corner).into(), Shape::rect_filled(drawn, corner, t.container)]);
|
||||
ui.painter().set(back, shape);
|
||||
answer.filter(|_| shown.open)
|
||||
}
|
||||
}
|
||||
|
||||
/// The content, as wide as `ui` with room around it for focus rings. Gives back its height.
|
||||
fn scroll(ui: &mut Ui, max: f32, shrink: bool, content: impl FnOnce(&mut Ui)) -> f32 {
|
||||
let room = space::XS;
|
||||
let rect = Rect::from_min_size(ui.cursor().min - Vec2::splat(room), vec2(ui.available_width(), max) + Vec2::splat(2.0 * room));
|
||||
let area = ScrollArea::vertical().max_height(rect.height()).auto_shrink([false, shrink]).content_margin(room);
|
||||
let used = ui.scope_builder(UiBuilder::new().max_rect(rect), |ui| {
|
||||
area.show(ui, |ui| {
|
||||
ui.spacing_mut().item_spacing = vec2(space::S, space::M);
|
||||
let top = ui.cursor().top();
|
||||
content(ui);
|
||||
(ui.min_rect().bottom() - top).max(0.0)
|
||||
})
|
||||
.inner
|
||||
});
|
||||
used.inner
|
||||
}
|
||||
|
||||
/// Text on half pixels is blurred.
|
||||
fn on_pixels(rect: Rect, ctx: &Context) -> Rect {
|
||||
let ppp = ctx.pixels_per_point();
|
||||
rect.translate((rect.min * ppp).round() / ppp - rect.min)
|
||||
}
|
||||
|
||||
/// A panel over the right side. True when it should close: the button, Escape or a click beside it.
|
||||
pub fn sheet(ctx: &Context, t: &Theme, id: &str, title: &str, open: bool, content: impl FnOnce(&mut Ui)) -> bool {
|
||||
let id = Id::unique(("sheet", id));
|
||||
let closed = overlay(ctx, id, title, open, |ui, shown| {
|
||||
let (pad, gap) = (space::XL, space::S);
|
||||
let window = ctx.content_rect().shrink(gap);
|
||||
let width = tokens::size::SHEET.min(window.width() - tokens::size::CONTROL);
|
||||
let x = window.right() - width + (1.0 - shown.v) * (width + gap);
|
||||
let rect = on_pixels(Rect::from_min_max(pos2(x, window.top()), pos2(x + width, window.bottom())), ctx);
|
||||
ui.interact(rect, id.with("ground"), Sense::CLICK | Sense::DRAG);
|
||||
ui.painter().add(elevation::floating(t.dark).as_shape(rect, cr(radius::XL)));
|
||||
ui.painter().rect_filled(rect, cr(radius::XL), t.container);
|
||||
let mut ui = ui.new_child(UiBuilder::new().max_rect(rect.shrink(pad)).layout(Layout::top_down(Align::Min)));
|
||||
let ui = &mut ui;
|
||||
let mut close = false;
|
||||
let head = Rect::from_min_size(ui.max_rect().min, vec2(ui.max_rect().width(), tokens::size::CONTROL));
|
||||
ui.advance_cursor_after_rect(head);
|
||||
ui.add_space(space::M);
|
||||
// First, so the focus starts in it.
|
||||
scroll(ui, ui.available_height(), false, content);
|
||||
ui.scope_builder(UiBuilder::new().max_rect(head).layout(Layout::right_to_left(Align::Center)), |ui| {
|
||||
close = Button::icon("close", &tr!("dialog.close")).keys("Esc").show(ui, t).clicked();
|
||||
ui.with_layout(Layout::left_to_right(Align::Center), |ui| {
|
||||
ui.add(eframe::egui::Label::new(RichText::new(title).font(fonts::semi(text::TITLE)).color(t.on_surface)).truncate());
|
||||
});
|
||||
});
|
||||
shown.open && (close || shown.scrim_clicked || shown.keys && key_down(ctx, Key::Escape))
|
||||
});
|
||||
closed.unwrap_or(false)
|
||||
}
|
||||
432
crates/app/src/ui/field.rs
Normal file
432
crates/app/src/ui/field.rs
Normal file
|
|
@ -0,0 +1,432 @@
|
|||
//! Text field, number with a unit, search, and the box that opens a list.
|
||||
|
||||
use super::menu::{self, Item};
|
||||
use super::widgets::{
|
||||
Button, Size, chevron, cr, disabled_fill, disabled_ink, feel, key_down, left, line, ring, spinner, take_enter, waiting,
|
||||
};
|
||||
use crate::motion::spring;
|
||||
use crate::theme::{Theme, alpha, mix};
|
||||
use crate::tokens::spring::{EFFECT, FAST};
|
||||
use crate::tokens::{self, radius, space, text};
|
||||
use crate::{fonts, icons};
|
||||
use eframe::egui::accesskit::Role;
|
||||
use eframe::egui::{
|
||||
Align, Frame, Key, Layout, Margin, Modifiers, Rect, Response, RichText, Sense, Stroke, StrokeKind, TextEdit, Ui, UiBuilder, WidgetInfo, pos2,
|
||||
vec2,
|
||||
};
|
||||
use medlar_core::tr;
|
||||
use std::ops::RangeInclusive;
|
||||
|
||||
/// A box to write in, with its name above and a line of help or the error below.
|
||||
pub struct Field<'a> {
|
||||
label: &'a str,
|
||||
hint: &'a str,
|
||||
icon: &'a str,
|
||||
unit: &'a str,
|
||||
/// `Some` keeps the line below, so an error moves nothing.
|
||||
help: Option<&'a str>,
|
||||
error: Option<&'a str>,
|
||||
enabled: bool,
|
||||
busy: bool,
|
||||
password: bool,
|
||||
clear: bool,
|
||||
rows: usize,
|
||||
round: bool,
|
||||
width: Option<f32>,
|
||||
trail: f32,
|
||||
}
|
||||
|
||||
impl<'a> Field<'a> {
|
||||
/// `label` may be empty when something else names it; `named` then says it to screen readers.
|
||||
pub fn new(label: &'a str) -> Self {
|
||||
Field {
|
||||
label,
|
||||
hint: "",
|
||||
icon: "",
|
||||
unit: "",
|
||||
help: None,
|
||||
error: None,
|
||||
enabled: true,
|
||||
busy: false,
|
||||
password: false,
|
||||
clear: false,
|
||||
rows: 1,
|
||||
round: false,
|
||||
width: None,
|
||||
trail: 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn hint(mut self, hint: &'a str) -> Self {
|
||||
self.hint = hint;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn icon(mut self, icon: &'a str) -> Self {
|
||||
self.icon = icon;
|
||||
self
|
||||
}
|
||||
|
||||
/// Shown after the text.
|
||||
pub fn unit(mut self, unit: &'a str) -> Self {
|
||||
self.unit = unit;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn help(mut self, help: &'a str) -> Self {
|
||||
self.help = Some(help);
|
||||
self
|
||||
}
|
||||
|
||||
/// Takes the place of the help. Keeps the line below free for an error that may come.
|
||||
pub fn error(mut self, error: Option<&'a str>) -> Self {
|
||||
self.error = error;
|
||||
self.help = self.help.or(Some(""));
|
||||
self
|
||||
}
|
||||
|
||||
pub fn enabled(mut self, enabled: bool) -> Self {
|
||||
self.enabled = enabled;
|
||||
self
|
||||
}
|
||||
|
||||
/// Something is looked up; a spinner shows after a moment.
|
||||
pub fn busy(mut self, busy: bool) -> Self {
|
||||
self.busy = busy;
|
||||
self
|
||||
}
|
||||
|
||||
/// Hidden letters, with a button to see them.
|
||||
pub fn password(mut self) -> Self {
|
||||
self.password = true;
|
||||
self
|
||||
}
|
||||
|
||||
/// A button that empties it.
|
||||
pub fn clear(mut self) -> Self {
|
||||
self.clear = true;
|
||||
self
|
||||
}
|
||||
|
||||
/// Several lines. Enter starts a new one.
|
||||
pub fn rows(mut self, rows: usize) -> Self {
|
||||
self.rows = rows;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn width(mut self, width: f32) -> Self {
|
||||
self.width = Some(width);
|
||||
self
|
||||
}
|
||||
|
||||
/// The response is the text's: `changed()`, `lost_focus()`, `request_focus()`.
|
||||
pub fn show(self, ui: &mut Ui, t: &Theme, value: &mut String) -> Response {
|
||||
let width = self.width.unwrap_or(ui.available_width()).min(ui.available_width());
|
||||
ui.allocate_ui_with_layout(vec2(width, 0.0), Layout::top_down(Align::Min), |ui| {
|
||||
ui.spacing_mut().item_spacing.y = space::XS;
|
||||
self.label_above(ui, t);
|
||||
let r = self.body(ui, t, value, width);
|
||||
self.help_below(ui, t);
|
||||
r
|
||||
})
|
||||
.inner
|
||||
}
|
||||
|
||||
fn label_above(&self, ui: &mut Ui, t: &Theme) {
|
||||
if !self.label.is_empty() && !self.round {
|
||||
let ink = match (self.enabled, self.error.is_some()) {
|
||||
(false, _) => disabled_ink(t),
|
||||
(_, true) => t.error,
|
||||
_ => t.on_variant,
|
||||
};
|
||||
ui.label(RichText::new(self.label).font(fonts::med(text::LABEL)).color(ink));
|
||||
}
|
||||
}
|
||||
|
||||
fn help_below(&self, ui: &mut Ui, t: &Theme) {
|
||||
if let Some(help) = self.help {
|
||||
let (rect, r) = ui.allocate_exact_size(vec2(ui.available_width(), space::L), Sense::hover());
|
||||
let (what, ink) = match self.error {
|
||||
Some(e) => (e, t.error),
|
||||
None => (help, if self.enabled { t.on_variant } else { disabled_ink(t) }),
|
||||
};
|
||||
r.widget_info(|| WidgetInfo::labeled(Role::Label, true, what));
|
||||
let g = line(ui.painter(), what, fonts::ui(text::LABEL), ink, rect.width());
|
||||
if g.elided {
|
||||
super::widgets::tip(&r, t, what, "");
|
||||
}
|
||||
left(ui.painter(), rect.left_center(), g);
|
||||
}
|
||||
}
|
||||
|
||||
fn body(&self, ui: &mut Ui, t: &Theme, value: &mut String, width: f32) -> Response {
|
||||
let font = fonts::ui(text::BODY);
|
||||
let row_h = ui.fonts_mut(|f| f.row_height(&font));
|
||||
let many = self.rows > 1;
|
||||
let pad_y = (tokens::size::CONTROL - row_h) / 2.0;
|
||||
let h = if many { row_h * self.rows as f32 + 2.0 * pad_y } else { tokens::size::CONTROL };
|
||||
let (rect, ground) = ui.allocate_exact_size(vec2(width, h), if self.enabled { Sense::CLICK } else { Sense::hover() });
|
||||
let id = ground.id.with("edit");
|
||||
if ground.clicked() {
|
||||
ui.memory_mut(|m| m.request_focus(id));
|
||||
}
|
||||
let focused = ui.memory(|m| m.has_focus(id));
|
||||
let hovered = ui.rect_contains_pointer(rect) && self.enabled;
|
||||
let lit = spring((id, "lit"), f32::from(focused), EFFECT);
|
||||
let tint = spring((id, "tint"), if hovered { tokens::state::HOVER } else { 0.0 }, EFFECT);
|
||||
let corner = cr(if self.round { h / 2.0 } else { radius::M });
|
||||
let line_color = match (self.enabled, self.error.is_some()) {
|
||||
(false, _) => disabled_fill(t),
|
||||
(_, true) => t.error,
|
||||
_ => mix(if self.round { alpha(t.outline, 0.0) } else { t.outline }, t.primary, lit),
|
||||
};
|
||||
let p = ui.painter();
|
||||
p.rect_filled(rect, corner, if !self.enabled { alpha(disabled_fill(t), 0.3) } else if self.round { t.high } else { t.lowest });
|
||||
p.rect_filled(rect, corner, alpha(t.on_surface, tint));
|
||||
let stroke = tokens::size::HAIRLINE + lit * (tokens::size::FOCUS_RING - tokens::size::HAIRLINE);
|
||||
p.rect_stroke(rect, corner, Stroke::new(stroke, line_color), StrokeKind::Inside);
|
||||
|
||||
let ink = if self.enabled { t.on_surface } else { disabled_ink(t) };
|
||||
let faint = if self.enabled { t.on_variant } else { disabled_ink(t) };
|
||||
let (mut x, mut end) = (rect.left() + space::M, rect.right() - space::M);
|
||||
if !self.icon.is_empty() {
|
||||
icons::paint(p, pos2(x + tokens::icon::M / 2.0, rect.top() + tokens::size::CONTROL / 2.0), tokens::icon::M, self.icon, faint);
|
||||
x += tokens::icon::M + space::S;
|
||||
}
|
||||
end -= self.trail;
|
||||
let shown_key = id.with("password shown");
|
||||
let mut shown = ui.data(|d| d.get_temp::<bool>(shown_key)).unwrap_or(false);
|
||||
let wait = waiting(ui.ctx(), id, self.busy);
|
||||
// Drawn after the text, so Tab reaches the text first.
|
||||
let button_at = pos2(end - space::S - 4.0, rect.center().y);
|
||||
let has_button = self.password || !wait && self.clear && !value.is_empty();
|
||||
if has_button {
|
||||
end -= tokens::size::HIT;
|
||||
} else if wait {
|
||||
spinner(p, pos2(end - space::S, rect.center().y), tokens::icon::M, t.primary);
|
||||
end -= tokens::icon::M + space::S;
|
||||
}
|
||||
if !self.unit.is_empty() {
|
||||
let g = line(ui.painter(), self.unit, fonts::ui(text::BODY), faint, rect.width());
|
||||
end -= g.size().x;
|
||||
left(ui.painter(), pos2(end, rect.center().y), g);
|
||||
end -= space::S;
|
||||
}
|
||||
let inner = Rect::from_min_max(pos2(x, rect.top() + pad_y), pos2(end.max(x + space::L), rect.bottom() - pad_y));
|
||||
let edit = if many { TextEdit::multiline(&mut *value).desired_rows(self.rows) } else { TextEdit::singleline(&mut *value) };
|
||||
let edit = edit
|
||||
.id(id)
|
||||
.frame(Frame::NONE)
|
||||
.margin(Margin::ZERO)
|
||||
.font(font.clone())
|
||||
.text_color(ink)
|
||||
.hint_text(RichText::new(self.hint).font(font).color(alpha(faint, 0.9)))
|
||||
.password(self.password && !shown)
|
||||
.interactive(self.enabled)
|
||||
.desired_width(inner.width());
|
||||
let mut child = ui.new_child(UiBuilder::new().max_rect(inner).layout(Layout::top_down(Align::Min)));
|
||||
// egui makes a field at least this high, which would move its middle.
|
||||
child.spacing_mut().interact_size.y = 0.0;
|
||||
child.shrink_clip_rect(inner.expand2(vec2(1.0, 2.0)));
|
||||
let mut r = if many {
|
||||
eframe::egui::ScrollArea::vertical().id_salt(id).max_height(inner.height()).auto_shrink(false).show(&mut child, |ui| ui.add(edit)).inner
|
||||
} else {
|
||||
child.add(edit)
|
||||
};
|
||||
if !self.label.is_empty() {
|
||||
r = r.accessible_name(self.label);
|
||||
}
|
||||
if has_button {
|
||||
let (icon, name) = match (self.password, shown) {
|
||||
(true, true) => ("visibility_off", tr!("field.hide_password")),
|
||||
(true, false) => ("visibility", tr!("field.show_password")),
|
||||
_ => ("close", tr!("field.clear")),
|
||||
};
|
||||
let at = Rect::from_center_size(button_at, vec2(tokens::size::HIT, tokens::size::HIT));
|
||||
let b = ui.scope_builder(UiBuilder::new().max_rect(at), |ui| Button::icon(icon, &name).size(Size::S).enabled(self.enabled).show(ui, t)).inner;
|
||||
if b.clicked() && self.password {
|
||||
shown = !shown;
|
||||
ui.data_mut(|d| d.insert_temp(shown_key, shown));
|
||||
} else if b.clicked() {
|
||||
value.clear();
|
||||
r.request_focus();
|
||||
r.mark_changed();
|
||||
}
|
||||
}
|
||||
if many && r.has_focus() && key_down(ui.ctx(), Key::Enter) && ui.input(|i| i.modifiers.is_none()) {
|
||||
take_enter(ui.ctx());
|
||||
}
|
||||
r
|
||||
}
|
||||
}
|
||||
|
||||
/// A round field with a magnifying glass. Escape empties it.
|
||||
pub fn search(ui: &mut Ui, t: &Theme, name: &str, value: &mut String, width: f32) -> Response {
|
||||
let mut r = Field { round: true, ..Field::new(name) }.hint(name).icon("search").clear().width(width).show(ui, t, value);
|
||||
// Escape has taken the focus away before this frame.
|
||||
if r.lost_focus() && !value.is_empty() && ui.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape)) {
|
||||
value.clear();
|
||||
r.mark_changed();
|
||||
r.request_focus();
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
/// A number with a unit, buttons for less and more, and the arrow keys. Text that is no number shows as an error and is
|
||||
/// dropped when the field is left.
|
||||
pub struct Number<'a> {
|
||||
pub label: &'a str,
|
||||
pub unit: &'a str,
|
||||
pub range: RangeInclusive<f64>,
|
||||
pub step: f64,
|
||||
pub enabled: bool,
|
||||
pub width: f32,
|
||||
}
|
||||
|
||||
impl Number<'_> {
|
||||
/// True when the value is new.
|
||||
pub fn show(self, ui: &mut Ui, t: &Theme, value: &mut f64) -> bool {
|
||||
let before = *value;
|
||||
let key = ui.next_auto_id().with("number");
|
||||
let mut typed = ui.data(|d| d.get_temp::<String>(key)).unwrap_or_else(|| write(*value));
|
||||
let bad = read(&typed).is_none_or(|v| !self.range.contains(&v));
|
||||
let why = tr!("number.range", from = write(*self.range.start()), to = write(*self.range.end()));
|
||||
let side = 2.0 * tokens::size::HIT;
|
||||
let field = Field { trail: side - space::S, ..Field::new(self.label) }.unit(self.unit).enabled(self.enabled).width(self.width);
|
||||
let field = field.error(bad.then_some(why.as_str()));
|
||||
let top = ui.cursor().top();
|
||||
let r = field.show(ui, t, &mut typed);
|
||||
let mut step = 0.0;
|
||||
let box_mid = r.rect.center().y.max(top);
|
||||
let outer = r.rect.left() - space::M + self.width;
|
||||
for (i, (icon, name, by)) in [("add", tr!("number.more"), 1.0), ("remove", tr!("number.less"), -1.0)].into_iter().enumerate() {
|
||||
let at = pos2(outer - space::XS - tokens::size::HIT * (i as f32 + 0.5), box_mid);
|
||||
let rect = Rect::from_center_size(at, vec2(tokens::size::HIT, tokens::size::HIT));
|
||||
let can = self.enabled && if by > 0.0 { *value < *self.range.end() } else { *value > *self.range.start() };
|
||||
let b = ui.scope_builder(UiBuilder::new().max_rect(rect), |ui| Button::icon(icon, &name).size(Size::S).enabled(can).show(ui, t)).inner;
|
||||
if b.clicked() {
|
||||
step += by;
|
||||
}
|
||||
}
|
||||
if r.has_focus() {
|
||||
for (k, by) in [(Key::ArrowUp, 1.0), (Key::ArrowDown, -1.0), (Key::PageUp, 10.0), (Key::PageDown, -10.0)] {
|
||||
if ui.input(|i| i.key_pressed(k)) {
|
||||
step += by;
|
||||
}
|
||||
}
|
||||
}
|
||||
if step != 0.0 {
|
||||
*value = (*value + step * self.step).clamp(*self.range.start(), *self.range.end());
|
||||
typed = write(*value);
|
||||
} else if r.changed()
|
||||
&& let Some(v) = read(&typed).filter(|v| self.range.contains(v))
|
||||
{
|
||||
*value = v;
|
||||
}
|
||||
if r.has_focus() {
|
||||
ui.data_mut(|d| d.insert_temp(key, typed));
|
||||
} else {
|
||||
ui.data_mut(|d| d.remove::<String>(key));
|
||||
}
|
||||
if r.lost_focus() && bad {
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
*value != before
|
||||
}
|
||||
}
|
||||
|
||||
/// Whole numbers without a point, others with up to two places.
|
||||
fn write(v: f64) -> String {
|
||||
let s = format!("{v:.2}");
|
||||
s.trim_end_matches('0').trim_end_matches('.').to_string()
|
||||
}
|
||||
|
||||
/// A comma counts as the point.
|
||||
fn read(s: &str) -> Option<f64> {
|
||||
s.trim().replace(',', ".").parse::<f64>().ok().filter(|v| v.is_finite())
|
||||
}
|
||||
|
||||
/// A box that shows the chosen one of `options` and opens the list of them.
|
||||
pub struct Combo<'a> {
|
||||
pub label: &'a str,
|
||||
pub options: &'a [String],
|
||||
pub enabled: bool,
|
||||
pub busy: bool,
|
||||
pub error: Option<&'a str>,
|
||||
pub width: f32,
|
||||
}
|
||||
|
||||
impl<'a> Combo<'a> {
|
||||
pub fn new(label: &'a str, options: &'a [String], width: f32) -> Self {
|
||||
Combo { label, options, enabled: true, busy: false, error: None, width }
|
||||
}
|
||||
|
||||
/// True when the choice changed.
|
||||
pub fn show(self, ui: &mut Ui, t: &Theme, chosen: &mut usize) -> bool {
|
||||
let width = self.width.min(ui.available_width());
|
||||
let look = Field { error: self.error, help: self.error, enabled: self.enabled, ..Field::new(self.label) };
|
||||
ui.allocate_ui_with_layout(vec2(width, 0.0), Layout::top_down(Align::Min), |ui| {
|
||||
ui.spacing_mut().item_spacing.y = space::XS;
|
||||
look.label_above(ui, t);
|
||||
let changed = self.body(ui, t, chosen, width);
|
||||
look.help_below(ui, t);
|
||||
changed
|
||||
})
|
||||
.inner
|
||||
}
|
||||
|
||||
fn body(&self, ui: &mut Ui, t: &Theme, chosen: &mut usize, width: f32) -> bool {
|
||||
let live = self.enabled && !self.busy;
|
||||
let (rect, r) = ui.allocate_exact_size(vec2(width, tokens::size::CONTROL), if live { Sense::click() } else { Sense::hover() });
|
||||
let now = self.options.get(*chosen).map_or("", String::as_str);
|
||||
r.widget_info(|| WidgetInfo {
|
||||
current_text_value: Some(now.to_string()),
|
||||
..WidgetInfo::labeled(Role::ComboBox, live, self.label)
|
||||
});
|
||||
let f = feel(&r, live);
|
||||
let open = menu::is_open(ui.ctx(), &r);
|
||||
let turn = spring((r.id, "turn"), f32::from(open), FAST);
|
||||
let lit = spring((r.id, "lit"), f32::from(open), EFFECT);
|
||||
let corner = cr(radius::M);
|
||||
let (edge, ink, faint) = match (self.enabled, self.error.is_some()) {
|
||||
(false, _) => (disabled_fill(t), disabled_ink(t), disabled_ink(t)),
|
||||
(_, true) => (t.error, t.on_surface, t.error),
|
||||
_ => (mix(t.outline, t.primary, lit), t.on_surface, t.on_variant),
|
||||
};
|
||||
let p = ui.painter();
|
||||
p.rect_filled(rect, corner, if self.enabled { t.lowest } else { alpha(disabled_fill(t), 0.3) });
|
||||
p.rect_filled(rect, corner, alpha(t.on_surface, f.tint));
|
||||
let stroke = tokens::size::HAIRLINE + lit * (tokens::size::FOCUS_RING - tokens::size::HAIRLINE);
|
||||
p.rect_stroke(rect, corner, Stroke::new(stroke, edge), StrokeKind::Inside);
|
||||
if f.focus {
|
||||
ring(p, t, rect, corner);
|
||||
}
|
||||
let mark = pos2(rect.right() - space::M - tokens::icon::S / 2.0, rect.center().y);
|
||||
if waiting(ui.ctx(), r.id, self.busy) {
|
||||
spinner(p, mark, tokens::icon::M, t.primary);
|
||||
} else {
|
||||
chevron(p, mark, tokens::icon::M, turn, faint);
|
||||
}
|
||||
let room = rect.width() - 2.0 * space::M - tokens::icon::M - space::S;
|
||||
left(p, rect.left_center() + vec2(space::M, 0.0), line(p, now, fonts::ui(text::BODY), ink, room));
|
||||
let items = || self.options.iter().enumerate().map(|(i, o)| Item::new(o.clone(), i).checked(i == *chosen)).collect();
|
||||
match menu::drop_down(ui, t, &r, width, items) {
|
||||
Some(i) if i != *chosen => {
|
||||
*chosen = i;
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn numbers_are_written_short_and_read_with_comma_or_point() {
|
||||
assert_eq!((write(500.0), write(1.5), write(0.25), write(0.0)), ("500".into(), "1.5".into(), "0.25".into(), "0".into()));
|
||||
assert_eq!((read(" 1,5 "), read("2.25"), read("x"), read(""), read("inf")), (Some(1.5), Some(2.25), None, None, None));
|
||||
}
|
||||
}
|
||||
380
crates/app/src/ui/gallery.rs
Normal file
380
crates/app/src/ui/gallery.rs
Normal file
|
|
@ -0,0 +1,380 @@
|
|||
//! Every control in every state (`medlar --gallery`). For whoever builds Medlar, so its words are not in the catalogue.
|
||||
|
||||
use super::dialog::{Answer, Dialog, sheet};
|
||||
use super::field::{Combo, Field, Number, search};
|
||||
use super::menu::{self, Item};
|
||||
use super::toast::Toasts;
|
||||
use super::widgets::{Button, Chip, Choice, Fab, Kind, Size, Slider, Tab, fab_menu, group, range, segmented, split, tabs, toolbar};
|
||||
use crate::app::App;
|
||||
use crate::fonts;
|
||||
use crate::theme::Theme;
|
||||
use crate::tokens::{self, space, text};
|
||||
use eframe::egui::{Id, RichText, ScrollArea, Ui, UiBuilder, vec2};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
pub const PAGES: [&str; 4] = ["Buttons", "Fields", "Choices", "Over it"];
|
||||
|
||||
struct Demo {
|
||||
page: usize,
|
||||
toggle: bool,
|
||||
chosen: usize,
|
||||
tab: usize,
|
||||
on: bool,
|
||||
text: String,
|
||||
long: String,
|
||||
search: String,
|
||||
password: String,
|
||||
number: f64,
|
||||
slide: f64,
|
||||
low: f64,
|
||||
high: f64,
|
||||
combo: usize,
|
||||
fab: bool,
|
||||
bar: bool,
|
||||
/// Opens the menu once, for screenshots.
|
||||
menu: Option<bool>,
|
||||
dialog: bool,
|
||||
confirm: bool,
|
||||
sheet: bool,
|
||||
toasts: Toasts<&'static str>,
|
||||
last: String,
|
||||
}
|
||||
|
||||
impl Default for Demo {
|
||||
fn default() -> Self {
|
||||
Demo {
|
||||
page: 0,
|
||||
toggle: true,
|
||||
chosen: 1,
|
||||
tab: 0,
|
||||
on: true,
|
||||
text: "report.pdf".into(),
|
||||
long: "A file name that is far too long for the box it has to fit in.tar.zst".into(),
|
||||
search: "linux".into(),
|
||||
password: "secret".into(),
|
||||
number: 500.0,
|
||||
slide: 40.0,
|
||||
low: 20.0,
|
||||
high: 70.0,
|
||||
combo: 1,
|
||||
fab: false,
|
||||
bar: true,
|
||||
menu: None,
|
||||
dialog: false,
|
||||
confirm: false,
|
||||
sheet: false,
|
||||
toasts: Toasts::default(),
|
||||
last: String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn demo(ui: &Ui) -> Arc<Mutex<Demo>> {
|
||||
ui.ctx().data_mut(|d| d.get_temp_mut_or_default::<Arc<Mutex<Demo>>>(Id::unique("gallery")).clone())
|
||||
}
|
||||
|
||||
/// The whole screen, in `App::frame`.
|
||||
pub fn show(app: &mut App, ui: &mut Ui) {
|
||||
let demo = demo(ui);
|
||||
let d = &mut *demo.lock().unwrap();
|
||||
let t = app.theme.clone();
|
||||
let window = ui.ctx().content_rect();
|
||||
let mut inner = ui.new_child(UiBuilder::new().max_rect(window.shrink(space::L)));
|
||||
let ui = &mut inner;
|
||||
ui.spacing_mut().item_spacing = vec2(space::S, space::M);
|
||||
let all = PAGES.map(|text| Tab { icon: "", text, count: (text == "Choices").then_some(12) });
|
||||
tabs(ui, &t, "Pages", &all, &mut d.page);
|
||||
let page = d.page;
|
||||
ScrollArea::vertical().id_salt(page).auto_shrink(false).show(ui, |ui| {
|
||||
ui.set_width(ui.available_width() - space::M);
|
||||
ui.add_space(space::XS);
|
||||
match page {
|
||||
0 => buttons(ui, &t, d),
|
||||
1 => fields(ui, &t, d),
|
||||
2 => choices(ui, &t, d),
|
||||
_ => over(ui, &t, d),
|
||||
}
|
||||
ui.add_space(space::XXL);
|
||||
});
|
||||
if page == 3 {
|
||||
floating(ui, &t, d);
|
||||
}
|
||||
if let Some(a) = d.toasts.show(ui.ctx(), &t, window.bottom()) {
|
||||
d.last = a.into();
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts on a page; for screenshots.
|
||||
pub fn page(app: &mut App, ui: &mut Ui, page: usize) {
|
||||
demo(ui).lock().unwrap().page = page;
|
||||
show(app, ui);
|
||||
}
|
||||
|
||||
/// Opens one of the things that float; for screenshots.
|
||||
pub fn open(ui: &Ui, what: &str) {
|
||||
let demo = demo(ui);
|
||||
let d = &mut *demo.lock().unwrap();
|
||||
match what {
|
||||
"dialog" => d.dialog = true,
|
||||
"confirm" => d.confirm = true,
|
||||
"sheet" => d.sheet = true,
|
||||
"menu" => d.menu = d.menu.or(Some(true)),
|
||||
"fab" => d.fab = true,
|
||||
_ if d.toasts.is_empty() => {
|
||||
d.toasts.info("download_done", "ubuntu.iso is done");
|
||||
d.toasts.undo("delete", "3 downloads were removed from the list", "undo");
|
||||
d.toasts.error("Couldn't save report-of-the-year-with-a-long-name.pdf to Downloads: there is no space left on the disk", Some(("Choose folder".into(), "folder")));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn head(ui: &mut Ui, t: &Theme, what: &str) {
|
||||
ui.add_space(space::XS);
|
||||
ui.label(RichText::new(what).font(fonts::med(text::LABEL)).color(t.on_variant));
|
||||
}
|
||||
|
||||
const KINDS: [(&str, Kind); 5] =
|
||||
[("Filled", Kind::Filled), ("Tonal", Kind::Tonal), ("Elevated", Kind::Elevated), ("Outlined", Kind::Outlined), ("Text", Kind::Text)];
|
||||
|
||||
fn buttons(ui: &mut Ui, t: &Theme, d: &mut Demo) {
|
||||
head(ui, t, "Five kinds, three sizes");
|
||||
for size in [Size::S, Size::M, Size::L] {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
for (name, kind) in KINDS {
|
||||
Button::new(name).with_icon("add").kind(kind).size(size).show(ui, t);
|
||||
}
|
||||
});
|
||||
}
|
||||
head(ui, t, "Danger, disabled, busy");
|
||||
for state in 0..3 {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
for (name, kind) in KINDS {
|
||||
let b = Button::new(name).kind(kind);
|
||||
match state {
|
||||
0 => b.danger(true),
|
||||
1 => b.enabled(false),
|
||||
_ => b.busy(true),
|
||||
}
|
||||
.show(ui, t);
|
||||
}
|
||||
});
|
||||
}
|
||||
head(ui, t, "Toggles and icon buttons");
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
for (name, kind) in KINDS {
|
||||
if Button::new(name).kind(kind).toggle(d.toggle).show(ui, t).clicked() {
|
||||
d.toggle = !d.toggle;
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
for (_, kind) in KINDS {
|
||||
Button::icon("pause", "Pause").keys("Space").kind(kind).show(ui, t);
|
||||
if Button::icon("bolt", "Full speed").kind(kind).toggle(d.toggle).show(ui, t).clicked() {
|
||||
d.toggle = !d.toggle;
|
||||
}
|
||||
}
|
||||
Button::icon("delete", "Remove").danger(true).show(ui, t);
|
||||
Button::icon("play_arrow", "Start").enabled(false).show(ui, t);
|
||||
Button::icon("refresh", "Check again").busy(true).show(ui, t);
|
||||
Button::icon("tune", "Options").size(Size::S).kind(Kind::Tonal).show(ui, t);
|
||||
Button::icon("download", "Download").size(Size::L).kind(Kind::Filled).show(ui, t);
|
||||
});
|
||||
head(ui, t, "Group, split button, FAB");
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
group(ui, t, "Show", &[("", "All"), ("download", "Loading"), ("done_all", "Done")], &mut d.chosen);
|
||||
ui.add_space(space::L);
|
||||
group(ui, t, "View", &[("view_list", ""), ("view_agenda", ""), ("stacks", "")], &mut d.chosen);
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
// The menu knows its arrow by the response of the frame before.
|
||||
let key = Id::unique("gallery split");
|
||||
let was = ui.data(|m| m.get_temp::<bool>(key)).unwrap_or(false);
|
||||
let (main, more) = split(ui, t, "download", "Download", "More ways to start", was);
|
||||
if main.clicked() {
|
||||
d.last = "Download".into();
|
||||
}
|
||||
if let Some(a) = menu::below(ui, t, &more, || vec![Item::new("Later", "Later").icon("schedule"), Item::new("Paused", "Paused").icon("pause")]) {
|
||||
d.last = a.into();
|
||||
}
|
||||
let open = menu::is_open(ui.ctx(), &more);
|
||||
ui.data_mut(|m| m.insert_temp(key, open));
|
||||
Fab { icon: "add", text: "", name: "Add links", keys: "Ctrl+N" }.show(ui, t);
|
||||
Fab { icon: "add", text: "Add links", name: "Add links", keys: "" }.show(ui, t);
|
||||
});
|
||||
}
|
||||
|
||||
fn fields(ui: &mut Ui, t: &Theme, d: &mut Demo) {
|
||||
let w = ((ui.available_width() - space::L) / 2.0).min(tokens::size::SHEET);
|
||||
ui.horizontal_top(|ui| {
|
||||
Field::new("File name").width(w).help("The ending decides the folder").show(ui, t, &mut d.text);
|
||||
Field::new("Folder").icon("folder").width(w).error(Some("This folder can't be written to")).show(ui, t, &mut d.long);
|
||||
});
|
||||
ui.horizontal_top(|ui| {
|
||||
Field::new("Link").icon("link").hint("Paste a link").width(w).busy(true).clear().show(ui, t, &mut d.search);
|
||||
Field::new("Server").width(w).enabled(false).show(ui, t, &mut d.text);
|
||||
});
|
||||
ui.horizontal_top(|ui| {
|
||||
Field::new("Password").icon("key").password().width(w).show(ui, t, &mut d.password);
|
||||
Number { label: "Speed limit", unit: "kB/s", range: 0.0..=1000.0, step: 50.0, enabled: true, width: w }.show(ui, t, &mut d.number);
|
||||
});
|
||||
ui.horizontal_top(|ui| {
|
||||
let options = ["Main queue", "Night", "A queue with a name that is much too long for this box"].map(String::from);
|
||||
Combo::new("Queue", &options, w).show(ui, t, &mut d.combo);
|
||||
Combo { enabled: false, ..Combo::new("Off", &options, w / 2.0 - space::XS) }.show(ui, t, &mut d.combo);
|
||||
Combo { busy: true, ..Combo::new("Busy", &options, w / 2.0 - space::XS) }.show(ui, t, &mut d.combo);
|
||||
});
|
||||
ui.horizontal_top(|ui| {
|
||||
search(ui, t, "Search downloads", &mut d.search, w);
|
||||
let options = ["Folder is gone"].map(String::from);
|
||||
Combo { error: Some("Choose another one"), ..Combo::new("Category", &options, w) }.show(ui, t, &mut d.chosen);
|
||||
});
|
||||
Field::new("Links, one per line").rows(3).width(2.0 * w + space::S).show(ui, t, &mut d.long);
|
||||
let words = |v: f64| format!("{v:.0} kB/s");
|
||||
ui.horizontal_top(|ui| {
|
||||
Slider::new("Limit", 0.0..=100.0, 1.0).width(w).show_value(&words).show(ui, t, &mut d.slide);
|
||||
range(ui, t, Slider::new("Hours", 0.0..=100.0, 5.0).width(w).show_value(&words), &mut d.low, &mut d.high);
|
||||
});
|
||||
ui.horizontal_top(|ui| {
|
||||
Slider::new("Off", 0.0..=100.0, 1.0).width(w).enabled(false).show(ui, t, &mut d.slide);
|
||||
Slider::new("Error", 0.0..=100.0, 1.0).width(w).error(true).show(ui, t, &mut d.slide);
|
||||
});
|
||||
}
|
||||
|
||||
fn choices(ui: &mut Ui, t: &Theme, d: &mut Demo) {
|
||||
head(ui, t, "Switch: on and off, disabled, error, busy");
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
Choice::new("On").switch(ui, t, &mut d.on);
|
||||
let mut off = !d.on;
|
||||
Choice::new("Off").switch(ui, t, &mut off);
|
||||
d.on = !off;
|
||||
Choice::new("Disabled on").enabled(false).switch(ui, t, &mut true);
|
||||
Choice::new("Disabled off").enabled(false).switch(ui, t, &mut false);
|
||||
Choice::new("Error").error(true).switch(ui, t, &mut d.on);
|
||||
Choice::new("Busy").busy(true).switch(ui, t, &mut d.on);
|
||||
});
|
||||
head(ui, t, "Checkbox");
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
Choice::new("Show hidden files").checkbox(ui, t, &mut d.on);
|
||||
Choice::new("Some").mixed(true).checkbox(ui, t, &mut d.toggle);
|
||||
Choice::new("Off").checkbox(ui, t, &mut d.toggle);
|
||||
Choice::new("Disabled").enabled(false).checkbox(ui, t, &mut true);
|
||||
Choice::new("Error").error(true).checkbox(ui, t, &mut d.on);
|
||||
Choice::new("Busy").busy(true).checkbox(ui, t, &mut d.on);
|
||||
});
|
||||
head(ui, t, "Radio");
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
for (i, what) in ["Rename", "Replace", "Skip"].into_iter().enumerate() {
|
||||
if Choice::new(what).radio(ui, t, d.chosen == i).clicked() {
|
||||
d.chosen = i;
|
||||
}
|
||||
}
|
||||
Choice::new("Disabled").enabled(false).radio(ui, t, true);
|
||||
Choice::new("Error").error(true).radio(ui, t, true);
|
||||
Choice::new("Busy").busy(true).radio(ui, t, true);
|
||||
});
|
||||
head(ui, t, "Chips");
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
Chip::new("Open folder").icon("folder_open").show(ui, t);
|
||||
if Chip::new("Video").filter(d.on).show(ui, t).response.clicked() {
|
||||
d.on = !d.on;
|
||||
}
|
||||
if Chip::new("Music").icon("music_note").filter(!d.on).show(ui, t).response.clicked() {
|
||||
d.on = !d.on;
|
||||
}
|
||||
Chip::new("work").icon("tag").closable().show(ui, t);
|
||||
Chip::new("Disabled").enabled(false).filter(false).show(ui, t);
|
||||
Chip::new("Broken").icon("error").error(true).show(ui, t);
|
||||
});
|
||||
head(ui, t, "Segmented control");
|
||||
let options = [("light_mode", "Light"), ("dark_mode", "Dark"), ("contrast", "Same as the desktop")];
|
||||
ui.scope(|ui| {
|
||||
ui.set_max_width(tokens::size::DIALOG_M);
|
||||
segmented(ui, t, "Appearance", &options, &mut d.chosen);
|
||||
});
|
||||
head(ui, t, "Tabs");
|
||||
let all = [("list", "All", Some(128)), ("download", "Loading", Some(3)), ("done_all", "Done", None)];
|
||||
tabs(ui, t, "State", &all.map(|(icon, text, count)| Tab { icon, text, count }), &mut d.tab);
|
||||
}
|
||||
|
||||
fn items() -> Vec<Item<&'static str>> {
|
||||
let more = (1..40).map(|i| Item::new(format!("Queue {i}"), "queue")).collect();
|
||||
vec![
|
||||
Item::new("Open file", "open").icon("file_open").keys("Enter"),
|
||||
Item::new("Open folder", "folder").icon("folder_open").keys("Ctrl+Enter"),
|
||||
Item::new("Copy link", "copy").icon("content_copy").keys("Ctrl+C"),
|
||||
Item::line(),
|
||||
Item::new("Pause", "pause").icon("pause").enabled(false),
|
||||
Item::sub("Priority", vec![Item::new("High", "high").checked(true), Item::new("Normal", "normal"), Item::new("Low", "low")]).icon("low_priority"),
|
||||
Item::sub("Move to", more).icon("stacks"),
|
||||
Item::new("Keep it as the first of everything that is in the list", "first").icon("priority_high"),
|
||||
Item::line(),
|
||||
Item::new("Remove", "remove").icon("delete").keys("Del").danger(),
|
||||
]
|
||||
}
|
||||
|
||||
fn over(ui: &mut Ui, t: &Theme, d: &mut Demo) {
|
||||
head(ui, t, "Menu, context menu on a right click, dialogs, sheet, toasts");
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
let r = Button::new("Menu").kind(Kind::Tonal).show(ui, t);
|
||||
if d.menu == Some(true) {
|
||||
d.menu = Some(false);
|
||||
menu::open(ui.ctx(), r.id, r.rect, 0.0, true);
|
||||
}
|
||||
if let Some(a) = menu::below(ui, t, &r, items).or_else(|| menu::context(ui, t, &r, items)) {
|
||||
d.last = a.into();
|
||||
}
|
||||
for (what, flag) in [("Dialog", &mut d.dialog), ("Confirm", &mut d.confirm), ("Sheet", &mut d.sheet), ("Toolbar", &mut d.bar)] {
|
||||
if Button::new(what).kind(Kind::Tonal).show(ui, t).clicked() {
|
||||
*flag = !*flag;
|
||||
}
|
||||
}
|
||||
if Button::new("Toast").kind(Kind::Tonal).show(ui, t).clicked() {
|
||||
d.toasts.undo("delete", "2 downloads were removed", "undo");
|
||||
}
|
||||
});
|
||||
ui.label(RichText::new(format!("Last: {}", d.last)).font(fonts::ui(text::BODY)).color(t.on_variant));
|
||||
}
|
||||
|
||||
fn floating(ui: &mut Ui, t: &Theme, d: &mut Demo) {
|
||||
let ctx = ui.ctx().clone();
|
||||
let window = ctx.content_rect();
|
||||
toolbar(&ctx, t, Id::unique("gallery bar"), window.center_bottom() - vec2(0.0, space::L), d.bar, |ui| {
|
||||
Button::icon("play_arrow", "Start").kind(Kind::Filled).show(ui, t);
|
||||
Button::icon("pause", "Pause").keys("Space").show(ui, t);
|
||||
Button::icon("folder_open", "Open folder").show(ui, t);
|
||||
Button::icon("delete", "Remove").keys("Del").danger(true).show(ui, t);
|
||||
});
|
||||
let at = window.right_bottom() - vec2(space::L, space::L);
|
||||
let items = [("link", "From a link"), ("content_paste", "From the clipboard"), ("file_open", "From a file")];
|
||||
if let Some(i) = fab_menu(&ctx, t, Id::unique("gallery fab"), at, ("Add", "Close"), &mut d.fab, &items) {
|
||||
d.last = items[i].1.into();
|
||||
d.fab = false;
|
||||
}
|
||||
let add = Dialog::new("gallery", "Add a download", "Download").body("The file goes to Downloads unless you choose another folder.");
|
||||
let options = ["Main queue", "Night"].map(String::from);
|
||||
let answer = add.show(&ctx, t, d.dialog, |ui| {
|
||||
Field::new("Link").icon("link").clear().show(ui, t, &mut d.text);
|
||||
Combo::new("Queue", &options, ui.available_width()).show(ui, t, &mut d.combo);
|
||||
Choice::new("Start now").checkbox(ui, t, &mut d.on);
|
||||
});
|
||||
if let Some(a) = answer {
|
||||
d.dialog = false;
|
||||
d.last = format!("{a:?}");
|
||||
}
|
||||
let ask = Dialog::confirm("gallery confirm", "Delete 3 files?", "The files are deleted from the disk. This can't be taken back.", "Delete files", true);
|
||||
if let Some(a) = ask.show(&ctx, t, d.confirm, |_| {}) {
|
||||
d.confirm = false;
|
||||
if a == Answer::Main {
|
||||
d.last = "Deleted".into();
|
||||
}
|
||||
}
|
||||
if sheet(&ctx, t, "gallery", "Details of a download with a long name.iso", d.sheet, |ui| {
|
||||
Field::new("File name").show(ui, t, &mut d.text);
|
||||
Slider::new("Limit", 0.0..=100.0, 1.0).show(ui, t, &mut d.slide);
|
||||
segmented(ui, t, "Parts", &[("", "One"), ("", "Few"), ("", "Many")], &mut d.chosen);
|
||||
}) {
|
||||
d.sheet = false;
|
||||
}
|
||||
}
|
||||
536
crates/app/src/ui/menu.rs
Normal file
536
crates/app/src/ui/menu.rs
Normal file
|
|
@ -0,0 +1,536 @@
|
|||
//! Menus, submenus and context menus. One is open at a time; it keeps to the window and has its own keyboard.
|
||||
|
||||
use super::widgets::{chevron, cr, left, lerp, line, take_enter, text_width, RIGHT};
|
||||
use crate::motion::{self, spring_from};
|
||||
use crate::theme::{Theme, alpha};
|
||||
use crate::tokens::spring::{EFFECT, FAST};
|
||||
use crate::tokens::{self, radius, space, state, text, time};
|
||||
use crate::{fonts, icons};
|
||||
use eframe::egui::accesskit::Role;
|
||||
use eframe::egui::emath::TSTransform;
|
||||
use eframe::egui::{
|
||||
Area, Context, Event, EventFilter, Id, Key, LayerId, Modifiers, Order, Pos2, Rect, Response, ScrollArea, Sense, Ui, Vec2, WidgetInfo, pos2, vec2,
|
||||
};
|
||||
use std::time::Duration;
|
||||
|
||||
/// A row of a menu that stands for `A`.
|
||||
#[derive(Clone)]
|
||||
pub struct Item<A> {
|
||||
text: String,
|
||||
icon: &'static str,
|
||||
keys: &'static str,
|
||||
enabled: bool,
|
||||
checked: Option<bool>,
|
||||
danger: bool,
|
||||
what: What<A>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
enum What<A> {
|
||||
Do(A),
|
||||
Sub(Vec<Item<A>>),
|
||||
Line,
|
||||
}
|
||||
|
||||
impl<A> Item<A> {
|
||||
fn with(text: impl Into<String>, what: What<A>) -> Self {
|
||||
Item { text: text.into(), icon: "", keys: "", enabled: true, checked: None, danger: false, what }
|
||||
}
|
||||
|
||||
pub fn new(text: impl Into<String>, action: A) -> Self {
|
||||
Item::with(text, What::Do(action))
|
||||
}
|
||||
|
||||
pub fn sub(text: impl Into<String>, items: Vec<Item<A>>) -> Self {
|
||||
Item { enabled: !items.is_empty(), ..Item::with(text, What::Sub(items)) }
|
||||
}
|
||||
|
||||
pub fn line() -> Self {
|
||||
Item::with("", What::Line)
|
||||
}
|
||||
|
||||
pub fn icon(mut self, icon: &'static str) -> Self {
|
||||
self.icon = icon;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn keys(mut self, keys: &'static str) -> Self {
|
||||
self.keys = keys;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn enabled(mut self, enabled: bool) -> Self {
|
||||
self.enabled = enabled && self.enabled;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn checked(mut self, checked: bool) -> Self {
|
||||
self.checked = Some(checked);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn danger(mut self) -> Self {
|
||||
self.danger = true;
|
||||
self
|
||||
}
|
||||
|
||||
fn pickable(&self) -> bool {
|
||||
self.enabled && !matches!(self.what, What::Line)
|
||||
}
|
||||
|
||||
fn height(&self) -> f32 {
|
||||
if matches!(self.what, What::Line) { space::S + tokens::size::HAIRLINE } else { tokens::size::ROW }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Open {
|
||||
owner: Id,
|
||||
/// What it opens from.
|
||||
anchor: Rect,
|
||||
min_width: f32,
|
||||
/// Has the focus back when it closes.
|
||||
back: Option<Id>,
|
||||
/// Opened with the keyboard: it is there at once.
|
||||
keyboard: bool,
|
||||
born: u64,
|
||||
/// Last pass it was drawn in, so one whose owner is gone counts as closed.
|
||||
seen: u64,
|
||||
/// Rows whose submenus are open, from the first level.
|
||||
path: Vec<usize>,
|
||||
/// The marked row of each level.
|
||||
mark: Vec<Option<usize>>,
|
||||
/// The row the pointer rests on, as level, row and time.
|
||||
rest: Option<(usize, usize, f64)>,
|
||||
}
|
||||
|
||||
fn slot() -> Id {
|
||||
Id::unique("medlar menu")
|
||||
}
|
||||
|
||||
fn load(ctx: &Context) -> Option<Open> {
|
||||
let pass = ctx.cumulative_pass_nr();
|
||||
ctx.data(|d| d.get_temp::<Open>(slot())).filter(|o| o.seen + 2 >= pass)
|
||||
}
|
||||
|
||||
fn close(ctx: &Context, o: &Open) {
|
||||
ctx.data_mut(|d| d.remove::<Open>(slot()));
|
||||
ctx.memory_mut(|m| match o.back {
|
||||
Some(id) => m.request_focus(id),
|
||||
None => m.surrender_focus(holder(o.owner)),
|
||||
});
|
||||
ctx.request_repaint();
|
||||
}
|
||||
|
||||
fn holder(owner: Id) -> Id {
|
||||
owner.with("menu focus")
|
||||
}
|
||||
|
||||
/// Is any menu open? Shortcuts of the view wait until it isn't.
|
||||
pub fn any_open(ctx: &Context) -> bool {
|
||||
load(ctx).is_some()
|
||||
}
|
||||
|
||||
/// Is the menu of this control open?
|
||||
pub fn is_open(ctx: &Context, r: &Response) -> bool {
|
||||
load(ctx).is_some_and(|o| o.owner == r.id)
|
||||
}
|
||||
|
||||
pub(super) fn open(ctx: &Context, owner: Id, anchor: Rect, min_width: f32, keyboard: bool) {
|
||||
let pass = ctx.cumulative_pass_nr();
|
||||
let back = ctx.memory(|m| m.focused());
|
||||
let o = Open { owner, anchor, min_width, back, keyboard, born: pass, seen: pass, path: vec![], mark: vec![None], rest: None };
|
||||
ctx.data_mut(|d| d.insert_temp(slot(), o));
|
||||
ctx.request_repaint();
|
||||
}
|
||||
|
||||
/// A menu under a control; a click on it opens and closes the menu. Gives back what was chosen.
|
||||
pub fn below<A: Clone>(ui: &Ui, t: &Theme, r: &Response, items: impl FnOnce() -> Vec<Item<A>>) -> Option<A> {
|
||||
drop_down(ui, t, r, 0.0, items)
|
||||
}
|
||||
|
||||
/// Like `below`, at least `min_width` wide; the down arrow opens it too.
|
||||
pub fn drop_down<A: Clone>(ui: &Ui, t: &Theme, r: &Response, min_width: f32, items: impl FnOnce() -> Vec<Item<A>>) -> Option<A> {
|
||||
let ctx = ui.ctx();
|
||||
let was = load(ctx).filter(|o| o.owner == r.id);
|
||||
let arrow = min_width > 0.0 && was.is_none() && r.has_focus() && ctx.input(|i| i.key_pressed(Key::ArrowDown));
|
||||
if r.clicked() || arrow {
|
||||
match was {
|
||||
Some(o) => close(ctx, &o),
|
||||
None => open(ctx, r.id, r.rect, min_width, r.has_focus()),
|
||||
}
|
||||
}
|
||||
show(ui, t, r.id, items)
|
||||
}
|
||||
|
||||
/// A menu at the pointer on a right click, or under the control on Shift+F10.
|
||||
pub fn context<A: Clone>(ui: &Ui, t: &Theme, r: &Response, items: impl FnOnce() -> Vec<Item<A>>) -> Option<A> {
|
||||
let ctx = ui.ctx();
|
||||
let owner = r.id.with("context");
|
||||
if r.secondary_clicked() {
|
||||
let at = r.interact_pointer_pos().unwrap_or(r.rect.center());
|
||||
open(ctx, owner, Rect::from_min_size(at, Vec2::ZERO), 0.0, false);
|
||||
} else if r.has_focus() && ctx.input_mut(|i| i.consume_key(Modifiers::SHIFT, Key::F10)) {
|
||||
open(ctx, owner, r.rect, 0.0, true);
|
||||
}
|
||||
show(ui, t, owner, items)
|
||||
}
|
||||
|
||||
/// The place of a menu of `size`: under `anchor`, or above when there is more room, or beside it for a submenu; always inside `window`.
|
||||
fn place(anchor: Rect, size: Vec2, window: Rect, beside: bool) -> Rect {
|
||||
let size = size.min(window.size());
|
||||
let mut at = if beside { pos2(anchor.right(), anchor.top() - space::XS) } else { pos2(anchor.left(), anchor.bottom() + space::XS) };
|
||||
if beside && at.x + size.x > window.right() {
|
||||
at.x = anchor.left() - size.x;
|
||||
}
|
||||
if !beside && at.y + size.y > window.bottom() && anchor.top() - window.top() > window.bottom() - anchor.bottom() {
|
||||
at.y = anchor.top() - space::XS - size.y;
|
||||
}
|
||||
let inside = |v: f32, lo: f32, hi: f32| v.min(hi).max(lo);
|
||||
at.x = inside(at.x, window.left(), window.right() - size.x);
|
||||
at.y = inside(at.y, window.top(), window.bottom() - size.y);
|
||||
Rect::from_min_size(at, size)
|
||||
}
|
||||
|
||||
const LEAD: f32 = tokens::icon::M + space::M;
|
||||
|
||||
fn size<A>(ctx: &Context, items: &[Item<A>], min_width: f32) -> Vec2 {
|
||||
let p = ctx.debug_painter();
|
||||
let lead = if has_lead(items) { LEAD } else { 0.0 };
|
||||
let wide = items.iter().map(|i| {
|
||||
let end = match (&i.what, i.keys) {
|
||||
(What::Sub(_), _) => tokens::icon::M + space::S,
|
||||
(_, "") => 0.0,
|
||||
(_, keys) => text_width(&p, keys, fonts::ui(text::LABEL)) + space::XL,
|
||||
};
|
||||
text_width(&p, &i.text, fonts::ui(text::BODY)) + end
|
||||
});
|
||||
let w = wide.fold(0.0, f32::max) + lead + 2.0 * (space::XS + space::M);
|
||||
let h = items.iter().map(Item::height).sum::<f32>() + 2.0 * space::XS;
|
||||
vec2(w.clamp(tokens::size::MENU_MIN, tokens::size::MENU_MAX).max(min_width), h)
|
||||
}
|
||||
|
||||
fn has_lead<A>(items: &[Item<A>]) -> bool {
|
||||
items.iter().any(|i| !i.icon.is_empty() || i.checked.is_some())
|
||||
}
|
||||
|
||||
/// The items of the level that `path` leads to.
|
||||
fn level<'a, A>(items: &'a [Item<A>], path: &[usize]) -> &'a [Item<A>] {
|
||||
path.iter().fold(items, |items, i| match items.get(*i).map(|i| &i.what) {
|
||||
Some(What::Sub(sub)) => sub,
|
||||
_ => &[],
|
||||
})
|
||||
}
|
||||
|
||||
/// The next row after `from` in direction `step` that can be chosen, around the ends.
|
||||
fn next<A>(items: &[Item<A>], from: Option<usize>, step: isize) -> Option<usize> {
|
||||
let n = items.len() as isize;
|
||||
let start = from.map_or(if step > 0 { -1 } else { n }, |f| f as isize);
|
||||
(1..=n).map(|k| (start + step * k).rem_euclid(n) as usize).find(|i| items[*i].pickable())
|
||||
}
|
||||
|
||||
fn show<A: Clone>(ui: &Ui, t: &Theme, owner: Id, items: impl FnOnce() -> Vec<Item<A>>) -> Option<A> {
|
||||
let ctx = ui.ctx();
|
||||
let mut o = load(ctx).filter(|o| o.owner == owner)?;
|
||||
let items = items();
|
||||
o.seen = ctx.cumulative_pass_nr();
|
||||
// What it is written on may have shrunk meanwhile.
|
||||
while !o.path.is_empty() && level(&items, &o.path).is_empty() {
|
||||
o.path.pop();
|
||||
}
|
||||
o.mark.resize(o.path.len() + 1, None);
|
||||
let mut chosen = None;
|
||||
let mut done = false;
|
||||
if o.born < o.seen {
|
||||
(chosen, done) = keys(ctx, &mut o, &items);
|
||||
} else if o.keyboard {
|
||||
o.mark[0] = items.iter().position(|i| i.checked == Some(true) && i.pickable()).or_else(|| next(&items, None, 1));
|
||||
}
|
||||
let window = ctx.content_rect().shrink(space::XS);
|
||||
let mut anchor = o.anchor;
|
||||
let mut rects = Vec::new();
|
||||
let mut hovered = None;
|
||||
for depth in 0..=o.path.len() {
|
||||
let rows = level(&items, &o.path[..depth]);
|
||||
let rect = place(anchor, size(ctx, rows, if depth == 0 { o.min_width } else { 0.0 }), window, depth > 0);
|
||||
let drawn = draw(ui, t, &o, depth, rows, rect, anchor);
|
||||
rects.push(rect);
|
||||
if let Some(i) = drawn.hovered {
|
||||
hovered = Some((depth, i));
|
||||
}
|
||||
if let Some(i) = drawn.clicked.filter(|i| rows[*i].pickable()) {
|
||||
match &rows[i].what {
|
||||
What::Do(a) => (chosen, done) = (Some(a.clone()), true),
|
||||
What::Sub(_) => {
|
||||
o.path.truncate(depth);
|
||||
o.path.push(i);
|
||||
o.mark.truncate(depth + 1);
|
||||
o.mark[depth] = Some(i);
|
||||
o.mark.push(None);
|
||||
ctx.request_repaint();
|
||||
break;
|
||||
}
|
||||
What::Line => {}
|
||||
}
|
||||
}
|
||||
match o.path.get(depth) {
|
||||
Some(i) => anchor = drawn.rows[*i],
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
rest(ctx, &mut o, &items, hovered);
|
||||
let pressed = ctx.input(|i| i.pointer.any_pressed().then(|| i.pointer.interact_pos()).flatten());
|
||||
let outside = pressed.is_some_and(|p| o.born < o.seen && !rects.iter().any(|r| r.contains(p)) && !o.anchor.contains(p));
|
||||
if done || outside {
|
||||
close(ctx, &o);
|
||||
} else {
|
||||
ctx.data_mut(|d| d.insert_temp(slot(), o));
|
||||
}
|
||||
chosen
|
||||
}
|
||||
|
||||
/// Follows the pointer: marks its row at once, opens and closes submenus when it has rested there.
|
||||
fn rest<A>(ctx: &Context, o: &mut Open, items: &[Item<A>], hovered: Option<(usize, usize)>) {
|
||||
let Some((depth, i)) = hovered.filter(|(d, _)| *d < o.mark.len()) else {
|
||||
o.rest = None;
|
||||
return;
|
||||
};
|
||||
let now = ctx.input(|i| i.time);
|
||||
let moved = ctx.input(|i| i.pointer.is_moving());
|
||||
if moved || o.mark[depth].is_none() {
|
||||
o.mark[depth] = level(items, &o.path[..depth])[i].pickable().then_some(i);
|
||||
}
|
||||
if o.rest.is_none_or(|(d, r, _)| (d, r) != (depth, i)) {
|
||||
o.rest = Some((depth, i, now));
|
||||
}
|
||||
let since = o.rest.map_or(now, |r| r.2);
|
||||
let row = &level(items, &o.path[..depth])[i];
|
||||
let sub = matches!(row.what, What::Sub(_)) && row.enabled;
|
||||
let open = o.path.get(depth).copied();
|
||||
if (open.is_none() && !sub) || open == Some(i) {
|
||||
return;
|
||||
}
|
||||
let left = time::SUBMENU - (now - since);
|
||||
if left > 0.0 {
|
||||
ctx.request_repaint_after(Duration::from_secs_f64(left));
|
||||
return;
|
||||
}
|
||||
o.path.truncate(depth);
|
||||
o.mark.truncate(depth + 1);
|
||||
if sub {
|
||||
o.path.push(i);
|
||||
o.mark.push(None);
|
||||
}
|
||||
ctx.request_repaint();
|
||||
}
|
||||
|
||||
/// What the keyboard does, in the innermost open level.
|
||||
fn keys<A: Clone>(ctx: &Context, o: &mut Open, items: &[Item<A>]) -> (Option<A>, bool) {
|
||||
let hit = |k: Key| ctx.input_mut(|i| i.consume_key(Modifiers::NONE, k));
|
||||
let rows = level(items, &o.path);
|
||||
let mark = o.mark[o.path.len()];
|
||||
let last = o.path.len();
|
||||
for (k, to) in [
|
||||
(Key::ArrowDown, next(rows, mark, 1)),
|
||||
(Key::ArrowUp, next(rows, mark, -1)),
|
||||
(Key::Home, next(rows, None, 1)),
|
||||
(Key::End, next(rows, None, -1)),
|
||||
] {
|
||||
if hit(k) {
|
||||
o.mark[last] = to;
|
||||
o.keyboard = true;
|
||||
}
|
||||
}
|
||||
let enter = hit(Key::Enter) | hit(Key::Space);
|
||||
let right = hit(Key::ArrowRight);
|
||||
if enter {
|
||||
take_enter(ctx);
|
||||
}
|
||||
if let Some((i, row)) = mark.and_then(|i| Some((i, rows.get(i)?))).filter(|(_, r)| (enter || right) && r.pickable()) {
|
||||
match &row.what {
|
||||
What::Do(a) if enter => return (Some(a.clone()), true),
|
||||
What::Sub(sub) => {
|
||||
o.mark.push(next(sub, None, 1));
|
||||
o.path.push(i);
|
||||
o.keyboard = true;
|
||||
ctx.request_repaint();
|
||||
return (None, false);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if hit(Key::ArrowLeft) && !o.path.is_empty() {
|
||||
o.path.pop();
|
||||
o.mark.pop();
|
||||
}
|
||||
if hit(Key::Escape) {
|
||||
if o.path.pop().is_none() {
|
||||
return (None, true);
|
||||
}
|
||||
o.mark.pop();
|
||||
}
|
||||
if hit(Key::Tab) || ctx.input_mut(|i| i.consume_key(Modifiers::SHIFT, Key::Tab)) {
|
||||
return (None, true);
|
||||
}
|
||||
let typed = ctx.input_mut(|i| {
|
||||
let typed = i.events.iter().find_map(|e| if let Event::Text(s) = e { Some(s.to_lowercase()) } else { None });
|
||||
i.events.retain(|e| !matches!(e, Event::Text(_)));
|
||||
typed.filter(|s| !s.trim().is_empty())
|
||||
});
|
||||
if let Some(typed) = typed.filter(|_| !rows.is_empty() && o.mark.len() == o.path.len() + 1) {
|
||||
let rows = level(items, &o.path);
|
||||
let mark = o.mark[o.path.len()];
|
||||
let from = mark.map_or(0, |m| m + 1);
|
||||
let found = (0..rows.len()).map(|k| (from + k) % rows.len()).find(|i| rows[*i].pickable() && rows[*i].text.to_lowercase().starts_with(&typed));
|
||||
if found.is_some() {
|
||||
o.mark[o.path.len()] = found;
|
||||
}
|
||||
}
|
||||
(None, false)
|
||||
}
|
||||
|
||||
struct Drawn {
|
||||
rows: Vec<Rect>,
|
||||
hovered: Option<usize>,
|
||||
clicked: Option<usize>,
|
||||
}
|
||||
|
||||
fn draw<A>(ui: &Ui, t: &Theme, o: &Open, depth: usize, rows: &[Item<A>], rect: Rect, anchor: Rect) -> Drawn {
|
||||
let ctx = ui.ctx();
|
||||
let id = o.owner.with(("menu", depth));
|
||||
let key = (id, o.born, &o.path[..depth]);
|
||||
let (from, fade_from) = if o.keyboard { (1.0, 1.0) } else { (0.0, 0.0) };
|
||||
let grow = spring_from((key, "grow"), from, 1.0, FAST);
|
||||
let fade = spring_from((key, "fade"), fade_from, 1.0, EFFECT).clamp(0.0, 1.0);
|
||||
let mut drawn = Drawn { rows: vec![], hovered: None, clicked: None };
|
||||
let layer = LayerId::new(Order::Foreground, id);
|
||||
let pivot = Pos2::new(anchor.left().clamp(rect.left(), rect.right()), if rect.top() < anchor.top() && depth == 0 { rect.bottom() } else { rect.top() });
|
||||
let scale = lerp(0.92, 1.0, grow);
|
||||
let transform = if motion::level() == medlar_core::settings::Motion::Reduced || (scale - 1.0).abs() < 0.001 {
|
||||
TSTransform::IDENTITY
|
||||
} else {
|
||||
TSTransform::from_translation(pivot.to_vec2()) * TSTransform::from_scaling(scale) * TSTransform::from_translation(-pivot.to_vec2())
|
||||
};
|
||||
ctx.set_transform_layer(layer, transform);
|
||||
Area::new(id).order(Order::Foreground).fixed_pos(rect.min).constrain(false).fade_in(false).show(ctx, |ui| {
|
||||
ui.set_opacity(fade);
|
||||
ui.set_clip_rect(ctx.content_rect());
|
||||
let (_, menu) = ui.allocate_exact_size(rect.size(), Sense::hover());
|
||||
menu.widget_info(|| WidgetInfo::new(Role::Menu));
|
||||
if depth == 0 {
|
||||
let r = ui.interact(rect, holder(o.owner), Sense::focusable_noninteractive());
|
||||
if !r.has_focus() {
|
||||
r.request_focus();
|
||||
}
|
||||
ui.memory_mut(|m| m.set_focus_lock_filter(r.id, EventFilter { tab: true, horizontal_arrows: true, vertical_arrows: true, escape: true }));
|
||||
}
|
||||
let corner = radius::L;
|
||||
ui.painter().add(tokens::elevation::floating(t.dark).as_shape(rect, corner));
|
||||
ui.painter().rect_filled(rect, corner, t.container);
|
||||
let mut inner = ui.new_child(eframe::egui::UiBuilder::new().max_rect(rect.shrink(space::XS)));
|
||||
inner.spacing_mut().item_spacing = Vec2::ZERO;
|
||||
ScrollArea::vertical().max_height(rect.height() - 2.0 * space::XS).auto_shrink(false).show(&mut inner, |ui| {
|
||||
for (i, item) in rows.iter().enumerate() {
|
||||
let r = row(ui, t, o, depth, i, item, has_lead(rows));
|
||||
drawn.rows.push(r.rect);
|
||||
if r.contains_pointer() {
|
||||
drawn.hovered = Some(i);
|
||||
}
|
||||
if r.clicked() {
|
||||
drawn.clicked = Some(i);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
drawn
|
||||
}
|
||||
|
||||
fn row<A>(ui: &mut Ui, t: &Theme, o: &Open, depth: usize, i: usize, item: &Item<A>, lead: bool) -> Response {
|
||||
let sense = if item.pickable() { Sense::CLICK } else { Sense::hover() };
|
||||
let (rect, r) = ui.allocate_exact_size(vec2(ui.available_width(), item.height()), sense);
|
||||
if matches!(item.what, What::Line) {
|
||||
ui.painter().hline(rect.shrink2(vec2(space::M, 0.0)).x_range(), rect.center().y, (tokens::size::HAIRLINE, t.outline_variant));
|
||||
return r;
|
||||
}
|
||||
r.widget_info(|| match item.checked {
|
||||
Some(on) => WidgetInfo::selected(Role::MenuItemCheckBox, item.enabled, on, &item.text),
|
||||
None => WidgetInfo::labeled(Role::MenuItem, item.enabled, &item.text),
|
||||
});
|
||||
let marked = o.mark.get(depth) == Some(&Some(i));
|
||||
let open = o.path.get(depth) == Some(&i);
|
||||
if marked && o.keyboard {
|
||||
ui.scroll_to_rect(rect, None);
|
||||
}
|
||||
let ink = match (item.enabled, item.danger) {
|
||||
(false, _) => alpha(t.on_surface, state::DISABLED),
|
||||
(_, true) => t.error,
|
||||
_ => t.on_surface,
|
||||
};
|
||||
let faint = if item.enabled && !item.danger { t.on_variant } else { ink };
|
||||
let tint = match (item.pickable() && r.is_pointer_button_down_on(), marked || open) {
|
||||
(true, _) => state::PRESS + state::HOVER,
|
||||
(_, true) => state::PRESS,
|
||||
_ => 0.0,
|
||||
};
|
||||
let tint = motion::spring((r.id, "tint"), tint, EFFECT);
|
||||
let press = motion::spring((r.id, "press"), f32::from(item.pickable() && r.is_pointer_button_down_on()), FAST);
|
||||
let p = ui.painter();
|
||||
if item.checked == Some(true) && !lead {
|
||||
p.rect_filled(rect, cr(radius::M), t.secondary_container);
|
||||
}
|
||||
p.rect_filled(rect.shrink2(vec2(2.0, 1.0) * press), cr(radius::inner(radius::L, space::XS)), alpha(ink, tint));
|
||||
let mut x = rect.left() + space::M;
|
||||
let mid = rect.center().y;
|
||||
if lead {
|
||||
let icon = if item.checked == Some(true) { "check" } else { item.icon };
|
||||
if !icon.is_empty() {
|
||||
icons::paint(p, pos2(x + tokens::icon::M / 2.0, mid), tokens::icon::M, icon, if item.checked == Some(true) { t.primary } else { faint });
|
||||
}
|
||||
x += LEAD;
|
||||
}
|
||||
let mut end = rect.right() - space::M;
|
||||
if matches!(item.what, What::Sub(_)) {
|
||||
chevron(p, pos2(end - tokens::icon::S / 2.0, mid), tokens::icon::S, RIGHT, faint);
|
||||
end -= tokens::icon::M + space::S;
|
||||
} else if !item.keys.is_empty() {
|
||||
let keys = line(p, item.keys, fonts::ui(text::LABEL), faint, rect.width());
|
||||
end -= keys.size().x;
|
||||
left(p, pos2(end, mid), keys);
|
||||
end -= space::M;
|
||||
}
|
||||
left(p, pos2(x, mid), line(p, &item.text, fonts::ui(text::BODY), ink, end - x + 1.0));
|
||||
r
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn menus_never_leave_the_window() {
|
||||
let window = Rect::from_min_size(Pos2::ZERO, vec2(480.0, 360.0)).shrink(4.0);
|
||||
for x in [0.0, 100.0, 300.0, 479.0] {
|
||||
for y in [0.0, 100.0, 200.0, 359.0] {
|
||||
for size in [vec2(176.0, 80.0), vec2(336.0, 300.0), vec2(600.0, 900.0)] {
|
||||
for beside in [false, true] {
|
||||
let r = place(Rect::from_min_size(pos2(x, y), vec2(40.0, 40.0)), size, window, beside);
|
||||
assert!(window.contains_rect(r), "{x} {y} {size:?} {beside}: {r:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let anchor = Rect::from_min_size(pos2(20.0, 300.0), vec2(40.0, 40.0));
|
||||
assert_eq!(place(anchor, vec2(176.0, 80.0), window, false).bottom(), 296.0, "above when there is no room below");
|
||||
let anchor = Rect::from_min_size(pos2(250.0, 100.0), vec2(180.0, 36.0));
|
||||
assert_eq!(place(anchor, vec2(176.0, 80.0), window, true).right(), 250.0, "to the left when there is no room on the right");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_mark_goes_around_and_over_what_cannot_be_chosen() {
|
||||
let items = vec![Item::new("a", 0).enabled(false), Item::new("b", 1), Item::line(), Item::new("c", 2)];
|
||||
assert_eq!((next(&items, None, 1), next(&items, Some(1), 1), next(&items, Some(3), 1)), (Some(1), Some(3), Some(1)));
|
||||
assert_eq!((next(&items, None, -1), next(&items, Some(1), -1)), (Some(3), Some(3)));
|
||||
assert_eq!(next(&[Item::<u8>::line()], None, 1), None);
|
||||
assert_eq!(next::<u8>(&[], None, 1), None);
|
||||
}
|
||||
}
|
||||
8
crates/app/src/ui/mod.rs
Normal file
8
crates/app/src/ui/mod.rs
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
//! What the screens are made of.
|
||||
|
||||
pub mod dialog;
|
||||
pub mod field;
|
||||
pub mod gallery;
|
||||
pub mod menu;
|
||||
pub mod toast;
|
||||
pub mod widgets;
|
||||
180
crates/app/src/ui/toast.rs
Normal file
180
crates/app/src/ui/toast.rs
Normal file
|
|
@ -0,0 +1,180 @@
|
|||
//! Short messages at the bottom of the window. They go by themselves, wait under the pointer, and stack.
|
||||
|
||||
use super::widgets::{Button, Kind, Size, cr, text_width};
|
||||
use crate::motion::{Spring, keep_alive};
|
||||
use crate::theme::{Theme, alpha};
|
||||
use crate::tokens::spring::{DEFAULT, EFFECT};
|
||||
use crate::tokens::{self, elevation, radius, space, text, time};
|
||||
use crate::{fonts, icons};
|
||||
use eframe::egui::text::LayoutJob;
|
||||
use eframe::egui::{Area, Color32, Context, Galley, Id, Order, Rect, Sense, Ui, UiBuilder, WidgetInfo, accesskit::Role, pos2, vec2};
|
||||
use medlar_core::tr;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
/// More than this and the oldest leaves.
|
||||
const MOST: usize = 4;
|
||||
|
||||
struct Toast<A> {
|
||||
id: u64,
|
||||
icon: &'static str,
|
||||
text: String,
|
||||
error: bool,
|
||||
action: Option<(String, A)>,
|
||||
left: f64,
|
||||
leaving: bool,
|
||||
/// How far up from the bottom, and how much of it is there.
|
||||
up: Spring,
|
||||
fade: Spring,
|
||||
}
|
||||
|
||||
/// All toasts of a window. `A` is what their buttons stand for.
|
||||
pub struct Toasts<A> {
|
||||
list: Vec<Toast<A>>,
|
||||
next: u64,
|
||||
last: f64,
|
||||
}
|
||||
|
||||
impl<A> Default for Toasts<A> {
|
||||
fn default() -> Self {
|
||||
Toasts { list: Vec::new(), next: 0, last: 0.0 }
|
||||
}
|
||||
}
|
||||
|
||||
impl<A: Clone> Toasts<A> {
|
||||
pub fn info(&mut self, icon: &'static str, text: impl Into<String>) {
|
||||
self.push(icon, text.into(), false, None);
|
||||
}
|
||||
|
||||
/// What failed, then why.
|
||||
pub fn error(&mut self, text: impl Into<String>, action: Option<(String, A)>) {
|
||||
self.push("error", text.into(), true, action);
|
||||
}
|
||||
|
||||
pub fn action(&mut self, icon: &'static str, text: impl Into<String>, label: impl Into<String>, action: A) {
|
||||
self.push(icon, text.into(), false, Some((label.into(), action)));
|
||||
}
|
||||
|
||||
/// Something that was done and can be taken back.
|
||||
pub fn undo(&mut self, icon: &'static str, text: impl Into<String>, action: A) {
|
||||
self.action(icon, text, tr!("toast.undo"), action);
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.list.is_empty()
|
||||
}
|
||||
|
||||
fn push(&mut self, icon: &'static str, text: String, error: bool, action: Option<(String, A)>) {
|
||||
let left = if error || action.is_some() { time::TOAST_ACTION } else { time::TOAST };
|
||||
let staying = self.list.iter().filter(|t| !t.leaving).count();
|
||||
if staying >= MOST
|
||||
&& let Some(oldest) = self.list.iter_mut().find(|t| !t.leaving)
|
||||
{
|
||||
oldest.leaving = true;
|
||||
}
|
||||
self.next += 1;
|
||||
let start = Spring::new(-tokens::size::LARGE);
|
||||
self.list.push(Toast { id: self.next, icon, text, error, action, left, leaving: false, up: start, fade: Spring::new(0.0) });
|
||||
}
|
||||
|
||||
/// Draws them above `bottom` and gives back the action that was clicked.
|
||||
pub fn show(&mut self, ctx: &Context, t: &Theme, bottom: f32) -> Option<A> {
|
||||
let now = ctx.input(|i| i.time);
|
||||
// A window that slept wakes for the one that ends first, so its time has really gone by.
|
||||
let dt = if self.last > 0.0 { (now - self.last).max(0.0) } else { 0.0 };
|
||||
self.last = if self.list.is_empty() { 0.0 } else { now };
|
||||
let window = ctx.content_rect();
|
||||
let mut picked = None;
|
||||
let mut held = false;
|
||||
let mut up = 0.0;
|
||||
let width = tokens::size::TOAST.min(window.width() - 2.0 * space::L);
|
||||
for toast in self.list.iter_mut().rev() {
|
||||
let h = (words(ctx, toast, width, Color32::WHITE).size().y + 2.0 * space::M).ceil().max(tokens::size::LARGE - space::S);
|
||||
if !toast.leaving {
|
||||
toast.up.target = up;
|
||||
toast.fade.target = 1.0;
|
||||
up += h + space::S;
|
||||
} else {
|
||||
toast.up.target = toast.up.target.min(toast.up.x) - if toast.fade.target > 0.0 { space::XL } else { 0.0 };
|
||||
toast.fade.target = 0.0;
|
||||
}
|
||||
toast.up.step(DEFAULT);
|
||||
toast.fade.step(EFFECT);
|
||||
let y = bottom - space::L - h - toast.up.x;
|
||||
let rect = Rect::from_min_size(pos2(window.center().x - width / 2.0, y), vec2(width, h));
|
||||
let mut gone = false;
|
||||
let area = Area::new(Id::unique(("toast", toast.id))).order(Order::Foreground).fixed_pos(rect.min).constrain(false).fade_in(false);
|
||||
area.enabled(!toast.leaving).show(ctx, |ui| {
|
||||
ui.set_opacity(toast.fade.x.clamp(0.0, 1.0));
|
||||
let (rect, r) = ui.allocate_exact_size(rect.size(), Sense::hover());
|
||||
r.widget_info(|| WidgetInfo::labeled(Role::Status, true, &toast.text));
|
||||
(picked, gone) = match draw(ui, t, toast, rect) {
|
||||
(Some(a), _) => (Some(a), true),
|
||||
(None, gone) => (picked.take(), gone),
|
||||
};
|
||||
});
|
||||
held |= !toast.leaving && ctx.input(|i| i.pointer.hover_pos()).is_some_and(|p| rect.contains(p));
|
||||
toast.leaving |= gone;
|
||||
}
|
||||
// All of them wait: one that went would move the others from under the pointer.
|
||||
if !held {
|
||||
for toast in self.list.iter_mut().filter(|t| !t.leaving) {
|
||||
toast.left -= dt;
|
||||
toast.leaving = toast.left <= 0.0;
|
||||
if !toast.leaving {
|
||||
ctx.request_repaint_after(Duration::from_secs_f64(toast.left));
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.list.iter().any(|t| t.leaving) {
|
||||
keep_alive();
|
||||
}
|
||||
self.list.retain(|t| !t.leaving || t.fade.x > 0.01);
|
||||
picked
|
||||
}
|
||||
}
|
||||
|
||||
/// How much of the row is not text.
|
||||
fn rest<A>(ctx: &Context, t: &Toast<A>) -> f32 {
|
||||
let p = ctx.debug_painter();
|
||||
let button = t.action.as_ref().map_or(0.0, |(label, _)| text_width(&p, label, fonts::med(text::BODY)) + 2.0 * space::M);
|
||||
space::L + tokens::icon::M + space::M + button + tokens::size::HIT + space::S + space::S
|
||||
}
|
||||
|
||||
/// The text, in as many lines as an error with its reason may need.
|
||||
fn words<A>(ctx: &Context, t: &Toast<A>, width: f32, ink: Color32) -> Arc<Galley> {
|
||||
let mut job = LayoutJob::simple(t.text.clone(), fonts::ui(text::BODY), ink, (width - rest(ctx, t)).max(0.0));
|
||||
job.wrap.max_rows = 4;
|
||||
ctx.debug_painter().layout_job(job)
|
||||
}
|
||||
|
||||
fn draw<A: Clone>(ui: &mut Ui, t: &Theme, toast: &Toast<A>, rect: Rect) -> (Option<A>, bool) {
|
||||
let (fill, ink, accent) =
|
||||
if toast.error { (t.error_container, t.on_error_container, t.on_error_container) } else { (t.inverse_surface, t.inverse_on_surface, t.inverse_primary) };
|
||||
let p = ui.painter();
|
||||
let corner = cr(radius::L);
|
||||
p.add(elevation::floating(t.dark).as_shape(rect, corner));
|
||||
p.rect_filled(rect, corner, fill);
|
||||
icons::paint(p, rect.left_center() + vec2(space::L + tokens::icon::M / 2.0, 0.0), tokens::icon::M, toast.icon, ink);
|
||||
let x = rect.left() + space::L + tokens::icon::M + space::M;
|
||||
let room = rect.width() - rest(ui.ctx(), toast);
|
||||
let words = words(ui.ctx(), toast, rect.width(), ink);
|
||||
p.galley(pos2(x, rect.center().y - words.size().y / 2.0), words, ink);
|
||||
// The buttons take the toast's own colours.
|
||||
let mut own = t.clone();
|
||||
(own.primary, own.on_variant) = (accent, alpha(ink, 0.9));
|
||||
let mut picked = None;
|
||||
let mut gone = false;
|
||||
let side = Rect::from_min_max(pos2(x + room, rect.top()), rect.right_bottom() - vec2(space::S, 0.0));
|
||||
let mut ui = ui.new_child(UiBuilder::new().max_rect(side).layout(eframe::egui::Layout::right_to_left(eframe::egui::Align::Center)));
|
||||
ui.spacing_mut().item_spacing.x = 0.0;
|
||||
if Button::icon("close", &tr!("toast.close")).size(Size::S).show(&mut ui, &own).clicked() {
|
||||
gone = true;
|
||||
}
|
||||
if let Some((label, action)) = &toast.action
|
||||
&& Button::new(label).kind(Kind::Text).size(Size::S).show(&mut ui, &own).clicked()
|
||||
{
|
||||
picked = Some(action.clone());
|
||||
}
|
||||
(picked, gone)
|
||||
}
|
||||
426
crates/app/src/ui/widgets/button.rs
Normal file
426
crates/app/src/ui/widgets/button.rs
Normal file
|
|
@ -0,0 +1,426 @@
|
|||
//! Buttons, and groups of them.
|
||||
|
||||
use super::{Content, Feel, Look, centered, chevron, cr, feel, key_down, lerp, line, text_width, tip, waiting};
|
||||
use crate::motion::{spring, spring_from};
|
||||
use crate::theme::Theme;
|
||||
use crate::tokens::spring::{DEFAULT, EFFECT, FAST};
|
||||
use crate::tokens::{self, radius, space, text};
|
||||
use crate::{fonts, icons};
|
||||
use eframe::egui::accesskit::Role;
|
||||
use eframe::egui::{Align2, Area, Color32, Context, CornerRadius, Id, Key, Order, Pos2, Rect, Response, Sense, Ui, Vec2, WidgetInfo, pos2, vec2};
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
pub enum Kind {
|
||||
/// The main action of a screen.
|
||||
Filled,
|
||||
Tonal,
|
||||
/// On busy ground. It has no shadow: only floating things do.
|
||||
Elevated,
|
||||
Outlined,
|
||||
/// No fill at rest; also the usual icon button.
|
||||
Text,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
pub enum Size {
|
||||
S,
|
||||
M,
|
||||
L,
|
||||
}
|
||||
|
||||
impl Size {
|
||||
pub fn height(self) -> f32 {
|
||||
match self {
|
||||
Size::S => tokens::size::HIT,
|
||||
Size::M => tokens::size::CONTROL,
|
||||
Size::L => tokens::size::LARGE,
|
||||
}
|
||||
}
|
||||
|
||||
fn pad(self) -> f32 {
|
||||
match self {
|
||||
Size::S => space::M,
|
||||
Size::M => space::L,
|
||||
Size::L => space::XL,
|
||||
}
|
||||
}
|
||||
|
||||
fn icon(self) -> f32 {
|
||||
match self {
|
||||
Size::S => tokens::icon::S,
|
||||
Size::M => tokens::icon::M,
|
||||
Size::L => tokens::icon::L,
|
||||
}
|
||||
}
|
||||
|
||||
fn font(self) -> eframe::egui::FontId {
|
||||
fonts::med(if self == Size::L { text::TITLE } else { text::BODY })
|
||||
}
|
||||
|
||||
/// Corner of a pressed or chosen button.
|
||||
fn square(self) -> f32 {
|
||||
if self == Size::S { radius::S } else { radius::M }
|
||||
}
|
||||
}
|
||||
|
||||
/// A button with a text, an icon, or both. `Button::icon` is the icon button.
|
||||
pub struct Button<'a> {
|
||||
text: &'a str,
|
||||
/// What screen readers and the tooltip say.
|
||||
name: &'a str,
|
||||
icon: &'a str,
|
||||
kind: Kind,
|
||||
size: Size,
|
||||
danger: bool,
|
||||
enabled: bool,
|
||||
busy: bool,
|
||||
on: Option<bool>,
|
||||
tip: &'a str,
|
||||
keys: &'a str,
|
||||
width: Option<f32>,
|
||||
}
|
||||
|
||||
impl<'a> Button<'a> {
|
||||
pub fn new(text: &'a str) -> Self {
|
||||
Button {
|
||||
text,
|
||||
name: text,
|
||||
icon: "",
|
||||
kind: Kind::Filled,
|
||||
size: Size::M,
|
||||
danger: false,
|
||||
enabled: true,
|
||||
busy: false,
|
||||
on: None,
|
||||
tip: "",
|
||||
keys: "",
|
||||
width: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Only an icon; `name` is its tooltip.
|
||||
pub fn icon(icon: &'a str, name: &'a str) -> Self {
|
||||
Button { text: "", icon, tip: name, kind: Kind::Text, ..Button::new(name) }
|
||||
}
|
||||
|
||||
pub fn with_icon(mut self, icon: &'a str) -> Self {
|
||||
self.icon = icon;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn kind(mut self, kind: Kind) -> Self {
|
||||
self.kind = kind;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn size(mut self, size: Size) -> Self {
|
||||
self.size = size;
|
||||
self
|
||||
}
|
||||
|
||||
/// In the error colours, for what can't be taken back.
|
||||
pub fn danger(mut self, danger: bool) -> Self {
|
||||
self.danger = danger;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn enabled(mut self, enabled: bool) -> Self {
|
||||
self.enabled = enabled;
|
||||
self
|
||||
}
|
||||
|
||||
/// Can't be clicked; a spinner shows after a moment. The width stays.
|
||||
pub fn busy(mut self, busy: bool) -> Self {
|
||||
self.busy = busy;
|
||||
self
|
||||
}
|
||||
|
||||
/// A toggle button, round when off and square when on. The caller flips it on a click.
|
||||
pub fn toggle(mut self, on: bool) -> Self {
|
||||
self.on = Some(on);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn tip(mut self, tip: &'a str) -> Self {
|
||||
self.tip = tip;
|
||||
self
|
||||
}
|
||||
|
||||
/// The shortcut, shown in the tooltip.
|
||||
pub fn keys(mut self, keys: &'a str) -> Self {
|
||||
self.keys = keys;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn width(mut self, width: f32) -> Self {
|
||||
self.width = Some(width);
|
||||
self
|
||||
}
|
||||
|
||||
fn look(&self, t: &Theme, on: bool) -> Look {
|
||||
let none = Color32::TRANSPARENT;
|
||||
if self.danger {
|
||||
return match self.kind {
|
||||
Kind::Filled => Look::new(t.error, t.on_error),
|
||||
Kind::Tonal => Look::new(t.error_container, t.on_error_container),
|
||||
Kind::Elevated => Look::new(t.high, t.error),
|
||||
Kind::Outlined => Look { edge: t.outline, ..Look::new(none, t.error) },
|
||||
Kind::Text => Look::new(none, t.error),
|
||||
};
|
||||
}
|
||||
match (self.kind, self.on.is_some(), on) {
|
||||
(Kind::Filled, true, false) => Look::new(t.highest, t.on_variant),
|
||||
(Kind::Filled, ..) | (Kind::Elevated, _, true) => Look::new(t.primary, t.on_primary),
|
||||
(Kind::Tonal, _, true) => Look::new(t.secondary, t.on_secondary),
|
||||
(Kind::Tonal, ..) => Look::new(t.secondary_container, t.on_secondary_container),
|
||||
(Kind::Elevated, ..) => Look::new(t.high, t.primary),
|
||||
(Kind::Outlined, _, true) => Look::new(t.inverse_surface, t.inverse_on_surface),
|
||||
(Kind::Outlined, ..) => Look { edge: t.outline, ..Look::new(none, t.on_variant) },
|
||||
(Kind::Text, _, true) => Look::new(t.secondary_container, t.on_secondary_container),
|
||||
(Kind::Text, ..) if self.text.is_empty() => Look::new(none, t.on_variant),
|
||||
(Kind::Text, ..) => Look::new(none, t.primary),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn show(self, ui: &mut Ui, t: &Theme) -> Response {
|
||||
let h = self.size.height();
|
||||
let mut content = Content { icon: self.icon, icon_size: self.size.icon(), text: self.text, font: self.size.font(), waiting: false };
|
||||
let only_icon = self.text.is_empty();
|
||||
let width = match self.width {
|
||||
Some(w) => w,
|
||||
None if only_icon => h,
|
||||
None => (content.width(ui.painter()) + 2.0 * self.size.pad()).min(ui.available_width().max(h)),
|
||||
};
|
||||
let live = self.enabled && !self.busy;
|
||||
let (rect, r) = ui.allocate_exact_size(vec2(width, h), if live { Sense::click() } else { Sense::hover() });
|
||||
r.widget_info(|| match self.on {
|
||||
Some(on) => WidgetInfo::selected(Role::Button, live, on, self.name),
|
||||
None => WidgetInfo::labeled(Role::Button, live, self.name),
|
||||
});
|
||||
let f = feel(&r, live);
|
||||
let on = spring((r.id, "on"), f32::from(self.on == Some(true)), FAST);
|
||||
let hue = spring((r.id, "on colour"), f32::from(self.on == Some(true)), EFFECT);
|
||||
content.waiting = waiting(ui.ctx(), r.id, self.busy);
|
||||
if ui.is_rect_visible(rect) {
|
||||
let mut look = self.look(t, false).mix(self.look(t, true), hue);
|
||||
if !self.enabled {
|
||||
look = look.disabled(t);
|
||||
}
|
||||
let square = self.size.square();
|
||||
let corner = lerp(lerp(h / 2.0, square, on), radius::inner(square, space::XS), f.press);
|
||||
let p = ui.painter();
|
||||
look.paint(p, t, rect, cr(corner.clamp(radius::XS, h / 2.0)), f);
|
||||
content.paint(p, rect, if only_icon { 0.0 } else { space::S }, look.ink);
|
||||
}
|
||||
tip(&r, t, self.tip, self.keys);
|
||||
r
|
||||
}
|
||||
}
|
||||
|
||||
/// Connected buttons of which one is chosen. The pressed one grows and its neighbours give way; the whole keeps its width.
|
||||
/// `options` are icon and text, either may be empty. True when the choice changed.
|
||||
pub fn group(ui: &mut Ui, t: &Theme, name: &str, options: &[(&str, &str)], chosen: &mut usize) -> bool {
|
||||
const GAP: f32 = 2.0;
|
||||
const GROW: f32 = 12.0;
|
||||
let (size, n) = (Size::M, options.len());
|
||||
let contents: Vec<Content> =
|
||||
options.iter().map(|(icon, text)| Content { icon, text, icon_size: size.icon(), font: size.font(), waiting: false }).collect();
|
||||
let mut widths: Vec<f32> = contents.iter().map(|c| c.width(ui.painter()) + 2.0 * space::L).collect();
|
||||
let total: f32 = widths.iter().sum::<f32>() + GAP * n.saturating_sub(1) as f32;
|
||||
let scale = (ui.available_width() / total).min(1.0);
|
||||
widths.iter_mut().for_each(|w| *w *= scale);
|
||||
let (rect, whole) = ui.allocate_exact_size(vec2(total * scale, size.height()), Sense::hover());
|
||||
let mut changed = false;
|
||||
// The pointer is tested against where they rest, or they would slip from under it.
|
||||
let mut x = rect.left();
|
||||
let mut seen = Vec::new();
|
||||
for (i, w) in widths.iter().enumerate() {
|
||||
let r = ui.interact(Rect::from_min_size(pos2(x, rect.top()), vec2(*w, rect.height())), whole.id.with(i), Sense::click());
|
||||
if r.clicked() && *chosen != i {
|
||||
*chosen = i;
|
||||
changed = true;
|
||||
}
|
||||
let on = *chosen == i;
|
||||
let (icon, text) = options[i];
|
||||
r.widget_info(|| WidgetInfo::selected(Role::RadioButton, true, on, if text.is_empty() { icon } else { text }));
|
||||
let f = feel(&r, true);
|
||||
let shape = spring((r.id, "on"), f32::from(on), FAST);
|
||||
let hue = spring((r.id, "on colour"), f32::from(on), EFFECT);
|
||||
seen.push((f, shape, hue));
|
||||
x += w + GAP * scale;
|
||||
}
|
||||
let given: Vec<f32> = seen.iter().map(|(f, ..)| if n > 1 { f.press * GROW } else { 0.0 }).collect();
|
||||
for i in 0..n {
|
||||
widths[i] += given[i];
|
||||
let sides = [i.checked_sub(1), Some(i + 1).filter(|j| *j < n)];
|
||||
let share = given[i] / sides.iter().flatten().count().max(1) as f32;
|
||||
sides.into_iter().flatten().for_each(|j| widths[j] -= share);
|
||||
}
|
||||
let mut x = rect.left();
|
||||
for (i, (f, shape, hue)) in seen.into_iter().enumerate() {
|
||||
let seg = Rect::from_min_size(pos2(x, rect.top()), vec2(widths[i], rect.height()));
|
||||
let full = rect.height() / 2.0;
|
||||
let inner = lerp(lerp(radius::S, full, shape), radius::XS, f.press).clamp(radius::XS, full) as u8;
|
||||
let (l, r) = (if i == 0 { full as u8 } else { inner }, if i + 1 == n { full as u8 } else { inner });
|
||||
let corners = CornerRadius { nw: l, sw: l, ne: r, se: r };
|
||||
let look = Look::new(t.secondary_container, t.on_secondary_container).mix(Look::new(t.primary, t.on_primary), hue);
|
||||
look.paint(ui.painter(), t, seg, corners, f);
|
||||
contents[i].paint(ui.painter(), seg, space::S, look.ink);
|
||||
x += widths[i] + GAP * scale;
|
||||
}
|
||||
whole.widget_info(|| WidgetInfo::labeled(Role::RadioGroup, true, name));
|
||||
changed
|
||||
}
|
||||
|
||||
/// A main action with more behind an arrow. `open` says whether the arrow's menu is open; give the second response to
|
||||
/// `menu::below`.
|
||||
pub fn split(ui: &mut Ui, t: &Theme, icon: &str, text: &str, more: &str, open: bool) -> (Response, Response) {
|
||||
const GAP: f32 = 2.0;
|
||||
let size = Size::M;
|
||||
let content = Content { icon, text, icon_size: size.icon(), font: size.font(), waiting: false };
|
||||
let (w, h) = (content.width(ui.painter()) + 2.0 * size.pad(), size.height());
|
||||
let (rect, whole) = ui.allocate_exact_size(vec2(w + GAP + h, h), Sense::hover());
|
||||
let main_rect = Rect::from_min_size(rect.min, vec2(w, h));
|
||||
let more_rect = Rect::from_min_max(pos2(main_rect.right() + GAP, rect.top()), rect.max);
|
||||
let main = ui.interact(main_rect, whole.id.with("main"), Sense::click());
|
||||
let arrow = ui.interact(more_rect, whole.id.with("more"), Sense::click());
|
||||
main.widget_info(|| WidgetInfo::labeled(Role::Button, true, text));
|
||||
arrow.widget_info(|| WidgetInfo::labeled(Role::Button, true, more));
|
||||
let (fm, fa) = (feel(&main, true), feel(&arrow, true));
|
||||
let turn = spring((arrow.id, "open"), f32::from(open), FAST);
|
||||
let look = Look::new(t.primary, t.on_primary);
|
||||
let full = h / 2.0;
|
||||
let inner = |f: Feel| lerp(radius::XS, radius::M, f.press).clamp(radius::XS, full);
|
||||
let (m, a) = (inner(fm) as u8, lerp(inner(fa), full, turn).clamp(radius::XS, full) as u8);
|
||||
let full = full as u8;
|
||||
look.paint(ui.painter(), t, main_rect, CornerRadius { nw: full, sw: full, ne: m, se: m }, fm);
|
||||
look.paint(ui.painter(), t, more_rect, CornerRadius { nw: a, sw: a, ne: full, se: full }, fa);
|
||||
content.paint(ui.painter(), main_rect, space::S, look.ink);
|
||||
chevron(ui.painter(), more_rect.center(), size.icon(), turn, look.ink);
|
||||
tip(&arrow, t, more, "");
|
||||
(main, arrow)
|
||||
}
|
||||
|
||||
/// The floating button of a screen. With a text it is the wide one.
|
||||
pub struct Fab<'a> {
|
||||
pub icon: &'a str,
|
||||
pub text: &'a str,
|
||||
/// What it does, for the tooltip and screen readers.
|
||||
pub name: &'a str,
|
||||
pub keys: &'a str,
|
||||
}
|
||||
|
||||
impl Fab<'_> {
|
||||
pub fn show(self, ui: &mut Ui, t: &Theme) -> Response {
|
||||
let side = tokens::size::LARGE;
|
||||
let content = Content { icon: self.icon, text: self.text, icon_size: tokens::icon::L, font: fonts::med(text::BODY), waiting: false };
|
||||
let w = if self.text.is_empty() { side } else { content.width(ui.painter()) + 2.0 * space::L };
|
||||
let (rect, r) = ui.allocate_exact_size(vec2(w, side), Sense::click());
|
||||
r.widget_info(|| WidgetInfo::labeled(Role::Button, true, self.name));
|
||||
let f = feel(&r, true);
|
||||
let look = Look::new(t.primary_container, t.on_primary_container);
|
||||
let corner = cr(lerp(radius::L, radius::XL, f.press));
|
||||
ui.painter().add(tokens::elevation::floating(t.dark).as_shape(rect, corner));
|
||||
look.paint(ui.painter(), t, rect, corner, f);
|
||||
content.paint(ui.painter(), rect, space::S, look.ink);
|
||||
tip(&r, t, self.name, self.keys);
|
||||
r
|
||||
}
|
||||
}
|
||||
|
||||
/// A FAB with its bottom right corner at `at`; a click turns it into a close button with `items` (icon, text) above it.
|
||||
/// Gives back the item that was chosen.
|
||||
pub fn fab_menu(ctx: &Context, t: &Theme, id: Id, at: Pos2, names: (&str, &str), open: &mut bool, items: &[(&str, &str)]) -> Option<usize> {
|
||||
let side = tokens::size::LARGE;
|
||||
let fab = Rect::from_min_max(at - Vec2::splat(side), at);
|
||||
let (row, step) = (tokens::size::CONTROL, tokens::size::CONTROL + space::S);
|
||||
let (mut picked, was_open) = (None, *open);
|
||||
let area = Rect::from_min_max(pos2(0.0, fab.top() - space::S - step * items.len() as f32), at);
|
||||
Area::new(id).order(Order::Middle).fixed_pos(area.min).constrain(false).fade_in(false).sense(Sense::hover()).show(ctx, |ui| {
|
||||
let r = ui.interact(fab, id.with("fab"), Sense::click());
|
||||
let name = if *open { names.1 } else { names.0 };
|
||||
r.widget_info(|| WidgetInfo::labeled(Role::Button, true, name));
|
||||
let f = feel(&r, true);
|
||||
let turn = spring((id, "turn"), f32::from(*open), FAST);
|
||||
let hue = spring((id, "hue"), f32::from(*open), EFFECT);
|
||||
let look = Look::new(t.primary_container, t.on_primary_container).mix(Look::new(t.primary, t.on_primary), hue);
|
||||
let corner = cr(lerp(lerp(radius::L, side / 2.0, turn), radius::XL, f.press).clamp(radius::S, side / 2.0));
|
||||
ui.painter().add(tokens::elevation::floating(t.dark).as_shape(fab, corner));
|
||||
look.paint(ui.painter(), t, fab, corner, f);
|
||||
let icon = tokens::icon::L;
|
||||
icons::paint(ui.painter(), fab.center(), icon, "add", crate::theme::alpha(look.ink, 1.0 - hue));
|
||||
icons::paint(ui.painter(), fab.center(), icon, "close", crate::theme::alpha(look.ink, hue));
|
||||
tip(&r, t, name, "");
|
||||
if r.clicked() {
|
||||
*open = !*open;
|
||||
}
|
||||
let by_keyboard = *open && !was_open && r.has_focus();
|
||||
let mut before = 1.0;
|
||||
for (i, (icon, label)) in items.iter().enumerate() {
|
||||
// Each starts when the one below it is on its way.
|
||||
let v = spring_from((id, "item", i), 0.0, f32::from(*open && before > 0.3), if *open { FAST } else { EFFECT });
|
||||
before = v;
|
||||
if v < 0.01 {
|
||||
continue;
|
||||
}
|
||||
let content = Content { icon, text: label, icon_size: tokens::icon::M, font: fonts::med(text::BODY), waiting: false };
|
||||
let w = content.width(ui.painter()) + 2.0 * space::L;
|
||||
let rest = Rect::from_min_max(pos2(at.x - w, fab.top() - step * (i + 1) as f32), pos2(at.x, fab.top() - step * (i + 1) as f32 + row));
|
||||
let shown = rest.translate(vec2(0.0, space::L * (1.0 - v)));
|
||||
let r = ui.interact(rest, id.with(("item", i)), if *open { Sense::click() } else { Sense::hover() });
|
||||
r.widget_info(|| WidgetInfo::labeled(Role::MenuItem, *open, *label));
|
||||
if by_keyboard && i == 0 {
|
||||
r.request_focus();
|
||||
}
|
||||
let f = feel(&r, *open);
|
||||
let mut p = ui.painter().clone();
|
||||
p.multiply_opacity(v.clamp(0.0, 1.0));
|
||||
let look = Look::new(t.primary_container, t.on_primary_container);
|
||||
let corner = cr(lerp(row / 2.0, radius::M, f.press));
|
||||
p.add(tokens::elevation::floating(t.dark).as_shape(shown, corner));
|
||||
look.paint(&p, t, shown, corner, f);
|
||||
content.paint(&p, shown, space::S, look.ink);
|
||||
if r.clicked() {
|
||||
picked = Some(i);
|
||||
}
|
||||
}
|
||||
let outside = ui.input(|i| i.pointer.any_click() && i.pointer.interact_pos().is_some_and(|p| !area.contains(p) || (p.x < fab.left() - 240.0)));
|
||||
let escape = key_down(ctx, Key::Escape);
|
||||
if was_open && (picked.is_some() || outside || escape) {
|
||||
*open = false;
|
||||
if escape {
|
||||
r.request_focus();
|
||||
}
|
||||
}
|
||||
});
|
||||
picked
|
||||
}
|
||||
|
||||
/// A floating bar of buttons with the middle of its bottom edge at `at`. It slides in and out with `open`.
|
||||
pub fn toolbar(ctx: &Context, t: &Theme, id: Id, at: Pos2, open: bool, add: impl FnOnce(&mut Ui)) {
|
||||
let v = spring((id, "shown"), f32::from(open), DEFAULT);
|
||||
let fade = spring((id, "fade"), f32::from(open), EFFECT);
|
||||
if !open && fade < 0.01 {
|
||||
return;
|
||||
}
|
||||
let pad = space::S;
|
||||
let at = at + vec2(0.0, (1.0 - v) * space::XXL);
|
||||
Area::new(id).order(Order::Middle).pivot(Align2::CENTER_BOTTOM).fixed_pos(at).constrain(false).fade_in(false).enabled(open).show(ctx, |ui| {
|
||||
ui.set_opacity(fade.clamp(0.0, 1.0));
|
||||
let corner = cr(tokens::size::CONTROL / 2.0 + pad);
|
||||
eframe::egui::Frame::NONE.fill(t.container).corner_radius(corner).shadow(tokens::elevation::floating(t.dark)).inner_margin(pad).show(ui, |ui| {
|
||||
ui.spacing_mut().item_spacing.x = space::XS;
|
||||
ui.horizontal(add);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// A small label in the middle of `rect`, for counters.
|
||||
pub(super) fn badge(ui: &Ui, rect: Rect, what: &str, look: Look) {
|
||||
ui.painter().rect_filled(rect, cr(rect.height() / 2.0), look.fill);
|
||||
centered(ui.painter(), rect, line(ui.painter(), what, fonts::med(text::LABEL), look.ink, rect.width()));
|
||||
}
|
||||
|
||||
pub(super) fn badge_width(ui: &Ui, what: &str) -> f32 {
|
||||
(text_width(ui.painter(), what, fonts::med(text::LABEL)) + space::M).max(space::L + space::XS)
|
||||
}
|
||||
410
crates/app/src/ui/widgets/choice.rs
Normal file
410
crates/app/src/ui/widgets/choice.rs
Normal file
|
|
@ -0,0 +1,410 @@
|
|||
//! Switch, checkbox, radio, chips, segmented control, tabs.
|
||||
|
||||
use super::button::{badge, badge_width};
|
||||
use super::{Content, Look, cr, disabled_fill, disabled_ink, feel, left, lerp, line, ring, spinner, text_width, tip, waiting};
|
||||
use crate::motion::spring;
|
||||
use crate::theme::{Theme, alpha, mix};
|
||||
use crate::tokens::spring::{DEFAULT, EFFECT, FAST};
|
||||
use crate::tokens::{self, radius, space, text};
|
||||
use crate::{fonts, icons};
|
||||
use eframe::egui::accesskit::Role;
|
||||
use eframe::egui::{Color32, Rect, Response, Sense, Stroke, StrokeKind, Ui, Vec2, WidgetInfo, pos2, vec2};
|
||||
use medlar_core::tr;
|
||||
|
||||
/// Yes or no, or one of some.
|
||||
pub struct Choice<'a> {
|
||||
label: &'a str,
|
||||
enabled: bool,
|
||||
busy: bool,
|
||||
error: bool,
|
||||
mixed: bool,
|
||||
}
|
||||
|
||||
/// Where the box or dot of a checkbox and radio is in its hit area.
|
||||
const BOX: f32 = 18.0;
|
||||
|
||||
impl<'a> Choice<'a> {
|
||||
pub fn new(label: &'a str) -> Self {
|
||||
Choice { label, enabled: true, busy: false, error: false, mixed: false }
|
||||
}
|
||||
|
||||
pub fn enabled(mut self, enabled: bool) -> Self {
|
||||
self.enabled = enabled;
|
||||
self
|
||||
}
|
||||
|
||||
/// Can't be changed; a spinner shows after a moment.
|
||||
pub fn busy(mut self, busy: bool) -> Self {
|
||||
self.busy = busy;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn error(mut self, error: bool) -> Self {
|
||||
self.error = error;
|
||||
self
|
||||
}
|
||||
|
||||
/// A checkbox for several things of which only some are on.
|
||||
pub fn mixed(mut self, mixed: bool) -> Self {
|
||||
self.mixed = mixed;
|
||||
self
|
||||
}
|
||||
|
||||
fn live(&self) -> bool {
|
||||
self.enabled && !self.busy
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
if self.live() { Sense::click() } else { Sense::hover() }
|
||||
}
|
||||
|
||||
/// Only the switch: the label is for screen readers, the row it sits in shows it.
|
||||
pub fn switch(self, ui: &mut Ui, t: &Theme, on: &mut bool) -> Response {
|
||||
let (rect, mut r) = ui.allocate_exact_size(tokens::size::SWITCH.into(), self.sense());
|
||||
if r.clicked() {
|
||||
*on = !*on;
|
||||
r.mark_changed();
|
||||
}
|
||||
let (live, is) = (self.live(), *on);
|
||||
r.widget_info(|| WidgetInfo::selected(Role::Switch, live, is, self.label));
|
||||
let f = feel(&r, live);
|
||||
let pos = spring((r.id, "on"), f32::from(is), FAST);
|
||||
let hue = spring((r.id, "hue"), f32::from(is), EFFECT);
|
||||
let wait = waiting(ui.ctx(), r.id, self.busy);
|
||||
let (track, knob, edge, mark) = if self.enabled {
|
||||
let on_track = if self.error { t.error } else { t.primary };
|
||||
let on_knob = if self.error { t.on_error } else { t.on_primary };
|
||||
(mix(t.highest, on_track, hue), mix(t.outline, on_knob, hue), mix(if self.error { t.error } else { t.outline }, on_track, hue), on_track)
|
||||
} else {
|
||||
let (fill, ink) = (disabled_fill(t), disabled_ink(t));
|
||||
(alpha(fill, hue), mix(ink, t.surface, hue), alpha(fill, 1.0 - hue), ink)
|
||||
};
|
||||
let p = ui.painter();
|
||||
let corner = cr(rect.height() / 2.0);
|
||||
p.rect(rect, corner, track, Stroke::new(tokens::size::FOCUS_RING, edge), StrokeKind::Inside);
|
||||
let x = rect.left() + lerp(rect.height() / 2.0, rect.width() - rect.height() / 2.0, pos);
|
||||
let at = pos2(x, rect.center().y);
|
||||
if f.tint > 0.0 {
|
||||
p.circle_filled(at, space::L + space::XS, alpha(if is { t.primary } else { t.on_surface }, f.tint));
|
||||
}
|
||||
let size = lerp(lerp(space::L, space::XL, pos), space::XL + space::XS, f.press).max(space::M);
|
||||
p.circle_filled(at, size / 2.0, knob);
|
||||
if wait {
|
||||
spinner(p, at, tokens::icon::S, if is { mark } else { t.highest });
|
||||
} else {
|
||||
icons::paint(p, at, tokens::icon::S, "check", alpha(mark, hue));
|
||||
}
|
||||
if f.focus {
|
||||
ring(p, t, rect, corner);
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
/// Space for a box and its label, which is part of the target. Gives back the middle of the box.
|
||||
fn row(&self, ui: &mut Ui, t: &Theme) -> (Response, eframe::egui::Pos2) {
|
||||
let font = fonts::ui(text::BODY);
|
||||
let box_w = tokens::size::HIT;
|
||||
let room = (ui.available_width() - box_w - space::XS).max(0.0);
|
||||
let w = if self.label.is_empty() { box_w } else { box_w + space::XS + text_width(ui.painter(), self.label, font.clone()).min(room) };
|
||||
let (rect, r) = ui.allocate_exact_size(vec2(w, tokens::size::HIT), self.sense());
|
||||
let ink = match (self.enabled, self.error) {
|
||||
(false, _) => disabled_ink(t),
|
||||
(_, true) => t.error,
|
||||
_ => t.on_surface,
|
||||
};
|
||||
if !self.label.is_empty() {
|
||||
left(ui.painter(), rect.left_center() + vec2(box_w + space::XS, 0.0), line(ui.painter(), self.label, font, ink, w - box_w - space::XS + 1.0));
|
||||
}
|
||||
(r, rect.left_center() + vec2(box_w / 2.0, 0.0))
|
||||
}
|
||||
|
||||
fn line_color(&self, t: &Theme) -> Color32 {
|
||||
match (self.enabled, self.error) {
|
||||
(false, _) => disabled_ink(t),
|
||||
(_, true) => t.error,
|
||||
_ => t.on_variant,
|
||||
}
|
||||
}
|
||||
|
||||
fn fill_color(&self, t: &Theme) -> Color32 {
|
||||
match (self.enabled, self.error) {
|
||||
(false, _) => disabled_ink(t),
|
||||
(_, true) => t.error,
|
||||
_ => t.primary,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn checkbox(self, ui: &mut Ui, t: &Theme, on: &mut bool) -> Response {
|
||||
let (mut r, at) = self.row(ui, t);
|
||||
if r.clicked() {
|
||||
// Some of them on: all of them.
|
||||
*on = self.mixed || !*on;
|
||||
r.mark_changed();
|
||||
}
|
||||
let (live, is) = (self.live(), *on);
|
||||
r.widget_info(|| WidgetInfo::selected(Role::CheckBox, live, is, self.label));
|
||||
let f = feel(&r, live);
|
||||
let full = is || self.mixed;
|
||||
let v = spring((r.id, "on"), f32::from(full), FAST);
|
||||
let hue = spring((r.id, "hue"), f32::from(full), EFFECT).clamp(0.0, 1.0);
|
||||
let wait = waiting(ui.ctx(), r.id, self.busy);
|
||||
let p = ui.painter();
|
||||
self.halo(p, t, at, f.tint, full);
|
||||
if wait {
|
||||
spinner(p, at, tokens::icon::M, self.fill_color(t));
|
||||
return r;
|
||||
}
|
||||
let b = Rect::from_center_size(at, Vec2::splat(BOX * lerp(1.0, 0.88, f.press)));
|
||||
let edge = mix(self.line_color(t), self.fill_color(t), hue);
|
||||
p.rect_stroke(b, radius::XS, Stroke::new(2.0, edge), StrokeKind::Inside);
|
||||
p.rect_filled(b, radius::XS, alpha(self.fill_color(t), hue));
|
||||
let ink = if !self.enabled { t.surface } else if self.error { t.on_error } else { t.on_primary };
|
||||
let scale = lerp(0.6, 1.0, v);
|
||||
if self.mixed {
|
||||
p.hline(at.x - 5.0 * scale..=at.x + 5.0 * scale, at.y, Stroke::new(2.0, alpha(ink, hue)));
|
||||
} else {
|
||||
let points = [vec2(-4.5, 0.5), vec2(-1.5, 3.5), vec2(4.5, -3.0)].map(|d| at + d * scale);
|
||||
p.line(points.to_vec(), Stroke::new(2.0, alpha(ink, hue)));
|
||||
}
|
||||
if f.focus {
|
||||
ring(p, t, b, cr(radius::XS));
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
/// The caller changes the choice on a click.
|
||||
pub fn radio(self, ui: &mut Ui, t: &Theme, on: bool) -> Response {
|
||||
let (r, at) = self.row(ui, t);
|
||||
let live = self.live();
|
||||
r.widget_info(|| WidgetInfo::selected(Role::RadioButton, live, on, self.label));
|
||||
let f = feel(&r, live);
|
||||
let v = spring((r.id, "on"), f32::from(on), FAST);
|
||||
let hue = spring((r.id, "hue"), f32::from(on), EFFECT);
|
||||
let wait = waiting(ui.ctx(), r.id, self.busy);
|
||||
let p = ui.painter();
|
||||
self.halo(p, t, at, f.tint, on);
|
||||
if wait {
|
||||
spinner(p, at, tokens::icon::M, self.fill_color(t));
|
||||
return r;
|
||||
}
|
||||
let color = mix(self.line_color(t), self.fill_color(t), hue);
|
||||
p.circle_stroke(at, BOX / 2.0 * lerp(1.0, 0.9, f.press), Stroke::new(2.0, color));
|
||||
p.circle_filled(at, (BOX / 4.0 * v).max(0.0), alpha(color, hue));
|
||||
if f.focus {
|
||||
ring(p, t, Rect::from_center_size(at, Vec2::splat(BOX)), cr(BOX / 2.0));
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
fn halo(&self, p: &eframe::egui::Painter, t: &Theme, at: eframe::egui::Pos2, tint: f32, on: bool) {
|
||||
if tint > 0.0 {
|
||||
p.circle_filled(at, tokens::size::HIT / 2.0, alpha(if self.error { t.error } else if on { t.primary } else { t.on_surface }, tint));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A small choice, filter or value. A chip that can be chosen keeps room for its tick.
|
||||
pub struct Chip<'a> {
|
||||
text: &'a str,
|
||||
icon: &'a str,
|
||||
on: Option<bool>,
|
||||
closable: bool,
|
||||
enabled: bool,
|
||||
error: bool,
|
||||
}
|
||||
|
||||
pub struct ChipOut {
|
||||
pub response: Response,
|
||||
pub closed: bool,
|
||||
}
|
||||
|
||||
impl<'a> Chip<'a> {
|
||||
pub fn new(text: &'a str) -> Self {
|
||||
Chip { text, icon: "", on: None, closable: false, enabled: true, error: false }
|
||||
}
|
||||
|
||||
pub fn icon(mut self, icon: &'a str) -> Self {
|
||||
self.icon = icon;
|
||||
self
|
||||
}
|
||||
|
||||
/// A filter chip. The caller flips it on a click.
|
||||
pub fn filter(mut self, on: bool) -> Self {
|
||||
self.on = Some(on);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn closable(mut self) -> Self {
|
||||
self.closable = true;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn enabled(mut self, enabled: bool) -> Self {
|
||||
self.enabled = enabled;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn error(mut self, error: bool) -> Self {
|
||||
self.error = error;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn show(self, ui: &mut Ui, t: &Theme) -> ChipOut {
|
||||
let (font, icon) = (fonts::med(text::LABEL), tokens::icon::S);
|
||||
let h = tokens::size::HIT;
|
||||
let has_lead = self.on.is_some() || !self.icon.is_empty();
|
||||
let lead = if has_lead { icon + space::XS } else { 0.0 };
|
||||
let trail = if self.closable { h - space::S } else { 0.0 };
|
||||
let natural = text_width(ui.painter(), self.text, font.clone()) + lead + trail + 2.0 * space::M;
|
||||
let w = natural.min(ui.available_width().max(h * 2.0));
|
||||
let sense = if self.enabled { Sense::click() } else { Sense::hover() };
|
||||
let (rect, r) = ui.allocate_exact_size(vec2(w, h), sense);
|
||||
let on = self.on == Some(true);
|
||||
r.widget_info(|| match self.on {
|
||||
Some(on) => WidgetInfo::selected(Role::Button, self.enabled, on, self.text),
|
||||
None => WidgetInfo::labeled(Role::Button, self.enabled, self.text),
|
||||
});
|
||||
let f = feel(&r, self.enabled);
|
||||
let hue = spring((r.id, "hue"), f32::from(on), EFFECT);
|
||||
let v = spring((r.id, "on"), f32::from(on), FAST);
|
||||
let rest = Look { edge: t.outline_variant, ..Look::new(Color32::TRANSPARENT, t.on_variant) };
|
||||
let mut look = rest.mix(Look::new(t.secondary_container, t.on_secondary_container), hue);
|
||||
if self.error {
|
||||
look = Look { edge: t.error, ..Look::new(Color32::TRANSPARENT, t.error) };
|
||||
}
|
||||
if !self.enabled {
|
||||
look = look.disabled(t);
|
||||
}
|
||||
let p = ui.painter();
|
||||
look.paint(p, t, rect, cr(lerp(lerp(radius::S, h / 2.0, v), radius::XS, f.press).clamp(radius::XS, h / 2.0)), f);
|
||||
let lead_at = rect.left_center() + vec2(space::S + icon / 2.0, 0.0);
|
||||
// Without an icon the text sits in the middle until the tick comes.
|
||||
let empty = self.icon.is_empty() && self.on.is_some();
|
||||
if !self.icon.is_empty() {
|
||||
icons::paint(p, lead_at, icon, self.icon, alpha(look.ink, look.ink.a() as f32 / 255.0 * if self.on.is_some() { 1.0 - hue } else { 1.0 }));
|
||||
}
|
||||
if self.on.is_some() {
|
||||
icons::paint(p, lead_at, icon, "check", alpha(look.ink, hue));
|
||||
}
|
||||
let shift = if empty { lead / 2.0 * (1.0 - v) } else { 0.0 };
|
||||
let start = if has_lead { space::S + lead } else { space::M };
|
||||
left(p, rect.left_center() + vec2(start - shift, 0.0), line(p, self.text, font, look.ink, w - start - trail - space::S));
|
||||
let mut closed = false;
|
||||
if self.closable {
|
||||
let x = ui.interact(Rect::from_center_size(rect.right_center() - vec2(h / 2.0, 0.0), Vec2::splat(h)), r.id.with("close"), sense);
|
||||
let name = tr!("chip.remove", name = self.text);
|
||||
x.widget_info(|| WidgetInfo::labeled(Role::Button, self.enabled, &name));
|
||||
let fx = feel(&x, self.enabled);
|
||||
let p = ui.painter();
|
||||
p.circle_filled(x.rect.center(), space::M, alpha(look.ink, fx.tint));
|
||||
icons::paint(p, x.rect.center(), icon, "close", look.ink);
|
||||
if fx.focus {
|
||||
ring(p, t, x.rect.shrink(space::XS), cr(h / 2.0));
|
||||
}
|
||||
tip(&x, t, &name, "");
|
||||
closed = x.clicked();
|
||||
}
|
||||
ChipOut { response: r, closed }
|
||||
}
|
||||
}
|
||||
|
||||
/// One of a few, with the chosen mark sliding to its place. Takes the whole width. True when the choice changed.
|
||||
pub fn segmented(ui: &mut Ui, t: &Theme, name: &str, options: &[(&str, &str)], chosen: &mut usize) -> bool {
|
||||
let (h, pad) = (tokens::size::CONTROL, space::XS);
|
||||
let (rect, whole) = ui.allocate_exact_size(vec2(ui.available_width(), h), Sense::hover());
|
||||
whole.widget_info(|| WidgetInfo::labeled(Role::RadioGroup, true, name));
|
||||
ui.painter().rect_filled(rect, cr(h / 2.0), t.high);
|
||||
let inside = rect.shrink(pad);
|
||||
let w = inside.width() / options.len().max(1) as f32;
|
||||
let seg = |i: f32| Rect::from_min_size(inside.min + vec2(w * i, 0.0), vec2(w, inside.height()));
|
||||
let (mut changed, mut rows) = (false, Vec::new());
|
||||
for i in 0..options.len() {
|
||||
let r = ui.interact(seg(i as f32), whole.id.with(i), Sense::click());
|
||||
if r.clicked() && *chosen != i {
|
||||
*chosen = i;
|
||||
changed = true;
|
||||
}
|
||||
rows.push(r);
|
||||
}
|
||||
let corner = cr(inside.height() / 2.0);
|
||||
let pos = spring((whole.id, "place"), *chosen as f32, DEFAULT);
|
||||
// It may overshoot, but never leaves the track.
|
||||
let pill = seg(pos);
|
||||
ui.painter().rect_filled(pill.intersect(inside), corner, t.secondary_container);
|
||||
for (i, r) in rows.iter().enumerate() {
|
||||
let on = *chosen == i;
|
||||
let (icon, what) = options[i];
|
||||
r.widget_info(|| WidgetInfo::selected(Role::RadioButton, true, on, if what.is_empty() { icon } else { what }));
|
||||
let f = feel(r, true);
|
||||
let hue = spring((r.id, "hue"), f32::from(on), EFFECT);
|
||||
let look = Look::new(Color32::TRANSPARENT, mix(t.on_variant, t.on_secondary_container, hue));
|
||||
look.paint(ui.painter(), t, seg(i as f32).shrink(2.0 * f.press), corner, f);
|
||||
Content { icon, text: what, icon_size: tokens::icon::S, font: fonts::med(text::BODY), waiting: false }.paint(ui.painter(), seg(i as f32), space::S, look.ink);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// A tab; `count` is a small number behind the name.
|
||||
pub struct Tab<'a> {
|
||||
pub icon: &'a str,
|
||||
pub text: &'a str,
|
||||
pub count: Option<usize>,
|
||||
}
|
||||
|
||||
/// Tabs with an underline that stretches to the chosen one. True when the choice changed.
|
||||
pub fn tabs(ui: &mut Ui, t: &Theme, name: &str, options: &[Tab], chosen: &mut usize) -> bool {
|
||||
let (h, bar) = (tokens::size::CONTROL + space::S, 3.0);
|
||||
let font = fonts::med(text::BODY);
|
||||
let counts: Vec<String> = options.iter().map(|o| o.count.map(|c| c.to_string()).unwrap_or_default()).collect();
|
||||
let content = |o: &Tab| (if o.icon.is_empty() { 0.0 } else { tokens::icon::M + space::S }) + text_width(ui.painter(), o.text, font.clone());
|
||||
let inner: Vec<f32> = options.iter().zip(&counts).map(|(o, c)| content(o) + if c.is_empty() { 0.0 } else { badge_width(ui, c) + space::S }).collect();
|
||||
let total: f32 = inner.iter().map(|w| w + 2.0 * space::L).sum();
|
||||
let scale = (ui.available_width() / total.max(1.0)).min(1.0);
|
||||
let (rect, whole) = ui.allocate_exact_size(vec2(ui.available_width(), h), Sense::hover());
|
||||
whole.widget_info(|| WidgetInfo::labeled(Role::TabList, true, name));
|
||||
ui.painter().hline(rect.x_range(), rect.bottom() - 0.5, Stroke::new(tokens::size::HAIRLINE, t.outline_variant));
|
||||
let (mut changed, mut x, mut mark) = (false, rect.left(), rect);
|
||||
for (i, o) in options.iter().enumerate() {
|
||||
let w = (inner[i] + 2.0 * space::L) * scale;
|
||||
let tab = Rect::from_min_size(pos2(x, rect.top()), vec2(w, h));
|
||||
x += w;
|
||||
let r = ui.interact(tab, whole.id.with(i), Sense::click());
|
||||
if r.clicked() && *chosen != i {
|
||||
*chosen = i;
|
||||
changed = true;
|
||||
}
|
||||
let on = *chosen == i;
|
||||
r.widget_info(|| WidgetInfo::selected(Role::Tab, true, on, o.text));
|
||||
let f = feel(&r, true);
|
||||
let hue = spring((r.id, "hue"), f32::from(on), EFFECT);
|
||||
let ink = mix(t.on_variant, t.primary, hue);
|
||||
Look::new(Color32::TRANSPARENT, ink).paint(ui.painter(), t, tab.shrink2(vec2(space::XS, space::XS)).shrink(2.0 * f.press), cr(radius::S), f);
|
||||
let wide = inner[i].min(w - 2.0 * space::S);
|
||||
let mut at = pos2(tab.center().x - wide / 2.0, tab.center().y);
|
||||
let end = at.x + wide;
|
||||
if !o.icon.is_empty() {
|
||||
icons::paint(ui.painter(), at + vec2(tokens::icon::M / 2.0, 0.0), tokens::icon::M, o.icon, ink);
|
||||
at.x += tokens::icon::M + space::S;
|
||||
}
|
||||
let badge_w = if counts[i].is_empty() { 0.0 } else { badge_width(ui, &counts[i]) + space::S };
|
||||
left(ui.painter(), at, line(ui.painter(), o.text, font.clone(), ink, end - at.x - badge_w + 1.0));
|
||||
if badge_w > 0.0 {
|
||||
let b = Rect::from_min_size(pos2(end - badge_w + space::S, tab.center().y - space::S - 1.0), vec2(badge_w - space::S, space::L + 2.0));
|
||||
badge(ui, b, &counts[i], Look::new(mix(t.highest, t.primary_container, hue), mix(t.on_variant, t.on_primary_container, hue)));
|
||||
}
|
||||
if on {
|
||||
mark = Rect::from_min_max(pos2(tab.center().x - wide / 2.0, h), pos2(tab.center().x + wide / 2.0, h));
|
||||
}
|
||||
}
|
||||
// The edge that leads is the faster one, so the bar stretches on its way.
|
||||
let (a, b) = (whole.id.with("bar left"), whole.id.with("bar right"));
|
||||
let now = spring((a, "seen"), mark.left(), EFFECT);
|
||||
let to_right = mark.left() > now;
|
||||
let l = spring(a, mark.left(), if to_right { EFFECT } else { FAST });
|
||||
let r = spring(b, mark.right(), if to_right { FAST } else { EFFECT });
|
||||
if !options.is_empty() {
|
||||
let bar = Rect::from_min_max(pos2(l.max(rect.left()), rect.bottom() - bar), pos2(r.min(rect.right()), rect.bottom()));
|
||||
ui.painter().rect_filled(bar, eframe::egui::CornerRadius { nw: 3, ne: 3, sw: 0, se: 0 }, t.primary);
|
||||
}
|
||||
changed
|
||||
}
|
||||
251
crates/app/src/ui/widgets/mod.rs
Normal file
251
crates/app/src/ui/widgets/mod.rs
Normal file
|
|
@ -0,0 +1,251 @@
|
|||
//! Controls. Every one takes the theme, answers hover, press and the keyboard, and draws frames only while it moves.
|
||||
|
||||
mod button;
|
||||
mod choice;
|
||||
mod slider;
|
||||
|
||||
pub use button::{Button, Fab, Kind, Size, fab_menu, group, split, toolbar};
|
||||
pub use choice::{Chip, ChipOut, Choice, Tab, segmented, tabs};
|
||||
pub use slider::{Slider, range};
|
||||
|
||||
use crate::icons;
|
||||
use crate::motion::{self, spring};
|
||||
use crate::theme::{Theme, alpha, mix};
|
||||
use crate::tokens::spring::{EFFECT, FAST};
|
||||
use crate::tokens::{self, radius, space, state, text};
|
||||
use crate::{fonts, motion::keep_alive};
|
||||
use eframe::egui::{
|
||||
self, Align2, Color32, Context, CornerRadius, Event, FontId, Frame, Galley, Id, Key, Painter, Pos2, Rect, Response, Stroke, StrokeKind, Tooltip, Ui,
|
||||
pos2, text::{LayoutJob, TextWrapping}, vec2,
|
||||
};
|
||||
use medlar_core::settings::Motion;
|
||||
use std::f32::consts::{FRAC_PI_2, TAU};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub fn lerp(a: f32, b: f32, t: f32) -> f32 {
|
||||
a + (b - a) * t
|
||||
}
|
||||
|
||||
pub fn cr(r: f32) -> CornerRadius {
|
||||
CornerRadius::same(r.round().clamp(0.0, 255.0) as u8)
|
||||
}
|
||||
|
||||
/// How a control answers right now.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct Feel {
|
||||
/// Opacity of the on-colour laid over it.
|
||||
pub tint: f32,
|
||||
/// 0 at rest, about 1 pressed; may overshoot.
|
||||
pub press: f32,
|
||||
/// The keyboard is on it.
|
||||
pub focus: bool,
|
||||
}
|
||||
|
||||
/// Call once per control and frame. `live` is false while it is disabled or busy.
|
||||
pub fn feel(r: &Response, live: bool) -> Feel {
|
||||
let down = live && r.is_pointer_button_down_on();
|
||||
let focus = live && r.has_focus();
|
||||
if focus && key_down(&r.ctx, Key::Enter) {
|
||||
take_enter(&r.ctx);
|
||||
}
|
||||
let tint = match (down, live && r.hovered()) {
|
||||
(true, _) => state::PRESS,
|
||||
(_, true) => state::HOVER,
|
||||
_ => 0.0,
|
||||
};
|
||||
Feel { tint: spring((r.id, "tint"), tint, EFFECT), press: spring((r.id, "press"), f32::from(down), FAST), focus }
|
||||
}
|
||||
|
||||
/// Was `key` pressed this frame, not held from before?
|
||||
pub(super) fn key_down(ctx: &Context, key: Key) -> bool {
|
||||
ctx.input(|i| i.events.iter().any(|e| matches!(e, Event::Key { key: k, pressed: true, repeat: false, .. } if *k == key)))
|
||||
}
|
||||
|
||||
/// Notes that a control used Enter, so a dialog doesn't use it too.
|
||||
pub(super) fn take_enter(ctx: &Context) {
|
||||
let pass = ctx.cumulative_pass_nr();
|
||||
ctx.data_mut(|d| d.insert_temp(Id::unique("enter taken"), pass));
|
||||
}
|
||||
|
||||
pub(super) fn enter_taken(ctx: &Context) -> bool {
|
||||
ctx.data(|d| d.get_temp::<u64>(Id::unique("enter taken"))) == Some(ctx.cumulative_pass_nr())
|
||||
}
|
||||
|
||||
pub(super) fn disabled_ink(t: &Theme) -> Color32 {
|
||||
alpha(t.on_surface, state::DISABLED)
|
||||
}
|
||||
|
||||
pub(super) fn disabled_fill(t: &Theme) -> Color32 {
|
||||
alpha(t.on_surface, state::DISABLED_FILL)
|
||||
}
|
||||
|
||||
/// The ring of keyboard focus. It is there at once and never animated.
|
||||
pub fn ring(p: &Painter, t: &Theme, rect: Rect, corners: CornerRadius) {
|
||||
let gap = tokens::size::FOCUS_RING;
|
||||
p.rect_stroke(rect.expand(gap), corners + CornerRadius::same(gap as u8), Stroke::new(gap, t.primary), StrokeKind::Outside);
|
||||
}
|
||||
|
||||
/// One line of text, cut with an ellipsis when it is wider than `width`.
|
||||
pub fn line(p: &Painter, what: &str, font: FontId, color: Color32, width: f32) -> Arc<Galley> {
|
||||
let mut job = LayoutJob::simple_singleline(what.to_string(), font, color);
|
||||
job.wrap = TextWrapping::truncate_at_width(width.max(0.0));
|
||||
p.layout_job(job)
|
||||
}
|
||||
|
||||
pub fn text_width(p: &Painter, what: &str, font: FontId) -> f32 {
|
||||
p.layout_no_wrap(what.to_string(), font, Color32::WHITE).size().x.ceil()
|
||||
}
|
||||
|
||||
/// Draws a line of text with its left edge and middle at `at`.
|
||||
pub fn left(p: &Painter, at: Pos2, galley: Arc<Galley>) {
|
||||
let rect = Align2::LEFT_CENTER.anchor_size(at, galley.size());
|
||||
p.galley(rect.min, galley, Color32::WHITE);
|
||||
}
|
||||
|
||||
/// A line of text in the middle of `rect`.
|
||||
pub fn centered(p: &Painter, rect: Rect, galley: Arc<Galley>) {
|
||||
p.galley(rect.center() - galley.size() / 2.0, galley, Color32::WHITE);
|
||||
}
|
||||
|
||||
/// An arrow of two strokes: 0 points down, 1 points up, `-0.5` points right.
|
||||
pub fn chevron(p: &Painter, center: Pos2, size: f32, turn: f32, color: Color32) {
|
||||
let (sin, cos) = (turn * std::f32::consts::PI).sin_cos();
|
||||
let points = [vec2(-0.3, -0.15), vec2(0.0, 0.15), vec2(0.3, -0.15)]
|
||||
.map(|v| center + vec2(v.x * cos - v.y * sin, v.x * sin + v.y * cos) * size);
|
||||
p.line(points.to_vec(), Stroke::new(1.75, color));
|
||||
}
|
||||
|
||||
/// True once `busy` has lasted long enough to say so.
|
||||
pub fn waiting(ctx: &Context, id: Id, busy: bool) -> bool {
|
||||
let key = id.with("busy since");
|
||||
if !busy {
|
||||
ctx.data_mut(|d| d.remove::<f64>(key));
|
||||
return false;
|
||||
}
|
||||
let now = ctx.input(|i| i.time);
|
||||
let since = ctx.data_mut(|d| *d.get_temp_mut_or(key, now));
|
||||
let rest = tokens::time::LOADING - (now - since);
|
||||
if rest > 0.0 {
|
||||
ctx.request_repaint_after(std::time::Duration::from_secs_f64(rest));
|
||||
}
|
||||
rest <= 0.0
|
||||
}
|
||||
|
||||
/// A turning arc; a still hourglass when motion is off.
|
||||
pub fn spinner(p: &Painter, center: Pos2, size: f32, color: Color32) {
|
||||
if motion::level() == Motion::Off {
|
||||
return icons::paint(p, center, size, "hourglass_empty", color);
|
||||
}
|
||||
keep_alive();
|
||||
let start = (p.ctx().input(|i| i.time) * 5.0 % TAU as f64) as f32;
|
||||
let r = size * 0.4;
|
||||
let points = (0..=24).map(|i| center + egui::Vec2::angled(start + i as f32 / 24.0 * 1.5 * std::f32::consts::PI) * r).collect();
|
||||
p.line(points, Stroke::new(size / 9.0, color));
|
||||
}
|
||||
|
||||
/// A tooltip with the name of the action and its shortcut.
|
||||
pub fn tip(r: &Response, t: &Theme, what: &str, keys: &str) {
|
||||
if what.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut tooltip = Tooltip::for_enabled(r).gap(space::S);
|
||||
let frame = Frame::NONE.fill(t.inverse_surface).corner_radius(radius::S).inner_margin(egui::Margin::symmetric(space::S as i8, space::XS as i8 + 2));
|
||||
tooltip.popup = tooltip.popup.frame(frame);
|
||||
tooltip.show(|ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(egui::RichText::new(what).font(fonts::ui(text::LABEL)).color(t.inverse_on_surface));
|
||||
if !keys.is_empty() {
|
||||
let w = text_width(ui.painter(), keys, fonts::med(text::LABEL)) + space::S;
|
||||
let (rect, _) = ui.allocate_exact_size(vec2(w, text::LABEL + space::S), egui::Sense::hover());
|
||||
ui.painter().rect_filled(rect, radius::XS, alpha(t.inverse_on_surface, state::DRAG));
|
||||
centered(ui.painter(), rect, line(ui.painter(), keys, fonts::med(text::LABEL), t.inverse_on_surface, w));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// Colours of a filled shape with something on it.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct Look {
|
||||
pub fill: Color32,
|
||||
pub ink: Color32,
|
||||
pub edge: Color32,
|
||||
}
|
||||
|
||||
impl Look {
|
||||
pub fn new(fill: Color32, ink: Color32) -> Look {
|
||||
Look { fill, ink, edge: Color32::TRANSPARENT }
|
||||
}
|
||||
|
||||
pub fn disabled(self, t: &Theme) -> Look {
|
||||
Look {
|
||||
fill: if self.fill.a() > 0 { disabled_fill(t) } else { self.fill },
|
||||
ink: disabled_ink(t),
|
||||
edge: if self.edge.a() > 0 { disabled_fill(t) } else { self.edge },
|
||||
}
|
||||
}
|
||||
|
||||
pub fn mix(self, o: Look, v: f32) -> Look {
|
||||
Look { fill: mix(self.fill, o.fill, v), ink: mix(self.ink, o.ink, v), edge: mix(self.edge, o.edge, v) }
|
||||
}
|
||||
|
||||
pub fn paint(&self, p: &Painter, t: &Theme, rect: Rect, corners: CornerRadius, f: Feel) {
|
||||
p.rect_filled(rect, corners, self.fill);
|
||||
if f.tint > 0.0 {
|
||||
p.rect_filled(rect, corners, alpha(self.ink, f.tint));
|
||||
}
|
||||
if self.edge.a() > 0 {
|
||||
p.rect_stroke(rect, corners, Stroke::new(tokens::size::HAIRLINE, self.edge), StrokeKind::Inside);
|
||||
}
|
||||
if f.focus {
|
||||
ring(p, t, rect, corners);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Icon and text side by side in the middle of `rect`; a spinner takes the icon's place.
|
||||
pub(super) struct Content<'a> {
|
||||
pub icon: &'a str,
|
||||
pub icon_size: f32,
|
||||
pub text: &'a str,
|
||||
pub font: FontId,
|
||||
pub waiting: bool,
|
||||
}
|
||||
|
||||
impl Content<'_> {
|
||||
pub fn width(&self, p: &Painter) -> f32 {
|
||||
let icon = if self.icon.is_empty() { 0.0 } else { self.icon_size };
|
||||
let gap = if self.icon.is_empty() || self.text.is_empty() { 0.0 } else { space::S };
|
||||
icon + gap + if self.text.is_empty() { 0.0 } else { text_width(p, self.text, self.font.clone()) }
|
||||
}
|
||||
|
||||
pub fn paint(&self, p: &Painter, rect: Rect, pad: f32, ink: Color32) {
|
||||
let no_icon = self.icon.is_empty();
|
||||
if self.waiting && no_icon {
|
||||
return spinner(p, rect.center(), self.icon_size, ink);
|
||||
}
|
||||
let width = self.width(p).min(rect.width() - 2.0 * pad);
|
||||
let x = rect.center().x - width / 2.0;
|
||||
let icon_at = pos2(x + self.icon_size / 2.0, rect.center().y);
|
||||
if self.waiting {
|
||||
spinner(p, icon_at, self.icon_size, ink);
|
||||
} else if !no_icon {
|
||||
icons::paint(p, icon_at, self.icon_size, self.icon, ink);
|
||||
}
|
||||
if !self.text.is_empty() {
|
||||
let skip = if no_icon { 0.0 } else { self.icon_size + space::S };
|
||||
left(p, pos2(x + skip, rect.center().y), line(p, self.text, self.font.clone(), ink, width - skip + 1.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Turns the arrow keys into steps while `r` has focus, instead of moving the focus.
|
||||
pub(super) fn hold_arrows(ui: &Ui, r: &Response, horizontal: bool, vertical: bool) {
|
||||
if r.has_focus() {
|
||||
let filter = egui::EventFilter { tab: false, horizontal_arrows: horizontal, vertical_arrows: vertical, escape: false };
|
||||
ui.memory_mut(|m| m.set_focus_lock_filter(r.id, filter));
|
||||
}
|
||||
}
|
||||
|
||||
/// A quarter turn back, for chevrons that point right.
|
||||
pub(super) const RIGHT: f32 = -FRAC_PI_2 / std::f32::consts::PI;
|
||||
240
crates/app/src/ui/widgets/slider.rs
Normal file
240
crates/app/src/ui/widgets/slider.rs
Normal file
|
|
@ -0,0 +1,240 @@
|
|||
//! Slider and range.
|
||||
|
||||
use super::{Feel, cr, disabled_fill, disabled_ink, feel, hold_arrows, lerp, line, ring, spinner, text_width, waiting};
|
||||
use crate::motion::spring;
|
||||
use crate::theme::Theme;
|
||||
use crate::tokens::spring::{EFFECT, FAST};
|
||||
use crate::tokens::{self, radius, space, text};
|
||||
use crate::fonts;
|
||||
use eframe::egui::{Color32, CornerRadius, Id, Key, Pos2, Rect, Response, Sense, Ui, WidgetInfo, pos2, vec2};
|
||||
use std::ops::RangeInclusive;
|
||||
|
||||
const TRACK: f32 = 16.0;
|
||||
const HANDLE: f32 = 4.0;
|
||||
const GAP: f32 = 6.0;
|
||||
|
||||
/// A bar with a handle. The grabbed point stays under the pointer; a click on the bar goes there.
|
||||
pub struct Slider<'a> {
|
||||
name: &'a str,
|
||||
range: RangeInclusive<f64>,
|
||||
step: f64,
|
||||
enabled: bool,
|
||||
busy: bool,
|
||||
error: bool,
|
||||
width: Option<f32>,
|
||||
show: Option<&'a dyn Fn(f64) -> String>,
|
||||
}
|
||||
|
||||
impl<'a> Slider<'a> {
|
||||
pub fn new(name: &'a str, range: RangeInclusive<f64>, step: f64) -> Self {
|
||||
Slider { name, range, step, enabled: true, busy: false, error: false, width: None, show: None }
|
||||
}
|
||||
|
||||
pub fn enabled(mut self, enabled: bool) -> Self {
|
||||
self.enabled = enabled;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn busy(mut self, busy: bool) -> Self {
|
||||
self.busy = busy;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn error(mut self, error: bool) -> Self {
|
||||
self.error = error;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn width(mut self, width: f32) -> Self {
|
||||
self.width = Some(width);
|
||||
self
|
||||
}
|
||||
|
||||
/// The words of the bubble over the handle while it is dragged.
|
||||
pub fn show_value(mut self, show: &'a dyn Fn(f64) -> String) -> Self {
|
||||
self.show = Some(show);
|
||||
self
|
||||
}
|
||||
|
||||
/// The response is `changed()` when the value is new, `drag_stopped()` when it is let go.
|
||||
pub fn show(self, ui: &mut Ui, t: &Theme, value: &mut f64) -> Response {
|
||||
let (rect, whole) = allocate(ui, self.width);
|
||||
let r = self.handle(ui, whole.id.with("handle"), rect, rect, value);
|
||||
let x = place(rect, &self.range, *value);
|
||||
let f = feel(&r, self.live());
|
||||
self.paint(ui, t, rect, whole.id, None, (x, f, &r), *value);
|
||||
r
|
||||
}
|
||||
|
||||
fn live(&self) -> bool {
|
||||
self.enabled && !self.busy
|
||||
}
|
||||
|
||||
fn snap(&self, v: f64) -> f64 {
|
||||
let (lo, hi) = (*self.range.start(), *self.range.end());
|
||||
let v = if self.step > 0.0 { lo + ((v - lo) / self.step).round() * self.step } else { v };
|
||||
v.clamp(lo, hi)
|
||||
}
|
||||
|
||||
fn handle(&self, ui: &Ui, id: Id, rect: Rect, hit: Rect, value: &mut f64) -> Response {
|
||||
let mut r = ui.interact(hit, id, if self.live() { Sense::click_and_drag() } else { Sense::hover() });
|
||||
let before = *value;
|
||||
let x = place(rect, &self.range, *value);
|
||||
let grab = id.with("grab");
|
||||
if r.is_pointer_button_down_on() && ui.input(|i| i.pointer.any_pressed()) {
|
||||
let off = r.interact_pointer_pos().map_or(0.0, |p| x - p.x);
|
||||
ui.data_mut(|d| d.insert_temp(grab, if off.abs() <= tokens::size::HIT / 2.0 { off } else { 0.0f32 }));
|
||||
}
|
||||
if let Some(p) = r.interact_pointer_pos().filter(|_| r.is_pointer_button_down_on() || r.dragged()) {
|
||||
let off = ui.data(|d| d.get_temp::<f32>(grab)).unwrap_or(0.0);
|
||||
// A press on the handle alone must not move it.
|
||||
if off == 0.0 || r.dragged() && r.drag_delta().x != 0.0 {
|
||||
*value = self.snap(value_at(rect, &self.range, p.x + off));
|
||||
}
|
||||
}
|
||||
hold_arrows(ui, &r, true, true);
|
||||
if r.has_focus() {
|
||||
let step = if self.step > 0.0 { self.step } else { (self.range.end() - self.range.start()) / 100.0 };
|
||||
let by = |k, n: f64| ui.input(|i| i.key_pressed(k)).then_some(n * step);
|
||||
let moves = [
|
||||
by(Key::ArrowRight, 1.0),
|
||||
by(Key::ArrowUp, 1.0),
|
||||
by(Key::ArrowLeft, -1.0),
|
||||
by(Key::ArrowDown, -1.0),
|
||||
by(Key::PageUp, 10.0),
|
||||
by(Key::PageDown, -10.0),
|
||||
];
|
||||
*value = self.snap(*value + moves.into_iter().flatten().sum::<f64>());
|
||||
if ui.input(|i| i.key_pressed(Key::Home)) {
|
||||
*value = *self.range.start();
|
||||
}
|
||||
if ui.input(|i| i.key_pressed(Key::End)) {
|
||||
*value = *self.range.end();
|
||||
}
|
||||
}
|
||||
if *value != before {
|
||||
r.mark_changed();
|
||||
}
|
||||
let v = *value;
|
||||
r.widget_info(|| WidgetInfo::slider(self.live(), v, self.name));
|
||||
r
|
||||
}
|
||||
|
||||
/// `low` is the second handle of a range.
|
||||
fn paint(&self, ui: &Ui, t: &Theme, rect: Rect, id: Id, low: Option<(f32, Feel, &Response, f64)>, high: (f32, Feel, &Response), value: f64) {
|
||||
let p = ui.painter();
|
||||
let mid = rect.center().y;
|
||||
let (on, off) = match (self.enabled, self.error) {
|
||||
(false, _) => (disabled_ink(t), disabled_fill(t)),
|
||||
(_, true) => (t.error, t.error_container),
|
||||
_ => (t.primary, t.secondary_container),
|
||||
};
|
||||
let half = |f: Feel| lerp(HANDLE, HANDLE / 2.0, f.press).max(1.0) / 2.0;
|
||||
let bar = |a: f32, b: f32, l: f32, r: f32, c: Color32| {
|
||||
if b - a >= 1.0 {
|
||||
let max = ((b - a) / 2.0).min(TRACK / 2.0);
|
||||
let corners = CornerRadius { nw: l.min(max) as u8, sw: l.min(max) as u8, ne: r.min(max) as u8, se: r.min(max) as u8 };
|
||||
p.rect_filled(Rect::from_min_max(pos2(a, mid - TRACK / 2.0), pos2(b, mid + TRACK / 2.0)), corners, c);
|
||||
}
|
||||
};
|
||||
let (full, small) = (TRACK / 2.0, 2.0);
|
||||
let hx = high.0;
|
||||
let mut start = rect.left();
|
||||
if let Some((lx, f, ..)) = low {
|
||||
bar(rect.left(), lx - half(f) - GAP, full, small, off);
|
||||
start = lx + half(f) + GAP;
|
||||
}
|
||||
bar(start, hx - half(high.1) - GAP, if low.is_some() { small } else { full }, small, on);
|
||||
bar(hx + half(high.1) + GAP, rect.right(), small, full, off);
|
||||
let one = |x: f32, f: Feel, r: &Response, v: f64| {
|
||||
let h = Rect::from_center_size(pos2(x, mid), vec2(half(f) * 2.0, rect.height()));
|
||||
p.rect_filled(h, cr(2.0), on);
|
||||
if f.tint > 0.0 && r.hovered() && !r.dragged() {
|
||||
p.rect_filled(h.expand(1.0), cr(3.0), on);
|
||||
}
|
||||
if f.focus {
|
||||
ring(p, t, h, cr(2.0));
|
||||
}
|
||||
let shown = spring((r.id, "bubble"), f32::from(r.dragged()), EFFECT);
|
||||
let up = spring((r.id, "bubble up"), f32::from(r.dragged()), FAST);
|
||||
if let Some(show) = self.show.filter(|_| shown > 0.01) {
|
||||
bubble(ui, t, r.id, pos2(x, rect.top()), &show(v), shown, up);
|
||||
}
|
||||
};
|
||||
if let Some((x, f, r, v)) = low {
|
||||
one(x, f, r, v);
|
||||
}
|
||||
one(hx, high.1, high.2, value);
|
||||
if waiting(ui.ctx(), id, self.busy) {
|
||||
spinner(p, pos2(rect.right() - TRACK / 2.0, mid), TRACK - 2.0, t.on_secondary_container);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Two handles, `low` never above `high`. True when one of them changed.
|
||||
pub fn range(ui: &mut Ui, t: &Theme, slider: Slider, low: &mut f64, high: &mut f64) -> bool {
|
||||
let (rect, whole) = allocate(ui, slider.width);
|
||||
let mid = (place(rect, &slider.range, *low) + place(rect, &slider.range, *high)) / 2.0;
|
||||
let (lid, hid) = (whole.id.with("low"), whole.id.with("high"));
|
||||
// The half nearer to a handle is its own, unless the pointer already holds one.
|
||||
let split = ui.data(|d| d.get_temp::<f32>(whole.id)).filter(|_| ui.ctx().is_being_dragged(lid) || ui.ctx().is_being_dragged(hid)).unwrap_or(mid);
|
||||
ui.data_mut(|d| d.insert_temp(whole.id, split));
|
||||
let left = Rect::from_min_max(rect.min, pos2(split, rect.max.y));
|
||||
let right = Rect::from_min_max(pos2(split, rect.min.y), rect.max);
|
||||
let a = slider.handle(ui, lid, rect, left, low);
|
||||
*low = low.min(*high);
|
||||
let b = slider.handle(ui, hid, rect, right, high);
|
||||
*high = high.max(*low);
|
||||
let (fa, fb) = (feel(&a, slider.live()), feel(&b, slider.live()));
|
||||
let (xa, xb) = (place(rect, &slider.range, *low), place(rect, &slider.range, *high));
|
||||
slider.paint(ui, t, rect, whole.id, Some((xa, fa, &a, *low)), (xb, fb, &b), *high);
|
||||
a.changed() || b.changed()
|
||||
}
|
||||
|
||||
fn allocate(ui: &mut Ui, width: Option<f32>) -> (Rect, Response) {
|
||||
let w = width.unwrap_or(ui.available_width()).max(tokens::size::LARGE);
|
||||
ui.allocate_exact_size(vec2(w, tokens::size::CONTROL), Sense::hover())
|
||||
}
|
||||
|
||||
fn place(rect: Rect, range: &RangeInclusive<f64>, v: f64) -> f32 {
|
||||
let span = (range.end() - range.start()).max(f64::MIN_POSITIVE);
|
||||
let part = ((v - range.start()) / span).clamp(0.0, 1.0) as f32;
|
||||
lerp(rect.left() + HANDLE / 2.0, rect.right() - HANDLE / 2.0, part)
|
||||
}
|
||||
|
||||
fn value_at(rect: Rect, range: &RangeInclusive<f64>, x: f32) -> f64 {
|
||||
let part = ((x - rect.left() - HANDLE / 2.0) / (rect.width() - HANDLE)).clamp(0.0, 1.0);
|
||||
range.start() + (range.end() - range.start()) * part as f64
|
||||
}
|
||||
|
||||
fn bubble(ui: &Ui, t: &Theme, id: Id, at: Pos2, what: &str, shown: f32, up: f32) {
|
||||
let layer = eframe::egui::LayerId::new(eframe::egui::Order::Tooltip, id.with("bubble"));
|
||||
let mut p = ui.ctx().layer_painter(layer);
|
||||
p.multiply_opacity(shown.clamp(0.0, 1.0));
|
||||
let font = fonts::med(text::LABEL);
|
||||
let size = vec2(text_width(&p, what, font.clone()) + 2.0 * space::M, tokens::size::HIT);
|
||||
let window = ui.ctx().content_rect().shrink(space::XS);
|
||||
let mut r = Rect::from_center_size(at - vec2(0.0, size.y / 2.0 + space::S * up), size);
|
||||
let into = vec2((window.left() - r.left()).max(0.0) - (r.right() - window.right()).max(0.0), (window.top() - r.top()).max(0.0));
|
||||
r = r.translate(into);
|
||||
p.rect_filled(r, cr(radius::FULL.min(size.y / 2.0)), t.inverse_surface);
|
||||
super::centered(&p, r, line(&p, what, font, t.inverse_on_surface, size.x));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn places_and_values_match_and_stay_inside() {
|
||||
let rect = Rect::from_min_size(pos2(10.0, 0.0), vec2(204.0, 40.0));
|
||||
let range = 0.0..=100.0;
|
||||
for v in [0.0, 12.5, 50.0, 100.0] {
|
||||
assert!((value_at(rect, &range, place(rect, &range, v)) - v).abs() < 0.01);
|
||||
}
|
||||
assert_eq!((value_at(rect, &range, -50.0), value_at(rect, &range, 900.0)), (0.0, 100.0));
|
||||
assert_eq!(place(rect, &(5.0..=5.0), 5.0), 12.0);
|
||||
let s = Slider::new("", 0.0..=10.0, 4.0);
|
||||
assert_eq!((s.snap(5.0), s.snap(9.9), s.snap(-3.0)), (4.0, 8.0, 0.0));
|
||||
}
|
||||
}
|
||||
|
|
@ -12,12 +12,24 @@ use medlar_app::desktop::Sources;
|
|||
use medlar_app::motion::spring;
|
||||
use medlar_app::theme::{alpha, mix};
|
||||
use medlar_app::tokens::{self, radius, space, text};
|
||||
use medlar_app::ui::gallery;
|
||||
use medlar_app::{fonts, icons};
|
||||
use medlar_core::settings::{Appearance, Settings};
|
||||
|
||||
type Scene = (&'static str, fn(&mut App, &mut Ui));
|
||||
|
||||
const SCENES: &[Scene] = &[("window", App::show), ("tokens", |app, ui| app.frame(ui, sheet))];
|
||||
const SCENES: &[Scene] = &[("window", App::show), ("tokens", |app, ui| app.frame(ui, sheet)),
|
||||
("buttons", |app, ui| app.frame(ui, |app, ui| gallery::page(app, ui, 0))),
|
||||
("fields", |app, ui| app.frame(ui, |app, ui| gallery::page(app, ui, 1))),
|
||||
("choices", |app, ui| app.frame(ui, |app, ui| gallery::page(app, ui, 2))),
|
||||
("over", |app, ui| app.frame(ui, |app, ui| gallery::page(app, ui, 3))),
|
||||
("menu", |app, ui| over(app, ui, "menu")),
|
||||
("dialog", |app, ui| over(app, ui, "dialog")),
|
||||
("confirm", |app, ui| over(app, ui, "confirm")),
|
||||
("sheet", |app, ui| over(app, ui, "sheet")),
|
||||
("fab", |app, ui| over(app, ui, "fab")),
|
||||
("toasts", |app, ui| over(app, ui, "toasts")),
|
||||
];
|
||||
|
||||
fn pair(s: &str, sep: char) -> Option<(f32, f32)> {
|
||||
let (a, b) = s.split_once(sep)?;
|
||||
|
|
@ -79,6 +91,11 @@ fn shots() {
|
|||
}
|
||||
}
|
||||
|
||||
fn over(app: &mut App, ui: &mut Ui, what: &str) {
|
||||
gallery::open(ui, what);
|
||||
app.frame(ui, |app, ui| gallery::page(app, ui, 3));
|
||||
}
|
||||
|
||||
/// Roles, type, icons, shapes and one control that answers the pointer.
|
||||
fn sheet(app: &mut App, ui: &mut Ui) {
|
||||
let t = app.theme.clone();
|
||||
|
|
|
|||
697
crates/app/tests/widgets.rs
Normal file
697
crates/app/tests/widgets.rs
Normal file
|
|
@ -0,0 +1,697 @@
|
|||
//! Controls answer the pointer and the keyboard, popups stay in the window, dialogs hold and return the focus.
|
||||
|
||||
use eframe::egui::accesskit::Role;
|
||||
use eframe::egui::{Event, Id, Key, Modifiers, PointerButton, Pos2, Rect, Ui, pos2, vec2};
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::{NodeT, Queryable};
|
||||
use medlar_app::app::App;
|
||||
use medlar_app::desktop::Sources;
|
||||
use medlar_app::theme::Theme;
|
||||
use medlar_app::ui::dialog::{Answer, Dialog, sheet};
|
||||
use medlar_app::ui::field::{Combo, Field, Number, search};
|
||||
use medlar_app::ui::menu::{self, Item};
|
||||
use medlar_app::ui::toast::Toasts;
|
||||
use medlar_app::ui::widgets::{Button, Chip, Choice, Slider, fab_menu, group, range, segmented, split};
|
||||
use medlar_core::settings::{Motion, Settings};
|
||||
|
||||
/// What a test changes and looks at.
|
||||
struct S {
|
||||
app: Option<App>,
|
||||
motion: Motion,
|
||||
open: bool,
|
||||
flag: bool,
|
||||
n: usize,
|
||||
value: f64,
|
||||
other: f64,
|
||||
text: String,
|
||||
said: Vec<String>,
|
||||
rects: Vec<Rect>,
|
||||
toasts: Toasts<&'static str>,
|
||||
}
|
||||
|
||||
type H = Harness<'static, S>;
|
||||
|
||||
fn harness(draw: impl Fn(&mut Ui, &Theme, &mut S) + 'static) -> H {
|
||||
let state = S {
|
||||
app: None,
|
||||
motion: Motion::Normal,
|
||||
open: false,
|
||||
flag: false,
|
||||
n: 0,
|
||||
value: 50.0,
|
||||
other: 80.0,
|
||||
text: String::new(),
|
||||
said: vec![],
|
||||
rects: vec![],
|
||||
toasts: Toasts::default(),
|
||||
};
|
||||
let frame = move |ui: &mut Ui, s: &mut S| {
|
||||
let nowhere = Sources { caelestia: "/nonexistent".into(), kde: "/nonexistent".into() };
|
||||
let Some(mut app) = s.app.take() else {
|
||||
s.app = Some(App::new(ui.ctx(), Settings::default(), nowhere));
|
||||
ui.ctx().request_repaint();
|
||||
return;
|
||||
};
|
||||
app.settings.motion = s.motion;
|
||||
app.frame(ui, |app, ui| {
|
||||
s.rects.clear();
|
||||
draw(ui, &app.theme.clone(), s);
|
||||
});
|
||||
s.app = Some(app);
|
||||
};
|
||||
let mut h = Harness::builder().with_size(vec2(480.0, 360.0)).with_step_dt(1.0 / 60.0).build_ui_state(frame, state);
|
||||
steps(&mut h, 10);
|
||||
h
|
||||
}
|
||||
|
||||
fn steps(h: &mut H, n: usize) {
|
||||
for _ in 0..n {
|
||||
h.step();
|
||||
}
|
||||
}
|
||||
|
||||
fn move_to(h: &mut H, at: Pos2) {
|
||||
h.input_mut().events.push(Event::PointerMoved(at));
|
||||
h.step();
|
||||
}
|
||||
|
||||
fn button(h: &mut H, at: Pos2, button: PointerButton, pressed: bool) {
|
||||
h.input_mut().events.push(Event::PointerButton { pos: at, button, pressed, modifiers: Modifiers::NONE });
|
||||
h.step();
|
||||
}
|
||||
|
||||
fn click(h: &mut H, at: Pos2) {
|
||||
move_to(h, at);
|
||||
button(h, at, PointerButton::Primary, true);
|
||||
button(h, at, PointerButton::Primary, false);
|
||||
steps(h, 40);
|
||||
}
|
||||
|
||||
fn press(h: &mut H, key: Key) {
|
||||
with(h, Modifiers::NONE, key);
|
||||
}
|
||||
|
||||
fn with(h: &mut H, modifiers: Modifiers, key: Key) {
|
||||
for pressed in [true, false] {
|
||||
h.input_mut().events.push(Event::ModifiersChanged(modifiers));
|
||||
h.input_mut().events.push(Event::Key { key, physical_key: None, pressed, repeat: false, modifiers });
|
||||
h.step();
|
||||
}
|
||||
h.input_mut().events.push(Event::ModifiersChanged(Modifiers::NONE));
|
||||
steps(h, 40);
|
||||
}
|
||||
|
||||
fn type_text(h: &mut H, text: &str) {
|
||||
h.input_mut().events.push(Event::Text(text.into()));
|
||||
steps(h, 3);
|
||||
}
|
||||
|
||||
fn rect(h: &H, label: &str) -> Rect {
|
||||
// The words above a field have its name too; the control comes after them.
|
||||
h.get_all_by_label(label).last().unwrap().rect()
|
||||
}
|
||||
|
||||
fn at(h: &H, label: &str) -> Pos2 {
|
||||
rect(h, label).center()
|
||||
}
|
||||
|
||||
fn focused(h: &H) -> Option<String> {
|
||||
h.query_all(egui_kittest::kittest::By::new().predicate(|n| n.is_focused())).next().and_then(|n| n.accesskit_node().label())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hover_and_press_tint_squeeze_and_go_back_even_when_the_pointer_left() {
|
||||
use medlar_app::ui::widgets::feel;
|
||||
let mut h = harness(|ui, t, s| {
|
||||
let r = Button::new("Go").show(ui, t);
|
||||
let f = feel(&r, true);
|
||||
(s.value, s.other) = (f.tint as f64, f.press as f64);
|
||||
if r.clicked() {
|
||||
s.n += 1;
|
||||
}
|
||||
});
|
||||
let mid = at(&h, "Go");
|
||||
move_to(&mut h, mid);
|
||||
assert!(h.state().value < 0.08, "eased in, not there at once");
|
||||
steps(&mut h, 30);
|
||||
assert!((h.state().value - 0.08).abs() < 0.001);
|
||||
button(&mut h, mid, PointerButton::Primary, true);
|
||||
steps(&mut h, 30);
|
||||
assert!((h.state().value - 0.12).abs() < 0.001 && (h.state().other - 1.0).abs() < 0.01);
|
||||
move_to(&mut h, pos2(400.0, 300.0));
|
||||
button(&mut h, pos2(400.0, 300.0), PointerButton::Primary, false);
|
||||
steps(&mut h, 60);
|
||||
assert_eq!((h.state().value, h.state().other, h.state().n), (0.0, 0.0, 0));
|
||||
assert!(!h.ctx.has_requested_repaint(), "idle");
|
||||
click(&mut h, mid);
|
||||
assert_eq!(h.state().n, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_and_busy_buttons_do_nothing_and_keep_their_place() {
|
||||
let mut h = harness(|ui, t, s| {
|
||||
let r = Button::new("Save file").enabled(!s.flag).busy(s.open).show(ui, t);
|
||||
s.rects.push(r.rect);
|
||||
s.n += usize::from(r.clicked());
|
||||
});
|
||||
let before = h.state().rects[0];
|
||||
for (disabled, busy) in [(true, false), (false, true)] {
|
||||
(h.state_mut().flag, h.state_mut().open) = (disabled, busy);
|
||||
steps(&mut h, 60);
|
||||
let mid = at(&h, "Save file");
|
||||
click(&mut h, mid);
|
||||
press(&mut h, Key::Tab);
|
||||
press(&mut h, Key::Enter);
|
||||
assert_eq!((h.state().n, h.state().rects[0]), (0, before));
|
||||
assert!(h.get_by_label("Save file").accesskit_node().is_disabled());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loading_shows_after_300_ms_and_not_before() {
|
||||
use medlar_app::ui::widgets::waiting;
|
||||
let mut h = harness(|ui, _, s| s.flag = waiting(ui.ctx(), Id::unique("wait"), s.open));
|
||||
h.state_mut().open = true;
|
||||
steps(&mut h, 17);
|
||||
assert!(!h.state().flag);
|
||||
steps(&mut h, 4);
|
||||
assert!(h.state().flag);
|
||||
h.state_mut().open = false;
|
||||
h.step();
|
||||
assert!(!h.state().flag);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_control_is_reached_and_used_with_the_keyboard() {
|
||||
let mut h = harness(|ui, t, s| {
|
||||
s.n += usize::from(Button::icon("pause", "Pause").show(ui, t).clicked());
|
||||
Choice::new("Night").switch(ui, t, &mut s.flag);
|
||||
Choice::new("Some").mixed(!s.open).checkbox(ui, t, &mut s.open);
|
||||
if Chip::new("Video").filter(s.text == "v").show(ui, t).response.clicked() {
|
||||
s.text = "v".into();
|
||||
}
|
||||
Slider::new("Limit", 0.0..=100.0, 5.0).width(200.0).show(ui, t, &mut s.value);
|
||||
});
|
||||
press(&mut h, Key::Tab);
|
||||
assert_eq!(focused(&h).as_deref(), Some("Pause"));
|
||||
press(&mut h, Key::Space);
|
||||
press(&mut h, Key::Tab);
|
||||
press(&mut h, Key::Enter);
|
||||
press(&mut h, Key::Tab);
|
||||
press(&mut h, Key::Space);
|
||||
press(&mut h, Key::Tab);
|
||||
press(&mut h, Key::Space);
|
||||
assert_eq!((h.state().n, h.state().flag, h.state().open, h.state().text.as_str()), (1, true, true, "v"));
|
||||
press(&mut h, Key::Tab);
|
||||
press(&mut h, Key::ArrowRight);
|
||||
press(&mut h, Key::ArrowUp);
|
||||
assert_eq!((h.state().value, focused(&h).as_deref()), (60.0, Some("Limit")), "arrows move the value, not the focus");
|
||||
press(&mut h, Key::End);
|
||||
press(&mut h, Key::ArrowRight);
|
||||
assert_eq!(h.state().value, 100.0);
|
||||
press(&mut h, Key::Home);
|
||||
assert_eq!(h.state().value, 0.0);
|
||||
with(&mut h, Modifiers::SHIFT, Key::Tab);
|
||||
assert_eq!(focused(&h).as_deref(), Some("Video"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_grabbed_point_of_a_slider_stays_under_the_pointer() {
|
||||
let mut h = harness(|ui, t, s| {
|
||||
s.rects.push(Slider::new("Limit", 0.0..=100.0, 0.0).width(204.0).show(ui, t, &mut s.value).rect);
|
||||
});
|
||||
let r = h.state().rects[0];
|
||||
let handle = pos2(r.left() + 102.0, r.center().y);
|
||||
let grab = handle + vec2(8.0, 0.0);
|
||||
move_to(&mut h, grab);
|
||||
button(&mut h, grab, PointerButton::Primary, true);
|
||||
steps(&mut h, 3);
|
||||
assert_eq!(h.state().value, 50.0, "a press on the handle doesn't move it");
|
||||
move_to(&mut h, grab + vec2(20.0, 0.0));
|
||||
move_to(&mut h, grab + vec2(40.0, 0.0));
|
||||
assert!((h.state().value - 70.0).abs() < 0.01, "{}", h.state().value);
|
||||
button(&mut h, grab + vec2(40.0, 0.0), PointerButton::Primary, false);
|
||||
steps(&mut h, 20);
|
||||
click(&mut h, pos2(r.left() + 22.0, r.center().y));
|
||||
assert!((h.state().value - 10.0).abs() < 0.01, "a click on the bar goes there: {}", h.state().value);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_handles_of_a_range_never_cross() {
|
||||
let mut h = harness(|ui, t, s| {
|
||||
let slider = Slider::new("Hours", 0.0..=100.0, 1.0).width(204.0);
|
||||
s.rects.push(Rect::from_min_size(ui.cursor().min, vec2(204.0, 40.0)));
|
||||
range(ui, t, slider, &mut s.value, &mut s.other);
|
||||
});
|
||||
let r = h.state().rects[0];
|
||||
let low = pos2(r.left() + 102.0, r.center().y);
|
||||
move_to(&mut h, low);
|
||||
button(&mut h, low, PointerButton::Primary, true);
|
||||
for x in [120.0, 160.0, 200.0, 400.0] {
|
||||
move_to(&mut h, pos2(r.left() + x, r.center().y));
|
||||
}
|
||||
assert_eq!((h.state().value, h.state().other), (80.0, 80.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pressed_button_of_a_group_grows_and_the_whole_keeps_its_width() {
|
||||
let mut h = harness(|ui, t, s| {
|
||||
ui.horizontal(|ui| {
|
||||
group(ui, t, "Show", &[("", "All"), ("", "Loading"), ("", "Done")], &mut s.n);
|
||||
s.rects.push(Button::new("Next").show(ui, t).rect);
|
||||
});
|
||||
});
|
||||
let next = h.state().rects[0];
|
||||
let mid = at(&h, "Loading");
|
||||
move_to(&mut h, mid);
|
||||
button(&mut h, mid, PointerButton::Primary, true);
|
||||
for _ in 0..20 {
|
||||
h.step();
|
||||
assert_eq!(h.state().rects[0], next, "what is beside the group stays");
|
||||
}
|
||||
button(&mut h, mid, PointerButton::Primary, false);
|
||||
assert_eq!(h.state().n, 1);
|
||||
let mut h = harness(|ui, t, s| {
|
||||
segmented(ui, t, "Look", &[("", "Light"), ("", "Dark")], &mut s.n);
|
||||
});
|
||||
let dark = at(&h, "Dark");
|
||||
click(&mut h, dark);
|
||||
assert_eq!(h.state().n, 1);
|
||||
}
|
||||
|
||||
fn items() -> Vec<Item<&'static str>> {
|
||||
let many = (0..40).map(|i| Item::new(format!("Queue {i}"), "queue")).collect();
|
||||
vec![
|
||||
Item::new("Off", "off").enabled(false),
|
||||
Item::new("Open", "open").keys("Enter"),
|
||||
Item::line(),
|
||||
Item::sub("Priority", vec![Item::new("High", "high"), Item::new("Low", "low")]),
|
||||
Item::sub("Move to", many),
|
||||
Item::new("Remove", "remove").danger(),
|
||||
]
|
||||
}
|
||||
|
||||
fn menu_harness(place: Pos2) -> H {
|
||||
harness(move |ui, t, s| {
|
||||
let at = Rect::from_min_size(place, vec2(80.0, 40.0));
|
||||
let r = ui.scope_builder(eframe::egui::UiBuilder::new().max_rect(at), |ui| Button::new("Menu").width(80.0).show(ui, t)).inner;
|
||||
if let Some(a) = menu::below(ui, t, &r, items).or_else(|| menu::context(ui, t, &r, items)) {
|
||||
s.said.push(a.into());
|
||||
}
|
||||
s.flag = menu::any_open(ui.ctx());
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn menus_and_submenus_stay_inside_the_window() {
|
||||
for place in [pos2(0.0, 0.0), pos2(400.0, 0.0), pos2(0.0, 320.0), pos2(400.0, 320.0), pos2(200.0, 160.0)] {
|
||||
let mut h = menu_harness(place);
|
||||
click(&mut h, place + vec2(40.0, 20.0));
|
||||
assert!(h.state().flag);
|
||||
let move_to_row = at(&h, "Move to");
|
||||
click(&mut h, move_to_row);
|
||||
let window = h.ctx.content_rect();
|
||||
for node in h.query_all_by_role(Role::Menu) {
|
||||
assert!(window.contains_rect(node.rect()), "{place:?}: {:?}", node.rect());
|
||||
}
|
||||
assert_eq!(h.query_all_by_role(Role::Menu).count(), 2);
|
||||
for node in ["Open", "Remove"] {
|
||||
assert!(window.contains_rect(rect(&h, node)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_menu_is_clicked_toggled_and_closed_from_outside() {
|
||||
let mut h = menu_harness(pos2(20.0, 20.0));
|
||||
let open = pos2(60.0, 40.0);
|
||||
click(&mut h, open);
|
||||
assert!(h.query_by_label("Open").is_some());
|
||||
click(&mut h, open);
|
||||
assert!(h.query_by_label("Open").is_none(), "the button closes it again");
|
||||
click(&mut h, open);
|
||||
let off = at(&h, "Off");
|
||||
click(&mut h, off);
|
||||
assert!(h.state().flag && h.state().said.is_empty(), "a disabled row does nothing");
|
||||
let row = at(&h, "Open");
|
||||
click(&mut h, row);
|
||||
assert!(!h.state().flag && h.state().said == ["open"]);
|
||||
click(&mut h, open);
|
||||
click(&mut h, pos2(470.0, 350.0));
|
||||
assert!(!h.state().flag);
|
||||
move_to(&mut h, open);
|
||||
button(&mut h, open, PointerButton::Secondary, true);
|
||||
button(&mut h, open, PointerButton::Secondary, false);
|
||||
steps(&mut h, 30);
|
||||
assert!(h.state().flag, "a right click opens the context menu");
|
||||
let menu = h.get_by_role(Role::Menu).rect();
|
||||
assert!((menu.min - open).length() < 12.0, "at the pointer: {menu:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_submenu_opens_by_resting_on_its_row_and_survives_a_diagonal() {
|
||||
let mut h = menu_harness(pos2(20.0, 20.0));
|
||||
click(&mut h, pos2(60.0, 40.0));
|
||||
let row = at(&h, "Priority");
|
||||
move_to(&mut h, row);
|
||||
steps(&mut h, 4);
|
||||
assert!(h.query_by_label("High").is_none(), "not at once");
|
||||
steps(&mut h, 30);
|
||||
let low = at(&h, "Low");
|
||||
// Over the row below for a moment, on the way to the submenu.
|
||||
let below = at(&h, "Move to");
|
||||
move_to(&mut h, below);
|
||||
steps(&mut h, 3);
|
||||
move_to(&mut h, low);
|
||||
steps(&mut h, 30);
|
||||
click(&mut h, low);
|
||||
assert_eq!(h.state().said, ["low"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_menu_is_used_with_the_keyboard_alone_and_gives_the_focus_back() {
|
||||
let mut h = menu_harness(pos2(20.0, 20.0));
|
||||
press(&mut h, Key::Tab);
|
||||
press(&mut h, Key::Enter);
|
||||
assert!(h.state().flag && h.state().said.is_empty(), "the key that opens it chooses nothing");
|
||||
press(&mut h, Key::ArrowDown);
|
||||
press(&mut h, Key::ArrowRight);
|
||||
assert!(h.query_by_label("High").is_some());
|
||||
press(&mut h, Key::ArrowLeft);
|
||||
assert!(h.query_by_label("High").is_none());
|
||||
press(&mut h, Key::ArrowRight);
|
||||
press(&mut h, Key::ArrowDown);
|
||||
press(&mut h, Key::Enter);
|
||||
assert_eq!(h.state().said, ["low"]);
|
||||
assert!(!h.state().flag);
|
||||
assert_eq!(focused(&h).as_deref(), Some("Menu"));
|
||||
press(&mut h, Key::Space);
|
||||
type_text(&mut h, "r");
|
||||
press(&mut h, Key::Enter);
|
||||
assert_eq!(h.state().said, ["low", "remove"], "a letter goes to its row");
|
||||
with(&mut h, Modifiers::SHIFT, Key::F10);
|
||||
assert!(h.state().flag);
|
||||
press(&mut h, Key::ArrowUp);
|
||||
press(&mut h, Key::Escape);
|
||||
assert!(!h.state().flag);
|
||||
assert_eq!(focused(&h).as_deref(), Some("Menu"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_combo_and_a_split_button_choose() {
|
||||
let mut h = harness(|ui, t, s| {
|
||||
let options = ["One", "Two", "Three"].map(String::from);
|
||||
Combo::new("Queue", &options, 200.0).show(ui, t, &mut s.n);
|
||||
let (main, more) = split(ui, t, "download", "Download", "More", false);
|
||||
if main.clicked() {
|
||||
s.said.push("main".into());
|
||||
}
|
||||
if let Some(a) = menu::below(ui, t, &more, || vec![Item::new("Later", "later")]) {
|
||||
s.said.push(a.into());
|
||||
}
|
||||
});
|
||||
press(&mut h, Key::Tab);
|
||||
press(&mut h, Key::ArrowDown);
|
||||
press(&mut h, Key::ArrowDown);
|
||||
press(&mut h, Key::Enter);
|
||||
assert_eq!(h.state().n, 1);
|
||||
let main = at(&h, "Download");
|
||||
click(&mut h, main);
|
||||
let more = at(&h, "More");
|
||||
click(&mut h, more);
|
||||
let later = at(&h, "Later");
|
||||
click(&mut h, later);
|
||||
assert_eq!(h.state().said, ["main", "later"]);
|
||||
}
|
||||
|
||||
fn dialog_harness() -> H {
|
||||
harness(|ui, t, s| {
|
||||
s.n += usize::from(Button::new("Behind").show(ui, t).clicked());
|
||||
if Button::new("Open").show(ui, t).clicked() {
|
||||
s.open = true;
|
||||
}
|
||||
let d = Dialog::new("test", "Add a download", "Download");
|
||||
let answer = d.show(ui.ctx(), t, s.open, |ui| {
|
||||
Field::new("Link").clear().show(ui, t, &mut s.text);
|
||||
let options = ["One", "Two"].map(String::from);
|
||||
Combo::new("Queue", &options, 200.0).show(ui, t, &mut s.rects.len().min(0));
|
||||
});
|
||||
if let Some(a) = answer {
|
||||
s.open = false;
|
||||
s.said.push(format!("{a:?}"));
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dialog_traps_the_focus_and_gives_it_back() {
|
||||
let mut h = dialog_harness();
|
||||
press(&mut h, Key::Tab);
|
||||
press(&mut h, Key::Tab);
|
||||
assert_eq!(focused(&h).as_deref(), Some("Open"));
|
||||
press(&mut h, Key::Enter);
|
||||
assert!(h.state().open && h.state().said.is_empty(), "the key that opens it answers nothing");
|
||||
assert_eq!(focused(&h).as_deref(), Some("Link"));
|
||||
let mut seen = vec![];
|
||||
for _ in 0..5 {
|
||||
seen.push(focused(&h).unwrap_or_default());
|
||||
press(&mut h, Key::Tab);
|
||||
}
|
||||
assert_eq!(seen, ["Link", "Queue", "Download", "Cancel", "Link"]);
|
||||
for key in [Key::ArrowUp, Key::ArrowUp, Key::ArrowLeft, Key::ArrowUp, Key::ArrowDown] {
|
||||
press(&mut h, key);
|
||||
assert!(!["Behind", "Open"].contains(&focused(&h).unwrap_or_default().as_str()), "{key:?} left the dialog");
|
||||
if h.query_by_label("Two").is_some() {
|
||||
press(&mut h, Key::Escape);
|
||||
}
|
||||
}
|
||||
assert!(h.state().open);
|
||||
press(&mut h, Key::Escape);
|
||||
assert_eq!(h.state().said, ["Cancel"]);
|
||||
assert_eq!(focused(&h).as_deref(), Some("Open"));
|
||||
assert!(h.query_by_label("Link").is_none(), "gone");
|
||||
assert!(!h.ctx.has_requested_repaint(), "idle");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enter_does_the_main_action_unless_a_button_has_it() {
|
||||
let mut h = dialog_harness();
|
||||
let open = at(&h, "Open");
|
||||
click(&mut h, open);
|
||||
type_text(&mut h, "https://example.org/a");
|
||||
press(&mut h, Key::Enter);
|
||||
assert_eq!((h.state().said.as_slice(), h.state().text.as_str()), (["Main".to_string()].as_slice(), "https://example.org/a"));
|
||||
click(&mut h, open);
|
||||
with(&mut h, Modifiers::SHIFT, Key::Tab);
|
||||
assert_eq!(focused(&h).as_deref(), Some("Cancel"));
|
||||
press(&mut h, Key::Enter);
|
||||
assert_eq!(h.state().said, ["Main", "Cancel"]);
|
||||
// Escape closes the list of a combo first, then the dialog.
|
||||
click(&mut h, open);
|
||||
let queue = at(&h, "Queue");
|
||||
click(&mut h, queue);
|
||||
assert!(h.query_by_label("Two").is_some());
|
||||
press(&mut h, Key::Escape);
|
||||
assert!(h.state().open && h.query_by_label("Two").is_none());
|
||||
press(&mut h, Key::Escape);
|
||||
assert!(!h.state().open);
|
||||
assert_eq!(h.state().n, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_is_behind_a_dialog_cannot_be_clicked_and_the_dialog_fits() {
|
||||
let mut h = dialog_harness();
|
||||
let (open, behind) = (at(&h, "Open"), at(&h, "Behind"));
|
||||
click(&mut h, open);
|
||||
click(&mut h, behind);
|
||||
assert!(h.state().n == 0 && h.state().open, "a click beside it loses nothing");
|
||||
let window = h.ctx.content_rect();
|
||||
for label in ["Link", "Queue", "Cancel", "Download"] {
|
||||
assert!(window.contains_rect(rect(&h, label)), "{label}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dangerous_question_starts_on_cancel() {
|
||||
let mut h = harness(|ui, t, s| {
|
||||
let d = Dialog::confirm("ask", "Delete the file?", "It can't be taken back.", "Delete", true);
|
||||
if let Some(a) = d.show(ui.ctx(), t, s.open, |_| {}) {
|
||||
s.open = false;
|
||||
s.said.push(format!("{a:?}"));
|
||||
}
|
||||
});
|
||||
h.state_mut().open = true;
|
||||
steps(&mut h, 40);
|
||||
assert_eq!(focused(&h).as_deref(), Some("Cancel"));
|
||||
press(&mut h, Key::Enter);
|
||||
assert_eq!(h.state().said, [format!("{:?}", Answer::Cancel)]);
|
||||
h.state_mut().open = true;
|
||||
steps(&mut h, 40);
|
||||
let delete = at(&h, "Delete");
|
||||
click(&mut h, delete);
|
||||
assert_eq!(h.state().said, ["Cancel", "Main"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dialog_works_with_motion_off() {
|
||||
let mut h = dialog_harness();
|
||||
h.state_mut().motion = Motion::Off;
|
||||
let open = at(&h, "Open");
|
||||
click(&mut h, open);
|
||||
assert_eq!(focused(&h).as_deref(), Some("Link"));
|
||||
press(&mut h, Key::Escape);
|
||||
assert!(h.query_by_label("Link").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sheet_closes_by_button_escape_and_scrim() {
|
||||
let mut h = harness(|ui, t, s| {
|
||||
if sheet(ui.ctx(), t, "test", "Details", s.open, |ui| {
|
||||
Field::new("Name").show(ui, t, &mut s.text);
|
||||
}) {
|
||||
s.open = false;
|
||||
s.n += 1;
|
||||
}
|
||||
});
|
||||
for i in 0..3 {
|
||||
h.state_mut().open = true;
|
||||
steps(&mut h, 60);
|
||||
assert_eq!(focused(&h).as_deref(), Some("Name"));
|
||||
assert!(h.ctx.content_rect().contains_rect(rect(&h, "Close")));
|
||||
match i {
|
||||
0 => press(&mut h, Key::Escape),
|
||||
1 => click(&mut h, pos2(20.0, 180.0)),
|
||||
_ => {
|
||||
let close = at(&h, "Close");
|
||||
click(&mut h, close);
|
||||
}
|
||||
}
|
||||
assert!(!h.state().open && h.state().n == i + 1, "way {i}");
|
||||
steps(&mut h, 60);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fields_clear_step_and_refuse() {
|
||||
let mut h = harness(|ui, t, s| {
|
||||
search(ui, t, "Search", &mut s.text, 200.0);
|
||||
Number { label: "Limit", unit: "KB/s", range: 0.0..=100.0, step: 10.0, enabled: true, width: 240.0 }.show(ui, t, &mut s.value);
|
||||
});
|
||||
press(&mut h, Key::Tab);
|
||||
type_text(&mut h, "iso");
|
||||
assert_eq!(h.state().text, "iso");
|
||||
press(&mut h, Key::Escape);
|
||||
assert_eq!((h.state().text.as_str(), focused(&h).as_deref()), ("", Some("Search")));
|
||||
type_text(&mut h, "deb");
|
||||
let clear = at(&h, "Clear");
|
||||
click(&mut h, clear);
|
||||
assert_eq!((h.state().text.as_str(), focused(&h).as_deref()), ("", Some("Search")));
|
||||
let more = at(&h, "More");
|
||||
click(&mut h, more);
|
||||
assert_eq!(h.state().value, 60.0);
|
||||
let limit = at(&h, "Limit");
|
||||
click(&mut h, limit);
|
||||
press(&mut h, Key::ArrowDown);
|
||||
assert_eq!(h.state().value, 50.0);
|
||||
let height = rect(&h, "Limit");
|
||||
with(&mut h, Modifiers::COMMAND, Key::A);
|
||||
type_text(&mut h, "900");
|
||||
assert_eq!(h.state().value, 50.0, "out of range is not taken");
|
||||
assert!(h.query_by_label("From 0 to 100").is_some());
|
||||
assert_eq!(rect(&h, "Limit"), height, "the error moves nothing");
|
||||
press(&mut h, Key::Tab);
|
||||
assert!(h.query_by_label("From 0 to 100").is_none(), "and dropped when the field is left");
|
||||
click(&mut h, limit);
|
||||
with(&mut h, Modifiers::COMMAND, Key::A);
|
||||
type_text(&mut h, "12,5");
|
||||
assert_eq!(h.state().value, 12.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toasts_stack_wait_under_the_pointer_and_undo() {
|
||||
let mut h = harness(|ui, t, s| {
|
||||
if let Some(a) = s.toasts.show(ui.ctx(), t, 360.0) {
|
||||
s.said.push(a.into());
|
||||
}
|
||||
});
|
||||
h.state_mut().toasts.info("info", "First");
|
||||
h.state_mut().toasts.undo("delete", "Second", "undo");
|
||||
steps(&mut h, 60);
|
||||
let (first, second) = (rect(&h, "First"), rect(&h, "Second"));
|
||||
assert!(first.bottom() < second.top() && h.ctx.content_rect().contains_rect(second));
|
||||
move_to(&mut h, second.center());
|
||||
steps(&mut h, 60 * 8);
|
||||
assert!(h.query_by_label("First").is_some(), "they wait while the pointer is there");
|
||||
move_to(&mut h, pos2(5.0, 5.0));
|
||||
steps(&mut h, 60 * 5);
|
||||
assert!(h.query_by_label("First").is_none() && h.query_by_label("Second").is_some());
|
||||
let undo = at(&h, "Undo");
|
||||
click(&mut h, undo);
|
||||
assert_eq!(h.state().said, ["undo"]);
|
||||
steps(&mut h, 60);
|
||||
assert!(h.state().toasts.is_empty() && !h.ctx.has_requested_repaint());
|
||||
for i in 0..7 {
|
||||
h.state_mut().toasts.info("info", format!("Toast {i}"));
|
||||
}
|
||||
steps(&mut h, 60);
|
||||
assert!(h.query_by_label("Toast 2").is_none() && h.query_by_label("Toast 3").is_some(), "four at most");
|
||||
assert!(rect(&h, "Toast 3").top() > 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fab_menu_opens_chooses_and_closes() {
|
||||
let mut h = harness(|ui, t, s| {
|
||||
let items = [("link", "From a link"), ("file_open", "From a file")];
|
||||
if let Some(i) = fab_menu(ui.ctx(), t, Id::unique("fab"), pos2(464.0, 344.0), ("Add", "Close"), &mut s.open, &items) {
|
||||
s.said.push(items[i].1.into());
|
||||
}
|
||||
});
|
||||
let fab = at(&h, "Add");
|
||||
click(&mut h, fab);
|
||||
assert!(h.state().open);
|
||||
let item = at(&h, "From a file");
|
||||
click(&mut h, item);
|
||||
assert!(!h.state().open && h.state().said == ["From a file"]);
|
||||
press(&mut h, Key::Tab);
|
||||
press(&mut h, Key::Enter);
|
||||
assert_eq!(focused(&h).as_deref(), Some("From a link"));
|
||||
press(&mut h, Key::Escape);
|
||||
assert!(!h.state().open);
|
||||
assert_eq!(focused(&h).as_deref(), Some("Add"));
|
||||
click(&mut h, fab);
|
||||
click(&mut h, pos2(20.0, 20.0));
|
||||
assert!(!h.state().open);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tooltip_shows_the_shortcut_and_stays_inside() {
|
||||
let mut h = harness(|ui, t, _| {
|
||||
let at = Rect::from_min_size(pos2(440.0, 320.0), vec2(40.0, 40.0));
|
||||
ui.scope_builder(eframe::egui::UiBuilder::new().max_rect(at), |ui| Button::icon("delete", "Remove from the list").keys("Del").show(ui, t));
|
||||
});
|
||||
move_to(&mut h, pos2(460.0, 340.0));
|
||||
steps(&mut h, 90);
|
||||
let window = h.ctx.content_rect();
|
||||
let tips: Vec<Rect> = h.get_all_by_label("Remove from the list").map(|n| n.rect()).collect();
|
||||
assert_eq!(tips.len(), 2, "the button and its tooltip");
|
||||
assert!(tips.iter().all(|r| window.contains_rect(*r)), "{tips:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_page_of_the_gallery_draws_at_the_smallest_size() {
|
||||
use medlar_app::ui::gallery;
|
||||
for page in 0..gallery::PAGES.len() {
|
||||
let mut app = None;
|
||||
let mut g = Harness::builder().with_size(vec2(480.0, 360.0)).build_ui(move |ui| {
|
||||
let nowhere = Sources { caelestia: "/nonexistent".into(), kde: "/nonexistent".into() };
|
||||
if app.is_none() {
|
||||
app = Some(App::new(ui.ctx(), Settings::default(), nowhere));
|
||||
return;
|
||||
}
|
||||
app.as_mut().unwrap().frame(ui, |app, ui| gallery::page(app, ui, page));
|
||||
});
|
||||
for _ in 0..5 {
|
||||
g.step();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -37,5 +37,17 @@
|
|||
"store.secret": "A login or cookie would have been saved outside the keyring, so nothing was saved.",
|
||||
"store.main_queue": "The main queue can't be removed.",
|
||||
"store.bad_value": "The download list holds a value this version doesn't know: {value}",
|
||||
"store.closed": "The download list stopped working. Start Medlar again."
|
||||
"store.closed": "The download list stopped working. Start Medlar again.",
|
||||
|
||||
"dialog.cancel": "Cancel",
|
||||
"dialog.close": "Close",
|
||||
"toast.undo": "Undo",
|
||||
"toast.close": "Close message",
|
||||
"chip.remove": "Remove {name}",
|
||||
"field.clear": "Clear",
|
||||
"field.show_password": "Show password",
|
||||
"field.hide_password": "Hide password",
|
||||
"number.more": "More",
|
||||
"number.less": "Less",
|
||||
"number.range": "From {from} to {to}"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,3 +21,4 @@
|
|||
- D-017 — 2026-11-24 — HTTP client is reqwest 0.13.5 (pinned exactly), rustls with ring and the system certificates, HTTP/1.1 only, `Accept-Encoding: identity`, no decompression, no Referer of its own, its retries off, ≤ 10 redirects, 20 s connect and 30 s idle timeout, no proxy from the environment. Segments go to the final link; cookies and logins are dropped when its origin differs. — Docs of 0.13.5 checked: `http1_only`, `redirect::Policy`, `connect_timeout`, `read_timeout` (per read), `retry::never`. — 02, 05, 06
|
||||
- D-018 — 2026-11-24 — HTTP/1.1 everywhere; no HTTP/2 or HTTP/3 (1.14), so reqwest's `http2` feature stays off. — Measured over TLS with netem, mean MB/s of HTTP/1.1 ×1, ×4, ×8 and HTTP/2 ×1: loopback 437, 950, 899, 306; 20 ms 8.7, 8.5, 8.9, 8.6; 20 ms with 0.1 % loss (15 runs) 7.6, 6.0, 7.3, 6.6; 50 ms with 0.5 % loss 1.7, 1.8, 3.2, 0.7. HTTP/2 never won. HTTP/3 was not measured: reqwest's needs an unstable build flag and another TLS stack (quinn). — 02
|
||||
- D-019 — 2026-11-24 — A stored part with `end: None` means the server had no ranges: it starts over on resume unless the server has ranges by then. A part with an end never starts over by itself (`Error::NoResume`, `Error::Changed` instead). The record of parts is written only after `fdatasync` of the data it names. — No state loses finished bytes. — 02
|
||||
- D-023 — 2026-11-25 — Menus are Medlar's own (`ui::menu`), not egui's: one open at a time, own keyboard. Dialogs never close by a click on the scrim (the side sheet does); Enter does the main action unless a button has the focus; dangerous questions start on Cancel. Elevated buttons have no shadow. — egui's arrow keys leave its menus; typed links must not be lost. — 03 and later
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue