mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 03:17:43 +00:00
Merge remote-tracking branch 'origin/next' into sync/next
# Conflicts: # crates/imaging/src/ui/layer_style/list.rs
This commit is contained in:
@@ -17,9 +17,9 @@ use super::blending::{BlendingInput, blending_page};
|
||||
use super::contour::{ContourAction, ContourRequest, ContourSampler};
|
||||
use super::labels::LayerStyleWords;
|
||||
use super::list::{LayerStyleCommand, ListAction, effect_list};
|
||||
use super::page::{PageInput, StyleOp, effect_page, push_edit, set_edit};
|
||||
use super::page::{PageInput, effect_page, push_edit};
|
||||
use super::styles::styles_page;
|
||||
use craft_behavior::EditEvents;
|
||||
use craft_behavior::{EditEvent, EditEvents, Mixed};
|
||||
|
||||
use crate::layer_style::{Contour, EffectId, EffectKind, EffectSpec, LayerStyle, LayerStyleDraft, LayerStylePage, StyleParams, StyleValue};
|
||||
|
||||
@@ -239,9 +239,6 @@ impl<'a> LayerStyleDialog<'a> {
|
||||
let name = label.as_str().to_owned();
|
||||
let shown = Row::new().label(label.clone()).show(ui, |ui, _| {
|
||||
let list = Stack::new().command_scope(LayerStyleCommand::SCOPE).show(ui, |ui, cx| effect_list(ui, cx, draft, specs, &words, &units));
|
||||
if let Some(action) = list.inner.flatten() {
|
||||
work.list_action(action, specs, draft, &name);
|
||||
}
|
||||
Divider::vertical().show(ui);
|
||||
Stack::new().label(title.clone()).show(ui, |ui, _| {
|
||||
let page = PageEnv {
|
||||
@@ -258,6 +255,9 @@ impl<'a> LayerStyleDialog<'a> {
|
||||
};
|
||||
work.page(ui, &page, style_presets);
|
||||
});
|
||||
if let Some(actions) = list.inner {
|
||||
work.list_actions(actions, specs, &name);
|
||||
}
|
||||
});
|
||||
let Work { next, edit, extras } = work;
|
||||
LayerStyleOutput {
|
||||
@@ -356,29 +356,43 @@ struct Work {
|
||||
}
|
||||
|
||||
impl Work {
|
||||
/// Applies a list action to the copy (its view state: the page an added effect opens on) and records its change to
|
||||
/// the style as the pass's edit.
|
||||
fn list_action(&mut self, action: ListAction, specs: &[EffectSpec], draft: &LayerStyleDraft, label: &str) {
|
||||
let op = match action {
|
||||
ListAction::Select(page) => {
|
||||
self.next.page = page;
|
||||
return;
|
||||
/// Apply the list's edits together, on top of any field edit the page reported on losing focus.
|
||||
fn list_actions(&mut self, actions: Vec<ListAction>, specs: &[EffectSpec], label: &str) {
|
||||
if actions.is_empty() {
|
||||
return;
|
||||
}
|
||||
if let Some(style) = self.edit.landed() {
|
||||
self.next.style = style.clone();
|
||||
}
|
||||
let before = self.next.style.clone();
|
||||
let defaults = |kind| specs.iter().find(|spec| spec.kind == kind).map(|spec| spec.defaults.clone()).unwrap_or_default();
|
||||
for action in actions {
|
||||
match action {
|
||||
ListAction::Select(page) => self.next.page = page,
|
||||
ListAction::Check(id, on) => {
|
||||
if self.next.style.effect(id).is_some_and(|effect| effect.on != on) {
|
||||
self.next.toggle(id);
|
||||
}
|
||||
}
|
||||
ListAction::CheckAbsent(kind, on) => {
|
||||
let present = self.next.style.instances(kind).next();
|
||||
match (present, on) {
|
||||
(None, true) => {
|
||||
self.next.add_instance(kind, &defaults(kind));
|
||||
}
|
||||
(Some(id), false) => self.next.remove_instance(id),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
ListAction::Add(kind) => {
|
||||
self.next.add_instance(kind, &defaults(kind));
|
||||
}
|
||||
ListAction::Remove(id) => self.next.remove_instance(id),
|
||||
}
|
||||
ListAction::Toggle(id) => {
|
||||
self.next.toggle(id);
|
||||
StyleOp::Toggle(id)
|
||||
}
|
||||
ListAction::Add(kind) => {
|
||||
let defaults = specs.iter().find(|spec| spec.kind == kind).map(|spec| spec.defaults.clone()).unwrap_or_default();
|
||||
self.next.add_instance(kind, &defaults);
|
||||
StyleOp::Add { kind, defaults }
|
||||
}
|
||||
ListAction::Remove(id) => {
|
||||
self.next.remove_instance(id);
|
||||
StyleOp::Remove(id)
|
||||
}
|
||||
};
|
||||
push_edit(&mut self.edit, set_edit(&draft.style, &op, label));
|
||||
}
|
||||
if self.next.style != before {
|
||||
self.edit.push(EditEvent::set(Mixed::Same(before), self.next.style.clone(), label.into(), None));
|
||||
}
|
||||
}
|
||||
|
||||
/// Draws the page of the pass; its controls add their edits to the pass's.
|
||||
|
||||
@@ -31,8 +31,10 @@ pub enum LayerStyleCommand {
|
||||
pub(super) enum ListAction {
|
||||
/// Show this page (a row click, Enter on the lead row).
|
||||
Select(LayerStylePage),
|
||||
/// An instance's check box: [`LayerStyleDraft::toggle`].
|
||||
Toggle(EffectId),
|
||||
/// The value of an instance's check box.
|
||||
Check(EffectId, bool),
|
||||
/// An absent effect is added when checked and removed again if its sweep is cancelled.
|
||||
CheckAbsent(EffectKind, bool),
|
||||
/// A click on an absent effect's row, or `+`: [`LayerStyleDraft::add_instance`].
|
||||
Add(EffectKind),
|
||||
/// `−`: [`LayerStyleDraft::remove_instance`].
|
||||
@@ -96,6 +98,10 @@ impl ItemSource<EffectRow> for Rows<'_> {
|
||||
fn toggled(&self, at: usize, _: &ColumnKey) -> bool {
|
||||
matches!(&self.rows[at], EffectRow::Instance(id) if self.draft.style.effect(*id).is_some_and(|instance| instance.on))
|
||||
}
|
||||
|
||||
fn toggle_enabled(&self, at: usize, _: &ColumnKey) -> bool {
|
||||
matches!(&self.rows[at], EffectRow::Instance(_) | EffectRow::Absent(_))
|
||||
}
|
||||
}
|
||||
|
||||
/// The name of instance `id` of `kind`: the effect's name, numbered when the style has several instances of the kind.
|
||||
@@ -128,7 +134,7 @@ pub(super) fn effect_list(
|
||||
specs: &[EffectSpec],
|
||||
words: &LayerStyleWords,
|
||||
units: &Units,
|
||||
) -> Option<ListAction> {
|
||||
) -> Vec<ListAction> {
|
||||
let mut rows = vec![EffectRow::Styles, EffectRow::Blending, EffectRow::Gap];
|
||||
for spec in specs {
|
||||
let before = rows.len();
|
||||
@@ -145,7 +151,7 @@ pub(super) fn effect_list(
|
||||
let shown = rows.iter().find(|row| row.page() == Some(draft.page)).cloned();
|
||||
let selection = shown.clone().map_or_else(Selection::default, Selection::single);
|
||||
let source = Rows { rows: &rows, draft };
|
||||
let columns = vec![ColumnSpec::toggle(CHECK, Label::Empty, ToggleColumn::default()), ColumnSpec::new(NAME, Label::Empty, ColumnWidth::Content)];
|
||||
let columns = vec![ColumnSpec::toggle(CHECK, Label::Empty, ToggleColumn::sweepable()), ColumnSpec::new(NAME, Label::Empty, ColumnWidth::Content)];
|
||||
|
||||
let out = List::<EffectRow>::new(words.effects.clone())
|
||||
.select(SelectMode::Single)
|
||||
@@ -194,48 +200,50 @@ pub(super) fn effect_list(
|
||||
}
|
||||
let lead = cx.keep::<Lead>().0.clone().filter(|row| rows.contains(row)).or(shown);
|
||||
|
||||
let mut action = None;
|
||||
let mut first = |next: Option<ListAction>| {
|
||||
if action.is_none() {
|
||||
action = next;
|
||||
}
|
||||
};
|
||||
let mut actions = Vec::new();
|
||||
for event in &out.events {
|
||||
match event {
|
||||
CollectionEvent::Toggle(edit) => {
|
||||
// This column does not sweep: each toggle edit is one press.
|
||||
if let Some(SweepStep::Flip(toggle) | SweepStep::Restore(toggle)) = cx.keep::<SweepApply>().feed(edit) {
|
||||
first(match &toggle.key {
|
||||
EffectRow::Instance(id) => Some(ListAction::Toggle(*id)),
|
||||
EffectRow::Absent(kind) => Some(ListAction::Add(*kind)),
|
||||
_ => None,
|
||||
});
|
||||
}
|
||||
}
|
||||
CollectionEvent::Item(row, RowEvent::Trailing { part, .. }) => first(match (row, *part) {
|
||||
let action = match event {
|
||||
CollectionEvent::Toggle(edit) => match cx.keep::<SweepApply>().feed(edit) {
|
||||
Some(SweepStep::Flip(toggle) | SweepStep::Restore(toggle)) => match toggle.key {
|
||||
EffectRow::Instance(id) => Some(ListAction::Check(id, toggle.on)),
|
||||
EffectRow::Absent(kind) => Some(ListAction::CheckAbsent(kind, toggle.on)),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
},
|
||||
CollectionEvent::Item(row, RowEvent::Trailing { part, .. }) => match (row, *part) {
|
||||
(EffectRow::Instance(_), ADD) => kind_of(row).map(ListAction::Add),
|
||||
(EffectRow::Instance(id), REMOVE) => Some(ListAction::Remove(*id)),
|
||||
_ => None,
|
||||
}),
|
||||
CollectionEvent::Activate(row) => first(match row {
|
||||
},
|
||||
CollectionEvent::Activate(row) => match row {
|
||||
EffectRow::Absent(kind) => Some(ListAction::Add(*kind)),
|
||||
other => other.page().map(ListAction::Select),
|
||||
}),
|
||||
},
|
||||
CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } => {
|
||||
first(keys.last().and_then(EffectRow::page).filter(|page| *page != draft.page).map(ListAction::Select));
|
||||
keys.last().and_then(EffectRow::page).filter(|page| *page != draft.page).map(ListAction::Select)
|
||||
}
|
||||
_ => {}
|
||||
_ => None,
|
||||
};
|
||||
if let Some(action) = action
|
||||
&& (actions.is_empty() || matches!(action, ListAction::Check(..) | ListAction::CheckAbsent(..)))
|
||||
{
|
||||
actions.push(action);
|
||||
}
|
||||
}
|
||||
while let Some((command, _)) = cx.take_command::<LayerStyleCommand>() {
|
||||
if !actions.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let kind = lead.as_ref().and_then(kind_of).filter(|kind| kind.allows_several());
|
||||
first(match (command, &lead) {
|
||||
let action = match (command, &lead) {
|
||||
(LayerStyleCommand::AddInstance, _) => kind.map(ListAction::Add),
|
||||
(LayerStyleCommand::RemoveInstance, Some(EffectRow::Instance(id))) => {
|
||||
kind.filter(|kind| draft.style.instances(*kind).count() > 1).map(|_| ListAction::Remove(*id))
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
};
|
||||
actions.extend(action);
|
||||
}
|
||||
action
|
||||
actions
|
||||
}
|
||||
|
||||
@@ -24,8 +24,7 @@ use super::blending::BlendingOp;
|
||||
use super::contour::{ContourAction, ContourField, ContourKey, ContourRequest, ContourSampler, contour_source};
|
||||
use super::labels::LayerStyleWords;
|
||||
use crate::layer_style::{
|
||||
Contour, EffectField, EffectId, EffectInstance, EffectKind, EffectSpec, FieldKind, FieldUnit, LayerStyle, LayerStyleDraft, StyleParams,
|
||||
StyleValue,
|
||||
Contour, EffectField, EffectId, EffectInstance, EffectSpec, FieldKind, FieldUnit, LayerStyle, LayerStyleDraft, StyleParams, StyleValue,
|
||||
};
|
||||
|
||||
/// The angle field shows whole degrees.
|
||||
@@ -36,12 +35,6 @@ const ANGLE_RANGE: std::ops::RangeInclusive<f64> = -180.0..=180.0;
|
||||
/// What a part of the dialog did to the style: the operation an event replays on the style it started from.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) enum StyleOp {
|
||||
/// [`LayerStyleDraft::toggle`].
|
||||
Toggle(EffectId),
|
||||
/// [`LayerStyleDraft::add_instance`] from `defaults`.
|
||||
Add { kind: EffectKind, defaults: StyleParams },
|
||||
/// [`LayerStyleDraft::remove_instance`].
|
||||
Remove(EffectId),
|
||||
/// A page field: [`LayerStyleDraft::set_param`] of `key` of instance `id`.
|
||||
Param { id: EffectId, key: String, value: StyleValue },
|
||||
/// A Blending Options control.
|
||||
@@ -52,11 +45,6 @@ pub(super) enum StyleOp {
|
||||
pub(super) fn apply_op(op: &StyleOp, style: &LayerStyle) -> Option<LayerStyle> {
|
||||
let mut draft = LayerStyleDraft::new(style.clone());
|
||||
match op {
|
||||
StyleOp::Toggle(id) => draft.toggle(*id),
|
||||
StyleOp::Add { kind, defaults } => {
|
||||
draft.add_instance(*kind, defaults);
|
||||
}
|
||||
StyleOp::Remove(id) => draft.remove_instance(*id),
|
||||
StyleOp::Param { id, key, value } => draft.set_param(*id, key, value.clone()),
|
||||
StyleOp::Blending(op) => op.apply(&mut draft.style.blending),
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ use craft_ui::contract::Role;
|
||||
use craft_ui::patterns::presets::{PresetFns, PresetRow, PresetSource};
|
||||
use craft_ui::testing::access::{NodeKey, name};
|
||||
use craft_ui::testing::focus::AccessActionKind;
|
||||
use craft_ui::testing::{Fixture, Target, trial};
|
||||
use craft_ui::testing::{Fixture, Target, pointer, trial};
|
||||
use egui::{Key, Modifiers, Vec2};
|
||||
|
||||
/// The room the dialog is shown in: tall enough for the longest effect page.
|
||||
@@ -116,6 +116,42 @@ fn a_list_click_commits_the_typing_of_the_page_it_leaves() {
|
||||
assert_eq!(host.borrow().draft.page, LayerStylePage::Effect(EffectId(2)), "the chosen page shows once the host applied it");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_fast_effect_sweep_applies_each_crossed_checkbox_and_ends_on_release() {
|
||||
let kinds = [EffectKind::DropShadow, EffectKind::Satin, EffectKind::OuterGlow, EffectKind::InnerGlow];
|
||||
let effects = kinds.into_iter().enumerate().map(|(i, kind)| instance(i as u32 + 1, kind, true)).collect();
|
||||
let draft = LayerStyleDraft::new(LayerStyle { effects, ..LayerStyle::default() });
|
||||
let (mut fixture, host) = rig_of(host(draft, kinds.into_iter().map(spec).collect()));
|
||||
let first = one(&fixture, Role::CHECK_BOX, "Drop Shadow");
|
||||
let last = one(&fixture, Role::CHECK_BOX, "Inner Glow");
|
||||
fixture.press(&first);
|
||||
fixture.release(&last);
|
||||
fixture.idle(2);
|
||||
assert!(host.borrow().draft.style.effects.iter().all(|effect| !effect.on));
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn cancelling_an_effect_sweep_restores_checks_and_removes_an_effect_it_added() {
|
||||
let effects = vec![instance(1, EffectKind::DropShadow, false), instance(2, EffectKind::OuterGlow, false)];
|
||||
let draft = LayerStyleDraft::new(LayerStyle { effects, ..LayerStyle::default() });
|
||||
let (mut fixture, host) = rig_of(host(draft, [EffectKind::DropShadow, EffectKind::Satin, EffectKind::OuterGlow].into_iter().map(spec).collect()));
|
||||
let first = one(&fixture, Role::CHECK_BOX, "Drop Shadow");
|
||||
let last = one(&fixture, Role::CHECK_BOX, "Outer Glow");
|
||||
fixture.press(&first);
|
||||
fixture.frame(vec![pointer::moved(last.center())]);
|
||||
{
|
||||
let host = host.borrow();
|
||||
assert_eq!(host.draft.style.effects.len(), 3);
|
||||
assert!(host.draft.style.effects.iter().all(|effect| effect.on));
|
||||
}
|
||||
fixture.key(Key::Escape, Modifiers::NONE);
|
||||
fixture.release(&last);
|
||||
fixture.idle(2);
|
||||
let host = host.borrow();
|
||||
assert_eq!(host.draft.style.effects.len(), 2);
|
||||
assert!(host.draft.style.effects.iter().all(|effect| !effect.on));
|
||||
}
|
||||
|
||||
/// A rig showing one effect of the Photoshop tables with its defaults, or `params` over them.
|
||||
fn page_rig(kind: EffectKind, params: Option<StyleParams>) -> (Fixture, Rc<RefCell<Host>>) {
|
||||
let spec = EffectSpec::photoshop(kind);
|
||||
|
||||
@@ -137,6 +137,8 @@ pub struct CxCore<'a> {
|
||||
/// For an arena root: the member activated this pass.
|
||||
pub(crate) activated_member: Option<Id>,
|
||||
pub(crate) press: PressState,
|
||||
/// The parent layout of a standalone control, used to keep a sweep within its siblings.
|
||||
pub(crate) pointer_group: Option<Id>,
|
||||
pub(crate) cursor: Option<(Cursor, CursorPriority)>,
|
||||
/// The declared cursors of the parts hovered this pass, recorded at step 8 and written at step 16.
|
||||
pub(crate) part_cursors: Vec<Cursor>,
|
||||
|
||||
@@ -265,6 +265,15 @@ impl<C: Component> Pointer for Cx<'_, C> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<C: Component> Cx<'_, C> {
|
||||
/// The value a primary-button sweep sets on this toggle. Only siblings in the same layout
|
||||
/// participate. A control that uses this must sense both clicks and drags.
|
||||
pub fn swept_toggle(&self, on: Option<bool>) -> Option<bool> {
|
||||
let group = self.pointer_group?;
|
||||
crate::runtime::toggle_sweep::value(self, group, on)
|
||||
}
|
||||
}
|
||||
|
||||
/// The cursor requests of the hovered parts' declared cursors, in registration order.
|
||||
pub(crate) fn declared_cursor(core: &CxCore<'_>) -> Option<Cursor> {
|
||||
core.part_cursors.first().cloned()
|
||||
|
||||
@@ -7,15 +7,17 @@
|
||||
//!
|
||||
//! [`SweepApply`] is the one host-side reader of those events: it turns each into the step the host applies.
|
||||
|
||||
use super::ItemsHooks;
|
||||
use super::marquee::MarqueeDrag;
|
||||
use super::{ItemsHooks, Placement};
|
||||
use crate::contract::collection::{
|
||||
CollectionEvent, CollectionProps, ColumnKind, DropAt, DropPayload, DropPlace, ListDrag, PendingDrop, ReorderMove, ToggleColumn, ToggleEdit,
|
||||
};
|
||||
use crate::contract::reorder;
|
||||
use crate::contract::{Collection, Cx, DragPreview, DropMark, DropTarget, Pointer as _};
|
||||
use crate::runtime::drag;
|
||||
use crate::runtime::egui::areas;
|
||||
use crate::runtime::env::Label;
|
||||
use crate::runtime::toggle_sweep::{self, Segment, Travel};
|
||||
use craft_behavior::{
|
||||
Axis, CancelReason, ColumnKey, DropOperation, EditEvent, Flow, GestureId, ItemLayout, Mixed, NavShape, Outline, PointerButton, PressCancel,
|
||||
PressPhase, ScrollPos,
|
||||
@@ -115,6 +117,7 @@ struct Sweep<K> {
|
||||
/// The modifiers held at the first press, which every flip of the sweep carries.
|
||||
mods: craft_keymap::Mods,
|
||||
crossed: Vec<usize>,
|
||||
travel: Travel,
|
||||
/// Where the cell the sweep began in lies across the rows (logical): it flips the crossed rows whose cell of the
|
||||
/// column lies there too, so a sweep down a toggle column passes sub-rows by and one down sub-rows passes rows by.
|
||||
span: egui::Rangef,
|
||||
@@ -461,9 +464,19 @@ impl<C: Collection> ItemsHooks<'_, '_, C> {
|
||||
/// exclusive column, turning a cell on turns the column's other cells off. A cell that is not open to toggling
|
||||
/// does nothing and starts no sweep.
|
||||
pub(super) fn begin_toggle(&mut self, cx: &mut Cx<'_, C>, at: usize, (column, toggle, cell): (ColumnKey, ToggleColumn, Rect)) {
|
||||
if toggle.sweepable {
|
||||
if toggle.sweepable
|
||||
&& let Some(start) = cx.core.press.phase.start()
|
||||
{
|
||||
let mods = crate::runtime::pointer::frame_raw(&cx.core.ctx).mods;
|
||||
self.drags.sweep = Some(Sweep { column: column.clone(), on: false, mods, crossed: vec![at], span: cell.x_range(), open: Vec::new() });
|
||||
self.drags.sweep = Some(Sweep {
|
||||
column: column.clone(),
|
||||
on: false,
|
||||
mods,
|
||||
crossed: vec![at],
|
||||
travel: Travel::new(start.origin),
|
||||
span: cell.x_range(),
|
||||
open: Vec::new(),
|
||||
});
|
||||
}
|
||||
match self.flip_toggle(cx, at, column, toggle) {
|
||||
Some(on) => {
|
||||
@@ -492,24 +505,53 @@ impl<C: Collection> ItemsHooks<'_, '_, C> {
|
||||
Some(on)
|
||||
}
|
||||
|
||||
fn sweep_to(&mut self, cx: &mut Cx<'_, C>, layout: &C::ItemLayout, rect: Rect, offset: ScrollPos, rtl: bool, pos: Pos2) {
|
||||
let Some(sweep) = self.drags.sweep.clone() else { return };
|
||||
if pos.y < rect.min.y {
|
||||
return;
|
||||
fn sweep_to(&mut self, cx: &mut Cx<'_, C>, layout: &C::ItemLayout, place: Placement, phase: PressPhase) {
|
||||
let Some(sweep) = &mut self.drags.sweep else { return };
|
||||
let input = crate::runtime::pointer::pass_pointer(&cx.ctx);
|
||||
let events = match phase {
|
||||
PressPhase::Down { start, .. } => toggle_sweep::after_press(&input.events, start),
|
||||
_ => &input.events,
|
||||
};
|
||||
let mut path = Vec::new();
|
||||
sweep.travel.advance(events, input.frame.as_ref().map_or(0.0, |frame| frame.slop), &mut path);
|
||||
for segment in path {
|
||||
self.sweep_segment(cx, layout, place, segment);
|
||||
}
|
||||
}
|
||||
|
||||
fn sweep_segment(&mut self, cx: &mut Cx<'_, C>, layout: &C::ItemLayout, place: Placement, segment: Segment) {
|
||||
let Placement { rect, offset, rtl } = place;
|
||||
let Some(sweep) = &self.drags.sweep else { return };
|
||||
let (column, on, mods, span) = (sweep.column.clone(), sweep.on, sweep.mods, sweep.span);
|
||||
let parent = cx.response.layer_id;
|
||||
let layer = self.xf.map_or(parent, |_| areas::body_layer(parent, cx.id));
|
||||
let clip = rect.intersect(cx.visible);
|
||||
let clip = self.xf.map_or(clip, |map| Rect::from_min_max(map.to_layer(clip.min), map.to_layer(clip.max)));
|
||||
let mut rows = Vec::new();
|
||||
layout.visible(offset, rect.size(), &mut rows);
|
||||
if segment.1.y < segment.0.y {
|
||||
rows.reverse();
|
||||
}
|
||||
let Some(now) = layout.hit(Self::logical(layout, rect, rtl, pos), offset) else { return };
|
||||
let Some(&last) = sweep.crossed.last() else { return };
|
||||
let rows: Vec<usize> = if now >= last { (last + 1..=now).collect() } else { (now..last).rev().collect() };
|
||||
for at in rows {
|
||||
if let Some(held) = &mut self.drags.sweep {
|
||||
held.crossed.push(at);
|
||||
if self.drags.sweep.as_ref().is_some_and(|sweep| sweep.crossed.contains(&at))
|
||||
|| !self.source.enabled(at)
|
||||
|| !self.toggle_open(at, &column)
|
||||
|| self.source.toggled(at, &column) == on
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let in_span = self
|
||||
let below_frozen = Rect::from_min_max(Pos2::new(rect.min.x, rect.min.y + layout.frozen_band(at)), rect.max);
|
||||
let crossed = self
|
||||
.row_cells(layout, at, offset)
|
||||
.into_iter()
|
||||
.any(|(key, cell)| key == sweep.column && cell.min.x < sweep.span.max && cell.max.x > sweep.span.min);
|
||||
if in_span && self.source.enabled(at) && self.toggle_open(at, &sweep.column) && self.source.toggled(at, &sweep.column) != sweep.on {
|
||||
self.emit_toggle(cx, at, &sweep.column, sweep.on, sweep.mods);
|
||||
.filter(|(key, cell)| *key == column && cell.min.x < span.max && cell.max.x > span.min)
|
||||
.map(|(_, cell)| self.to_screen(layout, rect, cell, rtl).intersect(clip).intersect(below_frozen))
|
||||
.any(|cell| toggle_sweep::crosses_visible(&cx.ctx, layer, cell, &[segment]));
|
||||
if crossed {
|
||||
if let Some(sweep) = &mut self.drags.sweep {
|
||||
sweep.crossed.push(at);
|
||||
}
|
||||
self.emit_toggle(cx, at, &column, on, mods);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -668,6 +710,9 @@ impl<C: Collection> ItemsHooks<'_, '_, C> {
|
||||
self.drags.pending = None;
|
||||
let free = matches!(layout.nav(), NavShape::Spatial);
|
||||
let phase = cx.core.press.phase;
|
||||
if phase.is_press() && !matches!(phase, PressPhase::Cancel { .. }) {
|
||||
self.sweep_to(cx, layout, Placement { rect, offset, rtl }, phase);
|
||||
}
|
||||
// The pointer comes in screen space; the rows and a move's offset are in the rows' own space.
|
||||
let xf = self.xf;
|
||||
let layer = |point: Pos2| xf.map_or(point, |map| map.to_layer(point));
|
||||
@@ -678,9 +723,9 @@ impl<C: Collection> ItemsHooks<'_, '_, C> {
|
||||
.then(|| layout.hit(Self::logical(layout, rect, rtl, origin), offset))
|
||||
.flatten()
|
||||
.filter(|&at| self.source.enabled(at) && !self.source.section_stop(at) && comp.can_drag(&self.source.key(at)));
|
||||
if self.drags.sweep.is_some() {
|
||||
self.sweep_to(cx, layout, rect, offset, rtl, layer(pos));
|
||||
} else if let Some(at) = hit {
|
||||
if self.drags.sweep.is_none()
|
||||
&& let Some(at) = hit
|
||||
{
|
||||
if free {
|
||||
self.free_move(cx, origin, layer(pos));
|
||||
} else if (props.reorder.is_some() || props.drag_payload.is_some()) && self.drags.grabbed.is_none() {
|
||||
|
||||
@@ -383,6 +383,7 @@ fn blank_core<'a>(
|
||||
member_of: None,
|
||||
lent: Default::default(),
|
||||
activation: None,
|
||||
pointer_group: None,
|
||||
injected: None,
|
||||
keep_open: false,
|
||||
part_clicked: false,
|
||||
@@ -1788,6 +1789,7 @@ fn run_passes(
|
||||
let env = begun.env();
|
||||
let id = resolved.id;
|
||||
let mut core = blank_core(env.view(), resolved, stage, begun.ctx.clone(), env.ink, steps::inert_response(ui, id), begun.step1.command.clone());
|
||||
core.pointer_group = Some(ui.scope_id());
|
||||
core.faded = begun.facts.faded && !resolved.enabled;
|
||||
// 6 to 16, in the host's `Ui`, once per call of the host.
|
||||
let mut host = t.host(HostCx { ui: &*ui, env, id, label: &begun.step1.label, size: sizes.size });
|
||||
|
||||
@@ -60,6 +60,33 @@ pub(crate) fn layer_at(ctx: &Context, point: Pos2) -> Option<LayerId> {
|
||||
crate::runtime::sampler::layer_at(ctx, point).or_else(|| ctx.layer_id_at(point))
|
||||
}
|
||||
|
||||
/// Whether some point of a screen segment belongs to this layer. A layer can begin or end only
|
||||
/// at an area edge, so testing one point between consecutive edges also finds subpixel gaps.
|
||||
pub(crate) fn layer_between(ctx: &Context, layer: LayerId, from: Pos2, to: Pos2) -> bool {
|
||||
let visible = |point| layer_at(ctx, point) == Some(layer);
|
||||
if visible(from) || visible(to) {
|
||||
return true;
|
||||
}
|
||||
if from == to {
|
||||
return false;
|
||||
}
|
||||
let mut cuts = vec![0.0, 1.0];
|
||||
let delta = to - from;
|
||||
let path = Rect::from_two_pos(from, to);
|
||||
let hole = crate::runtime::sampler::hole_of_pass(ctx);
|
||||
let bounds = interactive_layers(ctx, None).into_iter().map(|(_, rect)| rect).chain(hole.iter().flat_map(|hole| hole.bounds()));
|
||||
for bounds in bounds.filter(|rect| rect.intersects(path)) {
|
||||
let edges =
|
||||
[(bounds.min.x, from.x, delta.x), (bounds.max.x, from.x, delta.x), (bounds.min.y, from.y, delta.y), (bounds.max.y, from.y, delta.y)];
|
||||
cuts.extend(
|
||||
edges.into_iter().filter(|(_, _, step)| *step != 0.0).map(|(edge, start, step)| (edge - start) / step).filter(|t| 0.0 < *t && *t < 1.0),
|
||||
);
|
||||
}
|
||||
cuts.sort_unstable_by(f32::total_cmp);
|
||||
cuts.dedup();
|
||||
cuts.iter().copied().any(|t| visible(from.lerp(to, t))) || cuts.windows(2).any(|ends| visible(from.lerp(to, f32::midpoint(ends[0], ends[1]))))
|
||||
}
|
||||
|
||||
/// The topmost layer under a screen position, as if `skipped` were not shown: the layer below a window that moves
|
||||
/// with the pointer. A modal layer still holds the input, as in `layer_at`.
|
||||
pub(crate) fn layer_at_without(ctx: &Context, point: Pos2, skipped: LayerId) -> Option<LayerId> {
|
||||
|
||||
@@ -36,6 +36,7 @@ pub mod requests;
|
||||
pub mod sampler;
|
||||
pub(crate) mod shift;
|
||||
pub mod toast;
|
||||
pub(crate) mod toggle_sweep;
|
||||
pub mod wheel;
|
||||
pub mod windows;
|
||||
pub mod words;
|
||||
|
||||
@@ -122,6 +122,10 @@ pub(crate) struct Hole {
|
||||
}
|
||||
|
||||
impl Hole {
|
||||
pub(crate) fn bounds(&self) -> impl Iterator<Item = Rect> + '_ {
|
||||
std::iter::once(self.rect).chain(self.covers.iter().copied())
|
||||
}
|
||||
|
||||
/// The one let-through test: the canvas answers a pointer at `at` when `at` lies in its rect and no layer lies
|
||||
/// over its layer there.
|
||||
pub(crate) fn answers(&self, at: Pos2) -> bool {
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
//! A primary press on a standalone toggle can set the other toggles of its layout as it sweeps.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft_behavior::{PointerButton, PointerEvent, PressPhase, PressStart};
|
||||
use egui::{Context, Id, IdSet, LayerId, Pos2, Rect};
|
||||
|
||||
use crate::contract::{CxCore, Pointer as _};
|
||||
use crate::runtime::egui::{areas, pass};
|
||||
use crate::runtime::frame::{PerViewport, Stored};
|
||||
use crate::runtime::pointer::{self, PassPointer};
|
||||
|
||||
pub(crate) type Segment = (Pos2, Pos2);
|
||||
|
||||
/// Pointer travel of one primary press, shared by standalone checks and collection columns.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct Travel {
|
||||
origin: Pos2,
|
||||
last: Option<Pos2>,
|
||||
dragging: bool,
|
||||
released: bool,
|
||||
}
|
||||
|
||||
impl Travel {
|
||||
pub(crate) fn new(origin: Pos2) -> Self {
|
||||
Self { origin, last: Some(origin), dragging: false, released: false }
|
||||
}
|
||||
|
||||
pub(crate) fn advance(&mut self, events: &[PointerEvent], slop: f32, path: &mut Vec<Segment>) {
|
||||
if self.released {
|
||||
return;
|
||||
}
|
||||
for event in events {
|
||||
let (at, released) = match event {
|
||||
PointerEvent::Moved { at, .. } => (*at, false),
|
||||
PointerEvent::Released { button: PointerButton::Primary, pos, .. } => (*pos, true),
|
||||
PointerEvent::Gone => {
|
||||
self.last = None;
|
||||
continue;
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
let from = if self.dragging { self.last.unwrap_or(at) } else { self.origin };
|
||||
self.last = Some(at);
|
||||
self.released = released;
|
||||
self.dragging |= self.origin.distance(at) > slop;
|
||||
if self.dragging && from != at {
|
||||
path.push((from, at));
|
||||
}
|
||||
if released {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Ignore any motion in the batch before this press began.
|
||||
pub(crate) fn after_press(events: &[PointerEvent], press: PressStart) -> &[PointerEvent] {
|
||||
events
|
||||
.iter()
|
||||
.position(|event| {
|
||||
matches!(event, PointerEvent::Pressed { button: PointerButton::Primary, pos, time, .. } if *time == press.time && *pos == press.origin)
|
||||
})
|
||||
.map_or(events, |at| &events[at + 1..])
|
||||
}
|
||||
|
||||
struct Sweep {
|
||||
owner: Id,
|
||||
group: Id,
|
||||
on: bool,
|
||||
travel: Travel,
|
||||
visited: IdSet,
|
||||
}
|
||||
|
||||
struct CompletedSweep {
|
||||
sweep: Sweep,
|
||||
path: Arc<Vec<Segment>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Record {
|
||||
pass: u64,
|
||||
sweep: Option<Sweep>,
|
||||
path: Arc<Vec<Segment>>,
|
||||
// A press and move may arrive together; siblings drawn before the pressed control get that
|
||||
// initial path on the following pass. Visited ids keep the edit from applying twice.
|
||||
replay_first_path: bool,
|
||||
// The replay survives opening another gesture in the same pass.
|
||||
completed: Option<CompletedSweep>,
|
||||
}
|
||||
|
||||
impl Stored for Record {}
|
||||
|
||||
impl Record {
|
||||
fn advance(&mut self, pass: u64, input: &PassPointer, cancelled: bool) {
|
||||
if self.pass == pass {
|
||||
return;
|
||||
}
|
||||
self.completed = None;
|
||||
if !self.replay_first_path {
|
||||
Arc::make_mut(&mut self.path).clear();
|
||||
}
|
||||
let replay = std::mem::take(&mut self.replay_first_path);
|
||||
let previous = std::mem::replace(&mut self.pass, pass);
|
||||
if cancelled || previous.saturating_add(1) != pass {
|
||||
self.sweep = None;
|
||||
return;
|
||||
}
|
||||
if self.sweep.as_ref().is_some_and(|sweep| sweep.travel.released) {
|
||||
if replay {
|
||||
self.finish();
|
||||
} else {
|
||||
self.sweep = None;
|
||||
}
|
||||
return;
|
||||
}
|
||||
let next_press = input.events.iter().position(|event| matches!(event, PointerEvent::Pressed { button: PointerButton::Primary, .. }));
|
||||
if let Some(sweep) = &mut self.sweep {
|
||||
// Input following the first press is held for the next pass, which can then carry both its release and a new press.
|
||||
let events = &input.events[..next_press.unwrap_or(input.events.len())];
|
||||
sweep.travel.advance(events, input.frame.as_ref().map_or(0.0, |frame| frame.slop), Arc::make_mut(&mut self.path));
|
||||
if next_press.is_some() && sweep.travel.released {
|
||||
self.finish();
|
||||
return;
|
||||
}
|
||||
}
|
||||
if next_press.is_some() || (!input.primary_down && self.sweep.as_ref().is_some_and(|sweep| !sweep.travel.released)) {
|
||||
self.sweep = None;
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(&mut self) {
|
||||
self.completed = self.sweep.take().map(|sweep| CompletedSweep { sweep, path: std::mem::take(&mut self.path) });
|
||||
}
|
||||
|
||||
fn start(&mut self, owner: Id, group: Id, press: PressStart, on: bool, input: &PassPointer) {
|
||||
let mut sweep = Sweep { owner, group, on, travel: Travel::new(press.origin), visited: IdSet::default() };
|
||||
let path = Arc::make_mut(&mut self.path);
|
||||
path.clear();
|
||||
sweep.travel.advance(after_press(&input.events, press), input.frame.as_ref().map_or(0.0, |frame| frame.slop), path);
|
||||
self.replay_first_path = !path.is_empty();
|
||||
self.sweep = Some(sweep);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn value(cx: &CxCore<'_>, group: Id, on: Option<bool>) -> Option<bool> {
|
||||
let ctx = &cx.ctx;
|
||||
let viewport = pass::current_viewport(ctx);
|
||||
let pass = pointer::pass_of(ctx);
|
||||
let input = pointer::pass_pointer(ctx);
|
||||
let cancelled = pointer::cancel_of_pass(ctx).is_some();
|
||||
let layer = cx.response.layer_id;
|
||||
let enabled = cx.resolved.enabled && !cx.resolved.read_only;
|
||||
let eligible = |sweep: &Sweep| enabled && sweep.group == group && sweep.travel.dragging;
|
||||
let completed = PerViewport::<Record>::with(ctx, viewport, |record| {
|
||||
record.advance(pass, &input, cancelled);
|
||||
let finished = record.completed.as_ref().filter(|finished| eligible(&finished.sweep))?;
|
||||
let sweep = &finished.sweep;
|
||||
if sweep.owner == cx.id {
|
||||
return Some((sweep.on, None));
|
||||
}
|
||||
(!sweep.visited.contains(&cx.id)).then(|| (sweep.on, Some(Arc::clone(&finished.path))))
|
||||
})
|
||||
.and_then(|(on, path)| {
|
||||
if let Some(path) = path {
|
||||
if !crosses_visible(ctx, layer, cx.visible, &path) {
|
||||
return None;
|
||||
}
|
||||
PerViewport::<Record>::with(ctx, viewport, |record| {
|
||||
if let Some(finished) = &mut record.completed {
|
||||
finished.sweep.visited.insert(cx.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
Some(on)
|
||||
});
|
||||
let ready = PerViewport::<Record>::with(ctx, viewport, |record| {
|
||||
match cx.press().phase {
|
||||
PressPhase::Down { start, .. } if start.button == PointerButton::Primary && enabled => {
|
||||
record.start(cx.id, group, start, !completed.or(on).unwrap_or(false), &input);
|
||||
}
|
||||
PressPhase::Cancel { .. } if record.sweep.as_ref().is_some_and(|sweep| sweep.owner == cx.id) => record.sweep = None,
|
||||
_ => {}
|
||||
}
|
||||
let sweep = record.sweep.as_ref().filter(|sweep| eligible(sweep))?;
|
||||
if sweep.owner == cx.id {
|
||||
return Some((sweep.on, None, record.replay_first_path));
|
||||
}
|
||||
(!record.path.is_empty() && !sweep.visited.contains(&cx.id)).then(|| (sweep.on, Some(Arc::clone(&record.path)), false))
|
||||
});
|
||||
let Some(ready) = ready else { return completed };
|
||||
let (on, path, replay) = ready;
|
||||
if replay {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
if let Some(path) = path {
|
||||
if !crosses_visible(ctx, layer, cx.visible, &path) {
|
||||
return completed;
|
||||
}
|
||||
PerViewport::<Record>::with(ctx, viewport, |record| {
|
||||
if let Some(sweep) = &mut record.sweep {
|
||||
sweep.visited.insert(cx.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
Some(on)
|
||||
}
|
||||
|
||||
/// Keep the entire part of the path inside the rect: a floating layer may cover only part of it.
|
||||
fn clipped((from, to): Segment, rect: Rect) -> Option<Segment> {
|
||||
if !rect.is_positive() {
|
||||
return None;
|
||||
}
|
||||
let delta = to - from;
|
||||
let (mut start, mut end) = (0.0_f32, 1.0_f32);
|
||||
for (step, low, high, from) in [(delta.x, rect.min.x, rect.max.x, from.x), (delta.y, rect.min.y, rect.max.y, from.y)] {
|
||||
if step == 0.0 {
|
||||
if from < low || from > high {
|
||||
return None;
|
||||
}
|
||||
} else {
|
||||
let (a, b) = ((low - from) / step, (high - from) / step);
|
||||
start = start.max(a.min(b));
|
||||
end = end.min(a.max(b));
|
||||
}
|
||||
}
|
||||
(start <= end).then(|| (from + delta * start, from + delta * end))
|
||||
}
|
||||
|
||||
pub(crate) fn crosses_visible(ctx: &Context, layer: LayerId, rect: Rect, path: &[Segment]) -> bool {
|
||||
let map = areas::layer_map(ctx, layer);
|
||||
let rect = map.map_or(rect, |map| Rect::from_min_max(map.to_screen(rect.min), map.to_screen(rect.max)));
|
||||
path.iter().copied().filter_map(|segment| clipped(segment, rect)).any(|(from, to)| areas::layer_between(ctx, layer, from, to))
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Collections with columns and reordering, and the trials of the header's sideways reveal and its bound layout.
|
||||
|
||||
use super::kit::{Count, Dismissed, ROW_H, Row};
|
||||
use craft_behavior::{ColumnKey, ColumnWidth, ItemSource, Selection, SpanLayout};
|
||||
use craft_behavior::{CanvasTransform, ColumnKey, ColumnWidth, ItemSource, Selection, SpanLayout};
|
||||
use craft_ui::contract::{
|
||||
Bind, BindMut, Collection, CollectionEvent, CollectionProps, CollectionResponse, ColumnEvent, ColumnLayout, ColumnSpec, Common, Component,
|
||||
ContainerProps, Cx, Props as _, Role, ShowCollection as _,
|
||||
@@ -35,6 +35,11 @@ impl<'a> Table<'a> {
|
||||
self.column_layout = Some(layout);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn transformed(mut self, transform: CanvasTransform) -> Self {
|
||||
self.props = self.props.transform(transform);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Component for Table<'_> {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use super::kit::{Count, Dismissed, Row};
|
||||
use super::table::Table;
|
||||
use craft_behavior::{ColumnKey, ColumnWidth, ItemSource, keyed};
|
||||
use craft_behavior::{CanvasTransform, ColumnKey, ColumnWidth, ItemSource, keyed};
|
||||
use craft_ui::contract::{
|
||||
CollectionEvent, CollectionProps, CollectionResponse, ColumnEvent, ColumnKind, ColumnSpec, Props as _, ShowCollection as _, ToggleColumn,
|
||||
};
|
||||
@@ -181,6 +181,58 @@ fn a_keyed_slice_reports_toggle_presses_and_sweeps_by_key() {
|
||||
}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_collection_sweep_follows_each_move_in_the_same_frame() {
|
||||
let scene = Scene::default();
|
||||
let mut frames = Frames::new();
|
||||
let rows = [0, 1, 2];
|
||||
let mut show = |ui: &mut Ui| {
|
||||
let props = CollectionProps::new().columns(vec![
|
||||
ColumnSpec::new(NAME, "Name", ColumnWidth::Fixed(COL)),
|
||||
ColumnSpec::new(MUTE, "Mute", ColumnWidth::Fixed(COL)).kind(ColumnKind::Toggle(ToggleColumn::sweepable())),
|
||||
]);
|
||||
show_table(ui, props, &keyed(&rows, |row| *row), &scene);
|
||||
};
|
||||
frames.idle(3, &mut show);
|
||||
let cell = |row| Pos2::new(ORIGIN.x + COL * 1.5, scene.row(row).center().y);
|
||||
let (first, last) = (cell(0), cell(2));
|
||||
let outside_column = Vec2::new(-COL, 0.0);
|
||||
frames.frame(vec![pointer::moved(first)], &mut show);
|
||||
frames.frame(vec![pointer::press(first)], &mut show);
|
||||
frames.frame(vec![pointer::moved(first + outside_column), pointer::moved(last + outside_column), pointer::moved(last)], &mut show);
|
||||
frames.frame(vec![pointer::release(last)], &mut show);
|
||||
assert_eq!(scene.toggles(), vec![(0, true), (2, true)]);
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_sweep_uses_the_transformed_collection_body() {
|
||||
let scene = Scene::default();
|
||||
let mut frames = Frames::new();
|
||||
let scale = 0.75;
|
||||
let offset = Vec2::new(18.0, 7.0);
|
||||
let rows = [0, 1, 2];
|
||||
let mut show = |ui: &mut Ui| {
|
||||
let props = CollectionProps::new()
|
||||
.columns(vec![ColumnSpec::new(NAME, "Name", ColumnWidth::Fixed(COL)), ColumnSpec::toggle(MUTE, "Mute", ToggleColumn::sweepable())]);
|
||||
in_region(ui, Rect::from_min_size(ORIGIN, VIEW), |ui| {
|
||||
let source = keyed(&rows, |row| *row);
|
||||
let out = Table::new(props).id_salt("zoomed").transformed(CanvasTransform::new(scale, offset)).show_items(ui, &source, &mut |key, cx| {
|
||||
scene.note(*key, cx.rect);
|
||||
Row::new()
|
||||
});
|
||||
scene.take(out);
|
||||
});
|
||||
};
|
||||
frames.idle(3, &mut show);
|
||||
let origin = scene.row(0).min;
|
||||
let cell = |row| {
|
||||
let local = Pos2::new(ORIGIN.x + COL + 10.0, scene.row(row).center().y);
|
||||
origin + (local - origin) * scale + offset
|
||||
};
|
||||
pointer::drag(&mut frames, cell(0), cell(2) - cell(0), &mut show);
|
||||
assert_eq!(scene.toggles(), vec![(0, true), (1, true), (2, true)]);
|
||||
}
|
||||
|
||||
/// A toggle column's key flips that column on every selected row as one gesture, while Space keeps flipping the first
|
||||
/// toggle column.
|
||||
#[trial]
|
||||
|
||||
@@ -63,7 +63,7 @@ impl Component for Checkbox<'_> {
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
Sense::CLICK | Sense::FOCUS
|
||||
Sense::CLICK | Sense::DRAG | Sense::FOCUS
|
||||
}
|
||||
|
||||
fn bind(&mut self) -> Option<BindMut<'_, bool>> {
|
||||
@@ -71,9 +71,13 @@ impl Component for Checkbox<'_> {
|
||||
}
|
||||
|
||||
fn update(&mut self, cx: &mut Cx<'_, Self>) {
|
||||
if cx.activation().is_some() {
|
||||
let on = cx.value().copied().unwrap_or(false);
|
||||
cx.set(!on);
|
||||
let on = cx.value().copied();
|
||||
if let Some(swept) = cx.swept_toggle(on) {
|
||||
if on != Some(swept) {
|
||||
cx.set(swept);
|
||||
}
|
||||
} else if cx.activation().is_some() {
|
||||
cx.set(!on.unwrap_or(false));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
//! Dragging a checkbox sets the related controls the pointer crosses.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use craft_ui::choice::Checkbox;
|
||||
use craft_ui::contract::{Bind, Props as _, Show as _, ShowContainer as _};
|
||||
use craft_ui::layout_components::Stack;
|
||||
use craft_ui::testing::{Fixture, pointer, trial};
|
||||
use egui::{Area, Id, LayerId, Order, Pos2, Rect, emath::TSTransform};
|
||||
|
||||
#[trial]
|
||||
fn a_checkbox_sweep_keeps_its_group_and_skips_disabled_boxes() {
|
||||
let values = Rc::new(RefCell::new([true, false, true, true, true]));
|
||||
let shown = values.clone();
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut values = shown.borrow_mut();
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
for (index, label) in ["Above", "Already clear", "Disabled", "Start"].into_iter().enumerate() {
|
||||
Checkbox::new(Bind::bound(&mut values[index])).label(label).enabled(index != 2).show(ui);
|
||||
}
|
||||
});
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
Checkbox::new(Bind::bound(&mut values[4])).label("Other group").show(ui);
|
||||
});
|
||||
});
|
||||
fixture.settle();
|
||||
let above = fixture.by_label("Above").expect("above");
|
||||
let start = fixture.by_label("Start").expect("start");
|
||||
let other = fixture.by_label("Other group").expect("other group");
|
||||
fixture.press(&start);
|
||||
fixture.frame(vec![pointer::moved(above.center())]);
|
||||
fixture.release(&other);
|
||||
fixture.idle(2);
|
||||
assert_eq!(*values.borrow(), [false, false, true, false, true]);
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_checkbox_sweep_includes_the_release_position() {
|
||||
let values = Rc::new(RefCell::new([false, false, false]));
|
||||
let shown = values.clone();
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut values = shown.borrow_mut();
|
||||
for (value, label) in values.iter_mut().zip(["First", "Middle", "Last"]) {
|
||||
Checkbox::new(Bind::bound(value)).label(label).show(ui);
|
||||
}
|
||||
});
|
||||
fixture.settle();
|
||||
let first = fixture.by_label("First").expect("first");
|
||||
let last = fixture.by_label("Last").expect("last");
|
||||
fixture.press(&last);
|
||||
fixture.release(&first);
|
||||
fixture.idle(2);
|
||||
assert_eq!(*values.borrow(), [true, true, true]);
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_completed_checkbox_sweep_replays_before_the_next_press() {
|
||||
let values = Rc::new(RefCell::new([false; 3]));
|
||||
let shown = values.clone();
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut values = shown.borrow_mut();
|
||||
for (value, label) in values.iter_mut().zip(["Earlier sibling", "Sweep start", "Next checkbox"]) {
|
||||
Checkbox::new(Bind::bound(value)).label(label).show(ui);
|
||||
}
|
||||
});
|
||||
fixture.settle();
|
||||
let earlier = fixture.by_label("Earlier sibling").expect("earlier").center();
|
||||
let start = fixture.by_label("Sweep start").expect("start").center();
|
||||
let next = fixture.by_label("Next checkbox").expect("next").center();
|
||||
|
||||
fixture.frame(vec![pointer::moved(start)]);
|
||||
fixture.frame(vec![pointer::press(start), pointer::moved(earlier), pointer::release(earlier)]);
|
||||
assert_eq!(*values.borrow(), [false; 3], "the first frame only delivers the press");
|
||||
fixture.frame(vec![pointer::moved(next), pointer::press(next)]);
|
||||
assert_eq!(*values.borrow(), [true, true, false], "the completed sweep edits the earlier sibling even as the next press starts");
|
||||
fixture.frame(vec![pointer::release(next)]);
|
||||
fixture.idle(2);
|
||||
assert_eq!(*values.borrow(), [true, true, true], "the next click still toggles its own checkbox");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_completed_checkbox_sweep_allows_an_immediate_click_on_its_owner() {
|
||||
for batched_click in [false, true] {
|
||||
let values = Rc::new(RefCell::new([false; 2]));
|
||||
let shown = values.clone();
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut values = shown.borrow_mut();
|
||||
for (value, label) in values.iter_mut().zip(["Crossed checkbox", "Sweep owner"]) {
|
||||
Checkbox::new(Bind::bound(value)).label(label).show(ui);
|
||||
}
|
||||
});
|
||||
fixture.settle();
|
||||
let crossed = fixture.by_label("Crossed checkbox").expect("crossed").center();
|
||||
let owner = fixture.by_label("Sweep owner").expect("owner").center();
|
||||
|
||||
fixture.frame(vec![pointer::moved(owner)]);
|
||||
fixture.frame(vec![pointer::press(owner), pointer::moved(crossed), pointer::release(crossed)]);
|
||||
let mut click = vec![pointer::moved(owner), pointer::press(owner)];
|
||||
if batched_click {
|
||||
click.push(pointer::release(owner));
|
||||
}
|
||||
fixture.frame(click);
|
||||
if !batched_click {
|
||||
fixture.frame(vec![pointer::release(owner)]);
|
||||
}
|
||||
fixture.idle(2);
|
||||
assert_eq!(*values.borrow(), [true, false], "the next click toggles the same owner (batched: {batched_click})");
|
||||
}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_checkbox_sweep_uses_an_exposed_sliver_but_skips_covered_and_clipped_boxes() {
|
||||
let values = Rc::new(RefCell::new([false; 5]));
|
||||
let shown = values.clone();
|
||||
let covers = Rc::new(RefCell::new(Vec::<Rect>::new()));
|
||||
let overlays = covers.clone();
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut values = shown.borrow_mut();
|
||||
let clip = ui.clip_rect();
|
||||
for (i, (value, label)) in values.iter_mut().zip(["Start", "Sliver", "Covered", "Clipped", "End"]).enumerate() {
|
||||
if i == 3 {
|
||||
ui.set_clip_rect(Rect::from_min_max(clip.min, clip.min));
|
||||
}
|
||||
Checkbox::new(Bind::bound(value)).label(label).show(ui);
|
||||
ui.set_clip_rect(clip);
|
||||
}
|
||||
for (i, rect) in overlays.borrow().iter().enumerate() {
|
||||
let id = Id::unique(("checkbox-sweep-cover", i));
|
||||
let pos = Pos2::new(rect.min.x.floor(), rect.min.y.floor());
|
||||
ui.ctx().set_transform_layer(LayerId::new(Order::Foreground, id), TSTransform::from_translation(rect.min - pos));
|
||||
Area::new(id).order(Order::Foreground).fixed_pos(pos).default_size(rect.size()).show(ui.ctx(), |ui| {
|
||||
ui.set_min_size(rect.size());
|
||||
});
|
||||
}
|
||||
});
|
||||
fixture.settle();
|
||||
let start = fixture.by_label("Start").expect("start");
|
||||
let sliver = fixture.by_label("Sliver").expect("sliver").rect;
|
||||
let covered = fixture.by_label("Covered").expect("covered").rect;
|
||||
let end = fixture.by_label("End").expect("end");
|
||||
let edge = sliver.top() + 2.2;
|
||||
let x = start.center().x;
|
||||
*covers.borrow_mut() = vec![
|
||||
Rect::from_min_max(Pos2::new(x - 12.0, sliver.top() - 1.0), Pos2::new(x + 12.0, edge)),
|
||||
Rect::from_min_max(Pos2::new(x - 12.0, edge + 0.15), Pos2::new(x + 12.0, sliver.bottom() + 1.0)),
|
||||
Rect::from_min_max(Pos2::new(x - 12.0, covered.top() - 1.0), Pos2::new(x + 12.0, covered.bottom() + 1.0)),
|
||||
];
|
||||
fixture.settle();
|
||||
fixture.press(&start);
|
||||
fixture.frame(vec![pointer::moved(Pos2::new(x, end.center().y))]);
|
||||
fixture.release(&end);
|
||||
fixture.idle(2);
|
||||
assert_eq!(*values.borrow(), [true, true, false, false, true]);
|
||||
}
|
||||
@@ -7,6 +7,7 @@ pub(crate) mod access;
|
||||
pub(crate) mod bars;
|
||||
pub(crate) mod body;
|
||||
pub(crate) mod buttons;
|
||||
pub(crate) mod checkbox_sweep;
|
||||
pub(crate) mod commands;
|
||||
pub(crate) mod contract;
|
||||
pub(crate) mod disabled_fade;
|
||||
|
||||
Reference in New Issue
Block a user