mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-18 04:52:57 +00:00
Gallery and story renderer: every component's stories, old/new comparison
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
[package]
|
||||
name = "story-render"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish = false
|
||||
description = "Renders a component's stories to PNG files, offscreen, linking only the crates its features name"
|
||||
autotests = false
|
||||
|
||||
[[bin]]
|
||||
name = "story-render"
|
||||
path = "src/main.rs"
|
||||
test = false
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
default = []
|
||||
# One feature per domain crate whose stories can be rendered: each links that crate (through the viewer's feature of
|
||||
# the same name) and nothing else above the framework. `apps` links them all, like the gallery.
|
||||
apps = ["craft-ui-gallery/apps"]
|
||||
automation = ["craft-ui-gallery/automation"]
|
||||
browse = ["craft-ui-gallery/browse"]
|
||||
color = ["craft-ui-gallery/color"]
|
||||
draw = ["craft-ui-gallery/draw"]
|
||||
imaging = ["craft-ui-gallery/imaging"]
|
||||
layers = ["craft-ui-gallery/layers"]
|
||||
menu = ["craft-ui-gallery/menu"]
|
||||
pages = ["craft-ui-gallery/pages"]
|
||||
print = ["craft-ui-gallery/print"]
|
||||
review = ["craft-ui-gallery/review"]
|
||||
table = ["craft-ui-gallery/table"]
|
||||
text = ["craft-ui-gallery/text"]
|
||||
theme-store = ["craft-ui-gallery/theme-store"]
|
||||
timeline = ["craft-ui-gallery/timeline"]
|
||||
dialogs = ["craft-ui-gallery/dialogs"]
|
||||
font-manager = ["craft-ui-gallery/font-manager"]
|
||||
update = ["craft-ui-gallery/update"]
|
||||
|
||||
[dependencies]
|
||||
# The same framework features as the gallery, so the framework builds once for the gallery, the tests and this bin.
|
||||
craft-ui = { workspace = true, features = ["app", "testing", "snapshot"] }
|
||||
craft-ui-gallery = { path = "../ui-gallery", default-features = false }
|
||||
egui = { workspace = true }
|
||||
image = { version = "0.25", default-features = false, features = ["png"] }
|
||||
@@ -0,0 +1,285 @@
|
||||
//! Renders a component's stories to PNG files, offscreen and in one process, for the old/new comparison pages.
|
||||
//!
|
||||
//! `cargo run -p story-render --features <crate> -- --only <Name> --out <dir>` writes, into `<dir>`:
|
||||
//! `new-<Name>--<story>.png` for every story of the component, `new-<Name>.png` for the story its Overview card
|
||||
//! shows (its first), `stories.tsv` and `components.tsv`. Each story runs in a card's story body (`StoryBody`) in a
|
||||
//! fresh context, in ArtCraft Dark at 2 pixels per point with the interface fonts, and its image is cropped to the
|
||||
//! story's surface and the layers it opened. A story whose dialog the card holds behind its button is shown with the
|
||||
//! dialog open.
|
||||
//!
|
||||
//! The bin links the framework and only the domain crates its features name (`--features color` for craft-color's
|
||||
//! components; `--features apps` for every crate, as the gallery links them), so a change in one crate rebuilds that
|
||||
//! crate and this bin, not the gallery.
|
||||
//!
|
||||
//! Options: `--only Name,Name` renders those components only (all registered components without it); `--story name`
|
||||
//! renders the story of that name only; `--threads N` (default: the cores, at most 8); `--width W` and `--room H`
|
||||
//! set the card's story width and the height a filling story gets, in points.
|
||||
|
||||
use craft_ui::contract::{Pad, Surface};
|
||||
use craft_ui::fonts::{I18nScripts, UiFonts};
|
||||
use craft_ui::runtime::env::RootEnv;
|
||||
use craft_ui::testing::snapshot::{Renderer, RgbaImage, layer_rects};
|
||||
use craft_ui::testing::{Frames, StoryRegistration};
|
||||
use craft_ui_gallery::WINDOW;
|
||||
use craft_ui_gallery::chrome::{BodyShown, StoryBody};
|
||||
use craft_ui_gallery::viewer::{CardState, Catalog, GallerySettings, entry_of};
|
||||
use egui::{Pos2, Rect, Vec2};
|
||||
use std::cell::RefCell;
|
||||
use std::fmt::Write as _;
|
||||
use std::io::Write as _;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::ExitCode;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
/// The pixels per point of the images.
|
||||
const PIXELS_PER_POINT: f32 = 2.0;
|
||||
/// The width of an Overview card's story body at the gallery's default window (the room a story on another surface than
|
||||
/// the card's panel gets), measured in the running gallery: the Overview's grid takes it from the dock's centre panel at
|
||||
/// run time, and no function gives it for a window size.
|
||||
const WIDTH: f32 = 342.0;
|
||||
/// The height a filling story gets in that Overview: the visible height of its card view, measured the same way.
|
||||
const ROOM: f32 = 692.0;
|
||||
|
||||
struct Options {
|
||||
out: PathBuf,
|
||||
only: Option<Vec<String>>,
|
||||
story: Option<String>,
|
||||
threads: usize,
|
||||
width: f32,
|
||||
room: f32,
|
||||
}
|
||||
|
||||
fn options() -> Result<Options, String> {
|
||||
let mut args = std::env::args().skip(1);
|
||||
let threads = std::thread::available_parallelism().map_or(1, |n| n.get()).min(8);
|
||||
let mut options = Options { out: PathBuf::new(), only: None, story: None, threads, width: WIDTH, room: ROOM };
|
||||
while let Some(arg) = args.next() {
|
||||
let mut value = || args.next().ok_or_else(|| format!("{arg} needs a value"));
|
||||
match arg.as_str() {
|
||||
"--out" => options.out = PathBuf::from(value()?),
|
||||
"--only" => options.only = Some(value()?.split(',').map(str::to_owned).collect()),
|
||||
"--story" => options.story = Some(value()?),
|
||||
"--threads" => options.threads = value()?.parse().map_err(|_| "--threads takes a number".to_owned())?,
|
||||
"--width" => options.width = value()?.parse().map_err(|_| "--width takes points".to_owned())?,
|
||||
"--room" => options.room = value()?.parse().map_err(|_| "--room takes points".to_owned())?,
|
||||
_ => return Err(format!("unknown argument {arg}")),
|
||||
}
|
||||
}
|
||||
if options.out.as_os_str().is_empty() {
|
||||
return Err("--out <dir> is required".to_owned());
|
||||
}
|
||||
Ok(options)
|
||||
}
|
||||
|
||||
/// One story to render.
|
||||
struct Job {
|
||||
/// The component's display name.
|
||||
name: String,
|
||||
level: &'static str,
|
||||
crate_name: &'static str,
|
||||
story: &'static StoryRegistration,
|
||||
surface: Surface,
|
||||
/// The story the component's Overview card shows.
|
||||
first: bool,
|
||||
}
|
||||
|
||||
/// What became of one story.
|
||||
struct Done {
|
||||
status: String,
|
||||
size: Option<(u32, u32)>,
|
||||
}
|
||||
|
||||
fn jobs(options: &Options) -> Vec<Job> {
|
||||
let catalog = Catalog::linked();
|
||||
let mut jobs = Vec::new();
|
||||
for component in &catalog.components {
|
||||
if options.only.as_ref().is_some_and(|only| !only.iter().any(|name| *name == component.name)) {
|
||||
continue;
|
||||
}
|
||||
let Some(entry) = entry_of(component.type_name) else { continue };
|
||||
let stories = catalog.stories_of(component.type_name).iter().map(|&at| &catalog.entries[at]);
|
||||
for (at, story) in stories.enumerate() {
|
||||
if options.story.as_ref().is_some_and(|name| *name != story.registration.story.name) {
|
||||
continue;
|
||||
}
|
||||
jobs.push(Job {
|
||||
name: component.name.clone(),
|
||||
level: entry.level.title(),
|
||||
crate_name: story.registration.crate_name,
|
||||
story: story.registration,
|
||||
surface: entry.surface,
|
||||
first: at == 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
jobs
|
||||
}
|
||||
|
||||
/// The root values the stories are shown under: the gallery's defaults in dark mode, which give ArtCraft.
|
||||
fn root_env() -> RootEnv {
|
||||
let mut env = RootEnv::default();
|
||||
let mut settings = GallerySettings::default();
|
||||
settings.mode = "dark".to_owned();
|
||||
settings.restore_env(&mut env);
|
||||
env
|
||||
}
|
||||
|
||||
/// The story shown in a card's body at the screen's top left until it settles: the frames, then a second past every
|
||||
/// fade, then the frames again.
|
||||
fn settle(frames: &mut Frames, body: &StoryBody, width: f32, state: &mut CardState, shown: &mut BodyShown) {
|
||||
let region = Rect::from_min_size(Pos2::ZERO, Vec2::new(width, Vec2::from(WINDOW).y));
|
||||
let mut frame = |frames: &mut Frames| {
|
||||
frames.frame(Vec::new(), |ui| {
|
||||
*shown = craft_ui::testing::layout::in_region(ui, region, |ui| body.show(ui, state));
|
||||
});
|
||||
};
|
||||
for _ in 0..4 {
|
||||
frame(frames);
|
||||
}
|
||||
frames.advance(1.0);
|
||||
for _ in 0..4 {
|
||||
frame(frames);
|
||||
}
|
||||
}
|
||||
|
||||
/// The story rendered: its image cropped to the story's surface and the layers it opened, in pixels.
|
||||
fn render(job: &Job, renderer: &mut Renderer, env: &RootEnv, options: &Options) -> Result<RgbaImage, String> {
|
||||
let mut frames = Frames::new();
|
||||
UiFonts::new(&I18nScripts).install(&frames.ctx);
|
||||
frames.root(env.clone());
|
||||
frames.screen(Vec2::from(WINDOW));
|
||||
frames.pixels_per_point(PIXELS_PER_POINT);
|
||||
frames.record_paint();
|
||||
let body = StoryBody::new("sheet", job.story, job.surface, options.room, Pad::Regular);
|
||||
let mut state = CardState::default();
|
||||
let mut shown = BodyShown::default();
|
||||
settle(&mut frames, &body, options.width, &mut state, &mut shown);
|
||||
if state.dialog.hidden {
|
||||
state.show_dialog();
|
||||
settle(&mut frames, &body, options.width, &mut state, &mut shown);
|
||||
}
|
||||
let crop = layer_rects(&frames.ctx).into_iter().chain(shown.flow).fold(Rect::NOTHING, Rect::union);
|
||||
let paint = frames.take_paint().ok_or("no paint recorded")?;
|
||||
let image = renderer.render(&frames.ctx, paint);
|
||||
renderer.finish();
|
||||
let image = image?;
|
||||
if !crop.is_positive() {
|
||||
return Err("blank: the story showed nothing".to_owned());
|
||||
}
|
||||
let (w, h) = (image.width(), image.height());
|
||||
let px = |v: f32, max: u32| ((v * PIXELS_PER_POINT).max(0.0) as u32).min(max);
|
||||
let (x0, y0) = (px(crop.min.x.floor(), w), px(crop.min.y.floor(), h));
|
||||
let (x1, y1) = (px(crop.max.x.ceil(), w), px(crop.max.y.ceil(), h));
|
||||
if x1 <= x0 || y1 <= y0 {
|
||||
return Err("blank: the story's rect is off screen".to_owned());
|
||||
}
|
||||
Ok(image::imageops::crop_imm(&image, x0, y0, x1 - x0, y1 - y0).to_image())
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// The message of the last panic on this thread.
|
||||
static PANIC: RefCell<String> = const { RefCell::new(String::new()) };
|
||||
/// A story is running on this thread.
|
||||
static IN_STORY: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
fn file_name(job: &Job) -> String {
|
||||
let story: String = job.story.story.name.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' { c } else { '-' }).collect();
|
||||
format!("new-{}--{story}.png", job.name)
|
||||
}
|
||||
|
||||
fn run(job: &Job, renderer: &mut Renderer, env: &RootEnv, options: &Options) -> Done {
|
||||
IN_STORY.with(|running| running.set(true));
|
||||
let rendered = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| render(job, renderer, env, options)));
|
||||
IN_STORY.with(|running| running.set(false));
|
||||
let image = match rendered {
|
||||
Ok(Ok(image)) => image,
|
||||
Ok(Err(error)) => return Done { status: error, size: None },
|
||||
Err(_) => return Done { status: format!("panic: {}", PANIC.with(|message| message.borrow().clone())), size: None },
|
||||
};
|
||||
let save = |name: &str| image.save(options.out.join(name)).map_err(|error| format!("cannot write {name}: {error}"));
|
||||
let saved = save(&file_name(job)).and_then(|()| if job.first { save(&format!("new-{}.png", job.name)) } else { Ok(()) });
|
||||
match saved {
|
||||
Ok(()) => Done { status: "ok".to_owned(), size: Some((image.width(), image.height())) },
|
||||
Err(error) => Done { status: error, size: None },
|
||||
}
|
||||
}
|
||||
|
||||
fn clean(text: &str) -> String {
|
||||
text.replace(['\t', '\n'], " ")
|
||||
}
|
||||
|
||||
fn write_tables(out: &Path, jobs: &[Job], done: &[Option<Done>]) -> std::io::Result<()> {
|
||||
let mut stories = String::from("name\tlevel\tcrate\tstory\ttitle\tfile\tstatus\twidth\theight\n");
|
||||
let mut components = String::from("name\tlevel\tcrate\tstory used\tstatus\n");
|
||||
for (job, done) in jobs.iter().zip(done) {
|
||||
let (status, size) = done.as_ref().map_or(("not run".to_owned(), None), |done| (clean(&done.status), done.size));
|
||||
let (w, h) = size.map_or((String::new(), String::new()), |(w, h)| (w.to_string(), h.to_string()));
|
||||
let story = job.story.story.name;
|
||||
let title = clean(&job.story.story.caption(&job.name));
|
||||
let _ = writeln!(stories, "{}\t{}\t{}\t{story}\t{title}\t{}\t{status}\t{w}\t{h}", job.name, job.level, job.crate_name, file_name(job));
|
||||
if job.first {
|
||||
let _ = writeln!(components, "{}\t{}\t{}\t{story}\t{status}", job.name, job.level, job.crate_name);
|
||||
}
|
||||
}
|
||||
std::fs::write(out.join("stories.tsv"), stories)?;
|
||||
std::fs::write(out.join("components.tsv"), components)
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let options = match options() {
|
||||
Ok(options) => options,
|
||||
Err(error) => {
|
||||
let _ = writeln!(std::io::stderr(), "story-render: {error}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
if let Err(error) = std::fs::create_dir_all(&options.out) {
|
||||
let _ = writeln!(std::io::stderr(), "story-render: cannot create {}: {error}", options.out.display());
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
// A story's panic is its status; any other panic goes to the default hook.
|
||||
let default = std::panic::take_hook();
|
||||
std::panic::set_hook(Box::new(move |info| {
|
||||
if !IN_STORY.with(std::cell::Cell::get) {
|
||||
default(info);
|
||||
return;
|
||||
}
|
||||
let message = info.payload().downcast_ref::<&str>().map(|s| (*s).to_owned()).or_else(|| info.payload().downcast_ref::<String>().cloned());
|
||||
let at = info.location().map(|at| format!(" at {}:{}", at.file(), at.line())).unwrap_or_default();
|
||||
PANIC.with(|last| *last.borrow_mut() = clean(&format!("{}{at}", message.unwrap_or_default())));
|
||||
}));
|
||||
let jobs = jobs(&options);
|
||||
if jobs.is_empty() {
|
||||
let _ = writeln!(std::io::stderr(), "story-render: no story matches; is the component's crate among this bin's features?");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
let done: Vec<Mutex<Option<Done>>> = jobs.iter().map(|_| Mutex::new(None)).collect();
|
||||
let next = AtomicUsize::new(0);
|
||||
std::thread::scope(|scope| {
|
||||
for _ in 0..options.threads.max(1).min(jobs.len()) {
|
||||
scope.spawn(|| {
|
||||
let env = root_env();
|
||||
let mut renderer = Renderer::new();
|
||||
loop {
|
||||
let at = next.fetch_add(1, Ordering::Relaxed);
|
||||
let Some(job) = jobs.get(at) else { break };
|
||||
let result = run(job, &mut renderer, &env, &options);
|
||||
if let Ok(mut slot) = done[at].lock() {
|
||||
*slot = Some(result);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
let done: Vec<Option<Done>> = done.into_iter().map(|slot| slot.into_inner().ok().flatten()).collect();
|
||||
if let Err(error) = write_tables(&options.out, &jobs, &done) {
|
||||
let _ = writeln!(std::io::stderr(), "story-render: cannot write the tables: {error}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
let ok = done.iter().flatten().filter(|done| done.status == "ok").count();
|
||||
let components = jobs.iter().filter(|job| job.first).count();
|
||||
let _ = writeln!(std::io::stdout(), "story-render: {ok} of {} stories of {components} components rendered", jobs.len());
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
[package]
|
||||
name = "craft-ui-gallery"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
rust-version.workspace = true
|
||||
description = "Story viewer over craft-ui's registered stories"
|
||||
publish = false
|
||||
autotests = false
|
||||
default-run = "craft-ui-gallery"
|
||||
|
||||
[lib]
|
||||
path = "src/lib.rs"
|
||||
# Every test lives in the `it` integration binary.
|
||||
test = false
|
||||
|
||||
[[bin]]
|
||||
name = "craft-ui-gallery"
|
||||
path = "src/main.rs"
|
||||
test = false
|
||||
|
||||
[[bin]]
|
||||
name = "components-index"
|
||||
path = "src/bin/components-index.rs"
|
||||
test = false
|
||||
|
||||
[[bin]]
|
||||
name = "contract-api"
|
||||
path = "src/bin/contract-api.rs"
|
||||
test = false
|
||||
|
||||
# The component sheet's renderer: every story to a PNG, offscreen (desktop only).
|
||||
[features]
|
||||
# One feature per domain crate whose stories the viewer links; `apps` is all of them and the default. A build
|
||||
# that needs one crate's stories only (the story renderer) turns the default off and names the crate.
|
||||
default = ["apps"]
|
||||
apps = ["automation", "browse", "color", "draw", "imaging", "layers", "menu", "pages", "print", "review", "table", "text", "theme-store", "timeline", "dialogs", "font-manager", "update"]
|
||||
automation = ["dep:craft-automation"]
|
||||
browse = ["dep:craft-browse"]
|
||||
color = ["dep:craft-color"]
|
||||
draw = ["dep:craft-draw"]
|
||||
imaging = ["dep:craft-imaging"]
|
||||
layers = ["dep:craft-layers"]
|
||||
menu = ["dep:craft-menu"]
|
||||
pages = ["dep:craft-pages"]
|
||||
print = ["dep:craft-print"]
|
||||
review = ["dep:craft-review"]
|
||||
table = ["dep:craft-table"]
|
||||
text = ["dep:craft-text"]
|
||||
theme-store = ["dep:craft-theme-store"]
|
||||
timeline = ["dep:craft-timeline"]
|
||||
dialogs = ["dep:craft-dialogs"]
|
||||
font-manager = ["dep:craft-font-manager"]
|
||||
update = ["dep:craft-update"]
|
||||
|
||||
[[test]]
|
||||
name = "it"
|
||||
path = "tests/it/main.rs"
|
||||
harness = false
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-ui = { workspace = true, features = ["app", "testing"] }
|
||||
craft-i18n = { workspace = true }
|
||||
craft-theme = { workspace = true }
|
||||
craft-window = { workspace = true }
|
||||
egui = { workspace = true }
|
||||
eframe = { version = "0.37", default-features = false }
|
||||
proc-macro2 = "1"
|
||||
quote = "1"
|
||||
syn = { version = "2", features = ["full"] }
|
||||
|
||||
# The viewer's saved settings and its panel layout.
|
||||
craft-behavior = { workspace = true }
|
||||
craft-settings = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
web-time = "1.1"
|
||||
|
||||
# The domain crates' stories, registered under each crate's `screen-testing`.
|
||||
craft-automation = { workspace = true, features = ["screen-testing"], optional = true }
|
||||
craft-browse = { workspace = true, features = ["screen-testing"], optional = true }
|
||||
craft-color = { workspace = true, features = ["screen-testing"], optional = true }
|
||||
craft-draw = { workspace = true, features = ["screen-testing"], optional = true }
|
||||
craft-imaging = { workspace = true, features = ["screen-testing"], optional = true }
|
||||
craft-layers = { workspace = true, features = ["screen-testing"], optional = true }
|
||||
craft-menu = { workspace = true, features = ["screen-testing"], optional = true }
|
||||
craft-pages = { workspace = true, features = ["screen-testing"], optional = true }
|
||||
craft-print = { workspace = true, features = ["screen-testing"], optional = true }
|
||||
craft-review = { workspace = true, features = ["screen-testing"], optional = true }
|
||||
craft-table = { workspace = true, features = ["screen-testing"], optional = true }
|
||||
craft-text = { workspace = true, features = ["screen-testing"], optional = true }
|
||||
craft-theme-store = { workspace = true, features = ["screen-testing"], optional = true }
|
||||
craft-timeline = { workspace = true, features = ["screen-testing"], optional = true }
|
||||
|
||||
# Native only: these crates do not build for the web, so their stories are not in the web gallery.
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
craft-dialogs = { workspace = true, features = ["screen-testing"], optional = true }
|
||||
craft-font-manager = { workspace = true, features = ["screen-testing"], optional = true }
|
||||
craft-update = { workspace = true, features = ["screen-testing"], optional = true }
|
||||
# The component sheet crops and writes its images.
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
wasm-bindgen-futures = "0.4"
|
||||
|
||||
[dev-dependencies]
|
||||
@@ -0,0 +1,16 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>craft-ui stories</title>
|
||||
<link data-trunk rel="rust" data-bin="craft-ui-gallery" data-wasm-opt="z" />
|
||||
<style>
|
||||
html, body { margin: 0; height: 100%; overflow: hidden; }
|
||||
canvas { display: block; width: 100%; height: 100%; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<canvas id="gallery_canvas"></canvas>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,40 @@
|
||||
//! Writes `docs/components-index.md`: every registered component type and every craft-behavior module, with its
|
||||
//! module and one line of purpose.
|
||||
//!
|
||||
//! `cargo run -p craft-ui-gallery --bin components-index` rewrites the file; with `--check` it exits with an error
|
||||
//! when the file differs from what the registrations give. The `components_index` trial of craft-ui makes the same
|
||||
//! comparison.
|
||||
|
||||
use craft_ui::testing::index::components_index;
|
||||
use craft_ui::testing::library_registrations;
|
||||
use std::fs;
|
||||
use std::io::Write as _;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::ExitCode;
|
||||
|
||||
const OUTPUT: &str = "docs/components-index.md";
|
||||
|
||||
fn workspace_root() -> PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("../..")
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let root = workspace_root();
|
||||
let text = components_index(&root, &library_registrations());
|
||||
let target = root.join(OUTPUT);
|
||||
if std::env::args().any(|argument| argument == "--check") {
|
||||
let current = fs::read_to_string(&target).unwrap_or_default();
|
||||
if current == text {
|
||||
return ExitCode::SUCCESS;
|
||||
}
|
||||
let _ = writeln!(std::io::stderr(), "{OUTPUT} is stale; run the generator");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
match fs::write(&target, text) {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(error) => {
|
||||
let _ = writeln!(std::io::stderr(), "cannot write {OUTPUT}: {error}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,714 @@
|
||||
//! Writes `docs/contract-api.md`: every public item of craft-behavior and of craft-ui's shared modules (everything
|
||||
//! but the family modules), with its path, its signature line and the first line of its doc comment.
|
||||
//!
|
||||
//! `cargo run -p craft-ui-gallery --bin contract-api` rewrites the file. The sources are parsed with `syn`, following
|
||||
//! `mod`, `pub mod` and `pub use` from each crate root, so a re-export is listed under the path it is public at.
|
||||
//! Setters that `#[derive(Props)]` writes and impls written by other derives have no source to parse; the item's
|
||||
//! own docs and `Props` list them.
|
||||
|
||||
use quote::ToTokens;
|
||||
use std::collections::BTreeMap;
|
||||
use std::fmt::Write as _;
|
||||
use std::fs;
|
||||
use std::io::Write as _;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::ExitCode;
|
||||
use syn::{Attribute, Expr, ImplItem, Item, ItemUse, Lit, Meta, TraitItem, UseTree, Visibility};
|
||||
|
||||
const OUTPUT: &str = "docs/contract-api.md";
|
||||
|
||||
/// The crates listed, with the root module path of each and the modules of the second one left out: craft-ui's
|
||||
/// family modules and its patterns and shell layers, which are not shared contract.
|
||||
const CRATES: [(&str, &str); 2] = [("craft_behavior", "crates/behavior/src/lib.rs"), ("craft_ui", "crates/ui/src/lib.rs")];
|
||||
const SHARED_UI_MODULES: [&str; 7] = ["contract", "layout", "layout_components", "primitives", "runtime", "style", "testing"];
|
||||
|
||||
/// The depth at which following a chain of re-exports stops.
|
||||
const CHAIN_LIMIT: usize = 8;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Member {
|
||||
signature: String,
|
||||
doc: String,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Def {
|
||||
name: String,
|
||||
/// The line shown for the item: `pub struct Name<..>`, `pub fn name(..) -> ..`.
|
||||
signature: String,
|
||||
doc: String,
|
||||
public: bool,
|
||||
/// `#[doc(hidden)]`: kept so a re-export of it resolves, never listed.
|
||||
hidden: bool,
|
||||
members: Vec<Member>,
|
||||
is_type: bool,
|
||||
}
|
||||
|
||||
struct Reexport {
|
||||
alias: String,
|
||||
/// The absolute path, or `None` when it leaves the parsed crates.
|
||||
target: Option<Vec<String>>,
|
||||
/// The path as written, for an external re-export.
|
||||
written: String,
|
||||
glob: bool,
|
||||
/// A `#[doc(hidden)]` re-export: followed to resolve names, never listed.
|
||||
hidden: bool,
|
||||
}
|
||||
|
||||
struct Module {
|
||||
doc: String,
|
||||
/// Declared `pub mod` all the way from the crate root.
|
||||
reachable: bool,
|
||||
defs: Vec<Def>,
|
||||
reexports: Vec<Reexport>,
|
||||
children: Vec<String>,
|
||||
}
|
||||
|
||||
struct Impl {
|
||||
type_name: String,
|
||||
module: String,
|
||||
members: Vec<Member>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Tree {
|
||||
modules: BTreeMap<String, Module>,
|
||||
impls: Vec<Impl>,
|
||||
/// Exported macros, by crate root.
|
||||
macros: Vec<(String, Def)>,
|
||||
}
|
||||
|
||||
fn workspace_root() -> PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("../..")
|
||||
}
|
||||
|
||||
fn first_doc_line(attrs: &[Attribute]) -> String {
|
||||
for attr in attrs {
|
||||
if !attr.path().is_ident("doc") {
|
||||
continue;
|
||||
}
|
||||
if let Meta::NameValue(pair) = &attr.meta
|
||||
&& let Expr::Lit(literal) = &pair.value
|
||||
&& let Lit::Str(text) = &literal.lit
|
||||
{
|
||||
let line = text.value();
|
||||
let line = line.trim();
|
||||
if !line.is_empty() {
|
||||
return line.to_owned();
|
||||
}
|
||||
}
|
||||
}
|
||||
String::new()
|
||||
}
|
||||
|
||||
fn is_hidden(attrs: &[Attribute]) -> bool {
|
||||
attrs.iter().any(|attr| {
|
||||
let text = attr.to_token_stream().to_string();
|
||||
(attr.path().is_ident("doc") && text.contains("hidden")) || (attr.path().is_ident("cfg") && text.replace(' ', "") == "#[cfg(test)]")
|
||||
})
|
||||
}
|
||||
|
||||
fn is_public(vis: &Visibility) -> bool {
|
||||
matches!(vis, Visibility::Public(_))
|
||||
}
|
||||
|
||||
/// Token text with the spacing of source code.
|
||||
fn tidy(tokens: impl ToTokens) -> String {
|
||||
let mut text = tokens.to_token_stream().to_string();
|
||||
for (from, to) in [
|
||||
(" :: ", "::"),
|
||||
(" ::", "::"),
|
||||
(":: ", "::"),
|
||||
("& mut ", "&mut "),
|
||||
("& ", "&"),
|
||||
(" ,", ","),
|
||||
(" ;", ";"),
|
||||
("< ", "<"),
|
||||
(" <", "<"),
|
||||
(" >", ">"),
|
||||
(" :", ":"),
|
||||
("( ", "("),
|
||||
(" )", ")"),
|
||||
(" (", "("),
|
||||
("->(", "-> ("),
|
||||
("[ ", "["),
|
||||
(" ]", "]"),
|
||||
("? ", "?"),
|
||||
(" . ", "."),
|
||||
(" !", "!"),
|
||||
] {
|
||||
text = text.replace(from, to);
|
||||
}
|
||||
text.replace("> >", ">>").replace("pub(", "pub (")
|
||||
}
|
||||
|
||||
fn fn_line(vis: &Visibility, sig: &syn::Signature) -> String {
|
||||
let prefix = if is_public(vis) { "pub " } else { "" };
|
||||
format!("{prefix}{}", tidy(sig))
|
||||
}
|
||||
|
||||
fn generics_and_where(generics: &syn::Generics) -> String {
|
||||
let mut text = tidy(generics);
|
||||
if let Some(clause) = &generics.where_clause {
|
||||
let _ = write!(text, " {}", tidy(clause));
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
fn fields_summary(fields: &syn::Fields) -> String {
|
||||
match fields {
|
||||
syn::Fields::Named(named) => {
|
||||
let shown: Vec<String> = named
|
||||
.named
|
||||
.iter()
|
||||
.filter(|field| is_public(&field.vis))
|
||||
.map(|field| format!("pub {}: {}", field.ident.as_ref().map(ToString::to_string).unwrap_or_default(), tidy(&field.ty)))
|
||||
.collect();
|
||||
if shown.is_empty() { String::new() } else { format!(" {{ {} }}", shown.join(", ")) }
|
||||
}
|
||||
syn::Fields::Unnamed(unnamed) => {
|
||||
let shown: Vec<String> =
|
||||
unnamed.unnamed.iter().filter(|field| is_public(&field.vis)).map(|field| format!("pub {}", tidy(&field.ty))).collect();
|
||||
if shown.is_empty() { String::new() } else { format!("({})", shown.join(", ")) }
|
||||
}
|
||||
syn::Fields::Unit => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn variant_line(variant: &syn::Variant) -> String {
|
||||
let name = variant.ident.to_string();
|
||||
match &variant.fields {
|
||||
syn::Fields::Unit => name,
|
||||
syn::Fields::Unnamed(unnamed) => format!("{name}({})", unnamed.unnamed.iter().map(|field| tidy(&field.ty)).collect::<Vec<_>>().join(", ")),
|
||||
syn::Fields::Named(named) => format!(
|
||||
"{name} {{ {} }}",
|
||||
named
|
||||
.named
|
||||
.iter()
|
||||
.map(|field| format!("{}: {}", field.ident.as_ref().map(ToString::to_string).unwrap_or_default(), tidy(&field.ty)))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn def_of(item: &Item) -> Option<Def> {
|
||||
let (name, signature, doc, vis, members, is_type) = match item {
|
||||
Item::Fn(function) => {
|
||||
(function.sig.ident.to_string(), fn_line(&function.vis, &function.sig), first_doc_line(&function.attrs), &function.vis, Vec::new(), false)
|
||||
}
|
||||
Item::Struct(item) => {
|
||||
let signature = format!("pub struct {}{}{}", item.ident, generics_and_where(&item.generics), fields_summary(&item.fields));
|
||||
(item.ident.to_string(), signature, first_doc_line(&item.attrs), &item.vis, Vec::new(), true)
|
||||
}
|
||||
Item::Enum(item) => {
|
||||
let variants: Vec<String> = item.variants.iter().map(variant_line).collect();
|
||||
let signature = format!("pub enum {}{} {{ {} }}", item.ident, generics_and_where(&item.generics), variants.join(", "));
|
||||
(item.ident.to_string(), signature, first_doc_line(&item.attrs), &item.vis, Vec::new(), true)
|
||||
}
|
||||
Item::Trait(item) => {
|
||||
let supers = if item.supertraits.is_empty() { String::new() } else { format!(": {}", tidy(&item.supertraits)) };
|
||||
let signature = format!("pub trait {}{}{}", item.ident, generics_and_where(&item.generics), supers);
|
||||
let members = item
|
||||
.items
|
||||
.iter()
|
||||
.filter_map(|member| match member {
|
||||
TraitItem::Fn(function) => Some(Member { signature: tidy(&function.sig), doc: first_doc_line(&function.attrs) }),
|
||||
TraitItem::Type(assoc) => Some(Member { signature: format!("type {}", assoc.ident), doc: first_doc_line(&assoc.attrs) }),
|
||||
TraitItem::Const(assoc) => {
|
||||
Some(Member { signature: format!("const {}: {}", assoc.ident, tidy(&assoc.ty)), doc: first_doc_line(&assoc.attrs) })
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
(item.ident.to_string(), signature, first_doc_line(&item.attrs), &item.vis, members, true)
|
||||
}
|
||||
Item::Type(item) => {
|
||||
let signature = format!("pub type {}{} = {}", item.ident, generics_and_where(&item.generics), tidy(&item.ty));
|
||||
(item.ident.to_string(), signature, first_doc_line(&item.attrs), &item.vis, Vec::new(), true)
|
||||
}
|
||||
Item::Const(item) => (
|
||||
item.ident.to_string(),
|
||||
format!("pub const {}: {}", item.ident, tidy(&item.ty)),
|
||||
first_doc_line(&item.attrs),
|
||||
&item.vis,
|
||||
Vec::new(),
|
||||
false,
|
||||
),
|
||||
Item::Static(item) => (
|
||||
item.ident.to_string(),
|
||||
format!("pub static {}: {}", item.ident, tidy(&item.ty)),
|
||||
first_doc_line(&item.attrs),
|
||||
&item.vis,
|
||||
Vec::new(),
|
||||
false,
|
||||
),
|
||||
_ => return None,
|
||||
};
|
||||
let hidden = is_hidden(attrs_of(item));
|
||||
Some(Def { name, signature, doc, public: is_public(vis) && !hidden, hidden, members, is_type })
|
||||
}
|
||||
|
||||
/// The flag types a `bitflags!` invocation declares: `pub struct Name: Bits { .. }` with its first doc line.
|
||||
fn bitflags_defs(tokens: &proc_macro2::TokenStream) -> Vec<Def> {
|
||||
let mut defs = Vec::new();
|
||||
let mut doc = String::new();
|
||||
let mut previous: Option<proc_macro2::TokenTree> = None;
|
||||
let mut iter = tokens.clone().into_iter().peekable();
|
||||
let mut public = false;
|
||||
while let Some(token) = iter.next() {
|
||||
match &token {
|
||||
proc_macro2::TokenTree::Group(group)
|
||||
if previous.as_ref().is_some_and(|t| matches!(t, proc_macro2::TokenTree::Punct(p) if p.as_char() == '#')) =>
|
||||
{
|
||||
let text = group.stream().to_string();
|
||||
if doc.is_empty()
|
||||
&& let Some(rest) = text.strip_prefix("doc = \"")
|
||||
{
|
||||
doc = rest.trim_end_matches('"').trim().to_owned();
|
||||
}
|
||||
}
|
||||
proc_macro2::TokenTree::Ident(ident) if ident == "pub" => public = true,
|
||||
proc_macro2::TokenTree::Ident(ident) if ident == "struct" => {
|
||||
if let Some(proc_macro2::TokenTree::Ident(name)) = iter.next() {
|
||||
let mut bits = String::new();
|
||||
if matches!(iter.peek(), Some(proc_macro2::TokenTree::Punct(p)) if p.as_char() == ':') {
|
||||
iter.next();
|
||||
if let Some(proc_macro2::TokenTree::Ident(ty)) = iter.next() {
|
||||
bits = format!(": {ty}");
|
||||
}
|
||||
}
|
||||
defs.push(Def {
|
||||
name: name.to_string(),
|
||||
signature: format!("pub struct {name}{bits} (flag set)"),
|
||||
doc: std::mem::take(&mut doc),
|
||||
public,
|
||||
hidden: false,
|
||||
members: Vec::new(),
|
||||
is_type: true,
|
||||
});
|
||||
public = false;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
previous = Some(token);
|
||||
}
|
||||
defs
|
||||
}
|
||||
|
||||
fn attrs_of(item: &Item) -> &[Attribute] {
|
||||
match item {
|
||||
Item::Fn(item) => &item.attrs,
|
||||
Item::Struct(item) => &item.attrs,
|
||||
Item::Enum(item) => &item.attrs,
|
||||
Item::Trait(item) => &item.attrs,
|
||||
Item::Type(item) => &item.attrs,
|
||||
Item::Const(item) => &item.attrs,
|
||||
Item::Static(item) => &item.attrs,
|
||||
Item::Mod(item) => &item.attrs,
|
||||
Item::Use(item) => &item.attrs,
|
||||
Item::Impl(item) => &item.attrs,
|
||||
_ => &[],
|
||||
}
|
||||
}
|
||||
|
||||
/// Where `use` paths that start with `crate`, `self`, `super` or a sibling name start from.
|
||||
fn absolute(path: &[String], here: &str, known: &dyn Fn(&str) -> bool) -> Option<Vec<String>> {
|
||||
let here_parts: Vec<String> = here.split("::").map(str::to_owned).collect();
|
||||
let (first, rest) = path.split_first()?;
|
||||
let mut base: Vec<String> = match first.as_str() {
|
||||
"crate" => here_parts.first().cloned().into_iter().collect(),
|
||||
"self" => here_parts,
|
||||
"super" => here_parts.get(..here_parts.len().saturating_sub(1))?.to_vec(),
|
||||
other if CRATES.iter().any(|(name, _)| *name == other) => vec![other.to_owned()],
|
||||
_ => {
|
||||
let mut relative = here_parts.clone();
|
||||
relative.extend(path.iter().cloned());
|
||||
let parent = relative.get(..relative.len().saturating_sub(1)).map(|parent| parent.join("::")).unwrap_or_default();
|
||||
return (known(&relative.join("::")) || known(&parent)).then_some(relative);
|
||||
}
|
||||
};
|
||||
let mut rest = rest;
|
||||
// `super::super::x`
|
||||
while base.len() > 1 && rest.first().is_some_and(|segment| segment == "super") {
|
||||
base.pop();
|
||||
rest = rest.get(1..)?;
|
||||
}
|
||||
base.extend(rest.iter().cloned());
|
||||
Some(base)
|
||||
}
|
||||
|
||||
fn collect_use(tree: &UseTree, prefix: &mut Vec<String>, found: &mut Vec<(Vec<String>, String, bool)>) {
|
||||
match tree {
|
||||
UseTree::Path(path) => {
|
||||
prefix.push(path.ident.to_string());
|
||||
collect_use(&path.tree, prefix, found);
|
||||
prefix.pop();
|
||||
}
|
||||
UseTree::Name(name) => {
|
||||
let mut full = prefix.clone();
|
||||
let alias = name.ident.to_string();
|
||||
if alias == "self" {
|
||||
let last = full.last().cloned().unwrap_or_default();
|
||||
found.push((full, last, false));
|
||||
} else {
|
||||
full.push(alias.clone());
|
||||
found.push((full, alias, false));
|
||||
}
|
||||
}
|
||||
UseTree::Rename(rename) => {
|
||||
let mut full = prefix.clone();
|
||||
full.push(rename.ident.to_string());
|
||||
found.push((full, rename.rename.to_string(), false));
|
||||
}
|
||||
UseTree::Glob(_) => found.push((prefix.clone(), "*".to_owned(), true)),
|
||||
UseTree::Group(group) => {
|
||||
for inner in &group.items {
|
||||
collect_use(inner, prefix, found);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A child module to walk: its name, its directory, whether it is public from the root and its inline content with doc.
|
||||
type PendingModule = (String, PathBuf, bool, Option<(String, Vec<Item>)>);
|
||||
|
||||
struct Walker<'a> {
|
||||
tree: &'a mut Tree,
|
||||
}
|
||||
|
||||
impl Walker<'_> {
|
||||
fn file(&mut self, path: &Path, module: &str, reachable: bool) {
|
||||
let Ok(source) = fs::read_to_string(path) else { return };
|
||||
let Ok(file) = syn::parse_file(&source) else { return };
|
||||
let stem = path.file_stem().and_then(|stem| stem.to_str()).unwrap_or_default();
|
||||
let parent = path.parent().map(Path::to_path_buf).unwrap_or_default();
|
||||
let dir = if matches!(stem, "lib" | "mod" | "main") { parent } else { parent.join(stem) };
|
||||
let doc = first_doc_line(&file.attrs);
|
||||
self.items(&file.items, module, &dir, reachable, doc);
|
||||
}
|
||||
|
||||
fn items(&mut self, items: &[Item], module: &str, dir: &Path, reachable: bool, doc: String) {
|
||||
let mut entry = Module { doc, reachable, defs: Vec::new(), reexports: Vec::new(), children: Vec::new() };
|
||||
let mut pending: Vec<PendingModule> = Vec::new();
|
||||
for item in items {
|
||||
if is_hidden(attrs_of(item))
|
||||
&& !matches!(
|
||||
item,
|
||||
Item::Use(_) | Item::Fn(_) | Item::Struct(_) | Item::Enum(_) | Item::Trait(_) | Item::Type(_) | Item::Const(_) | Item::Static(_)
|
||||
)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
match item {
|
||||
Item::Mod(declared) => {
|
||||
let name = declared.ident.to_string();
|
||||
let public = is_public(&declared.vis);
|
||||
entry.children.push(name.clone());
|
||||
let inline = declared.content.as_ref().map(|(_, content)| content.clone());
|
||||
pending.push((name, dir.to_path_buf(), reachable && public, inline.map(|content| (first_doc_line(&declared.attrs), content))));
|
||||
}
|
||||
Item::Use(import) => Self::uses(import, &mut entry, is_hidden(&import.attrs)),
|
||||
Item::Impl(imp) if imp.trait_.is_none() => {
|
||||
if let syn::Type::Path(path) = &*imp.self_ty
|
||||
&& let Some(last) = path.path.segments.last()
|
||||
{
|
||||
let members = imp
|
||||
.items
|
||||
.iter()
|
||||
.filter_map(|member| match member {
|
||||
ImplItem::Fn(function) if is_public(&function.vis) && !is_hidden(&function.attrs) => {
|
||||
Some(Member { signature: fn_line(&function.vis, &function.sig), doc: first_doc_line(&function.attrs) })
|
||||
}
|
||||
ImplItem::Const(constant) if is_public(&constant.vis) => Some(Member {
|
||||
signature: format!("pub const {}: {}", constant.ident, tidy(&constant.ty)),
|
||||
doc: first_doc_line(&constant.attrs),
|
||||
}),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
self.tree.impls.push(Impl { type_name: last.ident.to_string(), module: module.to_owned(), members });
|
||||
}
|
||||
}
|
||||
Item::Macro(mac) if mac.mac.path.segments.last().is_some_and(|segment| segment.ident == "bitflags") => {
|
||||
entry.defs.extend(bitflags_defs(&mac.mac.tokens));
|
||||
}
|
||||
Item::Macro(mac) if mac.attrs.iter().any(|attr| attr.path().is_ident("macro_export")) && mac.mac.path.is_ident("macro_rules") => {
|
||||
if let Some(name) = &mac.ident {
|
||||
let root = module.split("::").next().unwrap_or_default().to_owned();
|
||||
let def = Def {
|
||||
name: format!("{name}!"),
|
||||
signature: format!("macro_rules! {name}"),
|
||||
doc: first_doc_line(&mac.attrs),
|
||||
public: true,
|
||||
hidden: false,
|
||||
members: Vec::new(),
|
||||
is_type: false,
|
||||
};
|
||||
self.tree.macros.push((root, def));
|
||||
}
|
||||
}
|
||||
other => {
|
||||
if let Some(def) = def_of(other) {
|
||||
entry.defs.push(def);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.tree.modules.insert(module.to_owned(), entry);
|
||||
for (name, dir, reachable, inline) in pending {
|
||||
let child = format!("{module}::{name}");
|
||||
if let Some((doc, content)) = inline {
|
||||
self.items(&content, &child, &dir.join(&name), reachable, doc);
|
||||
continue;
|
||||
}
|
||||
let flat = dir.join(format!("{name}.rs"));
|
||||
let nested = dir.join(&name).join("mod.rs");
|
||||
if flat.exists() {
|
||||
self.file(&flat, &child, reachable);
|
||||
} else if nested.exists() {
|
||||
self.file(&nested, &child, reachable);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn uses(import: &ItemUse, entry: &mut Module, hidden: bool) {
|
||||
if !is_public(&import.vis) {
|
||||
return;
|
||||
}
|
||||
let mut found = Vec::new();
|
||||
collect_use(&import.tree, &mut Vec::new(), &mut found);
|
||||
for (path, alias, glob) in found {
|
||||
let written = path.join("::");
|
||||
// The target resolves once every module is parsed.
|
||||
entry.reexports.push(Reexport { alias, target: Some(path), written, glob, hidden });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Tree {
|
||||
fn resolve_targets(&mut self) {
|
||||
let declared: Vec<String> = self.modules.keys().cloned().collect();
|
||||
for key in declared.clone() {
|
||||
let known = |path: &str| declared.iter().any(|module| module == path);
|
||||
if let Some(module) = self.modules.get_mut(&key) {
|
||||
for export in &mut module.reexports {
|
||||
let Some(path) = export.target.take() else { continue };
|
||||
export.target = absolute(&path, &key, &known);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn attach_impls(&mut self) {
|
||||
let impls = std::mem::take(&mut self.impls);
|
||||
for imp in impls {
|
||||
let same =
|
||||
self.modules.get_mut(&imp.module).and_then(|module| module.defs.iter_mut().find(|def| def.is_type && def.name == imp.type_name));
|
||||
if let Some(def) = same {
|
||||
def.members.extend(imp.members);
|
||||
continue;
|
||||
}
|
||||
// An impl written in a child module of the type's module.
|
||||
let mut parent = imp.module.as_str();
|
||||
let mut members = Some(imp.members);
|
||||
while let Some((up, _)) = parent.rsplit_once("::") {
|
||||
parent = up;
|
||||
if let Some(def) =
|
||||
self.modules.get_mut(parent).and_then(|module| module.defs.iter_mut().find(|def| def.is_type && def.name == imp.type_name))
|
||||
&& let Some(members) = members.take()
|
||||
{
|
||||
def.members.extend(members);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn def(&self, module: &str, name: &str, depth: usize) -> Option<(String, &Def)> {
|
||||
let entry = self.modules.get(module)?;
|
||||
if let Some(def) = entry.defs.iter().find(|def| def.name == name) {
|
||||
return Some((module.to_owned(), def));
|
||||
}
|
||||
if depth >= CHAIN_LIMIT {
|
||||
return None;
|
||||
}
|
||||
for export in &entry.reexports {
|
||||
if export.glob {
|
||||
if let Some(target) = &export.target
|
||||
&& let Some(found) = self.def(&target.join("::"), name, depth + 1)
|
||||
{
|
||||
return Some(found);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if export.alias == name
|
||||
&& let Some(target) = &export.target
|
||||
&& let Some((last, parent)) = target.split_last()
|
||||
&& let Some(found) = self.def(&parent.join("::"), last, depth + 1)
|
||||
{
|
||||
return Some(found);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The items a glob `use` of `module` brings in.
|
||||
fn glob_names(&self, module: &str, depth: usize) -> Vec<String> {
|
||||
let Some(entry) = self.modules.get(module) else { return Vec::new() };
|
||||
let mut names: Vec<String> = entry.defs.iter().filter(|def| def.public).map(|def| def.name.clone()).collect();
|
||||
if depth < CHAIN_LIMIT {
|
||||
for export in &entry.reexports {
|
||||
match (&export.target, export.glob) {
|
||||
(Some(target), true) => names.extend(self.glob_names(&target.join("::"), depth + 1)),
|
||||
(Some(_), false) => names.push(export.alias.clone()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
names
|
||||
}
|
||||
}
|
||||
|
||||
fn describe(out: &mut String, path: &str, def: &Def) {
|
||||
let doc = if def.doc.is_empty() { String::new() } else { format!(" {}", def.doc) };
|
||||
let _ = writeln!(out, "- `{path}`: `{}`.{doc}", def.signature);
|
||||
for member in &def.members {
|
||||
let doc = if member.doc.is_empty() { String::new() } else { format!(" {}", member.doc) };
|
||||
let _ = writeln!(out, " - `{}`.{doc}", member.signature);
|
||||
}
|
||||
}
|
||||
|
||||
fn included(path: &str) -> bool {
|
||||
let mut parts = path.split("::");
|
||||
match (parts.next(), parts.next()) {
|
||||
(Some("craft_ui"), Some(top)) => SHARED_UI_MODULES.contains(&top),
|
||||
(Some("craft_ui"), None) | (Some("craft_behavior"), _) => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn write_module(tree: &Tree, path: &str, out: &mut String) {
|
||||
let Some(module) = tree.modules.get(path) else { return };
|
||||
if !module.reachable {
|
||||
return;
|
||||
}
|
||||
let mut body = String::new();
|
||||
let mut defs: Vec<&Def> = module.defs.iter().filter(|def| def.public).collect();
|
||||
defs.sort_by(|a, b| a.name.cmp(&b.name));
|
||||
for def in defs {
|
||||
describe(&mut body, &format!("{path}::{}", def.name), def);
|
||||
}
|
||||
let is_root = !path.contains("::");
|
||||
if is_root {
|
||||
let mut seen: Vec<&str> = Vec::new();
|
||||
for (root, def) in &tree.macros {
|
||||
if root == path && !def.name.starts_with("__") && !seen.contains(&def.name.as_str()) {
|
||||
seen.push(&def.name);
|
||||
describe(&mut body, &format!("{path}::{}", def.name), def);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut exports: Vec<(String, String)> = Vec::new();
|
||||
for export in module.reexports.iter().filter(|export| !export.hidden) {
|
||||
let Some(target) = &export.target else {
|
||||
if !export.glob {
|
||||
exports.push((
|
||||
export.alias.clone(),
|
||||
format!("- `{path}::{}`: re-export of `{}` (outside these crates).\n", export.alias, export.written),
|
||||
));
|
||||
}
|
||||
continue;
|
||||
};
|
||||
let names = if export.glob { tree.glob_names(&target.join("::"), 0) } else { vec![export.alias.clone()] };
|
||||
for name in names {
|
||||
let source = if export.glob {
|
||||
Some((target.join("::"), name.as_str()))
|
||||
} else {
|
||||
target.split_last().map(|(last, parent)| (parent.join("::"), last.as_str()))
|
||||
};
|
||||
let Some((from, original)) = source else { continue };
|
||||
let mut text = String::new();
|
||||
match tree.def(&from, original, 0) {
|
||||
Some((_, def)) if def.hidden => {}
|
||||
Some((home, def)) => {
|
||||
let public_home = tree.modules.get(&home).is_some_and(|home_module| home_module.reachable) && included(&home) && def.public;
|
||||
if public_home && home != path {
|
||||
let _ = writeln!(text, "- `{path}::{name}`: re-export of `{home}::{}`.", def.name);
|
||||
} else {
|
||||
let mut shown = def.clone();
|
||||
shown.name.clone_from(&name);
|
||||
describe(&mut text, &format!("{path}::{name}"), &shown);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let known_module = tree.modules.contains_key(&format!("{from}::{original}"));
|
||||
if known_module {
|
||||
let _ = writeln!(text, "- `{path}::{name}`: re-export of the module `{from}::{original}`.");
|
||||
} else if !export.glob {
|
||||
let _ = writeln!(text, "- `{path}::{name}`: re-export of `{from}::{original}` (defined outside these crates).");
|
||||
}
|
||||
}
|
||||
}
|
||||
if !text.is_empty() {
|
||||
exports.push((name, text));
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
exports.dedup_by(|a, b| a.0 == b.0);
|
||||
for (_, text) in exports {
|
||||
body.push_str(&text);
|
||||
}
|
||||
if !body.is_empty() {
|
||||
let _ = writeln!(out, "## `{path}`\n");
|
||||
if !module.doc.is_empty() {
|
||||
let _ = writeln!(out, "{}\n", module.doc);
|
||||
}
|
||||
out.push_str(&body);
|
||||
out.push('\n');
|
||||
}
|
||||
let mut children = module.children.clone();
|
||||
children.sort();
|
||||
for child in children {
|
||||
let child_path = format!("{path}::{child}");
|
||||
if included(&child_path) {
|
||||
write_module(tree, &child_path, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn listing(root: &Path) -> String {
|
||||
let mut tree = Tree::default();
|
||||
for (name, file) in CRATES {
|
||||
let mut walker = Walker { tree: &mut tree };
|
||||
walker.file(&root.join(file), name, true);
|
||||
}
|
||||
tree.resolve_targets();
|
||||
tree.attach_impls();
|
||||
let mut out = String::new();
|
||||
out.push_str(
|
||||
"# Contract API\n\nGenerated by `cargo run -p craft-ui-gallery --bin contract-api`; do not edit. Every public item of\n\
|
||||
`craft_behavior` and of the shared modules of `craft_ui` (`contract`, `layout`, `layout_components`, `primitives`,\n\
|
||||
`runtime`, `style`, `testing` and the crate root), by public path, with its signature line and the first line of\n\
|
||||
its doc comment. Inherent methods and trait methods are indented under their type. Setters written by\n\
|
||||
`#[derive(Props)]` are not listed: each `#[prop]` field of a type is a setter of the same name.\n\n",
|
||||
);
|
||||
for (name, _) in CRATES {
|
||||
write_module(&tree, name, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let root = workspace_root();
|
||||
let text = listing(&root);
|
||||
match fs::write(root.join(OUTPUT), text) {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(error) => {
|
||||
let _ = writeln!(std::io::stderr(), "cannot write {OUTPUT}: {error}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,418 @@
|
||||
//! One card: stories live on their surface under a header with the component's name and, while a story differs from
|
||||
//! its start, Reset; the Open command of an Overview card opens the component's tab. A card of several stories lays
|
||||
//! them out as the component's catalog entry says, each under its caption. Each story runs in an embedded shell, so
|
||||
//! its dialogs open inside the card. [`StoryBody`] is the story part alone, which the component sheet renders too.
|
||||
|
||||
use crate::viewer::{CardState, Cells, DialogState};
|
||||
use craft_behavior::Proposal;
|
||||
use craft_behavior::{ColumnWidth, IconId};
|
||||
use craft_i18n::Direction;
|
||||
use craft_theme::{ControlSize, Mode};
|
||||
use craft_ui::buttons::Button;
|
||||
use craft_ui::contract::Show as _;
|
||||
use craft_ui::contract::{CommandSet, Commands as _, Gap, Pad, Props as _, ShowContainer as _, Sizing, StoryLayout, Surface, ThemeScope};
|
||||
use craft_ui::display::{Shade, Text};
|
||||
use craft_ui::layout_components::{Grid, Stack};
|
||||
use craft_ui::runtime::env::{BodyMode, ShellCx, WindowKey, with_env};
|
||||
use craft_ui::sections::{HeaderCommand, HeaderStrength, Panel};
|
||||
use craft_ui::shell::AppShell;
|
||||
use craft_ui::style::SurfaceKind;
|
||||
use craft_ui::testing::{StoryData, StoryOutput, StoryRegistration};
|
||||
|
||||
/// A story's show function.
|
||||
type StoryFn = fn(&mut Ui, &mut StoryData) -> StoryOutput;
|
||||
use egui::{Id, Rect, Ui, vec2};
|
||||
|
||||
/// The header commands of a card.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, CommandSet)]
|
||||
#[command(prefix = "galleryCard", scope = "gallery.card")]
|
||||
#[non_exhaustive]
|
||||
pub enum CardCommands {
|
||||
/// Open the component's tab.
|
||||
#[command(label = "Open", icon = "open")]
|
||||
Open,
|
||||
/// Give the story its start values.
|
||||
#[command(label = "Reset", icon = "undo")]
|
||||
Reset,
|
||||
/// Use the card's value, in a Variants view.
|
||||
#[command(label = "Use", icon = "check")]
|
||||
Use,
|
||||
}
|
||||
|
||||
/// The appearance values a card sets for its story beyond the window's.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct Look {
|
||||
/// The mode the story's tokens resolve in.
|
||||
pub mode: Option<Mode>,
|
||||
/// The layout direction.
|
||||
pub direction: Option<Direction>,
|
||||
/// The control size.
|
||||
pub size: Option<ControlSize>,
|
||||
}
|
||||
|
||||
/// One story a card shows.
|
||||
#[non_exhaustive]
|
||||
pub struct CardStory<'a> {
|
||||
/// The index of the story in the catalog: the key of its state.
|
||||
pub index: usize,
|
||||
/// The story.
|
||||
pub story: &'static StoryRegistration,
|
||||
/// The story's caption.
|
||||
pub caption: &'a str,
|
||||
}
|
||||
|
||||
impl<'a> CardStory<'a> {
|
||||
/// The story at catalog index `index`, under `caption`.
|
||||
pub fn new(index: usize, story: &'static StoryRegistration, caption: &'a str) -> Self {
|
||||
CardStory { index, story, caption }
|
||||
}
|
||||
}
|
||||
|
||||
/// What one card shows.
|
||||
#[non_exhaustive]
|
||||
pub struct Card<'a> {
|
||||
/// The id scope of the card: unique among the cards of a pass.
|
||||
pub key: String,
|
||||
/// The component's display name.
|
||||
pub title: &'a str,
|
||||
/// A note after the title.
|
||||
pub note: Option<&'a str>,
|
||||
/// The stories, in the order they show. A card of more than one shows each under its caption.
|
||||
pub stories: &'a [CardStory<'a>],
|
||||
/// How the stories are laid out together.
|
||||
pub layout: StoryLayout,
|
||||
/// The surface the stories sit on.
|
||||
pub surface: Surface,
|
||||
/// The height a story that fills is given: the visible height of the view the cards scroll in, as the old
|
||||
/// gallery's tiles gave it.
|
||||
pub room: f32,
|
||||
/// Whether the header has Open.
|
||||
pub open: bool,
|
||||
/// Whether the header has Use.
|
||||
pub usable: bool,
|
||||
/// Whether the card has the selection ring.
|
||||
pub selected: bool,
|
||||
/// The values the card sets for its stories.
|
||||
pub look: Look,
|
||||
/// Whether the stories' wheel takers take the wheel only while focused or armed: a card among others in a
|
||||
/// scrolling overview.
|
||||
pub gated: bool,
|
||||
}
|
||||
|
||||
/// What a card reported in a pass.
|
||||
#[derive(Debug, Default)]
|
||||
#[non_exhaustive]
|
||||
pub struct CardEvents {
|
||||
/// A press went down in the card.
|
||||
pub pressed: bool,
|
||||
/// Open was run.
|
||||
pub opened: bool,
|
||||
/// Reset was run.
|
||||
pub reset: bool,
|
||||
/// Use was run.
|
||||
pub used: bool,
|
||||
/// The card's rect.
|
||||
pub rect: Option<Rect>,
|
||||
}
|
||||
|
||||
/// The narrowest a column of stories may be, as the old gallery's story grids kept their cases.
|
||||
const STORY_MIN_WIDTH: f32 = 240.0;
|
||||
|
||||
/// The column lists of story grids, by count.
|
||||
static COLUMNS: [ColumnWidth; 4] = [ColumnWidth::fill(1.0); 4];
|
||||
|
||||
/// The columns of a form-rows card: the captions, the stories, then the values they show.
|
||||
const FORM_ROWS: &[ColumnWidth] = &[ColumnWidth::Content, ColumnWidth::fill(1.0), ColumnWidth::Content];
|
||||
|
||||
impl Card<'_> {
|
||||
/// Shows the card in the room `ui` offers, with the states of its stories.
|
||||
pub fn show(&self, ui: &mut Ui, cells: &mut Cells) -> CardEvents {
|
||||
let mut events = CardEvents::default();
|
||||
// A story on the card's own surface sits inside the card's padding; any other surface runs edge to edge under the
|
||||
// header band.
|
||||
let pad = if self.surface == Surface::Panel { Pad::Regular } else { Pad::None };
|
||||
let mut panel = Panel::new(self.title.to_owned())
|
||||
.sizing(Sizing::Fill)
|
||||
.command_scope(CardCommands::SCOPE)
|
||||
.selected(self.selected)
|
||||
.pickable()
|
||||
.framed()
|
||||
.band(SurfaceKind::Background)
|
||||
.strength(HeaderStrength::Heading)
|
||||
.pad(pad);
|
||||
if let Some(note) = self.note {
|
||||
panel = panel.subtitle(format!("· {note}"));
|
||||
}
|
||||
let mut commands = Vec::new();
|
||||
if self.open {
|
||||
commands.push(HeaderCommand::new(IconId::new("open"), CardCommands::Open).size(ControlSize::Sm));
|
||||
}
|
||||
if self.usable {
|
||||
commands.push(HeaderCommand::new(IconId::new("check"), CardCommands::Use).size(ControlSize::Sm));
|
||||
}
|
||||
let away = self.stories.iter().any(|story| cells.get(&story.index).is_some_and(|state| state.changed() || state.dialog.shown));
|
||||
if away {
|
||||
commands.push(HeaderCommand::new(IconId::new("undo"), CardCommands::Reset).size(ControlSize::Sm));
|
||||
}
|
||||
let shown = panel.commands(commands).show(ui, |ui, cx| {
|
||||
while let Some((command, _)) = cx.take_command::<CardCommands>() {
|
||||
match command {
|
||||
CardCommands::Open => events.opened = true,
|
||||
CardCommands::Reset => events.reset = true,
|
||||
CardCommands::Use => events.used = true,
|
||||
}
|
||||
}
|
||||
events.pressed |= cx.surface_pressed();
|
||||
self.stories_in(ui, cells);
|
||||
});
|
||||
events.rect = Some(shown.response.rect);
|
||||
events
|
||||
}
|
||||
|
||||
/// The card's stories in its layout; a lone story outside form rows without its caption.
|
||||
fn stories_in(&self, ui: &mut Ui, cells: &mut Cells) {
|
||||
if let ([story], false) = (self.stories, self.layout == StoryLayout::FormRows) {
|
||||
self.body(ui, story, None, cells);
|
||||
return;
|
||||
}
|
||||
match self.layout {
|
||||
StoryLayout::FormRows => {
|
||||
Grid::new(FORM_ROWS).fill_width().show(ui, |ui, _| {
|
||||
for story in self.stories {
|
||||
Text::new(story.caption.to_owned()).show(ui);
|
||||
let shown = Stack::new().fill_width().show(ui, |ui, _| self.body(ui, story, None, cells)).inner;
|
||||
Text::new(shown.and_then(|shown| shown.value_text).unwrap_or_default()).shade(Shade::Muted).show(ui);
|
||||
}
|
||||
});
|
||||
}
|
||||
StoryLayout::Columns(most) => {
|
||||
let gap = Gap::Item.points(ui);
|
||||
let fit = ((ui.available_width() + gap) / (STORY_MIN_WIDTH + gap)).floor() as usize;
|
||||
let columns = fit.clamp(1, usize::from(most).clamp(1, COLUMNS.len()));
|
||||
Grid::new(&COLUMNS[..columns]).gap(Gap::Item).fill_width().show(ui, |ui, _| {
|
||||
for story in self.stories {
|
||||
Stack::new().fill_width().show(ui, |ui, _| self.body(ui, story, Some(story.caption), cells));
|
||||
}
|
||||
});
|
||||
}
|
||||
_ => {
|
||||
Stack::new().fill_width().show(ui, |ui, _| {
|
||||
for story in self.stories {
|
||||
self.body(ui, story, Some(story.caption), cells);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The body of `story`, with its state, under `caption` when given.
|
||||
fn body(&self, ui: &mut Ui, story: &CardStory<'_>, caption: Option<&str>, cells: &mut Cells) -> BodyShown {
|
||||
let key = format!("{}/{}", self.key, story.story.story.name);
|
||||
let body = StoryBody {
|
||||
look: self.look,
|
||||
gated: self.gated,
|
||||
caption: caption.map(str::to_owned),
|
||||
..StoryBody::new(key, story.story, self.surface, self.room, Pad::None)
|
||||
};
|
||||
body.show(ui, cells.entry(story.index).or_default())
|
||||
}
|
||||
}
|
||||
|
||||
/// A story on its surface, as a card's body shows it, and what showed.
|
||||
#[non_exhaustive]
|
||||
pub struct StoryBody {
|
||||
/// The id scope of the story: unique among the stories of a pass.
|
||||
pub key: String,
|
||||
/// The story.
|
||||
pub story: &'static StoryRegistration,
|
||||
/// The surface the story sits on.
|
||||
pub surface: Surface,
|
||||
/// The height a story that fills is given.
|
||||
pub room: f32,
|
||||
/// The values the body sets for its story.
|
||||
pub look: Look,
|
||||
/// Whether the story's wheel takers take the wheel only while focused or armed.
|
||||
pub gated: bool,
|
||||
/// The margin of a story on the panel surface: none in a card, whose padding is that margin.
|
||||
pub panel_pad: Pad,
|
||||
/// The caption over the story, on the story's surface, in the old gallery's caption style.
|
||||
pub caption: Option<String>,
|
||||
}
|
||||
|
||||
/// What a story body showed.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
#[non_exhaustive]
|
||||
pub struct BodyShown {
|
||||
/// Where the story shows in flow: its surface, or the whole room for a story that takes no room in flow; `None`
|
||||
/// for a story that shows only a dialog.
|
||||
pub flow: Option<Rect>,
|
||||
/// The shown value as the story's component words it ([`StoryOutput::value_text`]).
|
||||
pub value_text: Option<String>,
|
||||
}
|
||||
|
||||
impl StoryBody {
|
||||
/// The body of `story` on `surface`, in the window's look, with ungated wheel takers.
|
||||
pub fn new(key: impl Into<String>, story: &'static StoryRegistration, surface: Surface, room: f32, panel_pad: Pad) -> Self {
|
||||
StoryBody { key: key.into(), story, surface, room, look: Look::default(), gated: false, panel_pad, caption: None }
|
||||
}
|
||||
|
||||
/// The story on its surface, in an embedded shell of its own so its dialogs stay in the card. The shell is as tall
|
||||
/// as the story measures in the card's room: its content height, or the whole room for a story that fills it or
|
||||
/// shows nothing in flow (a dialog).
|
||||
///
|
||||
/// A story that opens a dialog, a modal or a window starts closed behind a button, and nothing of what it opens
|
||||
/// paints before the button is pressed. Two records say what the story shows (`ShellCx::dialog_shown`): a measure
|
||||
/// that runs the story under a shell record of its own before anything paints, and the card's shell after it ran
|
||||
/// the story, for a dialog in an embedded shell of the story's own, whose body runs in real runs only. When the
|
||||
/// shell's record changes what the card shows, the card discards the pass, so nothing of that pass paints. The
|
||||
/// button turns the story's `open` value on and runs it, which opens the real thing (an OS window where the
|
||||
/// component uses one). Once nothing shows any more, the exit fade included, the card shows the button again.
|
||||
pub fn show(&self, ui: &mut Ui, state: &mut CardState) -> BodyShown {
|
||||
let window = WindowKey::new(format!("card-{}-{}", self.key, state.resets));
|
||||
let host = Host {
|
||||
caption: self.caption.as_deref(),
|
||||
id: craft_ui::testing::memory::global("gallery.card.story", (&self.key, state.resets)),
|
||||
room: self.room,
|
||||
look: self.look,
|
||||
surface: self.surface,
|
||||
gated: self.gated,
|
||||
panel_pad: self.panel_pad,
|
||||
};
|
||||
let show = self.story.story.show;
|
||||
let at = ui.available_rect_before_wrap().min;
|
||||
let record = ShellCx::detached(window.clone(), BodyMode::Normal, Rect::from_min_size(at, vec2(ui.available_width(), self.room)));
|
||||
// The measure runs in every pass, the card's own measuring runs included, where the shell below skips the story:
|
||||
// its value text is the one the card can measure beside the story.
|
||||
let mut measured_text = None;
|
||||
let took = host.stack().measure_in(ui, Proposal::Ideal, |ui, _| {
|
||||
measured_text = host.content(ui, show, &mut state.data, Some(&record)).value_text;
|
||||
});
|
||||
// A story that shows nothing in flow takes no more than its bare surface; under its own id, so its record does
|
||||
// not stand for the story's.
|
||||
let bare = host.stack().id(craft_ui::testing::memory::sub(host.id, "bare")).measure_in(ui, Proposal::Ideal, |ui, _| host.caption_in(ui));
|
||||
let height = if took.y > bare.y { took.y } else { self.room };
|
||||
if record.dialog_shown() && !state.dialog.painted {
|
||||
close_at_start(state);
|
||||
}
|
||||
if state.dialog.hidden {
|
||||
state.note_start();
|
||||
if Button::new("Show dialog").show(ui).clicks == 0 {
|
||||
return BodyShown::default();
|
||||
}
|
||||
ui.ctx().request_repaint();
|
||||
state.show_dialog();
|
||||
}
|
||||
// A story that has not painted yet runs only in a pass that can still be discarded: what its shell's record
|
||||
// finds open would paint otherwise. The next frame's first pass runs it.
|
||||
let runs = state.dialog.painted || craft_ui::runtime::frame::discardable(ui.ctx());
|
||||
let ran = std::cell::Cell::new(false);
|
||||
let flow = std::cell::Cell::new(None);
|
||||
let output = std::cell::RefCell::new(None);
|
||||
let rect = Rect::from_min_size(ui.available_rect_before_wrap().min, vec2(ui.available_width(), height));
|
||||
let shown = AppShell::embedded(window)
|
||||
.body(|ui, _, data: &mut StoryData| {
|
||||
if runs {
|
||||
ran.set(!ui.is_sizing_pass());
|
||||
let surface = host.stack().show(ui, |ui, _| host.content(ui, show, data, None));
|
||||
flow.set(Some(surface.output.rect));
|
||||
*output.borrow_mut() = Some(surface.inner);
|
||||
}
|
||||
})
|
||||
.show_at(ui, rect, &mut state.data);
|
||||
if !runs {
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
// The shell runs its body only in real runs (not in the card's own measuring runs, nor scrolled out of sight), so
|
||||
// its record counts only when the story ran.
|
||||
if ran.get() {
|
||||
let dialog = &mut state.dialog;
|
||||
if shown.dialog && !dialog.painted {
|
||||
close_at_start(state);
|
||||
craft_ui::runtime::frame::discard_pass(ui.ctx(), "gallery: a card's story showed a dialog the measure did not see");
|
||||
} else if dialog.known && !dialog.hidden && dialog.shown && !shown.dialog {
|
||||
*dialog = DialogState { known: true, hidden: true, shown: false, painted: true };
|
||||
craft_ui::runtime::frame::discard_pass(ui.ctx(), "gallery: a card's dialog closed");
|
||||
} else {
|
||||
dialog.shown |= dialog.known && shown.dialog;
|
||||
dialog.painted = true;
|
||||
}
|
||||
}
|
||||
state.note_start();
|
||||
// A story that takes no room in flow paints in the shell's whole room, unless what it shows is a dialog.
|
||||
let flow = if took.y > bare.y { flow.get() } else { (!state.dialog.known).then_some(rect) };
|
||||
let value_text = output.into_inner().flatten().and_then(|output| output.value_text).or(measured_text);
|
||||
BodyShown { flow, value_text }
|
||||
}
|
||||
}
|
||||
|
||||
/// Puts a story whose dialog shows at its start behind its button, with the dialog closed. The card's start is the
|
||||
/// story with its dialog closed, so a dialog closed by its own button is back at the start and Reset hides.
|
||||
fn close_at_start(state: &mut CardState) {
|
||||
state.dialog = DialogState { known: true, hidden: true, shown: false, painted: false };
|
||||
if let Some(open) = state.data.present::<bool>("open") {
|
||||
*open = false;
|
||||
}
|
||||
state.start = None;
|
||||
}
|
||||
|
||||
/// What a story runs in inside its card: the same in the measure and in the shell, ids included, so the measure reads
|
||||
/// the state the story shows.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Host<'a> {
|
||||
caption: Option<&'a str>,
|
||||
id: Id,
|
||||
/// The height a story that fills is given.
|
||||
room: f32,
|
||||
look: Look,
|
||||
surface: Surface,
|
||||
gated: bool,
|
||||
panel_pad: Pad,
|
||||
}
|
||||
|
||||
impl Host<'_> {
|
||||
/// The story's surface over the card's width, with the card's mode.
|
||||
fn stack(&self) -> Stack<'static> {
|
||||
let kind = match self.surface {
|
||||
Surface::Panel => SurfaceKind::Panel,
|
||||
Surface::Canvas => SurfaceKind::Canvas,
|
||||
Surface::Chrome => SurfaceKind::Chrome,
|
||||
// A story that paints its own surface sits on the background, as on the old gallery's cards.
|
||||
_ => SurfaceKind::Background,
|
||||
};
|
||||
// On the panel surface the margin is the body's `panel_pad` (in a card, the card's padding is the margin); another
|
||||
// surface keeps a margin of its own inside it.
|
||||
let pad = if kind == SurfaceKind::Panel { self.panel_pad } else { Pad::Regular };
|
||||
let mut stack = Stack::new().id(self.id).fill_width().room_height(self.room).surface(kind).pad(pad);
|
||||
if let Some(mode) = self.look.mode {
|
||||
stack = stack.theme(ThemeScope::mode(mode));
|
||||
}
|
||||
stack
|
||||
}
|
||||
|
||||
/// The caption, when the story has one.
|
||||
fn caption_in(&self, ui: &mut Ui) {
|
||||
if let Some(caption) = self.caption {
|
||||
Text::new(caption.to_owned()).shade(Shade::Muted).show(ui);
|
||||
}
|
||||
}
|
||||
|
||||
/// The story under its caption, in the card's direction and control size; in a measure, under `record`, the
|
||||
/// shell that records what the story opens.
|
||||
fn content(&self, ui: &mut Ui, show: StoryFn, data: &mut StoryData, record: Option<&ShellCx>) -> StoryOutput {
|
||||
self.caption_in(ui);
|
||||
let (look, gated) = (self.look, self.gated);
|
||||
with_env(
|
||||
ui,
|
||||
|env| {
|
||||
env.direction = look.direction;
|
||||
env.size = look.size;
|
||||
env.wheel_gated = Some(gated);
|
||||
if let Some(record) = record {
|
||||
record.put(&mut env.values);
|
||||
}
|
||||
},
|
||||
|ui| show(ui, data),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
//! Words for the facts the decision record shows: a reader sees what a component is, not how the code spells it.
|
||||
|
||||
use craft_behavior::Input;
|
||||
use craft_ui::contract::ShapeKind;
|
||||
use craft_ui::runtime::access::Role;
|
||||
use craft_ui::runtime::focus::{ActivateKeys, KeepKeys, KeyUse};
|
||||
|
||||
/// What the component shows: no body, a body from the caller, or an item per entry of a source.
|
||||
pub(super) fn shape(shape: ShapeKind) -> &'static str {
|
||||
match shape {
|
||||
ShapeKind::Leaf => "Leaf, no body",
|
||||
ShapeKind::Body => "Body from the caller",
|
||||
ShapeKind::Items => "An item per entry of a source",
|
||||
_ => "Another shape",
|
||||
}
|
||||
}
|
||||
|
||||
/// How input reaches the component.
|
||||
pub(super) fn input(input: Input) -> &'static str {
|
||||
match input {
|
||||
Input::Pointer => "The pointer acts on it",
|
||||
Input::Text => "A text field",
|
||||
Input::Display => "Shows something, takes no input",
|
||||
Input::Editor => "An editor with its own caret",
|
||||
_ => "Another kind of input",
|
||||
}
|
||||
}
|
||||
|
||||
/// What the component is to assistive technology. AccessKit names its roles by their variant, so the words are that
|
||||
/// name spaced out.
|
||||
pub(super) fn role(role: Role) -> String {
|
||||
match role {
|
||||
Role::None => "No node".to_owned(),
|
||||
Role::Merged => "Merged into its container's node".to_owned(),
|
||||
Role::Node(role) => {
|
||||
let name = format!("{role:?}");
|
||||
let mut words = String::with_capacity(name.len() + 4);
|
||||
for (at, letter) in name.chars().enumerate() {
|
||||
if at > 0 && letter.is_uppercase() {
|
||||
words.push(' ');
|
||||
}
|
||||
words.push(if at > 0 { letter.to_ascii_lowercase() } else { letter });
|
||||
}
|
||||
words
|
||||
}
|
||||
_ => "Another role".to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The keys the focused component keeps, as a sentence.
|
||||
pub(super) fn keys(keys: &KeyUse) -> String {
|
||||
let activates = match keys.activate {
|
||||
ActivateKeys::Neither => "no activation key",
|
||||
ActivateKeys::Enter => "Enter activates",
|
||||
ActivateKeys::Space => "Space activates",
|
||||
ActivateKeys::Both => "Enter and Space activate",
|
||||
_ => "other activation keys",
|
||||
};
|
||||
let kept = match keys.keep {
|
||||
KeepKeys::None => None,
|
||||
KeepKeys::Tab => Some("keeps Tab"),
|
||||
KeepKeys::InlineArrows => Some("keeps Left and Right"),
|
||||
KeepKeys::BlockArrows => Some("keeps all four arrows"),
|
||||
_ => Some("keeps other keys"),
|
||||
};
|
||||
let flags = [(keys.value, "arrows step a value"), (keys.moves, "takes arrow moves"), (keys.nudge, "arrows nudge its content")];
|
||||
let mut parts = vec![activates.to_owned()];
|
||||
parts.extend(kept.map(str::to_owned));
|
||||
parts.extend(flags.into_iter().filter(|(set, _)| *set).map(|(_, words)| words.to_owned()));
|
||||
if !keys.claims.is_empty() {
|
||||
parts.push(format!("claims {} shortcuts", keys.claims.len()));
|
||||
}
|
||||
parts.join(", ")
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
//! The dock: what the dock asks of the viewer for each panel of the shown workspace.
|
||||
|
||||
use super::panels::Panels;
|
||||
use crate::viewer::{GalleryCommands, PanelId, Preview};
|
||||
use craft_behavior::dock::Permissions;
|
||||
use craft_theme::variant::Tone;
|
||||
use craft_ui::contract::Show as _;
|
||||
use craft_ui::contract::{BodyCx, SizeLimits};
|
||||
use craft_ui::docking::{DockHeights, DockPanels, PanelSpec};
|
||||
use craft_ui::menu::PanelRow;
|
||||
use craft_ui::notices::Notice;
|
||||
use egui::Ui;
|
||||
|
||||
/// The viewer's panels as the dock's contents.
|
||||
#[non_exhaustive]
|
||||
pub struct GalleryDock<'a> {
|
||||
/// What the panel bodies read and edit.
|
||||
pub panels: Panels<'a>,
|
||||
/// What the theme workspace's preview shows.
|
||||
pub preview: Preview,
|
||||
/// The mock application the App preview shows.
|
||||
pub app: &'a mut crate::mock::MockState,
|
||||
}
|
||||
|
||||
impl DockPanels<PanelId> for GalleryDock<'_> {
|
||||
fn spec(&self, panel: &PanelId) -> PanelSpec {
|
||||
let spec = PanelSpec::new(panel.title()).limits(SizeLimits::default());
|
||||
match panel {
|
||||
PanelId::Stories => spec.heights(DockHeights::new(80.0).compact(60.0)),
|
||||
PanelId::Properties | PanelId::Inspect | PanelId::Tokens => spec.heights(DockHeights::new(240.0).compact(120.0).fill(300.0)),
|
||||
PanelId::Problems | PanelId::Detail | PanelId::AppSizes => spec.heights(DockHeights::new(210.0)),
|
||||
_ => spec,
|
||||
}
|
||||
}
|
||||
|
||||
fn permissions(&self, panel: &PanelId) -> Permissions {
|
||||
panel.permissions()
|
||||
}
|
||||
|
||||
fn body(&mut self, panel: &PanelId, ui: &mut Ui, _: &mut BodyCx<'_>) {
|
||||
match (panel, self.preview) {
|
||||
(PanelId::Preview, Preview::App) => {
|
||||
crate::mock::EditorMock::new("Preview", self.app).show(ui);
|
||||
}
|
||||
(PanelId::Preview, Preview::Components) => {
|
||||
Notice::new(Tone::Info, "The Controls level comes with the overview.").show(ui);
|
||||
}
|
||||
_ => self.panels.show(ui, *panel),
|
||||
}
|
||||
}
|
||||
|
||||
/// Reset args and Reset layout in the menu of the group that holds the target story's panels.
|
||||
fn panel_rows(&mut self, panel: &PanelId) -> Vec<PanelRow> {
|
||||
match panel {
|
||||
PanelId::Properties | PanelId::Inspect | PanelId::Tokens => {
|
||||
vec![PanelRow::Command(GalleryCommands::ResetStories.into()), PanelRow::Command(GalleryCommands::ResetLayout.into())]
|
||||
}
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
//! The viewer's chrome: the options bar, the dock of panels and the window that holds them.
|
||||
|
||||
mod card;
|
||||
mod describe;
|
||||
mod dock;
|
||||
mod options;
|
||||
mod overview;
|
||||
mod panels;
|
||||
mod persist;
|
||||
mod shell;
|
||||
mod variants;
|
||||
|
||||
pub use card::{BodyShown, Look, StoryBody};
|
||||
pub use options::options_bar;
|
||||
pub use panels::Panels;
|
||||
pub use persist::Persisted;
|
||||
pub use shell::Gallery;
|
||||
@@ -0,0 +1,103 @@
|
||||
//! The options bar: the theme and mode, the rarer appearance options in More, the workspace's own controls, and Reset
|
||||
//! layout and the workspace switch at the end.
|
||||
|
||||
use crate::viewer::{
|
||||
CONTRASTS, DENSITIES, DIRECTIONS, GalleryCommands, MODES, MOTIONS, Preview, SCALES, TEXT_SIZES, VariantAxis, Viewer, Workspace, theme_entries,
|
||||
};
|
||||
use craft_behavior::{IconId, Value};
|
||||
use craft_ui::bars::{Bar, BarCell, BarKind};
|
||||
use craft_ui::buttons::{IconButton, ToggleButton};
|
||||
use craft_ui::choice::Segmented;
|
||||
use craft_ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _, Trigger};
|
||||
use craft_ui::display::Divider;
|
||||
use craft_ui::layout_components::{Row, Stack};
|
||||
use craft_ui::menu::Menu;
|
||||
use craft_ui::pickers::Select;
|
||||
use craft_ui::popover::Popover;
|
||||
use egui::Ui;
|
||||
|
||||
/// A select over `entries` in a cell with its caption.
|
||||
fn pick<T: Value>(ui: &mut Ui, caption: &'static str, value: &mut T, entries: &[Entry<T>]) {
|
||||
BarCell::new(format!("{caption}:")).control(ui, |ui, label| {
|
||||
Select::new(label, Bind::bound(&mut *value), entries).show(ui);
|
||||
});
|
||||
}
|
||||
|
||||
/// A segmented row over `entries` in a cell with its caption.
|
||||
fn choose<T: Value>(ui: &mut Ui, caption: &'static str, value: &mut T, entries: &[Entry<T>]) {
|
||||
BarCell::new(format!("{caption}:")).control(ui, |ui, label| {
|
||||
Segmented::new(label, Bind::bound(&mut *value), entries).show(ui);
|
||||
});
|
||||
}
|
||||
|
||||
/// One line of a form: what `add` shows, in a row.
|
||||
fn line(ui: &mut Ui, mut add: impl FnMut(&mut Ui)) {
|
||||
Row::new().show(ui, |ui, _| add(ui));
|
||||
}
|
||||
|
||||
/// The More popover's form: the root values the bar's own controls leave out.
|
||||
fn more_form(ui: &mut Ui, viewer: &mut Viewer) {
|
||||
let env = &mut viewer.env;
|
||||
let (contrasts, densities, motions) = (CONTRASTS.entries(), DENSITIES.entries(), MOTIONS.entries());
|
||||
let (directions, text_sizes, scales) = (DIRECTIONS.entries(), TEXT_SIZES.entries(), SCALES.entries());
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
line(ui, |ui| choose(ui, "Contrast", &mut env.contrast, &contrasts));
|
||||
line(ui, |ui| choose(ui, "Size", &mut env.density, &densities));
|
||||
line(ui, |ui| choose(ui, "Reduced motion", &mut env.motion, &motions));
|
||||
line(ui, |ui| choose(ui, "Direction", &mut env.direction, &directions));
|
||||
line(ui, |ui| choose(ui, "Text", &mut env.text_size, &text_sizes));
|
||||
line(ui, |ui| pick(ui, "Scale", &mut env.scale, &scales));
|
||||
});
|
||||
}
|
||||
|
||||
/// The Variants toggle and its menu of axes: the toggle shows whether a Variants view is open, and a press opens the
|
||||
/// menu. Returns the axis chosen.
|
||||
fn variants_menu(ui: &mut Ui, shown: bool, has_target: bool) -> Option<VariantAxis> {
|
||||
let mut on = shown;
|
||||
let button =
|
||||
ToggleButton::new("Variants", Bind::bound(&mut on)).trailing_icon(craft_ui::controls::disclosure::DisclosureGlyph::menu_button()).show(ui);
|
||||
let entries: Vec<Entry<VariantAxis>> = VariantAxis::ALL.into_iter().map(|axis| Entry::new(axis, axis.menu_label()).enabled(has_target)).collect();
|
||||
Menu::new("Variants").values().opened_by(&button.response, Trigger::Press).pick(ui, &entries).picked
|
||||
}
|
||||
|
||||
/// The theme and mode, the More popover, the workspace's own controls, then Reset layout and the workspace switch.
|
||||
pub fn options_bar(ui: &mut Ui, viewer: &mut Viewer) {
|
||||
let (modes, themes) = (MODES.entries(), theme_entries());
|
||||
let (previews, workspaces) = (
|
||||
[Entry::new(Preview::App, "App"), Entry::new(Preview::Components, "Components")],
|
||||
[Entry::new(Workspace::Components, "Components"), Entry::new(Workspace::Theme, "Theme")],
|
||||
);
|
||||
let has_target = viewer.browser.target_story().is_some();
|
||||
let workspace = viewer.workspace;
|
||||
let mut more = None;
|
||||
let Viewer { env, more_open, variants, preview, workspace: shown, .. } = viewer;
|
||||
Bar::new("Appearance", BarKind::Options)
|
||||
.trailing(|ui| {
|
||||
IconButton::command(IconId::new("undo"), GalleryCommands::ResetLayout).show(ui);
|
||||
choose(ui, "Workspace", shown, &workspaces);
|
||||
})
|
||||
.show(ui, |ui, _| {
|
||||
pick(ui, "Theme", &mut env.theme, &themes);
|
||||
choose(ui, "Mode", &mut env.mode, &modes);
|
||||
let button = IconButton::new(IconId::new("more")).label("More appearance settings").selected(*more_open).show(ui);
|
||||
if button.clicks > 0 {
|
||||
*more_open = !*more_open;
|
||||
}
|
||||
more = Some(button);
|
||||
Divider::vertical().show(ui);
|
||||
match workspace {
|
||||
Workspace::Components => {
|
||||
if let Some(axis) = variants_menu(ui, variants.is_some(), has_target) {
|
||||
*variants = Some(axis);
|
||||
}
|
||||
}
|
||||
Workspace::Theme => choose(ui, "Preview", preview, &previews),
|
||||
}
|
||||
});
|
||||
// The popover is a layer of its own: shown inside the bar it would take the bar's height.
|
||||
if let Some(more) = more {
|
||||
let mut open = viewer.more_open;
|
||||
Popover::new("More appearance settings", Bind::bound(&mut open)).opened_by(&more.response).show(ui, |ui, _| more_form(ui, viewer));
|
||||
viewer.more_open = open;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
//! The centre tabs: the Overview (the cards of one level), a component's tab (a card per story group) and the Variants view
|
||||
//! that replaces the front one.
|
||||
|
||||
use super::card::{Card, CardEvents, CardStory, Look};
|
||||
use super::panels::Panels;
|
||||
use super::variants;
|
||||
use crate::viewer::{ComponentInfo, PanelId, TreeKey, by_level, entry_of};
|
||||
use craft_behavior::{ColumnWidth, Selection};
|
||||
use craft_theme::variant::Tone;
|
||||
use craft_ui::contract::{Bind, BodyCx, Entry, Gap, Lazy, Pad, Props as _, Scroll, Show as _, ShowContainer as _, StoryLayout};
|
||||
use craft_ui::display::{Shade, Text};
|
||||
use craft_ui::layout_components::{Grid, Row, Stack};
|
||||
use craft_ui::notices::Notice;
|
||||
use craft_ui::pickers::Select;
|
||||
use craft_ui::runtime::env::WindowKey;
|
||||
use craft_ui::shell::AppShell;
|
||||
use craft_ui::style::SurfaceKind;
|
||||
use craft_ui::testing::StoryRegistration;
|
||||
use egui::{Align, Ui};
|
||||
|
||||
/// The narrowest a card may be before the cards go to one column: a dock panel of the apps is about this wide, and a
|
||||
/// story drawn in less is no longer what the apps show.
|
||||
const CARD_MIN_WIDTH: f32 = 290.0;
|
||||
|
||||
const ONE: &[ColumnWidth] = &[ColumnWidth::fill(1.0)];
|
||||
const TWO: &[ColumnWidth] = &[ColumnWidth::fill(1.0); 2];
|
||||
|
||||
/// One story of a card to show.
|
||||
pub(super) struct SpecStory {
|
||||
/// The index of the story in the catalog.
|
||||
pub index: usize,
|
||||
pub story: &'static StoryRegistration,
|
||||
/// The story's caption.
|
||||
pub caption: String,
|
||||
}
|
||||
|
||||
impl SpecStory {
|
||||
/// The story at catalog index `index` of the component whose display name is `name`.
|
||||
pub fn of(p: &Panels<'_>, index: usize, name: &str) -> Self {
|
||||
let story = p.catalog.entries[index].registration;
|
||||
SpecStory { index, story, caption: story.story.caption(name) }
|
||||
}
|
||||
}
|
||||
|
||||
/// The card of one component to show, before it is laid out.
|
||||
pub(super) struct Spec {
|
||||
/// The id scope of the card.
|
||||
pub key: String,
|
||||
/// The registered name of the component.
|
||||
pub type_name: &'static str,
|
||||
/// The card's title.
|
||||
pub title: String,
|
||||
/// A note after the title.
|
||||
pub note: Option<String>,
|
||||
/// The stories the card shows, in order.
|
||||
pub stories: Vec<SpecStory>,
|
||||
/// How the stories are laid out together.
|
||||
pub layout: StoryLayout,
|
||||
pub surface: craft_ui::contract::Surface,
|
||||
pub open: bool,
|
||||
pub usable: bool,
|
||||
pub selected: bool,
|
||||
pub look: Look,
|
||||
/// Whether the card gates its story's wheel takers (`Card::gated`).
|
||||
pub gated: bool,
|
||||
}
|
||||
|
||||
/// What the cards of a pass reported, by card.
|
||||
pub(super) struct Reported {
|
||||
pub spec: usize,
|
||||
pub events: CardEvents,
|
||||
}
|
||||
|
||||
/// The index in `catalog` of the story the component registered as `type_name` shows: the one picked for it, else its
|
||||
/// first.
|
||||
pub(super) fn target_story(p: &Panels<'_>, type_name: &'static str) -> Option<usize> {
|
||||
p.catalog.pick(type_name, p.story_of.get(type_name).copied())
|
||||
}
|
||||
|
||||
/// The selected component's registered name.
|
||||
pub(super) fn selected_type(p: &Panels<'_>) -> Option<&'static str> {
|
||||
p.selection.items.iter().rev().find_map(|key| match key {
|
||||
TreeKey::Component(type_name) => Some(*type_name),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The window's background (an embedded shell, which paints it and keeps its cards' dialogs in the tab) with the
|
||||
/// panel's padding around `add`.
|
||||
pub(super) fn on_background(ui: &mut Ui, key: &str, mut add: impl FnMut(&mut Ui, &mut BodyCx<'_>)) {
|
||||
AppShell::embedded(WindowKey::new(format!("gallery-centre-{key}")))
|
||||
.body(|ui, cx, _: &mut ()| {
|
||||
Stack::new().fill().surface(SurfaceKind::Background).pad(Pad::Regular).show(ui, |ui, _| add(ui, cx));
|
||||
})
|
||||
.show(ui, &mut ());
|
||||
}
|
||||
|
||||
/// The cards in one or two columns, scrolling vertically; each row is as tall as its tallest card. A card out of view
|
||||
/// does not run (`Lazy`), except the one the selection scrolls to. The cards report into `reported`.
|
||||
pub(super) fn grid(
|
||||
ui: &mut Ui,
|
||||
scroll_id: impl std::hash::Hash + std::fmt::Debug,
|
||||
cards: &[Spec],
|
||||
p: &mut Panels<'_>,
|
||||
one_column: bool,
|
||||
) -> Vec<Reported> {
|
||||
let mut reported = Vec::new();
|
||||
let columns = if one_column || ui.available_width() < 2.0 * CARD_MIN_WIDTH { 1 } else { 2 };
|
||||
let generation = p.generation;
|
||||
// A story that fills its room gets the view's height, as on the old gallery's tiles.
|
||||
let room = ui.available_height();
|
||||
Stack::new().fill().scroll(Scroll::vertical()).gap(Gap::CardRow).id_salt(scroll_id).show(ui, |ui, _| {
|
||||
reported.clear();
|
||||
for (row, chunk) in cards.chunks(columns).enumerate() {
|
||||
Grid::new(if columns == 1 { ONE } else { TWO }).gap(Gap::CardColumn).fill_width().show(ui, |ui, _| {
|
||||
for (at, spec) in chunk.iter().enumerate() {
|
||||
let target = *p.scroll_to == Some(spec.type_name);
|
||||
// Keyed by the card alone: a change of the column count regroups the rows, and the cards out of
|
||||
// view keep their extents.
|
||||
Lazy::new((generation, spec.key.as_str())).keep(target).show(ui, |ui| {
|
||||
let stories: Vec<CardStory<'_>> =
|
||||
spec.stories.iter().map(|story| CardStory::new(story.index, story.story, &story.caption)).collect();
|
||||
// Each card is its own id scope: a story's `id_salt` and auto ids must not meet another card's.
|
||||
let card = Card {
|
||||
key: format!("{}-{generation}", spec.key),
|
||||
title: &spec.title,
|
||||
note: spec.note.as_deref(),
|
||||
stories: &stories,
|
||||
layout: spec.layout,
|
||||
surface: spec.surface,
|
||||
room,
|
||||
open: spec.open,
|
||||
usable: spec.usable,
|
||||
selected: spec.selected,
|
||||
look: spec.look,
|
||||
gated: spec.gated,
|
||||
};
|
||||
let events = card.show(ui, p.cells);
|
||||
reported.push(Reported { spec: row * columns + at, events });
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
reported
|
||||
}
|
||||
|
||||
/// Applies what the cards reported: a press selects the card's component and picks the card's first story unless the
|
||||
/// picked one is on the card, Open
|
||||
/// opens its tab, Reset gives the card's stories their start values.
|
||||
pub(super) fn apply(ui: &mut Ui, p: &mut Panels<'_>, cards: &[Spec], reported: Vec<Reported>) {
|
||||
let scroll = *p.scroll_to;
|
||||
let mut scrolled = false;
|
||||
for Reported { spec, events } in reported {
|
||||
let Some(spec) = cards.get(spec) else { continue };
|
||||
if events.reset {
|
||||
for story in &spec.stories {
|
||||
p.cells.entry(story.index).or_default().reset();
|
||||
}
|
||||
}
|
||||
if events.opened {
|
||||
*p.open_request = Some(spec.type_name);
|
||||
}
|
||||
if events.pressed || events.opened {
|
||||
*p.selection = Selection::single(TreeKey::Component(spec.type_name));
|
||||
// The picked story stays while it is one of the card's; else the card's first story is picked.
|
||||
let picked = target_story(p, spec.type_name);
|
||||
if let Some(first) = spec.stories.first()
|
||||
&& !spec.stories.iter().any(|story| Some(story.index) == picked)
|
||||
{
|
||||
p.story_of.insert(spec.type_name, first.story.story.name);
|
||||
}
|
||||
}
|
||||
if scroll == Some(spec.type_name)
|
||||
&& let Some(rect) = events.rect
|
||||
{
|
||||
ui.scroll_to_rect(rect, Some(Align::TOP));
|
||||
scrolled = true;
|
||||
}
|
||||
}
|
||||
if scrolled {
|
||||
*p.scroll_to = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// The level the selected component sits on, and a request to bring its card into view, when the selection changed
|
||||
/// since the last pass of the Overview.
|
||||
fn follow_selection(p: &mut Panels<'_>) {
|
||||
let selected = selected_type(p);
|
||||
if *p.followed == Some(selected) {
|
||||
return;
|
||||
}
|
||||
*p.followed = Some(selected);
|
||||
if let Some(type_name) = selected
|
||||
&& let Some(entry) = entry_of(type_name)
|
||||
{
|
||||
*p.level = entry.level.title().to_owned();
|
||||
*p.scroll_to = Some(type_name);
|
||||
}
|
||||
}
|
||||
|
||||
/// The Overview: the level select over the cards of the level's components.
|
||||
pub(super) fn overview(ui: &mut Ui, p: &mut Panels<'_>) {
|
||||
if variants::show(ui, p, PanelId::Overview) {
|
||||
return;
|
||||
}
|
||||
follow_selection(p);
|
||||
let groups = by_level(p.catalog, p.filter);
|
||||
let Some(shown) = groups.iter().position(|(level, _)| level.title() == p.level.as_str()).or(if groups.is_empty() { None } else { Some(0) })
|
||||
else {
|
||||
on_background(ui, "overview", |ui, _| {
|
||||
Notice::new(Tone::Info, "No components match the filter.").show(ui);
|
||||
});
|
||||
return;
|
||||
};
|
||||
let level = groups[shown].0;
|
||||
let entries: Vec<Entry<craft_ui::contract::Level>> = groups.iter().map(|(level, _)| Entry::new(*level, level.title())).collect();
|
||||
let selected = selected_type(p);
|
||||
let cards: Vec<Spec> = groups[shown].1.iter().filter_map(|component| component_card(p, component, selected)).collect();
|
||||
let mut chosen = level;
|
||||
let mut reported = Vec::new();
|
||||
on_background(ui, "overview", |ui, _| {
|
||||
Row::new().show(ui, |ui, _| {
|
||||
Text::new("Level:").shade(Shade::Muted).show(ui);
|
||||
Select::new("Level", Bind::bound(&mut chosen), &entries).show(ui);
|
||||
});
|
||||
reported = grid(ui, level.title(), &cards, p, false);
|
||||
});
|
||||
if chosen != level {
|
||||
*p.level = chosen.title().to_owned();
|
||||
}
|
||||
apply(ui, p, &cards, reported);
|
||||
}
|
||||
|
||||
/// The stories of group `group` of the component registered as `type_name`, under their captions.
|
||||
fn group_stories(p: &Panels<'_>, type_name: &'static str, group: usize, name: &str) -> Vec<SpecStory> {
|
||||
p.catalog.group_stories(type_name, group).into_iter().map(|at| SpecStory::of(p, at, name)).collect()
|
||||
}
|
||||
|
||||
/// The group the component registered as `type_name` shows: the group of its picked story, else its first.
|
||||
fn target_group(p: &Panels<'_>, type_name: &'static str) -> usize {
|
||||
target_story(p, type_name).and_then(|at| p.catalog.group_at(type_name, at)).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// The Overview's card of `component`: the cases of the group of its picked story, in catalog order, with the group's
|
||||
/// name as a note when it is not the first group.
|
||||
fn component_card(p: &Panels<'_>, component: &ComponentInfo, selected: Option<&'static str>) -> Option<Spec> {
|
||||
let entry = entry_of(component.type_name)?;
|
||||
let group = target_group(p, component.type_name);
|
||||
let name = &component.groups.get(group)?.name;
|
||||
let stories = group_stories(p, component.type_name, group, &entry.name);
|
||||
if stories.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(Spec {
|
||||
key: component.type_name.to_owned(),
|
||||
type_name: component.type_name,
|
||||
title: entry.name.clone(),
|
||||
note: (group > 0).then(|| name.clone()),
|
||||
stories,
|
||||
layout: entry.story_layout(name),
|
||||
surface: entry.surface,
|
||||
open: true,
|
||||
usable: false,
|
||||
selected: selected == Some(component.type_name),
|
||||
look: Look::default(),
|
||||
gated: true,
|
||||
})
|
||||
}
|
||||
|
||||
/// A component's tab: each story group of the component as a card in one column, titled with the group's name.
|
||||
pub(super) fn component_tab(ui: &mut Ui, p: &mut Panels<'_>, type_name: &'static str) {
|
||||
if variants::show(ui, p, PanelId::Component(type_name)) {
|
||||
return;
|
||||
}
|
||||
let (Some(entry), Some(component)) = (entry_of(type_name), p.catalog.component(type_name)) else {
|
||||
on_background(ui, "component", |ui, _| {
|
||||
Notice::new(Tone::Info, "The component has no stories.").show(ui);
|
||||
});
|
||||
return;
|
||||
};
|
||||
let target = target_group(p, type_name);
|
||||
let chosen = selected_type(p) == Some(type_name);
|
||||
let cards: Vec<Spec> = component
|
||||
.groups
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(at, group)| Spec {
|
||||
key: format!("{type_name}/{}", group.name),
|
||||
type_name,
|
||||
title: group.name.clone(),
|
||||
note: None,
|
||||
stories: group_stories(p, type_name, at, &entry.name),
|
||||
layout: entry.story_layout(&group.name),
|
||||
surface: entry.surface,
|
||||
open: false,
|
||||
usable: false,
|
||||
selected: chosen && target == at,
|
||||
look: Look::default(),
|
||||
gated: false,
|
||||
})
|
||||
.collect();
|
||||
let mut reported = Vec::new();
|
||||
on_background(ui, "component", |ui, _| reported = grid(ui, ("component", type_name), &cards, p, true));
|
||||
apply(ui, p, &cards, reported);
|
||||
}
|
||||
@@ -0,0 +1,327 @@
|
||||
//! The bodies of the viewer's panels: the component tree, the target component's stories, facts and decision record,
|
||||
//! and the theme workspace's tokens, problems, detail and app sizes. The dock draws each panel's tab and frame.
|
||||
|
||||
use super::describe;
|
||||
use super::overview;
|
||||
use crate::theme::{AppLayerEditor, Problems, ThemeSubject, ThemeWorkspace, TokenBrowser, TokenDetail};
|
||||
use crate::viewer::{self, CardState, Catalog, Cells, ComponentInfo, PanelId, TreeKey, TreeRow, TreeRows};
|
||||
use craft_behavior::IconId;
|
||||
use craft_behavior::{Selection, keyed};
|
||||
use craft_theme::Explained;
|
||||
use craft_theme::report::ContrastReport;
|
||||
use craft_ui::buttons::IconButton;
|
||||
use craft_ui::contract::{Bind, CollectionEvent, Pad, Props as _, RowAlign, Scroll, SelectMode, Show as _, ShowCollection as _, ShowContainer as _};
|
||||
use craft_ui::display::{Shade, Text};
|
||||
use craft_ui::layout_components::{Row, Stack};
|
||||
use craft_ui::list::{List, ListRow, OpenSet, RowEvent, TrailingFace, TrailingPart};
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::style::TypeRole;
|
||||
use craft_ui::testing::{StoryData, story_props};
|
||||
use craft_ui::text::TextField;
|
||||
use egui::Ui;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// What the panels read and edit in one pass.
|
||||
#[non_exhaustive]
|
||||
pub struct Panels<'a> {
|
||||
/// What is listed.
|
||||
pub catalog: &'a Catalog,
|
||||
/// The text that narrows the tree.
|
||||
pub filter: &'a mut String,
|
||||
/// The selected row of the tree.
|
||||
pub selection: &'a mut Selection<TreeKey>,
|
||||
/// The open level groups.
|
||||
pub open: &'a mut OpenSet<TreeKey>,
|
||||
/// The story each component's card shows.
|
||||
pub story_of: &'a mut HashMap<&'static str, &'static str>,
|
||||
/// The shown stories' values.
|
||||
pub cells: &'a mut Cells,
|
||||
/// The component whose tab the tree asked to open in this pass.
|
||||
pub open_request: &'a mut Option<&'static str>,
|
||||
/// The component whose card the Overview brings into view when it is drawn.
|
||||
pub scroll_to: &'a mut Option<&'static str>,
|
||||
/// The selected component the Overview last followed to its level.
|
||||
pub followed: &'a mut Option<Option<&'static str>>,
|
||||
/// The selected component the tree last opened the level of.
|
||||
pub tree_seen: &'a mut Option<Option<&'static str>>,
|
||||
/// The reset count the cards' id scopes carry.
|
||||
pub generation: u32,
|
||||
/// What the theme panels share.
|
||||
pub themes: &'a mut ThemeWorkspace,
|
||||
/// The theme and appearance the theme panels explain.
|
||||
pub subject: ThemeSubject<'a>,
|
||||
/// The level the Overview shows, by its title.
|
||||
pub level: &'a mut String,
|
||||
/// The Variants view of the target story, while one is open.
|
||||
pub variants: &'a mut Option<crate::viewer::VariantAxis>,
|
||||
/// The centre tab the Variants view is open in.
|
||||
pub variants_tab: &'a mut Option<PanelId>,
|
||||
/// The root values; a Variants card that is used sets its value.
|
||||
pub env: &'a mut craft_ui::runtime::env::RootEnv,
|
||||
/// The row the Problems view picked in this pass, which the token browser brings into view.
|
||||
pub revealed: Option<crate::theme::Pick>,
|
||||
}
|
||||
|
||||
/// `add` in the panel's padding, scrolling vertically. The body may run more than once in a pass, so `add` is `FnMut`.
|
||||
fn scrolled(ui: &mut Ui, mut add: impl FnMut(&mut Ui)) {
|
||||
Stack::new().fill().pad(Pad::Regular).scroll(Scroll::vertical()).show(ui, |ui, _| add(ui));
|
||||
}
|
||||
|
||||
/// `add` in the panel's padding, for a body that is a collection or scrolls itself. Like `scrolled`, `add` may run more
|
||||
/// than once in a pass.
|
||||
fn padded(ui: &mut Ui, mut add: impl FnMut(&mut Ui)) {
|
||||
Stack::new().fill().pad(Pad::Regular).show(ui, |ui, _| add(ui));
|
||||
}
|
||||
|
||||
/// The tree row part that opens a component's tab.
|
||||
const OPEN: TrailingPart = TrailingPart::new(0);
|
||||
|
||||
/// A faint line where a panel has nothing to show yet.
|
||||
fn hint(ui: &mut Ui, text: &'static str) {
|
||||
Text::new(text).shade(Shade::Faint).show(ui);
|
||||
}
|
||||
|
||||
/// A caption over a value.
|
||||
fn fact(ui: &mut Ui, name: &'static str, value: impl Into<Label>) {
|
||||
let value = value.into();
|
||||
Stack::new().fill_width().show(ui, |ui, _| {
|
||||
Text::new(name).role(TypeRole::Caption).shade(Shade::Muted).show(ui);
|
||||
Text::new(value.clone()).show(ui);
|
||||
});
|
||||
}
|
||||
|
||||
/// The values of the story at catalog index `index`: the one place the panels reach into the shown cells.
|
||||
fn state_of(cells: &mut Cells, index: usize) -> &mut CardState {
|
||||
cells.entry(index).or_default()
|
||||
}
|
||||
|
||||
impl Panels<'_> {
|
||||
/// Shows the body of `panel`.
|
||||
pub fn show(&mut self, ui: &mut Ui, panel: PanelId) {
|
||||
match panel {
|
||||
PanelId::Components => self.components(ui),
|
||||
PanelId::Stories => self.stories(ui),
|
||||
PanelId::Properties => self.properties(ui),
|
||||
PanelId::Inspect => self.record(ui),
|
||||
PanelId::Overview => overview::overview(ui, self),
|
||||
PanelId::Component(type_name) => overview::component_tab(ui, self, type_name),
|
||||
PanelId::Preview => {}
|
||||
PanelId::Problems => self.problems(ui),
|
||||
PanelId::Tokens => self.tokens(ui),
|
||||
PanelId::Detail => self.detail(ui),
|
||||
PanelId::AppSizes => self.overrides(ui),
|
||||
}
|
||||
}
|
||||
|
||||
/// The selected component.
|
||||
fn selected(&self) -> Option<&ComponentInfo> {
|
||||
let type_name = self.selection.items.iter().rev().find_map(|key| match key {
|
||||
TreeKey::Component(type_name) => Some(*type_name),
|
||||
_ => None,
|
||||
})?;
|
||||
self.catalog.component(type_name)
|
||||
}
|
||||
|
||||
fn components(&mut self, ui: &mut Ui) {
|
||||
let selected = self.selected().map(|component| component.type_name);
|
||||
viewer::open_level_of_selection(self.open, &self.catalog.components, selected, &mut *self.tree_seen);
|
||||
let shown = viewer::rows(&self.catalog.components, self.filter.as_str(), &*self.open);
|
||||
let groups = viewer::groups(&shown);
|
||||
let by_key: HashMap<&TreeKey, &TreeRow> = shown.iter().map(|row| (&row.key, row)).collect();
|
||||
let before = self.selected().map(|component| component.type_name);
|
||||
let mut opened = None;
|
||||
let (filter, selection, open) = (&mut *self.filter, &mut *self.selection, &mut *self.open);
|
||||
Stack::new().fill().pad(Pad::Regular).show(ui, |ui, _| {
|
||||
TextField::search("Filter components", Bind::bound(&mut *filter)).placeholder("Filter components").show(ui);
|
||||
let listed = List::<TreeKey>::new("Components")
|
||||
.select(SelectMode::Single)
|
||||
.tree(true)
|
||||
.selection(Bind::bound(&mut *selection))
|
||||
.empty("No component matches the filter")
|
||||
.show_items(ui, &TreeRows::new(&shown), &mut |key, cx| {
|
||||
let Some(row) = by_key.get(key) else { return ListRow::spacer() };
|
||||
let item = ListRow::new(row.label.clone()).depth(row.depth);
|
||||
if row.group {
|
||||
return item.group(row.open);
|
||||
}
|
||||
// The Open icon shows on the selected row and the row under the pointer.
|
||||
if cx.row.selected || cx.row.hovered {
|
||||
item.trailing_part(OPEN, TrailingFace::Icon(IconId::new("open").into()), format!("Open {}", row.label))
|
||||
} else {
|
||||
item
|
||||
}
|
||||
});
|
||||
for event in listed.events {
|
||||
match event {
|
||||
CollectionEvent::Open(change) => open.apply(&change.key, change.open, change.all, groups.iter()),
|
||||
CollectionEvent::Activate(TreeKey::Component(type_name)) => opened = Some(type_name),
|
||||
CollectionEvent::Item(TreeKey::Component(type_name), RowEvent::Trailing { .. }) => opened = Some(type_name),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
if let Some(type_name) = opened {
|
||||
*self.open_request = Some(type_name);
|
||||
}
|
||||
// Selecting a component opens its level.
|
||||
let now = self.selected().map(|component| (component.type_name, component.level));
|
||||
if let Some((type_name, level)) = now
|
||||
&& Some(type_name) != before
|
||||
{
|
||||
self.open.set(&TreeKey::Level(level), true);
|
||||
}
|
||||
}
|
||||
|
||||
/// The story groups of the selected component; picking one shows it on the component's Overview card.
|
||||
fn stories(&mut self, ui: &mut Ui) {
|
||||
let catalog = self.catalog;
|
||||
let Some(component) = self.selected() else {
|
||||
return scrolled(ui, |ui| {
|
||||
hint(ui, "Select a component");
|
||||
});
|
||||
};
|
||||
let (type_name, names) = (component.type_name, component.groups.iter().map(|group| group.name.clone()).collect::<Vec<_>>());
|
||||
let listed: Vec<usize> = (0..names.len()).collect();
|
||||
let shown = self.target(type_name).and_then(|at| catalog.group_at(type_name, at));
|
||||
let mut selection = Selection::default();
|
||||
selection.items.extend(shown);
|
||||
let before = selection.items.clone();
|
||||
Stack::new().fill().pad(Pad::Regular).show(ui, |ui, _| {
|
||||
let source = keyed(&listed, |at| *at);
|
||||
List::<usize>::new("Stories")
|
||||
.select(SelectMode::Single)
|
||||
.selection(Bind::bound(&mut selection))
|
||||
.show_items(ui, &source, &mut |at, _| ListRow::new(names.get(*at).cloned().unwrap_or_default()));
|
||||
});
|
||||
if selection.items != before
|
||||
&& let Some(&picked) = selection.items.first()
|
||||
&& let Some(&first) = catalog.group_stories(type_name, picked).first()
|
||||
{
|
||||
self.story_of.insert(type_name, catalog.entries[first].registration.story.name);
|
||||
}
|
||||
}
|
||||
|
||||
/// The index of the story the component registered as `type_name` shows: the one picked for it, else its first.
|
||||
fn target(&self, type_name: &'static str) -> Option<usize> {
|
||||
self.catalog.pick(type_name, self.story_of.get(type_name).copied())
|
||||
}
|
||||
|
||||
/// The display title of the story at catalog index `at` of `component`.
|
||||
fn title(&self, component: &ComponentInfo, at: usize) -> String {
|
||||
let place = self.catalog.stories_of(component.type_name).iter().position(|&story| story == at);
|
||||
place.and_then(|place| component.titles.get(place)).cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
fn properties(&mut self, ui: &mut Ui) {
|
||||
let component = self.selected().cloned();
|
||||
let target = component.as_ref().and_then(|component| self.target(component.type_name));
|
||||
let (Some(component), Some(index)) = (component, target) else {
|
||||
return scrolled(ui, |ui| {
|
||||
hint(ui, "Select a component");
|
||||
});
|
||||
};
|
||||
let title = self.title(&component, index);
|
||||
let state = state_of(self.cells, index);
|
||||
// The values exist once the story has run; the first pass that finds them records the start.
|
||||
if !state.data.changed_since(&StoryData::default().snapshot()).is_empty() {
|
||||
state.note_start();
|
||||
}
|
||||
let changed = state.changed();
|
||||
let mut reset = false;
|
||||
scrolled(ui, |ui| {
|
||||
Row::new().fill_width().align(RowAlign::SpaceBetween).show(ui, |ui, _| {
|
||||
Row::new().show(ui, |ui, _| {
|
||||
Text::new(component.name.clone()).role(TypeRole::Heading).show(ui);
|
||||
Text::new(title.clone()).shade(Shade::Muted).show(ui);
|
||||
});
|
||||
if changed {
|
||||
reset = IconButton::new(IconId::new("undo")).label("Reset args").show(ui).clicks > 0;
|
||||
}
|
||||
});
|
||||
story_props(ui, &mut state.data);
|
||||
});
|
||||
if reset {
|
||||
state.reset();
|
||||
}
|
||||
}
|
||||
|
||||
/// The decision record of the selected component, then where it is declared and what it is for.
|
||||
fn record(&mut self, ui: &mut Ui) {
|
||||
let component = self.selected().map(|component| component.type_name);
|
||||
let declared = component.and_then(|type_name| self.catalog.declared.get(type_name));
|
||||
scrolled(ui, |ui| {
|
||||
let (Some(type_name), Some(declared)) = (component, declared) else {
|
||||
hint(ui, "Select a component");
|
||||
return;
|
||||
};
|
||||
match declared.probe {
|
||||
None => hint(ui, "A pattern has no record of its own: its parts are the records."),
|
||||
Some(probe) => {
|
||||
fact(ui, "Shape", describe::shape(probe.shape));
|
||||
fact(ui, "Role", describe::role(probe.role));
|
||||
fact(ui, "Input", describe::input(probe.input));
|
||||
fact(ui, "Keys it keeps", describe::keys(&probe.keys));
|
||||
fact(ui, "Opens a popup", probe.overlay.to_string());
|
||||
fact(ui, "Shows its label", probe.shows_label.to_string());
|
||||
for exemption in probe.exempt {
|
||||
fact(ui, "Exempt from", format!("{}: {}", exemption.case, exemption.reason));
|
||||
}
|
||||
}
|
||||
}
|
||||
fact(ui, "Type", type_name);
|
||||
fact(ui, "Module", declared.module);
|
||||
fact(ui, "Purpose", declared.purpose);
|
||||
});
|
||||
}
|
||||
|
||||
/// A panel over the explanation and report of the subject.
|
||||
fn theme_panel(&mut self, ui: &mut Ui, mut body: impl FnMut(&mut Self, &mut Ui, &Arc<Explained>, &Arc<ContrastReport>)) {
|
||||
self.themes.refresh(&self.subject);
|
||||
let (Some(explained), Some(report)) = (self.themes.explained().cloned(), self.themes.report().cloned()) else { return };
|
||||
padded(ui, |ui| body(self, ui, &explained, &report));
|
||||
}
|
||||
|
||||
fn problems(&mut self, ui: &mut Ui) {
|
||||
self.theme_panel(ui, |panels, ui, explained, report| {
|
||||
let picked = Problems::new(report, explained, &panels.subject).show(ui).picked;
|
||||
if let Some(pick) = picked {
|
||||
panels.themes.pick = Some(pick.clone());
|
||||
panels.revealed = Some(pick);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn tokens(&mut self, ui: &mut Ui) {
|
||||
self.theme_panel(ui, |panels, ui, explained, _| {
|
||||
let mut browser = TokenBrowser::new(explained, Bind::bound(&mut panels.themes.pick));
|
||||
if let Some(pick) = &panels.revealed {
|
||||
browser = browser.reveal(pick);
|
||||
}
|
||||
browser.show(ui);
|
||||
});
|
||||
}
|
||||
|
||||
fn detail(&mut self, ui: &mut Ui) {
|
||||
self.theme_panel(ui, |panels, ui, explained, _| {
|
||||
let mut detail = TokenDetail::new(explained);
|
||||
if let Some(pick) = &panels.themes.pick {
|
||||
detail = detail.pick(pick);
|
||||
}
|
||||
detail.show(ui);
|
||||
});
|
||||
}
|
||||
|
||||
fn overrides(&mut self, ui: &mut Ui) {
|
||||
self.theme_panel(ui, |panels, ui, explained, _| {
|
||||
let pick = panels.themes.pick.clone();
|
||||
panels.themes.edit_sizes(|sizes| {
|
||||
let mut editor = AppLayerEditor::new(Bind::bound(sizes), explained);
|
||||
if let Some(pick) = &pick {
|
||||
editor = editor.pick(pick);
|
||||
}
|
||||
editor.show(ui)
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
//! What the viewer keeps between runs. On the desktop it is the gallery's `config.toml`; the web has no file system,
|
||||
//! so the settings live in memory for the tab's lifetime.
|
||||
|
||||
use crate::viewer::GallerySettings;
|
||||
use web_time::Instant;
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod store {
|
||||
use super::{GallerySettings, Instant};
|
||||
use craft_settings::{LoadReport, Location, SaveStatus, SettingsStore, Source};
|
||||
|
||||
/// The settings file and what loading and saving it told the user.
|
||||
pub struct Persisted {
|
||||
store: SettingsStore<GallerySettings>,
|
||||
notes: Vec<String>,
|
||||
save_error: Option<String>,
|
||||
}
|
||||
|
||||
impl Persisted {
|
||||
/// The settings in the gallery's `config.toml`.
|
||||
pub fn open() -> Self {
|
||||
let (store, report) = SettingsStore::<GallerySettings>::open(Location::Auto);
|
||||
Persisted::new(store, &report)
|
||||
}
|
||||
|
||||
/// `store`, which `report` describes.
|
||||
pub fn new(store: SettingsStore<GallerySettings>, report: &LoadReport) -> Self {
|
||||
Persisted { store, notes: load_notes(report), save_error: None }
|
||||
}
|
||||
|
||||
/// The settings now.
|
||||
pub fn get(&self) -> &GallerySettings {
|
||||
self.store.get()
|
||||
}
|
||||
|
||||
/// Records `settings`; whether they changed.
|
||||
pub fn set(&mut self, settings: GallerySettings) -> bool {
|
||||
self.store.set(settings)
|
||||
}
|
||||
|
||||
/// Writes the settings now.
|
||||
pub fn save(&mut self) {
|
||||
self.save_error = self.store.flush().err().map(|error| error.to_string());
|
||||
}
|
||||
|
||||
/// Saves what is due; the next time to tick, and the settings another process changed, if any.
|
||||
pub fn tick(&mut self, now: Instant) -> (Option<Instant>, Option<GallerySettings>) {
|
||||
let tick = self.store.tick(now);
|
||||
match tick.status {
|
||||
SaveStatus::Failed(error) => self.save_error = Some(error.to_string()),
|
||||
SaveStatus::Saved => self.save_error = None,
|
||||
_ => {}
|
||||
}
|
||||
for moved in self.store.take_moved_aside() {
|
||||
self.notes.push(format!("A damaged settings file was moved aside to {}", moved.display()));
|
||||
}
|
||||
let merged = self.store.take_merged_change().then(|| self.store.get().clone());
|
||||
(tick.next_deadline, merged)
|
||||
}
|
||||
|
||||
/// What the status bar says about the settings.
|
||||
pub fn notes(&self) -> Vec<String> {
|
||||
let mut parts = self.notes.clone();
|
||||
parts.extend(self.save_error.iter().map(|error| format!("Settings were not saved: {error}")));
|
||||
parts
|
||||
}
|
||||
}
|
||||
|
||||
/// What opening the settings told that the user should know.
|
||||
fn load_notes(report: &LoadReport) -> Vec<String> {
|
||||
let mut notes = Vec::new();
|
||||
if let Some(moved) = &report.broken_moved_to {
|
||||
notes.push(format!("A damaged settings file was moved aside to {}", moved.display()));
|
||||
}
|
||||
if let Some(reason) = &report.read_only {
|
||||
notes.push(format!("Settings are read-only: {reason}"));
|
||||
}
|
||||
if let Source::Legacy(from) = &report.source {
|
||||
notes.push(format!("Settings were imported from {}", from.display()));
|
||||
}
|
||||
if !report.section_errors.is_empty() {
|
||||
notes.push(format!("{} settings sections were reset to their defaults", report.section_errors.len()));
|
||||
}
|
||||
notes.extend(report.warning.iter().cloned());
|
||||
notes
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod store {
|
||||
use super::{GallerySettings, Instant};
|
||||
|
||||
/// The settings of this tab.
|
||||
pub struct Persisted {
|
||||
settings: GallerySettings,
|
||||
}
|
||||
|
||||
impl Persisted {
|
||||
/// Settings at their defaults.
|
||||
pub fn open() -> Self {
|
||||
Persisted { settings: GallerySettings::default() }
|
||||
}
|
||||
|
||||
/// The settings now.
|
||||
pub fn get(&self) -> &GallerySettings {
|
||||
&self.settings
|
||||
}
|
||||
|
||||
/// Records `settings`; nothing waits to be saved, so this is always false.
|
||||
pub fn set(&mut self, settings: GallerySettings) -> bool {
|
||||
self.settings = settings;
|
||||
false
|
||||
}
|
||||
|
||||
/// Nothing is written on the web.
|
||||
pub fn save(&mut self) {}
|
||||
|
||||
/// Nothing is due on the web.
|
||||
pub fn tick(&mut self, _now: Instant) -> (Option<Instant>, Option<GallerySettings>) {
|
||||
(None, None)
|
||||
}
|
||||
|
||||
/// The web has nothing to report about the settings.
|
||||
pub fn notes(&self) -> Vec<String> {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub use store::Persisted;
|
||||
@@ -0,0 +1,182 @@
|
||||
//! The viewer's window: the shell with the options bar over the dock of the shown workspace, and the settings it keeps.
|
||||
|
||||
use super::dock::GalleryDock;
|
||||
use super::options::options_bar;
|
||||
use super::panels::Panels;
|
||||
use super::persist::Persisted;
|
||||
use crate::theme::{ThemeSubject, parse_sizes};
|
||||
use crate::viewer::{Browser, Catalog, GalleryCommands, GallerySettings, Viewer, Workspace, theme_of};
|
||||
use craft_behavior::dock::Workspace as Dock;
|
||||
use craft_theme::AppSizes;
|
||||
use craft_ui::contract::{Bind, BodyCx, CommandSet as _, ShowContainer as _};
|
||||
use craft_ui::docking::DockConfig;
|
||||
use craft_ui::patterns::dock::DockArea;
|
||||
use craft_ui::popover::DropVeil;
|
||||
use craft_ui::runtime::drag::OsFile;
|
||||
use craft_ui::runtime::env::WindowKey;
|
||||
use craft_ui::runtime::frame::{FrameInput, FrameOutput};
|
||||
use craft_ui::runtime::toast::{self, Toast};
|
||||
use craft_ui::shell::AppShell;
|
||||
use craft_ui::shell::app::{CloseDecision, ShellApp};
|
||||
use egui::Ui;
|
||||
use std::collections::HashSet;
|
||||
use web_time::Instant;
|
||||
|
||||
/// The viewer as the root window's app.
|
||||
pub struct Gallery {
|
||||
viewer: Viewer,
|
||||
persisted: Persisted,
|
||||
/// What came of the files last dropped on the theme workspace.
|
||||
drop_note: Option<String>,
|
||||
/// The notes already shown as toasts.
|
||||
noted: HashSet<String>,
|
||||
/// A command changed the viewer since the settings were last compared.
|
||||
command_ran: bool,
|
||||
}
|
||||
|
||||
impl Gallery {
|
||||
/// The viewer of the stories linked into the binary, in the state the gallery's settings hold.
|
||||
pub fn open() -> Self {
|
||||
Gallery::new(Catalog::linked(), Persisted::open())
|
||||
}
|
||||
|
||||
/// The viewer of `catalog` over `persisted`.
|
||||
pub fn new(catalog: Catalog, persisted: Persisted) -> Self {
|
||||
let viewer = Viewer::new(catalog, persisted.get());
|
||||
Gallery { viewer, persisted, drop_note: None, noted: HashSet::new(), command_ran: false }
|
||||
}
|
||||
|
||||
/// Shows what the settings and a dropped file have to say, once each, as toasts.
|
||||
fn announce(&mut self, ctx: &egui::Context) {
|
||||
let notes = self.persisted.notes().into_iter().chain(self.drop_note.take());
|
||||
for note in notes {
|
||||
if self.noted.insert(note.clone()) {
|
||||
toast::post(ctx, Toast::new(note));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether an input event can have changed what a control edits: hover, focus and pointer motion alone cannot, the
|
||||
/// release or key that ends an edit can.
|
||||
fn is_edit(event: &egui::Event) -> bool {
|
||||
!matches!(event, egui::Event::PointerMoved(_) | egui::Event::MouseMoved(_) | egui::Event::PointerGone | egui::Event::WindowFocused(_))
|
||||
}
|
||||
|
||||
/// The app layer a dropped `sizes.json` holds.
|
||||
fn read_dropped(file: &OsFile) -> Result<AppSizes, String> {
|
||||
let bytes = match (&file.bytes, &file.path) {
|
||||
(Some(bytes), _) => bytes.to_vec(),
|
||||
(None, Some(path)) => std::fs::read(path).map_err(|error| format!("{}: {error}", file.name))?,
|
||||
(None, None) => return Err(format!("{}: the file has no content", file.name)),
|
||||
};
|
||||
parse_sizes(&file.name, &bytes)
|
||||
}
|
||||
|
||||
/// The dock of the shown workspace over the viewer's state.
|
||||
fn body(ui: &mut Ui, _: &mut BodyCx<'_>, viewer: &mut Viewer) {
|
||||
let Viewer { env, workspace, preview, browser, themes, theme_dock, mock, variants, variants_tab, .. } = viewer;
|
||||
let subject = ThemeSubject::new(theme_of(&env.theme), env.appearance(ui.ctx()));
|
||||
let in_theme = *workspace == Workspace::Theme;
|
||||
let Browser { catalog, filter, selection, open, dock, story_of, generation, cells, open_request, scroll_to, followed, tree_seen, level, .. } =
|
||||
browser;
|
||||
let dock: &mut Dock<_> = if in_theme { theme_dock } else { dock };
|
||||
let panels = Panels {
|
||||
catalog,
|
||||
filter,
|
||||
selection,
|
||||
open,
|
||||
story_of,
|
||||
cells,
|
||||
open_request,
|
||||
scroll_to,
|
||||
followed,
|
||||
tree_seen,
|
||||
generation: *generation,
|
||||
themes,
|
||||
subject,
|
||||
level,
|
||||
variants,
|
||||
variants_tab,
|
||||
env,
|
||||
revealed: None,
|
||||
};
|
||||
let mut content = GalleryDock { panels, preview: *preview, app: mock };
|
||||
// Component tabs are documents: they close from their ×.
|
||||
let config = DockConfig::default().tab_close_buttons(true);
|
||||
DockArea::new(if in_theme { "Theme dock" } else { "Components dock" }, Bind::bound(&mut *dock), &mut content, config).show(ui);
|
||||
if let Some(type_name) = content.panels.open_request.take() {
|
||||
let _ = dock.set_visible(crate::viewer::PanelId::Component(type_name), true, Some(crate::viewer::PanelId::Overview), false, |panel| {
|
||||
panel.permissions()
|
||||
});
|
||||
}
|
||||
// A closed component tab does not come back from the layout's record of closed panels.
|
||||
dock.hidden.retain(|(panel, _)| !matches!(panel, crate::viewer::PanelId::Component(_)));
|
||||
}
|
||||
|
||||
impl ShellApp for Gallery {
|
||||
fn frame_input(&mut self) -> FrameInput {
|
||||
FrameInput::new(self.viewer.env.clone())
|
||||
}
|
||||
|
||||
fn output(&mut self, output: FrameOutput) {
|
||||
for fired in output.fired {
|
||||
if let Some(command) = GalleryCommands::from_ref(&fired.command) {
|
||||
self.command_ran = true;
|
||||
self.viewer.run(command);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn tick(&mut self, now: Instant) -> Option<Instant> {
|
||||
let (deadline, merged) = self.persisted.tick(now);
|
||||
if let Some(settings) = merged {
|
||||
self.viewer.restore(&settings);
|
||||
}
|
||||
deadline
|
||||
}
|
||||
|
||||
fn close_requested(&mut self) -> CloseDecision {
|
||||
self.persisted.save();
|
||||
CloseDecision::Close
|
||||
}
|
||||
|
||||
fn ui(&mut self, ui: &mut Ui) {
|
||||
let in_theme = self.viewer.workspace == Workspace::Theme;
|
||||
let shell = |ui: &mut Ui, viewer: &mut Viewer| {
|
||||
AppShell::new(WindowKey::main())
|
||||
.options_bar(true, |ui, _, viewer: &mut Viewer| options_bar(ui, viewer))
|
||||
.body_label("Gallery")
|
||||
.body(body)
|
||||
.show(ui, viewer);
|
||||
};
|
||||
let dropped = if in_theme {
|
||||
let viewer = &mut self.viewer;
|
||||
DropVeil::new("Drop an app's sizes.json to load it").show(ui, |ui, _| shell(ui, viewer)).dropped.clone()
|
||||
} else {
|
||||
shell(ui, &mut self.viewer);
|
||||
None
|
||||
};
|
||||
if let Some(file) = dropped.as_ref().and_then(|dropped| dropped.files.first()) {
|
||||
self.drop_note = Some(match read_dropped(file) {
|
||||
Ok(sizes) => {
|
||||
self.viewer.themes.edit_sizes(|layer| {
|
||||
*layer = sizes;
|
||||
true
|
||||
});
|
||||
format!("Loaded {}", file.name)
|
||||
}
|
||||
Err(message) => message,
|
||||
});
|
||||
}
|
||||
self.viewer.sync_sizes();
|
||||
self.announce(ui.ctx());
|
||||
// The controls change the viewer only on input, and a command only in `output`: a pass with neither has
|
||||
// nothing new to save.
|
||||
let edited = std::mem::take(&mut self.command_ran) || ui.ctx().input(|input| input.events.iter().any(is_edit));
|
||||
if edited && self.persisted.set(GallerySettings::of(&self.viewer)) {
|
||||
// The pass after a change ticks the store, which names when the save is due.
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
//! The Variants view: the target story repeated over one axis of the appearance, a card for each value, in place of the
|
||||
//! front centre tab's content.
|
||||
|
||||
use super::card::Look;
|
||||
use super::overview::{Spec, SpecStory, apply, grid, on_background, selected_type, target_story};
|
||||
use super::panels::Panels;
|
||||
use crate::viewer::{DIRECTIONS, MODES, PanelId, VariantAxis, entry_of};
|
||||
use craft_i18n::Direction;
|
||||
use craft_theme::variant::Tone;
|
||||
use craft_theme::{ControlSize, Mode, ModeChoice};
|
||||
use craft_ui::buttons::Button;
|
||||
use craft_ui::contract::{Show as _, ShowContainer as _, StoryLayout};
|
||||
use craft_ui::display::{Shade, Text};
|
||||
use craft_ui::layout_components::Row;
|
||||
use craft_ui::notices::Notice;
|
||||
use craft_ui::style::TypeRole;
|
||||
use egui::Ui;
|
||||
|
||||
/// One value of an axis: its name, the look a card shows it with, and what picking it sets.
|
||||
struct Value {
|
||||
label: &'static str,
|
||||
look: Look,
|
||||
}
|
||||
|
||||
/// The words after "in every" in the view's heading.
|
||||
fn noun(axis: VariantAxis) -> &'static str {
|
||||
match axis {
|
||||
VariantAxis::Theme => "theme",
|
||||
VariantAxis::Mode => "mode",
|
||||
VariantAxis::Contrast => "contrast",
|
||||
VariantAxis::Size => "size",
|
||||
VariantAxis::Direction => "direction",
|
||||
VariantAxis::ControlSize => "control size",
|
||||
VariantAxis::DirectionAndControlSize => "direction and control size",
|
||||
}
|
||||
}
|
||||
|
||||
/// The values of `axis`, or `None` for an axis a card cannot be shown under: the theme, contrast and density of a
|
||||
/// region are the window's (a theme scope sets the mode only).
|
||||
fn values(axis: VariantAxis) -> Option<Vec<Value>> {
|
||||
let direction = |direction: Direction| Some(direction);
|
||||
let sizes = [(ControlSize::Sm, "Sm"), (ControlSize::Md, "Md")];
|
||||
match axis {
|
||||
VariantAxis::Mode => {
|
||||
// The two modes a card can show; System is the window's own choice.
|
||||
let mode_of = |choice: ModeChoice| match choice {
|
||||
ModeChoice::Light => Some(Mode::Light),
|
||||
ModeChoice::Dark => Some(Mode::Dark),
|
||||
_ => None,
|
||||
};
|
||||
Some(
|
||||
MODES
|
||||
.0
|
||||
.iter()
|
||||
.filter_map(|choice| {
|
||||
mode_of(choice.value).map(|mode| Value { label: choice.label, look: Look { mode: Some(mode), ..Look::default() } })
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
VariantAxis::Direction => Some(
|
||||
DIRECTIONS
|
||||
.0
|
||||
.iter()
|
||||
.map(|choice| Value { label: choice.label, look: Look { direction: direction(choice.value), ..Look::default() } })
|
||||
.collect(),
|
||||
),
|
||||
VariantAxis::ControlSize => {
|
||||
Some(sizes.iter().map(|(size, label)| Value { label, look: Look { size: Some(*size), ..Look::default() } }).collect())
|
||||
}
|
||||
VariantAxis::DirectionAndControlSize => Some(
|
||||
DIRECTIONS
|
||||
.0
|
||||
.iter()
|
||||
.flat_map(|choice| {
|
||||
sizes.iter().map(move |(size, _)| Value {
|
||||
label: if choice.value.is_rtl() {
|
||||
if *size == ControlSize::Sm { "RTL, Sm" } else { "RTL, Md" }
|
||||
} else if *size == ControlSize::Sm {
|
||||
"LTR, Sm"
|
||||
} else {
|
||||
"LTR, Md"
|
||||
},
|
||||
look: Look { direction: Some(choice.value), size: Some(*size), ..Look::default() },
|
||||
})
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the Variants view is open in `tab`: it opens in the tab that is in front when it is asked for and closes
|
||||
/// when another one comes to the front.
|
||||
fn open_in(p: &mut Panels<'_>, tab: PanelId) -> bool {
|
||||
if p.variants.is_none() {
|
||||
*p.variants_tab = None;
|
||||
return false;
|
||||
}
|
||||
match *p.variants_tab {
|
||||
None => {
|
||||
*p.variants_tab = Some(tab);
|
||||
true
|
||||
}
|
||||
Some(owner) if owner == tab => true,
|
||||
Some(_) => {
|
||||
*p.variants = None;
|
||||
*p.variants_tab = None;
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows the Variants view in `tab` when one is open there. Returns whether it did.
|
||||
pub(super) fn show(ui: &mut Ui, p: &mut Panels<'_>, tab: PanelId) -> bool {
|
||||
if !open_in(p, tab) {
|
||||
return false;
|
||||
}
|
||||
let Some(axis) = *p.variants else { return false };
|
||||
let mut closed = false;
|
||||
let target = selected_type(p).and_then(|type_name| target_story(p, type_name).map(|index| (type_name, index)));
|
||||
let cards: Vec<Spec> = match (target, values(axis)) {
|
||||
(Some((type_name, index)), Some(values)) => {
|
||||
let Some(entry) = entry_of(type_name) else { return false };
|
||||
let (mode, direction) = (p.env.appearance(ui.ctx()).mode, p.env.direction);
|
||||
let shown = |look: &Look| match axis {
|
||||
VariantAxis::Mode => look.mode == Some(mode),
|
||||
VariantAxis::Direction => look.direction == Some(direction),
|
||||
_ => false,
|
||||
};
|
||||
values
|
||||
.iter()
|
||||
.map(|value| Spec {
|
||||
key: format!("variant/{}/{}", noun(axis), value.label),
|
||||
type_name,
|
||||
title: value.label.to_owned(),
|
||||
note: shown(&value.look).then(|| "shown now".to_owned()),
|
||||
stories: vec![SpecStory::of(p, index, &entry.name)],
|
||||
layout: StoryLayout::Stacked,
|
||||
surface: entry.surface,
|
||||
open: false,
|
||||
usable: true,
|
||||
selected: false,
|
||||
look: value.look,
|
||||
gated: false,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let heading = target.and_then(|(type_name, index)| {
|
||||
let entry = entry_of(type_name)?;
|
||||
Some(format!("{} · {} in every {}", entry.name, p.catalog.entries[index].registration.story.caption(&entry.name), noun(axis)))
|
||||
});
|
||||
let mut reported = Vec::new();
|
||||
on_background(ui, "variants", |ui, cx| {
|
||||
Row::new().show(ui, |ui, _| {
|
||||
Text::new(heading.clone().unwrap_or_else(|| "Variants".to_owned())).role(TypeRole::Heading).show(ui);
|
||||
Text::new("Use one to set it").shade(Shade::Muted).show(ui);
|
||||
closed |= Button::new("Close").show(ui).clicks > 0;
|
||||
});
|
||||
if cards.is_empty() {
|
||||
let text = if target.is_none() {
|
||||
"Select a component to see its variants."
|
||||
} else {
|
||||
"Cards under this axis need a theme scope the framework does not have yet."
|
||||
};
|
||||
let _ = Notice::new(Tone::Info, text).show(ui);
|
||||
} else {
|
||||
reported = grid(ui, "variants", &cards, p, false);
|
||||
}
|
||||
closed |= cx.take_cancel();
|
||||
});
|
||||
let used = reported.iter().find(|reported| reported.events.used).map(|reported| reported.spec);
|
||||
apply(ui, p, &cards, reported);
|
||||
if let Some(card) = used.and_then(|spec| values(axis).and_then(|values| values.into_iter().nth(spec))) {
|
||||
if let Some(mode) = card.look.mode {
|
||||
p.env.mode = mode.into();
|
||||
}
|
||||
if let Some(direction) = card.look.direction {
|
||||
p.env.direction = direction;
|
||||
}
|
||||
closed = true;
|
||||
}
|
||||
if closed {
|
||||
*p.variants = None;
|
||||
}
|
||||
true
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
//! The craft-ui story viewer: the registered stories of the linked crates, shown under a chosen appearance.
|
||||
|
||||
pub mod chrome;
|
||||
pub mod viewer;
|
||||
|
||||
// The theme workspace.
|
||||
pub mod theme;
|
||||
|
||||
// The mock editor window.
|
||||
pub mod mock;
|
||||
|
||||
/// The gallery window's default size, in points.
|
||||
pub const WINDOW: [f32; 2] = [1280.0, 800.0];
|
||||
|
||||
/// The registrations of every crate whose stories the viewer shows, by crate.
|
||||
///
|
||||
/// Each entry is a function of its crate that is passed by pointer, so the linker keeps that crate's object files and
|
||||
/// the story registrations in them, which a release build for the web would otherwise drop.
|
||||
type Registered = fn() -> Vec<&'static craft_ui::testing::Registration>;
|
||||
|
||||
fn crates() -> Vec<(&'static str, Registered)> {
|
||||
#[allow(unused_mut, clippy::vec_init_then_push)]
|
||||
let mut crates: Vec<(&'static str, Registered)> = Vec::new();
|
||||
#[cfg(feature = "automation")]
|
||||
crates.push(("craft-automation", craft_automation::testing::registered));
|
||||
#[cfg(feature = "browse")]
|
||||
crates.push(("craft-browse", craft_browse::ui::testing::registered));
|
||||
#[cfg(feature = "color")]
|
||||
crates.push(("craft-color", craft_color::ui::testing::registered));
|
||||
#[cfg(feature = "draw")]
|
||||
crates.push(("craft-draw", craft_draw::testing::registered));
|
||||
#[cfg(feature = "imaging")]
|
||||
crates.push(("craft-imaging", craft_imaging::testing::registered));
|
||||
#[cfg(feature = "layers")]
|
||||
crates.push(("craft-layers", craft_layers::testing::registered));
|
||||
#[cfg(feature = "menu")]
|
||||
crates.push(("craft-menu", craft_menu::testing::registered));
|
||||
#[cfg(feature = "pages")]
|
||||
crates.push(("craft-pages", craft_pages::testing::registered));
|
||||
#[cfg(feature = "print")]
|
||||
crates.push(("craft-print", craft_print::testing::registered));
|
||||
#[cfg(feature = "review")]
|
||||
crates.push(("craft-review", craft_review::testing::registered));
|
||||
#[cfg(feature = "table")]
|
||||
crates.push(("craft-table", craft_table::ui::testing::registered));
|
||||
#[cfg(feature = "text")]
|
||||
crates.push(("craft-text", craft_text::testing::registered));
|
||||
#[cfg(feature = "theme-store")]
|
||||
crates.push(("craft-theme-store", craft_theme_store::ui::registered));
|
||||
#[cfg(feature = "timeline")]
|
||||
crates.push(("craft-timeline", craft_timeline::testing::registered));
|
||||
// These do not build for the web, so their stories are in the native gallery only.
|
||||
#[cfg(all(feature = "dialogs", not(target_arch = "wasm32")))]
|
||||
crates.push(("craft-dialogs", craft_dialogs::testing::registered));
|
||||
#[cfg(all(feature = "font-manager", not(target_arch = "wasm32")))]
|
||||
crates.push(("craft-font-manager", craft_font_manager::testing::registered));
|
||||
#[cfg(all(feature = "update", not(target_arch = "wasm32")))]
|
||||
crates.push(("craft-update", craft_update::testing::registered));
|
||||
std::hint::black_box(crates)
|
||||
}
|
||||
|
||||
/// How many registrations each linked crate contributes, with the viewer's own, and how many stories there are in all.
|
||||
pub fn linked_counts() -> (Vec<(&'static str, usize)>, usize) {
|
||||
let mut counts: Vec<(&'static str, usize)> = crates().into_iter().map(|(name, registered)| (name, registered().len())).collect();
|
||||
counts.push((env!("CARGO_PKG_NAME"), testing::registered().len()));
|
||||
(counts, craft_ui::testing::stories().len())
|
||||
}
|
||||
|
||||
/// The test registry of this package's stories.
|
||||
pub mod testing {
|
||||
craft_ui::testing_registered!();
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
//! The craft-ui story viewer: the registered stories of the linked crates, shown under a chosen appearance.
|
||||
|
||||
use craft_behavior::placement::Defaults;
|
||||
use craft_ui::shell::app::AppSpec;
|
||||
use craft_ui_gallery::WINDOW;
|
||||
use craft_ui_gallery::chrome::Gallery;
|
||||
|
||||
const TITLE: &str = "craft-ui stories";
|
||||
const WINDOW_MIN: [f32; 2] = [640.0, 480.0];
|
||||
|
||||
fn spec() -> AppSpec {
|
||||
AppSpec::new("craft-ui-gallery", TITLE, Defaults::new(WINDOW, WINDOW_MIN))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn main() -> eframe::Result {
|
||||
craft_ui::shell::app::run(spec(), |_| Gallery::open())
|
||||
}
|
||||
|
||||
/// The web build: the gallery on the page's `gallery_canvas`, started by trunk's bundle. The number of stories goes
|
||||
/// to the browser console, to compare with the native count.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn main() {
|
||||
use eframe::wasm_bindgen::{JsCast as _, JsValue};
|
||||
use eframe::web_sys::{HtmlCanvasElement, console, window};
|
||||
|
||||
wasm_bindgen_futures::spawn_local(async {
|
||||
let (counts, stories) = craft_ui_gallery::linked_counts();
|
||||
let per_crate: Vec<String> = counts.iter().map(|(name, count)| format!("{name}={count}")).collect();
|
||||
console::log_1(&JsValue::from_str(&format!("craft-ui-gallery: {stories} stories; registrations by crate: {}", per_crate.join(" "))));
|
||||
let canvas = window()
|
||||
.and_then(|window| window.document())
|
||||
.and_then(|document| document.get_element_by_id("gallery_canvas"))
|
||||
.and_then(|element| element.dyn_into::<HtmlCanvasElement>().ok());
|
||||
let Some(canvas) = canvas else {
|
||||
console::error_1(&JsValue::from_str("craft-ui-gallery: the page has no canvas with id gallery_canvas"));
|
||||
return;
|
||||
};
|
||||
if let Err(error) = craft_ui::shell::app::start_web(canvas, spec(), |_| Gallery::open()).await {
|
||||
console::error_2(&JsValue::from_str("craft-ui-gallery: the app did not start"), &error);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
//! The app commands of the menus.
|
||||
|
||||
use super::model::Panel;
|
||||
use craft_ui::contract::CommandSet;
|
||||
|
||||
/// The mock's app commands: the File, Image, Layer, Filter, View and Window menu rows. A row shows the command's label
|
||||
/// and chord and fires it; the window's body takes it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, CommandSet)]
|
||||
#[command(prefix = "mockApp")]
|
||||
#[non_exhaustive]
|
||||
pub enum AppCommand {
|
||||
/// A new document.
|
||||
#[command(label = "New…", default = "Cmd+N")]
|
||||
New,
|
||||
/// Opens a document.
|
||||
#[command(label = "Open…", default = "Cmd+O")]
|
||||
Open,
|
||||
/// Saves the document.
|
||||
#[command(label = "Save", default = "Cmd+S")]
|
||||
Save,
|
||||
/// Opens the Image Size dialog.
|
||||
#[command(label = "Image Size…", default = "Cmd+Alt+I")]
|
||||
ImageSize,
|
||||
/// Adds a layer above the current one.
|
||||
#[command(label = "New Layer", default = "Cmd+Shift+N")]
|
||||
NewLayer,
|
||||
/// Asks whether to delete the current layer.
|
||||
#[command(label = "Layer…")]
|
||||
DeleteLayer,
|
||||
/// Opens the Gaussian Blur dialog.
|
||||
#[command(label = "Gaussian Blur…")]
|
||||
GaussianBlur,
|
||||
/// Shows or hides the rulers.
|
||||
#[command(label = "Rulers", kind = "toggle", default = "Cmd+R")]
|
||||
Rulers,
|
||||
/// Shows or hides the canvas panel.
|
||||
#[command(label = "Canvas", kind = "toggle")]
|
||||
ShowCanvas,
|
||||
/// Shows or hides the Navigator.
|
||||
#[command(label = "Navigator", kind = "toggle")]
|
||||
ShowNavigator,
|
||||
/// Shows or hides the layer list.
|
||||
#[command(label = "Layers", kind = "toggle")]
|
||||
ShowLayers,
|
||||
}
|
||||
|
||||
impl AppCommand {
|
||||
/// The command that shows or hides `panel`.
|
||||
pub const fn showing(panel: Panel) -> AppCommand {
|
||||
match panel {
|
||||
Panel::Canvas => AppCommand::ShowCanvas,
|
||||
Panel::Navigator => AppCommand::ShowNavigator,
|
||||
Panel::Layers => AppCommand::ShowLayers,
|
||||
}
|
||||
}
|
||||
|
||||
/// The panel the command shows or hides.
|
||||
pub const fn panel(self) -> Option<Panel> {
|
||||
match self {
|
||||
AppCommand::ShowCanvas => Some(Panel::Canvas),
|
||||
AppCommand::ShowNavigator => Some(Panel::Navigator),
|
||||
AppCommand::ShowLayers => Some(Panel::Layers),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
//! `EditorMock`: a document editor window composed from library components.
|
||||
|
||||
use super::commands::AppCommand;
|
||||
use super::model::{MockState, Panel, Tool, ToolKey};
|
||||
use super::panels::Panels;
|
||||
use super::tools::Tools;
|
||||
use craft_behavior::dock::PanelState;
|
||||
use craft_ui::bars::{Bar, BarKind, StatusReadout, StatusValues};
|
||||
use craft_ui::canvas::{PickStep, ViewCommands};
|
||||
use craft_ui::contract::{Bind, BodyCx, Props as _, Remember as _, SaveKey, Show as _, ShowContainer as _};
|
||||
use craft_ui::dialog::{DialogResult, PromptChoice, StandardPrompt};
|
||||
use craft_ui::display::{Divider, Text};
|
||||
use craft_ui::docking::{DockConfig, DockEvent, DockPanels as _};
|
||||
use craft_ui::menu::{Menu, MenuBar, MenuItem, MenuTitle};
|
||||
use craft_ui::patterns::dock::DockArea;
|
||||
use craft_ui::patterns::form_dialogs::{
|
||||
DialogFields, HostedImageSize, HostedParamDialog, ImageSize, ImageSizeValues, Param, ParamDialog, ParamResult,
|
||||
};
|
||||
use craft_ui::rails::ToolRail;
|
||||
use craft_ui::runtime::commands::{CommandRef, Commands as _, EditCommands};
|
||||
use craft_ui::runtime::env::{Label, WindowKey};
|
||||
use craft_ui::shell::{AppShell, AppShellOutput, ShellDialogsCx as _, Title, TitleBar};
|
||||
use egui::Ui;
|
||||
|
||||
/// The parameters of Gaussian Blur.
|
||||
const BLUR: &str = r#"{"radius":0.1..1000=1}"#;
|
||||
|
||||
/// The command key of the Gaussian Blur dialog.
|
||||
const BLUR_KEY: &str = "gaussianBlur";
|
||||
|
||||
/// Where Gaussian Blur remembers its values.
|
||||
const BLUR_MEMORY: SaveKey = SaveKey::new("craft_ui_gallery.gaussianBlur");
|
||||
|
||||
/// The mock editor: the shell with its title bar and menus, options bar, tool rail and status bar around a dock whose
|
||||
/// canvas group holds the document tabs, the canvas with its rulers and pasteboard, and the Navigator and layer panels.
|
||||
///
|
||||
/// - Tool: the rail and the tool keys pick the current tool; Hand and Zoom run in the canvas's tool host.
|
||||
/// - Menus: every row is an app command with its chord; the body takes them.
|
||||
/// - Dialogs: Layer, Delete, Layer and Filter, Gaussian Blur open on the window's dialog host; Image, Image Size
|
||||
/// shows its dialog over the document's size.
|
||||
/// - Screen modes: the shell's own commands (F) and the reveal keys act inside the window's region.
|
||||
#[derive(craft_ui::contract::Pattern)]
|
||||
pub struct EditorMock<'a> {
|
||||
label: Label,
|
||||
state: &'a mut MockState,
|
||||
}
|
||||
|
||||
impl<'a> EditorMock<'a> {
|
||||
/// A mock editor named `label` over `state`.
|
||||
pub fn new(label: impl Into<Label>, state: &'a mut MockState) -> Self {
|
||||
EditorMock { label: label.into(), state }
|
||||
}
|
||||
|
||||
/// Shows the window in the room offered. Each instance keeps its screen mode, Tab toggle and dialogs apart.
|
||||
pub fn show(self, ui: &mut Ui) -> AppShellOutput {
|
||||
let EditorMock { label, state } = self;
|
||||
let window = WindowKey::new(format!("mock-{:x}-{}", ui.scope_id().value(), label.as_str()));
|
||||
AppShell::embedded(window)
|
||||
.title_bar_if(true, |ui, _, state: &mut MockState| title_bar(ui, state))
|
||||
.options_bar(true, |ui, _, state: &mut MockState| options_bar(ui, state))
|
||||
.tools(true, |ui, _, state: &mut MockState| tool_rail(ui, state))
|
||||
.status(true, |ui, _, state: &mut MockState| status_bar(ui, state))
|
||||
.body_label(label)
|
||||
.body(|ui, cx, state: &mut MockState| body(ui, cx, state))
|
||||
.show(ui, state)
|
||||
}
|
||||
}
|
||||
|
||||
/// The dock, then the commands and dialog answers of this pass.
|
||||
fn body(ui: &mut Ui, cx: &mut BodyCx<'_>, state: &mut MockState) {
|
||||
let mut tools = cx.keep::<Tools>().clone();
|
||||
let events = {
|
||||
let mut panels = Panels { document: &mut state.document, tool: state.tool, tools: &mut tools };
|
||||
let mut area = DockArea::new("Dock", Bind::bound(&mut state.workspace), &mut panels, DockConfig::default());
|
||||
if let Some(panel) = state.maximized {
|
||||
area = area.maximized(panel);
|
||||
}
|
||||
area.show(ui).events
|
||||
};
|
||||
for event in events {
|
||||
if let DockEvent::ToggleMaximize { panel, .. } = event {
|
||||
state.maximized = if state.maximized == Some(panel) { None } else { Some(panel) };
|
||||
}
|
||||
}
|
||||
|
||||
while let Some((command, _)) = cx.take_command::<Tool>() {
|
||||
state.tool = command;
|
||||
}
|
||||
while let Some((key, _)) = cx.take_command::<ToolKey>() {
|
||||
match key {
|
||||
ToolKey::PickBrush => pick(state, Tool::Brush, PickStep::Last),
|
||||
ToolKey::CycleBrush => pick(state, Tool::Brush, PickStep::Next),
|
||||
ToolKey::SwapColors => state.colors.swap(),
|
||||
ToolKey::ResetColors => state.colors.reset(),
|
||||
}
|
||||
}
|
||||
let mut asked = Vec::new();
|
||||
while let Some((command, _)) = cx.take_command::<AppCommand>() {
|
||||
asked.push(command);
|
||||
}
|
||||
let mut dialogs = Vec::new();
|
||||
for command in asked {
|
||||
if let Some(panel) = command.panel() {
|
||||
let shown = state.workspace.layout.panel_state(&panel) != PanelState::Hidden;
|
||||
let panels = Panels { document: &mut state.document, tool: state.tool, tools: &mut tools };
|
||||
let _ = state.workspace.set_visible(panel, !shown, None, false, |panel| panels.permissions(panel));
|
||||
continue;
|
||||
}
|
||||
match command {
|
||||
AppCommand::NewLayer => state.document.add_layer(),
|
||||
AppCommand::Rulers => state.document.rulers = !state.document.rulers,
|
||||
AppCommand::ImageSize | AppCommand::DeleteLayer | AppCommand::GaussianBlur => dialogs.push(command),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
*cx.keep::<Tools>() = tools;
|
||||
|
||||
if let Some(host) = cx.dialogs() {
|
||||
host.with(|host| {
|
||||
for command in dialogs {
|
||||
match command {
|
||||
AppCommand::GaussianBlur => {
|
||||
host.open(HostedParamDialog::new(BLUR_KEY, DialogFields::new(), |fields| {
|
||||
ParamDialog::new(BLUR_KEY, "Gaussian Blur", Param::parse_list(BLUR)).values(Bind::bound(fields)).remember(BLUR_MEMORY)
|
||||
}));
|
||||
}
|
||||
AppCommand::DeleteLayer => {
|
||||
let name = state.document.current_layer().map(|layer| layer.name.clone()).unwrap_or_default();
|
||||
host.open(StandardPrompt::confirm_delete([name], 1));
|
||||
}
|
||||
AppCommand::ImageSize => {
|
||||
let values = ImageSizeValues::new(state.document.pixel_size());
|
||||
host.open(HostedImageSize::new(values, |values: Bind<'_, ImageSizeValues>| ImageSize::new(values)));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let Some(result) = host.take::<HostedParamDialog>().and_then(DialogResult::<ParamResult>::ok) {
|
||||
result.remember(ui);
|
||||
state.document.dirty = true;
|
||||
}
|
||||
if let Some(result) = host.take::<HostedImageSize>().and_then(DialogResult::ok) {
|
||||
state.document.resize(result.size);
|
||||
}
|
||||
let confirmed = host.take::<StandardPrompt>().and_then(DialogResult::ok).is_some_and(|answer| answer.choice == PromptChoice::Proceed);
|
||||
if confirmed {
|
||||
state.document.delete_current();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Makes the tool a key picks in `tool`'s slot the current tool.
|
||||
fn pick(state: &mut MockState, tool: Tool, step: PickStep) {
|
||||
if let Some(picked) = Tool::pick(tool.slot(), state.tool, &state.last_used, step) {
|
||||
state.tool = picked;
|
||||
}
|
||||
}
|
||||
|
||||
fn title_bar(ui: &mut Ui, state: &MockState) {
|
||||
let document = &state.document;
|
||||
let title = if document.dirty { Title::unsaved(document.title.clone()) } else { Title::new(document.title.clone()) };
|
||||
TitleBar::new().show_titled(
|
||||
ui,
|
||||
title,
|
||||
|ui, _| {
|
||||
let titles = vec![
|
||||
MenuTitle::new("&File", |ui| {
|
||||
for command in [AppCommand::New, AppCommand::Open, AppCommand::Save] {
|
||||
MenuItem::command(command).enabled(false).show(ui);
|
||||
}
|
||||
}),
|
||||
MenuTitle::new("&Edit", |ui| {
|
||||
for command in [EditCommands::Undo, EditCommands::Redo] {
|
||||
MenuItem::command(command).enabled(false).show(ui);
|
||||
}
|
||||
Divider::horizontal().show(ui);
|
||||
for command in [EditCommands::Cut, EditCommands::Copy, EditCommands::Paste] {
|
||||
MenuItem::command(command).enabled(false).show(ui);
|
||||
}
|
||||
}),
|
||||
MenuTitle::new("&Image", |ui| {
|
||||
MenuItem::command(AppCommand::ImageSize).show(ui);
|
||||
}),
|
||||
MenuTitle::new("&Layer", |ui| {
|
||||
MenuItem::command(AppCommand::NewLayer).show(ui);
|
||||
Menu::submenu_row(ui, "Delete", |ui, _| {
|
||||
MenuItem::command(AppCommand::DeleteLayer).enabled(document.layers.len() > 1).show(ui);
|
||||
});
|
||||
}),
|
||||
MenuTitle::new("Fil&ter", |ui| {
|
||||
MenuItem::command(AppCommand::GaussianBlur).show(ui);
|
||||
}),
|
||||
MenuTitle::new("&View", |ui| {
|
||||
for command in
|
||||
[ViewCommands::FitOnScreen, ViewCommands::FillScreen, ViewCommands::ActualPixels, ViewCommands::ZoomIn, ViewCommands::ZoomOut]
|
||||
{
|
||||
MenuItem::command(command).show(ui);
|
||||
}
|
||||
Divider::horizontal().show(ui);
|
||||
MenuItem::command(AppCommand::Rulers).check(document.rulers).show(ui);
|
||||
}),
|
||||
MenuTitle::new("&Window", |ui| {
|
||||
for panel in Panel::ALL {
|
||||
let shown = state.workspace.layout.panel_state(&panel) != PanelState::Hidden;
|
||||
MenuItem::command(AppCommand::showing(panel)).check(shown).enabled(!panel.protected()).show(ui);
|
||||
}
|
||||
}),
|
||||
];
|
||||
MenuBar::new("Main menu", titles).show(ui);
|
||||
},
|
||||
|_, _| {},
|
||||
);
|
||||
}
|
||||
|
||||
fn options_bar(ui: &mut Ui, state: &MockState) {
|
||||
let colors = state.colors;
|
||||
let _ = Bar::new("Options", BarKind::Options).show(ui, |ui, _| {
|
||||
Text::new(format!("Foreground #{:06X} Background #{:06X}", colors.foreground, colors.background)).show(ui);
|
||||
});
|
||||
}
|
||||
|
||||
fn tool_rail(ui: &mut Ui, state: &mut MockState) {
|
||||
let slots = Tool::slots();
|
||||
let current = state.tool;
|
||||
let last_used = state.last_used.clone();
|
||||
let output = ToolRail::new("Tools", &slots, ¤t, &last_used).show_rail(ui, |_, _| {});
|
||||
if let Some(tool) = output.select {
|
||||
state.tool = tool;
|
||||
}
|
||||
if let Some(last_used) = output.last_used {
|
||||
state.last_used = last_used;
|
||||
}
|
||||
}
|
||||
|
||||
fn status_bar(ui: &mut Ui, state: &mut MockState) {
|
||||
let MockState { document, tool, status_item, .. } = state;
|
||||
let mut values = StatusValues::default();
|
||||
values.document_dimensions = Some(document.pixel_size());
|
||||
values.current_tool = Some(CommandRef::from(*tool));
|
||||
values.layer_count = Some(document.layers.len());
|
||||
let mut chosen = None;
|
||||
let _ = Bar::new("Status", BarKind::Status).show(ui, |ui, _| {
|
||||
chosen = StatusReadout::new(Bind::bound(&mut document.view), document.size, *status_item, &values).show(ui).item;
|
||||
});
|
||||
if let Some(item) = chosen {
|
||||
*status_item = item;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
//! The mock editor window: the shell, title bar, rails, dock, document tabs, canvas and dialogs of a document editor,
|
||||
//! composed from library components only.
|
||||
|
||||
mod commands;
|
||||
mod editor;
|
||||
mod model;
|
||||
mod panels;
|
||||
mod stories;
|
||||
mod tools;
|
||||
mod words;
|
||||
|
||||
pub use commands::AppCommand;
|
||||
pub use editor::EditorMock;
|
||||
pub use model::{ColorPair, Document, Layer, LayerId, MarqueeDrag, MockState, Panel, Tool, ToolKey};
|
||||
@@ -0,0 +1,385 @@
|
||||
//! What the mock editor reads and edits: a tool, a layer list, a canvas view, a document title and a dirty flag.
|
||||
|
||||
use craft_behavior::dock::{Column, DockEdge, Group, Layout, Node, SplitSize, Workspace};
|
||||
use craft_behavior::kurbo::Rect as DocRect;
|
||||
use craft_behavior::kurbo::{Point, Size};
|
||||
use craft_behavior::{Axis, PixelSize};
|
||||
use craft_behavior::{CanvasView, Selection};
|
||||
use craft_ui::bars::StatusItem;
|
||||
use craft_ui::canvas::{Guide, GuideKey, PickStep, PixelRect, tool_pick};
|
||||
use craft_ui::contract::CommandSet;
|
||||
use craft_ui::rails::{LastUsed, RailTool, SlotId, ToolSlot};
|
||||
use craft_ui::runtime::env::UnitKind;
|
||||
use egui::{Color32, Rect};
|
||||
|
||||
/// The width of the dock column at the end edge.
|
||||
const SIDE_WIDTH: f32 = 220.0;
|
||||
|
||||
/// The width of the mock document, in document units.
|
||||
const DOCUMENT_WIDTH: f64 = 1200.0;
|
||||
|
||||
/// The height of the mock document, in document units.
|
||||
const DOCUMENT_HEIGHT: f64 = 800.0;
|
||||
|
||||
/// The share of the dock the canvas group takes.
|
||||
const CANVAS_SHARE: f32 = 0.8;
|
||||
|
||||
/// The tools of the rail. Each is a command of the `tools` group; a tool alone in its slot carries its letter, and the
|
||||
/// letter of a slot with several is the pick command of [`ToolKey`].
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, CommandSet)]
|
||||
#[command(prefix = "mockTool")]
|
||||
#[non_exhaustive]
|
||||
pub enum Tool {
|
||||
/// Move.
|
||||
#[command(label = "Move", icon = "move", kind = "tool", group = "tools", default = "V")]
|
||||
Move,
|
||||
/// Rectangular Marquee.
|
||||
#[command(label = "Rectangular Marquee", icon = "marquee_rect", kind = "tool", group = "tools", default = "M")]
|
||||
Marquee,
|
||||
/// Brush.
|
||||
#[command(label = "Brush", icon = "brush", kind = "tool", group = "tools")]
|
||||
Brush,
|
||||
/// Pencil.
|
||||
#[command(label = "Pencil", icon = "pencil", kind = "tool", group = "tools")]
|
||||
Pencil,
|
||||
/// Eraser.
|
||||
#[command(label = "Eraser", icon = "eraser", kind = "tool", group = "tools", default = "E")]
|
||||
Eraser,
|
||||
/// Clone Stamp.
|
||||
#[command(label = "Clone Stamp", icon = "stamp", kind = "tool", group = "tools", default = "S")]
|
||||
Stamp,
|
||||
/// Hand.
|
||||
#[command(label = "Hand", icon = "hand", kind = "tool", group = "tools", default = "H")]
|
||||
Hand,
|
||||
/// Zoom.
|
||||
#[command(label = "Zoom", icon = "zoom_in", kind = "tool", group = "tools", default = "Z")]
|
||||
Zoom,
|
||||
}
|
||||
|
||||
/// The keys of the tool slots and the colour pair that are no tool: the letter of a slot with several tools picks
|
||||
/// the one it shows, Shift with the letter cycles them, and X and D act on the colour pair.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, CommandSet)]
|
||||
#[command(prefix = "mockToolKey")]
|
||||
#[non_exhaustive]
|
||||
pub enum ToolKey {
|
||||
/// Picks the Brush slot's tool.
|
||||
#[command(label = "Brush Tools", default = "B")]
|
||||
PickBrush,
|
||||
/// Cycles the Brush slot's tools.
|
||||
#[command(label = "Cycle Brush Tools", default = "Shift+B")]
|
||||
CycleBrush,
|
||||
/// Swaps the foreground and background colours.
|
||||
#[command(label = "Swap Foreground and Background Colors", default = "X")]
|
||||
SwapColors,
|
||||
/// Sets the colours to black and white.
|
||||
#[command(label = "Default Foreground and Background Colors", default = "D")]
|
||||
ResetColors,
|
||||
}
|
||||
|
||||
impl Tool {
|
||||
/// The rail's slots: Move and the Marquee alone, then the freehand tools that share a slot.
|
||||
pub fn slots() -> Vec<ToolSlot<Tool>> {
|
||||
let tool = |tool: Tool| RailTool::new(tool, tool);
|
||||
vec![
|
||||
ToolSlot::new(0, vec![tool(Tool::Move)]),
|
||||
ToolSlot::new(1, vec![tool(Tool::Marquee)]),
|
||||
ToolSlot::new(2, vec![tool(Tool::Brush), tool(Tool::Pencil)]),
|
||||
ToolSlot::new(3, vec![tool(Tool::Eraser)]),
|
||||
ToolSlot::new(4, vec![tool(Tool::Stamp)]),
|
||||
ToolSlot::new(5, vec![tool(Tool::Hand)]),
|
||||
ToolSlot::new(6, vec![tool(Tool::Zoom)]),
|
||||
]
|
||||
}
|
||||
|
||||
/// The slot that holds the tool.
|
||||
pub fn slot(self) -> SlotId {
|
||||
match self {
|
||||
Tool::Move => 0,
|
||||
Tool::Marquee => 1,
|
||||
Tool::Brush | Tool::Pencil => 2,
|
||||
Tool::Eraser => 3,
|
||||
Tool::Stamp => 4,
|
||||
Tool::Hand => 5,
|
||||
Tool::Zoom => 6,
|
||||
}
|
||||
}
|
||||
|
||||
/// The tool a key picks in the slot `slot` when `current` is the current tool.
|
||||
pub fn pick(slot: SlotId, current: Tool, last_used: &LastUsed<Tool>, step: PickStep) -> Option<Tool> {
|
||||
let slots = Tool::slots();
|
||||
let group = slots.iter().find(|group| group.id == slot)?;
|
||||
let tools: Vec<&RailTool<Tool>> = group.tools.iter().collect();
|
||||
tool_pick(&tools, slot, ¤t, last_used, step, |_| true).map(|tool| tool.id)
|
||||
}
|
||||
}
|
||||
|
||||
/// The foreground and background colours, as 24-bit RGB values.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub struct ColorPair {
|
||||
/// The foreground colour.
|
||||
pub foreground: u32,
|
||||
/// The background colour.
|
||||
pub background: u32,
|
||||
}
|
||||
|
||||
impl Default for ColorPair {
|
||||
fn default() -> Self {
|
||||
ColorPair { foreground: 0x00_0000, background: 0xFF_FFFF }
|
||||
}
|
||||
}
|
||||
|
||||
impl ColorPair {
|
||||
/// Swaps the two colours.
|
||||
pub fn swap(&mut self) {
|
||||
std::mem::swap(&mut self.foreground, &mut self.background);
|
||||
}
|
||||
|
||||
/// Sets black and white.
|
||||
pub fn reset(&mut self) {
|
||||
*self = ColorPair::default();
|
||||
}
|
||||
}
|
||||
|
||||
/// The panels of the dock.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
pub enum Panel {
|
||||
/// The document tabs over the canvas.
|
||||
Canvas,
|
||||
/// The Navigator.
|
||||
Navigator,
|
||||
/// The layer list.
|
||||
Layers,
|
||||
}
|
||||
|
||||
impl Panel {
|
||||
/// Every panel, in the Window menu's order.
|
||||
pub const ALL: [Panel; 3] = [Panel::Canvas, Panel::Navigator, Panel::Layers];
|
||||
|
||||
/// Whether the panel stays docked and open: the canvas.
|
||||
pub const fn protected(self) -> bool {
|
||||
matches!(self, Panel::Canvas)
|
||||
}
|
||||
}
|
||||
|
||||
/// The stable identity of a layer: it survives reordering, deleting and adding other layers.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub struct LayerId(u64);
|
||||
|
||||
/// One layer of the document: a named fill of one rectangle of the page.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct Layer {
|
||||
/// The layer's identity within its document.
|
||||
pub id: LayerId,
|
||||
/// The name the layers panel shows; distinct within a document.
|
||||
pub name: String,
|
||||
/// Whether the layer shows on the canvas.
|
||||
pub visible: bool,
|
||||
/// The colour the layer fills its bounds with.
|
||||
pub color: Color32,
|
||||
/// The part of the page the layer covers, in pixels.
|
||||
pub bounds: PixelRect,
|
||||
}
|
||||
|
||||
impl Layer {
|
||||
/// A visible layer.
|
||||
pub fn new(id: LayerId, name: impl Into<String>, color: Color32, bounds: PixelRect) -> Self {
|
||||
Layer { id, name: name.into(), visible: true, color, bounds }
|
||||
}
|
||||
}
|
||||
|
||||
/// A rectangle being dragged out with the Marquee: where the press began and where the pointer is now.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct MarqueeDrag {
|
||||
/// The document point of the press.
|
||||
pub start: Point,
|
||||
/// The document point of the pointer.
|
||||
pub now: Point,
|
||||
}
|
||||
|
||||
impl MarqueeDrag {
|
||||
/// The rectangle the drag spans.
|
||||
pub fn rect(&self) -> DocRect {
|
||||
DocRect::from_points(self.start, self.now)
|
||||
}
|
||||
}
|
||||
|
||||
/// The open document.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct Document {
|
||||
/// The title of the window and the tab.
|
||||
pub title: String,
|
||||
/// Whether the document has unsaved changes.
|
||||
pub dirty: bool,
|
||||
/// The size in document units.
|
||||
pub size: Size,
|
||||
/// The layers, top first.
|
||||
pub layers: Vec<Layer>,
|
||||
/// The selected layers; the lead is the current layer.
|
||||
pub selected: Selection<LayerId>,
|
||||
/// The canvas view. A view that was never shown opens fitted.
|
||||
pub view: CanvasView,
|
||||
/// The ruler zero point.
|
||||
pub zero: Point,
|
||||
/// The unit the rulers count in.
|
||||
pub units: UnitKind,
|
||||
/// The guides dragged out of the rulers.
|
||||
pub guides: Vec<Guide>,
|
||||
/// The selected guide.
|
||||
pub guide: Option<GuideKey>,
|
||||
/// The selection the Marquee made.
|
||||
pub marquee: Option<DocRect>,
|
||||
/// The marquee being dragged out.
|
||||
pub dragging: Option<MarqueeDrag>,
|
||||
/// Whether the rulers show.
|
||||
pub rulers: bool,
|
||||
/// The number the next layer gets as its identity.
|
||||
next_layer: u64,
|
||||
}
|
||||
|
||||
impl Default for Document {
|
||||
fn default() -> Self {
|
||||
let size = Size::new(DOCUMENT_WIDTH, DOCUMENT_HEIGHT);
|
||||
let view = CanvasView::new(Rect::NOTHING, Point::new(size.width / 2.0, size.height / 2.0), 1.0);
|
||||
let (width, height) = (DOCUMENT_WIDTH as i32, DOCUMENT_HEIGHT as i32);
|
||||
let layers = vec![
|
||||
Layer::new(LayerId(2), "Mountains", Color32::from_rgb(96, 110, 130), PixelRect::new(0, height * 5 / 8, width, height)),
|
||||
Layer::new(LayerId(1), "Sky", Color32::from_rgb(150, 190, 235), PixelRect::new(0, 0, width, height * 3 / 4)),
|
||||
Layer::new(LayerId(0), "Background", Color32::from_rgb(235, 226, 205), PixelRect::new(0, 0, width, height)),
|
||||
];
|
||||
Document {
|
||||
title: "Landscape.psd".to_owned(),
|
||||
dirty: false,
|
||||
size,
|
||||
selected: Selection::single(layers[0].id),
|
||||
layers,
|
||||
view,
|
||||
zero: Point::ZERO,
|
||||
units: UnitKind::Pixels,
|
||||
guides: Vec::new(),
|
||||
guide: None,
|
||||
marquee: None,
|
||||
dragging: None,
|
||||
rulers: true,
|
||||
next_layer: 3,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Document {
|
||||
/// The index of the current layer, counted from the top.
|
||||
pub fn current_index(&self) -> Option<usize> {
|
||||
let lead = self.selected.lead?;
|
||||
self.layers.iter().position(|layer| layer.id == lead)
|
||||
}
|
||||
|
||||
/// The current layer: the lead of the selection.
|
||||
pub fn current_layer(&self) -> Option<&Layer> {
|
||||
self.current_index().map(|at| &self.layers[at])
|
||||
}
|
||||
|
||||
/// The size in pixels.
|
||||
pub fn pixel_size(&self) -> PixelSize {
|
||||
PixelSize::new(self.size.width as u32, self.size.height as u32)
|
||||
}
|
||||
|
||||
/// The rectangle the Marquee shows: the one being dragged, else the selection.
|
||||
pub fn marquee_rect(&self) -> Option<DocRect> {
|
||||
self.dragging.map(|drag| drag.rect()).or(self.marquee)
|
||||
}
|
||||
|
||||
/// Gives the document `size`, which marks it changed when the size differs.
|
||||
pub fn resize(&mut self, size: PixelSize) {
|
||||
let size = Size::new(f64::from(size.width), f64::from(size.height));
|
||||
if self.size != size {
|
||||
self.size = size;
|
||||
self.dirty = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Makes the first layer current when the selection lost its lead (a click on no row).
|
||||
pub fn keep_current(&mut self) {
|
||||
if self.current_index().is_none()
|
||||
&& let Some(top) = self.layers.first()
|
||||
{
|
||||
self.selected = Selection::single(top.id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds a layer above the current one and makes it the only selected one, which marks the document changed.
|
||||
pub fn add_layer(&mut self) {
|
||||
let number = self.next_layer;
|
||||
self.next_layer += 1;
|
||||
let name = (self.layers.len() + 1..)
|
||||
.map(|number| format!("Layer {number}"))
|
||||
.find(|name| self.layers.iter().all(|layer| layer.name != *name))
|
||||
.unwrap_or_default();
|
||||
let (width, height) = (self.size.width as i32, self.size.height as i32);
|
||||
let shade = u8::try_from(number * 40 % 200).unwrap_or(0);
|
||||
let bounds = PixelRect::new(width / 4, height / 4, width * 3 / 4, height * 3 / 4);
|
||||
let layer = Layer::new(LayerId(number), name, Color32::from_rgb(220, 90 + shade / 2, 60 + shade), bounds);
|
||||
let at = self.current_index().unwrap_or(0);
|
||||
self.selected = Selection::single(layer.id);
|
||||
self.layers.insert(at, layer);
|
||||
self.dirty = true;
|
||||
}
|
||||
|
||||
/// Shows or hides the layer `id`, which marks the document changed.
|
||||
pub fn set_visible(&mut self, id: LayerId, visible: bool) {
|
||||
if let Some(layer) = self.layers.iter_mut().find(|layer| layer.id == id).filter(|layer| layer.visible != visible) {
|
||||
layer.visible = visible;
|
||||
self.dirty = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Deletes the current layer and selects the layer below it (the one above for the lowest), which marks the
|
||||
/// document changed. The last layer stays.
|
||||
pub fn delete_current(&mut self) -> Option<Layer> {
|
||||
let at = self.current_index().filter(|_| self.layers.len() > 1)?;
|
||||
let removed = self.layers.remove(at);
|
||||
let below = &self.layers[at.min(self.layers.len() - 1)];
|
||||
self.selected = Selection::single(below.id);
|
||||
self.dirty = true;
|
||||
Some(removed)
|
||||
}
|
||||
}
|
||||
|
||||
/// Everything the mock edits.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct MockState {
|
||||
/// The dock's panels and where they sit.
|
||||
pub workspace: Workspace<Panel>,
|
||||
/// The open document.
|
||||
pub document: Document,
|
||||
/// The current tool.
|
||||
pub tool: Tool,
|
||||
/// The tool each rail slot showed last.
|
||||
pub last_used: LastUsed<Tool>,
|
||||
/// The status bar's item.
|
||||
pub status_item: StatusItem,
|
||||
/// The foreground and background colours.
|
||||
pub colors: ColorPair,
|
||||
/// The panel whose frame shows alone.
|
||||
pub maximized: Option<Panel>,
|
||||
}
|
||||
|
||||
impl Default for MockState {
|
||||
fn default() -> Self {
|
||||
let side = Column::new(vec![Group::new(vec![Panel::Navigator], 0), Group::new(vec![Panel::Layers], 0)]).with_width(SIDE_WIDTH);
|
||||
let root = Node::split(Axis::X, SplitSize::Ratio(CANVAS_SHARE), Node::tabs(vec![Panel::Canvas], 0), Node::dock(DockEdge::End, vec![side]));
|
||||
MockState {
|
||||
workspace: Workspace::new(Layout::new(Some(root), Vec::new())),
|
||||
document: Document::default(),
|
||||
tool: Tool::Move,
|
||||
last_used: LastUsed::default(),
|
||||
status_item: StatusItem::DocumentDimensions,
|
||||
colors: ColorPair::default(),
|
||||
maximized: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
//! The panels of the dock: the canvas group the host draws, the Navigator and the layer table.
|
||||
|
||||
use super::model::{Document, Layer, Panel, Tool};
|
||||
use super::tools::{MarqueeTool, MoveTool, Tools};
|
||||
use super::words::MockWords;
|
||||
use craft_behavior::dock::Permissions;
|
||||
use craft_behavior::kurbo::Rect as DocRect;
|
||||
use craft_behavior::{ColumnKey, ColumnWidth, PixelSize, RulerUnits, Ticks, keyed};
|
||||
use craft_ui::canvas::{
|
||||
Canvas, CanvasScrollbars, CanvasSpace, NoTool, PageFrame, Pasteboard, PixelRect, RasterDisplay, RasterSource, RulerText, Rulers, ToolHost,
|
||||
};
|
||||
use craft_ui::canvas_controls::{Guides, Marquee};
|
||||
use craft_ui::contract::SizeLimits;
|
||||
use craft_ui::contract::{
|
||||
Bind, BodyCx, CollectionEvent, ColumnKind, ColumnSpec, Remember as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, SweepApply,
|
||||
SweepStep, ToggleColumn, WordSetCx as _,
|
||||
};
|
||||
use craft_ui::docking::{DockPanels, GroupAt, PanelSpec};
|
||||
use craft_ui::list::{ListRow, ToggleCell};
|
||||
use craft_ui::patterns::canvas::NavigatorPanel;
|
||||
use craft_ui::primitives::textures::Revision;
|
||||
use craft_ui::runtime::env::UnitKind;
|
||||
use craft_ui::shell::CanvasPanel;
|
||||
use craft_ui::table::Table;
|
||||
use craft_ui::tabs::{DocumentTab, DocumentTabs, DocumentTabsEvent};
|
||||
use egui::{Color32, ColorImage, Ui};
|
||||
use std::borrow::Cow;
|
||||
|
||||
/// The units the rulers' menu offers.
|
||||
const UNITS: [UnitKind; 5] = [UnitKind::Pixels, UnitKind::Points, UnitKind::Inches, UnitKind::Centimetres, UnitKind::Millimetres];
|
||||
|
||||
/// The resolution of the mock document, in pixels per inch.
|
||||
const PIXELS_PER_INCH: f64 = 72.0;
|
||||
|
||||
const NAME: ColumnKey = ColumnKey::new("name");
|
||||
const VISIBLE: ColumnKey = ColumnKey::new("visible");
|
||||
|
||||
/// The dock's panels over the open document.
|
||||
pub(super) struct Panels<'a> {
|
||||
pub(super) document: &'a mut Document,
|
||||
pub(super) tool: Tool,
|
||||
pub(super) tools: &'a mut Tools,
|
||||
}
|
||||
|
||||
impl Panels<'_> {
|
||||
/// The document tab's title: the name, the zoom of the device and the current layer.
|
||||
fn tab_title(&self, ui: &Ui, cx: &BodyCx<'_>) -> String {
|
||||
let document = &self.document;
|
||||
let zoom = CanvasSpace::new(document.view, ui.pixels_per_point()).zoom_device() * 100.0;
|
||||
let layer = document.current_layer().map_or("", |layer| layer.name.as_str());
|
||||
cx.words::<MockWords>().tab_title.fill(&[("name", &document.title), ("zoom", &cx.format().integer(zoom.round() as i64)), ("layer", layer)])
|
||||
}
|
||||
}
|
||||
|
||||
fn name(panel: Panel) -> &'static str {
|
||||
match panel {
|
||||
Panel::Canvas => "Canvas",
|
||||
Panel::Navigator => "Navigator",
|
||||
Panel::Layers => "Layers",
|
||||
}
|
||||
}
|
||||
|
||||
impl DockPanels<Panel> for Panels<'_> {
|
||||
fn spec(&self, panel: &Panel) -> PanelSpec {
|
||||
let spec = PanelSpec::new(name(*panel)).limits(SizeLimits::default());
|
||||
if *panel == Panel::Canvas { spec.canvas() } else { spec }
|
||||
}
|
||||
|
||||
fn permissions(&self, panel: &Panel) -> Permissions {
|
||||
if panel.protected() { Permissions::PROTECTED } else { Permissions::ALL }
|
||||
}
|
||||
|
||||
fn body(&mut self, panel: &Panel, ui: &mut Ui, cx: &mut BodyCx<'_>) {
|
||||
match panel {
|
||||
Panel::Navigator => {
|
||||
let size = self.document.size;
|
||||
let _ = NavigatorPanel::new("Navigator", Bind::bound(&mut self.document.view), size).show(ui);
|
||||
}
|
||||
Panel::Layers => layers(ui, cx, self.document),
|
||||
Panel::Canvas => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn group_view(&mut self, panels: &[Panel], _: usize, ui: &mut Ui, at: GroupAt, cx: &mut BodyCx<'_>) -> Option<f32> {
|
||||
// The canvas fills the rect it is shown in; protected, it never sits in a flyout, which is what measures.
|
||||
let GroupAt::Show(rect) = at else { return None };
|
||||
if !panels.contains(&Panel::Canvas) {
|
||||
return None;
|
||||
}
|
||||
let title = self.tab_title(ui, cx);
|
||||
let modified = self.document.dirty;
|
||||
let mut events = Vec::new();
|
||||
let document = &mut *self.document;
|
||||
let (tool, tools) = (self.tool, &mut *self.tools);
|
||||
CanvasPanel::new()
|
||||
.tabs(|ui, _| {
|
||||
let tabs = [DocumentTab::new(0_usize, title.clone()).modified(modified)];
|
||||
events = DocumentTabs::new("Documents", &tabs).selected(0).show(ui).events;
|
||||
})
|
||||
.show(ui, |ui, _| canvas(ui, document, tool, tools));
|
||||
for event in events {
|
||||
// The mock holds one document, so selecting its tab changes nothing; closing it discards the edits and
|
||||
// opens the document again as it was.
|
||||
if matches!(event, DocumentTabsEvent::CloseRequested(_)) {
|
||||
*self.document = Document::default();
|
||||
}
|
||||
}
|
||||
Some(rect.height())
|
||||
}
|
||||
}
|
||||
|
||||
/// The rulers' text in `kind`.
|
||||
fn ruler_text(kind: UnitKind) -> RulerText {
|
||||
let per_doc = kind.per_inch(PIXELS_PER_INCH).map_or(1.0, |per_inch| per_inch / PIXELS_PER_INCH);
|
||||
RulerText::new(RulerUnits::new(per_doc, Ticks::decimal(kind == UnitKind::Pixels)), kind)
|
||||
}
|
||||
|
||||
/// A layer as the raster display reads it: its colour over its bounds, transparent elsewhere.
|
||||
struct LayerFill<'a> {
|
||||
layer: &'a Layer,
|
||||
size: PixelSize,
|
||||
}
|
||||
|
||||
impl RasterSource for LayerFill<'_> {
|
||||
fn size(&self) -> PixelSize {
|
||||
self.size
|
||||
}
|
||||
|
||||
fn revision(&self) -> Revision {
|
||||
let b = self.layer.bounds;
|
||||
Revision::of(&(self.layer.id, self.layer.color.to_array(), [b.x0, b.y0, b.x1, b.y1]))
|
||||
}
|
||||
|
||||
fn damage(&self, _: Revision) -> Option<PixelRect> {
|
||||
None
|
||||
}
|
||||
|
||||
fn read(&self, region: PixelRect, factor: u32, out: &mut ColorImage) {
|
||||
let [width, height] = out.size;
|
||||
let bounds = self.layer.bounds;
|
||||
for row in 0..height {
|
||||
for column in 0..width {
|
||||
let x = region.x0 + (column as u32 * factor) as i32;
|
||||
let y = region.y0 + (row as u32 * factor) as i32;
|
||||
let inside = (bounds.x0..bounds.x1).contains(&x) && (bounds.y0..bounds.y1).contains(&y);
|
||||
out.pixels[row * width + column] = if inside { self.layer.color } else { Color32::TRANSPARENT };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the canvas body found out in a pass.
|
||||
struct BodyResult {
|
||||
/// The view the scroll bars set.
|
||||
scrolled: Option<craft_behavior::CanvasView>,
|
||||
/// The pointer is over a scroll bar, so the tool leaves the press alone.
|
||||
over_bars: bool,
|
||||
}
|
||||
|
||||
/// The document area: the pasteboard, the visible layers, the selection, the rulers with their guides and the scroll
|
||||
/// bars on a canvas whose tool host runs the current tool and reports the one view.
|
||||
fn canvas(ui: &mut Ui, document: &mut Document, tool: Tool, tools: &mut Tools) {
|
||||
let units = ruler_text(document.units);
|
||||
let page = DocRect::new(0.0, 0.0, document.size.width, document.size.height);
|
||||
let pages = [PageFrame::new(page)];
|
||||
let pixels = document.pixel_size();
|
||||
let (view, show_rulers) = (document.view, document.rulers);
|
||||
let editing = matches!(tool, Tool::Move | Tool::Marquee);
|
||||
let shown = {
|
||||
let Document { layers, guides, guide, marquee, zero, units: unit, .. } = &mut *document;
|
||||
Canvas::new("Document").view(view).document(page.size()).show_rulers(show_rulers).rulers(units, units, *zero).show(ui, |ui, body| {
|
||||
let _ = Pasteboard::new("Pasteboard", &pages).show_at(ui, body.rect);
|
||||
for layer in layers.iter().rev().filter(|layer| layer.visible) {
|
||||
let source = LayerFill { layer, size: pixels };
|
||||
let _ = RasterDisplay::new(layer.name.clone(), &source).show_at(ui, body.rect);
|
||||
}
|
||||
if let Some(rect) = *marquee {
|
||||
let _ = Marquee::rect("Selection", rect).show_at(ui, body.rect);
|
||||
}
|
||||
let mut content = body.rect;
|
||||
let mut pending = None;
|
||||
if show_rulers {
|
||||
let rulers = Rulers::new("Rulers", Bind::bound(zero)).units(&UNITS).show_at(ui, body.rect);
|
||||
content = rulers.content_rect();
|
||||
pending = rulers.guide;
|
||||
if let Some(picked) = rulers.unit_picked {
|
||||
*unit = picked;
|
||||
}
|
||||
}
|
||||
let mut controls = Guides::new("Guides", Bind::bound(guides)).interactive(editing);
|
||||
if let Some(selected) = *guide {
|
||||
controls = controls.selected_guide(selected);
|
||||
}
|
||||
if let Some(drag) = pending {
|
||||
controls = controls.pending(drag);
|
||||
}
|
||||
if let Some(select) = controls.show_at(ui, body.rect).select {
|
||||
*guide = select;
|
||||
}
|
||||
let bars = CanvasScrollbars::new("Scroll bars", Bind::given(view), page).show_at(ui, content);
|
||||
BodyResult { scrolled: bars.view.value().copied(), over_bars: bars.over }
|
||||
})
|
||||
};
|
||||
let result = shown.inner;
|
||||
let host = ToolHost::new().momentary(&mut tools.momentary).enabled(!result.as_ref().is_some_and(|result| result.over_bars));
|
||||
let reported = match tool {
|
||||
Tool::Hand => host.run(ui, &shown.output, &mut tools.hand),
|
||||
Tool::Zoom => host.run(ui, &shown.output, &mut tools.zoom),
|
||||
Tool::Move => host.run(ui, &shown.output, &mut MoveTool),
|
||||
Tool::Marquee => host.run(ui, &shown.output, &mut MarqueeTool::new(document)),
|
||||
Tool::Brush | Tool::Pencil | Tool::Eraser | Tool::Stamp => host.run(ui, &shown.output, &mut NoTool),
|
||||
};
|
||||
if let Some(next) = result.and_then(|result| result.scrolled).or(reported.view) {
|
||||
document.view = next;
|
||||
}
|
||||
}
|
||||
|
||||
/// The layer table: an eye column and a name column over the layers, top first, with several layers selectable and
|
||||
/// the lead being the current layer.
|
||||
fn layers(ui: &mut Ui, cx: &mut BodyCx<'_>, document: &mut Document) {
|
||||
let columns = vec![
|
||||
ColumnSpec::new(VISIBLE, "Visible", ColumnWidth::Controls(1.5)).kind(ColumnKind::Toggle(ToggleColumn::sweepable())),
|
||||
ColumnSpec::new(NAME, "Layer", ColumnWidth::fill(1.0)),
|
||||
];
|
||||
let events = {
|
||||
let Document { layers, selected, .. } = &mut *document;
|
||||
let source = keyed(layers, |layer| layer.id)
|
||||
.with_text(|layer| Cow::Borrowed(layer.name.as_str()))
|
||||
.with_toggled(|layer, column| *column == VISIBLE && layer.visible);
|
||||
Table::new("Layers", columns)
|
||||
.select(SelectMode::Multi)
|
||||
.selection(Bind::bound(selected))
|
||||
.show_items(ui, &source, &mut |id, icx| {
|
||||
let layer = layers.iter().find(|layer| layer.id == *id);
|
||||
let name = layer.map(|layer| layer.name.clone()).unwrap_or_default();
|
||||
ListRow::new(name).cells(icx.cells()).toggle(ToggleCell::eye(VISIBLE, layer.is_some_and(|layer| layer.visible)))
|
||||
})
|
||||
.events
|
||||
};
|
||||
for event in events {
|
||||
let CollectionEvent::Toggle(edit) = event else { continue };
|
||||
let step = cx.keep::<SweepApply>().feed(&edit);
|
||||
if let Some(SweepStep::Flip(toggle) | SweepStep::Restore(toggle)) = step {
|
||||
document.set_visible(toggle.key, toggle.on);
|
||||
}
|
||||
}
|
||||
document.keep_current();
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
//! The story of the mock editor window.
|
||||
|
||||
use super::tools::MoveTool;
|
||||
use super::{EditorMock, MockState};
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story, tool_story};
|
||||
use egui::Ui;
|
||||
|
||||
#[story(EditorMock<'static>, covers = [])]
|
||||
fn editor_window(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let state = data.value("mock", MockState::default());
|
||||
EditorMock::new("Editor", state).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(MoveTool, covers = [], drive = Drive::Never)]
|
||||
fn move_tool(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
tool_story(ui, "Document", &mut MoveTool)
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
//! The canvas tools of the mock: what the window keeps across passes in its root container, the Move tool and the
|
||||
//! rectangular Marquee.
|
||||
|
||||
use super::model::{Document, MarqueeDrag};
|
||||
use craft_behavior::kurbo::{Point, Rect as DocRect};
|
||||
use craft_behavior::{CancelReason, Cursor, CursorIcon};
|
||||
use craft_ui::canvas::{CanvasTool, HandTool, Momentary, NavigationOptions, ToolAction, ToolContext, ToolKey, ToolPath, ToolPointer, ZoomTool};
|
||||
use craft_ui::primitives::Draw;
|
||||
use craft_ui::runtime::env::Label;
|
||||
use egui::Pos2;
|
||||
|
||||
/// The tools the canvas runs for the rail's Hand and Zoom, and the momentary pair of both.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct Tools {
|
||||
pub(super) hand: HandTool,
|
||||
pub(super) zoom: ZoomTool,
|
||||
pub(super) momentary: Momentary,
|
||||
}
|
||||
|
||||
impl Default for Tools {
|
||||
fn default() -> Self {
|
||||
let options = NavigationOptions::default();
|
||||
Tools { hand: HandTool::new(options), zoom: ZoomTool::new(options), momentary: Momentary::new(options) }
|
||||
}
|
||||
}
|
||||
|
||||
/// The Move tool: it takes no press of its own (the guides over the canvas take theirs) and its command form is
|
||||
/// moving the current layer.
|
||||
#[derive(Debug, craft_ui::contract::Pattern)]
|
||||
#[pattern(tool)]
|
||||
pub(super) struct MoveTool;
|
||||
|
||||
impl CanvasTool for MoveTool {
|
||||
fn press(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) -> ToolAction {
|
||||
ToolAction::Ignored
|
||||
}
|
||||
|
||||
fn drag(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {}
|
||||
|
||||
fn release(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {}
|
||||
|
||||
fn cancel(&mut self, _: CancelReason, _: &mut ToolContext<'_>) {}
|
||||
|
||||
fn paint(&self, _: &Draw<'_>, _: &ToolContext<'_>) {}
|
||||
|
||||
fn command_form(&self) -> ToolPath {
|
||||
ToolPath::Command("the Move Layer command")
|
||||
}
|
||||
}
|
||||
|
||||
/// The rectangular Marquee over the document's selection: a drag makes the selection, a click away clears it, and
|
||||
/// Escape clears it too.
|
||||
#[derive(Debug)]
|
||||
pub(super) struct MarqueeTool<'a> {
|
||||
document: &'a mut Document,
|
||||
}
|
||||
|
||||
impl<'a> MarqueeTool<'a> {
|
||||
pub(super) fn new(document: &'a mut Document) -> Self {
|
||||
MarqueeTool { document }
|
||||
}
|
||||
|
||||
fn drag_to(&mut self, at: Pos2, cx: &mut ToolContext<'_>) {
|
||||
let (Some(space), Some(drag)) = (cx.space(), self.document.dragging.as_mut()) else { return };
|
||||
drag.now = space.view.to_doc(at);
|
||||
let rect = drag.rect();
|
||||
cx.readout(vec![(Label::from("W"), format!("{:.0}", rect.width())), (Label::from("H"), format!("{:.0}", rect.height()))]);
|
||||
}
|
||||
}
|
||||
|
||||
impl CanvasTool for MarqueeTool<'_> {
|
||||
fn press(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) -> ToolAction {
|
||||
let Some(space) = cx.space() else { return ToolAction::Ignored };
|
||||
let start = space.view.to_doc(pointer.pos);
|
||||
self.document.dragging = Some(MarqueeDrag { start, now: start });
|
||||
ToolAction::Claimed
|
||||
}
|
||||
|
||||
fn drag(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) {
|
||||
self.drag_to(pointer.pos, cx);
|
||||
}
|
||||
|
||||
fn release(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) {
|
||||
self.drag_to(pointer.pos, cx);
|
||||
let rect = self.document.dragging.take().map(|drag| drag.rect());
|
||||
// A press that never grew is a click away from the selection: it clears it.
|
||||
self.document.marquee = rect.filter(|rect| rect.area() > 0.0);
|
||||
}
|
||||
|
||||
fn cancel(&mut self, _: CancelReason, _: &mut ToolContext<'_>) {
|
||||
self.document.dragging = None;
|
||||
}
|
||||
|
||||
fn key(&mut self, key: &ToolKey, _: &mut ToolContext<'_>) -> bool {
|
||||
let clears = matches!(key, ToolKey::Cancel) && self.document.marquee.is_some();
|
||||
if clears {
|
||||
self.document.marquee = None;
|
||||
}
|
||||
clears
|
||||
}
|
||||
|
||||
fn paint(&self, _: &Draw<'_>, cx: &ToolContext<'_>) {
|
||||
let (Some(space), Some(drag)) = (cx.space(), self.document.dragging) else { return };
|
||||
let DocRect { x0, y0, x1, y1 } = drag.rect();
|
||||
let corners = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)].map(|(x, y)| space.view.to_screen(Point::new(x, y)));
|
||||
cx.marching_ants(&corners, true);
|
||||
}
|
||||
|
||||
fn cursor(&self, _: &ToolContext<'_>) -> Cursor {
|
||||
Cursor::System(CursorIcon::Crosshair)
|
||||
}
|
||||
|
||||
fn command_form(&self) -> ToolPath {
|
||||
ToolPath::Command("the Select Rectangle command")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
//! The words of the mock editor.
|
||||
|
||||
craft_ui::words! {
|
||||
/// The words of the mock editor's own text.
|
||||
pub struct MockWords {
|
||||
/// The document tab: `{name}`, the zoom as a number of percent in `{zoom}`, and the current layer in `{layer}`.
|
||||
tab_title: template "mockEditor.tabTitle" = "{name} @ {zoom}% ({layer}, RGB/8)";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
//! The token browser: every colour, component token and size of the subject theme as a list of groups, with filters
|
||||
//! over it.
|
||||
|
||||
use super::chip::chip;
|
||||
use super::rows::{Filters, Row, TokenRows};
|
||||
use super::subject::Pick;
|
||||
use super::words::{layer_words, lengths_words, value_words};
|
||||
use craft_behavior::{Selection, SelectionChange};
|
||||
use craft_theme::{Explained, Mode, Rgba, TokenRef};
|
||||
use craft_ui::choice::Checkbox;
|
||||
use craft_ui::contract::{Bind, CollectionEvent, Held, Pattern, Props, SelectMode, Show as _, ShowCollection as _, ShowContainer as _};
|
||||
use craft_ui::display::{Shade, Text};
|
||||
use craft_ui::layout_components::{Row as Line, Stack};
|
||||
use craft_ui::list::{List, ListRow, OpenSet, ThumbSize};
|
||||
use craft_ui::runtime::memory::Remember as _;
|
||||
use craft_ui::style::TypeRole;
|
||||
use craft_ui::text::TextField;
|
||||
use egui::Ui;
|
||||
|
||||
/// What the browser keeps between passes: the filters and which groups are open.
|
||||
#[derive(Clone, Default)]
|
||||
struct Session {
|
||||
filters: Filters,
|
||||
open: OpenSet<Row>,
|
||||
}
|
||||
|
||||
/// The list of tokens of an explanation, in groups that open and close, with a filter by path and by pins, moves
|
||||
/// and failing pairs.
|
||||
///
|
||||
/// - The selected row follows the bound pick. Selecting or activating a token or size row writes it there.
|
||||
/// - [`reveal`](TokenBrowser::reveal) opens a pick's group and scrolls its row into view in the pass it is given, as
|
||||
/// often as the host gives it, whether or not the pick changes.
|
||||
/// - A filter on shows every group's matches, open.
|
||||
#[derive(Pattern, Props)]
|
||||
pub struct TokenBrowser<'a> {
|
||||
explained: &'a Explained,
|
||||
pick: Held<'a, Option<Pick>>,
|
||||
/// The row to bring into view in this pass.
|
||||
#[prop]
|
||||
reveal: Option<&'a Pick>,
|
||||
}
|
||||
|
||||
impl<'a> TokenBrowser<'a> {
|
||||
/// A browser over `explained` that shows and edits `pick`.
|
||||
pub fn new(explained: &'a Explained, pick: Bind<'a, Option<Pick>>) -> Self {
|
||||
TokenBrowser { explained, pick: Held::new(pick), reveal: None }
|
||||
}
|
||||
|
||||
/// Shows the browser across the room offered.
|
||||
pub fn show(self, ui: &mut Ui) {
|
||||
let TokenBrowser { explained, mut pick, reveal } = self;
|
||||
Stack::new()
|
||||
.fill()
|
||||
.header(|ui, cx| {
|
||||
let filters = &mut cx.memory::<Session>().filters;
|
||||
Text::new(overview(explained)).role(TypeRole::Caption).shade(Shade::Muted).show(ui);
|
||||
TextField::search("Filter by path", Bind::bound(&mut filters.query)).placeholder("Filter by path").show(ui);
|
||||
Line::new().wrap(true).show(ui, |ui, _| {
|
||||
Checkbox::new(Bind::bound(&mut filters.pinned)).label("Pinned").show(ui);
|
||||
Checkbox::new(Bind::bound(&mut filters.moved)).label("Moved by contrast").show(ui);
|
||||
Checkbox::new(Bind::bound(&mut filters.failing)).label("Failing pairs only").show(ui);
|
||||
});
|
||||
})
|
||||
.show(ui, |ui, cx| {
|
||||
let current = pick.read(cx).flatten();
|
||||
let revealed = reveal.and_then(|pick| Row::of(pick, explained));
|
||||
let session = cx.memory::<Session>();
|
||||
if let Some(group) = revealed.and_then(|row| row.group(explained)) {
|
||||
session.open.set(&Row::Group(group), true);
|
||||
}
|
||||
let rows = TokenRows::of(explained, &session.filters, &session.open);
|
||||
let mut selection = current.as_ref().and_then(|pick| Row::of(pick, explained)).map_or_else(Selection::default, Selection::single);
|
||||
let mut list = List::<Row>::new("Tokens")
|
||||
.select(SelectMode::Single)
|
||||
.tree(true)
|
||||
.empty("No token matches the filters")
|
||||
.selection(Bind::bound(&mut selection));
|
||||
if let Some(row) = revealed.filter(|row| rows.contains(row)) {
|
||||
list = list.reveal(row);
|
||||
}
|
||||
let events = list.show_items(ui, &rows, &mut |key, _| row_of(explained, &rows, key)).events;
|
||||
let session = cx.memory::<Session>();
|
||||
let mut picked = None;
|
||||
for event in events {
|
||||
match event {
|
||||
CollectionEvent::Selection(SelectionChange::Set(keys)) => picked = keys.last().and_then(|row| row.pick(explained)),
|
||||
CollectionEvent::Activate(row) => match row.pick(explained) {
|
||||
Some(pick) => picked = Some(pick),
|
||||
None => session.open.set(&row, !rows.is_open(&row)),
|
||||
},
|
||||
CollectionEvent::Open(change) => session.open.apply(&change.key, change.open, change.all, rows.headings()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if picked.is_some() && picked != current {
|
||||
pick.write(cx, ¤t, picked, "Pick token");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// The line over the list: how many pairs the explanation measured and how many fall short.
|
||||
fn overview(explained: &Explained) -> String {
|
||||
let variant = if explained.resolved.variant_used == Mode::Dark { "dark" } else { "light" };
|
||||
let failing = explained.pairs.iter().filter(|pair| !pair.pair.passes()).count();
|
||||
format!(
|
||||
"{variant} variant: {} pairs measured, {failing} below their minimum, {} reported",
|
||||
explained.pairs.len(),
|
||||
explained.resolved.warnings.len()
|
||||
)
|
||||
}
|
||||
|
||||
/// The colour a token resolved to; a component token has none.
|
||||
pub(super) fn value_of(explained: &Explained, token: TokenRef) -> Rgba {
|
||||
match token {
|
||||
TokenRef::Color(token) => explained.resolved.tokens.color(token),
|
||||
TokenRef::Component(_) => Rgba::TRANSPARENT,
|
||||
}
|
||||
}
|
||||
|
||||
/// The list row of `key`: a heading, or a token with its colour chip and value, or a size with its value and layer.
|
||||
fn row_of(explained: &Explained, rows: &TokenRows, key: &Row) -> ListRow<'static> {
|
||||
let depth = rows.depth_of(key);
|
||||
match key {
|
||||
Row::Group(name) => ListRow::new(*name).heading().depth(depth).group(rows.is_open(key)),
|
||||
Row::Token(TokenRef::Component(field)) => {
|
||||
ListRow::new(field.path()).depth(depth).trailing(lengths_words(&explained.resolved.tokens.component, *field))
|
||||
}
|
||||
Row::Token(token) => {
|
||||
let value = value_of(explained, *token);
|
||||
ListRow::new(token.path()).depth(depth).thumb(ThumbSize::Small, chip(value)).trailing(value.to_hex())
|
||||
}
|
||||
Row::Size(at) => match explained.sizes.get(*at) {
|
||||
Some(origin) => {
|
||||
ListRow::new(origin.path.clone()).depth(depth).trailing(format!("{} · {}", value_words(origin.value), layer_words(origin.layer)))
|
||||
}
|
||||
None => ListRow::spacer(),
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
//! The specimens the theme panels draw in a row's thumbnail: a colour, and a foreground colour beside its
|
||||
//! background.
|
||||
|
||||
use craft_theme::Rgba;
|
||||
use craft_ui::primitives::ContentPainterCx;
|
||||
use egui::{Color32, Rect, pos2};
|
||||
|
||||
fn color_of(color: Rgba) -> Color32 {
|
||||
let [r, g, b, a] = color.0;
|
||||
Color32::from_rgba_unmultiplied(r, g, b, a)
|
||||
}
|
||||
|
||||
/// Fills `rect` with `color` over the transparency checker, which a translucent colour shows through.
|
||||
fn fill(cx: &ContentPainterCx, rect: Rect, color: Rgba) {
|
||||
if color.0[3] < u8::MAX {
|
||||
cx.checker(rect);
|
||||
}
|
||||
cx.painter.rect_filled(rect, 0.0, color_of(color));
|
||||
}
|
||||
|
||||
/// A thumbnail painter that fills the thumbnail with `color`, over the transparency checker where it is translucent.
|
||||
pub(crate) fn chip(color: Rgba) -> impl FnOnce(&ContentPainterCx, Rect) + 'static {
|
||||
move |cx, rect| fill(cx, rect, color)
|
||||
}
|
||||
|
||||
/// A thumbnail painter that shows `foreground` beside `background`: the background on the left half, the
|
||||
/// foreground on the right half.
|
||||
pub(crate) fn pair(foreground: Rgba, background: Rgba) -> impl FnOnce(&ContentPainterCx, Rect) + 'static {
|
||||
move |cx, rect| {
|
||||
let middle = rect.center().x;
|
||||
fill(cx, Rect::from_min_max(rect.min, pos2(middle, rect.max.y)), background);
|
||||
fill(cx, Rect::from_min_max(pos2(middle, rect.min.y), rect.max), foreground);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
//! The detail of the picked token or size: where its value comes from, the contrast pairs it takes part in and the
|
||||
//! ramp it steps through.
|
||||
|
||||
use super::browser::value_of;
|
||||
use super::chip::chip;
|
||||
use super::subject::Pick;
|
||||
use super::words::{layer_words, lengths_words, pin_words, ramp_name, value_words};
|
||||
use craft_behavior::keyed;
|
||||
use craft_theme::{ColorOrigin, ComponentField, Explained, Rgba, SizeOrigin, TokenRef};
|
||||
use craft_ui::contract::{Gap, Pattern, Props, Scroll, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing};
|
||||
use craft_ui::display::{Shade, Text};
|
||||
use craft_ui::layout_components::Stack;
|
||||
use craft_ui::list::{List, ListRow, ThumbSize};
|
||||
use craft_ui::sections::Section;
|
||||
use craft_ui::style::TypeRole;
|
||||
use egui::{Response, Ui};
|
||||
|
||||
/// One line of a facts list: a name, a value, an optional colour chip and an optional note under the name.
|
||||
struct Fact {
|
||||
id: usize,
|
||||
name: String,
|
||||
value: String,
|
||||
color: Option<Rgba>,
|
||||
note: Option<String>,
|
||||
}
|
||||
|
||||
/// The lines of one facts list.
|
||||
#[derive(Default)]
|
||||
struct Facts(Vec<Fact>);
|
||||
|
||||
impl Facts {
|
||||
fn push(&mut self, name: impl Into<String>, value: impl Into<String>) -> &mut Fact {
|
||||
let id = self.0.len();
|
||||
self.0.push(Fact { id, name: name.into(), value: value.into(), color: None, note: None });
|
||||
&mut self.0[id]
|
||||
}
|
||||
|
||||
/// Shows the lines as a read-only list named `label`.
|
||||
fn show(&self, ui: &mut Ui, label: &'static str) {
|
||||
let source = keyed(&self.0, |fact| fact.id);
|
||||
List::<usize>::new(label).select(SelectMode::None).sizing(Sizing::Content).show_items(ui, &source, &mut |key, _| {
|
||||
let Some(fact) = self.0.get(*key) else { return ListRow::spacer() };
|
||||
let mut row = ListRow::new(fact.name.clone()).trailing(fact.value.clone());
|
||||
if let Some(color) = fact.color {
|
||||
row = row.thumb(ThumbSize::Small, chip(color));
|
||||
}
|
||||
match &fact.note {
|
||||
Some(note) => row.detail(note.clone()),
|
||||
None => row,
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// The facts about the picked row of an explanation: for a colour its value, source and pin, the pairs it takes part
|
||||
/// in and its ramp; for a component token or a size its values and where they are set.
|
||||
#[derive(Pattern, Props)]
|
||||
pub struct TokenDetail<'a> {
|
||||
explained: &'a Explained,
|
||||
/// The row to describe; without one the detail says to select a row.
|
||||
#[prop]
|
||||
pick: Option<&'a Pick>,
|
||||
}
|
||||
|
||||
impl<'a> TokenDetail<'a> {
|
||||
/// A detail over `explained`.
|
||||
pub fn new(explained: &'a Explained) -> Self {
|
||||
TokenDetail { explained, pick: None }
|
||||
}
|
||||
|
||||
/// Shows the detail across the room offered, scrolling.
|
||||
pub fn show(self, ui: &mut Ui) -> Response {
|
||||
let TokenDetail { explained, pick } = self;
|
||||
Stack::new()
|
||||
.fill()
|
||||
.scroll(Scroll::vertical())
|
||||
.gap(Gap::Section)
|
||||
.show(ui, |ui, _| match pick {
|
||||
None => {
|
||||
Text::new("Select a row to see its facts, contrast pairs and ramp.").shade(Shade::Muted).show(ui);
|
||||
}
|
||||
Some(Pick::Size(path)) => match explained.sizes.iter().find(|origin| origin.path == *path) {
|
||||
Some(origin) => size(ui, origin),
|
||||
None => {
|
||||
Text::new("This size is not in the explanation.").shade(Shade::Muted).show(ui);
|
||||
}
|
||||
},
|
||||
Some(Pick::Token(TokenRef::Component(field))) => component(ui, explained, *field),
|
||||
Some(Pick::Token(TokenRef::Color(token))) => match explained.color(*token) {
|
||||
Some(origin) => color(ui, explained, TokenRef::Color(*token), origin),
|
||||
None => {
|
||||
Text::new("This colour is not in the explanation.").shade(Shade::Muted).show(ui);
|
||||
}
|
||||
},
|
||||
})
|
||||
.output
|
||||
}
|
||||
}
|
||||
|
||||
fn heading(ui: &mut Ui, text: String) {
|
||||
Text::new(text).role(TypeRole::Heading).show(ui);
|
||||
}
|
||||
|
||||
fn size(ui: &mut Ui, origin: &SizeOrigin) {
|
||||
heading(ui, origin.path.clone());
|
||||
let mut facts = Facts::default();
|
||||
facts.push("Value", value_words(origin.value));
|
||||
facts.push("Set by", layer_words(origin.layer));
|
||||
facts.push("Range", format!("{} to {}", origin.range.0, origin.range.1));
|
||||
facts.show(ui, "Size facts");
|
||||
}
|
||||
|
||||
fn component(ui: &mut Ui, explained: &Explained, field: ComponentField) {
|
||||
heading(ui, field.path());
|
||||
let mut facts = Facts::default();
|
||||
facts.push("Standard / small", lengths_words(&explained.resolved.tokens.component, field));
|
||||
facts.push("Set in", "the theme file's components map");
|
||||
facts.show(ui, "Component token facts");
|
||||
}
|
||||
|
||||
fn color(ui: &mut Ui, explained: &Explained, token: TokenRef, origin: &ColorOrigin) {
|
||||
heading(ui, token.path());
|
||||
Section::fixed("Value").show(ui, |ui, _| {
|
||||
let mut facts = Facts::default();
|
||||
let value = facts.push("Value", origin.value.to_hex());
|
||||
value.color = Some(origin.value);
|
||||
facts.push("Source", origin.source_words());
|
||||
let derived = facts.push("Derived", origin.derived.to_hex());
|
||||
derived.color = Some(origin.derived);
|
||||
facts.push("Pin", origin.pin.map_or("none", pin_words));
|
||||
if let Some(before) = origin.contrast_move {
|
||||
let moved = facts.push("Before the contrast pass", before.to_hex());
|
||||
moved.color = Some(before);
|
||||
}
|
||||
facts.show(ui, "Colour facts");
|
||||
});
|
||||
Section::fixed("Contrast pairs").show(ui, |ui, _| pairs(ui, explained, token));
|
||||
if let Some((shared, step, toward)) = explained.ramps.steps_of(origin.source) {
|
||||
// An anchored token's steps are the ramp moved to its anchor.
|
||||
let (title, steps) = match &origin.anchoring {
|
||||
Some(anchor) => (format!("Ramp (neutral, anchored on {})", anchor.on.path()), anchor.steps.0),
|
||||
None => (format!("Ramp ({})", ramp_name(origin.source)), shared.0),
|
||||
};
|
||||
Section::fixed(title).show(ui, |ui, _| ramp(ui, &steps, step, toward));
|
||||
}
|
||||
}
|
||||
|
||||
/// Every pair `token` takes part in: the other colour's chip and path, the ratio against the minimum and the result in
|
||||
/// words.
|
||||
fn pairs(ui: &mut Ui, explained: &Explained, token: TokenRef) {
|
||||
let mut facts = Facts::default();
|
||||
for report in explained.pairs_of(token) {
|
||||
let pair = &report.pair;
|
||||
let (other, role) = if pair.fg == token { (pair.bg, "on") } else { (pair.fg, "under") };
|
||||
let result = if pair.passes() { "pass" } else { "FAIL" };
|
||||
let line = facts.push(format!("{role} {}", other.path()), format!("{:.2} of {:.1} {result}", pair.ratio, pair.minimum));
|
||||
line.color = Some(value_of(explained, other));
|
||||
if report.fixed_by_pass {
|
||||
line.note = Some(format!("fixed by pass (was {:.2})", report.ratio_before));
|
||||
} else if report.moved_by_pass {
|
||||
line.note = Some(format!("moved (was {:.2})", report.ratio_before));
|
||||
}
|
||||
}
|
||||
if facts.0.is_empty() {
|
||||
Text::new("No contrast rule measures this colour.").shade(Shade::Muted).show(ui);
|
||||
} else {
|
||||
facts.show(ui, "Contrast pairs");
|
||||
}
|
||||
}
|
||||
|
||||
/// The twelve steps of a ramp, the used one and the one a mix moves toward marked.
|
||||
fn ramp(ui: &mut Ui, steps: &[Rgba; 12], used: usize, toward: Option<usize>) {
|
||||
let mut facts = Facts::default();
|
||||
for (at, color) in steps.iter().enumerate() {
|
||||
let number = at + 1;
|
||||
let mark = if number == used {
|
||||
" (used)"
|
||||
} else if toward == Some(number) {
|
||||
" (moves toward)"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let line = facts.push(format!("step {number}{mark}"), color.to_hex());
|
||||
line.color = Some(*color);
|
||||
}
|
||||
facts.show(ui, "Ramp");
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
//! The app layer editor: the base overrides and component pins of an app's `sizes.json`, edited from the size rows of
|
||||
//! the browser and applied to every theme the gallery shows.
|
||||
//!
|
||||
//! The file moves as text: it is loaded by pasting it into the field and exported by writing it to the field.
|
||||
|
||||
use super::subject::Pick;
|
||||
use craft_theme::variant::Tone;
|
||||
use craft_theme::{AppSizes, Explained, SizeMap, SizeOrigin, SizeValue};
|
||||
use craft_ui::buttons::Button;
|
||||
use craft_ui::choice::Segmented;
|
||||
use craft_ui::contract::{Bind, Entry, Gap, Held, Pattern, Props, Scroll, Show as _, ShowContainer as _, clicked};
|
||||
use craft_ui::display::Text;
|
||||
use craft_ui::layout_components::{Row, Stack};
|
||||
use craft_ui::notices::Notice;
|
||||
use craft_ui::runtime::memory::Remember as _;
|
||||
use craft_ui::sections::Section;
|
||||
use craft_ui::text::{NumberField, TextField};
|
||||
use egui::Ui;
|
||||
|
||||
/// The rows of the JSON field.
|
||||
const TEXT_ROWS: usize = 10;
|
||||
|
||||
/// The part of `sizes.json` an edit goes to.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
enum Part {
|
||||
#[default]
|
||||
All,
|
||||
Compact,
|
||||
Comfortable,
|
||||
}
|
||||
|
||||
/// What the editor keeps between passes: the part edited, the text of the file and what the last action reported.
|
||||
#[derive(Clone, Default)]
|
||||
struct Session {
|
||||
part: Part,
|
||||
text: String,
|
||||
/// The outcome of the last load or export, and whether it is an error.
|
||||
status: Option<(String, bool)>,
|
||||
}
|
||||
|
||||
/// Parses the file `bytes` named `name` as an app's `sizes.json`; the error names `name` and the offending paths.
|
||||
pub fn parse_sizes(name: &str, bytes: &[u8]) -> Result<AppSizes, String> {
|
||||
AppSizes::parse(bytes).map_err(|errors| format!("{name}: {errors}"))
|
||||
}
|
||||
|
||||
fn part_map(sizes: &AppSizes, part: Part) -> &SizeMap {
|
||||
match part {
|
||||
Part::All => &sizes.all,
|
||||
Part::Compact => &sizes.compact,
|
||||
Part::Comfortable => &sizes.comfortable,
|
||||
}
|
||||
}
|
||||
|
||||
fn part_map_mut(sizes: &mut AppSizes, part: Part) -> &mut SizeMap {
|
||||
match part {
|
||||
Part::All => &mut sizes.all,
|
||||
Part::Compact => &mut sizes.compact,
|
||||
Part::Comfortable => &mut sizes.comfortable,
|
||||
}
|
||||
}
|
||||
|
||||
fn number(value: SizeValue) -> f32 {
|
||||
match value {
|
||||
SizeValue::Number(n) => n,
|
||||
}
|
||||
}
|
||||
|
||||
/// The app's size overrides as an editor: for a picked size, its override in the chosen part of the file; always the
|
||||
/// file's text with Load, Export and Clear. Edits write to the bound layer.
|
||||
#[derive(Pattern, Props)]
|
||||
pub struct AppLayerEditor<'a> {
|
||||
sizes: Held<'a, AppSizes>,
|
||||
explained: &'a Explained,
|
||||
/// The row the host has picked; a size row shows its override editor.
|
||||
#[prop]
|
||||
pick: Option<&'a Pick>,
|
||||
}
|
||||
|
||||
impl<'a> AppLayerEditor<'a> {
|
||||
/// An editor over the layer `sizes`, with the sizes of `explained` to pick from.
|
||||
pub fn new(sizes: Bind<'a, AppSizes>, explained: &'a Explained) -> Self {
|
||||
AppLayerEditor { sizes: Held::new(sizes), explained, pick: None }
|
||||
}
|
||||
|
||||
/// Shows the editor across the room offered, scrolling. True when an edit wrote the layer this pass.
|
||||
pub fn show(self, ui: &mut Ui) -> bool {
|
||||
let AppLayerEditor { mut sizes, explained, pick } = self;
|
||||
let size = match pick {
|
||||
Some(Pick::Size(path)) => explained.sizes.iter().find(|origin| origin.path == *path),
|
||||
_ => None,
|
||||
};
|
||||
let mut edited = false;
|
||||
Stack::new().fill().scroll(Scroll::vertical()).gap(Gap::Section).show(ui, |ui, cx| {
|
||||
let Some(before) = sizes.read(cx) else { return };
|
||||
let mut layer = before.clone();
|
||||
let mut session = cx.memory::<Session>().clone();
|
||||
if let Some(origin) = size {
|
||||
override_section(ui, origin, &mut session, &mut layer);
|
||||
}
|
||||
file_section(ui, &mut session, &mut layer);
|
||||
*cx.memory::<Session>() = session;
|
||||
if layer != before {
|
||||
sizes.write(cx, &before, layer, "Edit app sizes");
|
||||
edited = true;
|
||||
}
|
||||
});
|
||||
edited
|
||||
}
|
||||
}
|
||||
|
||||
/// The value of the picked size in the chosen part of the file, and the control to remove it.
|
||||
fn override_section(ui: &mut Ui, origin: &SizeOrigin, session: &mut Session, layer: &mut AppSizes) {
|
||||
Section::fixed(format!("Override {}", origin.path)).show(ui, |ui, _| {
|
||||
let parts = [Entry::new(Part::All, "All"), Entry::new(Part::Compact, "Compact"), Entry::new(Part::Comfortable, "Comfortable")];
|
||||
Segmented::new("Part of sizes.json", Bind::bound(&mut session.part), &parts).show(ui);
|
||||
let set = part_map(layer, session.part).get(&origin.path).copied();
|
||||
let before = Some(f64::from(number(set.unwrap_or(origin.value))));
|
||||
let mut value = before;
|
||||
NumberField::new("Override", Bind::bound(&mut value)).range(f64::from(origin.range.0)..=f64::from(origin.range.1)).show(ui);
|
||||
if value != before
|
||||
&& let Some(edited) = value
|
||||
{
|
||||
part_map_mut(layer, session.part).insert(origin.path.clone(), SizeValue::Number(edited as f32));
|
||||
}
|
||||
if clicked(&Button::new("Remove override").enabled(set.is_some()).show(ui)) {
|
||||
part_map_mut(layer, session.part).remove(&origin.path);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// The file's text, the buttons that move it in and out of the layer and the outcome of the last one.
|
||||
fn file_section(ui: &mut Ui, session: &mut Session, layer: &mut AppSizes) {
|
||||
Section::fixed("sizes.json").show(ui, |ui, _| {
|
||||
let counts = (layer.all.len(), layer.compact.len(), layer.comfortable.len());
|
||||
Text::new(format!("{} overrides: {} for all, {} Compact, {} Comfortable", counts.0 + counts.1 + counts.2, counts.0, counts.1, counts.2))
|
||||
.show(ui);
|
||||
TextField::new("sizes.json", Bind::bound(&mut session.text)).placeholder("Paste an app's sizes.json").lines(TEXT_ROWS).show(ui);
|
||||
Row::new().wrap(true).show(ui, |ui, _| {
|
||||
if clicked(&Button::new("Load").show(ui)) {
|
||||
match parse_sizes("sizes.json", session.text.as_bytes()) {
|
||||
Ok(loaded) => {
|
||||
*layer = loaded;
|
||||
session.status = Some(("Loaded sizes.json".to_owned(), false));
|
||||
}
|
||||
Err(message) => session.status = Some((message, true)),
|
||||
}
|
||||
}
|
||||
if clicked(&Button::new("Export").show(ui)) {
|
||||
session.text = layer.to_json();
|
||||
session.status = Some(match parse_sizes("sizes.json", session.text.as_bytes()) {
|
||||
Ok(_) => ("Wrote sizes.json to the field; copy it from there".to_owned(), false),
|
||||
Err(errors) => (format!("sizes.json would not load: {errors}"), true),
|
||||
});
|
||||
}
|
||||
if clicked(&Button::new("Clear").enabled(!layer.is_empty()).show(ui)) {
|
||||
*layer = AppSizes::default();
|
||||
session.text.clear();
|
||||
session.status = None;
|
||||
}
|
||||
});
|
||||
if let Some((message, error)) = &session.status {
|
||||
Notice::new(if *error { Tone::Bad } else { Tone::Good }, message.clone()).show(ui);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
//! The theme workspace: the panels that explain a theme and its appearance. The host holds one [`ThemeWorkspace`],
|
||||
//! refreshes it for the theme on show and passes what it holds to the panels. The panels edit the workspace's pick
|
||||
//! and app sizes through bindings, and the Problems view reports the pick it makes.
|
||||
|
||||
mod browser;
|
||||
mod chip;
|
||||
mod detail;
|
||||
mod layer;
|
||||
mod problems;
|
||||
mod rows;
|
||||
mod stories;
|
||||
mod subject;
|
||||
mod words;
|
||||
|
||||
pub use browser::TokenBrowser;
|
||||
pub use detail::TokenDetail;
|
||||
pub use layer::{AppLayerEditor, parse_sizes};
|
||||
pub use problems::{Problems, ProblemsOutput};
|
||||
pub use rows::Row;
|
||||
pub use subject::{Pick, ThemeSubject, ThemeWorkspace};
|
||||
pub use words::summary;
|
||||
@@ -0,0 +1,123 @@
|
||||
//! The Problems view: the contrast pairs the subject theme falls short on.
|
||||
//!
|
||||
//! The sweep ([`craft_theme::report::contrast_report`]) resolves the theme for every mode, contrast and size.
|
||||
//! Standard contrast reports pairs as warnings (below their minimum); High contrast must meet every minimum, so its
|
||||
//! pairs are errors.
|
||||
|
||||
use super::browser::value_of;
|
||||
use super::chip::pair;
|
||||
use super::subject::{Pick, ThemeSubject};
|
||||
use super::words::summary;
|
||||
use craft_behavior::{Selection, SelectionChange};
|
||||
use craft_theme::report::ContrastReport;
|
||||
use craft_theme::{Appearance, Contrast, ContrastCheck, Explained, Mode, TokenRef, Variants};
|
||||
use craft_ui::contract::{Bind, CollectionEvent, Pattern, Show as _, ShowCollection as _, ShowContainer as _, WordSetCx as _};
|
||||
use craft_ui::display::{Shade, Text};
|
||||
use craft_ui::layout_components::Stack;
|
||||
use craft_ui::list::{Finding, Findings, FindingsList, FindingsSummary, FindingsWords, Severity, ThumbSize};
|
||||
use craft_ui::runtime::memory::Remember as _;
|
||||
use craft_ui::style::TypeRole;
|
||||
use egui::Ui;
|
||||
|
||||
/// The row selected, by its pair so that it survives a new report.
|
||||
#[derive(Clone, Default)]
|
||||
struct Session {
|
||||
selected: Option<(TokenRef, TokenRef)>,
|
||||
}
|
||||
|
||||
/// What the Problems view reports: the foreground token of the pair the user selected or activated in this pass.
|
||||
#[derive(Debug, Default)]
|
||||
#[non_exhaustive]
|
||||
pub struct ProblemsOutput {
|
||||
/// The token to show in the browser.
|
||||
pub picked: Option<Pick>,
|
||||
}
|
||||
|
||||
/// The pairs below their minimum in the shown appearance, with a count line per mode of the theme and the list of
|
||||
/// pairs. Selecting or activating a pair reports its foreground token.
|
||||
#[derive(Pattern)]
|
||||
pub struct Problems<'a> {
|
||||
report: &'a ContrastReport,
|
||||
explained: &'a Explained,
|
||||
variants: Variants,
|
||||
appearance: Appearance,
|
||||
}
|
||||
|
||||
impl<'a> Problems<'a> {
|
||||
/// The problems of `subject` in `report`, with the colours of `explained`.
|
||||
pub fn new(report: &'a ContrastReport, explained: &'a Explained, subject: &ThemeSubject<'_>) -> Self {
|
||||
Problems { report, explained, variants: subject.theme.variants, appearance: subject.appearance }
|
||||
}
|
||||
|
||||
/// The warnings of the shown mode, contrast and size.
|
||||
fn warnings(&self) -> &'a [ContrastCheck] {
|
||||
warnings_of(self.report, self.appearance.mode, self.appearance)
|
||||
}
|
||||
|
||||
/// Shows the view across the room offered.
|
||||
pub fn show(self, ui: &mut Ui) -> ProblemsOutput {
|
||||
let mut out = ProblemsOutput::default();
|
||||
let warnings = self.warnings();
|
||||
let severity = if self.appearance.contrast == Contrast::High { Severity::Error } else { Severity::Warning };
|
||||
let findings: Vec<Finding> = warnings
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(at, check)| {
|
||||
Finding::new(at as u64, severity, format!("{} on {}", check.fg.path(), check.bg.path()))
|
||||
.detail(format!("{:.1} of {:.1}", check.ratio, check.minimum))
|
||||
})
|
||||
.collect();
|
||||
Stack::new()
|
||||
.fill()
|
||||
.header(|ui, _| {
|
||||
for &mode in modes(self.variants) {
|
||||
let count = warnings_of(self.report, mode, self.appearance).len();
|
||||
Text::new(summary(mode, self.appearance.contrast, count)).role(TypeRole::Caption).shade(Shade::Muted).show(ui);
|
||||
}
|
||||
FindingsSummary::new(&findings).show(ui);
|
||||
})
|
||||
.show(ui, |ui, cx| {
|
||||
let session = cx.memory::<Session>();
|
||||
let at = session.selected.and_then(|chosen| warnings.iter().position(|check| (check.fg, check.bg) == chosen));
|
||||
let mut selection = at.map_or_else(Selection::default, |at| Selection::single(at as u64));
|
||||
let source = Findings::new(&findings);
|
||||
let events = FindingsList::new("Contrast problems")
|
||||
.selection(Bind::bound(&mut selection))
|
||||
.show_items(ui, &source, &mut |key, icx| {
|
||||
let at = *key as usize;
|
||||
let row = findings[at].row(&icx.words::<FindingsWords>());
|
||||
match warnings.get(at) {
|
||||
Some(check) => row.thumb(ThumbSize::Small, pair(value_of(self.explained, check.fg), value_of(self.explained, check.bg))),
|
||||
None => row,
|
||||
}
|
||||
})
|
||||
.events;
|
||||
for event in events {
|
||||
let key = match event {
|
||||
CollectionEvent::Selection(SelectionChange::Set(keys)) => keys.last().copied(),
|
||||
CollectionEvent::Activate(key) => Some(key),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(check) = key.and_then(|key| warnings.get(key as usize)) {
|
||||
cx.memory::<Session>().selected = Some((check.fg, check.bg));
|
||||
out.picked = Some(Pick::Token(check.fg));
|
||||
}
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The warnings of `report` for `mode` at the contrast and size of `appearance`.
|
||||
fn warnings_of(report: &ContrastReport, mode: Mode, appearance: Appearance) -> &[ContrastCheck] {
|
||||
report.for_appearance(None, mode, appearance.contrast, appearance.size).map_or(&[], |found| found.warnings.as_slice())
|
||||
}
|
||||
|
||||
/// The modes a theme has.
|
||||
fn modes(variants: Variants) -> &'static [Mode] {
|
||||
match variants {
|
||||
Variants::Both => &[Mode::Light, Mode::Dark],
|
||||
Variants::LightOnly => &[Mode::Light],
|
||||
Variants::DarkOnly => &[Mode::Dark],
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
//! The rows of the token browser: group headings with the tokens, component tokens and sizes under them, and the
|
||||
//! filters that keep some of them.
|
||||
|
||||
use super::subject::Pick;
|
||||
use super::words::{COMPONENT_GROUP, group_of, size_group};
|
||||
use craft_behavior::{DisplayOrder, ItemSource};
|
||||
use craft_theme::{ComponentField, Explained, SizeOrigin, TokenRef};
|
||||
use craft_ui::list::OpenSet;
|
||||
use std::borrow::Cow;
|
||||
|
||||
/// A row of the token list: a group's heading, or a token or size under it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
pub enum Row {
|
||||
/// A group heading.
|
||||
Group(&'static str),
|
||||
/// A colour or component token.
|
||||
Token(TokenRef),
|
||||
/// An index into [`Explained::sizes`].
|
||||
Size(usize),
|
||||
}
|
||||
|
||||
impl Row {
|
||||
/// The row a pick selects, when the explanation lists it.
|
||||
pub(crate) fn of(pick: &Pick, explained: &Explained) -> Option<Row> {
|
||||
match pick {
|
||||
Pick::Token(token) => Some(Row::Token(*token)),
|
||||
Pick::Size(path) => explained.sizes.iter().position(|origin| origin.path == *path).map(Row::Size),
|
||||
}
|
||||
}
|
||||
|
||||
/// The pick selecting the row makes; a group heading picks nothing.
|
||||
pub(crate) fn pick(self, explained: &Explained) -> Option<Pick> {
|
||||
match self {
|
||||
Row::Group(_) => None,
|
||||
Row::Token(token) => Some(Pick::Token(token)),
|
||||
Row::Size(at) => explained.sizes.get(at).map(|origin| Pick::Size(origin.path.clone())),
|
||||
}
|
||||
}
|
||||
|
||||
/// The heading the row is listed under.
|
||||
pub(crate) fn group(self, explained: &Explained) -> Option<&'static str> {
|
||||
match self {
|
||||
Row::Group(_) => None,
|
||||
Row::Token(TokenRef::Color(token)) => Some(group_of(token)),
|
||||
Row::Token(TokenRef::Component(_)) => Some(COMPONENT_GROUP),
|
||||
Row::Size(at) => explained.sizes.get(at).map(size_group),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the browser's filters keep.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub(crate) struct Filters {
|
||||
pub(crate) query: String,
|
||||
pub(crate) pinned: bool,
|
||||
pub(crate) moved: bool,
|
||||
pub(crate) failing: bool,
|
||||
}
|
||||
|
||||
impl Filters {
|
||||
/// Whether any filter narrows the list.
|
||||
pub(crate) fn active(&self) -> bool {
|
||||
!self.query.is_empty() || self.pinned || self.moved || self.failing
|
||||
}
|
||||
|
||||
fn matches_path(&self, path: &str) -> bool {
|
||||
self.query.is_empty() || path.contains(&self.query.to_lowercase())
|
||||
}
|
||||
|
||||
/// Whether a colour or component token passes.
|
||||
fn keeps_token(&self, explained: &Explained, token: TokenRef, pinned: bool, moved: bool) -> bool {
|
||||
self.matches_path(&token.path())
|
||||
&& (!self.pinned || pinned)
|
||||
&& (!self.moved || moved)
|
||||
&& (!self.failing || explained.pairs_of(token).any(|pair| !pair.pair.passes()))
|
||||
}
|
||||
|
||||
/// Whether a size passes. Contrast filters hide sizes, which have no colour.
|
||||
fn keeps_size(&self, origin: &SizeOrigin) -> bool {
|
||||
self.matches_path(&origin.path) && (!self.pinned || origin.layer.from_app()) && !self.moved && !self.failing
|
||||
}
|
||||
}
|
||||
|
||||
struct Entry {
|
||||
row: Row,
|
||||
depth: usize,
|
||||
open: bool,
|
||||
text: String,
|
||||
}
|
||||
|
||||
/// The visible rows of the list in display order, as a collection source.
|
||||
pub(crate) struct TokenRows {
|
||||
entries: Vec<Entry>,
|
||||
}
|
||||
|
||||
impl TokenRows {
|
||||
/// The rows `filters` keep, grouped. A group shows its children when it is open or a filter is on.
|
||||
pub(crate) fn of(explained: &Explained, filters: &Filters, open: &OpenSet<Row>) -> Self {
|
||||
let mut groups: Vec<(&'static str, Vec<Row>)> = Vec::new();
|
||||
let mut add = |group: &'static str, row: Row| {
|
||||
if !groups.last().is_some_and(|(name, _)| *name == group) {
|
||||
groups.push((group, Vec::new()));
|
||||
}
|
||||
if let Some((_, rows)) = groups.last_mut() {
|
||||
rows.push(row);
|
||||
}
|
||||
};
|
||||
for origin in &explained.colors {
|
||||
let token = TokenRef::Color(origin.token);
|
||||
if filters.keeps_token(explained, token, origin.pin.is_some(), origin.contrast_move.is_some()) {
|
||||
add(group_of(origin.token), Row::Token(token));
|
||||
}
|
||||
}
|
||||
for field in ComponentField::ALL {
|
||||
let token = TokenRef::Component(*field);
|
||||
if filters.keeps_token(explained, token, false, false) {
|
||||
add(COMPONENT_GROUP, Row::Token(token));
|
||||
}
|
||||
}
|
||||
for (at, origin) in explained.sizes.iter().enumerate() {
|
||||
if filters.keeps_size(origin) {
|
||||
add(size_group(origin), Row::Size(at));
|
||||
}
|
||||
}
|
||||
let mut entries = Vec::new();
|
||||
for (name, rows) in groups {
|
||||
let heading = Row::Group(name);
|
||||
let shown = filters.active() || open.is_open(&heading);
|
||||
entries.push(Entry { row: heading, depth: 0, open: shown, text: name.to_owned() });
|
||||
if shown {
|
||||
entries.extend(rows.into_iter().map(|row| Entry { row, depth: 1, open: false, text: text_of(explained, row) }));
|
||||
}
|
||||
}
|
||||
TokenRows { entries }
|
||||
}
|
||||
|
||||
/// The entry of `row`.
|
||||
fn entry(&self, row: &Row) -> Option<&Entry> {
|
||||
self.entries.iter().find(|entry| entry.row == *row)
|
||||
}
|
||||
|
||||
/// The depth of `row` in the list.
|
||||
pub(crate) fn depth_of(&self, row: &Row) -> usize {
|
||||
self.entry(row).map_or(0, |entry| entry.depth)
|
||||
}
|
||||
|
||||
/// Whether the group heading `row` is shown open.
|
||||
pub(crate) fn is_open(&self, row: &Row) -> bool {
|
||||
self.entry(row).is_some_and(|entry| entry.open)
|
||||
}
|
||||
|
||||
/// Whether the list shows `row`.
|
||||
pub(crate) fn contains(&self, row: &Row) -> bool {
|
||||
self.entry(row).is_some()
|
||||
}
|
||||
|
||||
/// Every group heading shown, for an Alt-click that opens or closes them all.
|
||||
pub(crate) fn headings(&self) -> impl Iterator<Item = &Row> {
|
||||
self.entries.iter().filter(|entry| entry.depth == 0).map(|entry| &entry.row)
|
||||
}
|
||||
}
|
||||
|
||||
fn text_of(explained: &Explained, row: Row) -> String {
|
||||
match row {
|
||||
Row::Group(name) => name.to_owned(),
|
||||
Row::Token(token) => token.path(),
|
||||
Row::Size(at) => explained.sizes.get(at).map(|origin| origin.path.clone()).unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
|
||||
impl DisplayOrder<Row> for TokenRows {
|
||||
fn len(&self) -> usize {
|
||||
self.entries.len()
|
||||
}
|
||||
|
||||
fn key(&self, at: usize) -> Row {
|
||||
self.entries[at].row
|
||||
}
|
||||
|
||||
fn depth(&self, at: usize) -> usize {
|
||||
self.entries[at].depth
|
||||
}
|
||||
|
||||
fn has_children(&self, at: usize) -> bool {
|
||||
matches!(self.entries[at].row, Row::Group(_))
|
||||
}
|
||||
|
||||
fn open(&self, at: usize) -> bool {
|
||||
self.entries[at].open
|
||||
}
|
||||
|
||||
fn text(&self, at: usize) -> Option<Cow<'_, str>> {
|
||||
Some(Cow::Borrowed(self.entries[at].text.as_str()))
|
||||
}
|
||||
}
|
||||
|
||||
impl ItemSource<Row> for TokenRows {}
|
||||
@@ -0,0 +1,63 @@
|
||||
//! Stories of the theme panels, over the first built-in theme.
|
||||
|
||||
use super::{AppLayerEditor, Pick, Problems, ThemeSubject, ThemeWorkspace, TokenBrowser, TokenDetail};
|
||||
use craft_theme::report::ContrastReport;
|
||||
use craft_theme::{AppSizes, Appearance, Contrast, Explained, Mode, Size, TextSize, builtins};
|
||||
use craft_ui::contract::Bind;
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use egui::Ui;
|
||||
use std::sync::LazyLock;
|
||||
|
||||
fn appearance() -> Appearance {
|
||||
Appearance { mode: Mode::Light, contrast: Contrast::Standard, size: Size::Compact, text_size: TextSize::Small, reduced_motion: false }
|
||||
}
|
||||
|
||||
/// The explanation and contrast report of the first built-in theme; a built-in theme always explains.
|
||||
fn explained() -> (&'static Explained, &'static ContrastReport) {
|
||||
static WORKSPACE: LazyLock<ThemeWorkspace> = LazyLock::new(|| {
|
||||
let mut workspace = ThemeWorkspace::new();
|
||||
workspace.refresh(&ThemeSubject::new(&builtins()[0], appearance()));
|
||||
workspace
|
||||
});
|
||||
let explained = WORKSPACE.explained().expect("a built-in theme explains");
|
||||
(explained, WORKSPACE.report().expect("a built-in theme has a contrast report"))
|
||||
}
|
||||
|
||||
#[story(TokenBrowser<'static>, covers = [])]
|
||||
fn token_browser(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
TokenBrowser::new(explained().0, Bind::bound(data.value("pick", None::<Pick>))).show(ui);
|
||||
StoryOutput::default()
|
||||
}
|
||||
|
||||
// A read-only view of the pick: nothing in it takes input.
|
||||
#[story(TokenDetail<'static>, covers = [], drive = Drive::Never)]
|
||||
fn token_detail(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
TokenDetail::new(explained().0).show(ui);
|
||||
StoryOutput::default()
|
||||
}
|
||||
|
||||
// A click on a pair reports its token; the story keeps the pick, as the host does.
|
||||
#[story(Problems<'static>, covers = [], drive = Drive::Activate)]
|
||||
fn problems(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let (explained, report) = explained();
|
||||
if let Some(pick) = Problems::new(report, explained, &ThemeSubject::new(&builtins()[0], appearance())).show(ui).picked {
|
||||
*data.value("pick", None::<Pick>) = Some(pick);
|
||||
}
|
||||
StoryOutput::default()
|
||||
}
|
||||
|
||||
/// The size the host has picked in the browser: its override editor shows only for a picked size.
|
||||
fn picked_size() -> &'static Pick {
|
||||
static PICK: LazyLock<Pick> = LazyLock::new(|| {
|
||||
let first = explained().0.sizes.first().expect("a built-in theme has sizes");
|
||||
Pick::Size(first.path.clone())
|
||||
});
|
||||
&PICK
|
||||
}
|
||||
|
||||
// The first size is picked, so the override editor and its controls show.
|
||||
#[story(AppLayerEditor<'static>, covers = [], drive = Drive::Activate)]
|
||||
fn app_layer_editor(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
AppLayerEditor::new(Bind::bound(data.value("sizes", AppSizes::default())), explained().0).pick(picked_size()).show(ui);
|
||||
StoryOutput::default()
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
//! The theme under inspection, what the user picked in the panels, and the caches of the two sweeps.
|
||||
|
||||
use craft_theme::report::{ContrastReport, contrast_report};
|
||||
use craft_theme::{AppId, AppSizes, Appearance, Explained, ThemeDef, ThemeId, TokenRef, explain_sized};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The theme and appearance the panels explain, and the app whose pins apply.
|
||||
#[derive(Clone)]
|
||||
pub struct ThemeSubject<'a> {
|
||||
pub(crate) theme: &'a ThemeDef,
|
||||
pub(crate) appearance: Appearance,
|
||||
pub(crate) app: Option<&'a AppId>,
|
||||
}
|
||||
|
||||
impl<'a> ThemeSubject<'a> {
|
||||
/// The subject `theme` shows in `appearance`, with no app pins.
|
||||
pub fn new(theme: &'a ThemeDef, appearance: Appearance) -> Self {
|
||||
ThemeSubject { theme, appearance, app: None }
|
||||
}
|
||||
|
||||
/// The pins of `app` apply.
|
||||
#[must_use]
|
||||
pub fn app(mut self, app: &'a AppId) -> Self {
|
||||
self.app = Some(app);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// A row the user picked in the browser, the Problems view or the detail: a colour or component token, or a size
|
||||
/// by its path.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
pub enum Pick {
|
||||
/// A colour or component token.
|
||||
Token(TokenRef),
|
||||
/// A size, by its path such as `size.control.md`.
|
||||
Size(String),
|
||||
}
|
||||
|
||||
/// The inputs of the last explanation, as the theme's id, the appearance, the app and the revision of the app layer,
|
||||
/// and the explanation.
|
||||
type Explanation = (ThemeId, Appearance, Option<AppId>, u64, Arc<Explained>);
|
||||
|
||||
/// What the theme panels share: the app layer, the picked row, and the explanation and contrast report of the
|
||||
/// subject, computed again only when the subject's theme, appearance or app changes or the app layer is edited.
|
||||
#[derive(Default)]
|
||||
#[non_exhaustive]
|
||||
pub struct ThemeWorkspace {
|
||||
explanation: Option<Explanation>,
|
||||
report: Option<(ThemeId, Arc<ContrastReport>)>,
|
||||
/// The row picked in the browser, the Problems view or the detail.
|
||||
pub pick: Option<Pick>,
|
||||
sizes: AppSizes,
|
||||
/// Counts the edits of `sizes`: the explanation is current while it has not moved.
|
||||
sizes_revision: u64,
|
||||
}
|
||||
|
||||
impl ThemeWorkspace {
|
||||
/// A workspace with an empty app layer and nothing picked.
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// The app's size overrides: the sizes the gallery resolves with.
|
||||
pub fn sizes(&self) -> &AppSizes {
|
||||
&self.sizes
|
||||
}
|
||||
|
||||
/// Counts the edits of the app's size overrides.
|
||||
pub fn sizes_revision(&self) -> u64 {
|
||||
self.sizes_revision
|
||||
}
|
||||
|
||||
/// Runs `edit` over the app's size overrides. It returns whether it changed them; a change makes the next
|
||||
/// `refresh` explain the subject again.
|
||||
pub fn edit_sizes(&mut self, edit: impl FnOnce(&mut AppSizes) -> bool) {
|
||||
if edit(&mut self.sizes) {
|
||||
self.sizes_revision += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// Brings the explanation and the contrast report up to date with `subject` and the app layer.
|
||||
pub fn refresh(&mut self, subject: &ThemeSubject<'_>) {
|
||||
let current = self.explanation.as_ref().is_some_and(|(theme, appearance, app, revision, _)| {
|
||||
*theme == subject.theme.id && *appearance == subject.appearance && app.as_ref() == subject.app && *revision == self.sizes_revision
|
||||
});
|
||||
if !current {
|
||||
let explained = Arc::new(explain_sized(subject.theme, subject.appearance, subject.app, &self.sizes));
|
||||
self.explanation = Some((subject.theme.id.clone(), subject.appearance, subject.app.cloned(), self.sizes_revision, explained));
|
||||
}
|
||||
if self.report.as_ref().is_none_or(|(theme, _)| *theme != subject.theme.id) {
|
||||
self.report = Some((subject.theme.id.clone(), Arc::new(contrast_report(subject.theme))));
|
||||
}
|
||||
}
|
||||
|
||||
/// The explanation of the subject of the last `refresh`.
|
||||
pub fn explained(&self) -> Option<&Arc<Explained>> {
|
||||
self.explanation.as_ref().map(|(_, _, _, _, explained)| explained)
|
||||
}
|
||||
|
||||
/// The contrast report of the theme of the last `refresh`.
|
||||
pub fn report(&self) -> Option<&Arc<ContrastReport>> {
|
||||
self.report.as_ref().map(|(_, report)| report)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
//! The words the theme panels use for tokens, sources, sizes and counts.
|
||||
|
||||
use craft_theme::{ColorSource, ColorToken, ComponentField, ComponentTokens, Contrast, Mode, PinLayer, SizeLayer, SizeOrigin, SizeValue, StatusKind};
|
||||
|
||||
/// "Dark: 3 pairs below minimum" in Standard contrast, "Dark: 3 pairs fail" in High, which must meet every minimum.
|
||||
pub fn summary(mode: Mode, contrast: Contrast, count: usize) -> String {
|
||||
let name = if mode == Mode::Light { "Light" } else { "Dark" };
|
||||
let pairs = if count == 1 { "1 pair".to_owned() } else { format!("{count} pairs") };
|
||||
match (count, contrast) {
|
||||
(0, _) => format!("{name}: every pair meets its minimum"),
|
||||
(1, Contrast::High) => format!("{name}: {pairs} fails"),
|
||||
(_, Contrast::High) => format!("{name}: {pairs} fail"),
|
||||
_ => format!("{name}: {pairs} below minimum"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The token's group as in `ColorTokens`: its first path segment.
|
||||
pub(crate) fn group_of(token: ColorToken) -> &'static str {
|
||||
let path = token.path();
|
||||
path.split_once('.').map_or(path, |(group, _)| group)
|
||||
}
|
||||
|
||||
/// The heading a size row is listed under.
|
||||
pub(crate) fn size_group(origin: &SizeOrigin) -> &'static str {
|
||||
match origin.path.split_once('.').map_or(origin.path.as_str(), |(group, _)| group) {
|
||||
"size" => "sizes",
|
||||
"space" => "spacing",
|
||||
"radius" => "corner radii",
|
||||
_ => "type",
|
||||
}
|
||||
}
|
||||
|
||||
/// The heading of the component tokens.
|
||||
pub(crate) const COMPONENT_GROUP: &str = "component tokens";
|
||||
|
||||
/// A size value as shown in a list and the detail.
|
||||
pub(crate) fn value_words(value: SizeValue) -> String {
|
||||
match value {
|
||||
SizeValue::Number(n) => n.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The layer that set a size, in words.
|
||||
pub(crate) fn layer_words(layer: SizeLayer) -> &'static str {
|
||||
match layer {
|
||||
SizeLayer::SizeSet => "size set",
|
||||
SizeLayer::App => "app",
|
||||
_ => "other",
|
||||
}
|
||||
}
|
||||
|
||||
/// The standard and small size of a component token, as `md / sm`.
|
||||
pub(crate) fn lengths_words(tokens: &ComponentTokens, field: ComponentField) -> String {
|
||||
let by = match field {
|
||||
ComponentField::SliderThumbWidth => tokens.slider.thumb_width,
|
||||
ComponentField::SliderThumbHeight => tokens.slider.thumb_height,
|
||||
};
|
||||
format!("{} / {}", by.md, by.sm)
|
||||
}
|
||||
|
||||
/// Where a pin came from.
|
||||
pub(crate) fn pin_words(layer: PinLayer) -> &'static str {
|
||||
match layer {
|
||||
PinLayer::Theme => "theme pin",
|
||||
PinLayer::App => "app pin",
|
||||
PinLayer::ThemeHighContrast => "theme high-contrast pin",
|
||||
PinLayer::AppHighContrast => "app high-contrast pin",
|
||||
_ => "pin",
|
||||
}
|
||||
}
|
||||
|
||||
fn status_name(kind: StatusKind) -> &'static str {
|
||||
match kind {
|
||||
StatusKind::Good => "good",
|
||||
StatusKind::Warn => "warn",
|
||||
StatusKind::Bad => "bad",
|
||||
StatusKind::Info => "info",
|
||||
}
|
||||
}
|
||||
|
||||
/// The ramp a colour takes its step from.
|
||||
pub(crate) fn ramp_name(source: ColorSource) -> String {
|
||||
match source {
|
||||
ColorSource::Neutral(_) | ColorSource::Anchored(_) | ColorSource::StateVariant { .. } | ColorSource::NeutralAlpha(..) => "neutral".to_owned(),
|
||||
ColorSource::Accent(_) | ColorSource::AccentMix { .. } => "accent".to_owned(),
|
||||
ColorSource::Status(kind, _) | ColorSource::StatusMix { kind, .. } => format!("status {}", status_name(kind)),
|
||||
_ => String::new(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
//! The choices of the options bar: the named options of each root value, the theme list and the Variants axes.
|
||||
|
||||
use craft_i18n::Direction;
|
||||
use craft_theme::{ContrastChoice, ModeChoice, MotionChoice, Size, TextSize, ThemeDef, ThemeId, builtins};
|
||||
use craft_ui::contract::Entry;
|
||||
use craft_ui::runtime::env::Scale;
|
||||
|
||||
/// One option of a choice: the value, the name it is saved under and the label the options bar shows.
|
||||
#[non_exhaustive]
|
||||
pub struct Choice<T: 'static> {
|
||||
/// The value.
|
||||
pub value: T,
|
||||
/// The saved name.
|
||||
pub name: &'static str,
|
||||
/// The text the options bar shows.
|
||||
pub label: &'static str,
|
||||
}
|
||||
|
||||
/// The options of one appearance field, in the order the options bar lists them.
|
||||
#[non_exhaustive]
|
||||
pub struct Choices<T: 'static>(pub &'static [Choice<T>]);
|
||||
|
||||
impl<T: Copy + PartialEq + 'static> Choices<T> {
|
||||
/// The value saved as `name`.
|
||||
pub fn parse(&self, name: &str) -> Option<T> {
|
||||
self.0.iter().find(|choice| choice.name == name).map(|choice| choice.value)
|
||||
}
|
||||
|
||||
/// The name `value` is saved under.
|
||||
pub fn name(&self, value: T) -> &'static str {
|
||||
self.0.iter().find(|choice| choice.value == value).map_or("", |choice| choice.name)
|
||||
}
|
||||
|
||||
/// The text the options bar shows for `value`.
|
||||
pub fn label(&self, value: T) -> &'static str {
|
||||
self.0.iter().find(|choice| choice.value == value).map_or("", |choice| choice.label)
|
||||
}
|
||||
|
||||
/// The entries of a select or a segmented row over the options.
|
||||
pub fn entries(&self) -> Vec<Entry<T>> {
|
||||
self.0.iter().map(|choice| Entry::new(choice.value, choice.label)).collect()
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! choices {
|
||||
($name:ident: $ty:ty = [$(($value:expr, $saved:literal, $label:literal)),+ $(,)?]) => {
|
||||
/// The options of the field.
|
||||
pub const $name: Choices<$ty> = Choices(&[$(Choice { value: $value, name: $saved, label: $label }),+]);
|
||||
};
|
||||
}
|
||||
|
||||
choices!(MODES: ModeChoice = [
|
||||
(ModeChoice::Light, "light", "Light"),
|
||||
(ModeChoice::Dark, "dark", "Dark"),
|
||||
(ModeChoice::System, "system", "System"),
|
||||
]);
|
||||
choices!(CONTRASTS: ContrastChoice = [
|
||||
(ContrastChoice::Standard, "standard", "Standard"),
|
||||
(ContrastChoice::High, "high", "High"),
|
||||
(ContrastChoice::System, "system", "System"),
|
||||
]);
|
||||
choices!(TEXT_SIZES: TextSize = [
|
||||
(TextSize::Tiny, "tiny", "Tiny"),
|
||||
(TextSize::Small, "small", "Small"),
|
||||
(TextSize::Medium, "medium", "Medium"),
|
||||
(TextSize::Large, "large", "Large"),
|
||||
]);
|
||||
choices!(DENSITIES: Size = [(Size::Compact, "compact", "Compact"), (Size::Comfortable, "comfortable", "Comfortable")]);
|
||||
choices!(MOTIONS: MotionChoice = [
|
||||
(MotionChoice::Full, "full", "Off"),
|
||||
(MotionChoice::Reduced, "reduced", "On"),
|
||||
(MotionChoice::System, "system", "System"),
|
||||
]);
|
||||
choices!(SCALES: Scale = [
|
||||
(Scale::new(1.0), "100", "100%"),
|
||||
(Scale::new(1.25), "125", "125%"),
|
||||
(Scale::new(1.5), "150", "150%"),
|
||||
(Scale::new(2.0), "200", "200%"),
|
||||
]);
|
||||
choices!(DIRECTIONS: Direction = [(Direction::Ltr, "ltr", "LTR"), (Direction::Rtl, "rtl", "RTL")]);
|
||||
|
||||
/// What a Variants view repeats the story over.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum VariantAxis {
|
||||
/// Every built-in theme.
|
||||
Theme,
|
||||
/// Light and dark.
|
||||
Mode,
|
||||
/// Standard and high contrast.
|
||||
Contrast,
|
||||
/// Compact and comfortable density.
|
||||
Size,
|
||||
/// Left to right and right to left.
|
||||
Direction,
|
||||
/// Small and medium controls.
|
||||
ControlSize,
|
||||
/// Every direction at every control size.
|
||||
DirectionAndControlSize,
|
||||
}
|
||||
|
||||
impl VariantAxis {
|
||||
/// Every axis, in menu order.
|
||||
pub const ALL: [VariantAxis; 7] = [
|
||||
VariantAxis::Theme,
|
||||
VariantAxis::Mode,
|
||||
VariantAxis::Contrast,
|
||||
VariantAxis::Size,
|
||||
VariantAxis::Direction,
|
||||
VariantAxis::ControlSize,
|
||||
VariantAxis::DirectionAndControlSize,
|
||||
];
|
||||
|
||||
/// The Variants menu's item.
|
||||
pub fn menu_label(self) -> &'static str {
|
||||
match self {
|
||||
VariantAxis::Theme => "Every theme",
|
||||
VariantAxis::Mode => "Every mode (light, dark)",
|
||||
VariantAxis::Contrast => "Every contrast (standard, high)",
|
||||
VariantAxis::Size => "Every size (compact, comfortable)",
|
||||
VariantAxis::Direction => "Every direction (LTR, RTL)",
|
||||
VariantAxis::ControlSize => "Every control size (Sm, Md)",
|
||||
VariantAxis::DirectionAndControlSize => "Every direction and control size",
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The built-in theme saved as `name`.
|
||||
pub fn theme_named(name: &str) -> Option<ThemeId> {
|
||||
builtins().iter().find(|theme| theme.id.as_str() == name).map(|theme| theme.id.clone())
|
||||
}
|
||||
|
||||
/// The built-in theme `id` names; the suite default when `id` names none.
|
||||
pub fn theme_of(id: &ThemeId) -> &'static ThemeDef {
|
||||
let themes = builtins();
|
||||
themes.iter().find(|theme| theme.id == *id).or_else(|| themes.iter().find(|theme| theme.id == ThemeId::suite_default())).unwrap_or(&themes[0])
|
||||
}
|
||||
|
||||
/// The entries of the Theme select: every built-in theme under its name.
|
||||
pub fn theme_entries() -> Vec<Entry<ThemeId>> {
|
||||
builtins().iter().map(|theme| Entry::new(theme.id.clone(), theme.name.clone())).collect()
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
//! What the viewer lists: every registered story, grouped by the component it shows.
|
||||
|
||||
use craft_ui::contract::{self, Level, Probe, Registration};
|
||||
use craft_ui::testing::{StoryRegistration, stories};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
/// One registered story with the facts the viewer lists.
|
||||
#[derive(Clone, Copy)]
|
||||
#[non_exhaustive]
|
||||
pub struct Entry {
|
||||
/// The registration.
|
||||
pub registration: &'static StoryRegistration,
|
||||
/// The registered name of the type the story shows.
|
||||
pub type_name: &'static str,
|
||||
}
|
||||
|
||||
/// The facts of one component the tree lists and the filter reads.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub struct ComponentInfo {
|
||||
/// The registered type name.
|
||||
pub type_name: &'static str,
|
||||
/// The level the tree lists the component under.
|
||||
pub level: Level,
|
||||
/// The component's plain name.
|
||||
pub name: String,
|
||||
/// The names of the component's stories.
|
||||
pub stories: Vec<&'static str>,
|
||||
/// The display titles of the stories, in the order of `stories`.
|
||||
pub titles: Vec<String>,
|
||||
/// The story groups, in the order of their first story.
|
||||
pub groups: Vec<StoryGroup>,
|
||||
/// The name, the titles and the group names in lower case, for the filter.
|
||||
folded: Vec<String>,
|
||||
/// The registry's level of the type and its display name in lower case; `None` when the registry does not list it.
|
||||
listed: Option<(Level, String)>,
|
||||
}
|
||||
|
||||
/// A named group of one component's stories, shown together as the cases of one old gallery story.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub struct StoryGroup {
|
||||
/// The group's name (`Story::group_name`).
|
||||
pub name: String,
|
||||
/// The group's stories, as places in the component's `stories`, in declaration order.
|
||||
pub members: Vec<usize>,
|
||||
}
|
||||
|
||||
impl ComponentInfo {
|
||||
/// A component with its stories, each a name and a display title, and each its own group under its title.
|
||||
pub fn new(type_name: &'static str, level: Level, name: impl Into<String>, stories: &[(&'static str, &str)]) -> Self {
|
||||
let name = name.into();
|
||||
let listed = linked_catalog().entry(type_name).map(|entry| (entry.level, entry.name.to_lowercase()));
|
||||
let mut info = ComponentInfo {
|
||||
type_name,
|
||||
level,
|
||||
folded: vec![name.to_lowercase()],
|
||||
name,
|
||||
stories: Vec::new(),
|
||||
titles: Vec::new(),
|
||||
groups: Vec::new(),
|
||||
listed,
|
||||
};
|
||||
for (story, title) in stories {
|
||||
info.push(story, (*title).to_owned(), (*title).to_owned());
|
||||
}
|
||||
info
|
||||
}
|
||||
|
||||
/// Adds `story` under `title` to the group named `group`, which is new unless an earlier story named it.
|
||||
fn push(&mut self, story: &'static str, title: String, group: String) {
|
||||
let place = self.stories.len();
|
||||
self.stories.push(story);
|
||||
self.folded.push(title.to_lowercase());
|
||||
self.titles.push(title);
|
||||
match self.groups.iter_mut().find(|known| known.name == group) {
|
||||
Some(known) => known.members.push(place),
|
||||
None => {
|
||||
self.folded.push(group.to_lowercase());
|
||||
self.groups.push(StoryGroup { name: group, members: vec![place] });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The group that holds the story at `place` in `stories`.
|
||||
pub fn group_of(&self, place: usize) -> Option<usize> {
|
||||
self.groups.iter().position(|group| group.members.contains(&place))
|
||||
}
|
||||
|
||||
/// Whether the name, one of the story titles or one of the group names contains the filter, ignoring case;
|
||||
/// `folded` is the filter as [`fold_filter`] gives it. An empty filter matches.
|
||||
pub fn matches(&self, folded: &str) -> bool {
|
||||
folded.is_empty() || self.folded.iter().any(|text| text.contains(folded))
|
||||
}
|
||||
|
||||
/// The registry's level of the type and its display name in lower case, the Overview's order within the level.
|
||||
pub(crate) fn listed(&self) -> Option<(Level, &str)> {
|
||||
self.listed.as_ref().map(|(level, name)| (*level, name.as_str()))
|
||||
}
|
||||
}
|
||||
|
||||
/// The filter as [`ComponentInfo::matches`] compares it: trimmed and in lower case.
|
||||
pub fn fold_filter(filter: &str) -> String {
|
||||
filter.trim().to_lowercase()
|
||||
}
|
||||
|
||||
/// The registry's catalog of the types linked into the running binary: each one's level and plain name.
|
||||
pub(crate) fn linked_catalog() -> &'static contract::Catalog {
|
||||
static CATALOG: OnceLock<contract::Catalog> = OnceLock::new();
|
||||
CATALOG.get_or_init(|| contract::catalog(&contract::registrations()))
|
||||
}
|
||||
|
||||
/// The plain name of the component registered as `type_name`; the registered name when the registry lists no such type.
|
||||
pub fn display_name(type_name: &str) -> String {
|
||||
linked_catalog().entry(type_name).map_or_else(|| type_name.to_owned(), |entry| entry.name.clone())
|
||||
}
|
||||
|
||||
/// Every story linked into the viewer, ordered by type then story name.
|
||||
pub fn entries() -> Vec<Entry> {
|
||||
stories().into_iter().map(|registration| Entry { registration, type_name: (registration.type_name)() }).collect()
|
||||
}
|
||||
|
||||
/// What a registration says about a type: where it is declared and what it is for.
|
||||
#[derive(Clone, Copy)]
|
||||
#[non_exhaustive]
|
||||
pub struct Declared {
|
||||
/// The module path of the declaration.
|
||||
pub module: &'static str,
|
||||
/// The first sentence of the type's doc comment.
|
||||
pub purpose: &'static str,
|
||||
/// The component probe; `None` for a pattern.
|
||||
pub probe: Option<&'static Probe>,
|
||||
}
|
||||
|
||||
/// The registration of each registered component and pattern type, by the type's registered name.
|
||||
pub fn declared() -> HashMap<&'static str, Declared> {
|
||||
let mut out = HashMap::new();
|
||||
for registration in contract::registrations() {
|
||||
match registration {
|
||||
Registration::Component(probe) => {
|
||||
out.insert(probe.type_name(), Declared { module: probe.module, purpose: probe.purpose, probe: Some(probe) });
|
||||
}
|
||||
Registration::Pattern(probe) => {
|
||||
out.insert(probe.type_name(), Declared { module: probe.module, purpose: probe.purpose, probe: None });
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The components of `entries` that the registry lists, in the order of their first story.
|
||||
pub fn components(entries: &[Entry]) -> Vec<ComponentInfo> {
|
||||
let mut out: Vec<ComponentInfo> = Vec::new();
|
||||
for entry in entries {
|
||||
let Some(listed) = linked_catalog().entry(entry.type_name) else { continue };
|
||||
let story = &entry.registration.story;
|
||||
let (title, group) = (story.caption(&listed.name), story.group_name(&listed.name));
|
||||
let at = match out.iter().position(|component| component.type_name == entry.type_name) {
|
||||
Some(at) => at,
|
||||
None => {
|
||||
out.push(ComponentInfo::new(entry.type_name, listed.level, listed.name.clone(), &[]));
|
||||
out.len() - 1
|
||||
}
|
||||
};
|
||||
out[at].push(story.name, title, group);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Every registered story, the components they show and what the registrations say about each type.
|
||||
#[non_exhaustive]
|
||||
pub struct Catalog {
|
||||
/// The stories, ordered by type then story name.
|
||||
pub entries: Vec<Entry>,
|
||||
/// The components of the stories.
|
||||
pub components: Vec<ComponentInfo>,
|
||||
/// The registration of each type.
|
||||
pub declared: HashMap<&'static str, Declared>,
|
||||
/// Each component's place in `components` and the catalog indices of its stories, in the order of its `stories`.
|
||||
by_type: HashMap<&'static str, (usize, Vec<usize>)>,
|
||||
}
|
||||
|
||||
impl Catalog {
|
||||
/// The catalog of the stories linked into the running binary.
|
||||
pub fn linked() -> Self {
|
||||
let entries = entries();
|
||||
let declared = declared();
|
||||
let components = components(&entries);
|
||||
Catalog::new(entries, components, declared)
|
||||
}
|
||||
|
||||
/// A catalog of `components` with no stories to show.
|
||||
pub fn listing(components: Vec<ComponentInfo>) -> Self {
|
||||
Catalog::new(Vec::new(), components, HashMap::new())
|
||||
}
|
||||
|
||||
fn new(entries: Vec<Entry>, components: Vec<ComponentInfo>, declared: HashMap<&'static str, Declared>) -> Self {
|
||||
let mut by_type: HashMap<&'static str, (usize, Vec<usize>)> =
|
||||
components.iter().enumerate().map(|(at, component)| (component.type_name, (at, Vec::new()))).collect();
|
||||
for (at, entry) in entries.iter().enumerate() {
|
||||
if let Some((_, stories)) = by_type.get_mut(entry.type_name) {
|
||||
stories.push(at);
|
||||
}
|
||||
}
|
||||
Catalog { entries, components, declared, by_type }
|
||||
}
|
||||
|
||||
/// The component registered as `type_name`.
|
||||
pub fn component(&self, type_name: &str) -> Option<&ComponentInfo> {
|
||||
self.by_type.get(type_name).map(|(at, _)| &self.components[*at])
|
||||
}
|
||||
|
||||
/// The catalog indices of the stories of the component registered as `type_name`, in the order of its `stories`.
|
||||
pub fn stories_of(&self, type_name: &str) -> &[usize] {
|
||||
self.by_type.get(type_name).map_or(&[], |(_, stories)| stories.as_slice())
|
||||
}
|
||||
|
||||
/// The catalog index of the story of the component registered as `type_name` that a view shows: the one named
|
||||
/// `picked`, else the component's first.
|
||||
pub fn pick(&self, type_name: &str, picked: Option<&str>) -> Option<usize> {
|
||||
let stories = self.stories_of(type_name);
|
||||
picked
|
||||
.and_then(|name| stories.iter().copied().find(|&at| self.entries[at].registration.story.name == name))
|
||||
.or_else(|| stories.first().copied())
|
||||
}
|
||||
|
||||
/// The catalog indices of the stories of group `group` of the component registered as `type_name`.
|
||||
pub fn group_stories(&self, type_name: &str, group: usize) -> Vec<usize> {
|
||||
let (Some(component), all) = (self.component(type_name), self.stories_of(type_name)) else { return Vec::new() };
|
||||
component.groups.get(group).map_or_else(Vec::new, |group| group.members.iter().filter_map(|&place| all.get(place).copied()).collect())
|
||||
}
|
||||
|
||||
/// The group of the component registered as `type_name` that holds the story at catalog index `story`.
|
||||
pub fn group_at(&self, type_name: &str, story: usize) -> Option<usize> {
|
||||
let place = self.stories_of(type_name).iter().position(|&at| at == story)?;
|
||||
self.component(type_name)?.group_of(place)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
//! The viewer's commands. Every action of a panel menu or the options bar is one of them, so a key, the palette
|
||||
//! or a script reaches it too.
|
||||
|
||||
use craft_ui::contract::CommandSet;
|
||||
|
||||
/// The viewer's app-scope commands.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, CommandSet)]
|
||||
#[command(prefix = "gallery")]
|
||||
#[non_exhaustive]
|
||||
pub enum GalleryCommands {
|
||||
/// Put the shown workspace's panels back at their default places; open component tabs stay.
|
||||
#[command(label = "Reset Layout", icon = "undo")]
|
||||
ResetLayout,
|
||||
/// Give every shown story fresh state.
|
||||
#[command(label = "Reset Args")]
|
||||
ResetStories,
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
//! The viewer's dock layouts: the panels of each workspace, the default arrangements, what the user may do with a
|
||||
//! panel, and the saved form of a layout.
|
||||
//!
|
||||
//! A saved layout names a component tab by its component's registered name. A name the catalog no longer has loads as a
|
||||
//! panel the reconciliation drops, so a layout saved by another build costs at most its component tabs.
|
||||
|
||||
use super::catalog::display_name;
|
||||
use super::state::Workspace;
|
||||
use craft_behavior::Axis;
|
||||
use craft_behavior::dock::{Column, DockEdge, Group, Layout, Node, Permissions, SplitSize, Workspace as Dock};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::{Mutex, PoisonError};
|
||||
|
||||
/// A panel of the viewer's dock layouts.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
pub enum PanelId {
|
||||
/// The component tree.
|
||||
Components,
|
||||
/// The target component's stories.
|
||||
Stories,
|
||||
/// The target story's facts and values.
|
||||
Properties,
|
||||
/// The decision record of the target component.
|
||||
Inspect,
|
||||
/// The token browser.
|
||||
Tokens,
|
||||
/// The centre's first tab: every component of one level.
|
||||
Overview,
|
||||
/// A centre tab with every story of one component, by the component's registered type name.
|
||||
Component(&'static str),
|
||||
/// The theme workspace's centre: the mock app or the Controls level.
|
||||
Preview,
|
||||
/// The picked token's detail.
|
||||
Detail,
|
||||
/// The theme's contrast problems.
|
||||
Problems,
|
||||
/// The app sizes editor.
|
||||
AppSizes,
|
||||
}
|
||||
|
||||
impl PanelId {
|
||||
/// The panel's title.
|
||||
pub fn title(self) -> String {
|
||||
match self {
|
||||
PanelId::Components => "Components".to_owned(),
|
||||
PanelId::Stories => "Stories".to_owned(),
|
||||
PanelId::Properties => "Properties".to_owned(),
|
||||
PanelId::Inspect => "Inspect".to_owned(),
|
||||
PanelId::Tokens => "Tokens".to_owned(),
|
||||
PanelId::Overview => "Overview".to_owned(),
|
||||
PanelId::Component(type_name) => display_name(type_name),
|
||||
PanelId::Preview => "Preview".to_owned(),
|
||||
PanelId::Detail => "Detail".to_owned(),
|
||||
PanelId::Problems => "Problems".to_owned(),
|
||||
PanelId::AppSizes => "App sizes".to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the layout of `workspace` holds the panel. The token browser is in both.
|
||||
pub fn in_workspace(self, workspace: Workspace) -> bool {
|
||||
match self {
|
||||
PanelId::Components | PanelId::Stories | PanelId::Properties | PanelId::Inspect | PanelId::Overview | PanelId::Component(_) => {
|
||||
workspace == Workspace::Components
|
||||
}
|
||||
PanelId::Tokens => true,
|
||||
PanelId::Preview | PanelId::Detail | PanelId::Problems | PanelId::AppSizes => workspace == Workspace::Theme,
|
||||
}
|
||||
}
|
||||
|
||||
/// Panels move, float and tab freely. Only a component tab closes: any other closed panel would have no way back
|
||||
/// besides Reset layout.
|
||||
pub fn permissions(&self) -> Permissions {
|
||||
Permissions::ALL.closable(matches!(self, PanelId::Component(_)))
|
||||
}
|
||||
}
|
||||
|
||||
/// [`PanelId`] as saved: the same variants, with a component tab named by an owned string.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum PanelRepr {
|
||||
Components,
|
||||
Stories,
|
||||
Properties,
|
||||
Inspect,
|
||||
Tokens,
|
||||
Overview,
|
||||
Component(String),
|
||||
Preview,
|
||||
Detail,
|
||||
Problems,
|
||||
AppSizes,
|
||||
}
|
||||
|
||||
/// The names of the component tabs read from saved layouts. A tab name is a `&'static str`, so each distinct name is
|
||||
/// kept once for the process.
|
||||
fn interned(name: String) -> &'static str {
|
||||
static NAMES: Mutex<BTreeSet<&'static str>> = Mutex::new(BTreeSet::new());
|
||||
let mut names = NAMES.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some(known) = names.get(name.as_str()) {
|
||||
return known;
|
||||
}
|
||||
let leaked: &'static str = Box::leak(name.into_boxed_str());
|
||||
names.insert(leaked);
|
||||
leaked
|
||||
}
|
||||
|
||||
impl Serialize for PanelId {
|
||||
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
let repr = match *self {
|
||||
PanelId::Components => PanelRepr::Components,
|
||||
PanelId::Stories => PanelRepr::Stories,
|
||||
PanelId::Properties => PanelRepr::Properties,
|
||||
PanelId::Inspect => PanelRepr::Inspect,
|
||||
PanelId::Tokens => PanelRepr::Tokens,
|
||||
PanelId::Overview => PanelRepr::Overview,
|
||||
PanelId::Component(name) => PanelRepr::Component(name.to_owned()),
|
||||
PanelId::Preview => PanelRepr::Preview,
|
||||
PanelId::Detail => PanelRepr::Detail,
|
||||
PanelId::Problems => PanelRepr::Problems,
|
||||
PanelId::AppSizes => PanelRepr::AppSizes,
|
||||
};
|
||||
repr.serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for PanelId {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
Ok(match PanelRepr::deserialize(deserializer)? {
|
||||
PanelRepr::Components => PanelId::Components,
|
||||
PanelRepr::Stories => PanelId::Stories,
|
||||
PanelRepr::Properties => PanelId::Properties,
|
||||
PanelRepr::Inspect => PanelId::Inspect,
|
||||
PanelRepr::Tokens => PanelId::Tokens,
|
||||
PanelRepr::Overview => PanelId::Overview,
|
||||
PanelRepr::Component(name) => PanelId::Component(interned(name)),
|
||||
PanelRepr::Preview => PanelId::Preview,
|
||||
PanelRepr::Detail => PanelId::Detail,
|
||||
PanelRepr::Problems => PanelId::Problems,
|
||||
PanelRepr::AppSizes => PanelId::AppSizes,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The share a split beside a dock records. The dock's width comes from its columns, so the split never reads it.
|
||||
const BESIDE_DOCK: SplitSize = SplitSize::Ratio(0.5);
|
||||
|
||||
/// The component tree column's width; the side column takes the dock column token.
|
||||
const TREE_WIDTH: f32 = 220.0;
|
||||
|
||||
/// The components workspace: the component tree at the start edge, the overview in the centre, the stories above the
|
||||
/// properties, the inspector and the token browser at the end edge.
|
||||
pub fn default_components() -> Dock<PanelId> {
|
||||
let tree = Column::new(vec![Group::new(vec![PanelId::Components], 0)]).with_width(TREE_WIDTH);
|
||||
let side = Column::new(vec![Group::new(vec![PanelId::Stories], 0), Group::new(vec![PanelId::Properties, PanelId::Inspect, PanelId::Tokens], 0)]);
|
||||
let centre = Node::split(Axis::X, BESIDE_DOCK, Node::tabs(vec![PanelId::Overview], 0), Node::dock(DockEdge::End, vec![side]));
|
||||
let root = Node::split(Axis::X, BESIDE_DOCK, Node::dock(DockEdge::Start, vec![tree]), centre);
|
||||
Dock::new(Layout::new(Some(root), Vec::new()))
|
||||
}
|
||||
|
||||
/// The theme workspace: the preview in the centre; the problems, detail and app sizes above the token browser at the
|
||||
/// end edge. The problems come first in the tree, so they are shown before the tokens in a pass: the token browser
|
||||
/// reveals the row a problem picks in the same pass.
|
||||
pub fn default_theme() -> Dock<PanelId> {
|
||||
let side = Column::new(vec![Group::new(vec![PanelId::Problems, PanelId::Detail, PanelId::AppSizes], 0), Group::new(vec![PanelId::Tokens], 0)]);
|
||||
let root = Node::split(Axis::X, BESIDE_DOCK, Node::tabs(vec![PanelId::Preview], 0), Node::dock(DockEdge::End, vec![side]));
|
||||
Dock::new(Layout::new(Some(root), Vec::new()))
|
||||
}
|
||||
|
||||
/// The default layout of `workspace`.
|
||||
pub fn default_for(workspace: Workspace) -> Dock<PanelId> {
|
||||
match workspace {
|
||||
Workspace::Components => default_components(),
|
||||
Workspace::Theme => default_theme(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `saved` made valid for `workspace`: a layout that fails validation is replaced by the default, panels of the other
|
||||
/// workspace and component tabs `known` rejects are dropped, and missing panels come back where the default has them.
|
||||
pub fn reconciled(mut saved: Dock<PanelId>, workspace: Workspace, known: &dyn Fn(&str) -> bool) -> Dock<PanelId> {
|
||||
let registered = |panel: &PanelId| {
|
||||
panel.in_workspace(workspace)
|
||||
&& match panel {
|
||||
PanelId::Component(name) => known(name),
|
||||
_ => true,
|
||||
}
|
||||
};
|
||||
saved.reconcile(registered, PanelId::permissions, &default_for(workspace));
|
||||
saved.hidden.retain(|(panel, _)| registered(panel));
|
||||
saved
|
||||
}
|
||||
|
||||
/// The saved text of `layout`.
|
||||
pub fn save(layout: &Dock<PanelId>) -> String {
|
||||
serde_json::to_string(layout).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The layout saved as `text`, made valid for `workspace`; the default when the text is empty or unreadable.
|
||||
pub fn load(text: &str, workspace: Workspace, known: &dyn Fn(&str) -> bool) -> Dock<PanelId> {
|
||||
serde_json::from_str::<Dock<PanelId>>(text).ok().map_or_else(|| default_for(workspace), |saved| reconciled(saved, workspace, known))
|
||||
}
|
||||
|
||||
/// The component tabs `layout` holds, in layout order.
|
||||
pub fn open_tabs(layout: &Dock<PanelId>) -> Vec<&'static str> {
|
||||
layout
|
||||
.layout
|
||||
.panels()
|
||||
.into_iter()
|
||||
.filter_map(|panel| match panel {
|
||||
PanelId::Component(name) => Some(*name),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
//! The viewer's state and the data its chrome shows.
|
||||
|
||||
mod appearance;
|
||||
mod catalog;
|
||||
mod commands;
|
||||
mod layout;
|
||||
mod picks;
|
||||
mod settings;
|
||||
mod state;
|
||||
mod tree;
|
||||
|
||||
pub use appearance::{
|
||||
CONTRASTS, Choice, Choices, DENSITIES, DIRECTIONS, MODES, MOTIONS, SCALES, TEXT_SIZES, VariantAxis, theme_entries, theme_named, theme_of,
|
||||
};
|
||||
pub use catalog::{Catalog, ComponentInfo, Declared, Entry, StoryGroup, display_name};
|
||||
pub use commands::GalleryCommands;
|
||||
pub use layout::{PanelId, default_components, default_for, default_theme, load as load_layout, open_tabs, reconciled, save as save_layout};
|
||||
pub use picks::{CardState, DialogState, by_level, entry_of, levels};
|
||||
pub use settings::GallerySettings;
|
||||
pub use state::{Browser, Cells, Preview, Viewer, Workspace};
|
||||
pub use tree::{TreeKey, TreeRow, TreeRows, groups, level_named, open_level_of_selection, rows, slug};
|
||||
@@ -0,0 +1,94 @@
|
||||
//! What the centre tabs keep and derive: each shown story's state, and the components of the catalog by level.
|
||||
|
||||
use super::catalog::{Catalog, ComponentInfo, fold_filter};
|
||||
use craft_ui::contract::{Catalog as Levels, CatalogEntry, Level};
|
||||
use craft_ui::testing::{StoryData, StorySnapshot};
|
||||
|
||||
/// Whether a story's dialog is closed behind its button.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
#[non_exhaustive]
|
||||
pub struct DialogState {
|
||||
/// The story opened a dialog.
|
||||
pub known: bool,
|
||||
/// The dialog is closed: the card shows its button and does not run the story.
|
||||
pub hidden: bool,
|
||||
/// The dialog was seen open since the button was pressed.
|
||||
pub shown: bool,
|
||||
/// The story has painted in the card, so it is past its start: a dialog the user opens with the story's own
|
||||
/// controls stays open.
|
||||
pub painted: bool,
|
||||
}
|
||||
|
||||
/// What one shown story keeps between frames.
|
||||
#[derive(Default)]
|
||||
#[non_exhaustive]
|
||||
pub struct CardState {
|
||||
/// The story's values.
|
||||
pub data: StoryData,
|
||||
/// The values after the first pass, which Reset restores; `None` before the story has run.
|
||||
pub start: Option<StorySnapshot>,
|
||||
/// Where the story's dialog is: a story that opens one is shown closed, behind a "Show dialog" button.
|
||||
pub dialog: DialogState,
|
||||
/// Counts the resets of this story; the card's id scope carries it, so a reset mounts the story anew.
|
||||
pub resets: u32,
|
||||
}
|
||||
|
||||
impl CardState {
|
||||
/// Whether the story's values differ from the ones it started with.
|
||||
pub fn changed(&self) -> bool {
|
||||
self.start.as_ref().is_some_and(|start| !self.data.changed_since(start).is_empty())
|
||||
}
|
||||
|
||||
/// Notes the values after the story's first pass as the ones Reset restores.
|
||||
pub fn note_start(&mut self) {
|
||||
if self.start.is_none() {
|
||||
self.start = Some(self.data.snapshot());
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens the dialog the card holds closed behind its button, as the button does: the story runs again with its
|
||||
/// `open` value on.
|
||||
pub fn show_dialog(&mut self) {
|
||||
self.dialog = DialogState { known: true, hidden: false, shown: false, painted: true };
|
||||
if let Some(open) = self.data.present::<bool>("open") {
|
||||
*open = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Gives the story its start values again, on a fresh id scope.
|
||||
pub fn reset(&mut self) {
|
||||
*self = CardState { resets: self.resets + 1, ..CardState::default() };
|
||||
}
|
||||
}
|
||||
|
||||
/// The level, display name and surface of every registered type linked into the binary, the library's and the
|
||||
/// domain crates'.
|
||||
pub fn levels() -> &'static Levels {
|
||||
super::catalog::linked_catalog()
|
||||
}
|
||||
|
||||
/// The level facts of the component registered as `type_name`.
|
||||
pub fn entry_of(type_name: &str) -> Option<&'static CatalogEntry> {
|
||||
levels().entry(type_name)
|
||||
}
|
||||
|
||||
/// The components of `catalog` that match `filter`, by level in listing order, each level's components by display name
|
||||
/// ignoring case; only levels that have components are listed.
|
||||
pub fn by_level<'a>(catalog: &'a Catalog, filter: &str) -> Vec<(Level, Vec<&'a ComponentInfo>)> {
|
||||
let filter = fold_filter(filter);
|
||||
let mut out: Vec<(Level, Vec<(&str, &ComponentInfo)>)> = Level::ALL.iter().map(|level| (*level, Vec::new())).collect();
|
||||
for component in catalog.components.iter().filter(|component| component.matches(&filter)) {
|
||||
if let Some((level, name)) = component.listed()
|
||||
&& let Some((_, list)) = out.iter_mut().find(|(at, _)| *at == level)
|
||||
{
|
||||
list.push((name, component));
|
||||
}
|
||||
}
|
||||
out.into_iter()
|
||||
.filter(|(_, list)| !list.is_empty())
|
||||
.map(|(level, mut list)| {
|
||||
list.sort_by_key(|(name, _)| *name);
|
||||
(level, list.into_iter().map(|(_, component)| component).collect())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
//! What the viewer keeps between runs, in the gallery's own `config.toml`.
|
||||
|
||||
use super::appearance::{CONTRASTS, DENSITIES, DIRECTIONS, MODES, MOTIONS, SCALES, TEXT_SIZES, theme_named};
|
||||
use super::catalog::Catalog;
|
||||
use super::layout;
|
||||
use super::state::{Preview, Viewer, Workspace};
|
||||
use craft_settings::Settings;
|
||||
use craft_ui::runtime::env::RootEnv;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
|
||||
/// The viewer's saved state. Choices are saved by name; a name this build does not know falls back to the default
|
||||
/// of its field, and a layout it cannot read to the default layout, without costing the other fields.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
#[non_exhaustive]
|
||||
pub struct GallerySettings {
|
||||
/// The id of the theme the stories are shown in.
|
||||
pub theme: String,
|
||||
/// Light or dark.
|
||||
pub mode: String,
|
||||
/// Standard or high contrast.
|
||||
pub contrast: String,
|
||||
/// The text-size step.
|
||||
pub text_size: String,
|
||||
/// The density preset.
|
||||
pub density: String,
|
||||
/// The motion mode.
|
||||
pub motion: String,
|
||||
/// The interface scale in percent.
|
||||
pub scale: String,
|
||||
/// The layout direction.
|
||||
pub direction: String,
|
||||
/// The workspace the dock shows: `components` or `theme`.
|
||||
pub workspace: String,
|
||||
/// What the theme workspace's preview shows: `app` or `components`.
|
||||
pub preview: String,
|
||||
/// The slug of the level the Overview shows; empty when none is chosen.
|
||||
pub level: String,
|
||||
/// The name of the story each component's card shows, by the component's registered type name.
|
||||
pub stories: BTreeMap<String, String>,
|
||||
/// The text that narrows the component tree.
|
||||
pub filter: String,
|
||||
/// The registered type name of the selected component; empty when none is.
|
||||
pub selected: String,
|
||||
/// The slugs of the levels that are open in the tree.
|
||||
pub open_levels: Vec<String>,
|
||||
/// The components workspace's dock layout, as `layout::save` writes it. Its own field and its own text, so a layout
|
||||
/// this build cannot read costs only the layout.
|
||||
pub dock: String,
|
||||
/// The theme workspace's dock layout, as `layout::save` writes it.
|
||||
pub theme_dock: String,
|
||||
}
|
||||
|
||||
impl Settings for GallerySettings {
|
||||
const APP_ID: &'static str = "craft-ui-gallery";
|
||||
const SCHEMA_VERSION: u32 = 2;
|
||||
}
|
||||
|
||||
impl GallerySettings {
|
||||
/// The saved state of `viewer`.
|
||||
pub fn of(viewer: &Viewer) -> GallerySettings {
|
||||
let env = &viewer.env;
|
||||
let browser = &viewer.browser;
|
||||
GallerySettings {
|
||||
theme: env.theme.as_str().to_owned(),
|
||||
mode: MODES.name(env.mode).to_owned(),
|
||||
contrast: CONTRASTS.name(env.contrast).to_owned(),
|
||||
text_size: TEXT_SIZES.name(env.text_size).to_owned(),
|
||||
density: DENSITIES.name(env.density).to_owned(),
|
||||
motion: MOTIONS.name(env.motion).to_owned(),
|
||||
scale: SCALES.name(env.scale).to_owned(),
|
||||
direction: DIRECTIONS.name(env.direction).to_owned(),
|
||||
workspace: workspace_name(viewer.workspace).to_owned(),
|
||||
preview: preview_name(viewer.preview).to_owned(),
|
||||
level: browser.level.clone(),
|
||||
stories: browser.story_of.iter().map(|(component, story)| ((*component).to_owned(), (*story).to_owned())).collect(),
|
||||
filter: browser.filter.clone(),
|
||||
selected: viewer.selected_type().unwrap_or_default().to_owned(),
|
||||
open_levels: viewer.open_levels(),
|
||||
dock: layout::save(&browser.dock),
|
||||
theme_dock: layout::save(&viewer.theme_dock),
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the root values these settings name on `env`; a field with an unknown name takes its default.
|
||||
pub fn restore_env(&self, env: &mut RootEnv) {
|
||||
let default = RootEnv::default();
|
||||
env.theme = theme_named(&self.theme).unwrap_or(default.theme);
|
||||
env.mode = MODES.parse(&self.mode).unwrap_or(default.mode);
|
||||
env.contrast = CONTRASTS.parse(&self.contrast).unwrap_or(default.contrast);
|
||||
env.text_size = TEXT_SIZES.parse(&self.text_size).unwrap_or(default.text_size);
|
||||
env.density = DENSITIES.parse(&self.density).unwrap_or(default.density);
|
||||
env.motion = MOTIONS.parse(&self.motion).unwrap_or(default.motion);
|
||||
env.scale = SCALES.parse(&self.scale).unwrap_or(default.scale);
|
||||
env.direction = DIRECTIONS.parse(&self.direction).unwrap_or(default.direction);
|
||||
}
|
||||
|
||||
/// The workspace these settings show; the components workspace when the name is unknown.
|
||||
pub fn workspace(&self) -> Workspace {
|
||||
if self.workspace == workspace_name(Workspace::Theme) { Workspace::Theme } else { Workspace::Components }
|
||||
}
|
||||
|
||||
/// The preview these settings show; the app when the name is unknown.
|
||||
pub fn preview(&self) -> Preview {
|
||||
if self.preview == preview_name(Preview::Components) { Preview::Components } else { Preview::App }
|
||||
}
|
||||
|
||||
/// The story each component shows, for the components and stories `catalog` has.
|
||||
pub fn story_of(&self, catalog: &Catalog) -> HashMap<&'static str, &'static str> {
|
||||
let mut shown = HashMap::new();
|
||||
for (component, story) in &self.stories {
|
||||
let Some(info) = catalog.component(component) else { continue };
|
||||
if let Some(name) = info.stories.iter().find(|name| **name == story.as_str()) {
|
||||
shown.insert(info.type_name, *name);
|
||||
}
|
||||
}
|
||||
shown
|
||||
}
|
||||
}
|
||||
|
||||
fn workspace_name(workspace: Workspace) -> &'static str {
|
||||
match workspace {
|
||||
Workspace::Components => "components",
|
||||
Workspace::Theme => "theme",
|
||||
}
|
||||
}
|
||||
|
||||
fn preview_name(preview: Preview) -> &'static str {
|
||||
match preview {
|
||||
Preview::App => "app",
|
||||
Preview::Components => "components",
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
//! The viewer's state: the root values the stories are shown under, the component tree, the story each component
|
||||
//! shows, the dock layout of each workspace and the theme workspace.
|
||||
|
||||
use super::appearance::VariantAxis;
|
||||
use super::catalog::Catalog;
|
||||
use super::commands::GalleryCommands;
|
||||
use super::layout::{self, PanelId};
|
||||
use super::picks::CardState;
|
||||
use super::settings::GallerySettings;
|
||||
use super::tree::{self, TreeKey};
|
||||
use crate::mock::MockState;
|
||||
use crate::theme::ThemeWorkspace;
|
||||
use craft_behavior::Selection;
|
||||
use craft_behavior::dock::Workspace as Dock;
|
||||
use craft_ui::contract::Level;
|
||||
use craft_ui::list::OpenSet;
|
||||
use craft_ui::runtime::env::RootEnv;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// What each shown story keeps between frames, by story index.
|
||||
pub type Cells = HashMap<usize, CardState>;
|
||||
|
||||
/// What the panels browse: the catalog, the tree's state and the shown cells.
|
||||
#[non_exhaustive]
|
||||
pub struct Browser {
|
||||
/// What is listed.
|
||||
pub catalog: Catalog,
|
||||
/// The text that narrows the tree.
|
||||
pub filter: String,
|
||||
/// The selected row of the tree.
|
||||
pub selection: Selection<TreeKey>,
|
||||
/// The open level groups.
|
||||
pub open: OpenSet<TreeKey>,
|
||||
/// The components workspace's dock layout.
|
||||
pub dock: Dock<PanelId>,
|
||||
/// The story each component's card shows, by the component's registered name and the story's name. A component
|
||||
/// without an entry shows its first story.
|
||||
pub story_of: HashMap<&'static str, &'static str>,
|
||||
/// The level the Overview shows, as its slug; empty until one is chosen.
|
||||
pub level: String,
|
||||
/// Counts the resets of the stories; a card's id scope names it, so a reset mounts the card anew.
|
||||
pub generation: u32,
|
||||
/// The shown stories' values.
|
||||
pub cells: Cells,
|
||||
/// The component whose tab a panel asked to open in this pass.
|
||||
pub open_request: Option<&'static str>,
|
||||
/// The component whose card the Overview brings into view when it is drawn, by its registered name.
|
||||
pub scroll_to: Option<&'static str>,
|
||||
/// The selected component the Overview last followed to its level; the outer `None` before the first pass.
|
||||
pub followed: Option<Option<&'static str>>,
|
||||
/// The selected component the tree last opened the level of; the outer `None` before the first pass. Applying settings
|
||||
/// sets it to the restored selection, so a level closed before a restart stays closed.
|
||||
pub tree_seen: Option<Option<&'static str>>,
|
||||
}
|
||||
|
||||
/// What the dock shows.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum Workspace {
|
||||
/// The component tree, the overview and component tabs, the stories and the target story's panels.
|
||||
#[default]
|
||||
Components,
|
||||
/// The theme workspace: the preview, and the tokens, contrast problems and app sizes of the chosen theme.
|
||||
Theme,
|
||||
}
|
||||
|
||||
/// What the theme workspace's preview shows.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum Preview {
|
||||
/// A mock application.
|
||||
#[default]
|
||||
App,
|
||||
/// The Controls level's overview.
|
||||
Components,
|
||||
}
|
||||
|
||||
/// The viewer: the options bar's values and the browser.
|
||||
#[non_exhaustive]
|
||||
pub struct Viewer {
|
||||
/// The root values the window and every story run under, with the chosen theme.
|
||||
pub env: RootEnv,
|
||||
/// What the dock shows.
|
||||
pub workspace: Workspace,
|
||||
/// What the theme workspace's preview shows.
|
||||
pub preview: Preview,
|
||||
/// The Variants view of the target story, over the front centre tab, while one is open.
|
||||
pub variants: Option<VariantAxis>,
|
||||
/// The centre tab the Variants view is open in.
|
||||
pub variants_tab: Option<PanelId>,
|
||||
/// Whether the More popover of the options bar is open.
|
||||
pub more_open: bool,
|
||||
/// What the panels browse.
|
||||
pub browser: Browser,
|
||||
/// What the theme panels share.
|
||||
pub themes: ThemeWorkspace,
|
||||
/// The theme workspace's dock layout.
|
||||
pub theme_dock: Dock<PanelId>,
|
||||
/// The mock application the theme workspace's App preview shows.
|
||||
pub mock: MockState,
|
||||
/// The revision of the theme workspace's app layer that `env.sizes` holds; none before the first sync.
|
||||
sizes_synced: Option<u64>,
|
||||
}
|
||||
|
||||
impl Viewer {
|
||||
/// The viewer of `catalog`, in the state `settings` saved.
|
||||
pub fn new(catalog: Catalog, settings: &GallerySettings) -> Self {
|
||||
let browser = Browser {
|
||||
catalog,
|
||||
filter: String::new(),
|
||||
selection: Selection::default(),
|
||||
open: OpenSet::new(),
|
||||
dock: layout::default_components(),
|
||||
story_of: HashMap::new(),
|
||||
level: String::new(),
|
||||
generation: 0,
|
||||
cells: Cells::new(),
|
||||
open_request: None,
|
||||
scroll_to: None,
|
||||
followed: None,
|
||||
tree_seen: None,
|
||||
};
|
||||
let mut viewer = Viewer {
|
||||
env: RootEnv::default(),
|
||||
workspace: Workspace::default(),
|
||||
preview: Preview::default(),
|
||||
variants: None,
|
||||
variants_tab: None,
|
||||
more_open: false,
|
||||
browser,
|
||||
themes: ThemeWorkspace::new(),
|
||||
theme_dock: layout::default_theme(),
|
||||
mock: MockState::default(),
|
||||
sizes_synced: None,
|
||||
};
|
||||
viewer.restore(settings);
|
||||
viewer
|
||||
}
|
||||
|
||||
/// Takes the state `settings` saved, keeping the catalog, the cells and the theme workspace.
|
||||
pub fn restore(&mut self, settings: &GallerySettings) {
|
||||
settings.restore_env(&mut self.env);
|
||||
self.workspace = settings.workspace();
|
||||
self.preview = settings.preview();
|
||||
let browser = &mut self.browser;
|
||||
browser.filter.clone_from(&settings.filter);
|
||||
browser.open = OpenSet::new();
|
||||
for level in settings.open_levels.iter().filter_map(|saved| tree::level_named(saved)) {
|
||||
browser.open.set(&TreeKey::Level(level), true);
|
||||
}
|
||||
browser.selection = browser
|
||||
.catalog
|
||||
.component(&settings.selected)
|
||||
.map_or_else(Selection::default, |component| Selection::single(TreeKey::Component(component.type_name)));
|
||||
browser.tree_seen = Some(browser.selected_type());
|
||||
browser.level.clone_from(&settings.level);
|
||||
browser.story_of = settings.story_of(&browser.catalog);
|
||||
let known = |name: &str| browser.catalog.component(name).is_some();
|
||||
browser.dock = layout::load(&settings.dock, Workspace::Components, &known);
|
||||
self.theme_dock = layout::load(&settings.theme_dock, Workspace::Theme, &known);
|
||||
}
|
||||
|
||||
/// Makes the root's app sizes the theme workspace's app layer, when the layer was edited since the last sync.
|
||||
pub fn sync_sizes(&mut self) {
|
||||
let revision = self.themes.sizes_revision();
|
||||
if self.sizes_synced != Some(revision) {
|
||||
self.env.sizes = Arc::new(self.themes.sizes().clone());
|
||||
self.sizes_synced = Some(revision);
|
||||
}
|
||||
}
|
||||
|
||||
/// The registered name of the selected component.
|
||||
pub fn selected_type(&self) -> Option<&'static str> {
|
||||
self.browser.selected_type()
|
||||
}
|
||||
|
||||
/// The slugs of the levels of the tree that are open, in level order.
|
||||
pub fn open_levels(&self) -> Vec<String> {
|
||||
let browser = &self.browser;
|
||||
Level::ALL.into_iter().filter(|level| browser.open.is_open(&TreeKey::Level(*level))).map(tree::slug).collect()
|
||||
}
|
||||
|
||||
/// The dock layout of the shown workspace.
|
||||
pub fn dock_mut(&mut self) -> &mut Dock<PanelId> {
|
||||
match self.workspace {
|
||||
Workspace::Components => &mut self.browser.dock,
|
||||
Workspace::Theme => &mut self.theme_dock,
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens the tab of the component registered as `type_name` beside the Overview and shows it.
|
||||
pub fn open_component(&mut self, type_name: &'static str) {
|
||||
let _ = self.browser.dock.set_visible(PanelId::Component(type_name), true, Some(PanelId::Overview), false, |panel| panel.permissions());
|
||||
}
|
||||
|
||||
/// Puts the shown workspace's panels back at their default places. The open component tabs are documents and stay.
|
||||
pub fn reset_layout(&mut self) {
|
||||
let workspace = self.workspace;
|
||||
let tabs = layout::open_tabs(&self.browser.dock);
|
||||
*self.dock_mut() = layout::default_for(workspace);
|
||||
if workspace == Workspace::Components {
|
||||
for tab in tabs {
|
||||
self.open_component(tab);
|
||||
}
|
||||
let _ = self.browser.dock.set_visible(PanelId::Overview, true, None, false, |panel| panel.permissions());
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `command`.
|
||||
pub fn run(&mut self, command: GalleryCommands) {
|
||||
match command {
|
||||
GalleryCommands::ResetLayout => self.reset_layout(),
|
||||
GalleryCommands::ResetStories => self.browser.reset_stories(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Browser {
|
||||
/// The registered name of the selected component.
|
||||
pub fn selected_type(&self) -> Option<&'static str> {
|
||||
self.selection.items.iter().rev().find_map(|key| match key {
|
||||
TreeKey::Component(type_name) => Some(*type_name),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The index in the catalog of the story the selected component shows: the one picked for it, else its first.
|
||||
pub fn target_story(&self) -> Option<usize> {
|
||||
let type_name = self.selected_type()?;
|
||||
self.catalog.pick(type_name, self.story_of.get(type_name).copied())
|
||||
}
|
||||
|
||||
/// The indices of the stories of the selected component, in listing order.
|
||||
pub fn selected_stories(&self) -> &[usize] {
|
||||
self.selected_type().map_or(&[], |type_name| self.catalog.stories_of(type_name))
|
||||
}
|
||||
|
||||
/// Gives every shown cell fresh state.
|
||||
pub fn reset_stories(&mut self) {
|
||||
self.generation += 1;
|
||||
self.cells.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
//! The component tree: one group per level, the components of each under it, narrowed by the filter.
|
||||
|
||||
use super::catalog::{ComponentInfo, fold_filter};
|
||||
use craft_behavior::{DisplayOrder, ItemSource};
|
||||
use craft_ui::contract::Level;
|
||||
use craft_ui::list::OpenSet;
|
||||
use std::borrow::Cow;
|
||||
|
||||
/// The key of a tree row.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
#[non_exhaustive]
|
||||
pub enum TreeKey {
|
||||
/// A level group.
|
||||
Level(Level),
|
||||
/// A component, by its registered type name.
|
||||
Component(&'static str),
|
||||
}
|
||||
|
||||
/// One shown row of the tree.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub struct TreeRow {
|
||||
/// The row's key.
|
||||
pub key: TreeKey,
|
||||
/// The text the row shows.
|
||||
pub label: String,
|
||||
/// 0 for a level, 1 for a component.
|
||||
pub depth: usize,
|
||||
/// Whether the row holds components.
|
||||
pub group: bool,
|
||||
/// Whether a group shows its components.
|
||||
pub open: bool,
|
||||
}
|
||||
|
||||
/// The slug a level is remembered by.
|
||||
pub fn slug(level: Level) -> String {
|
||||
level.title().to_lowercase()
|
||||
}
|
||||
|
||||
/// The level whose slug is `slug`.
|
||||
pub fn level_named(slug_text: &str) -> Option<Level> {
|
||||
Level::ALL.into_iter().find(|level| slug(*level) == slug_text)
|
||||
}
|
||||
|
||||
/// Opens the level of `selected` when the selection is not the one `seen` records, then records it, so a selection
|
||||
/// that moves into a closed level shows its row. The levels the user opened or closed otherwise stay as they are.
|
||||
pub fn open_level_of_selection(
|
||||
open: &mut OpenSet<TreeKey>,
|
||||
components: &[ComponentInfo],
|
||||
selected: Option<&'static str>,
|
||||
seen: &mut Option<Option<&'static str>>,
|
||||
) {
|
||||
if *seen == Some(selected) {
|
||||
return;
|
||||
}
|
||||
*seen = Some(selected);
|
||||
if let Some(component) = selected.and_then(|type_name| components.iter().find(|component| component.type_name == type_name)) {
|
||||
open.set(&TreeKey::Level(component.level), true);
|
||||
}
|
||||
}
|
||||
|
||||
/// The rows of the tree for `filter`: the levels in order, each with the components that match, sorted by name
|
||||
/// ignoring case. A filter opens every level that holds a match, so the matches show; the open set stays as it is.
|
||||
pub fn rows(components: &[ComponentInfo], filter: &str, open: &OpenSet<TreeKey>) -> Vec<TreeRow> {
|
||||
let filter = fold_filter(filter);
|
||||
let filtering = !filter.is_empty();
|
||||
let mut rows = Vec::new();
|
||||
for level in Level::ALL {
|
||||
let mut members: Vec<&ComponentInfo> = components.iter().filter(|component| component.level == level && component.matches(&filter)).collect();
|
||||
if members.is_empty() {
|
||||
continue;
|
||||
}
|
||||
members.sort_by_cached_key(|component| component.name.to_lowercase());
|
||||
let key = TreeKey::Level(level);
|
||||
let shown = filtering || open.is_open(&key);
|
||||
rows.push(TreeRow { key, label: level.title().to_owned(), depth: 0, group: true, open: shown });
|
||||
if shown {
|
||||
rows.extend(members.into_iter().map(|component| TreeRow {
|
||||
key: TreeKey::Component(component.type_name),
|
||||
label: component.name.clone(),
|
||||
depth: 1,
|
||||
group: false,
|
||||
open: false,
|
||||
}));
|
||||
}
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
/// The groups of `rows`, for an Alt-click that opens or closes every group.
|
||||
pub fn groups(rows: &[TreeRow]) -> Vec<TreeKey> {
|
||||
rows.iter().filter(|row| row.group).map(|row| row.key.clone()).collect()
|
||||
}
|
||||
|
||||
/// `rows` as the display order of the list.
|
||||
pub struct TreeRows<'a>(&'a [TreeRow]);
|
||||
|
||||
impl<'a> TreeRows<'a> {
|
||||
/// The display order of `rows`.
|
||||
pub fn new(rows: &'a [TreeRow]) -> Self {
|
||||
TreeRows(rows)
|
||||
}
|
||||
}
|
||||
|
||||
impl DisplayOrder<TreeKey> for TreeRows<'_> {
|
||||
fn len(&self) -> usize {
|
||||
self.0.len()
|
||||
}
|
||||
|
||||
fn key(&self, at: usize) -> TreeKey {
|
||||
self.0[at].key.clone()
|
||||
}
|
||||
|
||||
fn depth(&self, at: usize) -> usize {
|
||||
self.0[at].depth
|
||||
}
|
||||
|
||||
fn has_children(&self, at: usize) -> bool {
|
||||
self.0[at].group
|
||||
}
|
||||
|
||||
fn open(&self, at: usize) -> bool {
|
||||
self.0[at].open
|
||||
}
|
||||
|
||||
fn text(&self, at: usize) -> Option<Cow<'_, str>> {
|
||||
Some(Cow::Borrowed(self.0[at].label.as_str()))
|
||||
}
|
||||
}
|
||||
|
||||
impl ItemSource<TreeKey> for TreeRows<'_> {}
|
||||
@@ -0,0 +1,10 @@
|
||||
//! The viewer's integration tests: one binary, run by `libtest-mimic` over the registered trials.
|
||||
|
||||
mod overview;
|
||||
mod viewer;
|
||||
|
||||
use craft_ui_gallery::testing::registered;
|
||||
|
||||
fn main() {
|
||||
craft_ui::testing::run(module_path!(), env!("CARGO_PKG_NAME"), ®istered());
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
//! The Overview: the cards of a level, live.
|
||||
|
||||
use craft_settings::{Location, OpenOptions, SettingsStore};
|
||||
use craft_ui::runtime::access::Role;
|
||||
use craft_ui::shell::app::ShellApp;
|
||||
use craft_ui::testing::{Fixture, pointer, trial};
|
||||
use craft_ui_gallery::chrome::{Gallery, Persisted};
|
||||
use craft_ui_gallery::viewer::{Catalog, GallerySettings};
|
||||
use egui::Vec2;
|
||||
|
||||
fn gallery_at(level: &str) -> Gallery {
|
||||
gallery_filtered(level, "")
|
||||
}
|
||||
|
||||
fn gallery_filtered(level: &str, filter: &str) -> Gallery {
|
||||
let (mut store, report) = SettingsStore::<GallerySettings>::open_with(OpenOptions::new(Location::Memory));
|
||||
let mut settings = store.get().clone();
|
||||
settings.level = level.to_owned();
|
||||
settings.filter = filter.to_owned();
|
||||
store.set(settings);
|
||||
Gallery::new(Catalog::linked(), Persisted::new(store, &report))
|
||||
}
|
||||
|
||||
/// Every level opens in the Overview and runs all its cards.
|
||||
#[trial]
|
||||
fn every_level_of_the_overview_runs_its_cards() {
|
||||
for level in ["Primitives", "Controls", "Composites", "Patterns", "Shells"] {
|
||||
let mut gallery = gallery_at(level);
|
||||
let mut fixture = Fixture::new(move |ui| gallery.ui(ui));
|
||||
fixture.room(Vec2::new(1400.0, 900.0)).settle();
|
||||
assert!(fixture.by_label("Open").is_some(), "{level} has cards");
|
||||
}
|
||||
}
|
||||
|
||||
/// The registered type name of the component listed as `name`.
|
||||
fn type_of(name: &str) -> &'static str {
|
||||
Catalog::linked().components.iter().find(|component| component.name == name).unwrap_or_else(|| panic!("{name} is listed")).type_name
|
||||
}
|
||||
|
||||
fn painted(fixture: &Fixture, text: &str) -> bool {
|
||||
fixture.texts().iter().any(|run| run.text == text)
|
||||
}
|
||||
|
||||
fn openers(fixture: &Fixture) -> usize {
|
||||
fixture.texts().iter().filter(|run| run.text == "Show dialog").count()
|
||||
}
|
||||
|
||||
/// A dialog in an embedded shell of the story's own is out of the story's measure; the card still starts it closed
|
||||
/// before anything of it paints, opens it by the button, and shows the button again once the story closed both.
|
||||
#[trial]
|
||||
fn dialogs_in_a_storys_own_shell_start_closed_and_close_back_to_the_opener() {
|
||||
let (mut store, report) = SettingsStore::<GallerySettings>::open_with(OpenOptions::new(Location::Memory));
|
||||
let mut settings = store.get().clone();
|
||||
settings.level = "Shells".to_owned();
|
||||
settings.filter = "AppShell".to_owned();
|
||||
settings.stories.insert(type_of("AppShell").to_owned(), "app_shell_dialogs_in_regions".to_owned());
|
||||
store.set(settings);
|
||||
let mut gallery = Gallery::new(Catalog::linked(), Persisted::new(store, &report));
|
||||
let mut fixture = Fixture::new(move |ui| gallery.ui(ui));
|
||||
fixture.room(Vec2::new(1400.0, 900.0)).idle(1);
|
||||
let over = fixture.by_label("Open").expect("the card's Open").rect.center();
|
||||
let high = fixture.shown().height() / 5.0;
|
||||
assert_eq!(openers(&fixture), 1, "the picked story shows its opener");
|
||||
assert!(!painted(&fixture, "Snap to grid"), "nothing of the dialogs paints before the opener is pressed");
|
||||
let opener = fixture.by_label("Show dialog").expect("the opener");
|
||||
fixture.click(&opener).settle();
|
||||
assert!(painted(&fixture, "Snap to grid"), "the opener opens the dialogs");
|
||||
assert_eq!(openers(&fixture), 0, "the opener gives way to the story");
|
||||
// The story now takes a view's height under the opener's place: the wheel brings its dialogs up into view.
|
||||
for _ in 0..60 {
|
||||
if fixture.by_label("Close").is_some_and(|close| close.rect.top() < 2.0 * high) {
|
||||
break;
|
||||
}
|
||||
fixture.frame(vec![pointer::moved(over)]).frame(vec![pointer::wheel(-120.0)]).idle(1);
|
||||
}
|
||||
for _ in 0..2 {
|
||||
let close = fixture.by_label("Close").expect("a dialog's close button");
|
||||
fixture.click(&close).settle();
|
||||
// The exit fade runs on the fixture's clock.
|
||||
fixture.advance(1.0).settle();
|
||||
}
|
||||
assert!(!painted(&fixture, "Snap to grid"), "both dialogs closed");
|
||||
assert_eq!(openers(&fixture), 1, "closing the story's dialogs brings the opener back");
|
||||
}
|
||||
|
||||
/// Regression: the wheel over a canvas card went to its story and the Overview stopped scrolling; inside a
|
||||
/// card the wheel takers take the wheel only while focused or armed, so it scrolls the Overview.
|
||||
#[trial]
|
||||
fn the_wheel_over_a_card_scrolls_the_overview() {
|
||||
// The canvas overlays are Primitives.
|
||||
let mut gallery = gallery_at("Primitives");
|
||||
let mut fixture = Fixture::new(move |ui| gallery.ui(ui));
|
||||
fixture.room(Vec2::new(1400.0, 900.0)).settle();
|
||||
let visible = fixture.shown();
|
||||
let story = fixture
|
||||
.by_role(Role::CANVAS)
|
||||
.into_iter()
|
||||
.find(|t| visible.contains_rect(t.rect) && t.rect.height() > 40.0)
|
||||
.expect("a canvas card is in view");
|
||||
let title = fixture.by_label("Open").expect("a card header has Open").rect.min.y;
|
||||
fixture.frame(vec![pointer::moved(story.center())]).frame(vec![pointer::wheel(-120.0)]).settle();
|
||||
let after = fixture.by_label("Open").expect("a card header has Open").rect.min.y;
|
||||
assert!(after < title, "the wheel over a canvas card scrolled the Overview: {title} -> {after}");
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
//! The viewer's own logic: default and saved layouts, and the crates that register components.
|
||||
|
||||
use craft_ui::testing::trial;
|
||||
use craft_ui_gallery::viewer::{PanelId, Workspace, default_for, load_layout, open_tabs, save_layout};
|
||||
|
||||
const COMPONENTS: [PanelId; 6] = [PanelId::Components, PanelId::Stories, PanelId::Properties, PanelId::Inspect, PanelId::Overview, PanelId::Tokens];
|
||||
const THEME: [PanelId; 5] = [PanelId::Preview, PanelId::Detail, PanelId::Problems, PanelId::AppSizes, PanelId::Tokens];
|
||||
|
||||
/// Regression: a workspace's default layout that held another workspace's panel, or lost one of its own, opened the
|
||||
/// gallery with a missing or foreign panel.
|
||||
#[trial]
|
||||
fn each_default_layout_is_valid_and_holds_exactly_its_workspaces_panels() {
|
||||
for (workspace, panels) in [(Workspace::Components, &COMPONENTS[..]), (Workspace::Theme, &THEME[..])] {
|
||||
let layout = default_for(workspace);
|
||||
assert_eq!(layout.validate(), Ok(()));
|
||||
for panel in COMPONENTS.iter().chain(&THEME) {
|
||||
assert_eq!(layout.layout.contains(panel), panels.contains(panel), "{workspace:?} {panel:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Regression: a saved layout naming a component the catalog lacks, or lacking a default panel, must still load.
|
||||
#[trial]
|
||||
fn a_saved_layout_loads_without_the_components_the_catalog_lacks_and_with_every_default_panel() {
|
||||
let mut saved = default_for(Workspace::Components);
|
||||
let _ = saved.set_visible(PanelId::Component("craft_ui::buttons::link::Link"), true, Some(PanelId::Overview), false, |panel| panel.permissions());
|
||||
let _ = saved.set_visible(PanelId::Component("gone::Removed"), true, Some(PanelId::Overview), false, |panel| panel.permissions());
|
||||
let _ = saved.set_visible(PanelId::Stories, false, None, false, |_| craft_behavior::dock::Permissions::ALL);
|
||||
assert!(!saved.layout.contains(&PanelId::Stories));
|
||||
let loaded = load_layout(&save_layout(&saved), Workspace::Components, &|name| name == "craft_ui::buttons::link::Link");
|
||||
assert_eq!(loaded.validate(), Ok(()));
|
||||
assert_eq!(open_tabs(&loaded), ["craft_ui::buttons::link::Link"]);
|
||||
assert!(loaded.hidden.iter().all(|(panel, _)| !matches!(panel, PanelId::Component(_))));
|
||||
for panel in COMPONENTS {
|
||||
assert!(loaded.layout.contains(&panel), "{panel:?}");
|
||||
}
|
||||
let unreadable = load_layout("{\"layout\":", Workspace::Theme, &|_| true);
|
||||
assert_eq!(unreadable, default_for(Workspace::Theme));
|
||||
}
|
||||
|
||||
/// A crate with no registrations here was linked out, which in a release web build loses its stories.
|
||||
#[trial]
|
||||
fn every_linked_crate_registers() {
|
||||
let (counts, stories) = craft_ui_gallery::linked_counts();
|
||||
assert!(stories > 0);
|
||||
let empty: Vec<_> = counts.iter().filter(|(_, count)| *count == 0).collect();
|
||||
assert!(empty.is_empty(), "no registrations from {empty:?}");
|
||||
}
|
||||
Reference in New Issue
Block a user