Merge #2424: Restore the Home screen rail and empty-state card

This commit is contained in:
David Mann
2026-11-20 12:51:46 +01:00
4 changed files with 465 additions and 36 deletions
+219 -23
View File
@@ -6,29 +6,33 @@ mod stories;
use super::recent::{RecentFile, RecentSort, RecentView, Template, ThumbKey, sort_recent};
use super::words::ShellWords;
use crate::buttons::button::ButtonStyleKey;
use crate::buttons::{Button, Link};
use crate::choice::Segmented;
use crate::contract::{
ActivateOn, Bind, BodyCx, CollectionEvent, Entry, Gap, NoValue, Outcome, Pad, Pattern, Props, Remember as _, Scroll, SelectMode, Show as _,
ShowCollection as _, ShowContainer as _, Sizing, clicked,
};
use crate::display::{Divider, Icon};
use crate::display::{Divider, Icon, Text};
use crate::layout_components::{Row, Stack};
use crate::list::{List, ListRow, RowEvent, ThumbAspect, ThumbSize, TrailingFace, TrailingPart};
use crate::menu::{Menu, MenuItem};
use crate::notices::{Notice, NoticeLayout};
use crate::pickers::Select;
use crate::primitives::{CheckerArea, ContentPainterCx, IconSpec, Priority, ThumbPaint, ThumbRequest, ThumbSource, Thumbnails, paint_surround};
use crate::primitives::{
CheckerArea, ContentPainterCx, HAlign, IconSpec, Priority, RectSide, Rule, RuleKind, ThumbPaint, ThumbRequest, ThumbSource, Thumbnails,
paint_surround,
};
use crate::runtime::commands::{self, CommandRef, FireSource};
use crate::runtime::commands::{CommandSet as _, Commands as _};
use crate::runtime::env::{AgeStyle, Env, Label};
use crate::sections::Section;
use crate::style::{Corners, SurfaceKind, SurroundLook};
use crate::style::{Corners, StyleCx, SurfaceKind, SurroundLook, TypeRole};
use crate::tile_grid::{CaptionPlace, Tile, TileGrid, TilePartEvent};
use craft_behavior::{IconId, Proposal, SelectionChange, keyed};
use craft_theme::Variant;
use craft_theme::variant::Tone;
use egui::{CornerRadius, Rect, Response, Ui, Vec2};
use craft_theme::variant::{CustomVariant, Emphasis, RadiusStep, Tone, VariantLook};
use craft_theme::{Rgba, Tokens, Variant};
use egui::{CornerRadius, Rect, Response, Ui, Vec2, pos2, vec2};
use std::borrow::Cow;
use std::cell::RefCell;
use std::path::{Path, PathBuf};
@@ -39,10 +43,20 @@ const CARD_ZOOM: f32 = 2.0;
/// The width and height parts of a card's picture.
const PICTURE_WIDE: u16 = 16;
const PICTURE_HIGH: u16 = 9;
const HOME_RECENT_PICTURE_ASPECT: f32 = 3.0 / 2.0;
/// The number of recent files shown until `max_recent` says otherwise.
const RECENT_SHOWN: usize = 12;
const HOME_BREAKPOINT: f32 = 640.0;
const HOME_RAIL_WIDTH: f32 = 170.0;
const HOME_COMPACT_WIDTH: f32 = 520.0;
const HOME_DROP_WIDTH: f32 = 540.0;
const HOME_DROP_HEIGHT: f32 = 200.0;
const HOME_DROP_ICON: f32 = 34.0;
const HOME_DESKTOP_INSET: Vec2 = vec2(36.0, 54.0);
const HOME_DROP_LOOK: CustomVariant = CustomVariant::new::<ButtonStyleKey>("craft_ui.home-drop", home_drop_look);
/// The revealed part of a recent row that takes the file off the list.
const REMOVE: TrailingPart = TrailingPart::new(0);
@@ -172,6 +186,12 @@ pub struct StartScreen<'a> {
/// With no recent files, the Recent body is a drop card with this hint that opens a file on a click.
#[prop(into)]
drop_hint: Option<Label>,
home: Option<HomeLayout<'a>>,
}
struct HomeLayout<'a> {
title: Label,
footer_links: &'a [StartLink],
}
/// A link on the start screen's rail.
@@ -184,6 +204,7 @@ pub struct StartLink {
pub icon: Option<IconId>,
/// What the link does.
pub target: StartLinkTarget,
selected: bool,
}
/// What a [`StartLink`] does.
@@ -199,12 +220,18 @@ pub enum StartLinkTarget {
impl StartLink {
/// A link that opens `url`, shown as its tooltip.
pub fn url(label: impl Into<Label>, icon: Option<IconId>, url: impl Into<String>) -> Self {
StartLink { label: label.into(), icon, target: StartLinkTarget::Url(url.into()) }
StartLink { label: label.into(), icon, target: StartLinkTarget::Url(url.into()), selected: false }
}
/// A link that fires `command`.
pub fn command(label: impl Into<Label>, icon: Option<IconId>, command: impl Into<CommandRef>) -> Self {
StartLink { label: label.into(), icon, target: StartLinkTarget::Command(command.into()) }
StartLink { label: label.into(), icon, target: StartLinkTarget::Command(command.into()), selected: false }
}
/// Highlights this command link on a Home rail.
pub fn selected(mut self, selected: bool) -> Self {
self.selected = selected;
self
}
}
@@ -222,9 +249,17 @@ impl<'a> StartScreen<'a> {
thumbnails: None,
links: &[],
drop_hint: None,
home: None,
}
}
/// Uses a Home layout with a title above the page and a separate group of links at the bottom of its rail.
/// The navigation links come from [`Self::links`]. Narrow rooms put both groups below the content.
pub fn home_layout(mut self, title: impl Into<Label>, footer_links: &'a [StartLink]) -> Self {
self.home = Some(HomeLayout { title: title.into(), footer_links });
self
}
/// Cards, rows and templates ask `thumbnails.state(..)` for what they show; `source` gives each key's revision.
pub fn thumbnails(mut self, thumbnails: &'a Thumbnails<ThumbKey>, source: &'a dyn ThumbSource<ThumbKey>) -> Self {
self.thumbnails = Some((thumbnails, source));
@@ -341,7 +376,7 @@ fn read_events<K: Clone, E>(events: Vec<CollectionEvent<K, E>>, lead: &mut Optio
impl StartScreen<'_> {
/// Shows the page across the available room and reports what the user did.
pub fn show(self, ui: &mut Ui) -> StartOutput {
let StartScreen { view, sort, recent, pinned, templates, max_recent, now, thumbnails, links, drop_hint } = self;
let StartScreen { view, sort, recent, pinned, templates, max_recent, now, thumbnails, links, drop_hint, home } = self;
let env = Env::of(ui);
let collator = env.collator();
let words = env.words::<ShellWords>();
@@ -356,23 +391,28 @@ impl StartScreen<'_> {
let rail_stack = || Stack::new().gap(Gap::Tight).pad(Pad::Regular).label(words.start_links.clone());
let rail_body = |ui: &mut Ui| {
new_and_open(&page, ui);
new_and_open(&page, ui, Sizing::Content);
let _ = Divider::horizontal().show(ui);
link_items(ui, links);
link_items(ui, links, false);
};
let page_stack = || Stack::new().gap(Gap::Section).pad(Pad::Regular).fill_width();
// `beside` is whether the rail stands beside the page; without it New and Open lead the page and the links follow
// the sections.
let page_body = |ui: &mut Ui, cx: &mut BodyCx<'_>, beside: bool| {
let page_body = |ui: &mut Ui, cx: &mut BodyCx<'_>, beside: bool, drop_area: Option<(f32, bool)>| {
let current_view = view.borrow_mut().reborrow().read(cx).and_then(|held| held.same().copied()).unwrap_or_default();
let current_sort = sort.borrow_mut().reborrow().read(cx).and_then(|held| held.same().copied()).unwrap_or_default();
let mut files: Vec<RecentFile> = recent.iter().take(max_recent).cloned().collect();
sort_recent(&mut files, current_sort, &collator);
if !beside {
let _ = Row::new().gap(Gap::Tight).show(ui, |ui, _| new_and_open(&page, ui));
let _ = Row::new().gap(Gap::Tight).show(ui, |ui, _| new_and_open(&page, ui, Sizing::Content));
}
if let (true, Some(hint), Some((center, wide))) = (files.is_empty(), page.drop_hint, drop_area) {
home_drop(&page, ui, hint, center, wide);
} else {
let desktop_home = drop_area.is_some_and(|(_, wide)| wide);
recent_section(&page, ui, &view, &sort, current_view, &files, desktop_home);
}
recent_section(&page, ui, &view, &sort, current_view, &files);
if let Some(pinned) = pinned {
pinned_section(&page, ui, pinned);
}
@@ -380,15 +420,20 @@ impl StartScreen<'_> {
templates_section(&page, ui, templates);
}
if !beside && !links.is_empty() {
let _ = Stack::new().gap(Gap::Tight).label(words.start_links.clone()).show(ui, |ui, _| link_items(ui, links));
let _ = Stack::new().gap(Gap::Tight).label(words.start_links.clone()).show(ui, |ui, _| link_items(ui, links, false));
}
};
if let Some(home) = home {
let response = home.show(ui, &page, links, |ui, cx, center, wide| page_body(ui, cx, true, Some((center, wide))));
return StartOutput { response, actions: actions.into_inner() };
}
// The rail stands beside the sections when the room holds the rail, the gap and the sections' least width; a
// narrower page keeps New and Open in its row and lists the links after the sections.
let rail = !links.is_empty() && {
let rail_width = rail_stack().measure_in(ui, Proposal::Ideal, |ui, _| rail_body(ui)).x;
let sections_least = page_stack().measure_in(ui, Proposal::Min, |ui, cx| page_body(ui, cx, true)).x;
let sections_least = page_stack().measure_in(ui, Proposal::Min, |ui, cx| page_body(ui, cx, true, None)).x;
ui.available_width() >= rail_width + env.tokens.space.gap.section + sections_least
};
@@ -401,30 +446,174 @@ impl StartScreen<'_> {
if rail {
let _ = Row::new().gap(Gap::Section).fill_width().show(ui, |ui, _| {
let _ = rail_stack().show(ui, |ui, _| rail_body(ui));
let _ = page_stack().show(ui, |ui, cx| page_body(ui, cx, true));
let _ = page_stack().show(ui, |ui, cx| page_body(ui, cx, true, None));
});
} else {
let _ = page_stack().show(ui, |ui, cx| page_body(ui, cx, false));
let _ = page_stack().show(ui, |ui, cx| page_body(ui, cx, false, None));
}
});
StartOutput { response: shown.output, actions: actions.into_inner() }
}
}
impl HomeLayout<'_> {
fn show(&self, ui: &mut Ui, page: &Page<'_>, links: &[StartLink], mut sections: impl FnMut(&mut Ui, &mut BodyCx<'_>, f32, bool)) -> Response {
// Keep the opening gesture on the fixed surface, outside the two independent scrolling regions.
Stack::new()
.fill()
.senses_surface()
.show(ui, |ui, cx| {
if cx.surface_double_pressed() {
page.push(StartAction::Open);
}
let room = ui.available_rect_before_wrap();
let wide = room.width() >= HOME_BREAKPOINT;
let content = if wide {
let (rail, content) = home_columns(room, page.env.direction.is_rtl());
self.rail(ui, page, links, rail);
content
} else {
Rect::from_center_size(room.center(), vec2(room.width().min(HOME_COMPACT_WIDTH), room.height()))
};
let gap = if wide { Gap::CardRow } else { Gap::Section };
let _ =
Stack::new().id_salt("home-page").fill().pad(Pad::Regular).gap(gap).scroll(Scroll::vertical()).show_at(ui, content, |ui, cx| {
let top = ui.available_rect_before_wrap().top();
if !wide {
let _ = Row::new().gap(Gap::Tight).fill_width().show(ui, |ui, _| new_and_open(page, ui, Sizing::FillWidth));
}
let _ = Text::new(self.title.clone()).role(TypeRole::Display).show(ui);
home_divider(ui);
sections(ui, cx, top + content.height() / 2.0, wide);
if !wide {
home_links(ui, page, "home-nav", links, Gap::Tight);
home_links(ui, page, "home-footer", self.footer_links, Gap::Tight);
}
});
})
.output
}
fn rail(&self, ui: &mut Ui, page: &Page<'_>, links: &[StartLink], rect: Rect) {
let stack = || Stack::new().id_salt("home-rail").pad(Pad::Regular).gap(Gap::Section);
let top = |ui: &mut Ui| {
let _ = Stack::new().id_salt("home-actions").gap(Gap::Stack).fill_width().show(ui, |ui, _| {
new_and_open(page, ui, Sizing::FillWidth);
});
home_divider(ui);
home_links(ui, page, "home-nav", links, Gap::Section);
};
let footer = |ui: &mut Ui| {
if !self.footer_links.is_empty() {
home_divider(ui);
home_links(ui, page, "home-footer", self.footer_links, Gap::Section);
}
};
// A short window scrolls the entire rail so the fixed footer cannot crowd the opening buttons out.
let footer_fits = !self.footer_links.is_empty()
&& stack()
.measure_in(ui, Proposal::Ideal, |ui, _| {
top(ui);
footer(ui);
})
.y
<= rect.height();
let rail = stack().fill().scroll(Scroll::vertical());
if footer_fits {
let _ = rail.footer(|ui, _| footer(ui)).show_at(ui, rect, |ui, _| top(ui));
} else {
let _ = rail.show_at(ui, rect, |ui, _| {
top(ui);
footer(ui);
});
}
}
}
fn home_columns(room: Rect, rtl: bool) -> (Rect, Rect) {
// Leave enough height for the two scroll regions on short windows.
let inset_y = HOME_DESKTOP_INSET.y.min((room.height() - HOME_DROP_HEIGHT).max(0.0) / 2.0);
let room = room.shrink2(vec2(HOME_DESKTOP_INSET.x, inset_y));
let gap = HOME_DESKTOP_INSET.x;
if rtl {
let rail = Rect::from_min_max(pos2(room.right() - HOME_RAIL_WIDTH, room.top()), room.max);
let content = Rect::from_min_max(room.min, pos2(rail.left() - gap, room.bottom()));
(rail, content)
} else {
let rail = Rect::from_min_max(room.min, pos2(room.left() + HOME_RAIL_WIDTH, room.bottom()));
let content = Rect::from_min_max(pos2(rail.right() + gap, room.top()), room.max);
(rail, content)
}
}
fn home_links(ui: &mut Ui, page: &Page<'_>, id: &'static str, links: &[StartLink], gap: Gap) {
if !links.is_empty() {
let _ = Stack::new().id_salt(id).gap(gap).label(page.words.start_links.clone()).fill_width().show(ui, |ui, _| link_items(ui, links, true));
}
}
fn home_divider(ui: &mut Ui) {
let env = Env::of(ui);
let style = StyleCx::of_env(ui.ctx(), &env);
let mut look = style.rule(RuleKind::Divider);
look.color = style.color(home_edge(&env.tokens)).egui();
let scale = ui.ctx().pixels_per_point();
let room = ui.available_rect_before_wrap();
let line = Rect::from_min_size(room.min, vec2(room.width(), look.width.points(scale)));
let _ = Stack::new().show_at_taking_room(ui, line, |ui, _| ui.painter().extend(Rule::edge(&look, line, RectSide::Top, scale)));
}
/// Panel dividers can match the canvas surround exactly, so use existing muted ink on that surround.
fn home_edge(tokens: &Tokens) -> Rgba {
let color = &tokens.color;
if color.line.divider == color.surface.canvas { color.text.faint } else { color.line.divider }
}
fn home_drop_look(tokens: &Tokens) -> VariantLook {
let mut look = Variant::SECONDARY.resolve(tokens).radius(RadiusStep::Control);
if let Some(edge) = &mut look.edge {
edge.rest = home_edge(tokens);
}
look
}
fn home_drop(page: &Page<'_>, ui: &mut Ui, hint: &Label, center: f32, wide: bool) {
let room = ui.available_rect_before_wrap();
let width = HOME_DROP_WIDTH.min(room.width());
let top = (center - HOME_DROP_HEIGHT / 2.0).max(room.top());
let slot = Rect::from_min_max(room.min, pos2(room.right(), top + HOME_DROP_HEIGHT));
let left = room.center().x - width / 2.0;
let card = Rect::from_min_max(pos2(left, top), pos2(left + width, slot.bottom()));
let _ = Stack::new().id_salt("home-drop").show_at_taking_room(ui, slot, |ui, _| {
if clicked(&Button::new(hint.clone()).id_salt("drop").variant(Variant::Custom(HOME_DROP_LOOK)).show_at(ui, card)) {
page.push(StartAction::Open);
}
let tokens = &page.env.tokens;
let (side, offset) = if wide {
(HOME_DROP_ICON, (HOME_DROP_ICON + tokens.typography.label.line_height) / 2.0 + tokens.space.gap.stack)
} else {
let side = tokens.size.icon.lg;
(side, side + tokens.space.gap.tight)
};
let icon = Rect::from_center_size(card.center() - vec2(0.0, offset), Vec2::splat(side));
let _ = Icon::new(IconSpec::svg(IconId::new("image"))).show_at(ui, icon);
});
}
/// New and Open, the first Tab stops of the page.
fn new_and_open(page: &Page<'_>, ui: &mut Ui) {
fn new_and_open(page: &Page<'_>, ui: &mut Ui, sizing: Sizing) {
let words = page.words;
if clicked(&Button::new(words.new.clone()).id_salt("new").variant(Variant::PRIMARY).show(ui)) {
if clicked(&Button::new(words.new.clone()).id_salt("new").variant(Variant::PRIMARY).sizing(sizing).show(ui)) {
page.push(StartAction::New);
}
if clicked(&Button::new(words.open.clone()).id_salt("open").show(ui)) {
if clicked(&Button::new(words.open.clone()).id_salt("open").sizing(sizing).show(ui)) {
page.push(StartAction::Open);
}
}
/// The links, one under another: a URL opens through its `Link` (the URL is its tooltip), a command fires as a
/// pointer activation.
fn link_items(ui: &mut Ui, links: &[StartLink]) {
fn link_items(ui: &mut Ui, links: &[StartLink], home: bool) {
for (at, link) in links.iter().enumerate() {
match &link.target {
StartLinkTarget::Url(url) => {
@@ -437,6 +626,10 @@ fn link_items(ui: &mut Ui, links: &[StartLink]) {
}
StartLinkTarget::Command(command) => {
let mut button = Button::new(link.label.clone()).id_salt(("start-link", at));
if home {
let variant = if link.selected { Variant::look(Emphasis::Soft, Tone::Accent) } else { Variant::GHOST };
button = button.variant(variant).align(HAlign::Start).sizing(Sizing::FillWidth);
}
if let Some(icon) = &link.icon {
button = button.icon(icon.clone());
}
@@ -455,6 +648,7 @@ fn recent_section(
sort: &RefCell<Bind<'_, RecentSort>>,
current: RecentView,
files: &[RecentFile],
desktop_home: bool,
) {
let words = page.words;
let modes = [
@@ -507,7 +701,9 @@ fn recent_section(
let file_of = |path: &PathBuf| files.iter().find(|file| &file.path == path);
let source = keyed(files, |file: &RecentFile| file.path.clone()).with_text(|file| Cow::Borrowed(file.name.as_str()));
let (response, (opened, removed)) = if current == RecentView::Grid {
let out = page.grid::<PathBuf>(words.recent.clone(), true).show_items(ui, &source, &mut |path, _| {
let grid = page.grid::<PathBuf>(words.recent.clone(), true);
let grid = if desktop_home { grid.aspect(HOME_RECENT_PICTURE_ASPECT).regular_card_padding() } else { grid };
let out = grid.show_items(ui, &source, &mut |path, _| {
let Some(file) = file_of(path) else { return Tile::new(Label::Empty) };
page.tile(&file.name, page.age(file.opened), ThumbKey::Recent(file.path.clone()))
.corner_action(IconId::new("close"), StartRecentCommands::Remove)
+219
View File
@@ -90,3 +90,222 @@ fn the_recent_menu_offers_show_in_folder_where_the_platform_can_reveal() {
assert!(fixture.by_label("Remove from Recent").is_some(), "a right click on a recent file opens its menu");
assert_eq!(fixture.by_label("Show in Folder").is_some(), craft_platform::open::CAN_REVEAL);
}
fn home_screen(has_recent: bool) -> (Fixture, Log) {
let log: Log = Rc::default();
let seen = Rc::clone(&log);
let files: Vec<_> = has_recent.then(|| RecentFile::new("/tmp/work/Poster.psd", "Poster.psd")).into_iter().collect();
let links = [StartLink::command("Home", None, "window.home").selected(true), StartLink::url("Learn", None, "https://example.test/learn")];
let footer = [
StartLink::url("Website", None, "https://example.test"),
StartLink::url("Discord", None, "https://example.test/chat"),
StartLink::url("GitHub", None, "https://example.test/code"),
];
let (mut view, mut sort) = (RecentView::Grid, RecentSort::Opened);
let fixture = Fixture::new(move |ui| {
let out = StartScreen::new(Bind::bound(&mut view), Bind::bound(&mut sort), &files)
.links(&links)
.home_layout("Photo app", &footer)
.drop_hint("Drop an image")
.show(ui);
seen.borrow_mut().extend(out.actions);
});
(fixture, log)
}
/// At a desktop width the navigation stays left of the recent files and the community links sit below it.
#[trial]
fn the_home_screen_places_navigation_to_the_left_of_recent_files() {
let (mut fixture, _) = home_screen(true);
fixture.room(egui::vec2(1100.0, 700.0)).settle();
let rect = |label| fixture.by_label(label).expect(label).rect;
let recent = rect("Recent");
let new = rect("New…");
let open = rect("Open…");
assert!((new.width() - open.width()).abs() < 1.0);
assert!(open.top() - new.bottom() >= 6.0, "New and Open have room between them");
assert!(rect("Home").top() - open.bottom() >= 24.0, "the divider separates the actions from navigation");
assert!(recent.left() - new.right() >= 36.0, "the rail is separated from the content");
assert!(rect("Photo app").top() >= 54.0);
assert!(recent.top() - rect("Photo app").bottom() >= 32.0, "the title rule has space above and below");
for label in ["Home", "Learn", "Website", "Discord", "GitHub"] {
let navigation = rect(label);
assert!(navigation.right() < recent.left(), "{label} {navigation:?} must be left of Recent {recent:?}");
}
assert!(rect("Home").bottom() < rect("Learn").top());
assert!(rect("Website").top() > fixture.shown().center().y);
assert!(rect("Discord").top() - rect("Website").bottom() >= 6.0);
assert!(rect("GitHub").top() - rect("Discord").bottom() >= 6.0);
}
/// A desktop Recent tile gives its picture and filename room while keeping the whole card clickable.
#[trial]
fn desktop_home_recent_cards_give_the_picture_and_caption_room() {
use egui::{Shape, pos2, vec2};
let (mut fixture, log) = home_screen(true);
fixture.room(vec2(1100.0, 700.0)).settle();
let card = fixture.by_label("Poster.psd").expect("the recent file shows").rect;
let shapes = fixture.frame_shapes();
let picture = shapes
.iter()
.find_map(|shape| match shape {
Shape::Rect(shape)
if card.contains_rect(shape.rect)
&& shape.rect.width() > card.width() * 0.8
&& shape.rect.width() < card.width() - 1.0
&& shape.rect.height() > 100.0 =>
{
Some(shape.rect)
}
_ => None,
})
.expect("the tile paints an inset picture well");
let caption = shapes
.iter()
.find_map(|shape| match shape {
Shape::Text(text) if text.galley.text() == "Poster.psd" => Some(text.pos),
_ => None,
})
.expect("the tile paints its filename");
assert!((390.0..400.0).contains(&card.width()), "{card:?}");
assert!(card.height() >= 285.0, "there is more vertical room: {card:?}");
assert!(picture.left() - card.left() >= 8.0, "the picture has horizontal padding: {picture:?}");
assert!(picture.top() - card.top() >= 8.0, "the picture has top padding: {picture:?}");
assert!(caption.x - card.left() >= 8.0 && caption.y - picture.bottom() >= 8.0, "the filename has space: {caption:?}");
log.borrow_mut().clear();
fixture.click_at(pos2(card.left() + 3.0, card.top() + 3.0)).settle();
assert_eq!(*log.borrow(), vec![StartAction::OpenRecent(PathBuf::from("/tmp/work/Poster.psd"))]);
}
/// The Home surround can have the same colour as ordinary separators. The title and drop card still need visible ink.
#[trial]
fn the_home_title_and_drop_card_keep_their_outlines_visible() {
use craft_ui::runtime::env::{Env, RootEnv};
use craft_ui::testing::Frames;
use egui::{Color32, Shape, vec2};
let ppp = 1.25;
for mode in [craft_theme::Mode::Light, craft_theme::Mode::Dark] {
let mut frames = Frames::new();
frames.root(RootEnv::default().mode(mode));
frames.screen(vec2(1100.0, 700.0));
frames.pixels_per_point(ppp);
let (mut view, mut sort) = (RecentView::Grid, RecentSort::Opened);
let mut canvas = Color32::TRANSPARENT;
frames.record_paint();
frames.frame(Vec::new(), |ui| {
canvas = Color32::from(craft_theme::Srgba::from(Env::of(ui).tokens.color.surface.canvas));
let _ = StartScreen::new(Bind::bound(&mut view), Bind::bound(&mut sort), &[])
.home_layout("Photo app", &[])
.drop_hint("Drop an image")
.show(ui);
});
let tree = frames.tree();
let title =
tree.keys().into_iter().find(|key| tree.name_of(*key) == Some("Photo app")).and_then(|key| tree.bounds_of(key)).expect("the Home title");
let mut paint = frames.take_paint().expect("the frame drew Home");
paint.textures_delta.clear();
let rule = paint
.shapes
.iter()
.find_map(|shape| match &shape.shape {
Shape::LineSegment { points, stroke }
if (points[1].x - points[0].x) > 800.0 && (title.bottom()..title.bottom() + 32.0).contains(&points[0].y) =>
{
Some(stroke)
}
_ => None,
})
.expect("a full-width title rule");
assert!(rule.color.a() != 0 && rule.color != canvas, "the title rule contrasts with the {mode:?} surround");
assert!((rule.width * ppp - 1.0).abs() < 0.01);
let card = paint
.shapes
.iter()
.find_map(|shape| match &shape.shape {
Shape::Rect(rect)
if (rect.rect.width() - 540.0).abs() < 1.0 && (rect.rect.height() - 200.0).abs() < 1.0 && !rect.stroke.is_empty() =>
{
Some(rect)
}
_ => None,
})
.expect("the drop card has an outline");
assert!(card.stroke.color != canvas, "the drop card contrasts with the {mode:?} surround");
assert!(card.corner_radius.nw < 12, "the drop card uses control corners");
}
}
/// A one-point change at the breakpoint switches from a centred page to the reading-start rail.
#[trial]
fn the_home_screen_changes_layout_at_640_points_in_both_directions() {
for rtl in [false, true] {
let direction = if rtl { craft_i18n::Direction::Rtl } else { craft_i18n::Direction::Ltr };
let (mut fixture, _) = home_screen(true);
fixture.direction(direction).room(egui::vec2(639.0, 700.0)).settle();
let rect = |label| fixture.by_label(label).expect(label).rect;
let actions = rect("New…").union(rect("Open…"));
assert!((rect("New…").center().y - rect("Open…").center().y).abs() < 1.0);
assert!(actions.width() <= 520.0 && (actions.center().x - 319.5).abs() < 1.0);
assert!(rect("Home").top() > rect("Recent").top());
fixture.room(egui::vec2(640.0, 700.0)).settle();
let rect = |label| fixture.by_label(label).expect(label).rect;
assert!(rect("New…").bottom() < rect("Open…").top());
let (nav, content) = (rect("Home"), rect("Recent"));
assert!(if rtl { nav.left() > content.right() } else { nav.right() < content.left() }, "RTL {rtl}: {nav:?} beside {content:?}");
}
}
/// A short desktop rail scrolls as a unit without changing the page beside it.
#[trial]
fn a_short_home_rail_scrolls_to_its_community_links() {
let (mut fixture, _) = home_screen(true);
fixture.room(egui::vec2(1100.0, 120.0)).settle();
let recent = fixture.by_label("Recent").expect("the page is visible").rect;
let opening = fixture.by_label("New…").expect("the rail's first button");
assert!(fixture.shown().contains(opening.center()));
assert!(!fixture.by_label("GitHub").is_some_and(|link| fixture.shown().contains(link.center())));
fixture.frame(vec![moved(opening.center())]).frame(vec![craft_ui::testing::pointer::wheel(-400.0)]).settle();
let link = fixture.by_label("GitHub").expect("the end of the rail can be scrolled into view");
assert!(fixture.shown().contains(link.center()), "the link sits inside the short rail: {:?}", link.rect);
assert_eq!(fixture.by_label("Recent").expect("the page stays visible").rect, recent);
}
/// The empty card has its own pointer and keyboard activation and the blank page opens only on a double-click.
#[trial]
fn the_home_drop_card_is_bounded_and_opens_by_keyboard_or_pointer() {
use egui::{Key, Modifiers};
let (mut fixture, log) = home_screen(false);
fixture.room(egui::vec2(1100.0, 700.0)).settle();
let card = fixture.by_label("Drop an image").expect("an empty page has a drop target");
assert!((card.rect.width() - 540.0).abs() < 1.0 && (card.rect.height() - 200.0).abs() < 1.0, "{:?}", card.rect);
assert!((card.center().y - fixture.shown().center().y).abs() < 24.0, "{:?}", card.rect);
fixture.click(&card).settle();
assert_eq!(*log.borrow(), vec![StartAction::Open]);
log.borrow_mut().clear();
let corner = fixture.shown().max - egui::vec2(30.0, 30.0);
fixture.click_at(corner).click_at(corner).settle();
assert_eq!(*log.borrow(), vec![StartAction::Open], "blank room opens once");
let (mut fixture, log) = home_screen(false);
fixture.room(egui::vec2(1100.0, 700.0)).settle();
let card = fixture.by_label("Drop an image").expect("a separate keyboard target");
let focused = |fixture: &Fixture| fixture.focused().and_then(|id| fixture.node_of(id)).is_some_and(|target| target.node == card.node);
for _ in 0..10 {
if focused(&fixture) {
break;
}
fixture.key(Key::Tab, Modifiers::NONE).settle();
}
assert!(focused(&fixture), "Tab reaches the drop target");
fixture.key(Key::Enter, Modifiers::NONE).settle();
assert_eq!(*log.borrow(), vec![StartAction::Open]);
}
+10 -6
View File
@@ -149,13 +149,13 @@ struct GridSizes {
}
impl GridSizes {
fn of(cx: &StyleCx<'_>, card: bool, rows: RowHeight) -> GridSizes {
fn of(cx: &StyleCx<'_>, card: bool, rows: RowHeight, regular_card_padding: bool) -> GridSizes {
let spacing =
ArrangeSpacing::new(if card { cx.tokens.space.gap.section } else { cx.tokens.space.gap.stack }, cx.tokens.space.gap.inline, rows.of(cx));
GridSizes {
card: cx.tokens.size.thumb.card,
thumbs: [cx.tokens.size.thumb.sm, cx.tokens.size.thumb.md, cx.tokens.size.thumb.lg],
around: Tile::around(cx, card),
around: Tile::around(cx, card, regular_card_padding),
spacing,
// Bare tiles sit with no gap between them: the room around each picture keeps them apart.
bare_spacing: if card { spacing } else { ArrangeSpacing { gap: 0.0, ..spacing } },
@@ -239,6 +239,9 @@ pub struct TileGrid<'a, K: Clone + Eq + Hash + Send + Sync + 'static> {
/// Tiles are framed cards: the picture inset in a raised surface with the name and detail at the reading start.
#[prop(flag)]
card: bool,
/// Framed cards use the theme's regular padding around their picture and caption.
#[prop(flag)]
regular_card_padding: bool,
/// The headers over runs of tiles, in display order.
#[prop]
groups: &'a [TileGroup<K>],
@@ -311,6 +314,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> TileGrid<'a, K> {
caption: CaptionPlace::Below,
detail_line: false,
card: false,
regular_card_padding: false,
groups: &[],
collapsible: false,
tail: &[],
@@ -391,7 +395,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> TileGrid<'a, K> {
/// The layout of this pass: `previous` when it was made from the same recipe, else a new arrangement. A card is
/// the picture plus what the tile adds around it in every tiling.
fn laid_out(&self, previous: Option<GridLayout>, source: &dyn ItemSource<K>, width: f32, item: Option<Vec2>, cx: &StyleCx<'_>) -> GridLayout {
let style = GridSizes::of(cx, self.card, self.items.row_height);
let style = GridSizes::of(cx, self.card, self.items.row_height, self.regular_card_padding);
let spacing = style.spacing(self.caption);
let around = style.around.get(self.caption, self.detail_line);
// A card never outgrows the grid: in a column narrower than a card the card takes the column.
@@ -793,7 +797,7 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> Collection for TileGrid<'_, K
fn dress_inputs(&self) -> u64 {
use std::hash::{Hash as _, Hasher as _};
let mut hasher = std::collections::hash_map::DefaultHasher::new();
(self.caption, self.detail_line, self.card).hash(&mut hasher);
(self.caption, self.detail_line, self.card, self.regular_card_padding).hash(&mut hasher);
hasher.finish()
}
@@ -802,7 +806,7 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> Collection for TileGrid<'_, K
if self.card_columns == 0 {
return 0.0;
}
let style = GridSizes::of(cx, self.card, self.items.row_height);
let style = GridSizes::of(cx, self.card, self.items.row_height, self.regular_card_padding);
let aspect = if self.aspect.is_finite() && self.aspect > 0.0 { self.aspect } else { 1.0 };
let around = style.around.get(self.caption, self.detail_line);
let card = style.card(self.picture_side(&style, item, around), aspect, around).x;
@@ -826,7 +830,7 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> Collection for TileGrid<'_, K
/// Every tile gets the grid's caption place and detail line, the card look, and its row's rename state.
fn dress<'r>(&self, tile: Self::Item<'r>, row: &RowState) -> Self::Item<'r> {
let tile = tile.caption(self.caption).detail_line(self.detail_line).renaming(row.renaming);
if self.card { tile.card() } else { tile }
if self.card { tile.card().with_regular_card_padding(self.regular_card_padding) } else { tile }
}
fn can_rename(&self, key: &K) -> bool {
+17 -7
View File
@@ -121,8 +121,8 @@ pub(super) struct AroundPicture {
}
impl AroundPicture {
fn of(cx: &StyleCx<'_>, card: bool) -> AroundPicture {
let around = |place: CaptionPlace, detail: bool| Sizes::of(cx, card, place).around(place, detail);
fn of(cx: &StyleCx<'_>, card: bool, regular_card_padding: bool) -> AroundPicture {
let around = |place: CaptionPlace, detail: bool| Sizes::of(cx, card, place, regular_card_padding).around(place, detail);
AroundPicture {
below: around(CaptionPlace::Below, false),
below_detail: around(CaptionPlace::Below, true),
@@ -145,11 +145,12 @@ impl AroundPicture {
impl Sizes {
/// The sizes of a tile with its caption in `place`. A bare tile keeps only the room its selection ring draws in, so
/// a grid packs bare tiles close.
fn of(cx: &StyleCx<'_>, card: bool, place: CaptionPlace) -> Sizes {
fn of(cx: &StyleCx<'_>, card: bool, place: CaptionPlace, regular_card_padding: bool) -> Sizes {
let (tokens, control) = (cx.tokens, cx.control());
let line = tokens.typography.get(TypeRole::Caption).line_height;
let name_line = if card { tokens.typography.get(TypeRole::BodyStrong).line_height } else { line };
let inset = match (card, place) {
(true, _) if regular_card_padding => tokens.space.pad.regular,
(true, _) => tokens.space.pad.control,
(false, CaptionPlace::None) => tokens.space.gap.tight,
(false, _) => tokens.space.gap.inline,
@@ -297,6 +298,9 @@ pub struct Tile<'a> {
#[style_key]
#[prop]
caption: CaptionPlace,
/// The grid asked for the theme's regular padding around a framed card.
#[style_key]
regular_card_padding: bool,
/// The card has a line for the detail, whether this tile has one or not: the grid's, applied to its tiles.
#[prop]
detail_line: bool,
@@ -375,6 +379,7 @@ impl<'a> Tile<'a> {
Tile {
common: Common::new(),
caption: CaptionPlace::Below,
regular_card_padding: false,
detail_line: false,
card: false,
detail: None,
@@ -454,12 +459,17 @@ impl<'a> Tile<'a> {
/// What a tile adds around its picture: its padding, the caption band under the picture or the column at its
/// reading start. A tile grid sizes a tile as the picture plus this.
pub fn around_picture(cx: &StyleCx<'_>, place: CaptionPlace, detail: bool) -> Around {
Sizes::of(cx, false, place).around(place, detail)
Sizes::of(cx, false, place, false).around(place, detail)
}
/// What a tile adds around its picture for every caption arrangement.
pub(super) fn around(cx: &StyleCx<'_>, card: bool) -> AroundPicture {
AroundPicture::of(cx, card)
pub(super) fn around(cx: &StyleCx<'_>, card: bool, regular_card_padding: bool) -> AroundPicture {
AroundPicture::of(cx, card, regular_card_padding)
}
pub(super) fn with_regular_card_padding(mut self, enabled: bool) -> Self {
self.regular_card_padding = enabled;
self
}
/// Whether the caption band holds a detail line.
@@ -627,7 +637,7 @@ impl Component for Tile<'_> {
let (state, text) = (&colors.state, &colors.text);
let clear = Rgba::TRANSPARENT;
let c = |rgba: Rgba| cx.color(rgba);
let sizes = Sizes::of(cx, key.card, key.caption);
let sizes = Sizes::of(cx, key.card, key.caption, key.regular_card_padding);
// Selection and hover are rings around the picture; only a card has a fill of its own.
let fill = if key.card {
let raised = colors.surface.raised;