### Run Exit Application Example Source: https://github.com/plushie-ui/plushie-iced/blob/main/examples/exit/README.md To run this example, use the cargo command provided. Ensure you have the necessary package installed. ```bash cargo run --package exit ``` -------------------------------- ### Run Web Counter Example Source: https://github.com/plushie-ui/plushie-iced/blob/main/examples/counter/README.md Build and serve the web version of the counter example using Trunk. Navigate to the example directory first. ```bash cd examples/counter trunk serve ``` -------------------------------- ### Run the WebSocket example Source: https://github.com/plushie-ui/plushie-iced/blob/main/examples/websocket/README.md Execute the WebSocket example package using cargo. ```bash cargo run --package websocket ``` -------------------------------- ### Run Generic Example with Cargo Source: https://github.com/plushie-ui/plushie-iced/blob/main/examples/README.md General command to run any of the simpler 'Extras' examples using Cargo. Replace '' with the specific example name. ```bash cargo run --package ``` -------------------------------- ### Run Checkbox Example Source: https://github.com/plushie-ui/plushie-iced/blob/main/examples/checkbox/README.md Execute the checkbox example using Cargo. Ensure you have the necessary project setup. ```bash cargo run --package checkbox ``` -------------------------------- ### Run Tour Example with Cargo Source: https://github.com/plushie-ui/plushie-iced/blob/main/examples/README.md Command to run the 'Tour' example application using Cargo. This example showcases different widgets in Iced. ```bash cargo run --package tour ``` -------------------------------- ### Run Styling Example with Cargo Source: https://github.com/plushie-ui/plushie-iced/blob/main/examples/README.md Command to run the 'Styling' example application using Cargo. This example demonstrates custom styling with light and dark themes. ```bash cargo run --package styling ``` -------------------------------- ### Run Solar System Example Source: https://github.com/plushie-ui/plushie-iced/blob/main/examples/solar_system/README.md Execute the solar system example using the cargo package manager. ```bash cargo run --package solar_system ``` -------------------------------- ### Run Native Counter Example Source: https://github.com/plushie-ui/plushie-iced/blob/main/examples/counter/README.md Execute the counter example as a native application using Cargo. Ensure you have the Rust toolchain installed. ```bash cargo run --package counter ``` -------------------------------- ### Run Bézier Tool Example Source: https://github.com/plushie-ui/plushie-iced/blob/main/examples/bezier_tool/README.md Command to run the Bézier tool example. Ensure you are in the correct package directory. ```bash cargo run --package bezier_tool ``` -------------------------------- ### Run Arc Example Source: https://github.com/plushie-ui/plushie-iced/blob/main/examples/arc/README.md Execute the Arc demonstration package using the cargo build tool. ```bash cargo run --package arc ``` -------------------------------- ### Run custom widget example Source: https://github.com/plushie-ui/plushie-iced/blob/main/examples/custom_widget/README.md Execute the custom widget demonstration package using cargo. ```bash cargo run --package custom_widget ``` -------------------------------- ### Run QR Code Example Source: https://github.com/plushie-ui/plushie-iced/blob/main/examples/qr_code/README.md Execute the QR code generator example using the cargo package manager. ```bash cargo run --package qr_code ``` -------------------------------- ### Run Todos Example with Cargo Source: https://github.com/plushie-ui/plushie-iced/blob/main/examples/README.md Command to run the 'Todos' example application using Cargo. This example demonstrates dynamic layout, text input, checkboxes, and async actions. ```bash cargo run --package todos ``` -------------------------------- ### Execute Loading Spinners Example Source: https://github.com/plushie-ui/plushie-iced/blob/main/examples/loading_spinners/README.md Run the loading spinners example package using the cargo build tool. ```bash cargo run --package loading_spinners ``` -------------------------------- ### Run Event Logging Example Source: https://github.com/plushie-ui/plushie-iced/blob/main/examples/events/README.md Execute the event logging example using Cargo. This command builds and runs the 'events' package. ```bash cargo run --package events ``` -------------------------------- ### Run the Clock Example Source: https://github.com/plushie-ui/plushie-iced/blob/main/examples/clock/README.md Execute the clock application using the cargo package manager. ```shell cargo run --package clock ``` -------------------------------- ### Run Game of Life Example Source: https://github.com/plushie-ui/plushie-iced/blob/main/examples/game_of_life/README.md Execute the simulation using the cargo package manager. ```bash cargo run --package game_of_life ``` -------------------------------- ### Create and Manage Checkboxes in Iced Source: https://context7.com/plushie-ui/plushie-iced/llms.txt Provides examples for creating checkboxes with labels, supporting keyboard activation, and custom icons. Includes options for advanced text shaping, disabled states, and custom sizing. ```rust use iced::widget::{checkbox, column}; use iced::Element; fn view(state: &State) -> Element<'_, Message> { column![ // Basic checkbox with label checkbox(state.accept_terms) .label("I accept the terms and conditions") .on_toggle(Message::TermsToggled), // Checkbox with advanced text shaping for complex scripts checkbox(state.newsletter) .label("Subscribe to newsletter") .on_toggle(Message::NewsletterToggled) .shaping(iced::widget::text::Shaping::Advanced), // Disabled checkbox (no on_toggle handler) checkbox(state.locked_option) .label("This option is locked"), // Custom sized checkbox checkbox(state.large_option) .label("Large checkbox") .on_toggle(Message::LargeToggled) .size(24) .spacing(12), ] .spacing(10) .into() } fn update(state: &mut State, message: Message) { match message { Message::TermsToggled(is_checked) => state.accept_terms = is_checked, Message::NewsletterToggled(is_checked) => state.newsletter = is_checked, _ => {} } } ``` -------------------------------- ### Create and Style Buttons in Iced Source: https://context7.com/plushie-ui/plushie-iced/llms.txt Demonstrates creating various button types, including basic, custom content, disabled, conditionally enabled, and styled buttons (primary, danger, text link). Includes an example of an icon button with an accessibility label. ```rust use iced::widget::{button, column, row, text}; use iced::Element; fn view(state: &State) -> Element<'_, Message> { column![ // Basic button with on_press message button("Click me!").on_press(Message::ButtonClicked), // Button with custom content button(row![text("Save"), text(" (Ctrl+S)")].spacing(5)) .on_press(Message::Save) .padding(15), // Disabled button (no on_press handler) button("Disabled"), // Button with conditional enable using on_press_maybe button("Submit") .on_press_maybe(if state.is_valid { Some(Message::Submit) } else { None }), // Styled buttons button("Primary").on_press(Message::Action).style(button::primary), button("Danger").on_press(Message::Delete).style(button::danger), button("Text link").on_press(Message::Link).style(button::text), // Icon button with accessibility label button(text('\u{F1F8}')) // trash icon .on_press(Message::Delete) .label("Delete item"), // accessible name for screen readers ] .spacing(10) .into() } ``` -------------------------------- ### Creating a Time-Based Subscription Source: https://context7.com/plushie-ui/plushie-iced/llms.txt Subscribe to regular time-based events using `iced::time::every`. This example creates a tick every 100 milliseconds, mapping the event to a `Message::Tick`. ```rust time::every(milliseconds(100)).map(|_| Message::Tick) ``` -------------------------------- ### Define accessible metadata with a label Source: https://github.com/plushie-ui/plushie-iced/blob/main/docs/a11y-widget-guide.md Example of setting a direct label within the Accessible struct for a widget. ```rust Accessible { role: Role::CheckBox, label: Some("Accept terms"), ..Accessible::default() } ``` -------------------------------- ### Implement Scrollable Regions in Iced Source: https://context7.com/plushie-ui/plushie-iced/llms.txt Provides examples for vertical and horizontal scrolling, including programmatic control via IDs and custom scrollbar styling. ```rust use iced::widget::{column, container, scrollable, text, button, row}; use iced::{Element, Fill, Task}; fn view(state: &State) -> Element<'_, Message> { let content = column![ button("Scroll to end").on_press(Message::ScrollToEnd), text("Beginning of content"), // ... lots of content ... ] .spacing(20); // Vertical scrollable with ID for programmatic control scrollable(content) .id("main-scroll") .width(Fill) .height(Fill) .on_scroll(Message::Scrolled) .into() } fn update(state: &mut State, message: Message) -> Task { match message { Message::ScrollToEnd => { // Programmatically scroll to the end iced::widget::operation::snap_to("main-scroll", scrollable::RelativeOffset::END) } Message::ScrollToBeginning => { iced::widget::operation::snap_to("main-scroll", scrollable::RelativeOffset::START) } Message::Scrolled(viewport) => { state.scroll_offset = viewport.relative_offset(); Task::none() } _ => Task::none() } } // Horizontal scrollable fn horizontal_view(state: &State) -> Element<'_, Message> { scrollable( row![ text("Item 1"), text("Item 2"), // ... more items ] .spacing(20) ) .direction(scrollable::Direction::Horizontal( scrollable::Scrollbar::new() .width(8) .scroller_width(8) )) .into() } ``` -------------------------------- ### Initialize a basic application with iced::run Source: https://context7.com/plushie-ui/plushie-iced/llms.txt Use the run function for simple applications requiring only an update and view function. ```rust use iced::widget::{button, column, text}; use iced::{Center, Element}; pub fn main() -> iced::Result { iced::run(Counter::update, Counter::view) } #[derive(Default)] struct Counter { value: i64, } #[derive(Debug, Clone, Copy)] enum Message { Increment, Decrement, } impl Counter { fn update(&mut self, message: Message) { match message { Message::Increment => self.value += 1, Message::Decrement => self.value -= 1, } } fn view(&self) -> Element<'_, Message> { column![ button("Increment").on_press(Message::Increment), text(self.value).size(50), button("Decrement").on_press(Message::Decrement) ] .padding(20) .align_x(Center) .into() } } ``` -------------------------------- ### Implement Pick List Widgets in Iced Source: https://context7.com/plushie-ui/plushie-iced/llms.txt Shows how to create dropdown selection lists with custom display formatting, placeholder text, and styling options. ```rust use iced::widget::{column, pick_list, text}; use iced::Element; #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] enum Language { #[default] Rust, Python, JavaScript, Go, } impl Language { const ALL: &'static [Self] = &[Self::Rust, Self::Python, Self::JavaScript, Self::Go]; } impl std::fmt::Display for Language { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Rust => write!(f, "Rust"), Self::Python => write!(f, "Python"), Self::JavaScript => write!(f, "JavaScript"), Self::Go => write!(f, "Go"), } } } fn view(state: &State) -> Element<'_, Message> { column![ text("Select your favorite language:"), // Basic pick list with optional selection pick_list(state.selected, Language::ALL, Language::to_string) .on_select(Message::LanguageSelected) .placeholder("Choose a language..."), // Pick list with custom text width pick_list(state.selected, Language::ALL, Language::to_string) .on_select(Message::LanguageSelected) .text_size(18) .padding(10), ] .spacing(10) .into() } fn update(state: &mut State, message: Message) { match message { Message::LanguageSelected(language) => state.selected = Some(language), } } ``` -------------------------------- ### Run Web Todos App with Trunk Source: https://github.com/plushie-ui/plushie-iced/blob/main/examples/todos/README.md Build and serve the web version of the Todos tracker application using the Trunk build tool. ```bash cd examples/todos trunk serve ``` -------------------------------- ### Configure an application with iced::application Source: https://context7.com/plushie-ui/plushie-iced/llms.txt Use the application builder for advanced configuration including themes, subscriptions, and window settings. ```rust use iced::widget::{column, text, text_input}; use iced::{Element, Subscription, Task, Theme}; use iced::keyboard; pub fn main() -> iced::Result { iced::application(App::new, App::update, App::view) .subscription(App::subscription) .title(App::title) .theme(App::theme) .window_size((500.0, 400.0)) .run() } struct App { content: String, } impl App { fn new() -> (Self, Task) { (Self { content: String::new() }, Task::none()) } fn title(&self) -> String { format!("My App - {}", self.content.len()) } fn theme(&self) -> Theme { Theme::TokyoNight } fn subscription(&self) -> Subscription { keyboard::listen().filter_map(|event| match event { keyboard::Event::KeyPressed { key, .. } => Some(Message::KeyPressed(key)), _ => None, }) } fn update(&mut self, message: Message) -> Task { match message { Message::ContentChanged(content) => self.content = content, Message::KeyPressed(_) => {} } Task::none() } fn view(&self) -> Element<'_, Message> { column![ text("Enter text:"), text_input("Type here...", &self.content) .on_input(Message::ContentChanged) .padding(10), ] .spacing(10) .into() } } #[derive(Debug, Clone)] enum Message { ContentChanged(String), KeyPressed(keyboard::Key), } ``` -------------------------------- ### Implement Text Input Fields in Iced Source: https://context7.com/plushie-ui/plushie-iced/llms.txt Shows how to create text input fields for various purposes, including basic input, password fields, and inputs with custom submit and paste handlers. Also demonstrates input alignment and sizing. ```rust use iced::widget::{column, text, text_input}; use iced::Element; fn view(state: &State) -> Element<'_, Message> { column![ // Basic text input text_input("Type something here...", &state.content) .on_input(Message::ContentChanged) .padding(10), // Text input with ID for focus operations text_input("Email address", &state.email) .id("email-input") .on_input(Message::EmailChanged) .on_submit(Message::Submit), // Secure password input text_input("Password", &state.password) .on_input(Message::PasswordChanged) .secure(true) .on_submit(Message::Login), // With custom paste handler text_input("Paste content", &state.paste_content) .on_input(Message::InputChanged) .on_paste(Message::ContentPasted), // Centered alignment and custom size text_input("Search...", &state.search) .on_input(Message::SearchChanged) .size(20) .align_x(iced::Center), ] .spacing(10) .into() } fn update(state: &mut State, message: Message) -> Task { match message { Message::ContentChanged(content) => state.content = content, Message::Submit => { // Focus the next field programmatically return iced::widget::operation::focus("password-input"); } _ => {} } Task::none() } ``` -------------------------------- ### Handling Async Operation Results in Update Source: https://context7.com/plushie-ui/plushie-iced/llms.txt Process the result of an asynchronous operation within the `update` function. This example shows how to update the application state based on whether the data fetching was successful or resulted in an error. ```rust self.loading = false; match result { Ok(data) => self.data = Some(data), Err(_) => self.data = Some("Error fetching data".to_string()), } Task::none() ``` -------------------------------- ### NixOS shell.nix for Iced Dependencies Source: https://github.com/plushie-ui/plushie-iced/blob/main/DEPENDENCIES.md Use this Nix configuration to create a development shell with the required system libraries for Iced. It includes GPU and window system backends. Activate with `nix-shell`. ```nix { pkgs ? import { } }: let dlopenLibraries = with pkgs; [ libxkbcommon # GPU backend vulkan-loader # libGL # Window system wayland # xorg.libX11 # xorg.libXcursor # xorg.libXi ]; in pkgs.mkShell { nativeBuildInputs = with pkgs; [ cargo rustc ]; # additional libraries that your project # links to at build time, e.g. OpenSSL buildInputs = []; env.RUSTFLAGS = "-C link-arg=-Wl,-rpath,${pkgs.lib.makeLibraryPath dlopenLibraries}"; } ``` -------------------------------- ### Arrange Widgets with Iced Layout Widgets Source: https://context7.com/plushie-ui/plushie-iced/llms.txt Utilize Column, Row, Stack, and Container for flexible UI arrangement. Import necessary layout modules and alignment enums. ```rust use iced::widget::{column, row, container, stack, center, space, text, button}; use iced::{Element, Fill, Center, Bottom}; fn view(state: &State) -> Element<'_, Message> { // Column - vertical layout let vertical = column![ text("Top"), text("Middle"), text("Bottom"), ] .spacing(10) .padding(20) .align_x(Center); // Row - horizontal layout let horizontal = row![ text("Left"), space::horizontal(), // flexible space text("Right"), ] .spacing(10) .align_y(Center); // Container - single child positioning let centered = container(text("Centered content")) .width(Fill) .height(Fill) .center_x(Fill) .center_y(Fill) .padding(20); // Stack - layered content let layered = stack![ text("Background layer"), container(text("Foreground")) .center_x(Fill) .center_y(Fill), ]; // Combined layout column![ container(text("Header")).padding(10).style(container::rounded_box), row![ vertical, space::horizontal(), horizontal, ] .height(Fill), row![text("Footer left"), space::horizontal(), text("Footer right")] .align_y(Bottom), ] .spacing(20) .into() } ``` -------------------------------- ### NixOS flake.nix for Iced Dependencies Source: https://github.com/plushie-ui/plushie-iced/blob/main/DEPENDENCIES.md This Nix Flake configuration sets up a development environment for Iced, including essential system libraries for graphics and windowing. Activate the dev shell using `nix develop`. ```nix { inputs = { nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; systems.url = "github:nix-systems/default"; }; outputs = { nixpkgs, systems, ... }: let eachSystem = nixpkgs.lib.genAttrs (import systems); pkgsFor = nixpkgs.legacyPackages; in { devShells = eachSystem (system: let pkgs = pkgsFor.${system}; dlopenLibraries = with pkgs; [ libxkbcommon # GPU backend vulkan-loader # libGL # Window system wayland # xorg.libX11 # xorg.libXcursor # xorg.libXi ]; in { default = pkgs.mkShell { nativeBuildInputs = with pkgs; [ cargo rustc ]; # additional libraries that your project # links to at build time, e.g. OpenSSL buildInputs = []; env.RUSTFLAGS = "-C link-arg=-Wl,-rpath,${nixpkgs.lib.makeLibraryPath dlopenLibraries}"; }; }); }; } ``` -------------------------------- ### Run the Iced Application Source: https://github.com/plushie-ui/plushie-iced/blob/main/examples/markdown/overview.md Initializes and runs the Iced application. This function takes the application title, the update function, and the view function as arguments. ```rust fn main() -> iced::Result { iced::run("A cool counter", Counter::update, Counter::view) } ``` -------------------------------- ### Implement Slider Widgets in Iced Source: https://context7.com/plushie-ui/plushie-iced/llms.txt Demonstrates various slider configurations including step sizes, shift-modified fine control, release callbacks, default values, and vertical orientation. ```rust use iced::widget::{column, slider, text, vertical_slider}; use iced::Element; fn view(state: &State) -> Element<'_, Message> { column![ // Basic horizontal slider text!("Volume: {}%", state.volume as i32), slider(0.0..=100.0, state.volume, Message::VolumeChanged), // Slider with step size text!("Value: {}", state.stepped_value), slider(0..=100, state.stepped_value, Message::SteppedChanged) .step(5), // increments of 5 // Slider with shift step for fine control slider(0.0..=1.0, state.precise_value, Message::PreciseChanged) .step(0.1) .shift_step(0.01), // Hold Shift for finer control // Slider with release callback slider(0.0..=100.0, state.seeking_value, Message::Seeking) .on_release(Message::SeekComplete), // Slider with default value (double-click to reset) slider(0.0..=100.0, state.adjustable, Message::Adjusted) .default(50.0), // Vertical slider (requires iced::widget::vertical_slider) vertical_slider(0.0..=100.0, state.vertical_value, Message::VerticalChanged) .height(200), // Accessible slider with label slider(0.0..=100.0, state.brightness, Message::BrightnessChanged) .label("Screen brightness"), ] .spacing(20) .into() } ``` -------------------------------- ### Run Pokédex application Source: https://github.com/plushie-ui/plushie-iced/blob/main/examples/pokedex/README.md Execute the application on native platforms using the cargo package manager. ```shell cargo run --package pokedex ``` -------------------------------- ### Use Accessibility Selectors in iced_test Source: https://context7.com/plushie-ui/plushie-iced/llms.txt Demonstrates finding widgets using accessibility roles and labels. Also shows how to verify if a widget is focused. Requires `iced_test` and `iced` crates. ```rust use iced_test::{simulator, Error, Selector}; use iced_test::selector::{by_role, by_label, id}; use iced::core::widget::operation::accessible::Role; #[test] fn accessibility_selectors() -> Result<(), Error> { let app = App::default(); let mut ui = simulator(app.view()); // Find by accessibility role let button = ui.find(by_role(Role::Button))?; // Find by accessible label let submit = ui.find(by_label("Submit"))?; // Verify widget is focused let focused = ui.find(is_focused())?; Ok(()) } ``` -------------------------------- ### Subscribing to All Runtime Events Source: https://context7.com/plushie-ui/plushie-iced/llms.txt Capture all available runtime events using `iced::event::listen`. This provides a comprehensive way to handle various system-level events within your application. ```rust event::listen().map(Message::Event) ``` -------------------------------- ### Run color palette generator Source: https://github.com/plushie-ui/plushie-iced/blob/main/examples/color_palette/README.md Execute the color palette generator package using cargo. ```shell cargo run --package color_palette ``` -------------------------------- ### Expose accessibility metadata in custom widgets Source: https://context7.com/plushie-ui/plushie-iced/llms.txt Implement the operate method to provide accessibility roles, labels, and state information to assistive technologies. ```rust use iced::core::widget::operation::accessible::{Accessible, Role, Value, Orientation}; use iced::core::widget::operation::Operation; // In a custom widget's operate() method: fn operate( &mut self, tree: &mut Tree, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn Operation, ) { let state = tree.state.downcast_mut::(); // Expose accessibility metadata operation.accessible( self.id.as_ref(), layout.bounds(), &Accessible { role: Role::Slider, label: Some("Volume control"), description: Some("Adjust the audio volume from 0 to 100 percent"), value: Some(Value::Numeric { current: self.value as f64, min: 0.0, max: 100.0, step: Some(1.0), }), orientation: Some(Orientation::Horizontal), disabled: self.on_change.is_none(), ..Accessible::default() }, ); // Register for focus navigation operation.focusable(self.id.as_ref(), layout.bounds(), state); } ``` -------------------------------- ### Simulate Form Submission with iced_test Source: https://context7.com/plushie-ui/plushie-iced/llms.txt Tests form interactions including typing text and pressing keys. Uses widget IDs for selection and simulates keyboard input. Requires `iced_test` and `iced` crates. ```rust use iced_test::{simulator, Error, Selector}; use iced_test::selector::{by_role, by_label, id}; use iced::core::widget::operation::accessible::Role; #[test] fn form_submission() -> Result<(), Error> { let mut app = App::default(); let mut ui = simulator(app.view()); // Click by widget ID let _ = ui.click(id("email-input"))?; // Type text let _ = ui.typewrite("user@example.com"); // Press keys let _ = ui.tap_key(iced::keyboard::key::Named::Tab); let _ = ui.typewrite("password123"); let _ = ui.tap_key(iced::keyboard::key::Named::Enter); for message in ui.into_messages() { let _ = app.update(message); } Ok(()) } ``` -------------------------------- ### Subscribing to Window Resize Events Source: https://context7.com/plushie-ui/plushie-iced/llms.txt Receive notifications when the application window is resized using `iced::window::resize_events`. The event provides the window ID and its new size, which are mapped to `Message::WindowResized`. ```rust window::resize_events().map(|(_id, size)| Message::WindowResized(size)) ``` -------------------------------- ### Implement View Logic Source: https://github.com/plushie-ui/plushie-iced/blob/main/examples/markdown/overview.md Renders the user interface based on the current state. This function returns an `iced::widget::Column` containing buttons for increment/decrement and a text display for the counter value. ```rust use iced::widget::{button, column, text, Column}; impl Counter { pub fn view(&self) -> Column<'_, Message> { // We use a column: a simple vertical layout column![ // The increment button. We tell it to produce an // `Increment` message when pressed button("+").on_press(Message::Increment), // We show the value of the counter here text(self.value).size(50), // The decrement button. We tell it to produce a // `Decrement` message when pressed button("-").on_press(Message::Decrement), ] } } ``` -------------------------------- ### Live Region Announcements Source: https://github.com/plushie-ui/plushie-iced/blob/main/docs/a11y-widget-guide.md Use `Live::Polite` for queued announcements of ambient status updates and `Live::Assertive` for urgent, interrupting alerts via the `announce()` API. ```rust Live::Polite ``` ```rust Live::Assertive ``` -------------------------------- ### Verify Accessibility with Selectors Source: https://github.com/plushie-ui/plushie-iced/blob/main/docs/a11y-widget-guide.md Use the simulator and selector API to assert that widgets exist in the accessibility tree with the expected roles and labels. ```rust use iced_test::simulator; use iced::widget::selector::{by_role, by_label}; use iced::core::widget::operation::accessible::Role; let mut ui = simulator(my_view()); let button = ui.find(by_role(Role::Button)); assert!(button.is_ok(), "button should appear in the tree"); let submit = ui.find(by_label("Submit")); assert!(submit.is_ok(), "button should have the label 'Submit'"); ``` -------------------------------- ### Run Application with Accessibility Features Source: https://github.com/plushie-ui/plushie-iced/blob/main/docs/a11y-widget-guide.md Enable the a11y feature during development to expose accessibility information to screen readers. ```sh cargo run -p todos --features iced/a11y ``` -------------------------------- ### Subscribing to Keyboard Events Source: https://context7.com/plushie-ui/plushie-iced/llms.txt Listen for keyboard input events using `iced::keyboard::listen`. The `filter_map` is used here to specifically capture `KeyPressed` events and map them to a `Message::KeyPressed`. ```rust keyboard::listen().filter_map(|event| { match event { keyboard::Event::KeyPressed { key, .. } => Some(Message::KeyPressed(key)), _ => None, } }) ``` -------------------------------- ### Combining Multiple Subscriptions Source: https://context7.com/plushie-ui/plushie-iced/llms.txt Aggregate several individual subscriptions into a single stream using `Subscription::batch`. This allows your application to react to multiple types of external events simultaneously. ```rust Subscription::batch([ // Time-based subscription - tick every 100ms time::every(milliseconds(100)).map(|_| Message::Tick), // Keyboard events keyboard::listen().filter_map(|event| { match event { keyboard::Event::KeyPressed { key, .. } => Some(Message::KeyPressed(key)), _ => None, } }), // Window resize events window::resize_events().map(|(_id, size)| Message::WindowResized(size)), // All runtime events event::listen().map(Message::Event), ]) ``` -------------------------------- ### Define Application State Source: https://github.com/plushie-ui/plushie-iced/blob/main/examples/markdown/overview.md Defines the state of the counter application. Use `#[derive(Default)]` for easy initialization. ```rust #[derive(Default)] struct Counter { value: i32, } ``` -------------------------------- ### Perform Snapshot Testing with iced_test Source: https://context7.com/plushie-ui/plushie-iced/llms.txt Enables snapshot testing to compare the UI against a stored hash. Supports different themes for testing. Requires `iced_test` and `iced` crates. ```rust use iced_test::{simulator, Error, Selector}; use iced_test::selector::{by_role, by_label, id}; use iced::core::widget::operation::accessible::Role; #[test] fn snapshot_testing() -> Result<(), Error> { let app = App::default(); let mut ui = simulator(app.view()); // Create snapshot and compare against stored hash let snapshot = ui.snapshot(&Theme::Dark)?; assert!( snapshot.matches_hash("snapshots/app_initial")?, "UI should match expected snapshot" ); Ok(()) } ``` -------------------------------- ### Implement operate method for accessibility Source: https://github.com/plushie-ui/plushie-iced/blob/main/docs/a11y-widget-guide.md A standard implementation of the operate method that exposes metadata, handles focus, and traverses child widgets. ```rust fn operate( &mut self, tree: &mut Tree, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn Operation, ) { let state = tree.state.downcast_mut::(); // 1. Expose accessible metadata first operation.accessible( self.id.as_ref(), layout.bounds(), &Accessible { role: Role::Button, label: Some("Submit"), disabled: self.on_press.is_none(), ..Accessible::default() }, ); // 2. Then focus/text state (associated with the node above) operation.focusable(self.id.as_ref(), layout.bounds(), state); // 3. Then children operation.container(self.id.as_ref(), layout.bounds()); operation.traverse(&mut |operation| { self.content.as_widget_mut().operate( &mut tree.children[0], layout.children().next().unwrap(), renderer, operation, ); }); } ``` -------------------------------- ### Apply Built-in Button Styles in Iced Source: https://context7.com/plushie-ui/plushie-iced/llms.txt Use predefined style functions like `button::primary` for consistent button appearances. These styles are part of the Iced framework. ```rust use iced::widget::{button, container, text}; use iced::{Background, Border, Color, Element, Theme}; fn view(state: &State) -> Element<'_, Message> { column![ // Use built-in style functions button("Primary").on_press(Message::Click).style(button::primary), button("Secondary").on_press(Message::Click).style(button::secondary), button("Success").on_press(Message::Click).style(button::success), button("Warning").on_press(Message::Click).style(button::warning), button("Danger").on_press(Message::Click).style(button::danger), // Custom inline style button("Custom").on_press(Message::Click).style(|theme: &Theme, status| { let palette = theme.palette(); match status { button::Status::Active => button::Style { background: Some(Background::Color(Color::from_rgb(0.2, 0.4, 0.6))), text_color: Color::WHITE, border: Border::default().rounded(8), ..button::Style::default() }, button::Status::Hovered => button::Style { background: Some(Background::Color(Color::from_rgb(0.3, 0.5, 0.7))), text_color: Color::WHITE, border: Border::default().rounded(8), ..button::Style::default() }, button::Status::Pressed => button::Style { background: Some(Background::Color(Color::from_rgb(0.1, 0.3, 0.5))), text_color: Color::WHITE, border: Border::default().rounded(8), ..button::Style::default() }, _ => button::primary(theme, status), } }), // Container with rounded box style container(text("Boxed content")) .padding(20) .style(container::rounded_box), // Custom container style container(text("Custom box")) .padding(20) .style(|_theme| container::Style { background: Some(Color::from_rgb(0.1, 0.1, 0.1).into()), border: Border::default().rounded(12).width(2).color(Color::WHITE), ..container::Style::default() }), ] .spacing(10) .into() } // Dynamic theme based on state fn theme(state: &State) -> Theme { if state.dark_mode { Theme::Dark } else { Theme::Light } } ``` -------------------------------- ### A11yAdapter for Platform Bridge Source: https://github.com/plushie-ui/plushie-iced/blob/main/docs/a11y-internals-guide.md The `A11yAdapter` is a per-window wrapper around `accesskit_winit::Adapter`. It manages the connection to the platform's accessibility API and is created before the window becomes visible. ```rust pub struct A11yAdapter { adapter: accesskit_winit::Adapter, // ... other fields } impl A11yAdapter { pub fn new(window: &winit::window::Window) -> Self { let adapter = accesskit_winit::Adapter::new(window); Self { adapter } } pub fn is_active(&self) -> bool { self.adapter.is_active() } pub fn update(&mut self, tree_update: TreeUpdate) { self.adapter.update(tree_update); } } ``` -------------------------------- ### Batching Multiple Tasks in Iced Source: https://context7.com/plushie-ui/plushie-iced/llms.txt Execute multiple asynchronous tasks concurrently using `Task::batch`. This is useful when you have several independent operations that can run in parallel. Each task should return a message upon completion. ```rust Task::batch([ Task::perform(async { /* task 1 */ }, |_| Message::Task1Done), Task::perform(async { /* task 2 */ }, |_| Message::Task2Done), ]) ``` -------------------------------- ### Simulate Counter Increments with iced_test Source: https://context7.com/plushie-ui/plushie-iced/llms.txt Tests UI interactions like button clicks and verifies state changes. Requires `iced_test` and `iced` crates. Ensure the counter widget displays the correct value after interactions. ```rust use iced_test::{simulator, Error, Selector}; use iced_test::selector::{by_role, by_label, id}; use iced::core::widget::operation::accessible::Role; #[test] fn counter_increments() -> Result<(), Error> { let mut counter = Counter { value: 0 }; let mut ui = simulator(counter.view()); // Click buttons by text content let _ = ui.click("Increment")?; let _ = ui.click("Increment")?; let _ = ui.click("Decrement")?; // Process messages for message in ui.into_messages() { counter.update(message); } assert_eq!(counter.value, 1); // Rebuild UI and verify display let mut ui = simulator(counter.view()); assert!(ui.find("1").is_ok(), "Counter should display 1!"); Ok(()) } ``` -------------------------------- ### Configure Accessible Widget Properties Source: https://github.com/plushie-ui/plushie-iced/blob/main/docs/a11y-widget-guide.md Use struct update syntax to define accessibility roles and values while falling back to default values for unspecified fields. ```rust Accessible { role: Role::Slider, value: Some(Value::Numeric { current: 50.0, min: 0.0, max: 100.0, step: Some(1.0), }), orientation: Some(Orientation::Vertical), ..Accessible::default() } ```