app: cherry-pick rune's pause and sound fixes onto the checkout
Rune comes from app/vendor/rune now, a checkout of 63ad0209 on branch ported, carrying the four commits of upstream issues 1320 (a pause while a clip is layered holds the layer's picture and time) and 1325 (a video's sound is read ahead of the clock and leads it). Both were written against eb9f1104 and ported across the refactors since. The faults are the first two and the third in docs/rune-upstream.md; the app's workarounds in review.rs stay until the fixes arrive upstream.
This commit is contained in:
1 parent
80fef698ce
commit
5bf262b82b
3795 files changed
+663463
-28
No files matched your search
+21
@@ -0,0 +1,21 @@
|
||||
[package]
|
||||
name = "rune-knobs"
|
||||
version = "0.0.1"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
description = "Live tuning values for Rune apps: knobs in groups, and the ⌘⇧K panel that tunes them."
|
||||
|
||||
[dependencies]
|
||||
rune = { workspace = true }
|
||||
|
||||
[features]
|
||||
# The panel and its live values. Dev builds only: without it, knobs read their defaults.
|
||||
panel = []
|
||||
|
||||
[dev-dependencies]
|
||||
rune = { workspace = true, default-features = true }
|
||||
# The tests drive the panel, so they build with it on.
|
||||
rune-knobs = { path = ".", features = ["panel"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
# rune-knobs
|
||||
|
||||
Live tuning values for Rune apps. A `Knob` is a named number (a slider, or a choice between
|
||||
labels) with a range and a default; knobs live in `Group`s, each tied to the key of the element
|
||||
it tunes. ⌘⇧K opens a panel that tunes them while the app runs:
|
||||
|
||||
- **Side panel** (`side`): slides in down the window's right edge and pushes the page over. Its
|
||||
groups list in one scroll as a folding tree of pages and their parts, with sticky headers and a
|
||||
dot on the parts on screen; typing filters. Its left edge drags to resize it.
|
||||
- **Floating panel** (`layer`): floats over the window with a tab per group.
|
||||
- **Rows** (`inline`, `actions`): the same rows for an app's own layout, a storybook's column
|
||||
say. Choices lay out as a segmented control, a grid when they don't fit, or a ‹ › stepper over
|
||||
the whole list past ten options.
|
||||
|
||||
Each group has Random, Reset, Undo, Copy (`name = value` lines) and presets, declared in code or
|
||||
saved from the panel. Hovering a group's header outlines its part of the window, and the target
|
||||
button picks a part by pointing at it. With the panel focused, ↑/↓ pick a row, ←/→ fold, open or
|
||||
step it (⇧ for 10×), and Esc closes.
|
||||
|
||||
The panel is a dev tool. Without the `panel` feature, `side` returns the page alone, `layer`
|
||||
draws nothing, `key` takes nothing and `Knobs::get` returns each knob's default, so a shipped
|
||||
build runs on the constants:
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
rune-knobs = { git = "https://github.com/anomalyco/rune", rev = "…" }
|
||||
|
||||
[features]
|
||||
dev = ["rune-knobs/panel"]
|
||||
```
|
||||
|
||||
## A knob in an app
|
||||
|
||||
```rust
|
||||
use rune_knobs::{Group, Knob, Knobs, Style};
|
||||
|
||||
const RADIUS: Knob = Knob::new("Card radius", 0.0, 32.0, 14.0).about("How round the card's corners are");
|
||||
const TINT: Knob = Knob::choice("Card tint", &["Plain", "Accent", "Raised"], 0);
|
||||
const GROUPS: &[Group] = &[Group::new("Card", "card", &[RADIUS, TINT])];
|
||||
|
||||
struct State { knobs: Knobs, /* … */ }
|
||||
|
||||
fn view(s: &State, _: &mut Cx<State>) -> El {
|
||||
let card = col().key("card").radius(s.knobs.get(&RADIUS)) /* … */;
|
||||
let page = col().key("page").grow(1.0).h_full().center().child(card);
|
||||
rune_knobs::side(page, &s.knobs, GROUPS, Style::dark(), |s: &mut State| &mut s.knobs)
|
||||
}
|
||||
|
||||
fn on_key(s: &mut State, ev: &KeyEvent, tx: &mut Tx) -> bool {
|
||||
let taken = rune_knobs::key(&mut s.knobs, ev); // ⌘⇧K, and Esc while open
|
||||
if taken { tx.motion(s.knobs.slide()) } // the page slides over with the panel
|
||||
taken
|
||||
}
|
||||
```
|
||||
|
||||
`examples/knobs` is this app. `Knobs` is plain data: save `values`, `saved` and `width` with the
|
||||
app's other state so tuning survives a relaunch. `Knobs::settled` marks what the app is set to,
|
||||
so a choice row shows a dot on that option while others are tried.
|
||||
|
||||
## In the playground
|
||||
|
||||
`App::playground`'s side column takes any view, so a story's knobs go there as rows. The rows
|
||||
act on whatever state the side view is built for, so give the story's state a `Knobs` field:
|
||||
|
||||
```rust
|
||||
Story::new("Cards/Card", Card::default, card_view)
|
||||
.side(|c: &Card, _| rune_knobs::inline(&c.knobs, GROUPS, Style::dark(), |c: &mut Card| &mut c.knobs, false))
|
||||
```
|
||||
|
||||
`inline` fills its parent's width (the column's 240 pt or more), and its rows lay out from the
|
||||
width they get: a slider's track grows with the column, and a choice sits beside its label or
|
||||
under it as the room allows. The floating panel keeps its own 300 pt. `Style::light()` is the
|
||||
light look. `examples/knobs` has this story (`-- --playground Knobs`).
|
||||
|
||||
`Playground::side(scene, view)` does the same for one of the app's scenes, against a scene's
|
||||
fresh copy of the app state.
|
||||
@@ -0,0 +1,198 @@
|
||||
//! The filter is a real single-line field: editing keys are its own while it edits, and the
|
||||
//! panel's keys come back when it stops.
|
||||
use rune::{Cx, Env, Key, KeyEvent, Mods, Runtime};
|
||||
|
||||
use super::*;
|
||||
use crate::Knob;
|
||||
|
||||
struct T {
|
||||
knobs: Knobs,
|
||||
}
|
||||
const L: Knob = Knob::new("Left size", 0.0, 10.0, 5.0).label("Left column size");
|
||||
const R: Knob = Knob::new("Right pad", 0.0, 40.0, 20.0).step(1.0);
|
||||
const G: Knob = Knob::new("Right gap", 0.0, 40.0, 10.0).step(1.0);
|
||||
const GROUPS: &[Group] = &[Group::new("Left", "left", &[L]), Group::new("Right", "right", &[R, G])];
|
||||
|
||||
fn view(s: &T, _: &mut Cx<T>) -> El {
|
||||
let page = row().key("cols").w_full().h_full().child(col().key("left").w(300.0).h_full()).child(col().key("right").grow(1.0).h_full());
|
||||
side(page, &s.knobs, GROUPS, Style::dark(), |s: &mut T| &mut s.knobs)
|
||||
}
|
||||
|
||||
fn settle(rt: &mut Runtime<T>) {
|
||||
for _ in 0..40 {
|
||||
rt.frame(1.0 / 60.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn press(rt: &mut Runtime<T>, key: Key, mods: Mods) {
|
||||
rt.key(KeyEvent { key, mods });
|
||||
settle(rt);
|
||||
}
|
||||
fn tap(rt: &mut Runtime<T>, key: Key) {
|
||||
press(rt, key, Mods::default());
|
||||
}
|
||||
fn type_str(rt: &mut Runtime<T>, s: &str) {
|
||||
for c in s.chars() {
|
||||
tap(rt, Key::Text(c.to_string()));
|
||||
}
|
||||
}
|
||||
fn cmd(c: char) -> (Key, Mods) {
|
||||
(Key::Command(c), Mods { cmd: true, ..Mods::default() })
|
||||
}
|
||||
|
||||
/// An open panel with the keyboard in it, the filter editing.
|
||||
fn editing() -> Runtime<T> {
|
||||
let mut s = T { knobs: Knobs::default() };
|
||||
s.knobs.show();
|
||||
s.knobs.set_folded("Right", false);
|
||||
let mut rt = Runtime::new(s, view, (1000.0, 700.0), Env::new(true, 1.0));
|
||||
settle(&mut rt);
|
||||
let (x, y) = rt.find("knobs-filter").unwrap();
|
||||
rt.pointer_move(x, y);
|
||||
settle(&mut rt);
|
||||
rt.pointer_down(x, y);
|
||||
rt.pointer_up(x, y);
|
||||
settle(&mut rt);
|
||||
assert!(rt.state.knobs.filtering, "a click starts filtering");
|
||||
rt
|
||||
}
|
||||
|
||||
/// The panel focused with the filter idle, the keyboard on Right pad.
|
||||
fn idle() -> Runtime<T> {
|
||||
let mut rt = editing();
|
||||
type_str(&mut rt, "right");
|
||||
tap(&mut rt, Key::Escape);
|
||||
rt
|
||||
}
|
||||
|
||||
fn caret(rt: &Runtime<T>) -> (usize, usize) {
|
||||
rt.state.knobs.edit().range()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typing_filters_and_the_caret_moves_without_stepping_a_knob() {
|
||||
let mut rt = editing();
|
||||
assert!(rt.find("knobs-filter-input").is_some() && rt.state.knobs.edit().focused);
|
||||
type_str(&mut rt, "rigt");
|
||||
assert_eq!(rt.state.knobs.query, "rigt");
|
||||
tap(&mut rt, Key::Left);
|
||||
assert_eq!(caret(&rt), (3, 3), "← moves the caret");
|
||||
type_str(&mut rt, "h");
|
||||
assert_eq!(rt.state.knobs.query, "right");
|
||||
assert_eq!(rt.state.knobs.at(), Some(Node::Knob(1, 0)), "the keyboard is on the first match");
|
||||
let before = rt.state.knobs.clone();
|
||||
tap(&mut rt, Key::Right);
|
||||
tap(&mut rt, Key::Left);
|
||||
tap(&mut rt, Key::Left);
|
||||
assert_eq!(rt.state.knobs.values, before.values, "← → step no knob");
|
||||
assert_eq!((rt.state.knobs.folded.clone(), rt.state.knobs.unfolded.clone()), (before.folded, before.unfolded), "and fold nothing");
|
||||
press(&mut rt, Key::Left, Mods { shift: true, ..Mods::default() });
|
||||
assert_eq!(caret(&rt), (2, 3), "⇧← extends the selection");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_all_then_typing_replaces_the_query() {
|
||||
let mut rt = editing();
|
||||
type_str(&mut rt, "right");
|
||||
let (k, m) = cmd('a');
|
||||
press(&mut rt, k, m);
|
||||
assert_eq!(caret(&rt), (0, 5));
|
||||
type_str(&mut rt, "left");
|
||||
assert_eq!(rt.state.knobs.query, "left");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn word_and_line_deletes_and_paste_work() {
|
||||
let mut rt = editing();
|
||||
type_str(&mut rt, "right pad");
|
||||
press(&mut rt, Key::Backspace, Mods { alt: true, ..Mods::default() });
|
||||
assert_eq!(rt.state.knobs.query, "right ");
|
||||
press(&mut rt, Key::Left, Mods { alt: true, ..Mods::default() });
|
||||
assert_eq!(caret(&rt), (0, 0), "⌥← jumps a word");
|
||||
press(&mut rt, Key::Right, Mods { cmd: true, ..Mods::default() });
|
||||
assert_eq!(caret(&rt), (6, 6), "⌘→ goes to the end");
|
||||
press(&mut rt, Key::Backspace, Mods { cmd: true, ..Mods::default() });
|
||||
assert_eq!(rt.state.knobs.query, "");
|
||||
rt.paste("gap");
|
||||
settle(&mut rt);
|
||||
assert_eq!(rt.state.knobs.query, "gap");
|
||||
type_str(&mut rt, "/");
|
||||
assert_eq!(rt.state.knobs.query, "gap/", "a / is text while editing");
|
||||
assert!(rt.state.knobs.filtering);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn down_while_typing_moves_the_row() {
|
||||
let mut rt = editing();
|
||||
type_str(&mut rt, "right");
|
||||
assert_eq!(rt.state.knobs.at(), Some(Node::Knob(1, 0)));
|
||||
tap(&mut rt, Key::Down);
|
||||
assert_eq!(rt.state.knobs.at(), Some(Node::Knob(1, 1)));
|
||||
assert!(rt.state.knobs.filtering && rt.state.knobs.edit().focused, "the field keeps focus");
|
||||
tap(&mut rt, Key::Up);
|
||||
assert_eq!(rt.state.knobs.at(), Some(Node::Knob(1, 0)));
|
||||
assert_eq!(rt.state.knobs.query, "right");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escape_and_return_stop_filtering_then_clear_then_close() {
|
||||
let mut rt = editing();
|
||||
type_str(&mut rt, "right");
|
||||
tap(&mut rt, Key::Enter);
|
||||
assert!(!rt.state.knobs.filtering && rt.state.knobs.query == "right", "Return stops and keeps the matches");
|
||||
assert!(rt.find("knobs-filter-input").is_none());
|
||||
tap(&mut rt, Key::Text("/".into()));
|
||||
assert!(rt.state.knobs.filtering, "/ starts again");
|
||||
tap(&mut rt, Key::Escape);
|
||||
assert!(!rt.state.knobs.filtering && rt.state.knobs.query == "right");
|
||||
tap(&mut rt, Key::Escape);
|
||||
assert!(rt.state.knobs.query.is_empty() && rt.state.knobs.open, "a second Esc clears");
|
||||
tap(&mut rt, Key::Escape);
|
||||
assert!(!rt.state.knobs.open, "a third closes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_the_field_idle_the_arrows_step_and_fold_again() {
|
||||
let mut rt = idle();
|
||||
assert_eq!(rt.state.knobs.at(), Some(Node::Knob(1, 0)));
|
||||
tap(&mut rt, Key::Right);
|
||||
assert_eq!(rt.state.knobs.get(&R), 21.0, "→ steps the knob: focus went back to the panel");
|
||||
tap(&mut rt, Key::Left);
|
||||
assert_eq!(rt.state.knobs.get(&R), 20.0);
|
||||
rt.state.knobs.set_query("");
|
||||
rt.invalidate();
|
||||
settle(&mut rt);
|
||||
rt.state.knobs.set_at(Some(Node::Group(1)), GROUPS);
|
||||
tap(&mut rt, Key::Left);
|
||||
assert!(rt.state.knobs.folded.contains("Right"), "← folds a header");
|
||||
tap(&mut rt, Key::Text("/".into()));
|
||||
assert!(rt.state.knobs.filtering, "/ starts when the field is idle");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clicking_away_ends_editing() {
|
||||
let mut rt = editing();
|
||||
type_str(&mut rt, "gap");
|
||||
click_panel(&mut rt);
|
||||
tap(&mut rt, Key::Right);
|
||||
assert!(!rt.state.knobs.filtering, "the arrows are the panel's again");
|
||||
}
|
||||
|
||||
fn click_panel(rt: &mut Runtime<T>) {
|
||||
let (x, y) = rt.find("knobs-about").unwrap();
|
||||
rt.pointer_move(x, y);
|
||||
settle(rt);
|
||||
rt.pointer_down(x, y);
|
||||
rt.pointer_up(x, y);
|
||||
settle(rt);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn query_set_by_the_app_shows_in_the_field() {
|
||||
let mut rt = editing();
|
||||
rt.state.knobs.set_query("pad");
|
||||
rt.invalidate();
|
||||
settle(&mut rt);
|
||||
type_str(&mut rt, "s");
|
||||
assert_eq!(rt.state.knobs.query, "pads", "typing continues from the set text");
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
//! Phosphor Icons (regular, 256 grid), MIT © Phosphor Icons, as the web knobs panel draws them.
|
||||
|
||||
use rune::Icon;
|
||||
|
||||
pub static UNDO: Icon = Icon { name: "knobs-undo", view: 256.0, body: r#"<path d="M232,144a64.07,64.07,0,0,1-64,64H80a8,8,0,0,1,0-16h88a48,48,0,0,0,0-96H51.31l34.35,34.34a8,8,0,0,1-11.32,11.32l-48-48a8,8,0,0,1,0-11.32l48-48A8,8,0,0,1,85.66,45.66L51.31,80H168A64.07,64.07,0,0,1,232,144Z" fill="currentColor"/>"# };
|
||||
pub static RANDOM: Icon = Icon { name: "knobs-random", view: 256.0, body: r#"<path d="M192,32H64A32,32,0,0,0,32,64V192a32,32,0,0,0,32,32H192a32,32,0,0,0,32-32V64A32,32,0,0,0,192,32Zm16,160a16,16,0,0,1-16,16H64a16,16,0,0,1-16-16V64A16,16,0,0,1,64,48H192a16,16,0,0,1,16,16ZM104,92A12,12,0,1,1,92,80,12,12,0,0,1,104,92Zm72,0a12,12,0,1,1-12-12A12,12,0,0,1,176,92Zm-72,72a12,12,0,1,1-12-12A12,12,0,0,1,104,164Zm36-36a12,12,0,1,1-12-12A12,12,0,0,1,140,128Zm36,36a12,12,0,1,1-12-12A12,12,0,0,1,176,164Z" fill="currentColor"/>"# };
|
||||
pub static RESET: Icon = Icon { name: "knobs-reset", view: 256.0, body: r#"<path d="M224,128a96,96,0,0,1-94.71,96H128A95.38,95.38,0,0,1,62.1,197.8a8,8,0,0,1,11-11.63A80,80,0,1,0,71.43,71.39a3.07,3.07,0,0,1-.26.25L44.59,96H72a8,8,0,0,1,0,16H24a8,8,0,0,1-8-8V56a8,8,0,0,1,16,0V85.8L60.25,60A96,96,0,0,1,224,128Z" fill="currentColor"/>"# };
|
||||
pub static COPY: Icon = Icon { name: "knobs-copy", view: 256.0, body: r#"<path d="M216,32H88a8,8,0,0,0-8,8V80H40a8,8,0,0,0-8,8V216a8,8,0,0,0,8,8H168a8,8,0,0,0,8-8V176h40a8,8,0,0,0,8-8V40A8,8,0,0,0,216,32ZM160,208H48V96H160Zm48-48H176V88a8,8,0,0,0-8-8H96V48H208Z" fill="currentColor"/>"# };
|
||||
pub static TARGET: Icon = Icon { name: "knobs-target", view: 256.0, body: r#"<path d="M232,120h-8.34A96.14,96.14,0,0,0,136,32.34V24a8,8,0,0,0-16,0v8.34A96.14,96.14,0,0,0,32.34,120H24a8,8,0,0,0,0,16h8.34A96.14,96.14,0,0,0,120,223.66V232a8,8,0,0,0,16,0v-8.34A96.14,96.14,0,0,0,223.66,136H232a8,8,0,0,0,0-16Zm-96,87.6V200a8,8,0,0,0-16,0v7.6A80.15,80.15,0,0,1,48.4,136H56a8,8,0,0,0,0-16H48.4A80.15,80.15,0,0,1,120,48.4V56a8,8,0,0,0,16,0V48.4A80.15,80.15,0,0,1,207.6,120H200a8,8,0,0,0,0,16h7.6A80.15,80.15,0,0,1,136,207.6ZM128,88a40,40,0,1,0,40,40A40,40,0,0,0,128,88Zm0,64a24,24,0,1,1,24-24A24,24,0,0,1,128,152Z" fill="currentColor"/>"# };
|
||||
+737
@@ -0,0 +1,737 @@
|
||||
//! Live tuning for any Rune app, in the look of a web knobs panel.
|
||||
//! Knobs live in groups, each tied to the keyed element it tunes. ⌘⇧K opens the panel on the
|
||||
//! last group used. [`side`] makes it a right-hand side panel that slides in and pushes the page
|
||||
//! over, every group a section in one scroll; [`layer`] floats it over the window with a tab per
|
||||
//! group. Hovering a group's tab or header outlines its part of the window. The
|
||||
//! target button picks a part by pointing at it. With the panel focused (click in it), ↑/↓ pick
|
||||
//! a knob, ←/→ step it (⇧ for 10×), Tab or [ ] switch groups. Each group has Random, Reset, Undo, Copy (`name = value` lines)
|
||||
//! and presets, both declared in code and saved from the panel. Esc closes.
|
||||
//!
|
||||
//! Values are plain `name -> f32`; the app saves `values`, `saved` and `kept` with its other
|
||||
//! state. [`Knobs::change`] makes an undoable change ([`Knobs::undo`], [`Knobs::redo`]);
|
||||
//! [`Knobs::keep`] saves the values Revert goes back to and [`Knobs::differs`] marks.
|
||||
//! The panel is a dev tool: without the `panel` feature, `layer` draws nothing, `key` handles
|
||||
//! nothing and `get` returns each knob's default, so a shipped build runs on the constants.
|
||||
//!
|
||||
//! ```ignore
|
||||
//! const RIM: Knob = Knob::new("Rim width", 0.0, 3.0, 1.0);
|
||||
//! const GROUPS: &[Group] = &[Group::new("Panel", "panel", &[RIM])];
|
||||
//! panel.border(knobs.get(&RIM), ..);
|
||||
//! root.child(rune_knobs::layer(&s.knobs, GROUPS, Style::dark(), |s: &mut State| &mut s.knobs))
|
||||
//! // in on_key: if rune_knobs::key(&mut s.knobs, ev) { return true }
|
||||
//! ```
|
||||
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use rune::KeyEvent;
|
||||
|
||||
#[cfg(feature = "panel")]
|
||||
mod icons;
|
||||
#[cfg(feature = "panel")]
|
||||
mod rows;
|
||||
#[cfg(feature = "panel")]
|
||||
mod side;
|
||||
#[cfg(feature = "panel")]
|
||||
mod side_list;
|
||||
mod style;
|
||||
mod tree;
|
||||
#[cfg(feature = "panel")]
|
||||
mod view;
|
||||
|
||||
#[cfg(feature = "panel")]
|
||||
pub use side::side;
|
||||
pub use style::Style;
|
||||
#[cfg(feature = "panel")]
|
||||
pub use view::actions;
|
||||
#[cfg(feature = "panel")]
|
||||
pub use view::inline;
|
||||
#[cfg(feature = "panel")]
|
||||
pub use view::layer;
|
||||
|
||||
/// The spring the side panel slides in and out on by default; send ⌘⇧K's commit on
|
||||
/// [`Knobs::slide`] (`tx.motion(s.knobs.slide())`), so the page moves over with the panel.
|
||||
pub const SLIDE: rune::Spring = rune::Spring::new(0.3, 0.0);
|
||||
/// [`SLIDE`] as knobs, for a story that tunes it.
|
||||
pub const SLIDE_TIME: Knob = Knob::new("Knobs slide", 0.1, 0.8, 0.3).label("Panel slide time");
|
||||
pub const SLIDE_BOUNCE: Knob = Knob::new("Knobs slide bounce", 0.0, 0.4, 0.0).label("Panel slide bounce");
|
||||
/// How the side panel lays its groups out, for comparing: a tree of pages and their parts,
|
||||
/// what's on screen first, or a tab per page.
|
||||
pub const LAYOUT: Knob = Knob::choice("Knobs layout", &["Tree", "On screen", "Tabs"], 0).label("Panel layout").about("How this panel lists its parts: a folding tree, what's on screen first, or a tab per page");
|
||||
/// How long a section takes to fold or open.
|
||||
pub const FOLD_TIME: Knob = Knob::new("Knobs fold", 0.05, 0.6, 0.2).label("Section fold time").about("How long a section of this panel takes to fold or open");
|
||||
/// The side panel's width until its edge is dragged, and the range it can be dragged in.
|
||||
pub const SIDE_W: f32 = 340.0;
|
||||
pub const SIDE_MIN: f32 = 280.0;
|
||||
pub const SIDE_MAX: f32 = 640.0;
|
||||
|
||||
/// A button that does one thing, with the key that does it: see [`actions`].
|
||||
pub struct Action<S> {
|
||||
pub cap: &'static str,
|
||||
pub label: &'static str,
|
||||
pub run: fn(&mut S, &mut rune::Tx),
|
||||
}
|
||||
|
||||
/// A tunable number. `step` snaps it (0 is continuous); `labels` make it a choice between
|
||||
/// `min`, `min + 1`, … shown as a segmented control.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Knob {
|
||||
/// The knob's key: values and presets are stored under it, so it never changes.
|
||||
pub name: &'static str,
|
||||
/// What the panel calls it, in plain words, when that differs from `name`.
|
||||
pub label: &'static str,
|
||||
pub min: f32,
|
||||
pub max: f32,
|
||||
pub default: f32,
|
||||
pub step: f32,
|
||||
pub labels: &'static [&'static str],
|
||||
/// One plain line on what it changes, shown while it's hovered or the keyboard is on it.
|
||||
pub about: &'static str,
|
||||
/// One short line per option of a choice, shown while that option is hovered or picked.
|
||||
pub hints: &'static [&'static str],
|
||||
}
|
||||
|
||||
/// What an app says about a knob from one table instead of on the knob: a plainer name, one
|
||||
/// line on what it changes, and a line per option, keyed by the option's label so a reordered
|
||||
/// knob keeps them right. Hand the table to [`describe`]; a note wins over the knob's own label,
|
||||
/// about and hints.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Note {
|
||||
pub name: &'static str,
|
||||
pub label: &'static str,
|
||||
pub about: &'static str,
|
||||
pub hints: &'static [(&'static str, &'static str)],
|
||||
}
|
||||
|
||||
impl Note {
|
||||
pub const fn new(name: &'static str, about: &'static str) -> Self {
|
||||
Self { name, label: "", about, hints: &[] }
|
||||
}
|
||||
pub const fn label(mut self, label: &'static str) -> Self {
|
||||
self.label = label;
|
||||
self
|
||||
}
|
||||
pub const fn hints(mut self, hints: &'static [(&'static str, &'static str)]) -> Self {
|
||||
self.hints = hints;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
static NOTES: std::sync::OnceLock<&'static [Note]> = std::sync::OnceLock::new();
|
||||
|
||||
/// Sets the app's notes on its knobs, once; later calls are ignored.
|
||||
pub fn describe(notes: &'static [Note]) {
|
||||
NOTES.set(notes).ok();
|
||||
}
|
||||
|
||||
fn note(name: &str) -> Option<&'static Note> {
|
||||
NOTES.get()?.iter().find(|n| n.name == name)
|
||||
}
|
||||
|
||||
impl Knob {
|
||||
pub const fn new(name: &'static str, min: f32, max: f32, default: f32) -> Self {
|
||||
Self { name, label: "", min, max, default, step: 0.0, labels: &[], about: "", hints: &[] }
|
||||
}
|
||||
/// Shows the knob as `label` and keeps storing it under its name.
|
||||
pub const fn label(mut self, label: &'static str) -> Self {
|
||||
self.label = label;
|
||||
self
|
||||
}
|
||||
/// Says in one plain line what it changes.
|
||||
pub const fn about(mut self, about: &'static str) -> Self {
|
||||
self.about = about;
|
||||
self
|
||||
}
|
||||
/// One line per option, in order.
|
||||
pub const fn hints(mut self, hints: &'static [&'static str]) -> Self {
|
||||
self.hints = hints;
|
||||
self
|
||||
}
|
||||
/// What the panel calls it.
|
||||
pub fn title(&self) -> &'static str {
|
||||
match note(self.name) {
|
||||
Some(n) if !n.label.is_empty() => n.label,
|
||||
_ if self.label.is_empty() => self.name,
|
||||
_ => self.label,
|
||||
}
|
||||
}
|
||||
/// The line on what it changes: its note's, or its own.
|
||||
pub fn describe(&self) -> &'static str {
|
||||
note(self.name).map(|n| n.about).filter(|a| !a.is_empty()).unwrap_or(self.about)
|
||||
}
|
||||
/// The line on option `i` of a choice, or "" when there isn't one.
|
||||
pub fn hint(&self, i: usize) -> &'static str {
|
||||
let own = self.hints.get(i).copied().unwrap_or("");
|
||||
let label = self.labels.get(i).copied().unwrap_or("");
|
||||
note(self.name).and_then(|n| n.hints.iter().find(|(l, _)| *l == label)).map(|(_, h)| *h).filter(|h| !h.is_empty()).unwrap_or(own)
|
||||
}
|
||||
pub const fn step(mut self, step: f32) -> Self {
|
||||
self.step = step;
|
||||
self
|
||||
}
|
||||
/// One of `labels`, stored as its index.
|
||||
pub const fn choice(name: &'static str, labels: &'static [&'static str], default: usize) -> Self {
|
||||
Self { name, label: "", min: 0.0, max: (labels.len().saturating_sub(1)) as f32, default: default as f32, step: 1.0, labels, about: "", hints: &[] }
|
||||
}
|
||||
fn clamp(&self, v: f32) -> f32 {
|
||||
let v = v.clamp(self.min, self.max);
|
||||
if self.step > 0.0 { (self.min + ((v - self.min) / self.step).round() * self.step).min(self.max) } else { v }
|
||||
}
|
||||
}
|
||||
|
||||
/// Values a group starts from, by knob name; knobs it leaves out take their defaults.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Preset {
|
||||
pub name: &'static str,
|
||||
pub values: &'static [(&'static str, f32)],
|
||||
}
|
||||
|
||||
/// Knobs for one part of the window: `region` is the key of the element they tune.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Group {
|
||||
pub name: &'static str,
|
||||
pub region: &'static str,
|
||||
pub knobs: &'static [Knob],
|
||||
pub presets: &'static [Preset],
|
||||
/// What the defaults' chip says ("Default"), when they are a version with a name.
|
||||
pub default_label: &'static str,
|
||||
/// The page this group is a part of ("Item page"), which the side panel folds as one;
|
||||
/// empty for a group that stands alone.
|
||||
pub under: &'static str,
|
||||
}
|
||||
|
||||
impl Group {
|
||||
pub const fn new(name: &'static str, region: &'static str, knobs: &'static [Knob]) -> Self {
|
||||
Self { name, region, knobs, presets: &[], default_label: DEFAULT, under: "" }
|
||||
}
|
||||
/// Files the group under a page: names must still be unique across all groups.
|
||||
pub const fn under(mut self, page: &'static str) -> Self {
|
||||
self.under = page;
|
||||
self
|
||||
}
|
||||
/// The page it's on: its own name when it stands alone.
|
||||
pub fn page(&self) -> &'static str {
|
||||
if self.under.is_empty() { self.name } else { self.under }
|
||||
}
|
||||
pub const fn presets(mut self, presets: &'static [Preset]) -> Self {
|
||||
self.presets = presets;
|
||||
self
|
||||
}
|
||||
/// Names the defaults' chip, as knobs' `defaultLabel`: "Native" when the defaults are
|
||||
/// what the platform does.
|
||||
pub const fn default_label(mut self, label: &'static str) -> Self {
|
||||
self.default_label = label;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// A preset saved from the panel.
|
||||
pub type Saved = Vec<(String, BTreeMap<String, f32>)>;
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Knobs {
|
||||
/// The layer is showing.
|
||||
pub open: bool,
|
||||
/// Values that were changed; the rest are at their defaults.
|
||||
pub values: BTreeMap<String, f32>,
|
||||
/// Presets saved from the panel, by group name, in the order they were saved.
|
||||
pub saved: BTreeMap<String, Saved>,
|
||||
/// The values as last kept with [`Knobs::keep`]: [`Knobs::revert`] goes back to them and
|
||||
/// [`Knobs::differs`] marks a knob moved off them. Knobs left out were kept at their
|
||||
/// defaults. The app saves it with `values`.
|
||||
pub kept: BTreeMap<String, f32>,
|
||||
/// The group the panel shows; the last one used, and the first group until one is picked.
|
||||
pub group: Option<String>,
|
||||
/// Picking a region with the target button: the panel shows no group meanwhile.
|
||||
pub picking: bool,
|
||||
/// What the app is set to while other values are tried (a storybook sets it as it opens),
|
||||
/// by knob name: choice rows mark that option with a dot. Knobs left out get no mark.
|
||||
pub settled: Option<BTreeMap<String, f32>>,
|
||||
/// The side panel's width as dragged (0 until it is); the app saves it.
|
||||
pub width: f32,
|
||||
/// Side panel sections folded, and ones opened, by group or page name, while the panel
|
||||
/// is open. Opening it again folds everything but the group last opened (see [`show`]).
|
||||
///
|
||||
/// [`show`]: Knobs::show
|
||||
pub folded: BTreeSet<String>,
|
||||
pub unfolded: BTreeSet<String>,
|
||||
/// What has been typed to filter the side panel: the filter field's text, kept in step with
|
||||
/// it on every edit. Set it with [`Knobs::set_query`] so the field follows.
|
||||
pub query: String,
|
||||
/// The filter field is editing: `/` (or a click on it) starts, Esc or Return stops. While
|
||||
/// it does, the field owns the keys it edits with.
|
||||
pub filtering: bool,
|
||||
/// The filter field's model: caret, selection, undo. `query` mirrors its text.
|
||||
edit: rune::TextEdit,
|
||||
/// The page the side panel's Tabs layout shows, once one is picked.
|
||||
pub tab: Option<String>,
|
||||
/// The side panel's keyboard row.
|
||||
at: Option<tree::Node>,
|
||||
/// The long choice showing all its options under its stepper.
|
||||
expanded: Option<String>,
|
||||
/// The group whose region is outlined: under the pointer while picking, or its tab hovered.
|
||||
hover: Option<String>,
|
||||
/// The active knob for the keyboard, and whether the keyboard is driving the panel.
|
||||
cursor: usize,
|
||||
kbd: bool,
|
||||
/// The slider under the pointer, and the one being dragged.
|
||||
hot: Option<String>,
|
||||
/// The option of a choice under the pointer: its knob and index.
|
||||
hot_opt: Option<(String, usize)>,
|
||||
drag: Option<String>,
|
||||
/// The preset each group last applied.
|
||||
active: BTreeMap<String, String>,
|
||||
undo: Vec<BTreeMap<String, f32>>,
|
||||
redo: Vec<BTreeMap<String, f32>>,
|
||||
seed: u64,
|
||||
}
|
||||
|
||||
impl Knobs {
|
||||
/// The side panel's spring, from [`SLIDE_TIME`] and [`SLIDE_BOUNCE`].
|
||||
pub fn slide(&self) -> rune::Spring {
|
||||
rune::Spring::new(self.get(&SLIDE_TIME), self.get(&SLIDE_BOUNCE))
|
||||
}
|
||||
|
||||
pub fn get(&self, k: &Knob) -> f32 {
|
||||
if !cfg!(feature = "panel") {
|
||||
return k.default;
|
||||
}
|
||||
k.clamp(self.values.get(k.name).copied().unwrap_or(k.default))
|
||||
}
|
||||
pub fn set(&mut self, k: &Knob, v: f32) {
|
||||
self.values.insert(k.name.to_owned(), k.clamp(v));
|
||||
}
|
||||
|
||||
/// Opens on the last group used, or the first.
|
||||
/// The side panel's width, open or not.
|
||||
pub fn side_w(&self) -> f32 {
|
||||
if self.width > 0.0 { self.width.clamp(SIDE_MIN, SIDE_MAX) } else { SIDE_W }
|
||||
}
|
||||
/// How much room the side panel takes from the page: its width while open, else 0.
|
||||
pub fn side_room(&self) -> f32 {
|
||||
if cfg!(feature = "panel") && self.open { self.side_w() } else { 0.0 }
|
||||
}
|
||||
/// The side panel's fold spring, from [`FOLD_TIME`].
|
||||
pub fn fold_spring(&self) -> rune::Spring {
|
||||
rune::Spring::new(self.get(&FOLD_TIME), 0.0)
|
||||
}
|
||||
/// Whether side panel section `name` is folded, given whether it would be by default.
|
||||
pub fn is_folded(&self, name: &str, by_default: bool) -> bool {
|
||||
if self.folded.contains(name) {
|
||||
true
|
||||
} else if self.unfolded.contains(name) {
|
||||
false
|
||||
} else {
|
||||
by_default
|
||||
}
|
||||
}
|
||||
/// Folds or opens a side panel section, and remembers it.
|
||||
pub fn set_folded(&mut self, name: &str, fold: bool) {
|
||||
if fold {
|
||||
self.unfolded.remove(name);
|
||||
self.folded.insert(name.to_owned());
|
||||
} else {
|
||||
self.folded.remove(name);
|
||||
self.unfolded.insert(name.to_owned());
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens the panel. Coming from shut, every section starts folded, a list of all the parts,
|
||||
/// except the group last used if it was left open (and so its page).
|
||||
pub fn show(&mut self) {
|
||||
if !self.open {
|
||||
let keep = self.group.clone().filter(|g| self.unfolded.contains(g));
|
||||
self.folded.clear();
|
||||
self.unfolded.clear();
|
||||
self.unfolded.extend(keep);
|
||||
}
|
||||
self.open = true;
|
||||
self.picking = false;
|
||||
self.kbd = false;
|
||||
self.hover = None;
|
||||
}
|
||||
/// Starts picking a region of the window with the pointer.
|
||||
pub fn pick_region(&mut self) {
|
||||
self.picking = true;
|
||||
self.hover = None;
|
||||
}
|
||||
/// The group the panel shows, if not picking.
|
||||
pub fn current(&self, groups: &[Group]) -> Option<Group> {
|
||||
if self.picking {
|
||||
return None;
|
||||
}
|
||||
self.group.as_deref().and_then(|n| groups.iter().find(|g| g.name == n)).or(groups.first()).copied()
|
||||
}
|
||||
/// Puts the pointer over knob `name` (and option `option` of a choice), for a still or a test.
|
||||
pub fn hover(&mut self, name: &str, option: Option<usize>) {
|
||||
self.hot = Some(name.to_owned());
|
||||
self.hot_opt = option.map(|j| (name.to_owned(), j));
|
||||
}
|
||||
/// Sets the filter's text, in the field and in `query`.
|
||||
pub fn set_query(&mut self, q: &str) {
|
||||
self.query = q.to_owned();
|
||||
self.sync_edit();
|
||||
}
|
||||
/// Brings the field's text to `query`, if the app changed `query` itself.
|
||||
pub(crate) fn sync_edit(&mut self) {
|
||||
if self.edit.text != self.query {
|
||||
self.edit.replace_text(self.query.clone());
|
||||
}
|
||||
}
|
||||
/// Starts filtering, as `/` does: the field takes focus with its text selected, so typing
|
||||
/// replaces it.
|
||||
pub fn filter(&mut self, query: &str) {
|
||||
self.set_query(query);
|
||||
self.start_filter();
|
||||
}
|
||||
pub(crate) fn start_filter(&mut self) {
|
||||
self.sync_edit();
|
||||
self.filtering = true;
|
||||
self.edit.focused = true;
|
||||
self.edit.set_selection(0, self.edit.text.len());
|
||||
}
|
||||
/// Stops filtering; focus goes back to the panel.
|
||||
pub(crate) fn stop_filter(&mut self) {
|
||||
self.filtering = false;
|
||||
self.edit.focused = false;
|
||||
}
|
||||
/// The field's model, for [`rune::El::on_edit`].
|
||||
#[cfg(feature = "panel")]
|
||||
pub(crate) fn edit_mut(&mut self) -> &mut rune::TextEdit {
|
||||
&mut self.edit
|
||||
}
|
||||
/// The field's model as the view draws it.
|
||||
#[cfg(feature = "panel")]
|
||||
pub(crate) fn edit(&self) -> &rune::TextEdit {
|
||||
&self.edit
|
||||
}
|
||||
/// The field changed: `query` follows.
|
||||
#[cfg(feature = "panel")]
|
||||
pub(crate) fn edited(&mut self) {
|
||||
self.query = self.edit.text.clone();
|
||||
}
|
||||
pub fn close(&mut self) {
|
||||
self.open = false;
|
||||
self.picking = false;
|
||||
self.hover = None;
|
||||
self.kbd = false;
|
||||
self.stop_filter();
|
||||
self.hot = None;
|
||||
self.hot_opt = None;
|
||||
self.drag = None;
|
||||
}
|
||||
pub fn toggle(&mut self) {
|
||||
if self.open { self.close() } else { self.show() }
|
||||
}
|
||||
/// Shows `group`'s knobs.
|
||||
pub fn pick(&mut self, group: &str) {
|
||||
if self.group.as_deref() != Some(group) {
|
||||
self.cursor = 0;
|
||||
}
|
||||
self.group = Some(group.to_owned());
|
||||
self.set_folded(group, false);
|
||||
self.picking = false;
|
||||
self.hover = None;
|
||||
}
|
||||
|
||||
/// Keys for the panel while it has focus: ↑/↓ pick a knob, ←/→ step it (⇧ for 10×; a choice
|
||||
/// moves one option), Tab, ⇧Tab, `[` and `]` switch groups, Esc closes. True if taken.
|
||||
pub fn panel_key(&mut self, groups: &[Group], ev: &KeyEvent) -> bool {
|
||||
use rune::Key;
|
||||
// Focus left the filter field without the panel hearing of it.
|
||||
if self.filtering && !self.edit.focused {
|
||||
self.filtering = false;
|
||||
}
|
||||
if ev.mods.cmd || ev.mods.alt || ev.mods.ctrl || self.filtering {
|
||||
return false;
|
||||
}
|
||||
if ev.key == Key::Escape {
|
||||
self.close();
|
||||
return true;
|
||||
}
|
||||
let Some(g) = self.current(groups).or(groups.first().copied()) else { return false };
|
||||
let n = g.knobs.len();
|
||||
match &ev.key {
|
||||
Key::Up | Key::Down if n > 0 => {
|
||||
let at = self.cursor.min(n - 1) as i32 + if ev.key == Key::Down { 1 } else { -1 };
|
||||
self.cursor = at.rem_euclid(n as i32) as usize;
|
||||
}
|
||||
Key::Left | Key::Right if n > 0 => self.step(&g.knobs[self.cursor.min(n - 1)], ev.key == Key::Right, ev.mods.shift),
|
||||
Key::Tab | Key::Text(_) => {
|
||||
let back = match &ev.key {
|
||||
Key::Tab => ev.mods.shift,
|
||||
Key::Text(t) if t == "[" => true,
|
||||
Key::Text(t) if t == "]" => false,
|
||||
_ => return false,
|
||||
};
|
||||
let i = groups.iter().position(|x| x.name == g.name).unwrap_or(0) as i32;
|
||||
let next = (i + if back { -1 } else { 1 }).rem_euclid(groups.len() as i32) as usize;
|
||||
self.pick(groups[next].name);
|
||||
}
|
||||
_ => return false,
|
||||
}
|
||||
self.kbd = true;
|
||||
true
|
||||
}
|
||||
|
||||
/// One step of `d` up or down (⇧ for 10×; a choice moves one option), undoable.
|
||||
pub(crate) fn step(&mut self, d: &Knob, up: bool, big: bool) {
|
||||
let unit = if !d.labels.is_empty() { 1.0 } else if d.step > 0.0 { d.step } else { (d.max - d.min) / 100.0 };
|
||||
let unit = if big && d.labels.is_empty() { unit * 10.0 } else { unit };
|
||||
let before = self.get(d);
|
||||
self.checkpoint();
|
||||
self.set(d, before + if up { unit } else { -unit });
|
||||
if self.get(d) == before && self.undo.last() == Some(&self.values) {
|
||||
self.undo.pop();
|
||||
}
|
||||
}
|
||||
|
||||
/// Anything Reset would change in `g`.
|
||||
pub fn can_reset(&self, g: &Group) -> bool {
|
||||
g.knobs.iter().any(|k| (self.get(k) - k.default).abs() > 1e-4) || self.active.get(g.name).is_some_and(|a| self.drifted(g, a))
|
||||
}
|
||||
|
||||
/// Remembers the values for Undo, once per change: call it before a change the panel makes
|
||||
/// itself (a drag calls it once, as it starts). A new change drops what Redo had.
|
||||
pub fn checkpoint(&mut self) {
|
||||
if self.undo.last() != Some(&self.values) {
|
||||
self.undo.push(self.values.clone());
|
||||
if self.undo.len() > 100 {
|
||||
self.undo.remove(0);
|
||||
}
|
||||
}
|
||||
self.redo.clear();
|
||||
}
|
||||
/// Sets `k` to `v` so Undo can take it back.
|
||||
pub fn change(&mut self, k: &Knob, v: f32) {
|
||||
if (self.get(k) - k.clamp(v)).abs() > 1e-6 {
|
||||
self.checkpoint();
|
||||
self.set(k, v);
|
||||
}
|
||||
}
|
||||
/// Takes back the last change. True if there was one.
|
||||
pub fn undo(&mut self) -> bool {
|
||||
let Some(v) = self.undo.pop() else { return false };
|
||||
self.redo.push(std::mem::replace(&mut self.values, v));
|
||||
true
|
||||
}
|
||||
/// Puts back the change Undo took. True if there was one.
|
||||
pub fn redo(&mut self) -> bool {
|
||||
let Some(v) = self.redo.pop() else { return false };
|
||||
self.undo.push(std::mem::replace(&mut self.values, v));
|
||||
true
|
||||
}
|
||||
pub fn can_undo(&self) -> bool {
|
||||
!self.undo.is_empty()
|
||||
}
|
||||
pub fn can_redo(&self) -> bool {
|
||||
!self.redo.is_empty()
|
||||
}
|
||||
|
||||
/// What `k` was when the values were last kept.
|
||||
pub fn kept_value(&self, k: &Knob) -> f32 {
|
||||
k.clamp(self.kept.get(k.name).copied().unwrap_or(k.default))
|
||||
}
|
||||
/// `k` has moved off its kept value.
|
||||
pub fn differs(&self, k: &Knob) -> bool {
|
||||
(self.get(k) - self.kept_value(k)).abs() > 1e-4
|
||||
}
|
||||
/// Keeps every value as it is now, as what Revert goes back to.
|
||||
pub fn keep(&mut self) {
|
||||
self.kept = self.values.clone();
|
||||
}
|
||||
/// Keeps `knobs` as they are now, the rest as they were kept.
|
||||
pub fn keep_some(&mut self, knobs: &[Knob]) {
|
||||
for k in knobs {
|
||||
match self.values.get(k.name) {
|
||||
Some(v) => self.kept.insert(k.name.to_owned(), *v),
|
||||
None => self.kept.remove(k.name),
|
||||
};
|
||||
}
|
||||
}
|
||||
/// Puts `knobs` back to their kept values, undoably.
|
||||
pub fn revert(&mut self, knobs: &[Knob]) {
|
||||
if !knobs.iter().any(|k| self.differs(k)) {
|
||||
return;
|
||||
}
|
||||
self.checkpoint();
|
||||
for k in knobs {
|
||||
match self.kept.get(k.name) {
|
||||
Some(v) => self.values.insert(k.name.to_owned(), *v),
|
||||
None => self.values.remove(k.name),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// Each of `g`'s knobs to a random value in its range.
|
||||
pub fn random(&mut self, g: &Group) {
|
||||
self.checkpoint();
|
||||
if self.seed == 0 {
|
||||
self.seed = rune::time::system_now().duration_since(rune::time::UNIX_EPOCH).map_or(1, |d| d.as_nanos() as u64) | 1;
|
||||
}
|
||||
for k in g.knobs {
|
||||
// xorshift64
|
||||
self.seed ^= self.seed << 13;
|
||||
self.seed ^= self.seed >> 7;
|
||||
self.seed ^= self.seed << 17;
|
||||
let f = (self.seed >> 40) as f32 / (1u64 << 24) as f32;
|
||||
self.set(k, k.min + f * (k.max - k.min));
|
||||
}
|
||||
}
|
||||
|
||||
/// Back to the active preset, or, already there, to the defaults.
|
||||
/// Puts one knob back to its default, undoably.
|
||||
pub fn reset_knob(&mut self, d: &Knob) {
|
||||
if self.values.contains_key(d.name) {
|
||||
self.checkpoint();
|
||||
self.values.remove(d.name);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn reset(&mut self, g: &Group) {
|
||||
let at = self.active.get(g.name).cloned();
|
||||
match at {
|
||||
Some(name) if self.drifted(g, &name) => self.apply(g, &name),
|
||||
_ => {
|
||||
self.checkpoint();
|
||||
for k in g.knobs {
|
||||
self.values.remove(k.name);
|
||||
}
|
||||
self.active.remove(g.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A preset's values for every knob in `g`, defaults filled in; "Default" is the defaults.
|
||||
pub fn preset(&self, g: &Group, name: &str) -> Option<BTreeMap<String, f32>> {
|
||||
let mut out: BTreeMap<String, f32> = g.knobs.iter().map(|k| (k.name.to_owned(), k.default)).collect();
|
||||
if let Some(p) = g.presets.iter().find(|p| p.name == name) {
|
||||
out.extend(p.values.iter().map(|(n, v)| ((*n).to_owned(), *v)));
|
||||
} else if let Some((_, v)) = self.saved.get(g.name).and_then(|s| s.iter().find(|(n, _)| n == name)) {
|
||||
out.extend(v.iter().filter(|(n, _)| g.knobs.iter().any(|k| k.name == *n)).map(|(n, v)| (n.clone(), *v)));
|
||||
} else if name != DEFAULT {
|
||||
return None;
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
pub fn apply(&mut self, g: &Group, name: &str) {
|
||||
let Some(vals) = self.preset(g, name) else { return };
|
||||
self.checkpoint();
|
||||
for k in g.knobs {
|
||||
let v = vals.get(k.name).copied().unwrap_or(k.default);
|
||||
if v == k.default {
|
||||
self.values.remove(k.name);
|
||||
} else {
|
||||
self.set(k, v);
|
||||
}
|
||||
}
|
||||
if name == DEFAULT {
|
||||
self.active.remove(g.name);
|
||||
} else {
|
||||
self.active.insert(g.name.to_owned(), name.to_owned());
|
||||
}
|
||||
}
|
||||
/// The preset `g` last applied ("Default" if none).
|
||||
pub fn active(&self, g: &Group) -> &str {
|
||||
self.active.get(g.name).map_or(DEFAULT, |s| s.as_str())
|
||||
}
|
||||
/// The values have moved off preset `name`.
|
||||
pub fn drifted(&self, g: &Group, name: &str) -> bool {
|
||||
let Some(vals) = self.preset(g, name) else { return false };
|
||||
g.knobs.iter().any(|k| (self.get(k) - k.clamp(vals[k.name])).abs() > 1e-4)
|
||||
}
|
||||
/// Saves `g`'s values as a new preset and makes it active.
|
||||
pub fn save(&mut self, g: &Group) -> String {
|
||||
let list = self.saved.entry(g.name.to_owned()).or_default();
|
||||
let n = (1..).find(|n| !list.iter().any(|(s, _)| *s == format!("Saved {n}"))).unwrap_or(1);
|
||||
let name = format!("Saved {n}");
|
||||
let vals = g.knobs.iter().map(|k| (k.name.to_owned(), self.get(k))).collect();
|
||||
self.saved.entry(g.name.to_owned()).or_default().push((name.clone(), vals));
|
||||
self.active.insert(g.name.to_owned(), name.clone());
|
||||
name
|
||||
}
|
||||
pub fn delete(&mut self, g: &Group, name: &str) {
|
||||
if let Some(list) = self.saved.get_mut(g.name) {
|
||||
list.retain(|(n, _)| n != name);
|
||||
}
|
||||
if self.active.get(g.name).is_some_and(|a| a == name) {
|
||||
self.active.remove(g.name);
|
||||
}
|
||||
}
|
||||
|
||||
/// `name = value` lines for `g`'s knobs; a choice adds its label.
|
||||
pub fn code(&self, g: &Group) -> String {
|
||||
let line = |k: &Knob| {
|
||||
let v = self.get(k);
|
||||
match k.labels.get(v as usize) {
|
||||
Some(label) => format!("{} = {} ({label})", k.name, trim(v)),
|
||||
None => format!("{} = {}", k.name, trim(v)),
|
||||
}
|
||||
};
|
||||
g.knobs.iter().map(line).collect::<Vec<_>>().join("\n")
|
||||
}
|
||||
}
|
||||
|
||||
const DEFAULT: &str = "Default";
|
||||
|
||||
fn trim(v: f32) -> String {
|
||||
let s = format!("{v:.3}");
|
||||
let s = s.trim_end_matches('0').trim_end_matches('.');
|
||||
if s == "-0" { "0".into() } else { s.to_owned() }
|
||||
}
|
||||
|
||||
/// ⌘⇧K toggles the layer and Esc closes it. Returns true when it took the key.
|
||||
pub fn key(k: &mut Knobs, ev: &KeyEvent) -> bool {
|
||||
if !cfg!(feature = "panel") {
|
||||
return false;
|
||||
}
|
||||
match ev.key {
|
||||
rune::Key::Command('k' | 'K') if ev.mods.shift => k.toggle(),
|
||||
rune::Key::Escape if k.open => k.close(),
|
||||
_ => return false,
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// [`Knobs::panel_key`] as the keys of a playground story's side column, for
|
||||
/// `rune::Story::side_keys` beside [`inline`]: ↑ ↓ pick a knob, ← → step it (⇧ for 10×), `[`
|
||||
/// and `]` switch groups. It leaves Esc and Tab to the playground, which leaves the column.
|
||||
pub fn side_key<S: 'static>(groups: &'static [Group], lens: fn(&mut S) -> &mut Knobs) -> impl Fn(&mut S, &KeyEvent, &mut rune::Tx) -> bool + 'static {
|
||||
move |s, ev, tx| {
|
||||
if matches!(ev.key, rune::Key::Escape | rune::Key::Tab) {
|
||||
return false;
|
||||
}
|
||||
let taken = lens(s).panel_key(groups, ev);
|
||||
if taken {
|
||||
tx.instant();
|
||||
}
|
||||
taken
|
||||
}
|
||||
}
|
||||
|
||||
/// Without the `panel` feature the layer is an empty element.
|
||||
#[cfg(not(feature = "panel"))]
|
||||
pub fn layer<S: 'static>(_: &Knobs, _: &'static [Group], _: Style, _: fn(&mut S) -> &mut Knobs) -> rune::El {
|
||||
rune::el().key("knobs-layer")
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "panel"))]
|
||||
pub fn inline<S: 'static>(_: &Knobs, _: &'static [Group], _: Style, _: fn(&mut S) -> &mut Knobs, _: bool) -> rune::El {
|
||||
rune::el().key("knobs-panel")
|
||||
}
|
||||
|
||||
/// Without the `panel` feature the page shows alone.
|
||||
#[cfg(not(feature = "panel"))]
|
||||
pub fn side<S: 'static>(page: rune::El, _: &Knobs, _: &'static [Group], _: Style, _: fn(&mut S) -> &mut Knobs) -> rune::El {
|
||||
page
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "panel"))]
|
||||
pub fn actions<S: 'static>(_: Style, _: &[Action<S>]) -> rune::El {
|
||||
rune::el().key("knobs-actions")
|
||||
}
|
||||
|
||||
#[cfg(all(test, feature = "panel"))]
|
||||
#[path = "tests.rs"]
|
||||
mod tests;
|
||||
+399
@@ -0,0 +1,399 @@
|
||||
//! The rows every panel shares (the side panel, the floating one, a storybook's column): a
|
||||
//! group's preset tray and its card of knobs. Rows lay out for the card width they're given.
|
||||
|
||||
use rune::{Color, Drag, El, Phase, TextStyle, Tx, col, el, row, spacer, text};
|
||||
|
||||
use crate::{DEFAULT, Group, Knob, Knobs, Style};
|
||||
|
||||
pub(crate) const PAD: f32 = 10.0;
|
||||
pub(crate) const ROW: f32 = 32.0;
|
||||
|
||||
pub(crate) const LABEL: TextStyle = TextStyle::new(12.0, 450.0).lh(16.0);
|
||||
pub(crate) const VALUE: TextStyle = TextStyle::new(11.5, 450.0).lh(16.0).features("'tnum' 1");
|
||||
pub(crate) const TITLE: TextStyle = TextStyle::new(13.0, 600.0).lh(18.0).tracking(-0.13);
|
||||
pub(crate) const CHIP: TextStyle = TextStyle::new(12.0, 500.0).lh(16.0);
|
||||
const CHIP_ON: TextStyle = TextStyle::new(12.0, 600.0).lh(16.0);
|
||||
/// The number key over each option of the keyboard's choice.
|
||||
const DIGIT: TextStyle = TextStyle::new(8.5, 600.0).lh(10.0).features("'tnum' 1");
|
||||
|
||||
/// More options than this get a stepper, with the whole list a click away.
|
||||
const LONG: usize = 10;
|
||||
/// Option cells: their padding, the gap between them and the well's inset.
|
||||
const OPT_PAD: f32 = 7.0;
|
||||
const OPT_GAP: f32 = 2.0;
|
||||
const WELL: f32 = 2.0;
|
||||
|
||||
/// How wide `s` sets in `style`.
|
||||
fn text_w(s: &str, style: TextStyle) -> f32 {
|
||||
rune::text::measure(s, &[], style, None).0
|
||||
}
|
||||
|
||||
/// What the rows need: the knobs, the look, the way back to the app's `Knobs`, and the card's
|
||||
/// width.
|
||||
pub(crate) struct Ctx<'a, S> {
|
||||
pub k: &'a Knobs,
|
||||
pub st: Style,
|
||||
pub lens: fn(&mut S) -> &mut Knobs,
|
||||
pub w: f32,
|
||||
}
|
||||
|
||||
impl<S> Clone for Ctx<'_, S> {
|
||||
fn clone(&self) -> Self {
|
||||
*self
|
||||
}
|
||||
}
|
||||
impl<S> Copy for Ctx<'_, S> {}
|
||||
|
||||
/// Which knob a row is: its group's name and index among the groups, and its own index.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Id {
|
||||
group: &'static str,
|
||||
g: usize,
|
||||
i: usize,
|
||||
}
|
||||
|
||||
/// Using a knob makes it the panel's group and the keyboard's knob.
|
||||
fn touch(k: &mut Knobs, id: Id) {
|
||||
if k.group.as_deref() != Some(id.group) {
|
||||
k.group = Some(id.group.to_owned());
|
||||
}
|
||||
k.cursor = id.i;
|
||||
k.at = Some(crate::tree::Node::Knob(id.g, id.i));
|
||||
k.kbd = true;
|
||||
}
|
||||
|
||||
/// Hovering a knob shows what it does under the side panel; right-clicking it puts it back to
|
||||
/// its default.
|
||||
fn hovers<S: 'static>(e: El, lens: fn(&mut S) -> &mut Knobs, id: Id, d: Knob) -> El {
|
||||
let name = d.name;
|
||||
e.on_secondary_press(move |s: &mut S, _, tx: &mut Tx| {
|
||||
tx.instant();
|
||||
let k = lens(s);
|
||||
touch(k, id);
|
||||
k.reset_knob(&d);
|
||||
})
|
||||
.on_hover_change(move |s: &mut S, inside, tx: &mut Tx| {
|
||||
tx.instant();
|
||||
let k = lens(s);
|
||||
if inside {
|
||||
k.hot = Some(name.to_owned());
|
||||
} else if k.hot.as_deref() == Some(name) {
|
||||
k.hot = None;
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Knobs `show` of `g` (group `gi` of the panel's) on one card; `mark` is the keyboard's knob.
|
||||
pub(crate) fn card<S: 'static>(mut cx: Ctx<'_, S>, g: &Group, gi: usize, show: &[usize], mark: Option<usize>) -> El {
|
||||
// The rows that choose a layout by width (a choice: beside its label, or a grid) read the
|
||||
// card's laid-out width; `cx.w` is where the first frame starts. The read is rounded, so
|
||||
// only a real resize rebuilds.
|
||||
if let Some(w) = rune::memo::layout_with("knobs-card", |r| r[2].round()) {
|
||||
cx.w = w;
|
||||
}
|
||||
let mut card = col().key("knobs-card").w_full().radius(8.0).fill(cx.st.fill).clip_rounded(8.0);
|
||||
for (n, &i) in show.iter().enumerate() {
|
||||
let d = &g.knobs[i];
|
||||
let id = Id { group: g.name, g: gi, i };
|
||||
let mut r = if d.labels.is_empty() { slider(cx, id, *d) } else { choice(cx, id, *d) };
|
||||
if mark == Some(i) {
|
||||
r = r.fill(cx.st.fill_hover);
|
||||
}
|
||||
if n > 0 {
|
||||
r = r.child(el().key("rule").absolute(0.0, 0.0).w_full().h(0.5).fill(cx.st.rule));
|
||||
}
|
||||
card = card.child(r);
|
||||
}
|
||||
card
|
||||
}
|
||||
|
||||
pub(crate) fn presets<S: 'static>(cx: Ctx<'_, S>, g: &Group) -> El {
|
||||
let (k, st, lens) = (cx.k, cx.st, cx.lens);
|
||||
let active = k.active(g);
|
||||
let names: Vec<(String, bool)> = std::iter::once((DEFAULT.to_owned(), false))
|
||||
.chain(g.presets.iter().map(|p| (p.name.to_owned(), false)))
|
||||
.chain(k.saved.get(g.name).into_iter().flatten().map(|(n, _)| (n.clone(), true)))
|
||||
.collect();
|
||||
let mut tray = row().key("knobs-presets").w_full().flex_wrap().gap(2.0).padding(2.0).radius(8.0).fill(st.inset);
|
||||
for (i, (name, saved)) in names.into_iter().enumerate() {
|
||||
let on = name == active;
|
||||
let drifted = on && k.drifted(g, &name);
|
||||
let (g1, g2, n1, n2) = (*g, *g, name.clone(), name.clone());
|
||||
let shown = if name == DEFAULT { g.default_label.to_owned() } else { name };
|
||||
let mut chip = row()
|
||||
.key(format!("knobs-preset-{i}"))
|
||||
.role("button")
|
||||
.label(shown.clone())
|
||||
.grow(1.0)
|
||||
.min_w(52.0)
|
||||
.h(24.0)
|
||||
.px(8.0)
|
||||
.gap(5.0)
|
||||
.center()
|
||||
.radius(6.0)
|
||||
.fill(if on { st.raised } else { Color::TRANSPARENT })
|
||||
.hover(st.fill_hover)
|
||||
.on_press_tx(move |s: &mut S, tx: &mut Tx| {
|
||||
tx.instant();
|
||||
lens(s).apply(&g1, &n1);
|
||||
})
|
||||
.child(text(shown).font(if on { CHIP_ON } else { CHIP }).color(if on { st.fg } else { st.fg2 }));
|
||||
if drifted {
|
||||
chip = chip.child(el().key("drift").w(4.0).h(4.0).radius(2.0).fill(st.fg3));
|
||||
}
|
||||
if saved {
|
||||
chip = chip.help("Right-click to delete").on_secondary_press(move |s: &mut S, _, tx: &mut Tx| {
|
||||
tx.instant();
|
||||
lens(s).delete(&g2, &n2);
|
||||
});
|
||||
}
|
||||
tray = tray.child(chip);
|
||||
}
|
||||
let g = *g;
|
||||
tray.child(
|
||||
row()
|
||||
.key("knobs-save")
|
||||
.role("button")
|
||||
.label("Save preset")
|
||||
.help("Save preset")
|
||||
.w(28.0)
|
||||
.h(24.0)
|
||||
.center()
|
||||
.radius(6.0)
|
||||
.hover(st.fill_hover)
|
||||
.on_press_tx(move |s: &mut S, tx: &mut Tx| {
|
||||
tx.instant();
|
||||
lens(s).save(&g);
|
||||
})
|
||||
.child(text("+").font(TITLE).color(st.fg3)),
|
||||
)
|
||||
}
|
||||
|
||||
fn readout(d: &Knob, v: f32) -> String {
|
||||
let span = d.max - d.min;
|
||||
if d.step >= 1.0 || span > 20.0 {
|
||||
format!("{v:.0}")
|
||||
} else if span > 2.0 {
|
||||
format!("{v:.1}")
|
||||
} else {
|
||||
format!("{v:.2}")
|
||||
}
|
||||
}
|
||||
|
||||
fn slider<S: 'static>(cx: Ctx<'_, S>, id: Id, d: Knob) -> El {
|
||||
let i = id.i;
|
||||
let (k, st, lens) = (cx.k, cx.st, cx.lens);
|
||||
let v = k.get(&d);
|
||||
let frac = if d.max > d.min { (v - d.min) / (d.max - d.min) } else { 0.0 };
|
||||
let hot = k.hot.as_deref() == Some(d.name);
|
||||
let held = k.drag.as_deref() == Some(d.name);
|
||||
let changed = (v - d.default).abs() > 1e-4;
|
||||
let tint = if held { st.slider_active } else if hot { st.slider_hover } else { st.slider };
|
||||
hovers(el().key(format!("knobs-knob-{i}")).role("slider").label(d.title()).w_full().h(ROW).fill(if hot || held { st.fill_hover } else { Color::TRANSPARENT }), lens, id, d)
|
||||
.on_drag(move |s: &mut S, g: &mut Drag, tx: &mut Tx| {
|
||||
tx.instant();
|
||||
let k = lens(s);
|
||||
let span = d.max - d.min;
|
||||
match g.phase {
|
||||
Phase::Down => {
|
||||
k.checkpoint();
|
||||
touch(k, id);
|
||||
g.data = k.get(&d);
|
||||
k.drag = Some(d.name.to_owned());
|
||||
}
|
||||
Phase::Move => k.set(&d, g.data + g.dx / g.w.max(1.0) * span),
|
||||
Phase::Up => {
|
||||
if g.cancelled() {
|
||||
k.set(&d, g.data);
|
||||
} else if g.dx.abs() < 2.0 && g.dy.abs() < 2.0 {
|
||||
k.set(&d, d.min + (g.x / g.w.max(1.0)).clamp(0.0, 1.0) * span);
|
||||
}
|
||||
if k.undo.last() == Some(&k.values) {
|
||||
k.undo.pop();
|
||||
}
|
||||
k.drag = None;
|
||||
}
|
||||
}
|
||||
})
|
||||
.child(
|
||||
row().key("fill").absolute(0.0, 0.0).w_frac(frac).h(ROW).fill(tint).child(spacer()).child(
|
||||
el().key("handle")
|
||||
.w(3.0)
|
||||
.min_w(3.0)
|
||||
.h(ROW - 12.0)
|
||||
.mt(6.0)
|
||||
.radius(1.5)
|
||||
.fill(st.handle)
|
||||
.opacity(if held { 0.95 } else if hot { 0.65 } else { 0.0 }),
|
||||
),
|
||||
)
|
||||
.child(
|
||||
row()
|
||||
.key("text")
|
||||
.absolute(0.0, 0.0)
|
||||
.w_full()
|
||||
.h(ROW)
|
||||
.px(PAD)
|
||||
.gap(8.0)
|
||||
.center_y()
|
||||
.child(text(d.title()).font(LABEL).color(st.fg2).truncate_fade().shrink())
|
||||
.child(spacer())
|
||||
.child(text(readout(&d, v)).font(VALUE).color(if hot || held || changed { st.fg } else { st.fg2 })),
|
||||
)
|
||||
}
|
||||
|
||||
/// How a choice lays out at a card width.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) enum Shape {
|
||||
/// The options beside the label.
|
||||
Inline,
|
||||
/// The label over a grid of equal cells, `cols` across.
|
||||
Grid { cols: usize },
|
||||
/// The label and a stepper over the current option; the grid shows when expanded.
|
||||
Long { cols: usize },
|
||||
}
|
||||
|
||||
/// The narrowest cell that fits every option, the settled dot included.
|
||||
fn cell_w(d: &Knob, dot: bool) -> f32 {
|
||||
d.labels.iter().map(|l| text_w(l, CHIP_ON)).fold(0.0, f32::max) + 2.0 * OPT_PAD + if dot { 9.0 } else { 0.0 }
|
||||
}
|
||||
|
||||
/// Columns for `n` cells of at least `cell` in `room`, balanced so the rows come out even
|
||||
/// (six options in rows of three, not four and two).
|
||||
fn columns(n: usize, cell: f32, room: f32) -> usize {
|
||||
let fit = (((room - 2.0 * WELL + OPT_GAP) / (cell + OPT_GAP)).floor() as usize).clamp(1, n.max(1));
|
||||
let rows = n.div_ceil(fit);
|
||||
n.div_ceil(rows)
|
||||
}
|
||||
|
||||
pub(crate) fn shape(d: &Knob, w: f32, dot: bool) -> Shape {
|
||||
let n = d.labels.len();
|
||||
let inline_need: f32 = d.labels.iter().map(|l| text_w(l, CHIP_ON) + 2.0 * OPT_PAD).sum::<f32>() + OPT_GAP * (n.saturating_sub(1)) as f32 + 2.0 * WELL + if dot { 9.0 } else { 0.0 };
|
||||
if inline_need + text_w(d.title(), LABEL) + 2.0 * PAD + 16.0 <= w {
|
||||
return Shape::Inline;
|
||||
}
|
||||
let cols = columns(n, cell_w(d, dot), w - 2.0 * (PAD - 6.0));
|
||||
if n > LONG { Shape::Long { cols } } else { Shape::Grid { cols } }
|
||||
}
|
||||
|
||||
fn choice<S: 'static>(cx: Ctx<'_, S>, id: Id, d: Knob) -> El {
|
||||
let lens = cx.lens;
|
||||
// A click anywhere on the row, not only on an option, puts the keyboard on it for ←→.
|
||||
hovers(choice_row(cx, id, d), lens, id, d).on_press_tx(move |s: &mut S, tx: &mut Tx| {
|
||||
tx.instant();
|
||||
touch(lens(s), id);
|
||||
})
|
||||
}
|
||||
|
||||
fn choice_row<S: 'static>(cx: Ctx<'_, S>, id: Id, d: Knob) -> El {
|
||||
let i = id.i;
|
||||
let (k, st, lens, w) = (cx.k, cx.st, cx.lens, cx.w);
|
||||
let at = k.get(&d).round() as usize;
|
||||
let settled = k.settled.as_ref().and_then(|m| m.get(d.name)).map(|v| d.clamp(*v).round() as usize);
|
||||
let shape = shape(&d, w, settled.is_some());
|
||||
// The keyboard's choice numbers its options for 1–9, in the chip's left padding so nothing moves.
|
||||
let keyed = k.at() == Some(crate::tree::Node::Knob(id.g, id.i));
|
||||
let option = |j: usize, label: &'static str, cell: Option<f32>| {
|
||||
let on = j == at;
|
||||
let mut o = row()
|
||||
.key(format!("opt-{j}"))
|
||||
.role("button")
|
||||
.label(label)
|
||||
.h(22.0)
|
||||
.px(OPT_PAD)
|
||||
.gap(5.0)
|
||||
.center()
|
||||
.radius(5.0)
|
||||
.fill(if on { st.raised } else { Color::TRANSPARENT })
|
||||
.hover(st.fill_hover)
|
||||
.on_hover_change(move |s: &mut S, inside, tx: &mut Tx| {
|
||||
tx.instant();
|
||||
let k = lens(s);
|
||||
if inside {
|
||||
k.hot = Some(d.name.to_owned());
|
||||
k.hot_opt = Some((d.name.to_owned(), j));
|
||||
} else if k.hot_opt.as_ref().is_some_and(|(n, o)| *n == d.name && *o == j) {
|
||||
k.hot_opt = None;
|
||||
}
|
||||
})
|
||||
.on_press_tx(move |s: &mut S, tx: &mut Tx| {
|
||||
tx.instant();
|
||||
let k = lens(s);
|
||||
k.checkpoint();
|
||||
touch(k, id);
|
||||
k.set(&d, j as f32);
|
||||
})
|
||||
.child(text(label).font(CHIP).color(if on { st.fg } else { st.fg2 }).truncate_fade().shrink())
|
||||
.children((settled == Some(j)).then(|| el().key("current").w(4.0).h(4.0).radius(2.0).fill(st.fg3)))
|
||||
.children((keyed && j < 9).then(|| text((j + 1).to_string()).key("digit").font(DIGIT).color(st.fg3).absolute(1.5, 1.5)));
|
||||
if let Some(cw) = cell {
|
||||
o = o.w(cw);
|
||||
}
|
||||
o
|
||||
};
|
||||
let grid = |cols: usize| {
|
||||
let room = w - 2.0 * (PAD - 6.0) - 2.0 * WELL;
|
||||
let cw = (room - OPT_GAP * (cols - 1) as f32) / cols as f32;
|
||||
let mut g = col().key("seg").w_full().padding(WELL).gap(OPT_GAP).radius(7.0).fill(st.inset);
|
||||
for (r, chunk) in d.labels.chunks(cols).enumerate() {
|
||||
let mut line = row().key(format!("line-{r}")).gap(OPT_GAP);
|
||||
for (c, label) in chunk.iter().enumerate() {
|
||||
line = line.child(option(r * cols + c, label, Some(cw)));
|
||||
}
|
||||
g = g.child(line);
|
||||
}
|
||||
g
|
||||
};
|
||||
let title = text(d.title()).font(LABEL).color(st.fg2).truncate_fade().shrink();
|
||||
match shape {
|
||||
Shape::Inline => {
|
||||
let mut seg = row().key("seg").h(26.0).padding(WELL).gap(OPT_GAP).radius(7.0).fill(st.inset);
|
||||
for (j, label) in d.labels.iter().enumerate() {
|
||||
seg = seg.child(option(j, label, None));
|
||||
}
|
||||
row().key(format!("knobs-knob-{i}")).w_full().h(ROW + 4.0).pl(PAD).pr(PAD - 4.0).gap(8.0).center_y().child(title).child(spacer()).child(seg)
|
||||
}
|
||||
Shape::Grid { cols } => col().key(format!("knobs-knob-{i}")).w_full().px(PAD - 6.0).pb(6.0).child(row().key("head").w_full().h(ROW - 4.0).px(6.0).center_y().child(title)).child(grid(cols)),
|
||||
Shape::Long { cols } => {
|
||||
let open = k.expanded.as_deref() == Some(d.name);
|
||||
let n = d.labels.len();
|
||||
let step = move |by: i32| {
|
||||
move |s: &mut S, tx: &mut Tx| {
|
||||
tx.instant();
|
||||
let k = lens(s);
|
||||
let at = k.get(&d).round() as i32;
|
||||
k.checkpoint();
|
||||
touch(k, id);
|
||||
k.set(&d, (at + by).rem_euclid(n as i32) as f32);
|
||||
}
|
||||
};
|
||||
let arrow = |key: &str, glyph: &'static str, by: i32| {
|
||||
row().key(key).role("button").label(if by < 0 { "Previous" } else { "Next" }).w(22.0).h(22.0).center().radius(5.0).hover(st.fill_hover).on_press_tx(step(by)).child(text(glyph).font(CHIP).color(st.fg2))
|
||||
};
|
||||
let name = d.name;
|
||||
let current = row()
|
||||
.key("current")
|
||||
.role("button")
|
||||
.label("Show all options")
|
||||
.help("Show all options")
|
||||
.h(22.0)
|
||||
.px(8.0)
|
||||
.gap(6.0)
|
||||
.center()
|
||||
.radius(5.0)
|
||||
.fill(if open { st.raised } else { Color::TRANSPARENT })
|
||||
.hover(st.fill_hover)
|
||||
.on_press_tx(move |s: &mut S, tx: &mut Tx| {
|
||||
tx.instant();
|
||||
let k = lens(s);
|
||||
k.expanded = if k.expanded.as_deref() == Some(name) { None } else { Some(name.to_owned()) };
|
||||
})
|
||||
.child(text(d.labels.get(at).copied().unwrap_or("")).font(CHIP).color(st.fg))
|
||||
.child(text(format!("{}/{n}", at + 1)).font(VALUE).color(st.fg3));
|
||||
let stepper = row().key("stepper").h(26.0).padding(WELL).gap(OPT_GAP).center_y().radius(7.0).fill(st.inset).child(arrow("prev", "‹", -1)).child(current).child(arrow("next", "›", 1));
|
||||
let head = row().key("head").w_full().h(ROW + 4.0).pl(6.0).gap(8.0).center_y().child(title).child(spacer()).child(stepper);
|
||||
let c = col().key(format!("knobs-knob-{i}")).w_full().px(PAD - 6.0).child(head);
|
||||
if open { c.pb(6.0).child(grid(cols)) } else { c }
|
||||
}
|
||||
}
|
||||
}
|
||||
+247
@@ -0,0 +1,247 @@
|
||||
//! ⌘⇧K as a side panel down the window's right edge: it slides in on [`Knobs::slide`] and pushes the
|
||||
//! page over, its left edge drags to resize it, and its groups are listed in one scroll (see
|
||||
//! [`crate::tree`] for what's listed and folded, [`crate::side_list`] for how). The group last
|
||||
//! used is the panel's: its name heads the panel, over its presets, and Random and Reset act
|
||||
//! on it. Under the list, a line says what the hovered or keyboard's knob does.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use rune::{Cursor, Drag, El, Phase, ScrollSpec, Spring, SpringPair, TextStyle, Transition, Tx, col, edit_access, el, row, spacer, text, text_input};
|
||||
|
||||
use crate::rows::{Ctx, LABEL, PAD, VALUE, presets};
|
||||
use crate::side_list::{list, tabs};
|
||||
use crate::tree::{Did, Node, Plan, plan};
|
||||
use crate::view::{head, overlay};
|
||||
use crate::{Group, Knob, Knobs, SIDE_MAX, SIDE_MIN, Style};
|
||||
|
||||
/// The panel's inset from its edges.
|
||||
pub(crate) const INSET: f32 = 12.0;
|
||||
const ABOUT: TextStyle = TextStyle::new(12.0, 450.0).lh(16.0);
|
||||
const ABOUT_TITLE: TextStyle = TextStyle::new(12.0, 600.0).lh(16.0);
|
||||
|
||||
pub(crate) fn section_key(i: usize) -> String {
|
||||
format!("knobs-sec-{i}")
|
||||
}
|
||||
|
||||
/// Where the keyboard's row is, to scroll it into view.
|
||||
fn node_key(n: Node, groups: &[Group]) -> String {
|
||||
match n {
|
||||
Node::Page(p) => format!("knobs-page-{}", groups.iter().position(|g| g.page() == p).unwrap_or(0)),
|
||||
Node::Group(g) => format!("{}/head", section_key(g)),
|
||||
Node::Knob(g, i) => format!("{}/body/knobs-card/knobs-knob-{i}", section_key(g)),
|
||||
}
|
||||
}
|
||||
|
||||
/// `page` with the knobs beside it: put it where the page would go, filling the window. Read
|
||||
/// [`Knobs::side_room`] for the width the page loses while it's open.
|
||||
pub fn side<S: 'static>(page: El, k: &Knobs, groups: &'static [Group], st: Style, lens: fn(&mut S) -> &mut Knobs) -> El {
|
||||
let w = k.side_w();
|
||||
let host = col().key("knobs-page").grow(1.0).shrink().min_w(0.0).h_full().min_h(0.0).child(page).child(overlay(k, groups, st, lens, "knobs-over"));
|
||||
// The panel keeps its width and is anchored to the box's left edge, so as the box opens the
|
||||
// panel slides in from the right with it; closed, it waits off the window's edge.
|
||||
// Shut, the panel isn't built: it was a few hundred elements every commit of every app.
|
||||
// Its removal holds it through the slide out.
|
||||
let slide = k.slide();
|
||||
let panel = k.open.then(|| {
|
||||
let out = Transition::identity().hold_layout().springs(SpringPair::new(slide, Spring::new(slide.duration * 1.4, 0.0)));
|
||||
panel(k, groups, st, lens, w).transition(out)
|
||||
});
|
||||
let edge = el()
|
||||
.key("knobs-edge")
|
||||
.absolute(0.0, 0.0)
|
||||
.w(6.0)
|
||||
.h_full()
|
||||
.cursor(Cursor::ResizeColumn)
|
||||
.help("Drag to resize; double-click for the default width")
|
||||
.on_drag(move |s: &mut S, g: &mut Drag, tx: &mut Tx| {
|
||||
tx.instant();
|
||||
let k = lens(s);
|
||||
match g.phase {
|
||||
Phase::Down => g.data = k.side_w(),
|
||||
Phase::Move => k.width = (g.data - g.dx).clamp(SIDE_MIN, SIDE_MAX).round(),
|
||||
Phase::Up if g.cancelled() => k.width = g.data,
|
||||
Phase::Up => {}
|
||||
}
|
||||
})
|
||||
.on_double_press(move |s: &mut S| lens(s).width = 0.0);
|
||||
let mut bx = el().key("knobs-side").w(if k.open { w } else { 0.0 }).h_full().clip_soft(0.0).motion(slide).children(panel);
|
||||
if k.open {
|
||||
bx = bx.child(edge);
|
||||
}
|
||||
row().key("knobs-frame").w_full().h_full().min_h(0.0).child(host).child(bx)
|
||||
}
|
||||
|
||||
/// The groups whose part of the window shows now: their region is laid out and overlaps the
|
||||
/// page beside the panel.
|
||||
fn seen(k: &Knobs, groups: &[Group]) -> BTreeSet<usize> {
|
||||
if !k.open {
|
||||
return BTreeSet::new();
|
||||
}
|
||||
let Some(page) = rune::memo::window_layout("knobs-page") else { return BTreeSet::new() };
|
||||
let overlaps = |r: [f32; 4]| r[2] > 0.0 && r[3] > 0.0 && r[0] < page[0] + page[2] && r[0] + r[2] > page[0] && r[1] < page[1] + page[3] && r[1] + r[3] > page[1];
|
||||
(0..groups.len()).filter(|&g| !groups[g].region.is_empty() && rune::memo::window_layout(groups[g].region).is_some_and(overlaps)).collect()
|
||||
}
|
||||
|
||||
fn panel<S: 'static>(k: &Knobs, groups: &'static [Group], st: Style, lens: fn(&mut S) -> &mut Knobs, w: f32) -> El {
|
||||
let g = k.current(groups);
|
||||
let title = match g {
|
||||
Some(g) => g.name,
|
||||
None => "Pick a part",
|
||||
};
|
||||
let cx = Ctx { k, st, lens, w: w - 2.0 * INSET };
|
||||
let plan = plan(k, groups, seen(k, groups));
|
||||
let mut top = col().key("knobs-top").w_full().px(INSET).pt(INSET).pb(8.0).gap(PAD).child(head(k, groups, st, lens, g, title, true).pl(PAD));
|
||||
top = match g {
|
||||
Some(g) => top.child(presets(cx, &g)),
|
||||
None => top.child(text("Click a part of the window to tune it.").key("knobs-hint").font(LABEL).color(st.fg3).px(PAD).h(28.0)),
|
||||
};
|
||||
top = top.child(filter(k, groups, st, lens, &plan));
|
||||
if !plan.tabs.is_empty() && k.query.is_empty() {
|
||||
top = top.child(tabs(st, lens, &plan));
|
||||
}
|
||||
let scroll = col().key("knobs-scroll").w_full().grow(1.0).min_h(0.0).scroll(ScrollSpec { stick_bottom: false }).scroll_edge_fade(24.0).child(list(cx, groups, &plan));
|
||||
let keys = plan.clone();
|
||||
col()
|
||||
.key("knobs-panel")
|
||||
.absolute(0.0, 0.0)
|
||||
.w(w)
|
||||
.h_full()
|
||||
.min_h(0.0)
|
||||
.fill(st.bg)
|
||||
.focusable(true)
|
||||
.no_focus_ring()
|
||||
.on_key(move |s: &mut S, ev, tx: &mut Tx| {
|
||||
let k = lens(s);
|
||||
if !k.open {
|
||||
return false;
|
||||
}
|
||||
let did = k.tree_key(groups, &keys, ev);
|
||||
took(k, did, groups, tx)
|
||||
})
|
||||
// The pointer moving takes the highlight from the keyboard's row, so only one row is lit.
|
||||
.on_pointer_move_local(move |s: &mut S, _, tx: &mut Tx| {
|
||||
let k = lens(s);
|
||||
if k.kbd && k.drag.is_none() {
|
||||
k.kbd = false;
|
||||
tx.instant();
|
||||
} else {
|
||||
tx.live_only();
|
||||
}
|
||||
})
|
||||
.child(el().key("knobs-rim").absolute(0.0, 0.0).w(0.5).h_full().fill(st.border))
|
||||
.child(top)
|
||||
.child(scroll)
|
||||
.child(about(k, groups, st))
|
||||
}
|
||||
|
||||
/// What a panel key did, shown: the motion it asks for and the keyboard's row in view. True if
|
||||
/// the key was taken.
|
||||
fn took(k: &mut Knobs, did: Did, groups: &[Group], tx: &mut Tx) -> bool {
|
||||
match did {
|
||||
Did::Not => return false,
|
||||
Did::Now if k.open => tx.instant(),
|
||||
Did::Now => tx.motion(k.slide()),
|
||||
Did::Fold => tx.motion(k.fold_spring()),
|
||||
}
|
||||
if let Some(n) = k.at() {
|
||||
tx.scroll_into_view(node_key(n, groups));
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// How to start typing, or the field: a single-line text field while it edits, with the
|
||||
/// keys the panel keeps (↑ ↓ Tab, Return, Esc) handled before it, and the matches counted on
|
||||
/// the right.
|
||||
fn filter<S: 'static>(k: &Knobs, groups: &'static [Group], st: Style, lens: fn(&mut S) -> &mut Knobs, plan: &Plan) -> El {
|
||||
let typed = !k.query.is_empty();
|
||||
let mut r = row().key("knobs-filter").w_full().h(28.0).px(PAD).gap(8.0).center_y().radius(7.0).fill(st.inset);
|
||||
if k.filtering {
|
||||
let keys = plan.clone();
|
||||
let mut edit = k.edit().clone();
|
||||
if edit.text != k.query {
|
||||
edit.replace_text(k.query.clone());
|
||||
}
|
||||
let field = text_input(&edit, LABEL)
|
||||
.key("knobs-filter-input")
|
||||
.single_line()
|
||||
.color(st.fg)
|
||||
.caret(st.fg2, st.fg.alpha(0.22))
|
||||
.grow(1.0)
|
||||
.min_w(0.0)
|
||||
.on_edit(edit_access(move |s: &mut S| lens(s).edit_mut()))
|
||||
.on_input_key(move |s: &mut S, ev, tx: &mut Tx| {
|
||||
let k = lens(s);
|
||||
k.sync_edit();
|
||||
let did = k.filter_key(groups, &keys, ev);
|
||||
took(k, did, groups, tx)
|
||||
});
|
||||
let keys = plan.clone();
|
||||
let field = field.on_input_change(move |s: &mut S, tx: &mut Tx| {
|
||||
tx.instant();
|
||||
let k = lens(s);
|
||||
k.edited();
|
||||
k.kbd = true;
|
||||
k.refilter(groups, &keys);
|
||||
});
|
||||
// Taking the field out gives focus back to the panel.
|
||||
r = r.child(el().key("knobs-filter-field").grow(1.0).min_w(0.0).h_full().center_y().focus_return("knobs-panel").child(field));
|
||||
} else {
|
||||
r = r
|
||||
.on_press_tx(move |s: &mut S, tx: &mut Tx| {
|
||||
tx.instant();
|
||||
let k = lens(s);
|
||||
k.kbd = true;
|
||||
k.start_filter();
|
||||
})
|
||||
.child(text(if typed { k.query.clone() } else { "Press / to filter".to_owned() }).font(LABEL).color(if typed { st.fg } else { st.fg3 }).truncate_fade().shrink());
|
||||
}
|
||||
if typed {
|
||||
let n: usize = plan.sections.iter().flat_map(|s| &s.subs).map(|s| s.knobs.len()).sum();
|
||||
if !k.filtering {
|
||||
r = r.child(spacer());
|
||||
}
|
||||
r = r.child(text(if n == 1 { "1 knob".to_owned() } else { format!("{n} knobs") }).font(VALUE).color(st.fg3));
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
/// The knob the pointer is over, or else the keyboard's.
|
||||
fn described<'a>(k: &Knobs, groups: &'a [Group]) -> Option<&'a Knob> {
|
||||
if let Some(h) = k.hot.as_deref() {
|
||||
return groups.iter().flat_map(|g| g.knobs).find(|d| d.name == h);
|
||||
}
|
||||
match k.at() {
|
||||
Some(Node::Knob(g, i)) if k.kbd => groups.get(g).and_then(|g| g.knobs.get(i)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The line under the list: what the knob in hand does, and the option under the pointer
|
||||
/// (or the one picked), or the keys.
|
||||
fn about(k: &Knobs, groups: &[Group], st: Style) -> El {
|
||||
let c = col().key("knobs-about").w_full().h(64.0).px(INSET + PAD).pt(8.0).gap(2.0);
|
||||
match described(k, groups) {
|
||||
Some(d) => {
|
||||
let c = c.child(text(d.title()).font(ABOUT_TITLE).color(st.fg2).truncate_fade());
|
||||
let c = if d.describe().is_empty() { c } else { c.child(text(d.describe()).key("knobs-about-line").font(ABOUT).color(st.fg3).wrap()) };
|
||||
let opt = match &k.hot_opt {
|
||||
Some((n, j)) if *n == d.name => Some(*j),
|
||||
_ if !d.labels.is_empty() => Some(k.get(d).round() as usize),
|
||||
_ => None,
|
||||
};
|
||||
match opt.and_then(|j| Some((d.labels.get(j)?, d.hint(j)))) {
|
||||
Some((label, hint)) if !hint.is_empty() => c.child(text(format!("{label}: {hint}")).key("knobs-about-option").font(ABOUT).color(st.fg2).truncate_fade()),
|
||||
_ => c,
|
||||
}
|
||||
}
|
||||
None => c.child(text("↑↓ move ←→ fold, open or change 1–9 pick / filter").font(ABOUT).color(st.fg3).wrap()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "side_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "filter_tests.rs"]
|
||||
mod filter_tests;
|
||||
+181
@@ -0,0 +1,181 @@
|
||||
//! How the side panel draws its [`Plan`]: pages with their groups under them, captions, tabs.
|
||||
//! A header press folds or opens its section on [`Knobs::fold_spring`]; a folded section keeps
|
||||
//! its rows under a clip that closes to nothing, so they roll up rather than vanish.
|
||||
|
||||
use rune::{Color, El, TextStyle, Tx, col, el, row, spacer, text};
|
||||
|
||||
use crate::rows::{CHIP, Ctx, PAD, VALUE, card};
|
||||
use crate::side::{INSET, section_key};
|
||||
use crate::tree::{Head, Node, Plan, Section, Sub};
|
||||
use crate::view::tool;
|
||||
use crate::icons;
|
||||
use crate::{Group, Knobs, Style};
|
||||
|
||||
const PAGE_H: f32 = 34.0;
|
||||
const GROUP_H: f32 = 30.0;
|
||||
/// How far a page's groups sit in from its header.
|
||||
const NEST: f32 = 12.0;
|
||||
const PAGE: TextStyle = TextStyle::new(13.0, 600.0).lh(18.0);
|
||||
const GROUP: TextStyle = TextStyle::new(12.0, 550.0).lh(16.0);
|
||||
const CAPTION: TextStyle = TextStyle::new(11.0, 600.0).lh(14.0).tracking(0.3);
|
||||
|
||||
pub(crate) fn list<S: 'static>(cx: Ctx<'_, S>, groups: &'static [Group], plan: &Plan) -> El {
|
||||
let mut l = col().key("knobs-sections").w_full().px(INSET).pb(INSET);
|
||||
for s in &plan.sections {
|
||||
l = l.child(section(cx, groups, s));
|
||||
}
|
||||
if plan.sections.iter().all(|s| s.subs.is_empty()) {
|
||||
l = l.child(text("Nothing matches").key("knobs-none").font(GROUP).color(cx.st.fg3).px(PAD).h(GROUP_H));
|
||||
}
|
||||
l
|
||||
}
|
||||
|
||||
/// Rows that fold: open, they take their own height; folded, none, on the fold spring.
|
||||
fn body(open: bool) -> El {
|
||||
let b = col().key("body").w_full().clip_soft(0.0);
|
||||
if open { b } else { b.h(0.0) }
|
||||
}
|
||||
|
||||
fn section<S: 'static>(cx: Ctx<'_, S>, groups: &'static [Group], s: &Section) -> El {
|
||||
let (k, st, lens) = (cx.k, cx.st, cx.lens);
|
||||
let subs = |mut c: El, sticky: f32| {
|
||||
for sub in &s.subs {
|
||||
c = c.child(group(cx, groups, sub, sticky));
|
||||
}
|
||||
c
|
||||
};
|
||||
match s.head {
|
||||
Head::Bare => subs(col().key("knobs-bare").w_full(), 0.0),
|
||||
Head::Caption(c) => subs(col().key(format!("knobs-cap-{c}")).w_full().child(row().key("cap").w_full().h(28.0).px(PAD).items_end().pb(6.0).child(text(c.to_uppercase()).font(CAPTION).color(st.fg3))), 0.0),
|
||||
Head::Page(p) => {
|
||||
let i = groups.iter().position(|g| g.page() == p).unwrap_or(0);
|
||||
let on = k.kbd && k.at() == Some(Node::Page(p));
|
||||
let n: usize = s.subs.iter().map(|x| groups[x.g].knobs.len()).sum();
|
||||
let open = s.open;
|
||||
let header = row()
|
||||
.key("head")
|
||||
.role("button")
|
||||
.label(p)
|
||||
.w_full()
|
||||
.h(PAGE_H)
|
||||
.px(PAD)
|
||||
.gap(7.0)
|
||||
.center_y()
|
||||
.radius(7.0)
|
||||
.fill(if on { st.fill_hover } else { st.bg })
|
||||
.sticky_top(0.0)
|
||||
.on_press_tx(move |s: &mut S, tx: &mut Tx| {
|
||||
let k = lens(s);
|
||||
tx.motion(k.fold_spring());
|
||||
k.set_folded(p, open);
|
||||
k.at = Some(Node::Page(p));
|
||||
k.kbd = true;
|
||||
})
|
||||
.child(text(p).font(PAGE).color(if s.seen { st.fg } else { st.fg2 }).truncate_fade().shrink())
|
||||
.children(s.seen.then(|| dot(st)))
|
||||
.child(spacer())
|
||||
.child(text(n.to_string()).font(VALUE).color(if s.open { st.fg3 } else { st.fg2 }));
|
||||
col().key(format!("knobs-page-{i}")).w_full().child(header).child(subs(body(s.open), PAGE_H))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The on-screen mark beside a name.
|
||||
fn dot(st: Style) -> El {
|
||||
el().key("seen").w(5.0).h(5.0).radius(2.5).fill(st.fg3)
|
||||
}
|
||||
|
||||
/// A group under its page's header: `sticky` is where its header sticks, below the page's.
|
||||
fn group<S: 'static>(cx: Ctx<'_, S>, groups: &'static [Group], sub: &Sub, sticky: f32) -> El {
|
||||
let nested = sticky > 0.0;
|
||||
let (k, st, lens) = (cx.k, cx.st, cx.lens);
|
||||
let g = &groups[sub.g];
|
||||
let name = g.name;
|
||||
let gi = sub.g;
|
||||
let current = k.group.as_deref() == Some(name);
|
||||
let lit = current || k.hover.as_deref() == Some(name);
|
||||
let on = k.kbd && k.at() == Some(Node::Group(gi));
|
||||
let title = if sub.full && !g.under.is_empty() { format!("{} · {}", g.under, name) } else { name.to_owned() };
|
||||
let open = sub.open;
|
||||
let header = row()
|
||||
.key("head")
|
||||
.role("button")
|
||||
.label(name)
|
||||
.w_full()
|
||||
.h(GROUP_H)
|
||||
.pl(if nested { PAD + NEST } else { PAD })
|
||||
.pr(PAD)
|
||||
.gap(7.0)
|
||||
.center_y()
|
||||
.radius(7.0)
|
||||
.fill(if on { st.fill_hover } else { st.bg })
|
||||
.sticky_top(sticky)
|
||||
.on_hover_change(move |s: &mut S, inside, tx: &mut Tx| {
|
||||
tx.instant();
|
||||
let k = lens(s);
|
||||
if inside {
|
||||
k.hover = Some(name.to_owned());
|
||||
} else if k.hover.as_deref() == Some(name) {
|
||||
k.hover = None;
|
||||
}
|
||||
})
|
||||
.on_press_tx(move |s: &mut S, tx: &mut Tx| {
|
||||
let k = lens(s);
|
||||
tx.motion(k.fold_spring());
|
||||
k.set_folded(name, open);
|
||||
k.at = Some(Node::Group(gi));
|
||||
k.kbd = true;
|
||||
if !open {
|
||||
k.group = Some(name.to_owned());
|
||||
}
|
||||
})
|
||||
.on_secondary_press(move |s: &mut S, _, tx: &mut Tx| {
|
||||
tx.instant();
|
||||
lens(s).reset(g);
|
||||
})
|
||||
.child(text(title).font(GROUP).color(if lit { st.fg } else { st.fg2 }).truncate_fade().shrink())
|
||||
.children((sub.seen && !sub.full).then(|| dot(st)))
|
||||
.child(spacer());
|
||||
// Hovered, the header offers Random and Reset for its group in place of its count.
|
||||
let header = if k.hover.as_deref() == Some(name) {
|
||||
header
|
||||
.gap(2.0)
|
||||
.pr(PAD - 6.0)
|
||||
.child(tool(st, "random", &icons::RANDOM, "Random", true, lens, move |k, _| k.random(g)))
|
||||
.child(tool(st, "reset", &icons::RESET, "Reset", k.can_reset(g), lens, move |k, _| k.reset(g)))
|
||||
} else {
|
||||
header.child(text(sub.knobs.len().to_string()).font(VALUE).color(if open { st.fg3 } else { st.fg2 }))
|
||||
};
|
||||
let mark = match k.at() {
|
||||
Some(Node::Knob(g, i)) if k.kbd && g == gi => Some(i),
|
||||
_ => None,
|
||||
};
|
||||
col().key(section_key(gi)).w_full().child(header).child(body(open).child(card(cx, g, gi, &sub.knobs, mark).mb(INSET)))
|
||||
}
|
||||
|
||||
/// The Tabs layout's pages: the one showing underlined, pages with nothing on screen dimmer.
|
||||
pub(crate) fn tabs<S: 'static>(st: Style, lens: fn(&mut S) -> &mut Knobs, plan: &Plan) -> El {
|
||||
let mut r = row().key("knobs-tabs").w_full().flex_wrap().gap(14.0).px(PAD);
|
||||
for (i, (p, seen)) in plan.tabs.iter().enumerate() {
|
||||
let on = plan.tab == Some(*p);
|
||||
let p = *p;
|
||||
r = r.child(
|
||||
col()
|
||||
.key(format!("knobs-tab-{i}"))
|
||||
.role("tab")
|
||||
.label(p)
|
||||
.h(26.0)
|
||||
.on_press_tx(move |s: &mut S, tx: &mut Tx| {
|
||||
tx.instant();
|
||||
let k = lens(s);
|
||||
k.tab = Some(p.to_owned());
|
||||
k.at = None;
|
||||
})
|
||||
.child(spacer())
|
||||
.child(text(p).font(CHIP).color(if on { st.fg } else if *seen { st.fg2 } else { st.fg3 }))
|
||||
.child(spacer())
|
||||
.child(el().key("bar").w_full().h(1.5).radius(1.0).fill(if on { st.handle } else { Color::TRANSPARENT })),
|
||||
);
|
||||
}
|
||||
r
|
||||
}
|
||||
+264
@@ -0,0 +1,264 @@
|
||||
use rune::{Cx, Env, Runtime};
|
||||
|
||||
use super::*;
|
||||
use crate::Knob;
|
||||
use crate::rows::{Shape, shape};
|
||||
|
||||
struct T {
|
||||
knobs: Knobs,
|
||||
}
|
||||
const L: Knob = Knob::new("Left size", 0.0, 10.0, 5.0).label("Left column size");
|
||||
const C: Knob = Knob::choice("Style", &["One", "Two", "Three"], 0).hints(&["The first", "The second", ""]);
|
||||
const R: Knob = Knob::new("Right pad", 0.0, 40.0, 20.0);
|
||||
const GROUPS: &[Group] = &[Group::new("Left", "left", &[L, C]), Group::new("Right", "right", &[R])];
|
||||
|
||||
fn view(s: &T, _: &mut Cx<T>) -> El {
|
||||
let page = row().key("cols").w_full().h_full().child(col().key("left").w(300.0).h_full()).child(col().key("right").grow(1.0).h_full());
|
||||
side(page, &s.knobs, GROUPS, Style::dark(), |s: &mut T| &mut s.knobs)
|
||||
}
|
||||
|
||||
fn settle(rt: &mut Runtime<T>) {
|
||||
for _ in 0..40 {
|
||||
rt.frame(1.0 / 60.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn click(rt: &mut Runtime<T>, key: &str) {
|
||||
let (x, y) = rt.find(key).unwrap_or_else(|| panic!("no {key}"));
|
||||
rt.pointer_move(x, y);
|
||||
settle(rt);
|
||||
rt.pointer_down(x, y);
|
||||
rt.pointer_up(x, y);
|
||||
settle(rt);
|
||||
}
|
||||
|
||||
fn page_w(rt: &mut Runtime<T>) -> f32 {
|
||||
rt.elements().into_iter().find(|e| e.key.as_deref() == Some("knobs-page")).expect("page").target[2]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opening_pushes_the_page_over_and_closing_gives_it_back() {
|
||||
let mut rt = Runtime::new(T { knobs: Knobs::default() }, view, (1000.0, 700.0), Env::new(true, 1.0));
|
||||
settle(&mut rt);
|
||||
assert_eq!(page_w(&mut rt), 1000.0);
|
||||
rt.state.knobs.show();
|
||||
rt.invalidate();
|
||||
settle(&mut rt);
|
||||
assert_eq!(page_w(&mut rt), 1000.0 - crate::SIDE_W);
|
||||
assert_eq!(rt.state.knobs.side_room(), crate::SIDE_W);
|
||||
assert!(rt.find("knobs-sec-0").is_some() && rt.find("knobs-sec-1").is_some(), "every group is a section");
|
||||
rt.state.knobs.close();
|
||||
rt.invalidate();
|
||||
settle(&mut rt);
|
||||
assert_eq!(page_w(&mut rt), 1000.0);
|
||||
}
|
||||
|
||||
fn body(rt: &Runtime<T>, sec: &str) -> f32 {
|
||||
rt.elements().into_iter().find(|e| e.path.contains(sec) && e.key.as_deref() == Some("body")).map(|e| e.rect[3]).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_header_opens_its_group_and_picks_it() {
|
||||
let mut s = T { knobs: Knobs::default() };
|
||||
s.knobs.show();
|
||||
let mut rt = Runtime::new(s, view, (1000.0, 700.0), Env::new(true, 1.0));
|
||||
settle(&mut rt);
|
||||
assert_eq!(body(&rt, "knobs-sec-1"), 0.0, "folded up front, though on screen");
|
||||
click(&mut rt, "knobs-sec-1/head");
|
||||
assert!(rt.state.knobs.unfolded.contains("Right"));
|
||||
assert_eq!(rt.state.knobs.group.as_deref(), Some("Right"));
|
||||
assert!(body(&rt, "knobs-sec-1") > 20.0);
|
||||
click(&mut rt, "knobs-sec-1/head");
|
||||
assert!(rt.state.knobs.folded.contains("Right"));
|
||||
assert_eq!(body(&rt, "knobs-sec-1"), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_panel_reopens_folded_but_for_the_group_last_opened() {
|
||||
let mut s = T { knobs: Knobs::default() };
|
||||
s.knobs.show();
|
||||
let mut rt = Runtime::new(s, view, (1000.0, 700.0), Env::new(true, 1.0));
|
||||
settle(&mut rt);
|
||||
click(&mut rt, "knobs-sec-0/head");
|
||||
click(&mut rt, "knobs-sec-1/head");
|
||||
rt.state.knobs.close();
|
||||
rt.state.knobs.show();
|
||||
rt.invalidate();
|
||||
settle(&mut rt);
|
||||
assert_eq!(body(&rt, "knobs-sec-0"), 0.0);
|
||||
assert!(body(&rt, "knobs-sec-1") > 20.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn using_a_knob_makes_its_group_the_panels() {
|
||||
let mut s = T { knobs: Knobs::default() };
|
||||
s.knobs.show();
|
||||
let mut rt = Runtime::new(s, view, (1000.0, 700.0), Env::new(true, 1.0));
|
||||
settle(&mut rt);
|
||||
click(&mut rt, "knobs-sec-1/head");
|
||||
click(&mut rt, "knobs-sec-1/body/knobs-card/knobs-knob-0");
|
||||
assert_eq!(rt.state.knobs.group.as_deref(), Some("Right"));
|
||||
click(&mut rt, "knobs-random");
|
||||
assert!(rt.state.knobs.values.contains_key("Right pad"), "Random acts on the group in use");
|
||||
assert!(!rt.state.knobs.values.contains_key("Left size"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_edge_drags_to_resize() {
|
||||
let mut s = T { knobs: Knobs::default() };
|
||||
s.knobs.show();
|
||||
let mut rt = Runtime::new(s, view, (1000.0, 700.0), Env::new(true, 1.0));
|
||||
settle(&mut rt);
|
||||
let (x, y) = rt.find("knobs-edge").unwrap();
|
||||
rt.pointer_down(x, y);
|
||||
rt.pointer_move(x - 60.0, y);
|
||||
rt.pointer_up(x - 60.0, y);
|
||||
settle(&mut rt);
|
||||
assert_eq!(rt.state.knobs.side_w(), crate::SIDE_W + 60.0);
|
||||
assert_eq!(page_w(&mut rt), 1000.0 - crate::SIDE_W - 60.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn choices_fit_the_width() {
|
||||
const FEW: Knob = Knob::choice("Edge", &["Fade", "Line", "Tint"], 0);
|
||||
const SIX: Knob = Knob::choice("Question glyph", &["Disc", "? disc", "? mark", "? square", "? ring", "Bang"], 0);
|
||||
const MANY: Knob = Knob::choice("Theme picker style", &["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"], 0);
|
||||
assert_eq!(shape(&FEW, 316.0, false), Shape::Inline);
|
||||
// Six options come out as two even rows of three, not four and two.
|
||||
assert_eq!(shape(&SIX, 316.0, false), Shape::Grid { cols: 3 });
|
||||
assert_eq!(shape(&SIX, 600.0, false), Shape::Inline);
|
||||
assert!(matches!(shape(&MANY, 316.0, false), Shape::Long { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folding_rolls_the_rows_up_on_the_fold_spring() {
|
||||
let mut s = T { knobs: Knobs::default() };
|
||||
s.knobs.show();
|
||||
s.knobs.set_folded("Left", false);
|
||||
let mut rt = Runtime::new(s, view, (1000.0, 700.0), Env::new(true, 1.0));
|
||||
settle(&mut rt);
|
||||
let seen = |rt: &Runtime<T>| rt.elements().into_iter().find(|e| e.path.contains("knobs-sec-0") && e.key.as_deref() == Some("body")).map(|e| e.rect[3]).unwrap();
|
||||
let open = seen(&rt);
|
||||
let (x, y) = rt.find("knobs-sec-0/head").unwrap();
|
||||
rt.pointer_move(x, y);
|
||||
rt.frame(1.0 / 60.0);
|
||||
rt.pointer_down(x, y);
|
||||
rt.pointer_up(x, y);
|
||||
for _ in 0..4 {
|
||||
rt.frame(1.0 / 60.0);
|
||||
}
|
||||
let mid = seen(&rt);
|
||||
assert!(mid > 1.0 && mid < open - 1.0, "partway: {mid} of {open}");
|
||||
settle(&mut rt);
|
||||
assert!(seen(&rt) < 0.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hovering_an_option_says_what_it_does_under_the_list() {
|
||||
let mut s = T { knobs: Knobs::default() };
|
||||
s.knobs.show();
|
||||
s.knobs.set_folded("Left", false);
|
||||
let mut rt = Runtime::new(s, view, (1000.0, 700.0), Env::new(true, 1.0));
|
||||
settle(&mut rt);
|
||||
assert!(rt.find("knobs-about-option").is_none(), "nothing in hand, so the keys show");
|
||||
let (x, y) = rt.find("opt-1").expect("Style's second option");
|
||||
rt.pointer_move(x, y);
|
||||
settle(&mut rt);
|
||||
assert!(rt.find("knobs-about-option").is_some(), "the hovered option's line shows");
|
||||
assert_eq!(C.hint(1), "The second");
|
||||
assert_eq!(C.hint(2), "", "an option without a line says nothing");
|
||||
}
|
||||
|
||||
fn open_left() -> Runtime<T> {
|
||||
let mut s = T { knobs: Knobs::default() };
|
||||
s.knobs.show();
|
||||
s.knobs.set_folded("Left", false);
|
||||
let mut rt = Runtime::new(s, view, (1000.0, 700.0), Env::new(true, 1.0));
|
||||
settle(&mut rt);
|
||||
rt
|
||||
}
|
||||
|
||||
fn rect(rt: &Runtime<T>, suffix: &str) -> [f32; 4] {
|
||||
rt.elements().into_iter().find(|e| e.path.ends_with(suffix) && e.opacity > 0.0).unwrap_or_else(|| panic!("no {suffix}")).rect
|
||||
}
|
||||
|
||||
fn right_click(rt: &mut Runtime<T>, x: f32, y: f32) {
|
||||
rt.pointer_move(x, y);
|
||||
settle(rt);
|
||||
rt.secondary_down(x, y);
|
||||
rt.secondary_up(x, y);
|
||||
settle(rt);
|
||||
}
|
||||
|
||||
fn press(rt: &mut Runtime<T>, key: rune::Key) {
|
||||
rt.key(rune::KeyEvent { key, mods: Default::default() });
|
||||
settle(rt);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn right_clicking_a_knob_puts_only_it_back() {
|
||||
let mut rt = open_left();
|
||||
rt.state.knobs.set(&L, 8.0);
|
||||
rt.state.knobs.set(&C, 2.0);
|
||||
let r = rect(&rt, "knobs-sec-0/body/knobs-card/knobs-knob-0");
|
||||
right_click(&mut rt, r[0] + 40.0, r[1] + r[3] / 2.0);
|
||||
assert_eq!(rt.state.knobs.get(&L), 5.0, "back to its default");
|
||||
assert_eq!(rt.state.knobs.get(&C), 2.0, "its neighbour keeps its value");
|
||||
rt.state.knobs.undo();
|
||||
assert_eq!(rt.state.knobs.get(&L), 8.0, "undoable");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hovered_group_header_offers_random_and_reset() {
|
||||
let mut rt = open_left();
|
||||
rt.state.knobs.set(&L, 8.0);
|
||||
rt.state.knobs.set(&R, 30.0);
|
||||
assert!(rt.find("knobs-sec-0/head/reset").is_none(), "the count shows until hovered");
|
||||
let h = rect(&rt, "knobs-sec-0/head");
|
||||
rt.pointer_move(h[0] + 40.0, h[1] + h[3] / 2.0);
|
||||
settle(&mut rt);
|
||||
click(&mut rt, "knobs-sec-0/head/reset");
|
||||
assert_eq!(rt.state.knobs.get(&L), 5.0, "Reset puts the group back");
|
||||
assert_eq!(rt.state.knobs.get(&R), 30.0, "and leaves other groups alone");
|
||||
assert!(rt.find("knobs-sec-0/body/knobs-card/knobs-knob-0").is_some(), "without folding the group");
|
||||
click(&mut rt, "knobs-sec-0/head/random");
|
||||
assert!(rt.state.knobs.values.contains_key("Left size"), "Random sets the group's knobs");
|
||||
right_click(&mut rt, h[0] + 40.0, h[1] + h[3] / 2.0);
|
||||
assert!(!rt.state.knobs.values.contains_key("Left size"), "right-clicking the header resets it too");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clicking_a_choice_row_puts_the_arrows_on_its_options() {
|
||||
let mut rt = open_left();
|
||||
// Put the keyboard elsewhere first, on the slider above.
|
||||
let r = rect(&rt, "knobs-sec-0/head");
|
||||
click(&mut rt, "knobs-sec-0/head");
|
||||
click(&mut rt, "knobs-sec-0/head");
|
||||
assert_eq!(rt.state.knobs.at, Some(Node::Group(0)), "at {r:?}");
|
||||
let row = rect(&rt, "knobs-sec-0/body/knobs-card/knobs-knob-1");
|
||||
let (x, y) = (row[0] + 20.0, row[1] + row[3] / 2.0);
|
||||
rt.pointer_move(x, y);
|
||||
settle(&mut rt);
|
||||
rt.pointer_down(x, y);
|
||||
rt.pointer_up(x, y);
|
||||
settle(&mut rt);
|
||||
press(&mut rt, rune::Key::Right);
|
||||
assert_eq!(rt.state.knobs.get(&C), 1.0, "→ steps the clicked choice, not the group");
|
||||
press(&mut rt, rune::Key::Right);
|
||||
assert_eq!(rt.state.knobs.get(&C), 2.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_the_pointer_takes_the_highlight_from_the_keyboard() {
|
||||
let mut rt = open_left();
|
||||
click(&mut rt, "knobs-sec-0/head");
|
||||
click(&mut rt, "knobs-sec-0/head");
|
||||
press(&mut rt, rune::Key::Down);
|
||||
assert!(rt.state.knobs.kbd, "the keyboard's row is lit");
|
||||
let row = rect(&rt, "knobs-sec-0/body/knobs-card/knobs-knob-1");
|
||||
rt.pointer_move(row[0] + 30.0, row[1] + row[3] / 2.0);
|
||||
settle(&mut rt);
|
||||
assert!(!rt.state.knobs.kbd, "only the row under the pointer stays lit");
|
||||
press(&mut rt, rune::Key::Down);
|
||||
assert!(rt.state.knobs.kbd, "a key lights the keyboard's row again");
|
||||
}
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
use rune::Color;
|
||||
|
||||
/// The panel's colours. `dark()` is the knobs library's main look.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Style {
|
||||
pub bg: Color,
|
||||
/// Wells: the preset tray.
|
||||
pub inset: Color,
|
||||
/// The selected preset chip.
|
||||
pub raised: Color,
|
||||
pub fg: Color,
|
||||
/// Labels and readouts.
|
||||
pub fg2: Color,
|
||||
/// Group tabs at rest, icons, hints.
|
||||
pub fg3: Color,
|
||||
/// A card of rows.
|
||||
pub fill: Color,
|
||||
pub fill_hover: Color,
|
||||
pub fill_selected: Color,
|
||||
/// A slider's fill at rest, hovered and dragged.
|
||||
pub slider: Color,
|
||||
pub slider_hover: Color,
|
||||
pub slider_active: Color,
|
||||
pub handle: Color,
|
||||
pub border: Color,
|
||||
/// The hairline between rows, over their fills.
|
||||
pub rule: Color,
|
||||
/// The panel's top edge highlight.
|
||||
pub rim: Color,
|
||||
pub shadow: Color,
|
||||
/// The outline around a region.
|
||||
pub outline: Color,
|
||||
}
|
||||
|
||||
impl Style {
|
||||
/// Opaque colours worked out as the browser composites the knobs theme (sRGB), so they read
|
||||
/// the same in Rune's linear blending.
|
||||
pub fn dark() -> Self {
|
||||
let h = |s: &str| rune::color::hex(s).unwrap_or(Color::BLACK);
|
||||
Self {
|
||||
bg: h("#1d1d1f"),
|
||||
inset: h("#161618"),
|
||||
raised: h("#3c3c3e"),
|
||||
fg: h("#fafafa"),
|
||||
fg2: h("#c4c4c6"),
|
||||
fg3: h("#8a8a8d"),
|
||||
fill: h("#29292b"),
|
||||
fill_hover: h("#2f2f31"),
|
||||
fill_selected: h("#363638"),
|
||||
slider: h("#5a5a5c"),
|
||||
slider_hover: h("#626264"),
|
||||
slider_active: h("#6e6e70"),
|
||||
handle: h("#ffffff"),
|
||||
border: h("#2c2c2e"),
|
||||
rule: Color::WHITE.alpha(0.025),
|
||||
rim: h("#3a3a3c"),
|
||||
shadow: Color::BLACK.alpha(0.45),
|
||||
outline: Color::WHITE.alpha(0.55),
|
||||
}
|
||||
}
|
||||
|
||||
/// The light look: white card, dark text, grey fills.
|
||||
pub fn light() -> Self {
|
||||
let h = |s: &str| rune::color::hex(s).unwrap_or(Color::WHITE);
|
||||
Self {
|
||||
bg: h("#ffffff"),
|
||||
inset: h("#ececee"),
|
||||
raised: h("#ffffff"),
|
||||
fg: h("#1d1d1f"),
|
||||
fg2: h("#4a4a4d"),
|
||||
fg3: h("#8a8a8d"),
|
||||
fill: h("#f3f3f5"),
|
||||
fill_hover: h("#ececee"),
|
||||
fill_selected: h("#e4e4e7"),
|
||||
slider: h("#dcdce0"),
|
||||
slider_hover: h("#d3d3d8"),
|
||||
slider_active: h("#c8c8ce"),
|
||||
handle: h("#1d1d1f"),
|
||||
border: h("#e2e2e5"),
|
||||
rule: Color::BLACK.alpha(0.05),
|
||||
rim: h("#ffffff"),
|
||||
shadow: Color::BLACK.alpha(0.18),
|
||||
outline: Color::BLACK.alpha(0.45),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Style {
|
||||
fn default() -> Self {
|
||||
Self::dark()
|
||||
}
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
use super::*;
|
||||
|
||||
const A: Knob = Knob::new("A", 0.0, 10.0, 5.0);
|
||||
const B: Knob = Knob::new("B", -1.0, 1.0, 0.0).step(0.5);
|
||||
const C: Knob = Knob::choice("C", &["x", "y", "z"], 0);
|
||||
const G: Group = Group::new("G", "g", &[A, B, C]).presets(&[Preset { name: "Wide", values: &[("A", 9.0)] }]);
|
||||
|
||||
#[test]
|
||||
fn random_stays_in_range_and_on_steps() {
|
||||
let mut k = Knobs::default();
|
||||
for _ in 0..200 {
|
||||
k.random(&G);
|
||||
for d in G.knobs {
|
||||
let v = k.values[d.name];
|
||||
assert!((d.min..=d.max).contains(&v), "{} = {v}", d.name);
|
||||
}
|
||||
assert_eq!((k.values["B"] * 2.0).fract(), 0.0);
|
||||
assert_eq!(k.values["C"].fract(), 0.0);
|
||||
}
|
||||
let before = k.values.clone();
|
||||
k.random(&G);
|
||||
k.undo();
|
||||
assert_eq!(k.values, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn presets_reset_and_undo() {
|
||||
let mut k = Knobs::default();
|
||||
k.apply(&G, "Wide");
|
||||
assert_eq!(k.values.get("A"), Some(&9.0));
|
||||
assert_eq!(k.active(&G), "Wide");
|
||||
k.set(&A, 2.0);
|
||||
assert!(k.drifted(&G, "Wide"));
|
||||
k.reset(&G);
|
||||
assert_eq!(k.get(&A), 9.0, "reset goes back to the active preset first");
|
||||
k.reset(&G);
|
||||
assert!(k.values.is_empty());
|
||||
assert_eq!(k.active(&G), "Default");
|
||||
k.undo();
|
||||
assert_eq!(k.get(&A), 9.0);
|
||||
k.set(&A, 3.0);
|
||||
let name = k.save(&G);
|
||||
k.apply(&G, DEFAULT);
|
||||
k.apply(&G, &name);
|
||||
assert_eq!(k.get(&A), 3.0);
|
||||
assert_eq!(k.code(&G), "A = 3\nB = 0\nC = 0 (x)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn change_undoes_and_redoes_and_a_new_change_drops_redo() {
|
||||
let mut k = Knobs::default();
|
||||
k.change(&A, 7.0);
|
||||
k.change(&A, 7.0);
|
||||
k.change(&C, 2.0);
|
||||
assert!(k.undo());
|
||||
assert_eq!((k.get(&A), k.get(&C)), (7.0, 0.0));
|
||||
assert!(k.redo());
|
||||
assert_eq!(k.get(&C), 2.0);
|
||||
assert!(k.undo() && k.undo());
|
||||
assert!(k.values.is_empty(), "a repeat of the same value is no change");
|
||||
assert!(!k.undo());
|
||||
assert!(k.redo());
|
||||
k.change(&B, 0.5);
|
||||
assert!(!k.can_redo());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keep_marks_what_differs_and_revert_goes_back_undoably() {
|
||||
let mut k = Knobs::default();
|
||||
k.set(&A, 8.0);
|
||||
assert!(k.differs(&A), "nothing kept yet: the defaults are");
|
||||
k.keep();
|
||||
assert!(!k.differs(&A));
|
||||
k.change(&A, 1.0);
|
||||
k.change(&C, 1.0);
|
||||
assert!(k.differs(&A) && k.differs(&C) && !k.differs(&B));
|
||||
k.revert(&[A]);
|
||||
assert_eq!((k.get(&A), k.get(&C)), (8.0, 1.0));
|
||||
k.revert(&G.knobs);
|
||||
assert_eq!(k.get(&C), 0.0);
|
||||
assert!(!k.values.contains_key("C"), "kept at its default, so back to no value");
|
||||
assert!(k.undo());
|
||||
assert_eq!(k.get(&C), 1.0);
|
||||
k.keep_some(&[C]);
|
||||
k.change(&A, 3.0);
|
||||
k.revert(&G.knobs);
|
||||
assert_eq!((k.get(&A), k.get(&C)), (8.0, 1.0));
|
||||
}
|
||||
+393
@@ -0,0 +1,393 @@
|
||||
//! What the side panel lists, in what order and what's folded, and its keys. Groups filed
|
||||
//! under a page fold with it. The Tree layout starts with everything folded, a list of all the
|
||||
//! parts with a dot on what's on screen, until one is opened; the others open what's on screen. [`LAYOUT`] picks how they're laid out
|
||||
//! while comparing. ↑/↓ move a row, ← → fold and open a header or step a knob, `/` starts the
|
||||
//! filter (a real text field: see [`Knobs::filter_key`] for the few keys the panel keeps while
|
||||
//! it edits), Esc stops filtering, then clears the filter, then closes.
|
||||
#![cfg_attr(not(feature = "panel"), allow(dead_code))]
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use rune::{Key, KeyEvent};
|
||||
|
||||
use crate::{Group, Knobs, LAYOUT};
|
||||
|
||||
/// The On screen layout's second caption.
|
||||
pub(crate) const REST: &str = "Not on screen";
|
||||
pub(crate) const SEEN: &str = "On screen";
|
||||
|
||||
/// A row the keyboard can stand on: a page's header, a group's header (by index), or one of a
|
||||
/// group's knobs.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Node {
|
||||
Page(&'static str),
|
||||
Group(usize),
|
||||
Knob(usize, usize),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Layout {
|
||||
Tree,
|
||||
OnScreen,
|
||||
Tabs,
|
||||
}
|
||||
|
||||
pub(crate) fn layout(k: &Knobs) -> Layout {
|
||||
match k.get(&LAYOUT).round() as usize {
|
||||
1 => Layout::OnScreen,
|
||||
2 => Layout::Tabs,
|
||||
_ => Layout::Tree,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Head {
|
||||
/// A page's header, which folds the page.
|
||||
Page(&'static str),
|
||||
/// A caption over the groups, which doesn't fold.
|
||||
Caption(&'static str),
|
||||
/// The groups alone.
|
||||
Bare,
|
||||
}
|
||||
|
||||
/// A group as listed: open or folded, its part on screen or not, the knobs it shows (all of
|
||||
/// them unless filtered), and whether it's listed apart from its page, so its title names the
|
||||
/// page ("Item page · Header") and needs no on-screen mark.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct Sub {
|
||||
pub g: usize,
|
||||
pub open: bool,
|
||||
pub seen: bool,
|
||||
pub knobs: Vec<usize>,
|
||||
pub full: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct Section {
|
||||
pub head: Head,
|
||||
pub open: bool,
|
||||
pub seen: bool,
|
||||
pub subs: Vec<Sub>,
|
||||
}
|
||||
|
||||
/// The whole list, and in the Tabs layout the tabs (page, on screen) and the one showing.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub(crate) struct Plan {
|
||||
pub sections: Vec<Section>,
|
||||
pub tabs: Vec<(&'static str, bool)>,
|
||||
pub tab: Option<&'static str>,
|
||||
pub seen: BTreeSet<usize>,
|
||||
}
|
||||
|
||||
/// Pages in the order their first group is declared.
|
||||
fn pages(groups: &[Group]) -> Vec<&'static str> {
|
||||
let mut out: Vec<&'static str> = Vec::new();
|
||||
for g in groups {
|
||||
if !out.contains(&g.page()) {
|
||||
out.push(g.page());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Knob `i` of `g` matches every word of `q` across its page, group, title and description.
|
||||
fn matches(g: &Group, i: usize, words: &[String]) -> bool {
|
||||
let d = &g.knobs[i];
|
||||
let hay = format!("{} {} {} {} {}", g.under, g.name, d.title(), d.name, d.describe()).to_lowercase();
|
||||
words.iter().all(|w| hay.contains(w.as_str()))
|
||||
}
|
||||
|
||||
/// What the panel lists for `seen` (the groups whose part of the window is on screen).
|
||||
pub(crate) fn plan(k: &Knobs, groups: &[Group], seen: BTreeSet<usize>) -> Plan {
|
||||
let words: Vec<String> = k.query.split_whitespace().map(str::to_lowercase).collect();
|
||||
// `lead`: open by default while on screen; otherwise folded until it's opened.
|
||||
let sub = |g: usize, full: bool, lead: bool| {
|
||||
let s = seen.contains(&g);
|
||||
Sub { g, open: !k.is_folded(groups[g].name, !(s && lead)), seen: s, knobs: (0..groups[g].knobs.len()).collect(), full }
|
||||
};
|
||||
let mut plan = Plan::default();
|
||||
if !words.is_empty() {
|
||||
let subs = (0..groups.len())
|
||||
.filter_map(|g| {
|
||||
let knobs: Vec<usize> = (0..groups[g].knobs.len()).filter(|&i| matches(&groups[g], i, &words)).collect();
|
||||
(!knobs.is_empty()).then(|| Sub { open: true, knobs, ..sub(g, true, true) })
|
||||
})
|
||||
.collect();
|
||||
plan.sections.push(Section { head: Head::Bare, open: true, seen: false, subs });
|
||||
plan.seen = seen;
|
||||
return plan;
|
||||
}
|
||||
let of = |page: &str| (0..groups.len()).filter(|&g| groups[g].page() == page).collect::<Vec<_>>();
|
||||
match layout(k) {
|
||||
Layout::Tree => {
|
||||
for p in pages(groups) {
|
||||
let gs = of(p);
|
||||
let lit = gs.iter().any(|g| seen.contains(g));
|
||||
if gs.len() == 1 && groups[gs[0]].under.is_empty() {
|
||||
plan.sections.push(Section { head: Head::Bare, open: true, seen: lit, subs: vec![sub(gs[0], false, false)] });
|
||||
} else {
|
||||
// A page opens with the group left open in it.
|
||||
let holds = gs.iter().any(|&g| k.group.as_deref() == Some(groups[g].name) && k.unfolded.contains(groups[g].name));
|
||||
plan.sections.push(Section { head: Head::Page(p), open: !k.is_folded(p, !holds), seen: lit, subs: gs.iter().map(|&g| sub(g, false, false)).collect() });
|
||||
}
|
||||
}
|
||||
}
|
||||
Layout::OnScreen => {
|
||||
let (on, off): (Vec<usize>, Vec<usize>) = (0..groups.len()).partition(|g| seen.contains(g));
|
||||
if !on.is_empty() {
|
||||
plan.sections.push(Section { head: Head::Caption(SEEN), open: true, seen: true, subs: on.into_iter().map(|g| sub(g, true, true)).collect() });
|
||||
}
|
||||
if !off.is_empty() {
|
||||
plan.sections.push(Section { head: Head::Caption(REST), open: true, seen: false, subs: off.into_iter().map(|g| sub(g, true, true)).collect() });
|
||||
}
|
||||
}
|
||||
Layout::Tabs => {
|
||||
plan.tabs = pages(groups).into_iter().map(|p| (p, of(p).iter().any(|g| seen.contains(g)))).collect();
|
||||
let picked = k.tab.as_deref().and_then(|t| plan.tabs.iter().find(|(p, _)| *p == t));
|
||||
let tab = picked.or(plan.tabs.iter().find(|(_, on)| *on)).or(plan.tabs.first()).map(|(p, _)| *p);
|
||||
plan.tab = tab;
|
||||
if let Some(t) = tab {
|
||||
plan.sections.push(Section { head: Head::Bare, open: true, seen: true, subs: of(t).into_iter().map(|g| sub(g, false, true)).collect() });
|
||||
}
|
||||
}
|
||||
}
|
||||
plan.seen = seen;
|
||||
plan
|
||||
}
|
||||
|
||||
/// The rows the keyboard walks, top to bottom.
|
||||
pub(crate) fn rows(plan: &Plan) -> Vec<Node> {
|
||||
let mut out = Vec::new();
|
||||
for s in &plan.sections {
|
||||
if let Head::Page(p) = s.head {
|
||||
out.push(Node::Page(p));
|
||||
}
|
||||
if !s.open {
|
||||
continue;
|
||||
}
|
||||
for sub in &s.subs {
|
||||
out.push(Node::Group(sub.g));
|
||||
if sub.open {
|
||||
out.extend(sub.knobs.iter().map(|&i| Node::Knob(sub.g, i)));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// What a key did: nothing, a change to show at once, or a fold to animate.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Did {
|
||||
Not,
|
||||
Now,
|
||||
Fold,
|
||||
}
|
||||
|
||||
impl Knobs {
|
||||
pub(crate) fn at(&self) -> Option<Node> {
|
||||
self.at
|
||||
}
|
||||
/// Puts the keyboard on `n`; a group's row makes it the panel's group.
|
||||
pub(crate) fn set_at(&mut self, n: Option<Node>, groups: &[Group]) {
|
||||
self.at = n;
|
||||
let (g, i) = match n {
|
||||
Some(Node::Knob(g, i)) => (g, i),
|
||||
Some(Node::Group(g)) => (g, 0),
|
||||
_ => return,
|
||||
};
|
||||
if let Some(grp) = groups.get(g) {
|
||||
self.group = Some(grp.name.to_owned());
|
||||
self.cursor = i;
|
||||
}
|
||||
}
|
||||
|
||||
/// The side panel's keys, against what it lists now.
|
||||
pub(crate) fn tree_key(&mut self, groups: &[Group], plan: &Plan, ev: &KeyEvent) -> Did {
|
||||
if ev.mods.cmd || ev.mods.alt || ev.mods.ctrl {
|
||||
return Did::Not;
|
||||
}
|
||||
// Focus left the field without the panel hearing of it (a click elsewhere).
|
||||
if self.filtering && !self.edit.focused {
|
||||
self.filtering = false;
|
||||
}
|
||||
if self.filtering {
|
||||
return self.filter_key(groups, plan, ev);
|
||||
}
|
||||
let rows = rows(plan);
|
||||
let here = self.at.and_then(|n| rows.iter().position(|r| *r == n));
|
||||
let did = match &ev.key {
|
||||
Key::Escape if !self.query.is_empty() => {
|
||||
self.set_query("");
|
||||
Did::Now
|
||||
}
|
||||
Key::Escape => {
|
||||
self.close();
|
||||
return Did::Now;
|
||||
}
|
||||
Key::Up | Key::Down | Key::Tab => self.move_row(groups, plan, ev),
|
||||
Key::Left | Key::Right => {
|
||||
let right = ev.key == Key::Right;
|
||||
match self.at.filter(|_| here.is_some()) {
|
||||
Some(Node::Knob(g, i)) => {
|
||||
self.step(&groups[g].knobs[i], right, ev.mods.shift);
|
||||
Did::Now
|
||||
}
|
||||
Some(n @ (Node::Group(_) | Node::Page(_))) => {
|
||||
let (name, open) = match n {
|
||||
Node::Group(g) => (groups[g].name, plan.sections.iter().flat_map(|s| &s.subs).any(|s| s.g == g && s.open)),
|
||||
Node::Page(p) => (p, plan.sections.iter().any(|s| s.head == Head::Page(p) && s.open)),
|
||||
Node::Knob(..) => unreachable!(),
|
||||
};
|
||||
match (right, open) {
|
||||
(true, false) | (false, true) => {
|
||||
self.set_folded(name, !right);
|
||||
Did::Fold
|
||||
}
|
||||
(true, true) => {
|
||||
if let Some(next) = here.and_then(|i| rows.get(i + 1)) {
|
||||
self.set_at(Some(*next), groups);
|
||||
}
|
||||
Did::Now
|
||||
}
|
||||
(false, false) => {
|
||||
// A folded group's ← goes up to its page.
|
||||
if let Node::Group(g) = n
|
||||
&& !groups[g].under.is_empty()
|
||||
&& rows.contains(&Node::Page(groups[g].under))
|
||||
{
|
||||
self.set_at(Some(Node::Page(groups[g].under)), groups);
|
||||
}
|
||||
Did::Now
|
||||
}
|
||||
}
|
||||
}
|
||||
None if !rows.is_empty() => {
|
||||
self.set_at(Some(rows[0]), groups);
|
||||
Did::Now
|
||||
}
|
||||
None => Did::Not,
|
||||
}
|
||||
}
|
||||
Key::Enter => match self.at.filter(|_| here.is_some()) {
|
||||
Some(Node::Group(g)) => {
|
||||
let name = groups[g].name;
|
||||
let folded = !plan.sections.iter().flat_map(|s| &s.subs).any(|s| s.g == g && s.open);
|
||||
self.set_folded(name, !folded);
|
||||
Did::Fold
|
||||
}
|
||||
Some(Node::Page(p)) => {
|
||||
let folded = !plan.sections.iter().any(|s| s.head == Head::Page(p) && s.open);
|
||||
self.set_folded(p, !folded);
|
||||
Did::Fold
|
||||
}
|
||||
_ => Did::Not,
|
||||
},
|
||||
Key::Backspace if !self.query.is_empty() => {
|
||||
let mut q = self.query.clone();
|
||||
q.pop();
|
||||
self.set_query(&q);
|
||||
self.refilter(groups, plan);
|
||||
Did::Now
|
||||
}
|
||||
Key::Text(t) if t == "/" => {
|
||||
self.start_filter();
|
||||
Did::Now
|
||||
}
|
||||
// 1–9 pick the keyboard's choice's option.
|
||||
Key::Text(t) if t.len() == 1 && matches!(t.as_bytes()[0], b'1'..=b'9') => {
|
||||
let n = (t.as_bytes()[0] - b'1') as usize;
|
||||
match self.at.filter(|_| here.is_some()) {
|
||||
Some(Node::Knob(g, i)) if n < groups[g].knobs[i].labels.len() => {
|
||||
let d = groups[g].knobs[i];
|
||||
self.checkpoint();
|
||||
self.set(&d, n as f32);
|
||||
Did::Now
|
||||
}
|
||||
// Taken even so: the page's own number keys (a decision's options) wait for the panel to let go.
|
||||
_ => Did::Now,
|
||||
}
|
||||
}
|
||||
Key::Text(t) if (t == "[" || t == "]") && !plan.tabs.is_empty() => {
|
||||
let i = plan.tab.and_then(|c| plan.tabs.iter().position(|(p, _)| *p == c)).unwrap_or(0) as i32;
|
||||
let n = plan.tabs.len() as i32;
|
||||
self.tab = Some(plan.tabs[(i + if t == "[" { -1 } else { 1 }).rem_euclid(n) as usize].0.to_owned());
|
||||
self.at = None;
|
||||
Did::Now
|
||||
}
|
||||
_ => Did::Not,
|
||||
};
|
||||
if did != Did::Not {
|
||||
self.kbd = true;
|
||||
}
|
||||
did
|
||||
}
|
||||
|
||||
/// The keys the panel keeps while the filter field edits (it hears every other key first
|
||||
/// and owns ← →, digits, `[` `]`, `/`, Backspace and the ⌘ ⌥ chords): ↑ ↓ move the row so
|
||||
/// a result is an arrow away, Tab moves between headers, Return stops filtering, and Esc
|
||||
/// stops it too (the matches stay; Esc again clears them, and again closes).
|
||||
pub(crate) fn filter_key(&mut self, groups: &[Group], plan: &Plan, ev: &KeyEvent) -> Did {
|
||||
if ev.mods.cmd || ev.mods.alt || ev.mods.ctrl {
|
||||
return Did::Not;
|
||||
}
|
||||
let did = match &ev.key {
|
||||
Key::Escape => {
|
||||
self.stop_filter();
|
||||
if rows(plan).is_empty() {
|
||||
self.set_query("");
|
||||
}
|
||||
Did::Now
|
||||
}
|
||||
Key::Enter => {
|
||||
self.stop_filter();
|
||||
Did::Now
|
||||
}
|
||||
Key::Up | Key::Down | Key::Tab => self.move_row(groups, plan, ev),
|
||||
_ => Did::Not,
|
||||
};
|
||||
if did != Did::Not {
|
||||
self.kbd = true;
|
||||
}
|
||||
did
|
||||
}
|
||||
|
||||
/// ↑ ↓ walk the rows; Tab jumps between headers.
|
||||
fn move_row(&mut self, groups: &[Group], plan: &Plan, ev: &KeyEvent) -> Did {
|
||||
let rows = rows(plan);
|
||||
let here = self.at.and_then(|n| rows.iter().position(|r| *r == n));
|
||||
match &ev.key {
|
||||
Key::Up | Key::Down if !rows.is_empty() => {
|
||||
let down = ev.key == Key::Down;
|
||||
let i = match here {
|
||||
Some(i) if down => (i + 1).min(rows.len() - 1),
|
||||
Some(i) => i.saturating_sub(1),
|
||||
None if down => 0,
|
||||
None => rows.len() - 1,
|
||||
};
|
||||
self.set_at(Some(rows[i]), groups);
|
||||
Did::Now
|
||||
}
|
||||
Key::Tab => {
|
||||
let heads: Vec<usize> = (0..rows.len()).filter(|&i| !matches!(rows[i], Node::Knob(..))).collect();
|
||||
let at = here.unwrap_or(0);
|
||||
let next = if ev.mods.shift { heads.iter().rev().find(|&&i| i < at).or(heads.last()) } else { heads.iter().find(|&&i| i > at).or(heads.first()) };
|
||||
if let Some(&i) = next {
|
||||
self.set_at(Some(rows[i]), groups);
|
||||
}
|
||||
Did::Now
|
||||
}
|
||||
_ => Did::Not,
|
||||
}
|
||||
}
|
||||
|
||||
/// After the filter changes, the keyboard stands on the first knob it shows.
|
||||
pub(crate) fn refilter(&mut self, groups: &[Group], before: &Plan) {
|
||||
let now = plan(self, groups, before.seen.clone());
|
||||
let first = rows(&now).into_iter().find(|n| matches!(n, Node::Knob(..)));
|
||||
self.set_at(first, groups);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "tree_tests.rs"]
|
||||
mod tests;
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
use super::*;
|
||||
use crate::Knob;
|
||||
|
||||
const A: Knob = Knob::new("Header fade", 0.0, 10.0, 5.0).about("How tall the fade under the header is");
|
||||
const B: Knob = Knob::choice("Table look", &["Lines", "Zebra"], 0);
|
||||
const C: Knob = Knob::new("Row gap", 0.0, 8.0, 2.0);
|
||||
const D: Knob = Knob::new("Dock radius", 0.0, 24.0, 14.0);
|
||||
const GROUPS: &[Group] = &[
|
||||
Group::new("Header", "hdr", &[A]).under("Item page"),
|
||||
Group::new("Tables", "table", &[B]).under("Item page"),
|
||||
Group::new("Rows", "list", &[C]).under("Sidebar"),
|
||||
Group::new("Dock", "dock", &[D]),
|
||||
];
|
||||
|
||||
fn seen(gs: &[usize]) -> BTreeSet<usize> {
|
||||
gs.iter().copied().collect()
|
||||
}
|
||||
|
||||
fn key(k: &mut Knobs, ev: Key) -> Did {
|
||||
let p = plan(k, GROUPS, seen(&[0, 3]));
|
||||
k.tree_key(GROUPS, &p, &KeyEvent { key: ev, mods: Default::default() })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn everything_starts_folded_with_a_dot_on_whats_on_screen() {
|
||||
let k = Knobs::default();
|
||||
let p = plan(&k, GROUPS, seen(&[0, 3]));
|
||||
assert_eq!(p.sections.len(), 3, "Item page, Sidebar, Dock");
|
||||
assert_eq!(p.sections[0].head, Head::Page("Item page"));
|
||||
assert!(p.sections.iter().all(|s| s.head == Head::Bare || !s.open), "every page folded");
|
||||
assert!(p.sections.iter().flat_map(|s| &s.subs).all(|s| !s.open), "every group folded");
|
||||
assert!(p.sections[0].seen && !p.sections[1].seen);
|
||||
assert!(p.sections[0].subs[0].seen && !p.sections[0].subs[1].seen);
|
||||
assert_eq!(p.sections[2].head, Head::Bare, "a group on its own needs no page");
|
||||
assert_eq!(rows(&p), vec![Node::Page("Item page"), Node::Page("Sidebar"), Node::Group(3)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_folds_win() {
|
||||
let mut k = Knobs::default();
|
||||
k.set_folded("Header", false);
|
||||
k.set_folded("Item page", true);
|
||||
k.set_folded("Sidebar", false);
|
||||
let p = plan(&k, GROUPS, seen(&[0, 3]));
|
||||
assert!(p.sections[0].subs[0].open && !p.sections[0].open);
|
||||
assert!(p.sections[1].open);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reopening_folds_all_but_the_group_last_left_open() {
|
||||
let mut k = Knobs::default();
|
||||
k.show();
|
||||
k.set_folded("Sidebar", false);
|
||||
k.set_folded("Rows", false);
|
||||
k.set_folded("Item page", false);
|
||||
k.set_folded("Tables", false);
|
||||
k.group = Some("Tables".into());
|
||||
k.close();
|
||||
k.show();
|
||||
let p = plan(&k, GROUPS, seen(&[]));
|
||||
assert!(p.sections[0].open && p.sections[0].subs[1].open, "Tables and its page open");
|
||||
assert!(!p.sections[0].subs[0].open && !p.sections[1].open, "the rest folded");
|
||||
k.set_folded("Tables", true);
|
||||
k.close();
|
||||
k.show();
|
||||
let p = plan(&k, GROUPS, seen(&[]));
|
||||
assert!(!p.sections[0].open, "folded last, so nothing stays open");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn on_screen_layout_lists_whats_showing_first() {
|
||||
let mut k = Knobs::default();
|
||||
k.set(&LAYOUT, 1.0);
|
||||
let p = plan(&k, GROUPS, seen(&[1, 3]));
|
||||
assert_eq!(p.sections[0].head, Head::Caption(SEEN));
|
||||
assert_eq!(p.sections[0].subs.iter().map(|s| s.g).collect::<Vec<_>>(), vec![1, 3]);
|
||||
assert!(p.sections[0].subs[0].full, "it names its page");
|
||||
assert_eq!(p.sections[1].head, Head::Caption(REST));
|
||||
assert!(p.sections[1].subs.iter().all(|s| !s.open));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tabs_layout_opens_on_the_page_thats_showing() {
|
||||
let mut k = Knobs::default();
|
||||
k.set(&LAYOUT, 2.0);
|
||||
let p = plan(&k, GROUPS, seen(&[2]));
|
||||
assert_eq!(p.tab, Some("Sidebar"));
|
||||
assert_eq!(p.tabs.len(), 3);
|
||||
assert_eq!(p.sections[0].subs.iter().map(|s| s.g).collect::<Vec<_>>(), vec![2]);
|
||||
k.tree_key(GROUPS, &p, &KeyEvent { key: Key::Text("]".into()), mods: Default::default() });
|
||||
assert_eq!(plan(&k, GROUPS, seen(&[2])).tab, Some("Dock"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slash_then_a_query_filters_by_name_and_description() {
|
||||
let mut k = Knobs::default();
|
||||
assert_eq!(key(&mut k, Key::Text("t".into())), Did::Not, "a letter alone doesn't filter");
|
||||
assert!(k.query.is_empty());
|
||||
key(&mut k, Key::Text("/".into()));
|
||||
assert!(k.filtering);
|
||||
assert_eq!(key(&mut k, Key::Text("t".into())), Did::Not, "the field takes typing, not the tree");
|
||||
assert_eq!(key(&mut k, Key::Right), Did::Not, "and ← →");
|
||||
k.set_query("tall");
|
||||
k.refilter(GROUPS, &plan(&k, GROUPS, seen(&[])));
|
||||
let p = plan(&k, GROUPS, seen(&[]));
|
||||
assert_eq!(rows(&p), vec![Node::Group(0), Node::Knob(0, 0)], "matches A's description");
|
||||
assert_eq!(k.at(), Some(Node::Knob(0, 0)), "the keyboard lands on the first match");
|
||||
key(&mut k, Key::Escape);
|
||||
assert!(!k.filtering && k.query == "tall", "Esc stops typing and keeps the matches");
|
||||
key(&mut k, Key::Escape);
|
||||
assert!(k.query.is_empty(), "a second Esc clears the filter");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn number_keys_pick_the_keyboard_choices_option() {
|
||||
let mut k = Knobs::default();
|
||||
k.open = true;
|
||||
k.set_folded("Item page", false);
|
||||
k.set_folded("Tables", false);
|
||||
let p = plan(&k, GROUPS, seen(&[0, 3]));
|
||||
k.set_at(Some(Node::Knob(1, 0)), GROUPS);
|
||||
assert!(rows(&p).contains(&Node::Knob(1, 0)));
|
||||
assert_eq!(key(&mut k, Key::Text("2".into())), Did::Now);
|
||||
assert_eq!(k.get(&B), 1.0, "2 picks Zebra");
|
||||
key(&mut k, Key::Text("3".into()));
|
||||
assert_eq!(k.get(&B), 1.0, "past the last option does nothing");
|
||||
k.undo();
|
||||
assert_eq!(k.get(&B), 0.0, "undoable");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrows_walk_rows_and_fold_headers() {
|
||||
let mut k = Knobs::default();
|
||||
k.open = true;
|
||||
assert_eq!(key(&mut k, Key::Down), Did::Now);
|
||||
assert_eq!(k.at(), Some(Node::Page("Item page")));
|
||||
assert_eq!(key(&mut k, Key::Right), Did::Fold);
|
||||
assert!(k.unfolded.contains("Item page"));
|
||||
assert_eq!(key(&mut k, Key::Left), Did::Fold);
|
||||
assert!(k.folded.contains("Item page"));
|
||||
assert_eq!(key(&mut k, Key::Down), Did::Now);
|
||||
assert_eq!(k.at(), Some(Node::Page("Sidebar")), "the folded page's rows are skipped");
|
||||
assert_eq!(key(&mut k, Key::Right), Did::Fold);
|
||||
assert!(k.unfolded.contains("Sidebar"));
|
||||
key(&mut k, Key::Right);
|
||||
assert_eq!(k.at(), Some(Node::Group(2)), "→ on an open header goes in");
|
||||
key(&mut k, Key::Right);
|
||||
key(&mut k, Key::Right);
|
||||
assert_eq!(k.at(), Some(Node::Knob(2, 0)));
|
||||
key(&mut k, Key::Right);
|
||||
assert!((k.get(&C) - 2.08).abs() < 1e-4, "→ on a knob steps it");
|
||||
assert_eq!(k.group.as_deref(), Some("Rows"));
|
||||
}
|
||||
+262
@@ -0,0 +1,262 @@
|
||||
//! The layer ⌘⇧K opens: region picking over the window, and the panel, drawn to match the knobs
|
||||
//! library's main look (flat accent-tinted slider fills with a hairline handle, label left and
|
||||
//! readout right on one row, rows sharing one card, text tabs, a preset tray).
|
||||
|
||||
use rune::{Color, El, Icon, TextStyle, Tx, col, el, icon, row, spacer, text};
|
||||
|
||||
use crate::rows::{CHIP, Ctx, LABEL, PAD, ROW, TITLE, VALUE, card, presets};
|
||||
use crate::{Action, Group, Knobs, Style, icons};
|
||||
|
||||
const W: f32 = 300.0;
|
||||
const CARD_W: f32 = W - 2.0 * PAD;
|
||||
/// Where an inline panel's first frame starts, before its card's laid-out width is known: the
|
||||
/// playground's side column.
|
||||
const INLINE_CARD_W: f32 = 220.0;
|
||||
|
||||
const TAG: TextStyle = TextStyle::new(11.0, 550.0).lh(14.0);
|
||||
|
||||
/// The smallest region under the point.
|
||||
fn region_at(rects: &[(&'static str, [f32; 4])], x: f32, y: f32) -> Option<&'static str> {
|
||||
rects
|
||||
.iter()
|
||||
.filter(|(_, r)| x >= r[0] && x < r[0] + r[2] && y >= r[1] && y < r[1] + r[3])
|
||||
.min_by(|a, b| (a.1[2] * a.1[3]).total_cmp(&(b.1[2] * b.1[3])))
|
||||
.map(|(n, _)| *n)
|
||||
}
|
||||
|
||||
/// The whole layer, to add over the app's root (it draws nothing while closed). `lens` finds
|
||||
/// the app's `Knobs` in its state. Region rects are read in window points, so put it where
|
||||
/// its top-left is the window's and nothing scales it.
|
||||
pub fn layer<S: 'static>(k: &Knobs, groups: &'static [Group], st: Style, lens: fn(&mut S) -> &mut Knobs) -> El {
|
||||
let l = overlay(k, groups, st, lens, "knobs-layer");
|
||||
if !k.open {
|
||||
return l;
|
||||
}
|
||||
l.child(row().key("knobs-dock").absolute(0.0, 0.0).w_full().pt(12.0).pr(12.0).child(spacer()).child(panel(k, groups, st, lens, None)))
|
||||
}
|
||||
|
||||
/// Region picking and the outline around a group's region, over the element keyed `key`
|
||||
/// (which this is): it reads that element's place to put window rects inside it.
|
||||
pub(crate) fn overlay<S: 'static>(k: &Knobs, groups: &'static [Group], st: Style, lens: fn(&mut S) -> &mut Knobs, key: &'static str) -> El {
|
||||
let mut l = el().key(key).absolute(0.0, 0.0).w_full().h_full();
|
||||
if !k.open {
|
||||
return l;
|
||||
}
|
||||
let (ox, oy) = rune::memo::window_layout(key).map_or((0.0, 0.0), |r| (r[0], r[1]));
|
||||
let rects: Vec<(&'static str, [f32; 4])> = groups.iter().filter_map(|g| rune::memo::window_layout(g.region).map(|r| (g.name, r))).collect();
|
||||
let picking = k.picking;
|
||||
if picking {
|
||||
let at = rects.clone();
|
||||
l = l.child(
|
||||
el().key("knobs-pick")
|
||||
.absolute(0.0, 0.0)
|
||||
.w_full()
|
||||
.h_full()
|
||||
.on_pointer_move_local(move |s: &mut S, e, tx: &mut Tx| {
|
||||
tx.instant();
|
||||
let k = lens(s);
|
||||
let h = region_at(&at, e.window_x, e.window_y);
|
||||
if k.hover.as_deref() != h {
|
||||
k.hover = h.map(str::to_owned);
|
||||
}
|
||||
})
|
||||
.on_hover_change(move |s: &mut S, inside, tx: &mut Tx| {
|
||||
if !inside {
|
||||
tx.instant();
|
||||
lens(s).hover = None;
|
||||
}
|
||||
})
|
||||
.on_press_tx(move |s: &mut S, tx: &mut Tx| {
|
||||
tx.instant();
|
||||
let k = lens(s);
|
||||
if let Some(h) = k.hover.clone() {
|
||||
k.pick(&h);
|
||||
if let Some(i) = groups.iter().position(|g| g.name == h) {
|
||||
tx.scroll_into_view(crate::side::section_key(i));
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
let outlined = k.hover.clone();
|
||||
if let Some((name, r)) = outlined.and_then(|n| rects.iter().find(|(g, _)| *g == n).copied()) {
|
||||
let mut o = el().key("knobs-outline").absolute(r[0] - ox, r[1] - oy).w(r[2]).h(r[3]).radius(6.0).border(1.0, st.outline);
|
||||
if picking {
|
||||
o = o.child(row().key("knobs-tag").absolute(6.0, 6.0).h(20.0).px(7.0).center_y().radius(5.0).fill(st.bg).child(text(name).font(TAG).color(st.fg)));
|
||||
}
|
||||
l = l.child(o);
|
||||
}
|
||||
l
|
||||
}
|
||||
|
||||
/// The panel alone, for an app's own layout (a storybook's right-hand column): it doesn't
|
||||
/// float, pick regions or take keys itself, and a single group shows no tabs. The app sends it
|
||||
/// ↑ ↓ ← → with [`Knobs::panel_key`]; `active` marks the knob those keys move. It fills its
|
||||
/// parent's width, and its rows lay out from the width they get (a slider's track grows with
|
||||
/// it), so a 240 pt column and a 300 pt one both read.
|
||||
pub fn inline<S: 'static>(k: &Knobs, groups: &'static [Group], st: Style, lens: fn(&mut S) -> &mut Knobs, active: bool) -> El {
|
||||
panel(k, groups, st, lens, Some(active))
|
||||
}
|
||||
|
||||
/// A card of buttons that each do one thing, with the key that does it on a cap: a story's
|
||||
/// triggers ("R Replay", "F Finish a task"). The app binds the keys. It fills its parent's
|
||||
/// width up to 300 pt.
|
||||
pub fn actions<S: 'static>(st: Style, items: &[Action<S>]) -> El {
|
||||
let mut card = col().key("knobs-actions").w_full().max_w(W).padding(4.0).gap(2.0).radius(12.0).fill(st.bg).border_gradient(0.5, st.rim, st.border);
|
||||
for (i, a) in items.iter().enumerate() {
|
||||
let run = a.run;
|
||||
card = card.child(
|
||||
row()
|
||||
.key(format!("knobs-action-{i}"))
|
||||
.role("button")
|
||||
.label(a.label)
|
||||
.w_full()
|
||||
.h(ROW)
|
||||
.px(6.0)
|
||||
.gap(10.0)
|
||||
.center_y()
|
||||
.radius(8.0)
|
||||
.hover(st.fill_hover)
|
||||
.on_press_tx(move |s: &mut S, tx: &mut Tx| run(s, tx))
|
||||
.child(row().key("cap").h(20.0).min_w(22.0).px(6.0).radius(5.0).fill(st.fill_selected).center().child(text(a.cap).font(VALUE).color(st.fg)))
|
||||
.child(text(a.label).font(LABEL).color(st.fg2)),
|
||||
);
|
||||
}
|
||||
card
|
||||
}
|
||||
|
||||
pub(crate) fn tool<S: 'static>(st: Style, key: &str, glyph: &'static Icon, label: &str, enabled: bool, lens: fn(&mut S) -> &mut Knobs, f: impl Fn(&mut Knobs, &mut Tx) + 'static) -> El {
|
||||
let b = row()
|
||||
.key(key)
|
||||
.role("button")
|
||||
.label(label)
|
||||
.help(label)
|
||||
.w(22.0)
|
||||
.h(22.0)
|
||||
.radius(6.0)
|
||||
.center()
|
||||
.child(icon(glyph, 14.0).color(st.fg2));
|
||||
if !enabled {
|
||||
return b.opacity(0.3);
|
||||
}
|
||||
b.hover(st.fill_hover).on_press_tx(move |s: &mut S, tx: &mut Tx| {
|
||||
tx.instant();
|
||||
f(lens(s), tx);
|
||||
})
|
||||
}
|
||||
|
||||
/// The panel's title and its tools: pick a part (with `pick`), Random and Reset for `g`, Undo,
|
||||
/// Copy values.
|
||||
pub(crate) fn head<S: 'static>(k: &Knobs, groups: &'static [Group], st: Style, lens: fn(&mut S) -> &mut Knobs, g: Option<Group>, title: &str, pick: bool) -> El {
|
||||
let mut head = row().key("knobs-head").w_full().h(22.0).gap(2.0).center_y().child(text(title.to_owned()).font(TITLE).color(st.fg).truncate_fade().shrink()).child(spacer());
|
||||
if pick {
|
||||
head = head.child(tool(st, "knobs-repick", &icons::TARGET, "Pick a part", true, lens, |k, _| k.pick_region()));
|
||||
}
|
||||
if let Some(g) = g {
|
||||
head = head
|
||||
.child(tool(st, "knobs-random", &icons::RANDOM, "Random", true, lens, move |k, _| k.random(&g)))
|
||||
.child(tool(st, "knobs-reset", &icons::RESET, "Reset", k.can_reset(&g), lens, move |k, _| k.reset(&g)));
|
||||
}
|
||||
head.child(tool(st, "knobs-undo", &icons::UNDO, "Undo", k.can_undo(), lens, |k, _| {
|
||||
k.undo();
|
||||
})).child(tool(st, "knobs-copy", &icons::COPY, "Copy values", true, lens, move |k, tx| {
|
||||
let all: Vec<Group> = match k.current(groups) {
|
||||
Some(g) => vec![g],
|
||||
None => groups.to_vec(),
|
||||
};
|
||||
tx.copy(all.iter().map(|g| k.code(g)).collect::<Vec<_>>().join("\n"));
|
||||
}))
|
||||
}
|
||||
|
||||
/// `inline` is `Some(active)` for [`inline`].
|
||||
fn panel<S: 'static>(k: &Knobs, groups: &'static [Group], st: Style, lens: fn(&mut S) -> &mut Knobs, inline: Option<bool>) -> El {
|
||||
let g = k.current(groups);
|
||||
let title = match (inline, groups) {
|
||||
(Some(_), [one]) => one.name,
|
||||
_ => "Knobs",
|
||||
};
|
||||
let head = head(k, groups, st, lens, g, title, inline.is_none());
|
||||
|
||||
let mut tabs = row().key("knobs-tabs").w_full().gap(16.0).px(PAD);
|
||||
for (i, t) in groups.iter().enumerate() {
|
||||
let on = g.is_some_and(|g| g.name == t.name);
|
||||
let lit = on || k.hover.as_deref() == Some(t.name);
|
||||
let name = t.name;
|
||||
tabs = tabs.child(
|
||||
col()
|
||||
.key(format!("knobs-tab-{i}"))
|
||||
.role("tab")
|
||||
.label(name)
|
||||
.h(28.0)
|
||||
.on_hover_change(move |s: &mut S, inside, tx: &mut Tx| {
|
||||
tx.instant();
|
||||
let k = lens(s);
|
||||
if inside {
|
||||
k.hover = Some(name.to_owned());
|
||||
} else if k.hover.as_deref() == Some(name) {
|
||||
k.hover = None;
|
||||
}
|
||||
})
|
||||
.on_press_tx(move |s: &mut S, tx: &mut Tx| {
|
||||
tx.instant();
|
||||
lens(s).pick(name);
|
||||
})
|
||||
.child(spacer())
|
||||
.child(text(name).font(CHIP).color(if lit { st.fg } else { st.fg2 }))
|
||||
.child(spacer())
|
||||
.child(el().key("bar").w_full().h(1.5).radius(1.0).fill(if on { st.handle } else { Color::TRANSPARENT })),
|
||||
);
|
||||
}
|
||||
|
||||
let p = col().key("knobs-panel");
|
||||
let p = if inline.is_some() { p.w_full() } else { p.w(W) };
|
||||
let p = p.padding(PAD).radius(12.0).fill(st.bg).border_gradient(0.5, st.rim, st.border);
|
||||
if let Some(active) = inline {
|
||||
let p = p.child(head.pl(PAD));
|
||||
let p = if groups.len() > 1 { p.child(tabs.mt(4.0)).child(el().key("knobs-rule").w_full().h(0.5).fill(st.border)) } else { p };
|
||||
return match g {
|
||||
Some(g) => body(true, p, k, groups, &g, st, lens, active),
|
||||
None => p,
|
||||
};
|
||||
}
|
||||
let p = p
|
||||
.shadow(8.0, 24.0, st.shadow)
|
||||
.shadow(1.0, 3.0, st.shadow)
|
||||
.on_hover_change(move |s: &mut S, inside, tx: &mut Tx| {
|
||||
tx.instant();
|
||||
let k = lens(s);
|
||||
if inside && k.picking {
|
||||
k.hover = None;
|
||||
}
|
||||
})
|
||||
.focusable(true)
|
||||
.no_focus_ring()
|
||||
.on_key(move |s: &mut S, ev, tx: &mut Tx| {
|
||||
tx.instant();
|
||||
lens(s).panel_key(groups, ev)
|
||||
})
|
||||
.on_press_tx(move |s: &mut S, tx: &mut Tx| {
|
||||
tx.instant();
|
||||
lens(s).kbd = true;
|
||||
})
|
||||
.child(head.pl(PAD))
|
||||
.child(tabs.mt(4.0))
|
||||
.child(el().key("knobs-rule").w_full().h(0.5).fill(st.border));
|
||||
let Some(g) = g else {
|
||||
return p.child(text("Click a part of the window to tune it.").key("knobs-hint").font(LABEL).color(st.fg3).px(PAD).mt(12.0).mb(4.0));
|
||||
};
|
||||
body(false, p, k, groups, &g, st, lens, k.kbd)
|
||||
}
|
||||
|
||||
/// The presets and the knobs' card, under the panel's head; `active` marks the keyboard's knob.
|
||||
fn body<S: 'static>(inline: bool, p: El, k: &Knobs, groups: &[Group], g: &Group, st: Style, lens: fn(&mut S) -> &mut Knobs, active: bool) -> El {
|
||||
let cx = Ctx { k, st, lens, w: if inline { INLINE_CARD_W } else { CARD_W } };
|
||||
let gi = groups.iter().position(|x| x.name == g.name).unwrap_or(0);
|
||||
let all: Vec<usize> = (0..g.knobs.len()).collect();
|
||||
let mark = (active && !all.is_empty()).then(|| k.cursor.min(all.len() - 1));
|
||||
p.child(presets(cx, g).mt(PAD)).child(card(cx, g, gi, &all, mark).mt(PAD))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "view_tests.rs"]
|
||||
mod tests;
|
||||
+267
@@ -0,0 +1,267 @@
|
||||
use super::*;
|
||||
use crate::Knob;
|
||||
use rune::{Cx, Env, Runtime};
|
||||
|
||||
struct T {
|
||||
knobs: Knobs,
|
||||
}
|
||||
const L: Knob = Knob::new("Left size", 0.0, 10.0, 5.0);
|
||||
const I: Knob = Knob::new("Inner gap", 0.0, 1.0, 0.5);
|
||||
const R: Knob = Knob::new("Right pad", 0.0, 40.0, 20.0);
|
||||
const GROUPS: &[Group] = &[Group::new("Left", "left", &[L]), Group::new("Inner", "inner", &[I]), Group::new("Right", "right", &[R])];
|
||||
|
||||
fn view(s: &T, _: &mut Cx<T>) -> El {
|
||||
el().key("root")
|
||||
.w_full()
|
||||
.h_full()
|
||||
.child(
|
||||
row()
|
||||
.key("cols")
|
||||
.w_full()
|
||||
.h_full()
|
||||
.child(col().key("left").w(400.0).h_full().child(el().key("inner").w(200.0).h(200.0).mt(100.0).ml(100.0)))
|
||||
.child(col().key("right").grow(1.0).h_full()),
|
||||
)
|
||||
.child(layer(&s.knobs, GROUPS, Style::dark(), |s: &mut T| &mut s.knobs))
|
||||
}
|
||||
|
||||
fn settle(rt: &mut Runtime<T>) {
|
||||
for _ in 0..4 {
|
||||
rt.frame(1.0 / 60.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hover_outlines_the_smallest_region_and_a_click_opens_its_knobs() {
|
||||
let mut s = T { knobs: Knobs::default() };
|
||||
s.knobs.show();
|
||||
s.knobs.pick_region();
|
||||
let mut rt = Runtime::new(s, view, (1000.0, 700.0), Env::new(true, 1.0));
|
||||
settle(&mut rt);
|
||||
for (x, y, want) in [(150.0, 150.0, "Inner"), (50.0, 600.0, "Left"), (600.0, 500.0, "Right")] {
|
||||
rt.pointer_move(x, y);
|
||||
settle(&mut rt);
|
||||
assert_eq!(rt.state.knobs.hover.as_deref(), Some(want), "at {x},{y}");
|
||||
assert!(rt.find("knobs-outline").is_some());
|
||||
}
|
||||
rt.pointer_move(150.0, 150.0);
|
||||
settle(&mut rt);
|
||||
rt.pointer_down(150.0, 150.0);
|
||||
rt.pointer_up(150.0, 150.0);
|
||||
settle(&mut rt);
|
||||
assert_eq!(rt.state.knobs.group.as_deref(), Some("Inner"));
|
||||
assert!(rt.find("knobs-knob-0").is_some());
|
||||
|
||||
let (x, y) = rt.find("knobs-random").unwrap();
|
||||
rt.pointer_move(x, y);
|
||||
settle(&mut rt);
|
||||
rt.pointer_down(x, y);
|
||||
rt.pointer_up(x, y);
|
||||
settle(&mut rt);
|
||||
assert!(rt.state.knobs.values.contains_key("Inner gap"));
|
||||
assert!(rt.state.knobs.can_undo());
|
||||
|
||||
let (x, y) = rt.find("knobs-tab-2").unwrap();
|
||||
rt.pointer_move(x, y);
|
||||
settle(&mut rt);
|
||||
rt.pointer_down(x, y);
|
||||
rt.pointer_up(x, y);
|
||||
settle(&mut rt);
|
||||
assert_eq!(rt.state.knobs.group.as_deref(), Some("Right"));
|
||||
}
|
||||
|
||||
fn click(rt: &mut Runtime<T>, key: &str) {
|
||||
let (x, y) = rt.find(key).unwrap();
|
||||
rt.pointer_move(x, y);
|
||||
settle(rt);
|
||||
rt.pointer_down(x, y);
|
||||
rt.pointer_up(x, y);
|
||||
settle(rt);
|
||||
}
|
||||
fn press(rt: &mut Runtime<T>, key: rune::Key, shift: bool) {
|
||||
let mut ev = rune::KeyEvent { key, mods: Default::default() };
|
||||
ev.mods.shift = shift;
|
||||
rt.key(ev);
|
||||
settle(rt);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opens_on_a_group_and_outlines_only_on_tab_hover() {
|
||||
let mut s = T { knobs: Knobs::default() };
|
||||
s.knobs.show();
|
||||
let mut rt = Runtime::new(s, view, (1000.0, 700.0), Env::new(true, 1.0));
|
||||
settle(&mut rt);
|
||||
assert!(rt.find("knobs-knob-0").is_some(), "first group is open");
|
||||
assert!(rt.find("knobs-outline").is_none());
|
||||
let (x, y) = rt.find("knobs-knob-0").unwrap();
|
||||
rt.pointer_move(x, y);
|
||||
settle(&mut rt);
|
||||
assert!(rt.find("knobs-outline").is_none(), "no outline over a knob");
|
||||
let (x, y) = rt.find("knobs-tab-1").unwrap();
|
||||
rt.pointer_move(x, y);
|
||||
settle(&mut rt);
|
||||
assert!(rt.find("knobs-outline").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keyboard_steps_knobs_and_switches_groups() {
|
||||
let mut s = T { knobs: Knobs::default() };
|
||||
s.knobs.show();
|
||||
let mut rt = Runtime::new(s, view, (1000.0, 700.0), Env::new(true, 1.0));
|
||||
settle(&mut rt);
|
||||
click(&mut rt, "knobs-card");
|
||||
let k = |rt: &Runtime<T>| rt.state.knobs.get(&L);
|
||||
press(&mut rt, rune::Key::Right, false);
|
||||
assert!((k(&rt) - 5.1).abs() < 1e-3, "{}", k(&rt));
|
||||
press(&mut rt, rune::Key::Left, true);
|
||||
assert!((k(&rt) - 4.1).abs() < 1e-3, "{}", k(&rt));
|
||||
press(&mut rt, rune::Key::Tab, false);
|
||||
assert_eq!(rt.state.knobs.group.as_deref(), Some("Inner"));
|
||||
press(&mut rt, rune::Key::Text("[".into()), false);
|
||||
assert_eq!(rt.state.knobs.group.as_deref(), Some("Left"));
|
||||
press(&mut rt, rune::Key::Escape, false);
|
||||
assert!(!rt.state.knobs.open);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_and_reset_are_disabled_until_there_is_something_to_undo() {
|
||||
let mut s = T { knobs: Knobs::default() };
|
||||
s.knobs.show();
|
||||
assert!(!s.knobs.can_undo() && !s.knobs.can_reset(&GROUPS[0]));
|
||||
let mut rt = Runtime::new(s, view, (1000.0, 700.0), Env::new(true, 1.0));
|
||||
settle(&mut rt);
|
||||
click(&mut rt, "knobs-undo");
|
||||
click(&mut rt, "knobs-reset");
|
||||
assert!(rt.state.knobs.values.is_empty());
|
||||
click(&mut rt, "knobs-random");
|
||||
assert!(rt.state.knobs.can_undo() && rt.state.knobs.can_reset(&GROUPS[0]));
|
||||
click(&mut rt, "knobs-reset");
|
||||
assert!(!rt.state.knobs.can_reset(&GROUPS[0]));
|
||||
}
|
||||
|
||||
mod inline_width {
|
||||
use super::*;
|
||||
|
||||
const WIDE: Knob = Knob::new("A rather long slider label here", 0.0, 100.0, 50.0).step(1.0);
|
||||
const PICK: Knob = Knob::choice("Tint", &["Plain", "Accent", "Raised"], 1);
|
||||
const MANY: Knob = Knob::choice(
|
||||
"Corner style",
|
||||
&["Sharp", "Soft", "Round", "Pill", "Squircle"],
|
||||
0,
|
||||
);
|
||||
const G: &[Group] = &[Group::new("Card", "card", &[L, WIDE, PICK, MANY])];
|
||||
|
||||
struct W {
|
||||
knobs: Knobs,
|
||||
w: f32,
|
||||
}
|
||||
|
||||
fn inline_view(s: &W, _: &mut Cx<W>) -> El {
|
||||
row()
|
||||
.key("root")
|
||||
.w_full()
|
||||
.h_full()
|
||||
.child(col().key("column").w(s.w).child(inline(
|
||||
&s.knobs,
|
||||
G,
|
||||
Style::dark(),
|
||||
|s: &mut W| &mut s.knobs,
|
||||
false,
|
||||
)))
|
||||
}
|
||||
|
||||
fn rects(w: f32) -> Vec<rune::ElementInfo> {
|
||||
let mut rt = Runtime::new(
|
||||
W {
|
||||
knobs: Knobs::default(),
|
||||
w,
|
||||
},
|
||||
inline_view,
|
||||
(400.0, 700.0),
|
||||
Env::new(true, 1.0),
|
||||
);
|
||||
for _ in 0..6 {
|
||||
rt.frame(1.0 / 60.0);
|
||||
}
|
||||
rt.elements()
|
||||
}
|
||||
|
||||
fn rect(es: &[rune::ElementInfo], key: &str) -> [f32; 4] {
|
||||
es.iter()
|
||||
.find(|e| e.key.as_deref() == Some(key))
|
||||
.unwrap_or_else(|| panic!("no {key}"))
|
||||
.rect
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rows_stay_inside_the_column_at_240_and_300() {
|
||||
for w in [200.0, 240.0, 300.0] {
|
||||
let es = rects(w);
|
||||
let card = rect(&es, "knobs-card");
|
||||
assert!(
|
||||
card[0] >= 0.0 && card[0] + card[2] <= w + 0.01,
|
||||
"card in {w}: {card:?}"
|
||||
);
|
||||
for e in es
|
||||
.iter()
|
||||
.filter(|e| e.path.contains("knobs-card") && e.key.is_some())
|
||||
{
|
||||
let r = e.rect;
|
||||
assert!(
|
||||
r[0] >= card[0] - 0.01 && r[0] + r[2] <= card[0] + card[2] + 0.01,
|
||||
"{:?} at {w}: {r:?} vs {card:?}",
|
||||
e.key
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_slider_track_is_usable_and_grows_with_the_column() {
|
||||
let mut last = 0.0;
|
||||
for w in [200.0, 240.0, 300.0] {
|
||||
let es = rects(w);
|
||||
let track = rect(&es, "knobs-knob-0");
|
||||
assert!(track[2] > 100.0, "{w}: {track:?}");
|
||||
assert!(track[2] > last, "{w}");
|
||||
last = track[2];
|
||||
let fill = es
|
||||
.iter()
|
||||
.find(|e| e.path.contains("knobs-knob-0") && e.key.as_deref() == Some("fill"))
|
||||
.unwrap()
|
||||
.rect;
|
||||
assert!(
|
||||
(fill[2] - track[2] * 0.5).abs() < 0.6,
|
||||
"fill is the value's share of the track at {w}: {fill:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_choice_that_does_not_fit_beside_its_label_wraps_to_a_grid_when_narrow() {
|
||||
let wide = rects(300.0);
|
||||
let narrow = rects(200.0);
|
||||
assert!(rect(&narrow, "knobs-knob-3")[3] > rect(&wide, "knobs-knob-3")[3] - 0.01);
|
||||
assert!(
|
||||
rect(&narrow, "knobs-knob-3")[3] > 40.0,
|
||||
"the five options sit under their label"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_floating_panel_keeps_its_300_points() {
|
||||
let mut s = T {
|
||||
knobs: Knobs::default(),
|
||||
};
|
||||
s.knobs.show();
|
||||
let mut rt = Runtime::new(s, view, (1000.0, 700.0), Env::new(true, 1.0));
|
||||
settle(&mut rt);
|
||||
let p = rt
|
||||
.elements()
|
||||
.into_iter()
|
||||
.find(|e| e.key.as_deref() == Some("knobs-panel"))
|
||||
.unwrap()
|
||||
.rect;
|
||||
assert_eq!(p[2], 300.0);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user