### Run Example Source: https://github.com/marc2332/freya/blob/main/CONTRIBUTING.md Runs an example from the /examples folder. ```shell cargo run --example counter ``` -------------------------------- ### Gradient Syntax Example Source: https://github.com/marc2332/freya/blob/main/website/src/content/blog/0.3.md Provides an example of the syntax for linear, radial, and conic gradients. ```rust fn app() -> Element { let mut gradient = use_signal(|| GradientExample::Linear); let background = match *gradient.read() { GradientExample::Linear => { "linear-gradient(250deg, orange 15%, rgb(255, 0, 0) 50%, rgb(255, 192, 203) 80%)" } GradientExample::Radial => { "radial-gradient(orange 15%, rgb(255, 0, 0) 50%, rgb(255, 192, 203) 80%)" } GradientExample::Conic => { "conic-gradient(250deg, orange 15%, rgb(255, 0, 0) 50%, rgb(255, 192, 203) 80%)" } }; rsx!( rect { background, ... } ) } ``` -------------------------------- ### Counter Example Source: https://github.com/marc2332/freya/blob/main/website/public/llms.txt A simple counter example demonstrating state management and UI updates in Freya. ```rust fn app() -> impl IntoElement { let mut count = use_state(|| 4); let counter = rect() .width(Size::fill()) .height(Size::percent(50.)) .center() .color((255, 255, 255)) .background((15, 163, 242)) .font_weight(FontWeight::BOLD) .font_size(75.) .shadow((0., 4., 20., 4., (0, 0, 0, 80))) .child(count.read().to_string()); let actions = rect() .horizontal() .width(Size::fill()) .height(Size::percent(50.)) .center() .spacing(8.0) .child( Button::new() .on_press(move |_| { *count.write() += 1; }) .child("Increase"), ) .child( Button::new() .on_press(move |_| { *count.write() -= 1; }) .child("Decrease"), ); rect().child(counter).child(actions) } ``` -------------------------------- ### Theming Example Source: https://github.com/marc2332/freya/blob/main/website/src/content/blog/0.2.md Shows how to override component themes with custom props. ```rust rsx!( Button { theme: theme_with!(ButtonTheme { padding: "0".into(), // Passing custom padding before was possible hover_background: "black".into() // But passing custom hover wasn't possible }), label { "Hello, World!" } } ) ``` -------------------------------- ### Install Cargo Tools Source: https://github.com/marc2332/freya/blob/main/CONTRIBUTING.md Installs just, taplo, and cargo-nextest using cargo. ```shell cargo install just taplo-cli cargo-nextest ``` -------------------------------- ### Install Cargo Tools (binstall) Source: https://github.com/marc2332/freya/blob/main/CONTRIBUTING.md Installs just, taplo, and cargo-nextest using cargo binstall for faster installation. ```shell cargo binstall just taplo-cli cargo-nextest ``` -------------------------------- ### use_animation Example: Multiple Animations Source: https://github.com/marc2332/freya/blob/main/website/src/content/blog/0.2.md Demonstrates using use_animation for multiple concurrent animations. This example animates both a width and a color, starting automatically and reversing upon completion. ```rust // Create animation let animation = use_animation(|ctx| { ctx.auto_start(true); // Start the animation when this component is mounted ctx.on_finish(OnFinish::Reverse); // When the animation finishes, run it in reverse of the last run ( ctx.with(AnimNum::new(0., 100.).time(200)), // Animate a value from 0 to 100 in 200ms ctx.with(AnimColor::new("rgb(245, 25, 30)", "blue").time(200)) // Animate a color transition in 200ms ) }); // Retrieve values let (width, color) = animation.get(); let width = width.read().as_f32(); let background = color.read().as_string(); // UI rsx!( rect { height: "100%", width: "{width}", background: "{background}" } ) ``` -------------------------------- ### Plugins API Example Source: https://github.com/marc2332/freya/blob/main/website/src/content/blog/0.2.md Demonstrates the implementation and registration of a Freya plugin. ```rust struct BlogPlugin; impl FreyaPlugin for BlogPlugin { fn on_event(&mut self, event: &PluginEvent) { // You can react on certain events like after rendering if let PluginEvent::AfterRender { .. } = event { // Whenever you hover the button it will rerender and thus this log will be printed println!("The app just got rendered to the canvas."); } } } fn main() { launch_cfg( app, LaunchConfig::<()>::builder() .with_plugin(BlogPlugin) // Here you register the instance of the plugin .build(), ) } fn app() -> Element { rsx!( Button { label { "Hover me!" } } ) } ``` -------------------------------- ### Icons Source: https://github.com/marc2332/freya/blob/main/plugins/freya/skills/freya/SKILL.md Example of using Lucide icons. ```rust use freya::icons; svg(icons::lucide::antenna()).color((120, 50, 255)).expanded() ``` -------------------------------- ### Justfile Commands Source: https://github.com/marc2332/freya/blob/main/CLAUDE.md Examples of common commands available in the ./justfile for working with the Freya repository. ```bash just f ``` ```bash just tc ``` ```bash just d ``` ```bash just t-layout ``` -------------------------------- ### Tokio Integration Setup Source: https://github.com/marc2332/freya/blob/main/plugins/freya/skills/freya/SKILL.md Setting up a Tokio runtime context in main for using Tokio-ecosystem crates. ```rust fn main() { let rt = tokio::runtime::Builder::new_multi_thread().enable_all().build().unwrap(); let _guard = rt.enter(); // keep alive for the whole program launch(LaunchConfig::new().with_window(WindowConfig::new(app))) } ``` -------------------------------- ### WebView Source: https://github.com/marc2332/freya/blob/main/plugins/freya/skills/freya/SKILL.md Example of embedding a browser view using `WebView`. ```rust use freya::webview::*; WebView::new("https://example.com").expanded() ``` -------------------------------- ### Tooltip Example Source: https://github.com/marc2332/freya/blob/main/website/src/content/blog/0.3.md Shows how to implement tooltips using TooltipContainer and Tooltip components. ```rust fn app() -> Element { rsx!( TooltipContainer { tooltip: rsx!( Tooltip { text: "You can see me now!" } ), Button { label { "Hover me" } } } ) } ``` -------------------------------- ### Utility Function Example Source: https://github.com/marc2332/freya/blob/main/plugins/freya/skills/freya/SKILL.md Example of a stateless utility function that returns an element. ```rust fn colored_label(color: Color, text: &str) -> impl IntoElement { label().color(color).text(text.to_string()) } ``` -------------------------------- ### SelectableText Example Source: https://github.com/marc2332/freya/blob/main/website/src/content/blog/0.3.md A simple example demonstrating how to use the SelectableText component to render text that can be selected but not edited. ```rust fn app() -> Element { rsx!( SelectableText { value: "You can select this looooooooooong text" } ) } ``` -------------------------------- ### Install Nightly Toolchain Source: https://github.com/marc2332/freya/blob/main/CONTRIBUTING.md Installs the nightly Rust toolchain pinned in rust-toolchain-nightly.toml. ```shell rustup toolchain install nightly-2026-03-15 ``` -------------------------------- ### `content: fit` and `fill-min` example Source: https://github.com/marc2332/freya/blob/main/website/src/content/blog/0.2.md Shows how `content: fit` and `fill-min` can be used for flexible element sizing. ```rust rsx!( rect { content: "fit", height: "100%", rect { width: "fill-min", // Use the width of the biggest sibling element (300) height: "25%", background: "rgb(71, 147, 175)", } rect { width: "150", // Fixed size of 150 height: "25%", background: "rgb(255, 196, 112)", } rect { width: "fill-min", // Use the width of the biggest sibling element (300) height: "25%", background: "rgb(221, 87, 70)", } rect { width: "300", // Fixed size of 300 height: "25%", background: "rgb(139, 50, 44)", } } ) ``` -------------------------------- ### Canvas Snapshot Example Source: https://github.com/marc2332/freya/blob/main/website/src/content/blog/0.3.md An example demonstrating how to use Freya's headless testing runner to capture UI canvas snapshots before and after an event. ```rust fn app() -> Element { let mut count = use_signal(|| 0); rsx!( rect { onclick: move |_| count += 1, label { font_size: "100", font_weight: "bold", "{count}" } } ) } #[tokio::main] async fn main() { let mut utils = launch_test(app); // Initial render utils.wait_for_update().await; utils.save_snapshot("./snapshot_before.png"); // Emit click event utils.click_cursor((100., 100.)).await; // Render after click utils.save_snapshot("./snapshot_after.png"); } ``` -------------------------------- ### Rich Text Editor Example Source: https://github.com/marc2332/freya/blob/main/README.md A Rust code example demonstrating how to create a rich text editor with cursor management, text selection, and keyboard shortcuts using Freya. ```rust use freya::prelude::*; fn app() -> impl IntoElement { let holder = use_state(ParagraphHolder::default); let mut editable = use_editable(|| "Hello, World!".to_string(), EditableConfig::new); let focus = use_focus(); paragraph() .a11y_id(focus.a11y_id()) .cursor_index(editable.editor().read().cursor_pos()) .highlights( editable .editor() .read() .get_selection() .map(|selection| vec![selection]) .unwrap_or_default(), ) .on_mouse_down(move |e: Event| { focus.request_focus(); editable.process_event(EditableEvent::Down { location: e.element_location, editor_line: EditorLine::SingleParagraph, holder: &holder.read(), }); }) .on_mouse_move(move |e: Event| { editable.process_event(EditableEvent::Move { location: e.element_location, editor_line: EditorLine::SingleParagraph, holder: &holder.read(), }); }) .on_global_pointer_up(move |_| editable.process_event(EditableEvent::Release)) .on_key_down(move |e: Event| { editable.process_event(EditableEvent::KeyDown { key: &e.key, modifiers: e.modifiers, }); }) .on_key_up(move |e: Event| { editable.process_event(EditableEvent::KeyUp { key: &e.key }); }) .span(editable.editor().read().to_string()) .holder(holder.read().clone()) } ``` -------------------------------- ### Animations Source: https://github.com/marc2332/freya/blob/main/plugins/freya/skills/freya/SKILL.md Examples of manual animation control with `use_animation` and reactive transitions with `use_animation_transition`. ```rust // Manual: call .start() / .reverse() yourself let mut anim = use_animation(|_| AnimColor::new((240, 240, 240), (200, 80, 80)).time(400)); rect().background(&*anim.read()).on_press(move |_| anim.start()) // Transition: re-runs automatically when the tracked value changes let color = use_animation_transition(is_active, |from, to| AnimColor::new(from, to).time(300)); rect().background(&*color.read()) ``` -------------------------------- ### Body Component Example Source: https://github.com/marc2332/freya/blob/main/website/src/content/blog/0.2.md An example demonstrating the usage of the Body component, which provides a styled background matching the current theme and expands to fill available space. ```rust use_init_theme(DARK_THEME); rsx!( Body { Button { label { "Hello, World!" } } } ) ``` -------------------------------- ### Element Builder Pattern - Good Example Source: https://github.com/marc2332/freya/blob/main/plugins/freya/skills/freya/SKILL.md Illustrates the recommended fluent builder API for elements, chaining methods directly. ```rust // Good rect() .background((255, 0, 0)) .width(Size::fill()) .height(Size::px(100.)) .center() // centers children both axes .expanded() // fills available space in parent's main axis .horizontal() // sets layout direction to horizontal .maybe(is_active, |el| el.child("Active")) .map(some_value, |el, v| el.child(v.to_string())) ``` -------------------------------- ### Flex Layout Example Source: https://github.com/marc2332/freya/blob/main/website/src/content/blog/0.3.md Demonstrates how to use flexbox-like attributes for layouting in Freya. ```rust fn app() -> Element { rsx!( rect { content: "flex", // Marks this element as a Flex container direction: "horizontal", rect { width: "flex(1)", // Use 1/4 (25%) of the parent space after excluding the text from below height: "fill", background: "red" } label { "Some text here!" } rect { width: "flex(3)", // Use 3/4 (75%) of the parent space after excluding the text from above height: "fill", background: "green" } } ) } ``` -------------------------------- ### Layout direction and alignment example Source: https://github.com/marc2332/freya/blob/main/website/src/content/blog/0.2.md Shows how to use `direction`, `main_align`, and `cross_align` for layout control. ```rust rsx!( rect { height: "100%", width: "100%", direction: "vertical", main_align: "center", // All elements will be centered vertically because `direction` is vertical cross_align: "end", // All elements will be aligned horizontally in the end rect { width: "100", height: "100", background: "red", } rect { width: "100", height: "100", background: "yellow", } } ) ``` -------------------------------- ### Code Editor Source: https://github.com/marc2332/freya/blob/main/plugins/freya/skills/freya/SKILL.md Example of initializing and using the `CodeEditor` component with `CodeEditorData`. ```rust let editor = use_state(|| { let mut e = CodeEditorData::new(Rope::from_str(src), LanguageId::Rust); e.parse(); e.measure(14., "Jetbrains Mono"); e }); CodeEditor::new(editor, focus.a11y_id()) ``` -------------------------------- ### use_memo Example Source: https://github.com/marc2332/freya/blob/main/plugins/freya/skills/freya/SKILL.md Using use_memo for expensive computations that should only re-run when dependencies change. ```rust let expensive = use_memo(move || { let n = *count.read(); // subscribed - reruns when count changes compute_something(n) }); let value = expensive.read(); ``` -------------------------------- ### ActivableRoute and use_activable_route Example Source: https://github.com/marc2332/freya/blob/main/website/src/content/blog/0.2.md Shows how to use ActivableRoute and use_activable_route to conditionally style UI elements based on the active route. This example demonstrates activating a SidebarItem when the route matches Route::Home. ```rust Link { to: Route::Home, // Direction route ActivableRoute { route: Route::Home, // Activation route SidebarItem { // `SidebarItem` will now appear "activated" when the route is `Route::Home` // `ActivableRoute` is letting it know whether `Route::Home` is enabled // or not, without the need to add router-specific logic in `SidebarItem`. label { "Go to Hey ! 👋" } }, } } ``` -------------------------------- ### ProgressBar Component Example Source: https://github.com/marc2332/freya/blob/main/website/src/content/blog/0.2.md An example demonstrating the usage of the ProgressBar component, which displays the current progress of an operation using a float value. ```rust let progress = 67.0; // Could be derived from another state for example rsx!( ProgressBar { show_progress: true, progress } ) ``` -------------------------------- ### ResizableContainer Example Source: https://github.com/marc2332/freya/blob/main/website/src/content/blog/0.3.md Demonstrates the usage of ResizableContainer, ResizablePanel, and ResizableHandle to create resizable UI panels. ```rust fn app() -> Element { rsx!( ResizableContainer { ResizablePanel { initial_size: 50., label { "Hello" } } ResizableHandle { } ResizablePanel { initial_size: 50., ResizableContainer { direction: "horizontal", ResizablePanel { initial_size: 35., label { "World" } } ResizableHandle { } ResizablePanel { initial_size: 20., min_size: 20., label { "!" } } } } } ) } ``` -------------------------------- ### i18n Example Source: https://github.com/marc2332/freya/blob/main/website/src/content/blog/0.3.md An example showcasing the integration of dioxus-i18n for internationalization in Freya applications, including setting languages and using translation macros. ```rust #[allow(non_snake_case)] fn Body() -> Element { let mut i18n = i18n(); rsx!( rect { Button { onpress: move |_| i18n.set_language(langid!("en-US")), label { "English" } } Button { onpress: move |_| i18n.set_language(langid!("es-ES")), label { "Spanish" } } label { {t!("hello", name: "Dioxus")} } } ) } fn app() -> Element { use_init_i18n(|| { I18nConfig::new(langid!("en-US")) .with_locale(Locale::new_static( langid!("en-US"), include_str!("./en-US.ftl"), )) .with_locale(Locale::new_static( langid!("es-ES"), include_str!("./es-ES.ftl"), )) }); rsx!(Body {{}}) } ``` ```fluent # en-US.ftl hello_world = Hello, World! hello = Hello, {$name}! ``` -------------------------------- ### Headless Testing Example Source: https://github.com/marc2332/freya/blob/main/README.md Demonstrates how to use `freya-testing` for headless testing of Freya components, including rendering to a file. ```rust use freya::prelude::* use freya_testing::prelude::*; fn app() -> impl IntoElement { let mut state = use_consume::>(); rect() .expanded() .center() .background((240, 240, 240)) .on_mouse_up(move |_| *state.write() += 1) .child(format!("Clicked: {}", state.read())) } fn main() { // Create headless testing runner let (mut test, state) = TestingRunner::new( app, (300., 300.).into(), |runner| runner.provide_root_context(|| State::create(0)), 1., ); test.sync_and_update(); assert_eq!(*state.peek(), 0); // Simulate user interactions test.click_cursor((15., 15.)); assert_eq!(*state.peek(), 1); // Render the current ui state to a file test.render_to_file("./demo-1.png"); } ``` -------------------------------- ### Horizontal layout and alignment example Source: https://github.com/marc2332/freya/blob/main/website/src/content/blog/0.2.md Demonstrates horizontal layout with `main_align` and `cross_align`. ```rust rsx!( rect { height: "100%", width: "100%", direction: "horizontal", main_align: "center", // All elements will be centered horizontally because `horizontal` is vertical cross_align: "start", // All elements will be aligned vertically in the center rect { width: "100", height: "100", background: "red", } rect { width: "100", height: "100", background: "yellow", } } ) ``` -------------------------------- ### Absolute positioning example Source: https://github.com/marc2332/freya/blob/main/website/src/content/blog/0.2.md Illustrates how to use absolute positioning for elements. ```rust rsx!( rect { background: "blue", width: "100%", height: "100%", } rect { background: "yellow", position: "absolute", position_top: "10", position_left: "10", width: "50", height: "50", corner_radius: "100" } ) ``` -------------------------------- ### Plotting Source: https://github.com/marc2332/freya/blob/main/plugins/freya/skills/freya/SKILL.md Example of using the `plot()` element with `RenderCallback` and `PlotSkiaBackend`. ```rust plot(RenderCallback::new(|ctx| { let backend = PlotSkiaBackend::new(ctx.canvas, ctx.font_collection, size).into_drawing_area(); // ... Plotters drawing code })).expanded() ``` -------------------------------- ### WebView Integration Source: https://github.com/marc2332/freya/blob/main/README.md Example demonstrating a multi-tab WebView implementation, showing how to manage tabs and display web content. ```rust use freya::prelude::* use freya::webview::* fn app() -> impl IntoElement { // Multi-tab webview implementation let mut tabs = use_state(|| vec![Tab { id: WebViewId::new(), title: "Tab 1".to_string(), url: "https://duckduckgo.com".to_string(), }]); let mut active_tab = use_state(|| tabs.read()[0].id); rect() .expanded() .height(Size::fill()) .background((35, 35, 35)) .child( rect() .width(Size::fill()) .height(Size::px(45.)) .padding(4.) .background((50, 50, 50)) .horizontal() .cross_align(Alignment::Center) .spacing(4.) .children(tabs.read().iter().map(|tab| { // Tab implementation... })) ) .child(WebView::new("https://duckduckgo.com").expanded()) } ``` -------------------------------- ### AnimatedPosition Component Example Source: https://github.com/marc2332/freya/blob/main/website/src/content/blog/0.3.md An example demonstrating the usage of the AnimatedPosition component to animate the position of its inner content. ```rust fn app() -> Element { rsx!( AnimatedPosition { width: "110", height: "60", function: Function::Quad, duration: Duration::from_millis(250), rect { background: "red", width: "60", height: "110" } } ) } ``` -------------------------------- ### Table Component Example Source: https://github.com/marc2332/freya/blob/main/website/src/content/blog/0.2.md An example demonstrating the usage of the new Table component, including TableHead, TableRow, and TableCell, with support for sorting and virtual scrolling for large datasets. ```rust let data = use_signal(|| { (0..10) .map(|i| { vec![ format!("{i}"), format!("{}", 5 - i + 30), format!("{}", 10 - i + 70), ] }) .collect::>>() }); let columns = use_signal(|| { vec![ "ID".to_string(), "Age".to_string(), "Weight".to_string(), ] }); rsx!( Table { columns: columns.len(), // Render the head of the Table TableHead { // With only 1 row TableRow { // And 1 cell for every column for (n, text) in columns.read().iter().enumerate() { TableCell { key: "{n}", label { "{text}" } } } } } // Just the main content of the Table, where all the rows go TableBody { // You could even use VirtualScrollView if you had to deal with large data sets ScrollView { for (i, items) in data.read().iter().enumerate() { // 1 row for very data line TableRow { key: "{i}", alternate_colors: i % 2 == 0, for (n, item) in items.iter().enumerate() { TableCell { key: "{n}", label { width: "100%", text_align: "right", "{item}" } } } } } } } } ) ``` -------------------------------- ### Run desktop version Source: https://github.com/marc2332/freya/blob/main/examples/android/README.md Compiles and runs the Freya example as a regular desktop application. ```sh cargo run ``` -------------------------------- ### GlobalAnimatedPosition Example Source: https://github.com/marc2332/freya/blob/main/website/src/content/blog/0.3.md An example demonstrating the use of GlobalAnimatedPosition to animate grid elements that can be shuffled. It shows how to provide a GlobalAnimatedPositionProvider and use GlobalAnimatedPosition for individual cells, identified by a unique ID. ```rust fn app() -> Element { let mut grid = use_signal(|| Grid::new(5)); rsx!( rect { spacing: "12", main_align: "center", cross_align: "center", width: "fill", height: "fill", // This context provider is what stores the positions // The generic type is the ID type used for the cells GlobalAnimatedPositionProvider:: { Button { onpress: move |_| grid.write().suffle(), label { "Shuffle" } } rect { spacing: "6", for row in grid.read().cells.chunks(5) { rect { direction: "horizontal", spacing: "6", for cell in row { GlobalAnimatedPosition:: { key: "{cell.id:?}", width: "100", height: "100", function: Function::Expo, duration: Duration::from_millis(600), id: cell.id, rect { width: "100", height: "100", background: "rgb({cell.id * 6}, {cell.id * 8}, { cell.id * 2 })", corner_radius: "32", color: "white", main_align: "center", cross_align: "center", label { "{cell.id:?}" } } } } } } } } } ) } ``` -------------------------------- ### Focusable Element Example Source: https://github.com/marc2332/freya/blob/main/plugins/freya/skills/freya/SKILL.md Demonstrates how to create a focusable element with accessibility properties and track its focus state. ```rust #[derive(PartialEq)] struct FocusableBox; impl Component for FocusableBox { fn render(&self) -> impl IntoElement { let a11y_id = use_a11y(); let focus = use_focus(a11y_id); rect() .a11y_id(a11y_id) .a11y_focusable(true) .a11y_role(AccessibilityRole::Button) .on_press(move |_| println!("activated")) .maybe(focus() == Focus::Keyboard, |el| { el.border(Border::new().fill(Color::BLUE).width(2.)) }) .child("Click or Tab to me") } } ``` -------------------------------- ### Code Editor Example Source: https://github.com/marc2332/freya/blob/main/README.md A Rust code example for creating and controlling a code editor in Freya, utilizing Rope for text editing and tree-sitter for syntax highlighting. ```rust fn app() -> impl IntoElement { use_init_theme(dark_theme); let focus = use_focus(); let editor = use_state(|| { let path = PathBuf::from("./crates/freya-code-editor/src/editor_ui.rs"); let rope = Rope::from_str(&std::fs::read_to_string(&path).unwrap()); let mut editor = CodeEditorData::new(rope, LanguageId::Rust); editor.parse(); editor.measure(14., "Jetbrains Mono"); editor }); CodeEditor::new(editor, focus.a11y_id()) } ``` -------------------------------- ### NativeRouter Example Source: https://github.com/marc2332/freya/blob/main/website/src/content/blog/0.2.md Illustrates the integration of NativeRouter with dioxus-router for browser-like navigation using back and forward buttons. ```rust #[derive(Routable, Clone, PartialEq)] #[rustfmt::skip] pub enum Route { #[layout(Layout)] #[route("/")] Home, #[end_layout] #[route("/..route")] PageNotFound { }, } // Because this component is used as layout for all the routes // Using the back and forward buttons will work in all of them. #[component] fn Layout() -> Element { rsx!( NativeRouter { Outlet:: { } } ) } ``` -------------------------------- ### use_future Example Source: https://github.com/marc2332/freya/blob/main/plugins/freya/skills/freya/SKILL.md Using use_future to wrap async tasks and expose their state. ```rust let task = use_future(|| async { fetch_user(42).await }); match &*task.state() { FutureState::Pending | FutureState::Loading => "Loading...", FutureState::Fulfilled(user) => user.name.as_str(), } ``` -------------------------------- ### use_form hook example Source: https://github.com/marc2332/freya/blob/main/website/src/content/blog/0.2.md Demonstrates how to use the `use_form` hook for handling form inputs and submissions. ```rust #[derive(Hash, PartialEq, Eq, Clone, Debug)] enum FormEntry { Name, Description, } fn app() -> Element { let form = use_form(|data| { // This callback will be called once the submit button has been triggered. println!("Submitting: {data:?}"); }); rsx!( Input { // Register an input for the `Name` entry ..form.input(FormEntry::Name) }, Input { // Register an input for the `Description` entry ..form.input(FormEntry::Description) }, Button { // Register a submit button. children: rsx!( label { "Submit" } ), ..form.submit(), } ) } ``` -------------------------------- ### use_animation Example: Single Animation Source: https://github.com/marc2332/freya/blob/main/website/src/content/blog/0.2.md Illustrates creating and controlling a single animation using use_animation. This example animates a number from 25.0 to 75.0 over 200ms with an Expo function and Out ease, triggered by a button click. ```rust // Create animation let animation = use_animation(|ctx| { ctx.with( AnimNum::new(25.0, 75.0) .time(200) // Alternative to ".duration(Duration::from_millis(200))" .function(Function::Expo) .ease(Ease::Out), ) }); // Retrieve current value let value = animation.get().as_f32(); // UI rsx!( Button { onclick: move |_| animation.start(), // Start the animation on click label { "Value {value}" } } ) ``` -------------------------------- ### Hex Colors Example Source: https://github.com/marc2332/freya/blob/main/website/src/content/blog/0.2.md Demonstrates how to use hex color codes in Freya components. ```rsx rsx!( label { color: "#E93323", "Hello, World!" } ) ``` -------------------------------- ### Icon Library Integration Source: https://github.com/marc2332/freya/blob/main/README.md Example of how to integrate Lucide icons into a Freya application. ```rust use freya::prelude::* use freya::icons; fn app() -> impl IntoElement { svg(icons::lucide::antenna()) .color((120, 50, 255)) .expanded() } ``` -------------------------------- ### Event Bubbling Example Source: https://github.com/marc2332/freya/blob/main/website/src/content/blog/0.2.md Illustrates how event bubbling works and how to stop propagation. ```rust rsx!( rect { onclick: |_| { println!("Clicked B!"); }, rect { onclick: |e| { // Stop the bubbling of the event if you want to e.stop_propagation(); println!("Clicked A!"); }, background: "blue", label { "hey" } } } ) ``` -------------------------------- ### Cache Rendering with `cache_key` Source: https://github.com/marc2332/freya/blob/main/website/src/content/blog/0.3.md Example demonstrating how to cache image decoding using a `cache_key`. ```rust static RUST_LOGO: &[u8] = include_bytes!("./rust_logo.png"); fn app() -> Element { rsx!( image { image_data: static_bytes(RUST_LOGO), width: "fill", height: "fill", aspect_ratio: "min", cache_key: "rust-logo", } ) } ``` -------------------------------- ### AnimSequential Example Source: https://github.com/marc2332/freya/blob/main/website/src/content/blog/0.3.md Demonstrates the use of `AnimSequential` to animate multiple values simultaneously. ```rust fn app() -> Element { let animations = use_animation(|conf| { conf.auto_start(true); AnimSequential::new([ AnimNum::new(0., 360.) .time(500) .ease(Ease::InOut) .function(Function::Expo), AnimNum::new(0., 180.) .time(2000) .ease(Ease::Out) .function(Function::Elastic), ]) }); let sequential = animations.get(); let rotate_a = sequential.read()[0].read(); let rotate_b = sequential.read()[1].read(); rsx!( rect { width: "100", height: "100", rotate: "{rotate_a}deg", background: "rgb(0, 119, 182)" }, rect { width: "100", height: "100", rotate: "{rotate_b}deg", background: "rgb(0, 119, 182)" } ) } ``` -------------------------------- ### `fill` size attribute example Source: https://github.com/marc2332/freya/blob/main/website/src/content/blog/0.2.md Demonstrates the use of the `fill` attribute for width and height to occupy available space. ```rust rsx!( rect { height: "50%", width: "100%", background: "rgb(0, 119, 182)", } rect { height: "fill", width: "100%", background: "rgb(20, 150, 220)", } ) ``` -------------------------------- ### Headless Testing Source: https://github.com/marc2332/freya/blob/main/plugins/freya/skills/freya/SKILL.md Example of using `TestingRunner` to mount a component, simulate interactions, and assert on state. ```rust use freya_testing::prelude::*; let (mut runner, state) = TestingRunner::new(app, (300., 300.).into(), |r| { r.provide_root_context(|| State::create(0)) }, 1.); runner.sync_and_update(); runner.click_cursor((15., 15.)); assert_eq!(*state.peek(), 1); ``` -------------------------------- ### Passing Local State to Child Components Source: https://github.com/marc2332/freya/blob/main/plugins/freya/skills/freya/SKILL.md Example of how to pass local state to child components. ```rust #[derive(PartialEq)] struct Child(State); ``` -------------------------------- ### Simple Counter App Example Source: https://github.com/marc2332/freya/blob/main/website/src/content/blog/announcement.md A basic counter application demonstrating Freya's UI components and state management. ```rust fn app(cx: Scope) -> Element { let mut count = use_state(cx, || 0); render!( rect { height: "20%", width: "100%", background: "rgb(233, 196, 106)", padding: "12", color: "rgb(20, 33, 61)", label { font_size: "20", "Number is: {count}" } } rect { height: "80%", width: "100%", background: "rgb(168, 218, 220)", color: "black", padding: "12", onclick: move |_| count += 1, label { "Click to increase!" } } ) } ``` -------------------------------- ### Routing & Navigation Example Source: https://github.com/marc2332/freya/blob/main/README.md Demonstrates how to define routes, manage navigation state, and transition between different views using the `router` feature. ```rust use freya::prelude::*; use freya::router::prelude::*; #[derive(Routable, Clone, PartialEq)] #[rustfmt::skip] pub enum Route { #[layout(AppBottomBar)] #[route("/")] Home, #[route("/settings")] Settings, } fn app() -> impl IntoElement { router::(|| RouterConfig::default().with_initial_path(Route::Settings)) } #[derive(PartialEq)] struct AppBottomBar; impl Component for AppBottomBar { fn render(&self) -> impl IntoElement { NativeRouter::new().child( rect() .content(Content::flex()) .child( rect() .width(Size::fill()) .height(Size::flex(1.)) .center() .child(outlet::()), ) .child( rect() .horizontal() .width(Size::fill()) .main_align(Alignment::center()) .padding(8.) .spacing(8.) .child( Link::new(Route::Home) .child(FloatingTab::new().child("Home")) .activable_route(Route::Home) .exact(true), ) .child( Link::new(Route::Settings) .child(FloatingTab::new().child("Settings")) .activable_route(Route::Settings) .exact(true), ), ), ) } } #[derive(PartialEq)] struct Home {} impl Component for Home { fn render(&self) -> impl IntoElement { Button::new() .on_press(|_| { RouterContext::get().replace(Route::Settings); }) .child("Go Settings") } } #[derive(PartialEq)] struct Settings {} impl Component for Settings { fn render(&self) -> impl IntoElement { Button::new() .on_press(|_| { let _ = RouterContext::get().replace(Route::Home); }) .child("Go Home") } } ``` -------------------------------- ### Smooth Animations Example Source: https://github.com/marc2332/freya/blob/main/README.md This code snippet demonstrates how to create smooth animations for visual properties like colors in Freya. It includes buttons to start and reverse the animation. ```rust use freya::prelude::*; fn app() -> impl IntoElement { let mut animation = use_animation(|_| AnimColor::new((246, 240, 240), (205, 86, 86)).time(400)); rect() .background(&*animation.read()) .expanded() .center() .spacing(8.0) .child( Button::new() .on_press(move |_| { animation.start(); }) .child("Start"), ) .child( Button::new() .on_press(move |_| { animation.reverse(); }) .child("Reverse"), ) } ``` -------------------------------- ### Importing SVG as Components Source: https://github.com/marc2332/freya/blob/main/website/src/content/blog/0.3.md Example of using the `import_svg` macro to turn SVG files into reusable components. ```rust import_svg!(Ferris, "./ferris.svg", { width: "70%", height: "50%" }); fn app() -> Element { rsx!(Ferris {{}}) } ``` -------------------------------- ### Gradient Borders Example Source: https://github.com/marc2332/freya/blob/main/website/src/content/blog/0.3.md Illustrates using linear and radial gradients as borders for a rect element. ```rust fn app() -> Element { rsx!( rect { main_align: "center", cross_align: "center", width: "fill", height: "fill", rect { width: "100", height: "100", border: "15 inner linear-gradient(0deg,rgb(98, 67, 223) 0%,rgb(192, 74, 231) 33%,rgb(255, 130, 238) 66%, white 100%), 4 center radial-gradient(red 0%, blue 80%)" } } ) } ``` -------------------------------- ### Function Component (App Root) Source: https://github.com/marc2332/freya/blob/main/plugins/freya/skills/freya/SKILL.md Example of a function component used as the application root, where hooks like `use_init_theme` can be placed. ```rust fn app() -> impl IntoElement { rect().child("Hello, World!") } ``` -------------------------------- ### Struct Components Source: https://github.com/marc2332/freya/blob/main/plugins/freya/skills/freya/SKILL.md Example of a stateful struct component in Freya, demonstrating the use of `use_state` hook and basic event handling. ```rust #[derive(PartialEq)] struct Counter { initial: i32, } impl Component for Counter { fn render(&self) -> impl IntoElement { let mut count = use_state(|| self.initial); label() .on_mouse_up(move |_| *count.write() += 1) .text(format!("Count: {}", count.read())) } } ``` -------------------------------- ### Routing - Router initialization Source: https://github.com/marc2332/freya/blob/main/plugins/freya/skills/freya/SKILL.md Render routes with `router::()`. ```rust fn app() -> impl IntoElement { router::(|| RouterConfig::default()) } ``` -------------------------------- ### Derived State Example Source: https://github.com/marc2332/freya/blob/main/plugins/freya/skills/freya/SKILL.md Example of computing a derived value directly in render. ```rust let doubled = *count.read() * 2; ``` -------------------------------- ### Install Claude Code Skill Source: https://github.com/marc2332/freya/blob/main/README.md Commands to install the Claude Code skill for Freya from the marketplace. ```shell /plugin marketplace add marc2332/freya /plugin install freya@freya-marketplace ``` -------------------------------- ### ComponentOwned Example Source: https://github.com/marc2332/freya/blob/main/plugins/freya/skills/freya/SKILL.md Example of a `ComponentOwned` struct, useful when the `render` method needs to own `self` and move fields into closures. ```rust #[derive(PartialEq, Clone)] struct Item { state: State>, i: usize } impl ComponentOwned for Item { fn render(mut self) -> impl IntoElement { Button::new() .on_press(move |_| { self.state.write().remove(self.i); }) .child("Remove") } } ``` -------------------------------- ### Initializing a theme in the root component Source: https://github.com/marc2332/freya/blob/main/plugins/freya/skills/freya/SKILL.md Demonstrates how to initialize a theme and make it reactive, allowing app-wide theme switching. ```rust fn app() -> impl IntoElement { let mut theme = use_init_theme(light_theme); // or dark_theme, or your own rect() .theme_background() .theme_color() .expanded() .center() .child(Button::new().on_press(move |_| theme.set(dark_theme())).child("Dark")) } ``` -------------------------------- ### Install cargo-ndk and Android targets Source: https://github.com/marc2332/freya/blob/main/examples/android/README.md Installs the cargo-ndk utility and the required Android Rust targets (aarch64-linux-android, x86_64-linux-android). ```sh cargo install cargo-ndk rustup target add aarch64-linux-android x86_64-linux-android ``` -------------------------------- ### OverflowedContent Example Source: https://github.com/marc2332/freya/blob/main/website/src/content/blog/0.3.md A basic example showcasing the OverflowedContent component, which allows rendering long text within a limited space by animating it. ```rust fn app() -> Element { rsx!( Button { OverflowedContent { width: "100", rect { direction: "horizontal", cross_align: "center", label { "Freya is a cross-platform GUI library for Rust" } } } } ) } ``` -------------------------------- ### Import Image Macro Example Source: https://github.com/marc2332/freya/blob/main/website/src/content/blog/0.3.md Demonstrates how to use the `import_image` macro to turn an image file into a component with customizable attributes. ```rust import_image!(RustLogo, "./rust_logo.png", { width: "auto", height: "auto", sampling: "trilinear", aspect_ratio: "min", }); fn app() -> Element { rsx!(RustLogo {{}}) } ``` -------------------------------- ### Global State Management Example Source: https://github.com/marc2332/freya/blob/main/README.md Illustrates Freya's `freya-radio` state management system for efficient global state management using channels. ```rust use freya::prelude::*; use freya::radio::*; #[derive(Default)] struct Data { pub lists: Vec>, } #[derive(PartialEq, Eq, Clone, Debug, Copy, Hash)] pub enum DataChannel { ListCreation, SpecificListItemUpdate(usize), } impl RadioChannel for DataChannel {} fn app() -> impl IntoElement { use_init_radio_station::(Data::default); let mut radio = use_radio::(DataChannel::ListCreation); let on_press = move |_| { radio.write().lists.push(Vec::default()); }; rect() .horizontal() .child(Button::new().on_press(on_press).child("Add new list")) .children( radio .read() .lists .iter() .enumerate() .map(|(list_n, _)| ListComp(list_n).into()), ) } #[derive(PartialEq)] struct ListComp(usize); impl Component for ListComp { fn render(&self) -> impl IntoElement { let list_n = self.0; let mut radio = use_radio::(DataChannel::SpecificListItemUpdate(list_n)); println!("Running DataChannel::SpecificListItemUpdate({list_n})"); rect() .child( Button::new() .on_press(move |_| radio.write().lists[list_n].push("Hello, World".to_string())) .child("New Item"), ) .children( radio.read().lists[list_n] .iter() .enumerate() .map(move |(i, item)| label().key(i).text(item.clone()).into()), ) } } ``` -------------------------------- ### Material Design Source: https://github.com/marc2332/freya/blob/main/plugins/freya/skills/freya/SKILL.md Example of using the `.ripple()` style modifier. ```rust use freya::material_design::*; Button::new().ripple().child("Click me") ``` -------------------------------- ### Menu Component Example Source: https://github.com/marc2332/freya/blob/main/website/src/content/blog/0.2.md Demonstrates how to use the new Menu component with MenuButton and SubMenu to create floating menus. It shows how to toggle the menu's visibility and compose menu items. ```rust let mut show_menu = use_signal(|| false); rsx!( Button { onclick: move |_| show_menu.toggle(), label { "Open Menu" } }, if *show_menu.read() { Menu { onclose: move |_| show_menu.set(false), MenuButton { label { "Button 1" } } SubMenu { menu: rsx!( MenuButton { label { "Button 1" } } ), label { "More" } } } } ) ``` -------------------------------- ### Creating a custom brand theme Source: https://github.com/marc2332/freya/blob/main/plugins/freya/skills/freya/SKILL.md Shows how to create a custom theme by starting from a built-in theme and overriding specific color properties. ```rust fn brand_theme() -> Theme { let mut theme = dark_theme(); theme.name = "brand"; theme.colors = ColorsSheet { primary: Color::from_rgb(37, 52, 63), secondary: Color::from_rgb(255, 155, 81), tertiary: Color::from_rgb(81, 155, 255), ..DARK_COLORS }; theme } ``` -------------------------------- ### Checkbox Component Example Source: https://github.com/marc2332/freya/blob/main/website/src/content/blog/0.2.md Shows how to use the Checkbox component for toggling multiple options, also requiring manual state management. ```rust let mut selected = use_signal::>(HashSet::default); rsx!( Tile { onselect: move |_| { if selected.read().contains(&Choice::FirstChoice) { selected.write().remove(&Choice::FirstChoice); } else { selected.write().insert(Choice::FirstChoice); } }, leading: rsx!( Checkbox { selected: selected.read().contains(&Choice::FirstChoice), }, ), label { "First choice" } } ) ``` -------------------------------- ### use_side_effect Example Source: https://github.com/marc2332/freya/blob/main/plugins/freya/skills/freya/SKILL.md Using use_side_effect for side effects that should re-run when state changes. ```rust use_side_effect(move || { let value = *count.read(); // subscribed println!("count changed: {value}"); }); ```