Skip to content

Latest commit

 

History

History
375 lines (285 loc) · 8.53 KB

File metadata and controls

375 lines (285 loc) · 8.53 KB

UI Native - Project Summary

Overview

UI Native is a declarative, reactive UI framework for building native macOS applications with Rust. It provides a SwiftUI-like API with chain-able methods, reactive state management, and 20+ pre-built components.

Architecture

Directory Structure

ui-native/
├── src/
│   ├── lib.rs              # Library entry point
│   ├── examples.rs         # Example usage
│   ├── core/               # Core systems
│   │   ├── mod.rs
│   │   ├── types.rs        # Core type definitions
│   │   ├── state.rs        # Reactive state management
│   │   ├── layout.rs       # Layout system (Size, Constraints)
│   │   ├── style.rs        # Style system (Color, Font, Shadow)
│   │   └── event.rs        # Event handling system
│   ├── builder/            # UI builder
│   │   ├── mod.rs
│   │   ├── builder.rs      # Core UIBuilder with chainable methods
│   │   └── rect.rs         # Rect/Box component
│   └── components/         # UI components (20+)
│       ├── mod.rs
│       ├── button.rs
│       ├── label.rs
│       ├── text_field.rs
│       ├── image.rs
│       ├── slider.rs
│       ├── progress.rs
│       ├── checkbox.rs
│       ├── radio.rs
│       ├── toggle.rs
│       ├── scroll.rs
│       ├── list.rs
│       ├── table.rs
│       ├── picker.rs
│       ├── date_picker.rs
│       ├── color_picker.rs
│       ├── stepper.rs
│       ├── segmented.rs
│       ├── toolbar.rs
│       ├── tabs.rs
│       ├── split.rs
│       ├── search.rs
│       ├── menu.rs
│       ├── alert.rs
│       └── stack.rs
├── examples/
│   ├── counter.rs          # Counter app example
│   ├── form.rs             # Form example
│   └── gallery.rs          # Gallery example
├── Cargo.toml              # Package configuration
└── README.md               # Documentation

Core Systems

1. State Management (core/state.rs)

Reactive state system with automatic updates:

pub struct State<T> {
    value: Rc<RefCell<T>>,
    listeners: Rc<RefCell<Vec<Box<dyn Fn(&T)>>>>,
}

pub fn use_state<T>(factory: F) -> State<T>

Features:

  • Reactive updates on write
  • Subscribe to changes
  • Clone-able for use in closures
  • Automatically notifies listeners

2. Layout System (core/layout.rs)

Flexible sizing and constraints:

pub enum Size {
    Fixed(f64),      // Fixed size
    Percent(f64),    // Percentage of parent
    Fill,            // Fill available space
    Auto,            // Based on content
}

3. Style System (core/style.rs)

Comprehensive styling:

pub struct Color { r, g, b, a }
pub enum FontWeight { Thin, Light, Regular, Bold, ... }
pub struct Shadow { offset, blur, spread, color }
pub struct Border { width, color }

4. Event System (core/event.rs)

Type-safe event handling:

pub trait EventHandler {
    fn handle(&mut self, sender: &AnyObject);
}

pub fn create_action_target<F>(callback: F) -> Retained<ActionTarget>

UIBuilder

The core builder provides chainable methods for any NSView-based component:

pub struct UIBuilder<T = NSView> {
    view: Retained<T>,
    children: Vec<Retained<NSView>>,
    constraints: Vec<Retained<NSLayoutConstraint>>,
}

Methods:

  • Layout: width(), height(), center(), padding(), margin()
  • Style: background(), color(), corner_radius(), shadow(), alpha()
  • Font: font_size(), font_weight()
  • Structure: child(), text_child()
  • Layout modes: horizontal(), vertical(), spacing()

Components (20+)

Basic

  1. Rect/Box - Container view
  2. Label - Text display
  3. Button - Clickable button
  4. TextField - Text input
  5. Image - Image display

Input Controls

  1. Slider - Value slider
  2. Stepper - Increment/decrement
  3. Checkbox - Toggle checkbox
  4. RadioButton - Radio selection
  5. Toggle - On/off switch
  6. Picker - Dropdown picker
  7. SegmentedControl - Multi-segment
  8. DatePicker - Date selection
  9. ColorPicker - Color selection
  10. SearchField - Search input

