### Run Markdown Example Source: https://github.com/wess/guise/blob/main/docs/markdowneditor.md Execute the provided example project to test the markdown editor functionality. ```sh cargo run -p guise-ui --example markdown ``` -------------------------------- ### Configure and Start a Tour Entity Source: https://github.com/wess/guise/blob/main/docs/overlays.md Define onboarding steps and subscribe to tour events to manage UI state transitions. ```rust let tour = cx.new(|cx| { Tour::new(cx) .step("Welcome", "This is your workspace.") .step("Panels", "Drag tabs between panes; edges split.") .step("Command palette", "Cmd+K opens Spotlight.") }); tour.update(cx, |t, cx| t.start(cx)); cx.subscribe(&tour, |_this, _t, event: &TourEvent, _cx| match event { TourEvent::Step(i) => { /* highlight the relevant UI */ } TourEvent::Finished => { /* mark onboarding done */ } TourEvent::Skipped => { /* respect the dismissal */ } }) .detach(); ``` -------------------------------- ### Implement the minimal Workbench view Source: https://github.com/wess/guise/blob/main/docs/tutorial.md A complete example of a main.rs file implementing a Workbench struct and initializing the application with a dark theme. ```rust use gpui::prelude::*; use gpui::{ div, px, size, App, Application, Bounds, Context, IntoElement, SharedString, TitlebarOptions, Window, WindowBounds, WindowOptions, }; use guise::prelude::*; struct Workbench; impl Render for Workbench { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { let t = cx.global::(); div() .size_full() .bg(t.body().hsla()) .text_color(t.text().hsla()) .font_family(t.font_family.clone()) .p(px(24.0)) .child( Stack::new() .gap(Size::Md) .child(Title::new("Workbench").order(2)) .child(Text::new("A data workbench, one chapter at a time.").dimmed()), ) } } fn main() { Application::new().run(|cx: &mut App| { // 1. Install the theme global exactly once, before any window opens. Theme::dark().init(cx); // 2. Open a window hosting the root view. let bounds = Bounds::centered(None, size(px(1100.0), px(760.0)), cx); cx.open_window( WindowOptions { window_bounds: Some(WindowBounds::Windowed(bounds)), titlebar: Some(TitlebarOptions { title: Some(SharedString::new_static("workbench")), ..Default::default() }), ..Default::default() }, |_window, cx| cx.new(|_cx| Workbench), ) .expect("open window"); cx.activate(true); }); } ``` -------------------------------- ### Install Guise UI Source: https://github.com/wess/guise/blob/main/crates/guise/README.md Add the dependency via cargo command or Cargo.toml file. ```sh cargo add guise-ui ``` ```toml [dependencies] guise-ui = "0.2" gpui = "0.2" ``` -------------------------------- ### Reactive Hooks Usage Source: https://github.com/wess/guise/blob/main/docs/reactive.md Examples of state initialization, watching for changes, memoization, and side effects. ```rust let count = use_state(cx, 0i32); // = Signal::new watch(cx, &count); // re-render this view when `count` changes let label = use_memo(cx, &count, |n| format!("Count: {n}")); // derived signal use_effect(cx, &count, |n, _cx| println!("count -> {n}")); // side effect ``` -------------------------------- ### Initialize and configure Sparkline charts Source: https://github.com/wess/guise/blob/main/docs/charts.md Examples of creating a Sparkline with default settings and a customized version with specific color, stroke width, and layout. ```rust Sparkline::new([3.0, 5.0, 2.0, 8.0, 6.0]).fill() Sparkline::new(history).color(ColorName::Teal).stroke(1.0).full_width() ``` -------------------------------- ### Initialize and open a Spotlight command palette Source: https://github.com/wess/guise/blob/main/docs/overlays.md Create a Spotlight instance with command items and trigger its display using the open method within a window context. ```rust let palette = cx.new(|cx| { Spotlight::new(cx) .item("New file", |_w, _app| { /* ... */ }) .item_hint("Toggle theme", "⌘T", |_w, _app| { /* ... */ }) }); // open from a handler that has a window: palette.update(cx, |s, cx| s.open(window, cx)); ``` -------------------------------- ### Initialize a Theme Source: https://github.com/wess/guise/blob/main/README.md Apply a theme at application startup using the gpui global context. ```rust guise::Theme::dark().init(cx); // or Theme::light() guise::Theme::catppuccin().init(cx); // or nord / tokyonight / gruvbox / dracula / solarized_light ``` -------------------------------- ### PieChart Source: https://github.com/wess/guise/blob/main/docs/charts.md PieChart renders proportional slices starting at 12 o'clock. Supports donut-style rendering and legend entries. ```APIDOC ## PieChart ### Description Renders proportional slices. Supports donut holes and labeled entries. ### Methods - **new(values)** / **entries(pairs)** - **color(color)** - **colors(iter)** - **size(px)** (default 160.0) - **donut(fraction)** (clamped 0.05..=0.95) ### Example ```rust PieChart::new([40.0, 30.0, 20.0, 10.0]).donut(0.6) PieChart::entries([("Rust", 62.0), ("TOML", 25.0), ("Other", 13.0)]) ``` ``` -------------------------------- ### Initialize prebuilt themes Source: https://github.com/wess/guise/blob/main/docs/theming.md Apply one of the six built-in palettes or load a preset by name. ```rust Theme::catppuccin().init(cx); // Catppuccin Mocha (dark) Theme::nord().init(cx); Theme::tokyonight().init(cx); Theme::gruvbox().init(cx); Theme::dracula().init(cx); Theme::solarized_light().init(cx); // Or by name (see PRESET_NAMES): if let Some(theme) = Theme::preset("dracula") { theme.init(cx); } ``` -------------------------------- ### Initialize Theme Source: https://github.com/wess/guise/blob/main/crates/guise/README.md Set the global theme at application startup using the GPUI context. ```rust guise::Theme::dark().init(cx); // or Theme::light() ``` -------------------------------- ### Create a minimal Guise application Source: https://github.com/wess/guise/blob/main/docs/gettingstarted.md A basic implementation showing theme initialization and a simple UI component structure. ```rust use gpui::prelude::*; use gpui::{ div, px, size, App, Bounds, Context, IntoElement, Window, WindowBounds, WindowOptions, }; use guise::prelude::*; struct Hello; impl Render for Hello { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { // Read the active theme for window-level colors. let t = cx.global::(); div() .size_full() .bg(t.body().hsla()) .text_color(t.text().hsla()) .p(px(24.0)) .child( Stack::new() .gap(Size::Md) .child(Title::new("Hello, guise").order(1)) .child(Button::new("ok", "Click me")), ) } } fn main() { gpui::Application::new().run(|cx: &mut App| { // 1. Install a theme exactly once, before opening any window. Theme::dark().init(cx); // 2. Open a window hosting your root view. let bounds = Bounds::centered(None, size(px(640.0), px(480.0)), cx); cx.open_window( WindowOptions { window_bounds: Some(WindowBounds::Windowed(bounds)), ..Default::default() }, |_window, cx| cx.new(|_cx| Hello), ) .expect("open window"); cx.activate(true); }); } ``` -------------------------------- ### Create Keyboard Shortcut Hints Source: https://github.com/wess/guise/blob/main/docs/typography.md Use the Kbd builder to render individual keyboard key caps. ```rust Group::new() .child(Kbd::new("⌘")) .child(Kbd::new("K")) ``` -------------------------------- ### Initialize a new Rust project Source: https://github.com/wess/guise/blob/main/docs/tutorial.md Commands to create a new binary crate and navigate into the directory. ```sh cargo new workbench cd workbench ``` -------------------------------- ### Initialize and configure a Panel Source: https://github.com/wess/guise/blob/main/docs/panels.md Demonstrates creating a collapsible Panel with a title, icon, action, and footer. ```rust Panel::new() .id("status") .title("Project status") .description("Weekly summary") .icon(ThemeIcon::new("▦").color(ColorName::Blue)) .action(ActionIcon::new("status-more", "…").size(Size::Sm)) .collapsible() .collapsed(self.collapsed) .on_toggle(cx.listener(|this, _ev, _window, cx| { this.collapsed = !this.collapsed; cx.notify(); })) .footer(Text::new("Updated 5 minutes ago").size(Size::Xs).dimmed()) .child(Text::new("Everything on track.")) ``` -------------------------------- ### Run Guise Development Commands Source: https://github.com/wess/guise/blob/main/AGENTS.md Standard Cargo commands for building, testing, and running the gallery showcase. ```sh cargo run -p gallery # launch the showcase cargo check -p guise-ui # fast type-check (package is guise-ui; lib name is guise) cargo test -p guise-ui # unit tests (pure logic only) cargo build -p gallery # full binary build ``` -------------------------------- ### Initialize and trigger a ContextMenu Source: https://github.com/wess/guise/blob/main/docs/overlays.md Shows how to instantiate a ContextMenu with items and trigger it via a right-click mouse event. ```rust let menu = cx.new(|cx| { ContextMenu::new(cx) .section("File") .item_icon(IconName::Copy, "Copy path", |_w, _app| { /* ... */ }) .item("Rename", |_w, _app| { /* ... */ }) .divider() .danger_item("Delete", |_w, _app| { /* ... */ }) }); // In the parent's render (MouseButton / MouseDownEvent are gpui types): div() .id("target") .child("Right-click me") .on_mouse_down(MouseButton::Right, cx.listener(|this, ev: &MouseDownEvent, window, cx| { let position = ev.position; this.menu.update(cx, |menu, cx| menu.show(position, window, cx)); })) .child(self.menu.clone()) ``` -------------------------------- ### Initialize Application Menu Wiring Source: https://github.com/wess/guise/blob/main/docs/windowmenu.md Integrate menu definitions and action handlers within the application run closure. ```rust gpui::Application::new().run(|cx: &mut App| { Theme::dark().init(cx); cx.set_menus(/* … as above … */); cx.on_action::(|_, cx| cx.quit()); cx.on_action::(|_, cx| { /* … */ }); // open_window(...); cx.activate(true); }); ``` -------------------------------- ### Initialize and Configure a DataView Source: https://github.com/wess/guise/blob/main/docs/data.md Demonstrates creating a DataView bound to a signal, configuring item rendering, sorting, and handling selection events. ```rust let todos = use_state(cx, vec!["Write docs".to_string(), "Ship".to_string()]); let view = cx.new(|cx| { DataView::new(cx, &todos) .item(|todo, _ix, _window, _cx| Text::new(todo.clone())) .sort_by(|a, b| a.cmp(b)) .selectable() }); cx.subscribe(&view, |_this, _view, event: &DataViewEvent, _cx| { let DataViewEvent::Selected(ix) = event; // index into the SOURCE vec }) .detach(); // Later, from anywhere — the view repaints by itself: todos.update(cx, |list| list.push("Celebrate".into())); ``` -------------------------------- ### Initialize Spotlight Command Palette Source: https://github.com/wess/guise/blob/main/docs/tutorial.md Configure a Spotlight entity with custom command items and handlers that interact with application state. ```rust // In Workbench::new: let palette_log = log.clone(); let spotlight = cx.new(|cx| { Spotlight::new(cx) .item_hint("Toggle theme", "⌘T", |window, cx| { let next = cx.global::().scheme.toggled(); cx.global_mut::().scheme = next; window.refresh(); }) .item("Clear log", move |_window, cx| { palette_log.update(cx, |lines| lines.clear()); }) }); ``` -------------------------------- ### Initialize TreeSitterHighlighter Source: https://github.com/wess/guise/blob/main/docs/editor.md Create a highlighter instance using a language grammar and query, then attach it to an Editor. ```rust let rust = guise::TreeSitterHighlighter::new( tree_sitter_rust::LANGUAGE.into(), tree_sitter_rust::HIGHLIGHTS_QUERY, )?; // errors = query/grammar version mismatch let editor = cx.new(|cx| Editor::new(cx).highlighter(rust).value(source)); ``` -------------------------------- ### Initialize and Configure Editor Source: https://github.com/wess/guise/blob/main/docs/tutorial.md Constructs an Editor instance with SQL language support and subscribes to the Run event. ```rust const FIRST_QUERY: &str = "SELECT id, customer, total\nFROM orders\nORDER BY total DESC;"; // In Workbench::new: let editor = cx.new(|cx| { Editor::new(cx) .language(Language::Sql) .rows(10) .placeholder("SELECT * FROM orders;") .value(FIRST_QUERY) }); cx.subscribe(&editor, |this, _editor, event: &EditorEvent, cx| { if let EditorEvent::Run(source) = event { this.run_query(source.clone(), cx); // defined in chapter 9 } }) .detach(); ``` -------------------------------- ### Build and Test Guise Source: https://github.com/wess/guise/blob/main/crates/guise/README.md Commands to run the component gallery and library unit tests. ```sh cargo run -p gallery # launch the component gallery cargo test -p guise # run the library's unit tests ``` -------------------------------- ### Initialize a MenuBar Source: https://github.com/wess/guise/blob/main/docs/overlays.md Creates a new MenuBar instance with File and Edit menus, including shortcuts, dividers, and disabled items. ```rust let bar = cx.new(|cx| { MenuBar::new(cx) .menu("File", |m| { m.item_shortcut("New Tab", "⌘T", |_w, _app| { /* ... */ }) .item_shortcut("New Window", "⌘N", |_w, _app| { /* ... */ }) .divider() .danger_item("Quit", |_w, _app| { /* ... */ }) }) .menu("Edit", |m| { m.item_shortcut("Undo", "⌘Z", |_w, _app| {}) .disabled_item("Redo") .divider() .section("Clipboard") .item_shortcut("Copy", "⌘C", |_w, _app| {}) .item_shortcut("Paste", "⌘V", |_w, _app| {}) }) }); ``` -------------------------------- ### Initialize and Subscribe to WebView Events Source: https://github.com/wess/guise/blob/main/docs/webview.md Create a new WebView entity and subscribe to its lifecycle events using the Guise context. ```rust use guise::prelude::*; let view = cx.new(|cx| { WebView::new(cx) .url("https://example.com") .height(360.0) }); cx.subscribe(&view, |_this, _view, event: &WebViewEvent, _cx| { match event { WebViewEvent::TitleChanged(title) => println!("title: {title}"), WebViewEvent::UrlChanged(url) => println!("→ {url}"), WebViewEvent::LoadStarted => {} WebViewEvent::LoadFinished => {} } }) .detach(); ``` -------------------------------- ### Initialize and use OverlayHost Source: https://github.com/wess/guise/blob/main/docs/overlays.md Register the OverlayHost at the root view and trigger modals or toasts from any handler. ```rust // At the root view: create once, render last (so overlays paint above). let overlays = cx.new(OverlayHost::new); div().child(page_content).child(overlays.clone()) // From any handler: overlays.update(cx, |host, cx| { host.toast("Saved", cx); host.toast_titled("Deploy failed", "web-3 timed out", ColorName::Red, cx); host.open_modal(window, cx, |close, _window, _cx| { Modal::new() .title("Settings") .on_close(move |_ev, window, cx| close(window, cx)) .child(settings_form()) .into_any_element() }); }); ``` -------------------------------- ### Initialize and configure a Guise Image Source: https://github.com/wess/guise/blob/main/docs/data.md Creates an image element supporting remote URIs, asset paths, or filesystem paths with optional fallback content. ```rust Image::new("https://example.com/cat.png") // or a PathBuf, or an asset path .width(240.0) .height(160.0) .radius(Size::Md) .fit(ObjectFit::Cover) .fallback(|| Text::new("no image").dimmed()) ``` -------------------------------- ### DatePicker Initialization and Event Subscription Source: https://github.com/wess/guise/blob/main/docs/dates.md Shows how to initialize a DatePicker with constraints and subscribe to selection events. ```rust let picker = cx.new(|cx| { DatePicker::new(cx) .label("Ship date") .min(Date::new(2026, 1, 1).unwrap()) .format("YYYY-MM-DD") }); cx.subscribe(&picker, |_, event: &DatePickerEvent, _| match event { DatePickerEvent::Selected(date) => { /* single mode */ } DatePickerEvent::Range(start, end) => { /* range mode */ } }).detach(); ``` -------------------------------- ### MarkdownEditor Initialization Source: https://github.com/wess/guise/blob/main/docs/markdowneditor.md How to instantiate and configure a MarkdownEditor entity within the Guise framework. ```APIDOC ## MarkdownEditor Initialization ### Description Creates a new MarkdownEditor instance with initial content and placeholder text. ### Usage ```rust let editor = cx.new(|cx| { MarkdownEditor::new(cx) .value("# Notes\n\n- [ ] try **guise**") .placeholder("Start writing…") }); ``` ``` -------------------------------- ### Create a Card component with guise Source: https://github.com/wess/guise/blob/main/docs/readme.md Demonstrates building a simple UI layout using Card, Stack, Title, Text, and Button components. ```rust use guise::prelude::*; Card::new().child( Stack::new() .gap(Size::Sm) .child(Title::new("Welcome").order(3)) .child(Text::new("Build native UIs with a familiar component API.").dimmed()) .child( Group::new() .justify(Justify::End) .child(Button::new("cancel", "Cancel").variant(Variant::Default)) .child(Button::new("ok", "Get started")), ), ) ``` -------------------------------- ### Load a JSON theme file Source: https://github.com/wess/guise/blob/main/docs/theming.md Read a JSON file from the filesystem and initialize it as the active theme. ```rust let theme = Theme::from_json(&std::fs::read_to_string("theme.json")?)?; theme.init(cx); ``` -------------------------------- ### Configure component theme properties Source: https://github.com/wess/guise/blob/main/docs/tutorial.md Demonstrates applying Size, ColorName, and Variant tokens to component builders. ```rust Group::new() .gap(Size::Sm) .child(Button::new("run", "Run").color(ColorName::Teal)) .child(Button::new("fmt", "Format").variant(Variant::Light)) .child(Button::new("cancel", "Cancel").variant(Variant::Default).size(Size::Xs)) ``` -------------------------------- ### Create a Transition component Source: https://github.com/wess/guise/blob/main/docs/transitions.md Initializes a one-shot entrance animation with a stable ID and specified easing. ```rust Transition::new("hero") .kind(TransitionKind::SlideUp) .easing(Easing::Spring(Spring::default())) .duration_ms(220) .child(Card::new().child(content)) ``` -------------------------------- ### Execute build and test commands Source: https://github.com/wess/guise/blob/main/README.md Commands for running the component gallery and executing the library test suite. ```sh cargo run -p gallery # launch the component gallery cargo test -p guise-ui # run the library's tests (unit + gpui entity harness) ``` -------------------------------- ### Initialize FileInput Source: https://github.com/wess/guise/blob/main/docs/files.md Create a FileInput component and subscribe to selection events to handle chosen file paths. ```rust let avatar = cx.new(|cx| { FileInput::new(cx) .label("Avatar") .accept(["png", "jpg", "jpeg"]) }); cx.subscribe(&avatar, |_, FileInputEvent(paths), _| { // paths: Vec; empty means the user cleared the field }).detach(); ``` -------------------------------- ### Initialize the global theme Source: https://github.com/wess/guise/blob/main/docs/theming.md Sets the initial theme for the application using either light or dark mode. ```rust use guise::prelude::*; Theme::light().init(cx); // or Theme::dark() ``` -------------------------------- ### Initialize a TreeView Source: https://github.com/wess/guise/blob/main/docs/tutorial.md Create a hierarchical navigation tree with nodes and subscribe to activation events to route the main application view. ```rust // A new field to route the main area: enum MainView { Query, Settings, } // In Workbench::new: let tree = cx.new(|cx| { TreeView::new(cx) .nodes(vec![ TreeNode::new("queries", "queries") .child(TreeNode::new("orders", "orders.sql")) .child(TreeNode::new("revenue", "revenue.sql")), TreeNode::new("tables", "tables") .child(TreeNode::new("t-orders", "orders")) .child(TreeNode::new("t-customers", "customers")), TreeNode::new("settings", "settings").icon(IconName::Star), ]) .expand("queries") }); cx.subscribe(&tree, |this, _tree, event: &TreeViewEvent, cx| { if let TreeViewEvent::Activated(id) = event { this.view = if id.as_ref() == "settings" { MainView::Settings } else { MainView::Query }; cx.notify(); } }) .detach(); ``` -------------------------------- ### Build Application Menus Source: https://github.com/wess/guise/blob/main/docs/windowmenu.md Use cx.set_menus to define the menu bar structure, ensuring fully-qualified names to avoid conflicts with Guise components. ```rust cx.set_menus(vec![ gpui::Menu { name: SharedString::new_static("My App"), items: vec![ gpui::MenuItem::action("Toggle Theme", ToggleThemeAction), gpui::MenuItem::separator(), gpui::MenuItem::action("Quit", QuitAction), ], }, gpui::Menu { name: SharedString::new_static("View"), items: vec![gpui::MenuItem::action("Toggle Theme", ToggleThemeAction)], }, ]); ``` -------------------------------- ### Customize and initialize theme Source: https://github.com/wess/guise/blob/main/docs/theming.md Modifies theme fields before initializing the global theme instance. ```rust let mut theme = Theme::dark(); theme.primary_color = ColorName::Grape; theme.default_radius = Size::Md; theme.init(cx); ``` -------------------------------- ### Configure Cargo dependencies Source: https://github.com/wess/guise/blob/main/docs/tutorial.md Add gpui and guise-ui to the project's Cargo.toml file. ```toml [package] name = "workbench" version = "0.1.0" edition = "2021" [dependencies] gpui = "0.2" guise-ui = "0.2" ``` -------------------------------- ### Initialize Table Source: https://github.com/wess/guise/blob/main/docs/data.md Constructs a basic table with headers and rows. Columns are sized equally by default. ```rust Table::new() .with_border(true) .striped(true) .highlight_on_hover(true) .head(["Name", "Role", "Status"]) .row(["Ada", "Admin", "Active"]) .row(["Grace", "Editor", "Active"]) ``` -------------------------------- ### Initialize BarChart Source: https://github.com/wess/guise/blob/main/docs/charts.md Create a bar chart using either raw values or labeled entries with custom spacing. ```rust BarChart::new([12.0, 9.0, 15.0, 7.0]) BarChart::entries([("Mon", 12.0), ("Tue", 9.0), ("Wed", 15.0)]).gap(0.3) ``` -------------------------------- ### Initialize a branded theme Source: https://github.com/wess/guise/blob/main/docs/tutorial.md Overrides semantic colors app-wide using theme builders before initialization. ```rust Theme::dark() .with_primary(color!("#5f3dc4")) .with_body(color!(rgb(14, 14, 19))) .with_surface(color!(rgb(22, 22, 30))) .init(cx); ``` -------------------------------- ### TableView::new Source: https://github.com/wess/guise/blob/main/docs/tutorial.md Initializes a new TableView instance within the provided context. ```APIDOC ## TableView::new(cx) ### Description Creates a new instance of a TableView. This should be called within a context builder. ### Parameters - **cx** (Context) - Required - The application context used to initialize the component. ``` -------------------------------- ### Initialize and Subscribe to MarkdownEditor Source: https://github.com/wess/guise/blob/main/docs/markdowneditor.md Construct a new MarkdownEditor entity within a context and subscribe to its change and link-click events. ```rust use guise::markdown::{MarkdownEditor, MarkdownEditorEvent}; let editor = cx.new(|cx| { MarkdownEditor::new(cx) .value("# Notes\n\n- [ ] try **guise**") .placeholder("Start writing…") }); cx.subscribe(&editor, |_this, _editor, event: &MarkdownEditorEvent, _cx| { match event { MarkdownEditorEvent::Change(text) => { /* persist the document */ } MarkdownEditorEvent::LinkClick(target) => { /* open the target */ } } }) .detach(); ``` -------------------------------- ### Configure Container Source: https://github.com/wess/guise/blob/main/docs/flex.md Create a styled box with padding, radius, color, and alignment. ```rust Container::new() .padding(EdgeInsets::all(12.0)) .radius(8.0) .color(theme(cx).color(ColorName::Blue, 1)) .alignment(Alignment::Center) .child(Text::new("Boxed").bold()) ``` -------------------------------- ### Implement Responsive Layouts with Breakpoints Source: https://github.com/wess/guise/blob/main/docs/layout.md Use Breakpoint to read window dimensions and Responsive to define adaptive values. Responsive values are mobile-first and resolve automatically during each render. ```rust let bp = Breakpoint::from_window(window); // read during render let columns = Responsive::new(1).md(2).xl(4).resolve(bp); SimpleGrid::new(columns).children(cards) if bp.at_least(Breakpoint::Lg) { /* show the sidebar */ } ``` -------------------------------- ### Initialize a TextInput component Source: https://github.com/wess/guise/blob/main/docs/inputs.md Creates a single-line text input field with a label, placeholder, and description. ```rust let name = cx.new(|cx| { TextInput::new(cx) .label("Name") .placeholder("Ada Lovelace") .description("Click to focus, then type.") }); ``` -------------------------------- ### Initialize and subscribe to SplitPanel Source: https://github.com/wess/guise/blob/main/docs/panels.md Create a new SplitPanel with custom dimensions and directions, and subscribe to its resize events. ```rust let split = cx.new(|cx| { SplitPanel::new(cx) .direction(SplitDirection::Horizontal) .ratio(0.35) .min_first(140.0) .min_second(200.0) .first(|_w, _cx| Text::new("Sidebar")) .second(|_w, _cx| Text::new("Main content")) }); cx.subscribe(&split, |_this, _split, event: &SplitPanelEvent, cx| { let SplitPanelEvent::Resized(_ratio) = event; // persist it, relayout, … cx.notify(); }) .detach(); // In render: div().h(px(300.0)).w_full().child(self.split.clone()) ``` -------------------------------- ### Create a block with ConcreteBlock Source: https://github.com/wess/guise/blob/main/thirdparty/block/README.md Shows how to instantiate a block using ConcreteBlock and copy it to the heap before usage. ```rust let block = ConcreteBlock::new(|a: i32, b: i32| a + b); let block = block.copy(); assert!(unsafe { block.call((5, 8)) } == 13); ``` -------------------------------- ### Initialize a Collapse component Source: https://github.com/wess/guise/blob/main/README.md Configures a collapsible panel with spring physics and a defined height. ```rust Collapse::new("details") .open(self.expanded) .height(120.0) .easing(Easing::Spring(Spring::default())) .child(detail_panel()) ``` -------------------------------- ### Initialize and manipulate a Signal Source: https://github.com/wess/guise/blob/main/docs/reactive.md Demonstrates creating a new Signal and performing basic read/write operations using a context. ```rust let count = Signal::new(cx, 0i32); // cx: &mut App or &mut Context<_> count.get(cx); // T: Clone — copy the value out count.read(cx); // &T — borrow it count.set(cx, 5); // replace + notify count.update(cx, |n| *n += 1); // mutate in place + notify ``` -------------------------------- ### Initialize TableView Source: https://github.com/wess/guise/blob/main/docs/data.md Creates a rich, generic data table with support for sorting, selection, and virtualization. The body becomes virtualized when a fixed height is provided. ```rust struct User { name: String, age: u32 } let table = cx.new(|cx| { TableView::new(cx) .columns(vec![ Column::new("Name") .text(|u: &User| u.name.clone().into()) .sortable_by(|a, b| a.name.cmp(&b.name)), Column::new("Age") .width(80.0) .align(Align::End) .text(|u: &User| u.age.to_string().into()) .sortable_by(|a, b| a.age.cmp(&b.age)), ]) .rows(users) // or .bind_rows(&signal, cx) .selection_mode(SelectionMode::Multi) .striped(true) .with_border(true) .height(320.0) // fixed height => virtualized body }); cx.subscribe(&table, |_this, _table, event: &TableViewEvent, _cx| match event { TableViewEvent::SelectionChanged(rows) => { /* source-row indices */ } TableViewEvent::Activated(row) => { /* double-click or Enter */ } TableViewEvent::Sorted(sort) => { /* Some((column, dir)) or None */ } }) .detach(); ``` -------------------------------- ### Initialize AppShell layout Source: https://github.com/wess/guise/blob/main/docs/tutorial.md Defines a fixed-size header, navbar, and main content area. Region closures are re-invoked every render, so avoid moving captured variables into handlers. ```rust let shell = AppShell::new() .header(44.0, |_window, _cx| { div() .flex() .items_center() .justify_between() .h_full() .px(px(14.0)) .child(Title::new("Workbench").order(5)) .child( Button::new("theme", "Toggle theme") .variant(Variant::Default) .size(Size::Xs) .on_click(|_ev, window, cx| { let next = cx.global::().scheme.toggled(); cx.global_mut::().scheme = next; window.refresh(); }), ) }) .navbar(240.0, |_, _| { div() .p(px(10.0)) .child(Text::new("Queries").size(Size::Sm).dimmed()) }) .child( Container::new() .size(Size::Md) .padding(Size::Md) .child(Space::y(Size::Md)) .child(Title::new("Results").order(4)) .child(Space::y(Size::Sm)) .child(Text::new("Nothing to show yet.").dimmed().size(Size::Sm)), ); ``` -------------------------------- ### Render Inline HTML Source: https://github.com/wess/guise/blob/main/docs/webview.md Initialize a WebView with raw HTML content instead of a URL. ```rust WebView::new(cx).html("

