From a5469d5446b83fca4b6b6da7ab022c2279f6d2d3 Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 11 Nov 2026 16:09:04 +0000 Subject: [PATCH] Gallery and story renderer: every component's stories, old/new comparison --- crates/story-render/Cargo.toml | 48 ++ crates/story-render/src/main.rs | 285 +++++++ crates/ui-gallery/Cargo.toml | 109 +++ crates/ui-gallery/index.html | 16 + crates/ui-gallery/src/bin/components-index.rs | 40 + crates/ui-gallery/src/bin/contract-api.rs | 714 ++++++++++++++++++ crates/ui-gallery/src/chrome/card.rs | 418 ++++++++++ crates/ui-gallery/src/chrome/describe.rs | 74 ++ crates/ui-gallery/src/chrome/dock.rs | 61 ++ crates/ui-gallery/src/chrome/mod.rs | 17 + crates/ui-gallery/src/chrome/options.rs | 103 +++ crates/ui-gallery/src/chrome/overview.rs | 306 ++++++++ crates/ui-gallery/src/chrome/panels.rs | 327 ++++++++ crates/ui-gallery/src/chrome/persist.rs | 130 ++++ crates/ui-gallery/src/chrome/shell.rs | 182 +++++ crates/ui-gallery/src/chrome/variants.rs | 189 +++++ crates/ui-gallery/src/lib.rs | 72 ++ crates/ui-gallery/src/main.rs | 43 ++ crates/ui-gallery/src/mock/commands.rs | 66 ++ crates/ui-gallery/src/mock/editor.rs | 249 ++++++ crates/ui-gallery/src/mock/mod.rs | 14 + crates/ui-gallery/src/mock/model.rs | 385 ++++++++++ crates/ui-gallery/src/mock/panels.rs | 248 ++++++ crates/ui-gallery/src/mock/stories.rs | 17 + crates/ui-gallery/src/mock/tools.rs | 116 +++ crates/ui-gallery/src/mock/words.rs | 9 + crates/ui-gallery/src/theme/browser.rs | 140 ++++ crates/ui-gallery/src/theme/chip.rs | 34 + crates/ui-gallery/src/theme/detail.rs | 187 +++++ crates/ui-gallery/src/theme/layer.rs | 165 ++++ crates/ui-gallery/src/theme/mod.rs | 21 + crates/ui-gallery/src/theme/problems.rs | 123 +++ crates/ui-gallery/src/theme/rows.rs | 198 +++++ crates/ui-gallery/src/theme/stories.rs | 63 ++ crates/ui-gallery/src/theme/subject.rs | 105 +++ crates/ui-gallery/src/theme/words.rs | 89 +++ crates/ui-gallery/src/viewer/appearance.rs | 141 ++++ crates/ui-gallery/src/viewer/catalog.rs | 240 ++++++ crates/ui-gallery/src/viewer/commands.rs | 17 + crates/ui-gallery/src/viewer/layout.rs | 214 ++++++ crates/ui-gallery/src/viewer/mod.rs | 21 + crates/ui-gallery/src/viewer/picks.rs | 94 +++ crates/ui-gallery/src/viewer/settings.rs | 134 ++++ crates/ui-gallery/src/viewer/state.rs | 244 ++++++ crates/ui-gallery/src/viewer/tree.rs | 131 ++++ crates/ui-gallery/tests/it/main.rs | 10 + crates/ui-gallery/tests/it/overview.rs | 104 +++ crates/ui-gallery/tests/it/viewer.rs | 48 ++ 48 files changed, 6761 insertions(+) create mode 100644 crates/story-render/Cargo.toml create mode 100644 crates/story-render/src/main.rs create mode 100644 crates/ui-gallery/Cargo.toml create mode 100644 crates/ui-gallery/index.html create mode 100644 crates/ui-gallery/src/bin/components-index.rs create mode 100644 crates/ui-gallery/src/bin/contract-api.rs create mode 100644 crates/ui-gallery/src/chrome/card.rs create mode 100644 crates/ui-gallery/src/chrome/describe.rs create mode 100644 crates/ui-gallery/src/chrome/dock.rs create mode 100644 crates/ui-gallery/src/chrome/mod.rs create mode 100644 crates/ui-gallery/src/chrome/options.rs create mode 100644 crates/ui-gallery/src/chrome/overview.rs create mode 100644 crates/ui-gallery/src/chrome/panels.rs create mode 100644 crates/ui-gallery/src/chrome/persist.rs create mode 100644 crates/ui-gallery/src/chrome/shell.rs create mode 100644 crates/ui-gallery/src/chrome/variants.rs create mode 100644 crates/ui-gallery/src/lib.rs create mode 100644 crates/ui-gallery/src/main.rs create mode 100644 crates/ui-gallery/src/mock/commands.rs create mode 100644 crates/ui-gallery/src/mock/editor.rs create mode 100644 crates/ui-gallery/src/mock/mod.rs create mode 100644 crates/ui-gallery/src/mock/model.rs create mode 100644 crates/ui-gallery/src/mock/panels.rs create mode 100644 crates/ui-gallery/src/mock/stories.rs create mode 100644 crates/ui-gallery/src/mock/tools.rs create mode 100644 crates/ui-gallery/src/mock/words.rs create mode 100644 crates/ui-gallery/src/theme/browser.rs create mode 100644 crates/ui-gallery/src/theme/chip.rs create mode 100644 crates/ui-gallery/src/theme/detail.rs create mode 100644 crates/ui-gallery/src/theme/layer.rs create mode 100644 crates/ui-gallery/src/theme/mod.rs create mode 100644 crates/ui-gallery/src/theme/problems.rs create mode 100644 crates/ui-gallery/src/theme/rows.rs create mode 100644 crates/ui-gallery/src/theme/stories.rs create mode 100644 crates/ui-gallery/src/theme/subject.rs create mode 100644 crates/ui-gallery/src/theme/words.rs create mode 100644 crates/ui-gallery/src/viewer/appearance.rs create mode 100644 crates/ui-gallery/src/viewer/catalog.rs create mode 100644 crates/ui-gallery/src/viewer/commands.rs create mode 100644 crates/ui-gallery/src/viewer/layout.rs create mode 100644 crates/ui-gallery/src/viewer/mod.rs create mode 100644 crates/ui-gallery/src/viewer/picks.rs create mode 100644 crates/ui-gallery/src/viewer/settings.rs create mode 100644 crates/ui-gallery/src/viewer/state.rs create mode 100644 crates/ui-gallery/src/viewer/tree.rs create mode 100644 crates/ui-gallery/tests/it/main.rs create mode 100644 crates/ui-gallery/tests/it/overview.rs create mode 100644 crates/ui-gallery/tests/it/viewer.rs diff --git a/crates/story-render/Cargo.toml b/crates/story-render/Cargo.toml new file mode 100644 index 000000000..ec7f82c13 --- /dev/null +++ b/crates/story-render/Cargo.toml @@ -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"] } diff --git a/crates/story-render/src/main.rs b/crates/story-render/src/main.rs new file mode 100644 index 000000000..b0dafe560 --- /dev/null +++ b/crates/story-render/src/main.rs @@ -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 -- --only --out ` writes, into ``: +//! `new---.png` for every story of the component, `new-.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>, + story: Option, + threads: usize, + width: f32, + room: f32, +} + +fn options() -> Result { + 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 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 { + 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 { + 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 = const { RefCell::new(String::new()) }; + /// A story is running on this thread. + static IN_STORY: std::cell::Cell = 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]) -> 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::().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>> = 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> = 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 +} diff --git a/crates/ui-gallery/Cargo.toml b/crates/ui-gallery/Cargo.toml new file mode 100644 index 000000000..e341a609c --- /dev/null +++ b/crates/ui-gallery/Cargo.toml @@ -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] diff --git a/crates/ui-gallery/index.html b/crates/ui-gallery/index.html new file mode 100644 index 000000000..ee0bba966 --- /dev/null +++ b/crates/ui-gallery/index.html @@ -0,0 +1,16 @@ + + + + + + craft-ui stories + + + + + + + diff --git a/crates/ui-gallery/src/bin/components-index.rs b/crates/ui-gallery/src/bin/components-index.rs new file mode 100644 index 000000000..184daefac --- /dev/null +++ b/crates/ui-gallery/src/bin/components-index.rs @@ -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 + } + } +} diff --git a/crates/ui-gallery/src/bin/contract-api.rs b/crates/ui-gallery/src/bin/contract-api.rs new file mode 100644 index 000000000..82eaa193a --- /dev/null +++ b/crates/ui-gallery/src/bin/contract-api.rs @@ -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, + is_type: bool, +} + +struct Reexport { + alias: String, + /// The absolute path, or `None` when it leaves the parsed crates. + target: Option>, + /// 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, + reexports: Vec, + children: Vec, +} + +struct Impl { + type_name: String, + module: String, + members: Vec, +} + +#[derive(Default)] +struct Tree { + modules: BTreeMap, + impls: Vec, + /// 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 = 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 = + 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::>().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::>() + .join(", ") + ), + } +} + +fn def_of(item: &Item) -> Option { + 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 = 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 { + let mut defs = Vec::new(); + let mut doc = String::new(); + let mut previous: Option = 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> { + let here_parts: Vec = here.split("::").map(str::to_owned).collect(); + let (first, rest) = path.split_first()?; + let mut base: Vec = 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, found: &mut Vec<(Vec, 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)>); + +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 = 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 = 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 { + let Some(entry) = self.modules.get(module) else { return Vec::new() }; + let mut names: Vec = 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 + } + } +} diff --git a/crates/ui-gallery/src/chrome/card.rs b/crates/ui-gallery/src/chrome/card.rs new file mode 100644 index 000000000..99cab2136 --- /dev/null +++ b/crates/ui-gallery/src/chrome/card.rs @@ -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, + /// The layout direction. + pub direction: Option, + /// The control size. + pub size: Option, +} + +/// 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, +} + +/// 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::() { + 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, +} + +/// 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, + /// The shown value as the story's component words it ([`StoryOutput::value_text`]). + pub value_text: Option, +} + +impl StoryBody { + /// The body of `story` on `surface`, in the window's look, with ungated wheel takers. + pub fn new(key: impl Into, 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::("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), + ) + } +} diff --git a/crates/ui-gallery/src/chrome/describe.rs b/crates/ui-gallery/src/chrome/describe.rs new file mode 100644 index 000000000..398c2a5a8 --- /dev/null +++ b/crates/ui-gallery/src/chrome/describe.rs @@ -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(", ") +} diff --git a/crates/ui-gallery/src/chrome/dock.rs b/crates/ui-gallery/src/chrome/dock.rs new file mode 100644 index 000000000..7c96510bd --- /dev/null +++ b/crates/ui-gallery/src/chrome/dock.rs @@ -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 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 { + match panel { + PanelId::Properties | PanelId::Inspect | PanelId::Tokens => { + vec![PanelRow::Command(GalleryCommands::ResetStories.into()), PanelRow::Command(GalleryCommands::ResetLayout.into())] + } + _ => Vec::new(), + } + } +} diff --git a/crates/ui-gallery/src/chrome/mod.rs b/crates/ui-gallery/src/chrome/mod.rs new file mode 100644 index 000000000..3f5a0496d --- /dev/null +++ b/crates/ui-gallery/src/chrome/mod.rs @@ -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; diff --git a/crates/ui-gallery/src/chrome/options.rs b/crates/ui-gallery/src/chrome/options.rs new file mode 100644 index 000000000..1b487778f --- /dev/null +++ b/crates/ui-gallery/src/chrome/options.rs @@ -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(ui: &mut Ui, caption: &'static str, value: &mut T, entries: &[Entry]) { + 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(ui: &mut Ui, caption: &'static str, value: &mut T, entries: &[Entry]) { + 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 { + 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> = 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; + } +} diff --git a/crates/ui-gallery/src/chrome/overview.rs b/crates/ui-gallery/src/chrome/overview.rs new file mode 100644 index 000000000..aac6e1379 --- /dev/null +++ b/crates/ui-gallery/src/chrome/overview.rs @@ -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, + /// The stories the card shows, in order. + pub stories: Vec, + /// 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 { + 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 { + 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> = + 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) { + 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> = groups.iter().map(|(level, _)| Entry::new(*level, level.title())).collect(); + let selected = selected_type(p); + let cards: Vec = 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 { + 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 { + 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 = 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); +} diff --git a/crates/ui-gallery/src/chrome/panels.rs b/crates/ui-gallery/src/chrome/panels.rs new file mode 100644 index 000000000..82a36a814 --- /dev/null +++ b/crates/ui-gallery/src/chrome/panels.rs @@ -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, + /// The open level groups. + pub open: &'a mut OpenSet, + /// 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>, + /// The selected component the tree last opened the level of. + pub tree_seen: &'a mut Option>, + /// 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, + /// The centre tab the Variants view is open in. + pub variants_tab: &'a mut Option, + /// 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, +} + +/// `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