diff --git a/.github/workflows/fmt.yml b/.github/workflows/fmt.yml index 690e54d7f5e..2c8a8b9b495 100644 --- a/.github/workflows/fmt.yml +++ b/.github/workflows/fmt.yml @@ -16,7 +16,7 @@ jobs: - uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 with: - toolchain: stable + toolchain: nightly override: true profile: minimal components: rustfmt @@ -25,4 +25,5 @@ jobs: uses: actions-rs/cargo@v1 with: command: fmt + toolchain: nightly args: --all -- --check diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f27a882f158..94fe29828bb 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -73,7 +73,7 @@ The following command checks the code using Rustfmt and Clippy: cargo make lint ``` -To automatically fix formatting issues, run `cargo fmt` first. +To automatically fix formatting issues, run `cargo +nightly fmt` first. ## Benchmarks @@ -107,4 +107,4 @@ Below, you can find some useful guidance and best practices on how to write APIs The source code of our website ([https://yew.rs](https://yew.rs)) is in the [website directory](website). Most of the times, edits can be done in markdown. -[website/README.md](website/README.md) has more detailed instructions. \ No newline at end of file +[website/README.md](website/README.md) has more detailed instructions. diff --git a/Makefile.toml b/Makefile.toml index 2545218bc8e..3ef9b4de2e4 100644 --- a/Makefile.toml +++ b/Makefile.toml @@ -30,6 +30,7 @@ run_task = { name = ["lint", "lint-release", "tests"], fork = true } [tasks.lint] category = "Checks" description = "Check formatting and run Clippy" +toolchain = "nightly" run_task = { name = ["lint-flow"], fork = true } [tasks.tests] diff --git a/examples/agents/src/lib.rs b/examples/agents/src/lib.rs index aece68e3b9f..e6e04410cd8 100644 --- a/examples/agents/src/lib.rs +++ b/examples/agents/src/lib.rs @@ -1,6 +1,7 @@ pub mod native_worker; use std::rc::Rc; + use yew::{html, Component, Context, Html}; use yew_agent::{Bridge, Bridged}; diff --git a/examples/agents/src/native_worker.rs b/examples/agents/src/native_worker.rs index 12a2a061a44..b121fdee617 100644 --- a/examples/agents/src/native_worker.rs +++ b/examples/agents/src/native_worker.rs @@ -22,10 +22,10 @@ pub struct Worker { } impl yew_agent::Worker for Worker { - type Reach = Public; - type Message = Msg; type Input = Request; + type Message = Msg; type Output = Response; + type Reach = Public; fn create(link: WorkerLink) -> Self { let duration = 3; diff --git a/examples/boids/src/boid.rs b/examples/boids/src/boid.rs index f5a6fd31822..7e7de1367af 100644 --- a/examples/boids/src/boid.rs +++ b/examples/boids/src/boid.rs @@ -1,9 +1,11 @@ +use std::iter; + +use rand::Rng; +use yew::{html, Html}; + use crate::math::{self, Mean, Vector2D, WeightedMean}; use crate::settings::Settings; use crate::simulation::SIZE; -use rand::Rng; -use std::iter; -use yew::{html, Html}; #[derive(Clone, Debug, PartialEq)] pub struct Boid { diff --git a/examples/boids/src/main.rs b/examples/boids/src/main.rs index 28307bc8bfa..bb7e9405cc9 100644 --- a/examples/boids/src/main.rs +++ b/examples/boids/src/main.rs @@ -92,9 +92,10 @@ impl App { fn view_settings(&self, link: &Scope) -> Html { let Self { settings, .. } = self; - // This helper macro creates a callback which applies the new value to the current settings and sends `Msg::ChangeSettings`. - // Thanks to this, we don't need to have "ChangeBoids", "ChangeCohesion", etc. messages, - // but it comes at the cost of cloning the `Settings` struct each time. + // This helper macro creates a callback which applies the new value to the current settings + // and sends `Msg::ChangeSettings`. Thanks to this, we don't need to have + // "ChangeBoids", "ChangeCohesion", etc. messages, but it comes at the cost of + // cloning the `Settings` struct each time. macro_rules! settings_callback { ($link:expr, $settings:ident; $key:ident as $ty:ty) => {{ let settings = $settings.clone(); diff --git a/examples/boids/src/simulation.rs b/examples/boids/src/simulation.rs index ab88d01e986..6f74703b917 100644 --- a/examples/boids/src/simulation.rs +++ b/examples/boids/src/simulation.rs @@ -1,8 +1,9 @@ +use gloo::timers::callback::Interval; +use yew::{html, Component, Context, Html, Properties}; + use crate::boid::Boid; use crate::math::Vector2D; use crate::settings::Settings; -use gloo::timers::callback::Interval; -use yew::{html, Component, Context, Html, Properties}; pub const SIZE: Vector2D = Vector2D::new(1600.0, 1000.0); diff --git a/examples/boids/src/slider.rs b/examples/boids/src/slider.rs index 87f590531b9..b1bb59a37c6 100644 --- a/examples/boids/src/slider.rs +++ b/examples/boids/src/slider.rs @@ -1,6 +1,8 @@ use std::cell::Cell; + use web_sys::HtmlInputElement; -use yew::{events::InputEvent, html, Callback, Component, Context, Html, Properties, TargetCast}; +use yew::events::InputEvent; +use yew::{html, Callback, Component, Context, Html, Properties, TargetCast}; thread_local! { static SLIDER_ID: Cell = Cell::default(); diff --git a/examples/contexts/src/main.rs b/examples/contexts/src/main.rs index d8220feed37..d6531e49be1 100644 --- a/examples/contexts/src/main.rs +++ b/examples/contexts/src/main.rs @@ -3,13 +3,12 @@ mod producer; mod struct_component_subscriber; mod subscriber; +use msg_ctx::MessageProvider; use producer::Producer; use struct_component_subscriber::StructComponentSubscriber; use subscriber::Subscriber; use yew::prelude::*; -use msg_ctx::MessageProvider; - #[function_component] pub fn App() -> Html { html! { diff --git a/examples/contexts/src/struct_component_subscriber.rs b/examples/contexts/src/struct_component_subscriber.rs index 046b119cba8..5ed2121af69 100644 --- a/examples/contexts/src/struct_component_subscriber.rs +++ b/examples/contexts/src/struct_component_subscriber.rs @@ -1,7 +1,7 @@ -use super::msg_ctx::MessageContext; - use yew::prelude::*; +use super::msg_ctx::MessageContext; + pub enum Msg { MessageContextUpdated(MessageContext), } diff --git a/examples/contexts/src/subscriber.rs b/examples/contexts/src/subscriber.rs index ea93b11160c..7da9404655a 100644 --- a/examples/contexts/src/subscriber.rs +++ b/examples/contexts/src/subscriber.rs @@ -1,7 +1,7 @@ -use super::msg_ctx::MessageContext; - use yew::prelude::*; +use super::msg_ctx::MessageContext; + #[function_component] pub fn Subscriber() -> Html { let msg_ctx = use_context::().unwrap(); diff --git a/examples/dyn_create_destroy_apps/src/counter.rs b/examples/dyn_create_destroy_apps/src/counter.rs index 4a6dbc5c304..3154c19fa8d 100644 --- a/examples/dyn_create_destroy_apps/src/counter.rs +++ b/examples/dyn_create_destroy_apps/src/counter.rs @@ -1,4 +1,5 @@ -use gloo::{console, timers::callback::Interval}; +use gloo::console; +use gloo::timers::callback::Interval; use yew::prelude::*; pub struct CounterModel { @@ -17,7 +18,6 @@ pub enum CounterMessage { impl Component for CounterModel { type Message = CounterMessage; - type Properties = CounterProps; fn create(ctx: &Context) -> Self { diff --git a/examples/dyn_create_destroy_apps/src/main.rs b/examples/dyn_create_destroy_apps/src/main.rs index 658edbfac71..13740365eb4 100644 --- a/examples/dyn_create_destroy_apps/src/main.rs +++ b/examples/dyn_create_destroy_apps/src/main.rs @@ -16,7 +16,8 @@ pub enum Msg { } pub struct App { - apps: Slab<(Element, AppHandle)>, // Contains the spawned apps and their parent div elements + apps: Slab<(Element, AppHandle)>, /* Contains the spawned apps and their + * parent div elements */ apps_container_ref: NodeRef, } diff --git a/examples/file_upload/src/main.rs b/examples/file_upload/src/main.rs index 88584007aa0..0df42015646 100644 --- a/examples/file_upload/src/main.rs +++ b/examples/file_upload/src/main.rs @@ -1,10 +1,10 @@ use std::collections::HashMap; -use web_sys::{Event, HtmlInputElement}; -use yew::{html, html::TargetCast, Component, Context, Html}; - use gloo_file::callbacks::FileReader; use gloo_file::File; +use web_sys::{Event, HtmlInputElement}; +use yew::html::TargetCast; +use yew::{html, Component, Context, Html}; type Chunks = bool; diff --git a/examples/function_memory_game/src/components/app.rs b/examples/function_memory_game/src/components/app.rs index fae00a39fba..67a954e0c77 100644 --- a/examples/function_memory_game/src/components/app.rs +++ b/examples/function_memory_game/src/components/app.rs @@ -1,12 +1,13 @@ +use std::cell::RefCell; +use std::rc::Rc; + use gloo::timers::callback::{Interval, Timeout}; -use std::{cell::RefCell, rc::Rc}; use yew::prelude::*; use yew::{function_component, html}; -use crate::components::{ - chessboard::Chessboard, game_status_board::GameStatusBoard, score_board::ScoreBoard, -}; - +use crate::components::chessboard::Chessboard; +use crate::components::game_status_board::GameStatusBoard; +use crate::components::score_board::ScoreBoard; use crate::constant::Status; use crate::state::{Action, State}; diff --git a/examples/function_memory_game/src/components/game_status_board.rs b/examples/function_memory_game/src/components/game_status_board.rs index 19cd2813f14..de1aea5b7b7 100644 --- a/examples/function_memory_game/src/components/game_status_board.rs +++ b/examples/function_memory_game/src/components/game_status_board.rs @@ -1,7 +1,8 @@ -use crate::constant::Status; use yew::prelude::*; use yew::{function_component, html, Properties}; +use crate::constant::Status; + #[derive(Properties, Clone, PartialEq)] pub struct Props { pub status: Status, diff --git a/examples/function_memory_game/src/components/score_board.rs b/examples/function_memory_game/src/components/score_board.rs index e3c7efee0f2..03085f9ce40 100644 --- a/examples/function_memory_game/src/components/score_board.rs +++ b/examples/function_memory_game/src/components/score_board.rs @@ -1,8 +1,8 @@ use yew::{function_component, html, Html, Properties}; -use crate::components::{ - score_board_best_score::BestScore, score_board_logo::Logo, score_board_progress::GameProgress, -}; +use crate::components::score_board_best_score::BestScore; +use crate::components::score_board_logo::Logo; +use crate::components::score_board_progress::GameProgress; #[derive(PartialEq, Properties, Clone)] pub struct Props { diff --git a/examples/function_memory_game/src/state.rs b/examples/function_memory_game/src/state.rs index 6d3115ad76f..3baf243221b 100644 --- a/examples/function_memory_game/src/state.rs +++ b/examples/function_memory_game/src/state.rs @@ -1,6 +1,7 @@ +use std::rc::Rc; + use gloo::storage::{LocalStorage, Storage}; use serde::{Deserialize, Serialize}; -use std::rc::Rc; use yew::prelude::*; use crate::constant::{CardName, Status, KEY_BEST_SCORE}; diff --git a/examples/function_router/src/app.rs b/examples/function_router/src/app.rs index 4eac347d887..0195eaac9ba 100644 --- a/examples/function_router/src/app.rs +++ b/examples/function_router/src/app.rs @@ -6,10 +6,12 @@ use yew_router::history::{AnyHistory, History, MemoryHistory}; use yew_router::prelude::*; use crate::components::nav::Nav; -use crate::pages::{ - author::Author, author_list::AuthorList, home::Home, page_not_found::PageNotFound, post::Post, - post_list::PostList, -}; +use crate::pages::author::Author; +use crate::pages::author_list::AuthorList; +use crate::pages::home::Home; +use crate::pages::page_not_found::PageNotFound; +use crate::pages::post::Post; +use crate::pages::post_list::PostList; #[derive(Routable, PartialEq, Clone, Debug)] pub enum Route { diff --git a/examples/function_router/src/components/author_card.rs b/examples/function_router/src/components/author_card.rs index 98561d5e1cf..300d03e1ff5 100644 --- a/examples/function_router/src/components/author_card.rs +++ b/examples/function_router/src/components/author_card.rs @@ -1,9 +1,12 @@ use std::rc::Rc; -use crate::{content::Author, generator::Generated, Route}; use yew::prelude::*; use yew_router::prelude::*; +use crate::content::Author; +use crate::generator::Generated; +use crate::Route; + #[derive(Clone, Debug, PartialEq, Properties)] pub struct Props { pub seed: u32, diff --git a/examples/function_router/src/components/pagination.rs b/examples/function_router/src/components/pagination.rs index 5f859c8df55..80989bfb7eb 100644 --- a/examples/function_router/src/components/pagination.rs +++ b/examples/function_router/src/components/pagination.rs @@ -1,6 +1,6 @@ -use serde::Deserialize; -use serde::Serialize; use std::ops::Range; + +use serde::{Deserialize, Serialize}; use yew::prelude::*; use yew_router::prelude::*; diff --git a/examples/function_router/src/components/post_card.rs b/examples/function_router/src/components/post_card.rs index c48d3f599b4..02ae0005e05 100644 --- a/examples/function_router/src/components/post_card.rs +++ b/examples/function_router/src/components/post_card.rs @@ -1,9 +1,12 @@ use std::rc::Rc; -use crate::{content::PostMeta, generator::Generated, Route}; use yew::prelude::*; use yew_router::components::Link; +use crate::content::PostMeta; +use crate::generator::Generated; +use crate::Route; + #[derive(Clone, Debug, PartialEq, Properties)] pub struct Props { pub seed: u32, diff --git a/examples/function_router/src/generator.rs b/examples/function_router/src/generator.rs index b6d4da6b0fe..0ae69df0773 100644 --- a/examples/function_router/src/generator.rs +++ b/examples/function_router/src/generator.rs @@ -1,6 +1,9 @@ use lazy_static::lazy_static; use lipsum::MarkovChain; -use rand::{distributions::Bernoulli, rngs::StdRng, seq::IteratorRandom, Rng, SeedableRng}; +use rand::distributions::Bernoulli; +use rand::rngs::StdRng; +use rand::seq::IteratorRandom; +use rand::{Rng, SeedableRng}; const KEYWORDS: &str = include_str!("../data/keywords.txt"); const SYLLABLES: &str = include_str!("../data/syllables.txt"); diff --git a/examples/function_router/src/pages/author.rs b/examples/function_router/src/pages/author.rs index 1e3bafafc01..645f5d4e844 100644 --- a/examples/function_router/src/pages/author.rs +++ b/examples/function_router/src/pages/author.rs @@ -1,7 +1,9 @@ -use crate::components::author_card::AuthorState; -use crate::{content, generator::Generated}; use yew::prelude::*; +use crate::components::author_card::AuthorState; +use crate::content; +use crate::generator::Generated; + #[derive(Clone, Debug, Eq, PartialEq, Properties)] pub struct Props { pub seed: u32, diff --git a/examples/function_router/src/pages/author_list.rs b/examples/function_router/src/pages/author_list.rs index 005acd3de20..25d79b2d359 100644 --- a/examples/function_router/src/pages/author_list.rs +++ b/examples/function_router/src/pages/author_list.rs @@ -1,7 +1,9 @@ -use crate::components::{author_card::AuthorCard, progress_delay::ProgressDelay}; use rand::{distributions, Rng}; use yew::prelude::*; +use crate::components::author_card::AuthorCard; +use crate::components::progress_delay::ProgressDelay; + /// Amount of milliseconds to wait before showing the next set of authors. const CAROUSEL_DELAY_MS: u32 = 15000; diff --git a/examples/function_router/src/pages/post.rs b/examples/function_router/src/pages/post.rs index e1ecbf4d101..b5796b89da3 100644 --- a/examples/function_router/src/pages/post.rs +++ b/examples/function_router/src/pages/post.rs @@ -1,10 +1,12 @@ use std::rc::Rc; -use crate::{content, generator::Generated, Route}; use content::PostPart; use yew::prelude::*; use yew_router::prelude::*; +use crate::generator::Generated; +use crate::{content, Route}; + #[derive(Clone, Debug, Eq, PartialEq, Properties)] pub struct Props { pub seed: u32, diff --git a/examples/function_router/src/pages/post_list.rs b/examples/function_router/src/pages/post_list.rs index 264cf5cc05c..782b3cb58e0 100644 --- a/examples/function_router/src/pages/post_list.rs +++ b/examples/function_router/src/pages/post_list.rs @@ -1,9 +1,10 @@ -use crate::components::pagination::PageQuery; -use crate::components::{pagination::Pagination, post_card::PostCard}; -use crate::Route; use yew::prelude::*; use yew_router::prelude::*; +use crate::components::pagination::{PageQuery, Pagination}; +use crate::components::post_card::PostCard; +use crate::Route; + const ITEMS_PER_PAGE: u32 = 10; const TOTAL_PAGES: u32 = u32::MAX / ITEMS_PER_PAGE; diff --git a/examples/function_todomvc/src/components/entry.rs b/examples/function_todomvc/src/components/entry.rs index e59b3ac742b..147e8e1ad4a 100644 --- a/examples/function_todomvc/src/components/entry.rs +++ b/examples/function_todomvc/src/components/entry.rs @@ -1,9 +1,10 @@ -use crate::hooks::use_bool_toggle::use_bool_toggle; -use crate::state::Entry as Item; use web_sys::{HtmlInputElement, MouseEvent}; use yew::events::{Event, FocusEvent, KeyboardEvent}; use yew::prelude::*; +use crate::hooks::use_bool_toggle::use_bool_toggle; +use crate::state::Entry as Item; + #[derive(PartialEq, Properties, Clone)] pub struct EntryProps { pub entry: Item, diff --git a/examples/function_todomvc/src/components/filter.rs b/examples/function_todomvc/src/components/filter.rs index c540d14ef58..1c54f5fcf6d 100644 --- a/examples/function_todomvc/src/components/filter.rs +++ b/examples/function_todomvc/src/components/filter.rs @@ -1,6 +1,7 @@ -use crate::state::Filter as FilterEnum; use yew::prelude::*; +use crate::state::Filter as FilterEnum; + #[derive(PartialEq, Properties)] pub struct FilterProps { pub filter: FilterEnum, diff --git a/examples/function_todomvc/src/hooks/use_bool_toggle.rs b/examples/function_todomvc/src/hooks/use_bool_toggle.rs index d8281c1e7b1..128a7d8b01f 100644 --- a/examples/function_todomvc/src/hooks/use_bool_toggle.rs +++ b/examples/function_todomvc/src/hooks/use_bool_toggle.rs @@ -1,5 +1,6 @@ use std::ops::Deref; use std::rc::Rc; + use yew::prelude::*; #[derive(Clone)] diff --git a/examples/function_todomvc/src/main.rs b/examples/function_todomvc/src/main.rs index acfda1d23f3..a9eb5c6eb21 100644 --- a/examples/function_todomvc/src/main.rs +++ b/examples/function_todomvc/src/main.rs @@ -7,10 +7,10 @@ mod components; mod hooks; mod state; -use components::{ - entry::Entry as EntryItem, filter::Filter as FilterItem, header_input::HeaderInput, - info_footer::InfoFooter, -}; +use components::entry::Entry as EntryItem; +use components::filter::Filter as FilterItem; +use components::header_input::HeaderInput; +use components::info_footer::InfoFooter; const KEY: &str = "yew.functiontodomvc.self"; diff --git a/examples/function_todomvc/src/state.rs b/examples/function_todomvc/src/state.rs index f87586d34ed..e1ba147805a 100644 --- a/examples/function_todomvc/src/state.rs +++ b/examples/function_todomvc/src/state.rs @@ -1,9 +1,8 @@ use std::rc::Rc; -use yew::prelude::*; use serde::{Deserialize, Serialize}; -use strum_macros::Display; -use strum_macros::EnumIter; +use strum_macros::{Display, EnumIter}; +use yew::prelude::*; #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct State { diff --git a/examples/futures/src/main.rs b/examples/futures/src/main.rs index 1f2866d1851..cfd076c71c4 100644 --- a/examples/futures/src/main.rs +++ b/examples/futures/src/main.rs @@ -1,7 +1,6 @@ -use std::{ - error::Error, - fmt::{self, Debug, Display, Formatter}, -}; +use std::error::Error; +use std::fmt::{self, Debug, Display, Formatter}; + use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use wasm_bindgen_futures::JsFuture; diff --git a/examples/futures/src/markdown.rs b/examples/futures/src/markdown.rs index 4f105fa585b..415a0891b3e 100644 --- a/examples/futures/src/markdown.rs +++ b/examples/futures/src/markdown.rs @@ -107,7 +107,7 @@ pub fn render_markdown(src: &str) -> Html { fn make_tag(t: Tag) -> VTag { match t { Tag::Paragraph => VTag::new("p"), - Tag::Heading(n, _, _) => VTag::new(n.to_string()), + Tag::Heading(n, ..) => VTag::new(n.to_string()), Tag::BlockQuote => { let mut el = VTag::new("blockquote"); el.add_attribute("class", "blockquote"); @@ -118,9 +118,9 @@ fn make_tag(t: Tag) -> VTag { if let CodeBlockKind::Fenced(lang) = code_block_kind { // Different color schemes may be used for different code blocks, - // but a different library (likely js based at the moment) would be necessary to actually provide the - // highlighting support by locating the language classes and applying dom transforms - // on their contents. + // but a different library (likely js based at the moment) would be necessary to + // actually provide the highlighting support by locating the + // language classes and applying dom transforms on their contents. match lang.as_ref() { "html" => el.add_attribute("class", "html-language"), "rust" => el.add_attribute("class", "rust-language"), @@ -176,7 +176,9 @@ fn make_tag(t: Tag) -> VTag { } el } - Tag::FootnoteDefinition(ref _footnote_id) => VTag::new("span"), // Footnotes are not rendered as anything special + Tag::FootnoteDefinition(ref _footnote_id) => VTag::new("span"), // Footnotes are not + // rendered as anything + // special Tag::Strikethrough => { let mut el = VTag::new("span"); el.add_attribute("class", "text-decoration-strikethrough"); diff --git a/examples/js_callback/src/bindings.rs b/examples/js_callback/src/bindings.rs index 631193a6077..c99cefaf8fa 100644 --- a/examples/js_callback/src/bindings.rs +++ b/examples/js_callback/src/bindings.rs @@ -27,7 +27,8 @@ extern "C" { #[wasm_bindgen(module = "/js/unimp.js")] extern "C" { - /// This exists so that wasm bindgen copies js/unimp.js to dist/snippets/-/js/uninp.js + /// This exists so that wasm bindgen copies js/unimp.js to + /// dist/snippets/-/js/uninp.js #[wasm_bindgen] fn _dummy_fn_so_wasm_bindgen_copies_over_the_file(); } diff --git a/examples/js_callback/src/main.rs b/examples/js_callback/src/main.rs index 240b7bed3cd..6ba10851ce5 100644 --- a/examples/js_callback/src/main.rs +++ b/examples/js_callback/src/main.rs @@ -1,8 +1,7 @@ +use once_cell::sync::OnceCell; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use wasm_bindgen_futures::JsFuture; - -use once_cell::sync::OnceCell; use yew::prelude::*; use yew::suspense::{use_future, SuspensionResult}; diff --git a/examples/keyed_list/src/main.rs b/examples/keyed_list/src/main.rs index d5d6d9dae0e..a5be10bb355 100644 --- a/examples/keyed_list/src/main.rs +++ b/examples/keyed_list/src/main.rs @@ -178,6 +178,7 @@ impl App { } } + fn button_view(&self, link: &Scope) -> Html { html! { <> @@ -258,6 +259,7 @@ impl App { } } + fn info_view(&self) -> Html { let ids = if self.persons.len() < 20 { self.persons diff --git a/examples/keyed_list/src/person.rs b/examples/keyed_list/src/person.rs index 8a75ad4d53f..c7eda7e0cbf 100644 --- a/examples/keyed_list/src/person.rs +++ b/examples/keyed_list/src/person.rs @@ -1,11 +1,12 @@ -use crate::random; use std::rc::Rc; -use yew::{html, Component, Context, Html, Properties}; use fake::faker::address::raw::*; use fake::faker::name::raw::*; use fake::locales::*; use fake::Fake; +use yew::{html, Component, Context, Html, Properties}; + +use crate::random; #[derive(Clone, Debug, Eq, PartialEq)] pub struct PersonInfo { diff --git a/examples/nested_list/src/app.rs b/examples/nested_list/src/app.rs index f22e4570843..6c62b7d1c44 100644 --- a/examples/nested_list/src/app.rs +++ b/examples/nested_list/src/app.rs @@ -1,8 +1,9 @@ +use yew::prelude::*; + use super::header::ListHeader; use super::item::ListItem; use super::list::List; use super::{Hovered, WeakComponentLink}; -use yew::prelude::*; pub enum Msg { Hover(Hovered), diff --git a/examples/nested_list/src/header.rs b/examples/nested_list/src/header.rs index dbad68b6034..ac4296d5cfb 100644 --- a/examples/nested_list/src/header.rs +++ b/examples/nested_list/src/header.rs @@ -1,6 +1,7 @@ +use yew::prelude::*; + use super::list::{List, Msg as ListMsg}; use super::{Hovered, WeakComponentLink}; -use yew::prelude::*; #[derive(Clone, PartialEq, Properties)] pub struct Props { diff --git a/examples/nested_list/src/item.rs b/examples/nested_list/src/item.rs index fcbffd826c9..d93cc7a7670 100644 --- a/examples/nested_list/src/item.rs +++ b/examples/nested_list/src/item.rs @@ -1,6 +1,7 @@ -use crate::Hovered; use yew::prelude::*; +use crate::Hovered; + #[derive(PartialEq, Clone, Properties)] pub struct Props { #[prop_or_default] diff --git a/examples/nested_list/src/list.rs b/examples/nested_list/src/list.rs index 91e6db2acb2..66d999cce9d 100644 --- a/examples/nested_list/src/list.rs +++ b/examples/nested_list/src/list.rs @@ -1,11 +1,13 @@ -use crate::header::{ListHeader, Props as HeaderProps}; -use crate::item::{ListItem, Props as ItemProps}; -use crate::{Hovered, WeakComponentLink}; use std::rc::Rc; + use yew::html::{ChildrenRenderer, NodeRef}; use yew::prelude::*; use yew::virtual_dom::{VChild, VComp}; +use crate::header::{ListHeader, Props as HeaderProps}; +use crate::item::{ListItem, Props as ItemProps}; +use crate::{Hovered, WeakComponentLink}; + #[derive(Clone, PartialEq)] pub enum Variants { Item(Rc<::Properties>), diff --git a/examples/nested_list/src/main.rs b/examples/nested_list/src/main.rs index ea54369f213..881c0471b17 100644 --- a/examples/nested_list/src/main.rs +++ b/examples/nested_list/src/main.rs @@ -7,6 +7,7 @@ use std::cell::RefCell; use std::fmt; use std::ops::Deref; use std::rc::Rc; + use yew::html::{Component, ImplicitClone, Scope}; pub struct WeakComponentLink(Rc>>>); diff --git a/examples/password_strength/src/app.rs b/examples/password_strength/src/app.rs index 4bf55dcdd4b..b64f3e2829f 100644 --- a/examples/password_strength/src/app.rs +++ b/examples/password_strength/src/app.rs @@ -22,6 +22,7 @@ impl App { .ok() .map(|estimate| estimate.score()) } + fn redout_top_row_text(&self) -> String { if self.password.is_empty() { return "Provide a password".to_string(); diff --git a/examples/password_strength/src/text_input.rs b/examples/password_strength/src/text_input.rs index 48b099a7865..37c9ac357bb 100644 --- a/examples/password_strength/src/text_input.rs +++ b/examples/password_strength/src/text_input.rs @@ -1,8 +1,5 @@ -use wasm_bindgen::JsCast; -use wasm_bindgen::UnwrapThrowExt; -use web_sys::Event; -use web_sys::HtmlInputElement; -use web_sys::InputEvent; +use wasm_bindgen::{JsCast, UnwrapThrowExt}; +use web_sys::{Event, HtmlInputElement, InputEvent}; use yew::prelude::*; #[derive(Clone, PartialEq, Properties)] diff --git a/examples/router/src/components/author_card.rs b/examples/router/src/components/author_card.rs index 56eff10b159..74e0ecbb1ca 100644 --- a/examples/router/src/components/author_card.rs +++ b/examples/router/src/components/author_card.rs @@ -1,7 +1,10 @@ -use crate::{content::Author, generator::Generated, Route}; use yew::prelude::*; use yew_router::prelude::*; +use crate::content::Author; +use crate::generator::Generated; +use crate::Route; + #[derive(Clone, Debug, PartialEq, Properties)] pub struct Props { pub seed: u64, diff --git a/examples/router/src/components/pagination.rs b/examples/router/src/components/pagination.rs index 50e940d0ae3..76301d00ef9 100644 --- a/examples/router/src/components/pagination.rs +++ b/examples/router/src/components/pagination.rs @@ -1,5 +1,4 @@ -use serde::Deserialize; -use serde::Serialize; +use serde::{Deserialize, Serialize}; use yew::prelude::*; use yew_router::prelude::*; diff --git a/examples/router/src/components/post_card.rs b/examples/router/src/components/post_card.rs index ef29785f86e..a29a5506438 100644 --- a/examples/router/src/components/post_card.rs +++ b/examples/router/src/components/post_card.rs @@ -1,7 +1,10 @@ -use crate::{content::PostMeta, generator::Generated, Route}; use yew::prelude::*; use yew_router::components::Link; +use crate::content::PostMeta; +use crate::generator::Generated; +use crate::Route; + #[derive(Clone, Debug, PartialEq, Properties)] pub struct Props { pub seed: u64, @@ -19,6 +22,7 @@ impl Component for PostCard { post: PostMeta::generate_from_seed(ctx.props().seed), } } + fn changed(&mut self, ctx: &Context) -> bool { self.post = PostMeta::generate_from_seed(ctx.props().seed); true diff --git a/examples/router/src/generator.rs b/examples/router/src/generator.rs index ef6e4517e27..d71f51eab34 100644 --- a/examples/router/src/generator.rs +++ b/examples/router/src/generator.rs @@ -1,6 +1,9 @@ use lazy_static::lazy_static; use lipsum::MarkovChain; -use rand::{distributions::Bernoulli, rngs::SmallRng, seq::IteratorRandom, Rng, SeedableRng}; +use rand::distributions::Bernoulli; +use rand::rngs::SmallRng; +use rand::seq::IteratorRandom; +use rand::{Rng, SeedableRng}; const KEYWORDS: &str = include_str!("../data/keywords.txt"); const SYLLABLES: &str = include_str!("../data/syllables.txt"); diff --git a/examples/router/src/main.rs b/examples/router/src/main.rs index 14280b1897d..e108bdd3b92 100644 --- a/examples/router/src/main.rs +++ b/examples/router/src/main.rs @@ -5,10 +5,12 @@ mod components; mod content; mod generator; mod pages; -use pages::{ - author::Author, author_list::AuthorList, home::Home, page_not_found::PageNotFound, post::Post, - post_list::PostList, -}; +use pages::author::Author; +use pages::author_list::AuthorList; +use pages::home::Home; +use pages::page_not_found::PageNotFound; +use pages::post::Post; +use pages::post_list::PostList; use yew::html::Scope; #[derive(Routable, PartialEq, Clone, Debug)] diff --git a/examples/router/src/pages/author.rs b/examples/router/src/pages/author.rs index 2c183ff3ac2..02843274900 100644 --- a/examples/router/src/pages/author.rs +++ b/examples/router/src/pages/author.rs @@ -1,6 +1,8 @@ -use crate::{content, generator::Generated}; use yew::prelude::*; +use crate::content; +use crate::generator::Generated; + #[derive(Clone, Debug, Eq, PartialEq, Properties)] pub struct Props { pub seed: u64, diff --git a/examples/router/src/pages/author_list.rs b/examples/router/src/pages/author_list.rs index c93103cf1cf..477bd1abcf9 100644 --- a/examples/router/src/pages/author_list.rs +++ b/examples/router/src/pages/author_list.rs @@ -1,7 +1,9 @@ -use crate::components::{author_card::AuthorCard, progress_delay::ProgressDelay}; use rand::{distributions, Rng}; use yew::prelude::*; +use crate::components::author_card::AuthorCard; +use crate::components::progress_delay::ProgressDelay; + /// Amount of milliseconds to wait before showing the next set of authors. const CAROUSEL_DELAY_MS: u64 = 15000; diff --git a/examples/router/src/pages/post.rs b/examples/router/src/pages/post.rs index e8514acf0a9..92f716e3853 100644 --- a/examples/router/src/pages/post.rs +++ b/examples/router/src/pages/post.rs @@ -1,8 +1,10 @@ -use crate::{content, generator::Generated, Route}; use content::PostPart; use yew::prelude::*; use yew_router::prelude::*; +use crate::generator::Generated; +use crate::{content, Route}; + #[derive(Clone, Debug, Eq, PartialEq, Properties)] pub struct Props { pub seed: u64, diff --git a/examples/router/src/pages/post_list.rs b/examples/router/src/pages/post_list.rs index a85efba61e2..82fbe14badf 100644 --- a/examples/router/src/pages/post_list.rs +++ b/examples/router/src/pages/post_list.rs @@ -1,9 +1,10 @@ -use crate::components::pagination::PageQuery; -use crate::components::{pagination::Pagination, post_card::PostCard}; -use crate::Route; use yew::prelude::*; use yew_router::prelude::*; +use crate::components::pagination::{PageQuery, Pagination}; +use crate::components::post_card::PostCard; +use crate::Route; + const ITEMS_PER_PAGE: u64 = 10; const TOTAL_PAGES: u64 = u64::MAX / ITEMS_PER_PAGE; diff --git a/examples/simple_ssr/src/bin/simple_ssr_server.rs b/examples/simple_ssr/src/bin/simple_ssr_server.rs index 86b062081fd..bf86e7cf0dc 100644 --- a/examples/simple_ssr/src/bin/simple_ssr_server.rs +++ b/examples/simple_ssr/src/bin/simple_ssr_server.rs @@ -1,7 +1,8 @@ +use std::path::PathBuf; + use clap::Parser; use once_cell::sync::Lazy; use simple_ssr::App; -use std::path::PathBuf; use tokio_util::task::LocalPoolHandle; use warp::Filter; diff --git a/examples/simple_ssr/src/lib.rs b/examples/simple_ssr/src/lib.rs index ad7af2e0bba..893c2c94ce5 100644 --- a/examples/simple_ssr/src/lib.rs +++ b/examples/simple_ssr/src/lib.rs @@ -2,14 +2,13 @@ use std::cell::RefCell; use std::rc::Rc; use serde::{Deserialize, Serialize}; -use uuid::Uuid; -use yew::prelude::*; -use yew::suspense::{Suspension, SuspensionResult}; - #[cfg(not(target_arch = "wasm32"))] use tokio::task::spawn_local; +use uuid::Uuid; #[cfg(target_arch = "wasm32")] use wasm_bindgen_futures::spawn_local; +use yew::prelude::*; +use yew::suspense::{Suspension, SuspensionResult}; #[derive(Serialize, Deserialize)] struct UuidResponse { diff --git a/examples/ssr_router/src/bin/ssr_router_server.rs b/examples/ssr_router/src/bin/ssr_router_server.rs index d23a0e02198..fe29677afe2 100644 --- a/examples/ssr_router/src/bin/ssr_router_server.rs +++ b/examples/ssr_router/src/bin/ssr_router_server.rs @@ -1,8 +1,9 @@ +use std::collections::HashMap; +use std::path::PathBuf; + use clap::Parser; use function_router::{ServerApp, ServerAppProps}; use once_cell::sync::Lazy; -use std::collections::HashMap; -use std::path::PathBuf; use tokio_util::task::LocalPoolHandle; use warp::Filter; diff --git a/examples/timer/src/main.rs b/examples/timer/src/main.rs index 4f2ce8dada5..00d0df4504b 100644 --- a/examples/timer/src/main.rs +++ b/examples/timer/src/main.rs @@ -1,7 +1,5 @@ -use gloo::{ - console::{self, Timer}, - timers::callback::{Interval, Timeout}, -}; +use gloo::console::{self, Timer}; +use gloo::timers::callback::{Interval, Timeout}; use yew::{html, Component, Context, Html}; pub enum Msg { diff --git a/examples/todomvc/src/main.rs b/examples/todomvc/src/main.rs index 1ea9dc2b6de..1fa5e93a830 100644 --- a/examples/todomvc/src/main.rs +++ b/examples/todomvc/src/main.rs @@ -2,13 +2,9 @@ use gloo::storage::{LocalStorage, Storage}; use state::{Entry, Filter, State}; use strum::IntoEnumIterator; use web_sys::HtmlInputElement as InputElement; -use yew::{ - classes, - events::{FocusEvent, KeyboardEvent}, - html, - html::Scope, - Classes, Component, Context, Html, NodeRef, TargetCast, -}; +use yew::events::{FocusEvent, KeyboardEvent}; +use yew::html::Scope; +use yew::{classes, html, Classes, Component, Context, Html, NodeRef, TargetCast}; mod state; diff --git a/examples/web_worker_fib/src/agent.rs b/examples/web_worker_fib/src/agent.rs index 7f35e379aaa..c32e030b5cc 100644 --- a/examples/web_worker_fib/src/agent.rs +++ b/examples/web_worker_fib/src/agent.rs @@ -16,10 +16,10 @@ pub struct WorkerOutput { } impl yew_agent::Worker for Worker { - type Reach = Public; - type Message = (); type Input = WorkerInput; + type Message = (); type Output = WorkerOutput; + type Reach = Public; fn create(link: WorkerLink) -> Self { Self { link } diff --git a/examples/web_worker_fib/src/app.rs b/examples/web_worker_fib/src/app.rs index 0605760299b..2c6a605f712 100644 --- a/examples/web_worker_fib/src/app.rs +++ b/examples/web_worker_fib/src/app.rs @@ -1,10 +1,11 @@ -use crate::agent::{Worker, WorkerInput, WorkerOutput}; use std::rc::Rc; use web_sys::HtmlInputElement; use yew::prelude::*; use yew_agent::{Bridge, Bridged}; +use crate::agent::{Worker, WorkerInput, WorkerOutput}; + pub struct App { clicker_value: u32, input_ref: NodeRef, diff --git a/examples/webgl/src/main.rs b/examples/webgl/src/main.rs index 00f6ac21e0b..cc1166873fb 100644 --- a/examples/webgl/src/main.rs +++ b/examples/webgl/src/main.rs @@ -73,8 +73,8 @@ impl Component for App { request_animation_frame(move |time| link.send_message(Msg::Render(time))) }; - // A reference to the handle must be stored, otherwise it is dropped and the render won't - // occur. + // A reference to the handle must be stored, otherwise it is dropped and the render + // won't occur. self._render_loop = Some(handle); } } diff --git a/packages/yew-agent/src/hooks.rs b/packages/yew-agent/src/hooks.rs index a54324c2461..8422e5dedf7 100644 --- a/packages/yew-agent/src/hooks.rs +++ b/packages/yew-agent/src/hooks.rs @@ -1,9 +1,10 @@ use std::cell::RefCell; use std::rc::Rc; -use crate::*; use yew::prelude::*; +use crate::*; + /// State handle for [`use_bridge`] hook pub struct UseBridgeHandle where diff --git a/packages/yew-macro/src/derive_props/builder.rs b/packages/yew-macro/src/derive_props/builder.rs index 0fd6f9b9b50..7298b38a9dd 100644 --- a/packages/yew-macro/src/derive_props/builder.rs +++ b/packages/yew-macro/src/derive_props/builder.rs @@ -5,12 +5,13 @@ //! properties have been set, the builder moves to the final build step which implements the //! `build()` method. -use super::generics::{to_arguments, with_param_bounds, GenericArguments}; -use super::{DerivePropsInput, PropField}; use proc_macro2::{Ident, Span}; use quote::{format_ident, quote, ToTokens}; use syn::Attribute; +use super::generics::{to_arguments, with_param_bounds, GenericArguments}; +use super::{DerivePropsInput, PropField}; + pub struct PropsBuilder<'a> { builder_name: &'a Ident, step_trait: &'a Ident, diff --git a/packages/yew-macro/src/derive_props/field.rs b/packages/yew-macro/src/derive_props/field.rs index ed38abe7cf6..d122a5a03a1 100644 --- a/packages/yew-macro/src/derive_props/field.rs +++ b/packages/yew-macro/src/derive_props/field.rs @@ -1,13 +1,15 @@ -use super::generics::GenericArguments; -use super::should_preserve_attr; -use proc_macro2::{Ident, Span}; -use quote::{format_ident, quote, quote_spanned}; use std::cmp::{Ord, Ordering, PartialEq, PartialOrd}; use std::convert::TryFrom; + +use proc_macro2::{Ident, Span}; +use quote::{format_ident, quote, quote_spanned}; use syn::parse::Result; use syn::spanned::Spanned; use syn::{Attribute, Error, Expr, Field, Path, Type, TypePath, Visibility}; +use super::generics::GenericArguments; +use super::should_preserve_attr; + #[allow(clippy::large_enum_variant)] #[derive(PartialEq, Eq)] enum PropAttr { diff --git a/packages/yew-macro/src/derive_props/generics.rs b/packages/yew-macro/src/derive_props/generics.rs index 959e6bfd0d5..05ae5450dd5 100644 --- a/packages/yew-macro/src/derive_props/generics.rs +++ b/packages/yew-macro/src/derive_props/generics.rs @@ -1,8 +1,9 @@ use proc_macro2::{Ident, Span}; +use syn::punctuated::Punctuated; +use syn::token::Colon2; use syn::{ - punctuated::Punctuated, token::Colon2, GenericArgument, GenericParam, Generics, Path, - PathArguments, PathSegment, Token, TraitBound, TraitBoundModifier, Type, TypeParam, - TypeParamBound, TypePath, + GenericArgument, GenericParam, Generics, Path, PathArguments, PathSegment, Token, TraitBound, + TraitBoundModifier, Type, TypeParam, TypeParamBound, TypePath, }; /// Alias for a comma-separated list of `GenericArgument` @@ -18,7 +19,8 @@ fn first_default_or_const_param_position(generics: &Generics) -> Option { } /// Converts `GenericParams` into `GenericArguments` and adds `type_ident` as a type arg. -/// `type_ident` is added at the end of the existing type arguments which don't have a default value. +/// `type_ident` is added at the end of the existing type arguments which don't have a default +/// value. pub fn to_arguments(generics: &Generics, type_ident: Ident) -> GenericArguments { let mut args: GenericArguments = Punctuated::new(); args.extend(generics.params.iter().map(|param| match param { diff --git a/packages/yew-macro/src/derive_props/mod.rs b/packages/yew-macro/src/derive_props/mod.rs index 24160056b29..fc0edda21a7 100644 --- a/packages/yew-macro/src/derive_props/mod.rs +++ b/packages/yew-macro/src/derive_props/mod.rs @@ -3,11 +3,12 @@ mod field; mod generics; mod wrapper; +use std::convert::TryInto; + use builder::PropsBuilder; use field::PropField; use proc_macro2::{Ident, Span}; use quote::{format_ident, quote, ToTokens}; -use std::convert::TryInto; use syn::parse::{Parse, ParseStream, Result}; use syn::{Attribute, DeriveInput, Generics, Visibility}; use wrapper::PropsWrapper; @@ -23,10 +24,10 @@ pub struct DerivePropsInput { /// Some attributes on the original struct are to be preserved and added to the builder struct, /// in order to avoid warnings (sometimes reported as errors) in the output. fn should_preserve_attr(attr: &Attribute) -> bool { - // #[cfg(...)]: does not usually appear in macro inputs, but rust-analyzer seems to generate it sometimes. - // If not preserved, results in "no-such-field" errors generating the field setter for `build` - // #[allow(...)]: silences warnings from clippy, such as dead_code etc. - // #[deny(...)]: enable additional warnings from clippy + // #[cfg(...)]: does not usually appear in macro inputs, but rust-analyzer seems to generate it + // sometimes. If not preserved, results in "no-such-field" errors generating + // the field setter for `build` #[allow(...)]: silences warnings from clippy, such as + // dead_code etc. #[deny(...)]: enable additional warnings from clippy let path = &attr.path; path.is_ident("allow") || path.is_ident("deny") || path.is_ident("cfg") } diff --git a/packages/yew-macro/src/derive_props/wrapper.rs b/packages/yew-macro/src/derive_props/wrapper.rs index 7a7c147ac13..148a8e51feb 100644 --- a/packages/yew-macro/src/derive_props/wrapper.rs +++ b/packages/yew-macro/src/derive_props/wrapper.rs @@ -1,8 +1,9 @@ -use super::PropField; use proc_macro2::Ident; use quote::{quote, ToTokens}; use syn::{Attribute, Generics}; +use super::PropField; + pub struct PropsWrapper<'a> { wrapper_name: &'a Ident, generics: &'a Generics, diff --git a/packages/yew-macro/src/function_component.rs b/packages/yew-macro/src/function_component.rs index f5ad0008e03..75544fcdf88 100644 --- a/packages/yew-macro/src/function_component.rs +++ b/packages/yew-macro/src/function_component.rs @@ -253,8 +253,8 @@ impl FunctionComponent { let mut block = *block.clone(); let (impl_generics, _ty_generics, where_clause) = generics.split_for_impl(); - // We use _ctx here so if the component does not use any hooks, the usused_vars lint will not - // be triggered. + // We use _ctx here so if the component does not use any hooks, the usused_vars lint will + // not be triggered. let ctx_ident = Ident::new("_ctx", Span::mixed_site()); let mut body_rewriter = BodyRewriter::new(ctx_ident.clone()); diff --git a/packages/yew-macro/src/hook/body.rs b/packages/yew-macro/src/hook/body.rs index 13ea1dbdd5d..4bdba7bfc6c 100644 --- a/packages/yew-macro/src/hook/body.rs +++ b/packages/yew-macro/src/hook/body.rs @@ -1,5 +1,6 @@ -use proc_macro_error::emit_error; use std::sync::{Arc, Mutex}; + +use proc_macro_error::emit_error; use syn::spanned::Spanned; use syn::visit_mut::VisitMut; use syn::{ diff --git a/packages/yew-macro/src/hook/lifetime.rs b/packages/yew-macro/src/hook/lifetime.rs index 8b94ac5cdb6..03818effa4e 100644 --- a/packages/yew-macro/src/hook/lifetime.rs +++ b/packages/yew-macro/src/hook/lifetime.rs @@ -1,5 +1,6 @@ -use proc_macro2::Span; use std::sync::{Arc, Mutex}; + +use proc_macro2::Span; use syn::visit_mut::{self, VisitMut}; use syn::{ GenericArgument, Lifetime, ParenthesizedGenericArguments, Receiver, TypeBareFn, TypeImplTrait, diff --git a/packages/yew-macro/src/html_tree/html_block.rs b/packages/yew-macro/src/html_tree/html_block.rs index 2482326aaa8..82580ab03e0 100644 --- a/packages/yew-macro/src/html_tree/html_block.rs +++ b/packages/yew-macro/src/html_tree/html_block.rs @@ -1,11 +1,12 @@ -use super::{HtmlIterable, HtmlNode, ToNodeIterator}; -use crate::PeekValue; use proc_macro2::Delimiter; use quote::{quote, quote_spanned, ToTokens}; use syn::buffer::Cursor; use syn::parse::{Parse, ParseStream}; use syn::{braced, token}; +use super::{HtmlIterable, HtmlNode, ToNodeIterator}; +use crate::PeekValue; + pub struct HtmlBlock { pub content: BlockContent, brace: token::Brace, diff --git a/packages/yew-macro/src/html_tree/html_component.rs b/packages/yew-macro/src/html_tree/html_component.rs index b50af2c48bf..d2621db41a6 100644 --- a/packages/yew-macro/src/html_tree/html_component.rs +++ b/packages/yew-macro/src/html_tree/html_component.rs @@ -1,5 +1,3 @@ -use super::{HtmlChildrenTree, TagTokens}; -use crate::{props::ComponentProps, PeekValue}; use boolinator::Boolinator; use proc_macro2::Span; use quote::{quote, quote_spanned, ToTokens}; @@ -12,6 +10,10 @@ use syn::{ TypePath, }; +use super::{HtmlChildrenTree, TagTokens}; +use crate::props::ComponentProps; +use crate::PeekValue; + pub struct HtmlComponent { ty: Type, props: ComponentProps, diff --git a/packages/yew-macro/src/html_tree/html_dashed_name.rs b/packages/yew-macro/src/html_tree/html_dashed_name.rs index 8724ce4d6ea..72b3471d217 100644 --- a/packages/yew-macro/src/html_tree/html_dashed_name.rs +++ b/packages/yew-macro/src/html_tree/html_dashed_name.rs @@ -1,13 +1,16 @@ -use crate::{non_capitalized_ascii, stringify::Stringify, Peek}; +use std::fmt; + use boolinator::Boolinator; -use proc_macro2::Ident; -use proc_macro2::{Span, TokenStream}; +use proc_macro2::{Ident, Span, TokenStream}; use quote::{quote, ToTokens}; -use std::fmt; use syn::buffer::Cursor; use syn::ext::IdentExt; use syn::parse::{Parse, ParseStream}; -use syn::{spanned::Spanned, LitStr, Token}; +use syn::spanned::Spanned; +use syn::{LitStr, Token}; + +use crate::stringify::Stringify; +use crate::{non_capitalized_ascii, Peek}; #[derive(Clone, PartialEq)] pub struct HtmlDashedName { diff --git a/packages/yew-macro/src/html_tree/html_element.rs b/packages/yew-macro/src/html_tree/html_element.rs index fe7e7a8a6ff..a6f4908d3a1 100644 --- a/packages/yew-macro/src/html_tree/html_element.rs +++ b/packages/yew-macro/src/html_tree/html_element.rs @@ -1,7 +1,3 @@ -use super::{HtmlChildrenTree, HtmlDashedName, TagTokens}; -use crate::props::{ClassesForm, ElementProps, Prop}; -use crate::stringify::{Stringify, Value}; -use crate::{non_capitalized_ascii, Peek, PeekValue}; use boolinator::Boolinator; use proc_macro2::{Delimiter, TokenStream}; use proc_macro_error::emit_warning; @@ -11,6 +7,11 @@ use syn::parse::{Parse, ParseStream}; use syn::spanned::Spanned; use syn::{Block, Expr, Ident, Lit, LitStr, Token}; +use super::{HtmlChildrenTree, HtmlDashedName, TagTokens}; +use crate::props::{ClassesForm, ElementProps, Prop}; +use crate::stringify::{Stringify, Value}; +use crate::{non_capitalized_ascii, Peek, PeekValue}; + pub struct HtmlElement { pub name: TagName, pub props: ElementProps, @@ -55,7 +56,14 @@ impl Parse for HtmlElement { match name.to_ascii_lowercase_string().as_str() { "area" | "base" | "br" | "col" | "embed" | "hr" | "img" | "input" | "link" | "meta" | "param" | "source" | "track" | "wbr" => { - return Err(syn::Error::new_spanned(open.to_spanned(), format!("the tag `<{}>` is a void element and cannot have children (hint: rewrite this as `<{0}/>`)", name))); + return Err(syn::Error::new_spanned( + open.to_spanned(), + format!( + "the tag `<{}>` is a void element and cannot have children (hint: \ + rewrite this as `<{0}/>`)", + name + ), + )); } _ => {} } @@ -665,9 +673,10 @@ impl Parse for HtmlElementClose { if let TagName::Expr(name) = &name { if let Some(expr) = &name.expr { return Err(syn::Error::new_spanned( - expr, - "dynamic closing tags must not have a body (hint: replace it with just ``)", - )); + expr, + "dynamic closing tags must not have a body (hint: replace it with just \ + ``)", + )); } } diff --git a/packages/yew-macro/src/html_tree/html_if.rs b/packages/yew-macro/src/html_tree/html_if.rs index aae1890ab60..82793aba4fe 100644 --- a/packages/yew-macro/src/html_tree/html_if.rs +++ b/packages/yew-macro/src/html_tree/html_if.rs @@ -1,5 +1,3 @@ -use super::{HtmlRootBraced, ToNodeIterator}; -use crate::PeekValue; use boolinator::Boolinator; use proc_macro2::TokenStream; use quote::{quote_spanned, ToTokens}; @@ -8,6 +6,9 @@ use syn::parse::{Parse, ParseStream}; use syn::spanned::Spanned; use syn::{Expr, Token}; +use super::{HtmlRootBraced, ToNodeIterator}; +use crate::PeekValue; + pub struct HtmlIf { if_token: Token![if], cond: Box, diff --git a/packages/yew-macro/src/html_tree/html_iterable.rs b/packages/yew-macro/src/html_tree/html_iterable.rs index 700d28ab2ad..33d3333783b 100644 --- a/packages/yew-macro/src/html_tree/html_iterable.rs +++ b/packages/yew-macro/src/html_tree/html_iterable.rs @@ -1,5 +1,3 @@ -use super::ToNodeIterator; -use crate::PeekValue; use boolinator::Boolinator; use proc_macro2::TokenStream; use quote::{quote_spanned, ToTokens}; @@ -8,6 +6,9 @@ use syn::parse::{Parse, ParseStream}; use syn::spanned::Spanned; use syn::{Expr, Token}; +use super::ToNodeIterator; +use crate::PeekValue; + pub struct HtmlIterable(Expr); impl PeekValue<()> for HtmlIterable { diff --git a/packages/yew-macro/src/html_tree/html_list.rs b/packages/yew-macro/src/html_tree/html_list.rs index 4925ebdb3b3..c9ee3933c6d 100644 --- a/packages/yew-macro/src/html_tree/html_list.rs +++ b/packages/yew-macro/src/html_tree/html_list.rs @@ -1,5 +1,3 @@ -use super::{html_dashed_name::HtmlDashedName, HtmlChildrenTree, TagTokens}; -use crate::{props::Prop, Peek, PeekValue}; use boolinator::Boolinator; use quote::{quote, quote_spanned, ToTokens}; use syn::buffer::Cursor; @@ -7,6 +5,11 @@ use syn::parse::{Parse, ParseStream}; use syn::spanned::Spanned; use syn::Expr; +use super::html_dashed_name::HtmlDashedName; +use super::{HtmlChildrenTree, TagTokens}; +use crate::props::Prop; +use crate::{Peek, PeekValue}; + pub struct HtmlList { open: HtmlListOpen, pub children: HtmlChildrenTree, diff --git a/packages/yew-macro/src/html_tree/html_node.rs b/packages/yew-macro/src/html_tree/html_node.rs index d8cd6e19987..69457d92bd5 100644 --- a/packages/yew-macro/src/html_tree/html_node.rs +++ b/packages/yew-macro/src/html_tree/html_node.rs @@ -1,6 +1,3 @@ -use super::ToNodeIterator; -use crate::stringify::Stringify; -use crate::PeekValue; use proc_macro2::TokenStream; use quote::{quote_spanned, ToTokens}; use syn::buffer::Cursor; @@ -8,6 +5,10 @@ use syn::parse::{Parse, ParseStream, Result}; use syn::spanned::Spanned; use syn::{Expr, Lit}; +use super::ToNodeIterator; +use crate::stringify::Stringify; +use crate::PeekValue; + pub enum HtmlNode { Literal(Box), Expression(Box), diff --git a/packages/yew-macro/src/html_tree/lint/mod.rs b/packages/yew-macro/src/html_tree/lint/mod.rs index 48ca63406df..77fd51d96a3 100644 --- a/packages/yew-macro/src/html_tree/lint/mod.rs +++ b/packages/yew-macro/src/html_tree/lint/mod.rs @@ -4,11 +4,10 @@ use proc_macro_error::emit_warning; use syn::spanned::Spanned; +use super::html_element::{HtmlElement, TagName}; +use super::HtmlTree; use crate::props::{ElementProps, Prop}; -use super::html_element::TagName; -use super::{html_element::HtmlElement, HtmlTree}; - /// Lints HTML elements to check if they are well formed. If the element is not well-formed, then /// use `proc-macro-error` (and the `emit_warning!` macro) to produce a warning. At present, these /// are only emitted on nightly. @@ -100,7 +99,7 @@ impl Lint for ImgAltLint { emit_warning!( quote::quote! {#tag_name}.span(), "All `` tags should have an `alt` attribute which provides a \ - human-readable description " + human-readable description " ) } } diff --git a/packages/yew-macro/src/html_tree/mod.rs b/packages/yew-macro/src/html_tree/mod.rs index 038ccc36b85..94edaeefe8b 100644 --- a/packages/yew-macro/src/html_tree/mod.rs +++ b/packages/yew-macro/src/html_tree/mod.rs @@ -1,12 +1,12 @@ -use crate::PeekValue; use proc_macro2::{Delimiter, Ident, Span, TokenStream}; use quote::{quote, quote_spanned, ToTokens}; use syn::buffer::Cursor; use syn::ext::IdentExt; use syn::parse::{Parse, ParseStream}; use syn::spanned::Spanned; -use syn::Token; -use syn::{braced, token}; +use syn::{braced, token, Token}; + +use crate::PeekValue; mod html_block; mod html_component; @@ -65,9 +65,9 @@ impl Parse for HtmlTree { impl HtmlTree { /// Determine the [`HtmlType`] before actually parsing it. - /// Even though this method accepts a [`ParseStream`], it is forked and the original stream is not modified. - /// Once a certain `HtmlType` can be deduced for certain, the function eagerly returns with the appropriate type. - /// If invalid html tag, returns `None`. + /// Even though this method accepts a [`ParseStream`], it is forked and the original stream is + /// not modified. Once a certain `HtmlType` can be deduced for certain, the function eagerly + /// returns with the appropriate type. If invalid html tag, returns `None`. fn peek_html_type(input: ParseStream) -> Option { let input = input.fork(); // do not modify original ParseStream @@ -151,7 +151,8 @@ impl Parse for HtmlRoot { let stream: TokenStream = input.parse()?; Err(syn::Error::new_spanned( stream, - "only one root html element is allowed (hint: you can wrap multiple html elements in a fragment `<>`)", + "only one root html element is allowed (hint: you can wrap multiple html elements \ + in a fragment `<>`)", )) } else { Ok(html_root) @@ -189,9 +190,10 @@ impl ToTokens for HtmlRootVNode { /// This trait represents a type that can be unfolded into multiple html nodes. pub trait ToNodeIterator { - /// Generate a token stream which produces a value that implements IntoIterator where T is inferred by the compiler. - /// The easiest way to achieve this is to call `.into()` on each element. - /// If the resulting iterator only ever yields a single item this function should return None instead. + /// Generate a token stream which produces a value that implements IntoIterator where T + /// is inferred by the compiler. The easiest way to achieve this is to call `.into()` on + /// each element. If the resulting iterator only ever yields a single item this function + /// should return None instead. fn to_node_iterator_stream(&self) -> Option; } @@ -234,7 +236,8 @@ impl HtmlChildrenTree { let Self(children) = self; if self.only_single_node_children() { - // optimize for the common case where all children are single nodes (only using literal html). + // optimize for the common case where all children are single nodes (only using literal + // html). let children_into = children .iter() .map(|child| quote_spanned! {child.span()=> ::std::convert::Into::into(#child) }); diff --git a/packages/yew-macro/src/html_tree/tag.rs b/packages/yew-macro/src/html_tree/tag.rs index b81dd64257f..7c492f9843f 100644 --- a/packages/yew-macro/src/html_tree/tag.rs +++ b/packages/yew-macro/src/html_tree/tag.rs @@ -1,9 +1,7 @@ use proc_macro2::{Span, TokenStream, TokenTree}; use quote::{quote, ToTokens}; -use syn::{ - parse::{ParseStream, Parser}, - Token, -}; +use syn::parse::{ParseStream, Parser}; +use syn::Token; /// Check whether two spans are equal. /// The implementation is really silly but I couldn't find another way to do it on stable. @@ -60,10 +58,12 @@ impl TagTokens { let scope_spanned = tag.to_spanned(); let content_parser = |input: ParseStream| { parse(input, tag).map_err(|err| { - // we can't modify the scope span used by `ParseStream`. It just uses the call site by default. - // The scope span is used when an error can't be attributed to a token tree (ex. when the input is empty). - // We rewrite all spans to point at the tag which at least narrows down the correct location. - // It's not ideal, but it'll have to do until `syn` gives us more access. + // we can't modify the scope span used by `ParseStream`. It just uses the call site + // by default. The scope span is used when an error can't be + // attributed to a token tree (ex. when the input is empty). + // We rewrite all spans to point at the tag which at least narrows down the correct + // location. It's not ideal, but it'll have to do until `syn` gives + // us more access. error_replace_span(err, Span::call_site(), &scope_spanned) }) }; diff --git a/packages/yew-macro/src/props/component.rs b/packages/yew-macro/src/props/component.rs index 7dcc97ac6a0..d258d4f3974 100644 --- a/packages/yew-macro/src/props/component.rs +++ b/packages/yew-macro/src/props/component.rs @@ -1,13 +1,13 @@ -use super::{Prop, Props, SpecialProps, CHILDREN_LABEL}; +use std::convert::TryFrom; + use proc_macro2::{Ident, TokenStream}; use quote::{quote, quote_spanned, ToTokens}; -use std::convert::TryFrom; -use syn::{ - parse::{Parse, ParseStream}, - spanned::Spanned, - token::Dot2, - Expr, -}; +use syn::parse::{Parse, ParseStream}; +use syn::spanned::Spanned; +use syn::token::Dot2; +use syn::Expr; + +use super::{Prop, Props, SpecialProps, CHILDREN_LABEL}; struct BaseExpr { pub dot2: Dot2, diff --git a/packages/yew-macro/src/props/element.rs b/packages/yew-macro/src/props/element.rs index a3b06339e0a..37e71c23794 100644 --- a/packages/yew-macro/src/props/element.rs +++ b/packages/yew-macro/src/props/element.rs @@ -1,9 +1,11 @@ -use super::{Prop, Props, SpecialProps}; -use lazy_static::lazy_static; use std::collections::HashSet; + +use lazy_static::lazy_static; use syn::parse::{Parse, ParseStream}; use syn::{Expr, ExprTuple}; +use super::{Prop, Props, SpecialProps}; + pub enum ClassesForm { Tuple(ExprTuple), Single(Box), diff --git a/packages/yew-macro/src/props/prop.rs b/packages/yew-macro/src/props/prop.rs index 856b0a25d3d..4b9240a0208 100644 --- a/packages/yew-macro/src/props/prop.rs +++ b/packages/yew-macro/src/props/prop.rs @@ -1,17 +1,14 @@ +use std::cmp::Ordering; +use std::convert::TryFrom; +use std::ops::{Deref, DerefMut}; + +use proc_macro2::{Spacing, TokenTree}; +use syn::parse::{Parse, ParseBuffer, ParseStream}; +use syn::token::Brace; +use syn::{braced, Block, Expr, ExprBlock, ExprPath, ExprRange, Stmt, Token}; + use super::CHILDREN_LABEL; use crate::html_tree::HtmlDashedName; -use proc_macro2::{Spacing, TokenTree}; -use std::{ - cmp::Ordering, - convert::TryFrom, - ops::{Deref, DerefMut}, -}; -use syn::{ - braced, - parse::{Parse, ParseBuffer, ParseStream}, - token::Brace, - Block, Expr, ExprBlock, ExprPath, ExprRange, Stmt, Token, -}; pub struct Prop { pub label: HtmlDashedName, @@ -54,7 +51,8 @@ impl Prop { } else { return Err(syn::Error::new_spanned( expr, - "missing label for property value. If trying to use the shorthand property syntax, only identifiers may be used", + "missing label for property value. If trying to use the shorthand property \ + syntax, only identifiers may be used", )); }?; @@ -67,7 +65,11 @@ impl Prop { let equals = input.parse::().map_err(|_| { syn::Error::new_spanned( &label, - format!("`{}` doesn't have a value. (hint: set the value to `true` or `false` for boolean attributes)", label), + format!( + "`{}` doesn't have a value. (hint: set the value to `true` or `false` for \ + boolean attributes)", + label + ), ) })?; if input.is_empty() { @@ -100,12 +102,11 @@ fn parse_prop_value(input: &ParseBuffer) -> syn::Result { match &expr { Expr::Lit(_) => Ok(expr), - _ => { - Err(syn::Error::new_spanned( - &expr, - "the property value must be either a literal or enclosed in braces. Consider adding braces around your expression.", - )) - } + _ => Err(syn::Error::new_spanned( + &expr, + "the property value must be either a literal or enclosed in braces. Consider \ + adding braces around your expression.", + )), } } } @@ -120,13 +121,14 @@ fn strip_braces(block: ExprBlock) -> syn::Result { match stmt { Stmt::Expr(expr) => Ok(expr), Stmt::Semi(_expr, semi) => Err(syn::Error::new_spanned( - semi, - "only an expression may be assigned as a property. Consider removing this semicolon", + semi, + "only an expression may be assigned as a property. Consider removing this \ + semicolon", + )), + _ => Err(syn::Error::new_spanned( + stmt, + "only an expression may be assigned as a property", )), - _ => Err(syn::Error::new_spanned( - stmt, - "only an expression may be assigned as a property", - )) } } block => Ok(Expr::Block(block)), @@ -296,8 +298,8 @@ pub struct SpecialProps { pub key: Option, } impl SpecialProps { - const REF_LABEL: &'static str = "ref"; const KEY_LABEL: &'static str = "key"; + const REF_LABEL: &'static str = "ref"; fn pop_from(props: &mut SortedPropList) -> syn::Result { let node_ref = props.pop_unique(Self::REF_LABEL)?; diff --git a/packages/yew-macro/src/props/prop_macro.rs b/packages/yew-macro/src/props/prop_macro.rs index 0f48f32029f..172b5f53be6 100644 --- a/packages/yew-macro/src/props/prop_macro.rs +++ b/packages/yew-macro/src/props/prop_macro.rs @@ -1,15 +1,15 @@ -use super::{ComponentProps, Prop, Props, SortedPropList}; -use crate::html_tree::HtmlDashedName; +use std::convert::TryInto; + use proc_macro2::TokenStream; use quote::{quote_spanned, ToTokens}; -use std::convert::TryInto; -use syn::{ - parse::{Parse, ParseStream}, - punctuated::Punctuated, - spanned::Spanned, - token::Brace, - Expr, Token, TypePath, -}; +use syn::parse::{Parse, ParseStream}; +use syn::punctuated::Punctuated; +use syn::spanned::Spanned; +use syn::token::Brace; +use syn::{Expr, Token, TypePath}; + +use super::{ComponentProps, Prop, Props, SortedPropList}; +use crate::html_tree::HtmlDashedName; /// Pop from `Punctuated` without leaving it in a state where it has trailing punctuation. fn pop_last_punctuated(punctuated: &mut Punctuated) -> Option { @@ -30,7 +30,8 @@ fn is_associated_properties(ty: &TypePath) -> bool { if let Some(seg) = segments_it.next_back() { // ... and we can be reasonably sure that the previous segment is a component ... if !crate::non_capitalized_ascii(&seg.ident.to_string()) { - // ... then we assume that this is an associated type like `Component::Properties` + // ... then we assume that this is an associated type like + // `Component::Properties` return true; } } @@ -73,7 +74,8 @@ impl Parse for PropsExpr { fn parse(input: ParseStream) -> syn::Result { let mut ty: TypePath = input.parse()?; - // if the type isn't already qualified (``) and it's an associated type (`MyComp::Properties`) ... + // if the type isn't already qualified (``) and it's an associated type + // (`MyComp::Properties`) ... if ty.qself.is_none() && is_associated_properties(&ty) { pop_last_punctuated(&mut ty.path.segments); // .. transform it into a "qualified-self" type diff --git a/packages/yew-macro/tests/html_macro_test.rs b/packages/yew-macro/tests/html_macro_test.rs index 1c4a5b2b4d7..e242ebb87e4 100644 --- a/packages/yew-macro/tests/html_macro_test.rs +++ b/packages/yew-macro/tests/html_macro_test.rs @@ -11,7 +11,8 @@ fn html_macro() { #[test] #[should_panic( - expected = "a dynamic tag tried to create a `
` tag with children. `
` is a void element which can't have any children." + expected = "a dynamic tag tried to create a `
` tag with children. `
` is a void \ + element which can't have any children." )] fn dynamic_tags_catch_void_elements() { html! { diff --git a/packages/yew-router/src/components/link.rs b/packages/yew-router/src/components/link.rs index ac5e705cac0..b3db4702fb3 100644 --- a/packages/yew-router/src/components/link.rs +++ b/packages/yew-router/src/components/link.rs @@ -7,8 +7,7 @@ use yew::virtual_dom::AttrValue; use crate::navigator::NavigatorKind; use crate::scope_ext::RouterScopeExt; -use crate::utils; -use crate::Routable; +use crate::{utils, Routable}; /// Props for [`Link`] #[derive(Properties, Clone, PartialEq)] diff --git a/packages/yew-router/src/hooks.rs b/packages/yew-router/src/hooks.rs index 89c7585b348..c2b1059bbc7 100644 --- a/packages/yew-router/src/hooks.rs +++ b/packages/yew-router/src/hooks.rs @@ -1,12 +1,12 @@ //! Hooks to access router state and navigate between pages. +use yew::prelude::*; + use crate::history::*; use crate::navigator::Navigator; use crate::routable::Routable; use crate::router::{LocationContext, NavigatorContext}; -use yew::prelude::*; - /// A hook to access the [`Navigator`]. #[hook] pub fn use_navigator() -> Option { diff --git a/packages/yew-router/src/lib.rs b/packages/yew-router/src/lib.rs index 891cfbee0a4..30207682ced 100644 --- a/packages/yew-router/src/lib.rs +++ b/packages/yew-router/src/lib.rs @@ -4,8 +4,8 @@ //! # Usage //! //! ```rust -//! use yew::prelude::*; //! use yew::functional::*; +//! use yew::prelude::*; //! use yew_router::prelude::*; //! //! #[derive(Debug, Clone, Copy, PartialEq, Routable)] @@ -102,7 +102,5 @@ pub mod prelude { pub use crate::scope_ext::{LocationHandle, NavigatorHandle, RouterScopeExt}; #[doc(no_inline)] pub use crate::Routable; - pub use crate::{BrowserRouter, HashRouter, Router}; - - pub use crate::Switch; + pub use crate::{BrowserRouter, HashRouter, Router, Switch}; } diff --git a/packages/yew-router/src/routable.rs b/packages/yew-router/src/routable.rs index 6306117f78d..301e15fb222 100644 --- a/packages/yew-router/src/routable.rs +++ b/packages/yew-router/src/routable.rs @@ -32,8 +32,8 @@ pub trait Routable: Clone + PartialEq { /// A special route that accepts any route. /// -/// This can be used with [`History`](gloo::history::History) and [`Location`](gloo::history::Location) -/// when the type of [`Routable`] is unknown. +/// This can be used with [`History`](gloo::history::History) and +/// [`Location`](gloo::history::Location) when the type of [`Routable`] is unknown. #[derive(Debug, Clone, PartialEq)] pub struct AnyRoute { path: String, diff --git a/packages/yew-router/src/router.rs b/packages/yew-router/src/router.rs index fa32a77fa76..cd2a3fc38f0 100644 --- a/packages/yew-router/src/router.rs +++ b/packages/yew-router/src/router.rs @@ -1,11 +1,12 @@ //! Router Component. use std::rc::Rc; +use yew::prelude::*; +use yew::virtual_dom::AttrValue; + use crate::history::{AnyHistory, BrowserHistory, HashHistory, History, Location}; use crate::navigator::Navigator; use crate::utils::{base_url, strip_slash_suffix}; -use yew::prelude::*; -use yew::virtual_dom::AttrValue; /// Props for [`Router`]. #[derive(Properties, PartialEq, Clone)] diff --git a/packages/yew-router/src/scope_ext.rs b/packages/yew-router/src/scope_ext.rs index 153874e51eb..b504a9ccbdd 100644 --- a/packages/yew-router/src/scope_ext.rs +++ b/packages/yew-router/src/scope_ext.rs @@ -1,11 +1,11 @@ +use yew::context::ContextHandle; +use yew::prelude::*; + use crate::history::Location; use crate::navigator::Navigator; use crate::routable::Routable; use crate::router::{LocationContext, NavigatorContext}; -use yew::context::ContextHandle; -use yew::prelude::*; - /// A [`ContextHandle`] for [`add_location_listener`](RouterScopeExt::add_location_listener). pub struct LocationHandle { _inner: ContextHandle, diff --git a/packages/yew-router/src/switch.rs b/packages/yew-router/src/switch.rs index 9792d68f581..a527ae49803 100644 --- a/packages/yew-router/src/switch.rs +++ b/packages/yew-router/src/switch.rs @@ -20,6 +20,7 @@ impl RenderFn { pub fn new(value: impl Fn(&R) -> Html + 'static) -> Self { Self(Rc::new(value)) } + pub fn render(&self, route: &R) -> Html { (self.0)(route) } diff --git a/packages/yew-router/src/utils.rs b/packages/yew-router/src/utils.rs index 38c8beaa379..c87555ca4ff 100644 --- a/packages/yew-router/src/utils.rs +++ b/packages/yew-router/src/utils.rs @@ -1,4 +1,5 @@ use std::cell::RefCell; + use wasm_bindgen::JsCast; pub(crate) fn strip_slash_suffix(path: &str) -> &str { @@ -10,8 +11,8 @@ thread_local! { static BASE_URL: RefCell> = RefCell::new(None); } -// This exists so we can cache the base url. It costs us a `to_string` call instead of a DOM API call. -// Considering base urls are generally short, it *should* be less expensive. +// This exists so we can cache the base url. It costs us a `to_string` call instead of a DOM API +// call. Considering base urls are generally short, it *should* be less expensive. pub fn base_url() -> Option { BASE_URL_LOADED.call_once(|| { BASE_URL.with(|val| { diff --git a/packages/yew-router/tests/basename.rs b/packages/yew-router/tests/basename.rs index a22687718ad..c2ccdfb69e0 100644 --- a/packages/yew-router/tests/basename.rs +++ b/packages/yew-router/tests/basename.rs @@ -1,6 +1,7 @@ +use std::time::Duration; + use gloo::timers::future::sleep; use serde::{Deserialize, Serialize}; -use std::time::Duration; use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure}; use yew::functional::function_component; use yew::prelude::*; diff --git a/packages/yew-router/tests/browser_router.rs b/packages/yew-router/tests/browser_router.rs index ae43f640882..49c14bdfd2c 100644 --- a/packages/yew-router/tests/browser_router.rs +++ b/packages/yew-router/tests/browser_router.rs @@ -1,6 +1,7 @@ +use std::time::Duration; + use gloo::timers::future::sleep; use serde::{Deserialize, Serialize}; -use std::time::Duration; use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure}; use yew::functional::function_component; use yew::prelude::*; diff --git a/packages/yew-router/tests/hash_router.rs b/packages/yew-router/tests/hash_router.rs index cb5130abab8..9ae7883966c 100644 --- a/packages/yew-router/tests/hash_router.rs +++ b/packages/yew-router/tests/hash_router.rs @@ -1,6 +1,7 @@ +use std::time::Duration; + use gloo::timers::future::sleep; use serde::{Deserialize, Serialize}; -use std::time::Duration; use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure}; use yew::functional::function_component; use yew::prelude::*; diff --git a/packages/yew-router/tests/link.rs b/packages/yew-router/tests/link.rs index 718ce3f13d1..ddff1bd9556 100644 --- a/packages/yew-router/tests/link.rs +++ b/packages/yew-router/tests/link.rs @@ -1,6 +1,7 @@ +use std::time::Duration; + use gloo::timers::future::sleep; use serde::{Deserialize, Serialize}; -use std::time::Duration; use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure}; use yew::functional::function_component; use yew::prelude::*; diff --git a/packages/yew/src/app_handle.rs b/packages/yew/src/app_handle.rs index a3269e2f212..de429705b06 100644 --- a/packages/yew/src/app_handle.rs +++ b/packages/yew/src/app_handle.rs @@ -1,12 +1,13 @@ //! [AppHandle] contains the state Yew keeps to bootstrap a component in an isolated scope. -use crate::dom_bundle::BSubtree; -use crate::html::Scoped; -use crate::html::{BaseComponent, NodeRef, Scope}; use std::ops::Deref; use std::rc::Rc; + use web_sys::Element; +use crate::dom_bundle::BSubtree; +use crate::html::{BaseComponent, NodeRef, Scope, Scoped}; + /// An instance of an application. #[derive(Debug)] #[cfg_attr(documenting, doc(cfg(feature = "csr")))] @@ -68,7 +69,6 @@ fn clear_element(host: &Element) { #[cfg(feature = "hydration")] mod feat_hydration { use super::*; - use crate::dom_bundle::Fragment; impl AppHandle diff --git a/packages/yew/src/callback.rs b/packages/yew/src/callback.rs index 7d6c7caace3..613457f7028 100644 --- a/packages/yew/src/callback.rs +++ b/packages/yew/src/callback.rs @@ -4,10 +4,11 @@ //! - [Counter](https://github.com/yewstack/yew/tree/master/examples/counter) //! - [Timer](https://github.com/yewstack/yew/tree/master/examples/timer) -use crate::html::ImplicitClone; use std::fmt; use std::rc::Rc; +use crate::html::ImplicitClone; + /// Universal callback wrapper. /// /// An `Rc` wrapper is used to make it cloneable. diff --git a/packages/yew/src/context.rs b/packages/yew/src/context.rs index 7572c82ea71..a46321c77e4 100644 --- a/packages/yew/src/context.rs +++ b/packages/yew/src/context.rs @@ -1,9 +1,11 @@ //! This module defines the `ContextProvider` component. +use std::cell::RefCell; + +use slab::Slab; + use crate::html::Scope; use crate::{html, Callback, Children, Component, Context, Html, Properties}; -use slab::Slab; -use std::cell::RefCell; /// Props for [`ContextProvider`] #[derive(Debug, Clone, PartialEq, Properties)] diff --git a/packages/yew/src/dom_bundle/bcomp.rs b/packages/yew/src/dom_bundle/bcomp.rs index c749a6428b4..1011bd6e48e 100644 --- a/packages/yew/src/dom_bundle/bcomp.rs +++ b/packages/yew/src/dom_bundle/bcomp.rs @@ -1,12 +1,15 @@ //! This module contains the bundle implementation of a virtual component [BComp]. +use std::any::TypeId; +use std::borrow::Borrow; +use std::fmt; + +use web_sys::Element; + use super::{BNode, BSubtree, Reconcilable, ReconcileTarget}; use crate::html::{AnyScope, Scoped}; use crate::virtual_dom::{Key, VComp}; use crate::NodeRef; -use std::fmt; -use std::{any::TypeId, borrow::Borrow}; -use web_sys::Element; /// A virtual component. Compare with [VComp]. pub(super) struct BComp { @@ -130,7 +133,6 @@ impl Reconcilable for VComp { #[cfg(feature = "hydration")] mod feat_hydration { use super::*; - use crate::dom_bundle::{Fragment, Hydratable}; impl Hydratable for VComp { @@ -175,20 +177,16 @@ mod feat_hydration { #[cfg(feature = "wasm_test")] #[cfg(test)] mod tests { - use super::*; - use crate::dom_bundle::{Bundle, Reconcilable, ReconcileTarget}; - use crate::scheduler; - use crate::{ - html, - virtual_dom::{Key, VChild, VNode}, - Children, Component, Context, Html, NodeRef, Properties, - }; - use gloo_utils::document; use std::ops::Deref; - use web_sys::Element; - use web_sys::Node; + use gloo_utils::document; use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure}; + use web_sys::{Element, Node}; + + use super::*; + use crate::dom_bundle::{Bundle, Reconcilable, ReconcileTarget}; + use crate::virtual_dom::{Key, VChild, VNode}; + use crate::{html, scheduler, Children, Component, Context, Html, NodeRef, Properties}; wasm_bindgen_test_configure!(run_in_browser); @@ -353,12 +351,15 @@ mod tests { fn create(_: &Context) -> Self { Self } + fn update(&mut self, _ctx: &Context, _: Self::Message) -> bool { unimplemented!(); } + fn changed(&mut self, _ctx: &Context) -> bool { unimplemented!(); } + fn view(&self, ctx: &Context) -> Html { let item_iter = ctx .props() @@ -400,11 +401,7 @@ mod tests { .collect(); let children_renderer = Children::new(children.clone()); let expected_html = "\ -
    \ -
  • a
  • \ -
  • b
  • \ -
  • c
  • \ -