Hello from wry

") ``` -------------------------------- ### Configure Tree-sitter dependencies Source: https://github.com/wess/guise/blob/main/docs/editor.md Add the required features and grammar crates to your Cargo.toml file. ```toml guise-ui = { version = "…", features = ["treesitter"] } tree-sitter-rust = "0.24" # each grammar is its own crate ``` -------------------------------- ### WebView Builder Methods Source: https://github.com/wess/guise/blob/main/docs/webview.md Methods used to configure the WebView entity during initialization. ```APIDOC ## WebView Builder Methods ### Methods - **new(cx)** - Initializes a new WebView entity. - **url(into)** - Sets the initial URL to load. - **html(into)** - Sets the initial inline HTML (mutually exclusive with url). - **width(f32)** - Sets a fixed width in pixels. - **height(f32)** - Sets a fixed height in pixels. - **bordered(bool)** - Toggles themed border and rounded frame (default: true). - **radius(Size)** - Sets corner radius when bordered. - **transparent(bool)** - Allows page background to show through (default: false). ``` -------------------------------- ### Initialize VirtualList Source: https://github.com/wess/guise/blob/main/docs/data.md Creates a windowed list component for large collections. The factory closure runs per visible index every frame, so it should be kept lightweight. ```rust VirtualList::new("log", lines.len(), move |i, _window, _cx| { Text::new(lines[i].clone()).size(Size::Sm) }) .height(400.0) ``` -------------------------------- ### Initialize LineChart Source: https://github.com/wess/guise/blob/main/docs/charts.md Create line charts using either a single anonymous series or multiple named series with axes and labels. ```rust LineChart::new([12.0, 18.0, 9.0, 24.0, 20.0, 31.0]).fill().height(180.0) LineChart::series("Revenue", [12.0, 18.0, 24.0, 30.0]) .add_series("Costs", [8.0, 11.0, 13.0, 16.0]) .axis() .labels(["Q1", "Q2", "Q3", "Q4"]) .hover() ``` -------------------------------- ### Configure a StatusBar Source: https://github.com/wess/guise/blob/main/docs/navigation.md Sets up a themed status bar with content slots and layout pinning. ```rust StatusBar::new() .left(Text::new("guise gallery").size(Size::Xs)) .left(Badge::new("Dark").size(Size::Sm).color(ColorName::Grape)) .center(Text::new("Ready").size(Size::Xs).dimmed()) .right(Text::new("v0.1.0").size(Size::Xs).dimmed()) ``` ```rust div().relative().size_full().flex().flex_col() .child(div().id("scroll").flex_1().min_h(px(0.0)).overflow_y_scroll().child(content)) .child(status_bar) ``` -------------------------------- ### Spotlight Source: https://github.com/wess/guise/blob/main/docs/overlays.md A command palette overlay featuring a search field and a keyboard-navigable command list. ```APIDOC ## Spotlight ### Methods - **new(cx)** - Creates a new Spotlight instance. - **item(label, handler)** - Adds a command item. - **item_hint(label, hint, handler)** - Adds a command item with a keyboard hint. - **is_open()** - Returns the open state. - **open(window, cx)** - Opens the spotlight. - **close(cx)** - Closes the spotlight. ``` -------------------------------- ### Initialize and subscribe to ColorInput Source: https://github.com/wess/guise/blob/main/docs/inputs.md Constructs a ColorInput entity and subscribes to its color change events. ```rust let brand = cx.new(|cx| { ColorInput::new(cx).label("Brand color").value(rgb(34, 139, 230)) }); cx.subscribe(&brand, |_this, _input, event: &ColorInputEvent, _cx| { let color: Hsla = event.0; }).detach(); ``` -------------------------------- ### Implement DataView with filtering and selection Source: https://github.com/wess/guise/blob/main/docs/tutorial.md Initializes a DataView with a filter closure and selection subscription. Requires manual notification forwarding when the filter source changes. ```rust use std::cell::RefCell; use std::rc::Rc; // In Workbench::new, after `queries` and `filter` from chapter 5: let query_cache: Rc> = Rc::new(RefCell::new(String::new())); let filter_cache = query_cache.clone(); let query_list = cx.new(|cx| { DataView::new(cx, &queries) .item(|name: &String, _ix, _window, _cx| Text::new(name.clone()).size(Size::Sm)) .filter(move |name: &String| { let query = filter_cache.borrow(); query.is_empty() || name.to_lowercase().contains(&query.to_lowercase()) }) .sort_by(|a, b| a.to_lowercase().cmp(&b.to_lowercase())) .selectable() }); cx.subscribe(&query_list, |this, _view, event: &DataViewEvent, cx| { let DataViewEvent::Selected(ix) = event; this.active_query = Some(*ix); // a new Option field cx.notify(); }) .detach(); // Copy each filter write into the cell, then nudge the DataView to repaint. let filtered = query_list.clone(); cx.observe(filter.entity(), move |_this, changed, cx| { *query_cache.borrow_mut() = changed.read(cx).clone(); filtered.update(cx, |_, cx| cx.notify()); }) .detach(); ``` -------------------------------- ### Implement MenuBar Source: https://github.com/wess/guise/blob/main/docs/tutorial.md Creates a horizontal application menu bar with multiple dropdown menus. Shortcut strings serve as visual hints. ```rust let menubar = cx.new(|cx| { MenuBar::new(cx) .menu("File", |m| { m.item_shortcut("New query", "⌘N", |_window, _cx| { /* … */ }) .divider() .danger_item("Quit", |_window, cx| cx.quit()) }) .menu("View", |m| { m.item("Toggle theme", |window, cx| { let next = cx.global::().scheme.toggled(); cx.global_mut::().scheme = next; window.refresh(); }) }) }); ``` -------------------------------- ### Initialize and Subscribe to TabBar Events Source: https://github.com/wess/guise/blob/main/docs/tutorial.md Configures a new TabBar and handles Select, Close, and Add events to synchronize editor buffers. ```rust // New fields: tabbar: Entity, sources: Vec, active_tab: usize. let tabbar = cx.new(|cx| { TabBar::new(cx) .tabs(["orders.sql", "revenue.sql"]) .active(0) }); cx.subscribe(&tabbar, |this, bar, event: &TabBarEvent, cx| match event { TabBarEvent::Select(next) => { let next = *next; // Save the outgoing buffer, load the incoming one. this.sources[this.active_tab] = this.editor.read(cx).text(); this.active_tab = next; let source = this.sources[next].clone(); this.editor.update(cx, |e, cx| e.set_text(&source, cx)); } TabBarEvent::Close(i) => { // Closing is a *request* — decide (unsaved changes? last tab?), // then remove. let i = *i; if this.sources.len() > 1 { this.sources.remove(i); bar.update(cx, |b, cx| b.remove_tab(i, cx)); this.active_tab = bar.read(cx).active_index(); let source = this.sources[this.active_tab].clone(); this.editor.update(cx, |e, cx| e.set_text(&source, cx)); } } TabBarEvent::Add => { this.sources[this.active_tab] = this.editor.read(cx).text(); this.sources.push(String::new()); bar.update(cx, |b, cx| { let n = b.len() + 1; b.add_tab(format!("untitled {n}"), cx); }); this.active_tab = bar.read(cx).active_index(); this.editor.update(cx, |e, cx| e.set_text("", cx)); } }) .detach(); ``` -------------------------------- ### ContextMenu Methods Source: https://github.com/wess/guise/blob/main/docs/overlays.md Methods available for configuring and controlling a ContextMenu instance. ```APIDOC ## ContextMenu Methods ### new(cx) Creates a new ContextMenu instance. ### item(label, handler) Adds a standard menu item with a label and a handler function. ### item_icon(IconName, label, handler) Adds a menu item with a leading icon, label, and handler. ### danger_item(label, handler) Adds a menu item rendered in red, typically for destructive actions. ### section(label) / divider() Adds non-interactive structural elements to the menu. ### size(Size) Sets the item font scale (default: Sm). ### width(f32) Sets the fixed width of the menu (default: 220.0). ### show(position, window, cx) Opens the menu at the specified window coordinates and grabs focus. ### close(window, cx) / is_open() Programmatically manages the menu state; closing restores previous focus. ``` -------------------------------- ### Assemble Settings Panel Source: https://github.com/wess/guise/blob/main/docs/tutorial.md Constructs a settings panel with multiple input fields, a validation-enabled save button, and layout grouping. Ensure all bound inputs are initialized before inclusion in the panel structure. ```rust let save = Button::new("save-settings", "Save") .on_click(cx.listener(|this, _ev, _window, cx| { this.form.update(cx, |f| { f.validate(); }); if this.form.read(cx).is_valid() { this.toasts.update(cx, |t, cx| { t.push_titled("Saved", "Settings updated.", ColorName::Teal, cx); }); } cx.notify(); })); let settings_panel = Panel::new() .title("Settings") .description("Connection & workspace") .child( Stack::new() .gap(Size::Md) .child(host_field) .child(email_field) .child( Group::new() .align(Align::Start) .gap(Size::Lg) .child(div().flex_1().child(self.api_key_input.clone())) .child(div().flex_1().child(self.accent_input.clone())), ) .child(self.tags_input.clone()) .child( Stack::new() .gap(Size::Xs) .child(Text::new("Sampling range").size(Size::Sm)) .child(self.range_input.clone()), ) .child( Group::new() .align(Align::Center) .gap(Size::Md) .child(self.pin_input.clone()) .child(Text::new("2FA code").size(Size::Sm).dimmed()), ) .child(Rating::new("satisfaction").bind(self.rating.binding())) .child(Group::new().justify(Justify::End).child(save)), ); ``` -------------------------------- ### Initialize Dropzone Source: https://github.com/wess/guise/blob/main/docs/files.md Create a Dropzone component with custom labels and file filtering, using the on_files callback to process dropped or selected paths. ```rust Dropzone::new("uploads") .label("Drop images here") .hint("PNG or JPG") .accept(["png", "jpg"]) .on_files(|paths, _cx| { // every drop or dialog pick that passed the filter }) ``` -------------------------------- ### Create Bindings from Signals Source: https://github.com/wess/guise/blob/main/docs/reactive.md Demonstrates creating bindings from a full signal or a specific field lens using the bind method. ```rust let dark = use_state(cx, false); Switch::new("dark-mode").bind(dark.binding()); // the whole signal let settings = use_state(cx, Settings::default()); // one field (a lens) Checkbox::new("mute").bind(settings.lens(|s| s.muted, |s, v| s.muted = v)); ``` -------------------------------- ### Configure a SplitPanel Source: https://github.com/wess/guise/blob/main/docs/tutorial.md Create a vertical split panel with defined minimum sizes and dynamic content builders for each pane. ```rust // In Workbench::new — the results table moves into the bottom pane, // framed by a stateless Panel: let table = results.clone(); let split = cx.new(|cx| { SplitPanel::new(cx) .direction(SplitDirection::Vertical) .ratio(0.4) .min_first(140.0) .min_second(180.0) .first(|_, _| { div() .p(px(12.0)) .child(Text::new("Editor — chapter 8.").size(Size::Sm).dimmed()) }) .second(move |_, _| { div().p(px(12.0)).child( Panel::new() .title("Results") .description("orders") .child(table.clone()), ) }) }); cx.subscribe(&split, |_this, _split, _event: &SplitPanelEvent, cx| cx.notify()).detach(); ``` -------------------------------- ### Initialize and Render ToastStack Source: https://github.com/wess/guise/blob/main/docs/tutorial.md Create a toast manager instance and render it as a child of the root component. ```rust let toasts = cx.new(|_| ToastStack::new()); // in Workbench::new root = root.child(self.toasts.clone()); // in render, on the root ``` -------------------------------- ### Create a collapsible details drawer Source: https://github.com/wess/guise/blob/main/docs/appguide.md Configures a Collapse component with a fixed height and custom easing animation. ```rust Collapse::new("details") .open(self.details_open) .height(120.0) .easing(Easing::Spring(Spring::default())) .child(details_panel()) ``` -------------------------------- ### Initialize and style icons Source: https://github.com/wess/guise/blob/main/docs/icons.md Basic usage of the Icon component to render icons with optional size and color overrides. ```rust Icon::new(IconName::Check) Icon::new(IconName::Search).size(Size::Lg).color(ColorName::Blue) ``` -------------------------------- ### Initialize global theme in Rust Source: https://github.com/wess/guise/blob/main/docs/appguide.md Applies a theme globally using either a built-in palette or a custom JSON file. ```rust Theme::tokyonight().init(cx); // or: Theme::from_json(&std::fs::read_to_string("theme.json")?)?.init(cx); ``` -------------------------------- ### Define Easing variants in Rust Source: https://github.com/wess/guise/blob/main/docs/transitions.md Demonstrates how to instantiate various Easing variants including cubic bezier and physical springs. ```rust use guise::anim::{Easing, Spring}; Easing::EaseOutBack // overshoot + settle Easing::CubicBezier(0.25, 0.1, 0.25, 1.0) // CSS "ease" Easing::Spring(Spring::wobbly()) // physical spring ``` -------------------------------- ### Transition Source: https://github.com/wess/guise/blob/main/docs/transitions.md Plays a one-shot entrance animation around its child. Requires a stable ID for animation identity. ```APIDOC ## Transition ### Description Plays a one-shot entrance animation around its child. ### Methods - **new(id)**: Creates a new transition with a stable ID. - **kind(TransitionKind)**: Sets the animation type (Fade, SlideUp, SlideDown, SlideLeft, SlideRight). Default is Fade. - **easing(Easing)**: Sets the easing function. - **duration_ms(u64)**: Sets the duration in milliseconds. Default is 200. - **child(impl IntoElement)**: Sets the child element to animate. ```