summaryrefslogtreecommitdiffstats
path: root/native
diff options
context:
space:
mode:
Diffstat (limited to 'native')
-rw-r--r--native/src/command.rs10
-rw-r--r--native/src/command/action.rs7
-rw-r--r--native/src/element.rs37
-rw-r--r--native/src/overlay.rs9
-rw-r--r--native/src/overlay/element.rs10
-rw-r--r--native/src/user_interface.rs23
-rw-r--r--native/src/widget.rs17
-rw-r--r--native/src/widget/action.rs88
-rw-r--r--native/src/widget/button.rs16
-rw-r--r--native/src/widget/column.rs19
-rw-r--r--native/src/widget/container.rs17
-rw-r--r--native/src/widget/helpers.rs4
-rw-r--r--native/src/widget/id.rs43
-rw-r--r--native/src/widget/operation.rs60
-rw-r--r--native/src/widget/operation/focusable.rs169
-rw-r--r--native/src/widget/operation/scrollable.rs35
-rw-r--r--native/src/widget/row.rs19
-rw-r--r--native/src/widget/scrollable.rs63
-rw-r--r--native/src/widget/text_input.rs63
19 files changed, 700 insertions, 9 deletions
diff --git a/native/src/command.rs b/native/src/command.rs
index 89d0f045..b0b12805 100644
--- a/native/src/command.rs
+++ b/native/src/command.rs
@@ -3,6 +3,8 @@ mod action;
pub use action::Action;
+use crate::widget;
+
use iced_futures::MaybeSend;
use std::fmt;
@@ -24,6 +26,13 @@ impl<T> Command<T> {
Self(iced_futures::Command::single(action))
}
+ /// Creates a [`Command`] that performs a [`widget::Operation`].
+ pub fn widget(operation: impl widget::Operation<T> + 'static) -> Self {
+ Self(iced_futures::Command::single(Action::Widget(
+ widget::Action::new(operation),
+ )))
+ }
+
/// Creates a [`Command`] that performs the action of the given future.
pub fn perform<A>(
future: impl Future<Output = T> + 'static + MaybeSend,
@@ -51,6 +60,7 @@ impl<T> Command<T> {
) -> Command<A>
where
T: 'static,
+ A: 'static,
{
let Command(command) = self;
diff --git a/native/src/command/action.rs b/native/src/command/action.rs
index 1bb03cef..3fb02899 100644
--- a/native/src/command/action.rs
+++ b/native/src/command/action.rs
@@ -1,5 +1,6 @@
use crate::clipboard;
use crate::system;
+use crate::widget;
use crate::window;
use iced_futures::MaybeSend;
@@ -23,6 +24,9 @@ pub enum Action<T> {
/// Run a system action.
System(system::Action<T>),
+
+ /// Run a widget action.
+ Widget(widget::Action<T>),
}
impl<T> Action<T> {
@@ -34,6 +38,7 @@ impl<T> Action<T> {
f: impl Fn(T) -> A + 'static + MaybeSend + Sync,
) -> Action<A>
where
+ A: 'static,
T: 'static,
{
use iced_futures::futures::FutureExt;
@@ -43,6 +48,7 @@ impl<T> Action<T> {
Self::Clipboard(action) => Action::Clipboard(action.map(f)),
Self::Window(window) => Action::Window(window),
Self::System(system) => Action::System(system.map(f)),
+ Self::Widget(widget) => Action::Widget(widget.map(f)),
}
}
}
@@ -56,6 +62,7 @@ impl<T> fmt::Debug for Action<T> {
}
Self::Window(action) => write!(f, "Action::Window({:?})", action),
Self::System(action) => write!(f, "Action::System({:?})", action),
+ Self::Widget(_action) => write!(f, "Action::Widget"),
}
}
}
diff --git a/native/src/element.rs b/native/src/element.rs
index cc74035e..8b994d73 100644
--- a/native/src/element.rs
+++ b/native/src/element.rs
@@ -3,6 +3,7 @@ use crate::layout;
use crate::mouse;
use crate::overlay;
use crate::renderer;
+use crate::widget;
use crate::widget::tree::{self, Tree};
use crate::{Clipboard, Layout, Length, Point, Rectangle, Shell, Widget};
@@ -248,6 +249,42 @@ where
self.widget.layout(renderer, limits)
}
+ fn operate(
+ &self,
+ tree: &mut Tree,
+ layout: Layout<'_>,
+ operation: &mut dyn widget::Operation<B>,
+ ) {
+ struct MapOperation<'a, B> {
+ operation: &'a mut dyn widget::Operation<B>,
+ }
+
+ impl<'a, T, B> widget::Operation<T> for MapOperation<'a, B> {
+ fn container(
+ &mut self,
+ id: Option<&widget::Id>,
+ operate_on_children: &mut dyn FnMut(
+ &mut dyn widget::Operation<T>,
+ ),
+ ) {
+ self.operation.container(id, &mut |operation| {
+ operate_on_children(&mut MapOperation { operation });
+ });
+ }
+
+ fn focusable(
+ &mut self,
+ state: &mut dyn widget::operation::Focusable,
+ id: Option<&widget::Id>,
+ ) {
+ self.operation.focusable(state, id);
+ }
+ }
+
+ self.widget
+ .operate(tree, layout, &mut MapOperation { operation });
+ }
+
fn on_event(
&mut self,
tree: &mut Tree,
diff --git a/native/src/overlay.rs b/native/src/overlay.rs
index c2a98693..905d3389 100644
--- a/native/src/overlay.rs
+++ b/native/src/overlay.rs
@@ -10,6 +10,7 @@ use crate::event::{self, Event};
use crate::layout;
use crate::mouse;
use crate::renderer;
+use crate::widget;
use crate::widget::tree::{self, Tree};
use crate::{Clipboard, Layout, Point, Rectangle, Shell, Size};
@@ -63,6 +64,14 @@ where
/// Reconciliates the [`Widget`] with the provided [`Tree`].
fn diff(&self, _tree: &mut Tree) {}
+ /// Applies an [`Operation`] to the [`Widget`].
+ fn operate(
+ &self,
+ _layout: Layout<'_>,
+ _operation: &mut dyn widget::Operation<Message>,
+ ) {
+ }
+
/// Processes a runtime [`Event`].
///
/// It receives:
diff --git a/native/src/overlay/element.rs b/native/src/overlay/element.rs
index de2e1f37..b919c221 100644
--- a/native/src/overlay/element.rs
+++ b/native/src/overlay/element.rs
@@ -4,6 +4,7 @@ use crate::event::{self, Event};
use crate::layout;
use crate::mouse;
use crate::renderer;
+use crate::widget;
use crate::{Clipboard, Layout, Point, Rectangle, Shell, Size, Vector};
/// A generic [`Overlay`].
@@ -102,6 +103,15 @@ where
self.overlay
.draw(renderer, theme, style, layout, cursor_position)
}
+
+ /// Applies an [`Operation`] to the [`Element`].
+ pub fn operate(
+ &self,
+ layout: Layout<'_>,
+ operation: &mut dyn widget::Operation<Message>,
+ ) {
+ self.overlay.operate(layout, operation);
+ }
}
struct Map<'a, A, B, Renderer> {
diff --git a/native/src/user_interface.rs b/native/src/user_interface.rs
index 9f3a8e21..42669f95 100644
--- a/native/src/user_interface.rs
+++ b/native/src/user_interface.rs
@@ -479,6 +479,29 @@ where
.unwrap_or(base_interaction)
}
+ /// Applies a [`widget::Operation`] to the [`UserInterface`].
+ pub fn operate(
+ &mut self,
+ renderer: &Renderer,
+ operation: &mut dyn widget::Operation<Message>,
+ ) {
+ self.root.as_widget().operate(
+ &mut self.state,
+ Layout::new(&self.base),
+ operation,
+ );
+
+ if let Some(layout) = self.overlay.as_ref() {
+ if let Some(overlay) = self.root.as_widget().overlay(
+ &mut self.state,
+ Layout::new(&self.base),
+ renderer,
+ ) {
+ overlay.operate(Layout::new(layout), operation);
+ }
+ }
+ }
+
/// Relayouts and returns a new [`UserInterface`] using the provided
/// bounds.
pub fn relayout(self, bounds: Size, renderer: &mut Renderer) -> Self {
diff --git a/native/src/widget.rs b/native/src/widget.rs
index 9a4f373a..8890b8e7 100644
--- a/native/src/widget.rs
+++ b/native/src/widget.rs
@@ -17,6 +17,7 @@ pub mod column;
pub mod container;
pub mod helpers;
pub mod image;
+pub mod operation;
pub mod pane_grid;
pub mod pick_list;
pub mod progress_bar;
@@ -33,6 +34,9 @@ pub mod toggler;
pub mod tooltip;
pub mod tree;
+mod action;
+mod id;
+
#[doc(no_inline)]
pub use button::Button;
#[doc(no_inline)]
@@ -76,6 +80,10 @@ pub use tooltip::Tooltip;
#[doc(no_inline)]
pub use tree::Tree;
+pub use action::Action;
+pub use id::Id;
+pub use operation::Operation;
+
use crate::event::{self, Event};
use crate::layout;
use crate::mouse;
@@ -159,6 +167,15 @@ where
/// Reconciliates the [`Widget`] with the provided [`Tree`].
fn diff(&self, _tree: &mut Tree) {}
+ /// Applies an [`Operation`] to the [`Widget`].
+ fn operate(
+ &self,
+ _state: &mut Tree,
+ _layout: Layout<'_>,
+ _operation: &mut dyn Operation<Message>,
+ ) {
+ }
+
/// Processes a runtime [`Event`].
///
/// By default, it does nothing.
diff --git a/native/src/widget/action.rs b/native/src/widget/action.rs
new file mode 100644
index 00000000..766e902b
--- /dev/null
+++ b/native/src/widget/action.rs
@@ -0,0 +1,88 @@
+use crate::widget::operation::{self, Operation};
+use crate::widget::Id;
+
+use iced_futures::MaybeSend;
+
+/// An operation to be performed on the widget tree.
+#[allow(missing_debug_implementations)]
+pub struct Action<T>(Box<dyn Operation<T>>);
+
+impl<T> Action<T> {
+ /// Creates a new [`Action`] with the given [`Operation`].
+ pub fn new(operation: impl Operation<T> + 'static) -> Self {
+ Self(Box::new(operation))
+ }
+
+ /// Maps the output of an [`Action`] using the given function.
+ pub fn map<A>(
+ self,
+ f: impl Fn(T) -> A + 'static + MaybeSend + Sync,
+ ) -> Action<A>
+ where
+ T: 'static,
+ A: 'static,
+ {
+ Action(Box::new(Map {
+ operation: self.0,
+ f: Box::new(f),
+ }))
+ }
+
+ /// Consumes the [`Action`] and returns the internal [`Operation`].
+ pub fn into_operation(self) -> Box<dyn Operation<T>> {
+ self.0
+ }
+}
+
+#[allow(missing_debug_implementations)]
+struct Map<A, B> {
+ operation: Box<dyn Operation<A>>,
+ f: Box<dyn Fn(A) -> B>,
+}
+
+impl<A, B> Operation<B> for Map<A, B>
+where
+ A: 'static,
+ B: 'static,
+{
+ fn container(
+ &mut self,
+ id: Option<&Id>,
+ operate_on_children: &mut dyn FnMut(&mut dyn Operation<B>),
+ ) {
+ struct MapRef<'a, A, B> {
+ operation: &'a mut dyn Operation<A>,
+ f: &'a dyn Fn(A) -> B,
+ }
+
+ impl<'a, A, B> Operation<B> for MapRef<'a, A, B> {
+ fn container(
+ &mut self,
+ id: Option<&Id>,
+ operate_on_children: &mut dyn FnMut(&mut dyn Operation<B>),
+ ) {
+ let Self { operation, f } = self;
+
+ operation.container(id, &mut |operation| {
+ operate_on_children(&mut MapRef { operation, f });
+ });
+ }
+ }
+
+ let Self { operation, f } = self;
+
+ MapRef {
+ operation: operation.as_mut(),
+ f,
+ }
+ .container(id, operate_on_children);
+ }
+
+ fn focusable(
+ &mut self,
+ state: &mut dyn operation::Focusable,
+ id: Option<&Id>,
+ ) {
+ self.operation.focusable(state, id);
+ }
+}
diff --git a/native/src/widget/button.rs b/native/src/widget/button.rs
index 6eac6c1b..6c0b8f6e 100644
--- a/native/src/widget/button.rs
+++ b/native/src/widget/button.rs
@@ -8,6 +8,7 @@ use crate::overlay;
use crate::renderer;
use crate::touch;
use crate::widget::tree::{self, Tree};
+use crate::widget::Operation;
use crate::{
Background, Clipboard, Color, Element, Layout, Length, Padding, Point,
Rectangle, Shell, Vector, Widget,
@@ -164,6 +165,21 @@ where
)
}
+ fn operate(
+ &self,
+ tree: &mut Tree,
+ layout: Layout<'_>,
+ operation: &mut dyn Operation<Message>,
+ ) {
+ operation.container(None, &mut |operation| {
+ self.content.as_widget().operate(
+ &mut tree.children[0],
+ layout.children().next().unwrap(),
+ operation,
+ );
+ });
+ }
+
fn on_event(
&mut self,
tree: &mut Tree,
diff --git a/native/src/widget/column.rs b/native/src/widget/column.rs
index 834f9858..a8b0f183 100644
--- a/native/src/widget/column.rs
+++ b/native/src/widget/column.rs
@@ -4,7 +4,7 @@ use crate::layout;
use crate::mouse;
use crate::overlay;
use crate::renderer;
-use crate::widget::Tree;
+use crate::widget::{Operation, Tree};
use crate::{
Alignment, Clipboard, Element, Layout, Length, Padding, Point, Rectangle,
Shell, Widget,
@@ -143,6 +143,23 @@ where
)
}
+ fn operate(
+ &self,
+ tree: &mut Tree,
+ layout: Layout<'_>,
+ operation: &mut dyn Operation<Message>,
+ ) {
+ operation.container(None, &mut |operation| {
+ self.children
+ .iter()
+ .zip(&mut tree.children)
+ .zip(layout.children())
+ .for_each(|((child, state), layout)| {
+ child.as_widget().operate(state, layout, operation);
+ })
+ });
+ }
+
fn on_event(
&mut self,
tree: &mut Tree,
diff --git a/native/src/widget/container.rs b/native/src/widget/container.rs
index b0fa0315..2afad3f2 100644
--- a/native/src/widget/container.rs
+++ b/native/src/widget/container.rs
@@ -5,7 +5,7 @@ use crate::layout;
use crate::mouse;
use crate::overlay;
use crate::renderer;
-use crate::widget::Tree;
+use crate::widget::{Operation, Tree};
use crate::{
Background, Clipboard, Color, Element, Layout, Length, Padding, Point,
Rectangle, Shell, Widget,
@@ -165,6 +165,21 @@ where
)
}
+ fn operate(
+ &self,
+ tree: &mut Tree,
+ layout: Layout<'_>,
+ operation: &mut dyn Operation<Message>,
+ ) {
+ operation.container(None, &mut |operation| {
+ self.content.as_widget().operate(
+ &mut tree.children[0],
+ layout.children().next().unwrap(),
+ operation,
+ );
+ });
+ }
+
fn on_event(
&mut self,
tree: &mut Tree,
diff --git a/native/src/widget/helpers.rs b/native/src/widget/helpers.rs
index 518ac23b..a62448e9 100644
--- a/native/src/widget/helpers.rs
+++ b/native/src/widget/helpers.rs
@@ -49,8 +49,8 @@ where
/// [`Column`]: widget::Column
pub fn column<Message, Renderer>(
children: Vec<Element<'_, Message, Renderer>>,
-) -> widget::Row<'_, Message, Renderer> {
- widget::Row::with_children(children)
+) -> widget::Column<'_, Message, Renderer> {
+ widget::Column::with_children(children)
}
/// Creates a new [`Row`] with the given children.
diff --git a/native/src/widget/id.rs b/native/src/widget/id.rs
new file mode 100644
index 00000000..4b8fedf1
--- /dev/null
+++ b/native/src/widget/id.rs
@@ -0,0 +1,43 @@
+use std::borrow;
+use std::sync::atomic::{self, AtomicUsize};
+
+static NEXT_ID: AtomicUsize = AtomicUsize::new(0);
+
+/// The identifier of a generic widget.
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub struct Id(Internal);
+
+impl Id {
+ /// Creates a custom [`Id`].
+ pub fn new(id: impl Into<borrow::Cow<'static, str>>) -> Self {
+ Self(Internal::Custom(id.into()))
+ }
+
+ /// Creates a unique [`Id`].
+ ///
+ /// This function produces a different [`Id`] every time it is called.
+ pub fn unique() -> Self {
+ let id = NEXT_ID.fetch_add(1, atomic::Ordering::Relaxed);
+
+ Self(Internal::Unique(id))
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub enum Internal {
+ Unique(usize),
+ Custom(borrow::Cow<'static, str>),
+}
+
+#[cfg(test)]
+mod tests {
+ use super::Id;
+
+ #[test]
+ fn unique_generates_different_ids() {
+ let a = Id::unique();
+ let b = Id::unique();
+
+ assert_ne!(a, b);
+ }
+}
diff --git a/native/src/widget/operation.rs b/native/src/widget/operation.rs
new file mode 100644
index 00000000..ef636aa2
--- /dev/null
+++ b/native/src/widget/operation.rs
@@ -0,0 +1,60 @@
+//! Query or update internal widget state.
+pub mod focusable;
+pub mod scrollable;
+
+pub use focusable::Focusable;
+pub use scrollable::Scrollable;
+
+use crate::widget::Id;
+
+use std::fmt;
+
+/// A piece of logic that can traverse the widget tree of an application in
+/// order to query or update some widget state.
+pub trait Operation<T> {
+ /// Operates on a widget that contains other widgets.
+ ///
+ /// The `operate_on_children` function can be called to return control to
+ /// the widget tree and keep traversing it.
+ fn container(
+ &mut self,
+ id: Option<&Id>,
+ operate_on_children: &mut dyn FnMut(&mut dyn Operation<T>),
+ );
+
+ /// Operates on a widget that can be focused.
+ fn focusable(&mut self, _state: &mut dyn Focusable, _id: Option<&Id>) {}
+
+ /// Operates on a widget that can be scrolled.
+ fn scrollable(&mut self, _state: &mut dyn Scrollable, _id: Option<&Id>) {}
+
+ /// Finishes the [`Operation`] and returns its [`Outcome`].
+ fn finish(&self) -> Outcome<T> {
+ Outcome::None
+ }
+}
+
+/// The result of an [`Operation`].
+pub enum Outcome<T> {
+ /// The [`Operation`] produced no result.
+ None,
+
+ /// The [`Operation`] produced some result.
+ Some(T),
+
+ /// The [`Operation`] needs to be followed by another [`Operation`].
+ Chain(Box<dyn Operation<T>>),
+}
+
+impl<T> fmt::Debug for Outcome<T>
+where
+ T: fmt::Debug,
+{
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ Self::None => write!(f, "Outcome::None"),
+ Self::Some(output) => write!(f, "Outcome::Some({:?})", output),
+ Self::Chain(_) => write!(f, "Outcome::Chain(...)"),
+ }
+ }
+}
diff --git a/native/src/widget/operation/focusable.rs b/native/src/widget/operation/focusable.rs
new file mode 100644
index 00000000..f17bf178
--- /dev/null
+++ b/native/src/widget/operation/focusable.rs
@@ -0,0 +1,169 @@
+//! Operate on widgets that can be focused.
+use crate::widget::operation::{Operation, Outcome};
+use crate::widget::Id;
+
+/// The internal state of a widget that can be focused.
+pub trait Focusable {
+ /// Returns whether the widget is focused or not.
+ fn is_focused(&self) -> bool;
+
+ /// Focuses the widget.
+ fn focus(&mut self);
+
+ /// Unfocuses the widget.
+ fn unfocus(&mut self);
+}
+
+/// A summary of the focusable widgets present on a widget tree.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub struct Count {
+ /// The index of the current focused widget, if any.
+ focused: Option<usize>,
+
+ /// The total amount of focusable widgets.
+ total: usize,
+}
+
+/// Produces an [`Operation`] that focuses the widget with the given [`Id`].
+pub fn focus<T>(target: Id) -> impl Operation<T> {
+ struct Focus {
+ target: Id,
+ }
+
+ impl<T> Operation<T> for Focus {
+ fn focusable(&mut self, state: &mut dyn Focusable, id: Option<&Id>) {
+ match id {
+ Some(id) if id == &self.target => {
+ state.focus();
+ }
+ _ => {
+ state.unfocus();
+ }
+ }
+ }
+
+ fn container(
+ &mut self,
+ _id: Option<&Id>,
+ operate_on_children: &mut dyn FnMut(&mut dyn Operation<T>),
+ ) {
+ operate_on_children(self)
+ }
+ }
+
+ Focus { target }
+}
+
+/// Produces an [`Operation`] that generates a [`Count`] and chains it with the
+/// provided function to build a new [`Operation`].
+pub fn count<T, O>(f: fn(Count) -> O) -> impl Operation<T>
+where
+ O: Operation<T> + 'static,
+{
+ struct CountFocusable<O> {
+ count: Count,
+ next: fn(Count) -> O,
+ }
+
+ impl<T, O> Operation<T> for CountFocusable<O>
+ where
+ O: Operation<T> + 'static,
+ {
+ fn focusable(&mut self, state: &mut dyn Focusable, _id: Option<&Id>) {
+ if state.is_focused() {
+ self.count.focused = Some(self.count.total);
+ }
+
+ self.count.total += 1;
+ }
+
+ fn container(
+ &mut self,
+ _id: Option<&Id>,
+ operate_on_children: &mut dyn FnMut(&mut dyn Operation<T>),
+ ) {
+ operate_on_children(self)
+ }
+
+ fn finish(&self) -> Outcome<T> {
+ Outcome::Chain(Box::new((self.next)(self.count)))
+ }
+ }
+
+ CountFocusable {
+ count: Count::default(),
+ next: f,
+ }
+}
+
+/// Produces an [`Operation`] that searches for the current focused widget, and
+/// - if found, focuses the previous focusable widget.
+/// - if not found, focuses the last focusable widget.
+pub fn focus_previous<T>() -> impl Operation<T> {
+ struct FocusPrevious {
+ count: Count,
+ current: usize,
+ }
+
+ impl<T> Operation<T> for FocusPrevious {
+ fn focusable(&mut self, state: &mut dyn Focusable, _id: Option<&Id>) {
+ if self.count.total == 0 {
+ return;
+ }
+
+ match self.count.focused {
+ None if self.current == self.count.total - 1 => state.focus(),
+ Some(0) if self.current == 0 => state.unfocus(),
+ Some(0) => {}
+ Some(focused) if focused == self.current => state.unfocus(),
+ Some(focused) if focused - 1 == self.current => state.focus(),
+ _ => {}
+ }
+
+ self.current += 1;
+ }
+
+ fn container(
+ &mut self,
+ _id: Option<&Id>,
+ operate_on_children: &mut dyn FnMut(&mut dyn Operation<T>),
+ ) {
+ operate_on_children(self)
+ }
+ }
+
+ count(|count| FocusPrevious { count, current: 0 })
+}
+
+/// Produces an [`Operation`] that searches for the current focused widget, and
+/// - if found, focuses the next focusable widget.
+/// - if not found, focuses the first focusable widget.
+pub fn focus_next<T>() -> impl Operation<T> {
+ struct FocusNext {
+ count: Count,
+ current: usize,
+ }
+
+ impl<T> Operation<T> for FocusNext {
+ fn focusable(&mut self, state: &mut dyn Focusable, _id: Option<&Id>) {
+ match self.count.focused {
+ None if self.current == 0 => state.focus(),
+ Some(focused) if focused == self.current => state.unfocus(),
+ Some(focused) if focused + 1 == self.current => state.focus(),
+ _ => {}
+ }
+
+ self.current += 1;
+ }
+
+ fn container(
+ &mut self,
+ _id: Option<&Id>,
+ operate_on_children: &mut dyn FnMut(&mut dyn Operation<T>),
+ ) {
+ operate_on_children(self)
+ }
+ }
+
+ count(|count| FocusNext { count, current: 0 })
+}
diff --git a/native/src/widget/operation/scrollable.rs b/native/src/widget/operation/scrollable.rs
new file mode 100644
index 00000000..2210137d
--- /dev/null
+++ b/native/src/widget/operation/scrollable.rs
@@ -0,0 +1,35 @@
+//! Operate on widgets that can be scrolled.
+use crate::widget::{Id, Operation};
+
+/// The internal state of a widget that can be scrolled.
+pub trait Scrollable {
+ /// Snaps the scroll of the widget to the given `percentage`.
+ fn snap_to(&mut self, percentage: f32);
+}
+
+/// Produces an [`Operation`] that snaps the widget with the given [`Id`] to
+/// the provided `percentage`.
+pub fn snap_to<T>(target: Id, percentage: f32) -> impl Operation<T> {
+ struct SnapTo {
+ target: Id,
+ percentage: f32,
+ }
+
+ impl<T> Operation<T> for SnapTo {
+ fn scrollable(&mut self, state: &mut dyn Scrollable, id: Option<&Id>) {
+ if Some(&self.target) == id {
+ state.snap_to(self.percentage);
+ }
+ }
+
+ fn container(
+ &mut self,
+ _id: Option<&Id>,
+ operate_on_children: &mut dyn FnMut(&mut dyn Operation<T>),
+ ) {
+ operate_on_children(self)
+ }
+ }
+
+ SnapTo { target, percentage }
+}
diff --git a/native/src/widget/row.rs b/native/src/widget/row.rs
index c342c277..eda7c2d3 100644
--- a/native/src/widget/row.rs
+++ b/native/src/widget/row.rs
@@ -4,7 +4,7 @@ use crate::layout::{self, Layout};
use crate::mouse;
use crate::overlay;
use crate::renderer;
-use crate::widget::Tree;
+use crate::widget::{Operation, Tree};
use crate::{
Alignment, Clipboard, Element, Length, Padding, Point, Rectangle, Shell,
Widget,
@@ -130,6 +130,23 @@ where
)
}
+ fn operate(
+ &self,
+ tree: &mut Tree,
+ layout: Layout<'_>,
+ operation: &mut dyn Operation<Message>,
+ ) {
+ operation.container(None, &mut |operation| {
+ self.children
+ .iter()
+ .zip(&mut tree.children)
+ .zip(layout.children())
+ .for_each(|((child, state), layout)| {
+ child.as_widget().operate(state, layout, operation);
+ })
+ });
+ }
+
fn on_event(
&mut self,
tree: &mut Tree,
diff --git a/native/src/widget/scrollable.rs b/native/src/widget/scrollable.rs
index b40c3743..4ebb07a0 100644
--- a/native/src/widget/scrollable.rs
+++ b/native/src/widget/scrollable.rs
@@ -5,10 +5,12 @@ use crate::mouse;
use crate::overlay;
use crate::renderer;
use crate::touch;
+use crate::widget;
+use crate::widget::operation::{self, Operation};
use crate::widget::tree::{self, Tree};
use crate::{
- Background, Clipboard, Color, Element, Layout, Length, Point, Rectangle,
- Shell, Size, Vector, Widget,
+ Background, Clipboard, Color, Command, Element, Layout, Length, Point,
+ Rectangle, Shell, Size, Vector, Widget,
};
use std::{f32, u32};
@@ -30,6 +32,7 @@ where
Renderer: crate::Renderer,
Renderer::Theme: StyleSheet,
{
+ id: Option<Id>,
height: Length,
scrollbar_width: u16,
scrollbar_margin: u16,
@@ -47,6 +50,7 @@ where
/// Creates a new [`Scrollable`].
pub fn new(content: impl Into<Element<'a, Message, Renderer>>) -> Self {
Scrollable {
+ id: None,
height: Length::Shrink,
scrollbar_width: 10,
scrollbar_margin: 0,
@@ -57,6 +61,12 @@ where
}
}
+ /// Sets the [`Id`] of the [`Scrollable`].
+ pub fn id(mut self, id: Id) -> Self {
+ self.id = Some(id);
+ self
+ }
+
/// Sets the height of the [`Scrollable`].
pub fn height(mut self, height: Length) -> Self {
self.height = height;
@@ -150,6 +160,25 @@ where
)
}
+ fn operate(
+ &self,
+ tree: &mut Tree,
+ layout: Layout<'_>,
+ operation: &mut dyn Operation<Message>,
+ ) {
+ let state = tree.state.downcast_mut::<State>();
+
+ operation.scrollable(state, self.id.as_ref().map(|id| &id.0));
+
+ operation.container(None, &mut |operation| {
+ self.content.as_widget().operate(
+ &mut tree.children[0],
+ layout.children().next().unwrap(),
+ operation,
+ );
+ });
+ }
+
fn on_event(
&mut self,
tree: &mut Tree,
@@ -287,6 +316,30 @@ where
}
}
+/// The identifier of a [`Scrollable`].
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub struct Id(widget::Id);
+
+impl Id {
+ /// Creates a custom [`Id`].
+ pub fn new(id: impl Into<std::borrow::Cow<'static, str>>) -> Self {
+ Self(widget::Id::new(id))
+ }
+
+ /// Creates a unique [`Id`].
+ ///
+ /// This function produces a different [`Id`] every time it is called.
+ pub fn unique() -> Self {
+ Self(widget::Id::unique())
+ }
+}
+
+/// Produces a [`Command`] that snaps the [`Scrollable`] with the given [`Id`]
+/// to the provided `percentage`.
+pub fn snap_to<Message: 'static>(id: Id, percentage: f32) -> Command<Message> {
+ Command::widget(operation::scrollable::snap_to(id.0, percentage))
+}
+
/// Computes the layout of a [`Scrollable`].
pub fn layout<Renderer>(
renderer: &Renderer,
@@ -774,6 +827,12 @@ impl Default for State {
}
}
+impl operation::Scrollable for State {
+ fn snap_to(&mut self, percentage: f32) {
+ State::snap_to(self, percentage);
+ }
+}
+
/// The local state of a [`Scrollable`].
#[derive(Debug, Clone, Copy)]
enum Offset {
diff --git a/native/src/widget/text_input.rs b/native/src/widget/text_input.rs
index 4ef9e11b..8ddbc734 100644
--- a/native/src/widget/text_input.rs
+++ b/native/src/widget/text_input.rs
@@ -19,10 +19,12 @@ use crate::mouse::{self, click};
use crate::renderer;
use crate::text::{self, Text};
use crate::touch;
+use crate::widget;
+use crate::widget::operation::{self, Operation};
use crate::widget::tree::{self, Tree};
use crate::{
- Clipboard, Color, Element, Layout, Length, Padding, Point, Rectangle,
- Shell, Size, Vector, Widget,
+ Clipboard, Color, Command, Element, Layout, Length, Padding, Point,
+ Rectangle, Shell, Size, Vector, Widget,
};
pub use iced_style::text_input::{Appearance, StyleSheet};
@@ -53,6 +55,7 @@ where
Renderer: text::Renderer,
Renderer::Theme: StyleSheet,
{
+ id: Option<Id>,
placeholder: String,
value: Value,
is_secure: bool,
@@ -83,6 +86,7 @@ where
F: 'a + Fn(String) -> Message,
{
TextInput {
+ id: None,
placeholder: String::from(placeholder),
value: Value::new(value),
is_secure: false,
@@ -97,6 +101,12 @@ where
}
}
+ /// Sets the [`Id`] of the [`TextInput`].
+ pub fn id(mut self, id: Id) -> Self {
+ self.id = Some(id);
+ self
+ }
+
/// Converts the [`TextInput`] into a secure password input.
pub fn password(mut self) -> Self {
self.is_secure = true;
@@ -214,6 +224,17 @@ where
layout(renderer, limits, self.width, self.padding, self.size)
}
+ fn operate(
+ &self,
+ tree: &mut Tree,
+ _layout: Layout<'_>,
+ operation: &mut dyn Operation<Message>,
+ ) {
+ let state = tree.state.downcast_mut::<State>();
+
+ operation.focusable(state, self.id.as_ref().map(|id| &id.0));
+ }
+
fn on_event(
&mut self,
tree: &mut Tree,
@@ -293,6 +314,29 @@ where
}
}
+/// The identifier of a [`TextInput`].
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub struct Id(widget::Id);
+
+impl Id {
+ /// Creates a custom [`Id`].
+ pub fn new(id: impl Into<std::borrow::Cow<'static, str>>) -> Self {
+ Self(widget::Id::new(id))
+ }
+
+ /// Creates a unique [`Id`].
+ ///
+ /// This function produces a different [`Id`] every time it is called.
+ pub fn unique() -> Self {
+ Self(widget::Id::unique())
+ }
+}
+
+/// Produces a [`Command`] that focuses the [`TextInput`] with the given [`Id`].
+pub fn focus<Message: 'static>(id: Id) -> Command<Message> {
+ Command::widget(operation::focusable::focus(id.0))
+}
+
/// Computes the layout of a [`TextInput`].
pub fn layout<Renderer>(
renderer: &Renderer,
@@ -914,6 +958,7 @@ impl State {
/// Focuses the [`TextInput`].
pub fn focus(&mut self) {
self.is_focused = true;
+ self.move_cursor_to_end();
}
/// Unfocuses the [`TextInput`].
@@ -942,6 +987,20 @@ impl State {
}
}
+impl operation::Focusable for State {
+ fn is_focused(&self) -> bool {
+ State::is_focused(self)
+ }
+
+ fn focus(&mut self) {
+ State::focus(self)
+ }
+
+ fn unfocus(&mut self) {
+ State::unfocus(self)
+ }
+}
+
mod platform {
use crate::keyboard;