GPUI Component

repository·main·Indexed 11 days ago

https://github.com/longbridge/gpui-component

A library of over 60 cross-platform desktop UI components built for the GPUI framework. It provides high-performance components inspired by macOS, Windows, and shadcn/ui, featuring a code editor with LSP support, dock layouts, virtualized tables, and a Display Mapping System for coordinate conversion and code folding.

Tokens
200.4K
Snippets
580
Records
697
Agent score
93%

What's inside GPUI Component

  1. Overview of the DataTable component

    main

    The DataTable is a high-performance component designed to handle large datasets efficiently. It is suitable for displaying thousands of rows while maintaining smooth performance through features like virtual scrolling.

    Key capabilities include:

    • Selection Modes: Support for row, column, and individual cell selection.
    • Column Management: Columns can be resized, moved, or fixed.
    • Data Handling: Built-in support for sorting, filtering, and infinite loading (loading more data as the user scrolls).
    • Customization: Support for custom cell rendering and context menus (right-click support).
    • Navigation: Full keyboard navigation support for all selection modes.
  2. Overview of GPUI Component features

    main

    GPUI Component is a comprehensive UI library for GPUI providing 60+ cross-platform components. Key capabilities include:

    • Theming: Built-in Theme and ThemeColor support for multi-theme applications.
    • Layouts: Support for Dock layouts (panels, split views, tabs) and Tiles (freeform) layouts.
    • High Performance: Virtualized Table and List components for large datasets.
    • Content Rendering: Native support for Markdown and simple HTML.
    • Specialized Components: Built-in charts for visualization and a high-performance code editor with LSP support and Tree Sitter syntax highlighting.
    • Component Model: Stateless RenderOnce components designed for ease of use.
  3. Deep-dive GPUI Reference Topics

    main

    For advanced implementation and specialized patterns, refer to these extended documentation categories:

    Element Trait Deep-dives

    • API & Hitboxes: Complete API, hitbox system, and event handling.
    • Patterns: Text, interactive, container, and composite patterns.
    • Examples: Full implementations of text, interactive, and complex elements.
    • Best Practices: Performance optimization, state management, and common pitfalls.
    • Advanced Layouts: Masonry/circular layouts, async updates, and virtual lists.

    Entity Management Deep-dives

    • API & Lifecycle: Complete Entity API, methods, and lifecycle management.
    • Patterns: Model-view patterns, cross-entity communication, and observers.
    • Best Practices: Memory management, performance, and lifecycle handling.
    • Advanced Management: Collections, registries, debouncing, and state machines.

    Testing Deep-dives

    • Examples: Testing patterns and practical examples.
    • API Reference: Complete testing API reference.
  4. Explore GPUI Component library categories

    main

    The GPUI Component library is organized into four main categories to help you find the right UI element for your application:

    Basic Components

    Fundamental UI elements such as Button, Checkbox, Icon, Label, Progress, Switch, and Tooltip.

    Form Components

    Controls for user input, including Input, Select, Combobox, NumberInput, DatePicker, OtpInput, ColorPicker, and the Editor for multi-line or code text.

    Layout Components

    Structural elements for organizing your UI, such as Dialog (modals), Notification (toasts), Popover, Resizable panels, Sidebar, and StatusBar.

    Advanced Components

    Complex UI patterns like Chart (Line, Bar, Area, Pie, Candlestick), DataTable for high-performance data, Tabs, Tree for hierarchical data, and VirtualList for large datasets.

  5. GPUI Framework Reference Guide

    main

    The GPUI framework provides a set of primitives for building high-performance applications. Use the following topic mapping to find specific documentation for the task you are performing:

    Core Framework Concepts

    • Actions & Keybindings: Use when working with actions!, bind_keys, on_action, or key_context.
    • Async & Background Tasks: Use for cx.spawn, background_spawn, Task, or async I/O.
    • Context Management: Use for App, Window, Context<T>, or AsyncApp.
    • Custom Elements (Low-level): Use when implementing the Element trait, request_layout, prepaint, or paint.
    • Entity State Management: Use for Entity<T>, WeakEntity, and general state management.
    • Events & Subscriptions: Use for cx.emit, cx.subscribe, or cx.observe.
    • Focus & Keyboard Navigation: Use for FocusHandle, track_focus, or Tab navigation.
    • Global State: Use for the Global trait, cx.set_global, or app-wide configuration.
    • Layout & Styling: Use for div(), h_flex(), v_flex(), flexbox, overflow, and positioning.
    • Element Identification: Use for ElementId, .id(), uniqueness rules, and stateful elements.
    • Testing: Use for #[gpui::test], TestAppContext, or VisualTestContext.
  6. What is an Entity and how to use it

    main

    An Entity<T> is a handle to state of type T, providing safe access and updates through a locking mechanism. It supports both strong references (Entity<T>) and weak references (WeakEntity<T>).

    Key Methods:

    • entity.read(cx): Provides read-only access to the state.
    • entity.read_with(cx, |state, cx| ...): Provides read access via a closure.
    • entity.update(cx, |state, cx| ...): Provides mutable access to the state. Note: You must call cx.notify() inside the update closure to trigger a re-render.
    • entity.downgrade(): Creates a WeakEntity<T> which does not prevent the entity from being cleaned up.
    • entity.entity_id(): Returns a unique EntityId.
    // Create entity
    let counter = cx.new(|cx| Counter { count: 0 });
    
    // Read state
    let count = counter.read(cx).count;
    
    // Update state
    counter.update(cx, |state, cx| {
        state.count += 1;
        cx.notify(); // Trigger re-render
    });
  7. What is AlertDialog and how does it differ from Dialog

    main

    An AlertDialog is a modal dialog component designed for high-priority interruptions that require user response (e.g., confirmations or alerts). It is built on top of the Dialog component but applies opinionated defaults for alert scenarios:

    • Overlay closing: Disabled by default (enable via .overlay_closable(true)).
    • Close button: Hidden by default (enable via .close_button(true)).
    • Alignment: Footer buttons are center-aligned (unlike Dialog which uses right-alignment).
    • API: Provides a simplified API focused on alert/confirmation workflows.
  8. Configure Chart Theme Colors

    main

    Charts are designed to integrate with the application theme. You can use theme-provided chart colors to ensure visual consistency. The theme provides a series of chart color slots:

    • cx.theme().chart_1
    • cx.theme().chart_2
    • cx.theme().chart_3
    • cx.theme().chart_4
    • cx.theme().chart_5

    You can apply these to strokes, fills, or custom color logic in components like LineChart or BarChart.

    // Example: Using theme colors for a LineChart
    LineChart::new(data)
        .x(|d| d.date.clone())
        .y(|d| d.value)
        .stroke(cx.theme().chart_1);
  9. Best practices for using Dialogs

    main

    To ensure consistent UI and accessibility when using Dialogs, follow these guidelines:

    1. Use Declarative Components: Always prefer DialogHeader, DialogTitle, DialogDescription, and DialogFooter to maintain standard styling.
    2. Choose the right pattern:
      • Use the trigger pattern for simple dialogs that open from a button.
      • Use the builder pattern with window.open_dialog for complex dialogs requiring logic or state.
    3. Semantic Structure: Always include a DialogHeader with a title and description to support accessibility.
    4. Consistent Footer: Use DialogFooter for all action buttons to ensure visual consistency across your application.
    5. Proper Sizing: Explicitly set the dialog width using .w(px) or .width(px) when the content requires specific dimensions.
  10. Understand I18n lookup priority

    main

    GPUI Component uses a deep-merge lookup priority. When a component requests a translation key, the system searches in this order:

    1. Application locales (e.g., your locales/ui.yml)
    2. GPUI Component built-in locales (if not found in the application locales)

    Key behaviors:

    • Partial Overrides: You can define a single key (e.g., gpui_component.Calendar.month.January.en) to change only that specific label while keeping all other English labels from the built-in library.
    • New Languages: You can introduce a completely new language (e.g., fr) by only providing the keys you have translated; all other keys will fall back to the built-in defaults.
  11. Use VirtualList for high-performance large datasets

    main

    The VirtualList component is designed to efficiently render large datasets by only rendering items currently within the visible range. It supports both vertical and horizontal orientations and handles variable item sizes, making it suitable for complex layouts like tables or dynamic content feeds.

    To use it, you must provide a collection of item sizes (as Rc<Vec<Size<Pixels>>>) so the component can calculate scroll offsets and the visible range accurately.

    use gpui_component::{v_virtual_list, h_virtual_list, VirtualListScrollHandle};
    use std::rc::Rc;
    use gpui::{px, size, Size, Pixels};
    
    // Example setup for a vertical list
    v_virtual_list(
        cx.entity().clone(),
        "my-list",
        item_sizes.clone(),
        |view, visible_range, _, cx| {
            visible_range
                .map(|ix| {
                    div().child(format!("Item {}", ix))
                })
                .collect()
        },
    )
    .track_scroll(&self.scroll_handle)