From ff2519b1d43d481987351a83b6dd7237524c21f0 Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Wed, 27 Jul 2022 06:49:20 +0200 Subject: Replace stateful widgets with new `iced_pure` API --- examples/todos/src/main.rs | 285 ++++++++++++++++++--------------------------- 1 file changed, 112 insertions(+), 173 deletions(-) (limited to 'examples/todos') diff --git a/examples/todos/src/main.rs b/examples/todos/src/main.rs index 363e3fb8..7dde235a 100644 --- a/examples/todos/src/main.rs +++ b/examples/todos/src/main.rs @@ -1,16 +1,22 @@ use iced::alignment::{self, Alignment}; -use iced::button::{self, Button}; -use iced::scrollable::{self, Scrollable}; -use iced::text_input::{self, TextInput}; use iced::theme::{self, Theme}; -use iced::{ - Application, Checkbox, Color, Column, Command, Container, Element, Font, - Length, Row, Settings, Text, +use iced::widget::{ + button, checkbox, column, container, row, scrollable, text, text_input, + Text, }; +use iced::window; +use iced::{Application, Element}; +use iced::{Color, Command, Font, Length, Settings}; use serde::{Deserialize, Serialize}; pub fn main() -> iced::Result { - Todos::run(Settings::default()) + Todos::run(Settings { + window: window::Settings { + size: (500, 800), + ..window::Settings::default() + }, + ..Settings::default() + }) } #[derive(Debug)] @@ -21,12 +27,9 @@ enum Todos { #[derive(Debug, Default)] struct State { - scroll: scrollable::State, - input: text_input::State, input_value: String, filter: Filter, tasks: Vec, - controls: Controls, dirty: bool, saving: bool, } @@ -42,9 +45,9 @@ enum Message { } impl Application for Todos { - type Executor = iced::executor::Default; - type Theme = Theme; type Message = Message; + type Theme = Theme; + type Executor = iced::executor::Default; type Flags = (); fn new(_flags: ()) -> (Todos, Command) { @@ -140,26 +143,22 @@ impl Application for Todos { } } - fn view(&mut self) -> Element { + fn view(&self) -> Element { match self { Todos::Loading => loading_message(), Todos::Loaded(State { - scroll, - input, input_value, filter, tasks, - controls, .. }) => { - let title = Text::new("todos") + let title = text("todos") .width(Length::Fill) .size(100) .style(Color::from([0.5, 0.5, 0.5])) .horizontal_alignment(alignment::Horizontal::Center); - let input = TextInput::new( - input, + let input = text_input( "What needs to be done?", input_value, Message::InputChanged, @@ -168,21 +167,24 @@ impl Application for Todos { .size(30) .on_submit(Message::CreateTask); - let controls = controls.view(tasks, *filter); + let controls = view_controls(tasks, *filter); let filtered_tasks = tasks.iter().filter(|task| filter.matches(task)); let tasks: Element<_> = if filtered_tasks.count() > 0 { - tasks - .iter_mut() - .enumerate() - .filter(|(_, task)| filter.matches(task)) - .fold(Column::new().spacing(20), |column, (i, task)| { - column.push(task.view().map(move |message| { - Message::TaskMessage(i, message) - })) - }) - .into() + column( + tasks + .iter() + .enumerate() + .filter(|(_, task)| filter.matches(task)) + .map(|(i, task)| { + task.view().map(move |message| { + Message::TaskMessage(i, message) + }) + }) + .collect(), + ) + .into() } else { empty_message(match filter { Filter::All => "You have not created a task yet...", @@ -193,20 +195,17 @@ impl Application for Todos { }) }; - let content = Column::new() - .max_width(800) + let content = column![title, input, controls, tasks] .spacing(20) - .push(title) - .push(input) - .push(controls) - .push(tasks); - - Scrollable::new(scroll) - .padding(40) - .push( - Container::new(content).width(Length::Fill).center_x(), - ) - .into() + .max_width(800); + + scrollable( + container(content) + .width(Length::Fill) + .padding(40) + .center_x(), + ) + .into() } } } @@ -223,20 +222,13 @@ struct Task { #[derive(Debug, Clone)] pub enum TaskState { - Idle { - edit_button: button::State, - }, - Editing { - text_input: text_input::State, - delete_button: button::State, - }, + Idle, + Editing, } impl Default for TaskState { fn default() -> Self { - TaskState::Idle { - edit_button: button::State::new(), - } + Self::Idle } } @@ -254,9 +246,7 @@ impl Task { Task { description, completed: false, - state: TaskState::Idle { - edit_button: button::State::new(), - }, + state: TaskState::Idle, } } @@ -266,56 +256,43 @@ impl Task { self.completed = completed; } TaskMessage::Edit => { - let mut text_input = text_input::State::focused(); - text_input.select_all(); - - self.state = TaskState::Editing { - text_input, - delete_button: button::State::new(), - }; + self.state = TaskState::Editing; } TaskMessage::DescriptionEdited(new_description) => { self.description = new_description; } TaskMessage::FinishEdition => { if !self.description.is_empty() { - self.state = TaskState::Idle { - edit_button: button::State::new(), - } + self.state = TaskState::Idle; } } TaskMessage::Delete => {} } } - fn view(&mut self) -> Element { - match &mut self.state { - TaskState::Idle { edit_button } => { - let checkbox = Checkbox::new( - self.completed, + fn view(&self) -> Element { + match &self.state { + TaskState::Idle => { + let checkbox = checkbox( &self.description, + self.completed, TaskMessage::Completed, ) .width(Length::Fill); - Row::new() - .spacing(20) - .align_items(Alignment::Center) - .push(checkbox) - .push( - Button::new(edit_button, edit_icon()) - .on_press(TaskMessage::Edit) - .padding(10) - .style(theme::Button::Text), - ) - .into() + row![ + checkbox, + button(edit_icon()) + .on_press(TaskMessage::Edit) + .padding(10) + .style(theme::Button::Text), + ] + .spacing(20) + .align_items(Alignment::Center) + .into() } - TaskState::Editing { - text_input, - delete_button, - } => { - let text_input = TextInput::new( - text_input, + TaskState::Editing => { + let text_input = text_input( "Describe your task...", &self.description, TaskMessage::DescriptionEdited, @@ -323,93 +300,55 @@ impl Task { .on_submit(TaskMessage::FinishEdition) .padding(10); - Row::new() - .spacing(20) - .align_items(Alignment::Center) - .push(text_input) - .push( - Button::new( - delete_button, - Row::new() - .spacing(10) - .push(delete_icon()) - .push(Text::new("Delete")), - ) + row![ + text_input, + button(row![delete_icon(), "Delete"].spacing(10)) .on_press(TaskMessage::Delete) .padding(10) - .style(theme::Button::Destructive), - ) - .into() + .style(theme::Button::Destructive) + ] + .spacing(20) + .align_items(Alignment::Center) + .into() } } } } -#[derive(Debug, Default, Clone)] -pub struct Controls { - all_button: button::State, - active_button: button::State, - completed_button: button::State, -} - -impl Controls { - fn view(&mut self, tasks: &[Task], current_filter: Filter) -> Row { - let Controls { - all_button, - active_button, - completed_button, - } = self; - - let tasks_left = tasks.iter().filter(|task| !task.completed).count(); - - let filter_button = |state, label, filter, current_filter| { - let label = Text::new(label).size(16); - let button = - Button::new(state, label).style(if filter == current_filter { - theme::Button::Primary - } else { - theme::Button::Text - }); +fn view_controls(tasks: &[Task], current_filter: Filter) -> Element { + let tasks_left = tasks.iter().filter(|task| !task.completed).count(); - button.on_press(Message::FilterChanged(filter)).padding(8) - }; + let filter_button = |label, filter, current_filter| { + let label = text(label).size(16); - Row::new() - .spacing(20) - .align_items(Alignment::Center) - .push( - Text::new(format!( - "{} {} left", - tasks_left, - if tasks_left == 1 { "task" } else { "tasks" } - )) - .width(Length::Fill) - .size(16), - ) - .push( - Row::new() - .width(Length::Shrink) - .spacing(10) - .push(filter_button( - all_button, - "All", - Filter::All, - current_filter, - )) - .push(filter_button( - active_button, - "Active", - Filter::Active, - current_filter, - )) - .push(filter_button( - completed_button, - "Completed", - Filter::Completed, - current_filter, - )), - ) - } + let button = button(label).style(if filter == current_filter { + theme::Button::Primary + } else { + theme::Button::Text + }); + + button.on_press(Message::FilterChanged(filter)).padding(8) + }; + + row![ + text(format!( + "{} {} left", + tasks_left, + if tasks_left == 1 { "task" } else { "tasks" } + )) + .width(Length::Fill) + .size(16), + row![ + filter_button("All", Filter::All, current_filter), + filter_button("Active", Filter::Active, current_filter), + filter_button("Completed", Filter::Completed, current_filter,), + ] + .width(Length::Shrink) + .spacing(10) + ] + .spacing(20) + .align_items(Alignment::Center) + .into() } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] @@ -436,8 +375,8 @@ impl Filter { } fn loading_message<'a>() -> Element<'a, Message> { - Container::new( - Text::new("Loading...") + container( + text("Loading...") .horizontal_alignment(alignment::Horizontal::Center) .size(50), ) @@ -447,9 +386,9 @@ fn loading_message<'a>() -> Element<'a, Message> { .into() } -fn empty_message<'a>(message: &str) -> Element<'a, Message> { - Container::new( - Text::new(message) +fn empty_message(message: &str) -> Element<'_, Message> { + container( + text(message) .width(Length::Fill) .size(25) .horizontal_alignment(alignment::Horizontal::Center) @@ -464,11 +403,11 @@ fn empty_message<'a>(message: &str) -> Element<'a, Message> { // Fonts const ICONS: Font = Font::External { name: "Icons", - bytes: include_bytes!("../fonts/icons.ttf"), + bytes: include_bytes!("../../todos/fonts/icons.ttf"), }; fn icon(unicode: char) -> Text { - Text::new(unicode.to_string()) + text(unicode.to_string()) .font(ICONS) .width(Length::Units(20)) .horizontal_alignment(alignment::Horizontal::Center) -- cgit From 744edbd6c17c3c9d872992c84e074f14c8e75a47 Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Thu, 28 Jul 2022 03:54:02 +0200 Subject: Focus text inputs in `todos` example --- examples/todos/Cargo.toml | 1 + examples/todos/src/main.rs | 31 ++++++++++++++++++++++++++----- 2 files changed, 27 insertions(+), 5 deletions(-) (limited to 'examples/todos') diff --git a/examples/todos/Cargo.toml b/examples/todos/Cargo.toml index 5b068c78..2326ffc6 100644 --- a/examples/todos/Cargo.toml +++ b/examples/todos/Cargo.toml @@ -9,6 +9,7 @@ publish = false iced = { path = "../..", features = ["async-std", "debug"] } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" +lazy_static = "1.4" [target.'cfg(not(target_arch = "wasm32"))'.dependencies] async-std = "1.0" diff --git a/examples/todos/src/main.rs b/examples/todos/src/main.rs index 7dde235a..5cbb6228 100644 --- a/examples/todos/src/main.rs +++ b/examples/todos/src/main.rs @@ -7,8 +7,14 @@ use iced::widget::{ use iced::window; use iced::{Application, Element}; use iced::{Color, Command, Font, Length, Settings}; + +use lazy_static::lazy_static; use serde::{Deserialize, Serialize}; +lazy_static! { + static ref INPUT_ID: text_input::Id = text_input::Id::unique(); +} + pub fn main() -> iced::Result { Todos::run(Settings { window: window::Settings { @@ -84,10 +90,11 @@ impl Application for Todos { _ => {} } - Command::none() + text_input::focus(INPUT_ID.clone()) } Todos::Loaded(state) => { let mut saved = false; + let mut task_command = Command::none(); match message { Message::InputChanged(value) => { @@ -109,6 +116,11 @@ impl Application for Todos { } Message::TaskMessage(i, task_message) => { if let Some(task) = state.tasks.get_mut(i) { + if matches!(task_message, TaskMessage::Edit) { + task_command = + text_input::focus(Task::text_input_id(i)); + } + task.update(task_message); } } @@ -123,7 +135,7 @@ impl Application for Todos { state.dirty = true; } - if state.dirty && !state.saving { + let save = if state.dirty && !state.saving { state.dirty = false; state.saving = true; @@ -138,7 +150,9 @@ impl Application for Todos { ) } else { Command::none() - } + }; + + Command::batch(vec![task_command, save]) } } } @@ -163,6 +177,7 @@ impl Application for Todos { input_value, Message::InputChanged, ) + .id(INPUT_ID.clone()) .padding(15) .size(30) .on_submit(Message::CreateTask); @@ -178,12 +193,13 @@ impl Application for Todos { .enumerate() .filter(|(_, task)| filter.matches(task)) .map(|(i, task)| { - task.view().map(move |message| { + task.view(i).map(move |message| { Message::TaskMessage(i, message) }) }) .collect(), ) + .spacing(10) .into() } else { empty_message(match filter { @@ -242,6 +258,10 @@ pub enum TaskMessage { } impl Task { + fn text_input_id(i: usize) -> text_input::Id { + text_input::Id::new(format!("task-{}", i)) + } + fn new(description: String) -> Self { Task { description, @@ -270,7 +290,7 @@ impl Task { } } - fn view(&self) -> Element { + fn view(&self, i: usize) -> Element { match &self.state { TaskState::Idle => { let checkbox = checkbox( @@ -297,6 +317,7 @@ impl Task { &self.description, TaskMessage::DescriptionEdited, ) + .id(Self::text_input_id(i)) .on_submit(TaskMessage::FinishEdition) .padding(10); -- cgit From 77c6864e7c772c5e228bc09fe40c2c0b8884386d Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Tue, 2 Aug 2022 04:20:47 +0200 Subject: Implement `focus_next` operation ... as well as a `count_focusable` composable helper! --- examples/todos/src/main.rs | 57 ++++++++++++++++++++++++++++++++++++---------- 1 file changed, 45 insertions(+), 12 deletions(-) (limited to 'examples/todos') diff --git a/examples/todos/src/main.rs b/examples/todos/src/main.rs index 5cbb6228..25d90a0b 100644 --- a/examples/todos/src/main.rs +++ b/examples/todos/src/main.rs @@ -1,12 +1,15 @@ use iced::alignment::{self, Alignment}; +use iced::event::{self, Event}; +use iced::keyboard; +use iced::subscription; use iced::theme::{self, Theme}; use iced::widget::{ - button, checkbox, column, container, row, scrollable, text, text_input, - Text, + self, button, checkbox, column, container, row, scrollable, text, + text_input, Text, }; use iced::window; use iced::{Application, Element}; -use iced::{Color, Command, Font, Length, Settings}; +use iced::{Color, Command, Font, Length, Settings, Subscription}; use lazy_static::lazy_static; use serde::{Deserialize, Serialize}; @@ -48,6 +51,7 @@ enum Message { CreateTask, FilterChanged(Filter), TaskMessage(usize, TaskMessage), + TabPressed, } impl Application for Todos { @@ -94,11 +98,12 @@ impl Application for Todos { } Todos::Loaded(state) => { let mut saved = false; - let mut task_command = Command::none(); - match message { + let command = match message { Message::InputChanged(value) => { state.input_value = value; + + Command::none() } Message::CreateTask => { if !state.input_value.is_empty() { @@ -107,29 +112,44 @@ impl Application for Todos { .push(Task::new(state.input_value.clone())); state.input_value.clear(); } + + Command::none() } Message::FilterChanged(filter) => { state.filter = filter; + + Command::none() } Message::TaskMessage(i, TaskMessage::Delete) => { state.tasks.remove(i); + + Command::none() } Message::TaskMessage(i, task_message) => { if let Some(task) = state.tasks.get_mut(i) { - if matches!(task_message, TaskMessage::Edit) { - task_command = - text_input::focus(Task::text_input_id(i)); - } + let should_focus = + matches!(task_message, TaskMessage::Edit); task.update(task_message); + + if should_focus { + text_input::focus(Task::text_input_id(i)) + } else { + Command::none() + } + } else { + Command::none() } } Message::Saved(_) => { state.saving = false; saved = true; + + Command::none() } - _ => {} - } + Message::TabPressed => widget::focus_next(), + _ => Command::none(), + }; if !saved { state.dirty = true; @@ -152,7 +172,7 @@ impl Application for Todos { Command::none() }; - Command::batch(vec![task_command, save]) + Command::batch(vec![command, save]) } } } @@ -225,6 +245,19 @@ impl Application for Todos { } } } + + fn subscription(&self) -> Subscription { + subscription::events_with(|event, status| match (event, status) { + ( + Event::Keyboard(keyboard::Event::KeyPressed { + key_code: keyboard::KeyCode::Tab, + .. + }), + event::Status::Ignored, + ) => Some(Message::TabPressed), + _ => None, + }) + } } #[derive(Debug, Clone, Serialize, Deserialize)] -- cgit From 6eb3dd7e5edc8847875c288c41d1dec8b1dad06e Mon Sep 17 00:00:00 2001 From: Héctor Ramón Jiménez Date: Thu, 4 Aug 2022 03:24:44 +0200 Subject: Implement `focus_previous` operation --- examples/todos/src/main.rs | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) (limited to 'examples/todos') diff --git a/examples/todos/src/main.rs b/examples/todos/src/main.rs index 25d90a0b..bb00aac6 100644 --- a/examples/todos/src/main.rs +++ b/examples/todos/src/main.rs @@ -51,7 +51,7 @@ enum Message { CreateTask, FilterChanged(Filter), TaskMessage(usize, TaskMessage), - TabPressed, + TabPressed { shift: bool }, } impl Application for Todos { @@ -147,7 +147,13 @@ impl Application for Todos { Command::none() } - Message::TabPressed => widget::focus_next(), + Message::TabPressed { shift } => { + if shift { + widget::focus_previous() + } else { + widget::focus_next() + } + } _ => Command::none(), }; @@ -251,10 +257,13 @@ impl Application for Todos { ( Event::Keyboard(keyboard::Event::KeyPressed { key_code: keyboard::KeyCode::Tab, + modifiers, .. }), event::Status::Ignored, - ) => Some(Message::TabPressed), + ) => Some(Message::TabPressed { + shift: modifiers.shift(), + }), _ => None, }) } -- cgit