repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/classes_macro/classes-fail.rs
packages/yew-macro/tests/classes_macro/classes-fail.rs
use yew::prelude::*; fn compile_pass() { classes!(42); classes!(42.0); classes!("one" "two"); classes!(vec![42]); let some = Some(42); let none: Option<u32> = None; classes!(some); classes!(none); classes!("one", 42); classes!("one", "two three", "four"); } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/derive_props/fail.rs
packages/yew-macro/tests/derive_props/fail.rs
#![recursion_limit = "128"] use yew::prelude::*; mod t1 { use super::*; #[derive(Clone)] struct Value; #[derive(Clone, Properties, PartialEq)] pub struct Props { // ERROR: optional params must implement default #[prop_or_default] value: Value, } } mod t2 { use super::*; #[derive(Clone, Properties, PartialEq)] pub struct Props { // ERROR: old syntax no longer supported #[props(default)] value: String, } } mod t3 { use super::*; #[derive(Clone, Properties, PartialEq)] pub struct Props { value: String, } fn required_props_should_be_set() { ::yew::props!{ Props { } }; } } mod t4 { use super::*; #[derive(Clone, Properties, PartialEq)] pub struct Props { value: Option<String> } fn required_option_should_be_provided() { ::yew::props!{ Props { } }; } } mod t5 { use super::*; #[derive(Clone, Properties, PartialEq)] pub struct Props { // ERROR: prop_or must be given a value #[prop_or()] value: String, } } mod t6 { use super::*; #[derive(Clone, Properties, PartialEq)] pub struct Props { // ERROR: 123 is not a String #[prop_or(123)] value: String, } } mod t7 { use super::*; #[derive(Clone, Properties, PartialEq)] pub struct Props { // ERROR: 123 is not a function #[prop_or_else(123)] value: i32, } } mod t8 { use super::*; #[derive(Clone, Properties, PartialEq)] pub struct Props { // ERROR: cannot find function foo in this scope #[prop_or_else(foo)] value: String, } } mod t9 { use super::*; #[derive(Clone, Properties, PartialEq)] pub struct Props { // ERROR: the function must take no arguments #[prop_or_else(foo)] value: String, } fn foo(bar: i32) -> String { unimplemented!() } } mod t10 { use super::*; #[derive(Clone, Properties, PartialEq)] pub struct Props { // ERROR: the function returns incompatible types #[prop_or_else(foo)] value: String, } fn foo() -> i32 { unimplemented!() } } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/derive_props/pass.rs
packages/yew-macro/tests/derive_props/pass.rs
#![recursion_limit = "128"] // Shadow primitives #[allow(non_camel_case_types)] pub struct bool; #[allow(non_camel_case_types)] pub struct char; #[allow(non_camel_case_types)] pub struct f32; #[allow(non_camel_case_types)] pub struct f64; #[allow(non_camel_case_types)] pub struct i128; #[allow(non_camel_case_types)] pub struct i16; #[allow(non_camel_case_types)] pub struct i32; #[allow(non_camel_case_types)] pub struct i64; #[allow(non_camel_case_types)] pub struct i8; #[allow(non_camel_case_types)] pub struct isize; #[allow(non_camel_case_types)] pub struct str; #[allow(non_camel_case_types)] pub struct u128; #[allow(non_camel_case_types)] pub struct u16; #[allow(non_camel_case_types)] pub struct u32; #[allow(non_camel_case_types)] pub struct u64; #[allow(non_camel_case_types)] pub struct u8; #[allow(non_camel_case_types)] pub struct usize; mod t1 { #[derive(::std::clone::Clone, ::yew::Properties, ::std::cmp::PartialEq)] pub struct Props<T: ::std::clone::Clone + ::std::default::Default + ::std::cmp::PartialEq> { #[prop_or_default] value: T, } fn optional_prop_generics_should_work() { ::yew::props! { Props::<::std::primitive::bool> { } }; ::yew::props! { Props::<::std::primitive::bool> { value: true } }; } } mod t2 { #[derive(::std::clone::Clone, ::std::cmp::PartialEq)] struct Value; #[derive(::std::clone::Clone, ::yew::Properties, ::std::cmp::PartialEq)] pub struct Props<T: ::std::clone::Clone + ::std::cmp::PartialEq> { value: T, } fn required_prop_generics_should_work() { ::yew::props! { Props::<Value> { value: Value } }; } } mod t3 { #[derive(::std::clone::Clone, ::yew::Properties, ::std::cmp::PartialEq)] pub struct Props { b: ::std::primitive::i32, #[prop_or_default] a: ::std::primitive::i32, } fn order_is_alphabetized() { ::yew::props! { Props { b: 1 } }; ::yew::props! { Props { a: 1, b: 2 } }; } } mod t4 { #[derive(::std::clone::Clone, ::yew::Properties, ::std::cmp::PartialEq)] pub struct Props<T> where T: ::std::clone::Clone + ::std::default::Default + ::std::cmp::PartialEq, { #[prop_or_default] value: T, } fn optional_prop_generics_should_work() { ::yew::props! { Props::<::std::primitive::bool> { } }; ::yew::props! { Props::<::std::primitive::bool> { value: true } }; } } mod t5 { #[derive(::std::clone::Clone, ::yew::Properties, ::std::cmp::PartialEq)] pub struct Props< 'a, T: ::std::clone::Clone + ::std::default::Default + ::std::cmp::PartialEq + 'a, > { #[prop_or_default] static_value: &'static ::std::primitive::str, value: &'a T, } fn optional_prop_generics_with_lifetime_should_work() { use ::std::{convert::From, string::String}; let borrowed_value = &String::from(""); ::yew::props! { Props::<String> { value: borrowed_value, } }; ::yew::props! { Props::<String> { static_value: "", value: borrowed_value, } }; } } mod t6 { #[derive(::yew::Properties, ::std::clone::Clone, ::std::cmp::PartialEq)] pub struct Props<T: ::std::str::FromStr + ::std::clone::Clone + ::std::cmp::PartialEq> where <T as ::std::str::FromStr>::Err: ::std::clone::Clone + ::std::cmp::PartialEq, { value: ::std::result::Result<T, <T as ::std::str::FromStr>::Err>, } fn required_prop_generics_with_where_clause_should_work() { use ::std::{convert::From, result::Result::Ok, string::String}; ::yew::props! { Props::<String> { value: Ok(String::from("")) } }; } } mod t7 { #[derive(::std::clone::Clone, Debug, Eq, ::std::cmp::PartialEq)] pub enum Foo { One, Two, } #[derive(::std::clone::Clone, ::yew::Properties, ::std::cmp::PartialEq)] pub struct Props { #[prop_or(Foo::One)] value: Foo, } fn prop_or_value_should_work() { use ::std::assert_eq; let props = ::yew::props! { Props { } }; assert_eq!(props.value, Foo::One); ::yew::props! { Props { value: Foo::Two } }; } } mod t8 { #[derive(::std::clone::Clone, ::yew::Properties, ::std::cmp::PartialEq)] pub struct Props { #[prop_or_else(|| 123)] value: ::std::primitive::i32, } fn prop_or_else_closure_should_work() { use ::std::assert_eq; let props = ::yew::props! { Props { } }; assert_eq!(props.value, 123); ::yew::props! { Props { value: 123 } }; } } mod t9 { #[derive(::std::clone::Clone, ::yew::Properties, ::std::cmp::PartialEq)] pub struct Props<T: ::std::str::FromStr + ::std::clone::Clone + ::std::cmp::PartialEq> where <T as ::std::str::FromStr>::Err: ::std::clone::Clone + ::std::cmp::PartialEq, { #[prop_or_else(default_value)] value: ::std::result::Result<T, <T as ::std::str::FromStr>::Err>, } fn default_value<T: ::std::str::FromStr + ::std::clone::Clone>( ) -> ::std::result::Result<T, <T as ::std::str::FromStr>::Err> where <T as ::std::str::FromStr>::Err: ::std::clone::Clone, { "123".parse() } fn prop_or_else_function_with_generics_should_work() { use ::std::{assert_eq, result::Result::Ok}; let props = ::yew::props! { Props::<::std::primitive::i32> { } }; assert_eq!(props.value, Ok(123)); ::yew::props! { Props::<::std::primitive::i32> { value: Ok(456) } }; } } mod t10 { // this test makes sure that Yew handles generic params with default values properly. #[derive(::std::clone::Clone, ::yew::Properties, ::std::cmp::PartialEq)] pub struct Foo<S, M = S> where S: ::std::clone::Clone + ::std::cmp::PartialEq, M: ::std::clone::Clone + ::std::cmp::PartialEq, { bar: S, baz: M, } } mod t11 { // this test makes sure that Yew handles generic params with const generics properly. #[derive(::std::clone::Clone, ::yew::Properties, ::std::cmp::PartialEq)] pub struct Foo<T, const N: usize> where T: ::std::clone::Clone + ::std::cmp::PartialEq, { bar: [T; N], } } mod t12 { #[derive(::std::clone::Clone, ::yew::Properties, ::std::cmp::PartialEq)] pub struct Props<T: ::std::clone::Clone + ::std::cmp::PartialEq> { value: ::std::option::Option<T>, } fn optional_prop_generics_should_work() { ::yew::props! { Props::<::std::primitive::bool> { value: ::std::option::Option::Some(true) } }; ::yew::props! { Props::<::std::primitive::bool> { value: true } }; } } #[deny(non_snake_case, dead_code)] mod t13 { #[derive(::std::cmp::PartialEq, ::yew::Properties)] #[allow(non_snake_case)] // putting this on fields directly does not work, even in normal rust struct Props { #[allow(dead_code)] create_message: ::std::option::Option<bool>, NonSnakeCase: u32, } } mod raw_field_names { #[derive(::yew::Properties, ::std::cmp::PartialEq)] pub struct Props { r#true: u32, r#pointless_raw_name: u32, } } mod value_into_some_value_in_props { #[derive(::std::cmp::PartialEq, ::yew::Properties)] struct Props { required: ::std::option::Option<usize>, #[prop_or_default] optional: ::std::option::Option<usize> } #[::yew::component] fn Inner(_props: &Props) -> ::yew::html::Html { ::yew::html!{} } #[::yew::component] fn Main() -> ::yew::html::Html { ::yew::html! {<> <Inner required=3 optional=5/> <Inner required={::std::option::Option::Some(6)}/> </>} } } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/html_lints/fail.rs
packages/yew-macro/tests/html_lints/fail.rs
use yew::prelude::*; fn main() { let bad_a = html! { <a>{ "I don't have a href attribute" }</a> }; let bad_a_2 = html! { <a href="#">{ "I have a malformed href attribute" }</a> }; let bad_a_3 = html! { <a href="javascript:void(0)">{ "I have a malformed href attribute" }</a> }; let bad_img = html! { <img src="img.jpeg"/> }; let misformed_tagname = html! { <tExTAreA /> }; compile_error!("This macro call exists to deliberately fail the compilation of the test so we can verify output of lints"); }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/html_macro/generic-component-pass.rs
packages/yew-macro/tests/html_macro/generic-component-pass.rs
#![no_implicit_prelude] // Shadow primitives #[allow(non_camel_case_types)] pub struct bool; #[allow(non_camel_case_types)] pub struct char; #[allow(non_camel_case_types)] pub struct f32; #[allow(non_camel_case_types)] pub struct f64; #[allow(non_camel_case_types)] pub struct i128; #[allow(non_camel_case_types)] pub struct i16; #[allow(non_camel_case_types)] pub struct i32; #[allow(non_camel_case_types)] pub struct i64; #[allow(non_camel_case_types)] pub struct i8; #[allow(non_camel_case_types)] pub struct isize; #[allow(non_camel_case_types)] pub struct str; #[allow(non_camel_case_types)] pub struct u128; #[allow(non_camel_case_types)] pub struct u16; #[allow(non_camel_case_types)] pub struct u32; #[allow(non_camel_case_types)] pub struct u64; #[allow(non_camel_case_types)] pub struct u8; #[allow(non_camel_case_types)] pub struct usize; pub struct Generic<T> { marker: ::std::marker::PhantomData<T>, } impl<T> ::yew::Component for Generic<T> where T: 'static, { type Message = (); type Properties = (); fn create(_ctx: &::yew::Context<Self>) -> Self { ::std::unimplemented!() } fn view(&self, _ctx: &::yew::Context<Self>) -> ::yew::Html { ::std::unimplemented!() } } pub struct Generic2<T1, T2> { marker: ::std::marker::PhantomData<(T1, T2)>, } impl<T1, T2> ::yew::Component for Generic2<T1, T2> where T1: 'static, T2: 'static, { type Message = (); type Properties = (); fn create(_ctx: &::yew::Context<Self>) -> Self { ::std::unimplemented!() } fn view(&self, _ctx: &::yew::Context<Self>) -> ::yew::Html { ::std::unimplemented!() } } fn compile_pass() { _ = ::yew::html! { <Generic<::std::string::String> /> }; _ = ::yew::html! { <Generic<(u8, bool)> /> }; _ = ::yew::html! { <Generic<(u8, bool)> ></Generic<(u8, bool)>> }; _ = ::yew::html! { <Generic<::std::string::String> ></Generic<::std::string::String>> }; _ = ::yew::html! { <Generic<::std::vec::Vec<::std::string::String>> /> }; _ = ::yew::html! { <Generic<::std::vec::Vec<::std::string::String>>></ Generic<::std::vec::Vec<::std::string::String>>> }; _ = ::yew::html! { <Generic<::std::primitive::usize> /> }; _ = ::yew::html! { <Generic<::std::primitive::usize>></Generic<::std::primitive::usize>> }; _ = ::yew::html! { <Generic<::std::string::String, > /> }; _ = ::yew::html! { <Generic<::std::string::String, >></Generic<::std::string::String,>> }; _ = ::yew::html! { <Generic2<::std::string::String, ::std::string::String> /> }; _ = ::yew::html! { <Generic2<::std::string::String, ::std::string::String>></Generic2<::std::string::String, ::std::string::String>> }; _ = ::yew::html! { <Generic2<::std::string::String, ::std::string::String, > /> }; _ = ::yew::html! { <Generic2<::std::string::String, ::std::string::String, >></Generic2<::std::string::String, ::std::string::String, >> }; } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/html_macro/component-fail.rs
packages/yew-macro/tests/html_macro/component-fail.rs
use yew::html::ChildrenRenderer; use yew::prelude::*; #[derive(Clone, Properties, PartialEq)] pub struct ChildProperties { #[prop_or_default] pub string: String, pub int: i32, } pub struct Child; impl Component for Child { type Message = (); type Properties = ChildProperties; fn create(_ctx: &Context<Self>) -> Self { unimplemented!() } fn view(&self, _ctx: &Context<Self>) -> Html { unimplemented!() } } #[derive(Clone, Properties, PartialEq)] pub struct ChildContainerProperties { pub children: ChildrenWithProps<Child>, } pub struct ChildContainer; impl Component for ChildContainer { type Message = (); type Properties = ChildContainerProperties; fn create(_ctx: &Context<Self>) -> Self { unimplemented!() } fn view(&self, _ctx: &Context<Self>) -> Html { unimplemented!() } } fn compile_fail() { html! { <Child> }; html! { <Child:: /> }; html! { <Child with /> }; html! { <Child .. /> }; html! { <Child ..{ 5 + } /> }; html! { <Child props /> }; html! { <Child with props > }; html! { <Child ..props > }; let (p1, p2); html! { <Child with p1 with p2 /> }; html! { <Child ..p1 ..p2 /> }; html! { <Child with props ref={()} ref={()} /> }; html! { <Child ..props ref={()} ref={()} /> }; html! { <Child with props ref={()} ref={()} value=1 /> }; html! { <Child ..props ref={()} ref={()} value=1 /> }; html! { <Child with props ref={()} value=1 ref={()} /> }; html! { <Child ..props ref={()} value=1 ref={()} /> }; html! { <Child with props value=1 ref={()} ref={()} /> }; html! { <Child ..props value=1 ref={()} ref={()} /> }; html! { <Child value=1 with props ref={()} ref={()} /> }; html! { <Child value=1 ..props ref={()} ref={()} /> }; html! { <Child value=1 ref={()} with props ref={()} /> }; html! { <Child value=1 ref={()} ..props ref={()} /> }; html! { <Child ref={()} ref={()} value=1 with props /> }; html! { <Child ref={()} ref={()} value=1 ..props /> }; html! { <Child with props r#ref={()} r#ref={()} /> }; html! { <Child ..props r#ref={()} r#ref={()} /> }; html! { <Child with props r#ref={()} r#ref={()} value=1 /> }; html! { <Child ..props r#ref={()} r#ref={()} value=1 /> }; html! { <Child with props r#ref={()} value=1 r#ref={()} /> }; html! { <Child ..props r#ref={()} value=1 r#ref={()} /> }; html! { <Child with props value=1 r#ref={()} r#ref={()} /> }; html! { <Child ..props value=1 r#ref={()} r#ref={()} /> }; html! { <Child value=1 with props r#ref={()} r#ref={()} /> }; html! { <Child value=1 ..props r#ref={()} r#ref={()} /> }; html! { <Child value=1 r#ref={()} with props r#ref={()} /> }; html! { <Child value=1 r#ref={()} ..props r#ref={()} /> }; html! { <Child r#ref={()} r#ref={()} value=1 with props /> }; html! { <Child r#ref={()} r#ref={()} value=1 ..props /> }; html! { <Child ..blah /> }; html! { <Child value=1 ..props /> }; html! { <Child .. props value=1 /> }; html! { <Child type=0 /> }; html! { <Child ref=() /> }; html! { <Child invalid-prop-name=0 /> }; html! { <Child unknown="unknown" /> }; html! { <Child string= /> }; html! { <Child int=1 int=2 int=3 /> }; html! { <Child int=1 string={} /> }; html! { <Child int=1 string=3 /> }; html! { <Child int=1 string={3} /> }; html! { <Child int=1 ref={()} /> }; html! { <Child int=1 ref={()} ref={()} /> }; html! { <Child int=1 r#ref={()} /> }; html! { <Child int=1 r#ref={()} r#ref={()} /> }; html! { <Child int=0u32 /> }; html! { <Child string="abc" /> }; html! { </Child> }; html! { <Child><Child></Child> }; html! { <Child></Child><Child></Child> }; html! { <Child>{ "Not allowed" }</Child> }; let num = 1; html! { <Child int=num ..props /> }; // trying to overwrite `children` on props which don't take any. html! { <Child ..ChildProperties { string: "hello".to_owned(), int: 5 }> { "please error" } </Child> }; html! { <ChildContainer /> }; html! { <ChildContainer></ChildContainer> }; html! { <ChildContainer>{ "Not allowed" }</ChildContainer> }; html! { <ChildContainer><></></ChildContainer> }; html! { <ChildContainer><other /></ChildContainer> }; // using `children` as a prop while simultaneously passing children using the syntactic sugar let children = ChildrenRenderer::new(vec![html_nested! { <Child int=0 /> }]); html! { <ChildContainer {children}> <Child int=1 /> </ChildContainer> }; html_nested! { <span>{ 1 }</span> <span>{ 2 }</span> }; html! { <Child {std::f64::consts::PI} /> }; html! { <Child {7 + 6} /> }; html! { <Child {children.len()} /> }; } #[derive(Clone, Properties, PartialEq)] pub struct HtmlInPropsProperties { pub header: ::yew::Html, } #[component] fn HtmlInProps(props: &HtmlInPropsProperties) -> Html { let _ = (); unimplemented!() } fn not_expressions() { html! { <HtmlInProps header={macro_rules! declare { }} /> }; html! { <HtmlInProps header={format!("ending with semi");} /> }; } fn mismatch_closing_tags() { pub struct A; impl Component for A { type Message = (); type Properties = (); fn create(_ctx: &Context<Self>) -> Self { unimplemented!() } fn view(&self, _ctx: &Context<Self>) -> Html { unimplemented!() } } pub struct B; impl Component for B { type Message = (); type Properties = (); fn create(_ctx: &Context<Self>) -> Self { unimplemented!() } fn view(&self, _ctx: &Context<Self>) -> Html { unimplemented!() } } let _ = html! { <A></B> }; let _ = html! { <A></> }; } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/html_macro/dyn-element-pass.rs
packages/yew-macro/tests/html_macro/dyn-element-pass.rs
#![no_implicit_prelude] // Shadow primitives #[allow(non_camel_case_types)] pub struct bool; #[allow(non_camel_case_types)] pub struct char; #[allow(non_camel_case_types)] pub struct f32; #[allow(non_camel_case_types)] pub struct f64; #[allow(non_camel_case_types)] pub struct i128; #[allow(non_camel_case_types)] pub struct i16; #[allow(non_camel_case_types)] pub struct i32; #[allow(non_camel_case_types)] pub struct i64; #[allow(non_camel_case_types)] pub struct i8; #[allow(non_camel_case_types)] pub struct isize; #[allow(non_camel_case_types)] pub struct str; #[allow(non_camel_case_types)] pub struct u128; #[allow(non_camel_case_types)] pub struct u16; #[allow(non_camel_case_types)] pub struct u32; #[allow(non_camel_case_types)] pub struct u64; #[allow(non_camel_case_types)] pub struct u8; #[allow(non_camel_case_types)] pub struct usize; fn main() { let dyn_tag = || ::std::string::ToString::to_string("test"); let mut next_extra_tag = { let mut it = ::std::iter::IntoIterator::into_iter(::std::vec!["a", "b"]); move || ::std::option::Option::unwrap(::std::iter::Iterator::next(&mut it)) }; _ = ::yew::html! { <@{ dyn_tag() }> <@{ next_extra_tag() } class="extra-a"/> <@{ next_extra_tag() } class="extra-b"/> </@> }; _ = ::yew::html! { <@{ if dyn_tag() == "test" { "div" } else { "a" } }/> }; let input_tag = "input"; let input_dom = ::yew::html! { <@{input_tag} /> }; assert!( ::std::matches!(input_dom, ::yew::virtual_dom::VNode::VTag(ref vtag) if vtag.tag() == "input") ); }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/html_macro/node-pass.rs
packages/yew-macro/tests/html_macro/node-pass.rs
#![no_implicit_prelude] // Shadow primitives #[allow(non_camel_case_types)] pub struct bool; #[allow(non_camel_case_types)] pub struct char; #[allow(non_camel_case_types)] pub struct f32; #[allow(non_camel_case_types)] pub struct f64; #[allow(non_camel_case_types)] pub struct i128; #[allow(non_camel_case_types)] pub struct i16; #[allow(non_camel_case_types)] pub struct i32; #[allow(non_camel_case_types)] pub struct i64; #[allow(non_camel_case_types)] pub struct i8; #[allow(non_camel_case_types)] pub struct isize; #[allow(non_camel_case_types)] pub struct str; #[allow(non_camel_case_types)] pub struct u128; #[allow(non_camel_case_types)] pub struct u16; #[allow(non_camel_case_types)] pub struct u32; #[allow(non_camel_case_types)] pub struct u64; #[allow(non_camel_case_types)] pub struct u8; #[allow(non_camel_case_types)] pub struct usize; fn main() { _ = ::yew::html! { b'b' }; _ = ::yew::html! { 'a' }; _ = ::yew::html! { "hello" }; _ = ::yew::html! { 42 }; _ = ::yew::html! { 1.234 }; _ = ::yew::html! { true }; _ = ::yew::html! { <span>{ "" }</span> }; _ = ::yew::html! { <span>{ 'a' }</span> }; _ = ::yew::html! { <span>{ "hello" }</span> }; _ = ::yew::html! { <span>{ "42" }</span> }; _ = ::yew::html! { <span>{ "1.234" }</span> }; _ = ::yew::html! { <span>{ "true" }</span> }; _ = ::yew::html! { ::std::format!("Hello") }; _ = ::yew::html! { ::std::string::ToString::to_string("Hello") }; let msg = "Hello"; _ = ::yew::html! { msg }; }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/html_macro/component-unimplemented-fail.rs
packages/yew-macro/tests/html_macro/component-unimplemented-fail.rs
use yew::prelude::*; struct Unimplemented; fn compile_fail() { html! { <Unimplemented /> }; } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/html_macro/for-pass.rs
packages/yew-macro/tests/html_macro/for-pass.rs
#![no_implicit_prelude] // Shadow primitives #[allow(non_camel_case_types)] pub struct bool; #[allow(non_camel_case_types)] pub struct char; #[allow(non_camel_case_types)] pub struct f32; #[allow(non_camel_case_types)] pub struct f64; #[allow(non_camel_case_types)] pub struct i128; #[allow(non_camel_case_types)] pub struct i16; #[allow(non_camel_case_types)] pub struct i32; #[allow(non_camel_case_types)] pub struct i64; #[allow(non_camel_case_types)] pub struct i8; #[allow(non_camel_case_types)] pub struct isize; #[allow(non_camel_case_types)] pub struct str; #[allow(non_camel_case_types)] pub struct u128; #[allow(non_camel_case_types)] pub struct u16; #[allow(non_camel_case_types)] pub struct u32; #[allow(non_camel_case_types)] pub struct u64; #[allow(non_camel_case_types)] pub struct u8; #[allow(non_camel_case_types)] pub struct usize; fn main() { _ = ::yew::html!{ for i in 0 .. 10 { <span>{i}</span> } }; struct Pair { value1: &'static ::std::primitive::str, value2: ::std::primitive::i32 } _ = ::yew::html! { for Pair { value1, value2 } in ::std::iter::Iterator::map(0 .. 10, |value2| Pair { value1: "Yew", value2 }) { <span>{value1}</span> <span>{value2}</span> } }; fn rand_number() -> ::std::primitive::u32 { 4 // chosen by fair dice roll. guaranteed to be random. } _ = ::yew::html!{ for _ in 0..5 { <div> {{ loop { let a = rand_number(); if a % 2 == 0 { break a; } } }} </div> } } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/html_macro/component-any-children-pass.rs
packages/yew-macro/tests/html_macro/component-any-children-pass.rs
// Shadow primitives #[allow(non_camel_case_types)] pub struct bool; #[allow(non_camel_case_types)] pub struct char; #[allow(non_camel_case_types)] pub struct f32; #[allow(non_camel_case_types)] pub struct f64; #[allow(non_camel_case_types)] pub struct i128; #[allow(non_camel_case_types)] pub struct i16; #[allow(non_camel_case_types)] pub struct i32; #[allow(non_camel_case_types)] pub struct i64; #[allow(non_camel_case_types)] pub struct i8; #[allow(non_camel_case_types)] pub struct isize; #[allow(non_camel_case_types)] pub struct str; #[allow(non_camel_case_types)] pub struct u128; #[allow(non_camel_case_types)] pub struct u16; #[allow(non_camel_case_types)] pub struct u32; #[allow(non_camel_case_types)] pub struct u64; #[allow(non_camel_case_types)] pub struct u8; #[allow(non_camel_case_types)] pub struct usize; #[derive( ::std::clone::Clone, ::yew::Properties, ::std::default::Default, ::std::cmp::PartialEq, )] pub struct ContainerProperties { pub int: ::std::primitive::i32, // You can use Html as Children. #[prop_or_default] pub children: ::yew::Html, #[prop_or_default] pub header: ::yew::Html, } pub struct Container; impl ::yew::Component for Container { type Message = (); type Properties = ContainerProperties; fn create(_ctx: &::yew::Context<Self>) -> Self { ::std::unimplemented!() } fn view(&self, _ctx: &::yew::Context<Self>) -> ::yew::Html { ::std::unimplemented!() } } #[derive(::std::clone::Clone, ::std::cmp::PartialEq)] pub enum ChildrenVariants { Child(::yew::virtual_dom::VChild<Child>), AltChild(::yew::virtual_dom::VChild<AltChild>), } impl ::std::convert::From<::yew::virtual_dom::VChild<Child>> for ChildrenVariants { fn from(comp: ::yew::virtual_dom::VChild<Child>) -> Self { ChildrenVariants::Child(comp) } } impl ::std::convert::From<::yew::virtual_dom::VChild<AltChild>> for ChildrenVariants { fn from(comp: ::yew::virtual_dom::VChild<AltChild>) -> Self { ChildrenVariants::AltChild(comp) } } impl ::std::convert::Into<::yew::virtual_dom::VNode> for ChildrenVariants { fn into(self) -> ::yew::virtual_dom::VNode { match self { Self::Child(comp) => ::yew::virtual_dom::VNode::VComp(::std::rc::Rc::new(::std::convert::Into::< ::yew::virtual_dom::VComp, >::into(comp))), Self::AltChild(comp) => ::yew::virtual_dom::VNode::VComp(::std::rc::Rc::new(::std::convert::Into::< ::yew::virtual_dom::VComp, >::into(comp))), } } } #[derive( ::std::clone::Clone, ::yew::Properties, ::std::default::Default, ::std::cmp::PartialEq, )] pub struct ChildProperties { #[prop_or_default] pub string: ::std::string::String, #[prop_or_default] pub r#fn: ::std::primitive::i32, #[prop_or_default] pub r#ref: ::yew::NodeRef, pub int: ::std::primitive::i32, #[prop_or_default] pub opt_str: ::std::option::Option<::std::string::String>, #[prop_or_default] pub vec: ::std::vec::Vec<::std::primitive::i32>, #[prop_or_default] pub optional_callback: ::std::option::Option<::yew::Callback<()>>, } pub struct Child; impl ::yew::Component for Child { type Message = (); type Properties = ChildProperties; fn create(_ctx: &::yew::Context<Self>) -> Self { ::std::unimplemented!() } fn view(&self, _ctx: &::yew::Context<Self>) -> ::yew::Html { ::std::unimplemented!() } } pub struct AltChild; impl ::yew::Component for AltChild { type Message = (); type Properties = (); fn create(_ctx: &::yew::Context<Self>) -> Self { ::std::unimplemented!() } fn view(&self, _ctx: &::yew::Context<Self>) -> ::yew::Html { ::std::unimplemented!() } } mod scoped { pub use super::{Child, Container}; } #[derive( ::std::clone::Clone, ::yew::Properties, ::std::default::Default, ::std::cmp::PartialEq, )] pub struct RenderPropProps { // You can use Callback<()> as Children. #[prop_or_default] pub children: ::yew::Callback<()>, } #[::yew::component] pub fn RenderPropComp(_props: &RenderPropProps) -> ::yew::Html { ::yew::html! {} } fn compile_pass() { _ = ::yew::html! { <Child int=1 /> }; _ = ::yew::html! { <Child int=1 r#fn=1 /> }; _ = ::yew::html! { <> <Child int=1 /> <scoped::Child int=1 /> </> }; let props = <<Child as ::yew::Component>::Properties as ::std::default::Default>::default(); let node_ref = <::yew::NodeRef as ::std::default::Default>::default(); _ = ::yew::html! { <> <Child ..::std::clone::Clone::clone(&props) /> <Child int={1} ..props /> <Child r#ref={::std::clone::Clone::clone(&node_ref)} int={2} ..::yew::props!(Child::Properties { int: 5 }) /> <Child int=3 r#ref={::std::clone::Clone::clone(&node_ref)} ..::yew::props!(Child::Properties { int: 5 }) /> <Child r#ref={::std::clone::Clone::clone(&node_ref)} ..::yew::props!(Child::Properties { int: 5 }) /> <Child r#ref={&node_ref} ..<<Child as ::yew::Component>::Properties as ::std::default::Default>::default() /> <Child r#ref={node_ref} ..<<Child as ::yew::Component>::Properties as ::std::default::Default>::default() /> </> }; _ = ::yew::html! { <> <Child int=1 string="child" /> <Child int=1 /> <Child int={1+1} /> <Child int=1 vec={::std::vec![1]} /> <Child string={<::std::string::String as ::std::convert::From<&'static ::std::primitive::str>>::from("child")} int=1 /> <Child opt_str="child" int=1 /> <Child opt_str={<::std::string::String as ::std::convert::From<&'static ::std::primitive::str>>::from("child")} int=1 /> <Child opt_str={::std::option::Option::Some("child")} int=1 /> <Child opt_str={::std::option::Option::Some(<::std::string::String as ::std::convert::From<&'static ::std::primitive::str>>::from("child"))} int=1 /> </> }; let name_expr = "child"; _ = ::yew::html! { <Child int=1 string={name_expr} /> }; let string = "child"; let int = 1; _ = ::yew::html! { <Child {int} {string} /> }; _ = ::yew::html! { <> <Child int=1 /> <Child int=1 optional_callback={::std::option::Option::Some(<::yew::Callback<()> as ::std::convert::From<_>>::from(|_| ()))} /> <Child int=1 optional_callback={<::yew::Callback<()> as ::std::convert::From<_>>::from(|_| ())} /> <Child int=1 optional_callback={::std::option::Option::None::<::yew::Callback<_>>} /> </> }; let node_ref = <::yew::NodeRef as ::std::default::Default>::default(); _ = ::yew::html! { <> <Child int=1 r#ref={node_ref} /> </> }; let int = 1; let node_ref = <::yew::NodeRef as ::std::default::Default>::default(); _ = ::yew::html! { <> <Child {int} r#ref={node_ref} /> </> }; let props = <<Container as ::yew::Component>::Properties as ::std::default::Default>::default(); let child_props = <<Child as ::yew::Component>::Properties as ::std::default::Default>::default(); _ = ::yew::html! { <> <Container int=1 /> <Container int=1></Container> <Container ..::std::clone::Clone::clone(&props)> <div>{ "hello world" }</div> </Container> <Container int=1 ..::std::clone::Clone::clone(&props)> <div>{ "hello world" }</div> </Container> <Container int=1 ..::std::clone::Clone::clone(&props)> <Child int=2 opt_str="hello" ..::std::clone::Clone::clone(&child_props) /> </Container> <Container int=1 ..::std::clone::Clone::clone(&props)> <Child int=2 vec={::std::vec![0]} ..::std::clone::Clone::clone(&child_props) /> </Container> <Container int=1 ..props> <Child int=2 string="hello" ..child_props /> </Container> <Container int=1> <Child int=2 /> </Container> <scoped::Container int=1> <scoped::Container int=2/> </scoped::Container> <Container int=1 children={::yew::html::ChildrenRenderer::new( ::std::vec![::yew::html!{ "::std::string::String" }] )} /> <Container int=1 header={::yew::html!{ <Child int=2 /> }} /> </> }; let variants = || -> ::std::vec::Vec<ChildrenVariants> { ::std::vec![ ChildrenVariants::Child(::yew::virtual_dom::VChild::new( <ChildProperties as ::std::default::Default>::default(), ::std::option::Option::None, )), ChildrenVariants::AltChild(::yew::virtual_dom::VChild::new( (), ::std::option::Option::None )), ] }; _ = ::yew::html! { <> { ::std::iter::Iterator::collect::<::yew::virtual_dom::VNode>( ::std::iter::Iterator::filter( ::std::iter::IntoIterator::into_iter(variants()), |c| match c { ChildrenVariants::Child(_) => true, _ => false, } ) ) } <div> { ::std::iter::Iterator::collect::<::yew::virtual_dom::VNode>( ::std::iter::Iterator::filter( ::std::iter::IntoIterator::into_iter(variants()), |c| match c { ChildrenVariants::AltChild(_) => true, _ => false, } ) ) } </div> </> }; _ = ::yew::html_nested! { 1 }; _ = ::yew::html! { <RenderPropComp> {|_arg| {}} </RenderPropComp> }; } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/html_macro/block-fail.rs
packages/yew-macro/tests/html_macro/block-fail.rs
use yew::prelude::*; fn compile_fail() { html! { <> { () } </> }; let not_tree = || (); html! { <div>{ not_tree() }</div> }; html! { <>{ for (0..3).map(|_| not_tree()) }</> }; } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/html_macro/list-fail.rs
packages/yew-macro/tests/html_macro/list-fail.rs
use yew::prelude::*; fn compile_fail() { // missing closing tag html! { <> }; html! { <><> }; html! { <><></> }; // missing starting tag html! { </> }; html! { </></> }; // multiple root nodes html! { <></><></> }; // invalid child content html! { <>invalid</> }; // no key value html! { <key=></> }; // wrong closing tag html! { <key="key".to_string()></key> }; // multiple keys html! { <key="first key" key="second key" /> }; // invalid prop html! { <some_attr="test"></> }; } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/html_macro/iterable-fail.rs
packages/yew-macro/tests/html_macro/iterable-fail.rs
use yew::prelude::*; fn compile_fail() { html! { for }; html! { for () }; html! { {for ()} }; html! { for Vec::<()>::new().into_iter() }; let empty = Vec::<()>::new().into_iter(); html! { for empty }; let empty = Vec::<()>::new(); html! { {for empty.iter()} }; html! { <> <div/> { for () } </> }; } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/html_macro/html-node-pass.rs
packages/yew-macro/tests/html_macro/html-node-pass.rs
#![no_implicit_prelude] // Shadow primitives #[allow(non_camel_case_types)] pub struct bool; #[allow(non_camel_case_types)] pub struct char; #[allow(non_camel_case_types)] pub struct f32; #[allow(non_camel_case_types)] pub struct f64; #[allow(non_camel_case_types)] pub struct i128; #[allow(non_camel_case_types)] pub struct i16; #[allow(non_camel_case_types)] pub struct i32; #[allow(non_camel_case_types)] pub struct i64; #[allow(non_camel_case_types)] pub struct i8; #[allow(non_camel_case_types)] pub struct isize; #[allow(non_camel_case_types)] pub struct str; #[allow(non_camel_case_types)] pub struct u128; #[allow(non_camel_case_types)] pub struct u16; #[allow(non_camel_case_types)] pub struct u32; #[allow(non_camel_case_types)] pub struct u64; #[allow(non_camel_case_types)] pub struct u8; #[allow(non_camel_case_types)] pub struct usize; fn compile_pass() { _ = ::yew::html! { "" }; _ = ::yew::html! { 'a' }; _ = ::yew::html! { "hello" }; _ = ::yew::html! { 42 }; _ = ::yew::html! { 1.234 }; _ = ::yew::html! { <span>{ "" }</span> }; _ = ::yew::html! { <span>{ 'a' }</span> }; _ = ::yew::html! { <span>{ "hello" }</span> }; _ = ::yew::html! { <span>{ 42 }</span> }; _ = ::yew::html! { <span>{ 1.234 }</span> }; _ = ::yew::html! { ::std::format!("Hello") }; _ = ::yew::html! { {<::std::string::String as ::std::convert::From<&::std::primitive::str>>::from("Hello") } }; let msg = "Hello"; _ = ::yew::html! { msg }; } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/html_macro/list-pass.rs
packages/yew-macro/tests/html_macro/list-pass.rs
#![no_implicit_prelude] // Shadow primitives #[allow(non_camel_case_types)] pub struct bool; #[allow(non_camel_case_types)] pub struct char; #[allow(non_camel_case_types)] pub struct f32; #[allow(non_camel_case_types)] pub struct f64; #[allow(non_camel_case_types)] pub struct i128; #[allow(non_camel_case_types)] pub struct i16; #[allow(non_camel_case_types)] pub struct i32; #[allow(non_camel_case_types)] pub struct i64; #[allow(non_camel_case_types)] pub struct i8; #[allow(non_camel_case_types)] pub struct isize; #[allow(non_camel_case_types)] pub struct str; #[allow(non_camel_case_types)] pub struct u128; #[allow(non_camel_case_types)] pub struct u16; #[allow(non_camel_case_types)] pub struct u32; #[allow(non_camel_case_types)] pub struct u64; #[allow(non_camel_case_types)] pub struct u8; #[allow(non_camel_case_types)] pub struct usize; fn main() { _ = ::yew::html! {}; _ = ::yew::html! { <></> }; _ = ::yew::html! { <> <></> <></> </> }; _ = ::yew::html! { <key={::std::string::ToString::to_string("key")}> </> }; let children = ::std::vec![ ::yew::html! { <span>{ "Hello" }</span> }, ::yew::html! { <span>{ "World" }</span> }, ]; _ = ::yew::html! { <>{ children }</> }; }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/html_macro/svg-pass.rs
packages/yew-macro/tests/html_macro/svg-pass.rs
#![no_implicit_prelude] // Shadow primitives #[allow(non_camel_case_types)] pub struct bool; #[allow(non_camel_case_types)] pub struct char; #[allow(non_camel_case_types)] pub struct f32; #[allow(non_camel_case_types)] pub struct f64; #[allow(non_camel_case_types)] pub struct i128; #[allow(non_camel_case_types)] pub struct i16; #[allow(non_camel_case_types)] pub struct i32; #[allow(non_camel_case_types)] pub struct i64; #[allow(non_camel_case_types)] pub struct i8; #[allow(non_camel_case_types)] pub struct isize; #[allow(non_camel_case_types)] pub struct str; #[allow(non_camel_case_types)] pub struct u128; #[allow(non_camel_case_types)] pub struct u16; #[allow(non_camel_case_types)] pub struct u32; #[allow(non_camel_case_types)] pub struct u64; #[allow(non_camel_case_types)] pub struct u8; #[allow(non_camel_case_types)] pub struct usize; fn main() { // Ensure Rust keywords can be used as element names. // See: #1771 _ = ::yew::html! { <a class="btn btn-primary" href="https://example.org/"> <svg class="bi" fill="currentColor"> <use href="/bootstrap-icons.svg#wrench"/> </svg> <span>{"Go to example.org"}</span> </a> }; // some general SVG _ = ::yew::html! { <svg width="149" height="147" viewBox="0 0 149 147" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M60.5776 13.8268L51.8673 42.6431L77.7475 37.331L60.5776 13.8268Z" fill="#DEB819"/> <path d="M108.361 94.9937L138.708 90.686L115.342 69.8642" stroke="black" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/> <g filter="url(#filter0_d)"> <circle cx="75.3326" cy="73.4918" r="55" fill="#FDD630"/> <circle cx="75.3326" cy="73.4918" r="52.5" stroke="black" stroke-width="5"/> </g> <circle cx="71" cy="99" r="5" fill="white" fill-opacity="0.75" stroke="black" stroke-width="3"/> <defs> <filter id="filter0_d" x="16.3326" y="18.4918" width="118" height="118" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"> <feGaussianBlur stdDeviation="2"/> <feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"/> </filter> </defs> </svg> }; }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/html_macro/html-if-fail.rs
packages/yew-macro/tests/html_macro/html-if-fail.rs
use yew::prelude::*; fn compile_fail() { html! { if {} }; html! { if 42 {} }; html! { if true {} else }; html! { if true {} else if {} }; html! { if true {} else if true {} else }; html! { if true {} else if true {} else }; } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/html_macro/iterable-pass.rs
packages/yew-macro/tests/html_macro/iterable-pass.rs
#![no_implicit_prelude] // Shadow primitives #[allow(non_camel_case_types)] pub struct bool; #[allow(non_camel_case_types)] pub struct char; #[allow(non_camel_case_types)] pub struct f32; #[allow(non_camel_case_types)] pub struct f64; #[allow(non_camel_case_types)] pub struct i128; #[allow(non_camel_case_types)] pub struct i16; #[allow(non_camel_case_types)] pub struct i32; #[allow(non_camel_case_types)] pub struct i64; #[allow(non_camel_case_types)] pub struct i8; #[allow(non_camel_case_types)] pub struct isize; #[allow(non_camel_case_types)] pub struct str; #[allow(non_camel_case_types)] pub struct u128; #[allow(non_camel_case_types)] pub struct u16; #[allow(non_camel_case_types)] pub struct u32; #[allow(non_camel_case_types)] pub struct u64; #[allow(non_camel_case_types)] pub struct u8; #[allow(non_camel_case_types)] pub struct usize; fn empty_vec() -> ::std::vec::Vec<::yew::Html> { ::std::vec::Vec::<::yew::Html>::new() } fn empty_iter() -> impl ::std::iter::Iterator<Item = ::yew::Html> { ::std::iter::empty::<::yew::Html>() } fn main() { _ = ::yew::html! { {for empty_iter()} }; _ = ::yew::html! { {for { empty_iter() }} }; let empty = empty_vec(); _ = ::yew::html! { {for empty} }; _ = ::yew::html! {<> {for empty_vec()} </>}; _ = ::yew::html! {<> {for ::std::iter::IntoIterator::into_iter(empty_vec())} </>}; _ = ::yew::html! {<> {for ::std::iter::Iterator::map(0..3, |num| { ::yew::html! { <span>{ num }</span> } })} </>}; }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/html_macro/html-if-pass.rs
packages/yew-macro/tests/html_macro/html-if-pass.rs
#![no_implicit_prelude] fn compile_pass_lit() { _ = ::yew::html! { if true {} }; _ = ::yew::html! { if true { <div/> } }; _ = ::yew::html! { if true { <div/><div/> } }; _ = ::yew::html! { if true { <><div/><div/></> } }; _ = ::yew::html! { if true { { ::yew::html! {} } } }; _ = ::yew::html! { if true { { { let _x = 42; ::yew::html! {} } } } }; _ = ::yew::html! { if true {} else {} }; _ = ::yew::html! { if true {} else if true {} }; _ = ::yew::html! { if true {} else if true {} else {} }; _ = ::yew::html! { if let ::std::option::Option::Some(text) = ::std::option::Option::Some("text") { <span>{ text }</span> } }; _ = ::yew::html! { <><div/>if true {}<div/></> }; _ = ::yew::html! { <div>if true {}</div> }; } fn compile_pass_expr() { let condition = true; _ = ::yew::html! { if condition {} }; _ = ::yew::html! { if condition { <div/> } }; _ = ::yew::html! { if condition { <div/><div/> } }; _ = ::yew::html! { if condition { <><div/><div/></> } }; _ = ::yew::html! { if condition { { ::yew::html! {} } } }; _ = ::yew::html! { if condition { { { let _x = 42; ::yew::html! {} } } } }; _ = ::yew::html! { if condition {} else {} }; _ = ::yew::html! { if condition {} else if condition {} }; _ = ::yew::html! { if condition {} else if condition {} else {} }; _ = ::yew::html! { if let ::std::option::Option::Some(text) = ::std::option::Option::Some("text") { <span>{ text }</span> } }; _ = ::yew::html! { <><div/>if condition {}<div/></> }; _ = ::yew::html! { <div>if condition {}</div> }; } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/html_macro/component-pass.rs
packages/yew-macro/tests/html_macro/component-pass.rs
// Shadow primitives #[allow(non_camel_case_types)] pub struct bool; #[allow(non_camel_case_types)] pub struct char; #[allow(non_camel_case_types)] pub struct f32; #[allow(non_camel_case_types)] pub struct f64; #[allow(non_camel_case_types)] pub struct i128; #[allow(non_camel_case_types)] pub struct i16; #[allow(non_camel_case_types)] pub struct i32; #[allow(non_camel_case_types)] pub struct i64; #[allow(non_camel_case_types)] pub struct i8; #[allow(non_camel_case_types)] pub struct isize; #[allow(non_camel_case_types)] pub struct str; #[allow(non_camel_case_types)] pub struct u128; #[allow(non_camel_case_types)] pub struct u16; #[allow(non_camel_case_types)] pub struct u32; #[allow(non_camel_case_types)] pub struct u64; #[allow(non_camel_case_types)] pub struct u8; #[allow(non_camel_case_types)] pub struct usize; #[derive( ::std::clone::Clone, ::yew::Properties, ::std::default::Default, ::std::cmp::PartialEq, )] pub struct ContainerProperties { pub int: ::std::primitive::i32, #[prop_or_default] pub children: ::yew::Children, #[prop_or_default] pub header: ::yew::Html, } pub struct Container; impl ::yew::Component for Container { type Message = (); type Properties = ContainerProperties; fn create(_ctx: &::yew::Context<Self>) -> Self { ::std::unimplemented!() } fn view(&self, _ctx: &::yew::Context<Self>) -> ::yew::Html { ::std::unimplemented!() } } #[derive(::std::clone::Clone, ::implicit_clone::ImplicitClone, ::std::cmp::PartialEq)] pub enum ChildrenVariants { Child(::yew::virtual_dom::VChild<Child>), AltChild(::yew::virtual_dom::VChild<AltChild>), } impl ::std::convert::From<::yew::virtual_dom::VChild<Child>> for ChildrenVariants { fn from(comp: ::yew::virtual_dom::VChild<Child>) -> Self { ChildrenVariants::Child(comp) } } impl ::std::convert::From<::yew::virtual_dom::VChild<AltChild>> for ChildrenVariants { fn from(comp: ::yew::virtual_dom::VChild<AltChild>) -> Self { ChildrenVariants::AltChild(comp) } } impl ::std::convert::Into<::yew::virtual_dom::VNode> for ChildrenVariants { fn into(self) -> ::yew::virtual_dom::VNode { match self { Self::Child(comp) => ::yew::virtual_dom::VNode::VComp(::std::rc::Rc::new(::std::convert::Into::< ::yew::virtual_dom::VComp, >::into(comp))), Self::AltChild(comp) => ::yew::virtual_dom::VNode::VComp(::std::rc::Rc::new(::std::convert::Into::< ::yew::virtual_dom::VComp, >::into(comp))), } } } #[derive( ::std::clone::Clone, ::yew::Properties, ::std::default::Default, ::std::cmp::PartialEq, )] pub struct ChildProperties { #[prop_or_default] pub string: ::std::string::String, #[prop_or_default] pub r#fn: ::std::primitive::i32, #[prop_or_default] pub r#ref: ::yew::NodeRef, pub int: ::std::primitive::i32, #[prop_or_default] pub opt_str: ::std::option::Option<::std::string::String>, #[prop_or_default] pub vec: ::std::vec::Vec<::std::primitive::i32>, #[prop_or_default] pub optional_callback: ::std::option::Option<::yew::Callback<()>>, } pub struct Child; impl ::yew::Component for Child { type Message = (); type Properties = ChildProperties; fn create(_ctx: &::yew::Context<Self>) -> Self { ::std::unimplemented!() } fn view(&self, _ctx: &::yew::Context<Self>) -> ::yew::Html { ::std::unimplemented!() } } pub struct AltChild; impl ::yew::Component for AltChild { type Message = (); type Properties = (); fn create(_ctx: &::yew::Context<Self>) -> Self { ::std::unimplemented!() } fn view(&self, _ctx: &::yew::Context<Self>) -> ::yew::Html { ::std::unimplemented!() } } #[derive( ::std::clone::Clone, ::yew::Properties, ::std::default::Default, ::std::cmp::PartialEq, )] pub struct ChildContainerProperties { pub int: ::std::primitive::i32, #[prop_or_default] pub children: ::yew::html::ChildrenRenderer<ChildrenVariants>, } pub struct ChildContainer; impl ::yew::Component for ChildContainer { type Message = (); type Properties = ChildContainerProperties; fn create(_ctx: &::yew::Context<Self>) -> Self { ::std::unimplemented!() } fn view(&self, _ctx: &::yew::Context<Self>) -> ::yew::Html { ::std::unimplemented!() } } mod scoped { pub use super::{Child, Container}; } fn compile_pass() { _ = ::yew::html! { <Child int=1 /> }; _ = ::yew::html! { <Child int=1 r#fn=1 /> }; _ = ::yew::html! { <> <Child int=1 /> <scoped::Child int=1 /> </> }; let props = <<Child as ::yew::Component>::Properties as ::std::default::Default>::default(); let node_ref = <::yew::NodeRef as ::std::default::Default>::default(); _ = ::yew::html! { <> <Child ..::std::clone::Clone::clone(&props) /> <Child int={1} ..props /> <Child r#ref={::std::clone::Clone::clone(&node_ref)} int={2} ..::yew::props!(Child::Properties { int: 5 }) /> <Child int=3 r#ref={::std::clone::Clone::clone(&node_ref)} ..::yew::props!(Child::Properties { int: 5 }) /> <Child r#ref={::std::clone::Clone::clone(&node_ref)} ..::yew::props!(Child::Properties { int: 5 }) /> <Child r#ref={&node_ref} ..<<Child as ::yew::Component>::Properties as ::std::default::Default>::default() /> <Child r#ref={node_ref} ..<<Child as ::yew::Component>::Properties as ::std::default::Default>::default() /> </> }; _ = ::yew::html! { <> <Child int=1 string="child" /> <Child int=1 /> <Child int={1+1} /> <Child int=1 vec={::std::vec![1]} /> <Child string={<::std::string::String as ::std::convert::From<&'static ::std::primitive::str>>::from("child")} int=1 /> <Child opt_str="child" int=1 /> <Child opt_str={<::std::string::String as ::std::convert::From<&'static ::std::primitive::str>>::from("child")} int=1 /> <Child opt_str={::std::option::Option::Some("child")} int=1 /> <Child opt_str={::std::option::Option::Some(<::std::string::String as ::std::convert::From<&'static ::std::primitive::str>>::from("child"))} int=1 /> </> }; let name_expr = "child"; _ = ::yew::html! { <Child int=1 string={name_expr} /> }; let string = "child"; let int = 1; _ = ::yew::html! { <Child {int} {string} /> }; _ = ::yew::html! { <> <Child int=1 /> <Child int=1 optional_callback={::std::option::Option::Some(<::yew::Callback<()> as ::std::convert::From<_>>::from(|_| ()))} /> <Child int=1 optional_callback={<::yew::Callback<()> as ::std::convert::From<_>>::from(|_| ())} /> <Child int=1 optional_callback={::std::option::Option::None::<::yew::Callback<_>>} /> </> }; let node_ref = <::yew::NodeRef as ::std::default::Default>::default(); _ = ::yew::html! { <> <Child int=1 r#ref={node_ref} /> </> }; let int = 1; let node_ref = <::yew::NodeRef as ::std::default::Default>::default(); _ = ::yew::html! { <> <Child {int} r#ref={node_ref} /> </> }; let props = <<Container as ::yew::Component>::Properties as ::std::default::Default>::default(); let child_props = <<Child as ::yew::Component>::Properties as ::std::default::Default>::default(); _ = ::yew::html! { <> <Container int=1 /> <Container int=1></Container> <Container ..::std::clone::Clone::clone(&props)> <div>{ "hello world" }</div> </Container> <Container int=1 ..::std::clone::Clone::clone(&props)> <div>{ "hello world" }</div> </Container> <Container int=1 ..::std::clone::Clone::clone(&props)> <Child int=2 opt_str="hello" ..::std::clone::Clone::clone(&child_props) /> </Container> <Container int=1 ..::std::clone::Clone::clone(&props)> <Child int=2 vec={::std::vec![0]} ..::std::clone::Clone::clone(&child_props) /> </Container> <Container int=1 ..props> <Child int=2 string="hello" ..child_props /> </Container> <Container int=1> <Child int=2 /> </Container> <scoped::Container int=1> <scoped::Container int=2/> </scoped::Container> <Container int=1 children={::yew::html::ChildrenRenderer::new( ::std::vec![::yew::html!{ "::std::string::String" }] )} /> <Container int=1 header={::yew::html!{ <Child int=2 /> }} /> </> }; _ = ::yew::html! { <> <ChildContainer int=1 /> <ChildContainer int=1></ChildContainer> <ChildContainer int=1><Child int = 2 /></ChildContainer> <ChildContainer int=1><Child int = 2 /><Child int = 2 /></ChildContainer> </> }; _ = ::yew::html! { <ChildContainer int=1> <AltChild /> <Child int=1 /> { ::yew::html_nested! { <Child int=1 /> } } { ::std::iter::Iterator::collect::<::std::vec::Vec<_>>( ::std::iter::Iterator::map(0..2, |i| { ::yew::html_nested! { <Child int={i} /> } }) ) } </ChildContainer> }; let children = ::std::vec![ ::yew::html_nested! { <Child int=1 /> }, ::yew::html_nested! { <Child int=2 /> }, ]; _ = ::yew::html! { <ChildContainer int=1> { ::std::clone::Clone::clone(&children) } </ChildContainer> }; // https://github.com/yewstack/yew/issues/1527 _ = ::yew::html! { <ChildContainer int=1> { for children } </ChildContainer> }; let variants = || -> ::std::vec::Vec<ChildrenVariants> { ::std::vec![ ChildrenVariants::Child(::yew::virtual_dom::VChild::new( <ChildProperties as ::std::default::Default>::default(), ::std::option::Option::None, )), ChildrenVariants::AltChild(::yew::virtual_dom::VChild::new( (), ::std::option::Option::None )), ] }; _ = ::yew::html! { <> { ::std::iter::Iterator::collect::<::yew::virtual_dom::VNode>( ::std::iter::Iterator::filter( ::std::iter::IntoIterator::into_iter(variants()), |c| match c { ChildrenVariants::Child(_) => true, _ => false, } ) ) } <div> { ::std::iter::Iterator::collect::<::yew::virtual_dom::VNode>( ::std::iter::Iterator::filter( ::std::iter::IntoIterator::into_iter(variants()), |c| match c { ChildrenVariants::AltChild(_) => true, _ => false, } ) ) } </div> </> }; _ = ::yew::html_nested! { 1 }; } #[derive( ::std::clone::Clone, ::yew::Properties, ::std::default::Default, ::std::cmp::PartialEq, )] pub struct HtmlPassedAsPropProperties { pub value: ::yew::Html, } pub struct HtmlPassedAsProp; impl ::yew::Component for HtmlPassedAsProp { type Message = (); type Properties = HtmlPassedAsPropProperties; fn create(_ctx: &::yew::Context<Self>) -> Self { ::std::unimplemented!() } fn view(&self, _ctx: &::yew::Context<Self>) -> ::yew::Html { ::std::unimplemented!() } } pub struct HtmlPassedAsPropContainer; impl ::yew::Component for HtmlPassedAsPropContainer { type Message = (); type Properties = (); fn create(_ctx: &::yew::Context<Self>) -> Self { ::std::unimplemented!() } fn view(&self, _ctx: &::yew::Context<Self>) -> ::yew::Html { ::yew::html! { <> <HtmlPassedAsProp value={::yew::html!()} /> <HtmlPassedAsProp value="string literal" /> <HtmlPassedAsProp value={::std::format!("string")} /> <HtmlPassedAsProp value={::yew::AttrValue::Static("attr value")} /> </> } } } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/html_macro/html-element-pass.rs
packages/yew-macro/tests/html_macro/html-element-pass.rs
#![no_implicit_prelude] // Shadow primitives #[allow(non_camel_case_types)] pub struct bool; #[allow(non_camel_case_types)] pub struct char; #[allow(non_camel_case_types)] pub struct f32; #[allow(non_camel_case_types)] pub struct f64; #[allow(non_camel_case_types)] pub struct i128; #[allow(non_camel_case_types)] pub struct i16; #[allow(non_camel_case_types)] pub struct i32; #[allow(non_camel_case_types)] pub struct i64; #[allow(non_camel_case_types)] pub struct i8; #[allow(non_camel_case_types)] pub struct isize; #[allow(non_camel_case_types)] pub struct str; #[allow(non_camel_case_types)] pub struct u128; #[allow(non_camel_case_types)] pub struct u16; #[allow(non_camel_case_types)] pub struct u32; #[allow(non_camel_case_types)] pub struct u64; #[allow(non_camel_case_types)] pub struct u8; #[allow(non_camel_case_types)] pub struct usize; fn compile_pass() { let onclick = <::yew::Callback<::yew::events::MouseEvent> as ::std::convert::From<_>>::from( |_: ::yew::events::MouseEvent| (), ); let parent_ref = <::yew::NodeRef as ::std::default::Default>::default(); let dyn_tag = || <::std::string::String as ::std::convert::From<&::std::primitive::str>>::from("test"); let mut extra_tags_iter = ::std::iter::IntoIterator::into_iter(::std::vec!["a", "b"]); let attr_val_none: ::std::option::Option<::yew::virtual_dom::AttrValue> = ::std::option::Option::None; _ = ::yew::html! { <div> <div data-key="abc"></div> <div ref={&parent_ref}></div> <div ref={parent_ref} class="parent"> <span class="child" value="anything"></span> <label for="first-name">{"First Name"}</label> <input type="text" id="first-name" value="placeholder" /> <input type="checkbox" checked=true /> <textarea value="write a story" /> <select name="status"> <option selected=true disabled=false value="">{"Selected"}</option> <option selected=false disabled=true value="">{"Unselected"}</option> </select> <video autoplay=true controls=true /> </div> <svg width="149" height="147" viewBox="0 0 149 147" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M60.5776 13.8268L51.8673 42.6431L77.7475 37.331L60.5776 13.8268Z" fill="#DEB819"/> <path d="M108.361 94.9937L138.708 90.686L115.342 69.8642" stroke="black" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/> <g filter="url(#filter0_d)"> <circle cx="75.3326" cy="73.4918" r="55" fill="#FDD630"/> <circle cx="75.3326" cy="73.4918" r="52.5" stroke="black" stroke-width="5"/> </g> <circle cx="71" cy="99" r="5" fill="white" fill-opacity="0.75" stroke="black" stroke-width="3"/> <defs> <filter id="filter0_d" x="16.3326" y="18.4918" width="118" height="118" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"> <feGaussianBlur stdDeviation="2"/> <feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"/> </filter> </defs> </svg> <img class={::yew::classes!("avatar", "hidden")} src="http://pic.com" /> <img class="avatar hidden" /> <button onclick={&onclick} {onclick} /> <a href="http://google.com" /> <custom-tag-a> <custom-tag-b /> </custom-tag-a> <@{dyn_tag()}> <@{::std::iter::Iterator::next(&mut extra_tags_iter).unwrap()} class="extra-a"/> <@{::std::iter::Iterator::next(&mut extra_tags_iter).unwrap()} class="extra-b"/> </@> <@{ if dyn_tag() == "test" { "div" } else { "a" } }/> <a href={::std::option::Option::Some(::yew::virtual_dom::AttrValue::Static("http://google.com"))} media={::std::clone::Clone::clone(&attr_val_none)} /> <track kind={::std::option::Option::Some(::yew::virtual_dom::AttrValue::Static("subtitles"))} src={::std::clone::Clone::clone(&attr_val_none)} /> <track kind={::std::option::Option::Some(::yew::virtual_dom::AttrValue::Static("5"))} mixed="works" /> <input value={::std::option::Option::Some(::yew::virtual_dom::AttrValue::Static("value"))} onblur={::std::option::Option::Some(<::yew::Callback<::yew::FocusEvent> as ::std::convert::From<_>>::from(|_| ()))} /> </div> }; let children = ::std::vec![ ::yew::html! { <span>{ "Hello" }</span> }, ::yew::html! { <span>{ "World" }</span> }, ]; _ = ::yew::html! { <div>{children}</div> }; // handle misleading angle brackets _ = ::yew::html! { <div data-val={<::std::string::String as ::std::default::Default>::default()}></div> }; _ = ::yew::html! { <div><a data-val={<::std::string::String as ::std::default::Default>::default()} /></div> }; // test for https://github.com/yewstack/yew/issues/2810 _ = ::yew::html! { <div data-type="date" data-as="calender" /> }; let option_vnode = ::std::option::Option::Some(::yew::html! {}); _ = ::yew::html! { <div>{option_vnode}</div> }; } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/html_macro/generic-component-fail.rs
packages/yew-macro/tests/html_macro/generic-component-fail.rs
use std::marker::PhantomData; use yew::prelude::*; pub struct Generic<T> { marker: PhantomData<T>, } impl<T> Component for Generic<T> where T: 'static, { type Message = (); type Properties = (); fn create(_ctx: &Context<Self>) -> Self { unimplemented!() } fn view(&self, _ctx: &Context<Self>) -> Html { unimplemented!() } } pub struct Generic2<T1, T2> { marker: PhantomData<(T1, T2)>, } impl<T1, T2> Component for Generic2<T1, T2> where T1: 'static, T2: 'static, { type Message = (); type Properties = (); fn create(_ctx: &Context<Self>) -> Self { unimplemented!() } fn view(&self, _ctx: &Context<Self>) -> Html { unimplemented!() }} fn compile_fail() { #[allow(unused_imports)] use std::path::Path; html! { <Generic<String>> }; html! { <Generic<String>></Generic> }; html! { <Generic<String>></Generic<Vec<String>>> }; html! { <Generic<String>></Generic<Path>> }; html! { <Generic<String>></> }; } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/html_macro/as-return-value-pass.rs
packages/yew-macro/tests/html_macro/as-return-value-pass.rs
#![no_implicit_prelude] // Shadow primitives #[allow(non_camel_case_types)] pub struct bool; #[allow(non_camel_case_types)] pub struct char; #[allow(non_camel_case_types)] pub struct f32; #[allow(non_camel_case_types)] pub struct f64; #[allow(non_camel_case_types)] pub struct i128; #[allow(non_camel_case_types)] pub struct i16; #[allow(non_camel_case_types)] pub struct i32; #[allow(non_camel_case_types)] pub struct i64; #[allow(non_camel_case_types)] pub struct i8; #[allow(non_camel_case_types)] pub struct isize; #[allow(non_camel_case_types)] pub struct str; #[allow(non_camel_case_types)] pub struct u128; #[allow(non_camel_case_types)] pub struct u16; #[allow(non_camel_case_types)] pub struct u32; #[allow(non_camel_case_types)] pub struct u64; #[allow(non_camel_case_types)] pub struct u8; #[allow(non_camel_case_types)] pub struct usize; pub struct MyComponent; impl ::yew::Component for MyComponent { type Message = (); type Properties = (); fn create(_ctx: &::yew::Context<Self>) -> Self { ::std::unimplemented!() } fn view(&self, _ctx: &::yew::Context<Self>) -> ::yew::Html { ::std::unimplemented!() } } // can test "unused braces" warning inside the macro // https://github.com/yewstack/yew/issues/2157 fn make_my_component()-> ::yew::virtual_dom::VChild<MyComponent>{ ::yew::html_nested!{<MyComponent/>} } // can test "unused braces" warning inside the macro // https://github.com/yewstack/yew/issues/2157 fn make_my_component_html()-> ::yew::Html{ ::yew::html!{<MyComponent/>} } fn main(){}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/html_macro/missing-props-diagnostics-fail.rs
packages/yew-macro/tests/html_macro/missing-props-diagnostics-fail.rs
use yew::prelude::*; #[component] pub fn App() -> Html { html! { <Foo /> } } #[component] pub fn App1() -> Html { html! { <Foo bar={"bar".to_string()} /> } } #[component] pub fn App2() -> Html { html! { <Foo bar={"bar".to_string()} baz={42} /> } } #[derive(Properties, PartialEq, Clone)] pub struct FooProps { pub bar: String, pub baz: u32, } #[component] pub fn Foo(_props: &FooProps) -> Html { html! {} } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/html_macro/element-fail.rs
packages/yew-macro/tests/html_macro/element-fail.rs
use yew::prelude::*; struct NotToString; fn compile_fail() { // missing closing tag html! { <div> }; html! { <div><div> }; html! { <div><div></div> }; // missing opening tag html! { </div> }; html! { <div></span></div> }; html! { <img /></img> }; // tag mismatch html! { <div></span> }; html! { <tag-a></tag-b> }; // multiple root html! { <div></div><div></div> }; // invalid child content html! { <div>Invalid</div> }; // same attribute specified multiple times (tests for attributes with special treatment) html! { <input attr=1 attr=2 /> }; html! { <input value="123" value="456" /> }; html! { <input kind="checkbox" kind="submit" /> }; html! { <input checked=true checked=false /> }; html! { <input disabled=true disabled=false /> }; html! { <option selected=true selected=false /> }; html! { <div class="first" class="second" /> }; html! { <input ref={()} ref={()} /> }; // boolean attribute type mismatch html! { <input checked=1 /> }; html! { <input checked={Some(false)} /> }; html! { <input disabled=1 /> }; html! { <input disabled={Some(true)} /> }; html! { <option selected=1 /> }; // normal attribute type mismatch html! { <input type={()} /> }; html! { <input value={()} /> }; html! { <a href={()} /> }; html! { <input string={NotToString} /> }; html! { <a media={Some(NotToString)} /> }; html! { <a href={Some(5)} /> }; // listener type mismatch html! { <input onclick=1 /> }; html! { <input onclick={Callback::from(|a: String| ())} /> }; html! { <input onfocus={Some(5)} /> }; // NodeRef type mismatch html! { <input ref={()} /> }; html! { <input ref={Some(NodeRef::default())} /> }; html! { <input onclick={Callback::from(|a: String| ())} /> }; html! { <input string={NotToString} /> }; html! { <input ref={()} /> }; html! { <input ref={()} ref={()} /> }; // void element with children html! { <input type="text"></input> }; // <textarea> should have a custom error message explaining how to set its default value html! { <textarea>{"default value"}</textarea> } // make sure that capitalization doesn't matter for the void children check html! { <iNpUt type="text"></iNpUt> }; // no tag name html! { <@></@> }; html! { <@/> }; // invalid closing tag html! { <@{"test"}></@{"test"}> }; // type mismatch html! { <@{55}></@> }; // Missing curly braces html! { <input ref=() /> }; html! { <input ref=() ref=() /> }; html! { <input onfocus=Some(5) /> }; html! { <input string=NotToString /> }; html! { <a media=Some(NotToString) /> }; html! { <a href=Some(5) /> }; html! { <input type=() /> }; html! { <input value=() /> }; html! { <input string=NotToString /> }; } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/html_macro/for-fail.rs
packages/yew-macro/tests/html_macro/for-fail.rs
mod smth { const KEY: u32 = 42; } fn main() { _ = ::yew::html!{for x}; _ = ::yew::html!{for x in}; _ = ::yew::html!{for x in 0 .. 10}; _ = ::yew::html!{for (x, y) in 0 .. 10 { <span>{x}</span> }}; _ = ::yew::html!{for _ in 0 .. 10 { <span>{break}</span> }}; _ = ::yew::html!{for _ in 0 .. 10 { <div key="duplicate" /> }}; _ = ::yew::html!{for _ in 0 .. 10 { <div key={smth::KEY} /> }}; }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/html_macro/block-pass.rs
packages/yew-macro/tests/html_macro/block-pass.rs
#![no_implicit_prelude] // Shadow primitives #[allow(non_camel_case_types)] pub struct bool; #[allow(non_camel_case_types)] pub struct char; #[allow(non_camel_case_types)] pub struct f32; #[allow(non_camel_case_types)] pub struct f64; #[allow(non_camel_case_types)] pub struct i128; #[allow(non_camel_case_types)] pub struct i16; #[allow(non_camel_case_types)] pub struct i32; #[allow(non_camel_case_types)] pub struct i64; #[allow(non_camel_case_types)] pub struct i8; #[allow(non_camel_case_types)] pub struct isize; #[allow(non_camel_case_types)] pub struct str; #[allow(non_camel_case_types)] pub struct u128; #[allow(non_camel_case_types)] pub struct u16; #[allow(non_camel_case_types)] pub struct u32; #[allow(non_camel_case_types)] pub struct u64; #[allow(non_camel_case_types)] pub struct u8; #[allow(non_camel_case_types)] pub struct usize; fn main() { _ = ::yew::html! { <>{ "Hi" }</> }; _ = ::yew::html! { <>{ ::std::format!("Hello") }</> }; _ = ::yew::html! { <>{ ::std::string::ToString::to_string("Hello") }</> }; let msg = "Hello"; _ = ::yew::html! { <div>{ msg }</div> }; let subview = ::yew::html! { "subview!" }; _ = ::yew::html! { <div>{ subview }</div> }; let subview = || ::yew::html! { "subview!" }; _ = ::yew::html! { <div>{ subview() }</div> }; _ = ::yew::html! { <ul> { for ::std::iter::Iterator::map(0..3, |num| { ::yew::html! { <span>{ num }</span> }}) } </ul> }; let item = |num| ::yew::html! { <li>{ ::std::format!("item {}!", num) }</li> }; _ = ::yew::html! { <ul> { for ::std::iter::Iterator::map(0..3, item) } </ul> }; }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/html_macro/node-fail.rs
packages/yew-macro/tests/html_macro/node-fail.rs
use yew::prelude::*; fn compile_fail() { html! { "valid" "invalid" }; html! { <span>{ "valid" "invalid" }</span> }; html! { () }; html! { invalid }; // unsupported literals html! { b'a' }; html! { b"str" }; html! { <span>{ b'a' }</span> }; html! { <span>{ b"str" }</span> }; let not_node = || (); html! { not_node() }; } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/hook_macro/use_transitive_state-fail.rs
packages/yew-macro/tests/hook_macro/use_transitive_state-fail.rs
use yew::prelude::*; use yew_macro::{use_transitive_state_with_closure, use_transitive_state_without_closure}; #[component] fn Comp() -> HtmlResult { use_transitive_state_with_closure!(123)?; use_transitive_state_with_closure!(|_| { todo!() }, 123)?; use_transitive_state_with_closure!(123, |_| { todo!() })?; use_transitive_state_with_closure!(|_| -> u32 { todo!() })?; use_transitive_state_with_closure!(|_| -> u32 { todo!() }, 123)?; Ok(Html::default()) } #[component] fn Comp2() -> HtmlResult { use_transitive_state_without_closure!(123)?; use_transitive_state_without_closure!(|_| { todo!() }, 123)?; use_transitive_state_without_closure!(123, |_| { todo!() })?; use_transitive_state_without_closure!(|_| -> u32 { todo!() })?; use_transitive_state_without_closure!(|_| -> u32 { todo!() }, 123)?; Ok(Html::default()) } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/hook_macro/use_prepared_state-fail.rs
packages/yew-macro/tests/hook_macro/use_prepared_state-fail.rs
use yew::prelude::*; use yew_macro::{use_prepared_state_with_closure, use_prepared_state_without_closure}; #[component] fn Comp() -> HtmlResult { use_prepared_state_with_closure!(123)?; use_prepared_state_with_closure!(123, |_| { todo!() })?; use_prepared_state_with_closure!(|_| -> u32 { todo!() })?; use_prepared_state_with_closure!(|_| -> u32 { todo!() }, 123)?; use_prepared_state_with_closure!(async |_| -> u32 { todo!() })?; use_prepared_state_with_closure!(|_| { todo!() }, 123)?; Ok(Html::default()) } #[component] fn Comp2() -> HtmlResult { use_prepared_state_without_closure!(123)?; use_prepared_state_without_closure!(123, |_| { todo!() })?; use_prepared_state_without_closure!(|_| { todo!() }, 123)?; use_prepared_state_without_closure!(|_| -> u32 { todo!() })?; use_prepared_state_without_closure!(|_| -> u32 { todo!() }, 123)?; use_prepared_state_without_closure!(async |_| -> u32 { todo!() })?; Ok(Html::default()) } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-router/src/router.rs
packages/yew-router/src/router.rs
//! Router Component. use std::borrow::Cow; use std::rc::Rc; use gloo::history::query::Raw; 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}; /// Props for [`Router`]. #[derive(Properties, PartialEq, Clone)] pub struct RouterProps { #[prop_or_default] pub children: Html, pub history: AnyHistory, #[prop_or_default] pub basename: Option<AttrValue>, } #[derive(Clone)] pub(crate) struct LocationContext { location: Location, // Counter to force update. ctr: u32, } impl LocationContext { pub fn location(&self) -> Location { self.location.clone() } } impl PartialEq for LocationContext { fn eq(&self, rhs: &Self) -> bool { self.ctr == rhs.ctr } } impl Reducible for LocationContext { type Action = Location; fn reduce(self: Rc<Self>, action: Self::Action) -> Rc<Self> { Self { location: action, ctr: self.ctr + 1, } .into() } } #[derive(Clone, PartialEq)] pub(crate) struct NavigatorContext { navigator: Navigator, } impl NavigatorContext { pub fn navigator(&self) -> Navigator { self.navigator.clone() } } /// The base router. /// /// The implementation is separated to make sure <Router /> has the same virtual dom layout as /// the <BrowserRouter /> and <HashRouter />. #[component(BaseRouter)] fn base_router(props: &RouterProps) -> Html { let RouterProps { history, children, basename, } = props.clone(); let basename = basename.map(|m| strip_slash_suffix(&m).to_owned()); let navigator = Navigator::new(history.clone(), basename.clone()); let old_basename = use_mut_ref(|| Option::<String>::None); let mut old_basename = old_basename.borrow_mut(); if basename != *old_basename { // If `old_basename` is `Some`, path is probably prefixed with `old_basename`. // If `old_basename` is `None`, path may or may not be prefixed with the new `basename`, // depending on whether this is the first render. let old_navigator = Navigator::new( history.clone(), old_basename.as_ref().or(basename.as_ref()).cloned(), ); old_basename.clone_from(&basename); let location = history.location(); let stripped = old_navigator.strip_basename(Cow::from(location.path())); let prefixed = navigator.prefix_basename(&stripped); if prefixed != location.path() { history .replace_with_query(prefixed, Raw(location.query_str())) .unwrap_or_else(|never| match never {}); } else { // Reaching here is possible if the page loads with the correct path, including the // initial basename. In that case, the new basename would be stripped and then // prefixed right back. While replacing the history would probably be harmless, // we might as well avoid doing it. } } let navi_ctx = NavigatorContext { navigator }; let loc_ctx = use_reducer(|| LocationContext { location: history.location(), ctr: 0, }); { let loc_ctx_dispatcher = loc_ctx.dispatcher(); use_effect_with(history, move |history| { let history = history.clone(); // Force location update when history changes. loc_ctx_dispatcher.dispatch(history.location()); let history_cb = { let history = history.clone(); move || loc_ctx_dispatcher.dispatch(history.location()) }; let listener = history.listen(history_cb); // We hold the listener in the destructor. move || { std::mem::drop(listener); } }); } html! { <ContextProvider<NavigatorContext> context={navi_ctx}> <ContextProvider<LocationContext> context={(*loc_ctx).clone()}> {children} </ContextProvider<LocationContext>> </ContextProvider<NavigatorContext>> } } /// The Router component. /// /// This provides location and navigator context to its children and switches. /// /// If you are building a web application, you may want to consider using [`BrowserRouter`] instead. /// /// You only need one `<Router />` for each application. #[component(Router)] pub fn router(props: &RouterProps) -> Html { html! { <BaseRouter ..{props.clone()} /> } } /// Props for [`BrowserRouter`] and [`HashRouter`]. #[derive(Properties, PartialEq, Clone)] pub struct ConcreteRouterProps { pub children: Html, #[prop_or_default] pub basename: Option<AttrValue>, } /// A [`Router`] that provides location information and navigator via [`BrowserHistory`]. /// /// This Router uses browser's native history to manipulate session history /// and uses regular URL as route. /// /// # Note /// /// The router will by default use the value declared in `<base href="..." />` as its basename. /// You may also specify a different basename with props. #[component(BrowserRouter)] pub fn browser_router(props: &ConcreteRouterProps) -> Html { let ConcreteRouterProps { children, basename } = props.clone(); let history = use_state(|| AnyHistory::from(BrowserHistory::new())); // We acknowledge based in `<base href="..." />` let basename = basename.map(|m| m.to_string()).or_else(base_url); html! { <BaseRouter history={(*history).clone()} {basename}> {children} </BaseRouter> } } /// A [`Router`] that provides location information and navigator via [`HashHistory`]. /// /// This Router uses browser's native history to manipulate session history /// and stores route in hash fragment. /// /// # Warning /// /// Prefer [`BrowserRouter`] whenever possible and use this as a last resort. #[component(HashRouter)] pub fn hash_router(props: &ConcreteRouterProps) -> Html { let ConcreteRouterProps { children, basename } = props.clone(); let history = use_state(|| AnyHistory::from(HashHistory::new())); html! { <BaseRouter history={(*history).clone()} {basename}> {children} </BaseRouter> } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-router/src/lib.rs
packages/yew-router/src/lib.rs
//! Provides routing faculties using the browser history API to build //! Single Page Applications (SPAs) using [Yew web framework](https://yew.rs). //! //! # Usage //! //! ```rust //! use yew::functional::*; //! use yew::prelude::*; //! use yew_router::prelude::*; //! //! #[derive(Debug, Clone, Copy, PartialEq, Routable)] //! enum Route { //! #[at("/")] //! Home, //! #[at("/secure")] //! Secure, //! #[not_found] //! #[at("/404")] //! NotFound, //! } //! //! #[component(Secure)] //! fn secure() -> Html { //! let navigator = use_navigator().unwrap(); //! //! let onclick_callback = Callback::from(move |_| navigator.push(&Route::Home)); //! html! { //! <div> //! <h1>{ "Secure" }</h1> //! <button onclick={onclick_callback}>{ "Go Home" }</button> //! </div> //! } //! } //! //! #[component(Main)] //! fn app() -> Html { //! html! { //! <BrowserRouter> //! <Switch<Route> render={switch} /> //! </BrowserRouter> //! } //! } //! //! fn switch(routes: Route) -> Html { //! match routes { //! Route::Home => html! { <h1>{ "Home" }</h1> }, //! Route::Secure => html! { //! <Secure /> //! }, //! Route::NotFound => html! { <h1>{ "404" }</h1> }, //! } //! } //! ``` //! //! # Internals //! //! The router registers itself as a context provider and makes location information and navigator //! available via [`hooks`] or [`RouterScopeExt`](scope_ext::RouterScopeExt). //! //! # State //! //! The [`Location`](gloo::history::Location) API has a way to access / store state associated with //! session history. Please consult [`location.state()`](crate::history::Location::state) for //! detailed usage. extern crate self as yew_router; #[doc(hidden)] #[path = "macro_helpers.rs"] pub mod __macro; pub mod components; pub mod hooks; pub mod navigator; mod routable; pub mod router; pub mod scope_ext; pub mod switch; pub mod utils; pub use routable::{AnyRoute, Routable}; pub use router::{BrowserRouter, HashRouter, Router}; pub use switch::Switch; pub mod history { //! A module that provides universal session history and location information. pub use gloo::history::{ AnyHistory, BrowserHistory, HashHistory, History, HistoryError, HistoryResult, Location, MemoryHistory, }; } pub mod query { //! A module that provides custom query serialization & deserialization. pub use gloo::history::query::{FromQuery, Raw, ToQuery}; } pub mod prelude { //! Prelude module to be imported when working with `yew-router`. //! //! This module re-exports the frequently used types from the crate. pub use crate::components::{Link, Redirect}; pub use crate::history::Location; pub use crate::hooks::*; pub use crate::navigator::{NavigationError, NavigationResult, Navigator}; pub use crate::scope_ext::{LocationHandle, NavigatorHandle, RouterScopeExt}; #[doc(no_inline)] pub use crate::Routable; pub use crate::{BrowserRouter, HashRouter, Router, Switch}; }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-router/src/navigator.rs
packages/yew-router/src/navigator.rs
use std::borrow::Cow; use crate::history::{AnyHistory, History, HistoryError, HistoryResult}; use crate::query::ToQuery; use crate::routable::Routable; pub type NavigationError = HistoryError; pub type NavigationResult<T> = HistoryResult<T>; /// The kind of Navigator Provider. #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum NavigatorKind { /// Browser History. Browser, /// Hash History. Hash, /// Memory History. Memory, } /// A struct to navigate between locations. #[derive(Debug, PartialEq, Clone)] pub struct Navigator { inner: AnyHistory, basename: Option<String>, } impl Navigator { pub(crate) fn new(history: AnyHistory, basename: Option<String>) -> Self { Self { inner: history, basename, } } /// Returns basename of current navigator. pub fn basename(&self) -> Option<&str> { self.basename.as_deref() } /// Navigate back 1 page. pub fn back(&self) { self.go(-1); } /// Navigate forward 1 page. pub fn forward(&self) { self.go(1); } /// Navigate to a specific page with a `delta` relative to current page. /// /// See: <https://developer.mozilla.org/en-US/docs/Web/API/History/go> pub fn go(&self, delta: isize) { self.inner.go(delta); } /// Pushes a [`Routable`] entry. pub fn push<R>(&self, route: &R) where R: Routable, { self.inner.push(self.prefix_basename(&route.to_path())); } /// Replaces the current history entry with provided [`Routable`] and [`None`] state. pub fn replace<R>(&self, route: &R) where R: Routable, { self.inner.replace(self.prefix_basename(&route.to_path())); } /// Pushes a [`Routable`] entry with state. pub fn push_with_state<R, T>(&self, route: &R, state: T) where R: Routable, T: 'static, { self.inner .push_with_state(self.prefix_basename(&route.to_path()), state); } /// Replaces the current history entry with provided [`Routable`] and state. pub fn replace_with_state<R, T>(&self, route: &R, state: T) where R: Routable, T: 'static, { self.inner .replace_with_state(self.prefix_basename(&route.to_path()), state); } /// Same as `.push()` but affix the queries to the end of the route. pub fn push_with_query<R, Q>(&self, route: &R, query: Q) -> Result<(), Q::Error> where R: Routable, Q: ToQuery, { self.inner .push_with_query(self.prefix_basename(&route.to_path()), query) } /// Same as `.replace()` but affix the queries to the end of the route. pub fn replace_with_query<R, Q>(&self, route: &R, query: Q) -> Result<(), Q::Error> where R: Routable, Q: ToQuery, { self.inner .replace_with_query(self.prefix_basename(&route.to_path()), query) } /// Same as `.push_with_state()` but affix the queries to the end of the route. pub fn push_with_query_and_state<R, Q, T>( &self, route: &R, query: Q, state: T, ) -> Result<(), Q::Error> where R: Routable, Q: ToQuery, T: 'static, { self.inner .push_with_query_and_state(self.prefix_basename(&route.to_path()), query, state) } /// Same as `.replace_with_state()` but affix the queries to the end of the route. pub fn replace_with_query_and_state<R, Q, T>( &self, route: &R, query: Q, state: T, ) -> Result<(), Q::Error> where R: Routable, Q: ToQuery, T: 'static, { self.inner.replace_with_query_and_state( self.prefix_basename(&route.to_path()), query, state, ) } /// Returns the Navigator kind. pub fn kind(&self) -> NavigatorKind { match &self.inner { AnyHistory::Browser(_) => NavigatorKind::Browser, AnyHistory::Hash(_) => NavigatorKind::Hash, AnyHistory::Memory(_) => NavigatorKind::Memory, } } pub(crate) fn prefix_basename<'a>(&self, route_s: &'a str) -> Cow<'a, str> { match self.basename() { Some(base) => { if base.is_empty() && route_s.is_empty() { Cow::from("/") } else { Cow::from(format!("{base}{route_s}")) } } None => route_s.into(), } } pub(crate) fn strip_basename<'a>(&self, path: Cow<'a, str>) -> Cow<'a, str> { match self.basename() { Some(m) => { let mut path = path .strip_prefix(m) .map(|m| Cow::from(m.to_owned())) .unwrap_or(path); if !path.starts_with('/') { path = format!("/{m}").into(); } path } None => path, } } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-router/src/routable.rs
packages/yew-router/src/routable.rs
use std::collections::HashMap; pub use yew_router_macro::Routable; /// Marks an `enum` as routable. /// /// # Implementation /// /// Use derive macro to implement it. Although it *is* possible to implement it manually, /// it is discouraged. /// /// # Usage /// /// The functions exposed by this trait are **not** supposed to be consumed directly. Instead use /// the functions exposed at the [crate's root][crate] to perform operations with the router. pub trait Routable: Clone + PartialEq { /// Converts path to an instance of the routes enum. fn from_path(path: &str, params: &HashMap<&str, &str>) -> Option<Self>; /// Converts the route to a string that can passed to the history API. fn to_path(&self) -> String; /// Lists all the available routes fn routes() -> Vec<&'static str>; /// The route to redirect to on 404 fn not_found_route() -> Option<Self>; /// Match a route based on the path fn recognize(pathname: &str) -> Option<Self>; } /// 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. #[derive(Debug, Clone, PartialEq, Eq)] pub struct AnyRoute { path: String, } impl Routable for AnyRoute { fn from_path(path: &str, params: &HashMap<&str, &str>) -> Option<Self> { // No params allowed. if params.is_empty() { Some(Self { path: path.to_string(), }) } else { None } } fn to_path(&self) -> String { self.path.to_string() } fn routes() -> Vec<&'static str> { vec!["/*path"] } fn not_found_route() -> Option<Self> { Some(Self { path: "/404".to_string(), }) } fn recognize(pathname: &str) -> Option<Self> { Some(Self { path: pathname.to_string(), }) } } impl AnyRoute { pub fn new<S: Into<String>>(pathname: S) -> Self { Self { path: pathname.into(), } } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-router/src/utils.rs
packages/yew-router/src/utils.rs
use std::cell::RefCell; use wasm_bindgen::JsCast; pub(crate) fn strip_slash_suffix(path: &str) -> &str { path.strip_suffix('/').unwrap_or(path) } static BASE_URL_LOADED: std::sync::Once = std::sync::Once::new(); thread_local! { static BASE_URL: RefCell<Option<String>> = const { 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. pub fn base_url() -> Option<String> { BASE_URL_LOADED.call_once(|| { BASE_URL.with(|val| { *val.borrow_mut() = fetch_base_url(); }) }); BASE_URL.with(|it| it.borrow().as_ref().map(|it| it.to_string())) } pub fn fetch_base_url() -> Option<String> { match gloo::utils::document().query_selector("base[href]") { Ok(Some(base)) => { let base = base.unchecked_into::<web_sys::HtmlBaseElement>().href(); let url = web_sys::Url::new(&base).unwrap(); let base = url.pathname(); let base = if base != "/" { strip_slash_suffix(&base) } else { return None; }; Some(base.to_string()) } _ => None, } } #[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))] pub fn compose_path(pathname: &str, query: &str) -> Option<String> { gloo::utils::window() .location() .href() .ok() .and_then(|base| web_sys::Url::new_with_base(pathname, &base).ok()) .map(|url| { url.set_search(query); format!("{}{}", url.pathname(), url.search()) }) } #[cfg(any(not(target_arch = "wasm32"), target_os = "wasi"))] pub fn compose_path(pathname: &str, query: &str) -> Option<String> { let query = query.trim(); if !query.is_empty() { Some(format!("{pathname}?{query}")) } else { Some(pathname.to_owned()) } } // TODO: remove the cfg after wasm-bindgen-test stops emitting the function unconditionally #[cfg(all( test, target_arch = "wasm32", any(target_os = "unknown", target_os = "none") ))] mod tests { use gloo::utils::document; use wasm_bindgen_test::wasm_bindgen_test as test; use yew_router::prelude::*; use yew_router::utils::*; wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser); #[derive(Debug, Clone, Copy, PartialEq, Routable)] enum Routes { #[at("/")] Home, #[at("/no")] No, #[at("/404")] NotFound, } #[test] fn test_base_url() { document().head().unwrap().set_inner_html(r#""#); assert_eq!(fetch_base_url(), None); document() .head() .unwrap() .set_inner_html(r#"<base href="/base/">"#); assert_eq!(fetch_base_url(), Some("/base".to_string())); document() .head() .unwrap() .set_inner_html(r#"<base href="/base">"#); assert_eq!(fetch_base_url(), Some("/base".to_string())); } #[test] fn test_compose_path() { assert_eq!(compose_path("/home", ""), Some("/home".to_string())); assert_eq!( compose_path("/path/to", "foo=bar"), Some("/path/to?foo=bar".to_string()) ); assert_eq!( compose_path("/events", "from=2019&to=2021"), Some("/events?from=2019&to=2021".to_string()) ); } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-router/src/hooks.rs
packages/yew-router/src/hooks.rs
//! 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}; /// A hook to access the [`Navigator`]. #[hook] pub fn use_navigator() -> Option<Navigator> { use_context::<NavigatorContext>().map(|m| m.navigator()) } /// A hook to access the current [`Location`]. #[hook] pub fn use_location() -> Option<Location> { Some(use_context::<LocationContext>()?.location()) } /// A hook to access the current route. /// /// This hook will return [`None`] if there's no available location or none of the routes match. /// /// # Note /// /// If your `Routable` has a `#[not_found]` route, you can use `.unwrap_or_default()` instead of /// `.unwrap()` to unwrap. #[hook] pub fn use_route<R>() -> Option<R> where R: Routable + 'static, { let navigator = use_navigator()?; let location = use_location()?; let path = navigator.strip_basename(location.path().into()); R::recognize(&path) }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-router/src/scope_ext.rs
packages/yew-router/src/scope_ext.rs
use yew::context::ContextHandle; use yew::prelude::*; use crate::history::Location; use crate::navigator::Navigator; use crate::routable::Routable; use crate::router::{LocationContext, NavigatorContext}; /// A [`ContextHandle`] for [`add_location_listener`](RouterScopeExt::add_location_listener). pub struct LocationHandle { _inner: ContextHandle<LocationContext>, } /// A [`ContextHandle`] for [`add_navigator_listener`](RouterScopeExt::add_navigator_listener). pub struct NavigatorHandle { _inner: ContextHandle<NavigatorContext>, } /// An extension to [`Scope`](yew::html::Scope) that provides location information and navigator /// access. /// /// You can access them on `ctx.link()` /// /// # Example /// /// Below is an example of the implementation of the [`Link`](crate::components::Link) component. /// /// ``` /// # use std::marker::PhantomData; /// # use wasm_bindgen::UnwrapThrowExt; /// # use yew::prelude::*; /// # use yew_router::prelude::*; /// # use yew_router::components::LinkProps; /// # /// # pub struct Link<R: Routable + 'static> { /// # _data: PhantomData<R>, /// # } /// # /// # pub enum Msg { /// # OnClick, /// # } /// # /// impl<R: Routable + 'static> Component for Link<R> { /// type Message = Msg; /// type Properties = LinkProps<R>; /// /// fn create(_ctx: &Context<Self>) -> Self { /// Self { _data: PhantomData } /// } /// /// fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool { /// match msg { /// Msg::OnClick => { /// ctx.link() /// .navigator() /// .expect_throw("failed to get navigator.") /// .push(&ctx.props().to); /// false /// } /// } /// } /// /// fn view(&self, ctx: &Context<Self>) -> Html { /// html! { /// <a class={ctx.props().classes.clone()} /// href={ctx.props().to.to_path()} /// onclick={ctx.link().callback(|e: MouseEvent| { /// e.prevent_default(); /// Msg::OnClick /// })} /// > /// { ctx.props().children.clone() } /// </a> /// } /// } /// } /// ``` pub trait RouterScopeExt { /// Returns current [`Navigator`]. fn navigator(&self) -> Option<Navigator>; /// Returns current [`Location`]. fn location(&self) -> Option<Location>; /// Returns current route. fn route<R>(&self) -> Option<R> where R: Routable + 'static; /// Adds a listener that gets notified when location changes. /// /// # Note /// /// [`LocationHandle`] works like a normal [`ContextHandle`] and it unregisters the callback /// when the handle is dropped. You need to keep the handle for as long as you need the /// callback. fn add_location_listener(&self, cb: Callback<Location>) -> Option<LocationHandle>; /// Adds a listener that gets notified when navigator changes. /// /// # Note /// /// [`NavigatorHandle`] works like a normal [`ContextHandle`] and it unregisters the callback /// when the handle is dropped. You need to keep the handle for as long as you need the /// callback. fn add_navigator_listener(&self, cb: Callback<Navigator>) -> Option<NavigatorHandle>; } impl<COMP: Component> RouterScopeExt for yew::html::Scope<COMP> { fn navigator(&self) -> Option<Navigator> { self.context::<NavigatorContext>(Callback::from(|_| {})) .map(|(m, _)| m.navigator()) } fn location(&self) -> Option<Location> { self.context::<LocationContext>(Callback::from(|_| {})) .map(|(m, _)| m.location()) } fn route<R>(&self) -> Option<R> where R: Routable + 'static, { let navigator = self.navigator()?; let location = self.location()?; let path = navigator.strip_basename(location.path().into()); R::recognize(&path) } fn add_location_listener(&self, cb: Callback<Location>) -> Option<LocationHandle> { self.context::<LocationContext>(Callback::from(move |m: LocationContext| { cb.emit(m.location()) })) .map(|(_, m)| LocationHandle { _inner: m }) } fn add_navigator_listener(&self, cb: Callback<Navigator>) -> Option<NavigatorHandle> { self.context::<NavigatorContext>(Callback::from(move |m: NavigatorContext| { cb.emit(m.navigator()) })) .map(|(_, m)| NavigatorHandle { _inner: m }) } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-router/src/switch.rs
packages/yew-router/src/switch.rs
//! The [`Switch`] Component. use yew::prelude::*; use crate::prelude::*; /// Props for [`Switch`] #[derive(Properties, PartialEq, Clone)] pub struct SwitchProps<R> where R: Routable, { /// Callback which returns [`Html`] to be rendered for the current route. pub render: Callback<R, Html>, #[prop_or_default] pub pathname: Option<String>, } /// A Switch that dispatches route among variants of a [`Routable`]. /// /// When a route can't be matched, including when the path is matched but the deserialization fails, /// it looks for the route with `not_found` attribute. /// If such a route is provided, it redirects to the specified route. /// Otherwise `html! {}` is rendered and a message is logged to console /// stating that no route can be matched. /// See the [crate level document][crate] for more information. #[component] pub fn Switch<R>(props: &SwitchProps<R>) -> Html where R: Routable + 'static, { let route = use_route::<R>(); let route = props .pathname .as_ref() .and_then(|p| R::recognize(p)) .or(route); match route { Some(route) => props.render.emit(route), None => { tracing::warn!("no route matched"); Html::default() } } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-router/src/macro_helpers.rs
packages/yew-router/src/macro_helpers.rs
pub use urlencoding::{decode as decode_for_url, encode as encode_for_url}; use crate::utils::strip_slash_suffix; use crate::Routable; // re-export Router because the macro needs to access it pub type Router = route_recognizer::Router<String>; /// Build a `route_recognizer::Router` from a `Routable` type. pub fn build_router<R: Routable>() -> Router { let mut router = Router::new(); R::routes().iter().for_each(|path| { let stripped_route = strip_slash_suffix(path); router.add(stripped_route, path.to_string()); }); router } /// Use a `route_recognizer::Router` to build the route of a `Routable` pub fn recognize_with_router<R: Routable>(router: &Router, pathname: &str) -> Option<R> { let pathname = strip_slash_suffix(pathname); let matched = router.recognize(pathname); match matched { Ok(matched) => R::from_path(matched.handler(), &matched.params().into_iter().collect()) .or_else(R::not_found_route), Err(_) => R::not_found_route(), } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-router/src/components/link.rs
packages/yew-router/src/components/link.rs
use serde::Serialize; use wasm_bindgen::UnwrapThrowExt; use yew::prelude::*; use yew::virtual_dom::AttrValue; use crate::navigator::NavigatorKind; use crate::prelude::*; use crate::{utils, Routable}; /// Props for [`Link`] #[derive(Properties, Clone, PartialEq)] pub struct LinkProps<R, Q = (), S = ()> where R: Routable, Q: Clone + PartialEq + Serialize, S: Clone + PartialEq, { /// CSS classes to add to the anchor element (optional). #[prop_or_default] pub classes: Classes, /// Route that will be pushed when the anchor is clicked. pub to: R, /// Route query data #[prop_or_default] pub query: Option<Q>, /// Route state data #[prop_or_default] pub state: Option<S>, #[prop_or_default] pub disabled: bool, /// [`NodeRef`](yew::html::NodeRef) for the `<a>` element. #[prop_or_default] pub anchor_ref: NodeRef, #[prop_or_default] pub children: Html, } /// A wrapper around `<a>` tag to be used with [`Router`](crate::Router) #[component] pub fn Link<R, Q = (), S = ()>(props: &LinkProps<R, Q, S>) -> Html where R: Routable + 'static, Q: Clone + PartialEq + Serialize + 'static, S: Clone + PartialEq + 'static, { let LinkProps { classes, to, query, state, disabled, anchor_ref, children, } = props.clone(); let navigator = use_navigator().expect_throw("failed to get navigator"); let onclick = { let navigator = navigator.clone(); let to = to.clone(); let query = query.clone(); let state = state.clone(); Callback::from(move |e: MouseEvent| { if e.meta_key() || e.ctrl_key() || e.shift_key() || e.alt_key() { return; } e.prevent_default(); match (&state, &query) { (None, None) => { navigator.push(&to); } (Some(state), None) => { navigator.push_with_state(&to, state.clone()); } (None, Some(query)) => { navigator .push_with_query(&to, query) .expect_throw("failed push history with query"); } (Some(state), Some(query)) => { navigator .push_with_query_and_state(&to, query, state.clone()) .expect_throw("failed push history with query and state"); } } }) }; let href = { let route_s = to.to_path(); let pathname = navigator.prefix_basename(&route_s); let mut path = query .and_then(|query| serde_urlencoded::to_string(query).ok()) .and_then(|query| utils::compose_path(&pathname, &query)) .unwrap_or_else(|| pathname.into_owned()); if navigator.kind() == NavigatorKind::Hash { path.insert(0, '#'); } AttrValue::from(path) }; html! { <a class={classes} {href} {onclick} {disabled} ref={anchor_ref} > { children } </a> } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-router/src/components/redirect.rs
packages/yew-router/src/components/redirect.rs
use wasm_bindgen::UnwrapThrowExt; use yew::prelude::*; use crate::hooks::use_navigator; use crate::Routable; /// Props for [`Redirect`] #[derive(Properties, Clone, PartialEq, Eq)] pub struct RedirectProps<R: Routable> { /// Route that will be pushed when the component is rendered. pub to: R, } /// A component that will redirect to specified route when rendered. #[component(Redirect)] pub fn redirect<R>(props: &RedirectProps<R>) -> Html where R: Routable + 'static, { let history = use_navigator().expect_throw("failed to read history."); let target_route = props.to.clone(); use_effect(move || { history.push(&target_route); || {} }); Html::default() }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-router/src/components/mod.rs
packages/yew-router/src/components/mod.rs
//! Components to interface with [Router][crate::Router]. mod link; mod redirect; pub use link::*; pub use redirect::*;
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-router/tests/router_unit_tests.rs
packages/yew-router/tests/router_unit_tests.rs
// TODO: remove the cfg after wasm-bindgen-test stops emitting the function unconditionally #![cfg(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")))] use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure}; use yew_router::prelude::*; wasm_bindgen_test_configure!(run_in_browser); #[test] fn router_always_404() { #[derive(Routable, Debug, Clone, PartialEq)] enum AppRoute { #[at("/")] Home, #[at("/:id")] Article { id: u64 }, #[at("/404")] #[not_found] NotFound, } assert_eq!( Some(AppRoute::NotFound), AppRoute::recognize("/not/matched/route") ); assert_eq!( Some(AppRoute::NotFound), AppRoute::recognize("/not-matched-route") ); } #[test] fn router_trailing_slash() { #[derive(Routable, Debug, Clone, PartialEq)] enum AppRoute { #[at("/")] Home, #[at("/category/:name/")] Category { name: String }, #[at("/:id")] Article { id: u64 }, #[at("/404")] #[not_found] NotFound, } assert_eq!( Some(AppRoute::Category { name: "cooking-recipes".to_string() }), AppRoute::recognize("/category/cooking-recipes/") ); } #[test] fn router_url_encoding() { #[derive(Routable, Debug, Clone, PartialEq)] enum AppRoute { #[at("/")] Root, #[at("/search/:query")] Search { query: String }, } assert_eq!( yew_router::__macro::decode_for_url("/search/a%2Fb/").unwrap(), "/search/a/b/" ); assert_eq!( Some(AppRoute::Search { query: "a/b".to_string() }), AppRoute::recognize("/search/a%2Fb/") ); }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-router/tests/url_encoded_routes.rs
packages/yew-router/tests/url_encoded_routes.rs
// TODO: remove the cfg after wasm-bindgen-test stops emitting the function unconditionally #![cfg(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")))] use std::time::Duration; use yew::platform::time::sleep; use yew::prelude::*; use yew_router::prelude::*; mod utils; use utils::*; use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure}; wasm_bindgen_test_configure!(run_in_browser); #[derive(Routable, Debug, Clone, PartialEq)] enum AppRoute { #[at("/")] Root, #[at("/search/:query")] Search { query: String }, } #[component] fn Comp() -> Html { let switch = move |routes: AppRoute| match routes { AppRoute::Root => html! { <> <h1>{ "Root" }</h1> <Link<AppRoute> to={AppRoute::Search { query: "a/b".to_string() }}> {"Click me"} </Link<AppRoute>> </> }, AppRoute::Search { query } => html! { <p id="q">{ query }</p> }, }; html! { <Switch<AppRoute> render={switch} /> } } #[component(Root)] fn root() -> Html { html! { <BrowserRouter> <Comp /> </BrowserRouter> } } #[test] async fn url_encoded_roundtrip() { yew::Renderer::<Root>::with_root(gloo::utils::document().get_element_by_id("output").unwrap()) .render(); sleep(Duration::ZERO).await; click("a"); sleep(Duration::ZERO).await; let res = obtain_result_by_id("q"); assert_eq!(res, "a/b"); assert_eq!( gloo::utils::window().location().pathname().unwrap(), "/search/a%2Fb" ) }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-router/tests/link.rs
packages/yew-router/tests/link.rs
// TODO: remove the cfg after wasm-bindgen-test stops emitting the function unconditionally #![cfg(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")))] use std::sync::atomic::{AtomicU8, Ordering}; use std::time::Duration; use gloo::utils::window; use js_sys::{JsString, Object, Reflect}; use serde::{Deserialize, Serialize}; use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure}; use yew::functional::component; use yew::platform::time::sleep; use yew::prelude::*; use yew_router::prelude::*; mod utils; use utils::*; wasm_bindgen_test_configure!(run_in_browser); #[derive(Clone, Serialize, Deserialize, PartialEq)] struct PageParam { page: i32, } #[derive(Clone, Serialize, Deserialize, PartialEq)] struct SearchParams { q: String, lang: Option<String>, } impl SearchParams { fn new(q: &str) -> Self { Self { q: q.to_string(), lang: None, } } fn new_with_lang(q: &str, lang: &str) -> Self { Self { q: q.to_string(), lang: Some(lang.to_string()), } } } #[derive(Debug, Clone, Copy, PartialEq, Routable)] enum Routes { #[at("/posts")] Posts, #[at("/search")] Search, } #[derive(PartialEq, Properties)] struct NavigationMenuProps { #[prop_or(None)] assertion: Option<fn(&Navigator, &Location)>, } #[component(NavigationMenu)] fn navigation_menu(props: &NavigationMenuProps) -> Html { let navigator = use_navigator().unwrap(); let location = use_location().unwrap(); if let Some(assertion) = props.assertion { assertion(&navigator, &location); } html! { <ul> <li class="posts"> <Link<Routes> to={Routes::Posts}> { "Posts without parameters" } </Link<Routes>> </li> <li class="posts-page-2"> <Link<Routes, PageParam> to={Routes::Posts} query={Some(PageParam { page: 2 })}> { "Posts of 2nd page" } </Link<Routes, PageParam>> </li> <li class="search"> <Link<Routes> to={Routes::Search}> { "Search withfout parameters" } </Link<Routes>> </li> <li class="search-q"> <Link<Routes, SearchParams> to={Routes::Search} query={Some(SearchParams::new("Rust"))}> { "Search with keyword parameter" } </Link<Routes, SearchParams>> </li> <li class="search-q-lang"> <Link<Routes, SearchParams> to={Routes::Search} query={Some(SearchParams::new_with_lang("Rust", "en_US"))}> { "Search with keyword and language parameters" } </Link<Routes, SearchParams>> </li> </ul> } } #[component(RootForBrowserRouter)] fn root_for_browser_router() -> Html { html! { <BrowserRouter> <NavigationMenu /> </BrowserRouter> } } async fn link_in_browser_router() { let div = gloo::utils::document().create_element("div").unwrap(); let _ = div.set_attribute("id", "browser-router"); let _ = gloo::utils::body().append_child(&div); let handle = yew::Renderer::<RootForBrowserRouter>::with_root(div).render(); sleep(Duration::ZERO).await; assert_eq!("/posts", link_href("#browser-router ul > li.posts > a")); assert_eq!( "/posts?page=2", link_href("#browser-router ul > li.posts-page-2 > a") ); assert_eq!("/search", link_href("#browser-router ul > li.search > a")); assert_eq!( "/search?q=Rust", link_href("#browser-router ul > li.search-q > a") ); assert_eq!( "/search?q=Rust&lang=en_US", link_href("#browser-router ul > li.search-q-lang > a") ); handle.destroy(); } #[derive(PartialEq, Properties)] struct BasenameProps { basename: Option<String>, assertion: fn(&Navigator, &Location), } #[component(RootForBasename)] fn root_for_basename(props: &BasenameProps) -> Html { html! { <BrowserRouter basename={props.basename.clone()}> <NavigationMenu assertion={props.assertion}/> </BrowserRouter> } } async fn link_with_basename(correct_initial_path: bool) { if correct_initial_path { let cookie = Object::new(); Reflect::set(&cookie, &JsString::from("foo"), &JsString::from("bar")).unwrap(); window() .history() .unwrap() .replace_state_with_url(&cookie, "", Some("/base/")) .unwrap(); } static RENDERS: AtomicU8 = AtomicU8::new(0); RENDERS.store(0, Ordering::Relaxed); let div = gloo::utils::document().create_element("div").unwrap(); let _ = div.set_attribute("id", "with-basename"); let _ = gloo::utils::body().append_child(&div); let mut handle = yew::Renderer::<RootForBasename>::with_root_and_props( div, BasenameProps { basename: Some("/base/".to_owned()), assertion: |navigator, location| { RENDERS.fetch_add(1, Ordering::Relaxed); assert_eq!(navigator.basename(), Some("/base")); assert_eq!(location.path(), "/base/"); }, }, ) .render(); sleep(Duration::ZERO).await; if correct_initial_path { // If the initial path was correct, the router shouldn't have mutated the history. assert_eq!( Reflect::get( &window().history().unwrap().state().unwrap(), &JsString::from("foo") ) .unwrap() .as_string() .as_deref(), Some("bar") ); } assert_eq!( "/base/", gloo::utils::window().location().pathname().unwrap() ); assert_eq!("/base/posts", link_href("#with-basename ul > li.posts > a")); assert_eq!( "/base/posts?page=2", link_href("#with-basename ul > li.posts-page-2 > a") ); assert_eq!( "/base/search", link_href("#with-basename ul > li.search > a") ); assert_eq!( "/base/search?q=Rust", link_href("#with-basename ul > li.search-q > a") ); assert_eq!( "/base/search?q=Rust&lang=en_US", link_href("#with-basename ul > li.search-q-lang > a") ); // Some(a) -> Some(b) handle.update(BasenameProps { basename: Some("/bayes/".to_owned()), assertion: |navigator, location| { RENDERS.fetch_add(1, Ordering::Relaxed); assert_eq!(navigator.basename(), Some("/bayes")); assert_eq!(location.path(), "/bayes/"); }, }); sleep(Duration::ZERO).await; assert_eq!( "/bayes/", gloo::utils::window().location().pathname().unwrap() ); assert_eq!( "/bayes/posts", link_href("#with-basename ul > li.posts > a") ); // Some -> None handle.update(BasenameProps { basename: None, assertion: |navigator, location| { RENDERS.fetch_add(1, Ordering::Relaxed); assert_eq!(navigator.basename(), None); assert_eq!(location.path(), "/"); }, }); sleep(Duration::ZERO).await; assert_eq!("/", gloo::utils::window().location().pathname().unwrap()); assert_eq!("/posts", link_href("#with-basename ul > li.posts > a")); // None -> Some handle.update(BasenameProps { basename: Some("/bass/".to_string()), assertion: |navigator, location| { RENDERS.fetch_add(1, Ordering::Relaxed); assert_eq!(navigator.basename(), Some("/bass")); assert_eq!(location.path(), "/bass/"); }, }); sleep(Duration::ZERO).await; assert_eq!( "/bass/", gloo::utils::window().location().pathname().unwrap() ); assert_eq!("/bass/posts", link_href("#with-basename ul > li.posts > a")); handle.destroy(); // 1 initial, 1 rerender after initial, 3 props changes assert_eq!(RENDERS.load(Ordering::Relaxed), 5); } #[component(RootForHashRouter)] fn root_for_hash_router() -> Html { html! { <HashRouter> <NavigationMenu /> </HashRouter> } } async fn link_in_hash_router() { let div = gloo::utils::document().create_element("div").unwrap(); let _ = div.set_attribute("id", "hash-router"); let _ = gloo::utils::body().append_child(&div); let handle = yew::Renderer::<RootForHashRouter>::with_root(div).render(); sleep(Duration::ZERO).await; assert_eq!("#/posts", link_href("#hash-router ul > li.posts > a")); assert_eq!( "#/posts?page=2", link_href("#hash-router ul > li.posts-page-2 > a") ); assert_eq!("#/search", link_href("#hash-router ul > li.search > a")); assert_eq!( "#/search?q=Rust", link_href("#hash-router ul > li.search-q > a") ); assert_eq!( "#/search?q=Rust&lang=en_US", link_href("#hash-router ul > li.search-q-lang > a") ); handle.destroy(); } // These cannot be run in concurrently because they all read/write the URL. #[test] async fn sequential_tests() { link_in_hash_router().await; link_in_browser_router().await; link_with_basename(false).await; link_with_basename(true).await; }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-router/tests/hash_router.rs
packages/yew-router/tests/hash_router.rs
// TODO: remove the cfg after wasm-bindgen-test stops emitting the function unconditionally #![cfg(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")))] use std::time::Duration; use serde::{Deserialize, Serialize}; use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure}; use yew::functional::component; use yew::platform::time::sleep; use yew::prelude::*; use yew_router::prelude::*; mod utils; use utils::*; wasm_bindgen_test_configure!(run_in_browser); #[derive(Serialize, Deserialize)] struct Query { foo: String, } #[derive(Debug, Clone, Copy, PartialEq, Routable)] enum Routes { #[at("/")] Home, #[at("/no/:id")] No { id: u32 }, #[at("/404")] NotFound, } #[derive(Properties, PartialEq, Clone)] struct NoProps { id: u32, } #[component(No)] fn no(props: &NoProps) -> Html { let route = props.id.to_string(); let location = use_location().unwrap(); html! { <> <div id="result-params">{ route }</div> <div id="result-query">{ location.query::<Query>().unwrap().foo }</div> </> } } #[component(Comp)] fn component() -> Html { let navigator = use_navigator().unwrap(); let switch = move |routes| { let navigator_clone = navigator.clone(); let replace_route = Callback::from(move |_| { navigator_clone .replace_with_query( &Routes::No { id: 2 }, &Query { foo: "bar".to_string(), }, ) .unwrap(); }); let navigator_clone = navigator.clone(); let push_route = Callback::from(move |_| { navigator_clone .push_with_query( &Routes::No { id: 3 }, &Query { foo: "baz".to_string(), }, ) .unwrap(); }); match routes { Routes::Home => html! { <> <div id="result">{"Home"}</div> <button onclick={replace_route}>{"replace a route"}</button> </> }, Routes::No { id } => html! { <> <No id={id} /> <button onclick={push_route}>{"push a route"}</button> </> }, Routes::NotFound => html! { <div id="result">{"404"}</div> }, } }; html! { <Switch<Routes> render={switch} /> } } #[component(Root)] fn root() -> Html { html! { <HashRouter> <Comp /> </HashRouter> } } // all the tests are in place because document state isn't being reset between tests // different routes at the time of execution are set and it causes weird behavior (tests // failing randomly) // this test tests // - routing // - parameters in the path // - query parameters // - 404 redirects #[test] async fn router_works() { yew::Renderer::<Root>::with_root(gloo::utils::document().get_element_by_id("output").unwrap()) .render(); sleep(Duration::ZERO).await; assert_eq!("Home", obtain_result_by_id("result")); sleep(Duration::ZERO).await; let initial_length = history_length(); sleep(Duration::ZERO).await; click("button"); // replacing the current route sleep(Duration::ZERO).await; assert_eq!("2", obtain_result_by_id("result-params")); assert_eq!("bar", obtain_result_by_id("result-query")); assert_eq!(initial_length, history_length()); click("button"); // pushing a new route sleep(Duration::ZERO).await; assert_eq!("3", obtain_result_by_id("result-params")); assert_eq!("baz", obtain_result_by_id("result-query")); assert_eq!(initial_length + 1, history_length()); }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-router/tests/browser_router.rs
packages/yew-router/tests/browser_router.rs
// TODO: remove the cfg after wasm-bindgen-test stops emitting the function unconditionally #![cfg(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")))] use std::time::Duration; use serde::{Deserialize, Serialize}; use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure}; use yew::functional::component; use yew::platform::time::sleep; use yew::prelude::*; use yew_router::prelude::*; mod utils; use utils::*; wasm_bindgen_test_configure!(run_in_browser); #[derive(Serialize, Deserialize)] struct Query { foo: String, } #[derive(Debug, Clone, Copy, PartialEq, Routable)] enum Routes { #[at("/")] Home, #[at("/no/:id")] No { id: u32 }, #[at("/404")] NotFound, } #[derive(Properties, PartialEq, Clone)] struct NoProps { id: u32, } #[component(No)] fn no(props: &NoProps) -> Html { let route = props.id.to_string(); let location = use_location().unwrap(); html! { <> <div id="result-params">{ route }</div> <div id="result-query">{ location.query::<Query>().unwrap().foo }</div> </> } } #[component(Comp)] fn component() -> Html { let navigator = use_navigator().unwrap(); let switch = move |routes| { let navigator_clone = navigator.clone(); let replace_route = Callback::from(move |_| { navigator_clone .replace_with_query( &Routes::No { id: 2 }, &Query { foo: "bar".to_string(), }, ) .unwrap(); }); let navigator_clone = navigator.clone(); let push_route = Callback::from(move |_| { navigator_clone .push_with_query( &Routes::No { id: 3 }, &Query { foo: "baz".to_string(), }, ) .unwrap(); }); match routes { Routes::Home => html! { <> <div id="result">{"Home"}</div> <button onclick={replace_route}>{"replace a route"}</button> </> }, Routes::No { id } => html! { <> <No id={id} /> <button onclick={push_route}>{"push a route"}</button> </> }, Routes::NotFound => html! { <div id="result">{"404"}</div> }, } }; html! { <Switch<Routes> render={switch} /> } } #[component(Root)] fn root() -> Html { html! { <BrowserRouter> <Comp /> </BrowserRouter> } } // all the tests are in place because document state isn't being reset between tests // different routes at the time of execution are set and it causes weird behavior (tests // failing randomly) // this test tests // - routing // - parameters in the path // - query parameters // - 404 redirects #[test] async fn router_works() { yew::Renderer::<Root>::with_root(gloo::utils::document().get_element_by_id("output").unwrap()) .render(); sleep(Duration::ZERO).await; assert_eq!("Home", obtain_result_by_id("result")); sleep(Duration::ZERO).await; let initial_length = history_length(); sleep(Duration::ZERO).await; click("button"); // replacing the current route sleep(Duration::ZERO).await; assert_eq!("2", obtain_result_by_id("result-params")); assert_eq!("bar", obtain_result_by_id("result-query")); assert_eq!(initial_length, history_length()); click("button"); // pushing a new route sleep(Duration::ZERO).await; assert_eq!("3", obtain_result_by_id("result-params")); assert_eq!("baz", obtain_result_by_id("result-query")); assert_eq!(initial_length + 1, history_length()); }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-router/tests/utils.rs
packages/yew-router/tests/utils.rs
use wasm_bindgen::JsCast; #[allow(dead_code)] pub fn obtain_result_by_id(id: &str) -> String { gloo::utils::document() .get_element_by_id(id) .expect("No result found. Most likely, the application crashed and burned") .inner_html() } #[allow(dead_code)] pub fn click(selector: &str) { gloo::utils::document() .query_selector(selector) .unwrap() .unwrap() .dyn_into::<web_sys::HtmlElement>() .unwrap() .click(); } #[allow(dead_code)] pub fn history_length() -> u32 { gloo::utils::window() .history() .expect("No history found") .length() .expect("No history length found") } #[allow(dead_code)] pub fn link_href(selector: &str) -> String { gloo::utils::document() .query_selector(selector) .expect("Failed to run query selector") .unwrap_or_else(|| panic!("No such link: {selector}")) .get_attribute("href") .expect("No href attribute") }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-router/tests/basename.rs
packages/yew-router/tests/basename.rs
// TODO: remove the cfg after wasm-bindgen-test stops emitting the function unconditionally #![cfg(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none")))] use std::time::Duration; use serde::{Deserialize, Serialize}; use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure}; use yew::functional::component; use yew::platform::time::sleep; use yew::prelude::*; use yew_router::prelude::*; mod utils; use utils::*; wasm_bindgen_test_configure!(run_in_browser); #[derive(Serialize, Deserialize)] struct Query { foo: String, } #[derive(Debug, Clone, Copy, PartialEq, Routable)] enum Routes { #[at("/")] Home, #[at("/no/:id")] No { id: u32 }, #[at("/404")] NotFound, } #[derive(Properties, PartialEq, Clone)] struct NoProps { id: u32, } #[component(No)] fn no(props: &NoProps) -> Html { let route = props.id.to_string(); let location = use_location().unwrap(); html! { <> <div id="result-params">{ route }</div> <div id="result-query">{ location.query::<Query>().unwrap().foo }</div> </> } } #[component(Comp)] fn component() -> Html { let navigator = use_navigator().unwrap(); let switch = move |routes| { let navigator_clone = navigator.clone(); let replace_route = Callback::from(move |_| { navigator_clone .replace_with_query( &Routes::No { id: 2 }, &Query { foo: "bar".to_string(), }, ) .unwrap(); }); let navigator_clone = navigator.clone(); let push_route = Callback::from(move |_| { navigator_clone .push_with_query( &Routes::No { id: 3 }, &Query { foo: "baz".to_string(), }, ) .unwrap(); }); match routes { Routes::Home => html! { <> <div id="result">{"Home"}</div> <button onclick={replace_route}>{"replace a route"}</button> </> }, Routes::No { id } => html! { <> <No id={id} /> <button onclick={push_route}>{"push a route"}</button> </> }, Routes::NotFound => html! { <div id="result">{"404"}</div> }, } }; html! { <Switch<Routes> render={switch} /> } } #[component(Root)] fn root() -> Html { html! { <BrowserRouter basename="/base/"> <Comp /> </BrowserRouter> } } // all the tests are in place because document state isn't being reset between tests // different routes at the time of execution are set and it causes weird behavior (tests // failing randomly) // this test tests // - routing // - parameters in the path // - query parameters // - 404 redirects #[test] async fn router_works() { yew::Renderer::<Root>::with_root(gloo::utils::document().get_element_by_id("output").unwrap()) .render(); sleep(Duration::ZERO).await; assert_eq!("Home", obtain_result_by_id("result")); sleep(Duration::ZERO).await; let initial_length = history_length(); sleep(Duration::ZERO).await; click("button"); // replacing the current route sleep(Duration::ZERO).await; assert_eq!("2", obtain_result_by_id("result-params")); assert_eq!("bar", obtain_result_by_id("result-query")); assert_eq!(initial_length, history_length()); click("button"); // pushing a new route sleep(Duration::ZERO).await; assert_eq!("3", obtain_result_by_id("result-params")); assert_eq!("baz", obtain_result_by_id("result-query")); assert_eq!(initial_length + 1, history_length()); }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-agent/src/lib.rs
packages/yew-agent/src/lib.rs
#![doc = include_str!("../README.md")] #![deny( clippy::all, missing_docs, missing_debug_implementations, bare_trait_objects, anonymous_parameters, elided_lifetimes_in_paths )] extern crate self as yew_agent; pub mod codec; pub mod oneshot; pub mod reactor; pub mod worker; pub use codec::{Bincode, Codec}; pub mod traits; pub use traits::{Registrable, Spawnable}; mod reach; pub mod scope_ext; pub use reach::Reach; mod utils; #[doc(hidden)] pub mod __vendored { pub use futures; } pub mod prelude { //! Prelude module to be imported when working with `yew-agent`. //! //! This module re-exports the frequently used types from the crate. pub use crate::oneshot::{oneshot, use_oneshot_runner, UseOneshotRunnerHandle}; pub use crate::reach::Reach; pub use crate::reactor::{ reactor, use_reactor_bridge, use_reactor_subscription, ReactorEvent, ReactorScope, UseReactorBridgeHandle, UseReactorSubscriptionHandle, }; pub use crate::scope_ext::{AgentScopeExt, ReactorBridgeHandle, WorkerBridgeHandle}; pub use crate::worker::{ use_worker_bridge, use_worker_subscription, UseWorkerBridgeHandle, UseWorkerSubscriptionHandle, WorkerScope, }; pub use crate::{Registrable, Spawnable}; }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-agent/src/reach.rs
packages/yew-agent/src/reach.rs
/// The reachability of an agent. #[derive(Debug, Clone, PartialEq, Eq, Hash, Copy)] pub enum Reach { /// Public Reachability. Public, /// Private Reachability. Private, }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-agent/src/codec.rs
packages/yew-agent/src/codec.rs
//! Submodule providing the `Codec` trait and its default implementation using `bincode`. use js_sys::Uint8Array; use serde::{Deserialize, Serialize}; use wasm_bindgen::JsValue; /// Message Encoding and Decoding Format pub trait Codec { /// Encode an input to JsValue fn encode<I>(input: I) -> JsValue where I: Serialize; /// Decode a message to a type fn decode<O>(input: JsValue) -> O where O: for<'de> Deserialize<'de>; } /// Default message encoding with [bincode]. #[derive(Debug)] pub struct Bincode; impl Codec for Bincode { fn encode<I>(input: I) -> JsValue where I: Serialize, { let buf = bincode::serde::encode_to_vec(&input, bincode::config::standard()) .expect("can't serialize an worker message"); Uint8Array::from(buf.as_slice()).into() } fn decode<O>(input: JsValue) -> O where O: for<'de> Deserialize<'de>, { let data = Uint8Array::from(input).to_vec(); let (result, _) = bincode::serde::decode_from_slice(&data, bincode::config::standard()) .expect("can't deserialize an worker message"); result } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-agent/src/utils.rs
packages/yew-agent/src/utils.rs
use std::rc::Rc; use std::sync::atomic::{AtomicUsize, Ordering}; use wasm_bindgen::UnwrapThrowExt; use yew::Reducible; /// Convenience function to avoid repeating expect logic. pub fn window() -> web_sys::Window { web_sys::window().expect_throw("Can't find the global Window") } /// Gets a unique worker id pub(crate) fn get_next_id() -> usize { static CTR: AtomicUsize = AtomicUsize::new(0); CTR.fetch_add(1, Ordering::SeqCst) } #[derive(Default, PartialEq)] pub(crate) struct BridgeIdState { pub inner: usize, } impl Reducible for BridgeIdState { type Action = (); fn reduce(self: Rc<Self>, _: Self::Action) -> Rc<Self> { Self { inner: self.inner + 1, } .into() } } pub(crate) enum OutputsAction<T> { Push(Rc<T>), Close, Reset, } pub(crate) struct OutputsState<T> { pub ctr: usize, pub inner: Vec<Rc<T>>, pub closed: bool, } impl<T> Clone for OutputsState<T> { fn clone(&self) -> Self { Self { ctr: self.ctr, inner: self.inner.clone(), closed: self.closed, } } } impl<T> Reducible for OutputsState<T> { type Action = OutputsAction<T>; fn reduce(mut self: Rc<Self>, action: Self::Action) -> Rc<Self> { { let this = Rc::make_mut(&mut self); this.ctr += 1; match action { OutputsAction::Push(m) => this.inner.push(m), OutputsAction::Close => { this.closed = true; } OutputsAction::Reset => { this.closed = false; this.inner = Vec::new(); } } } self } } impl<T> Default for OutputsState<T> { fn default() -> Self { Self { ctr: 0, inner: Vec::new(), closed: false, } } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-agent/src/scope_ext.rs
packages/yew-agent/src/scope_ext.rs
//! This module contains extensions to the component scope for agent access. use std::any::type_name; use std::fmt; use std::rc::Rc; use futures::stream::SplitSink; use futures::{SinkExt, StreamExt}; use wasm_bindgen::UnwrapThrowExt; use yew::html::Scope; use yew::platform::pinned::RwLock; use yew::platform::spawn_local; use yew::prelude::*; use crate::oneshot::{Oneshot, OneshotProviderState}; use crate::reactor::{Reactor, ReactorBridge, ReactorEvent, ReactorProviderState, ReactorScoped}; use crate::worker::{Worker, WorkerBridge, WorkerProviderState}; /// A Worker Bridge Handle. #[derive(Debug)] pub struct WorkerBridgeHandle<W> where W: Worker, { inner: WorkerBridge<W>, } impl<W> WorkerBridgeHandle<W> where W: Worker, { /// Sends a message to the worker agent. pub fn send(&self, input: W::Input) { self.inner.send(input) } } type ReactorTx<R> = Rc<RwLock<SplitSink<ReactorBridge<R>, <<R as Reactor>::Scope as ReactorScoped>::Input>>>; /// A Reactor Bridge Handle. pub struct ReactorBridgeHandle<R> where R: Reactor + 'static, { tx: ReactorTx<R>, } impl<R> fmt::Debug for ReactorBridgeHandle<R> where R: Reactor + 'static, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct(type_name::<Self>()).finish_non_exhaustive() } } impl<R> ReactorBridgeHandle<R> where R: Reactor + 'static, { /// Sends a message to the reactor agent. pub fn send(&self, input: <R::Scope as ReactorScoped>::Input) { let tx = self.tx.clone(); spawn_local(async move { let mut tx = tx.write().await; let _ = tx.send(input).await; }); } } /// An extension to [`Scope`](yew::html::Scope) that provides communication mechanism to agents. /// /// You can access them on `ctx.link()` pub trait AgentScopeExt { /// Bridges to a Worker Agent. fn bridge_worker<W>(&self, callback: Callback<W::Output>) -> WorkerBridgeHandle<W> where W: Worker + 'static; /// Bridges to a Reactor Agent. fn bridge_reactor<R>(&self, callback: Callback<ReactorEvent<R>>) -> ReactorBridgeHandle<R> where R: Reactor + 'static, <R::Scope as ReactorScoped>::Output: 'static; /// Runs an oneshot in an Oneshot Agent. fn run_oneshot<T>(&self, input: T::Input, callback: Callback<T::Output>) where T: Oneshot + 'static; } impl<COMP> AgentScopeExt for Scope<COMP> where COMP: Component, { fn bridge_worker<W>(&self, callback: Callback<W::Output>) -> WorkerBridgeHandle<W> where W: Worker + 'static, { let inner = self .context::<Rc<WorkerProviderState<W>>>((|_| {}).into()) .expect_throw("failed to bridge to agent.") .0 .create_bridge(callback); WorkerBridgeHandle { inner } } fn bridge_reactor<R>(&self, callback: Callback<ReactorEvent<R>>) -> ReactorBridgeHandle<R> where R: Reactor + 'static, <R::Scope as ReactorScoped>::Output: 'static, { let (tx, mut rx) = self .context::<ReactorProviderState<R>>((|_| {}).into()) .expect_throw("failed to bridge to agent.") .0 .create_bridge() .split(); spawn_local(async move { while let Some(m) = rx.next().await { callback.emit(ReactorEvent::<R>::Output(m)); } callback.emit(ReactorEvent::<R>::Finished); }); let tx = Rc::new(RwLock::new(tx)); ReactorBridgeHandle { tx } } fn run_oneshot<T>(&self, input: T::Input, callback: Callback<T::Output>) where T: Oneshot + 'static, { let (inner, _) = self .context::<OneshotProviderState<T>>((|_| {}).into()) .expect_throw("failed to bridge to agent."); spawn_local(async move { callback.emit(inner.create_bridge().run(input).await) }); } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-agent/src/traits.rs
packages/yew-agent/src/traits.rs
//! Submodule providing the `Spawnable` and `Registrable` traits. /// A Worker that can be spawned by a spawner. pub trait Spawnable { /// Spawner Type. type Spawner; /// Creates a spawner. fn spawner() -> Self::Spawner; } /// A trait to enable public workers being registered in a web worker. pub trait Registrable { /// Registrar Type. type Registrar; /// Creates a registrar for the current worker. fn registrar() -> Self::Registrar; }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-agent/src/worker/messages.rs
packages/yew-agent/src/worker/messages.rs
use serde::{Deserialize, Serialize}; use super::handler_id::HandlerId; use super::traits::Worker; /// Serializable messages to worker #[derive(Serialize, Deserialize, Debug)] pub(crate) enum ToWorker<W> where W: Worker, { /// Client is connected Connected(HandlerId), /// Incoming message to Worker ProcessInput(HandlerId, W::Input), /// Client is disconnected Disconnected(HandlerId), /// Worker should be terminated Destroy, } /// Serializable messages sent by worker to consumer #[derive(Serialize, Deserialize, Debug)] pub(crate) enum FromWorker<W> where W: Worker, { /// Worker sends this message when `wasm` bundle has loaded. WorkerLoaded, /// Outgoing message to consumer ProcessOutput(HandlerId, W::Output), }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-agent/src/worker/spawner.rs
packages/yew-agent/src/worker/spawner.rs
use std::cell::RefCell; use std::collections::HashMap; use std::fmt; use std::marker::PhantomData; use std::rc::{Rc, Weak}; use js_sys::Array; use serde::de::Deserialize; use serde::ser::Serialize; use web_sys::{Blob, BlobPropertyBag, Url, WorkerOptions, WorkerType}; use super::bridge::{CallbackMap, WorkerBridge}; use super::handler_id::HandlerId; use super::messages::FromWorker; use super::native_worker::{DedicatedWorker, NativeWorkerExt}; use super::traits::Worker; use super::{Callback, Shared}; use crate::codec::{Bincode, Codec}; use crate::utils::window; /// A spawner to create workers. #[derive(Clone)] pub struct WorkerSpawner<W, CODEC = Bincode> where W: Worker, CODEC: Codec, { _marker: PhantomData<(W, CODEC)>, callback: Option<Callback<W::Output>>, with_loader: bool, as_module: bool, } impl<W, CODEC> fmt::Debug for WorkerSpawner<W, CODEC> where W: Worker, CODEC: Codec, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("WorkerScope<_>") } } impl<W, CODEC> Default for WorkerSpawner<W, CODEC> where W: Worker + 'static, CODEC: Codec, { fn default() -> Self { Self::new() } } impl<W, CODEC> WorkerSpawner<W, CODEC> where W: Worker + 'static, CODEC: Codec, { /// Creates a [WorkerSpawner]. pub const fn new() -> Self { Self { _marker: PhantomData, callback: None, with_loader: false, as_module: false, } } /// Sets a new message encoding. pub fn encoding<C>(&mut self) -> WorkerSpawner<W, C> where C: Codec, { WorkerSpawner { _marker: PhantomData, callback: self.callback.clone(), with_loader: self.with_loader, as_module: self.as_module, } } /// Sets a callback. pub fn callback<F>(&mut self, cb: F) -> &mut Self where F: 'static + Fn(W::Output), { self.callback = Some(Rc::new(cb)); self } /// Indicates that [`spawn`](WorkerSpawner#method.spawn) should expect a /// `path` to a loader shim script (e.g. when using Trunk, created by using /// the [`data-loader-shim`](https://trunkrs.dev/assets/#link-asset-types) /// asset type) and one does not need to be generated. `false` by default. pub fn with_loader(&mut self, with_loader: bool) -> &mut Self { self.with_loader = with_loader; self } /// Determines whether the worker will be spawned with /// [`options.type`](https://developer.mozilla.org/en-US/docs/Web/API/Worker/Worker#type) /// set to `module`. `true` by default. /// /// This option should be un-set if the worker was created with the /// `--target no-modules` flag of `wasm-bindgen`. If using Trunk, see the /// [`data-bindgen-target`](https://trunkrs.dev/assets/#link-asset-types) /// asset type. pub fn as_module(&mut self, as_module: bool) -> &mut Self { self.as_module = as_module; self } /// Spawns a Worker. pub fn spawn(&self, path: &str) -> WorkerBridge<W> where W::Input: Serialize + for<'de> Deserialize<'de>, W::Output: Serialize + for<'de> Deserialize<'de>, { let worker = self.create_worker(path).expect("failed to spawn worker"); self.spawn_inner(worker) } fn create_worker(&self, path: &str) -> Option<DedicatedWorker> { let path = if self.with_loader { std::borrow::Cow::Borrowed(path) } else { let js_shim_url = Url::new_with_base( path, &window().location().href().expect("failed to read href."), ) .expect("failed to create url for javascript entrypoint") .to_string(); let wasm_url = js_shim_url.replace(".js", "_bg.wasm"); let array = Array::new(); let shim = if self.as_module { format!(r#"import init from '{js_shim_url}';await init();"#) } else { format!(r#"importScripts("{js_shim_url}");wasm_bindgen("{wasm_url}");"#) }; array.push(&shim.into()); let blob_property = BlobPropertyBag::new(); blob_property.set_type("application/javascript"); let blob = Blob::new_with_str_sequence_and_options(&array, &blob_property).unwrap(); let url = Url::create_object_url_with_blob(&blob).unwrap(); std::borrow::Cow::Owned(url) }; let path = path.as_ref(); if self.as_module { let options = WorkerOptions::new(); options.set_type(WorkerType::Module); DedicatedWorker::new_with_options(path, &options).ok() } else { DedicatedWorker::new(path).ok() } } fn spawn_inner(&self, worker: DedicatedWorker) -> WorkerBridge<W> where W::Input: Serialize + for<'de> Deserialize<'de>, W::Output: Serialize + for<'de> Deserialize<'de>, { let pending_queue = Rc::new(RefCell::new(Some(Vec::new()))); let handler_id = HandlerId::new(); let mut callbacks = HashMap::new(); if let Some(m) = self.callback.as_ref().map(Rc::downgrade) { callbacks.insert(handler_id, m); } let callbacks: Shared<CallbackMap<W>> = Rc::new(RefCell::new(callbacks)); let handler = { let pending_queue = pending_queue.clone(); let callbacks = callbacks.clone(); let worker = worker.clone(); move |msg: FromWorker<W>| match msg { FromWorker::WorkerLoaded => { if let Some(pending_queue) = pending_queue.borrow_mut().take() { for to_worker in pending_queue.into_iter() { worker.post_packed_message::<_, CODEC>(to_worker); } } } FromWorker::ProcessOutput(id, output) => { let mut callbacks = callbacks.borrow_mut(); if let Some(m) = callbacks.get(&id) { if let Some(m) = Weak::upgrade(m) { m(output); } else { callbacks.remove(&id); } } } } }; worker.set_on_packed_message::<_, CODEC, _>(handler); WorkerBridge::<W>::new::<CODEC>( handler_id, worker, pending_queue, callbacks, self.callback.clone(), ) } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-agent/src/worker/lifecycle.rs
packages/yew-agent/src/worker/lifecycle.rs
use wasm_bindgen::prelude::*; use super::messages::ToWorker; use super::native_worker::{DedicatedWorker, WorkerSelf}; use super::scope::{WorkerDestroyHandle, WorkerScope}; use super::traits::Worker; use super::Shared; pub(crate) struct WorkerState<W> where W: Worker, { worker: Option<(W, WorkerScope<W>)>, to_destroy: bool, } impl<W> WorkerState<W> where W: Worker, { pub fn new() -> Self { WorkerState { worker: None, to_destroy: false, } } } /// Internal Worker lifecycle events pub(crate) enum WorkerLifecycleEvent<W: Worker> { /// Request to create the scope Create(WorkerScope<W>), /// Internal Worker message Message(W::Message), /// External Messages from bridges Remote(ToWorker<W>), /// Destroy the Worker Destroy, } pub(crate) struct WorkerRunnable<W: Worker> { pub state: Shared<WorkerState<W>>, pub event: WorkerLifecycleEvent<W>, } impl<W> WorkerRunnable<W> where W: Worker + 'static, { pub fn run(self) { let mut state = self.state.borrow_mut(); // We should block all event other than message after a worker is destroyed. match self.event { WorkerLifecycleEvent::Create(scope) => { if state.to_destroy { return; } state.worker = Some((W::create(&scope), scope)); } WorkerLifecycleEvent::Message(msg) => { if let Some((worker, scope)) = state.worker.as_mut() { worker.update(scope, msg); } } WorkerLifecycleEvent::Remote(ToWorker::Connected(id)) => { if state.to_destroy { return; } let (worker, scope) = state .worker .as_mut() .expect_throw("worker was not created to process connected messages"); worker.connected(scope, id); } WorkerLifecycleEvent::Remote(ToWorker::ProcessInput(id, inp)) => { if state.to_destroy { return; } let (worker, scope) = state .worker .as_mut() .expect_throw("worker was not created to process inputs"); worker.received(scope, inp, id); } WorkerLifecycleEvent::Remote(ToWorker::Disconnected(id)) => { if state.to_destroy { return; } let (worker, scope) = state .worker .as_mut() .expect_throw("worker was not created to process disconnected messages"); worker.disconnected(scope, id); } WorkerLifecycleEvent::Remote(ToWorker::Destroy) => { if state.to_destroy { return; } state.to_destroy = true; let (worker, scope) = state .worker .as_mut() .expect_throw("trying to destroy not existent worker"); let destruct = WorkerDestroyHandle::new(scope.clone()); worker.destroy(scope, destruct); } WorkerLifecycleEvent::Destroy => { state .worker .take() .expect_throw("worker is not initialised or already destroyed"); DedicatedWorker::worker_self().close(); } } } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-agent/src/worker/native_worker.rs
packages/yew-agent/src/worker/native_worker.rs
use serde::{Deserialize, Serialize}; use wasm_bindgen::closure::Closure; use wasm_bindgen::prelude::*; use wasm_bindgen::{JsCast, JsValue}; pub(crate) use web_sys::Worker as DedicatedWorker; use web_sys::{DedicatedWorkerGlobalScope, MessageEvent}; use crate::codec::Codec; pub(crate) trait WorkerSelf { type GlobalScope; fn worker_self() -> Self::GlobalScope; } impl WorkerSelf for DedicatedWorker { type GlobalScope = DedicatedWorkerGlobalScope; fn worker_self() -> Self::GlobalScope { JsValue::from(js_sys::global()).into() } } pub(crate) trait NativeWorkerExt { fn set_on_packed_message<T, CODEC, F>(&self, handler: F) where T: Serialize + for<'de> Deserialize<'de>, CODEC: Codec, F: 'static + Fn(T); fn post_packed_message<T, CODEC>(&self, data: T) where T: Serialize + for<'de> Deserialize<'de>, CODEC: Codec; } macro_rules! worker_ext_impl { ($($type:path),+) => {$( impl NativeWorkerExt for $type { fn set_on_packed_message<T, CODEC, F>(&self, handler: F) where T: Serialize + for<'de> Deserialize<'de>, CODEC: Codec, F: 'static + Fn(T) { let handler = move |message: MessageEvent| { let msg = CODEC::decode(message.data()); handler(msg); }; let closure = Closure::wrap(Box::new(handler) as Box<dyn Fn(MessageEvent)>).into_js_value(); self.set_onmessage(Some(closure.as_ref().unchecked_ref())); } fn post_packed_message<T, CODEC>(&self, data: T) where T: Serialize + for<'de> Deserialize<'de>, CODEC: Codec { self.post_message(&CODEC::encode(data)) .expect_throw("failed to post message"); } } )+}; } worker_ext_impl! { DedicatedWorker, DedicatedWorkerGlobalScope }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-agent/src/worker/bridge.rs
packages/yew-agent/src/worker/bridge.rs
use std::cell::RefCell; use std::collections::HashMap; use std::fmt; use std::marker::PhantomData; use std::rc::{Rc, Weak}; use serde::{Deserialize, Serialize}; use super::handler_id::HandlerId; use super::messages::ToWorker; use super::native_worker::NativeWorkerExt; use super::traits::Worker; use super::{Callback, Shared}; use crate::codec::Codec; pub(crate) type ToWorkerQueue<W> = Vec<ToWorker<W>>; pub(crate) type CallbackMap<W> = HashMap<HandlerId, Weak<dyn Fn(<W as Worker>::Output)>>; struct WorkerBridgeInner<W> where W: Worker, { // When worker is loaded, queue becomes None. pending_queue: Shared<Option<ToWorkerQueue<W>>>, callbacks: Shared<CallbackMap<W>>, post_msg: Rc<dyn Fn(ToWorker<W>)>, } impl<W> fmt::Debug for WorkerBridgeInner<W> where W: Worker, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("WorkerBridgeInner<_>") } } impl<W> WorkerBridgeInner<W> where W: Worker, { /// Send a message to the worker, queuing the message if necessary fn send_message(&self, msg: ToWorker<W>) { let mut pending_queue = self.pending_queue.borrow_mut(); match pending_queue.as_mut() { Some(m) => { m.push(msg); } None => { (self.post_msg)(msg); } } } } impl<W> Drop for WorkerBridgeInner<W> where W: Worker, { fn drop(&mut self) { let destroy = ToWorker::Destroy; self.send_message(destroy); } } /// A connection manager for components interaction with workers. pub struct WorkerBridge<W> where W: Worker, { inner: Rc<WorkerBridgeInner<W>>, id: HandlerId, _worker: PhantomData<W>, _cb: Option<Rc<dyn Fn(W::Output)>>, } impl<W> WorkerBridge<W> where W: Worker, { fn init(&self) { self.inner.send_message(ToWorker::Connected(self.id)); } pub(crate) fn new<CODEC>( id: HandlerId, native_worker: web_sys::Worker, pending_queue: Rc<RefCell<Option<ToWorkerQueue<W>>>>, callbacks: Rc<RefCell<CallbackMap<W>>>, callback: Option<Callback<W::Output>>, ) -> Self where CODEC: Codec, W::Input: Serialize + for<'de> Deserialize<'de>, { let post_msg = move |msg: ToWorker<W>| native_worker.post_packed_message::<_, CODEC>(msg); let self_ = Self { inner: WorkerBridgeInner { pending_queue, callbacks, post_msg: Rc::new(post_msg), } .into(), id, _worker: PhantomData, _cb: callback, }; self_.init(); self_ } /// Send a message to the current worker. pub fn send(&self, msg: W::Input) { let msg = ToWorker::ProcessInput(self.id, msg); self.inner.send_message(msg); } /// Forks the bridge with a different callback. /// /// This creates a new [HandlerID] that helps the worker to differentiate bridges. pub fn fork<F>(&self, cb: Option<F>) -> Self where F: 'static + Fn(W::Output), { let cb = cb.map(|m| Rc::new(m) as Rc<dyn Fn(W::Output)>); let handler_id = HandlerId::new(); if let Some(cb_weak) = cb.as_ref().map(Rc::downgrade) { self.inner .callbacks .borrow_mut() .insert(handler_id, cb_weak); } let self_ = Self { inner: self.inner.clone(), id: handler_id, _worker: PhantomData, _cb: cb, }; self_.init(); self_ } } impl<W> Drop for WorkerBridge<W> where W: Worker, { fn drop(&mut self) { let disconnected = ToWorker::Disconnected(self.id); self.inner.send_message(disconnected); } } impl<W> fmt::Debug for WorkerBridge<W> where W: Worker, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("WorkerBridge<_>") } } impl<W> PartialEq for WorkerBridge<W> where W: Worker, { fn eq(&self, rhs: &Self) -> bool { self.id == rhs.id } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-agent/src/worker/scope.rs
packages/yew-agent/src/worker/scope.rs
use std::cell::RefCell; use std::fmt; use std::future::Future; use std::rc::Rc; use serde::de::Deserialize; use serde::ser::Serialize; use wasm_bindgen_futures::spawn_local; use super::handler_id::HandlerId; use super::lifecycle::{WorkerLifecycleEvent, WorkerRunnable, WorkerState}; use super::messages::FromWorker; use super::native_worker::{DedicatedWorker, NativeWorkerExt, WorkerSelf}; use super::traits::Worker; use super::Shared; use crate::codec::Codec; /// A handle that closes the worker when it is dropped. pub struct WorkerDestroyHandle<W> where W: Worker + 'static, { scope: WorkerScope<W>, } impl<W: Worker> fmt::Debug for WorkerDestroyHandle<W> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("WorkerDestroyHandle<_>") } } impl<W> WorkerDestroyHandle<W> where W: Worker, { pub(crate) fn new(scope: WorkerScope<W>) -> Self { Self { scope } } } impl<W> Drop for WorkerDestroyHandle<W> where W: Worker, { fn drop(&mut self) { self.scope.send(WorkerLifecycleEvent::Destroy); } } /// This struct holds a reference to a component and to a global scheduler. pub struct WorkerScope<W: Worker> { state: Shared<WorkerState<W>>, post_msg: Rc<dyn Fn(FromWorker<W>)>, } impl<W: Worker> fmt::Debug for WorkerScope<W> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("WorkerScope<_>") } } impl<W: Worker> Clone for WorkerScope<W> { fn clone(&self) -> Self { WorkerScope { state: self.state.clone(), post_msg: self.post_msg.clone(), } } } impl<W> WorkerScope<W> where W: Worker + 'static, { /// Create worker scope pub(crate) fn new<CODEC>() -> Self where CODEC: Codec, W::Output: Serialize + for<'de> Deserialize<'de>, { let post_msg = move |msg: FromWorker<W>| { DedicatedWorker::worker_self().post_packed_message::<_, CODEC>(msg) }; let state = Rc::new(RefCell::new(WorkerState::new())); WorkerScope { post_msg: Rc::new(post_msg), state, } } /// Schedule message for sending to worker pub(crate) fn send(&self, event: WorkerLifecycleEvent<W>) { let state = self.state.clone(); // We can implement a custom scheduler, // but it's easier to borrow the one from wasm-bindgen-futures. spawn_local(async move { WorkerRunnable { state, event }.run(); }); } /// Send response to a worker bridge. pub fn respond(&self, id: HandlerId, output: W::Output) { let msg = FromWorker::<W>::ProcessOutput(id, output); (self.post_msg)(msg); } /// Send a message to the worker pub fn send_message<T>(&self, msg: T) where T: Into<W::Message>, { self.send(WorkerLifecycleEvent::Message(msg.into())); } /// Create a callback which will send a message to the worker when invoked. pub fn callback<F, IN, M>(&self, function: F) -> Rc<dyn Fn(IN)> where M: Into<W::Message>, F: Fn(IN) -> M + 'static, { let scope = self.clone(); let closure = move |input| { let output = function(input).into(); scope.send(WorkerLifecycleEvent::Message(output)); }; Rc::new(closure) } /// This method creates a callback which returns a Future which /// returns a message to be sent back to the worker /// /// # Panics /// If the future panics, then the promise will not resolve, and /// will leak. pub fn callback_future<FN, FU, IN, M>(&self, function: FN) -> Rc<dyn Fn(IN)> where M: Into<W::Message>, FU: Future<Output = M> + 'static, FN: Fn(IN) -> FU + 'static, { let scope = self.clone(); let closure = move |input: IN| { let future: FU = function(input); scope.send_future(future); }; Rc::new(closure) } /// This method processes a Future that returns a message and sends it back to the worker. /// /// # Panics /// If the future panics, then the promise will not resolve, and will leak. pub fn send_future<F, M>(&self, future: F) where M: Into<W::Message>, F: Future<Output = M> + 'static, { let scope = self.clone(); let js_future = async move { let message: W::Message = future.await.into(); let cb = scope.callback(|m: W::Message| m); (*cb)(message); }; wasm_bindgen_futures::spawn_local(js_future); } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-agent/src/worker/hooks.rs
packages/yew-agent/src/worker/hooks.rs
use std::any::type_name; use std::fmt; use std::ops::Deref; use std::rc::Rc; use wasm_bindgen::prelude::*; use yew::prelude::*; use crate::utils::{BridgeIdState, OutputsAction, OutputsState}; use crate::worker::provider::WorkerProviderState; use crate::worker::{Worker, WorkerBridge}; /// Hook handle for the [`use_worker_bridge`] hook. pub struct UseWorkerBridgeHandle<T> where T: Worker, { inner: Rc<WorkerBridge<T>>, ctr: UseReducerDispatcher<BridgeIdState>, } impl<T> UseWorkerBridgeHandle<T> where T: Worker, { /// Send an input to a worker agent. pub fn send(&self, msg: T::Input) { self.inner.send(msg); } /// Reset the bridge. /// /// Disconnect the old bridge and re-connects the agent with a new bridge. pub fn reset(&self) { self.ctr.dispatch(()); } } impl<T> Clone for UseWorkerBridgeHandle<T> where T: Worker, { fn clone(&self) -> Self { Self { inner: self.inner.clone(), ctr: self.ctr.clone(), } } } impl<T> fmt::Debug for UseWorkerBridgeHandle<T> where T: Worker, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct(type_name::<Self>()) .field("inner", &self.inner) .finish() } } impl<T> PartialEq for UseWorkerBridgeHandle<T> where T: Worker, { fn eq(&self, rhs: &Self) -> bool { self.inner == rhs.inner } } /// A hook to bridge to a [`Worker`]. /// /// This hooks will only bridge the worker once over the entire component lifecycle. /// /// Takes a callback as the argument. /// /// The callback will be updated on every render to make sure captured values (if any) are up to /// date. #[hook] pub fn use_worker_bridge<T, F>(on_output: F) -> UseWorkerBridgeHandle<T> where T: Worker + 'static, F: Fn(T::Output) + 'static, { let ctr = use_reducer(BridgeIdState::default); let worker_state = use_context::<Rc<WorkerProviderState<T>>>() .expect_throw("cannot find a provider for current agent."); let on_output = Rc::new(on_output); let on_output_clone = on_output.clone(); let on_output_ref = use_mut_ref(move || on_output_clone); // Refresh the callback on every render. { let mut on_output_ref = on_output_ref.borrow_mut(); *on_output_ref = on_output; } let bridge = use_memo((worker_state, ctr.inner), |(state, _ctr)| { state.create_bridge(Callback::from(move |output| { let on_output = on_output_ref.borrow().clone(); on_output(output); })) }); UseWorkerBridgeHandle { inner: bridge, ctr: ctr.dispatcher(), } } /// Hook handle for the [`use_worker_subscription`] hook. pub struct UseWorkerSubscriptionHandle<T> where T: Worker, { bridge: UseWorkerBridgeHandle<T>, outputs: Vec<Rc<T::Output>>, ctr: usize, } impl<T> UseWorkerSubscriptionHandle<T> where T: Worker, { /// Send an input to a worker agent. pub fn send(&self, msg: T::Input) { self.bridge.send(msg); } /// Reset the subscription. /// /// This disconnects the old bridge and re-connects the agent with a new bridge. /// Existing outputs stored in the subscription will also be cleared. pub fn reset(&self) { self.bridge.reset(); } } impl<T> Clone for UseWorkerSubscriptionHandle<T> where T: Worker, { fn clone(&self) -> Self { Self { bridge: self.bridge.clone(), outputs: self.outputs.clone(), ctr: self.ctr, } } } impl<T> fmt::Debug for UseWorkerSubscriptionHandle<T> where T: Worker, T::Output: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct(type_name::<Self>()) .field("bridge", &self.bridge) .field("outputs", &self.outputs) .finish() } } impl<T> Deref for UseWorkerSubscriptionHandle<T> where T: Worker, { type Target = [Rc<T::Output>]; fn deref(&self) -> &[Rc<T::Output>] { &self.outputs } } impl<T> PartialEq for UseWorkerSubscriptionHandle<T> where T: Worker, { fn eq(&self, rhs: &Self) -> bool { self.bridge == rhs.bridge && self.ctr == rhs.ctr } } /// A hook to subscribe to the outputs of a [Worker] agent. /// /// All outputs sent to current bridge will be collected into a slice. #[hook] pub fn use_worker_subscription<T>() -> UseWorkerSubscriptionHandle<T> where T: Worker + 'static, { let outputs = use_reducer(OutputsState::default); let bridge = { let outputs = outputs.clone(); use_worker_bridge::<T, _>(move |output| { outputs.dispatch(OutputsAction::Push(Rc::new(output))) }) }; { let outputs_dispatcher = outputs.dispatcher(); use_effect_with(bridge.clone(), move |_| { outputs_dispatcher.dispatch(OutputsAction::Reset); || {} }); } UseWorkerSubscriptionHandle { bridge, outputs: outputs.inner.clone(), ctr: outputs.ctr, } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-agent/src/worker/mod.rs
packages/yew-agent/src/worker/mod.rs
//! This module contains the worker agent implementation. //! //! This is a low-level implementation that uses an actor model. //! //! # Example //! //! ``` //! # mod example { //! use serde::{Deserialize, Serialize}; //! use yew::prelude::*; //! use yew_agent::worker::{use_worker_bridge, UseWorkerBridgeHandle}; //! //! // This would usually live in the same file as your worker //! #[derive(Serialize, Deserialize)] //! pub enum WorkerResponseType { //! IncrementCounter, //! } //! # mod my_worker_mod { //! # use yew_agent::worker::{HandlerId, WorkerScope}; //! # use super::WorkerResponseType; //! # pub struct MyWorker {} //! # //! # impl yew_agent::worker::Worker for MyWorker { //! # type Input = (); //! # type Output = WorkerResponseType; //! # type Message = (); //! # //! # fn create(scope: &WorkerScope<Self>) -> Self { //! # MyWorker {} //! # } //! # //! # fn update(&mut self, scope: &WorkerScope<Self>, _msg: Self::Message) { //! # // do nothing //! # } //! # //! # fn received(&mut self, scope: &WorkerScope<Self>, _msg: Self::Input, id: HandlerId) { //! # scope.respond(id, WorkerResponseType::IncrementCounter); //! # } //! # } //! # } //! use my_worker_mod::MyWorker; // note that <MyWorker as yew_agent::Worker>::Output == WorkerResponseType //! #[component(UseWorkerBridge)] //! fn bridge() -> Html { //! let counter = use_state(|| 0); //! //! // a scoped block to clone the state in //! { //! let counter = counter.clone(); //! // response will be of type MyWorker::Output, i.e. WorkerResponseType //! let bridge: UseWorkerBridgeHandle<MyWorker> = use_worker_bridge(move |response| match response { //! WorkerResponseType::IncrementCounter => { //! counter.set(*counter + 1); //! } //! }); //! } //! //! html! { //! <div> //! {*counter} //! </div> //! } //! } //! # } //! ``` mod bridge; mod handler_id; mod hooks; mod lifecycle; mod messages; mod native_worker; mod provider; mod registrar; mod scope; mod spawner; mod traits; use std::cell::RefCell; use std::rc::Rc; pub use bridge::WorkerBridge; pub use handler_id::HandlerId; pub use hooks::{ use_worker_bridge, use_worker_subscription, UseWorkerBridgeHandle, UseWorkerSubscriptionHandle, }; pub(crate) use provider::WorkerProviderState; pub use provider::{WorkerProvider, WorkerProviderProps}; pub use registrar::WorkerRegistrar; pub use scope::{WorkerDestroyHandle, WorkerScope}; pub use spawner::WorkerSpawner; pub use traits::Worker; /// Alias for `Rc<RefCell<T>>` type Shared<T> = Rc<RefCell<T>>; /// Alias for `Rc<dyn Fn(IN)>` type Callback<IN> = Rc<dyn Fn(IN)>;
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-agent/src/worker/traits.rs
packages/yew-agent/src/worker/traits.rs
use super::handler_id::HandlerId; use super::registrar::WorkerRegistrar; use super::scope::{WorkerDestroyHandle, WorkerScope}; use super::spawner::WorkerSpawner; use crate::traits::{Registrable, Spawnable}; /// Declares the behaviour of a worker. pub trait Worker: Sized { /// Update message type. type Message; /// Incoming message type. type Input; /// Outgoing message type. type Output; /// Creates an instance of a worker. fn create(scope: &WorkerScope<Self>) -> Self; /// Receives an update. /// /// This method is called when the worker send messages to itself via /// [`WorkerScope::send_message`]. fn update(&mut self, scope: &WorkerScope<Self>, msg: Self::Message); /// New bridge created. /// /// When a new bridge is created by [`WorkerSpawner::spawn`](crate::WorkerSpawner) /// or [`WorkerBridge::fork`](crate::WorkerBridge::fork), /// the worker will be notified the [`HandlerId`] of the created bridge via this method. fn connected(&mut self, scope: &WorkerScope<Self>, id: HandlerId) { let _scope = scope; let _id = id; } /// Receives an input from a connected bridge. /// /// When a bridge sends an input via [`WorkerBridge::send`](crate::WorkerBridge::send), the /// worker will receive the input via this method. fn received(&mut self, scope: &WorkerScope<Self>, msg: Self::Input, id: HandlerId); /// Existing bridge destroyed. /// /// When a bridge is dropped, the worker will be notified with this method. fn disconnected(&mut self, scope: &WorkerScope<Self>, id: HandlerId) { let _scope = scope; let _id = id; } /// Destroys the current worker. /// /// When all bridges are dropped, the method will be invoked. /// /// This method is provided a destroy handle where when it is dropped, the worker is closed. /// If the worker is closed immediately, then it can ignore the destroy handle. /// Otherwise hold the destroy handle until the clean up task is finished. /// /// # Note /// /// This method will only be called after all bridges are disconnected. /// Attempting to send messages after this method is called will have no effect. fn destroy(&mut self, scope: &WorkerScope<Self>, destruct: WorkerDestroyHandle<Self>) { let _scope = scope; let _destruct = destruct; } } impl<W> Spawnable for W where W: Worker + 'static, { type Spawner = WorkerSpawner<Self>; fn spawner() -> WorkerSpawner<Self> { WorkerSpawner::new() } } impl<W> Registrable for W where W: Worker + 'static, { type Registrar = WorkerRegistrar<Self>; fn registrar() -> WorkerRegistrar<Self> { WorkerRegistrar::new() } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-agent/src/worker/provider.rs
packages/yew-agent/src/worker/provider.rs
use std::any::type_name; use std::cell::RefCell; use std::fmt; use std::rc::Rc; use serde::{Deserialize, Serialize}; use yew::prelude::*; use super::{Worker, WorkerBridge}; use crate::reach::Reach; use crate::utils::get_next_id; use crate::{Bincode, Codec, Spawnable}; /// Properties for [WorkerProvider]. #[derive(Debug, Properties, PartialEq, Clone)] pub struct WorkerProviderProps { /// The path to an agent. pub path: AttrValue, /// The reachability of an agent. /// /// Default: [`Public`](Reach::Public). #[prop_or(Reach::Public)] pub reach: Reach, /// Whether the agent should be created /// with type `Module`. #[prop_or(false)] pub module: bool, /// Lazily spawn the agent. /// /// The agent will be spawned when the first time a hook requests a bridge. /// /// Does not affect private agents. /// /// Default: `true` #[prop_or(true)] pub lazy: bool, /// Children of the provider. #[prop_or_default] pub children: Html, } pub(crate) struct WorkerProviderState<W> where W: Worker, { id: usize, spawn_bridge_fn: Rc<dyn Fn() -> WorkerBridge<W>>, reach: Reach, held_bridge: RefCell<Option<Rc<WorkerBridge<W>>>>, } impl<W> fmt::Debug for WorkerProviderState<W> where W: Worker, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(type_name::<Self>()) } } impl<W> WorkerProviderState<W> where W: Worker, W::Output: 'static, { fn get_held_bridge(&self) -> Rc<WorkerBridge<W>> { let mut held_bridge = self.held_bridge.borrow_mut(); match held_bridge.as_mut() { Some(m) => m.clone(), None => { let bridge = Rc::new((self.spawn_bridge_fn)()); *held_bridge = Some(bridge.clone()); bridge } } } /// Creates a bridge, uses "fork" for public agents. pub fn create_bridge(&self, cb: Callback<W::Output>) -> WorkerBridge<W> { match self.reach { Reach::Public => { let held_bridge = self.get_held_bridge(); held_bridge.fork(Some(move |m| cb.emit(m))) } Reach::Private => (self.spawn_bridge_fn)(), } } } impl<W> PartialEq for WorkerProviderState<W> where W: Worker, { fn eq(&self, rhs: &Self) -> bool { self.id == rhs.id } } /// The Worker Agent Provider. /// /// This component provides its children access to a worker agent. #[component] pub fn WorkerProvider<W, C = Bincode>(props: &WorkerProviderProps) -> Html where W: Worker + 'static, W::Input: Serialize + for<'de> Deserialize<'de> + 'static, W::Output: Serialize + for<'de> Deserialize<'de> + 'static, C: Codec + 'static, { let WorkerProviderProps { children, path, lazy, module, reach, } = props.clone(); // Creates a spawning function so Codec is can be erased from contexts. let spawn_bridge_fn: Rc<dyn Fn() -> WorkerBridge<W>> = { let path = path.clone(); Rc::new(move || W::spawner().as_module(module).encoding::<C>().spawn(&path)) }; let state = { use_memo((path, lazy, reach), move |(_path, lazy, reach)| { let state = WorkerProviderState::<W> { id: get_next_id(), spawn_bridge_fn, reach: *reach, held_bridge: Default::default(), }; if *reach == Reach::Public && !*lazy { state.get_held_bridge(); } state }) }; html! { <ContextProvider<Rc<WorkerProviderState<W>>> context={state.clone()}> {children} </ContextProvider<Rc<WorkerProviderState<W>>>> } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-agent/src/worker/handler_id.rs
packages/yew-agent/src/worker/handler_id.rs
use std::sync::atomic::{AtomicUsize, Ordering}; use serde::{Deserialize, Serialize}; /// Identifier to send output to bridges. #[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Hash, Clone, Copy)] pub struct HandlerId(usize); impl HandlerId { pub(crate) fn new() -> Self { static CTR: AtomicUsize = AtomicUsize::new(0); let id = CTR.fetch_add(1, Ordering::SeqCst); HandlerId(id) } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-agent/src/worker/registrar.rs
packages/yew-agent/src/worker/registrar.rs
use std::fmt; use std::marker::PhantomData; use serde::de::Deserialize; use serde::ser::Serialize; use super::lifecycle::WorkerLifecycleEvent; use super::messages::{FromWorker, ToWorker}; use super::native_worker::{DedicatedWorker, NativeWorkerExt, WorkerSelf}; use super::scope::WorkerScope; use super::traits::Worker; use crate::codec::{Bincode, Codec}; /// A Worker Registrar. pub struct WorkerRegistrar<W, CODEC = Bincode> where W: Worker, CODEC: Codec, { _marker: PhantomData<(W, CODEC)>, } impl<W: Worker> fmt::Debug for WorkerRegistrar<W> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("WorkerRegistrar<_>") } } impl<W, CODEC> WorkerRegistrar<W, CODEC> where W: Worker + 'static, CODEC: Codec, { pub(crate) fn new() -> Self { Self { _marker: PhantomData, } } /// Sets a new message encoding. pub fn encoding<C>(&self) -> WorkerRegistrar<W, C> where C: Codec, { WorkerRegistrar::new() } /// Executes an worker in the current environment. pub fn register(&self) where CODEC: Codec, W::Input: Serialize + for<'de> Deserialize<'de>, W::Output: Serialize + for<'de> Deserialize<'de>, { let scope = WorkerScope::<W>::new::<CODEC>(); let upd = WorkerLifecycleEvent::Create(scope.clone()); scope.send(upd); let handler = move |msg: ToWorker<W>| { let upd = WorkerLifecycleEvent::Remote(msg); scope.send(upd); }; let loaded: FromWorker<W> = FromWorker::WorkerLoaded; let worker = DedicatedWorker::worker_self(); worker.set_on_packed_message::<_, CODEC, _>(handler); worker.post_packed_message::<_, CODEC>(loaded); } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-agent/src/oneshot/spawner.rs
packages/yew-agent/src/oneshot/spawner.rs
use serde::de::Deserialize; use serde::ser::Serialize; use super::bridge::OneshotBridge; use super::traits::Oneshot; use super::worker::OneshotWorker; use crate::codec::{Bincode, Codec}; use crate::worker::WorkerSpawner; /// A spawner to create oneshot workers. #[derive(Debug, Default)] pub struct OneshotSpawner<N, CODEC = Bincode> where N: Oneshot + 'static, CODEC: Codec, { inner: WorkerSpawner<OneshotWorker<N>, CODEC>, } impl<N, CODEC> OneshotSpawner<N, CODEC> where N: Oneshot + 'static, CODEC: Codec, { /// Creates a [OneshotSpawner]. pub const fn new() -> Self { Self { inner: WorkerSpawner::<OneshotWorker<N>, CODEC>::new(), } } /// Sets a new message encoding. pub const fn encoding<C>(&self) -> OneshotSpawner<N, C> where C: Codec, { OneshotSpawner { inner: WorkerSpawner::<OneshotWorker<N>, C>::new(), } } /// Indicates that [`spawn`](WorkerSpawner#method.spawn) should expect a /// `path` to a loader shim script (e.g. when using Trunk, created by using /// the [`data-loader-shim`](https://trunkrs.dev/assets/#link-asset-types) /// asset type) and one does not need to be generated. `false` by default. pub fn with_loader(mut self, with_loader: bool) -> Self { self.inner.with_loader(with_loader); self } /// Determines whether the worker will be spawned with /// [`options.type`](https://developer.mozilla.org/en-US/docs/Web/API/Worker/Worker#type) /// set to `module`. `true` by default. /// /// This option should be un-set if the worker was created with the /// `--target no-modules` flag of `wasm-bindgen`. If using Trunk, see the /// [`data-bindgen-target`](https://trunkrs.dev/assets/#link-asset-types) /// asset type. pub fn as_module(mut self, as_module: bool) -> Self { self.inner.as_module(as_module); self } /// Spawns a Oneshot Worker. pub fn spawn(mut self, path: &str) -> OneshotBridge<N> where N::Input: Serialize + for<'de> Deserialize<'de>, N::Output: Serialize + for<'de> Deserialize<'de>, { let rx = OneshotBridge::register_callback(&mut self.inner); let inner = self.inner.spawn(path); OneshotBridge::new(inner, rx) } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-agent/src/oneshot/bridge.rs
packages/yew-agent/src/oneshot/bridge.rs
use futures::stream::StreamExt; use pinned::mpsc; use pinned::mpsc::UnboundedReceiver; use super::traits::Oneshot; use super::worker::OneshotWorker; use crate::codec::Codec; use crate::worker::{WorkerBridge, WorkerSpawner}; /// A connection manager for components interaction with oneshot workers. #[derive(Debug)] pub struct OneshotBridge<N> where N: Oneshot + 'static, { inner: WorkerBridge<OneshotWorker<N>>, rx: UnboundedReceiver<N::Output>, } impl<N> OneshotBridge<N> where N: Oneshot + 'static, { #[inline(always)] pub(crate) fn new( inner: WorkerBridge<OneshotWorker<N>>, rx: UnboundedReceiver<N::Output>, ) -> Self { Self { inner, rx } } #[inline(always)] pub(crate) fn register_callback<CODEC>( spawner: &mut WorkerSpawner<OneshotWorker<N>, CODEC>, ) -> UnboundedReceiver<N::Output> where CODEC: Codec, { let (tx, rx) = mpsc::unbounded(); spawner.callback(move |output| { let _ = tx.send_now(output); }); rx } /// Forks the bridge. /// /// This method creates a new bridge that can be used to execute tasks on the same worker /// instance. pub fn fork(&self) -> Self { let (tx, rx) = mpsc::unbounded(); let inner = self.inner.fork(Some(move |output| { let _ = tx.send_now(output); })); Self { inner, rx } } /// Run the current oneshot worker once in the current worker instance. pub async fn run(&mut self, input: N::Input) -> N::Output { // &mut self guarantees that the bridge will be // exclusively borrowed during the time the oneshot worker is running. self.inner.send(input); // For each bridge, there can only be 1 active task running on the worker instance. // The next output will be the output for the input that we just sent. self.rx .next() .await .expect("failed to receive result from worker") } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-agent/src/oneshot/worker.rs
packages/yew-agent/src/oneshot/worker.rs
use super::traits::Oneshot; use crate::worker::{HandlerId, Worker, WorkerDestroyHandle, WorkerScope}; pub(crate) enum Message<T> where T: Oneshot, { Finished { handler_id: HandlerId, output: T::Output, }, } pub(crate) struct OneshotWorker<T> where T: 'static + Oneshot, { running_tasks: usize, destruct_handle: Option<WorkerDestroyHandle<Self>>, } impl<T> Worker for OneshotWorker<T> where T: 'static + Oneshot, { type Input = T::Input; type Message = Message<T>; type Output = T::Output; fn create(_scope: &WorkerScope<Self>) -> Self { Self { running_tasks: 0, destruct_handle: None, } } fn update(&mut self, scope: &WorkerScope<Self>, msg: Self::Message) { let Message::Finished { handler_id, output } = msg; self.running_tasks -= 1; scope.respond(handler_id, output); if self.running_tasks == 0 { self.destruct_handle = None; } } fn received(&mut self, scope: &WorkerScope<Self>, input: Self::Input, handler_id: HandlerId) { self.running_tasks += 1; scope.send_future(async move { let output = T::create(input).await; Message::Finished { handler_id, output } }); } fn destroy(&mut self, _scope: &WorkerScope<Self>, destruct: WorkerDestroyHandle<Self>) { if self.running_tasks > 0 { self.destruct_handle = Some(destruct); } } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-agent/src/oneshot/hooks.rs
packages/yew-agent/src/oneshot/hooks.rs
use yew::prelude::*; use super::provider::OneshotProviderState; use super::Oneshot; /// Hook handle for [`use_oneshot_runner`] #[derive(Debug)] pub struct UseOneshotRunnerHandle<T> where T: Oneshot + 'static, { state: OneshotProviderState<T>, } impl<T> UseOneshotRunnerHandle<T> where T: Oneshot + 'static, { /// Runs an oneshot agent. pub async fn run(&self, input: T::Input) -> T::Output { self.state.create_bridge().run(input).await } } impl<T> Clone for UseOneshotRunnerHandle<T> where T: Oneshot + 'static, { fn clone(&self) -> Self { Self { state: self.state.clone(), } } } impl<T> PartialEq for UseOneshotRunnerHandle<T> where T: Oneshot, { fn eq(&self, rhs: &Self) -> bool { self.state == rhs.state } } /// A hook to create a runner to an oneshot agent. #[hook] pub fn use_oneshot_runner<T>() -> UseOneshotRunnerHandle<T> where T: Oneshot + 'static, { let state = use_context::<OneshotProviderState<T>>().expect("failed to find worker context"); UseOneshotRunnerHandle { state } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-agent/src/oneshot/mod.rs
packages/yew-agent/src/oneshot/mod.rs
//! This module provides task agent implementation. mod bridge; mod hooks; mod provider; mod registrar; mod spawner; mod traits; mod worker; pub use bridge::OneshotBridge; pub use hooks::{use_oneshot_runner, UseOneshotRunnerHandle}; pub use provider::OneshotProvider; pub(crate) use provider::OneshotProviderState; pub use registrar::OneshotRegistrar; pub use spawner::OneshotSpawner; pub use traits::Oneshot; /// A procedural macro to create oneshot agents. pub use yew_agent_macro::oneshot;
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-agent/src/oneshot/traits.rs
packages/yew-agent/src/oneshot/traits.rs
use std::future::Future; /// A future-based worker that for each input, one output is produced. pub trait Oneshot: Future { /// Incoming message type. type Input; /// Creates an oneshot worker. fn create(input: Self::Input) -> Self; }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-agent/src/oneshot/provider.rs
packages/yew-agent/src/oneshot/provider.rs
use core::fmt; use std::any::type_name; use std::cell::RefCell; use std::rc::Rc; use serde::{Deserialize, Serialize}; use yew::prelude::*; use super::{Oneshot, OneshotBridge, OneshotSpawner}; use crate::utils::get_next_id; use crate::worker::WorkerProviderProps; use crate::{Bincode, Codec, Reach}; pub(crate) struct OneshotProviderState<T> where T: Oneshot + 'static, { id: usize, spawn_bridge_fn: Rc<dyn Fn() -> OneshotBridge<T>>, reach: Reach, held_bridge: Rc<RefCell<Option<OneshotBridge<T>>>>, } impl<T> fmt::Debug for OneshotProviderState<T> where T: Oneshot, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(type_name::<Self>()) } } impl<T> OneshotProviderState<T> where T: Oneshot, { fn get_held_bridge(&self) -> OneshotBridge<T> { let mut held_bridge = self.held_bridge.borrow_mut(); match held_bridge.as_mut() { Some(m) => m.fork(), None => { let bridge = (self.spawn_bridge_fn)(); *held_bridge = Some(bridge.fork()); bridge } } } /// Creates a bridge, uses "fork" for public agents. pub fn create_bridge(&self) -> OneshotBridge<T> { match self.reach { Reach::Public => { let held_bridge = self.get_held_bridge(); held_bridge.fork() } Reach::Private => (self.spawn_bridge_fn)(), } } } impl<T> Clone for OneshotProviderState<T> where T: Oneshot, { fn clone(&self) -> Self { Self { id: self.id, spawn_bridge_fn: self.spawn_bridge_fn.clone(), reach: self.reach, held_bridge: self.held_bridge.clone(), } } } impl<T> PartialEq for OneshotProviderState<T> where T: Oneshot, { fn eq(&self, rhs: &Self) -> bool { self.id == rhs.id } } /// The Oneshot Agent Provider. /// /// This component provides its children access to an oneshot agent. #[component] pub fn OneshotProvider<T, C = Bincode>(props: &WorkerProviderProps) -> Html where T: Oneshot + 'static, T::Input: Serialize + for<'de> Deserialize<'de> + 'static, T::Output: Serialize + for<'de> Deserialize<'de> + 'static, C: Codec + 'static, { let WorkerProviderProps { children, path, lazy, module, reach, } = props.clone(); // Creates a spawning function so Codec is can be erased from contexts. let spawn_bridge_fn: Rc<dyn Fn() -> OneshotBridge<T>> = { let path = path.clone(); Rc::new(move || { OneshotSpawner::<T>::new() .as_module(module) .encoding::<C>() .spawn(&path) }) }; let state = { use_memo((path, lazy, reach), move |(_path, lazy, reach)| { let state = OneshotProviderState::<T> { id: get_next_id(), spawn_bridge_fn, reach: *reach, held_bridge: Rc::default(), }; if *reach == Reach::Public && !*lazy { state.get_held_bridge(); } state }) }; html! { <ContextProvider<OneshotProviderState<T>> context={(*state).clone()}> {children} </ContextProvider<OneshotProviderState<T>>> } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-agent/src/oneshot/registrar.rs
packages/yew-agent/src/oneshot/registrar.rs
use std::fmt; use serde::de::Deserialize; use serde::ser::Serialize; use super::traits::Oneshot; use super::worker::OneshotWorker; use crate::codec::{Bincode, Codec}; use crate::traits::Registrable; use crate::worker::WorkerRegistrar; /// A registrar for oneshot workers. pub struct OneshotRegistrar<T, CODEC = Bincode> where T: Oneshot + 'static, CODEC: Codec + 'static, { inner: WorkerRegistrar<OneshotWorker<T>, CODEC>, } impl<T, CODEC> Default for OneshotRegistrar<T, CODEC> where T: Oneshot + 'static, CODEC: Codec + 'static, { fn default() -> Self { Self::new() } } impl<N, CODEC> OneshotRegistrar<N, CODEC> where N: Oneshot + 'static, CODEC: Codec + 'static, { /// Creates a new Oneshot Registrar. pub fn new() -> Self { Self { inner: OneshotWorker::<N>::registrar().encoding::<CODEC>(), } } /// Sets the encoding. pub fn encoding<C>(&self) -> OneshotRegistrar<N, C> where C: Codec + 'static, { OneshotRegistrar { inner: self.inner.encoding::<C>(), } } /// Registers the worker. pub fn register(&self) where N::Input: Serialize + for<'de> Deserialize<'de>, N::Output: Serialize + for<'de> Deserialize<'de>, { self.inner.register() } } impl<T, CODEC> fmt::Debug for OneshotRegistrar<T, CODEC> where T: Oneshot + 'static, CODEC: Codec + 'static, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("OneshotRegistrar<_>").finish() } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-agent/src/reactor/messages.rs
packages/yew-agent/src/reactor/messages.rs
use serde::{Deserialize, Serialize}; /// The Bridge Input. #[derive(Debug, Serialize, Deserialize)] pub(crate) enum ReactorInput<I> { /// An input message. Input(I), } /// The Bridge Output. #[derive(Debug, Serialize, Deserialize)] pub enum ReactorOutput<O> { /// An output message has been received. Output(O), /// Reactor for current bridge has exited. Finish, }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-agent/src/reactor/spawner.rs
packages/yew-agent/src/reactor/spawner.rs
use serde::de::Deserialize; use serde::ser::Serialize; use super::bridge::ReactorBridge; use super::scope::ReactorScoped; use super::traits::Reactor; use super::worker::ReactorWorker; use crate::codec::{Bincode, Codec}; use crate::worker::WorkerSpawner; /// A spawner to create oneshot workers. #[derive(Debug, Default)] pub struct ReactorSpawner<R, CODEC = Bincode> where R: Reactor + 'static, CODEC: Codec, { inner: WorkerSpawner<ReactorWorker<R>, CODEC>, } impl<R, CODEC> ReactorSpawner<R, CODEC> where R: Reactor + 'static, CODEC: Codec, { /// Creates a ReactorSpawner. pub const fn new() -> Self { Self { inner: WorkerSpawner::<ReactorWorker<R>, CODEC>::new(), } } /// Sets a new message encoding. pub const fn encoding<C>(&self) -> ReactorSpawner<R, C> where C: Codec, { ReactorSpawner { inner: WorkerSpawner::<ReactorWorker<R>, C>::new(), } } /// Indicates that [`spawn`](WorkerSpawner#method.spawn) should expect a /// `path` to a loader shim script (e.g. when using Trunk, created by using /// the [`data-loader-shim`](https://trunkrs.dev/assets/#link-asset-types) /// asset type) and one does not need to be generated. `false` by default. pub fn with_loader(mut self, with_loader: bool) -> Self { self.inner.with_loader(with_loader); self } /// Determines whether the worker will be spawned with /// [`options.type`](https://developer.mozilla.org/en-US/docs/Web/API/Worker/Worker#type) /// set to `module`. `true` by default. /// /// This option should be un-set if the worker was created with the /// `--target no-modules` flag of `wasm-bindgen`. If using Trunk, see the /// [`data-bindgen-target`](https://trunkrs.dev/assets/#link-asset-types) /// asset type. pub fn as_module(mut self, as_module: bool) -> Self { self.inner.as_module(as_module); self } /// Spawns a reactor worker. pub fn spawn(mut self, path: &str) -> ReactorBridge<R> where <R::Scope as ReactorScoped>::Input: Serialize + for<'de> Deserialize<'de>, <R::Scope as ReactorScoped>::Output: Serialize + for<'de> Deserialize<'de>, { let rx = ReactorBridge::register_callback(&mut self.inner); let inner = self.inner.spawn(path); ReactorBridge::new(inner, rx) } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-agent/src/reactor/bridge.rs
packages/yew-agent/src/reactor/bridge.rs
use std::fmt; use std::pin::Pin; use std::task::{Context, Poll}; use futures::sink::Sink; use futures::stream::{FusedStream, Stream}; use pinned::mpsc; use pinned::mpsc::{UnboundedReceiver, UnboundedSender}; use thiserror::Error; use super::messages::{ReactorInput, ReactorOutput}; use super::scope::ReactorScoped; use super::traits::Reactor; use super::worker::ReactorWorker; use crate::worker::{WorkerBridge, WorkerSpawner}; use crate::Codec; /// A connection manager for components interaction with oneshot workers. /// /// As this type implements [Stream] + [Sink], it can be split with [`StreamExt::split`]. pub struct ReactorBridge<R> where R: Reactor + 'static, { inner: WorkerBridge<ReactorWorker<R>>, rx: UnboundedReceiver<<R::Scope as ReactorScoped>::Output>, } impl<R> fmt::Debug for ReactorBridge<R> where R: Reactor, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("ReactorBridge<_>") } } impl<R> ReactorBridge<R> where R: Reactor + 'static, { #[inline(always)] pub(crate) fn new( inner: WorkerBridge<ReactorWorker<R>>, rx: UnboundedReceiver<<R::Scope as ReactorScoped>::Output>, ) -> Self { Self { inner, rx } } pub(crate) fn output_callback( tx: &UnboundedSender<<R::Scope as ReactorScoped>::Output>, output: ReactorOutput<<R::Scope as ReactorScoped>::Output>, ) { match output { ReactorOutput::Output(m) => { let _ = tx.send_now(m); } ReactorOutput::Finish => { tx.close_now(); } } } #[inline(always)] pub(crate) fn register_callback<CODEC>( spawner: &mut WorkerSpawner<ReactorWorker<R>, CODEC>, ) -> UnboundedReceiver<<R::Scope as ReactorScoped>::Output> where CODEC: Codec, { let (tx, rx) = mpsc::unbounded(); spawner.callback(move |output| Self::output_callback(&tx, output)); rx } /// Forks the bridge. /// /// This method creates a new bridge connected to a new reactor on the same worker instance. pub fn fork(&self) -> Self { let (tx, rx) = mpsc::unbounded(); let inner = self .inner .fork(Some(move |output| Self::output_callback(&tx, output))); Self { inner, rx } } /// Sends an input to the current reactor. pub fn send_input(&self, msg: <R::Scope as ReactorScoped>::Input) { self.inner.send(ReactorInput::Input(msg)); } } impl<R> Stream for ReactorBridge<R> where R: Reactor + 'static, { type Item = <R::Scope as ReactorScoped>::Output; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { Pin::new(&mut self.rx).poll_next(cx) } fn size_hint(&self) -> (usize, Option<usize>) { self.rx.size_hint() } } impl<R> FusedStream for ReactorBridge<R> where R: Reactor + 'static, { fn is_terminated(&self) -> bool { self.rx.is_terminated() } } /// An error type for bridge sink. #[derive(Error, Clone, PartialEq, Eq, Debug)] pub enum ReactorBridgeSinkError { /// A bridge is an RAII Guard, it can only be closed by dropping the value. #[error("attempting to close the bridge via the sink")] AttemptClosure, } impl<R> Sink<<R::Scope as ReactorScoped>::Input> for ReactorBridge<R> where R: Reactor + 'static, { type Error = ReactorBridgeSinkError; fn poll_close(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { Poll::Ready(Err(ReactorBridgeSinkError::AttemptClosure)) } fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { Poll::Ready(Ok(())) } fn poll_ready(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { Poll::Ready(Ok(())) } fn start_send( self: Pin<&mut Self>, item: <R::Scope as ReactorScoped>::Input, ) -> Result<(), Self::Error> { self.send_input(item); Ok(()) } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-agent/src/reactor/scope.rs
packages/yew-agent/src/reactor/scope.rs
use std::convert::Infallible; use std::fmt; use std::pin::Pin; use futures::stream::{FusedStream, Stream}; use futures::task::{Context, Poll}; use futures::Sink; /// A handle to communicate with bridges. pub struct ReactorScope<I, O> { input_stream: Pin<Box<dyn FusedStream<Item = I>>>, output_sink: Pin<Box<dyn Sink<O, Error = Infallible>>>, } impl<I, O> fmt::Debug for ReactorScope<I, O> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("ReactorScope<_>").finish() } } impl<I, O> Stream for ReactorScope<I, O> { type Item = I; #[inline(always)] fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { Pin::new(&mut self.input_stream).poll_next(cx) } #[inline(always)] fn size_hint(&self) -> (usize, Option<usize>) { self.input_stream.size_hint() } } impl<I, O> FusedStream for ReactorScope<I, O> { #[inline(always)] fn is_terminated(&self) -> bool { self.input_stream.is_terminated() } } /// A helper trait to extract the input and output type from a [ReactorStream]. pub trait ReactorScoped: Stream + FusedStream { /// The Input Message. type Input; /// The Output Message. type Output; /// Creates a ReactorReceiver. fn new<IS, OS>(input_stream: IS, output_sink: OS) -> Self where IS: Stream<Item = Self::Input> + FusedStream + 'static, OS: Sink<Self::Output, Error = Infallible> + 'static; } impl<I, O> ReactorScoped for ReactorScope<I, O> { type Input = I; type Output = O; #[inline] fn new<IS, OS>(input_stream: IS, output_sink: OS) -> Self where IS: Stream<Item = Self::Input> + FusedStream + 'static, OS: Sink<Self::Output, Error = Infallible> + 'static, { Self { input_stream: Box::pin(input_stream), output_sink: Box::pin(output_sink), } } } impl<I, O> Sink<O> for ReactorScope<I, O> { type Error = Infallible; fn start_send(mut self: Pin<&mut Self>, item: O) -> Result<(), Self::Error> { Pin::new(&mut self.output_sink).start_send(item) } fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { Pin::new(&mut self.output_sink).poll_close(cx) } fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { Pin::new(&mut self.output_sink).poll_flush(cx) } fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { Pin::new(&mut self.output_sink).poll_flush(cx) } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-agent/src/reactor/worker.rs
packages/yew-agent/src/reactor/worker.rs
use std::collections::HashMap; use std::convert::Infallible; use futures::sink; use futures::stream::StreamExt; use pinned::mpsc; use pinned::mpsc::UnboundedSender; use wasm_bindgen_futures::spawn_local; use super::messages::{ReactorInput, ReactorOutput}; use super::scope::ReactorScoped; use super::traits::Reactor; use crate::worker::{HandlerId, Worker, WorkerDestroyHandle, WorkerScope}; pub(crate) enum Message { ReactorExited(HandlerId), } pub(crate) struct ReactorWorker<R> where R: 'static + Reactor, { senders: HashMap<HandlerId, UnboundedSender<<R::Scope as ReactorScoped>::Input>>, destruct_handle: Option<WorkerDestroyHandle<Self>>, } impl<R> Worker for ReactorWorker<R> where R: 'static + Reactor, { type Input = ReactorInput<<R::Scope as ReactorScoped>::Input>; type Message = Message; type Output = ReactorOutput<<R::Scope as ReactorScoped>::Output>; fn create(_scope: &WorkerScope<Self>) -> Self { Self { senders: HashMap::new(), destruct_handle: None, } } fn update(&mut self, scope: &WorkerScope<Self>, msg: Self::Message) { match msg { Self::Message::ReactorExited(id) => { scope.respond(id, ReactorOutput::Finish); self.senders.remove(&id); } } // All reactors have closed themselves, the worker can now close. if self.destruct_handle.is_some() && self.senders.is_empty() { self.destruct_handle = None; } } fn connected(&mut self, scope: &WorkerScope<Self>, id: HandlerId) { let from_bridge = { let (tx, rx) = mpsc::unbounded(); self.senders.insert(id, tx); rx }; let to_bridge = { let scope_ = scope.clone(); let (tx, mut rx) = mpsc::unbounded(); spawn_local(async move { while let Some(m) = rx.next().await { scope_.respond(id, ReactorOutput::Output(m)); } }); sink::unfold((), move |_, item: <R::Scope as ReactorScoped>::Output| { let tx = tx.clone(); async move { let _ = tx.send_now(item); Ok::<(), Infallible>(()) } }) }; let reactor_scope = ReactorScoped::new(from_bridge, to_bridge); let reactor = R::create(reactor_scope); scope.send_future(async move { reactor.await; Message::ReactorExited(id) }); } fn received(&mut self, _scope: &WorkerScope<Self>, input: Self::Input, id: HandlerId) { match input { Self::Input::Input(input) => { if let Some(m) = self.senders.get_mut(&id) { let _result = m.send_now(input); } } } } fn disconnected(&mut self, _scope: &WorkerScope<Self>, id: HandlerId) { // We close this channel, but drop it when the reactor has exited itself. if let Some(m) = self.senders.get_mut(&id) { m.close_now(); } } fn destroy(&mut self, _scope: &WorkerScope<Self>, destruct: WorkerDestroyHandle<Self>) { if !self.senders.is_empty() { self.destruct_handle = Some(destruct); } } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-agent/src/reactor/hooks.rs
packages/yew-agent/src/reactor/hooks.rs
use std::any::type_name; use std::fmt; use std::ops::Deref; use std::rc::Rc; use futures::sink::SinkExt; use futures::stream::{SplitSink, StreamExt}; use wasm_bindgen::UnwrapThrowExt; use yew::platform::pinned::RwLock; use yew::platform::spawn_local; use yew::prelude::*; use super::provider::ReactorProviderState; use super::{Reactor, ReactorBridge, ReactorScoped}; use crate::utils::{BridgeIdState, OutputsAction, OutputsState}; type ReactorTx<R> = Rc<RwLock<SplitSink<ReactorBridge<R>, <<R as Reactor>::Scope as ReactorScoped>::Input>>>; /// A type that represents events from a reactor. pub enum ReactorEvent<R> where R: Reactor, { /// The reactor agent has sent an output. Output(<R::Scope as ReactorScoped>::Output), /// The reactor agent has exited. Finished, } impl<R> fmt::Debug for ReactorEvent<R> where R: Reactor, <R::Scope as ReactorScoped>::Output: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Output(m) => f.debug_tuple("ReactorEvent::Output").field(&m).finish(), Self::Finished => f.debug_tuple("ReactorEvent::Finished").finish(), } } } /// Hook handle for the [`use_reactor_bridge`] hook. pub struct UseReactorBridgeHandle<R> where R: 'static + Reactor, { tx: ReactorTx<R>, ctr: UseReducerDispatcher<BridgeIdState>, } impl<R> fmt::Debug for UseReactorBridgeHandle<R> where R: 'static + Reactor, <R::Scope as ReactorScoped>::Input: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct(type_name::<Self>()) .field("inner", &self.tx) .finish() } } impl<R> Clone for UseReactorBridgeHandle<R> where R: 'static + Reactor, { fn clone(&self) -> Self { Self { tx: self.tx.clone(), ctr: self.ctr.clone(), } } } impl<R> UseReactorBridgeHandle<R> where R: 'static + Reactor, { /// Send an input to a reactor agent. pub fn send(&self, msg: <R::Scope as ReactorScoped>::Input) { let tx = self.tx.clone(); spawn_local(async move { let mut tx = tx.write().await; let _ = tx.send(msg).await; }); } /// Reset the bridge. /// /// Disconnect the old bridge and re-connects the agent with a new bridge. pub fn reset(&self) { self.ctr.dispatch(()); } } impl<R> PartialEq for UseReactorBridgeHandle<R> where R: 'static + Reactor, { fn eq(&self, rhs: &Self) -> bool { self.ctr == rhs.ctr } } /// A hook to bridge to a [`Reactor`]. /// /// This hooks will only bridge the reactor once over the entire component lifecycle. /// /// Takes a callback as the argument. /// /// The callback will be updated on every render to make sure captured values (if any) are up to /// date. #[hook] pub fn use_reactor_bridge<R, F>(on_output: F) -> UseReactorBridgeHandle<R> where R: 'static + Reactor, F: Fn(ReactorEvent<R>) + 'static, { let ctr = use_reducer(BridgeIdState::default); let worker_state = use_context::<ReactorProviderState<R>>() .expect_throw("cannot find a provider for current agent."); let on_output = Rc::new(on_output); let on_output_ref = { let on_output = on_output.clone(); use_mut_ref(move || on_output) }; // Refresh the callback on every render. { let mut on_output_ref = on_output_ref.borrow_mut(); *on_output_ref = on_output; } let tx = use_memo((worker_state, ctr.inner), |(state, _ctr)| { let bridge = state.create_bridge(); let (tx, mut rx) = bridge.split(); spawn_local(async move { while let Some(m) = rx.next().await { let on_output = on_output_ref.borrow().clone(); on_output(ReactorEvent::<R>::Output(m)); } let on_output = on_output_ref.borrow().clone(); on_output(ReactorEvent::<R>::Finished); }); RwLock::new(tx) }); UseReactorBridgeHandle { tx: tx.clone(), ctr: ctr.dispatcher(), } } /// Hook handle for the [`use_reactor_subscription`] hook. pub struct UseReactorSubscriptionHandle<R> where R: 'static + Reactor, { bridge: UseReactorBridgeHandle<R>, outputs: Vec<Rc<<R::Scope as ReactorScoped>::Output>>, finished: bool, ctr: usize, } impl<R> UseReactorSubscriptionHandle<R> where R: 'static + Reactor, { /// Send an input to a reactor agent. pub fn send(&self, msg: <R::Scope as ReactorScoped>::Input) { self.bridge.send(msg); } /// Returns whether the current bridge has received a finish message. pub fn finished(&self) -> bool { self.finished } /// Reset the subscription. /// /// This disconnects the old bridge and re-connects the agent with a new bridge. /// Existing outputs stored in the subscription will also be cleared. pub fn reset(&self) { self.bridge.reset(); } } impl<R> Clone for UseReactorSubscriptionHandle<R> where R: 'static + Reactor, { fn clone(&self) -> Self { Self { bridge: self.bridge.clone(), outputs: self.outputs.clone(), ctr: self.ctr, finished: self.finished, } } } impl<R> fmt::Debug for UseReactorSubscriptionHandle<R> where R: 'static + Reactor, <R::Scope as ReactorScoped>::Input: fmt::Debug, <R::Scope as ReactorScoped>::Output: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct(type_name::<Self>()) .field("bridge", &self.bridge) .field("outputs", &self.outputs) .finish() } } impl<R> Deref for UseReactorSubscriptionHandle<R> where R: 'static + Reactor, { type Target = [Rc<<R::Scope as ReactorScoped>::Output>]; fn deref(&self) -> &Self::Target { &self.outputs } } impl<R> PartialEq for UseReactorSubscriptionHandle<R> where R: 'static + Reactor, { fn eq(&self, rhs: &Self) -> bool { self.bridge == rhs.bridge && self.ctr == rhs.ctr } } /// A hook to subscribe to the outputs of a [Reactor] agent. /// /// All outputs sent to current bridge will be collected into a slice. #[hook] pub fn use_reactor_subscription<R>() -> UseReactorSubscriptionHandle<R> where R: 'static + Reactor, { let outputs = use_reducer(OutputsState::<<R::Scope as ReactorScoped>::Output>::default); let bridge = { let outputs = outputs.clone(); use_reactor_bridge::<R, _>(move |output| { outputs.dispatch(match output { ReactorEvent::Output(m) => OutputsAction::Push(m.into()), ReactorEvent::Finished => OutputsAction::Close, }) }) }; { let outputs = outputs.clone(); use_effect_with(bridge.clone(), move |_| { outputs.dispatch(OutputsAction::Reset); || {} }); } UseReactorSubscriptionHandle { bridge, outputs: outputs.inner.clone(), ctr: outputs.ctr, finished: outputs.closed, } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-agent/src/reactor/mod.rs
packages/yew-agent/src/reactor/mod.rs
//! This module contains the reactor agent implementation. //! //! Reactor agents are agents that receive multiple inputs and send multiple outputs over a single //! bridge. A reactor is defined as an async function that takes a [ReactorScope] //! as the argument. //! //! The reactor scope is a stream that produces inputs from the bridge and a //! sink that implements an additional send method to send outputs to the connected bridge. //! When the bridge disconnects, the output stream and input sink will be closed. //! //! # Example //! //! ``` //! # use serde::{Serialize, Deserialize}; //! # #[derive(Serialize, Deserialize)] //! # pub struct ReactorInput {} //! # #[derive(Serialize, Deserialize)] //! # pub struct ReactorOutput {} //! # //! use futures::sink::SinkExt; //! use futures::stream::StreamExt; //! use yew_agent::reactor::{reactor, ReactorScope}; //! #[reactor(MyReactor)] //! pub async fn my_reactor(mut scope: ReactorScope<ReactorInput, ReactorOutput>) { //! while let Some(input) = scope.next().await { //! // handles each input. //! // ... //! # let output = ReactorOutput { /* ... */ }; //! //! // sends output //! if scope.send(output).await.is_err() { //! // sender closed, the bridge is disconnected //! break; //! } //! } //! } //! ``` mod bridge; mod hooks; mod messages; mod provider; mod registrar; mod scope; mod spawner; mod traits; mod worker; pub use bridge::{ReactorBridge, ReactorBridgeSinkError}; pub use hooks::{ use_reactor_bridge, use_reactor_subscription, ReactorEvent, UseReactorBridgeHandle, UseReactorSubscriptionHandle, }; pub use provider::ReactorProvider; pub(crate) use provider::ReactorProviderState; pub use registrar::ReactorRegistrar; pub use scope::{ReactorScope, ReactorScoped}; pub use spawner::ReactorSpawner; pub use traits::Reactor; /// A procedural macro to create reactor agents. pub use yew_agent_macro::reactor;
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-agent/src/reactor/traits.rs
packages/yew-agent/src/reactor/traits.rs
use std::future::Future; use super::scope::ReactorScoped; /// A reactor worker. pub trait Reactor: Future<Output = ()> { /// The Reactor Scope type Scope: ReactorScoped; /// Creates a reactor worker. fn create(scope: Self::Scope) -> Self; }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-agent/src/reactor/provider.rs
packages/yew-agent/src/reactor/provider.rs
use std::any::type_name; use std::cell::RefCell; use std::fmt; use std::rc::Rc; use serde::{Deserialize, Serialize}; use yew::prelude::*; use super::{Reactor, ReactorBridge, ReactorScoped, ReactorSpawner}; use crate::utils::get_next_id; use crate::worker::WorkerProviderProps; use crate::{Bincode, Codec, Reach}; pub(crate) struct ReactorProviderState<T> where T: Reactor + 'static, { id: usize, spawn_bridge_fn: Rc<dyn Fn() -> ReactorBridge<T>>, reach: Reach, held_bridge: Rc<RefCell<Option<ReactorBridge<T>>>>, } impl<T> fmt::Debug for ReactorProviderState<T> where T: Reactor, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(type_name::<Self>()) } } impl<T> ReactorProviderState<T> where T: Reactor, { fn get_held_bridge(&self) -> ReactorBridge<T> { let mut held_bridge = self.held_bridge.borrow_mut(); match held_bridge.as_mut() { Some(m) => m.fork(), None => { let bridge = (self.spawn_bridge_fn)(); *held_bridge = Some(bridge.fork()); bridge } } } /// Creates a bridge, uses "fork" for public agents. pub fn create_bridge(&self) -> ReactorBridge<T> { match self.reach { Reach::Public => { let held_bridge = self.get_held_bridge(); held_bridge.fork() } Reach::Private => (self.spawn_bridge_fn)(), } } } impl<T> Clone for ReactorProviderState<T> where T: Reactor, { fn clone(&self) -> Self { Self { id: self.id, spawn_bridge_fn: self.spawn_bridge_fn.clone(), reach: self.reach, held_bridge: self.held_bridge.clone(), } } } impl<T> PartialEq for ReactorProviderState<T> where T: Reactor, { fn eq(&self, rhs: &Self) -> bool { self.id == rhs.id } } /// The Reactor Agent Provider. /// /// This component provides its children access to a reactor agent. #[component] pub fn ReactorProvider<R, C = Bincode>(props: &WorkerProviderProps) -> Html where R: 'static + Reactor, <<R as Reactor>::Scope as ReactorScoped>::Input: Serialize + for<'de> Deserialize<'de> + 'static, <<R as Reactor>::Scope as ReactorScoped>::Output: Serialize + for<'de> Deserialize<'de> + 'static, C: Codec + 'static, { let WorkerProviderProps { children, path, lazy, module, reach, } = props.clone(); // Creates a spawning function so Codec is can be erased from contexts. let spawn_bridge_fn: Rc<dyn Fn() -> ReactorBridge<R>> = { let path = path.clone(); Rc::new(move || { ReactorSpawner::<R>::new() .as_module(module) .encoding::<C>() .spawn(&path) }) }; let state = { use_memo((path, lazy, reach), move |(_path, lazy, reach)| { let state = ReactorProviderState::<R> { id: get_next_id(), spawn_bridge_fn, reach: *reach, held_bridge: Rc::default(), }; if *reach == Reach::Public && !*lazy { state.get_held_bridge(); } state }) }; html! { <ContextProvider<ReactorProviderState<R>> context={(*state).clone()}> {children} </ContextProvider<ReactorProviderState<R>>> } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-agent/src/reactor/registrar.rs
packages/yew-agent/src/reactor/registrar.rs
use std::fmt; use serde::de::Deserialize; use serde::ser::Serialize; use super::scope::ReactorScoped; use super::traits::Reactor; use super::worker::ReactorWorker; use crate::codec::{Bincode, Codec}; use crate::traits::Registrable; use crate::worker::WorkerRegistrar; /// A registrar for reactor workers. pub struct ReactorRegistrar<R, CODEC = Bincode> where R: Reactor + 'static, CODEC: Codec + 'static, { inner: WorkerRegistrar<ReactorWorker<R>, CODEC>, } impl<R, CODEC> Default for ReactorRegistrar<R, CODEC> where R: Reactor + 'static, CODEC: Codec + 'static, { fn default() -> Self { Self::new() } } impl<R, CODEC> ReactorRegistrar<R, CODEC> where R: Reactor + 'static, CODEC: Codec + 'static, { /// Creates a new reactor registrar. pub fn new() -> Self { Self { inner: ReactorWorker::<R>::registrar().encoding::<CODEC>(), } } /// Sets the encoding. pub fn encoding<C>(&self) -> ReactorRegistrar<R, C> where C: Codec + 'static, { ReactorRegistrar { inner: self.inner.encoding::<C>(), } } /// Registers the worker. pub fn register(&self) where <R::Scope as ReactorScoped>::Input: Serialize + for<'de> Deserialize<'de>, <R::Scope as ReactorScoped>::Output: Serialize + for<'de> Deserialize<'de>, { self.inner.register() } } impl<R, CODEC> fmt::Debug for ReactorRegistrar<R, CODEC> where R: Reactor + 'static, CODEC: Codec + 'static, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("ReactorRegistrar<_>").finish() } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
lapce/lapce
https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/db.rs
lapce-app/src/db.rs
use std::{ path::{Path, PathBuf}, rc::Rc, sync::Arc, }; use anyhow::{Result, anyhow}; use crossbeam_channel::{Sender, unbounded}; use floem::{peniko::kurbo::Vec2, reactive::SignalGet}; use lapce_core::directory::Directory; use lapce_rpc::plugin::VoltID; use sha2::{Digest, Sha256}; use crate::{ app::{AppData, AppInfo}, doc::DocInfo, panel::{data::PanelOrder, kind::PanelKind}, window::{WindowData, WindowInfo}, window_tab::WindowTabData, workspace::{LapceWorkspace, WorkspaceInfo}, }; const APP: &str = "app"; const WINDOW: &str = "window"; const WORKSPACE_INFO: &str = "workspace_info"; const WORKSPACE_FILES: &str = "workspace_files"; const PANEL_ORDERS: &str = "panel_orders"; const DISABLED_VOLTS: &str = "disabled_volts"; const RECENT_WORKSPACES: &str = "recent_workspaces"; pub enum SaveEvent { App(AppInfo), Workspace(LapceWorkspace, WorkspaceInfo), RecentWorkspace(LapceWorkspace), Doc(DocInfo), DisabledVolts(Vec<VoltID>), WorkspaceDisabledVolts(Arc<LapceWorkspace>, Vec<VoltID>), PanelOrder(PanelOrder), } #[derive(Clone)] pub struct LapceDb { folder: PathBuf, workspace_folder: PathBuf, save_tx: Sender<SaveEvent>, } impl LapceDb { pub fn new() -> Result<Self> { let folder = Directory::config_directory() .ok_or_else(|| anyhow!("can't get config directory"))? .join("db"); let workspace_folder = folder.join("workspaces"); if let Err(err) = std::fs::create_dir_all(&workspace_folder) { tracing::error!("{:?}", err); } let (save_tx, save_rx) = unbounded(); let db = Self { save_tx, workspace_folder, folder, }; let local_db = db.clone(); std::thread::Builder::new() .name("SaveEventHandler".to_owned()) .spawn(move || -> Result<()> { loop { let event = save_rx.recv()?; match event { SaveEvent::App(info) => { if let Err(err) = local_db.insert_app_info(info) { tracing::error!("{:?}", err); } } SaveEvent::Workspace(workspace, info) => { if let Err(err) = local_db.insert_workspace(&workspace, &info) { tracing::error!("{:?}", err); } } SaveEvent::RecentWorkspace(workspace) => { if let Err(err) = local_db.insert_recent_workspace(workspace) { tracing::error!("{:?}", err); } } SaveEvent::Doc(info) => { if let Err(err) = local_db.insert_doc(&info) { tracing::error!("{:?}", err); } } SaveEvent::DisabledVolts(volts) => { if let Err(err) = local_db.insert_disabled_volts(volts) { tracing::error!("{:?}", err); } } SaveEvent::WorkspaceDisabledVolts(workspace, volts) => { if let Err(err) = local_db .insert_workspace_disabled_volts(workspace, volts) { tracing::error!("{:?}", err); } } SaveEvent::PanelOrder(order) => { if let Err(err) = local_db.insert_panel_orders(&order) { tracing::error!("{:?}", err); } } } } }) .unwrap(); Ok(db) } pub fn get_disabled_volts(&self) -> Result<Vec<VoltID>> { let volts = std::fs::read_to_string(self.folder.join(DISABLED_VOLTS))?; let volts: Vec<VoltID> = serde_json::from_str(&volts)?; Ok(volts) } pub fn save_disabled_volts(&self, volts: Vec<VoltID>) { if let Err(err) = self.save_tx.send(SaveEvent::DisabledVolts(volts)) { tracing::error!("{:?}", err); } } pub fn save_workspace_disabled_volts( &self, workspace: Arc<LapceWorkspace>, volts: Vec<VoltID>, ) { if let Err(err) = self .save_tx .send(SaveEvent::WorkspaceDisabledVolts(workspace, volts)) { tracing::error!("{:?}", err); } } pub fn insert_disabled_volts(&self, volts: Vec<VoltID>) -> Result<()> { let volts = serde_json::to_string_pretty(&volts)?; std::fs::write(self.folder.join(DISABLED_VOLTS), volts)?; Ok(()) } pub fn insert_workspace_disabled_volts( &self, workspace: Arc<LapceWorkspace>, volts: Vec<VoltID>, ) -> Result<()> { let folder = self .workspace_folder .join(workspace_folder_name(&workspace)); if let Err(err) = std::fs::create_dir_all(&folder) { tracing::error!("{:?}", err); } let volts = serde_json::to_string_pretty(&volts)?; std::fs::write(folder.join(DISABLED_VOLTS), volts)?; Ok(()) } pub fn get_workspace_disabled_volts( &self, workspace: &LapceWorkspace, ) -> Result<Vec<VoltID>> { let folder = self.workspace_folder.join(workspace_folder_name(workspace)); let volts = std::fs::read_to_string(folder.join(DISABLED_VOLTS))?; let volts: Vec<VoltID> = serde_json::from_str(&volts)?; Ok(volts) } pub fn recent_workspaces(&self) -> Result<Vec<LapceWorkspace>> { let workspaces = std::fs::read_to_string(self.folder.join(RECENT_WORKSPACES))?; let workspaces: Vec<LapceWorkspace> = serde_json::from_str(&workspaces)?; Ok(workspaces) } pub fn update_recent_workspace(&self, workspace: &LapceWorkspace) -> Result<()> { if workspace.path.is_none() { return Ok(()); } self.save_tx .send(SaveEvent::RecentWorkspace(workspace.clone()))?; Ok(()) } fn insert_recent_workspace(&self, workspace: LapceWorkspace) -> Result<()> { let mut workspaces = self.recent_workspaces().unwrap_or_default(); let mut exits = false; for w in workspaces.iter_mut() { if w.path == workspace.path && w.kind == workspace.kind { w.last_open = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() .as_secs(); exits = true; break; } } if !exits { let mut workspace = workspace; workspace.last_open = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() .as_secs(); workspaces.push(workspace); } workspaces.sort_by_key(|w| -(w.last_open as i64)); let workspaces = serde_json::to_string_pretty(&workspaces)?; std::fs::write(self.folder.join(RECENT_WORKSPACES), workspaces)?; Ok(()) } pub fn save_window_tab(&self, data: Rc<WindowTabData>) -> Result<()> { let workspace = (*data.workspace).clone(); let workspace_info = data.workspace_info(); self.save_tx .send(SaveEvent::Workspace(workspace, workspace_info))?; // self.insert_unsaved_buffer(main_split)?; Ok(()) } pub fn get_workspace_info( &self, workspace: &LapceWorkspace, ) -> Result<WorkspaceInfo> { let info = std::fs::read_to_string( self.workspace_folder .join(workspace_folder_name(workspace)) .join(WORKSPACE_INFO), )?; let info: WorkspaceInfo = serde_json::from_str(&info)?; Ok(info) } fn insert_workspace( &self, workspace: &LapceWorkspace, info: &WorkspaceInfo, ) -> Result<()> { let folder = self.workspace_folder.join(workspace_folder_name(workspace)); if let Err(err) = std::fs::create_dir_all(&folder) { tracing::error!("{:?}", err); } let workspace_info = serde_json::to_string_pretty(info)?; std::fs::write(folder.join(WORKSPACE_INFO), workspace_info)?; Ok(()) } pub fn save_app(&self, data: &AppData) -> Result<()> { let windows = data.windows.get_untracked(); for (_, window) in &windows { if let Err(err) = self.save_window(window.clone()) { tracing::error!("{:?}", err); } } let info = AppInfo { windows: windows .iter() .map(|(_, window_data)| window_data.info()) .collect(), }; if info.windows.is_empty() { return Ok(()); } self.save_tx.send(SaveEvent::App(info))?; Ok(()) } pub fn insert_app_info(&self, info: AppInfo) -> Result<()> { let info = serde_json::to_string_pretty(&info)?; std::fs::write(self.folder.join(APP), info)?; Ok(()) } pub fn insert_app(&self, data: AppData) -> Result<()> { let windows = data.windows.get_untracked(); if windows.is_empty() { // insert_app is called after window is closed, so we don't want to store it return Ok(()); } for (_, window) in &windows { if let Err(err) = self.insert_window(window.clone()) { tracing::error!("{:?}", err); } } let info = AppInfo { windows: windows .iter() .map(|(_, window_data)| window_data.info()) .collect(), }; self.insert_app_info(info)?; Ok(()) } pub fn get_app(&self) -> Result<AppInfo> { let info = std::fs::read_to_string(self.folder.join(APP))?; let mut info: AppInfo = serde_json::from_str(&info)?; for window in info.windows.iter_mut() { if window.size.width < 10.0 { window.size.width = 800.0; } if window.size.height < 10.0 { window.size.height = 600.0; } } Ok(info) } pub fn get_window(&self) -> Result<WindowInfo> { let info = std::fs::read_to_string(self.folder.join(WINDOW))?; let mut info: WindowInfo = serde_json::from_str(&info)?; if info.size.width < 10.0 { info.size.width = 800.0; } if info.size.height < 10.0 { info.size.height = 600.0; } Ok(info) } pub fn save_window(&self, data: WindowData) -> Result<()> { for (_, window_tab) in data.window_tabs.get_untracked().into_iter() { if let Err(err) = self.save_window_tab(window_tab) { tracing::error!("{:?}", err); } } Ok(()) } pub fn insert_window(&self, data: WindowData) -> Result<()> { for (_, window_tab) in data.window_tabs.get_untracked().into_iter() { if let Err(err) = self.insert_window_tab(window_tab) { tracing::error!("{:?}", err); } } let info = data.info(); let info = serde_json::to_string_pretty(&info)?; std::fs::write(self.folder.join(WINDOW), info)?; Ok(()) } pub fn insert_window_tab(&self, data: Rc<WindowTabData>) -> Result<()> { let workspace = (*data.workspace).clone(); let workspace_info = data.workspace_info(); self.insert_workspace(&workspace, &workspace_info)?; // self.insert_unsaved_buffer(main_split)?; Ok(()) } pub fn get_panel_orders(&self) -> Result<PanelOrder> { let panel_orders = std::fs::read_to_string(self.folder.join(PANEL_ORDERS))?; let mut panel_orders: PanelOrder = serde_json::from_str(&panel_orders)?; use strum::IntoEnumIterator; for kind in PanelKind::iter() { if kind.position(&panel_orders).is_none() { let panels = panel_orders.entry(kind.default_position()).or_default(); panels.push_back(kind); } } Ok(panel_orders) } pub fn save_panel_orders(&self, order: PanelOrder) { if let Err(err) = self.save_tx.send(SaveEvent::PanelOrder(order)) { tracing::error!("{:?}", err); } } fn insert_panel_orders(&self, order: &PanelOrder) -> Result<()> { let info = serde_json::to_string_pretty(order)?; std::fs::write(self.folder.join(PANEL_ORDERS), info)?; Ok(()) } pub fn save_doc_position( &self, workspace: &LapceWorkspace, path: PathBuf, cursor_offset: usize, scroll_offset: Vec2, ) { let info = DocInfo { workspace: workspace.clone(), path, scroll_offset: (scroll_offset.x, scroll_offset.y), cursor_offset, }; if let Err(err) = self.save_tx.send(SaveEvent::Doc(info)) { tracing::error!("{:?}", err); } } fn insert_doc(&self, info: &DocInfo) -> Result<()> { let folder = self .workspace_folder .join(workspace_folder_name(&info.workspace)) .join(WORKSPACE_FILES); if let Err(err) = std::fs::create_dir_all(&folder) { tracing::error!("{:?}", err); } let contents = serde_json::to_string_pretty(info)?; std::fs::write(folder.join(doc_path_name(&info.path)), contents)?; Ok(()) } pub fn get_doc_info( &self, workspace: &LapceWorkspace, path: &Path, ) -> Result<DocInfo> { let folder = self .workspace_folder .join(workspace_folder_name(workspace)) .join(WORKSPACE_FILES); let info = std::fs::read_to_string(folder.join(doc_path_name(path)))?; let info: DocInfo = serde_json::from_str(&info)?; Ok(info) } } fn workspace_folder_name(workspace: &LapceWorkspace) -> String { url::form_urlencoded::Serializer::new(String::new()) .append_key_only(&workspace.to_string()) .finish() } fn doc_path_name(path: &Path) -> String { let mut hasher = Sha256::new(); hasher.update(path.to_string_lossy().as_bytes()); format!("{:x}", hasher.finalize()) }
rust
Apache-2.0
59ce6df700ce4efbe4498a719fe52195e083d2ee
2026-01-04T15:32:17.267102Z
false
lapce/lapce
https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/config.rs
lapce-app/src/config.rs
use std::{ collections::HashMap, path::{Path, PathBuf}, sync::Arc, }; use ::core::slice; use floem::{peniko::Color, prelude::palette::css}; use itertools::Itertools; use lapce_core::directory::Directory; use lapce_proxy::plugin::wasi::find_all_volts; use lapce_rpc::plugin::VoltID; use lsp_types::{CompletionItemKind, SymbolKind}; use once_cell::sync::Lazy; use parking_lot::RwLock; use serde::Deserialize; use strum::VariantNames; use tracing::error; use self::{ color::LapceColor, color_theme::{ColorThemeConfig, ThemeColor, ThemeColorPreference}, core::CoreConfig, editor::{EditorConfig, SCALE_OR_SIZE_LIMIT, WrapStyle}, icon::LapceIcons, icon_theme::IconThemeConfig, svg::SvgStore, terminal::TerminalConfig, ui::UIConfig, }; use crate::workspace::{LapceWorkspace, LapceWorkspaceType}; pub mod color; pub mod color_theme; pub mod core; pub mod editor; pub mod icon; pub mod icon_theme; pub mod svg; pub mod terminal; pub mod ui; pub mod watcher; pub const LOGO: &str = include_str!("../../extra/images/logo.svg"); const DEFAULT_SETTINGS: &str = include_str!("../../defaults/settings.toml"); const DEFAULT_LIGHT_THEME: &str = include_str!("../../defaults/light-theme.toml"); const DEFAULT_DARK_THEME: &str = include_str!("../../defaults/dark-theme.toml"); const DEFAULT_ICON_THEME: &str = include_str!("../../defaults/icon-theme.toml"); static DEFAULT_CONFIG: Lazy<config::Config> = Lazy::new(LapceConfig::default_config); static DEFAULT_LAPCE_CONFIG: Lazy<LapceConfig> = Lazy::new(LapceConfig::default_lapce_config); static DEFAULT_DARK_THEME_CONFIG: Lazy<config::Config> = Lazy::new(|| { config::Config::builder() .add_source(config::File::from_str( DEFAULT_DARK_THEME, config::FileFormat::Toml, )) .build() .unwrap() }); /// The default theme is the dark theme. static DEFAULT_DARK_THEME_COLOR_CONFIG: Lazy<ColorThemeConfig> = Lazy::new(|| { let (_, theme) = LapceConfig::load_color_theme_from_str(DEFAULT_DARK_THEME).unwrap(); theme.get::<ColorThemeConfig>("color-theme") .expect("Failed to load default dark theme. This is likely due to a missing or misnamed field in dark-theme.toml") }); static DEFAULT_ICON_THEME_CONFIG: Lazy<config::Config> = Lazy::new(|| { config::Config::builder() .add_source(config::File::from_str( DEFAULT_ICON_THEME, config::FileFormat::Toml, )) .build() .unwrap() }); static DEFAULT_ICON_THEME_ICON_CONFIG: Lazy<IconThemeConfig> = Lazy::new(|| { DEFAULT_ICON_THEME_CONFIG.get::<IconThemeConfig>("icon-theme") .expect("Failed to load default icon theme. This is likely due to a missing or misnamed field in icon-theme.toml") }); /// Used for creating a `DropdownData` for a setting #[derive(Debug, Clone)] pub struct DropdownInfo { /// The currently selected item. pub active_index: usize, pub items: im::Vector<String>, } #[derive(Debug, Clone, Deserialize, Default)] #[serde(rename_all = "kebab-case")] pub struct LapceConfig { #[serde(skip)] pub id: u64, pub core: CoreConfig, pub ui: UIConfig, pub editor: EditorConfig, pub terminal: TerminalConfig, #[serde(default)] pub color_theme: ColorThemeConfig, #[serde(default)] pub icon_theme: IconThemeConfig, #[serde(flatten)] pub plugins: HashMap<String, HashMap<String, serde_json::Value>>, #[serde(skip)] pub color: ThemeColor, #[serde(skip)] pub available_color_themes: HashMap<String, (String, config::Config)>, #[serde(skip)] pub available_icon_themes: HashMap<String, (String, config::Config, Option<PathBuf>)>, // #[serde(skip)] // tab_layout_info: Arc<RwLock<HashMap<(FontFamily, usize), f64>>>, #[serde(skip)] svg_store: Arc<RwLock<SvgStore>>, /// A list of the themes that are available. This is primarily for populating /// the theme picker, and serves as a cache. #[serde(skip)] color_theme_list: im::Vector<String>, #[serde(skip)] icon_theme_list: im::Vector<String>, /// The couple names for the wrap style #[serde(skip)] wrap_style_list: im::Vector<String>, } impl LapceConfig { pub fn load( workspace: &LapceWorkspace, disabled_volts: &[VoltID], extra_plugin_paths: &[PathBuf], ) -> Self { let config = Self::merge_config(workspace, None, None); let mut lapce_config: LapceConfig = match config.try_deserialize() { Ok(config) => config, Err(error) => { error!("Failed to deserialize configuration file: {error}"); DEFAULT_LAPCE_CONFIG.clone() } }; lapce_config.available_color_themes = Self::load_color_themes(disabled_volts, extra_plugin_paths); lapce_config.available_icon_themes = Self::load_icon_themes(disabled_volts, extra_plugin_paths); lapce_config.resolve_theme(workspace); lapce_config.color_theme_list = lapce_config .available_color_themes .values() .map(|(name, _)| name.clone()) .sorted() .collect(); lapce_config.color_theme_list.sort(); lapce_config.icon_theme_list = lapce_config .available_icon_themes .values() .map(|(name, _, _)| name.clone()) .sorted() .collect(); lapce_config.icon_theme_list.sort(); lapce_config.wrap_style_list = im::vector![ WrapStyle::None.to_string(), WrapStyle::EditorWidth.to_string(), // TODO: WrapStyle::WrapColumn.to_string(), WrapStyle::WrapWidth.to_string() ]; lapce_config.terminal.get_indexed_colors(); lapce_config } fn merge_config( workspace: &LapceWorkspace, color_theme_config: Option<config::Config>, icon_theme_config: Option<config::Config>, ) -> config::Config { let mut config = DEFAULT_CONFIG.clone(); if let Some(theme) = color_theme_config { // TODO: use different color theme basis if the theme declares its color preference // differently config = config::Config::builder() .add_source(config.clone()) .add_source(DEFAULT_DARK_THEME_CONFIG.clone()) .add_source(theme) .build() .unwrap_or_else(|_| config.clone()); } if let Some(theme) = icon_theme_config { config = config::Config::builder() .add_source(config.clone()) .add_source(theme) .build() .unwrap_or_else(|_| config.clone()); } if let Some(path) = Self::settings_file() { config = config::Config::builder() .add_source(config.clone()) .add_source(config::File::from(path.as_path()).required(false)) .build() .unwrap_or_else(|_| config.clone()); } match workspace.kind { LapceWorkspaceType::Local => { if let Some(path) = workspace.path.as_ref() { let path = path.join("./.lapce/settings.toml"); config = config::Config::builder() .add_source(config.clone()) .add_source( config::File::from(path.as_path()).required(false), ) .build() .unwrap_or_else(|_| config.clone()); } } LapceWorkspaceType::RemoteSSH(_) => {} #[cfg(windows)] LapceWorkspaceType::RemoteWSL(_) => {} } config } fn update_id(&mut self) { self.id = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|d| d.as_millis() as u64) .unwrap_or(0); } fn default_config() -> config::Config { config::Config::builder() .add_source(config::File::from_str( DEFAULT_SETTINGS, config::FileFormat::Toml, )) .build() .unwrap() } fn default_lapce_config() -> LapceConfig { let mut default_lapce_config: LapceConfig = DEFAULT_CONFIG.clone().try_deserialize().expect("Failed to deserialize default config, this likely indicates a missing or misnamed field in settings.toml"); default_lapce_config.color_theme = DEFAULT_DARK_THEME_COLOR_CONFIG.clone(); default_lapce_config.icon_theme = DEFAULT_ICON_THEME_ICON_CONFIG.clone(); default_lapce_config.resolve_colors(None); default_lapce_config } fn resolve_theme(&mut self, workspace: &LapceWorkspace) { let default_lapce_config = DEFAULT_LAPCE_CONFIG.clone(); let color_theme_config = self .available_color_themes .get(&self.core.color_theme.to_lowercase()) .map(|(_, config)| config) .unwrap_or(&DEFAULT_DARK_THEME_CONFIG); let icon_theme_config = self .available_icon_themes .get(&self.core.icon_theme.to_lowercase()) .map(|(_, config, _)| config) .unwrap_or(&DEFAULT_ICON_THEME_CONFIG); let icon_theme_path = self .available_icon_themes .get(&self.core.icon_theme.to_lowercase()) .map(|(_, _, path)| path); if let Ok(new) = Self::merge_config( workspace, Some(color_theme_config.clone()), Some(icon_theme_config.clone()), ) .try_deserialize::<LapceConfig>() { self.core = new.core; self.ui = new.ui; self.editor = new.editor; self.terminal = new.terminal; self.terminal.get_indexed_colors(); self.color_theme = new.color_theme; self.icon_theme = new.icon_theme; if let Some(icon_theme_path) = icon_theme_path { self.icon_theme.path = icon_theme_path.clone().unwrap_or_default(); } self.plugins = new.plugins; } self.resolve_colors(Some(&default_lapce_config)); self.update_id(); } fn load_color_themes( disabled_volts: &[VoltID], extra_plugin_paths: &[PathBuf], ) -> HashMap<String, (String, config::Config)> { let mut themes = Self::load_local_themes().unwrap_or_default(); for (key, theme) in Self::load_plugin_color_themes(disabled_volts, extra_plugin_paths) { themes.insert(key, theme); } let (name, theme) = Self::load_color_theme_from_str(DEFAULT_LIGHT_THEME).unwrap(); themes.insert(name.to_lowercase(), (name, theme)); let (name, theme) = Self::load_color_theme_from_str(DEFAULT_DARK_THEME).unwrap(); themes.insert(name.to_lowercase(), (name, theme)); themes } pub fn default_color_theme(&self) -> &ColorThemeConfig { &DEFAULT_DARK_THEME_COLOR_CONFIG } /// Set the active color theme. /// Note that this does not save the config. pub fn set_color_theme(&mut self, workspace: &LapceWorkspace, theme: &str) { self.core.color_theme = theme.to_string(); self.resolve_theme(workspace); } /// Set the active icon theme. /// Note that this does not save the config. pub fn set_icon_theme(&mut self, workspace: &LapceWorkspace, theme: &str) { self.core.icon_theme = theme.to_string(); self.resolve_theme(workspace); } pub fn set_modal(&mut self, _workspace: &LapceWorkspace, modal: bool) { self.core.modal = modal; } /// Get the color by the name from the current theme if it exists /// Otherwise, get the color from the base them /// # Panics /// If the color was not able to be found in either theme, which may be indicative that /// it is misspelled or needs to be added to the base-theme. pub fn color(&self, name: &str) -> Color { match self.color.ui.get(name) { Some(c) => *c, None => { error!("Failed to find key: {name}"); css::HOT_PINK } } } /// Retrieve a color value whose key starts with "style." pub fn style_color(&self, name: &str) -> Option<Color> { self.color.syntax.get(name).copied() } pub fn completion_color( &self, kind: Option<CompletionItemKind>, ) -> Option<Color> { let kind = kind?; let theme_str = match kind { CompletionItemKind::METHOD => "method", CompletionItemKind::FUNCTION => "method", CompletionItemKind::ENUM => "enum", CompletionItemKind::ENUM_MEMBER => "enum-member", CompletionItemKind::CLASS => "class", CompletionItemKind::VARIABLE => "field", CompletionItemKind::STRUCT => "structure", CompletionItemKind::KEYWORD => "keyword", CompletionItemKind::CONSTANT => "constant", CompletionItemKind::PROPERTY => "property", CompletionItemKind::FIELD => "field", CompletionItemKind::INTERFACE => "interface", CompletionItemKind::SNIPPET => "snippet", CompletionItemKind::MODULE => "builtinType", _ => "string", }; self.style_color(theme_str) } fn resolve_colors(&mut self, default_config: Option<&LapceConfig>) { self.color.base = self .color_theme .base .resolve(default_config.map(|c| &c.color_theme.base)); self.color.ui = self .color_theme .resolve_ui_color(&self.color.base, default_config.map(|c| &c.color.ui)); self.color.syntax = self.color_theme.resolve_syntax_color( &self.color.base, default_config.map(|c| &c.color.syntax), ); let fg = self.color(LapceColor::EDITOR_FOREGROUND).to_rgba8(); let bg = self.color(LapceColor::EDITOR_BACKGROUND).to_rgba8(); let is_light = fg.r as u32 + fg.g as u32 + fg.b as u32 > bg.r as u32 + bg.g as u32 + bg.b as u32; let high_contrast = self.color_theme.high_contrast.unwrap_or(false); self.color.color_preference = match (is_light, high_contrast) { (true, true) => ThemeColorPreference::HighContrastLight, (false, true) => ThemeColorPreference::HighContrastDark, (true, false) => ThemeColorPreference::Light, (false, false) => ThemeColorPreference::Dark, }; } fn load_local_themes() -> Option<HashMap<String, (String, config::Config)>> { let themes_folder = Directory::themes_directory()?; let themes: HashMap<String, (String, config::Config)> = std::fs::read_dir(themes_folder) .ok()? .filter_map(|entry| { entry .ok() .and_then(|entry| Self::load_color_theme(&entry.path())) }) .collect(); Some(themes) } fn load_color_theme(path: &Path) -> Option<(String, (String, config::Config))> { if !path.is_file() { return None; } let config = config::Config::builder() .add_source(config::File::from(path)) .build() .ok()?; let table = config.get_table("color-theme").ok()?; let name = table.get("name")?.to_string(); Some((name.to_lowercase(), (name, config))) } /// Load the given theme by its contents. /// Returns `(name, theme fields)` fn load_color_theme_from_str(s: &str) -> Option<(String, config::Config)> { let config = config::Config::builder() .add_source(config::File::from_str(s, config::FileFormat::Toml)) .build() .ok()?; let table = config.get_table("color-theme").ok()?; let name = table.get("name")?.to_string(); Some((name, config)) } fn load_icon_themes( disabled_volts: &[VoltID], extra_plugin_paths: &[PathBuf], ) -> HashMap<String, (String, config::Config, Option<PathBuf>)> { let mut themes = HashMap::new(); for (key, (name, theme, path)) in Self::load_plugin_icon_themes(disabled_volts, extra_plugin_paths) { themes.insert(key, (name, theme, Some(path))); } let (name, theme) = Self::load_icon_theme_from_str(DEFAULT_ICON_THEME).unwrap(); themes.insert(name.to_lowercase(), (name, theme, None)); themes } fn load_icon_theme_from_str(s: &str) -> Option<(String, config::Config)> { let config = config::Config::builder() .add_source(config::File::from_str(s, config::FileFormat::Toml)) .build() .ok()?; let table = config.get_table("icon-theme").ok()?; let name = table.get("name")?.to_string(); Some((name, config)) } fn load_plugin_color_themes( disabled_volts: &[VoltID], extra_plugin_paths: &[PathBuf], ) -> HashMap<String, (String, config::Config)> { let mut themes: HashMap<String, (String, config::Config)> = HashMap::new(); for meta in find_all_volts(extra_plugin_paths) { if disabled_volts.contains(&meta.id()) { continue; } if let Some(plugin_themes) = meta.color_themes.as_ref() { for theme_path in plugin_themes { if let Some((key, theme)) = Self::load_color_theme(&PathBuf::from(theme_path)) { themes.insert(key, theme); } } } } themes } fn load_plugin_icon_themes( disabled_volts: &[VoltID], extra_plugin_paths: &[PathBuf], ) -> HashMap<String, (String, config::Config, PathBuf)> { let mut themes: HashMap<String, (String, config::Config, PathBuf)> = HashMap::new(); for meta in find_all_volts(extra_plugin_paths) { if disabled_volts.contains(&meta.id()) { continue; } if let Some(plugin_themes) = meta.icon_themes.as_ref() { for theme_path in plugin_themes { if let Some((key, theme)) = Self::load_icon_theme(&PathBuf::from(theme_path)) { themes.insert(key, theme); } } } } themes } fn load_icon_theme( path: &Path, ) -> Option<(String, (String, config::Config, PathBuf))> { if !path.is_file() { return None; } let config = config::Config::builder() .add_source(config::File::from(path)) .build() .ok()?; let table = config.get_table("icon-theme").ok()?; let name = table.get("name")?.to_string(); Some(( name.to_lowercase(), (name, config, path.parent().unwrap().to_path_buf()), )) } pub fn export_theme(&self) -> String { let mut table = toml::value::Table::new(); let mut theme = self.color_theme.clone(); theme.name = "".to_string(); table.insert( "color-theme".to_string(), toml::Value::try_from(&theme).unwrap(), ); table.insert("ui".to_string(), toml::Value::try_from(&self.ui).unwrap()); let value = toml::Value::Table(table); toml::to_string_pretty(&value).unwrap() } pub fn settings_file() -> Option<PathBuf> { let path = Directory::config_directory()?.join("settings.toml"); if !path.exists() { if let Err(err) = std::fs::OpenOptions::new() .create_new(true) .write(true) .open(&path) { tracing::error!("{:?}", err); } } Some(path) } pub fn keymaps_file() -> Option<PathBuf> { let path = Directory::config_directory()?.join("keymaps.toml"); if !path.exists() { if let Err(err) = std::fs::OpenOptions::new() .create_new(true) .write(true) .open(&path) { tracing::error!("{:?}", err); } } Some(path) } pub fn ui_svg(&self, icon: &'static str) -> String { let svg = self.icon_theme.ui.get(icon).and_then(|path| { let path = self.icon_theme.path.join(path); self.svg_store.write().get_svg_on_disk(&path) }); svg.unwrap_or_else(|| { let name = DEFAULT_ICON_THEME_ICON_CONFIG.ui.get(icon).unwrap(); self.svg_store.write().get_default_svg(name) }) } pub fn files_svg(&self, paths: &[&Path]) -> (String, Option<Color>) { let svg = self .icon_theme .resolve_path_to_icon(paths) .and_then(|p| self.svg_store.write().get_svg_on_disk(&p)); if let Some(svg) = svg { let color = if self.icon_theme.use_editor_color.unwrap_or(false) { Some(self.color(LapceColor::LAPCE_ICON_ACTIVE)) } else { None }; (svg, color) } else { ( self.ui_svg(LapceIcons::FILE), Some(self.color(LapceColor::LAPCE_ICON_ACTIVE)), ) } } pub fn file_svg(&self, path: &Path) -> (String, Option<Color>) { self.files_svg(slice::from_ref(&path)) } pub fn symbol_svg(&self, kind: &SymbolKind) -> Option<String> { let kind_str = match *kind { SymbolKind::ARRAY => LapceIcons::SYMBOL_KIND_ARRAY, SymbolKind::BOOLEAN => LapceIcons::SYMBOL_KIND_BOOLEAN, SymbolKind::CLASS => LapceIcons::SYMBOL_KIND_CLASS, SymbolKind::CONSTANT => LapceIcons::SYMBOL_KIND_CONSTANT, SymbolKind::ENUM_MEMBER => LapceIcons::SYMBOL_KIND_ENUM_MEMBER, SymbolKind::ENUM => LapceIcons::SYMBOL_KIND_ENUM, SymbolKind::EVENT => LapceIcons::SYMBOL_KIND_EVENT, SymbolKind::FIELD => LapceIcons::SYMBOL_KIND_FIELD, SymbolKind::FILE => LapceIcons::SYMBOL_KIND_FILE, SymbolKind::INTERFACE => LapceIcons::SYMBOL_KIND_INTERFACE, SymbolKind::KEY => LapceIcons::SYMBOL_KIND_KEY, SymbolKind::FUNCTION => LapceIcons::SYMBOL_KIND_FUNCTION, SymbolKind::METHOD => LapceIcons::SYMBOL_KIND_METHOD, SymbolKind::OBJECT => LapceIcons::SYMBOL_KIND_OBJECT, SymbolKind::NAMESPACE => LapceIcons::SYMBOL_KIND_NAMESPACE, SymbolKind::NUMBER => LapceIcons::SYMBOL_KIND_NUMBER, SymbolKind::OPERATOR => LapceIcons::SYMBOL_KIND_OPERATOR, SymbolKind::TYPE_PARAMETER => LapceIcons::SYMBOL_KIND_TYPE_PARAMETER, SymbolKind::PROPERTY => LapceIcons::SYMBOL_KIND_PROPERTY, SymbolKind::STRING => LapceIcons::SYMBOL_KIND_STRING, SymbolKind::STRUCT => LapceIcons::SYMBOL_KIND_STRUCT, SymbolKind::VARIABLE => LapceIcons::SYMBOL_KIND_VARIABLE, _ => return None, }; Some(self.ui_svg(kind_str)) } pub fn symbol_color(&self, kind: &SymbolKind) -> Option<Color> { let theme_str = match *kind { SymbolKind::METHOD => "method", SymbolKind::FUNCTION => "method", SymbolKind::ENUM => "enum", SymbolKind::ENUM_MEMBER => "enum-member", SymbolKind::CLASS => "class", SymbolKind::VARIABLE => "field", SymbolKind::STRUCT => "structure", SymbolKind::CONSTANT => "constant", SymbolKind::PROPERTY => "property", SymbolKind::FIELD => "field", SymbolKind::INTERFACE => "interface", SymbolKind::ARRAY => "", SymbolKind::BOOLEAN => "", SymbolKind::EVENT => "", SymbolKind::FILE => "", SymbolKind::KEY => "", SymbolKind::OBJECT => "", SymbolKind::NAMESPACE => "", SymbolKind::NUMBER => "number", SymbolKind::OPERATOR => "", SymbolKind::TYPE_PARAMETER => "", SymbolKind::STRING => "string", _ => return None, }; self.style_color(theme_str) } pub fn logo_svg(&self) -> String { self.svg_store.read().logo_svg() } /// List of the color themes that are available by their display names. pub fn color_theme_list(&self) -> im::Vector<String> { self.color_theme_list.clone() } /// List of the icon themes that are available by their display names. pub fn icon_theme_list(&self) -> im::Vector<String> { self.icon_theme_list.clone() } pub fn terminal_font_family(&self) -> &str { if self.terminal.font_family.is_empty() { self.editor.font_family.as_str() } else { self.terminal.font_family.as_str() } } pub fn terminal_font_size(&self) -> usize { if self.terminal.font_size > 0 { self.terminal.font_size } else { self.editor.font_size() } } pub fn terminal_line_height(&self) -> usize { let font_size = self.terminal_font_size(); if self.terminal.line_height > 0.0 { let line_height = if self.terminal.line_height < SCALE_OR_SIZE_LIMIT { self.terminal.line_height * font_size as f64 } else { self.terminal.line_height }; // Prevent overlapping lines (line_height.round() as usize).max(font_size) } else { self.editor.line_height() } } pub fn terminal_get_color( &self, color: &alacritty_terminal::vte::ansi::Color, colors: &alacritty_terminal::term::color::Colors, ) -> Color { match color { alacritty_terminal::vte::ansi::Color::Named(color) => { self.terminal_get_named_color(color) } alacritty_terminal::vte::ansi::Color::Spec(rgb) => { Color::from_rgb8(rgb.r, rgb.g, rgb.b) } alacritty_terminal::vte::ansi::Color::Indexed(index) => { if let Some(rgb) = colors[*index as usize] { return Color::from_rgb8(rgb.r, rgb.g, rgb.b); } const NAMED_COLORS: [alacritty_terminal::vte::ansi::NamedColor; 16] = [ alacritty_terminal::vte::ansi::NamedColor::Black, alacritty_terminal::vte::ansi::NamedColor::Red, alacritty_terminal::vte::ansi::NamedColor::Green, alacritty_terminal::vte::ansi::NamedColor::Yellow, alacritty_terminal::vte::ansi::NamedColor::Blue, alacritty_terminal::vte::ansi::NamedColor::Magenta, alacritty_terminal::vte::ansi::NamedColor::Cyan, alacritty_terminal::vte::ansi::NamedColor::White, alacritty_terminal::vte::ansi::NamedColor::BrightBlack, alacritty_terminal::vte::ansi::NamedColor::BrightRed, alacritty_terminal::vte::ansi::NamedColor::BrightGreen, alacritty_terminal::vte::ansi::NamedColor::BrightYellow, alacritty_terminal::vte::ansi::NamedColor::BrightBlue, alacritty_terminal::vte::ansi::NamedColor::BrightMagenta, alacritty_terminal::vte::ansi::NamedColor::BrightCyan, alacritty_terminal::vte::ansi::NamedColor::BrightWhite, ]; if (*index as usize) < NAMED_COLORS.len() { self.terminal_get_named_color(&NAMED_COLORS[*index as usize]) } else { self.terminal.indexed_colors.get(index).cloned().unwrap() } } } } fn terminal_get_named_color( &self, color: &alacritty_terminal::vte::ansi::NamedColor, ) -> Color { let (color, alpha) = match color { alacritty_terminal::vte::ansi::NamedColor::Cursor => { (LapceColor::TERMINAL_CURSOR, 1.0) } alacritty_terminal::vte::ansi::NamedColor::Foreground => { (LapceColor::TERMINAL_FOREGROUND, 1.0) } alacritty_terminal::vte::ansi::NamedColor::Background => { (LapceColor::TERMINAL_BACKGROUND, 1.0) } alacritty_terminal::vte::ansi::NamedColor::Blue => { (LapceColor::TERMINAL_BLUE, 1.0) } alacritty_terminal::vte::ansi::NamedColor::Green => { (LapceColor::TERMINAL_GREEN, 1.0) } alacritty_terminal::vte::ansi::NamedColor::Yellow => { (LapceColor::TERMINAL_YELLOW, 1.0) } alacritty_terminal::vte::ansi::NamedColor::Red => { (LapceColor::TERMINAL_RED, 1.0) } alacritty_terminal::vte::ansi::NamedColor::White => { (LapceColor::TERMINAL_WHITE, 1.0) } alacritty_terminal::vte::ansi::NamedColor::Black => { (LapceColor::TERMINAL_BLACK, 1.0) } alacritty_terminal::vte::ansi::NamedColor::Cyan => { (LapceColor::TERMINAL_CYAN, 1.0) } alacritty_terminal::vte::ansi::NamedColor::Magenta => { (LapceColor::TERMINAL_MAGENTA, 1.0) } alacritty_terminal::vte::ansi::NamedColor::BrightBlue => { (LapceColor::TERMINAL_BRIGHT_BLUE, 1.0) } alacritty_terminal::vte::ansi::NamedColor::BrightGreen => { (LapceColor::TERMINAL_BRIGHT_GREEN, 1.0) } alacritty_terminal::vte::ansi::NamedColor::BrightYellow => { (LapceColor::TERMINAL_BRIGHT_YELLOW, 1.0) } alacritty_terminal::vte::ansi::NamedColor::BrightRed => { (LapceColor::TERMINAL_BRIGHT_RED, 1.0) } alacritty_terminal::vte::ansi::NamedColor::BrightWhite => { (LapceColor::TERMINAL_BRIGHT_WHITE, 1.0) } alacritty_terminal::vte::ansi::NamedColor::BrightBlack => { (LapceColor::TERMINAL_BRIGHT_BLACK, 1.0) } alacritty_terminal::vte::ansi::NamedColor::BrightCyan => { (LapceColor::TERMINAL_BRIGHT_CYAN, 1.0) } alacritty_terminal::vte::ansi::NamedColor::BrightMagenta => { (LapceColor::TERMINAL_BRIGHT_MAGENTA, 1.0) } alacritty_terminal::vte::ansi::NamedColor::BrightForeground => { (LapceColor::TERMINAL_FOREGROUND, 1.0) } alacritty_terminal::vte::ansi::NamedColor::DimBlack => { (LapceColor::TERMINAL_BLACK, 0.66) } alacritty_terminal::vte::ansi::NamedColor::DimRed => { (LapceColor::TERMINAL_RED, 0.66) } alacritty_terminal::vte::ansi::NamedColor::DimGreen => { (LapceColor::TERMINAL_GREEN, 0.66) } alacritty_terminal::vte::ansi::NamedColor::DimYellow => { (LapceColor::TERMINAL_YELLOW, 0.66) } alacritty_terminal::vte::ansi::NamedColor::DimBlue => { (LapceColor::TERMINAL_BLUE, 0.66) } alacritty_terminal::vte::ansi::NamedColor::DimMagenta => { (LapceColor::TERMINAL_MAGENTA, 0.66) } alacritty_terminal::vte::ansi::NamedColor::DimCyan => { (LapceColor::TERMINAL_CYAN, 0.66) } alacritty_terminal::vte::ansi::NamedColor::DimWhite => { (LapceColor::TERMINAL_WHITE, 0.66) } alacritty_terminal::vte::ansi::NamedColor::DimForeground => { (LapceColor::TERMINAL_FOREGROUND, 0.66) } }; self.color(color).multiply_alpha(alpha) } /// Get the dropdown information for the specific setting, used for the settings UI.
rust
Apache-2.0
59ce6df700ce4efbe4498a719fe52195e083d2ee
2026-01-04T15:32:17.267102Z
true
lapce/lapce
https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/app.rs
lapce-app/src/app.rs
#[cfg(target_os = "windows")] use std::os::windows::process::CommandExt; use std::{ io::{BufReader, IsTerminal, Read, Write}, ops::Range, path::PathBuf, process::Stdio, rc::Rc, sync::{ Arc, atomic::AtomicU64, mpsc::{SyncSender, channel, sync_channel}, }, }; use anyhow::{Result, anyhow}; use clap::Parser; use floem::{ IntoView, View, action::show_context_menu, event::{Event, EventListener, EventPropagation}, ext_event::{create_ext_action, create_signal_from_channel}, menu::{Menu, MenuItem}, peniko::{ Color, kurbo::{Point, Rect, Size}, }, prelude::SignalTrack, reactive::{ ReadSignal, RwSignal, Scope, SignalGet, SignalUpdate, SignalWith, create_effect, create_memo, create_rw_signal, provide_context, use_context, }, style::{ AlignItems, CursorStyle, Display, FlexDirection, JustifyContent, Position, Style, }, taffy::{ Line, style_helpers::{self, auto, fr}, }, text::{Style as FontStyle, Weight}, unit::PxPctAuto, views::{ Decorators, VirtualVector, clip, container, drag_resize_window_area, drag_window_area, dyn_stack, editor::{core::register::Clipboard, text::SystemClipboard}, empty, label, rich_text, scroll::{PropagatePointerWheel, VerticalScrollAsHorizontal, scroll}, stack, svg, tab, text, tooltip, virtual_stack, }, window::{ResizeDirection, WindowConfig, WindowId}, }; use lapce_core::{ command::{EditCommand, FocusCommand}, directory::Directory, meta, syntax::{Syntax, highlight::reset_highlight_configs}, }; use lapce_rpc::{ RpcMessage, core::{CoreMessage, CoreNotification}, file::PathObject, }; use lsp_types::{CompletionItemKind, MessageType, ShowMessageParams}; use notify::Watcher; use serde::{Deserialize, Serialize}; use tracing_subscriber::{filter::Targets, reload::Handle}; use crate::{ about, alert, code_action::CodeActionStatus, command::{ CommandKind, InternalCommand, LapceCommand, LapceWorkbenchCommand, WindowCommand, }, config::{ LapceConfig, color::LapceColor, icon::LapceIcons, ui::TabSeparatorHeight, watcher::ConfigWatcher, }, db::LapceDb, debug::RunDebugMode, editor::{ diff::diff_show_more_section_view, location::{EditorLocation, EditorPosition}, view::editor_container_view, }, editor_tab::{EditorTabChild, EditorTabData}, focus_text::focus_text, id::{EditorTabId, SplitId}, keymap::keymap_view, keypress::keymap::KeyMap, listener::Listener, main_split::{ SplitContent, SplitData, SplitDirection, SplitMoveDirection, TabCloseKind, }, markdown::MarkdownContent, palette::{ PaletteStatus, item::{PaletteItem, PaletteItemContent}, }, panel::{position::PanelContainerPosition, view::panel_container_view}, plugin::{PluginData, plugin_info_view}, settings::{settings_view, theme_color_settings_view}, status::status, text_input::TextInputBuilder, title::{title, window_controls_view}, tracing::*, update::ReleaseInfo, window::{TabsInfo, WindowData, WindowInfo}, window_tab::{Focus, WindowTabData}, workspace::{LapceWorkspace, LapceWorkspaceType}, }; mod grammars; mod logging; #[derive(Parser)] #[clap(name = "Lapce")] #[clap(version=meta::VERSION)] #[derive(Debug)] struct Cli { /// Launch new window even if Lapce is already running #[clap(short, long, action)] new: bool, /// Don't return instantly when opened in a terminal #[clap(short, long, action)] wait: bool, /// Path(s) to plugins to load. /// This is primarily used for plugin development to make it easier to test changes to the /// plugin without needing to copy the plugin to the plugins directory. /// This will cause any plugin with the same author & name to not run. #[clap(long, action)] plugin_path: Vec<PathBuf>, /// Paths to file(s) and/or folder(s) to open. /// When path is a file (that exists or not), /// it accepts `path:line:column` syntax /// to specify line and column at which it should open the file #[clap(value_parser = lapce_proxy::cli::parse_file_line_column)] #[clap(value_hint = clap::ValueHint::AnyPath)] paths: Vec<PathObject>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AppInfo { pub windows: Vec<WindowInfo>, } #[derive(Clone)] pub enum AppCommand { SaveApp, NewWindow { folder: Option<PathBuf> }, CloseWindow(WindowId), WindowGotFocus(WindowId), WindowClosed(WindowId), } #[derive(Clone)] pub struct AppData { pub windows: RwSignal<im::HashMap<WindowId, WindowData>>, pub active_window: RwSignal<WindowId>, pub window_scale: RwSignal<f64>, pub app_command: Listener<AppCommand>, pub app_terminated: RwSignal<bool>, /// The latest release information pub latest_release: RwSignal<Arc<Option<ReleaseInfo>>>, pub watcher: Arc<notify::RecommendedWatcher>, pub tracing_handle: Handle<Targets>, pub config: RwSignal<Arc<LapceConfig>>, /// Paths to extra plugins to load pub plugin_paths: Arc<Vec<PathBuf>>, } impl AppData { pub fn reload_config(&self) { let config = LapceConfig::load(&LapceWorkspace::default(), &[], &self.plugin_paths); self.config.set(Arc::new(config)); let windows = self.windows.get_untracked(); for (_, window) in windows { window.reload_config(); } } pub fn active_window_tab(&self) -> Option<Rc<WindowTabData>> { if let Some(window) = self.active_window() { return window.active_window_tab(); } None } fn active_window(&self) -> Option<WindowData> { let windows = self.windows.get_untracked(); let active_window = self.active_window.get_untracked(); windows .get(&active_window) .cloned() .or_else(|| windows.iter().next().map(|(_, window)| window.clone())) } fn default_window_config(&self) -> WindowConfig { WindowConfig::default() .apply_default_theme(false) .title("Lapce") } pub fn new_window(&self, folder: Option<PathBuf>) { let config = self .active_window() .map(|window| { self.default_window_config() .size(window.common.size.get_untracked()) .position(window.position.get_untracked() + (50.0, 50.0)) }) .or_else(|| { let db: Arc<LapceDb> = use_context().unwrap(); db.get_window().ok().map(|info| { self.default_window_config() .size(info.size) .position(info.pos) }) }) .unwrap_or_else(|| { self.default_window_config().size(Size::new(800.0, 600.0)) }); let config = if cfg!(target_os = "macos") || self.config.get_untracked().core.custom_titlebar { config.show_titlebar(false) } else { config }; let workspace = LapceWorkspace { path: folder, ..Default::default() }; let app_data = self.clone(); floem::new_window( move |window_id| { app_data.app_view( window_id, WindowInfo { size: Size::ZERO, pos: Point::ZERO, maximised: false, tabs: TabsInfo { active_tab: 0, workspaces: vec![workspace], }, }, vec![], ) }, Some(config), ); } pub fn run_app_command(&self, cmd: AppCommand) { match cmd { AppCommand::SaveApp => { let db: Arc<LapceDb> = use_context().unwrap(); if let Err(err) = db.save_app(self) { tracing::error!("{:?}", err); } } AppCommand::WindowClosed(window_id) => { if self.app_terminated.get_untracked() { return; } let db: Arc<LapceDb> = use_context().unwrap(); if self.windows.with_untracked(|w| w.len()) == 1 { if let Err(err) = db.insert_app(self.clone()) { tracing::error!("{:?}", err); } } let window_data = self .windows .try_update(|windows| windows.remove(&window_id)) .unwrap(); if let Some(window_data) = window_data { window_data.scope.dispose(); } if let Err(err) = db.save_app(self) { tracing::error!("{:?}", err); } } AppCommand::CloseWindow(window_id) => { floem::close_window(window_id); } AppCommand::NewWindow { folder } => { self.new_window(folder); } AppCommand::WindowGotFocus(window_id) => { self.active_window.set(window_id); } } } fn create_windows( &self, db: Arc<LapceDb>, paths: Vec<PathObject>, ) -> floem::Application { let mut app = floem::Application::new(); let mut inital_windows = 0; // Split user input into known existing directors and // file paths that exist or not let (dirs, files): (Vec<&PathObject>, Vec<&PathObject>) = paths.iter().partition(|p| p.is_dir); let files: Vec<PathObject> = files.into_iter().cloned().collect(); let mut files = if files.is_empty() { None } else { Some(files) }; if !dirs.is_empty() { // There were directories specified, so we'll load those as windows // Use the last opened window's size and position as the default let (size, mut pos) = db .get_window() .map(|i| (i.size, i.pos)) .unwrap_or_else(|_| (Size::new(800.0, 600.0), Point::new(0.0, 0.0))); for dir in dirs { #[cfg(windows)] let workspace_type = if !std::env::var("WSL_DISTRO_NAME") .unwrap_or_default() .is_empty() || !std::env::var("WSL_INTEROP").unwrap_or_default().is_empty() { LapceWorkspaceType::RemoteWSL(crate::workspace::WslHost { host: String::new(), }) } else { LapceWorkspaceType::Local }; #[cfg(not(windows))] let workspace_type = LapceWorkspaceType::Local; let info = WindowInfo { size, pos, maximised: false, tabs: TabsInfo { active_tab: 0, workspaces: vec![LapceWorkspace { kind: workspace_type, path: Some(dir.path.to_owned()), last_open: 0, }], }, }; pos += (50.0, 50.0); let config = self .default_window_config() .size(info.size) .position(info.pos); let config = if cfg!(target_os = "macos") || self.config.get_untracked().core.custom_titlebar { config.show_titlebar(false) } else { config }; let app_data = self.clone(); let files = files.take().unwrap_or_default(); app = app.window( move |window_id| app_data.app_view(window_id, info, files), Some(config), ); inital_windows += 1; } } else if files.is_none() { // There were no dirs and no files specified, so we'll load the last windows match db.get_app() { Ok(app_info) => { for info in app_info.windows { let config = self .default_window_config() .size(info.size) .position(info.pos); let config = if cfg!(target_os = "macos") || self.config.get_untracked().core.custom_titlebar { config.show_titlebar(false) } else { config }; let app_data = self.clone(); app = app.window( move |window_id| { app_data.app_view(window_id, info, vec![]) }, Some(config), ); inital_windows += 1; } } Err(err) => { tracing::error!("{:?}", err); } } } if inital_windows == 0 { let mut info = db.get_window().unwrap_or_else(|_| WindowInfo { size: Size::new(800.0, 600.0), pos: Point::ZERO, maximised: false, tabs: TabsInfo { active_tab: 0, workspaces: vec![LapceWorkspace::default()], }, }); info.tabs = TabsInfo { active_tab: 0, workspaces: vec![LapceWorkspace::default()], }; let config = self .default_window_config() .size(info.size) .position(info.pos); let config = if cfg!(target_os = "macos") || self.config.get_untracked().core.custom_titlebar { config.show_titlebar(false) } else { config }; let app_data = self.clone(); app = app.window( move |window_id| { app_data.app_view( window_id, info, files.take().unwrap_or_default(), ) }, Some(config), ); } app } fn app_view( &self, window_id: WindowId, info: WindowInfo, files: Vec<PathObject>, ) -> impl View + use<> { let app_view_id = create_rw_signal(floem::ViewId::new()); let window_data = WindowData::new( window_id, app_view_id, info, self.window_scale, self.latest_release.read_only(), self.plugin_paths.clone(), self.app_command, ); { let cur_window_tab = window_data.active.get_untracked(); let (_, window_tab) = &window_data.window_tabs.get_untracked()[cur_window_tab]; for file in files { let position = file.linecol.map(|pos| { EditorPosition::Position(lsp_types::Position { line: pos.line.saturating_sub(1) as u32, character: pos.column.saturating_sub(1) as u32, }) }); window_tab.run_internal_command(InternalCommand::GoToLocation { location: EditorLocation { path: file.path.clone(), position, scroll_offset: None, // Create a new editor for the file, so we don't change any current unconfirmed // editor ignore_unconfirmed: true, same_editor_tab: false, }, }); } } self.windows.update(|windows| { windows.insert(window_id, window_data.clone()); }); let window_size = window_data.common.size; let position = window_data.position; let window_scale = window_data.window_scale; let app_command = window_data.app_command; let config = window_data.config; // The KeyDown and PointerDown event handlers both need ownership of a WindowData object. let key_down_window_data = window_data.clone(); let view = stack(( workspace_tab_header(window_data.clone()), window(window_data.clone()), stack(( drag_resize_window_area(ResizeDirection::West, empty()).style(|s| { s.absolute().width(4.0).height_full().pointer_events_auto() }), drag_resize_window_area(ResizeDirection::North, empty()).style( |s| s.absolute().width_full().height(4.0).pointer_events_auto(), ), drag_resize_window_area(ResizeDirection::East, empty()).style( move |s| { s.absolute() .margin_left(window_size.get().width as f32 - 4.0) .width(4.0) .height_full() .pointer_events_auto() }, ), drag_resize_window_area(ResizeDirection::South, empty()).style( move |s| { s.absolute() .margin_top(window_size.get().height as f32 - 4.0) .width_full() .height(4.0) .pointer_events_auto() }, ), drag_resize_window_area(ResizeDirection::NorthWest, empty()).style( |s| s.absolute().width(20.0).height(4.0).pointer_events_auto(), ), drag_resize_window_area(ResizeDirection::NorthWest, empty()).style( |s| s.absolute().width(4.0).height(20.0).pointer_events_auto(), ), drag_resize_window_area(ResizeDirection::NorthEast, empty()).style( move |s| { s.absolute() .margin_left(window_size.get().width as f32 - 20.0) .width(20.0) .height(4.0) .pointer_events_auto() }, ), drag_resize_window_area(ResizeDirection::NorthEast, empty()).style( move |s| { s.absolute() .margin_left(window_size.get().width as f32 - 4.0) .width(4.0) .height(20.0) .pointer_events_auto() }, ), drag_resize_window_area(ResizeDirection::SouthWest, empty()).style( move |s| { s.absolute() .margin_top(window_size.get().height as f32 - 4.0) .width(20.0) .height(4.0) .pointer_events_auto() }, ), drag_resize_window_area(ResizeDirection::SouthWest, empty()).style( move |s| { s.absolute() .margin_top(window_size.get().height as f32 - 20.0) .width(4.0) .height(20.0) .pointer_events_auto() }, ), drag_resize_window_area(ResizeDirection::SouthEast, empty()).style( move |s| { s.absolute() .margin_left(window_size.get().width as f32 - 20.0) .margin_top(window_size.get().height as f32 - 4.0) .width(20.0) .height(4.0) .pointer_events_auto() }, ), drag_resize_window_area(ResizeDirection::SouthEast, empty()).style( move |s| { s.absolute() .margin_left(window_size.get().width as f32 - 4.0) .margin_top(window_size.get().height as f32 - 20.0) .width(4.0) .height(20.0) .pointer_events_auto() }, ), )) .debug_name("Drag Resize Areas") .style(move |s| { s.absolute() .size_full() .apply_if( cfg!(target_os = "macos") || !config.get_untracked().core.custom_titlebar, |s| s.hide(), ) .pointer_events_none() }), )) .style(|s| s.flex_col().size_full()); let view_id = view.id(); app_view_id.set(view_id); view_id.request_focus(); view.window_scale(move || window_scale.get()) .keyboard_navigable() .on_event(EventListener::KeyDown, move |event| { if let Event::KeyDown(key_event) = event { if key_down_window_data.key_down(key_event) { view_id.request_focus(); } EventPropagation::Stop } else { EventPropagation::Continue } }) .on_event(EventListener::PointerDown, { let window_data = window_data.clone(); move |event| { if let Event::PointerDown(pointer_event) = event { window_data.key_down(pointer_event); EventPropagation::Stop } else { EventPropagation::Continue } } }) .on_event_stop(EventListener::WindowResized, move |event| { if let Event::WindowResized(size) = event { window_size.set(*size); } }) .on_event_stop(EventListener::WindowMoved, move |event| { if let Event::WindowMoved(point) = event { position.set(*point); } }) .on_event_stop(EventListener::WindowGotFocus, move |_| { app_command.send(AppCommand::WindowGotFocus(window_id)); }) .on_event_stop(EventListener::WindowClosed, move |_| { app_command.send(AppCommand::WindowClosed(window_id)); }) .on_event_stop(EventListener::DroppedFile, move |event: &Event| { if let Event::DroppedFile(file) = event { if file.path.is_dir() { app_command.send(AppCommand::NewWindow { folder: Some(file.path.clone()), }); } else if let Some(win_tab_data) = window_data.active_window_tab() { win_tab_data.common.internal_command.send( InternalCommand::GoToLocation { location: EditorLocation { path: file.path.clone(), position: None, scroll_offset: None, ignore_unconfirmed: false, same_editor_tab: false, }, }, ) } } }) .debug_name("App View") } } /// The top bar of an Editor tab. Includes the tab forward/back buttons, the tab scroll bar and the new split and tab close all button. fn editor_tab_header( window_tab_data: Rc<WindowTabData>, active_editor_tab: ReadSignal<Option<EditorTabId>>, editor_tab: RwSignal<EditorTabData>, dragging: RwSignal<Option<(RwSignal<usize>, EditorTabId)>>, ) -> impl View { let main_split = window_tab_data.main_split.clone(); let plugin = window_tab_data.plugin.clone(); let editors = window_tab_data.main_split.editors; let diff_editors = window_tab_data.main_split.diff_editors; let focus = window_tab_data.common.focus; let config = window_tab_data.common.config; let internal_command = window_tab_data.common.internal_command; let workbench_command = window_tab_data.common.workbench_command; let editor_tab_id = editor_tab.with_untracked(|editor_tab| editor_tab.editor_tab_id); let editor_tab_active = create_memo(move |_| editor_tab.with(|editor_tab| editor_tab.active)); let items = move || { let editor_tab = editor_tab.get(); for (i, (index, _, _)) in editor_tab.children.iter().enumerate() { if index.get_untracked() != i { index.set(i); } } editor_tab.children }; let key = |(_, _, child): &(RwSignal<usize>, RwSignal<Rect>, EditorTabChild)| { child.id() }; let is_focused = move || { if let Focus::Workbench = focus.get() { editor_tab.with_untracked(|e| Some(e.editor_tab_id)) == active_editor_tab.get() } else { false } }; let view_fn = move |(i, layout_rect, child): ( RwSignal<usize>, RwSignal<Rect>, EditorTabChild, )| { let local_child = child.clone(); let child_for_close = child.clone(); let child_for_mouse_close = child.clone(); let child_for_mouse_close_2 = child.clone(); let main_split = main_split.clone(); let plugin = plugin.clone(); let child_view = { let info = child.view_info(editors, diff_editors, plugin, config); let hovered = create_rw_signal(false); use crate::config::ui::TabCloseButton; let tab_icon = container({ svg("") .update_value(move || info.with(|info| info.icon.clone())) .style(move |s| { let config = config.get(); let size = config.ui.icon_size() as f32; s.size(size, size) .apply_opt(info.with(|info| info.color), |s, c| { s.color(c) }) .apply_if( !info.with(|info| info.is_pristine) && config.ui.tab_close_button == TabCloseButton::Off, |s| s.color(config.color(LapceColor::LAPCE_WARN)), ) }) }) .style(|s| s.padding(4.)); let tab_content = tooltip( label(move || info.with(|info| info.name.clone())).style(move |s| { s.apply_if( !info .with(|info| info.confirmed) .map(|confirmed| confirmed.get()) .unwrap_or(true), |s| s.font_style(FontStyle::Italic), ) .selectable(false) }), move || { tooltip_tip( config, text(info.with(|info| { info.path .clone() .map(|path| path.display().to_string()) .unwrap_or("local".to_string()) })), ) }, ); let tab_close_button = clickable_icon( move || { if hovered.get() || info.with(|info| info.is_pristine) { LapceIcons::CLOSE } else { LapceIcons::UNSAVED } }, move || { let editor_tab_id = editor_tab.with_untracked(|t| t.editor_tab_id); internal_command.send(InternalCommand::EditorTabChildClose { editor_tab_id, child: child_for_close.clone(), }); }, || false, || false, || "Close", config, ) .on_event_stop(EventListener::PointerDown, |_| {}) .on_event_stop(EventListener::PointerEnter, move |_| { hovered.set(true); }) .on_event_stop(EventListener::PointerLeave, move |_| { hovered.set(false); }); stack(( tab_icon.style(move |s| { let tab_close_button = config.get().ui.tab_close_button; s.apply_if(tab_close_button == TabCloseButton::Left, |s| { s.grid_column(Line { start: style_helpers::line(3), end: style_helpers::span(1), }) }) }), tab_content.style(move |s| { let tab_close_button = config.get().ui.tab_close_button; s.apply_if(tab_close_button == TabCloseButton::Left, |s| { s.grid_column(Line { start: style_helpers::line(2), end: style_helpers::span(1), }) }) .apply_if(tab_close_button == TabCloseButton::Off, |s| { s.padding_right(4.) }) }), tab_close_button.style(move |s| { let tab_close_button = config.get().ui.tab_close_button; s.apply_if(tab_close_button == TabCloseButton::Left, |s| { s.grid_column(Line { start: style_helpers::line(1), end: style_helpers::span(1), }) }) .apply_if(tab_close_button == TabCloseButton::Off, |s| s.hide()) }), )) .style(move |s| { s.items_center() .justify_center() .border_left(if i.get() == 0 { 1.0 } else { 0.0 }) .border_right(1.0) .border_color(config.get().color(LapceColor::LAPCE_BORDER)) .padding_horiz(6.) .gap(6.) .grid() .grid_template_columns(vec![auto(), fr(1.), auto()]) .apply_if( config.get().ui.tab_separator_height == TabSeparatorHeight::Full, |s| s.height_full(), ) }) }; let confirmed = match local_child { EditorTabChild::Editor(editor_id) => { editors.editor_untracked(editor_id).map(|e| e.confirmed) } EditorTabChild::DiffEditor(diff_editor_id) => diff_editors .with_untracked(|diff_editors| { diff_editors .get(&diff_editor_id) .map(|diff_editor_data| diff_editor_data.confirmed) }), _ => None,
rust
Apache-2.0
59ce6df700ce4efbe4498a719fe52195e083d2ee
2026-01-04T15:32:17.267102Z
true
lapce/lapce
https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/editor_tab.rs
lapce-app/src/editor_tab.rs
use std::{ path::{Path, PathBuf}, rc::Rc, sync::Arc, }; use floem::{ peniko::{ Color, kurbo::{Point, Rect}, }, reactive::{ Memo, ReadSignal, RwSignal, Scope, SignalGet, SignalUpdate, SignalWith, create_memo, create_rw_signal, }, views::editor::id::EditorId, }; use lapce_rpc::plugin::VoltID; use serde::{Deserialize, Serialize}; use crate::{ config::{LapceConfig, color::LapceColor, icon::LapceIcons}, doc::{Doc, DocContent}, editor::{ EditorData, EditorInfo, diff::{DiffEditorData, DiffEditorInfo}, location::EditorLocation, }, id::{ DiffEditorId, EditorTabId, KeymapId, SettingsId, SplitId, ThemeColorSettingsId, VoltViewId, }, main_split::{Editors, MainSplitData}, plugin::PluginData, window_tab::WindowTabData, }; #[derive(Clone, Serialize, Deserialize)] pub enum EditorTabChildInfo { Editor(EditorInfo), DiffEditor(DiffEditorInfo), Settings, ThemeColorSettings, Keymap, Volt(VoltID), } impl EditorTabChildInfo { pub fn to_data( &self, data: MainSplitData, editor_tab_id: EditorTabId, ) -> EditorTabChild { match &self { EditorTabChildInfo::Editor(editor_info) => { let editor_id = editor_info.to_data(data, editor_tab_id); EditorTabChild::Editor(editor_id) } EditorTabChildInfo::DiffEditor(diff_editor_info) => { let diff_editor_data = diff_editor_info.to_data(data, editor_tab_id); EditorTabChild::DiffEditor(diff_editor_data.id) } EditorTabChildInfo::Settings => { EditorTabChild::Settings(SettingsId::next()) } EditorTabChildInfo::ThemeColorSettings => { EditorTabChild::ThemeColorSettings(ThemeColorSettingsId::next()) } EditorTabChildInfo::Keymap => EditorTabChild::Keymap(KeymapId::next()), EditorTabChildInfo::Volt(id) => { EditorTabChild::Volt(VoltViewId::next(), id.to_owned()) } } } } #[derive(Clone, Serialize, Deserialize)] pub struct EditorTabInfo { pub active: usize, pub is_focus: bool, pub children: Vec<EditorTabChildInfo>, } impl EditorTabInfo { pub fn to_data( &self, data: MainSplitData, split: SplitId, ) -> RwSignal<EditorTabData> { let editor_tab_id = EditorTabId::next(); let editor_tab_data = { let cx = data.scope.create_child(); let editor_tab_data = EditorTabData { scope: cx, editor_tab_id, split, active: self.active, children: self .children .iter() .map(|child| { ( cx.create_rw_signal(0), cx.create_rw_signal(Rect::ZERO), child.to_data(data.clone(), editor_tab_id), ) }) .collect(), layout_rect: Rect::ZERO, window_origin: Point::ZERO, locations: cx.create_rw_signal(im::Vector::new()), current_location: cx.create_rw_signal(0), }; cx.create_rw_signal(editor_tab_data) }; if self.is_focus { data.active_editor_tab.set(Some(editor_tab_id)); } data.editor_tabs.update(|editor_tabs| { editor_tabs.insert(editor_tab_id, editor_tab_data); }); editor_tab_data } } pub enum EditorTabChildSource { Editor { path: PathBuf, doc: Rc<Doc> }, DiffEditor { left: Rc<Doc>, right: Rc<Doc> }, NewFileEditor, Settings, ThemeColorSettings, Keymap, Volt(VoltID), } #[derive(Clone, Debug, PartialEq, Eq)] pub enum EditorTabChild { Editor(EditorId), DiffEditor(DiffEditorId), Settings(SettingsId), ThemeColorSettings(ThemeColorSettingsId), Keymap(KeymapId), Volt(VoltViewId, VoltID), } #[derive(PartialEq)] pub struct EditorTabChildViewInfo { pub icon: String, pub color: Option<Color>, pub name: String, pub path: Option<PathBuf>, pub confirmed: Option<RwSignal<bool>>, pub is_pristine: bool, } impl EditorTabChild { pub fn id(&self) -> u64 { match self { EditorTabChild::Editor(id) => id.to_raw(), EditorTabChild::DiffEditor(id) => id.to_raw(), EditorTabChild::Settings(id) => id.to_raw(), EditorTabChild::ThemeColorSettings(id) => id.to_raw(), EditorTabChild::Keymap(id) => id.to_raw(), EditorTabChild::Volt(id, _) => id.to_raw(), } } pub fn is_settings(&self) -> bool { matches!(self, EditorTabChild::Settings(_)) } pub fn child_info(&self, data: &WindowTabData) -> EditorTabChildInfo { match &self { EditorTabChild::Editor(editor_id) => { let editor_data = data .main_split .editors .editor_untracked(*editor_id) .unwrap(); EditorTabChildInfo::Editor(editor_data.editor_info(data)) } EditorTabChild::DiffEditor(diff_editor_id) => { let diff_editor_data = data .main_split .diff_editors .get_untracked() .get(diff_editor_id) .cloned() .unwrap(); EditorTabChildInfo::DiffEditor(diff_editor_data.diff_editor_info()) } EditorTabChild::Settings(_) => EditorTabChildInfo::Settings, EditorTabChild::ThemeColorSettings(_) => { EditorTabChildInfo::ThemeColorSettings } EditorTabChild::Keymap(_) => EditorTabChildInfo::Keymap, EditorTabChild::Volt(_, id) => EditorTabChildInfo::Volt(id.to_owned()), } } pub fn view_info( &self, editors: Editors, diff_editors: RwSignal<im::HashMap<DiffEditorId, DiffEditorData>>, plugin: PluginData, config: ReadSignal<Arc<LapceConfig>>, ) -> Memo<EditorTabChildViewInfo> { match self.clone() { EditorTabChild::Editor(editor_id) => create_memo(move |_| { let config = config.get(); let editor_data = editors.editor(editor_id); let path = if let Some(editor_data) = editor_data { let doc = editor_data.doc_signal().get(); let (content, is_pristine, confirmed) = ( doc.content.get(), doc.buffer.with(|b| b.is_pristine()), editor_data.confirmed, ); match content { DocContent::File { path, .. } => { Some((path, confirmed, is_pristine)) } DocContent::Local => None, DocContent::History(_) => None, DocContent::Scratch { name, .. } => { Some((PathBuf::from(name), confirmed, is_pristine)) } } } else { None }; let (icon, color, name, confirmed, is_pristine) = match path { Some((ref path, confirmed, is_pritine)) => { let (svg, color) = config.file_svg(path); ( svg, color, path.file_name() .unwrap_or_default() .to_string_lossy() .into_owned(), confirmed, is_pritine, ) } None => ( config.ui_svg(LapceIcons::FILE), Some(config.color(LapceColor::LAPCE_ICON_ACTIVE)), "local".to_string(), create_rw_signal(true), true, ), }; EditorTabChildViewInfo { icon, color, name, path: path.map(|opt| opt.0), confirmed: Some(confirmed), is_pristine, } }), EditorTabChild::DiffEditor(diff_editor_id) => create_memo(move |_| { let config = config.get(); let diff_editor_data = diff_editors .with(|diff_editors| diff_editors.get(&diff_editor_id).cloned()); let confirmed = diff_editor_data.as_ref().map(|d| d.confirmed); let info = diff_editor_data .map(|diff_editor_data| { [diff_editor_data.left, diff_editor_data.right].map(|data| { let (content, is_pristine) = data.doc_signal().with(|doc| { ( doc.content.get(), doc.buffer.with(|b| b.is_pristine()), ) }); match content { DocContent::File { path, .. } => { Some((path, is_pristine)) } DocContent::Local => None, DocContent::History(_) => None, DocContent::Scratch { name, .. } => { Some((PathBuf::from(name), is_pristine)) } } }) }) .unwrap_or([None, None]); let (icon, color, path, is_pristine) = match info { [Some((path, is_pristine)), None] | [None, Some((path, is_pristine))] => { let (svg, color) = config.file_svg(&path); ( svg, color, format!( "{} (Diff)", path.file_name() .unwrap_or_default() .to_string_lossy() ), is_pristine, ) } [ Some((left_path, left_is_pristine)), Some((right_path, right_is_pristine)), ] => { let (svg, color) = config.files_svg(&[&left_path, &right_path]); let [left_file_name, right_file_name] = [&left_path, &right_path].map(|path| { path.file_name() .unwrap_or_default() .to_string_lossy() }); ( svg, color, format!("{left_file_name} - {right_file_name} (Diff)"), left_is_pristine && right_is_pristine, ) } [None, None] => ( config.ui_svg(LapceIcons::FILE), Some(config.color(LapceColor::LAPCE_ICON_ACTIVE)), "local".to_string(), true, ), }; EditorTabChildViewInfo { icon, color, name: path, path: None, confirmed, is_pristine, } }), EditorTabChild::Settings(_) => create_memo(move |_| { let config = config.get(); EditorTabChildViewInfo { icon: config.ui_svg(LapceIcons::SETTINGS), color: Some(config.color(LapceColor::LAPCE_ICON_ACTIVE)), name: "Settings".to_string(), path: None, confirmed: None, is_pristine: true, } }), EditorTabChild::ThemeColorSettings(_) => create_memo(move |_| { let config = config.get(); EditorTabChildViewInfo { icon: config.ui_svg(LapceIcons::SYMBOL_COLOR), color: Some(config.color(LapceColor::LAPCE_ICON_ACTIVE)), name: "Theme Colors".to_string(), path: None, confirmed: None, is_pristine: true, } }), EditorTabChild::Keymap(_) => create_memo(move |_| { let config = config.get(); EditorTabChildViewInfo { icon: config.ui_svg(LapceIcons::KEYBOARD), color: Some(config.color(LapceColor::LAPCE_ICON_ACTIVE)), name: "Keyboard Shortcuts".to_string(), path: None, confirmed: None, is_pristine: true, } }), EditorTabChild::Volt(_, id) => create_memo(move |_| { let config = config.get(); let display_name = plugin .installed .with(|volts| volts.get(&id).cloned()) .map(|volt| volt.meta.with(|m| m.display_name.clone())) .or_else(|| { plugin.available.volts.with(|volts| { let volt = volts.get(&id); volt.map(|volt| { volt.info.with(|m| m.display_name.clone()) }) }) }) .unwrap_or_else(|| id.name.clone()); EditorTabChildViewInfo { icon: config.ui_svg(LapceIcons::EXTENSIONS), color: Some(config.color(LapceColor::LAPCE_ICON_ACTIVE)), name: display_name, path: None, confirmed: None, is_pristine: true, } }), } } } #[derive(Clone)] pub struct EditorTabData { pub scope: Scope, pub split: SplitId, pub editor_tab_id: EditorTabId, pub active: usize, pub children: Vec<(RwSignal<usize>, RwSignal<Rect>, EditorTabChild)>, pub window_origin: Point, pub layout_rect: Rect, pub locations: RwSignal<im::Vector<EditorLocation>>, pub current_location: RwSignal<usize>, } impl EditorTabData { pub fn get_editor( &self, editors: Editors, path: &Path, ) -> Option<(usize, EditorData)> { for (i, child) in self.children.iter().enumerate() { if let (_, _, EditorTabChild::Editor(editor_id)) = child { if let Some(editor) = editors.editor_untracked(*editor_id) { let is_path = editor.doc().content.with_untracked(|content| { if let DocContent::File { path: p, .. } = content { p == path } else { false } }); if is_path { return Some((i, editor)); } } } } None } pub fn get_unconfirmed_editor_tab_child( &self, editors: Editors, diff_editors: &im::HashMap<EditorId, DiffEditorData>, ) -> Option<(usize, EditorTabChild)> { for (i, (_, _, child)) in self.children.iter().enumerate() { match child { EditorTabChild::Editor(editor_id) => { if let Some(editor) = editors.editor_untracked(*editor_id) { let confirmed = editor.confirmed.get_untracked(); if !confirmed { return Some((i, child.clone())); } } } EditorTabChild::DiffEditor(diff_editor_id) => { if let Some(diff_editor) = diff_editors.get(diff_editor_id) { let confirmed = diff_editor.confirmed.get_untracked(); if !confirmed { return Some((i, child.clone())); } } } _ => (), } } None } pub fn tab_info(&self, data: &WindowTabData) -> EditorTabInfo { EditorTabInfo { active: self.active, is_focus: data.main_split.active_editor_tab.get_untracked() == Some(self.editor_tab_id), children: self .children .iter() .map(|(_, _, child)| child.child_info(data)) .collect(), } } }
rust
Apache-2.0
59ce6df700ce4efbe4498a719fe52195e083d2ee
2026-01-04T15:32:17.267102Z
false
lapce/lapce
https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/settings.rs
lapce-app/src/settings.rs
use std::{collections::BTreeMap, rc::Rc, sync::Arc, time::Duration}; use floem::{ IntoView, View, action::{TimerToken, add_overlay, exec_after, remove_overlay}, event::EventListener, keyboard::Modifiers, peniko::kurbo::{Point, Rect, Size}, reactive::{ Memo, ReadSignal, RwSignal, Scope, SignalGet, SignalUpdate, SignalWith, create_effect, create_memo, create_rw_signal, }, style::CursorStyle, text::{Attrs, AttrsList, FamilyOwned, TextLayout}, views::{ Decorators, VirtualVector, container, dyn_stack, empty, label, scroll::{PropagatePointerWheel, scroll}, stack, svg, text, virtual_stack, }, }; use indexmap::IndexMap; use inflector::Inflector; use lapce_core::{buffer::rope_text::RopeText, mode::Mode}; use lapce_rpc::plugin::VoltID; use lapce_xi_rope::Rope; use serde::Serialize; use serde_json::Value; use crate::{ command::CommandExecuted, config::{ DropdownInfo, LapceConfig, color::LapceColor, core::CoreConfig, editor::EditorConfig, icon::LapceIcons, terminal::TerminalConfig, ui::UIConfig, }, keypress::KeyPressFocus, main_split::Editors, plugin::InstalledVoltData, text_input::TextInputBuilder, window_tab::CommonData, }; #[derive(Debug, Clone)] pub enum SettingsValue { Float(f64), Integer(i64), String(String), Bool(bool), Dropdown(DropdownInfo), Empty, } impl From<serde_json::Value> for SettingsValue { fn from(v: serde_json::Value) -> Self { match v { serde_json::Value::Number(n) => { if n.is_f64() { SettingsValue::Float(n.as_f64().unwrap()) } else { SettingsValue::Integer(n.as_i64().unwrap()) } } serde_json::Value::String(s) => SettingsValue::String(s), serde_json::Value::Bool(b) => SettingsValue::Bool(b), _ => SettingsValue::Empty, } } } #[derive(Clone, Debug)] struct SettingsItem { kind: String, name: String, field: String, description: String, filter_text: String, value: SettingsValue, serde_value: Value, pos: RwSignal<Point>, size: RwSignal<Size>, // this is only the header that give an visual sepeartion between different type of settings header: bool, } #[derive(Clone, Debug)] struct SettingsData { items: RwSignal<im::Vector<SettingsItem>>, kinds: RwSignal<im::Vector<(String, RwSignal<Point>)>>, plugin_items: RwSignal<im::Vector<SettingsItem>>, plugin_kinds: RwSignal<im::Vector<(String, RwSignal<Point>)>>, filtered_items: RwSignal<im::Vector<SettingsItem>>, common: Rc<CommonData>, } impl KeyPressFocus for SettingsData { fn get_mode(&self) -> lapce_core::mode::Mode { Mode::Insert } fn check_condition( &self, _condition: crate::keypress::condition::Condition, ) -> bool { false } fn run_command( &self, _command: &crate::command::LapceCommand, _count: Option<usize>, _mods: Modifiers, ) -> crate::command::CommandExecuted { CommandExecuted::No } fn receive_char(&self, _c: &str) {} } impl VirtualVector<SettingsItem> for SettingsData { fn total_len(&self) -> usize { self.filtered_items.get_untracked().len() } fn slice( &mut self, _range: std::ops::Range<usize>, ) -> impl Iterator<Item = SettingsItem> { Box::new(self.filtered_items.get().into_iter()) } } impl SettingsData { pub fn new( cx: Scope, installed_plugin: RwSignal<IndexMap<VoltID, InstalledVoltData>>, common: Rc<CommonData>, ) -> Self { fn into_settings_map( data: &impl Serialize, ) -> serde_json::Map<String, serde_json::Value> { match serde_json::to_value(data).unwrap() { serde_json::Value::Object(h) => h, _ => serde_json::Map::default(), } } let config = common.config; let plugin_items = cx.create_rw_signal(im::Vector::new()); let plugin_kinds = cx.create_rw_signal(im::Vector::new()); let filtered_items = cx.create_rw_signal(im::Vector::new()); let items = cx.create_rw_signal(im::Vector::new()); let kinds = cx.create_rw_signal(im::Vector::new()); cx.create_effect(move |_| { let config = config.get(); let mut data_items = im::Vector::new(); let mut data_kinds = im::Vector::new(); let mut item_height_accum = 0.0; for (kind, fields, descs, mut settings_map) in [ ( "Core", &CoreConfig::FIELDS[..], &CoreConfig::DESCS[..], into_settings_map(&config.core), ), ( "Editor", &EditorConfig::FIELDS[..], &EditorConfig::DESCS[..], into_settings_map(&config.editor), ), ( "UI", &UIConfig::FIELDS[..], &UIConfig::DESCS[..], into_settings_map(&config.ui), ), ( "Terminal", &TerminalConfig::FIELDS[..], &TerminalConfig::DESCS[..], into_settings_map(&config.terminal), ), ] { let pos = cx.create_rw_signal(Point::new(0.0, item_height_accum)); data_items.push_back(SettingsItem { kind: kind.to_string(), name: "".to_string(), field: "".to_string(), filter_text: "".to_string(), description: "".to_string(), value: SettingsValue::Empty, serde_value: Value::Null, pos, size: cx.create_rw_signal(Size::ZERO), header: true, }); data_kinds.push_back((kind.to_string(), pos)); for (name, desc) in fields.iter().zip(descs.iter()) { let field = name.replace('_', "-"); let (value, serde_value) = if let Some(dropdown) = config.get_dropdown_info(&kind.to_lowercase(), &field) { let index = dropdown.active_index; ( SettingsValue::Dropdown(dropdown), Value::Number(index.into()), ) } else { let value = settings_map.remove(&field).unwrap(); (SettingsValue::from(value.clone()), value) }; let name = format!( "{kind}: {}", name.replace('_', " ").to_title_case() ); let kind = kind.to_lowercase(); let filter_text = format!("{kind} {name} {desc}").to_lowercase(); let filter_text = format!("{filter_text}{}", filter_text.replace(' ', "")); data_items.push_back(SettingsItem { kind, name, field, filter_text, description: desc.to_string(), value, pos: cx.create_rw_signal(Point::ZERO), size: cx.create_rw_signal(Size::ZERO), serde_value, header: false, }); item_height_accum += 50.0; } } filtered_items.set(data_items.clone()); items.set(data_items); let plugins = installed_plugin.get(); let mut setting_items = im::Vector::new(); let mut plugin_kinds_tmp = im::Vector::new(); for (_, volt) in plugins { let meta = volt.meta.get(); let kind = meta.name; let plugin_config = config.plugins.get(&kind); if let Some(config) = meta.config { let pos = cx.create_rw_signal(Point::new(0.0, item_height_accum)); setting_items.push_back(SettingsItem { kind: meta.display_name.clone(), name: "".to_string(), field: "".to_string(), filter_text: "".to_string(), description: "".to_string(), value: SettingsValue::Empty, serde_value: Value::Null, pos, size: cx.create_rw_signal(Size::ZERO), header: true, }); plugin_kinds_tmp.push_back((meta.display_name.clone(), pos)); { let mut local_items = Vec::new(); for (name, config) in config { let field = name.clone(); let name = format!( "{}: {}", meta.display_name, name.replace('_', " ").to_title_case() ); let desc = config.description; let filter_text = format!("{kind} {name} {desc}").to_lowercase(); let filter_text = format!( "{filter_text}{}", filter_text.replace(' ', "") ); let value = plugin_config .and_then(|config| config.get(&field).cloned()) .unwrap_or(config.default); let value = SettingsValue::from(value); let item = SettingsItem { kind: kind.clone(), name, field, filter_text, description: desc.to_string(), value, pos: cx.create_rw_signal(Point::ZERO), size: cx.create_rw_signal(Size::ZERO), serde_value: Value::Null, header: false, }; local_items.push(item); item_height_accum += 50.0; } local_items.sort_by_key(|i| i.name.clone()); setting_items.extend(local_items.into_iter()); } } } plugin_items.set(setting_items); plugin_kinds.set(plugin_kinds_tmp); kinds.set(data_kinds); }); Self { filtered_items, plugin_items, plugin_kinds, items, kinds, common, } } } pub fn settings_view( installed_plugins: RwSignal<IndexMap<VoltID, InstalledVoltData>>, editors: Editors, common: Rc<CommonData>, ) -> impl View { let config = common.config; let cx = Scope::current(); let settings_data = SettingsData::new(cx, installed_plugins, common.clone()); let view_settings_data = settings_data.clone(); let plugin_kinds = settings_data.plugin_kinds; let search_editor = editors.make_local(cx, common); let doc = search_editor.doc_signal(); let items = settings_data.items; let kinds = settings_data.kinds; let filtered_items_signal = settings_data.filtered_items; create_effect(move |_| { let doc = doc.get(); let pattern = doc.buffer.with(|b| b.to_string().to_lowercase()); let plugin_items = settings_data.plugin_items.get(); let mut items = items.get(); if pattern.is_empty() { items.extend(plugin_items); filtered_items_signal.set(items); return; } let mut filtered_items = im::Vector::new(); for item in &items { if item.header || item.filter_text.contains(&pattern) { filtered_items.push_back(item.clone()); } } for item in plugin_items { if item.header || item.filter_text.contains(&pattern) { filtered_items.push_back(item); } } filtered_items_signal.set(filtered_items); }); let ensure_visible = create_rw_signal(Rect::ZERO); let settings_content_size = create_rw_signal(Size::ZERO); let scroll_pos = create_rw_signal(Point::ZERO); let current_kind = { create_memo(move |_| { let scroll_pos = scroll_pos.get(); let scroll_y = scroll_pos.y + 30.0; let plugin_kinds = plugin_kinds.get_untracked(); for (kind, pos) in plugin_kinds.iter().rev() { if pos.get_untracked().y < scroll_y { return kind.to_string(); } } let kinds = kinds.get(); for (kind, pos) in kinds.iter().rev() { if pos.get_untracked().y < scroll_y { return kind.to_string(); } } kinds.get(0).unwrap().0.to_string() }) }; let switcher_item = move |k: String, pos: Box<dyn Fn() -> Option<RwSignal<Point>>>, margin: f32| { let kind = k.clone(); container( label(move || k.clone()) .style(move |s| s.text_ellipsis().padding_left(margin)), ) .on_click_stop(move |_| { if let Some(pos) = pos() { ensure_visible.set( settings_content_size .get_untracked() .to_rect() .with_origin(pos.get_untracked()), ); } }) .style(move |s| { let config = config.get(); s.padding_horiz(20.0) .width_pct(100.0) .apply_if(kind == current_kind.get(), |s| { s.background(config.color(LapceColor::PANEL_CURRENT_BACKGROUND)) }) .hover(|s| { s.cursor(CursorStyle::Pointer).background( config.color(LapceColor::PANEL_HOVERED_BACKGROUND), ) }) .active(|s| { s.background( config.color(LapceColor::PANEL_HOVERED_ACTIVE_BACKGROUND), ) }) }) }; let switcher = || { stack(( dyn_stack( move || kinds.get().clone(), |(k, _)| k.clone(), move |(k, pos)| switcher_item(k, Box::new(move || Some(pos)), 0.0), ) .style(|s| s.flex_col().width_pct(100.0)), stack(( switcher_item( "Plugin Settings".to_string(), Box::new(move || { plugin_kinds .with_untracked(|k| k.get(0).map(|(_, pos)| *pos)) }), 0.0, ), dyn_stack( move || plugin_kinds.get(), |(k, _)| k.clone(), move |(k, pos)| { switcher_item(k, Box::new(move || Some(pos)), 10.0) }, ) .style(|s| s.flex_col().width_pct(100.0)), )) .style(move |s| { s.width_pct(100.0) .flex_col() .apply_if(plugin_kinds.with(|k| k.is_empty()), |s| s.hide()) }), )) .style(move |s| { s.width_pct(100.0) .flex_col() .line_height(1.8) .font_size(config.get().ui.font_size() as f32 + 1.0) }) }; stack(( container({ scroll({ container(switcher()) .style(|s| s.padding_vert(20.0).width_pct(100.0)) }) .style(|s| s.absolute().size_pct(100.0, 100.0)) }) .style(move |s| { s.height_pct(100.0) .width(200.0) .border_right(1.0) .border_color(config.get().color(LapceColor::LAPCE_BORDER)) }), stack(( container({ TextInputBuilder::new() .build_editor(search_editor) .placeholder(|| "Search Settings".to_string()) .keyboard_navigable() .style(move |s| { s.width_pct(100.0) .border_radius(6.0) .border(1.0) .border_color( config.get().color(LapceColor::LAPCE_BORDER), ) }) .request_focus(|| {}) }) .style(|s| s.padding_horiz(50.0).padding_vert(20.0)), container({ scroll({ dyn_stack( move || filtered_items_signal.get(), |item| { ( item.kind.clone(), item.name.clone(), item.serde_value.clone(), ) }, move |item| { settings_item_view( editors, view_settings_data.clone(), item, ) }, ) .style(|s| { s.flex_col() .padding_horiz(50.0) .min_width_pct(100.0) .max_width(400.0) }) }) .on_scroll(move |rect| { scroll_pos.set(rect.origin()); }) .ensure_visible(move || ensure_visible.get()) .on_resize(move |rect| { settings_content_size.set(rect.size()); }) .style(|s| s.absolute().size_pct(100.0, 100.0)) }) .style(|s| s.size_pct(100.0, 100.0)), )) .style(|s| s.flex_col().size_pct(100.0, 100.0)), )) .style(|s| s.absolute().size_pct(100.0, 100.0)) .debug_name("Settings") } fn settings_item_view( editors: Editors, settings_data: SettingsData, item: SettingsItem, ) -> impl View + use<> { let config = settings_data.common.config; let is_ticked = if let SettingsValue::Bool(is_ticked) = &item.value { Some(*is_ticked) } else { None }; let timer = create_rw_signal(TimerToken::INVALID); let editor_value = match &item.value { SettingsValue::Float(n) => Some(n.to_string()), SettingsValue::Integer(n) => Some(n.to_string()), SettingsValue::String(s) => Some(s.to_string()), SettingsValue::Bool(_) => None, SettingsValue::Dropdown(_) => None, SettingsValue::Empty => None, }; let view = { let item = item.clone(); move || { let cx = Scope::current(); if let Some(editor_value) = editor_value { let text_input_view = TextInputBuilder::new() .value(editor_value) .build(cx, editors, settings_data.common); let doc = text_input_view.doc_signal(); let kind = item.kind.clone(); let field = item.field.clone(); let item_value = item.value.clone(); create_effect(move |last| { let doc = doc.get_untracked(); let rev = doc.buffer.with(|b| b.rev()); if last.is_none() { return rev; } if last == Some(rev) { return rev; } let kind = kind.clone(); let field = field.clone(); let buffer = doc.buffer; let item_value = item_value.clone(); let token = exec_after(Duration::from_millis(500), move |token| { if let Some(timer) = timer.try_get_untracked() { if timer == token { let value = buffer.with_untracked(|b| b.to_string()); let value = match &item_value { SettingsValue::Float(_) => { value.parse::<f64>().ok().and_then(|v| { serde::Serialize::serialize( &v, toml_edit::ser::ValueSerializer::new(), ).ok() }) } SettingsValue::Integer(_) => { value.parse::<i64>().ok().and_then(|v| { serde::Serialize::serialize( &v, toml_edit::ser::ValueSerializer::new(), ).ok() }) } _ => serde::Serialize::serialize( &value, toml_edit::ser::ValueSerializer::new(), ) .ok(), }; if let Some(value) = value { LapceConfig::update_file( &kind, &field, value, ); } } } }); timer.set(token); rev }); text_input_view .keyboard_navigable() .style(move |s| { s.width(300.0).border(1.0).border_radius(6.0).border_color( config.get().color(LapceColor::LAPCE_BORDER), ) }) .into_any() } else if let SettingsValue::Dropdown(dropdown) = &item.value { let expanded = create_rw_signal(false); let current_value = dropdown .items .get(dropdown.active_index) .or_else(|| dropdown.items.last()) .map(|s| s.to_string()) .unwrap_or_default(); let current_value = create_rw_signal(current_value); dropdown_view( &item, current_value, dropdown, expanded, settings_data.common.window_common.size, config, ) .into_any() } else if item.header { label(move || item.kind.clone()) .style(move |s| { let config = config.get(); s.line_height(2.0) .font_bold() .width_pct(100.0) .padding_horiz(10.0) .font_size(config.ui.font_size() as f32 + 2.0) .background(config.color(LapceColor::PANEL_BACKGROUND)) }) .into_any() } else { empty().into_any() } } }; stack(( label(move || item.name.clone()).style(move |s| { s.font_bold() .text_ellipsis() .min_width(0.0) .max_width_pct(100.0) .line_height(1.8) .font_size(config.get().ui.font_size() as f32 + 1.0) }), stack(( label(move || item.description.clone()).style(move |s| { s.min_width(0.0) .max_width_pct(100.0) .line_height(1.8) .apply_if(is_ticked.is_some(), |s| { s.margin_left(config.get().ui.font_size() as f32 + 8.0) }) .apply_if(item.header, |s| s.hide()) }), if let Some(is_ticked) = is_ticked { let checked = create_rw_signal(is_ticked); let kind = item.kind.clone(); let field = item.field.clone(); create_effect(move |last| { let checked = checked.get(); if last.is_none() { return; } if let Ok(value) = serde::Serialize::serialize( &checked, toml_edit::ser::ValueSerializer::new(), ) { LapceConfig::update_file(&kind, &field, value); } }); container( stack(( checkbox(move || checked.get(), config), label(|| " ".to_string()).style(|s| s.line_height(1.8)), )) .style(|s| s.items_center()), ) .on_click_stop(move |_| { checked.update(|checked| { *checked = !*checked; }); }) .style(|s| { s.absolute() .cursor(CursorStyle::Pointer) .size_pct(100.0, 100.0) .items_start() }) } else { container(empty()).style(|s| s.hide()) }, )), view().style(move |s| s.apply_if(!item.header, |s| s.margin_top(6.0))), )) .on_resize(move |rect| { if item.header { item.pos.set(rect.origin()); } let old_size = item.size.get_untracked(); let new_size = rect.size(); if old_size != new_size { item.size.set(new_size); } }) .style(|s| { s.flex_col() .padding_vert(10.0) .min_width_pct(100.0) .max_width(300.0) }) } pub fn checkbox( checked: impl Fn() -> bool + 'static, config: ReadSignal<Arc<LapceConfig>>, ) -> impl View { const CHECKBOX_SVG: &str = r#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="-2 -2 16 16"><polygon points="5.19,11.83 0.18,7.44 1.82,5.56 4.81,8.17 10,1.25 12,2.75" /></svg>"#; let svg_str = move || if checked() { CHECKBOX_SVG } else { "" }.to_string(); svg(svg_str).style(move |s| { let config = config.get(); let size = config.ui.font_size() as f32; let color = config.color(LapceColor::EDITOR_FOREGROUND); s.min_width(size) .size(size, size) .color(color) .border_color(color) .border(1.) .border_radius(2.) }) } struct BTreeMapVirtualList(BTreeMap<String, String>); impl VirtualVector<(String, String)> for BTreeMapVirtualList { fn total_len(&self) -> usize { self.0.len() } fn slice( &mut self, range: std::ops::Range<usize>, ) -> impl Iterator<Item = (String, String)> { Box::new( self.0 .iter() .enumerate() .filter_map(|(index, (k, v))| { if range.contains(&index) { Some((k.to_string(), v.to_string())) } else { None } }) .collect::<Vec<_>>() .into_iter(), ) } } fn color_section_list( kind: &str, header: &str, list: impl Fn() -> BTreeMap<String, String> + 'static, max_width: Memo<f64>, text_height: Memo<f64>, editors: Editors, common: Rc<CommonData>, ) -> impl View { let config = common.config; let kind = kind.to_string(); stack(( text(header).style(|s| { s.margin_top(10) .margin_horiz(20) .font_bold() .line_height(2.0) }), virtual_stack( move || BTreeMapVirtualList(list()), move |(key, _)| key.to_owned(), move |(key, value)| { let cx = Scope::current(); let text_input_view = TextInputBuilder::new() .value(value.clone()) .build(cx, editors, common.clone()); let doc = text_input_view.doc_signal(); { let kind = kind.clone(); let key = key.clone(); let doc = text_input_view.doc_signal(); create_effect(move |_| { let doc = doc.get_untracked(); let config = config.get(); let current = doc.buffer.with_untracked(|b| b.to_string()); let value = match kind.as_str() { "base" => config.color_theme.base.get(&key), "ui" => config.color_theme.ui.get(&key), "syntax" => config.color_theme.syntax.get(&key), _ => None, }; if let Some(value) = value { if value != &current { doc.reload(Rope::from(value.to_string()), true); } } }); } { let timer = create_rw_signal(TimerToken::INVALID); let kind = kind.clone(); let field = key.clone(); create_effect(move |last| { let doc = doc.get_untracked(); let rev = doc.buffer.with(|b| b.rev()); if last.is_none() { return rev; } if last == Some(rev) { return rev; } let kind = kind.clone(); let field = field.clone(); let buffer = doc.buffer; let token = exec_after(Duration::from_millis(500), move |token| { if let Some(timer) = timer.try_get_untracked() { if timer == token { let value = buffer.with_untracked(|b| b.to_string()); let config = config.get_untracked(); let default = match kind.as_str() { "base" => config .default_color_theme() .base .get(&field),
rust
Apache-2.0
59ce6df700ce4efbe4498a719fe52195e083d2ee
2026-01-04T15:32:17.267102Z
true
lapce/lapce
https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/focus_text.rs
lapce-app/src/focus_text.rs
use floem::{ Renderer, View, ViewId, peniko::{ Color, kurbo::{Point, Rect}, }, prop_extractor, reactive::create_effect, style::{FontFamily, FontSize, LineHeight, Style, TextColor}, taffy::prelude::NodeId, text::{Attrs, AttrsList, FamilyOwned, TextLayout, Weight}, }; prop_extractor! { Extractor { color: TextColor, font_size: FontSize, font_family: FontFamily, line_height: LineHeight, } } enum FocusTextState { Text(String), FocusColor(Color), FocusIndices(Vec<usize>), } pub fn focus_text( text: impl Fn() -> String + 'static, focus_indices: impl Fn() -> Vec<usize> + 'static, focus_color: impl Fn() -> Color + 'static, ) -> FocusText { let id = ViewId::new(); create_effect(move |_| { let new_text = text(); id.update_state(FocusTextState::Text(new_text)); }); create_effect(move |_| { let focus_color = focus_color(); id.update_state(FocusTextState::FocusColor(focus_color)); }); create_effect(move |_| { let focus_indices = focus_indices(); id.update_state(FocusTextState::FocusIndices(focus_indices)); }); FocusText { id, text: "".to_string(), text_layout: None, focus_color: Color::BLACK, focus_indices: Vec::new(), text_node: None, available_text: None, available_width: None, available_text_layout: None, style: Default::default(), } } pub struct FocusText { id: ViewId, text: String, text_layout: Option<TextLayout>, focus_color: Color, focus_indices: Vec<usize>, text_node: Option<NodeId>, available_text: Option<String>, available_width: Option<f32>, available_text_layout: Option<TextLayout>, style: Extractor, } impl FocusText { fn set_text_layout(&mut self) { let mut attrs = Attrs::new().color(self.style.color().unwrap_or(Color::BLACK)); if let Some(font_size) = self.style.font_size() { attrs = attrs.font_size(font_size); } let font_family = self.style.font_family().as_ref().map(|font_family| { let family: Vec<FamilyOwned> = FamilyOwned::parse_list(font_family).collect(); family }); if let Some(font_family) = font_family.as_ref() { attrs = attrs.family(font_family); } if let Some(line_height) = self.style.line_height() { attrs = attrs.line_height(line_height); } let mut attrs_list = AttrsList::new(attrs.clone()); for &i_start in &self.focus_indices { let i_end = self .text .char_indices() .find(|(i, _)| *i == i_start) .map(|(_, c)| c.len_utf8() + i_start); let i_end = if let Some(i_end) = i_end { i_end } else { continue; }; attrs_list.add_span( i_start..i_end, attrs.clone().color(self.focus_color).weight(Weight::BOLD), ); } let mut text_layout = TextLayout::new(); text_layout.set_text(&self.text, attrs_list, None); self.text_layout = Some(text_layout); if let Some(new_text) = self.available_text.as_ref() { let new_text_len = new_text.len(); let mut attrs = Attrs::new().color(self.style.color().unwrap_or(Color::BLACK)); if let Some(font_size) = self.style.font_size() { attrs = attrs.font_size(font_size); } let font_family = self.style.font_family().as_ref().map(|font_family| { let family: Vec<FamilyOwned> = FamilyOwned::parse_list(font_family).collect(); family }); if let Some(font_family) = font_family.as_ref() { attrs = attrs.family(font_family); } let mut attrs_list = AttrsList::new(attrs.clone()); for &i_start in &self.focus_indices { if i_start + 3 > new_text_len { break; } let i_end = self .text .char_indices() .find(|(i, _)| *i == i_start) .map(|(_, c)| c.len_utf8() + i_start); let i_end = if let Some(i_end) = i_end { i_end } else { continue; }; attrs_list.add_span( i_start..i_end, attrs.clone().color(self.focus_color).weight(Weight::BOLD), ); } let mut text_layout = TextLayout::new(); text_layout.set_text(new_text, attrs_list, None); self.available_text_layout = Some(text_layout); } } } impl View for FocusText { fn id(&self) -> ViewId { self.id } fn update( &mut self, _cx: &mut floem::context::UpdateCx, state: Box<dyn std::any::Any>, ) { if let Ok(state) = state.downcast() { match *state { FocusTextState::Text(text) => { self.text = text; } FocusTextState::FocusColor(color) => { self.focus_color = color; } FocusTextState::FocusIndices(indices) => { self.focus_indices = indices; } } self.set_text_layout(); self.id.request_layout(); } } fn style_pass(&mut self, cx: &mut floem::context::StyleCx<'_>) { if self.style.read(cx) { self.set_text_layout(); self.id.request_layout(); } } fn layout( &mut self, cx: &mut floem::context::LayoutCx, ) -> floem::taffy::prelude::NodeId { cx.layout_node(self.id, true, |_cx| { if self.text_layout.is_none() { self.set_text_layout(); } let text_layout = self.text_layout.as_ref().unwrap(); let size = text_layout.size(); let width = size.width.ceil() as f32; let height = size.height as f32; if self.text_node.is_none() { self.text_node = Some(self.id.new_taffy_node()); } let text_node = self.text_node.unwrap(); let style = Style::new().width(width).height(height).to_taffy_style(); self.id.set_taffy_style(text_node, style); vec![text_node] }) } fn compute_layout( &mut self, _cx: &mut floem::context::ComputeLayoutCx, ) -> Option<Rect> { let text_node = self.text_node.unwrap(); let layout = self.id.taffy_layout(text_node).unwrap_or_default(); let text_layout = self.text_layout.as_ref().unwrap(); let width = text_layout.size().width as f32; if width > layout.size.width { if self.available_width != Some(layout.size.width) { let mut dots_text = TextLayout::new(); let mut attrs = Attrs::new().color( self.style .color() .unwrap_or_else(|| Color::from_rgb8(0xf0, 0xf0, 0xea)), ); if let Some(font_size) = self.style.font_size() { attrs = attrs.font_size(font_size); } let font_family = self.style.font_family().as_ref().map(|font_family| { let family: Vec<FamilyOwned> = FamilyOwned::parse_list(font_family).collect(); family }); if let Some(font_family) = font_family.as_ref() { attrs = attrs.family(font_family); } dots_text.set_text("...", AttrsList::new(attrs), None); let dots_width = dots_text.size().width as f32; let width_left = layout.size.width - dots_width; let hit_point = text_layout.hit_point(Point::new(width_left as f64, 0.0)); let index = hit_point.index; let new_text = if index > 0 { format!("{}...", &self.text[..index]) } else { "".to_string() }; self.available_text = Some(new_text); self.available_width = Some(layout.size.width); self.set_text_layout(); } } else { self.available_text = None; self.available_width = None; self.available_text_layout = None; } None } fn paint(&mut self, cx: &mut floem::context::PaintCx) { let text_node = self.text_node.unwrap(); let location = self.id.taffy_layout(text_node).unwrap_or_default().location; let point = Point::new(location.x as f64, location.y as f64); if let Some(text_layout) = self.available_text_layout.as_ref() { cx.draw_text(text_layout, point); } else { cx.draw_text(self.text_layout.as_ref().unwrap(), point); } } }
rust
Apache-2.0
59ce6df700ce4efbe4498a719fe52195e083d2ee
2026-01-04T15:32:17.267102Z
false
lapce/lapce
https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/workspace.rs
lapce-app/src/workspace.rs
use std::{collections::HashMap, fmt::Display, path::PathBuf}; use serde::{Deserialize, Serialize}; use crate::{debug::LapceBreakpoint, main_split::SplitInfo, panel::data::PanelInfo}; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Hash)] pub struct SshHost { pub user: Option<String>, pub host: String, pub port: Option<usize>, } impl SshHost { pub fn from_string(s: &str) -> Self { let mut whole_splits = s.split(':'); let splits = whole_splits .next() .unwrap() .split('@') .collect::<Vec<&str>>(); let mut splits = splits.iter().rev(); let host = splits.next().unwrap().to_string(); let user = splits.next().map(|s| s.to_string()); let port = whole_splits.next().and_then(|s| s.parse::<usize>().ok()); Self { user, host, port } } pub fn user_host(&self) -> String { if let Some(user) = self.user.as_ref() { format!("{user}@{}", self.host) } else { self.host.clone() } } } impl Display for SshHost { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { if let Some(user) = self.user.as_ref() { write!(f, "{user}@")?; } write!(f, "{}", self.host)?; if let Some(port) = self.port { write!(f, ":{port}")?; } Ok(()) } } #[cfg(windows)] #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Hash)] pub struct WslHost { pub host: String, } #[cfg(windows)] impl Display for WslHost { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.host)?; Ok(()) } } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum LapceWorkspaceType { Local, RemoteSSH(SshHost), #[cfg(windows)] RemoteWSL(WslHost), } impl LapceWorkspaceType { pub fn is_local(&self) -> bool { matches!(self, LapceWorkspaceType::Local) } pub fn is_remote(&self) -> bool { use LapceWorkspaceType::*; #[cfg(not(windows))] return matches!(self, RemoteSSH(_)); #[cfg(windows)] return matches!(self, RemoteSSH(_) | RemoteWSL(_)); } } impl std::fmt::Display for LapceWorkspaceType { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { LapceWorkspaceType::Local => f.write_str("Local"), LapceWorkspaceType::RemoteSSH(remote) => { write!(f, "ssh://{remote}") } #[cfg(windows)] LapceWorkspaceType::RemoteWSL(remote) => { write!(f, "{remote} (WSL)") } } } } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct LapceWorkspace { pub kind: LapceWorkspaceType, pub path: Option<PathBuf>, pub last_open: u64, } impl LapceWorkspace { pub fn display(&self) -> Option<String> { let path = self.path.as_ref()?; let path = path .file_name() .unwrap_or(path.as_os_str()) .to_string_lossy() .to_string(); let remote = match &self.kind { LapceWorkspaceType::Local => String::new(), LapceWorkspaceType::RemoteSSH(remote) => { format!(" [SSH: {}]", remote.host) } #[cfg(windows)] LapceWorkspaceType::RemoteWSL(remote) => { format!(" [WSL: {}]", remote.host) } }; Some(format!("{path}{remote}")) } } impl Default for LapceWorkspace { fn default() -> Self { Self { kind: LapceWorkspaceType::Local, path: None, last_open: 0, } } } impl std::fmt::Display for LapceWorkspace { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "{}:{}", self.kind, self.path.as_ref().and_then(|p| p.to_str()).unwrap_or("") ) } } #[derive(Clone, Serialize, Deserialize)] pub struct WorkspaceInfo { pub split: SplitInfo, pub panel: PanelInfo, pub breakpoints: HashMap<PathBuf, Vec<LapceBreakpoint>>, }
rust
Apache-2.0
59ce6df700ce4efbe4498a719fe52195e083d2ee
2026-01-04T15:32:17.267102Z
false
lapce/lapce
https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/lib.rs
lapce-app/src/lib.rs
pub mod about; pub mod alert; pub mod app; pub mod code_action; pub mod code_lens; pub mod command; pub mod completion; pub mod config; pub mod db; pub mod debug; pub mod doc; pub mod editor; pub mod editor_tab; pub mod file_explorer; pub mod find; pub mod focus_text; pub mod global_search; pub mod history; pub mod hover; pub mod id; pub mod inline_completion; pub mod keymap; pub mod keypress; pub mod listener; pub mod lsp; pub mod main_split; pub mod markdown; pub mod palette; pub mod panel; pub mod plugin; pub mod proxy; pub mod rename; pub mod settings; pub mod snippet; pub mod source_control; pub mod status; pub mod terminal; pub mod text_area; pub mod text_input; pub mod title; pub mod tracing; pub mod update; pub mod wave; pub mod web_link; pub mod window; pub mod window_tab; pub mod workspace; #[cfg(windows)] extern crate windows_sys as windows;
rust
Apache-2.0
59ce6df700ce4efbe4498a719fe52195e083d2ee
2026-01-04T15:32:17.267102Z
false
lapce/lapce
https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/command.rs
lapce-app/src/command.rs
use std::{path::PathBuf, rc::Rc}; pub use floem::views::editor::command::CommandExecuted; use floem::{ ViewId, keyboard::Modifiers, peniko::kurbo::Vec2, views::editor::command::Command, }; use indexmap::IndexMap; use lapce_core::command::{ EditCommand, FocusCommand, MotionModeCommand, MoveCommand, MultiSelectionCommand, ScrollCommand, }; use lapce_rpc::{ dap_types::{DapId, RunDebugConfig}, plugin::{PluginId, VoltID}, proxy::ProxyStatus, terminal::{TermId, TerminalProfile}, }; use lsp_types::{CodeActionOrCommand, Position, WorkspaceEdit}; use serde_json::Value; use strum::{EnumMessage, IntoEnumIterator}; use strum_macros::{Display, EnumIter, EnumString, IntoStaticStr}; use crate::{ alert::AlertButton, debug::RunDebugMode, doc::Doc, editor::location::EditorLocation, editor_tab::EditorTabChild, id::EditorTabId, main_split::{SplitDirection, SplitMoveDirection, TabCloseKind}, workspace::LapceWorkspace, }; #[derive(Clone, Debug, PartialEq, Eq)] pub struct LapceCommand { pub kind: CommandKind, pub data: Option<Value>, } #[derive(Clone, Debug, PartialEq, Eq)] pub enum CommandKind { Workbench(LapceWorkbenchCommand), Edit(EditCommand), Move(MoveCommand), Scroll(ScrollCommand), Focus(FocusCommand), MotionMode(MotionModeCommand), MultiSelection(MultiSelectionCommand), } impl CommandKind { pub fn desc(&self) -> Option<&'static str> { match &self { CommandKind::Workbench(cmd) => cmd.get_message(), CommandKind::Edit(cmd) => cmd.get_message(), CommandKind::Move(cmd) => cmd.get_message(), CommandKind::Scroll(cmd) => cmd.get_message(), CommandKind::Focus(cmd) => cmd.get_message(), CommandKind::MotionMode(cmd) => cmd.get_message(), CommandKind::MultiSelection(cmd) => cmd.get_message(), } } pub fn str(&self) -> &'static str { match &self { CommandKind::Workbench(cmd) => cmd.into(), CommandKind::Edit(cmd) => cmd.into(), CommandKind::Move(cmd) => cmd.into(), CommandKind::Scroll(cmd) => cmd.into(), CommandKind::Focus(cmd) => cmd.into(), CommandKind::MotionMode(cmd) => cmd.into(), CommandKind::MultiSelection(cmd) => cmd.into(), } } } impl From<Command> for CommandKind { fn from(cmd: Command) -> Self { use Command::*; match cmd { Edit(edit) => CommandKind::Edit(edit), Move(movement) => CommandKind::Move(movement), Scroll(scroll) => CommandKind::Scroll(scroll), MotionMode(motion_mode) => CommandKind::MotionMode(motion_mode), MultiSelection(multi_selection) => { CommandKind::MultiSelection(multi_selection) } } } } pub fn lapce_internal_commands() -> IndexMap<String, LapceCommand> { let mut commands = IndexMap::new(); for c in LapceWorkbenchCommand::iter() { let command = LapceCommand { kind: CommandKind::Workbench(c.clone()), data: None, }; commands.insert(c.to_string(), command); } for c in EditCommand::iter() { let command = LapceCommand { kind: CommandKind::Edit(c.clone()), data: None, }; commands.insert(c.to_string(), command); } for c in MoveCommand::iter() { let command = LapceCommand { kind: CommandKind::Move(c.clone()), data: None, }; commands.insert(c.to_string(), command); } for c in ScrollCommand::iter() { let command = LapceCommand { kind: CommandKind::Scroll(c.clone()), data: None, }; commands.insert(c.to_string(), command); } for c in FocusCommand::iter() { let command = LapceCommand { kind: CommandKind::Focus(c.clone()), data: None, }; commands.insert(c.to_string(), command); } for c in MotionModeCommand::iter() { let command = LapceCommand { kind: CommandKind::MotionMode(c.clone()), data: None, }; commands.insert(c.to_string(), command); } for c in MultiSelectionCommand::iter() { let command = LapceCommand { kind: CommandKind::MultiSelection(c.clone()), data: None, }; commands.insert(c.to_string(), command); } commands } #[derive( Display, EnumString, EnumIter, Clone, PartialEq, Eq, Debug, EnumMessage, IntoStaticStr, )] pub enum LapceWorkbenchCommand { #[strum(serialize = "enable_modal_editing")] #[strum(message = "Enable Modal Editing")] EnableModal, #[strum(serialize = "disable_modal_editing")] #[strum(message = "Disable Modal Editing")] DisableModal, #[strum(serialize = "open_folder")] #[strum(message = "Open Folder")] OpenFolder, #[strum(serialize = "close_folder")] #[strum(message = "Close Folder")] CloseFolder, #[strum(serialize = "open_file")] #[strum(message = "Open File")] OpenFile, #[strum(serialize = "show_call_hierarchy")] #[strum(message = "Show Call Hierarchy")] ShowCallHierarchy, #[strum(serialize = "find_references")] #[strum(message = "Find References")] FindReferences, #[strum(serialize = "go_to_implementation")] #[strum(message = "Go to Implementation")] GoToImplementation, #[strum(serialize = "reveal_in_panel")] #[strum(message = "Reveal in Panel")] RevealInPanel, #[strum(serialize = "source_control_open_active_file_remote_url")] #[strum(message = "Source Control: Open Remote File Url")] SourceControlOpenActiveFileRemoteUrl, #[cfg(not(target_os = "macos"))] #[strum(serialize = "reveal_in_file_explorer")] #[strum(message = "Reveal in System File Explorer")] RevealInFileExplorer, #[cfg(target_os = "macos")] #[strum(serialize = "reveal_in_file_explorer")] #[strum(message = "Reveal in Finder")] RevealInFileExplorer, #[strum(serialize = "run_in_terminal")] #[strum(message = "Run in Terminal")] RunInTerminal, #[strum(serialize = "reveal_active_file_in_file_explorer")] #[strum(message = "Reveal Active File in File Explorer")] RevealActiveFileInFileExplorer, #[strum(serialize = "open_ui_inspector")] #[strum(message = "Open Internal UI Inspector")] OpenUIInspector, #[strum(serialize = "show_env")] #[strum(message = "Show Environment")] ShowEnvironment, #[strum(serialize = "change_color_theme")] #[strum(message = "Change Color Theme")] ChangeColorTheme, #[strum(serialize = "change_icon_theme")] #[strum(message = "Change Icon Theme")] ChangeIconTheme, #[strum(serialize = "open_settings")] #[strum(message = "Open Settings")] OpenSettings, #[strum(serialize = "open_settings_file")] #[strum(message = "Open Settings File")] OpenSettingsFile, #[strum(serialize = "open_settings_directory")] #[strum(message = "Open Settings Directory")] OpenSettingsDirectory, #[strum(serialize = "open_theme_color_settings")] #[strum(message = "Open Theme Color Settings")] OpenThemeColorSettings, #[strum(serialize = "open_keyboard_shortcuts")] #[strum(message = "Open Keyboard Shortcuts")] OpenKeyboardShortcuts, #[strum(serialize = "open_keyboard_shortcuts_file")] #[strum(message = "Open Keyboard Shortcuts File")] OpenKeyboardShortcutsFile, #[strum(serialize = "open_log_file")] #[strum(message = "Open Log File")] OpenLogFile, #[strum(serialize = "open_logs_directory")] #[strum(message = "Open Logs Directory")] OpenLogsDirectory, #[strum(serialize = "open_proxy_directory")] #[strum(message = "Open Proxy Directory")] OpenProxyDirectory, #[strum(serialize = "open_themes_directory")] #[strum(message = "Open Themes Directory")] OpenThemesDirectory, #[strum(serialize = "open_plugins_directory")] #[strum(message = "Open Plugins Directory")] OpenPluginsDirectory, #[strum(serialize = "open_grammars_directory")] #[strum(message = "Open Grammars Directory")] OpenGrammarsDirectory, #[strum(serialize = "open_queries_directory")] #[strum(message = "Open Queries Directory")] OpenQueriesDirectory, #[strum(serialize = "zoom_in")] #[strum(message = "Zoom In")] ZoomIn, #[strum(serialize = "zoom_out")] #[strum(message = "Zoom Out")] ZoomOut, #[strum(serialize = "zoom_reset")] #[strum(message = "Reset Zoom")] ZoomReset, #[strum(serialize = "close_window_tab")] #[strum(message = "Close Current Window Tab")] CloseWindowTab, #[strum(serialize = "new_window_tab")] #[strum(message = "Create New Window Tab")] NewWindowTab, #[strum(serialize = "new_terminal_tab")] #[strum(message = "Create New Terminal Tab")] NewTerminalTab, #[strum(serialize = "close_terminal_tab")] #[strum(message = "Close Terminal Tab")] CloseTerminalTab, #[strum(serialize = "next_terminal_tab")] #[strum(message = "Next Terminal Tab")] NextTerminalTab, #[strum(serialize = "previous_terminal_tab")] #[strum(message = "Previous Terminal Tab")] PreviousTerminalTab, #[strum(serialize = "next_window_tab")] #[strum(message = "Go To Next Window Tab")] NextWindowTab, #[strum(serialize = "previous_window_tab")] #[strum(message = "Go To Previous Window Tab")] PreviousWindowTab, #[strum(serialize = "reload_window")] #[strum(message = "Reload Window")] ReloadWindow, #[strum(message = "New Window")] #[strum(serialize = "new_window")] NewWindow, #[strum(message = "Close Window")] #[strum(serialize = "close_window")] CloseWindow, #[strum(message = "New File")] #[strum(serialize = "new_file")] NewFile, #[strum(serialize = "connect_ssh_host")] #[strum(message = "Connect to SSH Host")] ConnectSshHost, #[cfg(windows)] #[strum(serialize = "connect_wsl_host")] #[strum(message = "Connect to WSL Host")] ConnectWslHost, #[strum(serialize = "disconnect_remote")] #[strum(message = "Disconnect From Remote")] DisconnectRemote, #[strum(message = "Go To Line")] #[strum(serialize = "palette.line")] PaletteLine, #[strum(serialize = "palette")] #[strum(message = "Go to File")] Palette, #[strum(message = "Go To Symbol In File")] #[strum(serialize = "palette.symbol")] PaletteSymbol, #[strum(message = "Go To Symbol In Workspace")] #[strum(serialize = "palette.workspace_symbol")] PaletteWorkspaceSymbol, #[strum(message = "Command Palette")] #[strum(serialize = "palette.command")] PaletteCommand, #[strum(message = "Open Recent Workspace")] #[strum(serialize = "palette.workspace")] PaletteWorkspace, #[strum(message = "Run and Debug")] #[strum(serialize = "palette.run_and_debug")] PaletteRunAndDebug, #[strum(message = "Source Control: Checkout")] #[strum(serialize = "palette.scm_references")] PaletteSCMReferences, #[strum(message = "List Palette Types")] #[strum(serialize = "palette.palette_help")] PaletteHelp, #[strum(message = "List Palette Types and Files")] #[strum(serialize = "palette.palette_help_and_file")] PaletteHelpAndFile, #[strum(message = "Run and Debug Restart Current Running")] #[strum(serialize = "palette.run_and_debug_restart")] RunAndDebugRestart, #[strum(message = "Run and Debug Stop Current Running")] #[strum(serialize = "palette.run_and_debug_stop")] RunAndDebugStop, #[strum(serialize = "source_control.checkout_reference")] CheckoutReference, #[strum(serialize = "toggle_maximized_panel")] ToggleMaximizedPanel, #[strum(serialize = "hide_panel")] HidePanel, #[strum(serialize = "show_panel")] ShowPanel, /// Toggles the panel passed in parameter. #[strum(serialize = "toggle_panel_focus")] TogglePanelFocus, /// Toggles the panel passed in parameter. #[strum(serialize = "toggle_panel_visual")] TogglePanelVisual, #[strum(message = "Toggle Left Panel")] #[strum(serialize = "toggle_panel_left_visual")] TogglePanelLeftVisual, #[strum(message = "Toggle Right Panel")] #[strum(serialize = "toggle_panel_right_visual")] TogglePanelRightVisual, #[strum(message = "Toggle Bottom Panel")] #[strum(serialize = "toggle_panel_bottom_visual")] TogglePanelBottomVisual, // Focus toggle commands #[strum(message = "Toggle Terminal Focus")] #[strum(serialize = "toggle_terminal_focus")] ToggleTerminalFocus, #[strum(serialize = "toggle_source_control_focus")] ToggleSourceControlFocus, #[strum(message = "Toggle Plugin Focus")] #[strum(serialize = "toggle_plugin_focus")] TogglePluginFocus, #[strum(message = "Toggle File Explorer Focus")] #[strum(serialize = "toggle_file_explorer_focus")] ToggleFileExplorerFocus, #[strum(message = "Toggle Problem Focus")] #[strum(serialize = "toggle_problem_focus")] ToggleProblemFocus, #[strum(message = "Toggle Search Focus")] #[strum(serialize = "toggle_search_focus")] ToggleSearchFocus, // Visual toggle commands #[strum(serialize = "toggle_terminal_visual")] ToggleTerminalVisual, #[strum(serialize = "toggle_source_control_visual")] ToggleSourceControlVisual, #[strum(serialize = "toggle_plugin_visual")] TogglePluginVisual, #[strum(serialize = "toggle_file_explorer_visual")] ToggleFileExplorerVisual, #[strum(serialize = "toggle_problem_visual")] ToggleProblemVisual, #[strum(serialize = "toggle_debug_visual")] ToggleDebugVisual, #[strum(serialize = "toggle_search_visual")] ToggleSearchVisual, #[strum(serialize = "focus_editor")] FocusEditor, #[strum(serialize = "focus_terminal")] FocusTerminal, #[strum(message = "Source Control: Init")] #[strum(serialize = "source_control_init")] SourceControlInit, #[strum(serialize = "source_control_commit")] SourceControlCommit, #[strum(message = "Source Control: Copy Remote File Url")] #[strum(serialize = "source_control_copy_active_file_remote_url")] SourceControlCopyActiveFileRemoteUrl, #[strum(message = "Source Control: Discard File Changes")] #[strum(serialize = "source_control_discard_active_file_changes")] SourceControlDiscardActiveFileChanges, #[strum(serialize = "source_control_discard_target_file_changes")] SourceControlDiscardTargetFileChanges, #[strum(message = "Source Control: Discard Workspace Changes")] #[strum(serialize = "source_control_discard_workspace_changes")] SourceControlDiscardWorkspaceChanges, #[strum(serialize = "export_current_theme_settings")] #[strum(message = "Export current settings to a theme file")] ExportCurrentThemeSettings, #[strum(serialize = "install_theme")] #[strum(message = "Install current theme file")] InstallTheme, #[strum(serialize = "change_file_language")] #[strum(message = "Change current file language")] ChangeFileLanguage, #[strum(serialize = "change_file_line_ending")] #[strum(message = "Change current file line ending")] ChangeFileLineEnding, #[strum(serialize = "next_editor_tab")] #[strum(message = "Next Editor Tab")] NextEditorTab, #[strum(serialize = "previous_editor_tab")] #[strum(message = "Previous Editor Tab")] PreviousEditorTab, #[strum(serialize = "toggle_inlay_hints")] #[strum(message = "Toggle Inlay Hints")] ToggleInlayHints, #[strum(serialize = "restart_to_update")] RestartToUpdate, #[strum(serialize = "show_about")] #[strum(message = "About Lapce")] ShowAbout, #[strum(message = "Save All Files")] #[strum(serialize = "save_all")] SaveAll, #[cfg(target_os = "macos")] #[strum(message = "Install Lapce to PATH")] #[strum(serialize = "install_to_path")] InstallToPATH, #[cfg(target_os = "macos")] #[strum(message = "Uninstall Lapce from PATH")] #[strum(serialize = "uninstall_from_path")] UninstallFromPATH, #[strum(serialize = "jump_location_backward")] JumpLocationBackward, #[strum(serialize = "jump_location_forward")] JumpLocationForward, #[strum(serialize = "jump_location_backward_local")] JumpLocationBackwardLocal, #[strum(serialize = "jump_location_forward_local")] JumpLocationForwardLocal, #[strum(message = "Next Error in Workspace")] #[strum(serialize = "next_error")] NextError, #[strum(message = "Previous Error in Workspace")] #[strum(serialize = "previous_error")] PreviousError, #[strum(message = "Diff Files")] #[strum(serialize = "diff_files")] DiffFiles, #[strum(serialize = "quit")] #[strum(message = "Quit Editor")] Quit, #[strum(serialize = "go_to_location")] #[strum(message = "Go to Location")] GoToLocation, #[strum(serialize = "add_run_debug_config")] #[strum(message = "Add Run Debug Config")] AddRunDebugConfig, } #[derive(Clone, Debug)] pub enum InternalCommand { ReloadConfig, OpenFile { path: PathBuf, }, OpenAndConfirmedFile { path: PathBuf, }, OpenFileInNewTab { path: PathBuf, }, MakeConfirmed, OpenFileChanges { path: PathBuf, }, ReloadFileExplorer, /// Test whether a file/directory can be created at that path TestPathCreation { new_path: PathBuf, }, FinishRenamePath { current_path: PathBuf, new_path: PathBuf, }, FinishNewNode { is_dir: bool, path: PathBuf, }, FinishDuplicate { source: PathBuf, path: PathBuf, }, GoToLocation { location: EditorLocation, }, JumpToLocation { location: EditorLocation, }, PaletteReferences { references: Vec<EditorLocation>, }, SaveJumpLocation { path: PathBuf, offset: usize, scroll_offset: Vec2, }, Split { direction: SplitDirection, editor_tab_id: EditorTabId, }, SplitMove { direction: SplitMoveDirection, editor_tab_id: EditorTabId, }, SplitExchange { editor_tab_id: EditorTabId, }, NewTerminal { profile: Option<TerminalProfile>, }, SplitTerminal { term_id: TermId, }, SplitTerminalPrevious { term_id: TermId, }, SplitTerminalNext { term_id: TermId, }, SplitTerminalExchange { term_id: TermId, }, EditorTabClose { editor_tab_id: EditorTabId, }, EditorTabChildClose { editor_tab_id: EditorTabId, child: EditorTabChild, }, EditorTabCloseByKind { editor_tab_id: EditorTabId, child: EditorTabChild, kind: TabCloseKind, }, ShowCodeActions { offset: usize, mouse_click: bool, plugin_id: PluginId, code_actions: im::Vector<CodeActionOrCommand>, }, RunCodeAction { plugin_id: PluginId, action: CodeActionOrCommand, }, ApplyWorkspaceEdit { edit: WorkspaceEdit, }, RunAndDebug { mode: RunDebugMode, config: RunDebugConfig, }, StartRename { path: PathBuf, placeholder: String, start: usize, position: Position, }, Search { pattern: Option<String>, }, FindEditorReceiveChar { s: String, }, ReplaceEditorReceiveChar { s: String, }, FindEditorCommand { command: LapceCommand, count: Option<usize>, mods: Modifiers, }, ReplaceEditorCommand { command: LapceCommand, count: Option<usize>, mods: Modifiers, }, FocusEditorTab { editor_tab_id: EditorTabId, }, SetColorTheme { name: String, /// Whether to save the theme to the config file save: bool, }, SetIconTheme { name: String, /// Whether to save the theme to the config file save: bool, }, SetModal { modal: bool, }, UpdateLogLevel { level: tracing_subscriber::filter::LevelFilter, }, OpenWebUri { uri: String, }, ShowAlert { title: String, msg: String, buttons: Vec<AlertButton>, }, HideAlert, SaveScratchDoc { doc: Rc<Doc>, }, SaveScratchDoc2 { doc: Rc<Doc>, }, UpdateProxyStatus { status: ProxyStatus, }, DapFrameScopes { dap_id: DapId, frame_id: usize, }, OpenVoltView { volt_id: VoltID, }, ResetBlinkCursor, OpenDiffFiles { left_path: PathBuf, right_path: PathBuf, }, ExecuteProcess { program: String, arguments: Vec<String>, }, ClearTerminalBuffer { view_id: ViewId, tab_index: usize, terminal_index: usize, }, CallHierarchyIncoming { item_id: ViewId, }, StopTerminal { term_id: TermId, }, RestartTerminal { term_id: TermId, }, } #[derive(Clone)] pub enum WindowCommand { SetWorkspace { workspace: LapceWorkspace, }, CloseWorkspaceTab { index: Option<usize>, }, NewWorkspaceTab { workspace: LapceWorkspace, end: bool, }, NextWorkspaceTab, PreviousWorkspaceTab, NewWindow, CloseWindow, }
rust
Apache-2.0
59ce6df700ce4efbe4498a719fe52195e083d2ee
2026-01-04T15:32:17.267102Z
false
lapce/lapce
https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/source_control.rs
lapce-app/src/source_control.rs
use std::{path::PathBuf, rc::Rc}; use floem::{ keyboard::Modifiers, reactive::{RwSignal, Scope, SignalWith}, }; use indexmap::IndexMap; use lapce_core::mode::Mode; use lapce_rpc::source_control::FileDiff; use crate::{ command::{CommandExecuted, CommandKind}, editor::EditorData, keypress::{KeyPressFocus, condition::Condition}, main_split::Editors, window_tab::CommonData, }; #[derive(Clone, Debug)] pub struct SourceControlData { // VCS modified files & whether they should be included in the next commit pub file_diffs: RwSignal<IndexMap<PathBuf, (FileDiff, bool)>>, pub branch: RwSignal<String>, pub branches: RwSignal<im::Vector<String>>, pub tags: RwSignal<im::Vector<String>>, pub editor: EditorData, pub common: Rc<CommonData>, } impl KeyPressFocus for SourceControlData { fn get_mode(&self) -> Mode { Mode::Insert } fn check_condition(&self, condition: Condition) -> bool { matches!( condition, Condition::PanelFocus | Condition::SourceControlFocus ) } fn run_command( &self, command: &crate::command::LapceCommand, count: Option<usize>, mods: Modifiers, ) -> CommandExecuted { match &command.kind { CommandKind::Edit(_) | CommandKind::Move(_) | CommandKind::MultiSelection(_) => { self.editor.run_command(command, count, mods) } _ => CommandExecuted::No, } } fn receive_char(&self, c: &str) { self.editor.receive_char(c); } } impl SourceControlData { pub fn new(cx: Scope, editors: Editors, common: Rc<CommonData>) -> Self { Self { file_diffs: cx.create_rw_signal(IndexMap::new()), branch: cx.create_rw_signal("".to_string()), branches: cx.create_rw_signal(im::Vector::new()), tags: cx.create_rw_signal(im::Vector::new()), editor: editors.make_local(cx, common.clone()), common, } } pub fn commit(&self) { let diffs: Vec<FileDiff> = self.file_diffs.with_untracked(|file_diffs| { file_diffs .iter() .filter_map( |(_, (diff, checked))| { if *checked { Some(diff) } else { None } }, ) .cloned() .collect() }); if diffs.is_empty() { return; } let message = self .editor .doc() .buffer .with_untracked(|buffer| buffer.to_string()); let message = message.trim(); if message.is_empty() { return; } self.editor.reset(); self.common.proxy.git_commit(message.to_string(), diffs); } }
rust
Apache-2.0
59ce6df700ce4efbe4498a719fe52195e083d2ee
2026-01-04T15:32:17.267102Z
false
lapce/lapce
https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/title.rs
lapce-app/src/title.rs
use std::{rc::Rc, sync::Arc}; use floem::{ View, event::EventListener, menu::{Menu, MenuItem}, peniko::Color, reactive::{ Memo, ReadSignal, RwSignal, SignalGet, SignalUpdate, SignalWith, create_memo, }, style::{AlignItems, CursorStyle, JustifyContent}, views::{Decorators, container, drag_window_area, empty, label, stack, svg}, }; use lapce_core::meta; use lapce_rpc::proxy::ProxyStatus; use crate::{ app::{clickable_icon, not_clickable_icon, tooltip_label, window_menu}, command::{LapceCommand, LapceWorkbenchCommand, WindowCommand}, config::{LapceConfig, color::LapceColor, icon::LapceIcons}, listener::Listener, main_split::MainSplitData, update::ReleaseInfo, window_tab::WindowTabData, workspace::LapceWorkspace, }; fn left( workspace: Arc<LapceWorkspace>, lapce_command: Listener<LapceCommand>, workbench_command: Listener<LapceWorkbenchCommand>, config: ReadSignal<Arc<LapceConfig>>, proxy_status: RwSignal<Option<ProxyStatus>>, num_window_tabs: Memo<usize>, ) -> impl View { let is_local = workspace.kind.is_local(); let is_macos = cfg!(target_os = "macos"); stack(( empty().style(move |s| { let should_hide = if is_macos { num_window_tabs.get() > 1 } else { true }; s.width(75.0).apply_if(should_hide, |s| s.hide()) }), container(svg(move || config.get().ui_svg(LapceIcons::LOGO)).style( move |s| { let config = config.get(); s.size(16.0, 16.0) .color(config.color(LapceColor::LAPCE_ICON_ACTIVE)) }, )) .style(move |s| s.margin_horiz(10.0).apply_if(is_macos, |s| s.hide())), not_clickable_icon( || LapceIcons::MENU, || false, || false, || "Menu", config, ) .popout_menu(move || window_menu(lapce_command, workbench_command)) .style(move |s| { s.margin_left(4.0) .margin_right(6.0) .apply_if(is_macos, |s| s.hide()) }), tooltip_label( config, container(svg(move || config.get().ui_svg(LapceIcons::REMOTE)).style( move |s| { let config = config.get(); let size = (config.ui.icon_size() as f32 + 2.0).min(30.0); s.size(size, size).color(if is_local { config.color(LapceColor::LAPCE_ICON_ACTIVE) } else { match proxy_status.get() { Some(_) => Color::WHITE, None => config.color(LapceColor::LAPCE_ICON_ACTIVE), } }) }, )), || "Connect to Remote", ) .popout_menu(move || { #[allow(unused_mut)] let mut menu = Menu::new("").entry( MenuItem::new("Connect to SSH Host").action(move || { workbench_command.send(LapceWorkbenchCommand::ConnectSshHost); }), ); if !is_local && proxy_status.get().is_some_and(|p| { matches!(p, ProxyStatus::Connecting | ProxyStatus::Connected) }) { menu = menu.entry(MenuItem::new("Disconnect remote").action( move || { workbench_command .send(LapceWorkbenchCommand::DisconnectRemote); }, )); } #[cfg(windows)] { menu = menu.entry(MenuItem::new("Connect to WSL Host").action( move || { workbench_command .send(LapceWorkbenchCommand::ConnectWslHost); }, )); } menu }) .style(move |s| { let config = config.get(); let color = if is_local { Color::TRANSPARENT } else { match proxy_status.get() { Some(ProxyStatus::Connected) => { config.color(LapceColor::LAPCE_REMOTE_CONNECTED) } Some(ProxyStatus::Connecting) => { config.color(LapceColor::LAPCE_REMOTE_CONNECTING) } Some(ProxyStatus::Disconnected) => { config.color(LapceColor::LAPCE_REMOTE_DISCONNECTED) } None => Color::TRANSPARENT, } }; s.height_pct(100.0) .padding_horiz(10.0) .items_center() .background(color) .hover(|s| { s.cursor(CursorStyle::Pointer).background( config.color(LapceColor::PANEL_HOVERED_BACKGROUND), ) }) .active(|s| { s.cursor(CursorStyle::Pointer).background( config.color(LapceColor::PANEL_HOVERED_ACTIVE_BACKGROUND), ) }) }), drag_window_area(empty()) .style(|s| s.height_pct(100.0).flex_basis(0.0).flex_grow(1.0)), )) .style(move |s| { s.height_pct(100.0) .flex_basis(0.0) .flex_grow(1.0) .items_center() }) .debug_name("Left Side of Top Bar") } fn middle( workspace: Arc<LapceWorkspace>, main_split: MainSplitData, workbench_command: Listener<LapceWorkbenchCommand>, config: ReadSignal<Arc<LapceConfig>>, ) -> impl View { let local_workspace = workspace.clone(); let can_jump_backward = { let main_split = main_split.clone(); create_memo(move |_| main_split.can_jump_location_backward(true)) }; let can_jump_forward = create_memo(move |_| main_split.can_jump_location_forward(true)); let jump_backward = move || { clickable_icon( || LapceIcons::LOCATION_BACKWARD, move || { workbench_command.send(LapceWorkbenchCommand::JumpLocationBackward); }, || false, move || !can_jump_backward.get(), || "Jump Backward", config, ) .style(move |s| s.margin_horiz(6.0)) }; let jump_forward = move || { clickable_icon( || LapceIcons::LOCATION_FORWARD, move || { workbench_command.send(LapceWorkbenchCommand::JumpLocationForward); }, || false, move || !can_jump_forward.get(), || "Jump Forward", config, ) .style(move |s| s.margin_right(6.0)) }; let open_folder = move || { not_clickable_icon( || LapceIcons::PALETTE_MENU, || false, || false, || "Open Folder / Recent Workspace", config, ) .popout_menu(move || { Menu::new("") .entry(MenuItem::new("Open Folder").action(move || { workbench_command.send(LapceWorkbenchCommand::OpenFolder); })) .entry(MenuItem::new("Open Recent Workspace").action(move || { workbench_command.send(LapceWorkbenchCommand::PaletteWorkspace); })) }) }; stack(( stack(( drag_window_area(empty()) .style(|s| s.height_pct(100.0).flex_basis(0.0).flex_grow(1.0)), jump_backward(), jump_forward(), )) .style(|s| { s.flex_basis(0) .flex_grow(1.0) .justify_content(Some(JustifyContent::FlexEnd)) }), container( stack(( svg(move || config.get().ui_svg(LapceIcons::SEARCH)).style( move |s| { let config = config.get(); let icon_size = config.ui.icon_size() as f32; s.size(icon_size, icon_size) .color(config.color(LapceColor::LAPCE_ICON_ACTIVE)) }, ), label(move || { if let Some(s) = local_workspace.display() { s } else { "Open Folder".to_string() } }) .style(|s| s.padding_left(10).padding_right(5).selectable(false)), open_folder(), )) .style(|s| s.align_items(Some(AlignItems::Center))), ) .on_event_stop(EventListener::PointerDown, |_| {}) .on_click_stop(move |_| { if workspace.clone().path.is_some() { workbench_command.send(LapceWorkbenchCommand::PaletteHelpAndFile); } else { workbench_command.send(LapceWorkbenchCommand::PaletteWorkspace); } }) .style(move |s| { let config = config.get(); s.flex_basis(0) .flex_grow(10.0) .min_width(200.0) .max_width(500.0) .height(26.0) .justify_content(Some(JustifyContent::Center)) .align_items(Some(AlignItems::Center)) .border(1.0) .border_color(config.color(LapceColor::LAPCE_BORDER)) .border_radius(6.0) .background(config.color(LapceColor::EDITOR_BACKGROUND)) }), stack(( clickable_icon( || LapceIcons::START, move || { workbench_command.send(LapceWorkbenchCommand::PaletteRunAndDebug) }, || false, || false, || "Run and Debug", config, ) .style(move |s| s.margin_horiz(6.0)), drag_window_area(empty()) .style(|s| s.height_pct(100.0).flex_basis(0.0).flex_grow(1.0)), )) .style(move |s| { s.flex_basis(0) .flex_grow(1.0) .justify_content(Some(JustifyContent::FlexStart)) }), )) .style(|s| { s.flex_basis(0) .flex_grow(2.0) .align_items(Some(AlignItems::Center)) .justify_content(Some(JustifyContent::Center)) }) .debug_name("Middle of Top Bar") } fn right( window_command: Listener<WindowCommand>, workbench_command: Listener<LapceWorkbenchCommand>, latest_release: ReadSignal<Arc<Option<ReleaseInfo>>>, update_in_progress: RwSignal<bool>, num_window_tabs: Memo<usize>, window_maximized: RwSignal<bool>, config: ReadSignal<Arc<LapceConfig>>, ) -> impl View { let latest_version = create_memo(move |_| { let latest_release = latest_release.get(); let latest_version = latest_release.as_ref().as_ref().map(|r| r.version.clone()); if latest_version.is_some() && latest_version.as_deref() != Some(meta::VERSION) { latest_version } else { None } }); let has_update = move || latest_version.with(|v| v.is_some()); stack(( drag_window_area(empty()) .style(|s| s.height_pct(100.0).flex_basis(0.0).flex_grow(1.0)), stack(( not_clickable_icon( || LapceIcons::SETTINGS, || false, || false, || "Settings", config, ) .popout_menu(move || { Menu::new("") .entry(MenuItem::new("Command Palette").action(move || { workbench_command.send(LapceWorkbenchCommand::PaletteCommand) })) .separator() .entry(MenuItem::new("Open Settings").action(move || { workbench_command.send(LapceWorkbenchCommand::OpenSettings) })) .entry(MenuItem::new("Open Keyboard Shortcuts").action( move || { workbench_command .send(LapceWorkbenchCommand::OpenKeyboardShortcuts) }, )) .entry(MenuItem::new("Open Theme Color Settings").action( move || { workbench_command .send(LapceWorkbenchCommand::OpenThemeColorSettings) }, )) .separator() .entry(if let Some(v) = latest_version.get_untracked() { if update_in_progress.get_untracked() { MenuItem::new(format!("Update in progress ({v})")) .enabled(false) } else { MenuItem::new(format!("Restart to update ({v})")).action( move || { workbench_command .send(LapceWorkbenchCommand::RestartToUpdate) }, ) } } else { MenuItem::new("No update available").enabled(false) }) .separator() .entry(MenuItem::new("About Lapce").action(move || { workbench_command.send(LapceWorkbenchCommand::ShowAbout) })) }), container(label(|| "1".to_string()).style(move |s| { let config = config.get(); s.font_size(10.0) .color(config.color(LapceColor::EDITOR_BACKGROUND)) .border_radius(100.0) .margin_left(5.0) .margin_top(10.0) .background(config.color(LapceColor::EDITOR_CARET)) })) .style(move |s| { let has_update = has_update(); s.absolute() .size_pct(100.0, 100.0) .justify_end() .items_end() .pointer_events_none() .apply_if(!has_update, |s| s.hide()) }), )) .style(move |s| s.margin_horiz(6.0)), window_controls_view( window_command, true, num_window_tabs, window_maximized, config, ), )) .style(|s| { s.flex_basis(0) .flex_grow(1.0) .justify_content(Some(JustifyContent::FlexEnd)) }) .debug_name("Right of top bar") } pub fn title(window_tab_data: Rc<WindowTabData>) -> impl View { let workspace = window_tab_data.workspace.clone(); let lapce_command = window_tab_data.common.lapce_command; let workbench_command = window_tab_data.common.workbench_command; let window_command = window_tab_data.common.window_common.window_command; let latest_release = window_tab_data.common.window_common.latest_release; let proxy_status = window_tab_data.common.proxy_status; let num_window_tabs = window_tab_data.common.window_common.num_window_tabs; let window_maximized = window_tab_data.common.window_common.window_maximized; let title_height = window_tab_data.title_height; let update_in_progress = window_tab_data.update_in_progress; let config = window_tab_data.common.config; stack(( left( workspace.clone(), lapce_command, workbench_command, config, proxy_status, num_window_tabs, ), middle( workspace, window_tab_data.main_split.clone(), workbench_command, config, ), right( window_command, workbench_command, latest_release, update_in_progress, num_window_tabs, window_maximized, config, ), )) .on_resize(move |rect| { let height = rect.height(); if height != title_height.get_untracked() { title_height.set(height); } }) .style(move |s| { let config = config.get(); s.width_pct(100.0) .height(37.0) .items_center() .background(config.color(LapceColor::PANEL_BACKGROUND)) .border_bottom(1.0) .border_color(config.color(LapceColor::LAPCE_BORDER)) }) .debug_name("Title / Top Bar") } pub fn window_controls_view( window_command: Listener<WindowCommand>, is_title: bool, num_window_tabs: Memo<usize>, window_maximized: RwSignal<bool>, config: ReadSignal<Arc<LapceConfig>>, ) -> impl View { stack(( clickable_icon( || LapceIcons::WINDOW_MINIMIZE, || { floem::action::minimize_window(); }, || false, || false, || "Minimize", config, ) .style(|s| s.margin_right(16.0).margin_left(10.0)), clickable_icon( move || { if window_maximized.get() { LapceIcons::WINDOW_RESTORE } else { LapceIcons::WINDOW_MAXIMIZE } }, move || { floem::action::set_window_maximized( !window_maximized.get_untracked(), ); }, || false, || false, || "Maximize", config, ) .style(|s| s.margin_right(16.0)), clickable_icon( || LapceIcons::WINDOW_CLOSE, move || { window_command.send(WindowCommand::CloseWindow); }, || false, || false, || "Close Window", config, ) .style(|s| s.margin_right(6.0)), )) .style(move |s| { s.apply_if( cfg!(target_os = "macos") || !config.get_untracked().core.custom_titlebar || (is_title && num_window_tabs.get() > 1), |s| s.hide(), ) }) }
rust
Apache-2.0
59ce6df700ce4efbe4498a719fe52195e083d2ee
2026-01-04T15:32:17.267102Z
false
lapce/lapce
https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/palette.rs
lapce-app/src/palette.rs
use std::{ cell::RefCell, collections::{HashMap, HashSet}, path::PathBuf, rc::Rc, sync::{ Arc, atomic::{AtomicU64, Ordering}, mpsc::{Receiver, Sender, TryRecvError, channel}, }, time::Instant, }; use anyhow::Result; use floem::{ ext_event::{create_ext_action, create_signal_from_channel}, keyboard::Modifiers, reactive::{ ReadSignal, RwSignal, Scope, SignalGet, SignalUpdate, SignalWith, use_context, }, }; use im::Vector; use itertools::Itertools; use lapce_core::{ buffer::rope_text::RopeText, command::FocusCommand, language::LapceLanguage, line_ending::LineEnding, mode::Mode, movement::Movement, selection::Selection, syntax::Syntax, }; use lapce_rpc::proxy::ProxyResponse; use lapce_xi_rope::Rope; use lsp_types::{DocumentSymbol, DocumentSymbolResponse}; use nucleo::Utf32Str; use strum::{EnumMessage, IntoEnumIterator}; use tracing::error; use self::{ item::{PaletteItem, PaletteItemContent}, kind::PaletteKind, }; use crate::{ command::{ CommandExecuted, CommandKind, InternalCommand, LapceCommand, WindowCommand, }, db::LapceDb, debug::{RunDebugConfigs, RunDebugMode}, editor::{ EditorData, location::{EditorLocation, EditorPosition}, }, keypress::{KeyPressData, KeyPressFocus, condition::Condition}, lsp::path_from_url, main_split::MainSplitData, source_control::SourceControlData, window_tab::{CommonData, Focus}, workspace::{LapceWorkspace, LapceWorkspaceType, SshHost}, }; pub mod item; pub mod kind; pub const DEFAULT_RUN_TOML: &str = include_str!("../../defaults/run.toml"); #[derive(Clone, PartialEq, Eq)] pub enum PaletteStatus { Inactive, Started, Done, } #[derive(Clone, Debug)] pub struct PaletteInput { pub input: String, pub kind: PaletteKind, } impl PaletteInput { /// Update the current input in the palette, and the kind of palette it is pub fn update_input(&mut self, input: String, kind: PaletteKind) { self.kind = kind.get_palette_kind(&input); self.input = self.kind.get_input(&input).to_string(); } } #[derive(Clone)] pub struct PaletteData { run_id_counter: Arc<AtomicU64>, pub run_id: RwSignal<u64>, pub workspace: Arc<LapceWorkspace>, pub status: RwSignal<PaletteStatus>, pub index: RwSignal<usize>, pub preselect_index: RwSignal<Option<usize>>, pub items: RwSignal<im::Vector<PaletteItem>>, pub filtered_items: ReadSignal<im::Vector<PaletteItem>>, pub input: RwSignal<PaletteInput>, kind: RwSignal<PaletteKind>, pub input_editor: EditorData, pub preview_editor: EditorData, pub has_preview: RwSignal<bool>, pub keypress: ReadSignal<KeyPressData>, /// Listened on for which entry in the palette has been clicked pub clicked_index: RwSignal<Option<usize>>, pub executed_commands: Rc<RefCell<HashMap<String, Instant>>>, pub executed_run_configs: Rc<RefCell<HashMap<(RunDebugMode, String), Instant>>>, pub main_split: MainSplitData, pub references: RwSignal<Vec<EditorLocation>>, pub source_control: SourceControlData, pub common: Rc<CommonData>, left_diff_path: RwSignal<Option<PathBuf>>, } impl std::fmt::Debug for PaletteData { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("PaletteData").finish() } } impl PaletteData { pub fn new( cx: Scope, workspace: Arc<LapceWorkspace>, main_split: MainSplitData, keypress: ReadSignal<KeyPressData>, source_control: SourceControlData, common: Rc<CommonData>, ) -> Self { let status = cx.create_rw_signal(PaletteStatus::Inactive); let items = cx.create_rw_signal(im::Vector::new()); let preselect_index = cx.create_rw_signal(None); let index = cx.create_rw_signal(0); let references = cx.create_rw_signal(Vec::new()); let input = cx.create_rw_signal(PaletteInput { input: "".to_string(), kind: PaletteKind::File, }); let kind = cx.create_rw_signal(PaletteKind::File); let input_editor = main_split.editors.make_local(cx, common.clone()); let preview_editor = main_split.editors.make_local(cx, common.clone()); let has_preview = cx.create_rw_signal(false); let run_id = cx.create_rw_signal(0); let run_id_counter = Arc::new(AtomicU64::new(0)); let (run_tx, run_rx) = channel(); { let run_id = run_id.read_only(); let input = input.read_only(); let items = items.read_only(); let tx = run_tx; { let tx = tx.clone(); // this effect only monitors items change cx.create_effect(move |_| { let items = items.get(); let input = input.get_untracked(); let run_id = run_id.get_untracked(); let preselect_index = preselect_index.try_update(|i| i.take()).unwrap(); if let Err(err) = tx.send((run_id, input.input, items, preselect_index)) { tracing::error!("{:?}", err); } }); } // this effect only monitors input change cx.create_effect(move |last_kind| { let input = input.get(); let kind = input.kind; if last_kind != Some(kind) { return kind; } let items = items.get_untracked(); let run_id = run_id.get_untracked(); if let Err(err) = tx.send((run_id, input.input, items, None)) { tracing::error!("{:?}", err); } kind }); } let (resp_tx, resp_rx) = channel(); { let run_id = run_id_counter.clone(); std::thread::Builder::new() .name("PaletteUpdateProcess".to_owned()) .spawn(move || { Self::update_process(run_id, run_rx, resp_tx); }) .unwrap(); } let (filtered_items, set_filtered_items) = cx.create_signal(im::Vector::new()); { let resp = create_signal_from_channel(resp_rx); let run_id = run_id.read_only(); let input = input.read_only(); cx.create_effect(move |_| { if let Some(( filter_run_id, filter_input, new_items, preselect_index, )) = resp.get() { if run_id.get_untracked() == filter_run_id && input.get_untracked().input == filter_input { set_filtered_items.set(new_items); let i = preselect_index.unwrap_or(0); index.set(i); } } }); } let clicked_index = cx.create_rw_signal(Option::<usize>::None); let left_diff_path = cx.create_rw_signal(None); let palette = Self { run_id_counter, main_split, run_id, workspace, status, index, preselect_index, items, filtered_items, input_editor, preview_editor, has_preview, input, kind, keypress, clicked_index, executed_commands: Rc::new(RefCell::new(HashMap::new())), executed_run_configs: Rc::new(RefCell::new(HashMap::new())), references, source_control, common, left_diff_path, }; { let palette = palette.clone(); let clicked_index = clicked_index.read_only(); let index = index.write_only(); cx.create_effect(move |_| { if let Some(clicked_index) = clicked_index.get() { index.set(clicked_index); palette.select(); } }); } { let palette = palette.clone(); let doc = palette.input_editor.doc(); let input = palette.input; let status = palette.status.read_only(); let preset_kind = palette.kind.read_only(); // Monitors when the palette's input changes, so that it can update the stored input // and kind of palette. cx.create_effect(move |last_input| { // TODO(minor, perf): this could have perf issues if the user accidentally pasted a huge amount of text into the palette. let new_input = doc.buffer.with(|buffer| buffer.to_string()); let status = status.get_untracked(); if status == PaletteStatus::Inactive { // If the status is inactive, we set the input to None, // so that when we actually run the palette, the input // can be compared with this None. return None; } let last_input = last_input.flatten(); // If the input is not equivalent to the current input, or not initialized, then we // need to update the information about the palette. let changed = last_input.as_deref() != Some(new_input.as_str()); if changed { let new_kind = input .try_update(|input| { let kind = input.kind; input.update_input( new_input.clone(), preset_kind.get_untracked(), ); if last_input.is_none() || kind != input.kind { Some(input.kind) } else { None } }) .unwrap(); if let Some(new_kind) = new_kind { palette.run_inner(new_kind); } else if input .with_untracked(|i| i.kind == PaletteKind::WorkspaceSymbol) { palette.run_inner(PaletteKind::WorkspaceSymbol); } } Some(new_input) }); } { let palette = palette.clone(); cx.create_effect(move |_| { let _ = palette.index.get(); palette.preview(); }); } { let palette = palette.clone(); cx.create_effect(move |_| { let focus = palette.common.focus.get(); if focus != Focus::Palette && palette.status.get_untracked() != PaletteStatus::Inactive { palette.cancel(); } }); } palette } /// Start and focus the palette for the given kind. pub fn run(&self, kind: PaletteKind) { self.common.focus.set(Focus::Palette); self.status.set(PaletteStatus::Started); let symbol = kind.symbol(); self.kind.set(kind); // Refresh the palette input with only the symbol prefix, losing old content. self.input_editor.doc().reload(Rope::from(symbol), true); self.input_editor .cursor() .update(|cursor| cursor.set_insert(Selection::caret(symbol.len()))); } /// Get the placeholder text to use in the palette input field. pub fn placeholder_text(&self) -> &'static str { match self.kind.get() { PaletteKind::SshHost => { "Type [user@]host or select a previously connected workspace below" } PaletteKind::DiffFiles => { if self.left_diff_path.with(Option::is_some) { "Select right file" } else { "Seleft left file" } } _ => "", } } /// Execute the internal behavior of the palette for the given kind. This ignores updating and /// focusing the palette input. fn run_inner(&self, kind: PaletteKind) { self.has_preview.set(false); let run_id = self.run_id_counter.fetch_add(1, Ordering::Relaxed) + 1; self.run_id.set(run_id); match kind { PaletteKind::PaletteHelp => self.get_palette_help(), PaletteKind::File | PaletteKind::DiffFiles => { self.get_files(); } PaletteKind::HelpAndFile => self.get_palette_help_and_file(), PaletteKind::Line => { self.get_lines(); } PaletteKind::Command => { self.get_commands(); } PaletteKind::Workspace => { self.get_workspaces(); } PaletteKind::Reference => { self.get_references(); } PaletteKind::DocumentSymbol => { self.get_document_symbols(); } PaletteKind::WorkspaceSymbol => { self.get_workspace_symbols(); } PaletteKind::SshHost => { self.get_ssh_hosts(); } #[cfg(windows)] PaletteKind::WslHost => { self.get_wsl_hosts(); } PaletteKind::RunAndDebug => { self.get_run_configs(); } PaletteKind::ColorTheme => { self.get_color_themes(); } PaletteKind::IconTheme => { self.get_icon_themes(); } PaletteKind::Language => { self.get_languages(); } PaletteKind::LineEnding => { self.get_line_endings(); } PaletteKind::SCMReferences => { self.get_scm_references(); } PaletteKind::TerminalProfile => self.get_terminal_profiles(), } } /// Initialize the palette with a list of the available palette kinds. fn get_palette_help(&self) { let items = self.get_palette_help_items(); self.items.set(items); } fn get_palette_help_items(&self) -> Vector<PaletteItem> { PaletteKind::iter() .filter_map(|kind| { // Don't include PaletteHelp as the user is already here. (kind != PaletteKind::PaletteHelp) .then(|| { let symbol = kind.symbol(); // Only include palette kinds accessible by typing a prefix into the // palette. (kind == PaletteKind::File || !symbol.is_empty()) .then_some(kind) }) .flatten() }) .filter_map(|kind| kind.command().map(|cmd| (kind, cmd))) .map(|(kind, cmd)| { let description = kind.symbol().to_string() + " " + cmd.get_message().unwrap_or(""); PaletteItem { content: PaletteItemContent::PaletteHelp { cmd }, filter_text: description, score: 0, indices: vec![], } }) .collect() } fn get_palette_help_and_file(&self) { let help_items: Vector<PaletteItem> = self.get_palette_help_items(); self.get_files_and_prepend(Some(help_items)); } // get the files in the current workspace // and prepend items if prepend is some // e.g. help_and_file fn get_files_and_prepend(&self, prepend: Option<im::Vector<PaletteItem>>) { let workspace = self.workspace.clone(); let set_items = self.items.write_only(); let send = create_ext_action(self.common.scope, move |items: Vec<PathBuf>| { let items = items .into_iter() .map(|full_path| { // Strip the workspace prefix off the path, to avoid clutter let path = if let Some(workspace_path) = workspace.path.as_ref() { full_path .strip_prefix(workspace_path) .unwrap_or(&full_path) .to_path_buf() } else { full_path.clone() }; let filter_text = path.to_string_lossy().into_owned(); PaletteItem { content: PaletteItemContent::File { path, full_path }, filter_text, score: 0, indices: Vec::new(), } }) .collect::<im::Vector<_>>(); let mut new_items = im::Vector::new(); if let Some(prepend) = prepend { new_items.append(prepend); } new_items.append(items); set_items.set(new_items); }); self.common.proxy.get_files(move |result| { if let Ok(ProxyResponse::GetFilesResponse { items }) = result { send(items); } }); } /// Initialize the palette with the files in the current workspace. fn get_files(&self) { self.get_files_and_prepend(None); } /// Initialize the palette with the lines in the current document. fn get_lines(&self) { let editor = self.main_split.active_editor.get_untracked(); let doc = match editor { Some(editor) => editor.doc(), None => { return; } }; let buffer = doc.buffer.get_untracked(); let last_line_number = buffer.last_line() + 1; let last_line_number_len = last_line_number.to_string().len(); let items = buffer .text() .lines(0..buffer.len()) .enumerate() .map(|(i, l)| { let line_number = i + 1; let text = format!( "{}{} {}", line_number, vec![" "; last_line_number_len - line_number.to_string().len()] .join(""), l ); PaletteItem { content: PaletteItemContent::Line { line: i, content: text.clone(), }, filter_text: text, score: 0, indices: vec![], } }) .collect(); self.items.set(items); } fn get_commands(&self) { const EXCLUDED_ITEMS: &[&str] = &["palette.command"]; let items = self.keypress.with_untracked(|keypress| { // Get all the commands we've executed, and sort them by how recently they were // executed. Ignore commands without descriptions. let mut items: im::Vector<PaletteItem> = self .executed_commands .borrow() .iter() .sorted_by_key(|(_, i)| *i) .rev() .filter_map(|(key, _)| { keypress.commands.get(key).and_then(|c| { c.kind.desc().as_ref().map(|m| PaletteItem { content: PaletteItemContent::Command { cmd: c.clone() }, filter_text: m.to_string(), score: 0, indices: vec![], }) }) }) .collect(); // Add all the rest of the commands, ignoring palette commands (because we're in it) // and commands that are sorted earlier due to being executed. items.extend(keypress.commands.iter().filter_map(|(_, c)| { if EXCLUDED_ITEMS.contains(&c.kind.str()) { return None; } if self.executed_commands.borrow().contains_key(c.kind.str()) { return None; } c.kind.desc().as_ref().map(|m| PaletteItem { content: PaletteItemContent::Command { cmd: c.clone() }, filter_text: m.to_string(), score: 0, indices: vec![], }) })); items }); self.items.set(items); } /// Initialize the palette with all the available workspaces, local and remote. fn get_workspaces(&self) { let db: Arc<LapceDb> = use_context().unwrap(); let workspaces = db.recent_workspaces().unwrap_or_default(); let items = workspaces .into_iter() .filter_map(|w| { let text = w.path.as_ref()?.to_str()?.to_string(); let filter_text = match &w.kind { LapceWorkspaceType::Local => text, LapceWorkspaceType::RemoteSSH(remote) => { format!("[{remote}] {text}") } #[cfg(windows)] LapceWorkspaceType::RemoteWSL(remote) => { format!("[{remote}] {text}") } }; Some(PaletteItem { content: PaletteItemContent::Workspace { workspace: w }, filter_text, score: 0, indices: vec![], }) }) .collect(); self.items.set(items); } /// Initialize the list of references in the file, from the current editor location. fn get_references(&self) { let items = self .references .get_untracked() .into_iter() .map(|l| { let full_path = l.path.clone(); let mut path = l.path.clone(); if let Some(workspace_path) = self.workspace.path.as_ref() { path = path .strip_prefix(workspace_path) .unwrap_or(&full_path) .to_path_buf(); } let filter_text = path.to_str().unwrap_or("").to_string(); PaletteItem { content: PaletteItemContent::Reference { path, location: l }, filter_text, score: 0, indices: vec![], } }) .collect(); self.items.set(items); } fn get_document_symbols(&self) { let editor = self.main_split.active_editor.get_untracked(); let doc = match editor { Some(editor) => editor.doc(), None => { self.items.update(|items| items.clear()); return; } }; let path = doc .content .with_untracked(|content| content.path().cloned()); let path = match path { Some(path) => path, None => { self.items.update(|items| items.clear()); return; } }; let set_items = self.items.write_only(); let send = create_ext_action(self.common.scope, move |result| { if let Ok(ProxyResponse::GetDocumentSymbols { resp }) = result { let items = Self::format_document_symbol_resp(resp); set_items.set(items); } else { set_items.update(|items| items.clear()); } }); self.common.proxy.get_document_symbols(path, move |result| { send(result); }); } fn format_document_symbol_resp( resp: DocumentSymbolResponse, ) -> im::Vector<PaletteItem> { match resp { DocumentSymbolResponse::Flat(symbols) => symbols .iter() .map(|s| { let mut filter_text = s.name.clone(); if let Some(container_name) = s.container_name.as_ref() { filter_text += container_name; } PaletteItem { content: PaletteItemContent::DocumentSymbol { kind: s.kind, name: s.name.replace('\n', "↵"), range: s.location.range, container_name: s.container_name.clone(), }, filter_text, score: 0, indices: Vec::new(), } }) .collect(), DocumentSymbolResponse::Nested(symbols) => { let mut items = im::Vector::new(); for s in symbols { Self::format_document_symbol(&mut items, None, s) } items } } } fn format_document_symbol( items: &mut im::Vector<PaletteItem>, parent: Option<String>, s: DocumentSymbol, ) { items.push_back(PaletteItem { content: PaletteItemContent::DocumentSymbol { kind: s.kind, name: s.name.replace('\n', "↵"), range: s.range, container_name: parent, }, filter_text: s.name.clone(), score: 0, indices: Vec::new(), }); if let Some(children) = s.children { let parent = Some(s.name.replace('\n', "↵")); for child in children { Self::format_document_symbol(items, parent.clone(), child); } } } fn get_workspace_symbols(&self) { let input = self.input.get_untracked().input; let set_items = self.items.write_only(); let send = create_ext_action(self.common.scope, move |result| { if let Ok(ProxyResponse::GetWorkspaceSymbols { symbols }) = result { let items: im::Vector<PaletteItem> = symbols .iter() .map(|s| { // TODO: Should we be using filter text? let mut filter_text = s.name.clone(); if let Some(container_name) = s.container_name.as_ref() { filter_text += container_name; } PaletteItem { content: PaletteItemContent::WorkspaceSymbol { kind: s.kind, name: s.name.clone(), location: EditorLocation { path: path_from_url(&s.location.uri), position: Some(EditorPosition::Position( s.location.range.start, )), scroll_offset: None, ignore_unconfirmed: false, same_editor_tab: false, }, container_name: s.container_name.clone(), }, filter_text, score: 0, indices: Vec::new(), } }) .collect(); set_items.set(items); } else { set_items.update(|items| items.clear()); } }); self.common .proxy .get_workspace_symbols(input, move |result| { send(result); }); } fn get_ssh_hosts(&self) { let db: Arc<LapceDb> = use_context().unwrap(); let workspaces = db.recent_workspaces().unwrap_or_default(); let mut hosts = HashSet::new(); for workspace in workspaces.iter() { if let LapceWorkspaceType::RemoteSSH(host) = &workspace.kind { hosts.insert(host.clone()); } } let items = hosts .iter() .map(|host| PaletteItem { content: PaletteItemContent::SshHost { host: host.clone() }, filter_text: host.to_string(), score: 0, indices: vec![], }) .collect(); self.items.set(items); } #[cfg(windows)] fn get_wsl_hosts(&self) { use std::{os::windows::process::CommandExt, process}; let cmd = process::Command::new("wsl") .creation_flags(0x08000000) // CREATE_NO_WINDOW .arg("-l") .arg("-v") .stdout(process::Stdio::piped()) .output(); let distros = if let Ok(proc) = cmd { let distros = String::from_utf16(bytemuck::cast_slice(&proc.stdout)) .unwrap_or_default() .lines() .skip(1) .filter_map(|line| { let line = line.trim_start(); // let default = line.starts_with('*'); let name = line .trim_start_matches('*') .trim_start() .split(' ') .next()?; Some(name.to_string()) }) .collect(); distros } else { vec![] }; let db: Arc<LapceDb> = use_context().unwrap(); let workspaces = db.recent_workspaces().unwrap_or_default(); let mut hosts = HashSet::new(); for distro in distros { hosts.insert(distro); } for workspace in workspaces.iter() { if let LapceWorkspaceType::RemoteWSL(host) = &workspace.kind { hosts.insert(host.host.clone()); } } let items = hosts .iter() .map(|host| PaletteItem { content: PaletteItemContent::WslHost { host: crate::workspace::WslHost { host: host.clone() }, }, filter_text: host.to_string(), score: 0, indices: vec![], }) .collect(); self.items.set(items); } fn set_run_configs(&self, content: String) { let configs: Option<RunDebugConfigs> = toml::from_str(&content).ok(); if configs.is_none() { if let Some(path) = self.workspace.path.as_ref() { let path = path.join(".lapce").join("run.toml"); self.common .internal_command .send(InternalCommand::OpenFile { path }); } } let executed_run_configs = self.executed_run_configs.borrow(); let mut items = Vec::new(); if let Some(configs) = configs.as_ref() { for config in &configs.configs { items.push(( executed_run_configs .get(&(RunDebugMode::Run, config.name.clone())), PaletteItem { content: PaletteItemContent::RunAndDebug { mode: RunDebugMode::Run, config: config.clone(), }, filter_text: format!( "Run {} {} {}", config.name, config.program, config.args.clone().unwrap_or_default().join(" ") ), score: 0, indices: vec![], }, )); if config.ty.is_some() {
rust
Apache-2.0
59ce6df700ce4efbe4498a719fe52195e083d2ee
2026-01-04T15:32:17.267102Z
true
lapce/lapce
https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/update.rs
lapce-app/src/update.rs
use std::path::{Path, PathBuf}; use anyhow::{Result, anyhow}; use lapce_core::{directory::Directory, meta}; use serde::Deserialize; #[derive(Clone, Deserialize, Debug)] pub struct ReleaseInfo { pub tag_name: String, pub target_commitish: String, pub assets: Vec<ReleaseAsset>, #[serde(skip)] pub version: String, } #[derive(Clone, Deserialize, Debug)] pub struct ReleaseAsset { pub name: String, pub browser_download_url: String, } pub fn get_latest_release() -> Result<ReleaseInfo> { let url = match meta::RELEASE { meta::ReleaseType::Debug => { return Err(anyhow!("no release for debug")); } meta::ReleaseType::Nightly => { "https://api.github.com/repos/lapce/lapce/releases/tags/nightly" } _ => "https://api.github.com/repos/lapce/lapce/releases/latest", }; let resp = lapce_proxy::get_url(url, Some("Lapce"))?; if !resp.status().is_success() { return Err(anyhow!("get release info failed {}", resp.text()?)); } let mut release: ReleaseInfo = serde_json::from_str(&resp.text()?)?; release.version = match release.tag_name.as_str() { "nightly" => format!( "{}+Nightly.{}", env!("CARGO_PKG_VERSION"), &release.target_commitish[..7] ), _ => release .tag_name .strip_prefix('v') .unwrap_or(&release.tag_name) .to_owned(), }; Ok(release) } pub fn download_release(release: &ReleaseInfo) -> Result<PathBuf> { let dir = Directory::updates_directory().ok_or_else(|| anyhow!("no directory"))?; let name = match std::env::consts::OS { "macos" => "Lapce-macos.dmg", "linux" => match std::env::consts::ARCH { "aarch64" => "lapce-linux-arm64.tar.gz", "x86_64" => "lapce-linux-amd64.tar.gz", _ => return Err(anyhow!("arch not supported")), }, #[cfg(feature = "portable")] "windows" => "Lapce-windows-portable.zip", #[cfg(not(feature = "portable"))] "windows" => "Lapce-windows.msi", _ => return Err(anyhow!("os not supported")), }; let file_path = dir.join(name); for asset in &release.assets { if asset.name == name { let mut resp = lapce_proxy::get_url(&asset.browser_download_url, None)?; if !resp.status().is_success() { return Err(anyhow!("download file error {}", resp.text()?)); } let mut out = std::fs::File::create(&file_path)?; resp.copy_to(&mut out)?; return Ok(file_path); } } Err(anyhow!("can't download release")) } #[cfg(target_os = "macos")] pub fn extract(src: &Path, process_path: &Path) -> Result<PathBuf> { let info = dmg::Attach::new(src).with()?; let dest = process_path.parent().ok_or_else(|| anyhow!("no parent"))?; let dest = if dest.file_name().and_then(|s| s.to_str()) == Some("MacOS") { dest.parent().unwrap().parent().unwrap().parent().unwrap() } else { dest }; std::fs::remove_dir_all(dest.join("Lapce.app"))?; fs_extra::copy_items( &[info.mount_point.join("Lapce.app")], dest, &fs_extra::dir::CopyOptions { overwrite: true, skip_exist: false, buffer_size: 64000, copy_inside: true, content_only: false, depth: 0, }, )?; Ok(dest.join("Lapce.app")) } #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] pub fn extract(src: &Path, process_path: &Path) -> Result<PathBuf> { let tar_gz = std::fs::File::open(src)?; let tar = flate2::read::GzDecoder::new(tar_gz); let mut archive = tar::Archive::new(tar); let parent = src.parent().ok_or_else(|| anyhow::anyhow!("no parent"))?; archive.unpack(parent)?; std::fs::remove_file(process_path)?; std::fs::copy(parent.join("Lapce").join("lapce"), process_path)?; Ok(process_path.to_path_buf()) } #[cfg(all(target_os = "windows", feature = "portable"))] pub fn extract(src: &Path, process_path: &Path) -> Result<PathBuf> { let parent = src .parent() .ok_or_else(|| anyhow::anyhow!("src has no parent"))?; let dst_parent = process_path .parent() .ok_or_else(|| anyhow::anyhow!("process_path has no parent"))?; { let mut archive = zip::ZipArchive::new(std::fs::File::open(src)?)?; archive.extract(parent)?; } // TODO(dbuga): instead of replacing the exe, run the msi installer for non-portable // TODO(dbuga): there's a very slight chance the user might end up with a backup file without a working .exe std::fs::rename(process_path, dst_parent.join("lapce.exe.bak"))?; std::fs::copy(parent.join("lapce.exe"), process_path)?; Ok(process_path.to_path_buf()) } #[cfg(all(target_os = "windows", not(feature = "portable")))] pub fn extract(src: &Path, _process_path: &Path) -> Result<PathBuf> { // We downloaded an uncompressed msi installer, nothing to extract. // On the other hand, we need to run this msi so pass its path back out. Ok(src.to_path_buf()) } #[cfg(target_os = "macos")] pub fn restart(path: &Path) -> Result<()> { use std::os::unix::process::CommandExt; let _ = std::process::Command::new("open") .arg("-n") .arg(path) .arg("--args") .arg("-n") .exec(); Ok(()) } #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] pub fn restart(path: &Path) -> Result<()> { use std::os::unix::process::CommandExt; let _ = std::process::Command::new(path).arg("-n").exec(); Ok(()) } #[cfg(all(target_os = "windows", feature = "portable"))] pub fn restart(path: &Path) -> Result<()> { use std::os::windows::process::CommandExt; const DETACHED_PROCESS: u32 = 0x00000008; let process_id = std::process::id(); let path = path .to_str() .ok_or_else(|| anyhow!("can't get path to str"))?; std::process::Command::new("cmd") .raw_arg(format!( r#"/C taskkill /PID {process_id} & start "" "{path}""# )) .creation_flags(DETACHED_PROCESS) .spawn()?; Ok(()) } #[cfg(all(target_os = "windows", not(feature = "portable")))] pub fn restart(path: &Path) -> Result<()> { use std::os::windows::process::CommandExt; const DETACHED_PROCESS: u32 = 0x00000008; let process_id = std::process::id(); let path = path .to_str() .ok_or_else(|| anyhow!("can't get path to str"))?; let lapce_exe = std::env::current_exe() .map_err(|err| anyhow!("can't get path to exe").context(err))?; let lapce_exe = lapce_exe .to_str() .ok_or_else(|| anyhow!("can't convert exe path to str"))?; std::process::Command::new("cmd") .raw_arg(format!( r#"/C taskkill /PID {process_id} & msiexec /i "{path}" /qb & start "" "{lapce_exe}""#, )) .creation_flags(DETACHED_PROCESS) .spawn()?; Ok(()) } #[cfg(all(target_os = "windows", feature = "portable"))] pub fn cleanup() { // Clean up backup exe after an update if let Ok(process_path) = std::env::current_exe() { if let Some(dst_parent) = process_path.parent() { if let Err(err) = std::fs::remove_file(dst_parent.join("lapce.exe.bak")) { tracing::error!("{:?}", err); } } } } #[cfg(any( not(target_os = "windows"), all(target_os = "windows", not(feature = "portable")) ))] pub fn cleanup() { // Nothing to do yet }
rust
Apache-2.0
59ce6df700ce4efbe4498a719fe52195e083d2ee
2026-01-04T15:32:17.267102Z
false
lapce/lapce
https://github.com/lapce/lapce/blob/59ce6df700ce4efbe4498a719fe52195e083d2ee/lapce-app/src/code_lens.rs
lapce-app/src/code_lens.rs
use std::rc::Rc; use lapce_rpc::dap_types::{ConfigSource, RunDebugConfig}; use serde::{Deserialize, Serialize}; use serde_json::Value; use crate::{command::InternalCommand, debug::RunDebugMode, window_tab::CommonData}; #[derive(Serialize, Deserialize)] struct CargoArgs { #[serde(rename = "cargoArgs")] pub cargo_args: Vec<String>, #[serde(rename = "cargoExtraArgs")] pub cargo_extra_args: Vec<String>, #[serde(rename = "executableArgs")] pub executable_args: Vec<String>, } #[derive(Serialize, Deserialize)] struct RustArgs { pub args: CargoArgs, pub kind: String, pub label: String, pub location: lsp_types::LocationLink, } #[derive(Clone)] pub struct CodeLensData { common: Rc<CommonData>, } impl CodeLensData { pub fn new(common: Rc<CommonData>) -> Self { Self { common } } pub fn run(&self, command: &str, args: Vec<Value>) { match command { "rust-analyzer.runSingle" | "rust-analyzer.debugSingle" => { let mode = if command == "rust-analyzer.runSingle" { RunDebugMode::Run } else { RunDebugMode::Debug }; if let Some(config) = self.get_rust_command_config(&args, mode) { self.common .internal_command .send(InternalCommand::RunAndDebug { mode, config }); } } _ => { tracing::debug!("todo {:}", command); } } } fn get_rust_command_config( &self, args: &[Value], mode: RunDebugMode, ) -> Option<RunDebugConfig> { if let Some(args) = args.first() { let Ok(mut cargo_args) = serde_json::from_value::<RustArgs>(args.clone()) else { tracing::error!("serde error"); return None; }; cargo_args .args .cargo_args .extend(cargo_args.args.cargo_extra_args); if !cargo_args.args.executable_args.is_empty() { cargo_args.args.cargo_args.push("--".to_string()); cargo_args .args .cargo_args .extend(cargo_args.args.executable_args); } Some(RunDebugConfig { ty: None, name: cargo_args.label, program: cargo_args.kind, args: Some(cargo_args.args.cargo_args), cwd: None, env: None, prelaunch: None, debug_command: None, dap_id: Default::default(), tracing_output: mode == RunDebugMode::Debug, config_source: ConfigSource::CodeLens, }) } else { tracing::error!("no args"); None } } }
rust
Apache-2.0
59ce6df700ce4efbe4498a719fe52195e083d2ee
2026-01-04T15:32:17.267102Z
false