### Basic GPUI Component Application Setup Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/getting-started.md A simple example demonstrating how to set up a basic GPUI Component application. Ensure `gpui_component::init(cx);` is called before using any GPUI Component features. ```rust use gpui::* use gpui_component::{button::*, *}; pub struct HelloWorld; impl Render for HelloWorld { fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { div() .v_flex() .gap_2() .size_full() .items_center() .justify_center() .child("Hello, World!") .child( Button::new("ok") .primary() .label("Let's Go!") .on_click(|_, _, _| println!("Clicked!")), ) } } fn main() { let app = gpui_platform::application().with_assets(gpui_component_assets::Assets); app.run(move |cx| { // This must be called before using any GPUI Component features. gpui_component::init(cx); cx.spawn(async move |cx| { cx.open_window(WindowOptions::default(), |window, cx| { let view = cx.new(|_| HelloWorld); // This first level on the window, should be a Root. cx.new(|cx| Root::new(view, window, cx)) }) .expect("Failed to open window"); }) .detach(); }); } ``` -------------------------------- ### Run Single Example Source: https://github.com/longbridge/gpui-component/blob/main/CONTRIBUTING.md Execute a specific example by appending its name after '--example'. ```bash cargo run --example table ``` -------------------------------- ### Run Wry Example Source: https://github.com/longbridge/gpui-component/blob/main/crates/webview/README.md Execute the webview example from the root of the repository. ```bash cargo run -p webview ``` -------------------------------- ### Run Specific Example Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/getting-started.md Use this command to run a specific example from the `examples` directory. Replace `` with the desired example's name. ```bash cargo run --example ``` -------------------------------- ### Run Standalone Examples Source: https://github.com/longbridge/gpui-component/blob/main/README.md Execute standalone example crates located in the `examples` directory. Each crate focuses on a single feature. ```bash # Basic hello world cargo run -p hello_world # System monitor (real-time charts with CPU/memory data) cargo run -p system_monitor # Window title customization cargo run -p window_title ``` -------------------------------- ### Helper Function for Test Setup (Rust) Source: https://github.com/longbridge/gpui-component/blob/main/skills/gpui/references/test-examples.md Utilize helper functions to encapsulate common setup logic, making tests cleaner and more maintainable. This example shows a `create_test_counter` helper. ```rust fn create_test_counter(cx: &mut TestAppContext) -> Entity { cx.new(|cx| Counter::new(cx)) } #[gpui::test] fn test_counter_operations(cx: &mut TestAppContext) { let counter = create_test_counter(cx); // Test operations } ``` -------------------------------- ### Build and Run Web Gallery (WASM) Source: https://github.com/longbridge/gpui-component/blob/main/README.md Build and run the web gallery using WebAssembly. This involves navigating to the `story-web` directory, installing dependencies, and starting the development server. ```bash cd crates/story-web # Install dependencies (first time only) make install # Build and run development server make dev ``` -------------------------------- ### Complete Settings Example Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/components/settings.md Demonstrates the creation of a comprehensive settings interface with multiple pages, groups, and various setting item types including switches, dropdowns, and number inputs. This example shows how to configure options like size, variant, and resettability for settings elements. ```rust use gpui::{App, SharedString}; use gpui_component::{ Settings, SettingPage, SettingGroup, SettingItem, SettingField, setting::NumberFieldOptions, group_box::GroupBoxVariant, Size, }; Settings::new("app-settings") .with_size(Size::Medium) .with_group_variant(GroupBoxVariant::Outline) .pages(vec![ SettingPage::new("General") .resettable(true) .default_open(true) .groups(vec![ SettingGroup::new() .title("Appearance") .items(vec![ SettingItem::new( "Dark Mode", SettingField::switch( |cx: &App| cx.theme().mode.is_dark(), |val: bool, cx: &mut App| { // Handle theme change }, ) ) .description("Switch between light and dark themes."), ]), SettingGroup::new() .title("Font") .items(vec![ SettingItem::new( "Font Family", SettingField::dropdown( vec![ ("Arial".into(), "Arial".into()), ("Helvetica".into(), "Helvetica".into()), ], |cx: &App| "Arial".into(), |val: SharedString, cx: &mut App| { // Handle font change }, ) ), SettingItem::new( "Font Size", SettingField::number_input( NumberFieldOptions { min: 8.0, max: 72.0, ..Default::default() }, |cx: &App| 14.0, |val: f64, cx: &mut App| { // Handle size change }, ) ), ]), ]), SettingPage::new("Software Update") .resettable(true) .group( SettingGroup::new() .title("Updates") .items(vec![ SettingItem::new( "Auto Update", SettingField::switch( |cx: &App| true, |val: bool, cx: &mut App| { // Handle auto update }, ) ) .description("Automatically download and install updates."), ]) ), ]) ``` -------------------------------- ### Run development server Source: https://github.com/longbridge/gpui-component/blob/main/docs/README.md Starts the development environment for the project. ```bash bun run dev ``` -------------------------------- ### Install project dependencies Source: https://github.com/longbridge/gpui-component/blob/main/docs/README.md Use this command to install all required project dependencies defined in the lockfile. ```bash bun install ``` -------------------------------- ### Run Individual Examples Source: https://github.com/longbridge/gpui-component/blob/main/CLAUDE.md Executes specific example applications within the project. Useful for testing isolated features or components. ```bash cargo run --example hello_world cargo run --example table ``` -------------------------------- ### Loading Article List Example Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/components/skeleton.md Example showing a loading article list with placeholders for thumbnails, titles, excerpts, and dates. ```rust v_flex() .gap_6() .children((0..3).map(|_| { h_flex() .gap_4() .child(Skeleton::new().w(px(120.)).h(px(80.)).rounded_md()) // Thumbnail .child( v_flex() .gap_2() .flex_1() .child(Skeleton::new().w_full().h_5().rounded_md()) // Title .child(Skeleton::new().w(px(300.)).h_4().rounded_md()) // Excerpt line 1 .child(Skeleton::new().w(px(250.)).h_4().rounded_md()) // Excerpt line 2 .child(Skeleton::new().w(px(100.)).h_3().rounded_md()) // Date ) })) ``` -------------------------------- ### Toolbar with Tooltips Example Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/components/tooltip.md Example of how to add tooltips to buttons in a toolbar. ```APIDOC ### Toolbar with Tooltips ```rust h_flex() .gap_1() .child( Button::new("new") .icon(IconName::Plus) .tooltip_with_action("Create new file", &NewFile, Some("Editor")) ) .child( Button::new("open") .icon(IconName::FolderOpen) .tooltip_with_action("Open file", &OpenFile, Some("Editor")) ) .child( Button::new("save") .icon(IconName::Save) .tooltip_with_action("Save file", &SaveFile, Some("Editor")) ) ``` ``` -------------------------------- ### Install Linux Dependencies Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/installation.md Execute this script to install system dependencies on Linux. ```bash ./script/bootstrap ``` -------------------------------- ### Run Specific Examples Source: https://github.com/longbridge/gpui-component/blob/main/README.md Execute specific example applications built into the `story` crate, such as the code editor, dock layout system, or markdown renderer. ```bash # Code editor with LSP support and syntax highlighting cargo run --example editor # Dock layout system (panels, split views, tabs) cargo run --example dock # Markdown rendering cargo run --example markdown # HTML rendering cargo run --example html ``` -------------------------------- ### Install System Dependencies (Linux/macOS) Source: https://github.com/longbridge/gpui-component/blob/main/CONTRIBUTING.md Run this script to set up system dependencies for development on Linux or macOS. ```bash ./script/bootstrap ``` -------------------------------- ### Simple Text Copy Example Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/components/clipboard.md A straightforward example of copying a static string. ```rust Clipboard::new("simple") .value("Hello, World!") ``` -------------------------------- ### Run Story Gallery Source: https://github.com/longbridge/gpui-component/blob/main/CLAUDE.md Starts the component showcase application. This is the primary way to view and test components during development. ```bash cargo run ``` -------------------------------- ### Install System Dependencies (Windows) Source: https://github.com/longbridge/gpui-component/blob/main/CONTRIBUTING.md Execute this PowerShell command to install system dependencies on Windows. ```powershell .\script\install-window.ps1 ``` -------------------------------- ### Loading Table Rows Example Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/components/skeleton.md Example demonstrating loading table rows with placeholders for status indicators, names, emails, roles, and actions. ```rust v_flex() .gap_2() .children((0..5).map(|_| { h_flex() .gap_4() .p_3() .border_b_1() .border_color(cx.theme().border) .child(Skeleton::new().size_8().rounded_full()) // Status indicator .child(Skeleton::new().w(px(150.)).h_4().rounded_md()) // Name .child(Skeleton::new().w(px(200.)).h_4().rounded_md()) // Email .child(Skeleton::new().w(px(80.)).h_4().rounded_md()) // Role .child(Skeleton::new().w(px(60.)).h_4().rounded_md()) // Actions })) ``` -------------------------------- ### Loading Profile Card Example Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/components/skeleton.md Example demonstrating a loading profile card using various Skeleton components for avatar, name, email, and bio lines. ```rust v_flex() .gap_4() .p_4() .border_1() .border_color(cx.theme().border) .rounded(cx.theme().radius_lg) .child( h_flex() .gap_3() .items_center() .child(Skeleton::new().size_12().rounded_full()) // Avatar .child( v_flex() .gap_2() .child(Skeleton::new().w(px(120.)).h_4().rounded_md()) // Name .child(Skeleton::new().w(px(100.)).h_3().rounded_md()) // Email ) ) .child( v_flex() .gap_2() .child(Skeleton::new().w_full().h_4().rounded_md()) // Bio line 1 .child(Skeleton::new().w(px(200.)).h_4().rounded_md()) // Bio line 2 ) ``` -------------------------------- ### Install Windows Dependencies Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/installation.md Run this PowerShell script to install required tools and dependencies on Windows. ```powershell .\script\install-window.ps1 ``` -------------------------------- ### Status Indicators with Tooltips Example Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/components/tooltip.md Example demonstrating tooltips on status indicator elements. ```APIDOC ### Status Indicators with Tooltips ```rust h_flex() .gap_2() .child( div() .size_3() .rounded_full() .bg(cx.theme().success) .tooltip(|window, cx| { Tooltip::new("Connected to server").build(window, cx) }) ) .child( div() .size_3() .rounded_full() .bg(cx.theme().warning) .tooltip(|window, cx| { Tooltip::new("Limited connectivity").build(window, cx) }) ) ``` ``` -------------------------------- ### User Profile Information Example Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/components/description-list.md An example of using DescriptionList to display user profile details with multiple columns and a full-width separator for a bio. ```rust DescriptionList::new() .columns(2) .bordered(true) .children([ DescriptionItem::new("Full Name").value("John Doe"), DescriptionItem::new("Email").value("john@example.com"), DescriptionItem::new("Phone").value("+1 (555) 123-4567"), DescriptionItem::new("Department").value("Engineering"), DescriptionItem::Separator, DescriptionItem::new("Bio").value( "Senior software engineer with 10+ years of experience in Rust and system programming." ).span(2), ]) ``` -------------------------------- ### Label Component Usage Examples Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/components/label.md Illustrative examples of how to use the Label component in various scenarios. ```APIDOC ## Label Component Usage Examples ### Basic Label ```rust use gpui_component::label::Label; Label::new("This is a label") ``` ### Label with Secondary Text ```rust // Label with optional indicator Label::new("Company Address") .secondary("(optional)") // Label with required indicator Label::new("Email Address") .secondary("(required)") ``` ### Text Alignment ```rust // Left aligned (default) Label::new("Text align left") // Center aligned Label::new("Text align center") .text_center() // Right aligned Label::new("Text align right") .text_right() ``` ### Text Highlighting ```rust use gpui_component::label::HighlightsMatch; // Full text highlighting (finds all matches) Label::new("Hello World Hello") .highlights("Hello") // Prefix highlighting (only matches at start) Label::new("Hello World") .highlights(HighlightsMatch::Prefix("Hello".into())) // Highlight with secondary text Label::new("Company Name") .secondary("(optional)") .highlights("Company") ``` ### Color and Styling ```rust use gpui_component::green_500; // Custom text color Label::new("Color Label") .text_color(green_500()) // Font styling Label::new("Font Size Label") .text_size(px(20.)) .font_semibold() .line_height(rems(1.8)) ``` ### Masked Labels ```rust // For sensitive information Label::new("9,182,1 USD") .text_2xl() .masked(true) // Shows as "•••••••••••" // Toggle masking programmatically Label::new("500 USD") .text_xl() .masked(self.masked) ``` ### Multi-line Text ```rust // Text wrapping with line height div().w(px(200.)).child( Label::new( "Label should support text wrap in default, \ if the text is too long, it should wrap to the next line." ) .line_height(rems(1.8)) ) ``` ### Different Sizes ```rust // Using text size utilities Label::new("Extra Large").text_2xl() Label::new("Large").text_xl() Label::new("Medium").text_base() // default Label::new("Small").text_sm() Label::new("Extra Small").text_xs() ``` ### Form Labels Example ```rust // Required field Label::new("Email Address") .secondary("*") .text_color(cx.theme().destructive) // Optional field Label::new("Phone Number") .secondary("(optional)") // Field with description Label::new("Password") .secondary("(minimum 8 characters)") ``` ### Search Highlighting Example ```rust // Interactive search highlighting let search_term = "Hello"; Label::new("Hello World Hello Universe") .highlights(search_term) // Highlights all "Hello" occurrences ``` ``` -------------------------------- ### Interactive Elements with Rich Tooltips Example Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/components/tooltip.md Example showcasing complex, multi-line tooltips for interactive elements. ```APIDOC ### Interactive Elements with Rich Tooltips ```rust v_flex() .gap_3() .child( div() .p_2() .border_1() .border_color(cx.theme().border) .rounded(cx.theme().radius) .child("File: document.txt") .id("file-item") .tooltip(|window, cx| { Tooltip::element(|_, cx| { v_flex() .gap_1() .child( h_flex() .gap_2() .child(IconName::File) .child("document.txt") .text_sm() .font_medium() ) .child( div() .child("Size: 2.4 KB") .text_xs() .text_color(cx.theme().muted_foreground) ) .child( div() .child("Modified: 2 hours ago") .text_xs() .text_color(cx.theme().muted_foreground) ) .child( h_flex() .gap_1() .child(Kbd::new("Enter")) .child("to open") .text_xs() .text_color(cx.theme().muted_foreground) ) }) .build(window, cx) }) ) ``` ``` -------------------------------- ### Basic Tab Implementation Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/components/tabs.md Standard tab bar setup with click event handling. ```rust TabBar::new("tabs") .selected_index(0) .on_click(|selected_index, _, _| { println!("Tab {} selected", selected_index); }) .child(Tab::new().label("Account")) .child(Tab::new().label("Profile")) .child(Tab::new().label("Settings")) ``` -------------------------------- ### Start Development Server Source: https://github.com/longbridge/gpui-component/blob/main/crates/story-web/README.md Starts the Vite development server after building the WASM in debug mode and generating JavaScript bindings. The server runs on http://localhost:3000. ```bash make dev ``` -------------------------------- ### Run All Story Examples Source: https://github.com/longbridge/gpui-component/blob/main/CONTRIBUTING.md Use 'cargo run' to execute all UI test cases and display them in a gallery of GPUI components. ```bash cargo run ``` -------------------------------- ### Multi-step Form Example Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/components/stepper.md A practical implementation of a stepper within a form context. ```rust Stepper::new("form-stepper") .w_full() .selected_index(form_step) .items([ StepperItem::new() .icon(IconName::User) .child("Personal Info"), StepperItem::new() .icon(IconName::CreditCard) .child("Payment"), StepperItem::new() .icon(IconName::CircleCheck) .child("Confirmation"), ]) .on_click(cx.listener(|this, step, _, cx| { this.form_step = *step; cx.notify(); })) ``` -------------------------------- ### Complex GroupBox Example Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/components/group-box.md A comprehensive example combining custom styling, layout, and multiple child components. ```rust GroupBox::new() .id("notification-settings") .outline() .bg(cx.theme().group_box) .rounded_xl() .p_5() .title("Notification Preferences") .title_style( StyleRefinement::default() .font_semibold() .line_height(relative(1.0)) .px_3() ) .content_style( StyleRefinement::default() .rounded_xl() .py_3() .px_4() .border_2() ) .child( v_flex() .gap_3() .child( h_flex() .justify_between() .child("Email notifications") .child(Switch::new("email").checked(true)) ) .child( h_flex() .justify_between() .child("Push notifications") .child(Switch::new("push").checked(false)) ) .child( h_flex() .justify_between() .child("SMS notifications") .child(Switch::new("sms").checked(false)) ) ) .child( h_flex() .justify_end() .gap_2() .child(Button::new("cancel").label("Cancel")) .child(Button::new("save").primary().label("Save Settings")) ) ``` -------------------------------- ### Loading States Examples Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/components/spinner.md Demonstrates different spinner configurations for various loading states, including custom colors and sizes. ```rust // Simple loading spinner Spinner::new() // Loading with custom color Spinner::new() .color(cx.theme().blue) // Large loading spinner Spinner::new() .large() .color(cx.theme().primary) ``` -------------------------------- ### Horizontal Virtual List Example Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/components/virtual-list.md Shows how to implement a horizontal virtual list, where item widths are specified. ```rust h_virtual_list( cx.entity().clone(), "horizontal-list", item_sizes.clone(), |view, visible_range, _, cx| { visible_range .map(|ix| { div() .w(px(120.)) // Width is used for horizontal lists .h_full() .bg(cx.theme().accent) .child(format!("Card {}", ix)) }) .collect() }, ) .track_scroll(&scroll_handle) ``` -------------------------------- ### Search Input Example Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/components/input.md A common use case for the Input component, demonstrating a search field with a prefix icon. ```rust let search = cx.new(|cx| InputState::new(window, cx) .placeholder("Search...") ); Input::new(&search) .prefix(Icon::new(IconName::Search).small()) ``` -------------------------------- ### Basic Vertical Virtual List Example Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/components/virtual-list.md Demonstrates the basic implementation of a vertical virtual list rendering 5000 items with uniform sizes. ```rust use std::rc::Rc; use gpui::{px, size, Size, Pixels}; pub struct ListViewExample { items: Vec, item_sizes: Rc>>, scroll_handle: VirtualListScrollHandle, } impl ListViewExample { fn new(cx: &mut Context) -> Self { let items = (0..5000).map(|i| format!("Item {}", i)).collect::>(); let item_sizes = Rc::new(items.iter().map(|_| size(px(200.), px(30.))).collect()); Self { items, item_sizes, scroll_handle: VirtualListScrollHandle::new(), } } } impl Render for ListViewExample { fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { v_virtual_list( cx.entity().clone(), "my-list", self.item_sizes.clone(), |view, visible_range, _, cx| { visible_range .map(|ix| { div() .h(px(30.)) .w_full() .bg(cx.theme().secondary) .child(format!("Item {}", ix)) }) .collect() }, ) .track_scroll(&self.scroll_handle) } } ``` -------------------------------- ### Form Section Example Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/components/group-box.md Use GroupBox to organize form inputs and actions into a logical section. ```rust GroupBox::new() .fill() .title("Personal Information") .child( v_flex() .gap_4() .child( h_flex() .gap_2() .child(Input::new("first-name").placeholder("First Name")) .child(Input::new("last-name").placeholder("Last Name")) ) .child(Input::new("email").placeholder("Email Address")) .child( h_flex() .justify_end() .child(Button::new("update").primary().label("Update Profile")) ) ) ``` -------------------------------- ### Create a Simple "Hello, World!" Application with a Button Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/index.md This example demonstrates how to set up a basic GPUI application, initialize GPUI components, open a window, and render a "Hello, World!" message with a clickable button. Ensure `gpui_component::init(cx)` is called before using any GPUI Component features. ```rust use gpui::* use gpui_component::{button::*, *}; pub struct HelloWorld; impl Render for HelloWorld { fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { div() .v_flex() .gap_2() .size_full() .items_center() .justify_center() .child("Hello, World!") .child( Button::new("ok") .primary() .label("Let's Go!") .on_click(|_, _, _| println!("Clicked!")), ) } } fn main() { gpui_platform::application().run(move |cx| { // This must be called before using any GPUI Component features. gpui_component::init(cx); cx.spawn(async move |cx| { cx.open_window(WindowOptions::default(), |window, cx| { let view = cx.new(|_| HelloWorld); // This first level on the window, should be a Root. cx.new(|cx| Root::new(view, window, cx)) }) .expect("Failed to open window"); }) .detach(); }); } ``` -------------------------------- ### Setup application root view for dialogs Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/components/dialog.md Integrate the dialog layer into the main application render loop using Root::render_dialog_layer. ```rust use gpui_component::TitleBar; struct MyApp { view: AnyView, } impl Render for MyApp { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { let dialog_layer = Root::render_dialog_layer(window, cx); div() .size_full() .child( v_flex() .size_full() .child(TitleBar::new()) .child(div().flex_1().overflow_hidden().child(self.view.clone())), ) // Render the dialog layer on top of the app content .children(dialog_layer) } } ``` -------------------------------- ### Example: Lazy Loading Tree Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/components/tree.md Illustrates how to implement lazy loading for tree items, loading children only when needed. ```APIDOC ## Lazy Loading Tree Example This example demonstrates a `LazyTreeView` struct that implements lazy loading of directory children. ### `LazyTreeView` Struct ```rust struct LazyTreeView { tree_state: Entity, loaded_paths: HashSet, } ``` ### `load_children` Method - **Description**: Loads children for a given item if they haven't been loaded yet and the item is a directory. - **Parameters**: - **item_id** (`&str`): The ID of the item whose children should be loaded. - **cx** (`&mut Context`): The context for the view. ### Logic: 1. Checks if the `item_id` has already been loaded. 2. If it's a directory, it spawns an asynchronous task to load its children. 3. Updates the `TreeState` with the loaded children. 4. Marks the path as loaded to prevent redundant loading. ``` -------------------------------- ### Basic GPUI Application Structure Source: https://github.com/longbridge/gpui-component/blob/main/README.md This example demonstrates the basic structure of a GPUI application using the component library. Ensure `gpui_component::init(cx)` is called before using any components. The application opens a window and renders a 'Hello, World!' message with a button. ```rust use gpui::* use gpui_component::{button::*, *}; pub struct HelloWorld; impl Render for HelloWorld { fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { div() .v_flex() .gap_2() .size_full() .items_center() .justify_center() .child("Hello, World!") .child( Button::new("ok") .primary() .label("Let\'s Go!") .on_click(|_, _, _| println!("Clicked!")), ) } } fn main() { gpui_platform::application().run(move |cx| { // This must be called before using any GPUI Component features. gpui_component::init(cx); cx.spawn(async move |cx| { cx.open_window(WindowOptions::default(), |window, cx| { let view = cx.new(|_| HelloWorld); // This first level on the window, should be a Root. cx.new(|cx| Root::new(view, window, cx)) }) .expect("Failed to open window"); }) .detach(); }); } ``` -------------------------------- ### Icon Usage Example Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/getting-started.md Shows how to use the `Icon` element with different `IconName` variants and sizes. Note that SVG files are not bundled by default. ```rust use gpui_component::{Icon, IconName}; Icon::new(IconName::Check) Icon::new(IconName::Search).small() ``` -------------------------------- ### Install Dependencies for WASM Source: https://github.com/longbridge/gpui-component/blob/main/crates/story-web/README.md Installs the necessary Rust target for WASM and the wasm-bindgen-cli tool. Also includes instructions for installing Bun. ```bash rustup target add wasm32-unknown-unknown cargo install wasm-bindgen-cli curl -fsSL https://bun.sh/install | bash ``` -------------------------------- ### Run the Application Source: https://github.com/longbridge/gpui-component/blob/main/docs/index.md Command to compile and run the GPUI Component 'Hello World' application. ```sh $ cargo run ``` -------------------------------- ### Responsive Spacing Example Source: https://github.com/longbridge/gpui-component/blob/main/skills/gpui/references/layout-style.md Applies various padding properties (all, horizontal, vertical, top) and sets the gap between child elements for responsive spacing control. ```rust div() .p(px(16.)) // Padding all sides .px(px(20.)) // Padding horizontal .py(px(12.)) // Padding vertical .pt(px(8.)) // Padding top .gap(px(8.)) // Gap between children ``` -------------------------------- ### Input Component Setup and Rendering Source: https://github.com/longbridge/gpui-component/blob/main/skills/gpui-component/references/usage.md Demonstrates how to initialize an `InputState` with a placeholder and default value, and then render the `Input` component with various configurations like `cleanable`, `disabled`, `prefix`, `suffix`, `mask_toggle`, and `appearance`. ```rust use gpui_component::input::{Input, InputState}; use gpui_component::{Icon, IconName, Button}; // State setup (in new/init) let input = cx.new(|cx| InputState::new(window, cx) .placeholder("Enter text...") .default_value("Hello") ); // Render Input::new(&input) Input::new(&input).cleanable(true) // clear button Input::new(&input).disabled(true) Input::new(&input).prefix(Icon::new(IconName::Search).small()) Input::new(&input).suffix(Button::new("b").ghost().icon(IconName::X).xsmall()) Input::new(&input).mask_toggle() // password reveal toggle Input::new(&input).appearance(false) // remove default border/bg ``` -------------------------------- ### Form Validation with Tooltips Example Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/components/tooltip.md Example of using tooltips to display form validation errors. ```APIDOC ### Form Validation with Tooltips ```rust struct FormView { email_error: Option, password_error: Option, } v_flex() .gap_4() .child( Input::new("email") .placeholder("Email address") .when_some(self.email_error.clone(), |this, error| { this.tooltip(move |window, cx| { Tooltip::element(|_, cx| { h_flex() .gap_1() .child(IconName::AlertCircle) .child(error.clone()) .text_color(cx.theme().destructive) }) .build(window, cx) }) }) ) ``` ``` -------------------------------- ### Run Desktop Gallery Source: https://github.com/longbridge/gpui-component/blob/main/README.md Build and run the `story` crate, which serves as a gallery for all available GPUI components. ```bash cargo run ``` -------------------------------- ### Initialize GPUI Component with Root Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/root.md This snippet shows the basic setup for running a GPUI application and initializing GPUI Component features. Ensure `gpui_component::init(cx)` is called before using any GPUI Component features. ```rust fn main() { gpui_platform::application().run(move |cx| { // This must be called before using any GPUI Component features. gpui_component::init(cx); cx.spawn(async move |cx| { cx.open_window(WindowOptions::default(), |window, cx| { let view = cx.new(|_| Example); // This first level on the window, should be a Root. cx.new(|cx| Root::new(view, window, cx)) }) .expect("Failed to open window"); }) .detach(); }); } ``` -------------------------------- ### Build Settings with Multiple Pages Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/components/settings.md Demonstrates creating a settings UI with multiple distinct pages, including one that defaults to being open. ```rust Settings::new("app-settings") .pages(vec![ SettingPage::new("General") .default_open(true) .group(SettingGroup::new().title("Appearance").items(vec![...])), SettingPage::new("Software Update") .group(SettingGroup::new().title("Updates").items(vec![...])), SettingPage::new("About") .group(SettingGroup::new().items(vec![...])), ]) ``` -------------------------------- ### Hello World Application with GPUI Component Source: https://github.com/longbridge/gpui-component/blob/main/docs/index.md A basic 'Hello, World!' application using GPUI Component. It initializes the component, opens a window, and renders a simple view with a button. ```rust use gpui::*; use gpui_component::{button::*, *}; pub struct HelloWorld; impl Render for HelloWorld { fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { div() .v_flex() .gap_2() .size_full() .items_center() .justify_center() .child("Hello, World!") .child( Button::new("ok") .primary() .label("Let's Go!") .on_click(|_, _, _| println!("Clicked!")), ) } } fn main() { gpui_platform::application().run(move |cx| { // This must be called before using any GPUI Component features. gpui_component::init(cx); cx.spawn(async move |cx| { cx.open_window(WindowOptions::default(), |window, cx| { let view = cx.new(|_| HelloWorld); // This first level on the window, should be a Root. cx.new(|cx| Root::new(view, window, cx)) }) .expect("Failed to open window"); }) .detach(); }); } ``` -------------------------------- ### File Manager Context Menu Example Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/components/menu.md Demonstrates creating a context menu for a file manager. Includes various menu items, separators, submenus, and icons for actions like opening, copying, pasting, and deleting files. ```rust div() .id("file-manager") .child("Right-click for options") .context_menu(|menu, window, cx| { menu.menu_with_icon("Open", IconName::FolderOpen, Box::new(Open)) .separator() .menu_with_icon("Copy", IconName::Copy, Box::new(Copy)) .menu_with_icon("Cut", IconName::Scissors, Box::new(Cut)) .menu_with_icon("Paste", IconName::Clipboard, Box::new(Paste)) .separator() .submenu("New", window, cx, |submenu, window, cx| { submenu.menu_with_icon("File", IconName::File, Box::new(NewFile)) .menu_with_icon("Folder", IconName::Folder, Box::new(NewFolder)) }) .separator() .menu_with_icon("Delete", IconName::Trash, Box::new(Delete)) .separator() .menu("Properties", Box::new(ShowProperties)) }) ``` -------------------------------- ### Example: Search and Filter Tree Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/components/tree.md Provides an example of a `SearchableTree` that filters tree items based on a search query. ```APIDOC ## Search and Filter Tree Example This example shows a `SearchableTree` that allows filtering items based on a search query. ### `SearchableTree` Struct ```rust struct SearchableTree { tree_state: Entity, original_items: Vec, search_query: String, } ``` ### `filter_tree` Method - **Description**: Filters the tree items based on the provided search query. - **Parameters**: - **query** (`&str`): The search query string. - **cx** (`&mut Context`): The context for the view. ### Logic: 1. Updates the `search_query`. 2. If the query is empty, it resets the tree to `original_items`. 3. Otherwise, it calls `filter_tree_items` to get the filtered list. 4. Updates the `TreeState` with the filtered items. ### `filter_tree_items` Function - **Description**: Recursively filters a list of `TreeItem`s based on a query. - **Parameters**: - **items** (`&[TreeItem]`): The list of items to filter. - **query** (`&str`): The search query. - **Returns**: `Vec` - The filtered list of items. ### Filtering Logic: - Items are filtered if their label contains the query (case-insensitive). - Matching items are automatically expanded. - If an item doesn't match directly, its children are recursively filtered. If any children match, the parent is included and expanded, with its children set to the filtered list. ``` -------------------------------- ### Basic Language Selector Example Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/components/select.md A simple example of a Select component used for language selection. It initializes with a list of languages and a placeholder. ```rust let languages = SearchableVec::new(vec![ "Rust".into(), "TypeScript".into(), "Go".into(), "Python".into(), "JavaScript".into(), ]); let state = cx.new(|cx| { SelectState::new(languages, None, window, cx) }); Select::new(&state) .placeholder("Select language...") .title_prefix("Language: ") ``` -------------------------------- ### Create a Basic Description List Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/components/description-list.md Construct a simple DescriptionList with key-value pairs using the `item` method. ```rust DescriptionList::new() .item("Name", "GPUI Component", 1) .item("Version", "0.1.0", 1) .item("License", "Apache-2.0", 1) ``` -------------------------------- ### Currency Input Example Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/components/input.md An example of an input field configured for currency, using a number mask with a comma separator and two decimal places. ```rust let amount = cx.new(|cx| InputState::new(window, cx) .mask_pattern(MaskPattern::Number { separator: Some(','), fraction: Some(2), }) ); div() .child(Input::new(&amount)) .child(format!("Value: {}", amount.read(cx).value())) ``` -------------------------------- ### CI/CD Test Workflow Example (YAML) Source: https://github.com/longbridge/gpui-component/blob/main/skills/gpui/references/test-examples.md A sample GitHub Actions workflow file (`.github/workflows/test.yml`) demonstrating how to set up continuous integration for running GPUI tests. ```yaml # .github/workflows/test.yml name: Tests on: [push, pull_request] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: dtolnay/rust-toolchain@stable - name: Run tests run: cargo test --features test-support ``` -------------------------------- ### Create a Settings Sidebar Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/components/sidebar.md Use Sidebar::new() to initialize a sidebar. Configure its width, header, and add groups of menu items. Each menu item can have an icon, active state, and nested children. ```rust Sidebar::new() .width(300) .header( SidebarHeader::new() .child("Settings") ) .child( SidebarGroup::new("General") .child( SidebarMenu::new() .child( SidebarMenuItem::new("Appearance") .icon(IconName::Palette) .active(true) ) .child( SidebarMenuItem::new("Notifications") .icon(IconName::Bell) .suffix( Switch::new("notifications") .checked(true) .xsmall() ) ) .child( SidebarMenuItem::new("Privacy") .icon(IconName::Shield) ) ) ) .child( SidebarGroup::new("Advanced") .child( SidebarMenu::new() .child( SidebarMenuItem::new("Developer") .icon(IconName::Code) .children([ SidebarMenuItem::new("Debug Mode") .suffix( Switch::new("debug") .checked(false) .xsmall() ), SidebarMenuItem::new("Console") .on_click(|_, _, _| println!("Open console")), ]) ) .child( SidebarMenuItem::new("Performance") .icon(IconName::Zap) ) ) ) ``` -------------------------------- ### Team Display Example Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/components/avatar.md An example demonstrating how to use AvatarGroup within a vertical flex layout to display a team with a limited number of avatars and an ellipsis. ```rust use gpui_component::{h_flex, v_flex}; v_flex() .gap_4() .child("Development Team") .child( AvatarGroup::new() .limit(4) .ellipsis() .child(Avatar::new().name("Alice Johnson").src("https://example.com/alice.jpg")) .child(Avatar::new().name("Bob Smith").src("https://example.com/bob.jpg")) .child(Avatar::new().name("Charlie Brown")) .child(Avatar::new().name("Diana Prince")) .child(Avatar::new().name("Eve Wilson")) ) ``` -------------------------------- ### Size Variations Examples Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/components/spinner.md Provides examples of spinners in various sizes, from extra small for inline text to large for prominent states, including custom sizes. ```rust // Extra small for inline text Spinner::new() .xsmall() .color(cx.theme().muted_foreground) // Small for buttons Spinner::new() .small() .color(cx.theme().primary_foreground) // Medium for general use (default) Spinner::new() .color(cx.theme().primary) // Large for prominent loading states Spinner::new() .large() .color(cx.theme().blue) // Custom size for specific requirements Spinner::new() .with_size(px(32.)) .color(cx.theme().orange) ``` -------------------------------- ### Panel with Size Limits Examples Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/components/resizable.md Illustrates different ways to apply size constraints to resizable panels, including minimum size only, min/max range, and fixed size. ```rust // Panel with minimum size only resizable_panel() .size_range(px(100.)..Pixels::MAX) .child("Flexible Panel") ``` ```rust // Panel with both min and max resizable_panel() .size_range(px(200.)..px(500.)) .child("Constrained Panel") ``` ```rust // Panel with exact constraints resizable_panel() .size(px(300.)) .size_range(px(300.)..px(300.)) // Fixed size .child("Fixed Panel") ``` -------------------------------- ### Image Sizing Options Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/components/image.md Shows how to set fixed dimensions, responsive widths with aspect ratios, and square sizes for images. ```rust // Fixed dimensions img("https://example.com/photo.jpg") .w(px(300.)) .h(px(200.)) ``` ```rust // Responsive width with aspect ratio img("https://example.com/banner.jpg") .w(relative(1.)) // Full width .max_w(px(800.)) .h(px(400.)) ``` ```rust // Square image img("https://example.com/avatar.jpg") .size(px(100.)) // 100x100px ``` -------------------------------- ### Status Indicator Examples Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/components/badge.md Common patterns for status badges. ```rust // Online status Badge::new() .dot() .color(cx.theme().green) .child(Avatar::new().src("https://example.com/user.jpg")) // Verified status Badge::new() .icon(IconName::CheckCircle) .color(cx.theme().blue) .child(Avatar::new().src("https://example.com/verified-user.jpg")) // Warning status Badge::new() .icon(IconName::AlertTriangle) .color(cx.theme().yellow) .child(Avatar::new().src("https://example.com/user.jpg")) ``` -------------------------------- ### Create a Basic SettingPage Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/components/settings.md Use `SettingPage::new` to create a new settings page with a title and add groups of settings. ```rust SettingPage::new("General") .group(SettingGroup::new().title("Options").items(vec![...])) ``` -------------------------------- ### Notification Indicator Examples Source: https://github.com/longbridge/gpui-component/blob/main/docs/docs/components/badge.md Common patterns for notification badges. ```rust // Unread messages Badge::new() .count(12) .child(Icon::new(IconName::Mail).large()) // New notifications Badge::new() .count(3) .color(cx.theme().red) .child(Icon::new(IconName::Bell).large()) // High priority with custom max Badge::new() .count(1234) .max(999) .color(cx.theme().orange) .child(Icon::new(IconName::AlertTriangle)) ``` -------------------------------- ### Initialize gpui-component in Main Application Source: https://github.com/longbridge/gpui-component/blob/main/skills/gpui-component/references/usage.md Initialize the gpui_component library first, then open a window and create a root element. The Root element is required for dialogs, sheets, and notifications. ```rust fn main() { gpui_platform::application() .with_assets(gpui_component_assets::Assets) .run(move |cx| { gpui_component::init(cx); // MUST be first cx.spawn(async move |cx| { cx.open_window(WindowOptions::default(), |window, cx| { let view = cx.new(|_| MyApp); cx.new(|cx| Root::new(view, window, cx)) // Root wraps first view }).expect("Failed to open window"); }).detach(); }); } ``` -------------------------------- ### Initialize Application and Create Entities Source: https://github.com/longbridge/gpui-component/blob/main/skills/gpui/references/context.md Use the `App` context to initialize the application and create new entities. Entities can be created within the application's run loop. ```rust fn main() { let app = Application::new(); app.run(|cx: &mut App| { // Create entities let entity = cx.new(|cx| MyState::default()); // Open windows cx.open_window(WindowOptions::default(), |window, cx| { cx.new(|cx| Root::new(view, window, cx)) }); }); } ```