"; +
  • a
  • b
  • c
"; let prop_method = html! { @@ -487,13 +484,13 @@ mod tests { mod layout_tests { extern crate self as yew; - use crate::html; - use crate::tests::layout_tests::{diff_layouts, TestLayout}; - use crate::{Children, Component, Context, Html, Properties}; use std::marker::PhantomData; use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure}; + use crate::tests::layout_tests::{diff_layouts, TestLayout}; + use crate::{html, Children, Component, Context, Html, Properties}; + wasm_bindgen_test_configure!(run_in_browser); struct Comp { diff --git a/packages/yew/src/dom_bundle/blist.rs b/packages/yew/src/dom_bundle/blist.rs index 99afaf229d7..3d6c406aab3 100644 --- a/packages/yew/src/dom_bundle/blist.rs +++ b/packages/yew/src/dom_bundle/blist.rs @@ -1,15 +1,17 @@ //! This module contains fragments bundles, a [BList] -use super::{test_log, BNode, BSubtree}; -use crate::dom_bundle::{Reconcilable, ReconcileTarget}; -use crate::html::{AnyScope, NodeRef}; -use crate::virtual_dom::{Key, VList, VNode, VText}; use std::borrow::Borrow; use std::cmp::Ordering; use std::collections::HashSet; use std::hash::Hash; use std::ops::Deref; + use web_sys::Element; +use super::{test_log, BNode, BSubtree}; +use crate::dom_bundle::{Reconcilable, ReconcileTarget}; +use crate::html::{AnyScope, NodeRef}; +use crate::virtual_dom::{Key, VList, VNode, VText}; + /// This struct represents a mounted [VList] #[derive(Debug)] pub(super) struct BList { @@ -242,8 +244,8 @@ impl BList { writer = writer.patch(l, r); } - // Step 2. Diff matching children in the middle, that is between the first and last key mismatch - // Find first key mismatch from the front + // Step 2. Diff matching children in the middle, that is between the first and last key + // mismatch Find first key mismatch from the front let matching_len_start = matching_len( lefts.iter().map(|v| key!(v)), rev_bundles.iter().map(|v| key!(v)).rev(), @@ -264,14 +266,15 @@ impl BList { // The goal is to shift as few nodes as possible. // We handle runs of in-order nodes. When we encounter one out-of-order, we decide whether: - // - to shift all nodes in the current run to the position after the node before of the run, or to + // - to shift all nodes in the current run to the position after the node before of the run, + // or to // - "commit" to the current run, shift all nodes before the end of the run that we might // encounter in the future, and then start a new run. // Example of a run: // barrier_idx --v v-- end_idx // spliced_middle [ ... , M , N , C , D , E , F , G , ... ] (original element order) - // ^---^-----------^ the nodes that are part of the current run - // v start_writer + // ^---^-----------^ the nodes that are part of the current + // run v start_writer // replacements [ ... , M , C , D , G ] (new element order) // ^-- start_idx let mut barrier_idx = 0; // nodes from spliced_middle[..barrier_idx] are shifted unconditionally @@ -292,13 +295,16 @@ impl BList { if let Some(KeyedEntry(idx, _)) = ancestor { // If there are only few runs, this is a cold path if idx < run.end_idx { - // Have to decide whether to shift or commit the current run. A few calculations: - // A perfect estimate of the amount of nodes we have to shift if we move this run: + // Have to decide whether to shift or commit the current run. A few + // calculations: A perfect estimate of the amount of + // nodes we have to shift if we move this run: let run_length = replacements.len() - run.start_idx; - // A very crude estimate of the amount of nodes we will have to shift if we commit the run: - // Note nodes of the current run should not be counted here! + // A very crude estimate of the amount of nodes we will have to shift if we + // commit the run: Note nodes of the current run + // should not be counted here! let estimated_skipped_nodes = run.end_idx - idx.max(barrier_idx); - // double run_length to counteract that the run is part of the estimated_skipped_nodes + // double run_length to counteract that the run is part of the + // estimated_skipped_nodes if 2 * run_length > estimated_skipped_nodes { // less work to commit to this run barrier_idx = 1 + run.end_idx; @@ -318,7 +324,8 @@ impl BList { // We know that idx >= run.end_idx, so this node doesn't need to shift Some(run) => run.end_idx = idx, None => match idx.cmp(&barrier_idx) { - // peep hole optimization, don't start a run as the element is already where it should be + // peep hole optimization, don't start a run as the element is already where + // it should be Ordering::Equal => barrier_idx += 1, // shift the node unconditionally, don't start a run Ordering::Less => writer.shift(&mut r_bundle), @@ -456,7 +463,6 @@ impl Reconcilable for VList { #[cfg(feature = "hydration")] mod feat_hydration { use super::*; - use crate::dom_bundle::{Fragment, Hydratable}; impl Hydratable for VList { @@ -498,12 +504,12 @@ mod feat_hydration { mod layout_tests { extern crate self as yew; - use crate::html; - use crate::tests::layout_tests::{diff_layouts, TestLayout}; - #[cfg(feature = "wasm_test")] use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure}; + use crate::html; + use crate::tests::layout_tests::{diff_layouts, TestLayout}; + #[cfg(feature = "wasm_test")] wasm_bindgen_test_configure!(run_in_browser); @@ -576,14 +582,13 @@ mod layout_tests { mod layout_tests_keys { extern crate self as yew; - use crate::html; - use crate::tests::layout_tests::{diff_layouts, TestLayout}; - use crate::virtual_dom::VNode; - use crate::{Children, Component, Context, Html, Properties}; - use web_sys::Node; - #[cfg(feature = "wasm_test")] use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure}; + use web_sys::Node; + + use crate::tests::layout_tests::{diff_layouts, TestLayout}; + use crate::virtual_dom::VNode; + use crate::{html, Children, Component, Context, Html, Properties}; #[cfg(feature = "wasm_test")] wasm_bindgen_test_configure!(run_in_browser); diff --git a/packages/yew/src/dom_bundle/bnode.rs b/packages/yew/src/dom_bundle/bnode.rs index 79586b70361..b5e4ac5de4f 100644 --- a/packages/yew/src/dom_bundle/bnode.rs +++ b/packages/yew/src/dom_bundle/bnode.rs @@ -1,12 +1,14 @@ //! This module contains the bundle version of an abstract node [BNode] +use std::fmt; + +use gloo::console; +use web_sys::{Element, Node}; + use super::{BComp, BList, BPortal, BSubtree, BSuspense, BTag, BText}; use crate::dom_bundle::{Reconcilable, ReconcileTarget}; use crate::html::{AnyScope, NodeRef}; use crate::virtual_dom::{Key, VNode}; -use gloo::console; -use std::fmt; -use web_sys::{Element, Node}; /// The bundle implementation to [VNode]. pub(super) enum BNode { @@ -236,7 +238,6 @@ impl fmt::Debug for BNode { #[cfg(feature = "hydration")] mod feat_hydration { use super::*; - use crate::dom_bundle::{Fragment, Hydratable}; impl Hydratable for VNode { @@ -266,11 +267,17 @@ mod feat_hydration { } // You cannot hydrate a VRef. VNode::VRef(_) => { - panic!("VRef is not hydratable. Try moving it to a component mounted after an effect.") + panic!( + "VRef is not hydratable. Try moving it to a component mounted after an \ + effect." + ) } // You cannot hydrate a VPortal. VNode::VPortal(_) => { - panic!("VPortal is not hydratable. Try creating your portal by delaying it with use_effect.") + panic!( + "VPortal is not hydratable. Try creating your portal by delaying it with \ + use_effect." + ) } VNode::VSuspense(vsuspense) => { let (node_ref, suspense) = @@ -284,12 +291,12 @@ mod feat_hydration { #[cfg(test)] mod layout_tests { - use super::*; - use crate::tests::layout_tests::{diff_layouts, TestLayout}; - #[cfg(feature = "wasm_test")] use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure}; + use super::*; + use crate::tests::layout_tests::{diff_layouts, TestLayout}; + #[cfg(feature = "wasm_test")] wasm_bindgen_test_configure!(run_in_browser); diff --git a/packages/yew/src/dom_bundle/bportal.rs b/packages/yew/src/dom_bundle/bportal.rs index 155f37c60ae..c6ff790a6f2 100644 --- a/packages/yew/src/dom_bundle/bportal.rs +++ b/packages/yew/src/dom_bundle/bportal.rs @@ -1,11 +1,11 @@ //! This module contains the bundle implementation of a portal [BPortal]. +use web_sys::Element; + use super::{test_log, BNode, BSubtree}; use crate::dom_bundle::{Reconcilable, ReconcileTarget}; use crate::html::{AnyScope, NodeRef}; -use crate::virtual_dom::Key; -use crate::virtual_dom::VPortal; -use web_sys::Element; +use crate::virtual_dom::{Key, VPortal}; /// The bundle implementation to [VPortal]. #[derive(Debug)] @@ -120,13 +120,13 @@ impl BPortal { mod layout_tests { extern crate self as yew; + #[cfg(feature = "wasm_test")] + use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure}; + use yew::virtual_dom::VPortal; + use crate::html; use crate::tests::layout_tests::{diff_layouts, TestLayout}; use crate::virtual_dom::VNode; - use yew::virtual_dom::VPortal; - - #[cfg(feature = "wasm_test")] - use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure}; #[cfg(feature = "wasm_test")] wasm_bindgen_test_configure!(run_in_browser); diff --git a/packages/yew/src/dom_bundle/bsuspense.rs b/packages/yew/src/dom_bundle/bsuspense.rs index 8be6af8afb9..0aee86d034c 100644 --- a/packages/yew/src/dom_bundle/bsuspense.rs +++ b/packages/yew/src/dom_bundle/bsuspense.rs @@ -1,14 +1,14 @@ //! This module contains the bundle version of a supsense [BSuspense] -use super::{BNode, BSubtree, Reconcilable, ReconcileTarget}; -use crate::html::AnyScope; -use crate::virtual_dom::{Key, VSuspense}; -use crate::NodeRef; use gloo::utils::document; use web_sys::Element; #[cfg(feature = "hydration")] use super::Fragment; +use super::{BNode, BSubtree, Reconcilable, ReconcileTarget}; +use crate::html::AnyScope; +use crate::virtual_dom::{Key, VSuspense}; +use crate::NodeRef; #[derive(Debug)] enum Fallback { @@ -194,7 +194,8 @@ impl Reconcilable for VSuspense { (false, None) => { children.reconcile_node(root, parent_scope, parent, next_sibling, children_bundle) } - // Freshly suspended. Shift children into the detached parent, then add fallback to the DOM + // Freshly suspended. Shift children into the detached parent, then add fallback to the + // DOM (true, None) => { children_bundle.shift(&suspense.detached_parent, NodeRef::default()); @@ -237,7 +238,6 @@ impl Reconcilable for VSuspense { #[cfg(feature = "hydration")] mod feat_hydration { use super::*; - use crate::dom_bundle::{Fragment, Hydratable}; use crate::virtual_dom::Collectable; diff --git a/packages/yew/src/dom_bundle/btag/attributes.rs b/packages/yew/src/dom_bundle/btag/attributes.rs index 587f31b1edf..601da687899 100644 --- a/packages/yew/src/dom_bundle/btag/attributes.rs +++ b/packages/yew/src/dom_bundle/btag/attributes.rs @@ -1,17 +1,19 @@ -use super::Apply; -use crate::dom_bundle::BSubtree; -use crate::virtual_dom::vtag::{InputFields, Value}; -use crate::virtual_dom::Attributes; -use indexmap::IndexMap; use std::collections::HashMap; use std::iter; use std::ops::Deref; + +use indexmap::IndexMap; use web_sys::{Element, HtmlInputElement as InputElement, HtmlTextAreaElement as TextAreaElement}; use yew::AttrValue; +use super::Apply; +use crate::dom_bundle::BSubtree; +use crate::virtual_dom::vtag::{InputFields, Value}; +use crate::virtual_dom::Attributes; + impl Apply for Value { - type Element = T; type Bundle = Self; + type Element = T; fn apply(self, _root: &BSubtree, el: &Self::Element) -> Self { if let Some(v) = self.deref() { @@ -61,8 +63,8 @@ pub(super) trait AccessValue { } impl Apply for InputFields { - type Element = InputElement; type Bundle = Self; + type Element = InputElement; fn apply(mut self, root: &BSubtree, el: &Self::Element) -> Self { // IMPORTANT! This parameter has to be set every time @@ -182,8 +184,8 @@ impl Attributes { } impl Apply for Attributes { - type Element = Element; type Bundle = Self; + type Element = Element; fn apply(self, _root: &BSubtree, el: &Element) -> Self { match &self { diff --git a/packages/yew/src/dom_bundle/btag/listeners.rs b/packages/yew/src/dom_bundle/btag/listeners.rs index bba75bc6d1e..1d6dd283a86 100644 --- a/packages/yew/src/dom_bundle/btag/listeners.rs +++ b/packages/yew/src/dom_bundle/btag/listeners.rs @@ -1,13 +1,16 @@ -use super::Apply; -use crate::dom_bundle::{test_log, BSubtree, EventDescriptor}; -use crate::virtual_dom::{Listener, Listeners}; use std::cell::RefCell; use std::collections::HashMap; use std::ops::Deref; use std::rc::Rc; -use wasm_bindgen::{prelude::wasm_bindgen, JsCast}; + +use wasm_bindgen::prelude::wasm_bindgen; +use wasm_bindgen::JsCast; use web_sys::{Element, Event, EventTarget as HtmlEventTarget}; +use super::Apply; +use crate::dom_bundle::{test_log, BSubtree, EventDescriptor}; +use crate::virtual_dom::{Listener, Listeners}; + #[wasm_bindgen] extern "C" { // Duck-typing, not a real class on js-side. On rust-side, use impls of EventTarget below @@ -45,8 +48,8 @@ pub(super) enum ListenerRegistration { } impl Apply for Listeners { - type Element = Element; type Bundle = ListenerRegistration; + type Element = Element; fn apply(self, root: &BSubtree, el: &Self::Element) -> ListenerRegistration { match self { @@ -202,14 +205,16 @@ mod tests { use web_sys::{Event, EventInit, HtmlElement, MouseEvent}; wasm_bindgen_test_configure!(run_in_browser); - use crate::{ - create_portal, html, html::TargetCast, scheduler, virtual_dom::VNode, AppHandle, Component, - Context, Html, NodeRef, Properties, - }; use gloo_utils::document; use wasm_bindgen::JsCast; use yew::Callback; + use crate::html::TargetCast; + use crate::virtual_dom::VNode; + use crate::{ + create_portal, html, scheduler, AppHandle, Component, Context, Html, NodeRef, Properties, + }; + #[derive(Clone)] enum Message { Action, @@ -576,7 +581,8 @@ mod tests { assert_count(&el, 1); } - /// Here an event is being from inside a shadow root. It should only be caught exactly once on each handler + /// Here an event is being from inside a shadow root. It should only be caught exactly once on + /// each handler #[test] fn open_shadow_dom_bubbling() { use web_sys::{ShadowRootInit, ShadowRootMode}; diff --git a/packages/yew/src/dom_bundle/btag/mod.rs b/packages/yew/src/dom_bundle/btag/mod.rs index df9f9deb975..8c41a6e8ba5 100644 --- a/packages/yew/src/dom_bundle/btag/mod.rs +++ b/packages/yew/src/dom_bundle/btag/mod.rs @@ -3,20 +3,22 @@ mod attributes; mod listeners; +use std::borrow::Cow; +use std::hint::unreachable_unchecked; +use std::ops::DerefMut; + +use gloo::console; +use gloo_utils::document; +use listeners::ListenerRegistration; pub use listeners::Registry; +use wasm_bindgen::JsCast; +use web_sys::{Element, HtmlTextAreaElement as TextAreaElement}; use super::{insert_node, BList, BNode, BSubtree, Reconcilable, ReconcileTarget}; use crate::html::AnyScope; use crate::virtual_dom::vtag::{InputFields, VTagInner, Value, SVG_NAMESPACE}; use crate::virtual_dom::{Attributes, Key, VTag}; use crate::NodeRef; -use gloo::console; -use gloo_utils::document; -use listeners::ListenerRegistration; -use std::ops::DerefMut; -use std::{borrow::Cow, hint::unreachable_unchecked}; -use wasm_bindgen::JsCast; -use web_sys::{Element, HtmlTextAreaElement as TextAreaElement}; /// Applies contained changes to DOM [web_sys::Element] trait Apply { @@ -289,10 +291,10 @@ impl BTag { #[cfg(feature = "hydration")] mod feat_hydration { - use super::*; + use web_sys::Node; + use super::*; use crate::dom_bundle::{node_type_str, Fragment, Hydratable}; - use web_sys::Node; impl Hydratable for VTag { fn hydrate( @@ -382,18 +384,17 @@ mod feat_hydration { #[cfg(feature = "wasm_test")] #[cfg(test)] mod tests { + use gloo_utils::document; + use wasm_bindgen::JsCast; + use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure}; + use web_sys::HtmlInputElement as InputElement; + use super::*; use crate::dom_bundle::{BNode, Reconcilable, ReconcileTarget}; - use crate::html; use crate::html::AnyScope; use crate::virtual_dom::vtag::{HTML_NAMESPACE, SVG_NAMESPACE}; use crate::virtual_dom::{AttrValue, VNode, VTag}; - use crate::{Html, NodeRef}; - use gloo_utils::document; - use wasm_bindgen::JsCast; - use web_sys::HtmlInputElement as InputElement; - - use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure}; + use crate::{html, Html, NodeRef}; wasm_bindgen_test_configure!(run_in_browser); @@ -912,8 +913,8 @@ mod tests {
}; - // The point of this diff is to first render the "after" div and then detach the "before" div, - // while both should be bound to the same node ref + // The point of this diff is to first render the "after" div and then detach the "before" + // div, while both should be bound to the same node ref let (_, mut elem) = before.attach(&root, &scope, &parent, NodeRef::default()); after.reconcile_node(&root, &scope, &parent, NodeRef::default(), &mut elem); @@ -934,12 +935,12 @@ mod tests { mod layout_tests { extern crate self as yew; - use crate::html; - use crate::tests::layout_tests::{diff_layouts, TestLayout}; - #[cfg(feature = "wasm_test")] use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure}; + use crate::html; + use crate::tests::layout_tests::{diff_layouts, TestLayout}; + #[cfg(feature = "wasm_test")] wasm_bindgen_test_configure!(run_in_browser); diff --git a/packages/yew/src/dom_bundle/btext.rs b/packages/yew/src/dom_bundle/btext.rs index 8a0f506fce8..17a38debbcf 100644 --- a/packages/yew/src/dom_bundle/btext.rs +++ b/packages/yew/src/dom_bundle/btext.rs @@ -1,12 +1,13 @@ //! This module contains the bundle implementation of text [BText]. +use gloo::console; +use gloo_utils::document; +use web_sys::{Element, Text as TextNode}; + use super::{insert_node, BNode, BSubtree, Reconcilable, ReconcileTarget}; use crate::html::AnyScope; use crate::virtual_dom::{AttrValue, VText}; use crate::NodeRef; -use gloo::console; -use gloo_utils::document; -use web_sys::{Element, Text as TextNode}; /// The bundle implementation to [VText] pub(super) struct BText { @@ -91,12 +92,11 @@ impl std::fmt::Debug for BText { #[cfg(feature = "hydration")] mod feat_hydration { - use super::*; - + use wasm_bindgen::JsCast; use web_sys::Node; + use super::*; use crate::dom_bundle::{Fragment, Hydratable}; - use wasm_bindgen::JsCast; impl Hydratable for VText { fn hydrate( @@ -113,8 +113,9 @@ mod feat_hydration { // pop current node. fragment.pop_front(); - // TODO: It may make sense to assert the text content in the text node against - // the VText when #[cfg(debug_assertions)] is true, but this may be complicated. + // TODO: It may make sense to assert the text content in the text node + // against the VText when #[cfg(debug_assertions)] + // is true, but this may be complicated. // We always replace the text value for now. // // Please see the next comment for a detailed explanation. @@ -131,10 +132,11 @@ mod feat_hydration { } } - // If there are multiple text nodes placed back-to-back in SSR, it may be parsed as a single - // text node by browser, hence we need to add extra text nodes here if the next node is not a text node. - // Similarly, the value of the text node may be a combination of multiple VText vnodes. - // So we always need to override their values. + // If there are multiple text nodes placed back-to-back in SSR, it may be parsed as a + // single text node by browser, hence we need to add extra text nodes here + // if the next node is not a text node. Similarly, the value of the text + // node may be a combination of multiple VText vnodes. So we always need to + // override their values. self.attach( root, parent_scope, @@ -153,11 +155,11 @@ mod feat_hydration { mod test { extern crate self as yew; - use crate::html; - #[cfg(feature = "wasm_test")] use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure}; + use crate::html; + #[cfg(feature = "wasm_test")] wasm_bindgen_test_configure!(run_in_browser); @@ -177,12 +179,12 @@ mod test { mod layout_tests { extern crate self as yew; - use crate::html; - use crate::tests::layout_tests::{diff_layouts, TestLayout}; - #[cfg(feature = "wasm_test")] use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure}; + use crate::html; + use crate::tests::layout_tests::{diff_layouts, TestLayout}; + #[cfg(feature = "wasm_test")] wasm_bindgen_test_configure!(run_in_browser); diff --git a/packages/yew/src/dom_bundle/mod.rs b/packages/yew/src/dom_bundle/mod.rs index af5658c825b..aff317c277f 100644 --- a/packages/yew/src/dom_bundle/mod.rs +++ b/packages/yew/src/dom_bundle/mod.rs @@ -7,8 +7,7 @@ use web_sys::Element; -use crate::html::AnyScope; -use crate::html::NodeRef; +use crate::html::{AnyScope, NodeRef}; use crate::virtual_dom::VNode; mod bcomp; @@ -31,23 +30,19 @@ use blist::BList; use bnode::BNode; use bportal::BPortal; use bsuspense::BSuspense; - use btag::{BTag, Registry}; use btext::BText; -use subtree_root::EventDescriptor; -use traits::{Reconcilable, ReconcileTarget}; -use utils::{insert_node, test_log}; - -pub use subtree_root::set_event_bubbling; - -pub(crate) use subtree_root::BSubtree; - #[cfg(feature = "hydration")] pub(crate) use fragment::Fragment; +pub use subtree_root::set_event_bubbling; +pub(crate) use subtree_root::BSubtree; +use subtree_root::EventDescriptor; #[cfg(feature = "hydration")] use traits::Hydratable; +use traits::{Reconcilable, ReconcileTarget}; #[cfg(feature = "hydration")] use utils::node_type_str; +use utils::{insert_node, test_log}; /// A Bundle. /// diff --git a/packages/yew/src/dom_bundle/subtree_root.rs b/packages/yew/src/dom_bundle/subtree_root.rs index 6a2dbace540..c717123e683 100644 --- a/packages/yew/src/dom_bundle/subtree_root.rs +++ b/packages/yew/src/dom_bundle/subtree_root.rs @@ -1,16 +1,19 @@ //! Per-subtree state of apps -use super::{test_log, Registry}; -use crate::virtual_dom::{Listener, ListenerKind}; -use gloo::events::{EventListener, EventListenerOptions, EventListenerPhase}; use std::cell::RefCell; use std::collections::HashSet; use std::hash::{Hash, Hasher}; use std::rc::{Rc, Weak}; use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; -use wasm_bindgen::{prelude::wasm_bindgen, JsCast}; + +use gloo::events::{EventListener, EventListenerOptions, EventListenerPhase}; +use wasm_bindgen::prelude::wasm_bindgen; +use wasm_bindgen::JsCast; use web_sys::{Element, Event, EventTarget as HtmlEventTarget, ShadowRoot}; +use super::{test_log, Registry}; +use crate::virtual_dom::{Listener, ListenerKind}; + /// DOM-Types that capture (bubbling) events. This generally includes event targets, /// but also subtree roots. pub trait EventGrating { @@ -111,7 +114,6 @@ impl From<&dyn Listener> for EventDescriptor { } /// Ensures event handler registration. -// // Separate struct to DRY, while avoiding partial struct mutability. #[derive(Debug)] struct HostHandlers { @@ -201,6 +203,7 @@ impl AppData { weak_ref: Rc::downgrade(subtree), }); } + fn ensure_handled(&mut self, desc: &EventDescriptor) { if !self.listening.insert(desc.clone()) { return; @@ -342,13 +345,14 @@ impl SubtreeData { &'s self, event: &'s Event, ) -> Option> { - // Note: the event is not necessarily indentically the same object for all installed handlers - // hence this cache can be unreliable. Hence the cached repsonsible_tree_id might be missing. - // On the other hand, due to event retargeting at shadow roots, the cache might be wrong! - // Keep in mind that we handle events in the capture phase, so top-down. When descending and - // retargeting into closed shadow-dom, the event might have been handled 'prematurely'. - // TODO: figure out how to prevent this and establish correct event handling for closed shadow root. - // Note: Other frameworks also get this wrong and dispatch such events multiple times. + // Note: the event is not necessarily indentically the same object for all installed + // handlers hence this cache can be unreliable. Hence the cached repsonsible_tree_id + // might be missing. On the other hand, due to event retargeting at shadow roots, + // the cache might be wrong! Keep in mind that we handle events in the capture + // phase, so top-down. When descending and retargeting into closed shadow-dom, the + // event might have been handled 'prematurely'. TODO: figure out how to prevent this + // and establish correct event handling for closed shadow root. Note: Other + // frameworks also get this wrong and dispatch such events multiple times. let event_path = event.composed_path(); let derived_cached_key = event_path.length(); let cached_branding = if matches!(event.cache_key(), Some(cache_key) if cache_key == derived_cached_key) @@ -359,8 +363,8 @@ impl SubtreeData { }; if matches!(cached_branding, Some(responsible_tree_id) if responsible_tree_id != self.subtree_id) { - // some other handler has determined (via this function, but other `self`) a subtree that is - // responsible for handling this event, and it's not this subtree. + // some other handler has determined (via this function, but other `self`) a subtree + // that is responsible for handling this event, and it's not this subtree. return None; } // We're tasked with finding the subtree that is reponsible with handling the event, and/or @@ -396,8 +400,8 @@ impl SubtreeData { // # More details: When nesting occurs // // Event listeners are installed only on the subtree roots. Still, those roots can - // nest. This could lead to events getting handled multiple times. We want event handling to start - // at the most deeply nested subtree. + // nest. This could lead to events getting handled multiple times. We want event handling to + // start at the most deeply nested subtree. // // A nested subtree portals into an element that is controlled by the user and rendered // with VNode::VRef. We get the following dom nesting: @@ -412,6 +416,7 @@ impl SubtreeData { // {create_portal(, #portal_target)} // } + /// Handle a global event firing fn handle(&self, desc: EventDescriptor, event: Event) { let run_handler = |root: &Self, el: &Element| { @@ -430,6 +435,7 @@ impl SubtreeData { } } } + fn add_listener(self: &Rc, desc: &EventDescriptor) { let this = self.clone(); let listener = { @@ -454,10 +460,12 @@ impl BSubtree { root.brand_element(host_element); root } + /// Create a bundle root at the specified host element pub fn create_root(host_element: &HtmlEventTarget) -> Self { Self::do_create_root(host_element, None) } + /// Create a bundle root at the specified host element, that is logically /// mounted under the specified element in this tree. pub fn create_subroot(&self, mount_point: Element, host_element: &HtmlEventTarget) -> Self { @@ -467,15 +475,18 @@ impl BSubtree { }; Self::do_create_root(host_element, Some(parent_information)) } + /// Ensure the event described is handled on all subtrees pub fn ensure_handled(&self, desc: &EventDescriptor) { self.0.app_data.borrow_mut().ensure_handled(desc); } + /// Run f with access to global Registry #[inline] pub fn with_listener_registry(&self, f: impl FnOnce(&mut Registry) -> R) -> R { f(&mut *self.0.event_registry().borrow_mut()) } + pub fn brand_element(&self, el: &dyn EventGrating) { el.set_subtree_id(self.0.subtree_id); } diff --git a/packages/yew/src/dom_bundle/traits.rs b/packages/yew/src/dom_bundle/traits.rs index e87f17fc31b..481ba3929d9 100644 --- a/packages/yew/src/dom_bundle/traits.rs +++ b/packages/yew/src/dom_bundle/traits.rs @@ -1,6 +1,7 @@ +use web_sys::Element; + use super::{BNode, BSubtree}; use crate::html::{AnyScope, NodeRef}; -use web_sys::Element; /// A Reconcile Target. /// @@ -26,8 +27,7 @@ pub(super) trait Reconcilable { /// /// Parameters: /// - `root`: bundle of the subtree root - /// - `parent_scope`: the parent `Scope` used for passing messages to the - /// parent `Component`. + /// - `parent_scope`: the parent `Scope` used for passing messages to the parent `Component`. /// - `parent`: the parent node in the DOM. /// - `next_sibling`: to find where to put the node. /// @@ -48,14 +48,11 @@ pub(super) trait Reconcilable { /// the actual DOM representation. /// /// Parameters: - /// - `parent_scope`: the parent `Scope` used for passing messages to the - /// parent `Component`. + /// - `parent_scope`: the parent `Scope` used for passing messages to the parent `Component`. /// - `parent`: the parent node in the DOM. - /// - `next_sibling`: the next sibling, used to efficiently find where to - /// put the node. - /// - `bundle`: the node that this node will be replacing in the DOM. This - /// method will remove the `bundle` from the `parent` if it is of the wrong - /// kind, and otherwise reuse it. + /// - `next_sibling`: the next sibling, used to efficiently find where to put the node. + /// - `bundle`: the node that this node will be replacing in the DOM. This method will remove + /// the `bundle` from the `parent` if it is of the wrong kind, and otherwise reuse it. /// /// Returns a reference to the newly inserted element. fn reconcile_node( @@ -101,7 +98,6 @@ pub(super) trait Reconcilable { #[cfg(feature = "hydration")] mod feat_hydration { use super::*; - use crate::dom_bundle::Fragment; pub(in crate::dom_bundle) trait Hydratable: Reconcilable { diff --git a/packages/yew/src/dom_bundle/utils.rs b/packages/yew/src/dom_bundle/utils.rs index ee247ab28b1..8f0eb44f79e 100644 --- a/packages/yew/src/dom_bundle/utils.rs +++ b/packages/yew/src/dom_bundle/utils.rs @@ -32,13 +32,13 @@ pub(super) use test_log; #[cfg(feature = "hydration")] mod feat_hydration { - use super::*; - use std::borrow::Cow; use wasm_bindgen::JsCast; use web_sys::Element; + use super::*; + pub(in crate::dom_bundle) fn node_type_str(node: &Node) -> Cow<'static, str> { match node.node_type() { Node::ELEMENT_NODE => { diff --git a/packages/yew/src/functional/hooks/mod.rs b/packages/yew/src/functional/hooks/mod.rs index 57470f2aa03..1addd6ab413 100644 --- a/packages/yew/src/functional/hooks/mod.rs +++ b/packages/yew/src/functional/hooks/mod.rs @@ -20,9 +20,9 @@ use crate::functional::{AnyScope, HookContext}; /// A trait that is implemented on hooks. /// -/// Hooks are defined via the [`#[hook]`](crate::functional::hook) macro. It provides rewrites to hook invocations -/// and ensures that hooks can only be called at the top-level of a function component or a hook. -/// Please refer to its documentation on how to implement hooks. +/// Hooks are defined via the [`#[hook]`](crate::functional::hook) macro. It provides rewrites to +/// hook invocations and ensures that hooks can only be called at the top-level of a function +/// component or a hook. Please refer to its documentation on how to implement hooks. pub trait Hook { /// The return type when a hook is run. type Output; diff --git a/packages/yew/src/functional/hooks/use_callback.rs b/packages/yew/src/functional/hooks/use_callback.rs index 89dc0f1c788..af74cf0cec2 100644 --- a/packages/yew/src/functional/hooks/use_callback.rs +++ b/packages/yew/src/functional/hooks/use_callback.rs @@ -39,10 +39,7 @@ use crate::functional::{hook, use_memo}; /// /// // This callback depends on (), so it's created only once, then MyComponent /// // will be rendered only once even when you click the button mutiple times. -/// let callback = use_callback( -/// move |name, _| format!("Hello, {}!", name), -/// () -/// ); +/// let callback = use_callback(move |name, _| format!("Hello, {}!", name), ()); /// /// // It can also be used for events, this callback depends on `counter`. /// let oncallback = { @@ -51,7 +48,7 @@ use crate::functional::{hook, use_memo}; /// move |_e, counter| { /// let _ = **counter; /// }, -/// counter +/// counter, /// ) /// }; /// diff --git a/packages/yew/src/functional/hooks/use_context.rs b/packages/yew/src/functional/hooks/use_context.rs index a6bf2376e62..0a925659a87 100644 --- a/packages/yew/src/functional/hooks/use_context.rs +++ b/packages/yew/src/functional/hooks/use_context.rs @@ -3,8 +3,9 @@ use crate::context::ContextHandle; use crate::functional::{hook, use_component_scope, use_memo, use_state}; /// Hook for consuming context values in function components. -/// The context of the type passed as `T` is returned. If there is no such context in scope, `None` is returned. -/// A component which calls `use_context` will re-render when the data of the context changes. +/// The context of the type passed as `T` is returned. If there is no such context in scope, `None` +/// is returned. A component which calls `use_context` will re-render when the data of the context +/// changes. /// /// More information about contexts and how to define and consume them can be found on [Yew Docs](https://yew.rs). /// diff --git a/packages/yew/src/functional/hooks/use_force_update.rs b/packages/yew/src/functional/hooks/use_force_update.rs index 713dc14ac8c..e28fc06d274 100644 --- a/packages/yew/src/functional/hooks/use_force_update.rs +++ b/packages/yew/src/functional/hooks/use_force_update.rs @@ -1,6 +1,7 @@ +use std::fmt; + use super::{Hook, HookContext}; use crate::functional::ReRender; -use std::fmt; /// A handle which can be used to force a re-render of the associated /// function component. diff --git a/packages/yew/src/functional/hooks/use_memo.rs b/packages/yew/src/functional/hooks/use_memo.rs index f73b7c20dda..a40e0a13cab 100644 --- a/packages/yew/src/functional/hooks/use_memo.rs +++ b/packages/yew/src/functional/hooks/use_memo.rs @@ -1,6 +1,7 @@ -use super::use_mut_ref; -use std::{borrow::Borrow, rc::Rc}; +use std::borrow::Borrow; +use std::rc::Rc; +use super::use_mut_ref; use crate::functional::hook; /// Get a immutable reference to a memoized value. @@ -60,7 +61,7 @@ where /// // Will only get recalculated if `props.step` value changes /// let message = use_memo( /// |step| format!("{}. Do Some Expensive Calculation", step), -/// props.step +/// props.step, /// ); /// /// html! { diff --git a/packages/yew/src/functional/hooks/use_reducer.rs b/packages/yew/src/functional/hooks/use_reducer.rs index e764d813a3f..15ae1af68d7 100644 --- a/packages/yew/src/functional/hooks/use_reducer.rs +++ b/packages/yew/src/functional/hooks/use_reducer.rs @@ -217,10 +217,11 @@ where } /// This hook is an alternative to [`use_state`](super::use_state()). -/// It is used to handle component's state and is used when complex actions needs to be performed on said state. +/// It is used to handle component's state and is used when complex actions needs to be performed on +/// said state. /// -/// The state is expected to implement the [`Reducible`] trait which provides an `Action` type and a reducer -/// function. +/// The state is expected to implement the [`Reducible`] trait which provides an `Action` type and a +/// reducer function. /// /// The state object returned by the initial state function is required to /// implement a `Reducible` trait which defines the associated `Action` type and a @@ -260,7 +261,7 @@ where /// fn reduce(self: Rc, action: Self::Action) -> Rc { /// let next_ctr = match action { /// CounterAction::Double => self.counter * 2, -/// CounterAction::Square => self.counter.pow(2) +/// CounterAction::Square => self.counter.pow(2), /// }; /// /// Self { counter: next_ctr }.into() @@ -272,7 +273,7 @@ where /// // The use_reducer hook takes an initialization function which will be called only once. /// let counter = use_reducer(CounterState::default); /// -/// let double_onclick = { +/// let double_onclick = { /// let counter = counter.clone(); /// Callback::from(move |_| counter.dispatch(CounterAction::Double)) /// }; diff --git a/packages/yew/src/functional/hooks/use_ref.rs b/packages/yew/src/functional/hooks/use_ref.rs index a2c514b9568..7c769cad45d 100644 --- a/packages/yew/src/functional/hooks/use_ref.rs +++ b/packages/yew/src/functional/hooks/use_ref.rs @@ -20,7 +20,8 @@ impl T> Hook for UseMutRef { /// Its state persists across renders. /// /// It is important to note that you do not get notified of state changes. -/// If you need the component to be re-rendered on state change, consider using [`use_state`](super::use_state()). +/// If you need the component to be re-rendered on state change, consider using +/// [`use_state`](super::use_state()). /// /// # Example /// ```rust @@ -48,7 +49,7 @@ impl T> Hook for UseMutRef { /// /// let onchange = { /// let message = message.clone(); -/// Callback::from(move |e: Event| { +/// Callback::from(move |e: Event| { /// let input: HtmlInputElement = e.target_unchecked_into(); /// message.set(input.value()) /// }) diff --git a/packages/yew/src/functional/hooks/use_state.rs b/packages/yew/src/functional/hooks/use_state.rs index 1e83c4f64e4..489e1d1d292 100644 --- a/packages/yew/src/functional/hooks/use_state.rs +++ b/packages/yew/src/functional/hooks/use_state.rs @@ -11,6 +11,7 @@ struct UseStateReducer { impl Reducible for UseStateReducer { type Action = T; + fn reduce(self: Rc, action: Self::Action) -> Rc { Rc::new(Self { value: action }) } @@ -45,7 +46,6 @@ where /// Callback::from(move |_| counter.set(*counter + 1)) /// }; /// -/// /// html! { ///
/// diff --git a/packages/yew/src/functional/mod.rs b/packages/yew/src/functional/mod.rs index ca4dc006c52..7cde8da7a3a 100644 --- a/packages/yew/src/functional/mod.rs +++ b/packages/yew/src/functional/mod.rs @@ -2,9 +2,10 @@ //! They consist of a single function annotated with the attribute `#[function_component]` //! that receives props and determines what should be rendered by returning [`Html`](crate::Html). //! -//! Functions with the attribute have to return `Html` and may take a single parameter for the type of props the component should accept. -//! The parameter type needs to be a reference to a `Properties` type (ex. `props: &MyProps`). -//! If the function doesn't have any parameters the resulting component doesn't accept any props. +//! Functions with the attribute have to return `Html` and may take a single parameter for the type +//! of props the component should accept. The parameter type needs to be a reference to a +//! `Properties` type (ex. `props: &MyProps`). If the function doesn't have any parameters the +//! resulting component doesn't accept any props. //! //! Just mark the component with the attribute. The component will be named after the function. //! @@ -19,8 +20,6 @@ //! //! More details about function components and Hooks can be found on [Yew Docs](https://yew.rs/docs/next/concepts/function-components/introduction) -use crate::html::{AnyScope, BaseComponent, Context, HtmlResult}; -use crate::Properties; use std::any::Any; use std::cell::RefCell; use std::fmt; @@ -28,18 +27,20 @@ use std::rc::Rc; use wasm_bindgen::prelude::*; +use crate::html::{AnyScope, BaseComponent, Context, HtmlResult}; +use crate::Properties; + mod hooks; pub use hooks::*; - /// This attribute creates a function component from a normal Rust function. /// -/// Functions with this attribute **must** return `Html` and can optionally take an argument for props. -/// Note that the function only receives a reference to the props. +/// Functions with this attribute **must** return `Html` and can optionally take an argument +/// for props. Note that the function only receives a reference to the props. /// /// When using this attribute you need to provide a name for the component: /// `#[function_component(ComponentName)]`. -/// The attribute will then automatically create a [`FunctionComponent`] with the given identifier -/// which you can use like a normal component. +/// The attribute will then automatically create a [`FunctionComponent`] with the given +/// identifier which you can use like a normal component. /// /// # Example /// ```rust @@ -58,7 +59,6 @@ pub use hooks::*; /// } /// ``` pub use yew_macro::function_component; - /// This attribute creates a user-defined hook from a normal Rust function. pub use yew_macro::hook; @@ -142,8 +142,8 @@ impl HookContext { /// This function asserts that the number of hooks matches for every render. #[cfg(debug_assertions)] fn assert_hook_context(&mut self, render_ok: bool) { - // Procedural Macros can catch most conditionally called hooks at compile time, but it cannot - // detect early return (as the return can be Err(_), Suspension). + // Procedural Macros can catch most conditionally called hooks at compile time, but it + // cannot detect early return (as the return can be Err(_), Suspension). match (render_ok, self.total_hook_counter) { // First rendered, // we store the hook counter. @@ -197,7 +197,8 @@ pub trait FunctionProvider { /// Properties for the Function Component. type Properties: Properties + PartialEq; - /// Render the component. This function returns the [`Html`](crate::Html) to be rendered for the component. + /// Render the component. This function returns the [`Html`](crate::Html) to be rendered for the + /// component. /// /// Equivalent of [`Component::view`](crate::html::Component::view). fn run(ctx: &mut HookContext, props: &Self::Properties) -> HtmlResult; diff --git a/packages/yew/src/html/classes.rs b/packages/yew/src/html/classes.rs index 6c57e9b4de5..5311ca6e163 100644 --- a/packages/yew/src/html/classes.rs +++ b/packages/yew/src/html/classes.rs @@ -1,12 +1,12 @@ +use std::borrow::{Borrow, Cow}; +use std::hint::unreachable_unchecked; +use std::iter::FromIterator; +use std::rc::Rc; + +use indexmap::IndexSet; + use super::IntoPropValue; use crate::virtual_dom::AttrValue; -use indexmap::IndexSet; -use std::rc::Rc; -use std::{ - borrow::{Borrow, Cow}, - hint::unreachable_unchecked, - iter::FromIterator, -}; /// A set of classes. /// @@ -117,8 +117,8 @@ impl> FromIterator for Classes { } impl IntoIterator for Classes { - type Item = Cow<'static, str>; type IntoIter = indexmap::set::IntoIter>; + type Item = Cow<'static, str>; fn into_iter(self) -> Self::IntoIter { self.set.into_iter() diff --git a/packages/yew/src/html/component/children.rs b/packages/yew/src/html/component/children.rs index 69368c0cdc3..efd2149b6d9 100644 --- a/packages/yew/src/html/component/children.rs +++ b/packages/yew/src/html/component/children.rs @@ -1,9 +1,10 @@ //! Component children module +use std::fmt; + use crate::html::Html; use crate::virtual_dom::{VChild, VNode}; use crate::Properties; -use std::fmt; /// A type used for accepting children elements in Component::Properties. /// @@ -12,25 +13,25 @@ use std::fmt; /// /// In this example, the `Wrapper` component is used to wrap other elements. /// ``` -///# use yew::{Children, Html, Properties, Component, Context, html}; -///# #[derive(Clone, Properties, PartialEq)] -///# struct WrapperProps { -///# children: Children, -///# } -///# struct Wrapper; -///# impl Component for Wrapper { -///# type Message = (); -///# type Properties = WrapperProps; -///# fn create(ctx: &Context) -> Self { Self } -///# fn view(&self, ctx: &Context) -> Html { +/// # use yew::{Children, Html, Properties, Component, Context, html}; +/// # #[derive(Clone, Properties, PartialEq)] +/// # struct WrapperProps { +/// # children: Children, +/// # } +/// # struct Wrapper; +/// # impl Component for Wrapper { +/// # type Message = (); +/// # type Properties = WrapperProps; +/// # fn create(ctx: &Context) -> Self { Self } +/// # fn view(&self, ctx: &Context) -> Html { /// html! { /// ///

