mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-30 02:04:32 +01:00
fw-patterns: resolve the origin/next sync for ui-patterns dock area, form dialogs, preferences, preset browser and their trials
Dock area: upstream's specs/Arc workspace/memo rewrite with the port's top inset, rail footer, IconicMode::Rail widths, group view room and title count/caption/command re-applied. Form dialogs: upstream's held answer, preset sources and button place with the port's tabs, read-only, Document layout, host notes, one action channel and preview pager; both beside_previous and beside_next rows in one section_rows; SetOrClear carried into PasswordFields as an opt-in clearable. Preferences (L-312): upstream's PreferencesPage structure with a PreferencesLayout option, Paged by default, Cards carrying the port's scrolling cards, segmented short choices and match count; body.rs removed.
This commit is contained in:
33 files changed
+835
-1567
No files matched your search
@@ -5,27 +5,18 @@ use super::hide::{self, PruneKey};
|
||||
use crate::contract::Revision;
|
||||
use crate::contract::overlay::{PlacementChange, PlacementKind};
|
||||
use crate::contract::{
|
||||
<<<<<<< HEAD
|
||||
Bind, BindMut, BodyCx, Cx, Entry, Gap, Lazy, NoValue, Outcome, Pad, Pointer as _, Props as _, ShowContainer as _, Sizing, WordSetCx as _,
|
||||
=======
|
||||
Bind, BindMut, BodyCx, Cx, Entry, MemoKey, MemoProps, MemoView, NoValue, Outbox, Outcome, Pad, Pointer as _, Props as _, Show as _,
|
||||
Bind, BindMut, BodyCx, Cx, Entry, Gap, MemoKey, MemoProps, MemoView, NoValue, Outbox, Outcome, Pad, Pointer as _, Props as _, Show as _,
|
||||
ShowContainer as _, Sizing, Tracked, WordSetCx as _,
|
||||
>>>>>>> origin/next
|
||||
};
|
||||
use crate::docking::SplitFramesCx as _;
|
||||
use crate::docking::stack::{StackSection, StackSections, section_heights};
|
||||
use crate::docking::tree::FrameRules;
|
||||
use crate::docking::{Arrangement, close_requests, cross_window, end_replaced_drags, float_drop, native, open_requests};
|
||||
use crate::docking::{
|
||||
ColumnArrow, ColumnBar, DockColumn, DockCommands, DockConfig, DockDropTarget, DockDropped, DockEvent, DockGroup, DockPanels, DockRoot, DockScene,
|
||||
<<<<<<< HEAD
|
||||
DockSizes, DockSpot, DockTargets, DockTo, DockWords, DragUnit, FloatSpace, FloatingGroup, FlyoutResize, GroupAt, GroupDrag, HidePanels,
|
||||
IconicColumn, IconicMode, IconicSizes, PanelDrag, PanelKey, PanelSpec, PanelTitle, SplitArea, WindowColumn, actions, dock_states, fit_widths,
|
||||
frame, move_actions, stepped,
|
||||
=======
|
||||
DockSizes, DockSpot, DockTargets, DockTo, DockWords, DragUnit, FloatSpace, FloatingGroup, FlyoutResize, GroupAt, GroupDrag, GroupGrip,
|
||||
HidePanels, IconicColumn, IconicSizes, PanelDrag, PanelKey, PanelSpec, PanelSpecs, PanelTitle, Placing, SpecSource, SplitArea, Titles,
|
||||
WindowColumn, actions, column_cells, dock_states, frame, move_actions, with_area_rules,
|
||||
>>>>>>> origin/next
|
||||
HidePanels, IconicColumn, IconicMode, IconicSizes, PanelDrag, PanelKey, PanelSpec, PanelSpecs, PanelTitle, Placing, SpecSource, SplitArea,
|
||||
Titles, WindowColumn, actions, dock_states, fit_widths, frame, move_actions,
|
||||
};
|
||||
use crate::layout_components::Stack;
|
||||
use crate::menu::{GroupItem, MenuWords, PanelMenu, PanelRow};
|
||||
@@ -42,13 +33,8 @@ use craft_behavior::dock::{
|
||||
use craft_behavior::overlay::Side;
|
||||
use craft_behavior::{CancelReason, DockSide, EditEvent, EditEvents, Flow, GestureId, GesturePhase, Mixed, Proposal};
|
||||
use craft_host::target::WindowKind;
|
||||
<<<<<<< HEAD
|
||||
use egui::{Context, Id, Pos2, Rect, Response, Ui, Vec2, ViewportId};
|
||||
use std::cell::{Cell, RefCell};
|
||||
=======
|
||||
use egui::{Context, Id, Pos2, Rect, Response, Ui, UiBuilder, Vec2, ViewportId};
|
||||
use std::cell::{Cell, OnceCell, RefCell};
|
||||
>>>>>>> origin/next
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::Debug;
|
||||
use std::hash::Hash;
|
||||
@@ -265,17 +251,12 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Drops<'_, P> {
|
||||
fn take(&self, cx: &mut Cx<'_, DockRoot<'_, DockDropped<P>>>) -> Option<DockDropped<P>> {
|
||||
let ctx = cx.core.ctx.clone();
|
||||
let sizes = *cx.style.sizes();
|
||||
<<<<<<< HEAD
|
||||
let bounds = inset_top(cx.env.get::<ShellEntry>().0.as_ref().map_or(cx.rect, ShellCx::float_bounds), self.top_inset);
|
||||
let space = float_space(bounds, &sizes, self.config, self.specs);
|
||||
=======
|
||||
let shell = cx.env.get::<ShellEntry>().0;
|
||||
let bounds = shell.as_ref().map_or(cx.rect, ShellCx::float_bounds);
|
||||
let bounds = inset_top(shell.as_ref().map_or(cx.rect, ShellCx::float_bounds), self.top_inset);
|
||||
let space = float_space(&ctx, bounds, &sizes, self.config, self.specs);
|
||||
let spec = |panel: &P| spec_in(self.specs, panel);
|
||||
let protected = |panel: &P| (self.permissions)(panel).is_protected();
|
||||
let (hide, _) = hide::resolved(self.hide, shell.as_ref());
|
||||
>>>>>>> origin/next
|
||||
let mut target = DockDropTarget::new(&ctx, self.dock, self.layout, self.permissions);
|
||||
target.rtl = self.rtl;
|
||||
target.space = Some(&space);
|
||||
@@ -381,7 +362,9 @@ impl<P: Clone + Eq + Hash> Scene<'_, P> {
|
||||
fn rail_beside(&self, column: &Column<P>) -> bool {
|
||||
let spec = |panel: &P| self.spec(panel);
|
||||
let collapses = column.panels().all(|panel| self.permissions(panel).collapses);
|
||||
self.config.iconic_mode == IconicMode::Rail && !column.iconic && ColumnArrow::of(column, &spec, collapses) == ColumnArrow::Collapse
|
||||
self.config.iconic_mode == IconicMode::Rail
|
||||
&& !column.iconic
|
||||
&& ColumnArrow::of(column, &self.sizes, &spec, collapses) == ColumnArrow::Collapse
|
||||
}
|
||||
|
||||
/// The `(width, floor)` of each docked column of a dock, for [`fit_widths`]: a rail beside an expanded column adds
|
||||
@@ -481,11 +464,8 @@ struct Pass<'s, P> {
|
||||
impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> {
|
||||
/// Shows the area across the room offered.
|
||||
pub fn show(self, ui: &mut Ui) -> DockAreaOutput<P> {
|
||||
<<<<<<< HEAD
|
||||
let DockArea { label, mut workspace, panels, config, hide, maximized, auto_collapse, locked, mut flyout, rail_footer, top_inset } = self;
|
||||
=======
|
||||
let DockArea { label, mut workspace, specs, panels, config, hide, maximized, auto_collapse, locked, mut flyout } = self;
|
||||
>>>>>>> origin/next
|
||||
let DockArea { label, mut workspace, specs, panels, config, hide, maximized, auto_collapse, locked, mut flyout, rail_footer, top_inset } =
|
||||
self;
|
||||
let ctx = ui.ctx().clone();
|
||||
let (rtl, window) = {
|
||||
let env = Env::of(ui);
|
||||
@@ -502,11 +482,6 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> {
|
||||
let current = if error.is_none() { held } else { Arc::default() };
|
||||
let rights = &model.rights;
|
||||
let policy = |panel: &P| rights.get(panel).copied().unwrap_or(Permissions::ALL);
|
||||
<<<<<<< HEAD
|
||||
let specs: HashMap<P, PanelSpec> = current.layout.panels().into_iter().map(|panel| (panel.clone(), panels.spec(panel))).collect();
|
||||
let drops = Drops { dock: id, layout: ¤t.layout, permissions: &policy, config: &config, specs: &specs, rtl, top_inset };
|
||||
let shows = Arrangement { dock: id, revision: current.revision() };
|
||||
=======
|
||||
let drops = Drops {
|
||||
dock: id,
|
||||
layout: current.layout(),
|
||||
@@ -516,9 +491,9 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> {
|
||||
hide,
|
||||
maximized: maximized.as_ref(),
|
||||
rtl,
|
||||
top_inset,
|
||||
};
|
||||
let shows = Arrangement { dock: id, generation: current.generation() };
|
||||
>>>>>>> origin/next
|
||||
end_replaced_drags::<P>(&ctx, shows);
|
||||
let dropped: RefCell<Option<Action<P>>> = RefCell::new(None);
|
||||
let root = DockRoot::new(|cx| {
|
||||
@@ -684,11 +659,7 @@ fn show_area<P: Clone + Eq + Hash + Debug + Send + Sync + 'static>(
|
||||
panels: &mut dyn DockPanels<P>,
|
||||
mut flyout: Option<&mut Bind<'_, Option<P>>>,
|
||||
) -> Passed<P> {
|
||||
<<<<<<< HEAD
|
||||
let Input { id, ctx, current, config, specs, hide, maximized, auto_collapse, sizes, rtl, rail_footer, top_inset } = *input;
|
||||
=======
|
||||
let Input { id, ctx, current, config, specs, keys, hide, model, maximized, auto_collapse, sizes, rtl } = *input;
|
||||
>>>>>>> origin/next
|
||||
let Input { id, ctx, current, config, specs, keys, hide, model, maximized, auto_collapse, sizes, rtl, rail_footer, top_inset } = *input;
|
||||
let shell = body.shell();
|
||||
let mut memory = body.memory::<AreaMemory<P>>().clone();
|
||||
let protected = |panel: &P| rights.get(panel).is_some_and(|rights| rights.is_protected());
|
||||
@@ -696,13 +667,8 @@ fn show_area<P: Clone + Eq + Hash + Debug + Send + Sync + 'static>(
|
||||
let prune = PruneKey { model, hide, floating, maximized: maximized.map(PanelKey::of) };
|
||||
let view = derived(ctx, id.with("pruned"), &prune, || frame::maximize(current.layout(), maximized, hide, &protected).into_owned());
|
||||
let layout: &Layout<P> = &view.layout;
|
||||
<<<<<<< HEAD
|
||||
let bounds = inset_top(shell.as_ref().map_or(body.rect, ShellCx::float_bounds), top_inset);
|
||||
let space = float_space(bounds, &sizes, config, specs);
|
||||
=======
|
||||
let bounds = shell.as_ref().map_or(body.rect, ShellCx::float_bounds);
|
||||
let space = float_space(ctx, bounds, &sizes, config, specs);
|
||||
>>>>>>> origin/next
|
||||
let scene = Scene {
|
||||
dock: id,
|
||||
view: MemoKey::of(&prune),
|
||||
@@ -716,12 +682,8 @@ fn show_area<P: Clone + Eq + Hash + Debug + Send + Sync + 'static>(
|
||||
bounds,
|
||||
auto_collapse,
|
||||
rtl,
|
||||
<<<<<<< HEAD
|
||||
floated: ¤t.floated,
|
||||
rail_footer,
|
||||
=======
|
||||
floated: current.floated(),
|
||||
>>>>>>> origin/next
|
||||
rail_footer,
|
||||
};
|
||||
let open = open_of(&mut flyout, body, &memory);
|
||||
let mut pass = Pass {
|
||||
@@ -740,38 +702,32 @@ fn show_area<P: Clone + Eq + Hash + Debug + Send + Sync + 'static>(
|
||||
dock: id,
|
||||
};
|
||||
|
||||
<<<<<<< HEAD
|
||||
let limits = |panel: &P| scene.spec(panel).limits;
|
||||
let dock_width = |columns: &[Column<P>]| scene.natural(columns).iter().map(|(width, _)| *width).sum::<f32>();
|
||||
let stripless = |panel: &P| scene.spec(panel).canvas;
|
||||
let rules = FrameRules::new(&limits).dock_width(&dock_width).stripless(&stripless);
|
||||
=======
|
||||
let spec_of = |panel: &P| scene.spec(panel);
|
||||
>>>>>>> origin/next
|
||||
let label = Label::from(body.words::<DockWords>().panels.as_str().to_owned());
|
||||
let mut leaves: Vec<(Vec<bool>, Rect)> = Vec::new();
|
||||
let area = with_area_rules(&scene.sizes, &spec_of, |rules| {
|
||||
SplitArea::new(label, Bind::given(layout.clone()), rules).show(ui, |ui, split| {
|
||||
DockTargets::<P>::register_room(ctx, id, split.rect);
|
||||
for (anchor, rect) in split.group_frames::<P>() {
|
||||
let Some(place) = scene.layout.place(&anchor) else { continue };
|
||||
let Some(node) = scene.layout.node_of(&place) else { continue };
|
||||
if let PanelPlace::Node(path) = &place {
|
||||
leaves.push((path.clone(), rect));
|
||||
}
|
||||
pass.leaf(ui, split, node, rect);
|
||||
}
|
||||
let flow = Flow::new(split.rect, rtl);
|
||||
for (edge, rect) in split.dock_frames() {
|
||||
let Some(path) = scene.layout.dock_path(edge) else { continue };
|
||||
let Some(Node::Dock { columns, .. }) = scene.layout.root.as_ref().and_then(|root| node_at(root, &path)) else { continue };
|
||||
let area = SplitArea::new(label, Bind::given(layout.clone()), rules).show(ui, |ui, split| {
|
||||
DockTargets::<P>::register_room(ctx, id, split.rect);
|
||||
for (anchor, rect) in split.group_frames::<P>() {
|
||||
let Some(place) = scene.layout.place(&anchor) else { continue };
|
||||
let Some(node) = scene.layout.node_of(&place) else { continue };
|
||||
if let PanelPlace::Node(path) = &place {
|
||||
leaves.push((path.clone(), rect));
|
||||
if let Some(shell) = shell.as_ref().filter(|shell| shell.revealed()) {
|
||||
shell.reveal_rect(ctx, if edge == DockEdge::Start { RevealEdge::Start } else { RevealEdge::End }, rect);
|
||||
}
|
||||
pass.dock(ui, split, DockPlan { edge, columns, rect, flow, open: open.clone() });
|
||||
}
|
||||
})
|
||||
pass.leaf(ui, split, node, rect);
|
||||
}
|
||||
let flow = Flow::new(split.rect, rtl);
|
||||
for (edge, rect) in split.dock_frames() {
|
||||
let Some(path) = scene.layout.dock_path(edge) else { continue };
|
||||
let Some(Node::Dock { columns, .. }) = scene.layout.root.as_ref().and_then(|root| node_at(root, &path)) else { continue };
|
||||
leaves.push((path.clone(), rect));
|
||||
if let Some(shell) = shell.as_ref().filter(|shell| shell.revealed()) {
|
||||
shell.reveal_rect(ctx, if edge == DockEdge::Start { RevealEdge::Start } else { RevealEdge::End }, rect);
|
||||
}
|
||||
pass.dock(ui, split, DockPlan { edge, columns, rect, flow, open: open.clone() });
|
||||
}
|
||||
});
|
||||
let mut edit = area.output.edit.events.map(|edited| {
|
||||
let mut layout = current.layout().clone();
|
||||
@@ -1063,28 +1019,6 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
|
||||
let scene = self.scene;
|
||||
let anchor = members.first()?;
|
||||
let active = active.min(members.len() - 1);
|
||||
<<<<<<< HEAD
|
||||
let viewed = match at {
|
||||
// The view draws in the group's rect as a layout room of its own: it lays out in the group's room, never in
|
||||
// the room the area has left, and a view that fills takes the whole group.
|
||||
GroupAt::Show(rect) => in_room(ui, rect, |ui| self.panels.group_view(members, active, ui, at, body)),
|
||||
GroupAt::Measure(_) => self.panels.group_view(members, active, ui, at, body),
|
||||
};
|
||||
if let Some(height) = viewed {
|
||||
return matches!(at, GroupAt::Measure(_)).then_some(height);
|
||||
}
|
||||
let titles: Vec<PanelTitle> = members
|
||||
.iter()
|
||||
.map(|panel| {
|
||||
let spec = scene.spec(panel);
|
||||
PanelTitle::new(PanelKey::of(panel), spec.label)
|
||||
.closable(scene.permissions(panel).closable)
|
||||
.command(spec.command)
|
||||
.count(spec.count)
|
||||
.caption(spec.caption)
|
||||
})
|
||||
.collect();
|
||||
=======
|
||||
// A tool rail (a panel with a grid) that the host shows itself gets the dock's grip strip on top, under its
|
||||
// column bar, as the references' toolbar: the host's view takes the room under it.
|
||||
let grip = if members.get(active).is_some_and(|panel| scene.spec(panel).grid.is_some()) { scene.sizes.grip } else { 0.0 };
|
||||
@@ -1093,7 +1027,6 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
|
||||
{
|
||||
return Some(height + grip);
|
||||
}
|
||||
>>>>>>> origin/next
|
||||
let shown = &members[active];
|
||||
let words = body.words::<MenuWords>();
|
||||
let ctx = ui.ctx().clone();
|
||||
@@ -1110,7 +1043,14 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
|
||||
Titles::from_content(
|
||||
members
|
||||
.iter()
|
||||
.map(|panel| PanelTitle::new(PanelKey::of(panel), scene.spec(panel).label).closable(scene.permissions(panel).closable))
|
||||
.map(|panel| {
|
||||
let spec = scene.spec(panel);
|
||||
PanelTitle::new(PanelKey::of(panel), spec.label)
|
||||
.closable(scene.permissions(panel).closable)
|
||||
.command(spec.command)
|
||||
.count(spec.count)
|
||||
.caption(spec.caption)
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
});
|
||||
@@ -1172,12 +1112,8 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
|
||||
let (strip, view) = if grip > 0.0 { rect.split_top_bottom_at_y(rect.top() + grip.min(rect.height())) } else { (Rect::NOTHING, rect) };
|
||||
let output = ui
|
||||
.scope_builder(UiBuilder::new().max_rect(rect), |ui| {
|
||||
let taken = ui
|
||||
.scope_builder(UiBuilder::new().max_rect(view), |ui| {
|
||||
ui.shrink_clip_rect(view);
|
||||
panels.borrow_mut().group_view(members, active, ui, GroupAt::Show(view), body)
|
||||
})
|
||||
.inner;
|
||||
// The view is a layout room of its own: a view that fills takes the whole group.
|
||||
let taken = in_room(ui, view, |ui| panels.borrow_mut().group_view(members, active, ui, GroupAt::Show(view), body));
|
||||
match taken {
|
||||
Some(_) => None,
|
||||
None => Some(make(active, look.minimized).show_at(ui, rect, |ui, body| panel_body(&panels, shown, ui, body)).output),
|
||||
@@ -1255,7 +1191,6 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
|
||||
/// The columns of a dock, from the window edge inwards.
|
||||
fn dock(&mut self, ui: &mut Ui, body: &mut BodyCx<'_>, plan: DockPlan<'_, P>) {
|
||||
let scene = self.scene;
|
||||
<<<<<<< HEAD
|
||||
let widths = fit_widths(&scene.natural(plan.columns), plan.rect.width());
|
||||
let reading = plan.flow.to_physical(plan.rect);
|
||||
let start = plan.edge == DockEdge::Start;
|
||||
@@ -1263,12 +1198,7 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
|
||||
for (column, width) in plan.columns.iter().zip(widths) {
|
||||
let span = if start { (cursor, cursor + width) } else { (cursor - width, cursor) };
|
||||
cursor = if start { span.1 } else { span.0 };
|
||||
let mut cell = plan.flow.to_physical(Rect::from_x_y_ranges(span.0..=span.1, reading.y_range()));
|
||||
=======
|
||||
let spec = |panel: &P| scene.spec(panel);
|
||||
let cells = column_cells(plan.columns, plan.rect, plan.edge, plan.flow, &scene.sizes, &spec);
|
||||
for (column, cell) in plan.columns.iter().zip(cells) {
|
||||
>>>>>>> origin/next
|
||||
let cell = plan.flow.to_physical(Rect::from_x_y_ranges(span.0..=span.1, reading.y_range()));
|
||||
let Some(first) = column.groups.first().and_then(|group| group.panels.first()) else { continue };
|
||||
// A docked column takes the dock's height, a stepped one (a tool rail) too: the references' docked
|
||||
// toolbar keeps its column's surface down to the dock's foot, with the tools at the top
|
||||
@@ -1408,22 +1338,11 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
|
||||
}
|
||||
};
|
||||
let work = if column.iconic {
|
||||
<<<<<<< HEAD
|
||||
let Some(output) = icons(cell, open) else { return };
|
||||
=======
|
||||
let shown = IconicColumn::new(name, dock, column, Bind::given(open), &spec)
|
||||
.edge(edge)
|
||||
.opens(opens)
|
||||
.bar(bar)
|
||||
.within(within)
|
||||
.auto_collapse(scene.auto_collapse);
|
||||
let output = shown.show_flyouts_at(ui, cell, |group, at, ui, body| self.group_of(ui, body, group, at, in_window));
|
||||
>>>>>>> origin/next
|
||||
self.report.flyout.extend(output.edit.events);
|
||||
self.rail_work(output.front);
|
||||
ColumnWork { iconic: output.iconic, picked: output.picked, resized: Vec::new(), width: output.width, flyout: output.flyout }
|
||||
} else {
|
||||
<<<<<<< HEAD
|
||||
if !in_window && scene.rail_beside(column) {
|
||||
// The rail keeps to the dock's window edge and the expanded column shows inward of it.
|
||||
let rail = scene.sizes.iconic_width(column, &spec).min(cell.width());
|
||||
@@ -1442,10 +1361,7 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
|
||||
self.report.actions.push(Action::resize_iconic(first.clone(), Some(width)));
|
||||
}
|
||||
}
|
||||
let output = DockColumn::new(name, dock, column, &spec)
|
||||
=======
|
||||
let shown = DockColumn::new(name, dock, column, &spec)
|
||||
>>>>>>> origin/next
|
||||
.edge(edge)
|
||||
.bar(bar)
|
||||
.arrow(self.arrow_of(column))
|
||||
|
||||
@@ -3,15 +3,9 @@
|
||||
use super::DockArea;
|
||||
use crate::buttons::IconButton;
|
||||
use crate::contract::SizeLimits;
|
||||
<<<<<<< HEAD
|
||||
use crate::contract::{Bind, BodyCx, Props as _, Show as _};
|
||||
use crate::contract::{BodyCx, Props as _, Show as _, Tracked};
|
||||
use crate::display::Text;
|
||||
use crate::docking::{DockConfig, DockGrid, DockPanels, GroupAt, IconicMode, PanelSpec};
|
||||
=======
|
||||
use crate::contract::{BodyCx, Show as _, Tracked};
|
||||
use crate::display::Text;
|
||||
use crate::docking::{DockConfig, DockGrid, DockPanels, GroupAt, PanelSpec, PanelSpecs};
|
||||
>>>>>>> origin/next
|
||||
use crate::docking::{DockConfig, DockGrid, DockPanels, GroupAt, IconicMode, PanelSpec, PanelSpecs};
|
||||
use crate::menu::PanelRow;
|
||||
use crate::patterns::presets::{PresetPanelMenu, PresetView};
|
||||
use crate::testing::{Drive, StoryData, StoryOutput, story};
|
||||
@@ -123,9 +117,10 @@ fn workspace(minimized: bool) -> Arc<Workspace<usize>> {
|
||||
Arc::new(Workspace::new(Layout::new(Some(root), vec![window, collapsed])))
|
||||
}
|
||||
|
||||
/// One spec model for every story, so its revision stays put across frames.
|
||||
static SPECS: LazyLock<Tracked<DemoSpecs>> = LazyLock::new(|| Tracked::new(DemoSpecs));
|
||||
|
||||
fn dock(ui: &mut Ui, data: &mut StoryData, demo: &mut Demo, minimized: bool) -> StoryOutput {
|
||||
/// One spec model for every story, so its revision stays put across frames.
|
||||
static SPECS: LazyLock<Tracked<DemoSpecs>> = LazyLock::new(|| Tracked::new(DemoSpecs));
|
||||
let (workspace, workspace_at) = data.value_at("workspace", workspace(minimized));
|
||||
DockArea::new("Dock", workspace_at.bind(&mut *workspace), &*SPECS, demo, DockConfig::default()).show(ui).into()
|
||||
}
|
||||
@@ -153,14 +148,12 @@ fn a_minimized_floating_window(ui: &mut Ui, data: &mut StoryData) -> StoryOutput
|
||||
|
||||
#[story(DockArea<'static, usize>, covers = [Default], drive = Drive::Never, title = "Rail with fixed controls")]
|
||||
fn rail_with_fixed_controls(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let workspace = data.value("rail workspace", {
|
||||
let (workspace, workspace_at) = data.value_at("rail workspace", {
|
||||
let side = Column::new(vec![Group::new(vec![LAYERS, CHANNELS, PROPERTIES, HISTORY, SWATCHES, NAVIGATOR], 0)]).with_iconic(true);
|
||||
let root = Node::split(Axis::X, SplitSize::Ratio(0.8), Node::tabs(vec![CANVAS], 0), Node::dock(DockEdge::End, vec![side]));
|
||||
Workspace::new(Layout::new(Some(root), Vec::new()))
|
||||
Arc::new(Workspace::new(Layout::new(Some(root), Vec::new())))
|
||||
});
|
||||
let mut demo = Demo { canvas_view: false, host_rows: false };
|
||||
DockArea::new("Rail dock", Bind::bound(&mut *workspace), &mut demo, DockConfig::default().iconic_mode(IconicMode::Rail))
|
||||
.rail_footer(LAYERS)
|
||||
.show(ui)
|
||||
.into()
|
||||
let config = DockConfig::default().iconic_mode(IconicMode::Rail);
|
||||
DockArea::new("Rail dock", workspace_at.bind(&mut *workspace), &*SPECS, &mut demo, config).rail_footer(LAYERS).show(ui).into()
|
||||
}
|
||||
@@ -229,13 +229,9 @@ impl Outcome for AboutOutput {
|
||||
|
||||
/// Help > About: tabs About, Contributors and Models over the app's [`AboutInfo`] and [`Credits`], with an OK button.
|
||||
///
|
||||
<<<<<<< HEAD
|
||||
/// - **About.** The app's mark when it has one, the blurb, the version, the community button and the link row
|
||||
/// centred, then "Part of" with the suite's logo when it has one, the built-with line faint.
|
||||
=======
|
||||
/// - **About.** The blurb, the version, the community button and the link row centred, the built-with line faint; or,
|
||||
/// with [`AboutLayout::Listed`], the name, version, blurb and links one to a line, and Close for OK.
|
||||
>>>>>>> origin/next
|
||||
/// centred, then "Part of" with the suite's logo when it has one, the built-with line faint; or, with
|
||||
/// [`AboutLayout::Listed`], the name, version, blurb and links one to a line, and Close for OK.
|
||||
/// - **Contributors.** Show (Username, Display name, Real name), Sort (the list, with a button to reverse) and View
|
||||
/// (Grab bag or Table). The grab bag flows the names as links: a click reports the contributor's profile URL as the
|
||||
/// link (nothing for one without a profile), and the link's tooltip is the summary. The table has every figure; a
|
||||
@@ -385,43 +381,6 @@ impl Shown<'_> {
|
||||
/// The About tab, laid out as [`AboutLayout`] says.
|
||||
fn about(&self, ui: &mut Ui, link: &RefCell<Option<String>>) {
|
||||
let (words, info) = (self.words, self.info);
|
||||
<<<<<<< HEAD
|
||||
let dark = Env::of(ui).view().mode() == Mode::Dark;
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
if let Some(mark) = &info.mark {
|
||||
Row::new().align(RowAlign::Center).show(ui, |ui, _| {
|
||||
Picture::svg(mark.label.clone(), mark.source(dark)).extent(PictureSize::Thumb(ThumbSize::Small)).show(ui);
|
||||
});
|
||||
}
|
||||
Text::new(info.blurb.clone()).show(ui);
|
||||
Text::new(words.version.fill(&[("version", info.version.as_str())])).show(ui);
|
||||
Row::new().align(RowAlign::Center).show(ui, |ui, _| {
|
||||
if let Some(community) = &info.community
|
||||
&& clicked(&Button::new(community.label.clone()).variant(Variant::PRIMARY).id_salt("community").show(ui))
|
||||
{
|
||||
*link.borrow_mut() = Some(community.url.clone());
|
||||
}
|
||||
});
|
||||
Row::new().align(RowAlign::Center).show(ui, |ui, _| {
|
||||
for (at, item) in info.links.iter().enumerate() {
|
||||
if at > 0 && item.icon.is_none() && info.links.get(at - 1).is_some_and(|previous| previous.icon.is_none()) {
|
||||
Text::new("·").shade(Shade::Faint).show(ui);
|
||||
}
|
||||
let activated = if let Some(icon) = &item.icon {
|
||||
clicked(&Button::new(item.label.clone()).icon(icon.clone()).variant(Variant::GHOST).id_salt(("link", at)).show(ui))
|
||||
} else {
|
||||
clicked(&Link::new(item.label.clone()).id_salt(("link", at)).show(ui))
|
||||
};
|
||||
if activated {
|
||||
*link.borrow_mut() = Some(item.url.clone());
|
||||
}
|
||||
}
|
||||
});
|
||||
if let Some(logo) = &info.part_of {
|
||||
Row::new().align(RowAlign::Center).show(ui, |ui, _| {
|
||||
Text::new(words.part_of.clone()).shade(Shade::Muted).show(ui);
|
||||
Picture::svg(logo.label.clone(), logo.source(dark)).show(ui);
|
||||
=======
|
||||
if self.layout == AboutLayout::Listed {
|
||||
// Three blocks set apart by the item gap, as WordCraft's About spaced them: the name, version and blurb; the
|
||||
// links; the built-with line.
|
||||
@@ -442,9 +401,16 @@ impl Shown<'_> {
|
||||
});
|
||||
return;
|
||||
}
|
||||
let dark = Env::of(ui).view().mode() == Mode::Dark;
|
||||
// Four blocks set apart by the section gap: the blurb and version at the start edge, the community button and
|
||||
// the link row each centred across the body, the built-with line at the start edge.
|
||||
// the link row each centred across the body, the built-with line at the start edge. The app's mark, when it has
|
||||
// one, is centred above them, and "Part of" with the suite's logo, when it has one, follows the link row.
|
||||
Stack::new().gap(Gap::Section).fill_width().show(ui, |ui, _| {
|
||||
if let Some(mark) = &info.mark {
|
||||
Row::new().fill_width().align(RowAlign::Center).show(ui, |ui, _| {
|
||||
Picture::svg(mark.label.clone(), mark.source(dark)).extent(PictureSize::Thumb(ThumbSize::Small)).show(ui);
|
||||
});
|
||||
}
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
Text::new(info.blurb.clone()).show(ui);
|
||||
Text::new(words.version.fill(&[("version", info.version.as_str())])).show(ui);
|
||||
@@ -459,14 +425,25 @@ impl Shown<'_> {
|
||||
if !info.links.is_empty() {
|
||||
Row::new().fill_width().align(RowAlign::Center).show(ui, |ui, _| {
|
||||
for (at, item) in info.links.iter().enumerate() {
|
||||
if at > 0 {
|
||||
// A dot sets apart two text links; a link with an icon is a button of its own.
|
||||
if at > 0 && item.icon.is_none() && info.links.get(at - 1).is_some_and(|previous| previous.icon.is_none()) {
|
||||
Text::new("·").shade(Shade::Faint).show(ui);
|
||||
}
|
||||
if clicked(&Link::new(item.label.clone()).id_salt(("link", at)).show(ui)) {
|
||||
let activated = if let Some(icon) = &item.icon {
|
||||
clicked(&Button::new(item.label.clone()).icon(icon.clone()).variant(Variant::GHOST).id_salt(("link", at)).show(ui))
|
||||
} else {
|
||||
clicked(&Link::new(item.label.clone()).id_salt(("link", at)).show(ui))
|
||||
};
|
||||
if activated {
|
||||
*link.borrow_mut() = Some(item.url.clone());
|
||||
}
|
||||
}
|
||||
>>>>>>> origin/next
|
||||
});
|
||||
}
|
||||
if let Some(logo) = &info.part_of {
|
||||
Row::new().fill_width().align(RowAlign::Center).show(ui, |ui, _| {
|
||||
Text::new(words.part_of.clone()).shade(Shade::Muted).show(ui);
|
||||
Picture::svg(logo.label.clone(), logo.source(dark)).show(ui);
|
||||
});
|
||||
}
|
||||
Text::new(info.built_with.clone()).shade(Shade::Faint).show(ui);
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
//! Stories of `AboutDialog`: the About tab (centred and listed), the Contributors tab with a PR-only contributor, and an app tab.
|
||||
|
||||
<<<<<<< HEAD
|
||||
use super::{AboutDialog, AboutImage, AboutInfo, AboutLink, AboutTab, Contributor, Credits, HostedAbout, ModelCredit};
|
||||
=======
|
||||
use super::{AboutAppTab, AboutDialog, AboutInfo, AboutLayout, AboutLink, AboutTab, Contributor, Credits, HostedAbout, ModelCredit};
|
||||
use super::{AboutAppTab, AboutDialog, AboutImage, AboutInfo, AboutLayout, AboutLink, AboutTab, Contributor, Credits, HostedAbout, ModelCredit};
|
||||
use crate::contract::Show as _;
|
||||
>>>>>>> origin/next
|
||||
use crate::dialog::stories::hosted;
|
||||
use crate::display::Text;
|
||||
use crate::testing::{Drive, StoryData, StoryOutput, story};
|
||||
@@ -45,7 +41,27 @@ fn about_dialog(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
hosted(ui, data, (tab, community), || HostedAbout::new(info(community), CREDITS.clone()).tab(tab))
|
||||
}
|
||||
|
||||
<<<<<<< HEAD
|
||||
/// The About tab in the listed layout: name, version, blurb and links one to a line, and Close.
|
||||
#[story(AboutDialog<'static>, covers = [], drive = Drive::Never)]
|
||||
fn about_dialog_listed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let community = *data.value("community_link", true);
|
||||
hosted(ui, data, community, || HostedAbout::new(info(community), CREDITS.clone()).layout(AboutLayout::Listed))
|
||||
}
|
||||
|
||||
/// 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))
|
||||
})
|
||||
}
|
||||
|
||||
/// The story's app mark: a rounded square with a page corner folded down.
|
||||
const MARK: &[u8] = br##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48"><rect x="4" y="4" width="40" height="40" rx="10" fill="#3b6fd8"/><path d="M16 12h12l8 8v16H16z" fill="#ffffff"/><path d="M28 12v8h8z" fill="#c9d8f7"/></svg>"##;
|
||||
|
||||
@@ -71,26 +87,6 @@ fn about_dialog_icon_links(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
AboutLink::new("Source", "https://example.org/source").icon(craft_behavior::IconId::new("file")),
|
||||
];
|
||||
HostedAbout::new(info(false).links(links), CREDITS.clone())
|
||||
=======
|
||||
/// The About tab in the listed layout: name, version, blurb and links one to a line, and Close.
|
||||
#[story(AboutDialog<'static>, covers = [], drive = Drive::Never)]
|
||||
fn about_dialog_listed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let community = *data.value("community_link", true);
|
||||
hosted(ui, data, community, || HostedAbout::new(info(community), CREDITS.clone()).layout(AboutLayout::Listed))
|
||||
}
|
||||
|
||||
/// 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))
|
||||
>>>>>>> origin/next
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -25,12 +25,9 @@ use crate::display::{Shade, Text};
|
||||
use crate::form::SliderFieldLayout;
|
||||
use crate::layout::RowAlign;
|
||||
use crate::layout_components::{Row, Stack};
|
||||
<<<<<<< HEAD
|
||||
use crate::notices::{Notice, NoticeLayout};
|
||||
use crate::style::DataColor;
|
||||
use crate::tabs::{Tab, TabKind, TabStrip};
|
||||
=======
|
||||
>>>>>>> origin/next
|
||||
|
||||
use crate::primitives::ContentPainterCx;
|
||||
use crate::runtime::env::{Env, Label};
|
||||
@@ -45,13 +42,8 @@ use crate::sections::{DialogRole, FooterButton};
|
||||
|
||||
use crate::contract::LabelScheme;
|
||||
use craft_theme::Srgba;
|
||||
<<<<<<< HEAD
|
||||
use craft_theme::variant::Tone;
|
||||
use egui::{Context, Pos2, Rect, Response, Ui};
|
||||
=======
|
||||
use egui::load::SizedTexture;
|
||||
use egui::{Context, Pos2, Response, Ui};
|
||||
>>>>>>> origin/next
|
||||
use serde_json::Value;
|
||||
|
||||
use std::borrow::Cow;
|
||||
@@ -89,15 +81,9 @@ pub enum ParamLayout {
|
||||
}
|
||||
|
||||
impl ParamLayout {
|
||||
<<<<<<< HEAD
|
||||
/// Whether a dialog that previews stands its buttons in a column beside the body.
|
||||
fn side_buttons(self) -> bool {
|
||||
!matches!(self, ParamLayout::Stacked | ParamLayout::Document)
|
||||
=======
|
||||
/// Where a dialog that previews stands its buttons: in a column beside the body, or across the foot.
|
||||
fn button_place(self) -> ButtonPlace {
|
||||
if matches!(self, ParamLayout::Stacked) { ButtonPlace::Foot } else { ButtonPlace::Side }
|
||||
>>>>>>> origin/next
|
||||
if matches!(self, ParamLayout::Stacked | ParamLayout::Document) { ButtonPlace::Foot } else { ButtonPlace::Side }
|
||||
}
|
||||
|
||||
/// How the range rows arrange their slider and number field.
|
||||
@@ -260,18 +246,11 @@ pub struct ParamDialogOutput {
|
||||
/// The point of the preview picture a click landed on this pass (`PreviewOutput::clicked`): an eyedropper on the
|
||||
/// preview samples there.
|
||||
pub preview_click: Option<Pos2>,
|
||||
<<<<<<< HEAD
|
||||
/// The id of the extra footer button or the custom row's button pressed this pass (`ParamDialog::extra_buttons`,
|
||||
/// `CustomContext::request_action`).
|
||||
pub action: Option<String>,
|
||||
/// The step the preview pager took this pass (`ParamDialog::preview_pager`).
|
||||
pub preview_step: Option<PagerStep>,
|
||||
/// The answer OK would have given, the pass OK was pressed on a dialog that holds its OK for the host.
|
||||
pub(crate) held: Option<ParamResult>,
|
||||
=======
|
||||
/// The id of the extra footer button pressed this pass (`ParamDialog::extra_buttons`).
|
||||
pub footer_action: Option<String>,
|
||||
>>>>>>> origin/next
|
||||
/// The picture point at the centre of the view the preview pane drew this pass; `None` without a preview.
|
||||
pub(crate) preview_centre: Option<Pos2>,
|
||||
}
|
||||
@@ -436,15 +415,12 @@ pub struct ParamDialog<'a> {
|
||||
/// The colours the colour rows show in place of their values in this pass, by row key.
|
||||
#[prop(vis = "pub(crate)")]
|
||||
preview_colors: Vec<(String, Srgba)>,
|
||||
<<<<<<< HEAD
|
||||
/// The lines the host shows under the rows, after `below` ([`HostedParamDialog::set_notes`]).
|
||||
#[prop(vis = "pub(crate)")]
|
||||
host_notes: Vec<Label>,
|
||||
=======
|
||||
/// OK files the values in `held` and the dialog stays open; a refusal shows until the values change.
|
||||
#[prop(vis = "pub(crate)")]
|
||||
held: Option<&'a mut HeldAnswer<DialogFields>>,
|
||||
>>>>>>> origin/next
|
||||
/// The lines the host shows under the rows, after `below` ([`HostedParamDialog::set_notes`]).
|
||||
#[prop(vis = "pub(crate)")]
|
||||
host_notes: Vec<Label>,
|
||||
}
|
||||
|
||||
/// What `ParamDialog::shaped` applies to the built [`Dialog`].
|
||||
@@ -507,11 +483,8 @@ impl<'a> ParamDialog<'a> {
|
||||
values_opened: None,
|
||||
centre: None,
|
||||
preview_colors: Vec::new(),
|
||||
<<<<<<< HEAD
|
||||
host_notes: Vec::new(),
|
||||
=======
|
||||
held: None,
|
||||
>>>>>>> origin/next
|
||||
host_notes: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -623,11 +596,8 @@ impl<'a> ParamDialog<'a> {
|
||||
values_opened,
|
||||
centre,
|
||||
preview_colors,
|
||||
<<<<<<< HEAD
|
||||
host_notes,
|
||||
=======
|
||||
held,
|
||||
>>>>>>> origin/next
|
||||
host_notes,
|
||||
} = self;
|
||||
let env = Env::of(ui);
|
||||
let layout = layout.unwrap_or_else(|| env.view().get::<DialogLayout>().0);
|
||||
@@ -653,11 +623,7 @@ impl<'a> ParamDialog<'a> {
|
||||
// The tab strip is a collection in the body, as a browse list is.
|
||||
.collection_body(collection_body || tabbed)
|
||||
.closable(closable)
|
||||
<<<<<<< HEAD
|
||||
.close_unchanged(close_unchanged)
|
||||
.accept_stays_open(hold)
|
||||
=======
|
||||
>>>>>>> origin/next
|
||||
.answers(answers);
|
||||
if let Some(held) = held {
|
||||
form = form.held(held);
|
||||
@@ -720,14 +686,12 @@ impl<'a> ParamDialog<'a> {
|
||||
let mut live = Live::default();
|
||||
let mut rows = None;
|
||||
let mut shown_preview = ShownPreview::default();
|
||||
<<<<<<< HEAD
|
||||
let mut latest = None::<DialogFields>;
|
||||
let body = DialogRows {
|
||||
title: &title,
|
||||
shared: ¶ms,
|
||||
tabs: &tabs,
|
||||
place: shared_rows,
|
||||
patterns: &patterns,
|
||||
patterns: patterns.as_ref(),
|
||||
preview_colors: &preview_colors,
|
||||
sliders: layout.sliders(),
|
||||
// A tabbed document dialog (Document Properties) is an aligned form: no colons, one caption column, the
|
||||
@@ -736,17 +700,11 @@ impl<'a> ParamDialog<'a> {
|
||||
canvas,
|
||||
read_only,
|
||||
};
|
||||
let shown = form.show(ui, |ui, cx, values| {
|
||||
if cx.first() && !host_opened {
|
||||
let saved = remember.as_ref().and_then(|key| cx.saved::<Option<DialogFields>>(key).clone());
|
||||
Self::open_values(&every, &patterns, saved.as_ref(), values);
|
||||
=======
|
||||
let shown = form.show(ui, |ui, cx, values| {
|
||||
if cx.first() && !host_opened {
|
||||
let saved = remember.as_ref().and_then(|key| cx.saved::<Option<DialogFields>>(key).clone());
|
||||
let offered = patterns.as_ref().map(|source| source.rows(ui.ctx(), &Env::of(ui))).unwrap_or_default();
|
||||
Self::open_values(¶ms, &offered, saved.as_ref(), values);
|
||||
>>>>>>> origin/next
|
||||
Self::open_values(&every, &offered, saved.as_ref(), values);
|
||||
}
|
||||
for answer in cx.take_answers() {
|
||||
let answered = match &answer {
|
||||
@@ -783,23 +741,11 @@ impl<'a> ParamDialog<'a> {
|
||||
if let (Some(point), Some(PreviewState::Ready(texture))) = (centre, &preview) {
|
||||
live.view = live.view.centred_on(point, texture.size);
|
||||
}
|
||||
<<<<<<< HEAD
|
||||
// The `tab` binding, when there is one, says which tab shows; the dialog's memory does otherwise.
|
||||
let last = tabs.len().saturating_sub(1);
|
||||
let bound_tab = match tab.as_mut().map(|bind| bind.reborrow().read(&mut **cx)) {
|
||||
Some(Some(Mixed::Same(at))) => Some(at),
|
||||
_ => None,
|
||||
=======
|
||||
let mut show_rows = |ui: &mut Ui, values: &mut DialogFields| {
|
||||
let mut shown = ParamRows::new(title.clone(), ¶ms, Bind::bound(values)).preview_colors(&preview_colors).sliders(layout.sliders());
|
||||
if let Some(source) = patterns.as_ref() {
|
||||
shown = shown.patterns(source);
|
||||
}
|
||||
if let Some(canvas) = canvas {
|
||||
shown = shown.canvas(canvas);
|
||||
}
|
||||
rows = Some(shown.show(ui));
|
||||
>>>>>>> origin/next
|
||||
};
|
||||
let held_tab = bound_tab.unwrap_or_else(|| cx.memory::<OpenTab>().0).min(last);
|
||||
let mut shown_tab = held_tab;
|
||||
@@ -835,18 +781,11 @@ impl<'a> ParamDialog<'a> {
|
||||
}
|
||||
(None, _) => show_rows(ui, values),
|
||||
}
|
||||
<<<<<<< HEAD
|
||||
if let Some(bind) = tab.as_mut().filter(|_| bound_tab != Some(shown_tab)) {
|
||||
let event = EditEvent::set(bound_tab.map_or(Mixed::Mixed, Mixed::Same), shown_tab, title.as_str().into(), None);
|
||||
let _ = bind.reborrow().write(&mut **cx, &event);
|
||||
}
|
||||
cx.memory::<OpenTab>().0 = shown_tab;
|
||||
// The host's refusal of the held OK stays until a value changes.
|
||||
if let Some((reason, _)) = refusal.as_ref().filter(|(_, refused)| *refused == *values) {
|
||||
Notice::new(Tone::Bad, reason.clone()).layout(NoticeLayout::Inline).show(ui);
|
||||
}
|
||||
=======
|
||||
>>>>>>> origin/next
|
||||
if let Some(BelowRows(draw)) = &below {
|
||||
draw(ui, values);
|
||||
}
|
||||
@@ -866,21 +805,15 @@ impl<'a> ParamDialog<'a> {
|
||||
Some(ResetPick::Extra(at)) => extra_buttons.get(at).map(|(id, _)| id.clone()),
|
||||
_ => None,
|
||||
};
|
||||
<<<<<<< HEAD
|
||||
// Footer and row buttons share one channel. The rows' own slot is emptied, so a host that absorbs the rows
|
||||
// files the press once.
|
||||
let action = rows.as_mut().and_then(|rows: &mut ParamRowsOutput| rows.action.take()).or(pressed);
|
||||
let closed = shown.closed.is_some();
|
||||
let (result, held) = match (shown.accepted, pick, latest) {
|
||||
// A read-only dialog answers with no values, whichever way it closes.
|
||||
_ if read_only => (closed.then(|| Self::result(key, &every, None, DialogFields::new())), None),
|
||||
(Some(fields), _, _) => (Some(Self::result(key, &every, remember, fields)), None),
|
||||
(None, Some(ResetPick::Accept), Some(fields)) if hold => (None, Some(Self::result(key, &every, remember, fields))),
|
||||
_ => (None, None),
|
||||
// A read-only dialog answers with no values, whichever way it closes.
|
||||
let result = if read_only {
|
||||
shown.closed.is_some().then(|| Self::result(key, &every, None, DialogFields::new()))
|
||||
} else {
|
||||
shown.accepted.map(|fields| Self::result(key, &every, remember, fields))
|
||||
};
|
||||
=======
|
||||
let result = shown.accepted.map(|fields| Self::result(key, ¶ms, remember, fields));
|
||||
>>>>>>> origin/next
|
||||
ParamDialogOutput {
|
||||
response: shown.response,
|
||||
closed: shown.closed,
|
||||
@@ -890,13 +823,8 @@ impl<'a> ParamDialog<'a> {
|
||||
preview_on: shown.preview_on,
|
||||
comparing: shown.comparing,
|
||||
preview_click: shown_preview.clicked,
|
||||
<<<<<<< HEAD
|
||||
action,
|
||||
preview_step: shown_preview.step,
|
||||
held,
|
||||
=======
|
||||
footer_action,
|
||||
>>>>>>> origin/next
|
||||
preview_centre: shown_preview.centre,
|
||||
}
|
||||
}
|
||||
@@ -1041,7 +969,7 @@ struct DialogRows<'p> {
|
||||
shared: &'p [Param],
|
||||
tabs: &'p [ParamTab],
|
||||
place: SharedRows,
|
||||
patterns: &'p [PresetRow<String>],
|
||||
patterns: Option<&'p PresetSource<'p, String>>,
|
||||
preview_colors: &'p [(String, Srgba)],
|
||||
sliders: SliderFieldLayout,
|
||||
/// The label scheme the layout sets for the rows.
|
||||
@@ -1055,10 +983,12 @@ impl DialogRows<'_> {
|
||||
/// The rows `params` over `values`, their group named `label`; `read_only` for the rows of a read-only tab.
|
||||
fn group(&self, ui: &mut Ui, label: &Label, params: &[Param], read_only: bool, values: &mut DialogFields) -> ParamRowsOutput {
|
||||
let mut rows = ParamRows::new(label.clone(), params, Bind::bound(values))
|
||||
.patterns(self.patterns)
|
||||
.preview_colors(self.preview_colors)
|
||||
.sliders(self.sliders)
|
||||
.read_only(self.read_only || read_only);
|
||||
if let Some(source) = self.patterns {
|
||||
rows = rows.patterns(source);
|
||||
}
|
||||
if let Some(scheme) = self.labels {
|
||||
rows = rows.labels(scheme);
|
||||
}
|
||||
@@ -1207,7 +1137,10 @@ fn show_preview(
|
||||
let pane = pane.show(ui);
|
||||
// Under the pane the row is there before the picture is: a dialog sized from its first pass keeps room for it.
|
||||
let below = (zoom_row == ZoomRow::Below).then(|| PreviewZoom::new(&live.view).show(ui));
|
||||
let step = extras.pager.as_ref().and_then(|pager| Row::new().fill_width().align(RowAlign::Center).show(ui, |ui, _| pager.clone().show(ui)).inner.flatten());
|
||||
let step = extras
|
||||
.pager
|
||||
.as_ref()
|
||||
.and_then(|pager| Row::new().fill_width().align(RowAlign::Center).show(ui, |ui, _| pager.clone().show(ui)).inner.flatten());
|
||||
live.view = above.or(below).and_then(|zoom| zoom.view).or(pane.view).unwrap_or(pane.shown.clone());
|
||||
ShownPreview { clicked: pane.clicked, centre: picture.map(|size| pane.shown.centre(size)), step }
|
||||
}
|
||||
@@ -1337,15 +1270,10 @@ impl HostedParamDialog {
|
||||
build: impl for<'b> Fn(&'b mut DialogFields) -> ParamDialog<'b> + Send + 'static,
|
||||
) -> Self {
|
||||
let key = key.into();
|
||||
<<<<<<< HEAD
|
||||
let ParamDialog { params, tabs, remember, patterns, previews, .. } = build(&mut fields);
|
||||
let (params, patterns) = (every_param(params, &tabs).into_owned(), patterns.into_owned());
|
||||
=======
|
||||
let ParamDialog { params, remember, patterns, previews, .. } = build(&mut fields);
|
||||
// No pass runs here: the rows are built in the root scope, whose words name them; only their keys are read.
|
||||
let patterns = patterns.map(|source| source.rows(ctx, &Env::of_root(ctx))).unwrap_or_default();
|
||||
let params = params.into_owned();
|
||||
>>>>>>> origin/next
|
||||
let params = every_param(params, &tabs).into_owned();
|
||||
let saved = remember.and_then(|key| MemoryStage::peek_saved::<Option<DialogFields>>(ctx, &key));
|
||||
ParamDialog::open_values(¶ms, &patterns, saved.as_ref(), &mut fields);
|
||||
let id = dialog_id(key.as_str());
|
||||
@@ -1546,10 +1474,15 @@ impl HostedParamDialog {
|
||||
|
||||
/// The answer OK gives with `fields`: the key, the part a remembering dialog saves and this dialog's id, as the
|
||||
/// dialog's own build says them.
|
||||
/// A read-only dialog answers with no values, as its OK does.
|
||||
fn result_of(&mut self, fields: DialogFields) -> ParamResult {
|
||||
let ParamDialog { key, params, remember, .. } = (self.build)(&mut self.fields);
|
||||
let params = params.into_owned();
|
||||
let mut result = ParamDialog::result(key, ¶ms, remember, fields);
|
||||
let ParamDialog { key, params, tabs, remember, read_only, .. } = (self.build)(&mut self.fields);
|
||||
let params = every_param(params, &tabs).into_owned();
|
||||
let mut result = if read_only {
|
||||
ParamDialog::result(key, ¶ms, None, DialogFields::new())
|
||||
} else {
|
||||
ParamDialog::result(key, ¶ms, remember, fields)
|
||||
};
|
||||
result.id = self.id;
|
||||
result
|
||||
}
|
||||
@@ -1721,11 +1654,6 @@ impl StackDialog for HostedParamDialog {
|
||||
if let Some(point) = centre {
|
||||
dialog = dialog.centre_on(point);
|
||||
}
|
||||
<<<<<<< HEAD
|
||||
// OK waits for the host's answer: a second OK cannot file over the held one.
|
||||
if self.held.is_waiting() {
|
||||
dialog = dialog.ok_enabled(false);
|
||||
}
|
||||
if let Err(reason) = &self.ready {
|
||||
dialog = dialog.ok_enabled(false).ok_reason(reason.clone());
|
||||
}
|
||||
@@ -1733,9 +1661,6 @@ impl StackDialog for HostedParamDialog {
|
||||
dialog = dialog.host_notes(self.notes.clone());
|
||||
}
|
||||
if let Some(picture) = self.picture.clone() {
|
||||
=======
|
||||
if let Some(picture) = self.picture {
|
||||
>>>>>>> origin/next
|
||||
dialog = dialog.preview(picture);
|
||||
}
|
||||
if let Some(pager) = self.pager.clone() {
|
||||
@@ -1800,24 +1725,10 @@ impl StackDialog for HostedParamDialog {
|
||||
if self.held.is_waiting() {
|
||||
return None;
|
||||
}
|
||||
<<<<<<< HEAD
|
||||
let ParamDialog { key, params, tabs, remember, ok_enabled, read_only, .. } = (self.build)(&mut self.fields);
|
||||
let ok_enabled = (self.build)(&mut self.fields).ok_enabled;
|
||||
if !ok_enabled || self.ready.is_err() {
|
||||
return None;
|
||||
}
|
||||
let params = every_param(params, &tabs).into_owned();
|
||||
// A read-only dialog answers with no values, as its OK does.
|
||||
let mut result = if read_only {
|
||||
ParamDialog::result(key, ¶ms, None, DialogFields::new())
|
||||
} else {
|
||||
ParamDialog::result(key, ¶ms, remember, self.fields.clone())
|
||||
};
|
||||
=======
|
||||
let ok_enabled = (self.build)(&mut self.fields).ok_enabled;
|
||||
if !ok_enabled {
|
||||
return None;
|
||||
}
|
||||
>>>>>>> origin/next
|
||||
if self.hold {
|
||||
self.held.file(self.fields.clone());
|
||||
return None;
|
||||
|
||||
@@ -36,13 +36,8 @@ fn blur_story(ui: &mut Ui, data: &mut StoryData, preview: bool, layout: ParamLay
|
||||
let preview = *data.value("preview", preview);
|
||||
let layout = *data.choice("layout", layout, &LAYOUTS);
|
||||
let comparing = *data.value("comparing", false);
|
||||
<<<<<<< HEAD
|
||||
let dialog = ParamDialog::new("blur", "Blur", Param::parse_list(SPEC)).opened(Bind::bound(data.value("open", true))).history(true).layout(layout);
|
||||
let dialog = if preview { dialog.previews(true).preview(PreviewState::Ready(picture(ui, comparing))) } else { dialog };
|
||||
=======
|
||||
let dialog = ParamDialog::new("blur", "Blur", Param::parse_list(SPEC)).opened(data.bind("open", true)).history(true).layout(layout);
|
||||
let dialog = if preview { dialog.previews(true).preview(picture(ui, comparing)) } else { dialog };
|
||||
>>>>>>> origin/next
|
||||
let dialog = if preview { dialog.previews(true).preview(PreviewState::Ready(picture(ui, comparing))) } else { dialog };
|
||||
let shown = dialog.show(ui);
|
||||
*data.value("comparing", false) = shown.comparing;
|
||||
shown.into()
|
||||
@@ -155,7 +150,7 @@ fn tabs() -> Vec<ParamTab> {
|
||||
|
||||
/// A tabbed dialog over `tabs`, with `shared` as its own rows, open while the story's `open` value is on.
|
||||
fn tabbed(data: &mut StoryData, tabs: Vec<ParamTab>, shared: Vec<Param>) -> ParamDialog<'_> {
|
||||
ParamDialog::new("ocr", "Recognize Text", shared).tabs(tabs).opened(Bind::bound(data.value("open", true)))
|
||||
ParamDialog::new("ocr", "Recognize Text", shared).tabs(tabs).opened(data.bind("open", true))
|
||||
}
|
||||
|
||||
/// Editable tabs: the strip shows the titles and the shown tab's rows; the values of both tabs answer at OK.
|
||||
@@ -204,7 +199,7 @@ fn outline(cx: &ContentPainterCx, rect: Rect) {
|
||||
#[story(ParamDialog<'static>, covers = [], drive = Drive::Never)]
|
||||
fn param_dialog_preview_pending(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
ParamDialog::new("ocr", "Recognize Text", Param::parse_list(GENERAL_SPEC))
|
||||
.opened(Bind::bound(data.value("open", true)))
|
||||
.opened(data.bind("open", true))
|
||||
.previews(true)
|
||||
.preview(PreviewState::Pending(Some(0.4)))
|
||||
.preview_pager(pager())
|
||||
@@ -218,7 +213,7 @@ fn param_dialog_preview_pending(ui: &mut Ui, data: &mut StoryData) -> StoryOutpu
|
||||
fn param_dialog_preview_tinted(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let picture = picture(ui, false);
|
||||
ParamDialog::new("ocr", "Recognize Text", Param::parse_list(GENERAL_SPEC))
|
||||
.opened(Bind::bound(data.value("open", true)))
|
||||
.opened(data.bind("open", true))
|
||||
.previews(true)
|
||||
.preview(PreviewState::Ready(picture))
|
||||
.preview_pager(pager())
|
||||
@@ -231,5 +226,5 @@ fn param_dialog_preview_tinted(ui: &mut Ui, data: &mut StoryData) -> StoryOutput
|
||||
/// A muted note after the title.
|
||||
#[story(ParamDialog<'static>, covers = [], drive = Drive::Never)]
|
||||
fn param_dialog_title_note(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
ParamDialog::new("blur", "Blur", Param::parse_list(SPEC)).opened(Bind::bound(data.value("open", true))).title_note("Layer 1").show(ui).into()
|
||||
ParamDialog::new("blur", "Blur", Param::parse_list(SPEC)).opened(data.bind("open", true)).title_note("Layer 1").show(ui).into()
|
||||
}
|
||||
@@ -508,12 +508,8 @@ impl<'a, V: Value + Default> FormDialog<'a, V> {
|
||||
};
|
||||
let mut dialog = Dialog::new(title)
|
||||
.closable(closable)
|
||||
<<<<<<< HEAD
|
||||
.close_unchanged(close_unchanged)
|
||||
.close_on_enter(ok_enabled && enter_confirms)
|
||||
=======
|
||||
.close_on_enter(enter_confirms && if no_ok { enter_extra } else { ok_enabled })
|
||||
>>>>>>> origin/next
|
||||
.outer_gesture(outer_gesture)
|
||||
.button_place(button_place);
|
||||
dialog = match close {
|
||||
|
||||
@@ -433,11 +433,7 @@ impl<'a> ListManager<'a> {
|
||||
list = list.empty(empty.clone());
|
||||
}
|
||||
if searchable {
|
||||
<<<<<<< HEAD
|
||||
list = list.filter(&session.name, |at| vec![Label::from(entries[*at].name.clone())]);
|
||||
=======
|
||||
list = list.filter(text.as_str(), |at| Label::from(entries[*at].name.clone()));
|
||||
>>>>>>> origin/next
|
||||
list = list.filter(text.as_str(), |at| vec![Label::from(entries[*at].name.clone())]);
|
||||
}
|
||||
let events = list
|
||||
.show_items(ui, &source, &mut |at, _| {
|
||||
|
||||
@@ -18,8 +18,8 @@ pub(crate) mod path_row;
|
||||
pub(crate) mod preview;
|
||||
|
||||
pub use dialog::{
|
||||
BelowRows, DialogLayout, HostedParamDialog, ParamDialog, ParamDialogOutput, ParamDialogWords, ParamLayout, ParamResult, ParamTab, ResetFooter, ResetPick,
|
||||
SharedOverlay, SharedRows, set_param_field,
|
||||
BelowRows, DialogLayout, HostedParamDialog, ParamDialog, ParamDialogOutput, ParamDialogWords, ParamLayout, ParamResult, ParamTab, ResetFooter,
|
||||
ResetPick, SharedOverlay, SharedRows, set_param_field,
|
||||
};
|
||||
pub use form::{FormButtons, FormCx, FormDialog, FormDialogWords, FormOutput};
|
||||
pub use host_requests::{HostRequests, PreviewRequest};
|
||||
@@ -66,13 +66,8 @@ pub use new_document::{
|
||||
pub(crate) mod about;
|
||||
|
||||
pub use about::{
|
||||
<<<<<<< HEAD
|
||||
AboutDialog, AboutImage, AboutInfo, AboutLink, AboutOutput, AboutTab, AboutWords, CommitShare, Contributor, ContributorSort, Credits,
|
||||
HostedAbout, ModelCredit, NameMode,
|
||||
=======
|
||||
AboutAppTab, AboutDialog, AboutInfo, AboutLayout, AboutLink, AboutOutput, AboutTab, AboutWords, CommitShare, Contributor, ContributorSort,
|
||||
Credits, HostedAbout, ModelCredit, NameMode,
|
||||
>>>>>>> origin/next
|
||||
AboutAppTab, AboutDialog, AboutImage, AboutInfo, AboutLayout, AboutLink, AboutOutput, AboutTab, AboutWords, CommitShare, Contributor,
|
||||
ContributorSort, Credits, HostedAbout, ModelCredit, NameMode,
|
||||
};
|
||||
|
||||
mod color_choice;
|
||||
|
||||
@@ -480,13 +480,10 @@ pub(crate) struct RowOptions {
|
||||
eyedropper: bool,
|
||||
eyedropper_armed: bool,
|
||||
full_width: bool,
|
||||
<<<<<<< HEAD
|
||||
beside: bool,
|
||||
=======
|
||||
beside_next: bool,
|
||||
/// A radio row's options stand in one row with no caption ([`Param::options_in_row`]).
|
||||
options_in_row: bool,
|
||||
>>>>>>> origin/next
|
||||
beside: bool,
|
||||
not_remembered: bool,
|
||||
/// The lines a multi-line text row shows.
|
||||
lines: Option<usize>,
|
||||
@@ -959,19 +956,19 @@ impl Param {
|
||||
self
|
||||
}
|
||||
|
||||
<<<<<<< HEAD
|
||||
/// The row stands on the same line as the row before it (production's Font, Size, Underline and Colour on one
|
||||
/// line), wrapping to the next line when the form is too narrow. The first row of a form or group ignores it.
|
||||
#[must_use]
|
||||
pub fn beside_previous(mut self) -> Self {
|
||||
self.options.get_or_insert_default().beside = true;
|
||||
=======
|
||||
/// For a [`ParamKind::Radio`] row: the options stand side by side in one row, with no caption over them; the label
|
||||
/// still names the group for assistive technology. Other kinds are unchanged.
|
||||
#[must_use]
|
||||
pub fn options_in_row(mut self) -> Self {
|
||||
self.options.get_or_insert_default().options_in_row = true;
|
||||
>>>>>>> origin/next
|
||||
self
|
||||
}
|
||||
|
||||
/// The row stands on the same line as the row before it (production's Font, Size, Underline and Colour on one
|
||||
/// line), wrapping to the next line when the form is too narrow. The first row of a form or group ignores it.
|
||||
#[must_use]
|
||||
pub fn beside_previous(mut self) -> Self {
|
||||
self.options.get_or_insert_default().beside = true;
|
||||
self
|
||||
}
|
||||
|
||||
|
||||
@@ -49,15 +49,12 @@ craft_ui::words! {
|
||||
medium: "passwordDialog.medium" = "Medium";
|
||||
strong: "passwordDialog.strong" = "Strong";
|
||||
wrong: "passwordDialog.wrong" = "That password is not correct.";
|
||||
<<<<<<< HEAD
|
||||
open_several: count "passwordDialog.openSeveral" =
|
||||
"{n} file is protected. Enter a password to open it." | "{n} files are protected. Enter a password to open them.";
|
||||
permissions_several: count "passwordDialog.permissionsSeveral" =
|
||||
"{n} file has security restrictions. Enter its permissions password to lift them."
|
||||
| "{n} files have security restrictions. Enter their permissions password to lift them.";
|
||||
=======
|
||||
clear_hint: "passwordDialog.clearHint" = "Leave both fields empty to remove the password.";
|
||||
>>>>>>> origin/next
|
||||
}
|
||||
}
|
||||
|
||||
@@ -245,7 +242,8 @@ impl Outcome for PasswordOutput {
|
||||
pub struct PasswordFieldsOutput {
|
||||
/// The fields' response.
|
||||
pub response: Response,
|
||||
/// Whether the entries are valid: with a confirmation field, non-empty and equal.
|
||||
/// Whether the entries are valid: with a confirmation field, non-empty and equal, or both empty when
|
||||
/// [`clearable`](PasswordFields::clearable).
|
||||
pub valid: bool,
|
||||
}
|
||||
|
||||
@@ -267,12 +265,13 @@ pub struct PasswordFields<'a> {
|
||||
confirm: Option<Bind<'a, String>>,
|
||||
error: Option<Label>,
|
||||
bare: bool,
|
||||
clearable: bool,
|
||||
}
|
||||
|
||||
impl<'a> PasswordFields<'a> {
|
||||
/// The masked field named `label` over `input`.
|
||||
pub fn new(label: impl Into<Label>, input: Bind<'a, String>) -> Self {
|
||||
PasswordFields { label: label.into(), input, confirm: None, error: None, bare: false }
|
||||
PasswordFields { label: label.into(), input, confirm: None, error: None, bare: false, clearable: false }
|
||||
}
|
||||
|
||||
/// Adds the Re-type field over `confirm`, with the mismatch help and the strength help and meter.
|
||||
@@ -282,6 +281,13 @@ impl<'a> PasswordFields<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// With a confirmation field, two empty entries are valid too: they clear the password. Off by default.
|
||||
#[must_use]
|
||||
pub fn clearable(mut self, on: bool) -> Self {
|
||||
self.clearable = on;
|
||||
self
|
||||
}
|
||||
|
||||
/// The line under the field, in the error colour.
|
||||
#[must_use]
|
||||
pub fn error(mut self, error: Option<Label>) -> Self {
|
||||
@@ -300,7 +306,7 @@ impl<'a> PasswordFields<'a> {
|
||||
/// Shows the fields. With a confirmation field the first one takes the strength help once something is typed,
|
||||
/// else the error line; without one, the error line.
|
||||
pub fn show(self, ui: &mut Ui) -> PasswordFieldsOutput {
|
||||
let PasswordFields { label, mut input, mut confirm, error, bare } = self;
|
||||
let PasswordFields { label, mut input, mut confirm, error, bare, clearable } = self;
|
||||
let env = Env::of(ui);
|
||||
let words = env.words::<PasswordWords>();
|
||||
let mut valid = false;
|
||||
@@ -373,7 +379,7 @@ impl<'a> PasswordFields<'a> {
|
||||
// The entries after this pass's edits: a bound or kept entry holds them now.
|
||||
let typed = bound_text(&mut input, cx);
|
||||
let retyped = confirm.as_mut().map(|confirm| bound_text(confirm, cx));
|
||||
valid = entries_valid(&typed, retyped.as_deref());
|
||||
valid = entries_valid(&typed, retyped.as_deref()) || (clearable && typed.is_empty() && retyped.as_deref().is_some_and(str::is_empty));
|
||||
*cx.memory::<Revealed>() = Revealed(revealed);
|
||||
});
|
||||
PasswordFieldsOutput { response: shown.output, valid }
|
||||
@@ -399,24 +405,8 @@ fn entries_valid(input: &str, confirm: Option<&str>) -> bool {
|
||||
struct Entries {
|
||||
input: String,
|
||||
confirm: String,
|
||||
<<<<<<< HEAD
|
||||
/// The fields' verdict; `None` before the first pass, when only a dialog that asks no confirmation may be accepted.
|
||||
valid: Option<bool>,
|
||||
=======
|
||||
reveal: bool,
|
||||
}
|
||||
|
||||
impl Entries {
|
||||
/// Whether OK may be pressed: a new password needs a non-empty entry that its confirmation repeats; one that may
|
||||
/// also be cleared takes two empty entries too, and two entries that differ never pass.
|
||||
fn valid(&self, purpose: &PasswordPurpose) -> bool {
|
||||
match purpose {
|
||||
PasswordPurpose::Set => !self.input.is_empty() && self.input == self.confirm,
|
||||
PasswordPurpose::SetOrClear => self.input == self.confirm,
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
>>>>>>> origin/next
|
||||
}
|
||||
|
||||
/// A question with a lock icon, the message, the masked field and the buttons. A new password adds a confirmation
|
||||
@@ -457,13 +447,9 @@ impl<'a> PasswordDialog<'a> {
|
||||
let env = Env::of(ui);
|
||||
let words = env.words::<PasswordWords>();
|
||||
let common = env.words::<CommonWords>();
|
||||
<<<<<<< HEAD
|
||||
let setting = matches!(purpose, PasswordPurpose::Set);
|
||||
let counted = |count: usize| (count as u64, env.format().integer(count as u64));
|
||||
=======
|
||||
let setting = matches!(purpose, PasswordPurpose::Set | PasswordPurpose::SetOrClear);
|
||||
let clearing = matches!(purpose, PasswordPurpose::SetOrClear);
|
||||
>>>>>>> origin/next
|
||||
let counted = |count: usize| (count as u64, env.format().integer(count as u64));
|
||||
let (title, message, ok) = match &purpose {
|
||||
PasswordPurpose::Open { files } => {
|
||||
let message = match files {
|
||||
@@ -488,11 +474,9 @@ impl<'a> PasswordDialog<'a> {
|
||||
PasswordPurpose::Set => (words.set_title.clone(), None, common.ok.clone()),
|
||||
PasswordPurpose::SetOrClear => (words.set_title.clone(), None, common.ok.clone()),
|
||||
};
|
||||
let (guard_purpose, settle_purpose) = (purpose.clone(), purpose.clone());
|
||||
let mut dialog = Dialog::new(title)
|
||||
.title_icon(IconId::new("lock"))
|
||||
.buttons([FooterButton::new(ok, DialogRole::Accept), FooterButton::new(common.cancel.clone(), DialogRole::Cancel)])
|
||||
<<<<<<< HEAD
|
||||
.close_on_enter(true)
|
||||
.close_guard(move |_, cx| {
|
||||
let entries = cx.memory::<Entries>();
|
||||
@@ -509,11 +493,6 @@ impl<'a> PasswordDialog<'a> {
|
||||
})
|
||||
.settle_buttons(move |cx, buttons| {
|
||||
let valid = cx.memory::<Entries>().valid.unwrap_or(false);
|
||||
=======
|
||||
.close_guard(move |_, cx| cx.memory::<Entries>().valid(&guard_purpose))
|
||||
.settle_buttons(move |cx, buttons| {
|
||||
let valid = cx.memory::<Entries>().valid(&settle_purpose);
|
||||
>>>>>>> origin/next
|
||||
if let Some(accept) = buttons.first_mut() {
|
||||
accept.set_enabled(valid);
|
||||
}
|
||||
@@ -529,86 +508,23 @@ impl<'a> PasswordDialog<'a> {
|
||||
if let Some(message) = &message {
|
||||
Text::new(message.clone()).show(ui);
|
||||
}
|
||||
<<<<<<< HEAD
|
||||
if let Some(note) = ¬e {
|
||||
Text::new(note.clone()).shade(Shade::Muted).show(ui);
|
||||
=======
|
||||
let strength = (setting && !entries.input.is_empty()).then(|| password_strength(&entries.input));
|
||||
FieldGroup::new(words.fields.clone()).show(ui, |ui, _| {
|
||||
let first = if setting { words.type_password.clone() } else { words.password.clone() };
|
||||
let mut field = Field::new(first.clone());
|
||||
if let Some(strength) = strength {
|
||||
let (word, tone) = match strength {
|
||||
PasswordStrength::Weak => (&words.weak, Tone::Bad),
|
||||
PasswordStrength::Medium => (&words.medium, Tone::Warn),
|
||||
PasswordStrength::Strong => (&words.strong, Tone::Good),
|
||||
};
|
||||
field = field.help(Help::Status(tone, Label::from(words.strength.fill(&[("strength", word.as_str())]))));
|
||||
} else if let (false, Some(error)) = (setting, &error) {
|
||||
field = field.help(Help::Status(Tone::Bad, error.clone()));
|
||||
}
|
||||
field.show(ui, |ui, _| {
|
||||
Row::new().show(ui, |ui, _| {
|
||||
let mut text = TextField::new(first.clone(), Bind::bound(&mut entries.input));
|
||||
if !entries.reveal {
|
||||
text = text.masked();
|
||||
}
|
||||
let text = text.show(ui);
|
||||
let name = if entries.reveal { words.hide.clone() } else { words.show.clone() };
|
||||
let reveal = ToggleButton::new(name, Bind::bound(&mut entries.reveal))
|
||||
.icon(IconId::new("eye"))
|
||||
.on_icon(IconId::new("eye_off"))
|
||||
.icon_only()
|
||||
.show(ui);
|
||||
// Typing goes on in the field: the reveal button hands the focus back, as does a press that left
|
||||
// nothing focused.
|
||||
if clicked(reveal.response()) || focus::focused_rec(ui.ctx()).is_none() {
|
||||
focus::request(ui.ctx(), FocusTarget::Id(text.response().id));
|
||||
}
|
||||
});
|
||||
});
|
||||
if setting {
|
||||
let mismatch = (!entries.confirm.is_empty() && entries.input != entries.confirm).then(|| words.mismatch.clone());
|
||||
let mut confirm = Field::new(words.retype_password.clone());
|
||||
if let Some(mismatch) = mismatch {
|
||||
confirm = confirm.help(Help::Status(Tone::Bad, mismatch));
|
||||
}
|
||||
confirm.show(ui, |ui, _| {
|
||||
let mut text = TextField::new(words.retype_password.clone(), Bind::bound(&mut entries.confirm));
|
||||
if !entries.reveal {
|
||||
text = text.masked();
|
||||
}
|
||||
text.show(ui);
|
||||
});
|
||||
}
|
||||
});
|
||||
if clearing {
|
||||
Text::new(words.clear_hint.clone()).shade(Shade::Muted).show(ui);
|
||||
}
|
||||
if let Some(strength) = strength {
|
||||
let (filled, variant) = match strength {
|
||||
PasswordStrength::Weak => (1.0 / 3.0, Variant::DANGER),
|
||||
PasswordStrength::Medium => (2.0 / 3.0, Variant::look(Emphasis::Solid, Tone::Warn)),
|
||||
PasswordStrength::Strong => (1.0, Variant::look(Emphasis::Solid, Tone::Good)),
|
||||
};
|
||||
Progress::new(filled).variant(variant).label(words.strength_meter.clone()).show(ui);
|
||||
>>>>>>> origin/next
|
||||
}
|
||||
let first = if setting { words.type_password.clone() } else { words.password.clone() };
|
||||
// A new password has no wrong-password line: its first field shows the strength instead.
|
||||
let mut fields =
|
||||
PasswordFields::new(first, Bind::bound(&mut entries.input)).bare(!setting).error(if setting { None } else { error.clone() });
|
||||
if setting {
|
||||
fields = fields.confirm(Bind::bound(&mut entries.confirm));
|
||||
fields = fields.confirm(Bind::bound(&mut entries.confirm)).clearable(clearing);
|
||||
}
|
||||
let shown = fields.show(ui);
|
||||
if clearing {
|
||||
Text::new(words.clear_hint.clone()).shade(Shade::Muted).show(ui);
|
||||
}
|
||||
valid.set(shown.valid);
|
||||
entries.valid = Some(shown.valid);
|
||||
});
|
||||
<<<<<<< HEAD
|
||||
=======
|
||||
valid.set(entries.valid(&purpose));
|
||||
>>>>>>> origin/next
|
||||
*typed.borrow_mut() = entries.input.clone();
|
||||
*cx.memory::<Entries>() = entries;
|
||||
});
|
||||
|
||||
@@ -1,13 +1,8 @@
|
||||
//! Stories of `PasswordDialog` and `PasswordFields`.
|
||||
|
||||
<<<<<<< HEAD
|
||||
use super::{PasswordDialog, PasswordFields, PasswordPurpose};
|
||||
use crate::contract::Bind;
|
||||
=======
|
||||
use super::{PasswordDialog, PasswordPurpose};
|
||||
use crate::buttons::Button;
|
||||
use crate::contract::{Show as _, clicked};
|
||||
>>>>>>> origin/next
|
||||
use crate::contract::{Bind, Show as _, clicked};
|
||||
use crate::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use egui::Ui;
|
||||
|
||||
@@ -52,7 +47,7 @@ fn password_dialog_several(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
Asks::Open => PasswordPurpose::open_several(3),
|
||||
Asks::Permissions => PasswordPurpose::permissions_several(3),
|
||||
};
|
||||
PasswordDialog::new(purpose).note("The files share one password.").opened(Bind::bound(data.value("open", true))).show(ui).into()
|
||||
PasswordDialog::new(purpose).note("The files share one password.").opened(data.bind("open", true)).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(PasswordFields<'static>, covers = [], drive = Drive::Never)]
|
||||
|
||||
@@ -463,20 +463,15 @@ impl Component for PreviewPane<'_> {
|
||||
}
|
||||
|
||||
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
<<<<<<< HEAD
|
||||
if self.thumbnail {
|
||||
let width = cx.tokens.size.thumb.sample.lg;
|
||||
return Vec2::new(width, width * THUMBNAIL_HEIGHT_IN_WIDTHS);
|
||||
}
|
||||
let width = cx.picture_width(cx.tokens.size.plot.width, f32::INFINITY);
|
||||
Vec2::new(width, self.aspect.filter(|aspect| *aspect > 0.0).map_or(0.0, |aspect| width / aspect))
|
||||
=======
|
||||
let least = cx.tokens.size.plot.width;
|
||||
match self.aspect.filter(|aspect| *aspect > 0.0) {
|
||||
Some(aspect) => cx.picture_size(least, f32::INFINITY, |width| width / aspect),
|
||||
None => Vec2::new(cx.picture_width(least, f32::INFINITY), 0.0),
|
||||
}
|
||||
>>>>>>> origin/next
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
|
||||
@@ -43,18 +43,12 @@ fn shown(
|
||||
#[story(PropertiesDialog<'static>, covers = [], drive = Drive::Never)]
|
||||
fn properties_dialog(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let read_only = *data.value("read_only", false);
|
||||
<<<<<<< HEAD
|
||||
shown(ui, data, tabs(), |dialog| dialog.read_only(read_only))
|
||||
=======
|
||||
let (values, values_at) = data.value_at("values", DialogFields::new());
|
||||
PropertiesDialog::new("Properties", tabs(), values_at.bind(values)).read_only(read_only).opened(Bind::given(true)).show(ui).into()
|
||||
>>>>>>> origin/next
|
||||
}
|
||||
|
||||
#[story(PropertiesDialog<'static>, covers = [], drive = Drive::Never)]
|
||||
fn properties_dialog_read_only(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let read_only = *data.value("read_only", true);
|
||||
<<<<<<< HEAD
|
||||
shown(ui, data, tabs(), |dialog| dialog.read_only(read_only))
|
||||
}
|
||||
|
||||
@@ -76,8 +70,4 @@ fn properties_dialog_extras(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
shown(ui, data, tabs(), |dialog| {
|
||||
dialog.shared(shared).shared_rows(SharedRows::Below).extra_buttons(vec![("metadata".to_owned(), Label::from("Additional Metadata…"))])
|
||||
})
|
||||
=======
|
||||
let (values, values_at) = data.value_at("values", DialogFields::new());
|
||||
PropertiesDialog::new("Properties", tabs(), values_at.bind(values)).read_only(read_only).opened(Bind::given(true)).show(ui).into()
|
||||
>>>>>>> origin/next
|
||||
}
|
||||
@@ -13,12 +13,8 @@ use super::words::ParamWords;
|
||||
use crate::buttons::{Button, ToggleButton};
|
||||
use crate::choice::{Checkbox, Radio, RadioGroup, Swatch};
|
||||
use crate::contract::{
|
||||
<<<<<<< HEAD
|
||||
LabelScheme, Pad, Sizing, Bind, BodyCx, CanvasGesture, Entry, FieldLayout, NoValue, Outcome, Props as _, Remember as _, Sampler as _, Show as _, ShowContainer as _,
|
||||
SideLabel, TooltipSpec, clicked,
|
||||
=======
|
||||
Bind, BodyCx, CanvasGesture, Entry, NoValue, Outcome, Props as _, Remember as _, Sampler as _, Show as _, ShowContainer as _, Sizing, clicked,
|
||||
>>>>>>> origin/next
|
||||
Bind, BodyCx, CanvasGesture, Entry, FieldLayout, LabelScheme, NoValue, Outcome, Pad, Props as _, Remember as _, Sampler as _, Show as _,
|
||||
ShowContainer as _, SideLabel, Sizing, TooltipSpec, clicked,
|
||||
};
|
||||
use crate::display::Text;
|
||||
use crate::form::{Field, FieldGroup, SliderField, SliderFieldLayout};
|
||||
@@ -30,20 +26,15 @@ use crate::pickers::{Select, UnitSelect};
|
||||
use crate::runtime::env::{Env, Label, UnitKind, Units, with_env};
|
||||
|
||||
use crate::sections::{HeaderStrength, Section};
|
||||
<<<<<<< HEAD
|
||||
use crate::text::{NumberField, RangeAlert, SelectableText, TextField};
|
||||
use crate::display::Text;
|
||||
=======
|
||||
use crate::text::{NumberField, RangeAlert, SelectableText, TextField, UnitPlacement};
|
||||
>>>>>>> origin/next
|
||||
|
||||
use crate::value_drag::{AngleDial, PointPicker, SliderScale};
|
||||
|
||||
use craft_behavior::{EditEvent, IconId, Mixed, NumberCodec, decimals_for_step};
|
||||
use craft_host::PickRequest;
|
||||
|
||||
use craft_theme::Srgba;
|
||||
use crate::style::SurfaceKind;
|
||||
use craft_theme::Srgba;
|
||||
use egui::{Id, Response, Ui};
|
||||
use std::collections::BTreeMap;
|
||||
use std::ops::RangeInclusive;
|
||||
@@ -336,8 +327,6 @@ struct Pass<'p> {
|
||||
shaded: bool,
|
||||
/// The heading the rows stand under (`ParamRows::heading`).
|
||||
heading: Option<String>,
|
||||
/// The rows being shown share one line ([`Param::beside_previous`]).
|
||||
in_line: bool,
|
||||
}
|
||||
|
||||
/// A parameter as the pass shows it: its key, its label without the colon, and whether it takes input.
|
||||
@@ -346,27 +335,19 @@ struct Line<'r> {
|
||||
key: &'r str,
|
||||
name: Label,
|
||||
enabled: bool,
|
||||
<<<<<<< HEAD
|
||||
/// The row stands in a shared line: it takes its content's width, not the form's.
|
||||
content: bool,
|
||||
=======
|
||||
compact: bool,
|
||||
>>>>>>> origin/next
|
||||
}
|
||||
|
||||
impl Line<'_> {
|
||||
/// Shows `body` in a field named by the row: its label beside the control, its tooltip over both.
|
||||
fn show(&self, ui: &mut Ui, mut body: impl FnMut(&mut Ui)) {
|
||||
let mut field = Field::new(self.name.clone()).id_salt(self.key).enabled(self.enabled);
|
||||
<<<<<<< HEAD
|
||||
// In a document dialog a custom row is a group of controls (page range options, say): its name heads it.
|
||||
if matches!(self.param.kind, ParamKind::Custom(_)) && Env::of(ui).view().get::<LabelScheme>() == LabelScheme::Inline {
|
||||
field = field.layout(FieldLayout::Above);
|
||||
}
|
||||
if self.content {
|
||||
=======
|
||||
if self.compact {
|
||||
>>>>>>> origin/next
|
||||
field = field.sizing(Sizing::Content);
|
||||
}
|
||||
if let Some(tip) = self.param.tooltip_text() {
|
||||
@@ -375,10 +356,11 @@ impl Line<'_> {
|
||||
field.show(ui, |ui, _| body(ui));
|
||||
}
|
||||
|
||||
/// A scalar field with the parameter's declared unit drawn beside the existing editable text.
|
||||
fn scalar_field(&self, units: &Units, value: f64, decimals: u32) -> NumberField<'static> {
|
||||
/// A scalar field with the parameter's declared unit drawn beside the existing editable text. A `fixed` field
|
||||
/// shows every one of its decimals ([`number_field`]).
|
||||
fn scalar_field(&self, units: &Units, value: f64, decimals: u32, fixed: bool) -> NumberField<'static> {
|
||||
let unit = self.param.unit;
|
||||
let field = number_field(units, self.name.clone(), Some(value), decimals, unit);
|
||||
let field = number_field(units, self.name.clone(), Some(value), decimals, unit, fixed);
|
||||
if let Some(unit) = unit { field.unit_kind(unit) } else { field }
|
||||
}
|
||||
|
||||
@@ -414,7 +396,6 @@ impl<'p> Pass<'p> {
|
||||
sliders: SliderFieldLayout::Inline,
|
||||
shaded: false,
|
||||
heading: None,
|
||||
in_line: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -472,97 +453,72 @@ impl<'p> Pass<'p> {
|
||||
fn rows(&mut self, ui: &mut Ui, params: &[Param]) {
|
||||
let is_section = |param: &Param| matches!(param.kind, ParamKind::Section);
|
||||
let first = params.iter().position(is_section).unwrap_or(params.len());
|
||||
<<<<<<< HEAD
|
||||
self.run(ui, ¶ms[..first]);
|
||||
=======
|
||||
self.section_rows(ui, ¶ms[..first]);
|
||||
>>>>>>> origin/next
|
||||
let mut rest = ¶ms[first..];
|
||||
while let Some((head, tail)) = rest.split_first() {
|
||||
let end = tail.iter().position(is_section).unwrap_or(tail.len());
|
||||
let (body, after) = tail.split_at(end);
|
||||
if head.visible(&self.work) {
|
||||
<<<<<<< HEAD
|
||||
let outer = self.heading.replace(plain(&head.label).as_str().to_owned());
|
||||
if self.shaded {
|
||||
// A document dialog's option group: a caption over its rows on a card.
|
||||
Section::fixed(plain(&head.label)).id_salt(head.key.as_str()).strength(HeaderStrength::Caption).show(ui, |ui, _| {
|
||||
Stack::new().fill_width().surface(SurfaceKind::Raised).pad(Pad::Control).show(ui, |ui, _| {
|
||||
self.run(ui, body);
|
||||
self.section_rows(ui, body);
|
||||
});
|
||||
});
|
||||
} else {
|
||||
Section::fixed(plain(&head.label)).id_salt(head.key.as_str()).show(ui, |ui, _| {
|
||||
self.run(ui, body);
|
||||
self.section_rows(ui, body);
|
||||
});
|
||||
}
|
||||
self.heading = outer;
|
||||
=======
|
||||
Section::fixed(plain(&head.label)).id_salt(head.key.as_str()).show(ui, |ui, _| {
|
||||
self.section_rows(ui, body);
|
||||
});
|
||||
>>>>>>> origin/next
|
||||
}
|
||||
rest = after;
|
||||
}
|
||||
}
|
||||
|
||||
<<<<<<< HEAD
|
||||
/// Shows `params` in order: a row marked [`Param::beside_previous`] shares the line of the shown row before it.
|
||||
fn run(&mut self, ui: &mut Ui, params: &[Param]) {
|
||||
/// Shows `params` in order. A row marked [`Param::beside_next`] pairs with the row after it; the rows marked
|
||||
/// [`Param::beside_previous`] after a shown row share its line. Both wrap when the form is too narrow.
|
||||
fn section_rows(&mut self, ui: &mut Ui, params: &[Param]) {
|
||||
let mut rest = params;
|
||||
while let Some((head, tail)) = rest.split_first() {
|
||||
if head.pairs_with_next()
|
||||
&& let Some((next, after)) = tail.split_first()
|
||||
{
|
||||
rest = after;
|
||||
// A row with no visible fields must not add a gap to the form.
|
||||
if !head.visible(&self.work) && !next.visible(&self.work) {
|
||||
continue;
|
||||
}
|
||||
Row::new().id_salt(head.key.as_str()).wrap(true).fill_width().show(ui, |ui, _| {
|
||||
self.row(ui, head, true);
|
||||
self.row(ui, next, true);
|
||||
});
|
||||
continue;
|
||||
}
|
||||
let beside = tail.iter().take_while(|param| param.option().beside()).count();
|
||||
if beside == 0 || !head.visible(&self.work) {
|
||||
self.row(ui, head);
|
||||
self.row(ui, head, false);
|
||||
rest = tail;
|
||||
continue;
|
||||
}
|
||||
let (line, after) = tail.split_at(beside);
|
||||
self.in_line = true;
|
||||
Row::new().wrap(true).show(ui, |ui, _| {
|
||||
self.row(ui, head);
|
||||
self.row(ui, head, true);
|
||||
for param in line {
|
||||
self.row(ui, param);
|
||||
self.row(ui, param, true);
|
||||
}
|
||||
});
|
||||
self.in_line = false;
|
||||
rest = after;
|
||||
}
|
||||
}
|
||||
|
||||
fn row(&mut self, ui: &mut Ui, param: &Param) {
|
||||
if !param.visible(&self.work) {
|
||||
return;
|
||||
}
|
||||
let line = Line { param, key: param.key.as_str(), name: plain(¶m.label), enabled: param.enabled(&self.work), content: self.in_line };
|
||||
=======
|
||||
fn section_rows(&mut self, ui: &mut Ui, params: &[Param]) {
|
||||
let mut params = params.iter();
|
||||
while let Some(param) = params.next() {
|
||||
if param.pairs_with_next()
|
||||
&& let Some(next) = params.next()
|
||||
{
|
||||
// A row with no visible fields must not add a gap to the form.
|
||||
if !param.visible(&self.work) && !next.visible(&self.work) {
|
||||
continue;
|
||||
}
|
||||
Row::new().id_salt(param.key.as_str()).wrap(true).fill_width().show(ui, |ui, _| {
|
||||
self.row(ui, param, true);
|
||||
self.row(ui, next, true);
|
||||
});
|
||||
} else {
|
||||
self.row(ui, param, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn row(&mut self, ui: &mut Ui, param: &Param, compact: bool) {
|
||||
if !param.visible(&self.work) {
|
||||
return;
|
||||
}
|
||||
let line = Line { param, key: param.key.as_str(), name: plain(¶m.label), enabled: param.enabled(&self.work), compact };
|
||||
>>>>>>> origin/next
|
||||
let held = self.work.get(line.key).cloned();
|
||||
self.show_row(ui, &line);
|
||||
param.drop_dependents(held.as_ref(), &mut self.work);
|
||||
@@ -673,11 +629,7 @@ impl<'p> Pass<'p> {
|
||||
fn number(&mut self, ui: &mut Ui, line: &Line<'_>, range: Option<RangeInclusive<f64>>, step: f64, decimals: u32) {
|
||||
let value = self.work.number(line.key).unwrap_or(0.0);
|
||||
line.show(ui, |ui| {
|
||||
<<<<<<< HEAD
|
||||
let mut field = unit_field(self.units, line.name.clone(), Some(value), decimals, line.param.unit, self.shaded).step(step);
|
||||
=======
|
||||
let mut field = line.scalar_field(self.units, value, decimals).step(step);
|
||||
>>>>>>> origin/next
|
||||
let mut field = line.scalar_field(self.units, value, decimals, self.shaded).step(step);
|
||||
if let Some(range) = range.clone() {
|
||||
field = field.range(range);
|
||||
}
|
||||
@@ -742,11 +694,7 @@ impl<'p> Pass<'p> {
|
||||
let random = line.param.option().randomize();
|
||||
line.show(ui, |ui| {
|
||||
beside(ui, |ui| {
|
||||
<<<<<<< HEAD
|
||||
let mut field = number_field(self.units, line.name.clone(), Some(value as f64), WHOLE, line.param.unit, false).id_salt("field");
|
||||
=======
|
||||
let mut field = line.scalar_field(self.units, value as f64, WHOLE).id_salt("field");
|
||||
>>>>>>> origin/next
|
||||
let mut field = line.scalar_field(self.units, value as f64, WHOLE, false).id_salt("field");
|
||||
if let Some(range) = range.clone() {
|
||||
field = field.range(range);
|
||||
}
|
||||
@@ -829,12 +777,8 @@ impl<'p> Pass<'p> {
|
||||
let first = patterns.clone().next();
|
||||
let current = patterns.find(|key| Some(key.as_str()) == stored).or(first).cloned();
|
||||
// With no pattern to offer the row is disabled and writes nothing.
|
||||
<<<<<<< HEAD
|
||||
let line = Line { param: line.param, key: line.key, name: line.name.clone(), enabled: line.enabled && current.is_some(), content: line.content };
|
||||
=======
|
||||
let line =
|
||||
Line { param: line.param, key: line.key, name: line.name.clone(), enabled: line.enabled && current.is_some(), compact: line.compact };
|
||||
>>>>>>> origin/next
|
||||
line.show(ui, |ui| {
|
||||
let picked = PresetPicker::pattern(line.name.clone(), Bind::given(current.clone()), source, Bind::kept()).show(ui).picked;
|
||||
if let Some(id) = picked.filter(|id| rows.iter().any(|row| matches!(row.kind, PresetKind::Item) && row.key == *id)) {
|
||||
@@ -897,84 +841,63 @@ impl<'p> Pass<'p> {
|
||||
/// A radio row is its own section: the title shows the row's name once, and the group it names follows. A row with
|
||||
/// [`options_in_row`](Param::options_in_row) has no title and stands its options side by side.
|
||||
fn radio_options(&mut self, ui: &mut Ui, line: &Line<'_>, options: &[(String, Label)]) {
|
||||
<<<<<<< HEAD
|
||||
let value = self.work.text(line.key).map(str::to_owned).or_else(|| line.param.kind.default_value().and_then(text_of)).unwrap_or_default();
|
||||
let inline = Env::of(ui).view().get::<LabelScheme>() == LabelScheme::Inline;
|
||||
let mut body = |ui: &mut Ui| {
|
||||
let mut group = RadioGroup::new(line.name.clone(), Bind::given(value.clone())).enabled(line.enabled);
|
||||
if let Some(tip) = line.param.tooltip_text() {
|
||||
group = group.tooltip(tip.clone());
|
||||
}
|
||||
let group = group.show(ui, |ui, _| {
|
||||
let mut options_row = |ui: &mut Ui, cx: &mut BodyCx<'_>| {
|
||||
for (id, label) in options {
|
||||
let mut radio = Radio::new(id.clone()).enabled(line.param.option_enabled(id) && line.enabled);
|
||||
if let Some(reason) = line.param.disabled_reason(id) {
|
||||
radio = radio.tooltip(TooltipSpec::new(reason.clone()).disabled_text(reason.clone()));
|
||||
}
|
||||
match line.param.option_description_text(id) {
|
||||
Some(text) => {
|
||||
let side = SideLabel::new().layout(FieldLayout::After).detail(text.clone());
|
||||
cx.labelled(ui, id.as_str(), label.clone(), side, radio);
|
||||
}
|
||||
None => {
|
||||
radio.label(label.clone()).show(ui);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
if inline {
|
||||
Row::new().wrap(true).show(ui, &mut options_row);
|
||||
} else {
|
||||
Stack::new().show(ui, &mut options_row);
|
||||
}
|
||||
});
|
||||
if let Some(v) = group.output.value().cloned() {
|
||||
self.work.set(line.key, FieldValue::Text(v));
|
||||
}
|
||||
};
|
||||
// A document dialog sets the caption and its options on one line, as production's do.
|
||||
if inline {
|
||||
Row::new().wrap(true).show(ui, |ui, _| {
|
||||
if self.heading.as_deref() != Some(plain(&line.name).as_str()) {
|
||||
Text::new(line.name.clone()).show(ui);
|
||||
}
|
||||
body(ui);
|
||||
});
|
||||
} else {
|
||||
Section::fixed(line.name.clone()).strength(HeaderStrength::Caption).id_salt(line.key).show(ui, |ui, _| body(ui));
|
||||
=======
|
||||
if line.param.option().options_in_row() {
|
||||
self.radio_group(ui, line, options, true);
|
||||
return;
|
||||
}
|
||||
// A document dialog sets the caption and its options on one line, as production's do; the caption is left out
|
||||
// under a heading of the same name.
|
||||
if inline {
|
||||
let caption = self.heading.as_deref() != Some(plain(&line.name).as_str());
|
||||
Row::new().wrap(true).show(ui, |ui, _| {
|
||||
if caption {
|
||||
Text::new(line.name.clone()).show(ui);
|
||||
}
|
||||
self.radio_group(ui, line, options, true);
|
||||
});
|
||||
return;
|
||||
}
|
||||
Section::fixed(line.name.clone()).strength(HeaderStrength::Caption).id_salt(line.key).show(ui, |ui, _| {
|
||||
self.radio_group(ui, line, options, false);
|
||||
});
|
||||
}
|
||||
|
||||
/// The radio group of `line`, its options in a column, or side by side when `in_row`.
|
||||
/// The radio group of `line`, its options in a column, or side by side (wrapping when the room is short) when
|
||||
/// `in_row`. An option shows its description beside it ([`Param::option_description`]) and, while disabled, its
|
||||
/// reason as its tooltip ([`Param::disabled_option`]).
|
||||
fn radio_group(&mut self, ui: &mut Ui, line: &Line<'_>, options: &[(String, Label)], in_row: bool) {
|
||||
let value = self.work.text(line.key).map(str::to_owned).or_else(|| line.param.kind.default_value().and_then(text_of)).unwrap_or_default();
|
||||
let mut group = RadioGroup::new(line.name.clone(), Bind::given(value)).enabled(line.enabled);
|
||||
if let Some(tip) = line.param.tooltip_text() {
|
||||
group = group.tooltip(tip.clone());
|
||||
}
|
||||
let radios = |ui: &mut Ui| {
|
||||
let radios = |ui: &mut Ui, cx: &mut BodyCx<'_>| {
|
||||
for (id, label) in options {
|
||||
Radio::new(id.clone()).label(label.clone()).enabled(line.param.option_enabled(id) && line.enabled).show(ui);
|
||||
let mut radio = Radio::new(id.clone()).enabled(line.param.option_enabled(id) && line.enabled);
|
||||
if let Some(reason) = line.param.disabled_reason(id) {
|
||||
radio = radio.tooltip(TooltipSpec::new(reason.clone()).disabled_text(reason.clone()));
|
||||
}
|
||||
match line.param.option_description_text(id) {
|
||||
Some(text) => {
|
||||
let side = SideLabel::new().layout(FieldLayout::After).detail(text.clone());
|
||||
cx.labelled(ui, id.as_str(), label.clone(), side, radio);
|
||||
}
|
||||
None => {
|
||||
radio.label(label.clone()).show(ui);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
let group = group.show(ui, |ui, _| {
|
||||
if in_row {
|
||||
Row::new().show(ui, |ui, _| radios(ui));
|
||||
Row::new().wrap(true).show(ui, radios);
|
||||
} else {
|
||||
Stack::new().show(ui, |ui, _| radios(ui));
|
||||
Stack::new().show(ui, radios);
|
||||
}
|
||||
});
|
||||
if let Some(v) = group.output.value().cloned() {
|
||||
self.work.set(line.key, FieldValue::Text(v));
|
||||
>>>>>>> origin/next
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1091,7 +1014,8 @@ impl<'p> Pass<'p> {
|
||||
_ => point,
|
||||
};
|
||||
for (axis, name) in names.iter().enumerate() {
|
||||
let field = number_field(self.units, name.clone(), Some(point[axis]), 1, Some(UnitKind::Percent), false).range(PERCENT).id_salt(axis);
|
||||
let field =
|
||||
number_field(self.units, name.clone(), Some(point[axis]), 1, Some(UnitKind::Percent), false).range(PERCENT).id_salt(axis);
|
||||
let shown = field.show(ui);
|
||||
self.alert(shown.out_of_range);
|
||||
if let Some(v) = shown.edit.value().cloned().flatten() {
|
||||
@@ -1174,11 +1098,7 @@ impl<'p> Pass<'p> {
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
<<<<<<< HEAD
|
||||
let field = unit_field(self.units, line.name.clone(), Some(last), decimals, line.param.unit, self.shaded).range(range.clone());
|
||||
=======
|
||||
let field = line.scalar_field(self.units, last, decimals).range(range.clone());
|
||||
>>>>>>> origin/next
|
||||
let field = line.scalar_field(self.units, last, decimals, self.shaded).range(range.clone());
|
||||
let field = field.id_salt("field").enabled(self.work.number(line.key).is_some());
|
||||
let shown = field.show(ui);
|
||||
self.alert(shown.out_of_range);
|
||||
@@ -1258,15 +1178,6 @@ fn number_field(units: &Units, name: Label, value: Option<f64>, decimals: u32, u
|
||||
NumberField::new(name, Bind::given(value)).codec(if fixed && decimals > 0 { codec.fixed() } else { codec })
|
||||
}
|
||||
|
||||
/// A [`number_field`] that shows the symbol of its unit after the number (the parameter's `unit`).
|
||||
fn unit_field(units: &Units, name: Label, value: Option<f64>, decimals: u32, unit: Option<UnitKind>, fixed: bool) -> NumberField<'static> {
|
||||
let field = number_field(units, name, value, decimals, unit, fixed);
|
||||
match unit {
|
||||
Some(kind) => field.unit_kind(kind),
|
||||
None => field,
|
||||
}
|
||||
}
|
||||
|
||||
/// The range that has the bounds that are set, open on the other side; `None` when neither is.
|
||||
fn bounds(min: Option<f64>, max: Option<f64>) -> Option<RangeInclusive<f64>> {
|
||||
(min.is_some() || max.is_some()).then(|| min.unwrap_or(f64::NEG_INFINITY)..=max.unwrap_or(f64::INFINITY))
|
||||
|
||||
@@ -1,179 +0,0 @@
|
||||
//! The contents of the preferences window: a search field with its match count over one scrolling page of cards.
|
||||
|
||||
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::{Bind, Pad, Props as _, Scroll, Show as _, ShowContainer as _};
|
||||
use crate::display::{Shade, Text};
|
||||
use crate::form::FieldGroup;
|
||||
use crate::layout_components::{Row, Stack};
|
||||
use crate::notices::{Notice, NoticeLayout};
|
||||
use crate::runtime::env::{Env, Label, Units};
|
||||
use crate::sections::Section;
|
||||
use crate::style::{SurfaceKind, TypeRole};
|
||||
use crate::text::TextField;
|
||||
use craft_i18n::matcher::Matcher;
|
||||
use craft_theme::variant::Tone;
|
||||
use egui::Ui;
|
||||
|
||||
/// 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 cards to show, in order, and how many matches the search
|
||||
/// found.
|
||||
pub(super) struct Snapshot {
|
||||
pub shown: Vec<ShownPage>,
|
||||
pub searching: bool,
|
||||
/// The settings the search matched: rows whose text matches, and a listed page that has none counts itself.
|
||||
pub matches: usize,
|
||||
}
|
||||
|
||||
/// The cards of `host` under `matcher`: every listed page, each with the rows the search keeps.
|
||||
pub(super) fn snapshot<H: PreferencesModel + ?Sized>(host: &H, matcher: &Matcher) -> Snapshot {
|
||||
let pages = host.pages();
|
||||
let listed = search::list_pages(&pages, matcher);
|
||||
let searching = !matcher.is_empty();
|
||||
let mut matches = 0;
|
||||
let shown = listed
|
||||
.iter()
|
||||
.map(|l| {
|
||||
let page = &pages[l.index];
|
||||
if searching {
|
||||
let rows = page.groups.iter().flat_map(|g| &g.rows).filter(|r| r.visible && search::row_matches(matcher, r)).count();
|
||||
matches += rows.max(usize::from(!page.has_content() || l.all_rows && rows == 0));
|
||||
}
|
||||
shown_page(matcher, l, page)
|
||||
})
|
||||
.collect();
|
||||
Snapshot { shown, searching, matches }
|
||||
}
|
||||
|
||||
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,
|
||||
/// The page whose Reset Section was pressed.
|
||||
pub reset: Option<String>,
|
||||
pub custom_changed: bool,
|
||||
}
|
||||
|
||||
impl BodyOut {
|
||||
pub fn edits(&mut self) -> Vec<(String, PrefValue)> {
|
||||
std::mem::take(&mut self.rows.edits)
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows the search field with its match count over the cards: one scrolling page, a card per page. `state.search`
|
||||
/// changes as the user types; a `state.selected` the page has not scrolled to yet is brought into view once.
|
||||
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,
|
||||
) {
|
||||
Row::new().fill_width().show(ui, |ui, _| {
|
||||
TextField::search(words.search_label.clone(), Bind::bound(&mut state.search)).placeholder(words.search_placeholder.clone()).show(ui);
|
||||
if snap.searching {
|
||||
let env = Env::of(ui);
|
||||
let n = env.format().integer(snap.matches as u64);
|
||||
let text = if snap.matches == 1 { words.match_one.fill(&[("n", &n)]) } else { words.match_other.fill(&[("n", &n)]) };
|
||||
let shade = if snap.matches == 0 { Shade::Faint } else { Shade::Muted };
|
||||
Text::new(text).role(TypeRole::Caption).shade(shade).show(ui);
|
||||
}
|
||||
});
|
||||
if snap.shown.is_empty() {
|
||||
Notice::new(Tone::Info, words.no_matches.clone()).layout(NoticeLayout::Centred).show(ui);
|
||||
return;
|
||||
}
|
||||
// The scroll goes to the page the host named once, when it is first shown or changes.
|
||||
let jump = !state.selected.is_empty() && state.scrolled_to != state.selected && snap.shown.iter().any(|page| page.id == state.selected);
|
||||
Stack::new().fill().scroll(Scroll::vertical()).label(words.pages_label.clone()).show(ui, |ui, _| {
|
||||
for page in &snap.shown {
|
||||
let top = ui.cursor().min;
|
||||
show_card(ui, host, page, snap.searching, words, units, out);
|
||||
if jump && page.id == state.selected {
|
||||
ui.scroll_to_rect(egui::Rect::from_min_size(top, egui::vec2(1.0, 1.0)), Some(egui::Align::TOP));
|
||||
}
|
||||
}
|
||||
});
|
||||
if jump {
|
||||
state.scrolled_to = state.selected.clone();
|
||||
}
|
||||
}
|
||||
|
||||
/// One page as a card: its title, groups, footnote and Reset Section.
|
||||
fn show_card<H: PreferencesModel + ?Sized>(
|
||||
ui: &mut Ui,
|
||||
host: &mut H,
|
||||
page: &ShownPage,
|
||||
searching: bool,
|
||||
words: &PreferencesWords,
|
||||
units: &Units,
|
||||
out: &mut BodyOut,
|
||||
) {
|
||||
Stack::new().fill_width().surface(SurfaceKind::Raised).pad(Pad::Regular).label(page.title.clone()).id_salt(page.id.as_str()).show(ui, |ui, _| {
|
||||
Text::new(page.title.clone()).role(TypeRole::Heading).show(ui);
|
||||
if page.custom {
|
||||
Stack::new().show(ui, |ui, _| out.custom_changed |= 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 = Some(page.id.clone());
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -123,7 +123,8 @@ pub struct RowSpec<'a> {
|
||||
/// decimals. Ignored by other kinds.
|
||||
pub step: Option<f64>,
|
||||
/// A choice row: `Some(true)` draws its options as a segmented (pill) control, `Some(false)` as a drop-down; by
|
||||
/// default a short choice of up to five options is segmented. Ignored by other kinds.
|
||||
/// default a drop-down, and on a card ([`PreferencesLayout::Cards`](super::PreferencesLayout::Cards)) a short
|
||||
/// choice of up to five options is segmented. Ignored by other kinds.
|
||||
pub pills: Option<bool>,
|
||||
/// The control and the value it shows.
|
||||
pub kind: RowKind<'a>,
|
||||
@@ -320,28 +321,12 @@ pub trait PreferencesModel {
|
||||
fn set_color(&mut self, key: &str, color: Srgba) {
|
||||
self.set(key, PrefValue::Color(color.into()));
|
||||
}
|
||||
<<<<<<< HEAD
|
||||
/// Draws a [`RowKind::Custom`] row's control, returning whether its draft changed this pass.
|
||||
fn custom_row(&mut self, ui: &mut Ui, key: &str) -> bool;
|
||||
/// Draws a [`PageSpec::custom`] page, returning whether its draft changed this pass.
|
||||
fn custom_page(&mut self, ui: &mut Ui, page: &str) -> bool;
|
||||
/// Whether the draft differs from the saved settings: enables Apply.
|
||||
fn differs(&self) -> bool;
|
||||
/// Whether OK may close the window.
|
||||
fn can_ok(&self) -> bool {
|
||||
true
|
||||
}
|
||||
/// Commits the draft. `Err` keeps it and the window open and shows the message.
|
||||
fn apply(&mut self) -> Result<(), String>;
|
||||
/// Drops the draft and undoes previews (the language).
|
||||
fn cancel(&mut self);
|
||||
=======
|
||||
/// Draws a [`RowKind::Custom`] row's control, which the window labels from the row's label (an empty label shows
|
||||
/// an empty one), or a [`RowKind::CustomRows`] row's whole rows, labels included.
|
||||
fn custom_row(&mut self, ui: &mut Ui, key: &str);
|
||||
/// Draws a [`PageSpec::custom`] page.
|
||||
fn custom_page(&mut self, ui: &mut Ui, page: &str);
|
||||
>>>>>>> origin/next
|
||||
/// an empty one), or a [`RowKind::CustomRows`] row's whole rows, labels included. Returns whether the row changed
|
||||
/// the draft this pass, so an edit made there clears a failed apply's message as any row's edit does.
|
||||
fn custom_row(&mut self, ui: &mut Ui, key: &str) -> bool;
|
||||
/// Draws a [`PageSpec::custom`] page, returning whether it changed the draft this pass.
|
||||
fn custom_page(&mut self, ui: &mut Ui, page: &str) -> bool;
|
||||
/// Resets the page's rows in the draft to their defaults.
|
||||
fn reset_page(&mut self, page: &str);
|
||||
/// Draws the dialogs the host opened from this window (a colour picker) inside the same viewport. Called last in
|
||||
|
||||
@@ -9,7 +9,7 @@ use super::search::{self, Listed};
|
||||
use super::window::PreferencesState;
|
||||
use super::words::PreferencesWords;
|
||||
use crate::contract::{
|
||||
ActivateOn, Bind, CollectionEvent, NoValue, Outcome, Pattern, Props, Scroll, SelectMode, Show as _, ShowCollection as _, ShowContainer as _,
|
||||
ActivateOn, Bind, CollectionEvent, NoValue, Outcome, Pad, Pattern, Props, Scroll, SelectMode, Show as _, ShowCollection as _, ShowContainer as _,
|
||||
Sizing,
|
||||
};
|
||||
use crate::display::{Divider, Shade, Text};
|
||||
@@ -21,7 +21,7 @@ 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::style::{SurfaceKind, TypeRole};
|
||||
use crate::text::TextField;
|
||||
use craft_behavior::{DisplayOrder, EditEvent, ItemSource, Mixed, Selection, SelectionChange};
|
||||
use craft_i18n::matcher::Matcher;
|
||||
@@ -29,21 +29,38 @@ use craft_theme::variant::Tone;
|
||||
use egui::{Response, Ui};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// How a [`PreferencesPage`] lays out the host's pages. Both keep the same search, rows, edits and Reset Section.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum PreferencesLayout {
|
||||
/// A page list beside the shown page, each row's control in a field named by the row: WordCraft's preferences.
|
||||
#[default]
|
||||
Paged,
|
||||
/// One scrolling column of cards, a card per listed page with its groups, each row's label then its control on one
|
||||
/// line and a short choice as a segmented control ([`RowSpec::pills`](super::RowSpec::pills)); the search field
|
||||
/// shows its match count beside it, and the column brings the picked page into view once: PdfCraft's preferences.
|
||||
Cards,
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// page list. With [`PreferencesLayout::Cards`] every listed page shows as a card in one scrolling column instead,
|
||||
/// the search field shows how many settings match, and a picked page the column has not scrolled to is brought
|
||||
/// into view once.
|
||||
/// - **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.
|
||||
/// appeared starts with no search and no error; an edit, a custom row's or page's change, or a Reset clears the
|
||||
/// error.
|
||||
///
|
||||
/// [`PreferencesWindow`]: super::PreferencesWindow
|
||||
#[derive(Pattern, Props)]
|
||||
pub struct PreferencesPage<'a> {
|
||||
state: Bind<'a, PreferencesState>,
|
||||
layout: PreferencesLayout,
|
||||
}
|
||||
|
||||
/// What a [`PreferencesPage`] reports: its response, the colour the host should pick and the page shown.
|
||||
@@ -54,7 +71,8 @@ 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 id of the page shown, `None` when the search lists no page.
|
||||
/// The id of the page shown, `None` when the search lists no page. With [`PreferencesLayout::Cards`], the picked
|
||||
/// page while the search lists it, else the first card.
|
||||
pub page: Option<String>,
|
||||
}
|
||||
|
||||
@@ -66,11 +84,13 @@ impl Outcome for PreferencesPageOutput {
|
||||
}
|
||||
}
|
||||
|
||||
/// What the rows of one run ask of the host: the values they edited and whether Reset Section was pressed.
|
||||
/// What the rows of one run ask of the host: the values they edited, the page whose Reset Section was pressed and
|
||||
/// whether a custom page changed the draft.
|
||||
#[derive(Default)]
|
||||
struct BodyOut {
|
||||
rows: RowsOut,
|
||||
reset: bool,
|
||||
reset: Option<String>,
|
||||
custom_changed: 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.
|
||||
@@ -82,15 +102,22 @@ struct PageRun {
|
||||
}
|
||||
|
||||
impl<'a> PreferencesPage<'a> {
|
||||
/// A page over the host's `state`.
|
||||
/// A page over the host's `state`, laid out as [`PreferencesLayout::Paged`].
|
||||
pub fn new(state: Bind<'a, PreferencesState>) -> Self {
|
||||
PreferencesPage { state }
|
||||
PreferencesPage { state, layout: PreferencesLayout::default() }
|
||||
}
|
||||
|
||||
/// Lays the pages out as `layout` says.
|
||||
#[must_use]
|
||||
pub fn layout(mut self, layout: PreferencesLayout) -> Self {
|
||||
self.layout = layout;
|
||||
self
|
||||
}
|
||||
|
||||
/// 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 PreferencesPage { mut state } = self;
|
||||
let PreferencesPage { mut state, layout } = self;
|
||||
let env = Env::of(ui);
|
||||
let words = env.words::<PreferencesWords>();
|
||||
let units = env.units();
|
||||
@@ -106,23 +133,32 @@ impl<'a> PreferencesPage<'a> {
|
||||
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 page = match layout {
|
||||
PreferencesLayout::Paged => {
|
||||
let snap = snapshot(&*host, &matcher, &work.selected);
|
||||
show_body(ui, &mut *host, &snap, &mut work, &words, &units, &mut out);
|
||||
snap.shown.map(|page| page.id)
|
||||
}
|
||||
PreferencesLayout::Cards => {
|
||||
let snap = cards_snapshot(&*host, &matcher);
|
||||
show_cards(ui, &mut *host, &snap, &mut work, &words, &units, &mut out);
|
||||
let shown = snap.shown.iter().find(|page| page.id == work.selected).or(snap.shown.first());
|
||||
shown.map(|page| page.id.clone())
|
||||
}
|
||||
};
|
||||
PageRun { before, work, out, page }
|
||||
});
|
||||
let pick_color = shown
|
||||
.settle(|cx, run| {
|
||||
let edits = std::mem::take(&mut run.out.rows.edits);
|
||||
if !edits.is_empty() || run.out.reset {
|
||||
if !edits.is_empty() || run.out.reset.is_some() || run.out.custom_changed || run.out.rows.custom_changed {
|
||||
run.work.error = None;
|
||||
}
|
||||
for (key, value) in edits {
|
||||
host.set(&key, value);
|
||||
}
|
||||
if run.out.reset
|
||||
&& let Some(page) = &run.page
|
||||
{
|
||||
if let Some(page) = &run.out.reset {
|
||||
host.reset_page(page);
|
||||
}
|
||||
if run.work != run.before {
|
||||
@@ -166,6 +202,15 @@ struct Snapshot {
|
||||
searching: bool,
|
||||
}
|
||||
|
||||
/// What the host's pages look like under the search as cards: the cards to show, in order, and how many settings the
|
||||
/// search matched.
|
||||
struct CardsSnapshot {
|
||||
shown: Vec<ShownPage>,
|
||||
searching: bool,
|
||||
/// The settings the search matched: rows whose text matches, and a listed page that has none counts itself.
|
||||
matches: usize,
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
@@ -179,6 +224,26 @@ fn snapshot<H: PreferencesModel + ?Sized>(host: &H, matcher: &Matcher, selected:
|
||||
Snapshot { list, shown, searching: !matcher.is_empty() }
|
||||
}
|
||||
|
||||
/// The cards of `host` under `matcher`: every listed page, each with the rows the search keeps.
|
||||
fn cards_snapshot<H: PreferencesModel + ?Sized>(host: &H, matcher: &Matcher) -> CardsSnapshot {
|
||||
let pages = host.pages();
|
||||
let listed = search::list_pages(&pages, matcher);
|
||||
let searching = !matcher.is_empty();
|
||||
let mut matches = 0;
|
||||
let shown = listed
|
||||
.iter()
|
||||
.map(|l| {
|
||||
let page = &pages[l.index];
|
||||
if searching {
|
||||
let rows = page.groups.iter().flat_map(|g| &g.rows).filter(|r| r.visible && search::row_matches(matcher, r)).count();
|
||||
matches += rows.max(usize::from(!page.has_content() || l.all_rows && rows == 0));
|
||||
}
|
||||
shown_page(matcher, l, page)
|
||||
})
|
||||
.collect();
|
||||
CardsSnapshot { shown, searching, matches }
|
||||
}
|
||||
|
||||
fn shown_page(matcher: &Matcher, listed: &Listed, page: &PageSpec<'_>) -> ShownPage {
|
||||
let groups = page
|
||||
.groups
|
||||
@@ -280,7 +345,7 @@ fn show_page<H: PreferencesModel + ?Sized>(
|
||||
) {
|
||||
Text::new(page.title.clone()).role(TypeRole::Title).show(ui);
|
||||
if page.custom {
|
||||
Stack::new().show(ui, |ui, _| host.custom_page(ui, &page.id));
|
||||
Stack::new().show(ui, |ui, _| out.custom_changed |= 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);
|
||||
}
|
||||
@@ -290,7 +355,7 @@ fn show_page<H: PreferencesModel + ?Sized>(
|
||||
let mut rows = |ui: &mut Ui| {
|
||||
Stack::new().id_salt(at).show(ui, |ui, _| {
|
||||
for row in &group.rows {
|
||||
show_row(ui, host, row, units, &mut out.rows);
|
||||
show_row(ui, host, row, units, PreferencesLayout::Paged, &mut out.rows);
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -307,6 +372,89 @@ fn show_page<H: PreferencesModel + ?Sized>(
|
||||
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;
|
||||
out.reset = Some(page.id.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows the search field with its match count over the cards: one scrolling column, a card per page. `state.search`
|
||||
/// changes as the user types; a `state.selected` the column has not scrolled to yet is brought into view once.
|
||||
fn show_cards<H: PreferencesModel + ?Sized>(
|
||||
ui: &mut Ui,
|
||||
host: &mut H,
|
||||
snap: &CardsSnapshot,
|
||||
state: &mut PreferencesState,
|
||||
words: &PreferencesWords,
|
||||
units: &Units,
|
||||
out: &mut BodyOut,
|
||||
) {
|
||||
Row::new().fill_width().show(ui, |ui, _| {
|
||||
TextField::search(words.search_label.clone(), Bind::bound(&mut state.search)).placeholder(words.search_placeholder.clone()).show(ui);
|
||||
if snap.searching {
|
||||
let env = Env::of(ui);
|
||||
let n = env.format().integer(snap.matches as u64);
|
||||
let text = if snap.matches == 1 { words.match_one.fill(&[("n", &n)]) } else { words.match_other.fill(&[("n", &n)]) };
|
||||
let shade = if snap.matches == 0 { Shade::Faint } else { Shade::Muted };
|
||||
Text::new(text).role(TypeRole::Caption).shade(shade).show(ui);
|
||||
}
|
||||
});
|
||||
if snap.shown.is_empty() {
|
||||
Notice::new(Tone::Info, words.no_matches.clone()).layout(NoticeLayout::Centred).show(ui);
|
||||
return;
|
||||
}
|
||||
// The scroll goes to the page the host named once, when it is first shown or changes.
|
||||
let jump = !state.selected.is_empty() && state.scrolled_to != state.selected && snap.shown.iter().any(|page| page.id == state.selected);
|
||||
Stack::new().fill().scroll(Scroll::vertical()).label(words.cards_label.clone()).show(ui, |ui, _| {
|
||||
for page in &snap.shown {
|
||||
let top = ui.cursor().min;
|
||||
show_card(ui, host, page, snap.searching, words, units, out);
|
||||
if jump && page.id == state.selected {
|
||||
ui.scroll_to_rect(egui::Rect::from_min_size(top, egui::vec2(1.0, 1.0)), Some(egui::Align::TOP));
|
||||
}
|
||||
}
|
||||
});
|
||||
if jump {
|
||||
state.scrolled_to = state.selected.clone();
|
||||
}
|
||||
}
|
||||
|
||||
/// One page as a card: its title, groups, footnote and Reset Section.
|
||||
fn show_card<H: PreferencesModel + ?Sized>(
|
||||
ui: &mut Ui,
|
||||
host: &mut H,
|
||||
page: &ShownPage,
|
||||
searching: bool,
|
||||
words: &PreferencesWords,
|
||||
units: &Units,
|
||||
out: &mut BodyOut,
|
||||
) {
|
||||
Stack::new().fill_width().surface(SurfaceKind::Raised).pad(Pad::Regular).label(page.title.clone()).id_salt(page.id.as_str()).show(ui, |ui, _| {
|
||||
Text::new(page.title.clone()).role(TypeRole::Heading).show(ui);
|
||||
if page.custom {
|
||||
Stack::new().show(ui, |ui, _| out.custom_changed |= 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, PreferencesLayout::Cards, &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 = Some(page.id.clone());
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Stories of `PreferencesPage`.
|
||||
|
||||
use super::PreferencesLayout;
|
||||
use crate::patterns::preferences::{PageSpec, PrefValue, PreferencesModel, PreferencesPage, PreferencesState, RowKind, RowSpec};
|
||||
use crate::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use craft_theme::Rgba;
|
||||
@@ -52,9 +53,13 @@ impl PreferencesModel for Live {
|
||||
}
|
||||
}
|
||||
|
||||
fn custom_row(&mut self, _: &mut Ui, _: &str) {}
|
||||
fn custom_row(&mut self, _: &mut Ui, _: &str) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn custom_page(&mut self, _: &mut Ui, _: &str) {}
|
||||
fn custom_page(&mut self, _: &mut Ui, _: &str) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn reset_page(&mut self, page: &str) {
|
||||
let defaults = Live::default();
|
||||
@@ -68,8 +73,13 @@ impl PreferencesModel for Live {
|
||||
|
||||
/// The page over the story's settings.
|
||||
fn page(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
laid_out(ui, data, PreferencesLayout::Paged)
|
||||
}
|
||||
|
||||
/// The page over the story's settings, laid out as `layout` says.
|
||||
fn laid_out(ui: &mut Ui, data: &mut StoryData, layout: PreferencesLayout) -> StoryOutput {
|
||||
let mut live = data.value("live", Live::default()).clone();
|
||||
let shown = PreferencesPage::new(data.bind("state", PreferencesState::default())).show(ui, &mut live);
|
||||
let shown = PreferencesPage::new(data.bind("state", PreferencesState::default())).layout(layout).show(ui, &mut live);
|
||||
*data.value("live", Live::default()) = live;
|
||||
shown.into()
|
||||
}
|
||||
@@ -84,3 +94,9 @@ fn preferences_page(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
fn preferences_page_searching(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
page(ui, data)
|
||||
}
|
||||
|
||||
/// The page as one scrolling column of cards.
|
||||
#[story(PreferencesPage<'static>, covers = [], drive = Drive::Never)]
|
||||
fn preferences_page_cards(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
laid_out(ui, data, PreferencesLayout::Cards)
|
||||
}
|
||||
@@ -1,16 +1,18 @@
|
||||
//! One row of a page: the library's control for its kind in a `Field`, reporting the value it edited.
|
||||
//! One row of a page: the library's control for its kind, in a `Field` or on a card's line, reporting the value it
|
||||
//! edited.
|
||||
|
||||
use super::model::{PrefValue, PreferencesModel, RowKind, RowSpec};
|
||||
use super::page::PreferencesLayout;
|
||||
use crate::buttons::Button;
|
||||
use crate::choice::{Checkbox, Segmented, Swatch};
|
||||
use crate::display::{Shade, Text};
|
||||
use crate::style::TypeRole;
|
||||
use crate::contract::{Bind, Entry, FieldLayout, Props as _, Show as _, ShowContainer as _, clicked};
|
||||
use crate::display::{Shade, Text};
|
||||
use crate::form::{Field, Help};
|
||||
use crate::layout_components::{Row, Stack};
|
||||
use crate::pickers::Select;
|
||||
use crate::runtime::env::{Label, UnitKind, Units};
|
||||
use crate::runtime::requests::ColorRequest;
|
||||
use crate::style::TypeRole;
|
||||
use crate::text::{HexField, NumberField, TextField};
|
||||
use craft_behavior::NumberCodec;
|
||||
use craft_theme::{Rgba, Srgba};
|
||||
@@ -81,6 +83,7 @@ impl ShownRow {
|
||||
#[derive(Default)]
|
||||
pub(super) struct RowsOut {
|
||||
pub edits: Vec<(String, PrefValue)>,
|
||||
/// A custom row's host reported that its draft changed.
|
||||
pub custom_changed: bool,
|
||||
/// The request of the swatch pressed this pass, keyed by the row.
|
||||
pub pick_color: Option<ColorRequest>,
|
||||
@@ -104,18 +107,20 @@ fn counted_option(units: &Units, kind: UnitKind, option: &Entry<String>) -> Entr
|
||||
}
|
||||
}
|
||||
|
||||
/// The most options and the most label characters of a choice shown as a segmented control; a longer choice is a
|
||||
/// drop-down.
|
||||
/// The most options and the most label characters of a choice a card shows as a segmented control by default; a
|
||||
/// longer choice is a drop-down.
|
||||
const SEGMENTS_MAX: usize = 5;
|
||||
const SEGMENTS_CHARS: usize = 48;
|
||||
|
||||
fn as_segments(options: &[Entry<String>], unit: Option<UnitKind>, pills: Option<bool>) -> bool {
|
||||
/// Whether a choice of `options` shows as a segmented control: as the row's [`RowSpec::pills`] says, else on a card
|
||||
/// (`cards`) when it is short, and never with separators or fewer than two options.
|
||||
fn as_segments(options: &[Entry<String>], unit: Option<UnitKind>, pills: Option<bool>, cards: bool) -> bool {
|
||||
let plain = options.iter().all(|option| !option.is_separator());
|
||||
let count = options.len();
|
||||
let chars: usize = options.iter().map(|option| option.label().as_str().chars().count()).sum();
|
||||
match pills {
|
||||
Some(want) => want && plain && count >= 2,
|
||||
None => plain && unit.is_none() && (2..=SEGMENTS_MAX).contains(&count) && chars <= SEGMENTS_CHARS,
|
||||
None => cards && plain && unit.is_none() && (2..=SEGMENTS_MAX).contains(&count) && chars <= SEGMENTS_CHARS,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,17 +131,28 @@ fn help_line(ui: &mut Ui, help: &Option<Label>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows `row` and records what it edited in `out`.
|
||||
pub(super) fn show_row<H: PreferencesModel + ?Sized>(ui: &mut Ui, host: &mut H, row: &ShownRow, units: &Units, out: &mut RowsOut) {
|
||||
/// The field a row's control stands in: named by the row, with its help.
|
||||
fn field_of(row: &ShownRow) -> Field {
|
||||
let field = Field::new(row.label.clone()).id_salt(row.key.as_str()).enabled(row.enabled);
|
||||
match &row.help {
|
||||
Some(help) => field.help(Help::Text(help.clone())),
|
||||
None => field,
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows `row` as `layout` lays rows out and records what it edited in `out`.
|
||||
pub(super) fn show_row<H: PreferencesModel + ?Sized>(
|
||||
ui: &mut Ui,
|
||||
host: &mut H,
|
||||
row: &ShownRow,
|
||||
units: &Units,
|
||||
layout: PreferencesLayout,
|
||||
out: &mut RowsOut,
|
||||
) {
|
||||
let key = row.key.as_str();
|
||||
let label = &row.label;
|
||||
let field = || {
|
||||
let field = Field::new(label.clone()).id_salt(key).enabled(row.enabled);
|
||||
match &row.help {
|
||||
Some(help) => field.help(Help::Text(help.clone())),
|
||||
None => field,
|
||||
}
|
||||
};
|
||||
let cards = layout == PreferencesLayout::Cards;
|
||||
let field = || field_of(row);
|
||||
let mut record = |value: Option<PrefValue>| {
|
||||
if let Some(value) = value {
|
||||
out.edits.push((key.to_owned(), value));
|
||||
@@ -160,8 +176,8 @@ pub(super) fn show_row<H: PreferencesModel + ?Sized>(ui: &mut Ui, host: &mut H,
|
||||
}
|
||||
None => options,
|
||||
};
|
||||
let segments = as_segments(options, *unit, row.pills);
|
||||
inline(ui, row, |ui| {
|
||||
let segments = as_segments(options, *unit, row.pills, cards);
|
||||
control(ui, row, cards, |ui| {
|
||||
next = if segments {
|
||||
Segmented::new(label.clone(), Bind::given(value.clone()), options).show(ui).value().cloned()
|
||||
} else {
|
||||
@@ -172,7 +188,7 @@ pub(super) fn show_row<H: PreferencesModel + ?Sized>(ui: &mut Ui, host: &mut H,
|
||||
}
|
||||
Kind::Int { value, range, unit } => {
|
||||
let mut next = None;
|
||||
inline(ui, row, |ui| {
|
||||
control(ui, row, cards, |ui| {
|
||||
let shown = number(units, label, *value as f64, *unit, 0).range(*range.start() as f64..=*range.end() as f64).step(1.0);
|
||||
next = shown.show(ui).edit.events.landed().cloned().flatten();
|
||||
});
|
||||
@@ -180,7 +196,7 @@ pub(super) fn show_row<H: PreferencesModel + ?Sized>(ui: &mut Ui, host: &mut H,
|
||||
}
|
||||
Kind::Float { value, range, decimals, step, unit } => {
|
||||
let mut next = None;
|
||||
inline(ui, row, |ui| {
|
||||
control(ui, row, cards, |ui| {
|
||||
let shown = number(units, label, *value, *unit, usize::from(*decimals))
|
||||
.range(range.clone())
|
||||
.step(step.unwrap_or_else(|| step_for(range, *decimals)));
|
||||
@@ -190,7 +206,7 @@ pub(super) fn show_row<H: PreferencesModel + ?Sized>(ui: &mut Ui, host: &mut H,
|
||||
}
|
||||
Kind::Text(value) => {
|
||||
let mut next = None;
|
||||
inline(ui, row, |ui| {
|
||||
control(ui, row, cards, |ui| {
|
||||
next = TextField::new(label.clone(), Bind::given(value.clone())).show(ui).events.landed().cloned();
|
||||
});
|
||||
record(next.map(PrefValue::Text));
|
||||
@@ -198,29 +214,32 @@ pub(super) fn show_row<H: PreferencesModel + ?Sized>(ui: &mut Ui, host: &mut H,
|
||||
Kind::Color(color) => {
|
||||
let mut next = None;
|
||||
let mut ask = None;
|
||||
inline(ui, row, |ui| {
|
||||
let mut pair = |ui: &mut Ui| {
|
||||
let swatch = Swatch::new(label.clone(), Srgba::from(*color)).picker(key).id_salt("choose").show(ui);
|
||||
ask = swatch.pick_color;
|
||||
next = HexField::hex(label.clone(), Bind::given(*color)).id_salt("hex").show(ui).events.landed().cloned();
|
||||
};
|
||||
// A card's line holds the swatch and the hex field after the label; a field holds them in a row.
|
||||
control(ui, row, cards, |ui| {
|
||||
if cards {
|
||||
pair(ui);
|
||||
} else {
|
||||
Row::new().show(ui, |ui, _| pair(ui));
|
||||
}
|
||||
});
|
||||
record(next.map(PrefValue::Color));
|
||||
if ask.is_some() {
|
||||
out.pick_color = ask;
|
||||
}
|
||||
}
|
||||
<<<<<<< HEAD
|
||||
Kind::Custom if label.as_str().is_empty() => {
|
||||
Stack::new().id_salt(key).show(ui, |ui, _| out.custom_changed |= host.custom_row(ui, key));
|
||||
=======
|
||||
Kind::CustomRows => {
|
||||
// The host draws the rows and their labels; the rule's enabled state and help apply to them as to a field.
|
||||
Stack::new().id_salt(key).enabled(row.enabled).show(ui, |ui, _| {
|
||||
host.custom_row(ui, key);
|
||||
out.custom_changed |= host.custom_row(ui, key);
|
||||
if let Some(help) = &row.help {
|
||||
Help::Text(help.clone()).text().show(ui);
|
||||
}
|
||||
});
|
||||
>>>>>>> origin/next
|
||||
}
|
||||
Kind::Custom => {
|
||||
field().show(ui, |ui, _| {
|
||||
@@ -230,7 +249,21 @@ pub(super) fn show_row<H: PreferencesModel + ?Sized>(ui: &mut Ui, host: &mut H,
|
||||
}
|
||||
}
|
||||
|
||||
/// One row on a line, as production's cards draw them: the label, then the control, then the help under both.
|
||||
/// Shows a row's control, drawn by `body`: on one line after the row's label on a card (`cards`), else in the row's field.
|
||||
fn control(ui: &mut Ui, row: &ShownRow, cards: bool, body: impl FnOnce(&mut Ui)) {
|
||||
if cards {
|
||||
inline(ui, row, body);
|
||||
return;
|
||||
}
|
||||
let mut body = Some(body);
|
||||
field_of(row).show(ui, |ui, _| {
|
||||
if let Some(body) = body.take() {
|
||||
body(ui);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// One row on a line, as a card draws it: the label, then the control, then the help under both.
|
||||
fn inline(ui: &mut Ui, row: &ShownRow, control: impl FnOnce(&mut Ui)) {
|
||||
let mut control = Some(control);
|
||||
Stack::new().id_salt(row.key.as_str()).enabled(row.enabled).show(ui, |ui, _| {
|
||||
|
||||
@@ -7,7 +7,7 @@ pub(crate) mod stories;
|
||||
#[cfg(doc)]
|
||||
use super::model::PreferencesModel;
|
||||
use super::model::{Closed, PreferencesDraft, PreferencesOutput};
|
||||
use super::page::PreferencesPage;
|
||||
use super::page::{PreferencesLayout, PreferencesPage};
|
||||
use super::words::PreferencesWords;
|
||||
use crate::contract::{Bind, Props as _, SaveKey, Show as _, ShowContainer as _};
|
||||
use crate::dialog::{Dialog, DialogOutput};
|
||||
@@ -23,11 +23,15 @@ use egui::{Ui, Vec2, vec2};
|
||||
use std::cell::RefCell;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The size the window opens at until the user resizes it.
|
||||
<<<<<<< HEAD
|
||||
pub const DEFAULT_SIZE: Vec2 = vec2(640.0, 720.0); // design: allow[literal-size/vec2](the window's own opening size in points)
|
||||
/// The size the window opens at until the user resizes it, with the page list ([`PreferencesLayout::Paged`]).
|
||||
pub const DEFAULT_SIZE: Vec2 = vec2(1040.0, 800.0);
|
||||
/// The least size the window may be resized to.
|
||||
pub const MIN_SIZE: Vec2 = vec2(420.0, 320.0); // design: allow[literal-size/vec2](the window's own least size in points)
|
||||
pub const MIN_SIZE: Vec2 = vec2(560.0, 400.0);
|
||||
/// The size a window of cards ([`PreferencesLayout::Cards`]) opens at: one column of cards needs no room for a page
|
||||
/// list.
|
||||
const CARDS_SIZE: Vec2 = vec2(640.0, 720.0);
|
||||
/// The least size a window of cards may be resized to.
|
||||
const CARDS_MIN_SIZE: Vec2 = vec2(420.0, 320.0);
|
||||
|
||||
/// When preferences changes are applied.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
@@ -39,11 +43,6 @@ pub enum PreferencesMode {
|
||||
/// Apply changes as they happen; OK closes the window.
|
||||
Live,
|
||||
}
|
||||
=======
|
||||
pub const DEFAULT_SIZE: Vec2 = vec2(1040.0, 800.0);
|
||||
/// The least size the window may be resized to.
|
||||
pub const MIN_SIZE: Vec2 = vec2(560.0, 400.0);
|
||||
>>>>>>> origin/next
|
||||
|
||||
/// What the window keeps between passes; the host owns it and binds it with [`PreferencesWindow::new`].
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
@@ -74,6 +73,9 @@ pub struct PreferencesState {
|
||||
/// - **Buttons.** OK applies and closes, Apply applies and stays (enabled while the draft differs), Cancel drops the
|
||||
/// draft. A failed apply keeps the window open and shows its message in the footer. Enter activates OK and Escape
|
||||
/// cancels, once the search text, a field's own gesture and a popup have had them.
|
||||
/// - **Layout.** [`layout`](PreferencesWindow::layout) passes a [`PreferencesLayout`] to the page:
|
||||
/// [`PreferencesLayout::Cards`] shows one scrolling column of cards with the search's match count, and the window
|
||||
/// opens narrower, as it needs no room for a page list.
|
||||
/// - **Live mode.** [`PreferencesMode::Live`] applies changes as they occur and shows only OK, which closes without
|
||||
/// applying again. Closing the window does not cancel changes. A failed apply shows its message until another edit.
|
||||
/// - **Nested dialogs.** While [`PreferencesModel::nested_open`] is true the window takes no input and refuses to
|
||||
@@ -97,6 +99,7 @@ pub struct PreferencesWindow<'a> {
|
||||
#[prop]
|
||||
remember: Option<SaveKey>,
|
||||
mode: PreferencesMode,
|
||||
layout: PreferencesLayout,
|
||||
}
|
||||
|
||||
/// What the body, the footer and the buttons' guard share during one pass: the host, the window's state as the pass
|
||||
@@ -151,7 +154,14 @@ impl<H: PreferencesDraft + ?Sized> Session<'_, '_, H> {
|
||||
impl<'a> PreferencesWindow<'a> {
|
||||
/// A window over the host's `state`.
|
||||
pub fn new(state: Bind<'a, PreferencesState>) -> Self {
|
||||
PreferencesWindow { state, title: None, embedded: false, remember: None, mode: PreferencesMode::Staged }
|
||||
PreferencesWindow { state, title: None, embedded: false, remember: None, mode: PreferencesMode::Staged, layout: PreferencesLayout::Paged }
|
||||
}
|
||||
|
||||
/// Lays the page out as `layout` says ([`PreferencesPage::layout`]); the default is [`PreferencesLayout::Paged`].
|
||||
#[must_use]
|
||||
pub fn layout(mut self, layout: PreferencesLayout) -> Self {
|
||||
self.layout = layout;
|
||||
self
|
||||
}
|
||||
|
||||
/// Selects whether changes are staged or applied while the window is open.
|
||||
@@ -162,13 +172,8 @@ impl<'a> PreferencesWindow<'a> {
|
||||
}
|
||||
|
||||
/// Shows the window for this pass over `host`. The output's `closed` tells the host to stop showing it.
|
||||
<<<<<<< HEAD
|
||||
pub fn show<H: PreferencesModel + ?Sized>(self, ui: &mut Ui, host: &mut H) -> PreferencesOutput {
|
||||
let PreferencesWindow { state, title, embedded, remember, mode } = self;
|
||||
=======
|
||||
pub fn show<H: PreferencesDraft + ?Sized>(self, ui: &mut Ui, host: &mut H) -> PreferencesOutput {
|
||||
let PreferencesWindow { state, title, embedded, remember } = self;
|
||||
>>>>>>> origin/next
|
||||
let PreferencesWindow { state, title, embedded, remember, mode, layout } = self;
|
||||
let env = Env::of(ui);
|
||||
let words = env.words::<PreferencesWords>();
|
||||
let common = env.words::<CommonWords>();
|
||||
@@ -185,6 +190,10 @@ impl<'a> PreferencesWindow<'a> {
|
||||
let buttons =
|
||||
if mode == PreferencesMode::Live { vec![ok] } else { vec![ok, apply, FooterButton::new(common.cancel.clone(), DialogRole::Cancel)] };
|
||||
|
||||
let (size, least) = match layout {
|
||||
PreferencesLayout::Paged => (DEFAULT_SIZE, MIN_SIZE),
|
||||
PreferencesLayout::Cards => (CARDS_SIZE, CARDS_MIN_SIZE),
|
||||
};
|
||||
let mut open = true;
|
||||
// Filed by a swatch press in this pass.
|
||||
let mut pick_color = None;
|
||||
@@ -200,7 +209,7 @@ impl<'a> PreferencesWindow<'a> {
|
||||
let mut dialog = Dialog::new(title.clone())
|
||||
.collection_body()
|
||||
.resizable(true)
|
||||
.overlay(|overlay| overlay.size(DEFAULT_SIZE).min_size(MIN_SIZE))
|
||||
.overlay(|overlay| overlay.size(size).min_size(least))
|
||||
.close_on_enter(can_ok)
|
||||
.on_pick(|button, cx| {
|
||||
if button.role() == DialogRole::Other && !nested {
|
||||
@@ -228,38 +237,15 @@ impl<'a> PreferencesWindow<'a> {
|
||||
let mut guard = session.borrow_mut();
|
||||
let session = &mut *guard;
|
||||
session.begin(cx);
|
||||
<<<<<<< HEAD
|
||||
let matcher = Matcher::new(&env.folder(), session.work.search.trim());
|
||||
let snap = body::snapshot(&*session.host, &matcher);
|
||||
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)).layout(layout).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.is_some() || out.custom_changed || out.rows.custom_changed {
|
||||
session.work.error = None;
|
||||
}
|
||||
for (key, value) in edits {
|
||||
session.host.set(&key, value);
|
||||
}
|
||||
if let Some(page) = &out.reset {
|
||||
session.host.reset_page(page);
|
||||
}
|
||||
session.host.nested(ui);
|
||||
if mode == PreferencesMode::Live && session.work.error.is_none() && session.host.differs() {
|
||||
session.apply(cx);
|
||||
}
|
||||
let selected = session.work.selected.clone();
|
||||
session.page = snap.shown.iter().find(|page| page.id == selected).or(snap.shown.first()).map(|page| page.id.clone());
|
||||
=======
|
||||
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);
|
||||
}
|
||||
session.host.nested(ui.ctx());
|
||||
session.page = shown.page;
|
||||
>>>>>>> origin/next
|
||||
session.commit(cx);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,15 +1,9 @@
|
||||
//! Stories of `PreferencesWindow`.
|
||||
|
||||
<<<<<<< HEAD
|
||||
use super::{PreferencesMode, PreferencesState, PreferencesWindow};
|
||||
use super::{PreferencesLayout, PreferencesMode, PreferencesState, PreferencesWindow};
|
||||
use crate::buttons::Button;
|
||||
use crate::contract::{Bind, Entry, Show as _, clicked};
|
||||
use crate::patterns::preferences::{GroupSpec, PageSpec, PrefValue, PreferencesModel, RowKind, RowSpec};
|
||||
=======
|
||||
use super::{PreferencesState, PreferencesWindow};
|
||||
use crate::contract::Entry;
|
||||
use crate::patterns::preferences::{PageSpec, PrefValue, PreferencesDraft, PreferencesModel, RowKind, RowSpec};
|
||||
>>>>>>> origin/next
|
||||
use crate::patterns::preferences::{GroupSpec, PageSpec, PrefValue, PreferencesDraft, PreferencesModel, RowKind, RowSpec};
|
||||
use crate::runtime::env::UnitKind;
|
||||
use crate::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use craft_theme::Rgba;
|
||||
@@ -113,11 +107,12 @@ impl PreferencesModel for Demo {
|
||||
match page {
|
||||
"general" => (self.draft.snap, self.draft.language, self.draft.name) = (defaults.snap, defaults.language, defaults.name),
|
||||
"canvas" => (self.draft.size, self.draft.opacity, self.draft.tint) = (defaults.size, defaults.opacity, defaults.tint),
|
||||
"plugins" => (self.draft.load_plugins, self.draft.plugin_folder) = (defaults.load_plugins, defaults.plugin_folder),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn nested(&mut self, _: &Context) {}
|
||||
fn nested(&mut self, _: &mut Ui) {}
|
||||
}
|
||||
|
||||
impl PreferencesDraft for Demo {
|
||||
@@ -136,27 +131,17 @@ impl PreferencesDraft for Demo {
|
||||
fn cancel(&mut self) {
|
||||
self.draft = self.saved.clone();
|
||||
}
|
||||
<<<<<<< HEAD
|
||||
|
||||
fn reset_page(&mut self, page: &str) {
|
||||
let defaults = Values::default();
|
||||
match page {
|
||||
"general" => (self.draft.snap, self.draft.language, self.draft.name) = (defaults.snap, defaults.language, defaults.name),
|
||||
"canvas" => (self.draft.size, self.draft.opacity, self.draft.tint) = (defaults.size, defaults.opacity, defaults.tint),
|
||||
"plugins" => (self.draft.load_plugins, self.draft.plugin_folder) = (defaults.load_plugins, defaults.plugin_folder),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn nested(&mut self, _: &mut Ui) {}
|
||||
=======
|
||||
>>>>>>> origin/next
|
||||
}
|
||||
|
||||
fn window(ui: &mut Ui, data: &mut StoryData, state: PreferencesState, demo: Demo) -> StoryOutput {
|
||||
laid_out(ui, data, state, demo, PreferencesLayout::Paged)
|
||||
}
|
||||
|
||||
/// The window laid out as `layout` says.
|
||||
fn laid_out(ui: &mut Ui, data: &mut StoryData, state: PreferencesState, demo: Demo, layout: PreferencesLayout) -> StoryOutput {
|
||||
let mut demo = data.value("demo", demo).clone();
|
||||
let (state, state_at) = data.value_at("state", state);
|
||||
let shown = PreferencesWindow::new(state_at.bind(state)).embedded().show(ui, &mut demo).into();
|
||||
let shown = PreferencesWindow::new(state_at.bind(state)).layout(layout).embedded().show(ui, &mut demo).into();
|
||||
*data.value("demo", Demo::default()) = demo;
|
||||
shown
|
||||
}
|
||||
@@ -186,6 +171,19 @@ fn preferences_window_with_error(ui: &mut Ui, data: &mut StoryData) -> StoryOutp
|
||||
window(ui, data, state, Demo { refuse: true, ..Demo::default() })
|
||||
}
|
||||
|
||||
/// The cards layout: one scrolling column of cards, short choices as segments.
|
||||
#[story(PreferencesWindow<'static>, covers = [], drive = Drive::Never)]
|
||||
fn preferences_window_cards(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
laid_out(ui, data, PreferencesState::default(), Demo::default(), PreferencesLayout::Cards)
|
||||
}
|
||||
|
||||
/// The cards layout under a search: the field shows how many settings match.
|
||||
#[story(PreferencesWindow<'static>, covers = [], drive = Drive::Never)]
|
||||
fn preferences_window_cards_searching(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let state = PreferencesState { search: "size".to_owned(), ..PreferencesState::default() };
|
||||
laid_out(ui, data, state, Demo::default(), PreferencesLayout::Cards)
|
||||
}
|
||||
|
||||
/// Preferences that apply each edit immediately.
|
||||
#[story(PreferencesWindow<'static>, covers = [], drive = Drive::Never)]
|
||||
fn preferences_window_live(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
@@ -197,7 +195,8 @@ fn preferences_window_live(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let mut result = StoryOutput::default();
|
||||
if open {
|
||||
let state = data.value("live_state", PreferencesState::default());
|
||||
let shown = PreferencesWindow::new(Bind::bound(state)).mode(PreferencesMode::Live).embedded().show(ui, &mut demo);
|
||||
let shown =
|
||||
PreferencesWindow::new(Bind::bound(state)).mode(PreferencesMode::Live).layout(PreferencesLayout::Cards).embedded().show(ui, &mut demo);
|
||||
open = shown.closed.is_none();
|
||||
result = shown.into();
|
||||
}
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
//! Built-in words of the preferences family.
|
||||
|
||||
craft_ui::words! {
|
||||
/// The words of the preferences window: its title, search, page list and buttons that are not shared words. OK and
|
||||
/// The words of the preferences window: its title, search, page list or cards and buttons that are not shared words. OK and
|
||||
/// Cancel are `CommonWords`.
|
||||
pub struct PreferencesWords {
|
||||
title: "preferences.title" = "Preferences";
|
||||
search_label: "preferences.searchLabel" = "Search settings";
|
||||
search_placeholder: "preferences.searchPlaceholder" = "Search";
|
||||
clear_search: "preferences.clearSearch" = "Clear search";
|
||||
pages_label: "preferences.pagesLabel" = "Settings";
|
||||
pages_label: "preferences.pagesLabel" = "Pages";
|
||||
cards_label: "preferences.cardsLabel" = "Settings";
|
||||
match_one: template "preferences.matchOne" = "{n} match";
|
||||
match_other: template "preferences.matchOther" = "{n} matches";
|
||||
no_matches: "preferences.noMatches" = "No matching settings";
|
||||
|
||||
@@ -647,280 +647,6 @@ impl<K: Clone + Eq + Hash + Send + Sync + MemoProps + 'static> PresetBrowser<'_,
|
||||
empty: empty_text.clone(),
|
||||
sent: Outbox::new(&mut sent),
|
||||
};
|
||||
<<<<<<< HEAD
|
||||
// No drop lands on an action row; the list also keeps every drop before them.
|
||||
let accepts = |drag: &ListDrag<BrowserKey<K>>, over: Option<&BrowserKey<K>>, insert: usize| {
|
||||
let (Some(rules), Some(drag)) = (reorder.as_ref(), app_drag(drag)) else { return false };
|
||||
match over {
|
||||
Some(BrowserKey::Action(_)) => false,
|
||||
over => rules.allows(rows, &drag, over.and_then(BrowserKey::preset), insert),
|
||||
}
|
||||
};
|
||||
let list_accepts =
|
||||
|drag: &ListDrag<BrowserKey<K>>, over: Option<&BrowserKey<K>>, insert: usize| insert <= shown.len() && accepts(drag, over, insert);
|
||||
let rename_ok = |key: &K| can_rename.as_ref().is_none_or(|test| test.passes(key));
|
||||
let rename_row = |key: &BrowserKey<K>| key.preset().is_some_and(rename_ok);
|
||||
let painter = thumb.as_ref();
|
||||
let paint = |row: &PresetRow<K>, selected: bool| {
|
||||
let key = row.key.clone();
|
||||
let preview = row.preview.clone();
|
||||
move |cx: &ContentPainterCx, rect: Rect, painter: Option<&ThumbPainter<'_, K>>| match (painter, &preview) {
|
||||
(Some(painter), _) => (painter.0)(cx, rect, ThumbInfo::new(&key, selected, false)),
|
||||
(None, Some(preview)) => (preview.paint)(cx, rect),
|
||||
(None, None) => {}
|
||||
}
|
||||
};
|
||||
|
||||
let (response, displayed, pass) = if shown.is_empty() && actions.is_empty() {
|
||||
let message = if query.is_empty() { empty_text.clone().unwrap_or_else(|| words.empty.clone()) } else { words.no_match.clone() };
|
||||
let response = Notice::new(Tone::Neutral, message).layout(NoticeLayout::Centred).show(ui).response;
|
||||
(response, Vec::new(), Pass { seen: Vec::new(), grid: Vec::new() })
|
||||
} else if view == PresetView::Grid {
|
||||
let plan = grid_plan(rows, &shown, |at| open_flags[at], counted);
|
||||
let tiles = Shown { rows, at: plan.tiles.clone(), open: vec![false; plan.tiles.len()], tree: false, actions: 0 };
|
||||
let tail: Vec<TailRow<BrowserKey<K>>> =
|
||||
actions.iter().enumerate().map(|(at, label)| TailRow::new(BrowserKey::Action(at), label.clone())).collect();
|
||||
let aspect = card_aspect(cell_shape);
|
||||
let grid = TileGrid::<BrowserKey<K>>::new(label.clone())
|
||||
.id(list_id)
|
||||
.select(SelectMode::Single)
|
||||
.arrows_select(false)
|
||||
.selection(Bind::given(selection))
|
||||
.aspect(aspect);
|
||||
let grid = match tile_size {
|
||||
PresetTiles::Thumbnails => {
|
||||
let captions = if has_captions(rows) { CaptionPlace::Below } else { CaptionPlace::None };
|
||||
grid.caption(captions).thumb_size(ThumbSize::Large).zoom(GridZoom::Fixed(zoom))
|
||||
}
|
||||
// The zoom is a factor on the picture's width: a wide chip is the small thumbnail high.
|
||||
PresetTiles::Chips => grid
|
||||
.caption(CaptionPlace::None)
|
||||
.thumb_size(ThumbSize::Small)
|
||||
.zoom(GridZoom::Fixed(f64::from(aspect.max(1.0))))
|
||||
.row_height(RowHeight::Text),
|
||||
};
|
||||
let mut grid = grid
|
||||
.groups(&plan.groups)
|
||||
.tail(&tail)
|
||||
.collapsible()
|
||||
.rename(true)
|
||||
.deletable(true)
|
||||
.rows_stamp(stamp)
|
||||
.can_rename(rename_row)
|
||||
.can_drag(can_drag)
|
||||
.accepts(accepts)
|
||||
.card_columns(usize::from(columns));
|
||||
if reorder.is_some() {
|
||||
grid = grid.reorder(ReorderRule::new());
|
||||
}
|
||||
if reorder.is_some() || drop_zone.is_some() {
|
||||
grid = grid.drag_payload(app_drag::<K>);
|
||||
}
|
||||
if let Some(rows) = max_rows {
|
||||
grid = grid.max_rows(rows);
|
||||
}
|
||||
let aspect = cell_shape.aspect();
|
||||
let out = grid.show_items(ui, &tiles, &mut |key, icx| {
|
||||
let Some(row) = tiles.index_of(key).and_then(|at| tiles.row(at)) else { return Tile::new(Label::default()) };
|
||||
let mut tile = Tile::new(row.label.clone());
|
||||
if let Some(detail) = &row.caption {
|
||||
tile = tile.detail(detail.clone());
|
||||
}
|
||||
if row.dimmed {
|
||||
tile = tile.dimmed();
|
||||
}
|
||||
if let Some(tip) = &row.tooltip {
|
||||
tile = tile.tooltip(tip.clone());
|
||||
}
|
||||
if let Some(name) = &row.accessible_name {
|
||||
tile = tile.accessible_name(name.clone());
|
||||
}
|
||||
let selected = icx.row.selected;
|
||||
let draw = paint(row, selected);
|
||||
tile.thumb(row.preview.as_ref().map_or(aspect, |preview| preview.aspect), move |cx, rect| draw(cx, rect, painter))
|
||||
});
|
||||
(out.response.response.clone(), plan.tiles.clone(), Pass { seen: seen(out.response.events), grid: out.events })
|
||||
} else {
|
||||
let open: Vec<bool> = shown.iter().map(|&at| open_flags[at]).collect();
|
||||
let source = Shown { rows, at: shown.clone(), open, tree: true, actions: actions.len() };
|
||||
let thumb_size = list_thumb(zoom);
|
||||
let mut list = List::<BrowserKey<K>>::new(label.clone())
|
||||
.id(list_id)
|
||||
.tree(true)
|
||||
.select(SelectMode::Single)
|
||||
.arrows_select(false)
|
||||
.selection(Bind::given(selection))
|
||||
.rename(true)
|
||||
.deletable(true)
|
||||
.rows_stamp(stamp)
|
||||
.can_rename(rename_row)
|
||||
.can_drag(can_drag)
|
||||
.accepts(list_accepts);
|
||||
if reorder.is_some() {
|
||||
list = list.reorder(ReorderRule::new().into_groups());
|
||||
}
|
||||
if reorder.is_some() || drop_zone.is_some() {
|
||||
list = list.drag_payload(app_drag::<K>);
|
||||
}
|
||||
if let Some(rows) = max_rows {
|
||||
list = list.max_rows(rows);
|
||||
}
|
||||
let aspect = cell_shape.aspect();
|
||||
// The last preset row draws the divider above the action rows.
|
||||
let ruled = |at: usize| !actions.is_empty() && at + 1 == shown.len();
|
||||
let out = list.show_items(ui, &source, &mut |_, icx| {
|
||||
let Some(&at) = source.at.get(icx.at) else {
|
||||
return ListRow::new(actions[icx.at - shown.len()].clone());
|
||||
};
|
||||
let row = &rows[at];
|
||||
if row.is_group() {
|
||||
let mut line = ListRow::new(row.label.clone())
|
||||
.heading()
|
||||
.depth(row.depth)
|
||||
.group(icx.row.open)
|
||||
.icon(IconSpec::svg(folder(icx.row.open)))
|
||||
.rule(ruled(icx.at));
|
||||
if let Some(detail) = counted(at) {
|
||||
line = line.detail(detail);
|
||||
}
|
||||
return line;
|
||||
}
|
||||
let mut line = ListRow::new(row.label.clone()).depth(row.depth).rule(ruled(icx.at));
|
||||
if let Some(caption) = &row.caption {
|
||||
line = line.detail(caption.clone());
|
||||
}
|
||||
if row.dimmed {
|
||||
line = line.ink(RowInk::Dimmed);
|
||||
}
|
||||
if let Some(tip) = &row.tooltip {
|
||||
line = line.tooltip(tip.clone());
|
||||
}
|
||||
if let Some(name) = &row.accessible_name {
|
||||
line = line.accessible_name(name.clone());
|
||||
}
|
||||
let draw = paint(row, icx.row.selected);
|
||||
line.thumb_aspect(thumb_size, row.preview.as_ref().map_or(aspect, |preview| preview.aspect), move |cx, rect| {
|
||||
draw(cx, rect, painter)
|
||||
})
|
||||
});
|
||||
(out.response.clone(), shown.clone(), Pass { seen: seen(out.events), grid: Vec::new() })
|
||||
};
|
||||
|
||||
let mods = crate::runtime::pointer::frame(ui.ctx()).mods;
|
||||
let row_of = |key: &K| rows.iter().position(|row| row.key == *key);
|
||||
if let Some(zone) = drop_zone {
|
||||
let target = ZoneDrop { source: response.id, rows, zone };
|
||||
if let Some((key, at)) = drag::zone_target(ui.ctx(), list_id.with("drop zone"), zone, &target) {
|
||||
events.push(PresetEvent::DropAt { key, at, mods });
|
||||
}
|
||||
}
|
||||
let toggle = |local: &mut PresetState<K>, events: &mut Vec<PresetEvent<K>>, at: usize, open: Option<bool>| {
|
||||
let open = open.unwrap_or_else(|| !local.is_open(rows, at, default_open));
|
||||
let change = OpenChange::new(rows[at].key.clone(), open);
|
||||
local.apply_open(rows, &change, default_open);
|
||||
events.push(PresetEvent::Open(change));
|
||||
};
|
||||
for event in pass.grid {
|
||||
match event {
|
||||
GridEvent::GroupOpen { group, open } => {
|
||||
if let Some(&at) = grid_group_row(&shown, rows, group) {
|
||||
toggle(&mut local, &mut events, at, Some(open));
|
||||
}
|
||||
}
|
||||
GridEvent::GroupPicked { group, .. } => {
|
||||
if let Some(&at) = grid_group_row(&shown, rows, group) {
|
||||
toggle(&mut local, &mut events, at, None);
|
||||
}
|
||||
}
|
||||
GridEvent::GroupMenu { group, .. } => {
|
||||
if let Some(&at) = grid_group_row(&shown, rows, group) {
|
||||
menu_target = Some(rows[at].key.clone());
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// A secondary press or release selects the row it lands on so that the row's menu acts on it; that selection
|
||||
// is not a pick, and a picker would commit it.
|
||||
let frame = crate::runtime::pointer::frame(ui.ctx());
|
||||
let secondary =
|
||||
frame.buttons.contains(craft_behavior::Buttons::SECONDARY) || frame.release == Some(craft_behavior::PointerButton::Secondary);
|
||||
// An action row of the list is a plain row: a single press picks it, and Enter activates it. Its selection by
|
||||
// an arrow key, and the activation by the second click of a double click, are not a choice. The grid's
|
||||
// tail rows report Enter and a click as their activation.
|
||||
let list = view == PresetView::List;
|
||||
let first_press = frame.press.as_ref().is_some_and(|press| press.clicks == 1);
|
||||
let released = frame.release.is_some();
|
||||
let action = |events: &mut Vec<PresetEvent<K>>, at: usize| {
|
||||
if !events.contains(&PresetEvent::Action(at)) {
|
||||
events.push(PresetEvent::Action(at));
|
||||
}
|
||||
};
|
||||
for event in pass.seen {
|
||||
match event {
|
||||
Seen::Select(BrowserKey::Preset(key)) => {
|
||||
if !secondary && row_of(&key).is_some_and(|at| !rows[at].is_group()) {
|
||||
events.push(PresetEvent::Select { key, mods });
|
||||
}
|
||||
}
|
||||
Seen::Select(BrowserKey::Action(at)) => {
|
||||
if list && first_press && !secondary {
|
||||
action(&mut events, at);
|
||||
}
|
||||
}
|
||||
Seen::Activate(BrowserKey::Preset(key)) => match row_of(&key) {
|
||||
Some(at) if rows[at].is_group() => toggle(&mut local, &mut events, at, None),
|
||||
Some(_) => events.push(PresetEvent::Activate { key, mods }),
|
||||
None => {}
|
||||
},
|
||||
Seen::Activate(BrowserKey::Action(at)) => {
|
||||
if !(list && released) {
|
||||
action(&mut events, at);
|
||||
}
|
||||
}
|
||||
Seen::Open(change) => {
|
||||
if let BrowserKey::Preset(key) = change.key {
|
||||
let change = OpenChange { key, open: change.open, all: change.all };
|
||||
local.apply_open(rows, &change, default_open);
|
||||
events.push(PresetEvent::Open(change));
|
||||
}
|
||||
}
|
||||
Seen::Menu(key) => {
|
||||
if let BrowserKey::Preset(key) = key {
|
||||
menu_target = Some(key);
|
||||
}
|
||||
}
|
||||
Seen::Reorder(edit) => {
|
||||
let moved = |mv: ReorderMove<BrowserKey<K>>| {
|
||||
let mv = app_move(mv)?;
|
||||
let to = full_position(rows, &displayed, &mv);
|
||||
Some(ReorderMove { to, ..mv })
|
||||
};
|
||||
events.extend(edit.filter_map(moved).map(PresetEvent::Reorder));
|
||||
}
|
||||
// Delete and Backspace give the same event as the row menu's Delete and the footer button; an
|
||||
// open rename field takes the keys itself.
|
||||
Seen::Delete(keys) => {
|
||||
for key in keys {
|
||||
if let BrowserKey::Preset(key) = key
|
||||
&& can_delete.as_ref().is_none_or(|test| test.passes(&key))
|
||||
{
|
||||
events.push(PresetEvent::Delete(key));
|
||||
}
|
||||
}
|
||||
}
|
||||
Seen::Rename(edit) => {
|
||||
let ended = matches!(edit.phase(), Some(GesturePhase::Commit) | None);
|
||||
if let (true, Some(rename)) = (ended, edit.value())
|
||||
&& let BrowserKey::Preset(key) = &rename.key
|
||||
{
|
||||
let text = rename.name.trim();
|
||||
let changed = row_of(key).is_some_and(|at| rows[at].label != text);
|
||||
if changed && !text.is_empty() {
|
||||
events.push(PresetEvent::Rename { key: key.clone(), text: text.to_owned() });
|
||||
}
|
||||
}
|
||||
=======
|
||||
let _ = MemoView::new("presets", props, list_view::<K>).show(ui);
|
||||
let mut events = Vec::new();
|
||||
let mut menu_target = cx.keep::<BrowserMemory<K>>().menu_target.clone();
|
||||
@@ -928,7 +654,6 @@ impl<K: Clone + Eq + Hash + Send + Sync + MemoProps + 'static> PresetBrowser<'_,
|
||||
for event in &run.events {
|
||||
if let PresetEvent::Open(change) = event {
|
||||
local.apply_open(rows, change, default_open);
|
||||
>>>>>>> origin/next
|
||||
}
|
||||
}
|
||||
events.extend(run.events);
|
||||
@@ -1075,10 +800,14 @@ fn list_view<K: Clone + Eq + Hash + Send + Sync + MemoProps + 'static>(props: &m
|
||||
let grid = match tile_size {
|
||||
PresetTiles::Thumbnails => {
|
||||
let captions = if has_captions(rows) { CaptionPlace::Below } else { CaptionPlace::None };
|
||||
grid.caption(captions).thumb_size(ThumbSize::Large).zoom(zoom as f32)
|
||||
grid.caption(captions).thumb_size(ThumbSize::Large).zoom(GridZoom::Fixed(zoom))
|
||||
}
|
||||
// The zoom is a factor on the picture's width: a wide chip is the small thumbnail high.
|
||||
PresetTiles::Chips => grid.caption(CaptionPlace::None).thumb_size(ThumbSize::Small).zoom(aspect.max(1.0)).row_height(RowHeight::Text),
|
||||
PresetTiles::Chips => grid
|
||||
.caption(CaptionPlace::None)
|
||||
.thumb_size(ThumbSize::Small)
|
||||
.zoom(GridZoom::Fixed(f64::from(aspect.max(1.0))))
|
||||
.row_height(RowHeight::Text),
|
||||
};
|
||||
let mut grid = grid
|
||||
.groups(&plan.groups)
|
||||
|
||||
@@ -4,11 +4,7 @@ use craft_behavior::Axis;
|
||||
use craft_behavior::dock::{Action, Column, DockEdge, Floating, Group, Layout, Node, Permissions, SplitSize, Workspace, node_at};
|
||||
use craft_ui::contract::{Bind, BodyCx, PlainData, Role, Show as _, SizeLimits, Tracked};
|
||||
use craft_ui::display::Text;
|
||||
<<<<<<< HEAD
|
||||
use craft_ui::docking::{DockConfig, DockGrid, DockHeights, DockPanels, GroupSize, IconicMode, PanelSpec, group_heights};
|
||||
=======
|
||||
use craft_ui::docking::{DockConfig, DockGrid, DockHeights, DockPanels, DockSizes, GroupSize, PanelSpec, PanelSpecs, group_heights};
|
||||
>>>>>>> origin/next
|
||||
use craft_ui::docking::{DockConfig, DockGrid, DockHeights, DockPanels, DockSizes, GroupSize, IconicMode, PanelSpec, PanelSpecs, group_heights};
|
||||
use craft_ui::patterns::dock::DockArea;
|
||||
use craft_ui::testing::{Fixture, pointer, trial};
|
||||
use egui::{Pos2, Rect, Ui, Vec2};
|
||||
@@ -281,9 +277,10 @@ fn a_floating_stepped_windows_left_and_top_edge_drags_keep_the_opposite_edge() {
|
||||
}
|
||||
|
||||
/// Two side panels in one group, named and with a line of content each.
|
||||
#[derive(PlainData)]
|
||||
struct Sides;
|
||||
|
||||
impl DockPanels<u32> for Sides {
|
||||
impl PanelSpecs<u32> for Sides {
|
||||
fn spec(&self, panel: &u32) -> PanelSpec {
|
||||
PanelSpec::new(match panel {
|
||||
10 => "Alpha",
|
||||
@@ -291,7 +288,9 @@ impl DockPanels<u32> for Sides {
|
||||
_ => "Canvas",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl DockPanels<u32> for Sides {
|
||||
fn body(&mut self, panel: &u32, ui: &mut Ui, _: &mut BodyCx<'_>) {
|
||||
match panel {
|
||||
10 => Text::new("Alpha body").show(ui),
|
||||
@@ -301,13 +300,16 @@ impl DockPanels<u32> for Sides {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(PlainData)]
|
||||
struct RailWithFooter;
|
||||
|
||||
impl DockPanels<u32> for RailWithFooter {
|
||||
impl PanelSpecs<u32> for RailWithFooter {
|
||||
fn spec(&self, panel: &u32) -> PanelSpec {
|
||||
PanelSpec::new(format!("Panel {panel}"))
|
||||
}
|
||||
}
|
||||
|
||||
impl DockPanels<u32> for RailWithFooter {
|
||||
fn body(&mut self, _: &u32, _: &mut Ui, _: &mut BodyCx<'_>) {}
|
||||
|
||||
fn rail_footer(&mut self, _: &u32, ui: &mut Ui, _: &mut BodyCx<'_>) {
|
||||
@@ -327,18 +329,16 @@ fn rail_footer_stays_clear_of_icons_on_either_dock_side() {
|
||||
} else {
|
||||
Node::split(Axis::X, SplitSize::Ratio(0.6), Node::tabs(vec![1], 0), dock)
|
||||
};
|
||||
let workspace = Rc::new(RefCell::new(Workspace::new(Layout::new(Some(root), Vec::new()))));
|
||||
let held = Rc::clone(&workspace);
|
||||
let workspace = Rc::new(RefCell::new(Arc::new(Workspace::new(Layout::new(Some(root), Vec::new())))));
|
||||
let (held, specs) = (Rc::clone(&workspace), Tracked::new(RailWithFooter));
|
||||
let actions = Rc::new(RefCell::new(Vec::new()));
|
||||
let seen = Rc::clone(&actions);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut workspace = held.borrow().clone();
|
||||
let out =
|
||||
DockArea::new("Rail dock", Bind::given(workspace.clone()), &mut RailWithFooter, DockConfig::default().iconic_mode(IconicMode::Rail))
|
||||
.rail_footer(10)
|
||||
.show(ui);
|
||||
let mut workspace = Arc::clone(&held.borrow());
|
||||
let config = DockConfig::default().iconic_mode(IconicMode::Rail);
|
||||
let out = DockArea::new("Rail dock", Bind::given(Arc::clone(&workspace)), &specs, &mut RailWithFooter, config).rail_footer(10).show(ui);
|
||||
for action in out.actions {
|
||||
drop(workspace.apply(action.clone(), false, |_| Permissions::ALL));
|
||||
drop(Arc::make_mut(&mut workspace).apply(action.clone(), false, |_| Permissions::ALL));
|
||||
seen.borrow_mut().push(action);
|
||||
}
|
||||
*held.borrow_mut() = workspace;
|
||||
@@ -378,14 +378,14 @@ fn rail_footer_stays_clear_of_icons_on_either_dock_side() {
|
||||
fn rail_icons_stay_beside_the_expanded_column_and_the_open_panels_icon_collapses_it() {
|
||||
let side = Column::new(vec![Group::new(vec![10, 11], 0)]).with_iconic(true);
|
||||
let root = Node::split(Axis::X, SplitSize::Ratio(0.6), Node::tabs(vec![1], 0), Node::dock(DockEdge::End, vec![side]));
|
||||
let workspace = Rc::new(RefCell::new(Workspace::new(Layout::new(Some(root), Vec::new()))));
|
||||
let held = Rc::clone(&workspace);
|
||||
let workspace = Rc::new(RefCell::new(Arc::new(Workspace::new(Layout::new(Some(root), Vec::new())))));
|
||||
let (held, specs) = (Rc::clone(&workspace), Tracked::new(Sides));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut workspace = held.borrow().clone();
|
||||
let mut workspace = Arc::clone(&held.borrow());
|
||||
let config = DockConfig::default().iconic_mode(IconicMode::Rail);
|
||||
let out = DockArea::new("Rail dock", Bind::given(workspace.clone()), &mut Sides, config).show(ui);
|
||||
let out = DockArea::new("Rail dock", Bind::given(Arc::clone(&workspace)), &specs, &mut Sides, config).show(ui);
|
||||
for action in out.actions {
|
||||
drop(workspace.apply(action, false, |_: &u32| Permissions::ALL));
|
||||
drop(Arc::make_mut(&mut workspace).apply(action, false, |_: &u32| Permissions::ALL));
|
||||
}
|
||||
*held.borrow_mut() = workspace;
|
||||
});
|
||||
@@ -398,7 +398,7 @@ fn rail_icons_stay_beside_the_expanded_column_and_the_open_panels_icon_collapses
|
||||
.find(|button| craft_ui::testing::access::name(tree, button.node) == Some(name))
|
||||
.unwrap_or_else(|| panic!("the rail shows the {name} icon"))
|
||||
};
|
||||
let iconic = || end_columns(&workspace.borrow().layout)[0].iconic;
|
||||
let iconic = || end_columns(workspace.borrow().layout())[0].iconic;
|
||||
let shown = |fixture: &Fixture, text: &str| fixture.texts().iter().any(|run| run.text == text);
|
||||
|
||||
let beta = icon(&fixture, "Beta");
|
||||
@@ -418,13 +418,16 @@ fn rail_icons_stay_beside_the_expanded_column_and_the_open_panels_icon_collapses
|
||||
assert!(!shown(&fixture, "Alpha body"), "and its panel no longer shows");
|
||||
}
|
||||
|
||||
#[derive(PlainData)]
|
||||
struct RailWithMenu;
|
||||
|
||||
impl DockPanels<u32> for RailWithMenu {
|
||||
impl PanelSpecs<u32> for RailWithMenu {
|
||||
fn spec(&self, panel: &u32) -> PanelSpec {
|
||||
PanelSpec::new(format!("Panel {panel}"))
|
||||
}
|
||||
}
|
||||
|
||||
impl DockPanels<u32> for RailWithMenu {
|
||||
fn body(&mut self, _: &u32, _: &mut Ui, _: &mut BodyCx<'_>) {}
|
||||
|
||||
fn rail_footer(&mut self, _: &u32, ui: &mut Ui, _: &mut BodyCx<'_>) {
|
||||
@@ -443,11 +446,11 @@ impl DockPanels<u32> for RailWithMenu {
|
||||
fn a_menu_opens_from_the_rail_footer() {
|
||||
let side = Column::new(vec![Group::new(vec![10, 11], 0)]).with_iconic(true);
|
||||
let root = Node::split(Axis::X, SplitSize::Ratio(0.6), Node::tabs(vec![1], 0), Node::dock(DockEdge::End, vec![side]));
|
||||
let workspace = Workspace::new(Layout::new(Some(root), Vec::new()));
|
||||
let workspace = Arc::new(Workspace::new(Layout::new(Some(root), Vec::new())));
|
||||
let specs = Tracked::new(RailWithMenu);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
DockArea::new("Rail dock", Bind::given(workspace.clone()), &mut RailWithMenu, DockConfig::default().iconic_mode(IconicMode::Rail))
|
||||
.rail_footer(10)
|
||||
.show(ui);
|
||||
let config = DockConfig::default().iconic_mode(IconicMode::Rail);
|
||||
DockArea::new("Rail dock", Bind::given(Arc::clone(&workspace)), &specs, &mut RailWithMenu, config).rail_footer(10).show(ui);
|
||||
});
|
||||
fixture.room(Vec2::new(900.0, 500.0)).settle();
|
||||
let opener = fixture.by_label("Rail menu").expect("the rail menu button");
|
||||
|
||||
@@ -2,27 +2,17 @@
|
||||
//! tool rail the host takes has the dock's grip strip on top.
|
||||
|
||||
use craft_behavior::Axis;
|
||||
<<<<<<< HEAD
|
||||
use craft_behavior::dock::{Layout, Node, SplitSize, Workspace};
|
||||
use craft_ui::buttons::Button;
|
||||
use craft_ui::contract::{Bind, BodyCx, Scroll, Show as _, ShowContainer as _};
|
||||
use craft_ui::display::Text;
|
||||
use craft_ui::docking::{DockConfig, DockPanels, GroupAt, PanelSpec};
|
||||
use craft_ui::layout_components::Stack;
|
||||
use craft_ui::patterns::dock::DockArea;
|
||||
use craft_ui::testing::{Fixture, pointer, trial};
|
||||
use egui::{Rect, Ui, Vec2};
|
||||
use std::cell::Cell;
|
||||
=======
|
||||
use craft_behavior::dock::{Column, DockEdge, Group, Layout, Node, SplitSize, Workspace};
|
||||
use craft_ui::contract::{Bind, BodyCx, PlainData, Tracked};
|
||||
use craft_ui::buttons::Button;
|
||||
use craft_ui::contract::{Bind, BodyCx, PlainData, Scroll, Show as _, ShowContainer as _, Tracked};
|
||||
use craft_ui::display::Text;
|
||||
use craft_ui::docking::{DockConfig, DockGrid, DockPanels, DockSizes, DragUnit, GroupAt, GroupDrag, PanelSpec, PanelSpecs};
|
||||
use craft_ui::layout_components::Stack;
|
||||
use craft_ui::patterns::dock::DockArea;
|
||||
use craft_ui::runtime::drag;
|
||||
use craft_ui::testing::{Fixture, last_pass_runs, pointer, trial};
|
||||
use egui::{Rect, Shape, Ui, Vec2};
|
||||
use std::cell::{Cell, RefCell};
|
||||
>>>>>>> origin/next
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -75,49 +65,6 @@ fn a_group_view_lays_out_and_clips_to_its_group_rect() {
|
||||
assert!(rect.contains_rect(clip), "the view's clip {clip:?} lies in its group's rect {rect:?}");
|
||||
}
|
||||
|
||||
<<<<<<< HEAD
|
||||
/// A panel whose body lists more rows than its group shows, with a footer of one action.
|
||||
struct Listed;
|
||||
|
||||
impl DockPanels<usize> for Listed {
|
||||
fn spec(&self, _: &usize) -> PanelSpec {
|
||||
PanelSpec::new("Findings").footer()
|
||||
}
|
||||
|
||||
fn body(&mut self, _: &usize, ui: &mut Ui, _: &mut BodyCx<'_>) {
|
||||
Stack::new().fill().scroll(Scroll::vertical()).show(ui, |ui, _| {
|
||||
for row in 0..60 {
|
||||
Text::new(format!("Row {row}")).show(ui);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn footer(&mut self, _: &usize, ui: &mut Ui, _: &mut BodyCx<'_>) {
|
||||
Button::new("Apply all").show(ui);
|
||||
}
|
||||
}
|
||||
|
||||
/// A panel's footer is pinned under its body: it shows inside the group while the body is taller than the group, and
|
||||
/// stays where it is when the body scrolls.
|
||||
#[trial]
|
||||
fn a_panels_footer_stays_in_view_under_a_scrolling_body() {
|
||||
let workspace = Workspace::new(Layout::new(Some(Node::tabs(vec![1], 0)), Vec::new()));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
DockArea::new("Dock", Bind::given(workspace.clone()), &mut Listed, DockConfig::default()).show(ui);
|
||||
});
|
||||
let room = Vec2::new(400.0, 300.0);
|
||||
fixture.room(room).settle();
|
||||
let footer = fixture.by_label("Apply all").expect("the footer shows its action").rect;
|
||||
assert!(footer.bottom() <= room.y, "the footer lies inside the group: {footer:?}");
|
||||
let row = |fixture: &Fixture| fixture.by_label("Row 0").expect("the first row").rect;
|
||||
let before = row(&fixture);
|
||||
assert!(before.bottom() <= footer.top(), "the body lies above the footer: {before:?}, footer {footer:?}");
|
||||
|
||||
fixture.frame(vec![egui::Event::PointerMoved(before.center())]);
|
||||
fixture.frame(vec![pointer::wheel(-120.0)]).settle();
|
||||
assert!(row(&fixture).top() < before.top(), "the body scrolls: {before:?}, then {:?}", row(&fixture));
|
||||
assert_eq!(fixture.by_label("Apply all").map(|action| action.rect), Some(footer), "the footer stays where it was");
|
||||
=======
|
||||
/// The tool rail of the grip trial: a panel with a rail grid, which the host shows itself.
|
||||
const RAIL: usize = 7;
|
||||
/// The height the host's rail measures at.
|
||||
@@ -262,5 +209,51 @@ fn a_floating_tool_rails_grip_moves_its_window() {
|
||||
"the window moved by the pointer's travel {travel:?}, keeping the grabbed point under it: {before:?} -> {after:?}"
|
||||
);
|
||||
assert_eq!(layout.borrow().as_ref().map(|l| l.floating.len()), Some(1), "still one floating window");
|
||||
>>>>>>> origin/next
|
||||
}
|
||||
|
||||
/// A panel whose body lists more rows than its group shows, with a footer of one action.
|
||||
#[derive(PlainData)]
|
||||
struct Listed;
|
||||
|
||||
impl PanelSpecs<usize> for Listed {
|
||||
fn spec(&self, _: &usize) -> PanelSpec {
|
||||
PanelSpec::new("Findings").footer()
|
||||
}
|
||||
}
|
||||
|
||||
impl DockPanels<usize> for Listed {
|
||||
fn body(&mut self, _: &usize, ui: &mut Ui, _: &mut BodyCx<'_>) {
|
||||
Stack::new().fill().scroll(Scroll::vertical()).show(ui, |ui, _| {
|
||||
for row in 0..60 {
|
||||
Text::new(format!("Row {row}")).show(ui);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn footer(&mut self, _: &usize, ui: &mut Ui, _: &mut BodyCx<'_>) {
|
||||
Button::new("Apply all").show(ui);
|
||||
}
|
||||
}
|
||||
|
||||
/// A panel's footer is pinned under its body: it shows inside the group while the body is taller than the group, and
|
||||
/// stays where it is when the body scrolls.
|
||||
#[trial]
|
||||
fn a_panels_footer_stays_in_view_under_a_scrolling_body() {
|
||||
let mut workspace = Arc::new(Workspace::new(Layout::new(Some(Node::tabs(vec![1], 0)), Vec::new())));
|
||||
let specs = Tracked::new(Listed);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
DockArea::new("Dock", Bind::bound(&mut workspace), &specs, &mut Listed, DockConfig::default()).show(ui);
|
||||
});
|
||||
let room = Vec2::new(400.0, 300.0);
|
||||
fixture.room(room).settle();
|
||||
let footer = fixture.by_label("Apply all").expect("the footer shows its action").rect;
|
||||
assert!(footer.bottom() <= room.y, "the footer lies inside the group: {footer:?}");
|
||||
let row = |fixture: &Fixture| fixture.by_label("Row 0").expect("the first row").rect;
|
||||
let before = row(&fixture);
|
||||
assert!(before.bottom() <= footer.top(), "the body lies above the footer: {before:?}, footer {footer:?}");
|
||||
|
||||
fixture.frame(vec![egui::Event::PointerMoved(before.center())]);
|
||||
fixture.frame(vec![pointer::wheel(-120.0)]).settle();
|
||||
assert!(row(&fixture).top() < before.top(), "the body scrolls: {before:?}, then {:?}", row(&fixture));
|
||||
assert_eq!(fixture.by_label("Apply all").map(|action| action.rect), Some(footer), "the footer stays where it was");
|
||||
}
|
||||
@@ -3,15 +3,10 @@
|
||||
|
||||
use craft_ui::contract::{Bind, Role};
|
||||
use craft_ui::dialog::{DialogHost, StackDialog as _};
|
||||
<<<<<<< HEAD
|
||||
use craft_ui::patterns::form_dialogs::{AboutDialog, AboutInfo, AboutLink, AboutTab, Contributor, Credits, HostedAbout, ModelCredit};
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
=======
|
||||
use craft_ui::patterns::form_dialogs::{
|
||||
AboutAppTab, AboutDialog, AboutInfo, AboutLayout, AboutLink, AboutTab, Contributor, Credits, HostedAbout, ModelCredit,
|
||||
};
|
||||
use craft_ui::testing::{Fixture, access, trial};
|
||||
>>>>>>> origin/next
|
||||
use egui::Vec2;
|
||||
use serde_json::json;
|
||||
use std::cell::RefCell;
|
||||
@@ -64,47 +59,6 @@ fn a_click_on_a_name_in_the_grab_bag_reports_its_profile() {
|
||||
assert!(!fixture.by_role(Role::TABLE).is_empty(), "Table shows the contributors as a table");
|
||||
}
|
||||
|
||||
<<<<<<< HEAD
|
||||
/// The names of the grab bag, in the order it shows them.
|
||||
fn grab_bag(fixture: &Fixture) -> Vec<String> {
|
||||
fixture.by_role(Role::LINK).iter().filter_map(|link| fixture.tree().name_of(link.node).map(str::to_owned)).collect()
|
||||
}
|
||||
|
||||
/// Picks `entry` from the Sort list.
|
||||
fn sort_by(fixture: &mut Fixture, entry: &str) {
|
||||
let sort = fixture.by_label("Sort").expect("the Sort list");
|
||||
fixture.click(&sort).idle(4);
|
||||
let pick = fixture.by_label(entry).unwrap_or_else(|| panic!("the Sort list offers {entry}"));
|
||||
fixture.click(&pick).idle(10);
|
||||
}
|
||||
|
||||
// The name order ignores the `@` of a username and the case, so display names and usernames interleave; someone
|
||||
// with no commit date sorts after everyone with one, by first and by last commit. A slip reorders the credits.
|
||||
#[trial]
|
||||
fn contributors_sort_by_name_without_at_or_case_and_undated_last() {
|
||||
let credits = Credits::new(
|
||||
vec![
|
||||
Contributor::new("carl").counts(0, 9).active("2025-01-01T10:00:00Z", "2026-01-01T10:00:00Z"),
|
||||
Contributor::new("zed").display_name("Bea").counts(1, 0),
|
||||
Contributor::new("alice").counts(0, 3).active("2025-03-01T10:00:00Z", "2025-04-01T10:00:00Z"),
|
||||
],
|
||||
Vec::new(),
|
||||
12,
|
||||
);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let _ = AboutDialog::new(&INFO, &credits).tab(Bind::given(AboutTab::Contributors)).show(ui);
|
||||
});
|
||||
fixture.room(Vec2::new(1400.0, 1000.0)).idle(30);
|
||||
assert_eq!(grab_bag(&fixture), ["@carl", "@alice", "@zed"], "oldest first commit first, the undated last");
|
||||
|
||||
sort_by(&mut fixture, "Last commit");
|
||||
assert_eq!(grab_bag(&fixture), ["@alice", "@carl", "@zed"], "oldest last commit first, the undated last");
|
||||
|
||||
let display = fixture.by_label("Display name").expect("Show offers Display name");
|
||||
fixture.click(&display).idle(10);
|
||||
sort_by(&mut fixture, "Name (A\u{2013}Z)");
|
||||
assert_eq!(grab_bag(&fixture), ["@alice", "Bea", "@carl"], "names compare without the `@` and the case");
|
||||
=======
|
||||
// The listed layout stands the name, version, blurb, links and built-with line in one column from the start edge,
|
||||
// the links in the community-then-links order, one to a line; a link click reports its URL and the button is Close.
|
||||
#[trial]
|
||||
@@ -220,7 +174,47 @@ fn the_listed_about_shows_tab_faces() {
|
||||
let (listed, centred) = (inset(AboutLayout::Listed), inset(AboutLayout::Centred));
|
||||
assert!(centred.abs() < 1.0, "a centred tab is its text: {centred}");
|
||||
assert!(listed > 3.0, "a listed tab is a face with its title set in: {listed}");
|
||||
>>>>>>> origin/next
|
||||
}
|
||||
|
||||
/// The names of the grab bag, in the order it shows them.
|
||||
fn grab_bag(fixture: &Fixture) -> Vec<String> {
|
||||
fixture.by_role(Role::LINK).iter().filter_map(|link| fixture.tree().name_of(link.node).map(str::to_owned)).collect()
|
||||
}
|
||||
|
||||
/// Picks `entry` from the Sort list.
|
||||
fn sort_by(fixture: &mut Fixture, entry: &str) {
|
||||
let sort = fixture.by_label("Sort").expect("the Sort list");
|
||||
fixture.click(&sort).idle(4);
|
||||
let pick = fixture.by_label(entry).unwrap_or_else(|| panic!("the Sort list offers {entry}"));
|
||||
fixture.click(&pick).idle(10);
|
||||
}
|
||||
|
||||
// The name order ignores the `@` of a username and the case, so display names and usernames interleave; someone
|
||||
// with no commit date sorts after everyone with one, by first and by last commit. A slip reorders the credits.
|
||||
#[trial]
|
||||
fn contributors_sort_by_name_without_at_or_case_and_undated_last() {
|
||||
let credits = Credits::new(
|
||||
vec![
|
||||
Contributor::new("carl").counts(0, 9).active("2025-01-01T10:00:00Z", "2026-01-01T10:00:00Z"),
|
||||
Contributor::new("zed").display_name("Bea").counts(1, 0),
|
||||
Contributor::new("alice").counts(0, 3).active("2025-03-01T10:00:00Z", "2025-04-01T10:00:00Z"),
|
||||
],
|
||||
Vec::new(),
|
||||
12,
|
||||
);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let _ = AboutDialog::new(&INFO, &credits).tab(Bind::given(AboutTab::Contributors)).show(ui);
|
||||
});
|
||||
fixture.room(Vec2::new(1400.0, 1000.0)).idle(30);
|
||||
assert_eq!(grab_bag(&fixture), ["@carl", "@alice", "@zed"], "oldest first commit first, the undated last");
|
||||
|
||||
sort_by(&mut fixture, "Last commit");
|
||||
assert_eq!(grab_bag(&fixture), ["@alice", "@carl", "@zed"], "oldest last commit first, the undated last");
|
||||
|
||||
let display = fixture.by_label("Display name").expect("Show offers Display name");
|
||||
fixture.click(&display).idle(10);
|
||||
sort_by(&mut fixture, "Name (A\u{2013}Z)");
|
||||
assert_eq!(grab_bag(&fixture), ["@alice", "Bea", "@carl"], "names compare without the `@` and the case");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
|
||||
@@ -4,22 +4,14 @@
|
||||
//! request slots and the rows an edit changed, disabled options and the remembered values a row refuses.
|
||||
|
||||
use craft_ui::buttons::Button;
|
||||
<<<<<<< HEAD
|
||||
use craft_ui::contract::{Bind, Outcome as _, Role, SaveKey, Show as _, clicked};
|
||||
use craft_ui::dialog::{DialogHost, DialogResult, HeldOk, dialog_id};
|
||||
use craft_ui::patterns::form_dialogs::{
|
||||
DialogFields, FieldValue, HostedParamDialog, PagerStep, PanePager, Param, ParamDialog, ParamKind, ParamLayout, ParamResult, PreviewState,
|
||||
};
|
||||
use craft_ui::patterns::presets::PresetRow;
|
||||
=======
|
||||
use craft_ui::choice::Checkbox;
|
||||
use craft_ui::contract::{Bind, Outcome as _, Props as _, Role, SaveKey, Show as _, clicked};
|
||||
use craft_ui::dialog::{DialogHost, DialogResult, HeldAnswer, HeldOk, dialog_id};
|
||||
use craft_ui::patterns::form_dialogs::{
|
||||
DialogFields, FieldValue, FormButtons, FormDialog, HostedParamDialog, Param, ParamDialog, ParamKind, ParamLayout, ParamResult,
|
||||
DialogFields, FieldValue, FormButtons, FormDialog, HostedParamDialog, PagerStep, PanePager, Param, ParamDialog, ParamKind, ParamLayout,
|
||||
ParamResult, PreviewState,
|
||||
};
|
||||
use craft_ui::patterns::presets::{PresetFns, PresetRow, PresetSource};
|
||||
>>>>>>> origin/next
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::runtime::overlay::CloseReason;
|
||||
use craft_ui::sections::{DialogRole, FooterButton};
|
||||
|
||||
@@ -1,32 +1,18 @@
|
||||
//! The form dialogs' own logic: the parameter model, its spec-string parser, the value store, the size model,
|
||||
//! guide layout and the export file name.
|
||||
|
||||
<<<<<<< HEAD
|
||||
mod about;
|
||||
mod dialog;
|
||||
mod document_layout;
|
||||
mod export;
|
||||
mod files;
|
||||
mod hosted;
|
||||
mod long_value;
|
||||
mod new_document;
|
||||
mod param_tabs;
|
||||
mod params;
|
||||
mod password;
|
||||
mod preview;
|
||||
mod preview_width;
|
||||
mod save_for_web;
|
||||
mod size_model;
|
||||
=======
|
||||
pub(crate) mod about;
|
||||
pub(crate) mod dialog;
|
||||
pub(crate) mod document_layout;
|
||||
pub(crate) mod export;
|
||||
pub(crate) mod files;
|
||||
pub(crate) mod hosted;
|
||||
pub(crate) mod image_unit_order;
|
||||
pub(crate) mod list_manager;
|
||||
pub(crate) mod long_value;
|
||||
pub(crate) mod new_document;
|
||||
pub(crate) mod new_document_orientation;
|
||||
pub(crate) mod param_tabs;
|
||||
pub(crate) mod params;
|
||||
pub(crate) mod password;
|
||||
pub(crate) mod picker;
|
||||
@@ -34,4 +20,3 @@ pub(crate) mod preview;
|
||||
pub(crate) mod preview_width;
|
||||
pub(crate) mod save_for_web;
|
||||
pub(crate) mod size_model;
|
||||
>>>>>>> origin/next
|
||||
@@ -316,41 +316,6 @@ fn a_blend_row_steps_and_picks_by_its_keys_inside_the_dialog() {
|
||||
assert_eq!(held().as_deref(), Some("multiply"), "Down on the closed list skips the greyed mode");
|
||||
}
|
||||
|
||||
<<<<<<< HEAD
|
||||
/// The y of each thin horizontal line in `shapes`.
|
||||
|
||||
/// `separated_at(index)` draws the framework's list separator before that option of a choice row's open list and
|
||||
/// between no other two: a separator placed by the wrong index, or one drawn on every option, would split the standard
|
||||
/// paper sizes from the wrong neighbour.
|
||||
#[trial]
|
||||
fn a_choice_row_draws_its_separator_before_the_named_option() {
|
||||
let sizes: Vec<(String, Label)> = [("letter", "Letter"), ("legal", "Legal"), ("a4", "A4"), ("custom", "Custom")]
|
||||
.into_iter()
|
||||
.map(|(id, label)| (id.to_owned(), label.into()))
|
||||
.collect();
|
||||
let params = vec![Param::new("paper", "Paper Size", ParamKind::choice(sizes, Some("letter".to_owned()))).separated_at(3)];
|
||||
let values = Rc::new(RefCell::new(DialogFields::new()));
|
||||
let shown = values.clone();
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let _ = ParamRows::new("Page Setup", ¶ms, Bind::bound(&mut *shown.borrow_mut())).show(ui);
|
||||
});
|
||||
fixture.room(Vec2::new(1200.0, 800.0));
|
||||
fixture.settle();
|
||||
let field = fixture.by_role(Role::COMBO_BOX).first().copied().expect("the choice field shows");
|
||||
fixture.click(&field);
|
||||
fixture.idle(3);
|
||||
|
||||
let line_of = |fixture: &Fixture, text: &str| {
|
||||
let run = fixture.texts().iter().rev().find(|run| run.text == text).unwrap_or_else(|| panic!("the list shows {text}"));
|
||||
run.rect
|
||||
};
|
||||
let (letter, legal, a4, custom) = (line_of(&fixture, "Letter"), line_of(&fixture, "Legal"), line_of(&fixture, "A4"), line_of(&fixture, "Custom"));
|
||||
// The separator is a row of its own in the open list: the step from A4 to Custom is wider than the step between two
|
||||
// options with none between them, and those two steps are equal.
|
||||
let plain = legal.top() - letter.top();
|
||||
assert!((a4.top() - legal.top() - plain).abs() < 0.5, "no separator between Legal and A4: {letter:?} {legal:?} {a4:?}");
|
||||
assert!(custom.top() - a4.top() > plain + 1.0, "a separator between A4 and Custom: A4 {a4:?}, Custom {custom:?}, plain step {plain}");
|
||||
=======
|
||||
#[trial]
|
||||
fn paired_parameter_fields_15539_keep_their_controls_and_values() {
|
||||
let values = Rc::new(RefCell::new(DialogFields::new()));
|
||||
@@ -412,7 +377,39 @@ fn paired_parameter_fields_15539_leave_no_gap_when_both_are_hidden() {
|
||||
assert!(hidden.by_label("Mode").is_none() && hidden.by_label("Opacity").is_none());
|
||||
let absent = rows(vec![before, after], &Rc::new(RefCell::new(DialogFields::new())));
|
||||
assert_eq!(gap(&hidden), gap(&absent), "a hidden pair uses no space");
|
||||
>>>>>>> origin/next
|
||||
}
|
||||
|
||||
/// `separated_at(index)` draws the framework's list separator before that option of a choice row's open list and
|
||||
/// between no other two: a separator placed by the wrong index, or one drawn on every option, would split the standard
|
||||
/// paper sizes from the wrong neighbour.
|
||||
#[trial]
|
||||
fn a_choice_row_draws_its_separator_before_the_named_option() {
|
||||
let sizes: Vec<(String, Label)> = [("letter", "Letter"), ("legal", "Legal"), ("a4", "A4"), ("custom", "Custom")]
|
||||
.into_iter()
|
||||
.map(|(id, label)| (id.to_owned(), label.into()))
|
||||
.collect();
|
||||
let params = vec![Param::new("paper", "Paper Size", ParamKind::choice(sizes, Some("letter".to_owned()))).separated_at(3)];
|
||||
let values = Rc::new(RefCell::new(DialogFields::new()));
|
||||
let shown = values.clone();
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let _ = ParamRows::new("Page Setup", ¶ms, Bind::bound(&mut *shown.borrow_mut())).show(ui);
|
||||
});
|
||||
fixture.room(Vec2::new(1200.0, 800.0));
|
||||
fixture.settle();
|
||||
let field = fixture.by_role(Role::COMBO_BOX).first().copied().expect("the choice field shows");
|
||||
fixture.click(&field);
|
||||
fixture.idle(3);
|
||||
|
||||
let line_of = |fixture: &Fixture, text: &str| {
|
||||
let run = fixture.texts().iter().rev().find(|run| run.text == text).unwrap_or_else(|| panic!("the list shows {text}"));
|
||||
run.rect
|
||||
};
|
||||
let (letter, legal, a4, custom) = (line_of(&fixture, "Letter"), line_of(&fixture, "Legal"), line_of(&fixture, "A4"), line_of(&fixture, "Custom"));
|
||||
// The separator is a row of its own in the open list: the step from A4 to Custom is wider than the step between two
|
||||
// options with none between them, and those two steps are equal.
|
||||
let plain = legal.top() - letter.top();
|
||||
assert!((a4.top() - legal.top() - plain).abs() < 0.5, "no separator between Legal and A4: {letter:?} {legal:?} {a4:?}");
|
||||
assert!(custom.top() - a4.top() > plain + 1.0, "a separator between A4 and Custom: A4 {a4:?}, Custom {custom:?}, plain step {plain}");
|
||||
}
|
||||
|
||||
/// A pattern row shows the first pattern for a stored id the rows lack without writing it, a pick writes the pattern's
|
||||
@@ -517,26 +514,6 @@ fn an_optional_number_is_held_to_its_bounds_and_remembered_while_off() {
|
||||
assert_eq!(values.borrow().number("quality"), Some(7.0), "the box on again brings back the value typed before");
|
||||
}
|
||||
|
||||
<<<<<<< HEAD
|
||||
/// A row marked `beside_previous` stands on the line of the row before it, where an unmarked one stands below.
|
||||
#[trial]
|
||||
fn a_row_beside_the_previous_one_shares_its_line() {
|
||||
let top = |beside: bool| {
|
||||
let second = Param::number("second", "Second", 1.0, 1.0, 0);
|
||||
let params = vec![Param::number("first", "First", 1.0, 1.0, 0), if beside { second.beside_previous() } else { second }];
|
||||
let values = Rc::new(RefCell::new(DialogFields::new()));
|
||||
let shown = values.clone();
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let _ = ParamRows::new("Form", ¶ms, Bind::bound(&mut *shown.borrow_mut())).labels(LabelScheme::Inline).show(ui);
|
||||
});
|
||||
fixture.settle();
|
||||
let at = |name: &str| fixture.texts().iter().find(|text| text.text.contains(name)).map(|text| text.rect.center().y);
|
||||
at("First").zip(at("Second")).map(|(first, second)| second - first)
|
||||
};
|
||||
let (stacked, beside) = (top(false), top(true));
|
||||
assert!(stacked.is_some_and(|gap| gap > 10.0), "unmarked rows stack: {stacked:?}");
|
||||
assert!(beside.is_some_and(|gap| gap.abs() < 3.0), "a beside row shares the line: {beside:?}");
|
||||
=======
|
||||
// A text row with `max_chars` stops typing at its limit, and the host's `set` refuses longer text; the limit counts
|
||||
// characters, not bytes.
|
||||
#[trial]
|
||||
@@ -632,5 +609,24 @@ fn parameter_dialogs_15539_show_declared_units_and_keep_parsing() {
|
||||
assert_eq!(held.int("copies"), Some(1));
|
||||
}
|
||||
}
|
||||
>>>>>>> origin/next
|
||||
}
|
||||
|
||||
/// A row marked `beside_previous` stands on the line of the row before it, where an unmarked one stands below.
|
||||
#[trial]
|
||||
fn a_row_beside_the_previous_one_shares_its_line() {
|
||||
let top = |beside: bool| {
|
||||
let second = Param::number("second", "Second", 1.0, 1.0, 0);
|
||||
let params = vec![Param::number("first", "First", 1.0, 1.0, 0), if beside { second.beside_previous() } else { second }];
|
||||
let values = Rc::new(RefCell::new(DialogFields::new()));
|
||||
let shown = values.clone();
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let _ = ParamRows::new("Form", ¶ms, Bind::bound(&mut *shown.borrow_mut())).labels(LabelScheme::Inline).show(ui);
|
||||
});
|
||||
fixture.settle();
|
||||
let at = |name: &str| fixture.texts().iter().find(|text| text.text.contains(name)).map(|text| text.rect.center().y);
|
||||
at("First").zip(at("Second")).map(|(first, second)| second - first)
|
||||
};
|
||||
let (stacked, beside) = (top(false), top(true));
|
||||
assert!(stacked.is_some_and(|gap| gap > 10.0), "unmarked rows stack: {stacked:?}");
|
||||
assert!(beside.is_some_and(|gap| gap.abs() < 3.0), "a beside row shares the line: {beside:?}");
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use craft_ui::contract::Bind;
|
||||
use craft_ui::patterns::preferences::{
|
||||
PageSpec, PrefValue, PreferencesMode, PreferencesModel, PreferencesState, PreferencesWindow, RowKind, RowSpec,
|
||||
PageSpec, PrefValue, PreferencesDraft, PreferencesMode, PreferencesModel, PreferencesState, PreferencesWindow, RowKind, RowSpec,
|
||||
};
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::Ui;
|
||||
@@ -31,6 +31,12 @@ impl PreferencesModel for Model {
|
||||
fn custom_page(&mut self, _: &mut Ui, _: &str) -> bool {
|
||||
false
|
||||
}
|
||||
fn reset_page(&mut self, _: &str) {
|
||||
self.draft = false;
|
||||
}
|
||||
}
|
||||
|
||||
impl PreferencesDraft for Model {
|
||||
fn differs(&self) -> bool {
|
||||
self.draft != self.saved
|
||||
}
|
||||
@@ -42,9 +48,6 @@ impl PreferencesModel for Model {
|
||||
fn cancel(&mut self) {
|
||||
self.draft = self.saved;
|
||||
}
|
||||
fn reset_page(&mut self, _: &str) {
|
||||
self.draft = false;
|
||||
}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
@@ -89,6 +92,10 @@ impl PreferencesModel for CustomModel {
|
||||
fn custom_page(&mut self, _: &mut Ui, _: &str) -> bool {
|
||||
false
|
||||
}
|
||||
fn reset_page(&mut self, _: &str) {}
|
||||
}
|
||||
|
||||
impl PreferencesDraft for CustomModel {
|
||||
fn differs(&self) -> bool {
|
||||
self.draft != self.saved
|
||||
}
|
||||
@@ -100,7 +107,6 @@ impl PreferencesModel for CustomModel {
|
||||
Ok(())
|
||||
}
|
||||
fn cancel(&mut self) {}
|
||||
fn reset_page(&mut self, _: &str) {}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
|
||||
@@ -1,13 +1,7 @@
|
||||
//! The data and rules of the preferences family: the search over the row model and the settings document, the
|
||||
//! window's answers and the hex codec.
|
||||
|
||||
<<<<<<< HEAD
|
||||
mod live;
|
||||
mod model;
|
||||
mod path_setting;
|
||||
mod page;
|
||||
=======
|
||||
pub(crate) mod live;
|
||||
pub(crate) mod model;
|
||||
pub(crate) mod page;
|
||||
pub(crate) mod path_setting;
|
||||
>>>>>>> origin/next
|
||||
@@ -1,86 +1,14 @@
|
||||
<<<<<<< HEAD
|
||||
//! Preferences is one scrolling page of cards: every page is shown at once, short choices are segmented and the
|
||||
//! search counts its matches.
|
||||
|
||||
use craft_ui::contract::{Bind, Entry};
|
||||
use craft_ui::patterns::preferences::{PageSpec, PrefValue, PreferencesModel, PreferencesState, PreferencesWindow, RowKind, RowSpec};
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::Ui;
|
||||
|
||||
struct Model {
|
||||
side: String,
|
||||
}
|
||||
|
||||
impl PreferencesModel for Model {
|
||||
fn pages(&self) -> Vec<PageSpec<'_>> {
|
||||
let sides = vec![Entry::new("left", "Left"), Entry::new("right", "Right")];
|
||||
vec![
|
||||
PageSpec::new("general", "General", vec![RowSpec::new("side", "Tools side", RowKind::choice(&self.side, sides))]),
|
||||
PageSpec::new("canvas", "Canvas", vec![RowSpec::new("snap", "Snap", RowKind::Bool(true))]),
|
||||
]
|
||||
}
|
||||
fn set(&mut self, _: &str, value: PrefValue) {
|
||||
if let PrefValue::Choice(side) = value {
|
||||
self.side = side;
|
||||
}
|
||||
}
|
||||
fn custom_row(&mut self, _: &mut Ui, _: &str) -> bool {
|
||||
false
|
||||
}
|
||||
fn custom_page(&mut self, _: &mut Ui, _: &str) -> bool {
|
||||
false
|
||||
}
|
||||
fn differs(&self) -> bool {
|
||||
false
|
||||
}
|
||||
fn apply(&mut self) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
fn cancel(&mut self) {}
|
||||
fn reset_page(&mut self, _: &str) {}
|
||||
}
|
||||
|
||||
fn fixture() -> Fixture {
|
||||
let mut model = Model { side: "left".into() };
|
||||
let mut state = PreferencesState::default();
|
||||
Fixture::new(move |ui| {
|
||||
let _ = PreferencesWindow::new(Bind::bound(&mut state)).embedded().show(ui, &mut model);
|
||||
})
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn every_page_is_a_card_on_one_scrolling_page() {
|
||||
let mut fixture = fixture();
|
||||
fixture.room(egui::vec2(700.0, 900.0)).settle();
|
||||
assert!(fixture.by_label("General").is_some() && fixture.by_label("Canvas").is_some(), "both cards show at once");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_short_choice_is_a_row_of_segments() {
|
||||
let mut fixture = fixture();
|
||||
fixture.room(egui::vec2(700.0, 900.0)).settle();
|
||||
let right = fixture.by_label("Right").expect("a segment for each option");
|
||||
fixture.click(&right).settle();
|
||||
assert!(fixture.texts().iter().any(|t| t.text == "Left"), "the other option stays shown beside it");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn the_search_shows_how_many_settings_match() {
|
||||
let mut fixture = fixture();
|
||||
fixture.room(egui::vec2(700.0, 900.0)).settle();
|
||||
assert!(!fixture.texts().iter().any(|t| t.text.contains("match")), "no count without a search");
|
||||
let search = fixture.by_label("Search settings").expect("the search field");
|
||||
fixture.click(&search).type_text("snap").settle();
|
||||
assert!(fixture.texts().iter().any(|t| t.text == "1 match"), "{:?}", fixture.texts().iter().map(|t| &t.text).collect::<Vec<_>>());
|
||||
=======
|
||||
//! `PreferencesPage` over a model with no draft: each edit reaches the model in the pass it lands in.
|
||||
//! `PreferencesPage` over a model with no draft: each edit reaches the model in the pass it lands in. With
|
||||
//! [`PreferencesLayout::Cards`] the page is one scrolling column of cards: every page is shown at once, short choices
|
||||
//! are segmented and the search counts its matches.
|
||||
|
||||
use craft_ui::buttons::Button;
|
||||
use craft_ui::contract::{Bind, Role, Show as _, ShowContainer as _};
|
||||
use craft_ui::contract::{Bind, Entry, Role, Show as _, ShowContainer as _};
|
||||
use craft_ui::display::Text;
|
||||
use craft_ui::form::Field;
|
||||
use craft_ui::patterns::preferences::{
|
||||
GroupSpec, PageSpec, PrefValue, PreferencesModel, PreferencesPage, PreferencesState, PreferencesWords, RowKind, RowSpec,
|
||||
GroupSpec, PageSpec, PrefValue, PreferencesDraft, PreferencesLayout, PreferencesModel, PreferencesPage, PreferencesState, PreferencesWindow,
|
||||
PreferencesWords, RowKind, RowSpec,
|
||||
};
|
||||
use craft_ui::runtime::env::Env;
|
||||
use craft_ui::runtime::words::CommonWords;
|
||||
@@ -111,9 +39,13 @@ impl PreferencesModel for Live {
|
||||
self.sets.push((key.to_owned(), value, self.pass));
|
||||
}
|
||||
|
||||
fn custom_row(&mut self, _: &mut Ui, _: &str) {}
|
||||
fn custom_row(&mut self, _: &mut Ui, _: &str) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn custom_page(&mut self, _: &mut Ui, _: &str) {}
|
||||
fn custom_page(&mut self, _: &mut Ui, _: &str) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn reset_page(&mut self, _: &str) {}
|
||||
}
|
||||
@@ -180,13 +112,16 @@ impl PreferencesModel for Grouped {
|
||||
|
||||
fn set(&mut self, _: &str, _: PrefValue) {}
|
||||
|
||||
fn custom_row(&mut self, ui: &mut Ui, _: &str) {
|
||||
fn custom_row(&mut self, ui: &mut Ui, _: &str) -> bool {
|
||||
let _ = Field::new("Hosted").show(ui, |ui, _| {
|
||||
Text::new("hosted value").show(ui);
|
||||
});
|
||||
false
|
||||
}
|
||||
|
||||
fn custom_page(&mut self, _: &mut Ui, _: &str) {}
|
||||
fn custom_page(&mut self, _: &mut Ui, _: &str) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn reset_page(&mut self, _: &str) {}
|
||||
}
|
||||
@@ -229,11 +164,14 @@ impl PreferencesModel for HelpedRows {
|
||||
|
||||
fn set(&mut self, _: &str, _: PrefValue) {}
|
||||
|
||||
fn custom_row(&mut self, ui: &mut Ui, _: &str) {
|
||||
fn custom_row(&mut self, ui: &mut Ui, _: &str) -> bool {
|
||||
Button::new("Hosted button").show(ui);
|
||||
false
|
||||
}
|
||||
|
||||
fn custom_page(&mut self, _: &mut Ui, _: &str) {}
|
||||
fn custom_page(&mut self, _: &mut Ui, _: &str) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn reset_page(&mut self, _: &str) {}
|
||||
}
|
||||
@@ -250,5 +188,75 @@ fn a_host_labelled_row_shows_its_rules_help_and_follows_its_enabled_state() {
|
||||
let help = fixture.texts().iter().find(|run| run.text == "Drawn with its note").map(|run| run.rect).expect("the help shows");
|
||||
assert!(help.top() >= button.rect.bottom(), "the help {help:?} sits under the host's rows {:?}", button.rect);
|
||||
assert!(fixture.tree().is_disabled_key(button.node), "the disabled rule disables the host's button");
|
||||
>>>>>>> origin/next
|
||||
}
|
||||
|
||||
struct Model {
|
||||
side: String,
|
||||
}
|
||||
|
||||
impl PreferencesModel for Model {
|
||||
fn pages(&self) -> Vec<PageSpec<'_>> {
|
||||
let sides = vec![Entry::new("left", "Left"), Entry::new("right", "Right")];
|
||||
vec![
|
||||
PageSpec::new("general", "General", vec![RowSpec::new("side", "Tools side", RowKind::choice(&self.side, sides))]),
|
||||
PageSpec::new("canvas", "Canvas", vec![RowSpec::new("snap", "Snap", RowKind::Bool(true))]),
|
||||
]
|
||||
}
|
||||
fn set(&mut self, _: &str, value: PrefValue) {
|
||||
if let PrefValue::Choice(side) = value {
|
||||
self.side = side;
|
||||
}
|
||||
}
|
||||
fn custom_row(&mut self, _: &mut Ui, _: &str) -> bool {
|
||||
false
|
||||
}
|
||||
fn custom_page(&mut self, _: &mut Ui, _: &str) -> bool {
|
||||
false
|
||||
}
|
||||
fn reset_page(&mut self, _: &str) {}
|
||||
}
|
||||
|
||||
impl PreferencesDraft for Model {
|
||||
fn differs(&self) -> bool {
|
||||
false
|
||||
}
|
||||
fn apply(&mut self) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
fn cancel(&mut self) {}
|
||||
}
|
||||
|
||||
/// A window of cards ([`PreferencesLayout::Cards`]) over two pages.
|
||||
fn fixture() -> Fixture {
|
||||
let mut model = Model { side: "left".into() };
|
||||
let mut state = PreferencesState::default();
|
||||
Fixture::new(move |ui| {
|
||||
let _ = PreferencesWindow::new(Bind::bound(&mut state)).layout(PreferencesLayout::Cards).embedded().show(ui, &mut model);
|
||||
})
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn every_page_is_a_card_on_one_scrolling_page() {
|
||||
let mut fixture = fixture();
|
||||
fixture.room(egui::vec2(700.0, 900.0)).settle();
|
||||
assert!(fixture.by_label("General").is_some() && fixture.by_label("Canvas").is_some(), "both cards show at once");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_short_choice_is_a_row_of_segments() {
|
||||
let mut fixture = fixture();
|
||||
fixture.room(egui::vec2(700.0, 900.0)).settle();
|
||||
let right = fixture.by_label("Right").expect("a segment for each option");
|
||||
fixture.click(&right).settle();
|
||||
assert!(fixture.texts().iter().any(|t| t.text == "Left"), "the other option stays shown beside it");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn the_search_shows_how_many_settings_match() {
|
||||
let mut fixture = fixture();
|
||||
fixture.room(egui::vec2(700.0, 900.0)).settle();
|
||||
assert!(!fixture.texts().iter().any(|t| t.text.contains("match")), "no count without a search");
|
||||
let search = fixture.by_label("Search settings").expect("the search field");
|
||||
fixture.click(&search).type_text("snap").settle();
|
||||
assert!(fixture.texts().iter().any(|t| t.text == "1 match"), "{:?}", fixture.texts().iter().map(|t| &t.text).collect::<Vec<_>>());
|
||||
}
|
||||
Reference in new issue
Block a user