mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-24 19:41:51 +01:00
chrome-w6: net change of 1 commits
- chrome-w6: written from its sheet
This commit is contained in:
1 parent
4ed94f62c0
commit
11b865d3ea
9 files changed
+405
-61
No files matched your search
@@ -93,8 +93,36 @@ impl<P: Clone + Eq + Hash> Workspace<P> {
|
||||
/// and the revision stays. `MissingPanel` when `from` is in none of them, `DuplicatePanel` when `to` is
|
||||
/// already there.
|
||||
pub fn rename(&mut self, from: &P, to: P) -> Result<(), DockError> {
|
||||
let _ = (from, to);
|
||||
todo!("ch.K27")
|
||||
if !self.holds(from) {
|
||||
return Err(DockError::MissingPanel);
|
||||
}
|
||||
if self.holds(&to) {
|
||||
return Err(DockError::DuplicatePanel);
|
||||
}
|
||||
let swap = |panel: &mut P| {
|
||||
if *panel == *from {
|
||||
*panel = to.clone();
|
||||
}
|
||||
};
|
||||
let mut proposed = self.clone();
|
||||
if let Some(root) = proposed.layout.root.as_mut() {
|
||||
rename_in_tree(root, &swap);
|
||||
}
|
||||
for window in &mut proposed.layout.floating {
|
||||
rename_in_column(&mut window.column, &swap);
|
||||
}
|
||||
for (panel, location) in proposed.hidden.iter_mut().chain(&mut proposed.floated) {
|
||||
swap(panel);
|
||||
rename_in_location(location, &swap);
|
||||
}
|
||||
proposed.validate()?;
|
||||
*self = proposed;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether `panel` is in the layout or is the key of a hidden or floated record.
|
||||
fn holds(&self, panel: &P) -> bool {
|
||||
self.layout.contains(panel) || self.hidden.iter().chain(&self.floated).any(|(held, _)| held == panel)
|
||||
}
|
||||
|
||||
/// Check the version, the layout, that every hidden panel is hidden once and absent
|
||||
@@ -439,6 +467,37 @@ fn dock_columns_mut<P>(root: &mut Node<P>) -> Vec<&mut Column<P>> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Applies `swap` to every panel of `root`, walking the tree with a stack: a loaded tree can be deeper than the call
|
||||
/// stack.
|
||||
fn rename_in_tree<P>(root: &mut Node<P>, swap: &impl Fn(&mut P)) {
|
||||
let mut visit = vec![root];
|
||||
while let Some(node) = visit.pop() {
|
||||
match node {
|
||||
Node::Split { first, second, .. } => {
|
||||
visit.push(second);
|
||||
visit.push(first);
|
||||
}
|
||||
Node::Tabs { panels, .. } => panels.iter_mut().for_each(swap),
|
||||
Node::Stack { entries } => entries.iter_mut().for_each(|entry| swap(&mut entry.panel)),
|
||||
Node::Dock { columns, .. } => columns.iter_mut().for_each(|column| rename_in_column(column, swap)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies `swap` to every panel of the groups of `column`.
|
||||
fn rename_in_column<P>(column: &mut Column<P>, swap: &impl Fn(&mut P)) {
|
||||
column.groups.iter_mut().for_each(|group| group.panels.iter_mut().for_each(swap));
|
||||
}
|
||||
|
||||
/// Applies `swap` to the panels a location names: its anchor, its siblings and the tab it goes before.
|
||||
fn rename_in_location<P>(location: &mut Location<P>, swap: &impl Fn(&mut P)) {
|
||||
location.anchor.iter_mut().for_each(swap);
|
||||
location.sibling.iter_mut().for_each(swap);
|
||||
if let DockPlacement::Tab { before: Some(panel) } = &mut location.placement {
|
||||
swap(panel);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `panel` is in a floating window of `layout`.
|
||||
fn floats<P: Clone + Eq + Hash>(layout: &Layout<P>, panel: &P) -> bool {
|
||||
matches!(layout.place(panel), Some(PanelPlace::Floating { .. }))
|
||||
|
||||
@@ -400,6 +400,58 @@ fn a_panel_that_docks_only_in_columns_never_lands_in_a_frame() {
|
||||
assert_eq!(sorted(&saved.layout), [1, 2, 3, 4, 6]);
|
||||
}
|
||||
|
||||
/// A location whose anchor, sibling and tab-before name `anchor`.
|
||||
fn recorded(layout: &Layout<u32>, anchor: u32) -> craft_behavior::dock::Location<u32> {
|
||||
let mut location = layout.location(&5).unwrap();
|
||||
location.anchor = Some(anchor);
|
||||
location.sibling = vec![anchor];
|
||||
location.placement = DockPlacement::tab(Some(anchor));
|
||||
location
|
||||
}
|
||||
|
||||
/// Every place of `workspace` that holds the panel `id`: the layout, the keys of the records and their locations.
|
||||
fn mentions(workspace: &Workspace<u32>, id: u32) -> bool {
|
||||
let records = workspace.hidden.iter().chain(&workspace.floated);
|
||||
let named = records.clone().any(|(panel, location)| {
|
||||
let before = matches!(&location.placement, DockPlacement::Tab { before: Some(p) } if *p == id);
|
||||
*panel == id || location.anchor == Some(id) || location.sibling.contains(&id) || before
|
||||
});
|
||||
named || workspace.layout.contains(&id)
|
||||
}
|
||||
|
||||
/// A rename keeps the panel's place wherever the id sits (tab group, dock column, floating window, records and the
|
||||
/// anchors of other records), refuses a missing source and a taken name, and leaves the workspace as it was then.
|
||||
#[test]
|
||||
fn a_renamed_panel_keeps_its_place_and_a_taken_name_changes_nothing() {
|
||||
for from in [11, 3, 7, 50, 51] {
|
||||
let layout = docked();
|
||||
let mut base = Workspace::default();
|
||||
base.replace(Workspace::new(layout.clone()));
|
||||
base.hidden = vec![(50, recorded(&layout, from)), (52, recorded(&layout, 5))];
|
||||
base.floated = vec![(51, recorded(&layout, from))];
|
||||
base.validate().unwrap();
|
||||
let swap = |panel: u32| if panel == from { 99 } else { panel };
|
||||
|
||||
let mut renamed = base.clone();
|
||||
renamed.rename(&from, 99).unwrap_or_else(|e| panic!("{from}: {e:?}"));
|
||||
let panels = |workspace: &Workspace<u32>| workspace.layout.panels().into_iter().copied().collect::<Vec<_>>();
|
||||
assert_eq!(panels(&renamed), panels(&base).into_iter().map(swap).collect::<Vec<_>>(), "{from}: the panel keeps its position");
|
||||
let keys = |records: &[(u32, _)]| records.iter().map(|(panel, _)| *panel).collect::<Vec<_>>();
|
||||
assert_eq!(keys(&renamed.hidden), keys(&base.hidden).into_iter().map(swap).collect::<Vec<_>>(), "{from}: hidden keys");
|
||||
assert_eq!(keys(&renamed.floated), keys(&base.floated).into_iter().map(swap).collect::<Vec<_>>(), "{from}: floated keys");
|
||||
assert!(!mentions(&renamed, from) && mentions(&renamed, 99), "{from}: no field holds the old id");
|
||||
renamed.validate().unwrap();
|
||||
assert_eq!(renamed.revision(), base.revision(), "{from}: a rename is an edit");
|
||||
|
||||
for (source, name, error) in [(40, 99, DockError::MissingPanel), (from, 4, DockError::DuplicatePanel), (from, 52, DockError::DuplicatePanel)] {
|
||||
let mut refused = base.clone();
|
||||
assert_eq!(refused.rename(&source, name), Err(error), "{from}: {source} to {name}");
|
||||
assert_eq!(refused, base, "{from}: a refused rename changes nothing");
|
||||
assert_eq!(refused.revision(), base.revision());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A stepped column (a toolbar's) keeps its step count docked, floating and through JSON, and its width moves only
|
||||
/// by steps.
|
||||
#[test]
|
||||
|
||||
@@ -6,13 +6,13 @@ use super::words::RailWords;
|
||||
use crate::buttons::{Button, IconButton};
|
||||
use crate::contract::overlay::{Anchor, Dismiss, Overlay, Place};
|
||||
use crate::contract::{
|
||||
ActivateOn, Bind, CollectionEvent, Gap, ListDrag, NoValue, Outcome, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _,
|
||||
Sizing, clicked,
|
||||
ActivateOn, Bind, CollectionEvent, Gap, ListDrag, NoValue, Outcome, PopupKind, Props as _, SelectMode, Show as _, ShowCollection as _,
|
||||
ShowContainer as _, Sizing, Trigger, clicked,
|
||||
};
|
||||
use crate::display::{Shade, Text};
|
||||
use crate::display::{Shade, TargetMark, Text};
|
||||
use crate::layout_components::{Row, Stack};
|
||||
use crate::list::{List, ListRow, RowInk};
|
||||
use crate::menu::PanelRow;
|
||||
use crate::list::{List, ListRow, RowInk, RowRun};
|
||||
use crate::menu::{Menu, PanelMenu, PanelRow};
|
||||
use crate::popover::Popover;
|
||||
use crate::primitives::IconSpec;
|
||||
use crate::runtime::commands::{self, ResolvedCommand};
|
||||
@@ -49,8 +49,8 @@ impl<T> DrawerGroup<T> {
|
||||
/// A group headed `label` that lists the tools of `slots` one after another; each row carries its slot's run by
|
||||
/// position.
|
||||
pub fn slotted(label: impl Into<Label>, slots: Vec<Vec<RailTool<T>>>) -> Self {
|
||||
let _ = (label, slots);
|
||||
todo!("ch.K23")
|
||||
let lengths = slots.iter().map(Vec::len).collect();
|
||||
DrawerGroup { label: label.into(), tools: slots.into_iter().flatten().collect(), slots: lengths }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -135,6 +135,8 @@ impl<T: Value> Outcome for ToolbarDrawerOutput<T> {
|
||||
/// - **Closing.** Escape, the close button or a press outside the drawer and the rail closes it: `closed` is set and
|
||||
/// the host stops showing it. A press on the rail is the start of a drag or a pick there, so it leaves the drawer open.
|
||||
/// The focus then returns to the drawer's [opener](ToolbarDrawer::opened_by), the rail's Edit Toolbar button.
|
||||
/// - **Menu and footer.** With [`menu`](ToolbarDrawer::menu) rows the header holds a menu button, and
|
||||
/// [`show_with`](ToolbarDrawer::show_with) draws the host's content in the footer above Restore Defaults.
|
||||
#[must_use = "show the drawer with `show`"]
|
||||
#[derive(crate::contract::Pattern, crate::contract::Props)]
|
||||
#[pattern(probe(ToolbarDrawer<'static, u8>))]
|
||||
@@ -146,13 +148,11 @@ pub struct ToolbarDrawer<'a, T: Value + 'static> {
|
||||
#[prop]
|
||||
opens: Side,
|
||||
/// The tool whose row wears the target mark.
|
||||
#[prop]
|
||||
#[allow(dead_code)] // P3(chrome-w6): dp.T3
|
||||
mark: Option<&'a T>,
|
||||
/// A request of the pass: scrolls the tool's row into the list's view.
|
||||
#[prop]
|
||||
#[allow(dead_code)] // P3(chrome-w6): dp.T3
|
||||
reveal: Option<&'a T>,
|
||||
/// The rows of the menu the header's menu button opens; no button without rows.
|
||||
menu: Vec<PanelRow>,
|
||||
dropped: Option<ToolDropped>,
|
||||
opener: Option<Response>,
|
||||
}
|
||||
@@ -161,7 +161,7 @@ impl<'a, T: Value + 'static> ToolbarDrawer<'a, T> {
|
||||
/// A drawer beside `rail` (the rail's rect), listing `groups`, over a toolbar of `toolbar` slots. `dropped` is the
|
||||
/// drag the rail took in this pass (`ToolRailOutput::dropped`); the drawer turns it into an edit.
|
||||
pub fn new(rail: Rect, groups: &'a [DrawerGroup<T>], toolbar: &'a [ToolSlot<T>], dropped: Option<ToolDropped>) -> Self {
|
||||
ToolbarDrawer { rail, groups, toolbar, opens: Side::End, mark: None, reveal: None, dropped, opener: None }
|
||||
ToolbarDrawer { rail, groups, toolbar, opens: Side::End, mark: None, reveal: None, menu: Vec::new(), dropped, opener: None }
|
||||
}
|
||||
|
||||
/// The control that opened the drawer, the rail's Edit Toolbar button (`ToolRailOutput::edit_toolbar`): the focus
|
||||
@@ -170,6 +170,18 @@ impl<'a, T: Value + 'static> ToolbarDrawer<'a, T> {
|
||||
self.opener = Some(opener.clone());
|
||||
self
|
||||
}
|
||||
|
||||
/// The tool whose row wears the target mark; `None` marks none.
|
||||
pub fn mark(mut self, tool: Option<&'a T>) -> Self {
|
||||
self.mark = tool;
|
||||
self
|
||||
}
|
||||
|
||||
/// A request: scrolls the row of `tool` into the list's view. Send it in the pass that needs it, not every pass.
|
||||
pub fn reveal(mut self, tool: Option<&'a T>) -> Self {
|
||||
self.reveal = tool;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// A row of the drawer's list.
|
||||
@@ -226,6 +238,24 @@ impl DisplayOrder<DrawerKey> for Rows<'_> {
|
||||
|
||||
impl ItemSource<DrawerKey> for Rows<'_> {}
|
||||
|
||||
/// The place of the row at `tool` in the runs `slots` count: `None` without slots or past the last run.
|
||||
fn run_of(slots: &[usize], tool: usize) -> Option<RowRun> {
|
||||
let mut start = 0;
|
||||
for length in slots {
|
||||
let end = start + length;
|
||||
if tool < end {
|
||||
return Some(match (tool == start, tool + 1 == end) {
|
||||
(true, true) => RowRun::Alone,
|
||||
(true, false) => RowRun::First,
|
||||
(false, true) => RowRun::Last,
|
||||
(false, false) => RowRun::Middle,
|
||||
});
|
||||
}
|
||||
start = end;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Whether the toolbar holds the tool `id`.
|
||||
fn on_toolbar<T: PartialEq>(toolbar: &[ToolSlot<T>], id: &T) -> bool {
|
||||
toolbar.iter().any(|slot| slot.tools.iter().any(|tool| tool.id == *id))
|
||||
@@ -234,20 +264,19 @@ fn on_toolbar<T: PartialEq>(toolbar: &[ToolSlot<T>], id: &T) -> bool {
|
||||
impl<T: Value + 'static> ToolbarDrawer<'_, T> {
|
||||
/// With rows, an icon button after the title opens a menu of `rows`.
|
||||
#[must_use]
|
||||
pub fn menu(self, rows: Vec<PanelRow>) -> Self {
|
||||
let _ = rows;
|
||||
todo!("ch.K21")
|
||||
}
|
||||
|
||||
/// [`show`](ToolbarDrawer::show) with `below` drawn in the footer above Restore Defaults.
|
||||
pub fn show_with(self, ui: &mut Ui, below: impl FnMut(&mut Ui)) -> ToolbarDrawerOutput<T> {
|
||||
let _ = (ui, below);
|
||||
todo!("ch.K22")
|
||||
pub fn menu(mut self, rows: Vec<PanelRow>) -> Self {
|
||||
self.menu = rows;
|
||||
self
|
||||
}
|
||||
|
||||
/// Shows the drawer and reports what the user changed.
|
||||
pub fn show(self, ui: &mut Ui) -> ToolbarDrawerOutput<T> {
|
||||
let ToolbarDrawer { rail, groups, toolbar, opens, dropped, opener, .. } = self;
|
||||
self.show_with(ui, |_| {})
|
||||
}
|
||||
|
||||
/// [`show`](ToolbarDrawer::show) with `below` drawn in the footer above Restore Defaults.
|
||||
pub fn show_with(self, ui: &mut Ui, mut below: impl FnMut(&mut Ui)) -> ToolbarDrawerOutput<T> {
|
||||
let ToolbarDrawer { rail, groups, toolbar, opens, mark, reveal, menu, dropped, opener } = self;
|
||||
let env = Env::of(ui);
|
||||
let words = env.words::<RailWords>();
|
||||
let os = os_of(ui.ctx());
|
||||
@@ -261,6 +290,9 @@ impl<T: Value + 'static> ToolbarDrawer<'_, T> {
|
||||
let mut restore = false;
|
||||
let layout = env.view().keyboard_layout();
|
||||
let chord_of = |command: &ResolvedCommand| command.chord.as_ref().map(|chord| chord.display_for(os, layout));
|
||||
let key_of = |id: &T| {
|
||||
groups.iter().enumerate().find_map(|(group, held)| held.tools.iter().position(|tool| tool.id == *id).map(|tool| DrawerKey::Tool { group, tool }))
|
||||
};
|
||||
|
||||
let mut popover = Popover::new(words.drawer_title.clone(), Bind::bound(&mut open));
|
||||
if let Some(opener) = &opener {
|
||||
@@ -286,14 +318,23 @@ impl<T: Value + 'static> ToolbarDrawer<'_, T> {
|
||||
.header(|ui, _| {
|
||||
Row::new().show(ui, |ui, _| {
|
||||
Text::new(words.drawer_title.clone()).role(TypeRole::Title).show(ui);
|
||||
if !menu.is_empty() {
|
||||
let more = IconButton::new(IconId::new("menu")).label(words.drawer_menu.clone()).popup(PopupKind::Menu).show(ui);
|
||||
let _ = Menu::new(words.drawer_menu.clone()).opened_by(&more, Trigger::Click).show(ui, |ui, _| {
|
||||
PanelMenu::new(menu.clone(), Vec::new()).show(ui);
|
||||
});
|
||||
}
|
||||
let close = IconButton::new(IconId::new("close")).label(words.drawer_close.clone()).show(ui);
|
||||
leave |= clicked(&close);
|
||||
});
|
||||
Text::new(words.drawer_hint.clone()).role(TypeRole::Caption).shade(Shade::Faint).show(ui);
|
||||
})
|
||||
.footer(|ui, _| restore |= clicked(&Button::new(words.drawer_restore.clone()).show(ui)))
|
||||
.footer(|ui, _| {
|
||||
below(ui);
|
||||
restore |= clicked(&Button::new(words.drawer_restore.clone()).show(ui));
|
||||
})
|
||||
.show(ui, |ui, _| {
|
||||
let list = List::<DrawerKey>::new(words.drawer_tools.clone())
|
||||
let mut list = List::<DrawerKey>::new(words.drawer_tools.clone())
|
||||
.id(ui.scope_id().with("drawer-tools"))
|
||||
.select(SelectMode::None)
|
||||
.activate(ActivateOn::Click)
|
||||
@@ -306,11 +347,17 @@ impl<T: Value + 'static> ToolbarDrawer<'_, T> {
|
||||
DrawerKey::Group(_) => None,
|
||||
})
|
||||
.sizing(Sizing::Content);
|
||||
if let Some(key) = reveal.and_then(key_of) {
|
||||
list = list.reveal(key);
|
||||
}
|
||||
let out = list.show_items(ui, &rows, &mut |key, _| match *key {
|
||||
DrawerKey::Group(group) => ListRow::new(groups[group].label.clone()).section_heading(),
|
||||
DrawerKey::Tool { group, tool } => {
|
||||
let command = &resolved[group][tool];
|
||||
let mut row = ListRow::new(command.label.to_string());
|
||||
if let Some(run) = run_of(&groups[group].slots, tool) {
|
||||
row = row.run(run);
|
||||
}
|
||||
if let Some(icon) = &command.icon {
|
||||
row = row.icon(IconSpec::svg(IconId::from(icon.clone())));
|
||||
}
|
||||
@@ -323,6 +370,11 @@ impl<T: Value + 'static> ToolbarDrawer<'_, T> {
|
||||
}
|
||||
}
|
||||
});
|
||||
if let Some(key) = mark.and_then(key_of)
|
||||
&& let Some(row) = out.shown.iter().find(|row| row.key == key)
|
||||
{
|
||||
TargetMark::new(row.rect).show_mark(ui);
|
||||
}
|
||||
let tool_of = |key: &DrawerKey| match *key {
|
||||
DrawerKey::Tool { group, tool } => groups[group].tools.get(tool),
|
||||
DrawerKey::Group(_) => None,
|
||||
|
||||
@@ -1,30 +1,87 @@
|
||||
//! Stories of `ToolbarDrawer`.
|
||||
|
||||
use super::{DrawerGroup, ToolbarDrawer};
|
||||
use crate::rails::tool::stories::{BRUSH, tools};
|
||||
use crate::contract::Show as _;
|
||||
use crate::display::Text;
|
||||
use crate::menu::PanelRow;
|
||||
use crate::rails::tool::stories::{BRUSH, StoryTools, tools};
|
||||
use crate::rails::tool::{LastUsed, ToolRail, ToolSlot};
|
||||
use crate::runtime::commands::CommandRef;
|
||||
use crate::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use egui::Ui;
|
||||
|
||||
/// The drawer closed beside the tool rail until the rail's Edit Toolbar button opens it, `tune`d by the story. `tune`
|
||||
/// also learns whether this pass opened the drawer, for a request that is sent once.
|
||||
fn staged<'a>(
|
||||
ui: &mut Ui,
|
||||
data: &mut StoryData,
|
||||
groups: &'a [DrawerGroup<u8>],
|
||||
slots: &'a [ToolSlot<u8>],
|
||||
tune: impl FnOnce(ToolbarDrawer<'a, u8>, bool) -> ToolbarDrawer<'a, u8>,
|
||||
below: impl FnMut(&mut Ui),
|
||||
) -> StoryOutput {
|
||||
let last = LastUsed::default();
|
||||
let rail = ToolRail::new("Tools", slots, &BRUSH, &last).edit_toolbar("Edit Toolbar").show_rail(ui, |_, _| {});
|
||||
let open = data.value("open", false);
|
||||
let Some(opener) = rail.edit_toolbar.as_ref() else { return rail.into() };
|
||||
let mut fresh = false;
|
||||
if crate::contract::clicked(opener) {
|
||||
*open = !*open;
|
||||
fresh = *open;
|
||||
}
|
||||
if !*open {
|
||||
return rail.into();
|
||||
}
|
||||
let drawer = tune(ToolbarDrawer::new(rail.response.rect, groups, slots, rail.dropped), fresh).opened_by(opener).show_with(ui, below);
|
||||
if drawer.closed {
|
||||
*open = false;
|
||||
}
|
||||
drawer.into()
|
||||
}
|
||||
|
||||
/// The slots of the toolbar the stories start from.
|
||||
fn toolbar() -> [ToolSlot<u8>; 2] {
|
||||
[ToolSlot::new(0, tools(&[0])), ToolSlot::new(1, tools(&[BRUSH, BRUSH + 1]))]
|
||||
}
|
||||
|
||||
/// The drawer as an app shows it: closed beside the tool rail until the rail's Edit Toolbar button opens it. The eraser
|
||||
/// and the clone stamp are off the toolbar, so the drawer has tools to drag onto it.
|
||||
#[story(ToolbarDrawer<'static, u8>, covers = [], drive = Drive::Never)]
|
||||
fn toolbar_drawer(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let groups = [DrawerGroup::new("Drawing", tools(&[0, 1, 2])), DrawerGroup::new("Retouching", tools(&[3, 4]))];
|
||||
let slots = [ToolSlot::new(0, tools(&[0])), ToolSlot::new(1, tools(&[BRUSH, BRUSH + 1]))];
|
||||
let last = LastUsed::default();
|
||||
let rail = ToolRail::new("Tools", &slots, &BRUSH, &last).edit_toolbar("Edit Toolbar").show_rail(ui, |_, _| {});
|
||||
let open = data.value("open", false);
|
||||
let Some(opener) = rail.edit_toolbar.as_ref() else { return rail.into() };
|
||||
if crate::contract::clicked(opener) {
|
||||
*open = !*open;
|
||||
}
|
||||
if !*open {
|
||||
return rail.into();
|
||||
}
|
||||
let drawer = ToolbarDrawer::new(rail.response.rect, &groups, &slots, rail.dropped).opened_by(opener).show(ui);
|
||||
if drawer.closed {
|
||||
*open = false;
|
||||
}
|
||||
drawer.into()
|
||||
staged(ui, data, &groups, &toolbar(), |drawer, _| drawer, |_| {})
|
||||
}
|
||||
|
||||
/// The drawer with a header menu, content in the footer above Restore Defaults, and the first group's tools in runs of
|
||||
/// 2, 1 and 3 rows.
|
||||
#[story(ToolbarDrawer<'static, u8>, covers = [], drive = Drive::Never)]
|
||||
fn toolbar_drawer_menu_footer_and_runs(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let groups = [
|
||||
DrawerGroup::slotted("Drawing", vec![tools(&[0, 1]), tools(&[2]), tools(&[3, 4, 5])]),
|
||||
DrawerGroup::new("Retouching", tools(&[6, 7])),
|
||||
DrawerGroup::new("Other", tools(&[8])),
|
||||
];
|
||||
let rows = vec![
|
||||
PanelRow::Command(CommandRef::from(StoryTools::Move)),
|
||||
PanelRow::Separator,
|
||||
PanelRow::Command(CommandRef::from(StoryTools::Brush)),
|
||||
];
|
||||
staged(
|
||||
ui,
|
||||
data,
|
||||
&groups,
|
||||
&toolbar(),
|
||||
|drawer, _| drawer.menu(rows),
|
||||
|ui| {
|
||||
Text::new("Below").show(ui);
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// The drawer with the row of a tool of the last group marked and scrolled into view as it opens.
|
||||
#[story(ToolbarDrawer<'static, u8>, covers = [], drive = Drive::Never)]
|
||||
fn toolbar_drawer_marked_tool(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let marked = 4_u8;
|
||||
let groups = [DrawerGroup::new("Drawing", tools(&[0, 1, 2])), DrawerGroup::new("Retouching", tools(&[3, 4]))];
|
||||
staged(ui, data, &groups, &toolbar(), |drawer, fresh| drawer.mark(Some(&marked)).reveal(fresh.then_some(&marked)), |_| {})
|
||||
}
|
||||
@@ -154,3 +154,38 @@ fn the_drawer_opens_on_the_side_it_is_given() {
|
||||
assert!(away, "{opens:?}: the drawer row {row:?} lies on that side of the rail {rail:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// With two groups of tools the list holds heading rows between the tools, so a tool's key is not its flat index: a
|
||||
/// revealed tool far down the list scrolls into the drawer's room, and only a marked tool wears the mark.
|
||||
#[trial]
|
||||
fn a_revealed_tool_scrolls_into_view_and_wears_the_mark() {
|
||||
use craft_ui::display::TargetMark;
|
||||
use craft_ui::rails::{DrawerGroup, ToolbarDrawer};
|
||||
use egui::{Pos2, Rect};
|
||||
use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
const ROOM: Vec2 = Vec2::new(480.0, 240.0);
|
||||
let shown = |marked: bool| {
|
||||
let pending = Rc::new(Cell::new(true));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let ids = |from: u8, to: u8| (from..to).map(tool).collect::<Vec<_>>();
|
||||
let mut second = ids(30, 49);
|
||||
second.push(tool(CUT));
|
||||
let groups = [DrawerGroup::new("First", ids(10, 30)), DrawerGroup::new("Second", second)];
|
||||
let toolbar = [slot(0, &[UNDO])];
|
||||
let rail = Rect::from_min_size(Pos2::ZERO, Vec2::new(48.0, ROOM.y));
|
||||
let target = CUT;
|
||||
let reveal = pending.replace(false).then_some(&target);
|
||||
ToolbarDrawer::new(rail, &groups, &toolbar, None).reveal(reveal).mark(marked.then_some(&target)).show(ui);
|
||||
});
|
||||
fixture.room(ROOM).idle(60);
|
||||
let row = fixture.by_label("Cut").expect("the revealed tool's row is shown").rect;
|
||||
(row, !fixture.styles_of(std::any::type_name::<TargetMark>()).is_empty())
|
||||
};
|
||||
let room = Rect::from_min_size(Pos2::ZERO, ROOM);
|
||||
let (row, marked) = shown(true);
|
||||
assert!(room.contains_rect(row), "the revealed row {row:?} lies inside the room {room:?}");
|
||||
assert!(marked, "the marked tool wears the mark");
|
||||
let (_, unmarked) = shown(false);
|
||||
assert!(!unmarked, "without a mark no ring is drawn");
|
||||
}
|
||||
@@ -217,7 +217,8 @@ impl<'a, P: Clone + Eq + Hash> DeleteWorkspaceDialog<'a, P> {
|
||||
}
|
||||
|
||||
/// A [`NewWorkspaceDialog`] the [`DialogHost`](crate::dialog::DialogHost) owns, over a copy of the workspace set. It
|
||||
/// answers with the [`NewWorkspace`] at OK.
|
||||
/// answers with the [`NewWorkspace`] at OK. It opens with its [`value`](HostedNewWorkspace::value): an empty name with
|
||||
/// every box off unless the app gives one.
|
||||
pub struct HostedNewWorkspace<P> {
|
||||
id: DialogId,
|
||||
set: WorkspaceSet<P>,
|
||||
@@ -256,9 +257,9 @@ impl<P: Clone> HostedNewWorkspace<P> {
|
||||
|
||||
/// The name and captures the dialog opens with; without it, `NewWorkspace::default()`.
|
||||
#[must_use]
|
||||
pub fn value(self, value: NewWorkspace) -> Self {
|
||||
let _ = (self, value);
|
||||
todo!("ch.K26")
|
||||
pub fn value(mut self, value: NewWorkspace) -> Self {
|
||||
self.value = value;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ use crate::runtime::words::CommonWords;
|
||||
use crate::sections::{DialogRole, FooterButton};
|
||||
use crate::style::TypeRole;
|
||||
use crate::text::TextField;
|
||||
use craft_behavior::{DisplayOrder, ItemSource, Selection};
|
||||
use craft_behavior::{DisplayOrder, EditEvent, ItemSource, Mixed, Selection};
|
||||
use craft_i18n::Folder;
|
||||
use egui::{Response, Ui};
|
||||
use std::borrow::Cow;
|
||||
@@ -187,13 +187,12 @@ pub struct ListManagerChoice {
|
||||
}
|
||||
|
||||
impl ListManagerChoice {
|
||||
/// The action id of an in-place rename ([`ListManager::renames`]).
|
||||
/// The action id of an in-place rename ([`ListManager::renames`]). An app's own action must not use this id.
|
||||
pub const RENAME: &'static str = "rename";
|
||||
|
||||
/// Whether the choice is an in-place rename.
|
||||
pub fn is_rename(&self) -> bool {
|
||||
let _ = self;
|
||||
todo!("ch.K25")
|
||||
self.action == Self::RENAME
|
||||
}
|
||||
}
|
||||
|
||||
@@ -320,6 +319,8 @@ fn is_enabled(action: &ListManagerAction, entries: &[ListManagerEntry], folder:
|
||||
/// it is enabled, Delete in the list runs the `delete` action, Escape cancels.
|
||||
/// - Actions are the buttons in a column beside the list: the first action, Cancel, then the other actions in the
|
||||
/// given order. The app replaces `entries` between passes; the name box keeps its text.
|
||||
/// - Rename: with `renames`, F2 on an entry of that kind edits its name in the row. A commit reports a choice whose
|
||||
/// action is [`ListManagerChoice::RENAME`] and leaves the dialog open; Escape reports nothing.
|
||||
#[must_use = "show the dialog with `show`"]
|
||||
#[derive(crate::contract::Pattern, crate::contract::Props)]
|
||||
pub struct ListManager<'a> {
|
||||
@@ -342,6 +343,10 @@ pub struct ListManager<'a> {
|
||||
/// Binds the open state to `open`.
|
||||
#[prop(name = "opened")]
|
||||
open: Option<Bind<'a, bool>>,
|
||||
/// Entries of this kind rename in place: a commit reports a [`ListManagerChoice`] with the `RENAME` action, the
|
||||
/// entry's id and the trimmed name, and the dialog stays open.
|
||||
#[prop]
|
||||
renames: Option<u32>,
|
||||
}
|
||||
|
||||
impl<'a> ListManager<'a> {
|
||||
@@ -362,20 +367,13 @@ impl<'a> ListManager<'a> {
|
||||
searchable: false,
|
||||
name: None,
|
||||
open: None,
|
||||
renames: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Entries of `kind` rename in place: a commit reports a [`ListManagerChoice`] with the `RENAME` action, the
|
||||
/// entry's id and the trimmed name, and the dialog stays open.
|
||||
#[must_use]
|
||||
pub fn renames(self, kind: u32) -> Self {
|
||||
let _ = (self, kind);
|
||||
todo!("ch.K25")
|
||||
}
|
||||
|
||||
/// Shows the dialog.
|
||||
pub fn show(self, ui: &mut Ui) -> ListManagerOutput {
|
||||
let ListManager { title, name_label, entries, actions, empty, note, searchable, name, open } = self;
|
||||
let ListManager { title, name_label, entries, actions, empty, note, searchable, name, open, renames } = self;
|
||||
let env = Env::of(ui);
|
||||
let words = env.words::<ListManagerWords>();
|
||||
let common = env.words::<CommonWords>();
|
||||
@@ -416,6 +414,7 @@ impl<'a> ListManager<'a> {
|
||||
let folder = env.folder();
|
||||
let activated = Cell::new(None::<usize>);
|
||||
let typed = RefCell::new(String::new());
|
||||
let renamed = RefCell::new(None::<(usize, String)>);
|
||||
let shown = dialog.show(ui, |ui, cx| {
|
||||
let mut session = cx.memory::<Session>().clone();
|
||||
if cx.appeared()
|
||||
@@ -458,6 +457,9 @@ impl<'a> ListManager<'a> {
|
||||
if searchable {
|
||||
list = list.filter(&session.name, |at| Label::from(entries[*at].name.clone()));
|
||||
}
|
||||
if let Some(kind) = renames {
|
||||
list = list.rename(true).can_rename(move |at| entries[*at].kind == kind);
|
||||
}
|
||||
let events = list
|
||||
.show_items(ui, &source, &mut |at, _| {
|
||||
let entry = &entries[*at];
|
||||
@@ -488,6 +490,13 @@ impl<'a> ListManager<'a> {
|
||||
let delete = actions.iter().position(|action| action.id == DELETE);
|
||||
activated.set(delete.filter(|at| is_enabled(&actions[*at], entries, &folder, &session.name)));
|
||||
}
|
||||
CollectionEvent::Rename(EditEvent::Commit { after: Mixed::Same(rename), .. }) => {
|
||||
let name = rename.name.trim();
|
||||
if !name.is_empty() {
|
||||
session.name = name.to_owned();
|
||||
*renamed.borrow_mut() = Some((rename.key, session.name.clone()));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -509,6 +518,9 @@ impl<'a> ListManager<'a> {
|
||||
let entry = entries.iter().find(|entry| is_named(entry, &folder, &typed) && accepts(&actions[at], entry));
|
||||
ListManagerChoice { action: actions[at].id.clone(), entry: entry.map(|entry| entry.id.clone()), name: typed.trim().to_owned() }
|
||||
});
|
||||
ListManagerOutput { response, closed, choice }
|
||||
let rename = renamed.take().and_then(|(at, name)| {
|
||||
entries.get(at).map(|entry| ListManagerChoice { action: ListManagerChoice::RENAME.to_owned(), entry: Some(entry.id.clone()), name })
|
||||
});
|
||||
ListManagerOutput { response, closed, choice: choice.or(rename) }
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,15 @@ fn list_manager(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
.into()
|
||||
}
|
||||
|
||||
/// Entries of kind 1 rename in place: F2 on a row edits its name there.
|
||||
#[story(ListManager<'static>, covers = [], drive = Drive::Never)]
|
||||
fn list_manager_renames(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let words = Env::of(ui).words::<ListManagerWords>();
|
||||
let actions = vec![ListManagerAction::run(&words), ListManagerAction::delete(&words)];
|
||||
let entries: Vec<ListManagerEntry> = entries().into_iter().enumerate().map(|(at, entry)| if at == 1 { entry } else { entry.kind(1) }).collect();
|
||||
ListManager::new("Macros", "Macro name:", entries, actions).renames(1).opened(Bind::bound(data.value("open", true))).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(ListManager<'static>, covers = [], drive = Drive::Never)]
|
||||
fn list_manager_empty(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let words = Env::of(ui).words::<ListManagerWords>();
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
//! `ListManager`'s in-place rename: a commit is a choice, Escape and an entry of another kind are not.
|
||||
|
||||
use craft_ui::contract::Bind;
|
||||
use craft_ui::patterns::form_dialogs::{ActionEnabled, ListManager, ListManagerAction, ListManagerChoice, ListManagerEntry};
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::{Key, Modifiers, Vec2};
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
|
||||
#[trial]
|
||||
fn a_committed_rename_reports_entry_and_name_and_escape_keeps_it() {
|
||||
let rows = Rc::new(RefCell::new(vec![
|
||||
ListManagerEntry::new("a", "Alpha").kind(1),
|
||||
ListManagerEntry::new("b", "Bravo"),
|
||||
ListManagerEntry::new("c", "Gamma").kind(1),
|
||||
]));
|
||||
let choices = Rc::new(RefCell::new(Vec::<ListManagerChoice>::new()));
|
||||
let closed = Rc::new(Cell::new(false));
|
||||
let (held, seen, ended) = (Rc::clone(&rows), Rc::clone(&choices), Rc::clone(&closed));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let entries = held.borrow().clone();
|
||||
let actions = vec![ListManagerAction::new("run", "Run", ActionEnabled::OnEntry { kind: None })];
|
||||
let out = ListManager::new("Macros", "Macro name:", entries, actions).renames(1).opened(Bind::given(true)).show(ui);
|
||||
ended.set(ended.get() || out.closed.is_some());
|
||||
if let Some(choice) = out.choice {
|
||||
if choice.is_rename() {
|
||||
for entry in held.borrow_mut().iter_mut().filter(|entry| Some(&entry.id) == choice.entry.as_ref()) {
|
||||
entry.name.clone_from(&choice.name);
|
||||
}
|
||||
}
|
||||
seen.borrow_mut().push(choice);
|
||||
}
|
||||
});
|
||||
fixture.room(Vec2::new(1400.0, 1000.0)).idle(30);
|
||||
let renames = || choices.borrow().iter().filter(|choice| choice.is_rename()).count();
|
||||
|
||||
let alpha = fixture.by_label("Alpha").expect("the list shows Alpha");
|
||||
fixture.click(&alpha).idle(4);
|
||||
fixture.key(Key::F2, Modifiers::NONE).idle(4);
|
||||
fixture.key(Key::A, Modifiers::COMMAND).idle(2);
|
||||
fixture.type_text(" Zed ").idle(2);
|
||||
fixture.key(Key::Enter, Modifiers::NONE).idle(6);
|
||||
{
|
||||
let seen = choices.borrow();
|
||||
let [choice] = seen.as_slice() else { panic!("one choice for the commit, got {seen:?}") };
|
||||
assert!(choice.is_rename(), "the commit is a rename");
|
||||
assert_eq!(choice.entry.as_deref(), Some("a"), "it names the renamed entry");
|
||||
assert_eq!(choice.name, "Zed", "it carries the trimmed name");
|
||||
}
|
||||
assert!(!closed.get(), "the dialog stays open");
|
||||
|
||||
let zed = fixture.by_label("Zed").expect("the row shows the new name");
|
||||
fixture.click(&zed).idle(4);
|
||||
fixture.key(Key::F2, Modifiers::NONE).idle(4);
|
||||
fixture.type_text("Q").idle(2);
|
||||
fixture.key(Key::Escape, Modifiers::NONE).idle(6);
|
||||
assert_eq!(renames(), 1, "Escape reports no rename");
|
||||
assert!(!closed.get(), "Escape ends the editor and keeps the dialog");
|
||||
assert_eq!(rows.borrow()[0].name, "Zed", "the entry keeps its name");
|
||||
|
||||
let bravo = fixture.by_label("Bravo").expect("the list shows Bravo");
|
||||
fixture.click(&bravo).idle(4);
|
||||
fixture.key(Key::F2, Modifiers::NONE).idle(4);
|
||||
fixture.type_text("X").idle(2);
|
||||
fixture.key(Key::Enter, Modifiers::NONE).idle(6);
|
||||
assert_eq!(renames(), 1, "an entry of another kind does not rename");
|
||||
}
|
||||
Reference in new issue
Block a user