### Full Feature Setup Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/_autodocs/configuration.md A complete example demonstrating project dependencies, main function setup with routes, and basic component definitions. ```toml [package] name = "my_tui_app" version = "0.1.0" edition = "2024" [dependencies] ratatui-kit = { version = "0.6", features = ["full"] } tokio = { version = "1", features = ["rt-multi-thread", "macros", "time"] } serde = { version = "1.0", features = ["derive"] } [dev-dependencies] # For testing with TestBackend ``` ```rust use ratatui_kit::prelude::*; #[tokio::main] async fn main() { let routes = routes! { "/" => element!(Home()), "/settings" => element!(Settings()), }; element!(RouterProvider(routes: routes) { element!(Layout()) }) .fullscreen() .await .expect("Application error"); } #[component] fn Layout(props: &mut NoProps, _hooks: Hooks) -> impl Into> { element!(View(flex_direction: Direction::Vertical) { element!(Outlet()), }) } #[component] fn Home(props: &mut NoProps, _hooks: Hooks) -> impl Into> { element!(Text(text: Line::from("Home"))) } #[component] fn Settings(props: &mut NoProps, _hooks: Hooks) -> impl Into> { element!(Text(text: Line::from("Settings"))) } ``` -------------------------------- ### Full Feature Setup Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/_autodocs/INDEX.md A comprehensive example demonstrating the setup of various features and configurations within a Ratatui-Kit application. ```rust // This is a placeholder for a full example that would likely span multiple files // and demonstrate feature flags, macro configurations, and component composition. // Example snippet showing feature flag usage: // #[cfg(feature = "some_feature")] // fn enabled_feature_component() -> impl Component { // // ... component implementation ... // } // Example snippet showing macro configuration: // #[with_layout_style(width: Constraint::Fill, height: Constraint::Length(5))] // fn ConfiguredComponent() -> impl Component { // // ... component implementation ... // } fn main() { // Initialize application with specific configurations // ratatui_kit::init(AppConfig { // feature_flags: vec![...], // macro_configs: vec![...] // }); // Run the main application component // let app = App {}; // ratatui_kit::run(app); } ``` -------------------------------- ### Run Example Command Source: https://github.com/yexiyue/ratatui-kit/blob/main/docs/src/content/docs/start/quick-start.mdx This bash command executes the 'hello_world' example from the project's examples directory. ```bash cargo run --example hello_world ``` -------------------------------- ### Run Modal Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/docs/src/content/docs/components/modal.mdx Execute the modal example from the command line. This command starts the application demonstrating the modal component's behavior. ```bash cargo run --example modal ``` -------------------------------- ### Run Todo App Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/docs/src/content/docs/apps/todo-app.mdx Execute the Todo App example using Cargo. This command starts the application, allowing interaction with the task list. ```bash cargo run --example todo_app ``` -------------------------------- ### Run ShortcutInfoModal Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/docs/src/content/docs/components/shortcut-info-modal.mdx Command to run the example demonstrating the ShortcutInfoModal component. ```bash cargo run --example shortcut_info_modal ``` -------------------------------- ### List All Examples Source: https://github.com/yexiyue/ratatui-kit/blob/main/README.md Lists all available examples that can be run using 'cargo run --example '. Some examples require optional features. ```text hello_world counter async_state atom_state router control_flow input_mutex input search_input scrollview wrapped_text modal confirm_modal alert_modal shortcut_info_modal select multi_select tree_select virtual_list virtual_multi_select custom_widget custom_hook custom_provider todo_app ``` -------------------------------- ### Run Ratatui-Kit Examples Source: https://github.com/yexiyue/ratatui-kit/blob/main/_autodocs/README.md Examples can be run using cargo run. Each example demonstrates a specific feature of the library. ```bash cargo run --example counter # Local state + timers ``` ```bash cargo run --example atom_state # Global atoms ``` ```bash cargo run --example router # Multi-page routing ``` ```bash cargo run --example modal # Modal dialogs ``` ```bash cargo run --example todo_app # Full application ``` -------------------------------- ### Run Router Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/README.md Runs the router example, demonstrating RouterProvider and nested Outlet for routing. ```bash cargo run --example router # RouterProvider and nested Outlet ``` -------------------------------- ### Run Custom Provider Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/docs/src/content/docs/advanced/custom-provider.mdx Execute the custom provider example using Cargo. ```bash cargo run --example custom_provider ``` -------------------------------- ### Start Local Development Server Source: https://github.com/yexiyue/ratatui-kit/blob/main/docs/README.md Starts a local development server for previewing the documentation site. Run this command from the 'docs/' directory. ```bash pnpm dev ``` -------------------------------- ### Run Todo App Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/README.md Runs the todo app example, a full workflow example including state, input, routing, and modals. ```bash cargo run --example todo_app # full workflow: state, input, routing, modals ``` -------------------------------- ### Run Virtual Multi Select Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/docs/src/content/docs/components/virtual-multi-select.mdx Execute the example to see the virtual multi-select pattern in action. This command builds and runs the example demonstrating the component's functionality. ```bash cargo run --example virtual_multi_select ``` -------------------------------- ### Run Compiled Example Application Source: https://github.com/yexiyue/ratatui-kit/blob/main/dev-notes/blog/2026-06-15-terminal-recording-from-zero.md Execute the compiled binary of your example application. This is the command that will be typed into the VHS tape. ```bash ./target/debug/examples/counter ``` -------------------------------- ### Run Select Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/docs/src/content/docs/components/select.mdx This command runs the example for the Select component. Press 'j/k' to move, 'Enter' to select, 'e' to toggle the empty state, and 'q' to quit. ```bash cargo run --example select ``` -------------------------------- ### Run Custom Widget Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/docs/src/content/docs/advanced/custom-widget.mdx Execute the custom widget example using Cargo. ```bash cargo run --example custom_widget ``` -------------------------------- ### Run Custom Hook Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/docs/src/content/docs/advanced/custom-hook.mdx Command to run the custom hook example. ```bash cargo run --example custom_hook ``` -------------------------------- ### Complete Routing Example in Rust Source: https://github.com/yexiyue/ratatui-kit/blob/main/_autodocs/api-reference/routing.md This Rust code demonstrates a full routing setup with nested components, navigation, and dynamic route parameters. It requires `tokio` for async operations and `serde` for deserialization. ```rust use ratatui_kit::prelude::*; use serde::Deserialize; #[tokio::main] async fn main() { let routes = routes! { "/" => element!(Home()), "/settings" => element!(Settings()), "/user/:id" => element!(UserDetail()), }; element!(RouterProvider(routes: routes) { element!(Layout()) }) .fullscreen() .await .unwrap(); } #[component] fn Layout(props: &mut NoProps, mut hooks: Hooks) -> impl Into> { element!(View(flex_direction: Direction::Vertical) { element!(Navbar()), element!(Outlet()), }) } #[component] fn Navbar(props: &mut NoProps, mut hooks: Hooks) -> impl Into> { let navigate = hooks.use_navigate(); element!(View(flex_direction: Direction::Horizontal, gap: 2) { element!(NavLink(path: "/", navigate: navigate.clone(), label: "Home")), element!(NavLink(path: "/settings", navigate: navigate.clone(), label: "Settings")), }) } #[component] fn NavLink( props: &mut NavLinkProps, mut hooks: Hooks, ) -> impl Into> { let navigate = props.navigate.clone(); let path = props.path.to_string(); hooks.use_event_handler(EventScope::Current, EventPriority::Normal, move |event| { let Event::Key(key) = event else { return EventResult::Ignored; }; if key.code == KeyCode::Enter { navigate(path.clone()); return EventResult::Consumed; } EventResult::Ignored }); element!(Text(text: Line::from(props.label))) } #[component] fn Home(props: &mut NoProps, _hooks: Hooks) -> impl Into> { element!(Text(text: Line::from("Welcome to Home"))) } #[component] fn Settings(props: &mut NoProps, _hooks: Hooks) -> impl Into> { element!(Text(text: Line::from("Settings Page"))) } #[derive(Deserialize)] struct UserParams { id: u64, } #[component] fn UserDetail(props: &mut NoProps, hooks: Hooks) -> impl Into> { let params = hooks.use_params::(); element!(Text(text: Line::from(format!("User: {}", params.id)))) } #[derive(Props)] pub struct NavLinkProps { pub path: &'static str, pub navigate: Box, pub label: &'static str, } ``` -------------------------------- ### Run Counter Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/README.md Runs the counter example, demonstrating local state and asynchronous updates. ```bash cargo run --example counter # local state + async updates ``` -------------------------------- ### Registering an Example in Cargo.toml Source: https://github.com/yexiyue/ratatui-kit/blob/main/docs/src/content/docs/examples/index.mdx This TOML snippet shows how to explicitly register an example within a grouping directory in the root Cargo.toml file. This is necessary for examples not located in the top-level examples directory. ```toml [[example]] name = "counter" path = "examples/start/counter.rs" ``` -------------------------------- ### Run Modal Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/README.md Runs the modal example, illustrating modal input isolation. ```bash cargo run --example modal # modal input isolation ``` -------------------------------- ### Run Confirm Modal Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/docs/src/content/docs/components/confirm-modal.mdx Execute the confirm_modal example from the command line. This is typically used to test or demonstrate the component's functionality. ```bash cargo run --example confirm_modal ``` -------------------------------- ### Install Documentation Dependencies Source: https://github.com/yexiyue/ratatui-kit/blob/main/docs/README.md Installs the necessary dependencies for the documentation site using pnpm. Ensure you are in the 'docs/' directory. ```bash pnpm install --frozen-lockfile ``` -------------------------------- ### Run Atom State Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/README.md Runs the atom state example, showcasing global atom state management. ```bash cargo run --example atom_state # global atom state ``` -------------------------------- ### Run TreeSelect Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/docs/src/content/docs/components/tree-select.mdx Execute the tree_select example to see the TreeSelect component in action. This command requires the cargo build tool. ```bash cargo run --example tree_select ``` -------------------------------- ### Running Ratatui-Kit Examples Source: https://github.com/yexiyue/ratatui-kit/blob/main/_autodocs/quick-reference.md Execute the provided examples using Cargo to test different features of the Ratatui-Kit library, such as local state, routing, and modal dialogs. ```bash cargo run --example counter # Local state + async cargo run --example router # Multi-page routing cargo run --example modal # Modal dialogs cargo run --example todo_app # Full application ``` -------------------------------- ### Run Counter Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/README.md Execute the counter example from the repository using cargo run. ```bash cargo run --example counter ``` -------------------------------- ### Run the Routing Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/docs/src/content/docs/tutorials/router.mdx Execute the routing example application. Use keys 1, 2, and 3 to switch pages, j/k to navigate lists, Enter to open details, b/f for back/forward, and r to replace the current history entry. ```bash cargo run --example router ``` -------------------------------- ### Run MultiSelect Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/docs/src/content/docs/components/multi-select.mdx Command to run the MultiSelect example. Press j/k to move, Space to toggle selection, Enter to submit, e to toggle empty state, and q to quit. ```bash cargo run --example multi_select ``` -------------------------------- ### Full Example: Defining and Using Routes Source: https://github.com/yexiyue/ratatui-kit/blob/main/_autodocs/macros.md A comprehensive example demonstrating the `routes!` macro for defining a complex route tree, including static, dynamic, and nested routes. It also shows how to integrate these routes with a `RouterProvider` and render elements. ```rust #[derive(Deserialize)] struct UserParams { id: u64, } #[derive(Deserialize)] struct PostParams { id: u64, } #[tokio::main] async fn main() { let routes = routes! { "/" => element!(Home()), "/about" => element!(About()), "/user/:id" => element!(UserDetail()), "/user/:id/posts/:post_id" => element!(PostPage()), "/blog" => { routes! { "/" => element!(BlogIndex()), "/post/:id" => element!(BlogPost()), } } }; element!(RouterProvider(routes: routes) { element!(MainLayout()) }) .fullscreen() .await .unwrap(); } #[component] fn UserDetail(props: &mut NoProps, hooks: Hooks) -> impl Into> { let params = hooks.use_params::(); element!(Text(text: Line::from(format!("User {}", params.id)))) } ``` -------------------------------- ### Run Input Mutex Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/docs/src/content/docs/tutorials/input-mutex.mdx Execute the input mutex example to observe its behavior. Press various keys to interact with different layers and see how input is handled. ```bash cargo run --example input_mutex ``` -------------------------------- ### Run Async State Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/docs/src/content/docs/tutorials/async-state.mdx Execute the asynchronous state example using Cargo. Press 'r' to refresh and 'q' to quit. ```bash cargo run --example async_state ``` -------------------------------- ### ConfirmModal Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/_autodocs/api-reference/components.md An example demonstrating how to instantiate and use the ConfirmModal component with a title, message, and an OK handler. ```rust element!(ConfirmModal( open: true, title: Line::from("Confirm"), message: "Are you sure?", ok_handler: Handler::new(|confirmed| { if confirmed { /* ... */ } }) )) ``` -------------------------------- ### Run All Tests and Examples Source: https://github.com/yexiyue/ratatui-kit/blob/main/openspec/changes/input-layer-event-system/tasks.md Executes all tests, including workspace, library, and example tests, with locked features. This command is used to verify the integrity of the framework after migrations. ```bash cargo test --locked --all-features --workspace --lib --tests --examples ``` -------------------------------- ### Run ScrollView Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/docs/src/content/docs/components/scroll-view.mdx Command to run the scrollview example. Press j/k or arrow keys to scroll line by line, PageDown/PageUp to page, Home/End to jump to the top or bottom, and q to quit. ```bash cargo run --example scrollview ``` -------------------------------- ### Select Component Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/_autodocs/api-reference/components.md An example of how to use the Select component, providing a vector of items and an on_select handler to process user selections. ```rust element!(Select( items: vec!["Option A", "Option B", "Option C"], on_select: Handler::new(|selected| { println!("Selected: {}", selected); }) )) ``` -------------------------------- ### Event Handling Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/_autodocs/api-reference/input-handling.md This example shows how to use `use_event_handler` to capture and process keyboard events for actions like quitting or typing characters. ```APIDOC ## Event Handling Example This example demonstrates how to attach an event handler to capture and process keyboard input. ### Description Attaches an event handler to process keyboard events. It specifically handles 'q' or 'Q' to exit, character input to append to a text buffer, and backspace to remove characters. ### Method `hooks.use_event_handler(EventScope::Current, EventPriority::Normal, move |event| { ... });` ### Parameters - `event`: The input event to process. ### Event Types Handled - `Event::Key(KeyEvent)`: Processes key press events. ### KeyCode Handling - `KeyCode::Char(c)`: Appends the character `c` to the input. - `KeyCode::Backspace`: Removes the last character from the input. - `KeyCode::Char('q')` or `KeyCode::Char('Q')`: Exits the application. ### Response - `EventResult::Consumed`: If the event is handled. - `EventResult::Ignored`: If the event is not relevant or handled. ### Example ```rust hooks.use_event_handler(EventScope::Current, EventPriority::Normal, move |event| { let Event::Key(key) = event else { return EventResult::Ignored; }; if key.kind != KeyEventKind::Press { return EventResult::Ignored; } match key.code { KeyCode::Char('q') | KeyCode::Char('Q') => { exit(); EventResult::Consumed } KeyCode::Char(c) => { input_text.push(c); EventResult::Consumed } KeyCode::Backspace => { input_text.pop(); EventResult::Consumed } _ => EventResult::Ignored, } }); ``` ``` -------------------------------- ### Modal Component Usage Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/_autodocs/api-reference/components.md Shows an example of a Modal component, configured to be 50% width and height, centered, with a Border and Text content. ```rust element!(Modal( open: show_modal.get(), placement: Placement::Center, width: Constraint::Percentage(50), height: Constraint::Percentage(50), ) { element!(Border() { element!(Text(text: Line::from("Modal Content"))) }) }) ``` -------------------------------- ### Text Component Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/_autodocs/api-reference/components.md Shows how to render a styled line of text using the Text component. The example applies a cyan style to the text 'Hello'. ```rust element!(Text(text: Line::styled("Hello", Style::default().cyan()))) ``` -------------------------------- ### Full Example: TodoList Component Source: https://github.com/yexiyue/ratatui-kit/blob/main/_autodocs/macros.md A comprehensive example demonstrating the `element!` macro within a component, including state management, dynamic lists, conditional rendering, and nested components. ```rust #[component] fn TodoList(props: &mut TodoListProps, mut hooks: Hooks) -> impl Into> { let mut todos = hooks.use_state(Vec::new); let filter = hooks.use_state(Filter::All); let filtered = todos.read() .iter() .filter(|t| match filter.get() { Filter::All => true, Filter::Active => !t.done, Filter::Completed => t.done, }) .collect::>(); element!(View(flex_direction: Direction::Vertical, gap: 1) { element!(Text(text: Line::from("My Todos"))), // Dynamic list for todo in filtered { element!(TodoItem( key: ElementKey::user(&todo.id), todo: todo.clone(), )) }, // Conditional if todos.read().is_empty() { element!(Text(text: Line::from("No todos").dim())), }, // Footer buttons element!(View(flex_direction: Direction::Horizontal, gap: 1) { element!(FilterButton(label: "All")), element!(FilterButton(label: "Active")), element!(FilterButton(label: "Done")), }) }) } ``` -------------------------------- ### RouterProvider Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/_autodocs/INDEX.md Sets up routing for the application using the RouterProvider component. ```rust use ratatui_kit::routing::RouterProvider; use ratatui_kit::component::View; fn AppRouter() { RouterProvider(routes! { "/" => View { /* ... */ }, "/about" => View { /* ... */ } }) } ``` -------------------------------- ### Ctrl+C Handling Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/_autodocs/INDEX.md Illustrates how to gracefully handle Ctrl+C signals for application shutdown. ```rust use tokio::signal; use std::io; #[tokio::main] async fn main() -> io::Result<()> { // ... application setup ... // Wait for Ctrl+C signal signal::ctrl_c().await?; println!("Ctrl+C received, shutting down..."); // ... perform cleanup ... Ok(()) } ``` -------------------------------- ### ContextProvider Component Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/_autodocs/INDEX.md Demonstrates how to provide context to child components using the ContextProvider component. ```rust use ratatui_kit::component::ContextProvider; use ratatui_kit::context::SystemContext; fn App() { let system_context = SystemContext { /* ... */ }; ContextProvider(system_context, element! { // Child components that can access the context ChildComponent {} }) } ``` -------------------------------- ### LayoutStyle Configuration Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/_autodocs/api-reference/layout.md Configure component layout using LayoutStyle properties like flex direction, justification, gap, margin, and constraints. This example shows a vertically stacked view with centered content. ```rust element!(View( flex_direction: Direction::Vertical, justify_content: Flex::Center, gap: 2, margin: Margin { top: 1, right: 2, bottom: 1, left: 2 }, width: Constraint::Min(20), height: Constraint::Length(10), ) { element!(Text(text: Line::from("Centered"))), element!(Text(text: Line::from("Content"))), }) ``` -------------------------------- ### Routes Macro Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/_autodocs/INDEX.md Shows how to define static and dynamic routes using the routes! macro, including nested routes. ```rust use ratatui_kit::routing::routes; routes! { // Static route "/home" => HomePage, // Dynamic route with parameter "/users/:id" => UserProfile, // Nested routes "/settings" => { "/profile" => ProfileSettings, "/account" => AccountSettings } } ``` -------------------------------- ### Add ratatui-kit Crate Source: https://github.com/yexiyue/ratatui-kit/blob/main/README.md Install the ratatui-kit crate using cargo. ```bash cargo add ratatui-kit ``` -------------------------------- ### use_state Hook Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/_autodocs/INDEX.md Demonstrates the use of the use_state hook for managing local component state. ```rust use ratatui_kit::hooks::use_state; fn Counter() { let count = use_state(|| 0); // Increment count when a button is clicked // let increment = || count.set(*count + 1); } ``` -------------------------------- ### Hello World Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/_autodocs/00-START-HERE.md A basic 'Hello World' application using Ratatui-Kit. This demonstrates the fundamental structure for launching a Ratatui-Kit application. ```rust use ratatui_kit::prelude::*; #[tokio::main] async fn main() { element!(App()).fullscreen().await.unwrap(); } #[component] fn App(props: &mut NoProps, _hooks: Hooks) -> impl Into> { element!(Text(text: Line::from("Hello, World!"))) } ``` -------------------------------- ### Example: Mutating Shared State with use_context_mut Source: https://github.com/yexiyue/ratatui-kit/blob/main/_autodocs/api-reference/context.md Demonstrates using `use_context_mut` to get a mutable reference to a shared counter and increment it on key press. Panics if the context is not found or already borrowed. ```rust #[component] fn Counter(props: &mut NoProps, mut hooks: Hooks) -> impl Into> { let mut shared_count = hooks.use_context_mut::(); hooks.use_event_handler(EventScope::Current, EventPriority::Normal, move |event| { let Event::Key(key) = event else { return EventResult::Ignored; }; if key.code == KeyCode::Char('+') { *shared_count += 1; return EventResult::Consumed; } EventResult::Ignored }); element!(Text(text: Line::from(format!("Count: {}", *shared_count)))) } ``` -------------------------------- ### Input Handling Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/_autodocs/INDEX.md Shows a complete modal component that isolates input handling and demonstrates event dispatch flow. ```rust use ratatui_kit::component::Component; use ratatui_kit::input_handling::{EventScope, EventResult, InputLayer}; use crossterm::event::{KeyEvent, KeyCode}; use ratatui_kit::component::View; struct Modal { is_open: bool, } impl Component for Modal { // ... other methods ... fn handle_input(&self, event: KeyEvent) -> EventResult { if self.is_open { match event.code { KeyCode::Esc => { // Close modal EventResult::Consumed } KeyCode::Enter => { // Confirm action EventResult::Consumed } _ => EventResult::Ignored, } } else { EventResult::Ignored } } fn render(&self, frame: &mut ratatui::prelude::Frame, area: ratatui::prelude::Rect) { if self.is_open { // Render modal content let modal_area = /* calculate modal area */; frame.render_widget(ratatui::widgets::Clear, modal_area); // ... render modal content ... } } } // Usage within an application context // let modal = Modal { is_open: true }; // let input_layer = InputLayer::new(vec![Box::new(modal)]); // input_layer.handle_input(event); ``` -------------------------------- ### Build Example Application Source: https://github.com/yexiyue/ratatui-kit/blob/main/dev-notes/blog/2026-06-15-terminal-recording-from-zero.md Before recording, build your terminal application's binary. This ensures the recording showcases the application itself, not the compilation process. ```bash cargo build --example counter ``` -------------------------------- ### Flex Layout Examples Source: https://github.com/yexiyue/ratatui-kit/blob/main/_autodocs/api-reference/layout.md Demonstrates using Flex enum for centering and spreading elements in a horizontal layout. ```rust element!(View( flex_direction: Direction::Horizontal, justify_content: Flex::Center, gap: 2, ) { element!(Button(label: "OK")), element!(Button(label: "Cancel")), }) // Spread buttons apart element!(View( flex_direction: Direction::Horizontal, justify_content: Flex::SpaceBetween, ) { element!(Button(label: "Back")), element!(Button(label: "Next")), }) ``` -------------------------------- ### Example: Mutating Optional Context with try_use_context_mut Source: https://github.com/yexiyue/ratatui-kit/blob/main/_autodocs/api-reference/context.md Shows how to use `try_use_context_mut` to safely attempt to get a mutable reference to a `u32` context and increment it. Returns `None` if the context is not found or already borrowed. ```rust #[component] fn OptionalCounter(props: &mut NoProps, mut hooks: Hooks) -> impl Into> { if let Some(mut count) = hooks.try_use_context_mut::() { *count += 1; } element!(Text(text: Line::from("Updated"))) } ``` -------------------------------- ### Verify VHS and FFmpeg Installation Source: https://github.com/yexiyue/ratatui-kit/blob/main/dev-notes/blog/2026-06-15-terminal-recording-from-zero.md Check the installed versions of VHS and ffmpeg. This is a good practice after installation to ensure they are set up correctly. ```bash vhs --version ffmpeg -version | head -n 1 ``` -------------------------------- ### App Entry Point with Fullscreen Source: https://github.com/yexiyue/ratatui-kit/blob/main/docs/src/content/docs/internals/render-loop.mdx Demonstrates how to start an application using ElementExt, entering fullscreen mode and initiating the render loop with custom options. ```rust element!(App).fullscreen().await?; element!(App).render_loop(options).await?; ``` -------------------------------- ### NoProps Usage Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/_autodocs/api-reference/component.md This example demonstrates how to use the NoProps struct with a component that does not require any props. ```APIDOC ## NoProps **Type:** `pub struct NoProps` **Location:** `crates/ratatui-kit/src/props.rs` A unit struct used for components that don't accept any props. ### Example: ```rust #[component] pub fn SimpleText(props: &mut NoProps, _hooks: Hooks) -> impl Into> { element!(Text(text: Line::from("Static content"))) } ``` ``` -------------------------------- ### Basic Application Entrypoint Source: https://github.com/yexiyue/ratatui-kit/blob/main/docs/src/content/docs/start/quick-start.mdx This Rust code demonstrates the simplest way to run a Ratatui-Kit application using the `.fullscreen()` method. It automatically handles terminal setup and teardown. ```rust #[tokio::main] async fn main() { element!(HelloWorld) .fullscreen() .await .expect("Failed to run the application"); } ``` -------------------------------- ### AsyncCounter Component Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/_autodocs/api-reference/hooks.md An example demonstrating the `use_future` hook to create an asynchronous counter that updates every second. ```rust @component fn AsyncCounter(props: &mut CounterProps, mut hooks: Hooks) -> impl Into> { let mut count = hooks.use_state(|| 0); hooks.use_future(async move { loop { tokio::time::sleep(Duration::from_secs(1)).await; count += 1; } }); element!(Text(text: Line::from(format!("Count: {}", count.get())))) } ``` -------------------------------- ### Start a Ratatui-Kit Application Source: https://github.com/yexiyue/ratatui-kit/blob/main/_autodocs/quick-reference.md This snippet shows the basic structure for launching a ratatui-kit application. It includes the necessary imports and the main function that renders a simple 'Hello, World!' component. ```rust use ratatui_kit::prelude::*; #[tokio::main] async fn main() { element!(MyApp()) .fullscreen() .await .expect("Application error"); } #[component] fn MyApp(props: &mut NoProps, _hooks: Hooks) -> impl Into> { element!(Text(text: Line::from("Hello, World!"))) } ``` -------------------------------- ### WrappedText Component Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/_autodocs/api-reference/components.md Example of how to use the WrappedText component to render a long string that will automatically wrap. Requires the `element!` macro. ```rust element!(WrappedText( text: "Long text that wraps automatically".to_string(), style: Style::default().white() )) ``` -------------------------------- ### Routing Setup Source: https://github.com/yexiyue/ratatui-kit/blob/main/_autodocs/README.md Sets up application routes using the `routes!` macro and renders them with `RouterProvider`. Includes a basic `Outlet` for nested routing. ```rust let routes = routes! { "/" => element!(Home()), "/settings" => element!(Settings()), "/user/:id" => element!(UserDetail()), }; element!(RouterProvider(routes: routes) { element!(Outlet()) }) ``` -------------------------------- ### Build Static Documentation Site Source: https://github.com/yexiyue/ratatui-kit/blob/main/docs/README.md Builds the static version of the documentation site, outputting to the 'dist/' directory. Execute from 'docs/'. ```bash pnpm build ``` -------------------------------- ### Preview Built Documentation Site Source: https://github.com/yexiyue/ratatui-kit/blob/main/docs/README.md Previews the statically built documentation site. This command should be run from the 'docs/' directory. ```bash pnpm preview ``` -------------------------------- ### Using VirtualList Component Source: https://github.com/yexiyue/ratatui-kit/blob/main/skills/ratatui-kit/references/components.md Demonstrates how to instantiate and configure the VirtualList component. It shows setting up state, item count, rendering logic, and event handling. Ensure the 'virtual-list' feature is enabled. ```rust use ratatui::prelude::*; use ratatui_kit::components::tui_widget_list::{ListBuildContext, ListState}; // Assuming 'hooks' and 'submitted' are available in the scope let list_state = hooks.use_state(ListState::default); VirtualList::new( Constraint::Length(42), list_state, 10_000, Some(42), Block::bordered().title_top(Line::from(" build log ").centered()), 2u16, false, |context: &ListBuildContext| { let style = if context.is_selected { Style::new().on_green() } else { Style::new() }; (Line::styled(format!("row {:05}", context.index + 1), style), 1u16) }, move |index: usize| { submitted.set(format!("selected row {}", index + 1)); }, ) ``` -------------------------------- ### Example: Injecting and Using AppTheme Context Source: https://github.com/yexiyue/ratatui-kit/blob/main/_autodocs/api-reference/context.md Demonstrates how to provide an AppTheme context using ContextProvider and access it in a descendant component with use_context. ```rust #[derive(Clone)] struct AppTheme { primary_color: Color, secondary_color: Color, text_color: Color, } #[component] fn App(props: &mut NoProps, _hooks: Hooks) -> impl Into> { let theme = AppTheme { primary_color: Color::Cyan, secondary_color: Color::Magenta, text_color: Color::White, }; element!(ContextProvider(context: theme) { element!(MainContent()), }) } #[component] fn MainContent(props: &mut NoProps, hooks: Hooks) -> impl Into> { let theme = hooks.use_context::(); element!(Text(text: Line::styled( "Styled Text", Style::default().fg(theme.primary_color), ))) } ``` -------------------------------- ### Border Component Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/_autodocs/api-reference/components.md Example of using the Border component to add a cyan border with a centered top title around a Text element. Requires the `element!` macro. ```rust element!(Border( border_style: Style::default().cyan(), top_title: Line::from(" Title ").centered(), ) { element!(Text(text: Line::from("Content"))) }) ``` -------------------------------- ### Install Companion Rust Skills Source: https://github.com/yexiyue/ratatui-kit/blob/main/docs/src/content/docs/start/ai-skill.mdx Install additional Rust skills to complement the ratatui-kit skill. These cover general Rust best practices and asynchronous programming patterns. ```bash npx skills add rust-best-practices ``` ```bash npx skills add rust-async-patterns ``` -------------------------------- ### Example: Fetching Data with use_context Source: https://github.com/yexiyue/ratatui-kit/blob/main/_autodocs/api-reference/context.md Shows how to use `use_context` to retrieve configuration for an asynchronous data fetching operation. Panics if the Config context is not found. ```rust #[derive(Clone)] struct Config { api_url: String, timeout_secs: u64, } #[component] fn DataFetcher(props: &mut NoProps, mut hooks: Hooks) -> impl Into> { let config = hooks.use_context::(); hooks.use_future(async move { let url = config.api_url.clone(); // Fetch data... }); element!(Text(text: Line::from("Loading..."))) } ``` -------------------------------- ### Hello World Component Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/docs/src/content/docs/start/quick-start.mdx This Rust code defines a simple 'Hello, World!' component for a Ratatui-Kit application. It includes event handling to quit the application when 'q' is pressed. ```rust use ratatui_kit::{ crossterm::event::{Event, KeyCode, KeyEventKind}, prelude::*, ratatui::{ layout::{Constraint, Direction, Flex}, style::{Style, Stylize}, text::Line, }, }; #[tokio::main] async fn main() { element!(HelloWorld) .fullscreen() .await .expect("Failed to run the application"); } #[component] fn HelloWorld(mut hooks: Hooks) -> impl Into> { let mut exit = hooks.use_exit(); hooks.use_event_handler(EventScope::Current, EventPriority::Normal, move |event| { let Event::Key(key) = event else { return EventResult::Ignored; }; if key.kind == KeyEventKind::Press && matches!(key.code, KeyCode::Char('q') | KeyCode::Char('Q')) { exit(); return EventResult::Consumed; } EventResult::Ignored }); element!( Center( width: Constraint::Length(42), height: Constraint::Length(7), ) { Border( flex_direction: Direction::Vertical, justify_content: Flex::Center, border_style: Style::new().cyan(), top_title: Line::from(" ratatui-kit ").cyan().bold().centered(), bottom_title: Line::from(" q quit · Ctrl+C exit ").dark_gray().centered(), ) { Text(text: Line::from("Hello, World!").green().bold().centered()) } } ) } ``` -------------------------------- ### Install VHS using Homebrew Source: https://github.com/yexiyue/ratatui-kit/blob/main/dev-notes/blog/2026-06-15-terminal-recording-from-zero.md Install VHS on macOS using the Homebrew package manager. Ensure ffmpeg is also available for advanced features like extracting static images. ```bash brew install vhs ``` -------------------------------- ### Rust use_context Minimal Usage Source: https://github.com/yexiyue/ratatui-kit/blob/main/skills/ratatui-kit/references/hooks.md Examples demonstrating how to retrieve theme and SystemContext using use_context and use_context_mut. Remember to handle potential panics or use the try variants. ```rust let theme = hooks.use_context::(); // &*theme let mut sys = hooks.use_context_mut::(); ``` -------------------------------- ### Using Ratatui-Kit Prelude Source: https://github.com/yexiyue/ratatui-kit/blob/main/CLAUDE.md The `prelude` module exports commonly used items, simplifying imports for examples and general usage. It's standard practice to import these items with `use ratatui_kit::prelude::*;`. ```rust use ratatui_kit::prelude::*; ``` -------------------------------- ### Get Mutable Reference without Update Notification Source: https://github.com/yexiyue/ratatui-kit/blob/main/_autodocs/api-reference/state-management.md Use `get_mut()` to get a mutable reference to the state without triggering an update notification. This is useful for internal modifications that should not cause a re-render. ```rust let mut count = hooks.use_state(|| 0); let mut guard = count.get_mut(); *guard += 1; // No re-render triggered by this modification ``` -------------------------------- ### Global Quit Event Handler Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/_autodocs/api-reference/input-handling.md Example of a highest-priority event handler that consumes the 'q' key press to exit the application. This handler is attached to the root scope, making it globally effective. ```rust hooks.use_event_handler(EventScope::Root, EventPriority::Highest, move |event| { // Global quit handler that works everywhere if matches!(event, Event::Key(key) if key.code == KeyCode::Char('q')) { exit(); EventResult::Consumed } else { EventResult::Ignored } }); ``` -------------------------------- ### Minimal Ratatui-Kit App Source: https://github.com/yexiyue/ratatui-kit/blob/main/skills/ratatui-kit/SKILL.md This is a complete, runnable example of a Ratatui-Kit application. It includes an entry point, a component, local reactive state, an asynchronous side effect, and a keyboard handler for quitting. ```rust use ratatui_kit:: crossterm::event::{Event, KeyCode, KeyEventKind}, prelude::*, ratatui:: layout::{Constraint, Direction, Flex}, style::{Style, Stylize}, text::Line, }; #[tokio::main] async fn main() { element!(App) .fullscreen() .await .expect("Failed to run the application"); } #[component] fn App(mut hooks: Hooks) -> impl Into> { let mut count = hooks.use_state(|| 0_u64); let mut exit = hooks.use_exit(); // Async side effect: writing state wakes the render loop — no manual redraw. hooks.use_future(async move { loop { tokio::time::sleep(std::time::Duration::from_secs(1)).await; count += 1; } }); // Standard keyboard-handler shape: destructure Key → check Press → match code. hooks.use_event_handler(EventScope::Current, EventPriority::Normal, move |event| { let Event::Key(key) = event else { return EventResult::Ignored }; if key.kind != KeyEventKind::Press { return EventResult::Ignored } match key.code { KeyCode::Char('q') | KeyCode::Char('Q') => { exit(); EventResult::Consumed } _ => EventResult::Ignored, } }); element!( Center(width: Constraint::Length(48), height: Constraint::Length(9)) { Border( flex_direction: Direction::Vertical, justify_content: Flex::Center, border_style: Style::new().cyan(), top_title: Line::from(" ratatui-kit ").cyan().bold().centered(), bottom_title: Line::from(" q quit · Ctrl+C exit ").dark_gray().centered(), ) { Text(text: Line::styled( format!("Counter: {:02}", count.get()), Style::new().green().bold(), ).centered()) } } ) } ``` -------------------------------- ### Theme Context Pattern Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/_autodocs/INDEX.md Demonstrates a common pattern for managing and accessing theme settings throughout the application using context. ```rust use ratatui_kit::context::Context; use ratatui_kit::component::ContextProvider; use ratatui_kit::hooks::use_context; #[derive(Clone, Debug)] struct Theme { primary_color: String, secondary_color: String, } // Define the context impl Context for Theme {} fn App() { let theme = Theme { primary_color: "blue".to_string(), secondary_color: "gray".to_string() }; ContextProvider(theme, element! { ThemedComponent {} }) } fn ThemedComponent() { let theme = use_context::(); // Use theme.primary_color for styling // Text { text: format!("Primary: {}", theme.primary_color) } } ``` -------------------------------- ### Start a New Future on Dependency Change with use_async_effect Source: https://github.com/yexiyue/ratatui-kit/blob/main/docs/src/content/docs/core/hooks.mdx Use `use_async_effect` to start a new asynchronous task when dependencies change. This replaces the older future-based approach for effects that need to be re-run based on external state. ```rust hooks.use_async_effect( async move { status.set("checking".to_string()); // async work }, validation_key, ); ``` -------------------------------- ### Form State Pattern Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/_autodocs/INDEX.md Demonstrates a pattern for managing form state using Ratatui-Kit's state management tools. ```rust use ratatui_kit::state_management::State; use ratatui_kit::hooks::use_state; #[derive(Clone, Debug)] struct FormData { username: String, email: String, } fn MyForm() { let form_state = use_state(|| FormData { username: "".to_string(), email: "".to_string(), }); // Update username // let update_username = |new_name: String| { // form_state.update(|data| data.username = new_name); // }; // Update email // let update_email = |new_email: String| { // form_state.update(|data| data.email = new_email); // }; // Render input fields bound to form_state } ``` -------------------------------- ### use_route Hook Example Source: https://github.com/yexiyue/ratatui-kit/blob/main/_autodocs/INDEX.md Retrieves information about the current route using the use_route hook. ```rust use ratatui_kit::hooks::use_route; fn CurrentRouteDisplay() { let route = use_route(); // Text { text: format!("Current route: {}", route.path) } } ```