PresetPicker as a pattern over a Popover container: open at a point without the field (open_at), resizable with a remembered size; PopoverOutput reports its open state from its binding (ColorPopover and PresetPicker read it, not the exit fade); no hover proposals

This commit is contained in:
aiongg
2026-11-13 18:40:30 +00:00
parent 4daa178128
commit a555f84b71
9 changed files with 408 additions and 189 deletions
+1 -1
View File
@@ -132,7 +132,7 @@ fn popover(
}
picker.show(ui)
});
let open = shown.inner.is_some() && shown.output.closed.is_none();
let open = shown.output.open;
match shown.inner {
Some(ColorPickerOutput { events, screen_pick, .. }) => (events, screen_pick, open),
None => (EditEvents::new(), None, open),
+4 -4
View File
@@ -278,13 +278,13 @@ fn field_row(ui: &mut Ui, input: &PageInput<'_>, field: &EffectField, shown: &St
let current = stored.map(str::to_owned).or(first.clone());
let picker = Field::new(label.clone())
.id_salt(key)
.show(ui, |ui, _| PresetPicker::new(label.clone(), Bind::given(current.clone()), input.patterns, Bind::kept()).show(ui))
.show(ui, |ui, _| PresetPicker::new(label.clone(), Bind::given(current.clone()), input.patterns, Bind::kept()).show(ui).edit)
.inner;
if let Some(picker) = picker {
if picker.edit.events.is_empty() && stored.is_none() && first.is_some() {
if let Some(edit) = picker {
if edit.events.is_empty() && stored.is_none() && first.is_some() {
out.fill_default = current.map(|text| (key.to_owned(), StyleValue::Text(text)));
}
let edit = picker.edit.map(Option::unwrap_or_default);
let edit = edit.map(Option::unwrap_or_default);
push_edit(&mut out.edit, style_edit(&edit, input.style, |v| param(StyleValue::Text(v.clone()))));
}
}
@@ -20,8 +20,8 @@ use super::words::PresetWords;
use crate::bars::{Bar, BarKind};
use crate::choice::Segmented;
use crate::contract::{
Bind, BodyCx, CollectionEvent, DropMark, DropTarget, DropZone, Entry, LeadSource, ListDrag, OpenChange, Pattern, Props, Rename, ReorderMove,
ReorderRule, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, request_rename,
Bind, BodyCx, CollectionEvent, DropMark, DropTarget, DropZone, Entry, ListDrag, OpenChange, Pattern, Props, Rename, ReorderMove, ReorderRule,
SelectMode, Show as _, ShowCollection as _, ShowContainer as _, request_rename,
};
use crate::display::Divider;
use crate::layout_components::Stack;
@@ -206,6 +206,10 @@ pub struct PresetBrowser<'a, K: Clone + Eq + Hash + Send + Sync + 'static> {
/// A row above the presets with the search field and the grid and list buttons.
#[prop]
toolbar: bool,
/// The toolbar's search field; off, the toolbar keeps the view buttons and the host's tools, and the search is
/// cleared.
#[prop]
search: bool,
/// The host's controls at the reading end of the toolbar.
#[prop(func = "FnMut(&mut Ui)")]
tools: Option<BrowserTools<'a>>,
@@ -266,6 +270,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> PresetBrowser<'a, K> {
thumb_range: TileZoom::Ladder,
default_open: DefaultOpen::All,
toolbar: false,
search: true,
tools: None,
row_menu: true,
view_lock: None,
@@ -473,7 +478,6 @@ enum Seen<K> {
Activate(K),
Open(OpenChange<K>),
Menu(K),
Pointer(K),
Reorder(EditEvent<ReorderMove<K>>),
Rename(EditEvent<Rename<K>>),
}
@@ -487,7 +491,6 @@ fn seen<K, E>(events: Vec<CollectionEvent<K, E>>) -> Vec<Seen<K>> {
CollectionEvent::Activate(key) => Some(Seen::Activate(key)),
CollectionEvent::Open(change) => Some(Seen::Open(change)),
CollectionEvent::ContextMenu(request) => Some(Seen::Menu(request.key)),
CollectionEvent::LeadMoved { key, by: LeadSource::Pointer } => Some(Seen::Pointer(key)),
CollectionEvent::Reorder(edit) => Some(Seen::Reorder(edit)),
CollectionEvent::Rename(edit) => Some(Seen::Rename(edit)),
_ => None,
@@ -546,6 +549,7 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> PresetBrowser<'_, K> {
thumb_range,
default_open,
toolbar,
search,
mut tools,
row_menu,
view_lock,
@@ -595,14 +599,21 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> PresetBrowser<'_, K> {
bar = bar.trailing(|ui, _| tools.show(ui));
}
let _ = bar.show(ui, |ui, _| {
let field = TextField::search(words.search.clone(), Bind::bound(&mut local.filter)).placeholder(words.search.clone());
let field = field.drives(list_id);
field.show(ui);
if search {
let field = TextField::search(words.search.clone(), Bind::bound(&mut local.filter)).placeholder(words.search.clone());
let field = field.drives(list_id);
field.show(ui);
}
if !locked {
Segmented::new(words.view.clone(), Bind::bound(&mut local.view), &modes).show(ui);
}
});
}
// A hidden search field filters nothing: a search typed before hiding it would otherwise keep presets
// out of the list with no field to show why.
if toolbar && !search {
local.filter.clear();
}
let view = view_lock.unwrap_or(local.view);
let query = local.filter.trim().to_owned();
@@ -645,7 +656,6 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> PresetBrowser<'_, K> {
}
};
let mut hovered: Option<K> = None;
let (response, displayed, pass) = if shown.is_empty() && actions.is_empty() {
let message = if query.is_empty() { words.empty.clone() } else { words.no_match.clone() };
let response = Notice::new(Tone::Neutral, message).layout(NoticeLayout::Centred).show(ui).response;
@@ -852,7 +862,6 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> PresetBrowser<'_, K> {
menu_target = Some(key);
}
}
Seen::Pointer(key) => hovered = key.preset().filter(|key| row_of(key).is_some_and(|at| !rows[at].is_group())).cloned(),
Seen::Reorder(edit) => {
let moved = |mv: ReorderMove<BrowserKey<K>>| {
let mv = app_move(mv)?;
@@ -932,7 +941,7 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> PresetBrowser<'_, K> {
if !has_footer {
commit(cx, &state, rows, &name);
}
(response, hovered, events)
(response, events)
};
let footer_region = |ui: &mut Ui, cx: &mut BodyCx<'_>| {
@@ -948,10 +957,10 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> PresetBrowser<'_, K> {
let stack = room_height.map_or_else(|| Stack::new().fill(), |height| Stack::new().fill_width().room_height(height));
let stack = if has_footer { stack.footer(footer_region) } else { stack };
let shown = stack.show(ui, body);
let (response, hovered, mut events) = shown.inner.unwrap_or_else(|| (shown.output.clone(), None, Vec::new()));
let (response, mut events) = shown.inner.unwrap_or_else(|| (shown.output.clone(), Vec::new()));
events.extend(footer_events.take().into_iter().map(PresetEvent::Footer));
let drag = crate::runtime::drag::active::<ListDrag<K>>(ui.ctx()).filter(|drag| drag.list == list_id).map(|drag| (*drag).clone());
PresetOutput::new(response, events, drag, hovered)
PresetOutput::new(response, events, drag)
}
}
@@ -115,15 +115,12 @@ pub struct PresetOutput<K> {
/// While a preset or group is dragged, its payload, so the host can draw its own drop highlight; `None`
/// otherwise.
pub drag: Option<ListDrag<K>>,
/// The preset under the pointer this pass, for a hover preview; `None` off the list, over a header, or while a
/// drag is under way.
pub hovered: Option<K>,
}
impl<K> PresetOutput<K> {
/// The output of a browser pass.
pub fn new(response: Response, events: Vec<PresetEvent<K>>, drag: Option<ListDrag<K>>, hovered: Option<K>) -> Self {
PresetOutput { response, events, drag, hovered }
pub fn new(response: Response, events: Vec<PresetEvent<K>>, drag: Option<ListDrag<K>>) -> Self {
PresetOutput { response, events, drag }
}
}
+318 -156
View File
@@ -1,33 +1,37 @@
//! `PresetPicker`: a closed field that shows the current preset and opens a `PresetBrowser` in a popover.
//!
//! The closed field is a `SelectFace` over the field well, as `Select` shows it. Hovering a preset in the popover
//! proposes it, a pick commits and closes, and closing without a pick restores the value. A host can put content
//! above the browser (`head`), keep the popover open on a click (`keep_open`), give the browser a footer and set
//! how far the thumbnails zoom.
//! The closed field is a `SelectFace` over the field well, as `Select` shows it; the popover is a `Popover` container
//! with the browser. A pick sets the value and closes. A host can put content above the browser (`head`), keep the popover open on a click
//! (`keep_open`), give the browser a footer, set how far the thumbnails zoom, open the popover at a point without the
//! field (`open_at`) and let the user resize it (`resizable`).
#[cfg(feature = "testing")]
mod stories;
use std::sync::Arc;
use super::browser::{BrowserTools, PresetBrowser, ThumbPainter};
use super::event::PresetEvent;
use super::event::{PresetEvent, PresetOutput};
use super::footer::PresetFooterOptions;
use super::model::{CellShape, PresetRow, ThumbInfo};
use super::state::{DefaultOpen, PresetState, PresetView};
use super::words::PresetWords;
use crate::contract::{
Access, Bind, BindMut, BodyCx, Common, Component, Cx, Edit as _, EditResponse, MeasureCx, Outcome, Overlay, OverlayUi, Overlays as _, PaintUi,
PartsCx, Pointer as _, Props as _, Role, ShowContainer as _, WordSetCx as _,
Access, Bind, BindMut, BodyCx, Common, Component, Cx, Edit as _, EditResponse, Focus as _, MeasureCx, Outcome, PaintUi, PartsCx, Pointer as _,
Props as _, Remember as _, Role, SaveKey, Show as _, ShowContainer as _, Tooltip, WordSetCx as _,
};
use crate::layout_components::Stack;
use crate::list::RowTest;
use crate::pickers::{SelectFace, toggle_on_key};
use crate::pickers::SelectFace;
use crate::popover::Popover;
use crate::primitives::ContentPainterCx;
use crate::runtime::env::{EnvView, Label};
use crate::runtime::memory::StageAccess;
use crate::runtime::overlay::CloseReason;
use crate::style::{ComponentStyle, FocusLook, StyleCx, SurfaceLook};
use crate::tile_grid::TileZoom;
use craft_behavior::{CancelReason, GesturePhase, HitLevel, HitPriority, Metrics, PartKey, PressPhase, Sense, Value};
use egui::{Id, Rect, Response, Ui, Vec2};
use craft_behavior::{EditEvent, EditEvents, HitLevel, HitPriority, Intent, Metrics, Mixed, PartKey, PressPhase, Sense, Value};
use egui::{Pos2, Rect, Response, Ui, Vec2};
use std::hash::Hash;
/// The face under the whole field.
@@ -61,7 +65,7 @@ pub enum PickerField {
ThumbnailAndName,
}
/// The style of a preset picker: the field well and the focus edge; the face carries the padding.
/// The style of a preset picker's field: the field well and the focus edge; the face carries the padding.
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
#[non_exhaustive]
pub struct PresetPickerStyle {
@@ -80,7 +84,7 @@ pub struct PresetPickerStyle {
#[non_exhaustive]
#[must_use = "the host applies the picker's events"]
pub struct PresetPickerOutput<K> {
/// The field's response and the edit of its value.
/// The field's response and the edit of its value, with the popover's picks.
pub edit: EditResponse<Option<K>>,
/// The preset picked in this pass, which the binding now holds.
pub picked: Option<K>,
@@ -89,6 +93,11 @@ pub struct PresetPickerOutput<K> {
pub events: Vec<PresetEvent<K>>,
/// The pick closed the popover (a double click or Enter); false for a click while `keep_open` holds it open.
pub closed: bool,
/// How the popover closed in this pass (a pick is `Activated`, Escape is `Escape`); `None` while it stays open
/// or stays closed.
pub closed_as: Option<CloseReason>,
/// Whether the popover is open after this pass.
pub open: bool,
/// The thumbnail of the face was pressed (with `edit_face`): the host opens its editor.
pub edit_requested: bool,
/// The row `PresetPicker::create_row` added was chosen in this pass; the popover has closed.
@@ -111,22 +120,22 @@ impl<K: Value> Outcome for PresetPickerOutput<K> {
}
/// A field that shows the current preset and opens its presets. A click, Enter, Space or Alt+Down opens the popover
/// with the browser; hovering a preset proposes it, a click or Enter picks it and closes, and Escape closes and
/// restores the value.
/// with the browser; a click or Enter picks a preset and closes, and Escape closes and keeps the value.
///
/// - **Value.** The binding holds the picked preset's key, or none while the value is no preset of `rows`; the field
/// then shows `placeholder`, "Custom" by default.
/// - **State.** `state` is the browser's view settings; bind it with `Bind::bound`.
/// - **Thumbnails.** Each row's `preview` paints its thumbnail, in the field and in the browser.
/// - **Popover.** A `Popover` container: it hangs from the field, or from a point with [`open_at`](Self::open_at),
/// and with [`resizable`](Self::resizable) its edge grips resize it and the size is saved.
///
/// ```ignore
/// let out = PresetPicker::new("Contour", Bind::bound(&mut shape), &rows, Bind::bound(&mut state)).field(PickerField::ThumbnailAndName).show(ui);
/// ```
#[derive(crate::contract::Component, crate::contract::Props)]
#[component(overlay, probe(PresetPicker<'static, u32>))]
#[derive(crate::contract::Pattern, crate::contract::Props)]
#[pattern(probe(PresetPicker<'static, u32>))]
pub struct PresetPicker<'a, K: Value + Eq + Hash + 'static> {
#[common]
common: Common,
label: Label,
value: Bind<'a, Option<K>>,
rows: &'a [PresetRow<K>],
state: Bind<'a, PresetState<K>>,
@@ -145,13 +154,16 @@ pub struct PresetPicker<'a, K: Value + Eq + Hash + 'static> {
/// A row above the presets with the search field.
#[prop]
toolbar: bool,
/// The search field in the toolbar; off, the toolbar keeps the host's tools and the search is cleared.
#[prop]
search: bool,
/// The host's controls at the reading end of the browser's toolbar.
#[prop(func = "FnMut(&mut Ui)")]
tools: Option<BrowserTools<'a>>,
/// The id of the browser in the popover, which `PresetBrowser::request_rename` names: a host that starts a rename
/// from its own control (a menu's Rename) gives one.
#[prop]
browser_id: Option<Id>,
browser_id: Option<egui::Id>,
/// Which presets and groups the browser may rename.
#[prop(func = "Fn(&K) -> bool")]
can_rename: Option<RowTest<'a, K>>,
@@ -173,11 +185,13 @@ pub struct PresetPicker<'a, K: Value + Eq + Hash + 'static> {
/// A short line under the field's thumbnail (a brush's current size).
#[prop(into)]
caption: Option<Label>,
/// The field's tooltip.
#[prop(into)]
tooltip: Option<Tooltip>,
/// Content above the browser in the popover.
#[prop(func = "FnMut(&mut Ui, &mut BodyCx<'_>)")]
head: Option<PickerHead<'a>>,
/// A click on a preset picks it and keeps the popover open; a double click or Enter picks it and closes. Hovering
/// proposes nothing.
/// A click on a preset picks it and keeps the popover open; a double click or Enter picks it and closes.
#[prop(flag)]
keep_open: bool,
/// The browser's footer.
@@ -199,19 +213,23 @@ pub struct PresetPicker<'a, K: Value + Eq + Hash + 'static> {
/// Paints the popover's thumbnails (a swatch, a gradient ramp, a brush tip) in place of each row's own `preview`.
#[prop(func = "Fn(&ContentPainterCx, Rect, ThumbInfo<'_, K>)")]
preview: Option<ThumbPainter<'a, K>>,
picked: Option<K>,
closed: bool,
edit_requested: bool,
create: bool,
detach: bool,
events: Vec<PresetEvent<K>>,
/// Edge grips resize the popover, and the size the user leaves it at is saved under this key.
#[prop]
resizable: Option<SaveKey>,
opened_at: Option<(Pos2, Bind<'a, bool>)>,
}
/// The picker's state while its field is shown: the popover's open state (without `open_at`).
#[derive(Clone, Default)]
struct Session {
open: bool,
}
impl<'a, K: Value + Eq + Hash + 'static> PresetPicker<'a, K> {
/// A picker named `label` over `value`, choosing among the presets of `rows`.
pub fn new(label: impl Into<Label>, value: Bind<'a, Option<K>>, rows: &'a [PresetRow<K>], state: Bind<'a, PresetState<K>>) -> Self {
PresetPicker {
common: Common::new(),
label: label.into(),
value,
rows,
state,
@@ -220,6 +238,7 @@ impl<'a, K: Value + Eq + Hash + 'static> PresetPicker<'a, K> {
view: PresetView::Grid,
default_open: DefaultOpen::All,
toolbar: false,
search: true,
tools: None,
browser_id: None,
can_rename: None,
@@ -229,6 +248,7 @@ impl<'a, K: Value + Eq + Hash + 'static> PresetPicker<'a, K> {
placeholder: None,
display_name: None,
caption: None,
tooltip: None,
head: None,
keep_open: false,
footer: None,
@@ -237,14 +257,16 @@ impl<'a, K: Value + Eq + Hash + 'static> PresetPicker<'a, K> {
create_row: None,
detach_row: None,
preview: None,
picked: None,
closed: false,
edit_requested: false,
create: false,
detach: false,
events: Vec::new(),
resizable: None,
opened_at: None,
}
.label(label)
}
/// Opens the popover at `at`, a point in the parent's layer space, while `open` is true, and shows no field: the
/// app opens it (a right-click on the canvas) and every close writes `false`.
pub fn open_at(mut self, at: Pos2, open: Bind<'a, bool>) -> Self {
self.opened_at = Some((at, open));
self
}
/// The rows the picker chooses among.
@@ -255,11 +277,256 @@ impl<'a, K: Value + Eq + Hash + 'static> PresetPicker<'a, K> {
/// The key the binding holds, when it holds one.
pub(super) fn held_key(&mut self, cx: &mut impl StageAccess) -> Option<K> {
match self.value.reborrow().read(cx) {
Some(craft_behavior::Mixed::Same(held)) => held,
Some(Mixed::Same(held)) => held,
_ => None,
}
}
/// Shows the field and, while open, the popover.
pub fn show(self, ui: &mut Ui) -> PresetPickerOutput<K> {
let PresetPicker {
label,
mut value,
rows,
mut state,
field,
cell_shape,
view,
default_open,
toolbar,
search,
mut tools,
browser_id,
can_rename,
can_delete,
can_move,
row_menu,
placeholder,
display_name,
caption,
tooltip,
mut head,
keep_open,
footer,
thumb_range,
edit_face,
create_row,
detach_row,
preview,
resizable,
mut opened_at,
} = self;
let name: Arc<str> = Arc::from(label.as_str());
let shown = Stack::new().show(ui, |ui, cx| {
let mut session = cx.memory::<Session>().clone();
// Without the field (`open_at`) the face does not run, so no field shows in the tree; the popover hangs
// from the point instead of from the face.
let mut open = session.open;
let (popover, face_edit, edit_requested) = match opened_at.as_mut() {
Some((at, bind)) => (Popover::new(label.clone(), bind.reborrowed()).at_point(*at), None, false),
None => {
let face = PickerFace {
common: Common::new(),
value: value.reborrowed(),
rows,
field,
cell_shape,
placeholder: placeholder.clone(),
display_name: display_name.clone(),
caption: caption.clone(),
edit_face,
open,
toggle: false,
edit_requested: false,
}
.label(label.clone());
let face = match tooltip.clone() {
Some(tooltip) => face.tooltip(tooltip),
None => face,
};
let FaceOutput { edit, toggle, edit_requested } = face.show(ui);
if toggle {
open = !open;
}
let popover = Popover::new(label.clone(), Bind::bound(&mut open)).opened_by(&edit.response);
(popover, Some(edit), edit_requested)
}
};
let current = match value.reborrow().read(cx) {
Some(Mixed::Same(held)) => held,
_ => None,
};
// The actions follow the presets as rows of the browser's collection, set off by a divider, as the
// preset menu lists them.
let actions: Vec<(Label, bool)> =
[create_row.clone().map(|label| (label, true)), detach_row.clone().map(|label| (label, false))].into_iter().flatten().collect();
let action_labels = actions.iter().map(|(label, _)| label.clone());
let mut browse = |ui: &mut Ui| {
let mut browser = PresetBrowser::new(label.clone(), state.reborrowed(), rows)
.cell_shape(cell_shape)
.view_lock(view)
.default_open(default_open)
.toolbar(toolbar)
.search(search)
.row_menu(row_menu)
.thumb_range(thumb_range)
.actions(action_labels.clone());
if let Some(options) = footer.as_ref() {
browser = browser.footer(options.clone());
}
if let Some(tools) = tools.as_mut() {
browser = browser.tools(|ui| tools.show(ui));
}
if let Some(id) = browser_id {
browser = browser.browser_id(id);
}
if let Some(key) = current.clone() {
browser = browser.selected(key);
}
if let Some(test) = can_rename.as_ref() {
browser = browser.can_rename(|key| test.passes(key));
}
if let Some(test) = can_delete.as_ref() {
browser = browser.can_delete(|key| test.passes(key));
}
if let Some(test) = can_move.as_ref() {
browser = browser.can_move(|key| test.passes(key));
}
if let Some(painter) = preview.as_ref() {
browser = browser.thumb(|cx, rect, info| painter.paint(cx, rect, info));
}
browser.show(ui)
};
let popover = popover.collection_body();
let popover = match resizable.clone() {
Some(key) => popover.resizable(true).remember(key),
None => popover,
};
let popup = popover.show(ui, |ui, body| {
let out: PresetOutput<K> = Stack::new()
.fill()
.header(|ui, cx| {
if let Some(head) = head.as_mut() {
(head.0)(ui, cx);
}
})
.show(ui, |ui, _| browse(ui))
.inner?;
let closing = out.events.iter().any(|event| match event {
PresetEvent::Select { .. } => !keep_open,
PresetEvent::Activate { .. } => true,
PresetEvent::Action(at) => *at < actions.len(),
_ => false,
});
if closing {
body.request_close_as(CloseReason::Activated);
}
Some(out)
});
let closed_as = popup.output.closed;
let open_after = popup.output.open;
let browsed = popup.inner.flatten();
let mut edit = face_edit.unwrap_or_else(|| EditResponse::lifted(popup.output.response.clone(), EditEvents::new(), None));
let mut out = PresetPickerOutput {
edit: EditResponse::lifted(edit.response.clone(), EditEvents::new(), None),
picked: None,
events: Vec::new(),
closed: false,
closed_as,
open: open_after,
edit_requested,
create: false,
detach: false,
};
let mut pick: Option<(K, bool)> = None;
if let Some(browsed) = browsed {
for event in browsed.events {
match event {
PresetEvent::Select { key, .. } => pick = Some((key, !keep_open)),
PresetEvent::Activate { key, .. } => pick = Some((key, true)),
PresetEvent::Open(_) => {}
PresetEvent::Action(at) => match actions.get(at) {
Some(&(_, true)) => out.create = true,
Some(&(_, false)) => out.detach = true,
None => {}
},
other => out.events.push(other),
}
}
}
let mut events = EditEvents::new();
if let Some((key, close)) = pick {
events.push(EditEvent::set(Mixed::Same(current.clone()), Some(key.clone()), Arc::clone(&name), None));
out.picked = Some(key);
out.closed = close;
}
for event in events.iter() {
value.reborrow().write(cx, event);
}
edit.events.extend(events);
out.edit = edit;
if opened_at.is_none() {
session.open = open_after;
}
*cx.memory::<Session>() = session;
out
});
match shown.inner {
Some(out) => out,
None => PresetPickerOutput {
edit: EditResponse::lifted(shown.output, EditEvents::new(), None),
picked: None,
events: Vec::new(),
closed: false,
closed_as: None,
open: false,
edit_requested: false,
create: false,
detach: false,
},
}
}
}
/// The picker's closed field: the face of the current preset. It owns the picker's value for the field's edit
/// response; the popover's picks are written by `PresetPicker`.
#[derive(crate::contract::Component, crate::contract::Props)]
#[component(unregistered)]
struct PickerFace<'a, K: Value + Eq + Hash + 'static> {
#[common]
common: Common,
value: Bind<'a, Option<K>>,
rows: &'a [PresetRow<K>],
field: PickerField,
cell_shape: CellShape,
placeholder: Option<Label>,
display_name: Option<Label>,
caption: Option<Label>,
edit_face: bool,
open: bool,
toggle: bool,
edit_requested: bool,
}
/// What the field reports.
#[derive(Debug)]
struct FaceOutput<K> {
edit: EditResponse<Option<K>>,
/// A click on the face, Enter or Space toggles the popover; Alt+Down opens it.
toggle: bool,
edit_requested: bool,
}
impl<K: Value> Outcome for FaceOutput<K> {
type Value = Option<K>;
fn response(&self) -> &Response {
&self.edit.response
}
}
impl<K: Value + Eq + Hash + 'static> PickerFace<'_, K> {
fn preset(&self, key: &K) -> Option<&PresetRow<K>> {
self.rows.iter().find(|row| !row.is_group() && row.key == *key)
}
@@ -292,7 +559,7 @@ impl<'a, K: Value + Eq + Hash + 'static> PresetPicker<'a, K> {
/// candidates and the painted face are both built here.
fn face_of(&self, text: Label, row: Option<&PresetRow<K>>, paint: bool) -> SelectFace<'static> {
let face = SelectFace::new(text);
let face = match (row, self.field) {
match (row, self.field) {
(None, PickerField::Thumbnail) => self.empty_thumb(face.placeholder()),
(None, _) => face.placeholder(),
(Some(row), field) => match (&row.preview, field) {
@@ -309,17 +576,16 @@ impl<'a, K: Value + Eq + Hash + 'static> PresetPicker<'a, K> {
self.captioned(face)
}
},
};
face
}
}
}
impl<K: Value + Eq + Hash + 'static> Component for PresetPicker<'_, K> {
impl<K: Value + Eq + Hash + 'static> Component for PickerFace<'_, K> {
const ROLE: Role = Role::COMBO_BOX;
type Style = PresetPickerStyle;
type Output = PresetPickerOutput<K>;
type Output = FaceOutput<K>;
fn style(cx: &StyleCx<'_>, _: PresetPickerStyleKey<K>) -> PresetPickerStyle {
fn style(cx: &StyleCx<'_>, _: PickerFaceStyleKey<K>) -> PresetPickerStyle {
PresetPickerStyle { surface: cx.dropdown(), metrics: Metrics::new(), focus: cx.focus_look() }
}
@@ -347,8 +613,7 @@ impl<K: Value + Eq + Hash + 'static> Component for PresetPicker<'_, K> {
cx.part(FACE, rect)
.sense(Sense::CLICK | Sense::HOVER | Sense::TAKE_FOCUS)
.priority(HitPriority::new(HitLevel::Body, 0))
.pointer_only("Enter, Space and Alt+Down open the presets")
.toggles("browser");
.pointer_only("Enter, Space and Alt+Down open the presets");
if self.edit_face {
let (thumb, _) = cx.flow.take_start(cx.content_rect.height());
cx.part(THUMB, thumb)
@@ -362,117 +627,22 @@ impl<K: Value + Eq + Hash + 'static> Component for PresetPicker<'_, K> {
Some(self.value.reborrow())
}
/// A press on the face and Alt+Down open the popover through the face's `toggles`; Enter and Space toggle it
/// (`toggle_on_key`). A preview that the popover closed on without a pick is cancelled.
/// A click on the face, Enter and Space toggle the popover; Alt+Down opens it.
fn update(&mut self, cx: &mut Cx<'_, Self>) {
let popup = cx.popup("browser");
toggle_on_key(cx, popup);
let clicked = matches!(cx.part(FACE).press.phase, PressPhase::Release { click: true, .. });
let keyed = cx.activation().is_some_and(|activation| activation.by_key);
let opens = !self.open && cx.intents().take(Intent::Open);
self.toggle = clicked || keyed || opens;
if self.edit_face && matches!(cx.part(THUMB).press.phase, PressPhase::Release { click: true, .. }) {
self.edit_requested = true;
}
if !popup.is_open(cx) && matches!(cx.gesture(), Some(GesturePhase::Begin | GesturePhase::Update)) {
cx.cancel(CancelReason::Dismissed);
}
}
/// The popover: the browser over the rows. The preset the pointer moves the lead to is proposed; a click or Enter
/// on a preset proposes it, commits and closes the popover.
fn overlay(&mut self, ui: &mut OverlayUi<'_>, cx: &mut Cx<'_, Self>) {
let popup = cx.popup("browser");
let name = cx.label();
let current = cx.value().and_then(Clone::clone);
let (rows, shape, view, default_open, toolbar) = (self.rows, self.cell_shape, self.view, self.default_open, self.toolbar);
let (can_rename, can_delete, can_move, row_menu) =
(self.can_rename.as_ref(), self.can_delete.as_ref(), self.can_move.as_ref(), self.row_menu);
let (thumb_range, footer, keep_open) = (self.thumb_range, self.footer.as_ref(), self.keep_open);
let state = &mut self.state;
let head = &mut self.head;
let tools = &mut self.tools;
let browser_id = self.browser_id;
let preview = self.preview.as_ref();
// The actions follow the presets as rows of the browser's collection, set off by a divider, as the preset menu
// lists them.
let actions: Vec<(Label, bool)> =
[self.create_row.clone().map(|label| (label, true)), self.detach_row.clone().map(|label| (label, false))].into_iter().flatten().collect();
let action_labels = actions.iter().map(|(label, _)| label.clone());
let mut browse = |ui: &mut Ui| {
let mut browser = PresetBrowser::new(name.clone(), state.reborrowed(), rows)
.cell_shape(shape)
.view_lock(view)
.default_open(default_open)
.toolbar(toolbar)
.row_menu(row_menu)
.thumb_range(thumb_range)
.actions(action_labels.clone());
if let Some(options) = footer {
browser = browser.footer(options.clone());
}
if let Some(tools) = tools.as_mut() {
browser = browser.tools(|ui| tools.show(ui));
}
if let Some(id) = browser_id {
browser = browser.browser_id(id);
}
if let Some(key) = current.clone() {
browser = browser.selected(key);
}
if let Some(test) = can_rename {
browser = browser.can_rename(|key| test.passes(key));
}
if let Some(test) = can_delete {
browser = browser.can_delete(|key| test.passes(key));
}
if let Some(test) = can_move {
browser = browser.can_move(|key| test.passes(key));
}
if let Some(painter) = preview {
browser = browser.thumb(|cx, rect, info| painter.paint(cx, rect, info));
}
browser.show(ui)
};
let out = ui.show(popup, Overlay::popover(), |ui, _| {
let Some(head) = head.as_mut() else { return Some(browse(ui)) };
Stack::new().fill().header(|ui, cx| (head.0)(ui, cx)).show(ui, |ui, _| browse(ui)).inner
});
let Some(out) = out.flatten() else { return };
let mut pick: Option<(K, bool)> = None;
for event in out.events {
match event {
PresetEvent::Select { key, .. } => pick = Some((key, !keep_open)),
PresetEvent::Activate { key, .. } => pick = Some((key, true)),
PresetEvent::Open(_) => {}
PresetEvent::Action(at) => {
let Some(&(_, create)) = actions.get(at) else { continue };
if create {
self.create = true;
} else {
self.detach = true;
}
popup.close(cx);
}
other => self.events.push(other),
}
}
match (pick, out.hovered) {
(Some((key, close)), _) => {
cx.propose(Some(key.clone()));
cx.commit();
if close {
popup.close(cx);
}
self.picked = Some(key);
self.closed = close;
}
(None, Some(key)) if !keep_open && current.as_ref() != Some(&key) => cx.propose(Some(key)),
_ => {}
}
}
/// The current preset's name as the field's value.
/// The current preset's name as the field's value, and whether the popover is open after this pass's toggle.
fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) {
let words = cx.words::<PresetWords>();
let (text, _) = self.shown(cx.value(), &words, &cx.env);
access.value(text.as_str().to_owned());
access.value(text.as_str().to_owned()).expanded(self.open != self.toggle);
}
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
@@ -481,15 +651,7 @@ impl<K: Value + Eq + Hash + 'static> Component for PresetPicker<'_, K> {
ui.face(FACE, self.face_of(text, row, true));
}
fn finish(self, cx: Cx<'_, Self>) -> PresetPickerOutput<K> {
PresetPickerOutput {
edit: cx.edit_response(),
picked: self.picked,
events: self.events,
closed: self.closed,
edit_requested: self.edit_requested,
create: self.create,
detach: self.detach,
}
fn finish(self, cx: Cx<'_, Self>) -> FaceOutput<K> {
FaceOutput { edit: cx.edit_response(), toggle: self.toggle, edit_requested: self.edit_requested }
}
}
@@ -2,7 +2,7 @@
use super::{PickerField, PresetPicker};
use crate::choice::SwatchFace;
use crate::contract::{Bind, Props as _, Role, Show as _, Validity};
use crate::contract::{Bind, Role, Validity};
use crate::list::ThumbAspect;
use crate::patterns::presets::{PresetRow, PresetState};
use crate::runtime::env::Message;
+50 -3
View File
@@ -1,13 +1,60 @@
//! `PresetPicker` inside a popover: the picker's own popover nests in the parent, which stays open through the pick.
//! `PresetPicker`: a click on a preset in the popover picks it and closes; Escape closes and keeps the value; inside a
//! popover, the picker's own popover nests in the parent, which stays open through the pick.
use craft_ui::buttons::Button;
use craft_ui::contract::{Bind, Show as _, ShowContainer as _};
use craft_ui::contract::{Bind, Role, Show as _, ShowContainer as _};
use craft_ui::patterns::presets::{PresetPicker, PresetRow, PresetState};
use craft_ui::popover::Popover;
use craft_ui::testing::{Fixture, trial};
use std::cell::Cell;
use egui::{Key, Modifiers, Vec2};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
const CORAL: u32 = 12;
const TEAL: u32 = 21;
struct Host {
value: Option<u32>,
state: PresetState<u32>,
picked: Vec<u32>,
open: bool,
}
#[trial]
fn a_click_picks_and_closes_and_escape_closes_keeping_the_value() {
let host = Rc::new(RefCell::new(Host { value: Some(CORAL), state: PresetState::new(), picked: Vec::new(), open: false }));
let shown = Rc::clone(&host);
let rows = vec![PresetRow::item(CORAL, "Coral", 0), PresetRow::item(TEAL, "Teal", 0)];
let mut fixture = Fixture::new(move |ui| {
let mut host = shown.borrow_mut();
let Host { value, state, picked, open } = &mut *host;
let out = PresetPicker::new("Swatch", Bind::bound(value), &rows, Bind::bound(state)).show(ui);
picked.extend(out.picked);
*open = out.open;
});
fixture.room(Vec2::new(480.0, 480.0));
fixture.settle();
let field = fixture.by_role(Role::COMBO_BOX).first().copied().expect("the field shows");
fixture.click(&field);
fixture.idle(3);
assert!(fixture.by_label("Teal").is_some(), "the field opens the popover with the presets");
fixture.key(Key::Escape, Modifiers::NONE);
fixture.idle(3);
assert_eq!(host.borrow().value, Some(CORAL), "Escape keeps the value");
assert!(fixture.by_role(Role::DIALOG).is_empty(), "and closes the popover");
assert!(!host.borrow().open, "the picker reports it closed");
fixture.click(&field);
fixture.idle(3);
let teal = fixture.by_label("Teal").expect("the popover lists the presets");
fixture.click(&teal);
fixture.idle(3);
let host = host.borrow();
assert_eq!((host.value, host.picked.as_slice()), (Some(TEAL), &[TEAL][..]), "the click picks");
assert!(fixture.by_role(Role::DIALOG).is_empty(), "and closes the popover");
}
#[trial]
fn a_picker_in_a_popover_opens_and_picks_with_the_popover_kept_open() {
let (parent, value) = (Rc::new(Cell::new(true)), Rc::new(Cell::new(Some(1u32))));
+10 -6
View File
@@ -8,7 +8,7 @@ use crate::runtime::env::Label;
use crate::runtime::focus::{FocusPolicy, Initial};
use crate::runtime::overlay::CloseReason;
use crate::style::{ComponentStyle, StyleCx, SurfaceKind};
use craft_behavior::{CancelRule, Metrics, Sense};
use craft_behavior::{CancelRule, Metrics, Mixed, Sense};
use egui::{Pos2, Response};
/// The style of a popover: the surface and padding come from the container.
@@ -27,16 +27,20 @@ pub struct PopoverOutput {
pub response: Response,
/// How the popover closed in this pass; `None` while it stays open. Reported once for each close.
pub closed: Option<CloseReason>,
/// Whether the popover is open after this pass: its binding as the close rules left it. False through the exit
/// fade, while the closed popover's body still runs.
pub open: bool,
/// A press landed outside the popover, its opener and the popups opened from it while an
/// [`Outside::Keep`] rule kept it open: the caller decides whether that closes it.
pub pressed_outside: bool,
}
impl PopoverOutput {
/// The output of the container `cx` that closed as `closed` in this pass.
pub(super) fn of<C: Component>(cx: &Cx<'_, C>, closed: Option<CloseReason>) -> Self {
/// The output of the container `cx` that closed as `closed` in this pass, open while `open` holds true.
pub(super) fn of<C: Component>(mut cx: Cx<'_, C>, closed: Option<CloseReason>, mut open: Bind<'_, bool>) -> Self {
let pressed_outside = crate::runtime::overlay::pressed_outside(&cx.core.ctx, cx.core.id);
PopoverOutput { response: cx.response.clone(), closed, pressed_outside }
let open = matches!(open.reborrow().read(&mut cx), Some(Mixed::Same(true)));
PopoverOutput { response: cx.response.clone(), closed, open, pressed_outside }
}
}
@@ -48,7 +52,7 @@ impl Outcome for PopoverOutput {
}
fn unshown(response: Response) -> Option<Self> {
Some(PopoverOutput { response, closed: None, pressed_outside: false })
Some(PopoverOutput { response, closed: None, open: false, pressed_outside: false })
}
}
@@ -188,7 +192,7 @@ impl Component for Popover<'_> {
}
fn finish(self, cx: Cx<'_, Self>) -> PopoverOutput {
PopoverOutput::of(&cx, self.closed)
PopoverOutput::of(cx, self.closed, self.open)
}
}
+1 -1
View File
@@ -75,7 +75,7 @@ impl Component for PopupList<'_> {
}
fn finish(self, cx: Cx<'_, Self>) -> PopoverOutput {
PopoverOutput::of(&cx, self.closed)
PopoverOutput::of(cx, self.closed, self.open)
}
}