{ "Hi" }

///
{ "Hello" }
///
/// } -///# } -///# } +/// # } +/// # } /// ``` /// /// **`wrapper.rs`** @@ -38,19 +39,19 @@ use std::fmt; /// The Wrapper component must define a `children` property in order to wrap other elements. The /// children property can be used to render the wrapped elements. /// ``` -///# use yew::{Children, Html, Properties, Component, Context, html}; +/// # use yew::{Children, Html, Properties, Component, Context, html}; /// #[derive(Clone, Properties, PartialEq)] /// struct WrapperProps { /// children: Children, /// } /// -///# struct Wrapper; +/// # struct Wrapper; /// impl Component for Wrapper { /// // ... -///# type Message = (); -///# type Properties = WrapperProps; +/// # type Message = (); +/// # type Properties = WrapperProps; /// # fn create(ctx: &Context) -> Self { Self } -/// fn view(&self, ctx: &Context) -> Html { +/// fn view(&self, ctx: &Context) -> Html { /// html! { ///
/// { ctx.props().children.clone() } @@ -68,39 +69,39 @@ pub type Children = ChildrenRenderer; /// /// In this example, the `List` component can wrap `ListItem` components. /// ``` -///# use yew::{html, Component, Html, Context, ChildrenWithProps, Properties}; -///# -///# #[derive(Clone, Properties, PartialEq)] -///# struct ListProps { -///# children: ChildrenWithProps, -///# } -///# struct List; -///# impl Component for List { -///# type Message = (); -///# type Properties = ListProps; +/// # use yew::{html, Component, Html, Context, ChildrenWithProps, Properties}; +/// # +/// # #[derive(Clone, Properties, PartialEq)] +/// # struct ListProps { +/// # children: ChildrenWithProps, +/// # } +/// # struct List; +/// # impl Component for List { +/// # type Message = (); +/// # type Properties = ListProps; /// # fn create(ctx: &Context) -> Self { Self } /// # fn view(&self, ctx: &Context) -> Html { unimplemented!() } -///# } -///# #[derive(Clone, Properties, PartialEq)] -///# struct ListItemProps { -///# value: String -///# } -///# struct ListItem; -///# impl Component for ListItem { -///# type Message = (); -///# type Properties = ListItemProps; +/// # } +/// # #[derive(Clone, Properties, PartialEq)] +/// # struct ListItemProps { +/// # value: String +/// # } +/// # struct ListItem; +/// # impl Component for ListItem { +/// # type Message = (); +/// # type Properties = ListItemProps; /// # fn create(ctx: &Context) -> Self { Self } /// # fn view(&self, ctx: &Context) -> Html { unimplemented!() } -///# } -///# fn view() -> Html { -/// html!{ +/// # } +/// # fn view() -> Html { +/// html! { /// /// /// /// /// /// } -///# } +/// # } /// ``` /// /// **`list.rs`** @@ -108,20 +109,20 @@ pub type Children = ChildrenRenderer; /// The `List` component must define a `children` property in order to wrap the list items. The /// `children` property can be used to filter, mutate, and render the items. /// ``` -///# use yew::{html, Component, Html, ChildrenWithProps, Context, Properties}; -///# use std::rc::Rc; -///# +/// # use yew::{html, Component, Html, ChildrenWithProps, Context, Properties}; +/// # use std::rc::Rc; +/// # /// #[derive(Clone, Properties, PartialEq)] /// struct ListProps { /// children: ChildrenWithProps, /// } /// -///# struct List; +/// # struct List; /// impl Component for List { -///# type Message = (); -///# type Properties = ListProps; -///# fn create(ctx: &Context) -> Self { Self } -///# fn view(&self, ctx: &Context) -> Html { +/// # type Message = (); +/// # type Properties = ListProps; +/// # fn create(ctx: &Context) -> Self { Self } +/// # fn view(&self, ctx: &Context) -> Html { /// html!{{ /// for ctx.props().children.iter().map(|mut item| { /// let mut props = Rc::make_mut(&mut item.props); @@ -131,20 +132,20 @@ pub type Children = ChildrenRenderer; /// }} /// } /// } -///# -///# #[derive(Clone, Properties, PartialEq)] -///# struct ListItemProps { -///# #[prop_or_default] -///# value: String -///# } -///# -///# struct ListItem; -///# impl Component for ListItem { -///# type Message = (); -///# type Properties = ListItemProps; -///# fn create(ctx: &Context) -> Self { Self } -///# fn view(&self, ctx: &Context) -> Html { unimplemented!() } -///# } +/// # +/// # #[derive(Clone, Properties, PartialEq)] +/// # struct ListItemProps { +/// # #[prop_or_default] +/// # value: String +/// # } +/// # +/// # struct ListItem; +/// # impl Component for ListItem { +/// # type Message = (); +/// # type Properties = ListItemProps; +/// # fn create(ctx: &Context) -> Self { Self } +/// # fn view(&self, ctx: &Context) -> Html { unimplemented!() } +/// # } /// ``` pub type ChildrenWithProps = ChildrenRenderer>; @@ -202,8 +203,8 @@ impl fmt::Debug for ChildrenRenderer { } impl IntoIterator for ChildrenRenderer { - type Item = T; type IntoIter = std::vec::IntoIter; + type Item = T; fn into_iter(self) -> Self::IntoIter { self.children.into_iter() diff --git a/packages/yew/src/html/component/lifecycle.rs b/packages/yew/src/html/component/lifecycle.rs index b9e08215214..c35b62e8ea8 100644 --- a/packages/yew/src/html/component/lifecycle.rs +++ b/packages/yew/src/html/component/lifecycle.rs @@ -1,25 +1,25 @@ //! Component lifecycle module -use super::scope::{AnyScope, Scope}; - -use super::BaseComponent; -#[cfg(feature = "hydration")] -use crate::html::RenderMode; -use crate::html::{Html, RenderError}; -use crate::scheduler::{self, Runnable, Shared}; -use crate::suspense::{BaseSuspense, Suspension}; -use crate::{Callback, Context, HtmlResult}; use std::any::Any; use std::rc::Rc; +#[cfg(feature = "csr")] +use web_sys::Element; + +use super::scope::{AnyScope, Scope}; +use super::BaseComponent; #[cfg(feature = "hydration")] use crate::dom_bundle::Fragment; #[cfg(feature = "csr")] use crate::dom_bundle::{BSubtree, Bundle}; #[cfg(feature = "csr")] use crate::html::NodeRef; -#[cfg(feature = "csr")] -use web_sys::Element; +#[cfg(feature = "hydration")] +use crate::html::RenderMode; +use crate::html::{Html, RenderError}; +use crate::scheduler::{self, Runnable, Shared}; +use crate::suspense::{BaseSuspense, Suspension}; +use crate::{Callback, Context, HtmlResult}; pub(crate) enum ComponentRenderState { #[cfg(feature = "csr")] @@ -208,6 +208,7 @@ where fn as_any(&self) -> &dyn Any { self } + fn as_any_mut(&mut self) -> &mut dyn Any { self } @@ -612,16 +613,17 @@ use feat_csr::*; mod tests { extern crate self as yew; - use super::*; - use crate::dom_bundle::BSubtree; - use crate::html; - use crate::html::*; - use crate::Properties; use std::cell::RefCell; use std::ops::Deref; use std::rc::Rc; + use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure}; + use super::*; + use crate::dom_bundle::BSubtree; + use crate::html::*; + use crate::{html, Properties}; + wasm_bindgen_test_configure!(run_in_browser); #[derive(Clone, Properties, Default, PartialEq)] diff --git a/packages/yew/src/html/component/marker.rs b/packages/yew/src/html/component/marker.rs index bcd9dd1b4b9..9a970b6d242 100644 --- a/packages/yew/src/html/component/marker.rs +++ b/packages/yew/src/html/component/marker.rs @@ -1,21 +1,20 @@ //! Primitive Components & Properties Types -use crate::function_component; -use crate::html; use crate::html::{BaseComponent, ChildrenProps, Html}; +use crate::{function_component, html}; /// A Component to represent a component that does not exist in current implementation. /// -/// During Hydration, Yew expected the Virtual DOM hierarchy to match the the layout used in server-side -/// rendering. However, sometimes it is possible / reasonable to omit certain components from one -/// side of the implementation. This component is used to represent a component as if a component "existed" -/// in the place it is defined. +/// During Hydration, Yew expected the Virtual DOM hierarchy to match the the layout used in +/// server-side rendering. However, sometimes it is possible / reasonable to omit certain components +/// from one side of the implementation. This component is used to represent a component as if a +/// component "existed" in the place it is defined. /// /// # Warning /// /// The Real DOM hierarchy must also match the server-side rendered artifact. This component is -/// only usable when the original component does not introduce any additional elements. (e.g.: Context -/// Providers) +/// only usable when the original component does not introduce any additional elements. (e.g.: +/// Context Providers) /// /// A generic parameter is provided to help identify the component to be substituted. /// The type of the generic parameter is not required to be the same component that was in the other diff --git a/packages/yew/src/html/component/mod.rs b/packages/yew/src/html/component/mod.rs index 07b81827a58..edd1809181d 100644 --- a/packages/yew/src/html/component/mod.rs +++ b/packages/yew/src/html/component/mod.rs @@ -7,15 +7,16 @@ mod marker; mod properties; mod scope; -use super::{Html, HtmlResult, IntoHtmlResult}; +use std::rc::Rc; + pub use children::*; pub use marker::*; pub use properties::*; - #[cfg(feature = "csr")] pub(crate) use scope::Scoped; pub use scope::{AnyScope, Scope, SendAsMessage}; -use std::rc::Rc; + +use super::{Html, HtmlResult, IntoHtmlResult}; #[cfg(debug_assertions)] #[cfg(any(feature = "csr", feature = "ssr"))] @@ -94,7 +95,8 @@ impl Context { /// If you are taken here by doc links, you might be looking for [`Component`] or /// [`#[function_component]`](crate::functional::function_component). /// -/// We provide a blanket implementation of this trait for every member that implements [`Component`]. +/// We provide a blanket implementation of this trait for every member that implements +/// [`Component`]. pub trait BaseComponent: Sized + 'static { /// The Component's Message. type Message: 'static; @@ -188,7 +190,6 @@ where T: Sized + Component + 'static, { type Message = ::Message; - type Properties = ::Properties; fn create(ctx: &Context) -> Self { diff --git a/packages/yew/src/html/component/scope.rs b/packages/yew/src/html/component/scope.rs index b83a6a2d052..dd8cba39576 100644 --- a/packages/yew/src/html/component/scope.rs +++ b/packages/yew/src/html/component/scope.rs @@ -1,21 +1,20 @@ //! Component scope module -#[cfg(any(feature = "csr", feature = "ssr"))] -use crate::scheduler::Shared; +use std::any::{Any, TypeId}; #[cfg(any(feature = "csr", feature = "ssr"))] use std::cell::RefCell; +use std::marker::PhantomData; +use std::ops::Deref; +use std::rc::Rc; +use std::{fmt, iter}; #[cfg(any(feature = "csr", feature = "ssr"))] use super::lifecycle::{ComponentState, UpdateEvent, UpdateRunner}; use super::BaseComponent; - use crate::callback::Callback; use crate::context::{ContextHandle, ContextProvider}; -use std::any::{Any, TypeId}; -use std::marker::PhantomData; -use std::ops::Deref; -use std::rc::Rc; -use std::{fmt, iter}; +#[cfg(any(feature = "csr", feature = "ssr"))] +use crate::scheduler::Shared; /// Untyped scope used for accessing parent scope #[derive(Clone)] @@ -183,14 +182,13 @@ impl Scope { #[cfg(feature = "ssr")] mod feat_ssr { - use super::*; - use crate::scheduler; use futures::channel::oneshot; + use super::*; use crate::html::component::lifecycle::{ ComponentRenderState, CreateRunner, DestroyRunner, RenderRunner, }; - + use crate::scheduler; use crate::virtual_dom::Collectable; impl Scope { @@ -274,11 +272,12 @@ mod feat_no_csr_ssr { #[cfg(any(feature = "ssr", feature = "csr"))] mod feat_csr_ssr { - use super::*; - use crate::scheduler::{self, Shared}; use std::cell::Ref; use std::sync::atomic::{AtomicUsize, Ordering}; + use super::*; + use crate::scheduler::{self, Shared}; + #[derive(Debug)] pub(crate) struct MsgQueue(Shared>); @@ -394,6 +393,10 @@ pub(crate) use feat_csr_ssr::*; #[cfg(feature = "csr")] mod feat_csr { + use std::cell::Ref; + + use web_sys::Element; + use super::*; use crate::dom_bundle::{BSubtree, Bundle}; use crate::html::component::lifecycle::{ @@ -401,8 +404,6 @@ mod feat_csr { }; use crate::html::NodeRef; use crate::scheduler; - use std::cell::Ref; - use web_sys::Element; impl AnyScope { #[cfg(test)] @@ -515,16 +516,15 @@ mod feat_csr { #[cfg_attr(documenting, doc(cfg(feature = "hydration")))] #[cfg(feature = "hydration")] mod feat_hydration { - use super::*; + use web_sys::Element; + use super::*; use crate::dom_bundle::{BSubtree, Fragment}; use crate::html::component::lifecycle::{ComponentRenderState, CreateRunner, RenderRunner}; use crate::html::NodeRef; use crate::scheduler; use crate::virtual_dom::Collectable; - use web_sys::Element; - impl Scope where COMP: BaseComponent, @@ -660,7 +660,8 @@ mod feat_io { } /// Defines a message type that can be sent to a component. -/// Used for the return value of closure given to [Scope::batch_callback](struct.Scope.html#method.batch_callback). +/// Used for the return value of closure given to +/// [Scope::batch_callback](struct.Scope.html#method.batch_callback). pub trait SendAsMessage { /// Sends the message to the given component's scope. /// See [Scope::batch_callback](struct.Scope.html#method.batch_callback). diff --git a/packages/yew/src/html/conversion.rs b/packages/yew/src/html/conversion.rs index 7c6545b22fc..5035796d77d 100644 --- a/packages/yew/src/html/conversion.rs +++ b/packages/yew/src/html/conversion.rs @@ -1,7 +1,8 @@ +use std::rc::Rc; + use super::super::callback::Callback; use super::{Component, NodeRef, Scope}; use crate::virtual_dom::AttrValue; -use std::rc::Rc; /// Marker trait for types that the [`html!`](macro@crate::html) macro may clone implicitly. pub trait ImplicitClone: Clone {} diff --git a/packages/yew/src/html/listener/mod.rs b/packages/yew/src/html/listener/mod.rs index 4882fa684b2..0024fe2c5e6 100644 --- a/packages/yew/src/html/listener/mod.rs +++ b/packages/yew/src/html/listener/mod.rs @@ -1,11 +1,11 @@ #[macro_use] mod events; +pub use events::*; use wasm_bindgen::JsCast; use web_sys::{Event, EventTarget}; use crate::Callback; -pub use events::*; /// Cast [Event] `e` into it's target `T`. /// @@ -37,8 +37,8 @@ where /// # Example /// /// ``` - /// use yew::prelude::*; /// use web_sys::HtmlTextAreaElement; + /// use yew::prelude::*; /// # enum Msg { /// # Value(String), /// # } @@ -94,8 +94,8 @@ where /// # Example /// /// ``` - /// use yew::prelude::*; /// use web_sys::HtmlInputElement; + /// use yew::prelude::*; /// # enum Msg { /// # Value(String), /// # } diff --git a/packages/yew/src/html/mod.rs b/packages/yew/src/html/mod.rs index d5983f39188..1953b545168 100644 --- a/packages/yew/src/html/mod.rs +++ b/packages/yew/src/html/mod.rs @@ -6,18 +6,19 @@ mod conversion; mod error; mod listener; +use std::cell::RefCell; +use std::rc::Rc; + pub use classes::*; pub use component::*; pub use conversion::*; pub use error::*; pub use listener::*; +use wasm_bindgen::JsValue; +use web_sys::{Element, Node}; use crate::sealed::Sealed; use crate::virtual_dom::{VNode, VPortal}; -use std::cell::RefCell; -use std::rc::Rc; -use wasm_bindgen::JsValue; -use web_sys::{Element, Node}; /// A type which expected as a result of `view` function implementation. pub type Html = VNode; @@ -53,7 +54,7 @@ impl IntoHtmlResult for Html { /// Focus an `` element on mount. /// ``` /// use web_sys::HtmlInputElement; -///# use yew::prelude::*; +/// # use yew::prelude::*; /// /// pub struct Input { /// node_ref: NodeRef, @@ -182,11 +183,11 @@ pub fn create_portal(child: Html, host: Element) -> Html { #[cfg(feature = "wasm_test")] #[cfg(test)] mod tests { - use super::*; use gloo_utils::document; - use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure}; + use super::*; + wasm_bindgen_test_configure!(run_in_browser); #[test] diff --git a/packages/yew/src/lib.rs b/packages/yew/src/lib.rs index 667355e9ccb..16360a8eee8 100644 --- a/packages/yew/src/lib.rs +++ b/packages/yew/src/lib.rs @@ -6,9 +6,12 @@ //! //! Yew is a modern Rust framework for creating multi-threaded front-end web apps using WebAssembly //! -//! - Features a macro for declaring interactive HTML with Rust expressions. Developers who have experience using JSX in React should feel quite at home when using Yew. -//! - Achieves high performance by minimizing DOM API calls for each page render and by making it easy to offload processing to background web workers. -//! - Supports JavaScript interoperability, allowing developers to leverage NPM packages and integrate with existing JavaScript applications. +//! - Features a macro for declaring interactive HTML with Rust expressions. Developers who have +//! experience using JSX in React should feel quite at home when using Yew. +//! - Achieves high performance by minimizing DOM API calls for each page render and by making it +//! easy to offload processing to background web workers. +//! - Supports JavaScript interoperability, allowing developers to leverage NPM packages and +//! integrate with existing JavaScript applications. //! //! ### Supported Targets (Client-Side Rendering) //! - `wasm32-unknown-unknown` @@ -18,14 +21,15 @@ //! Server-Side Rendering should work on all targets when feature `ssr` is enabled. //! //! ### Supported Features: -//! - `csr`: Enables Client-side Rendering support and [`Renderer`]. -//! Only enable this feature if you are making a Yew application (not a library). +//! - `csr`: Enables Client-side Rendering support and [`Renderer`]. Only enable this feature if you +//! are making a Yew application (not a library). //! - `ssr`: Enables Server-side Rendering support and [`ServerRenderer`]. //! - `tokio`: Enables future-based APIs on non-wasm32 targets with tokio runtime. (You may want to //! enable this if your application uses future-based APIs and it does not compile / lint on //! non-wasm32 targets.) //! - `hydration`: Enables Hydration support. -//! - `trace_hydration`: Enables trace logging on hydration. (Implies `hydration`. You may want to enable this if you are +//! - `trace_hydration`: Enables trace logging on hydration. (Implies `hydration`. You may want to +//! enable this if you are //! trying to debug hydration layout mismatch.) //! //! ## Example @@ -46,9 +50,7 @@ //! type Properties = (); //! //! fn create(ctx: &Context) -> Self { -//! Self { -//! value: 0, -//! } +//! Self { value: 0 } //! } //! //! fn update(&mut self, _ctx: &Context, msg: Self::Message) -> bool { @@ -70,13 +72,12 @@ //! } //! } //! -//!# fn dont_execute() { +//! # fn dont_execute() { //! fn main() { //! yew::Renderer::::new().render(); //! } -//!# } +//! # } //! ``` -//! #![deny( missing_docs, @@ -91,8 +92,9 @@ extern crate self as yew; /// This macro provides a convenient way to create [`Classes`]. /// -/// The macro takes a list of items similar to the [`vec!`] macro and returns a [`Classes`] instance. -/// Each item can be of any type that implements `Into` (See the implementations on [`Classes`] to learn what types can be used). +/// The macro takes a list of items similar to the [`vec!`] macro and returns a [`Classes`] +/// instance. Each item can be of any type that implements `Into` (See the +/// implementations on [`Classes`] to learn what types can be used). /// /// # Example /// @@ -100,7 +102,12 @@ extern crate self as yew; /// # use yew::prelude::*; /// # fn test() { /// let conditional_class = Some("my-other-class"); -/// let vec_of_classes = vec!["one-bean", "two-beans", "three-beans", "a-very-small-casserole"]; +/// let vec_of_classes = vec![ +/// "one-bean", +/// "two-beans", +/// "three-beans", +/// "a-very-small-casserole", +/// ]; /// /// html! { ///
@@ -110,7 +117,6 @@ extern crate self as yew; /// # } /// ``` pub use yew_macro::classes; - /// This macro implements JSX-like templates. /// /// This macro always returns [`Html`]. @@ -122,7 +128,6 @@ pub use yew_macro::classes; /// [`html_nested!`]: ./macro.html_nested.html /// [Yew Docs]: https://yew.rs/docs/next/concepts/html pub use yew_macro::html; - /// This macro is similar to [`html!`], but preserves the component type instead /// of wrapping it in [`Html`]. /// @@ -141,14 +146,14 @@ pub use yew_macro::html; /// /// #[derive(Clone, Properties, PartialEq)] /// struct ListProps { -/// children: ChildrenRenderer, +/// children: ChildrenRenderer, /// } /// /// struct List; /// impl Component for List { /// # type Message = (); -/// type Properties = ListProps; -/// // ... +/// type Properties = ListProps; +/// // ... /// # fn create(ctx: &Context) -> Self { Self } /// # fn view(&self, ctx: &Context) -> Html { unimplemented!() } /// } @@ -158,18 +163,22 @@ pub use yew_macro::html; /// impl Component for ListItem { /// # type Message = (); /// # type Properties = (); -/// // ... +/// // ... /// # fn create(ctx: &Context) -> Self { Self } /// # fn view(&self, ctx: &Context) -> Html { unimplemented!() } /// } /// /// // Required for ChildrenRenderer /// impl From> for ListItem { -/// fn from(child: VChild) -> Self { Self } +/// fn from(child: VChild) -> Self { +/// Self +/// } /// } /// /// impl Into for ListItem { -/// fn into(self) -> Html { html! { } } +/// fn into(self) -> Html { +/// html! { } +/// } /// } /// // You can use `List` with nested `ListItem` components. /// // Using any other kind of element would result in a compile error. @@ -205,14 +214,14 @@ pub use yew_macro::html; /// [`nested_list`]: https://github.com/yewstack/yew/tree/master/examples/nested_list /// [`ChildrenRenderer`]: ./html/struct.ChildrenRenderer.html pub use yew_macro::html_nested; - /// Build [`Properties`] outside of the [`html!`] macro. /// /// It's already possible to create properties like normal Rust structs /// but if there are lots of optional props the end result is often needlessly verbose. /// This macro allows you to build properties the same way the [`html!`] macro does. /// -/// The macro doesn't support special props like `ref` and `key`, they need to be set in the [`html!`] macro. +/// The macro doesn't support special props like `ref` and `key`, they need to be set in the +/// [`html!`] macro. /// /// You can read more about `Properties` in the [Yew Docs]. /// @@ -240,10 +249,15 @@ pub use yew_macro::html_nested; /// /// # fn foo() -> Html { /// // You can build props directly ... -/// let props = yew::props!(Props { name: Cow::from("Minka") }); +/// let props = yew::props!(Props { +/// name: Cow::from("Minka") +/// }); /// # assert_eq!(props.name, "Minka"); /// // ... or build the associated properties of a component -/// let props = yew::props!(MyComponent::Properties { id: 2, name: Cow::from("Lemmy") }); +/// let props = yew::props!(MyComponent::Properties { +/// id: 2, +/// name: Cow::from("Lemmy") +/// }); /// # assert_eq!(props.id, 2); /// /// // Use the Rust-like struct update syntax to create a component with the props. @@ -260,10 +274,7 @@ pub use yew_macro::props; /// This module contains macros which implements html! macro and JSX-like templates pub mod macros { - pub use crate::classes; - pub use crate::html; - pub use crate::html_nested; - pub use crate::props; + pub use crate::{classes, html, html_nested, props}; } pub mod callback; @@ -295,16 +306,15 @@ pub mod tests; /// The module that contains all events available in the framework. pub mod events { - pub use crate::html::TargetCast; - - #[cfg(feature = "csr")] - pub use crate::dom_bundle::set_event_bubbling; - #[doc(no_inline)] pub use web_sys::{ AnimationEvent, DragEvent, ErrorEvent, Event, FocusEvent, InputEvent, KeyboardEvent, MouseEvent, PointerEvent, ProgressEvent, TouchEvent, TransitionEvent, UiEvent, WheelEvent, }; + + #[cfg(feature = "csr")] + pub use crate::dom_bundle::set_event_bubbling; + pub use crate::html::TargetCast; } #[cfg(feature = "csr")] @@ -327,6 +337,7 @@ pub mod prelude { pub use crate::callback::Callback; pub use crate::context::{ContextHandle, ContextProvider}; pub use crate::events::*; + pub use crate::functional::*; pub use crate::html::{ create_portal, BaseComponent, Children, ChildrenWithProps, Classes, Component, Context, Html, HtmlResult, NodeRef, Properties, @@ -334,8 +345,6 @@ pub mod prelude { pub use crate::macros::{classes, html, html_nested}; pub use crate::suspense::Suspense; pub use crate::virtual_dom::AttrValue; - - pub use crate::functional::*; } pub use self::prelude::*; diff --git a/packages/yew/src/scheduler.rs b/packages/yew/src/scheduler.rs index 9abc7f347de..3da8da98ea0 100644 --- a/packages/yew/src/scheduler.rs +++ b/packages/yew/src/scheduler.rs @@ -126,11 +126,10 @@ mod feat_hydration { } } -#[cfg(feature = "hydration")] -pub(crate) use feat_hydration::*; - #[cfg(feature = "csr")] pub(crate) use feat_csr::*; +#[cfg(feature = "hydration")] +pub(crate) use feat_hydration::*; /// Execute any pending [Runnable]s pub(crate) fn start_now() { diff --git a/packages/yew/src/suspense/component.rs b/packages/yew/src/suspense/component.rs index 34625567cce..42ff2ae2138 100644 --- a/packages/yew/src/suspense/component.rs +++ b/packages/yew/src/suspense/component.rs @@ -15,7 +15,6 @@ pub struct SuspenseProps { #[cfg(any(feature = "csr", feature = "ssr"))] mod feat_csr_ssr { use super::*; - #[cfg(feature = "hydration")] use crate::callback::Callback; #[cfg(feature = "hydration")] @@ -48,8 +47,8 @@ mod feat_csr_ssr { } impl Component for BaseSuspense { - type Properties = BaseSuspenseProps; type Message = BaseSuspenseMsg; + type Properties = BaseSuspenseProps; fn create(ctx: &Context) -> Self { #[cfg(not(feature = "hydration"))] @@ -171,7 +170,6 @@ pub use feat_csr_ssr::*; #[cfg(not(any(feature = "ssr", feature = "csr")))] mod feat_no_csr_ssr { use super::*; - use crate::function_component; /// Suspend rendering and show a fallback UI until the underlying task completes. diff --git a/packages/yew/src/tests/layout_tests.rs b/packages/yew/src/tests/layout_tests.rs index a6509679562..aa7467f234a 100644 --- a/packages/yew/src/tests/layout_tests.rs +++ b/packages/yew/src/tests/layout_tests.rs @@ -1,10 +1,10 @@ +use gloo::console::log; +use yew::NodeRef; + use crate::dom_bundle::{BSubtree, Bundle}; use crate::html::AnyScope; -use crate::scheduler; use crate::virtual_dom::VNode; -use crate::{Component, Context, Html}; -use gloo::console::log; -use yew::NodeRef; +use crate::{scheduler, Component, Context, Html}; struct Comp; impl Component for Comp { diff --git a/packages/yew/src/utils/mod.rs b/packages/yew/src/utils/mod.rs index 29e9a8874f0..e5b999e72c5 100644 --- a/packages/yew/src/utils/mod.rs +++ b/packages/yew/src/utils/mod.rs @@ -1,6 +1,7 @@ //! This module contains useful utilities to get information about the current document. use std::marker::PhantomData; + use yew::html::ChildrenRenderer; /// Map IntoIterator> to Iterator @@ -41,8 +42,8 @@ impl, OUT> From> for NodeSeq { } impl IntoIterator for NodeSeq { - type Item = OUT; type IntoIter = std::vec::IntoIter; + type Item = OUT; fn into_iter(self) -> Self::IntoIter { self.0.into_iter() @@ -50,7 +51,6 @@ impl IntoIterator for NodeSeq { } /// Hack to force type mismatch compile errors in yew-macro. -// // TODO: replace with `compile_error!`, when `type_name_of_val` is stabilised (https://github.com/rust-lang/rust/issues/66359). #[doc(hidden)] pub fn __ensure_type(_: T) {} diff --git a/packages/yew/src/virtual_dom/key.rs b/packages/yew/src/virtual_dom/key.rs index e6ead5ca905..4a0cadd882a 100644 --- a/packages/yew/src/virtual_dom/key.rs +++ b/packages/yew/src/virtual_dom/key.rs @@ -1,10 +1,11 @@ //! This module contains the implementation yew's virtual nodes' keys. -use crate::html::ImplicitClone; use std::fmt::{self, Display, Formatter}; use std::ops::Deref; use std::rc::Rc; +use crate::html::ImplicitClone; + /// Represents the (optional) key of Yew's virtual nodes. /// /// Keys are cheap to clone. @@ -69,12 +70,13 @@ key_impl_from_to_string!(isize); #[cfg(test)] mod test { - use crate::html; use std::rc::Rc; #[cfg(feature = "wasm_test")] use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure}; + use crate::html; + #[cfg(feature = "wasm_test")] wasm_bindgen_test_configure!(run_in_browser); diff --git a/packages/yew/src/virtual_dom/mod.rs b/packages/yew/src/virtual_dom/mod.rs index f33e3fb614d..66fc22cff6c 100644 --- a/packages/yew/src/virtual_dom/mod.rs +++ b/packages/yew/src/virtual_dom/mod.rs @@ -19,6 +19,16 @@ pub mod vtag; #[doc(hidden)] pub mod vtext; +use std::borrow::{Borrow, Cow}; +use std::fmt; +use std::fmt::Formatter; +use std::hash::{Hash, Hasher}; +use std::hint::unreachable_unchecked; +use std::ops::Deref; +use std::rc::Rc; + +use indexmap::IndexMap; + #[doc(inline)] pub use self::key::Key; #[doc(inline)] @@ -38,14 +48,6 @@ pub use self::vtag::VTag; #[doc(inline)] pub use self::vtext::VText; -use indexmap::IndexMap; -use std::borrow::{Borrow, Cow}; -use std::fmt::Formatter; -use std::hash::{Hash, Hasher}; -use std::ops::Deref; -use std::rc::Rc; -use std::{fmt, hint::unreachable_unchecked}; - /// Attribute value #[derive(Debug)] pub enum AttrValue { @@ -147,8 +149,8 @@ impl Eq for AttrValue {} impl AttrValue { /// Consumes the AttrValue and returns the owned String from the AttrValue whenever possible. - /// For AttrValue::Rc the is cloned to String in case there are other Rc or Weak pointers to the - /// same allocation. + /// For AttrValue::Rc the is cloned to String in case there are other Rc or Weak pointers + /// to the same allocation. pub fn into_string(self) -> String { match self { AttrValue::Static(s) => (*s).to_owned(), @@ -223,6 +225,7 @@ mod feat_ssr_hydration { Self::Suspense => " &'static str { match self { #[cfg(debug_assertions)] @@ -307,7 +310,8 @@ pub enum Attributes { /// Attribute keys. Includes both always set and optional attribute keys. keys: &'static [&'static str], - /// Attribute values. Matches [keys](Attributes::Dynamic::keys). Optional attributes are designated by setting [None]. + /// Attribute values. Matches [keys](Attributes::Dynamic::keys). Optional attributes are + /// designated by setting [None]. values: Box<[Option]>, }, diff --git a/packages/yew/src/virtual_dom/vcomp.rs b/packages/yew/src/virtual_dom/vcomp.rs index e556e286757..c330b12ec8e 100644 --- a/packages/yew/src/virtual_dom/vcomp.rs +++ b/packages/yew/src/virtual_dom/vcomp.rs @@ -1,25 +1,24 @@ //! This module contains the implementation of a virtual component (`VComp`). -use super::Key; -use crate::html::{BaseComponent, NodeRef}; use std::any::TypeId; use std::fmt; use std::rc::Rc; -#[cfg(any(feature = "ssr", feature = "csr"))] -use crate::html::{AnyScope, Scope}; +#[cfg(feature = "ssr")] +use futures::future::{FutureExt, LocalBoxFuture}; +#[cfg(feature = "csr")] +use web_sys::Element; +use super::Key; #[cfg(feature = "csr")] use crate::dom_bundle::BSubtree; #[cfg(feature = "hydration")] use crate::dom_bundle::Fragment; #[cfg(feature = "csr")] use crate::html::Scoped; -#[cfg(feature = "csr")] -use web_sys::Element; - -#[cfg(feature = "ssr")] -use futures::future::{FutureExt, LocalBoxFuture}; +#[cfg(any(feature = "ssr", feature = "csr"))] +use crate::html::{AnyScope, Scope}; +use crate::html::{BaseComponent, NodeRef}; /// A virtual component. pub struct VComp { diff --git a/packages/yew/src/virtual_dom/vlist.rs b/packages/yew/src/virtual_dom/vlist.rs index 3471636c75e..6a2249c165f 100644 --- a/packages/yew/src/virtual_dom/vlist.rs +++ b/packages/yew/src/virtual_dom/vlist.rs @@ -1,7 +1,8 @@ //! This module contains fragments implementation. -use super::{Key, VNode}; use std::ops::{Deref, DerefMut}; +use super::{Key, VNode}; + /// This struct represents a fragment of the Virtual DOM tree. #[derive(Clone, Debug, PartialEq)] pub struct VList { diff --git a/packages/yew/src/virtual_dom/vnode.rs b/packages/yew/src/virtual_dom/vnode.rs index 5cf7b1f2d42..fbfb6ffdf17 100644 --- a/packages/yew/src/virtual_dom/vnode.rs +++ b/packages/yew/src/virtual_dom/vnode.rs @@ -1,12 +1,14 @@ //! This module contains the implementation of abstract virtual node. -use super::{Key, VChild, VComp, VList, VPortal, VSuspense, VTag, VText}; -use crate::html::BaseComponent; use std::cmp::PartialEq; use std::fmt; use std::iter::FromIterator; + use web_sys::Node; +use super::{Key, VChild, VComp, VList, VPortal, VSuspense, VTag, VText}; +use crate::html::BaseComponent; + /// Bind virtual element to a DOM reference. #[derive(Clone)] pub enum VNode { @@ -147,9 +149,10 @@ impl PartialEq for VNode { #[cfg(feature = "ssr")] mod feat_ssr { + use futures::future::{FutureExt, LocalBoxFuture}; + use super::*; use crate::html::AnyScope; - use futures::future::{FutureExt, LocalBoxFuture}; impl VNode { // Boxing is needed here, due to: https://rust-lang.github.io/async-book/07_workarounds/04_recursion.html @@ -171,11 +174,11 @@ mod feat_ssr { VNode::VList(vlist) => { vlist.render_to_string(w, parent_scope, hydratable).await } - // We are pretty safe here as it's not possible to get a web_sys::Node without DOM - // support in the first place. + // We are pretty safe here as it's not possible to get a web_sys::Node without + // DOM support in the first place. // - // The only exception would be to use `ServerRenderer` in a browser or wasm32 environment with - // jsdom present. + // The only exception would be to use `ServerRenderer` in a browser or wasm32 + // environment with jsdom present. VNode::VRef(_) => { panic!("VRef is not possible to be rendered in to a string.") } diff --git a/packages/yew/src/virtual_dom/vportal.rs b/packages/yew/src/virtual_dom/vportal.rs index abcb4f1a19b..1e418a867a2 100644 --- a/packages/yew/src/virtual_dom/vportal.rs +++ b/packages/yew/src/virtual_dom/vportal.rs @@ -1,8 +1,9 @@ //! This module contains the implementation of a portal `VPortal`. +use web_sys::{Element, Node}; + use super::VNode; use crate::html::NodeRef; -use web_sys::{Element, Node}; #[derive(Debug, Clone)] pub struct VPortal { @@ -23,6 +24,7 @@ impl VPortal { node: Box::new(content), } } + /// Creates a [VPortal] rendering `content` in the DOM hierarchy under `host`. /// If `next_sibling` is given, the content is inserted before that [Node]. /// The parent of `next_sibling`, if given, must be `host`. diff --git a/packages/yew/src/virtual_dom/vtag.rs b/packages/yew/src/virtual_dom/vtag.rs index 21e26b7a354..03c4d7d6dcd 100644 --- a/packages/yew/src/virtual_dom/vtag.rs +++ b/packages/yew/src/virtual_dom/vtag.rs @@ -1,15 +1,17 @@ //! This module contains the implementation of a virtual element node [VTag]. -use super::{AttrValue, Attributes, Key, Listener, Listeners, VList, VNode}; -use crate::html::{IntoPropValue, NodeRef}; +use std::borrow::Cow; use std::cmp::PartialEq; use std::marker::PhantomData; use std::mem; -use std::ops::Deref; +use std::ops::{Deref, DerefMut}; use std::rc::Rc; -use std::{borrow::Cow, ops::DerefMut}; + use web_sys::{HtmlInputElement as InputElement, HtmlTextAreaElement as TextAreaElement}; +use super::{AttrValue, Attributes, Key, Listener, Listeners, VList, VNode}; +use crate::html::{IntoPropValue, NodeRef}; + /// SVG namespace string used for creating svg elements pub const SVG_NAMESPACE: &str = "http://www.w3.org/2000/svg"; @@ -27,11 +29,14 @@ impl Default for Value { } impl Value { - /// Create a new value. The caller should take care that the value is valid for the element's `value` property + /// Create a new value. The caller should take care that the value is valid for the element's + /// `value` property fn new(value: Option) -> Self { Value(value, PhantomData) } - /// Set a new value. The caller should take care that the value is valid for the element's `value` property + + /// Set a new value. The caller should take care that the value is valid for the element's + /// `value` property fn set(&mut self, value: Option) { self.0 = value; } @@ -39,6 +44,7 @@ impl Value { impl Deref for Value { type Target = Option; + fn deref(&self) -> &Self::Target { &self.0 } @@ -414,10 +420,12 @@ impl PartialEq for VTag { #[cfg(feature = "ssr")] mod feat_ssr { - use super::*; - use crate::{html::AnyScope, virtual_dom::VText}; use std::fmt::Write; + use super::*; + use crate::html::AnyScope; + use crate::virtual_dom::VText; + // Elements that cannot have any child elements. static VOID_ELEMENTS: &[&str; 14] = &[ "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", diff --git a/packages/yew/src/virtual_dom/vtext.rs b/packages/yew/src/virtual_dom/vtext.rs index 09b03928231..dff927de7c2 100644 --- a/packages/yew/src/virtual_dom/vtext.rs +++ b/packages/yew/src/virtual_dom/vtext.rs @@ -1,8 +1,9 @@ //! This module contains the implementation of a virtual text node `VText`. -use super::AttrValue; use std::cmp::PartialEq; +use super::AttrValue; + /// A type for a virtual /// [`TextNode`](https://developer.mozilla.org/en-US/docs/Web/API/Document/createTextNode) /// representation. diff --git a/packages/yew/tests/hydration.rs b/packages/yew/tests/hydration.rs index f7b1bc81e12..f85c97e74aa 100644 --- a/packages/yew/tests/hydration.rs +++ b/packages/yew/tests/hydration.rs @@ -6,7 +6,6 @@ use std::time::Duration; mod common; use common::{obtain_result, obtain_result_by_id}; - use gloo::timers::future::sleep; use wasm_bindgen::JsCast; use wasm_bindgen_futures::spawn_local; diff --git a/packages/yew/tests/mod.rs b/packages/yew/tests/mod.rs index 3f5cc20a19d..a211d28e02a 100644 --- a/packages/yew/tests/mod.rs +++ b/packages/yew/tests/mod.rs @@ -2,9 +2,10 @@ mod common; +use std::time::Duration; + use common::obtain_result; use gloo::timers::future::sleep; -use std::time::Duration; use wasm_bindgen_test::*; use yew::prelude::*; diff --git a/packages/yew/tests/use_callback.rs b/packages/yew/tests/use_callback.rs index 31b8faf0d71..4f4707dfd3a 100644 --- a/packages/yew/tests/use_callback.rs +++ b/packages/yew/tests/use_callback.rs @@ -4,9 +4,10 @@ use std::sync::atomic::{AtomicBool, Ordering}; mod common; +use std::time::Duration; + use common::obtain_result; use gloo::timers::future::sleep; -use std::time::Duration; use wasm_bindgen_test::*; use yew::prelude::*; diff --git a/packages/yew/tests/use_context.rs b/packages/yew/tests/use_context.rs index 19d23d2c64d..23206fb99fa 100644 --- a/packages/yew/tests/use_context.rs +++ b/packages/yew/tests/use_context.rs @@ -2,10 +2,11 @@ mod common; -use common::obtain_result_by_id; -use gloo::timers::future::sleep; use std::rc::Rc; use std::time::Duration; + +use common::obtain_result_by_id; +use gloo::timers::future::sleep; use wasm_bindgen_test::*; use yew::prelude::*; diff --git a/packages/yew/tests/use_effect.rs b/packages/yew/tests/use_effect.rs index 9ca90ea27f1..0d8830cfbac 100644 --- a/packages/yew/tests/use_effect.rs +++ b/packages/yew/tests/use_effect.rs @@ -2,11 +2,12 @@ mod common; -use common::obtain_result; -use gloo::timers::future::sleep; use std::ops::{Deref, DerefMut}; use std::rc::Rc; use std::time::Duration; + +use common::obtain_result; +use gloo::timers::future::sleep; use wasm_bindgen_test::*; use yew::prelude::*; diff --git a/packages/yew/tests/use_memo.rs b/packages/yew/tests/use_memo.rs index 10a47a125bc..a233c654e30 100644 --- a/packages/yew/tests/use_memo.rs +++ b/packages/yew/tests/use_memo.rs @@ -4,9 +4,10 @@ use std::sync::atomic::{AtomicBool, Ordering}; mod common; +use std::time::Duration; + use common::obtain_result; use gloo::timers::future::sleep; -use std::time::Duration; use wasm_bindgen_test::*; use yew::prelude::*; diff --git a/packages/yew/tests/use_reducer.rs b/packages/yew/tests/use_reducer.rs index 4935ac79721..e9cf0e424e4 100644 --- a/packages/yew/tests/use_reducer.rs +++ b/packages/yew/tests/use_reducer.rs @@ -2,10 +2,10 @@ use std::collections::HashSet; use std::rc::Rc; +use std::time::Duration; use gloo::timers::future::sleep; use gloo_utils::document; -use std::time::Duration; use wasm_bindgen::JsCast; use wasm_bindgen_test::*; use web_sys::HtmlElement; diff --git a/packages/yew/tests/use_ref.rs b/packages/yew/tests/use_ref.rs index ee03d669e79..e07d78c2068 100644 --- a/packages/yew/tests/use_ref.rs +++ b/packages/yew/tests/use_ref.rs @@ -2,10 +2,11 @@ mod common; -use common::obtain_result; -use gloo::timers::future::sleep; use std::ops::DerefMut; use std::time::Duration; + +use common::obtain_result; +use gloo::timers::future::sleep; use wasm_bindgen_test::*; use yew::prelude::*; diff --git a/packages/yew/tests/use_state.rs b/packages/yew/tests/use_state.rs index 33e7364a0d3..5f22fea548b 100644 --- a/packages/yew/tests/use_state.rs +++ b/packages/yew/tests/use_state.rs @@ -2,9 +2,10 @@ mod common; +use std::time::Duration; + use common::obtain_result; use gloo::timers::future::sleep; -use std::time::Duration; use wasm_bindgen_test::*; use yew::prelude::*; diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 00000000000..473c88723dd --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,12 @@ +format_code_in_doc_comments = true +wrap_comments = true +comment_width = 100 # same as default max_width +normalize_doc_attributes = true +normalize_comments = true + +condense_wildcard_suffixes = true +format_strings = true +group_imports = "StdExternalCrate" +imports_granularity = "Module" +reorder_impl_items = true +use_field_init_shorthand = true diff --git a/tools/benchmark-hooks/src/lib.rs b/tools/benchmark-hooks/src/lib.rs index 9a22efa551f..171938e6ab6 100644 --- a/tools/benchmark-hooks/src/lib.rs +++ b/tools/benchmark-hooks/src/lib.rs @@ -1,7 +1,8 @@ -use rand::prelude::*; use std::cmp::min; use std::ops::Deref; use std::rc::Rc; + +use rand::prelude::*; use wasm_bindgen::prelude::*; use web_sys::window; use yew::prelude::*; diff --git a/tools/benchmark-struct/src/lib.rs b/tools/benchmark-struct/src/lib.rs index d6d03c52700..c9c805fd47a 100644 --- a/tools/benchmark-struct/src/lib.rs +++ b/tools/benchmark-struct/src/lib.rs @@ -1,5 +1,6 @@ -use rand::prelude::*; use std::cmp::min; + +use rand::prelude::*; use wasm_bindgen::prelude::*; use web_sys::window; use yew::prelude::*; @@ -189,8 +190,8 @@ pub struct JumbotronProps { pub struct Jumbotron {} impl Component for Jumbotron { - type Properties = JumbotronProps; type Message = (); + type Properties = JumbotronProps; fn create(_ctx: &Context) -> Self { Self {} @@ -245,8 +246,8 @@ struct Row { } impl Component for Row { - type Properties = RowProps; type Message = (); + type Properties = RowProps; fn create(ctx: &Context) -> Self { let id = ctx.props().data.id; diff --git a/tools/changelog/src/cli.rs b/tools/changelog/src/cli.rs index b2db74ffeec..6e0de33fed2 100644 --- a/tools/changelog/src/cli.rs +++ b/tools/changelog/src/cli.rs @@ -1,3 +1,7 @@ +use anyhow::{bail, Result}; +use semver::Version; +use structopt::StructOpt; + use crate::create_log_lines::create_log_lines; use crate::get_latest_version::get_latest_version; use crate::new_version_level::NewVersionLevel; @@ -6,10 +10,6 @@ use crate::write_changelog_file::write_changelog; use crate::write_log_lines::write_log_lines; use crate::write_version_changelog::write_changelog_file; use crate::yew_package::YewPackage; -use anyhow::bail; -use anyhow::Result; -use semver::Version; -use structopt::StructOpt; #[derive(StructOpt)] pub struct Cli { diff --git a/tools/changelog/src/create_log_line.rs b/tools/changelog/src/create_log_line.rs index ad0e9be966d..93c53a72489 100644 --- a/tools/changelog/src/create_log_line.rs +++ b/tools/changelog/src/create_log_line.rs @@ -1,12 +1,9 @@ -use anyhow::anyhow; -use anyhow::Context; -use anyhow::Result; -use git2::Error; -use git2::Oid; -use git2::Repository; +use std::sync::Mutex; + +use anyhow::{anyhow, Context, Result}; +use git2::{Error, Oid, Repository}; use lazy_static::lazy_static; use regex::Regex; -use std::sync::Mutex; use crate::github_issue_labels_fetcher::GitHubIssueLabelsFetcher; use crate::github_user_fetcher::GitHubUsersFetcher; diff --git a/tools/changelog/src/create_log_lines.rs b/tools/changelog/src/create_log_lines.rs index 2bd5308c1d8..6377dc792fe 100644 --- a/tools/changelog/src/create_log_lines.rs +++ b/tools/changelog/src/create_log_lines.rs @@ -1,7 +1,5 @@ -use anyhow::Context; -use anyhow::Result; -use git2::Repository; -use git2::Sort; +use anyhow::{Context, Result}; +use git2::{Repository, Sort}; use crate::create_log_line::create_log_line; use crate::log_line::LogLine; diff --git a/tools/changelog/src/get_latest_version.rs b/tools/changelog/src/get_latest_version.rs index 22ce2a66933..a1634877d5f 100644 --- a/tools/changelog/src/get_latest_version.rs +++ b/tools/changelog/src/get_latest_version.rs @@ -1,8 +1,8 @@ -use crate::yew_package::YewPackage; use anyhow::Result; use git2::Repository; -use semver::Error; -use semver::Version; +use semver::{Error, Version}; + +use crate::yew_package::YewPackage; pub fn get_latest_version(package: &YewPackage) -> Result { let common_tag_pattern = format!("{}-v", package); diff --git a/tools/changelog/src/github_fetch.rs b/tools/changelog/src/github_fetch.rs index 255c426809f..7f6f07ca297 100644 --- a/tools/changelog/src/github_fetch.rs +++ b/tools/changelog/src/github_fetch.rs @@ -1,13 +1,10 @@ -use reqwest::header::HeaderMap; -use reqwest::header::ACCEPT; -use reqwest::header::AUTHORIZATION; -use reqwest::header::USER_AGENT; -use serde::de::DeserializeOwned; use std::thread; use std::time::Duration; use anyhow::{bail, Result}; use reqwest::blocking::Client; +use reqwest::header::{HeaderMap, ACCEPT, AUTHORIZATION, USER_AGENT}; +use serde::de::DeserializeOwned; pub fn github_fetch(url: &str, token: Option) -> Result { thread::sleep(Duration::from_secs(1)); diff --git a/tools/changelog/src/github_issue_labels_fetcher.rs b/tools/changelog/src/github_issue_labels_fetcher.rs index 1747b355bc7..76dccf7a084 100644 --- a/tools/changelog/src/github_issue_labels_fetcher.rs +++ b/tools/changelog/src/github_issue_labels_fetcher.rs @@ -1,6 +1,7 @@ +use std::collections::HashMap; + use anyhow::Result; use serde::Deserialize; -use std::collections::HashMap; use super::github_fetch::github_fetch; diff --git a/tools/changelog/src/github_user_fetcher.rs b/tools/changelog/src/github_user_fetcher.rs index 28381bb4679..b6bb8944f59 100644 --- a/tools/changelog/src/github_user_fetcher.rs +++ b/tools/changelog/src/github_user_fetcher.rs @@ -1,6 +1,7 @@ +use std::collections::HashMap; + use anyhow::Result; use serde::Deserialize; -use std::collections::HashMap; use super::github_fetch::github_fetch; diff --git a/tools/changelog/src/new_version_level.rs b/tools/changelog/src/new_version_level.rs index 43606c3c9d0..6955dfb16fb 100644 --- a/tools/changelog/src/new_version_level.rs +++ b/tools/changelog/src/new_version_level.rs @@ -1,6 +1,5 @@ use semver::Version; -use strum::Display; -use strum::EnumString; +use strum::{Display, EnumString}; #[derive(Debug, Clone, EnumString, Display)] #[strum(serialize_all = "lowercase")] diff --git a/tools/changelog/src/stdout_tag_description_changelog.rs b/tools/changelog/src/stdout_tag_description_changelog.rs index fc03f8d8cc6..adbb7ab0739 100644 --- a/tools/changelog/src/stdout_tag_description_changelog.rs +++ b/tools/changelog/src/stdout_tag_description_changelog.rs @@ -1,6 +1,6 @@ +use std::io::{stdout, Write}; + use anyhow::Result; -use std::io::stdout; -use std::io::Write; pub fn stdout_tag_description_changelog(fixes_logs: &[u8], features_logs: &[u8]) -> Result<()> { let mut tag_changelog = Vec::new(); diff --git a/tools/changelog/src/write_changelog_file.rs b/tools/changelog/src/write_changelog_file.rs index 6c96e2f0193..23d12c3a8b7 100644 --- a/tools/changelog/src/write_changelog_file.rs +++ b/tools/changelog/src/write_changelog_file.rs @@ -1,10 +1,8 @@ -use anyhow::Context; -use anyhow::Result; use std::fs; use std::fs::File; -use std::io::BufRead; -use std::io::BufReader; -use std::io::Write; +use std::io::{BufRead, BufReader, Write}; + +use anyhow::{Context, Result}; pub fn write_changelog(changelog_path: &str, version_changelog: &[u8]) -> Result<()> { let old_changelog = File::open(changelog_path) diff --git a/tools/changelog/src/write_log_lines.rs b/tools/changelog/src/write_log_lines.rs index 331f98bab15..12260c2460f 100644 --- a/tools/changelog/src/write_log_lines.rs +++ b/tools/changelog/src/write_log_lines.rs @@ -1,6 +1,7 @@ -use anyhow::Result; use std::io::Write; +use anyhow::Result; + use crate::log_line::LogLine; pub fn write_log_lines(log_lines: Vec) -> Result> { diff --git a/tools/changelog/src/write_version_changelog.rs b/tools/changelog/src/write_version_changelog.rs index 1eef3fc0b11..a5285d75807 100644 --- a/tools/changelog/src/write_version_changelog.rs +++ b/tools/changelog/src/write_version_changelog.rs @@ -1,6 +1,7 @@ +use std::io::Write; + use anyhow::Result; use semver::Version; -use std::io::Write; use crate::yew_package::YewPackage; diff --git a/tools/changelog/src/yew_package.rs b/tools/changelog/src/yew_package.rs index b0f773d60fc..30278c993d0 100644 --- a/tools/changelog/src/yew_package.rs +++ b/tools/changelog/src/yew_package.rs @@ -1,5 +1,4 @@ -use strum::Display; -use strum::EnumString; +use strum::{Display, EnumString}; #[derive(Debug, Clone, EnumString, Display)] #[strum(serialize_all = "kebab-case")] diff --git a/tools/changelog/tests/generate_yew_changelog_file.rs b/tools/changelog/tests/generate_yew_changelog_file.rs index 8cfc5d957e5..c4782cd1901 100644 --- a/tools/changelog/tests/generate_yew_changelog_file.rs +++ b/tools/changelog/tests/generate_yew_changelog_file.rs @@ -1,7 +1,6 @@ use std::fs; use std::fs::File; -use std::io::BufRead; -use std::io::BufReader; +use std::io::{BufRead, BufReader}; use std::str::FromStr; use anyhow::Result; diff --git a/tools/process-benchmark-results/src/main.rs b/tools/process-benchmark-results/src/main.rs index 286caa920b3..66eb157bad3 100644 --- a/tools/process-benchmark-results/src/main.rs +++ b/tools/process-benchmark-results/src/main.rs @@ -1,8 +1,9 @@ +use std::io; +use std::io::{Read, Write}; + use anyhow::Result; use serde::Serialize; use serde_json::Value; -use std::io; -use std::io::{Read, Write}; #[derive(Serialize)] struct GhActionBenchmark { diff --git a/tools/website-test/build.rs b/tools/website-test/build.rs index 596da514d23..8f3ac705cdb 100644 --- a/tools/website-test/build.rs +++ b/tools/website-test/build.rs @@ -1,9 +1,9 @@ -use glob::glob; use std::collections::HashMap; -use std::env; use std::fmt::{self, Write}; -use std::fs; use std::path::{Path, PathBuf}; +use std::{env, fs}; + +use glob::glob; #[derive(Debug, Default)] struct Level {