chrome-w4: net change of 4 commits

- chrome-w4: written by an agent
- chrome-w4: finished by an agent
- chrome-w4: finished by an agent
- chrome-w4: review fixes (review-1)
This commit is contained in:
Martin Ball
2026-11-18 16:01:11 +00:00
parent e7613f6a30
commit b912c077f0
21 changed files with 1161 additions and 310 deletions
+7 -2
View File
@@ -315,15 +315,20 @@ impl State {
self.focus_stop(arrival)
}
/// F6: the first stop of the next pane, with its label as the announcement.
/// F6: the first stop of the next pane, with its label as the announcement. Inside a trapping scope (a modal
/// dialog or a popup, also when nothing in it is focused) F6 moves nothing and announces nothing: a pane move
/// would carry the focus out of the trap, which only closing the dialog may do.
pub(super) fn pane(&mut self, forward: bool, all_controls: bool) -> (Vec<Act>, Vec<String>) {
let current = self.stop_of_focus();
if self.trap_of(current.as_ref()).is_some() {
return (Vec::new(), Vec::new());
}
let panes: Vec<Id> = self
.last_scope_order
.iter()
.copied()
.filter(|id| self.last_scopes.get(id).is_some_and(|scope| scope.policy.kind == ScopeKind::Pane))
.collect();
let current = self.stop_of_focus();
let here = current.as_ref().and_then(|rec| self.pane_of(rec));
let at = here.and_then(|pane| panes.iter().position(|id| *id == pane));
let next = match (at, forward) {
@@ -1,20 +1,22 @@
//! Trials of the keys and presses a host's own egui widgets keep while the runtime is installed on the whole window.
use crate::runtime::commands::{CommandInput, CommandSet as _, EditCommands, NavCommand};
use crate::contract::{Common, Component, Container, ContainerProps, Cx, Mount, Overlay, Props as _, Role, ShowContainer as _};
use crate::runtime::commands::{AppCatalog, Binding, CommandDef, CommandInput, CommandSet as _, EditCommands, NavCommand, Scope};
use crate::runtime::drag::{self, DragPreview};
use crate::runtime::egui::{areas, fixture};
use crate::runtime::env::RootEnv;
use crate::runtime::focus::{EditSet, FocusTarget, KeepKeys, KeyUse, host_canvas, request};
use crate::runtime::focus::{EditSet, FocusPolicy, FocusTarget, KeepKeys, KeyUse, host_canvas, request};
use crate::runtime::frame::{ChromeToggle, take_output};
use crate::runtime::keys::with_window_intents;
use crate::testing::focus::{Stop, egui_focused, named_id, register_stop, widget};
use crate::style::{ComponentStyle, StyleCx};
use crate::testing::focus::{Stop, egui_focused, named_id, pop_scope, push_scope, register_stop, widget};
use crate::testing::input::{key_press, key_reached, slop};
use crate::testing::pointer::{self, moved, press, release};
use crate::testing::sensing::{self, ProbeRoot};
use crate::testing::{Frames, trial};
use craft_behavior::{EditCommand, Input, Intent, Sense};
use egui::{Event, Id, ImeEvent, Key, Modifiers, Pos2, Rect, Ui, ViewportId};
use std::cell::RefCell;
use craft_behavior::{EditCommand, Input, Intent, Metrics, Sense};
use egui::{Event, Id, ImeEvent, Key, Modifiers, Pos2, Rect, Response, Ui, ViewportId};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::sync::Arc;
@@ -500,3 +502,171 @@ fn an_app_binding_on_f6_beats_the_pane_move() {
unbound.insert(NavCommand::NextPane.id(), Vec::new());
assert_eq!(f6_under(Some(unbound)), (true, Vec::new()), "with the pane move unbound, F6 is egui's");
}
/// The panes the pane trials show, in order: the scope's name, its stop and its label.
const PANES: [(&str, &str, &str); 2] = [("left pane", "left", "Left"), ("right pane", "right", "Right")];
/// Shows the two panes of `PANES`, each a pane scope holding one button stop.
fn show_panes(ui: &mut Ui) {
for (pane, stop, label) in PANES {
push_scope(ui.ctx(), named_id(pane), FocusPolicy::PANE, Some(Arc::from(label)));
widget(ui, named_id(stop));
register_stop(ui.ctx(), Stop::new(named_id(stop), KeyUse::of(Input::Pointer)));
pop_scope(ui.ctx());
}
}
/// A press of F6 with `mods` and the frame after it: where egui focus is then, and what the move announced.
fn pane_key(frames: &mut Frames, show: &mut impl FnMut(&mut Ui), mods: Modifiers) -> (Option<Id>, Vec<String>) {
take_output(&frames.ctx);
frames.frame(vec![key_press(Key::F6, mods)], &mut *show);
frames.frame(Vec::new(), &mut *show);
(egui_focused(&frames.ctx), take_output(&frames.ctx).announcements)
}
/// Focuses the stop `id` and settles one frame.
fn focus_stop(frames: &mut Frames, show: &mut impl FnMut(&mut Ui), id: Id) {
request(&frames.ctx, FocusTarget::Id(id));
frames.frame(Vec::new(), &mut *show);
}
/// A dialog's focus trap (`FocusPolicy::DIALOG`, the scope a modal dialog's layer pushes) holds F6: the pane move would
/// carry focus out of the dialog, so F6 and Shift+F6 move nothing and announce nothing while the trap is shown. The trap
/// is the focus scope alone, with no modal layer, so only the pane move's own guard can keep the focus in it.
#[trial]
fn f6_inside_a_modal_dialog_keeps_the_focus_in_it() {
let open = Rc::new(Cell::new(false));
let shown = Rc::clone(&open);
let ok = named_id("dialog ok");
let mut show = move |ui: &mut Ui| {
show_panes(ui);
if shown.get() {
push_scope(ui.ctx(), named_id("dialog"), FocusPolicy::DIALOG, Some(Arc::from("Dialog")));
widget(ui, ok);
register_stop(ui.ctx(), Stop::new(ok, KeyUse::of(Input::Pointer)));
pop_scope(ui.ctx());
}
};
let (left, right) = (named_id("left"), named_id("right"));
let mut frames = Frames::new();
frames.frame(Vec::new(), &mut show);
focus_stop(&mut frames, &mut show, left);
let (at, said) = pane_key(&mut frames, &mut show, Modifiers::NONE);
assert_eq!(at, Some(right), "outside a dialog F6 moves to the next pane");
assert!(said.iter().any(|text| text == "Right"), "and names it: {said:?}");
open.set(true);
frames.frame(Vec::new(), &mut show);
focus_stop(&mut frames, &mut show, ok);
assert_eq!(egui_focused(&frames.ctx), Some(ok), "the dialog's button has the focus");
assert_eq!(pane_key(&mut frames, &mut show, Modifiers::NONE), (Some(ok), Vec::new()), "F6 keeps the focus in the dialog and says nothing");
assert_eq!(pane_key(&mut frames, &mut show, Modifiers::SHIFT), (Some(ok), Vec::new()), "so does Shift+F6");
open.set(false);
frames.frame(Vec::new(), &mut show);
focus_stop(&mut frames, &mut show, left);
assert_eq!(pane_key(&mut frames, &mut show, Modifiers::NONE).0, Some(right), "with the dialog gone F6 moves panes again");
}
/// The app command the routing trial presses, from the app's catalog so that no other trial's keymap binds its key.
const REPLACE: &str = "hostKeyTrial.replace";
/// An app catalog binding `REPLACE` to the plain key Q. Its modal rule is the default one, `Blocked`: a modal dialog
/// with the keys keeps it from running. `None` when the definition is refused.
fn replace_catalog() -> Option<AppCatalog> {
let binding = Binding::parse("Q").ok()?;
AppCatalog::new(vec![CommandDef::new(REPLACE, "Replace", Scope::app()).with_default(binding)], 1).ok()
}
/// The style of a `TrialDialog`: its size comes from its content.
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
struct TrialDialogStyle {
#[style(metrics)]
metrics: Metrics,
}
/// A modal dialog layer (`Overlay::dialog`), whose body the trial fills.
#[derive(Component)]
#[component(container, unregistered)]
struct TrialDialog {
#[common]
common: Common,
#[container]
props: ContainerProps,
}
impl Component for TrialDialog {
const ROLE: Role = Role::GROUP;
type Style = TrialDialogStyle;
type Output = Response;
fn style(_: &StyleCx<'_>, _: TrialDialogStyleKey) -> TrialDialogStyle {
TrialDialogStyle { metrics: Metrics::new() }
}
fn finish(self, cx: Cx<'_, Self>) -> Response {
cx.response.clone()
}
}
impl Container for TrialDialog {}
/// S-X7: a window shortcut runs while the keyboard is on a pane's title, as after F6, and runs neither from a button of
/// an open modal dialog (the dialog owns the keys, and the command's modal rule blocks it) nor from a text field (a plain
/// key there is typing).
#[trial]
fn a_window_shortcut_runs_from_a_pane_title_and_not_from_a_modal_dialog_or_a_text_field() {
let (title, field, button) = (named_id("pane title"), named_id("pane field"), named_id("dialog button"));
let open = Rc::new(Cell::new(false));
let shown = Rc::clone(&open);
let mut show = move |ui: &mut Ui| {
push_scope(ui.ctx(), named_id("pane"), FocusPolicy::PANE, Some(Arc::from("Pane")));
widget(ui, title);
register_stop(ui.ctx(), Stop::new(title, KeyUse::of(Input::Pointer)));
widget(ui, field);
register_stop(ui.ctx(), Stop::new(field, KeyUse::of(Input::Text)));
pop_scope(ui.ctx());
if shown.get() {
let props = ContainerProps::new().mount(Mount::Layer(Overlay::dialog()));
TrialDialog { common: Common::new(), props }.id_salt("trial dialog").show(ui, |ui, _| {
widget(ui, button);
register_stop(ui.ctx(), Stop::new(button, KeyUse::of(Input::Pointer)));
});
}
};
// The ids of the commands a press of the shortcut's key fired.
let fired = |frames: &mut Frames, show: &mut dyn FnMut(&mut Ui)| -> Vec<String> {
take_output(&frames.ctx);
frames.frame(vec![key_press(Key::Q, Modifiers::NONE)], &mut *show);
frames.frame(Vec::new(), &mut *show);
take_output(&frames.ctx).fired.into_iter().map(|fired| fired.command.id).collect()
};
let replace = vec![REPLACE.to_owned()];
let catalog = replace_catalog();
assert!(catalog.is_some(), "the trial's catalog is valid");
let mut frames = Frames::new();
if let Some(catalog) = catalog {
frames.commands(CommandInput::new().catalog(catalog));
}
frames.frame(Vec::new(), &mut show);
focus_stop(&mut frames, &mut show, title);
assert_eq!(egui_focused(&frames.ctx), Some(title));
assert_eq!(fired(&mut frames, &mut show), replace, "the pane's title leaves the shortcut to the window");
focus_stop(&mut frames, &mut show, field);
assert_eq!(egui_focused(&frames.ctx), Some(field));
assert_eq!(fired(&mut frames, &mut show), Vec::<String>::new(), "a text field keeps the plain key for its typing");
focus_stop(&mut frames, &mut show, title);
open.set(true);
frames.idle(2, &mut show);
focus_stop(&mut frames, &mut show, button);
assert_eq!(egui_focused(&frames.ctx), Some(button), "the dialog's button has the keyboard");
assert_eq!(fired(&mut frames, &mut show), Vec::<String>::new(), "a modal dialog keeps the window's shortcut from running");
open.set(false);
frames.idle(2, &mut show);
focus_stop(&mut frames, &mut show, title);
assert_eq!(fired(&mut frames, &mut show), replace, "with the dialog closed the title runs it again");
}
+43 -17
View File
@@ -190,20 +190,31 @@ pub struct PaneSpec {
pub edges: PaneEdges,
}
/// A set of dock edges.
/// The edges a pane may dock at: a set over `Start`, `End`, `Top` and `Bottom`. The centre is no edge of a pane area
/// and is in no set.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PaneEdges(u8);
impl PaneEdges {
/// Every edge, the centre included.
pub const ALL: PaneEdges = PaneEdges(0b1_1111);
/// The four sides, without the centre.
pub const SIDES: PaneEdges = PaneEdges(0b1111);
/// Every edge: start, end, top and bottom.
pub const ALL: PaneEdges = PaneEdges(0b1111);
/// The start and end edges only: a pane that docks beside the document, never above or below it.
pub const SIDES: PaneEdges = PaneEdges(0b0011);
/// Whether `edge` is in the set.
/// The bit of `edge`; the centre has none.
fn bit(edge: PaneEdge) -> u8 {
match edge {
PaneEdge::Start => 0b0001,
PaneEdge::End => 0b0010,
PaneEdge::Top => 0b0100,
PaneEdge::Bottom => 0b1000,
_ => 0,
}
}
/// Whether `edge` is in the set; never for the centre.
pub fn contains(self, edge: PaneEdge) -> bool {
let _ = (self, edge);
todo!("ch.C12")
self.0 & Self::bit(edge) != 0
}
}
@@ -280,9 +291,13 @@ impl<P> Shown<P> {
}
/// The requests that dock `dragged` at `edge`, directly before the pane `before` in the order (`None`: after every
/// pane). None when it lands where it is.
/// pane). None when it lands where it is, or when the pane may not dock at `edge` ([`PaneSpec::edges`]): every docked
/// move, a command's and a drop's, comes here, and an empty answer makes a drop draw no mark.
fn dock_requests<P: Clone>(panes: &[Shown<P>], dragged: PanelKey, edge: PaneEdge, before: Option<PanelKey>) -> Vec<PaneRequest<P>> {
let Some(moved) = panes.iter().find(|s| s.key == dragged) else { return Vec::new() };
if !moved.spec.edges.contains(edge) {
return Vec::new();
}
let order: Vec<PanelKey> = panes.iter().map(|s| s.key).collect();
let mut after: Vec<PanelKey> = order.iter().copied().filter(|key| *key != dragged).collect();
let at = before.and_then(|before| after.iter().position(|key| *key == before)).unwrap_or(after.len());
@@ -602,6 +617,8 @@ struct LastFocus(Option<PanelKey>);
/// [`PaneRequest`]s for the app to apply, and reads the states again through [`PaneContent::state`].
/// - **Menu.** Each pane's menu holds the app's rows, then the [`PaneCommands`] rows. Every row is also a command that
/// acts on the pane holding focus.
/// - **Edges.** A pane docks only at its [`PaneSpec::edges`]: its menu and commands leave out the other edges, and a
/// drop on one is refused and draws no mark.
/// - **Centre.** The closure given to `show` fills what the docked panes leave.
#[must_use = "show the pane area with `show`"]
#[derive(crate::contract::Pattern, crate::contract::Props)]
@@ -774,9 +791,9 @@ fn show_floating<P: Clone + Eq + Hash + Debug + Send + Sync + 'static>(ui: &mut
pass.content.borrow_mut().body(&pane.pane, ui, bcx);
})
.output;
if let Some(change) = shown.placed
&& change.phase != GesturePhase::Cancel
{
// A cancelled move or resize (Escape) reports the rect from before the gesture: the app takes it back, as the
// steps of the gesture moved its kept rect. A click on the title with no drag reports nothing.
if let Some(change) = shown.placed {
pass.sink.borrow_mut().push(PaneRequest::FloatRect(pane.pane.clone(), change.rect));
}
if shown.minimized_toggled {
@@ -804,10 +821,22 @@ fn queue_action<P: Clone>(action: Option<HeaderAction>, pass: &Pass<'_, P>, pane
pass.sink.borrow_mut().extend(command_requests(pass.panes, pass.policy, pane.key, command));
}
/// Whether the pane offers the move `command`: a movable pane offers Float and a Move to an edge it may dock at.
fn offers_move(spec: &PaneSpec, command: PaneCommands) -> bool {
let edge = match command {
PaneCommands::MoveToStart => PaneEdge::Start,
PaneCommands::MoveToEnd => PaneEdge::End,
PaneCommands::MoveToTop => PaneEdge::Top,
PaneCommands::MoveToBottom => PaneEdge::Bottom,
_ => return spec.movable,
};
spec.movable && spec.edges.contains(edge)
}
/// Publishes the state of the pane commands and queues the ones that reached the pane this pass.
fn take_commands<P: Clone>(cx: &mut BodyCx<'_>, pass: &Pass<'_, P>, pane: &Shown<P>) {
for command in MOVES {
cx.publish(command, CommandState::new().enabled(pane.spec.movable));
cx.publish(command, CommandState::new().enabled(offers_move(&pane.spec, command)));
}
cx.publish(PaneCommands::Close, CommandState::new().enabled(pane.spec.closable));
while let Some((command, _)) = cx.take_command::<PaneCommands>() {
@@ -819,10 +848,7 @@ fn take_commands<P: Clone>(cx: &mut BodyCx<'_>, pass: &Pass<'_, P>, pane: &Shown
fn pane_menu<P: Clone>(ui: &mut Ui, cx: &mut BodyCx<'_>, pane: &Shown<P>, content: &RefCell<&mut dyn PaneContent<P>>) {
content.borrow_mut().menu(&pane.pane, ui, cx);
Divider::horizontal().show(ui);
let mut commands = Vec::new();
if pane.spec.movable {
commands.extend(MOVES);
}
let mut commands: Vec<PaneCommands> = MOVES.into_iter().filter(|command| offers_move(&pane.spec, *command)).collect();
if pane.spec.closable {
commands.push(PaneCommands::Close);
}
@@ -1,6 +1,6 @@
//! Stories of `PaneArea` and `PaneFrame`.
use super::{PaneArea, PaneContent, PaneFrame, PaneSpec, PaneState};
use super::{PaneArea, PaneContent, PaneEdges, PaneFrame, PaneSpec, PaneState};
use crate::contract::{BodyCx, PaneEdge, Show as _, ShowCollection as _, ShowContainer as _};
use crate::display::Text;
use crate::list::{List, ListRow};
@@ -21,20 +21,27 @@ fn layer_list(ui: &mut Ui, names: &[String]) {
List::<String>::new("Layers").show_items(ui, &source, &mut |key, _| ListRow::new(key.clone()));
}
/// Two panes: the first on the start edge with a scrolling body, the second on the bottom edge with a list.
/// Two panes that dock at `edges`: the first on the start edge with a scrolling body, the second with a list on the
/// bottom edge, or on the end edge when the bottom is not one of `edges`.
struct Panes {
float: Vec2,
side: f32,
layers: Vec<String>,
edges: PaneEdges,
}
const LIST_PANE: u32 = 1;
impl PaneContent<u32> for Panes {
fn spec(&self, pane: &u32) -> PaneSpec {
let edge = if *pane == 0 { PaneEdge::Start } else { PaneEdge::Bottom };
let edge = match *pane {
0 => PaneEdge::Start,
_ if self.edges.contains(PaneEdge::Bottom) => PaneEdge::Bottom,
_ => PaneEdge::End,
};
let mut spec = PaneSpec::new(format!("Pane {pane}"), PaneState::docked(edge, self.side), self.float);
spec.collection_body = *pane == LIST_PANE;
spec.edges = self.edges;
spec
}
@@ -47,10 +54,11 @@ impl PaneContent<u32> for Panes {
}
}
#[story(PaneArea<'static, u32>, covers = [], drive = Drive::Never)]
fn pane_area(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
/// The two panes around a document, each docking only at `edges`.
fn area(ui: &mut Ui, edges: PaneEdges) -> StoryOutput {
let size = &Env::of(ui).tokens.size;
let mut content = Panes { float: Vec2::new(size.float.width, size.float.height), side: size.length.field.md, layers: layer_names() };
let mut content =
Panes { float: Vec2::new(size.float.width, size.float.height), side: size.length.field.md, layers: layer_names(), edges };
let open = [0_u32, 1];
PaneArea::new("Panes", &open, &mut content)
.show(ui, |ui, _| {
@@ -59,6 +67,17 @@ fn pane_area(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
.into()
}
#[story(PaneArea<'static, u32>, covers = [], drive = Drive::Never)]
fn pane_area(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
area(ui, PaneEdges::ALL)
}
/// Panes that dock beside the document only: their menus offer no Move to Top or Bottom.
#[story(PaneArea<'static, u32>, covers = [], drive = Drive::Never)]
fn pane_area_sides_only(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
area(ui, PaneEdges::SIDES)
}
fn spec(ui: &Ui, title: &str, collection_body: bool) -> PaneSpec {
let size = &Env::of(ui).tokens.size;
let mut spec =
@@ -1,5 +1,5 @@
//! `AboutDialog`: Help > About in one window for every app, with the app's own data. Tabs About, Contributors and
//! Models.
//! Models, then the app's own tabs.
mod contributors;
mod credits;
@@ -109,12 +109,11 @@ pub enum AboutTab {
}
/// A tab the app adds after Models: a name for the hosted dialog's `tab` field, a title and a body.
///
/// The body is `Send` because a [`HostedAbout`] lives on the dialog stack, which needs its dialogs `Send`.
pub struct AboutAppTab {
#[allow(dead_code)] // P3(chrome-w4): ch.C11
name: &'static str,
#[allow(dead_code)] // P3(chrome-w4): ch.C11
title: Label,
#[allow(dead_code)] // P3(chrome-w4): ch.C11
body: Box<dyn FnMut(&mut Ui) + Send>,
}
@@ -220,6 +219,8 @@ impl Outcome for AboutOutput {
/// header press sorts by its column, activating a row (Enter or a double click) reports the profile URL, and the
/// row's tooltip is the summary.
/// - **Models.** A table of the credited models with their commits, share of all commits and lines.
/// - **App tabs.** The app's own [`AboutAppTab`]s ([`app_tabs`](AboutDialog::app_tabs)) follow Models, each body in a
/// vertically scrolling stack.
///
/// The name mode, the sort order and the view are kept in the dialog's container while it is open, and so is the tab
/// unless [`tab`](AboutDialog::tab) binds it. Links are reported
@@ -252,8 +253,9 @@ impl<'a> AboutDialog<'a> {
/// Shows the dialog.
pub fn show(self, ui: &mut Ui) -> AboutOutput {
let AboutDialog { info, credits, open, tab, app_tabs } = self;
let _ = app_tabs; // P3(chrome-w4): ch.C11
let AboutDialog { info, credits, open, tab, mut app_tabs } = self;
// The strip shows the titles while the body draws a tab, so it reads its own copy of them.
let app_titles: Vec<Label> = app_tabs.as_deref().unwrap_or_default().iter().map(|app| app.title.clone()).collect();
let env = Env::of(ui);
let words = env.words::<AboutWords>();
let common = env.words::<CommonWords>();
@@ -280,13 +282,20 @@ impl<'a> AboutDialog<'a> {
}
let before = kept.tab;
*view.borrow_mut() = kept;
Stack::new().header(|ui, _| shown.tabs(ui, &title, &view)).show(ui, |ui, _| {
Stack::new().header(|ui, _| shown.tabs(ui, &title, &app_titles, &view)).show(ui, |ui, _| {
let tab = view.borrow().tab;
match tab {
AboutTab::About => shown.about(ui, &link),
AboutTab::Contributors => shown.contributors(ui, &view, &link),
AboutTab::Models => shown.models(ui),
AboutTab::App(_) => todo!("ch.C11"),
let app = match tab {
AboutTab::App(at) => app_tabs.as_deref_mut().and_then(|tabs| tabs.get_mut(usize::from(at))),
_ => None,
};
match (tab, app) {
(AboutTab::Contributors, _) => shown.contributors(ui, &view, &link),
(AboutTab::Models, _) => shown.models(ui),
(AboutTab::App(_), Some(app)) => {
Stack::new().scroll(Scroll::vertical()).fill().show(ui, |ui, _| (app.body)(ui));
}
// An app tab past the given ones shows About.
_ => shown.about(ui, &link),
}
});
let picked = view.borrow().tab;
@@ -312,14 +321,15 @@ struct Shown<'s> {
}
impl Shown<'_> {
/// The tab strip; a pick of a tab is kept in `view`.
fn tabs(&self, ui: &mut Ui, title: &Label, view: &RefCell<View>) {
/// The tab strip: the three built in, then one per app tab titled `app`. A pick of a tab is kept in `view`.
fn tabs(&self, ui: &mut Ui, title: &Label, app: &[Label], view: &RefCell<View>) {
let words = self.words;
let tabs = [
let mut tabs = vec![
(AboutTab::About, words.about_tab.clone()),
(AboutTab::Contributors, words.contributors_tab.clone()),
(AboutTab::Models, words.models_tab.clone()),
];
tabs.extend(app.iter().enumerate().filter_map(|(at, title)| u8::try_from(at).ok().map(|at| (AboutTab::App(at), title.clone()))));
let source = keyed(&tabs[..], |tab: &(AboutTab, Label)| tab.0).with_text(|tab| Cow::Borrowed(tab.1.as_str()));
let shown = view.borrow().tab;
// The strip sits in the stack's header, which is as tall as what it holds: it takes its tabs' height.
@@ -565,7 +575,8 @@ const ABOUT_KEY: &str = "help.about";
const TAB_NAMES: [(AboutTab, &str); 3] = [(AboutTab::About, "about"), (AboutTab::Contributors, "contributors"), (AboutTab::Models, "models")];
impl HostedAbout {
/// The name of `tab` in the dialog's `tab` field: the app tabs' names as well as the three built in.
/// The name of `tab` in the dialog's `tab` field: the app tabs' names as well as the three built in. An app tab
/// past the given ones shows About, so it is named so.
fn tab_name(&self, tab: AboutTab) -> &str {
if let AboutTab::App(at) = tab
&& let Some(app) = self.app_tabs.get(usize::from(at))
@@ -574,6 +585,15 @@ impl HostedAbout {
}
TAB_NAMES.iter().find(|(known, _)| *known == tab).map_or("about", |(_, name)| *name)
}
/// The tab named `name` in the dialog's `tab` field; a name built in wins over an app tab's of the same name.
fn tab_named(&self, name: &str) -> Option<AboutTab> {
if let Some((tab, _)) = TAB_NAMES.iter().find(|(_, known)| *known == name) {
return Some(*tab);
}
let at = self.app_tabs.iter().position(|app| app.name == name)?;
u8::try_from(at).ok().map(AboutTab::App)
}
}
impl StackDialog for HostedAbout {
@@ -591,7 +611,7 @@ impl StackDialog for HostedAbout {
if field != "tab" {
return Err(FieldRefusal::Unknown.message(field));
}
let picked = value.as_str().and_then(|name| TAB_NAMES.iter().find(|(_, known)| *known == name)).map(|(tab, _)| *tab);
let picked = value.as_str().and_then(|name| self.tab_named(name));
let Some(picked) = picked else { return Err(FieldRefusal::Rejects(&value).message(field)) };
self.tab = picked;
Ok(())
@@ -143,8 +143,6 @@ fn name_key(name: &str) -> String {
}
fn compare(a: &Contributor, b: &Contributor, mode: NameMode, sort: ContributorSort) -> Ordering {
// Someone credited only through a merged pull request has no date and sorts after everyone with one.
let dated = |date: &str| (date.is_empty(), date.to_owned());
match sort {
ContributorSort::Name => name_key(&a.name(mode)).cmp(&name_key(&b.name(mode))),
ContributorSort::Prs => a.prs.cmp(&b.prs),
@@ -154,8 +152,17 @@ fn compare(a: &Contributor, b: &Contributor, mode: NameMode, sort: ContributorSo
ContributorSort::LinesDelta => a.lines_delta().cmp(&b.lines_delta()),
ContributorSort::BinaryAdded => a.binary_added.cmp(&b.binary_added),
ContributorSort::BinaryDeleted => a.binary_deleted.cmp(&b.binary_deleted),
ContributorSort::FirstCommit => dated(&a.first_commit).cmp(&dated(&b.first_commit)),
ContributorSort::LastCommit => dated(&a.last_commit).cmp(&dated(&b.last_commit)),
ContributorSort::FirstCommit => a.first_commit.cmp(&b.first_commit),
ContributorSort::LastCommit => a.last_commit.cmp(&b.last_commit),
}
}
/// Whether `c` has no date for a sort by date: someone credited only through a merged pull request.
fn undated(c: &Contributor, sort: ContributorSort) -> bool {
match sort {
ContributorSort::FirstCommit => c.first_commit.is_empty(),
ContributorSort::LastCommit => c.last_commit.is_empty(),
_ => false,
}
}
@@ -168,6 +175,9 @@ pub(super) fn sorted_indices(list: &[Contributor], mode: NameMode, sort: Contrib
sort_rows(&mut order, Some(&by), |&a, &b, column| {
ContributorSort::of_column(column).map_or(Ordering::Equal, |key| compare(&list[a], &list[b], mode, key))
});
// The undated follow the dated after the direction is applied, so a descending sort keeps them last; the sort is
// stable, so each part keeps its order.
order.sort_by_key(|&at| undated(&list[at], sort));
order
}
@@ -1,7 +1,9 @@
//! Stories of `AboutDialog`: the About tab and the Contributors tab with a PR-only contributor.
//! Stories of `AboutDialog`: the About tab, the Contributors tab with a PR-only contributor, and an app tab.
use super::{AboutDialog, AboutInfo, AboutLink, AboutTab, Contributor, Credits, HostedAbout, ModelCredit};
use super::{AboutAppTab, AboutDialog, AboutInfo, AboutLink, AboutTab, Contributor, Credits, HostedAbout, ModelCredit};
use crate::contract::Show as _;
use crate::dialog::stories::hosted;
use crate::display::Text;
use crate::testing::{Drive, StoryData, StoryOutput, story};
use egui::Ui;
use std::sync::LazyLock;
@@ -39,6 +41,20 @@ fn about_dialog(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
hosted(ui, data, (tab, community), || HostedAbout::new(info(community), CREDITS.clone()).tab(tab))
}
/// The dialog with one app tab after Models, open on it.
#[story(AboutDialog<'static>, covers = [], drive = Drive::Never)]
fn about_dialog_app_tab(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let community = *data.value("community_button", true);
hosted(ui, data, community, || {
let languages = AboutAppTab::new("languageData", "Languages", |ui: &mut Ui| {
Text::new("English (built in)").show(ui);
Text::new("Français 1.2 · 98% translated").show(ui);
Text::new("Deutsch 1.1 · 91% translated").show(ui);
});
HostedAbout::new(info(community), CREDITS.clone()).app_tab(languages).tab(AboutTab::App(0))
})
}
#[story(AboutDialog<'static>, covers = [], drive = Drive::Never)]
fn about_dialog_contributors(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let tab = *data.choice("tab", AboutTab::Contributors, &TABS);
@@ -1,207 +0,0 @@
//! The contents of the preferences window: a search field over a page list and the shown page.
use super::model::{PageSpec, PrefValue, PreferencesModel};
use super::rows::{RowsOut, ShownRow, reset_button, show_row};
use super::search::{self, Listed};
use super::window::PreferencesState;
use super::words::PreferencesWords;
use crate::contract::{
ActivateOn, Bind, CollectionEvent, Props as _, Scroll, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing,
};
use crate::display::{Divider, Shade, Text};
use crate::form::FieldGroup;
use crate::layout_components::{Row, Stack};
use crate::list::{List, ListRow, RowInk};
use crate::notices::{Notice, NoticeLayout};
use crate::runtime::env::{Label, Units};
use crate::sections::Section;
use crate::style::TypeRole;
use crate::text::TextField;
use craft_behavior::{DisplayOrder, ItemSource, Selection, SelectionChange};
use craft_i18n::matcher::Matcher;
use craft_theme::variant::Tone;
use egui::Ui;
/// One entry of the page list.
pub(super) struct PageEntry {
pub id: String,
pub title: Label,
pub dimmed: bool,
}
/// A group of the shown page: its title and the rows the search keeps.
struct ShownGroup {
title: Option<Label>,
rows: Vec<ShownRow>,
}
/// The page to draw, copied from the host's model so that the host can be borrowed again to draw custom rows.
pub(super) struct ShownPage {
pub id: String,
title: Label,
custom: bool,
footnote: Option<Label>,
groups: Vec<ShownGroup>,
}
/// What the host's pages look like under the search: the pages to list and the page to show.
pub(super) struct Snapshot {
pub list: Vec<PageEntry>,
pub shown: Option<ShownPage>,
pub searching: bool,
}
/// The listed pages of `host` under `matcher`, and the part of the selected page the search keeps (the first listed
/// page when the search hides the selected one).
pub(super) fn snapshot<H: PreferencesModel + ?Sized>(host: &H, matcher: &Matcher, selected: &str) -> Snapshot {
let pages = host.pages();
let listed = search::list_pages(&pages, matcher);
let list = listed
.iter()
.map(|l| PageEntry { id: pages[l.index].id.to_owned(), title: Label::from(pages[l.index].title.to_owned()), dimmed: l.dimmed })
.collect();
let shown = search::shown_position(&listed, &pages, selected).map(|at| shown_page(matcher, &listed[at], &pages[listed[at].index]));
Snapshot { list, shown, searching: !matcher.is_empty() }
}
fn shown_page(matcher: &Matcher, listed: &Listed, page: &PageSpec<'_>) -> ShownPage {
let groups = page
.groups
.iter()
.filter_map(|group| {
let rows: Vec<ShownRow> = group.rows.iter().filter(|row| search::row_shown(matcher, listed, row)).map(ShownRow::of).collect();
(!rows.is_empty()).then(|| ShownGroup { title: group.title.map(|title| Label::from(title.to_owned())), rows })
})
.collect();
ShownPage {
id: page.id.to_owned(),
title: Label::from(page.title.to_owned()),
custom: page.custom,
footnote: page.footnote.map(|note| Label::from(note.to_owned())),
groups,
}
}
/// What the body asks of the window: the values the rows edited and whether Reset Section was pressed.
#[derive(Default)]
pub(super) struct BodyOut {
pub rows: RowsOut,
pub reset: bool,
}
impl BodyOut {
pub fn edits(&mut self) -> Vec<(String, PrefValue)> {
std::mem::take(&mut self.rows.edits)
}
}
/// The page list's rows: one per listed page, keyed by the page id.
struct Pages<'a>(&'a [PageEntry]);
impl DisplayOrder<String> for Pages<'_> {
fn len(&self) -> usize {
self.0.len()
}
fn key(&self, at: usize) -> String {
self.0[at].id.clone()
}
fn text(&self, at: usize) -> Option<std::borrow::Cow<'_, str>> {
Some(std::borrow::Cow::Borrowed(self.0[at].title.as_str()))
}
}
impl ItemSource<String> for Pages<'_> {}
/// Shows the search field, the page list and the page. `state.search` and `state.selected` change as the user types
/// and picks.
pub(super) fn show_body<H: PreferencesModel + ?Sized>(
ui: &mut Ui,
host: &mut H,
snap: &Snapshot,
state: &mut PreferencesState,
words: &PreferencesWords,
units: &Units,
out: &mut BodyOut,
) {
let list_id = ui.scope_id().with("pages");
TextField::search(words.search_label.clone(), Bind::bound(&mut state.search))
.placeholder(words.search_placeholder.clone())
.drives(list_id)
.show(ui);
let Some(page) = &snap.shown else {
Notice::new(Tone::Info, words.no_matches.clone()).layout(NoticeLayout::Centred).show(ui);
return;
};
Row::new().fill().show(ui, |ui, _| {
let current = Selection::single(page.id.clone());
let source = Pages(&snap.list);
let listed = List::<String>::new(words.pages_label.clone())
.id(list_id)
.select(SelectMode::Single)
.activate(ActivateOn::Click)
.allow_empty(false)
.header(false)
.sizing(Sizing::Content)
.selection(Bind::given(current))
.show_items(ui, &source, &mut |key, _| {
let entry = snap.list.iter().find(|entry| entry.id == *key);
let row = ListRow::new(entry.map_or_else(Label::default, |entry| entry.title.clone()));
if entry.is_some_and(|entry| entry.dimmed) { row.ink(RowInk::Dimmed) } else { row }
});
for event in listed.events {
if let CollectionEvent::Selection(SelectionChange::Set(keys)) = event
&& let Some(key) = keys.into_iter().last()
{
state.selected = key;
}
}
Divider::vertical().show(ui);
Stack::new()
.fill()
.scroll(Scroll::vertical())
.label(page.title.clone())
.show(ui, |ui, _| show_page(ui, host, page, snap.searching, words, units, out));
});
}
/// The page's title, groups, footnote and Reset Section.
fn show_page<H: PreferencesModel + ?Sized>(
ui: &mut Ui,
host: &mut H,
page: &ShownPage,
searching: bool,
words: &PreferencesWords,
units: &Units,
out: &mut BodyOut,
) {
Text::new(page.title.clone()).role(TypeRole::Title).show(ui);
if page.custom {
Stack::new().show(ui, |ui, _| host.custom_page(ui, &page.id));
} else if page.groups.is_empty() && !searching {
Notice::new(Tone::Info, words.empty_page.clone()).layout(NoticeLayout::Centred).show(ui);
}
for (at, group) in page.groups.iter().enumerate() {
let mut rows = |ui: &mut Ui| {
let name = group.title.clone().unwrap_or_else(|| page.title.clone());
FieldGroup::new(name).show(ui, |ui, _| {
for row in &group.rows {
show_row(ui, host, row, units, &mut out.rows);
}
});
};
match &group.title {
Some(title) => {
Section::fixed(title.clone()).id_salt(at).show(ui, |ui, _| rows(ui));
}
None => rows(ui),
}
}
if let Some(note) = &page.footnote {
Text::new(note.clone()).role(TypeRole::Caption).shade(Shade::Muted).show(ui);
}
if !searching && (page.custom || !page.groups.is_empty()) && reset_button(ui, words.reset_section.clone()) {
out.reset = true;
}
}
@@ -3,7 +3,10 @@
//!
//! - [`PageSpec`], [`GroupSpec`], [`RowSpec`], [`RowKind`], [`PrefValue`]: the row model the host builds each frame
//! from its settings and its draft. The library keeps no copy of the values.
//! - [`PreferencesModel`]: what the app implements: pages, draft, apply, cancel, reset, custom rows and nested dialogs.
//! - [`PreferencesModel`]: what the app implements: pages, edits, reset, custom rows and nested dialogs.
//! [`PreferencesDraft`] adds the draft's apply, cancel and differs for a window with OK, Cancel and Apply.
//! - [`PreferencesPage`]: the search, page list and shown page, applying each edit to the model at once.
//! - [`PreferencesWindow`]: the page in a modal window with OK, Cancel and Apply over a [`PreferencesDraft`].
//! - [`PreferencesWords`]: every caption of the window.
//! - [`PathSetting`]: a path setting for a custom row or page, typed or picked through the host's file service.
//! - [`SettingsDocument`]: a [`PreferencesModel`] built from the app's settings struct, one row per setting by type,
@@ -23,8 +26,7 @@ pub use model::{Closed, GroupSpec, PageSpec, PrefValue, PreferencesDraft, Prefer
pub use search::{Listed, list_pages, matches, row_matches, row_shown, shown_position};
pub use words::{PreferencesWords, SettingsDocumentWords};
// The window, its body and its rows.
mod body;
// The page, the window around it and their rows.
mod page;
mod path_setting;
mod rows;
@@ -278,12 +278,15 @@ impl Outcome for PreferencesOutput {
}
}
/// The app's side of the preferences window. The model keeps the saved settings and the draft; the window shows the
/// pages [`pages`](PreferencesModel::pages) returns, filters them and reports edits through
/// [`set`](PreferencesModel::set).
/// The app's side of a preferences page. The page shows the pages [`pages`](PreferencesModel::pages) returns, filters
/// them and reports each edit through [`set`](PreferencesModel::set) in the pass it lands in.
///
/// The window reads its words and numbers from the scope's language. To preview a language while the window is open,
/// install the host with the draft's language; the window follows on the next pass. [`cancel`](PreferencesModel::cancel)
/// A [`PreferencesPage`](super::PreferencesPage) needs only this trait: its edits apply at once. A
/// [`PreferencesWindow`](super::PreferencesWindow) also needs [`PreferencesDraft`]: there `set` edits a draft that OK
/// or Apply commits and Cancel drops.
///
/// The page reads its words and numbers from the scope's language. To preview a language while the window is open,
/// install the host with the draft's language; the page follows on the next pass. [`PreferencesDraft::cancel`]
/// installs the saved language again.
pub trait PreferencesModel {
/// The pages, built from the draft.
@@ -310,7 +313,8 @@ pub trait PreferencesModel {
}
}
/// The draft side of a preferences model: what a window with Apply, OK and Cancel needs beyond the rows.
/// The draft side of a [`PreferencesModel`]: what a [`PreferencesWindow`](super::PreferencesWindow) with OK, Cancel and
/// Apply needs beyond the rows. A [`PreferencesPage`](super::PreferencesPage) never calls it.
pub trait PreferencesDraft: PreferencesModel {
/// Whether the draft differs from the saved settings: enables Apply.
fn differs(&self) -> bool;
@@ -1,18 +1,48 @@
//! `PreferencesPage`: the preferences body without a window, applying each value at once.
use super::model::PreferencesModel;
#[cfg(feature = "testing")]
mod stories;
use super::model::{PageSpec, PreferencesModel};
use super::rows::{RowsOut, ShownRow, reset_button, show_row};
use super::search::{self, Listed};
use super::window::PreferencesState;
use crate::contract::{Bind, Pattern, Props};
use super::words::PreferencesWords;
use crate::contract::{
ActivateOn, Bind, CollectionEvent, NoValue, Outcome, Pattern, Props, Scroll, SelectMode, Show as _, ShowCollection as _,
ShowContainer as _, Sizing,
};
use crate::display::{Divider, Shade, Text};
use crate::form::FieldGroup;
use crate::layout_components::{Row, Stack};
use crate::list::{List, ListRow, RowInk};
use crate::notices::{Notice, NoticeLayout};
use crate::runtime::env::{Env, Label, Units};
use crate::runtime::memory::Remember as _;
use crate::runtime::requests::ColorRequest;
use crate::sections::Section;
use crate::style::TypeRole;
use crate::text::TextField;
use craft_behavior::{DisplayOrder, EditEvent, ItemSource, Mixed, Selection, SelectionChange};
use craft_i18n::matcher::Matcher;
use craft_theme::variant::Tone;
use egui::{Response, Ui};
use std::sync::Arc;
/// A preferences page that applies each value at once, with search and Reset Section. [`PreferencesWindow`] shows its
/// body through this page, so one page path remains.
///
/// - **Pages and search.** The page lists the host's pages that match the search (the empty ones dimmed) and shows
/// the picked one, or the first listed when the search hides it. Up, Down and Enter in the search field go to the
/// page list.
/// - **Edits.** Each edit reaches [`PreferencesModel::set`] in the pass it lands in, and Reset Section reaches
/// [`PreferencesModel::reset_page`]; the page has no OK, Cancel or Apply of its own.
/// - **State.** The search, the picked page and the error live in the bound [`PreferencesState`]. A page that has just
/// appeared starts with no search and no error; an edit or a Reset clears the error.
///
/// [`PreferencesWindow`]: super::PreferencesWindow
#[derive(Pattern, Props)]
pub struct PreferencesPage<'a> {
#[allow(dead_code)] // P3(chrome-w4): ch.C10
state: Bind<'a, PreferencesState>,
}
@@ -24,19 +54,256 @@ pub struct PreferencesPageOutput {
pub response: Response,
/// A colour row asked for the picker; the host answers through [`PreferencesModel::set_color`].
pub pick_color: Option<ColorRequest>,
/// The page the user switched to in this pass.
/// The id of the page shown, `None` when the search lists no page.
pub page: Option<String>,
}
impl Outcome for PreferencesPageOutput {
type Value = NoValue;
fn response(&self) -> &Response {
&self.response
}
}
/// What the rows of one run ask of the host: the values they edited and whether Reset Section was pressed.
#[derive(Default)]
struct BodyOut {
rows: RowsOut,
reset: bool,
}
/// What one run of the page's body did: the state it read and the state it leaves, and what the rows asked for.
struct PageRun {
before: PreferencesState,
work: PreferencesState,
out: BodyOut,
page: Option<String>,
}
impl<'a> PreferencesPage<'a> {
/// A page over the host's `state`.
pub fn new(state: Bind<'a, PreferencesState>) -> Self {
PreferencesPage { state }
}
/// Shows the page for this pass over `host`.
/// Shows the page for this pass over `host`. The values the rows edit and Reset Section reach the host once, after
/// the body's real run, so a measuring run of the body applies nothing.
pub fn show<H: PreferencesModel + ?Sized>(self, ui: &mut Ui, host: &mut H) -> PreferencesPageOutput {
let _ = (ui, host);
todo!("ch.C10")
let PreferencesPage { mut state } = self;
let env = Env::of(ui);
let words = env.words::<PreferencesWords>();
let units = env.units();
let title: Arc<str> = words.title.as_str().into();
let mut shown = Stack::new().fill().show(ui, |ui, cx| {
let before = match state.reborrow().read(cx) {
Some(Mixed::Same(held)) => held,
_ => PreferencesState::default(),
};
let mut work = before.clone();
if cx.appeared() {
work.search.clear();
work.error = None;
}
let matcher = Matcher::new(&env.folder(), work.search.trim());
let snap = snapshot(&*host, &matcher, &work.selected);
let mut out = BodyOut::default();
show_body(ui, &mut *host, &snap, &mut work, &words, &units, &mut out);
PageRun { before, work, out, page: snap.shown.map(|page| page.id) }
});
let pick_color = shown
.settle(|cx, run| {
let edits = std::mem::take(&mut run.out.rows.edits);
if !edits.is_empty() || run.out.reset {
run.work.error = None;
}
for (key, value) in edits {
host.set(&key, value);
}
if run.out.reset
&& let Some(page) = &run.page
{
host.reset_page(page);
}
if run.work != run.before {
let event = EditEvent::set(Mixed::Same(run.before.clone()), run.work.clone(), title.clone(), None);
let _ = state.reborrow().write(cx, &event);
}
run.out.rows.pick_color.take()
})
.flatten();
let page = shown.inner.and_then(|run| run.page);
PreferencesPageOutput { response: shown.output, pick_color, page }
}
}
/// One entry of the page list.
struct PageEntry {
id: String,
title: Label,
dimmed: bool,
}
/// A group of the shown page: its title and the rows the search keeps.
struct ShownGroup {
title: Option<Label>,
rows: Vec<ShownRow>,
}
/// The page to draw, copied from the host's model so that the host can be borrowed again to draw custom rows.
struct ShownPage {
id: String,
title: Label,
custom: bool,
footnote: Option<Label>,
groups: Vec<ShownGroup>,
}
/// What the host's pages look like under the search: the pages to list and the page to show.
struct Snapshot {
list: Vec<PageEntry>,
shown: Option<ShownPage>,
searching: bool,
}
/// The listed pages of `host` under `matcher`, and the part of the selected page the search keeps (the first listed
/// page when the search hides the selected one).
fn snapshot<H: PreferencesModel + ?Sized>(host: &H, matcher: &Matcher, selected: &str) -> Snapshot {
let pages = host.pages();
let listed = search::list_pages(&pages, matcher);
let list = listed
.iter()
.map(|l| PageEntry { id: pages[l.index].id.to_owned(), title: Label::from(pages[l.index].title.to_owned()), dimmed: l.dimmed })
.collect();
let shown = search::shown_position(&listed, &pages, selected).map(|at| shown_page(matcher, &listed[at], &pages[listed[at].index]));
Snapshot { list, shown, searching: !matcher.is_empty() }
}
fn shown_page(matcher: &Matcher, listed: &Listed, page: &PageSpec<'_>) -> ShownPage {
let groups = page
.groups
.iter()
.filter_map(|group| {
let rows: Vec<ShownRow> = group.rows.iter().filter(|row| search::row_shown(matcher, listed, row)).map(ShownRow::of).collect();
(!rows.is_empty()).then(|| ShownGroup { title: group.title.map(|title| Label::from(title.to_owned())), rows })
})
.collect();
ShownPage {
id: page.id.to_owned(),
title: Label::from(page.title.to_owned()),
custom: page.custom,
footnote: page.footnote.map(|note| Label::from(note.to_owned())),
groups,
}
}
/// The page list's rows: one per listed page, keyed by the page id.
struct Pages<'a>(&'a [PageEntry]);
impl DisplayOrder<String> for Pages<'_> {
fn len(&self) -> usize {
self.0.len()
}
fn key(&self, at: usize) -> String {
self.0[at].id.clone()
}
fn text(&self, at: usize) -> Option<std::borrow::Cow<'_, str>> {
Some(std::borrow::Cow::Borrowed(self.0[at].title.as_str()))
}
}
impl ItemSource<String> for Pages<'_> {}
/// Shows the search field, the page list and the page. `state.search` and `state.selected` change as the user types
/// and picks; the rows' edits and a press of Reset Section go to `out`.
fn show_body<H: PreferencesModel + ?Sized>(
ui: &mut Ui,
host: &mut H,
snap: &Snapshot,
state: &mut PreferencesState,
words: &PreferencesWords,
units: &Units,
out: &mut BodyOut,
) {
let list_id = ui.scope_id().with("pages");
TextField::search(words.search_label.clone(), Bind::bound(&mut state.search))
.placeholder(words.search_placeholder.clone())
.drives(list_id)
.show(ui);
let Some(page) = &snap.shown else {
Notice::new(Tone::Info, words.no_matches.clone()).layout(NoticeLayout::Centred).show(ui);
return;
};
Row::new().fill().show(ui, |ui, _| {
let current = Selection::single(page.id.clone());
let source = Pages(&snap.list);
let listed = List::<String>::new(words.pages_label.clone())
.id(list_id)
.select(SelectMode::Single)
.activate(ActivateOn::Click)
.allow_empty(false)
.header(false)
.sizing(Sizing::Content)
.selection(Bind::given(current))
.show_items(ui, &source, &mut |key, _| {
let entry = snap.list.iter().find(|entry| entry.id == *key);
let row = ListRow::new(entry.map_or_else(Label::default, |entry| entry.title.clone()));
if entry.is_some_and(|entry| entry.dimmed) { row.ink(RowInk::Dimmed) } else { row }
});
for event in listed.events {
if let CollectionEvent::Selection(SelectionChange::Set(keys)) = event
&& let Some(key) = keys.into_iter().last()
{
state.selected = key;
}
}
Divider::vertical().show(ui);
Stack::new()
.fill()
.scroll(Scroll::vertical())
.label(page.title.clone())
.show(ui, |ui, _| show_page(ui, host, page, snap.searching, words, units, out));
});
}
/// The page's title, groups, footnote and Reset Section.
fn show_page<H: PreferencesModel + ?Sized>(
ui: &mut Ui,
host: &mut H,
page: &ShownPage,
searching: bool,
words: &PreferencesWords,
units: &Units,
out: &mut BodyOut,
) {
Text::new(page.title.clone()).role(TypeRole::Title).show(ui);
if page.custom {
Stack::new().show(ui, |ui, _| host.custom_page(ui, &page.id));
} else if page.groups.is_empty() && !searching {
Notice::new(Tone::Info, words.empty_page.clone()).layout(NoticeLayout::Centred).show(ui);
}
for (at, group) in page.groups.iter().enumerate() {
let mut rows = |ui: &mut Ui| {
let name = group.title.clone().unwrap_or_else(|| page.title.clone());
FieldGroup::new(name).show(ui, |ui, _| {
for row in &group.rows {
show_row(ui, host, row, units, &mut out.rows);
}
});
};
match &group.title {
Some(title) => {
Section::fixed(title.clone()).id_salt(at).show(ui, |ui, _| rows(ui));
}
None => rows(ui),
}
}
if let Some(note) = &page.footnote {
Text::new(note.clone()).role(TypeRole::Caption).shade(Shade::Muted).show(ui);
}
if !searching && (page.custom || !page.groups.is_empty()) && reset_button(ui, words.reset_section.clone()) {
out.reset = true;
}
}
@@ -0,0 +1,87 @@
//! Stories of `PreferencesPage`.
use crate::contract::Bind;
use crate::patterns::preferences::{PageSpec, PrefValue, PreferencesModel, PreferencesPage, PreferencesState, RowKind, RowSpec};
use crate::testing::{Drive, StoryData, StoryOutput, story};
use craft_theme::Rgba;
use egui::Ui;
/// Settings that change as soon as a row does: a model with no draft, as an options page keeps.
#[derive(Clone, Debug, PartialEq)]
struct Live {
snap: bool,
name: String,
size: i64,
tint: Rgba,
}
impl Default for Live {
fn default() -> Self {
Live { snap: true, name: "Poster".to_owned(), size: 24, tint: Rgba([0xff, 0x88, 0x00, 0xff]) }
}
}
impl PreferencesModel for Live {
fn pages(&self) -> Vec<PageSpec<'_>> {
vec![
PageSpec::new(
"general",
"General",
vec![
RowSpec::new("general.snap", "Snap to grid", RowKind::Bool(self.snap)),
RowSpec::new("general.name", "Name", RowKind::Text(&self.name)),
],
),
PageSpec::new(
"canvas",
"Canvas",
vec![
RowSpec::new("canvas.size", "Brush size", RowKind::int(self.size, 1..=64)),
RowSpec::new("canvas.tint", "Tint", RowKind::Color(self.tint)),
],
),
]
}
fn set(&mut self, key: &str, value: PrefValue) {
match (key, value) {
("general.snap", PrefValue::Bool(on)) => self.snap = on,
("general.name", PrefValue::Text(text)) => self.name = text,
("canvas.size", PrefValue::Int(size)) => self.size = size,
("canvas.tint", PrefValue::Color(tint)) => self.tint = tint,
_ => {}
}
}
fn custom_row(&mut self, _: &mut Ui, _: &str) {}
fn custom_page(&mut self, _: &mut Ui, _: &str) {}
fn reset_page(&mut self, page: &str) {
let defaults = Live::default();
match page {
"general" => (self.snap, self.name) = (defaults.snap, defaults.name),
"canvas" => (self.size, self.tint) = (defaults.size, defaults.tint),
_ => {}
}
}
}
/// The page over the story's settings.
fn page(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let mut live = data.value("live", Live::default()).clone();
let shown = PreferencesPage::new(Bind::bound(data.value("state", PreferencesState::default()))).show(ui, &mut live);
*data.value("live", Live::default()) = live;
shown.into()
}
#[story(PreferencesPage<'static>, covers = [], drive = Drive::Never)]
fn preferences_page(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
page(ui, data)
}
/// The search field takes the focus first, so the typed text lands in it.
#[story(PreferencesPage<'static>, covers = [], drive = Drive::Type("size"))]
fn preferences_page_searching(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
page(ui, data)
}
@@ -4,12 +4,12 @@
#[cfg(feature = "testing")]
mod stories;
use super::body::{self, BodyOut};
#[cfg(doc)]
use super::model::PreferencesModel;
use super::model::{Closed, PreferencesDraft, PreferencesOutput};
use super::page::PreferencesPage;
use super::words::PreferencesWords;
use crate::contract::{Bind, Props as _, Remember, SaveKey, Show as _, ShowContainer as _};
use crate::contract::{Bind, Props as _, SaveKey, Show as _, ShowContainer as _};
use crate::dialog::{Dialog, DialogOutput};
use crate::notices::{Notice, NoticeLayout};
use crate::runtime::env::{Env, Label};
@@ -18,7 +18,6 @@ use crate::runtime::overlay::CloseReason;
use crate::runtime::words::CommonWords;
use crate::sections::{DialogRole, FooterButton};
use craft_behavior::{EditEvent, Mixed};
use craft_i18n::matcher::Matcher;
use craft_theme::variant::Tone;
use egui::{Ui, Vec2, vec2};
use std::cell::RefCell;
@@ -44,7 +43,8 @@ pub struct PreferencesState {
/// The preferences window: a search field over a page list and the shown page, with OK, Cancel and Apply under them.
///
/// The host keeps the model ([`PreferencesModel`]) and calls [`show`](PreferencesWindow::show) on every pass the window
/// The body is a [`PreferencesPage`] over the window's state. The host keeps the model ([`PreferencesModel`] and
/// [`PreferencesDraft`]) and calls [`show`](PreferencesWindow::show) on every pass the window
/// should exist; it stops calling to close the window, and does so when the output says `closed`.
///
/// - **Pages and search.** The host builds the pages each pass; the window lists the pages that match the search (the
@@ -91,17 +91,14 @@ struct Session<'h, 'b, H: ?Sized> {
}
impl<H: PreferencesDraft + ?Sized> Session<'_, '_, H> {
/// Reads the state at the start of the body. A window that has just opened starts with no search and no error.
fn begin(&mut self, cx: &mut (impl StageAccess + Remember)) {
/// Reads the state at the start of the body. The page clears the search and the error of a window that has just
/// opened.
fn begin(&mut self, cx: &mut impl StageAccess) {
self.before = match self.state.reborrow().read(cx) {
Some(Mixed::Same(held)) => held,
_ => PreferencesState::default(),
};
self.work = self.before.clone();
if cx.appeared() {
self.work.search.clear();
self.work.error = None;
}
}
/// Writes the state the pass changed through the binding.
@@ -141,7 +138,6 @@ impl<'a> PreferencesWindow<'a> {
let env = Env::of(ui);
let words = env.words::<PreferencesWords>();
let common = env.words::<CommonWords>();
let units = env.units();
let nested = host.nested_open();
let can_ok = host.can_ok() && !nested;
@@ -197,27 +193,12 @@ impl<'a> PreferencesWindow<'a> {
let mut guard = session.borrow_mut();
let session = &mut *guard;
session.begin(cx);
let matcher = Matcher::new(&env.folder(), session.work.search.trim());
let snap = body::snapshot(&*session.host, &matcher, &session.work.selected);
let mut out = BodyOut::default();
body::show_body(ui, &mut *session.host, &snap, &mut session.work, &words, &units, &mut out);
if let Some(request) = out.rows.pick_color.take() {
let shown = PreferencesPage::new(Bind::bound(&mut session.work)).show(ui, &mut *session.host);
if let Some(request) = shown.pick_color {
pick_color = Some(request);
}
let edits = out.edits();
if !edits.is_empty() || out.reset {
session.work.error = None;
}
for (key, value) in edits {
session.host.set(&key, value);
}
if out.reset
&& let Some(page) = &snap.shown
{
session.host.reset_page(&page.id);
}
session.host.nested(ui.ctx());
session.page = snap.shown.map(|page| page.id);
session.page = shown.page;
session.commit(cx);
});
@@ -25,6 +25,7 @@ mod group_view;
mod workspace_dialogs;
mod native;
mod panes;
/// The docking sizes of the default theme with the given divider gap, least pane and strip height.
fn sizes(gap: f32, least_pane: f32, strip: f32) -> DockSizes {
@@ -0,0 +1,173 @@
//! `PaneArea`: a pane docks only at the edges its spec allows, and Escape during a pane's title drag cancels the drag.
use craft_behavior::Intent;
use craft_ui::contract::{BodyCx, PaneEdge, Role};
use craft_ui::docking::GroupDrag;
use craft_ui::patterns::dock::{PaneArea, PaneCommands, PaneContent, PaneEdges, PanePlace, PaneRequest, PaneSpec, PaneState};
use craft_ui::runtime::commands::{FireSource, fire};
use craft_ui::runtime::{drag, keys};
use craft_ui::testing::pointer::{moved, press, release};
use craft_ui::testing::{Fixture, trial};
use egui::{Key, Modifiers, Pos2, Rect, Ui, Vec2};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
const ROOM: Vec2 = Vec2::new(900.0, 600.0);
/// The floating frame a pane starts in, clear of every edge band.
const FLOAT: Rect = Rect { min: Pos2::new(300.0, 200.0), max: Pos2::new(540.0, 360.0) };
/// A point on a floating frame's title row, clear of the action parts at its end.
const TITLE_AT: Vec2 = Vec2::new(24.0, 10.0);
/// The app's one pane: it docks at `edges` and the app keeps its state by applying the area's requests.
struct Panes {
edges: PaneEdges,
state: Rc<Cell<PaneState>>,
}
impl PaneContent<u32> for Panes {
fn spec(&self, pane: &u32) -> PaneSpec {
let mut spec = PaneSpec::new(format!("Pane {pane}"), PaneState::floating(FLOAT), FLOAT.size());
spec.edges = self.edges;
spec
}
fn state(&self, _: &u32) -> Option<PaneState> {
Some(self.state.get())
}
fn body(&mut self, _: &u32, _: &mut Ui, _: &mut BodyCx<'_>) {}
}
/// A pane area of one pane starting at `start`, with what the app saw.
struct Bed {
fixture: Fixture,
state: Rc<Cell<PaneState>>,
requests: Rc<RefCell<Vec<PaneRequest<u32>>>>,
/// The window Cancels no component took, read last in the UI.
window_cancels: Rc<Cell<usize>>,
}
fn bed(edges: PaneEdges, start: PaneState) -> Bed {
let state = Rc::new(Cell::new(start));
let requests = Rc::new(RefCell::new(Vec::new()));
let window_cancels = Rc::new(Cell::new(0));
let (kept, seen, cancels) = (Rc::clone(&state), Rc::clone(&requests), Rc::clone(&window_cancels));
let mut fixture = Fixture::new(move |ui| {
let mut content = Panes { edges, state: Rc::clone(&kept) };
let out = PaneArea::new("Panes", &[0_u32], &mut content).show(ui, |_, _| {});
for request in out.requests {
let mut next = kept.get();
next.apply(&request);
kept.set(next);
seen.borrow_mut().push(request);
}
if keys::with_window_intents(ui.ctx(), false, |window| window.take(Intent::Cancel)) {
cancels.set(cancels.get() + 1);
}
});
fixture.room(ROOM).settle();
Bed { fixture, state, requests, window_cancels }
}
impl Bed {
/// The requests since the last call.
fn take(&self) -> Vec<PaneRequest<u32>> {
std::mem::take(&mut *self.requests.borrow_mut())
}
/// The places the requests since the last call asked for.
fn places(&self) -> Vec<PanePlace> {
self.take()
.into_iter()
.filter_map(|request| match request {
PaneRequest::Place(_, place) => Some(place),
_ => None,
})
.collect()
}
/// The point on the floating pane's title row.
fn title(&self) -> Pos2 {
self.state.get().float_rect.unwrap_or(FLOAT).min + TITLE_AT
}
/// Presses the floating pane's title and moves it to `to` in steps, leaving the button down.
fn hold_title_at(&mut self, to: Pos2) {
let from = self.title();
self.fixture.frame(vec![moved(from)]);
self.fixture.frame(vec![press(from)]);
for step in 1..=4 {
self.fixture.frame(vec![moved(from + (to - from) * (step as f32 / 4.0))]);
}
self.fixture.idle(1);
}
/// Whether the pane menu shows a row labelled `label`.
fn menu_has(&self, label: &str) -> bool {
self.fixture.by_label(label).is_some()
}
}
/// `PaneEdges::SIDES`: the pane menu lists no Move to Top or Bottom, a run of those commands does nothing, and a drop
/// in the top edge band is refused with no drop mark; Start and End still dock.
#[trial]
fn a_pane_offers_and_takes_only_its_dock_edges() {
let mut start = PaneState::docked(PaneEdge::Start, 200.0);
start.float_rect = Some(FLOAT);
let mut bed = bed(PaneEdges::SIDES, start);
let menu = bed.fixture.by_label("More actions").expect("the docked pane's menu button");
bed.fixture.click(&menu).idle(2);
assert!(bed.menu_has("Move to Start") && bed.menu_has("Move to End") && bed.menu_has("Float"), "the side moves and Float are listed");
// Start, End, Float and Close: a row for Top or Bottom, under any label, makes the count larger.
assert_eq!(bed.fixture.by_role(Role::MENU_ITEM).len(), 4, "no move to an edge the pane may not dock at");
bed.fixture.key(Key::Escape, Modifiers::NONE).idle(2);
bed.take();
for refused in [PaneCommands::MoveToTop, PaneCommands::MoveToBottom] {
assert!(!fire(bed.fixture.ctx(), refused, FireSource::Key), "{refused:?} is disabled for the pane");
bed.fixture.idle(2);
assert_eq!(bed.places(), Vec::new(), "{refused:?} moves nothing");
}
assert!(fire(bed.fixture.ctx(), PaneCommands::MoveToEnd, FireSource::Key), "Move to End runs");
bed.fixture.idle(2);
assert_eq!(bed.places(), vec![PanePlace::Docked(PaneEdge::End)], "the pane docks at the end edge");
assert!(fire(bed.fixture.ctx(), PaneCommands::Float, FireSource::Key), "Float runs");
bed.fixture.idle(2);
assert_eq!(bed.places(), vec![PanePlace::Floating]);
let area = bed.fixture.shown();
let top = Pos2::new(area.center().x, area.top() + 2.0);
bed.hold_title_at(top);
assert!(drag::active::<GroupDrag<u32>>(bed.fixture.ctx()).is_some(), "the title move started a window drag");
assert!(drag::mark(bed.fixture.ctx()).is_none(), "the top edge band takes no drop and draws no mark");
bed.fixture.frame(vec![release(top)]).idle(2);
assert_eq!(bed.places(), Vec::new(), "the release over the top edge docks nothing");
assert_eq!(bed.state.get().place, PanePlace::Floating);
let side = Pos2::new(area.left() + 2.0, area.center().y);
bed.hold_title_at(side);
assert!(drag::mark(bed.fixture.ctx()).is_some(), "the start edge band takes the drop and marks it");
bed.fixture.frame(vec![release(side)]).idle(2);
assert_eq!(bed.places(), vec![PanePlace::Docked(PaneEdge::Start)], "the release over the start edge docks the pane there");
}
/// Escape during a floating pane's title drag cancels the drag: no drop runs, the pane is back at the rect it had, and
/// neither the window nor the app sees the Escape.
#[trial]
fn escape_during_a_pane_title_drag_cancels_it_and_reaches_nothing_else() {
let mut bed = bed(PaneEdges::ALL, PaneState::floating(FLOAT));
bed.take();
let area = bed.fixture.shown();
let start = Pos2::new(area.left() + 2.0, area.center().y);
bed.hold_title_at(start);
assert!(drag::active::<GroupDrag<u32>>(bed.fixture.ctx()).is_some(), "the title move started a window drag");
assert!(drag::mark(bed.fixture.ctx()).is_some(), "over the start edge band a release would dock the pane");
bed.window_cancels.set(0);
bed.fixture.key(Key::Escape, Modifiers::NONE);
assert!(drag::active::<GroupDrag<u32>>(bed.fixture.ctx()).is_none(), "Escape cancelled the drag");
bed.fixture.frame(vec![release(start)]).idle(2);
assert_eq!(bed.places(), Vec::new(), "the release after Escape docks nothing");
assert_eq!(bed.state.get().place, PanePlace::Floating, "the pane stays floating");
assert_eq!(bed.state.get().float_rect, Some(FLOAT), "the pane is back where the drag began");
assert_eq!(bed.window_cancels.get(), 0, "the Escape went to the drag alone");
}
@@ -1,14 +1,16 @@
//! About's Contributors tab (the grab bag of name links and the Table view) and the hosted dialog's `tab` field.
//! About's Contributors tab (the grab bag of name links and the Table view and its order), the hosted dialog's `tab`
//! field and the app's own tabs.
use craft_ui::contract::{Bind, Role};
use craft_ui::dialog::{DialogHost, StackDialog as _};
use craft_ui::patterns::form_dialogs::{AboutDialog, AboutInfo, AboutTab, Contributor, Credits, HostedAbout, ModelCredit};
use craft_ui::patterns::form_dialogs::{AboutAppTab, AboutDialog, AboutInfo, AboutTab, Contributor, Credits, HostedAbout, ModelCredit};
use craft_ui::testing::{Fixture, trial};
use egui::Vec2;
use serde_json::json;
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::LazyLock;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, LazyLock};
static INFO: LazyLock<AboutInfo> = LazyLock::new(|| AboutInfo::new("PhotoCraft", "An image editor.", "1.0"));
static CREDITS: LazyLock<Credits> = LazyLock::new(|| {
@@ -64,3 +66,106 @@ fn about_tab_is_a_field() {
let fields = host.borrow().get::<HostedAbout>().and_then(|about| about.json_fields());
assert_eq!(fields, Some(json!({ "tab": "contributors" })), "the field lists the tab a click picked");
}
/// Guards the app tabs of the About dialog: an app tab is listed after Models, `tab` takes its name and shows its
/// body, a click on it reports its name in the field, and a name that is neither built in nor an app tab's is refused.
#[trial]
fn an_app_tab_shows_after_models_and_is_a_tab_field_value() {
let drawn = Arc::new(AtomicUsize::new(0));
let counted = Arc::clone(&drawn);
let languages = AboutAppTab::new("languageData", "Languages", move |_| {
counted.fetch_add(1, Ordering::Relaxed);
});
let host = Rc::new(RefCell::new(DialogHost::new()));
let shown = Rc::clone(&host);
let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui));
fixture.room(Vec2::new(1400.0, 1000.0));
let info = AboutInfo::new("PhotoCraft", "An image editor.", "1.0");
let id = host.borrow_mut().open(HostedAbout::new(info, CREDITS.clone()).app_tab(languages));
fixture.idle(10);
assert_eq!(drawn.load(Ordering::Relaxed), 0, "the dialog opens on About");
let tabs: Vec<String> =
fixture.by_role(Role::TAB).iter().filter_map(|tab| fixture.tree().name_of(tab.node).map(str::to_owned)).collect();
let models = tabs.iter().position(|name| name == "Models").expect("the strip lists Models");
assert_eq!(tabs.get(models + 1).map(String::as_str), Some("Languages"), "the app tab follows Models: {tabs:?}");
let ctx = fixture.ctx().clone();
host.borrow_mut().set_json_field(&ctx, id, "tab", json!("languageData")).expect("`tab` takes the app tab's name");
fixture.idle(4);
assert!(drawn.load(Ordering::Relaxed) > 0, "setting `tab` to the app tab's name shows its body");
host.borrow_mut().set_json_field(&ctx, id, "tab", json!("about")).expect("`tab` takes a built-in name");
fixture.idle(4);
let fields = host.borrow().get::<HostedAbout>().and_then(|about| about.json_fields());
assert_eq!(fields, Some(json!({ "tab": "about" })));
let app = fixture.by_label("Languages").expect("the strip offers the app tab");
fixture.click(&app).idle(4);
let fields = host.borrow().get::<HostedAbout>().and_then(|about| about.json_fields());
assert_eq!(fields, Some(json!({ "tab": "languageData" })), "the field names the app tab a click picked");
let refused = host.borrow_mut().set_json_field(&ctx, id, "tab", json!("languages"));
assert!(refused.is_err(), "a name that is no tab's is refused");
}
/// The contributors of the order trial: a capitalised login with a display name, an undated (pull request only)
/// contributor, and one with a real name.
static PEOPLE: LazyLock<Credits> = LazyLock::new(|| {
let dated = |login: &'static str, day: &'static str| Contributor::new(login).counts(0, 1).active(day, day);
Credits::new(
vec![
dated("zed", "2026-01-02T00:00:00Z").lines(5, 50),
dated("Bob", "2026-01-01T00:00:00Z").display_name("Ann").lines(10, 0),
Contributor::new("alice").counts(1, 0).lines(7, 1),
dated("carol", "2026-01-03T00:00:00Z").real_name("Dana").lines(1, 0),
],
Vec::new(),
3,
)
});
/// The contributors' names among `names` in the order the table shows them, top to bottom.
fn rows(fixture: &Fixture, names: &[&str]) -> Vec<String> {
let mut placed: Vec<(f32, &str)> =
names.iter().map(|name| (fixture.by_label(name).expect("the table lists every contributor").rect.top(), *name)).collect();
placed.sort_by(|a, b| a.0.total_cmp(&b.0));
placed.into_iter().map(|(_, name)| name.to_owned()).collect()
}
/// A press on the column head `head`. The idle frames outlast the double-click time, so a second press of the same
/// head is a click of its own.
fn sort_by(fixture: &mut Fixture, head: &str) {
let cell = fixture
.by_role(Role::COLUMN_HEADER)
.into_iter()
.find(|cell| fixture.tree().name_of(cell.node) == Some(head))
.expect("the table has the column");
fixture.click(&cell).idle(30);
}
/// Guards the contributors' order: names compare without the `@` and without case, a display name sorts among the
/// usernames, and a contributor with no commit date follows everyone with one whichever way the dates sort.
#[trial]
fn names_sort_without_at_and_case_and_undated_contributors_sort_last_both_ways() {
let mut fixture = Fixture::new(move |ui| {
let _ = AboutDialog::new(&INFO, &PEOPLE).tab(Bind::given(AboutTab::Contributors)).show(ui);
});
fixture.room(Vec2::new(1400.0, 1000.0)).idle(30);
let table = fixture.by_label("Table").expect("the View control offers Table");
fixture.click(&table).idle(30);
let logins = ["@zed", "@Bob", "@alice", "@carol"];
assert_eq!(rows(&fixture, &logins), ["@Bob", "@zed", "@carol", "@alice"], "oldest first commit first, the undated last");
sort_by(&mut fixture, "First");
assert_eq!(rows(&fixture, &logins), ["@carol", "@zed", "@Bob", "@alice"], "newest first commit first, the undated still last");
sort_by(&mut fixture, "Name");
assert_eq!(rows(&fixture, &logins), ["@alice", "@Bob", "@carol", "@zed"], "A to Z without the @ and without case");
sort_by(&mut fixture, "Name");
assert_eq!(rows(&fixture, &logins), ["@zed", "@carol", "@Bob", "@alice"], "Z to A");
let display = fixture.by_label("Display name").expect("the Show control offers Display name");
fixture.click(&display).idle(30);
sort_by(&mut fixture, "Name");
assert_eq!(rows(&fixture, &["@zed", "Ann", "@alice", "@carol"]), ["@alice", "Ann", "@carol", "@zed"], "a display name sorts among the usernames");
}
@@ -2,4 +2,5 @@
//! window's answers and the hex codec.
mod model;
mod page;
mod path_setting;
@@ -1,7 +1,6 @@
//! The settings document without a window: rows, applied edits, rebase and row conditions.
use craft_theme::Rgba;
// P3(chrome-w4): ch.C10
use craft_ui::patterns::preferences::{
CustomSettings, PageInfo, PrefValue, PreferencesDraft, PreferencesModel, RowKind, SettingRule, SettingsDocument, SettingsDraft, StandardPage,
};
@@ -0,0 +1,87 @@
//! `PreferencesPage` over a model with no draft: each edit reaches the model in the pass it lands in.
use craft_ui::contract::{Bind, Role};
use craft_ui::patterns::preferences::{
PageSpec, PrefValue, PreferencesModel, PreferencesPage, PreferencesState, PreferencesWords, RowKind, RowSpec,
};
use craft_ui::runtime::env::Env;
use craft_ui::runtime::words::CommonWords;
use craft_ui::testing::pointer::{moved, press, release};
use craft_ui::testing::{Fixture, trial};
use egui::Ui;
use std::cell::{Cell, RefCell};
use std::rc::Rc;
/// One page with one check box row. Every `set` is recorded with the index of the pass it ran in. The model implements
/// no `PreferencesDraft`, so nothing can apply or cancel a draft.
#[derive(Default)]
struct Live {
snap: bool,
pass: usize,
sets: Vec<(String, PrefValue, usize)>,
}
impl PreferencesModel for Live {
fn pages(&self) -> Vec<PageSpec<'_>> {
vec![PageSpec::new("general", "General", vec![RowSpec::new("general.snap", "Snap to grid", RowKind::Bool(self.snap))])]
}
fn set(&mut self, key: &str, value: PrefValue) {
if let ("general.snap", PrefValue::Bool(on)) = (key, &value) {
self.snap = *on;
}
self.sets.push((key.to_owned(), value, self.pass));
}
fn custom_row(&mut self, _: &mut Ui, _: &str) {}
fn custom_page(&mut self, _: &mut Ui, _: &str) {}
fn reset_page(&mut self, _: &str) {}
}
/// Guards the apply-at-once path of an options page: a click on a check box calls `set` once, with the new value, in
/// the pass that received the click, and a second pass of the same frame does not call it again. The page shows none
/// of a window's OK, Cancel or Apply.
#[trial]
fn a_page_edit_reaches_the_model_in_the_same_pass_and_no_draft_method_runs() {
let live = Rc::new(RefCell::new(Live::default()));
let footer = Rc::new(RefCell::new(Vec::<String>::new()));
let rerun = Rc::new(Cell::new(false));
let (shown, words, twice) = (Rc::clone(&live), Rc::clone(&footer), Rc::clone(&rerun));
let mut state = PreferencesState::default();
let mut fixture = Fixture::new(move |ui| {
if twice.get() && ui.ctx().current_pass_index() == 0 {
ui.ctx().request_discard("the trial runs a second pass");
}
let env = Env::of(ui);
let (common, own) = (env.words::<CommonWords>(), env.words::<PreferencesWords>());
*words.borrow_mut() = vec![common.ok.as_str().to_owned(), common.cancel.as_str().to_owned(), own.apply.as_str().to_owned()];
let mut live = shown.borrow_mut();
live.pass = ui.ctx().current_pass_index();
PreferencesPage::new(Bind::bound(&mut state)).show(ui, &mut *live);
});
fixture.settle();
let buttons: Vec<String> =
fixture.by_role(Role::BUTTON).iter().filter_map(|button| fixture.tree().name_of(button.node).map(str::to_owned)).collect();
assert!(!buttons.is_empty(), "the page shows Reset Section");
assert!(buttons.iter().all(|name| !footer.borrow().contains(name)), "the page has no OK, Cancel or Apply: {buttons:?}");
let check = fixture.by_role(Role::CHECK_BOX).into_iter().next().expect("the row shows a check box");
fixture.frame(vec![moved(check.center())]);
assert!(live.borrow().sets.is_empty(), "a hover edits nothing");
rerun.set(true);
fixture.frame(vec![press(check.center())]);
fixture.frame(vec![release(check.center())]);
assert!(fixture.passes() >= 2, "the click's frame ran a second pass");
rerun.set(false);
assert_eq!(
live.borrow().sets,
vec![("general.snap".to_owned(), PrefValue::Bool(true), 0)],
"one set, with the new value, in the first pass of the click's frame"
);
fixture.settle();
assert_eq!(live.borrow().sets.len(), 1, "later passes apply nothing again");
assert!(live.borrow().snap, "the model holds the value");
}
+84
View File
@@ -0,0 +1,84 @@
//! F6 through the app shell: the pane move visits the shell's slots in their order, then the body, then wraps.
use craft_ui::buttons::Button;
use craft_ui::contract::Show as _;
use craft_ui::runtime::env::WindowKey;
use craft_ui::shell::{AppShell, Slot};
use craft_ui::testing::focus::egui_focused;
use craft_ui::testing::input::key_press;
use craft_ui::testing::{Frames, trial};
use egui::{Id, Key, Modifiers, Ui};
use std::cell::RefCell;
use std::rc::Rc;
/// The key the trial gives the body pane beside the slot keys.
const BODY: &str = "body";
/// What the shell showed in its last pass: the id of the one button in each pane, and the slot keys in the order the
/// shell laid them out.
#[derive(Default)]
struct Seen {
buttons: Vec<(&'static str, Id)>,
order: Vec<&'static str>,
}
impl Seen {
/// The pane whose button has egui focus.
fn pane_of(&self, focused: Option<Id>) -> Option<&'static str> {
let focused = focused?;
self.buttons.iter().find(|(_, id)| *id == focused).map(|(key, _)| *key)
}
}
/// A shell with a slot at every edge, added out of the shell's order (end before start, a bottom slot before a top
/// one), each holding one button, and a body holding one button.
fn shell(seen: &Rc<RefCell<Seen>>) -> impl FnMut(&mut Ui) {
let seen = Rc::clone(seen);
move |ui: &mut Ui| {
let buttons = RefCell::new(Vec::new());
let button = |ui: &mut Ui, key: &'static str| {
let id = Button::new(key).show(ui).response.id;
buttons.borrow_mut().push((key, id));
};
let shown = AppShell::new(WindowKey::main())
.end(Slot::new("inspector"), |ui, _, _: &mut ()| button(ui, "inspector"))
.status(true, |ui, _, _| button(ui, "status"))
.start(Slot::new("tools"), |ui, _, _| button(ui, "tools"))
.options_bar(true, |ui, _, _| button(ui, "options"))
.body(|ui, _, _| button(ui, BODY))
.show(ui, &mut ());
let mut seen = seen.borrow_mut();
seen.buttons = buttons.into_inner();
seen.order = shown.regions.slots.iter().map(|(key, _)| *key).collect();
}
}
/// A press of F6 with `mods` and the frame after it, in which the move's focus lands: the pane that has the focus then.
fn f6(frames: &mut Frames, show: &mut impl FnMut(&mut Ui), seen: &RefCell<Seen>, mods: Modifiers) -> Option<&'static str> {
frames.frame(vec![key_press(Key::F6, mods)], &mut *show);
frames.frame(Vec::new(), &mut *show);
seen.borrow().pane_of(egui_focused(&frames.ctx))
}
/// From nothing focused, F6 visits every slot in the shell's layout order (the F6 order `AppShell` documents), then
/// the body, then wraps to the first slot; Shift+F6 walks the same cycle backwards.
#[trial]
fn f6_cycles_the_slots_the_panes_and_the_body_and_wraps() {
let seen = Rc::new(RefCell::new(Seen::default()));
let mut show = shell(&seen);
let mut frames = Frames::new();
frames.idle(2, &mut show);
let mut cycle: Vec<&'static str> = seen.borrow().order.clone();
assert_eq!(cycle.len(), 4, "every slot shows: {cycle:?}");
cycle.push(BODY);
assert_eq!(seen.borrow().pane_of(egui_focused(&frames.ctx)), None, "nothing has the focus before F6");
let forward: Vec<Option<&'static str>> = (0..cycle.len()).map(|_| f6(&mut frames, &mut show, &seen, Modifiers::NONE)).collect();
assert_eq!(forward, cycle.iter().copied().map(Some).collect::<Vec<_>>(), "F6 visits the slots in the shell's order, then the body");
assert_eq!(f6(&mut frames, &mut show, &seen, Modifiers::NONE), Some(cycle[0]), "F6 past the body wraps to the first slot");
let backward: Vec<Option<&'static str>> = (0..cycle.len()).map(|_| f6(&mut frames, &mut show, &seen, Modifiers::SHIFT)).collect();
// From the first slot Shift+F6 wraps to the body and walks back to the first slot.
let reversed: Vec<Option<&'static str>> = cycle.iter().rev().copied().map(Some).collect();
assert_eq!(backward, reversed, "Shift+F6 walks the cycle backwards, wrapping from the first slot to the body");
}
+1
View File
@@ -5,6 +5,7 @@ mod canvas_panel;
mod caption_button;
mod document_window;
mod embed;
mod f6;
mod opening;
mod reveal;
mod screen_mode;