Containers

  1. Stack - Horizontal/vertical layout
  2. ScrollView - Scrollable container
  3. SplitView - Split panel
  4. TabView - Tabbed interface

Data Display

  1. ListView - List display
  2. TableView - Table display
  3. ProgressBar - Progress indicator

UI Elements

  1. Toolbar - Window toolbar
  2. Menu - Context menu
  3. Alert - Alert dialog

API Design Principles

1. Declarative

Build UIs by describing what you want:

rect()
    .width(Size::fill())
    .background((240, 240, 245))
    .child(label)

2. Chainable

Every method returns self for fluent API:

Button::new()
    .title("Click Me")
    .width(Size::Fixed(100.0))
    .height(Size::Fixed(44.0))
    .background((0, 122, 255))
    .corner_radius(8.0)
    .on_press(|_| {})

3. Type-Safe

Leverage Rust's type system:

UIBuilder<NSButton>  // Button-specific methods
UIBuilder<NSView>    // Generic view methods

4. Reactive

State changes automatically update UI:

let count = use_state(|| 0);
*count.write() += 1;  // Triggers UI update

5. Zero-Cost

Direct bindings to AppKit with minimal overhead:

unsafe {
    msg_send![view, setBackgroundColor: color]
}

Usage Pattern

1. Create State

let count = use_state(|| 0);

2. Build UI

let ui = rect()
    .child(label)
    .child(button);

3. Handle Events

Button::new()
    .on_press(move |_| {
        *count.write() += 1;
    })

4. Build and Display

let view = ui.build();
window.setContentView(Some(&view));

Technical Details

Dependencies

  • objc2: Safe Objective-C bindings
  • objc2-foundation: Foundation framework types
  • objc2-app-kit: AppKit UI components

Memory Management

  • Uses Retained<T> for automatic reference counting
  • Safe ownership with Rust's type system
  • Proper cleanup on drop

Performance

  • Zero-cost abstractions over AppKit
  • Direct native calls
  • Minimal allocations
  • Efficient state updates

Safety

  • Type-safe wrappers around unsafe code
  • Compile-time guarantees
  • Proper lifetime management
  • Safe event handling

Future Enhancements

Planned Features

  1. Animations - Smooth transitions and animations
  2. Gestures - Pan, pinch, rotate recognizers
  3. Accessibility - Full a11y support
  4. Custom Drawing - Canvas API for custom graphics
  5. Layout Algorithms - Advanced layout systems
  6. Performance - Optimize rendering and updates
  7. Testing - Comprehensive test suite
  8. Documentation - API docs and tutorials

API Improvements

  1. Better state binding to UI elements
  2. Diffing algorithm for efficient updates
  3. Virtual DOM for complex UIs
  4. Theme system for consistent styling
  5. Animation DSL
  6. Custom components macro

Development Guidelines

Code Quality

  1. Follow Rust API guidelines
  2. Comprehensive documentation
  3. Unit tests for core functionality
  4. Integration tests for components
  5. Example apps for common patterns

Performance

  1. Profile and optimize hot paths
  2. Minimize allocations
  3. Efficient state propagation
  4. Lazy evaluation where possible

Safety

  1. Minimize unsafe code
  2. Document all unsafe blocks
  3. Maintain invariants
  4. Proper error handling

Comparison with Other Frameworks

vs Native AppKit/Objective-C

Advantages:

  • Type safety
  • Memory safety
  • Modern API design
  • Reactive state

Trade-offs:

  • Learning curve
  • Some boilerplate

vs SwiftUI

Advantages:

  • Rust ecosystem integration
  • More explicit control
  • No Xcode required

Trade-offs:

  • Manually managed updates
  • Less mature tooling

vs Electron/Tauri

Advantages:

  • True native performance
  • Small binary size
  • No web tech overhead

Trade-offs:

  • macOS only
  • More complex API

Conclusion

UI Native provides a modern, safe, and efficient way to build native macOS applications with Rust. It combines the best of declarative UI frameworks with the performance and safety of Rust, while maintaining direct access to native AppKit capabilities.

The framework is designed for production use with professional code standards, comprehensive documentation, and a focus on developer experience.