# Fusabi TUI - Architecture
> Technical architecture and design decisions for the fusabi-tui library
**Created**: 2025-01-26
**Status**: Repository scaffold complete, implementation pending
---
## Overview
`fusabi-tui` is a Rust library that bridges [Ratatui](https://ratatui.rs/) (terminal UI framework) with [Fusabi](https://github.com/fusabi-lang/fusabi) (F# scripting runtime). It enables F# scripts to create rich, interactive terminal interfaces using a type-safe, declarative API.
## Design Goals
1. **Type Safety**: Leverage Rust's type system to prevent runtime errors
2. **Performance**: Zero-copy where possible, optimized for low latency
3. **Ergonomics**: Provide intuitive builders and APIs
4. **Modularity**: Clean separation of concerns between modules
5. **Compatibility**: Seamless integration with Fusabi VM
## Module Architecture
```
fusabi-tui/
├── src/
│ ├── lib.rs # Public API and re-exports
│ ├── widgets/ # Widget builders and wrappers
│ │ └── mod.rs
│ ├── layouts/ # Layout utilities and constraints
│ │ └── mod.rs
│ ├── canvas/ # Low-level drawing primitives
│ │ └── mod.rs
│ └── bindings/ # Fusabi VM integration
│ └── mod.rs
├── examples/ # Usage demonstrations
├── tests/ # Integration tests
└── benches/ # Performance benchmarks
```
### Module Responsibilities
#### 1. Widgets (`src/widgets/`)
**Purpose**: High-level UI component builders
**Key Types**:
- `Widget` trait - Common interface for all widgets
- `WidgetBuilder` trait - Type-safe construction pattern
**Planned Widgets**:
- List (scrollable item lists)
- Table (multi-column data grids)
- Gauge (progress indicators)
- Chart (line/bar/scatter plots)
- Paragraph (formatted text blocks)
- Block (containers with borders)
**Design Pattern**: Builder pattern for flexible configuration
```rust
pub trait Widget {
fn render(&self, area: Rect, buf: &mut Buffer);
}
pub trait WidgetBuilder {
type Output: Widget;
fn build(self) -> Result<Self::Output>;
}
```
#### 2. Layouts (`src/layouts/`)
**Purpose**: Constraint-based space division
**Key Types**:
- `Layout` - Configures how to split rectangular areas
- `Constraint` - Defines sizing rules
- `Direction` - Horizontal or vertical splitting
**Constraint Types**:
- Percentage (0-100%)
- Ratio (numerator/denominator)
- Length (fixed size)
- Min/Max (flexible with bounds)
**Design Pattern**: Fluent builder API
```rust
Layout::vertical()
.constraints(vec![
Constraint::Percentage(50),
Constraint::Min(10),
])
.margin(1)
```
#### 3. Canvas (`src/canvas/`)
**Purpose**: Low-level graphics primitives
**Key Features**:
- Shape rendering (lines, rectangles, circles)
- Coordinate mapping (world → canvas space)
- Custom paint functions
- High-resolution Braille patterns
**Use Cases**:
- Custom visualizations
- GPU topology diagrams
- Real-time graphs
- Heatmaps
#### 4. Bindings (`src/bindings/`)
**Purpose**: Fusabi VM integration layer
**Key Responsibilities**:
- Native function registration
- Type marshaling (F# ↔ Rust)
- Error handling and conversion
- Resource lifetime management
**Integration Points**:
- `FusabiTuiModule` - Main registration struct
- Native function wrappers for each widget/layout type
- Serialization/deserialization helpers
## Data Flow
### Widget Rendering Pipeline
```
F# Script → Fusabi VM → Native Functions → Widget Builders → Ratatui → Terminal
↓ ↓ ↓ ↓ ↓ ↓
.fsx file Interpret fusabi_tui fusabi_tui ratatui ANSI codes
bindings widgets render to stdout
```
### Typical Usage Flow
1. **Script Initialization**: F# script imports `Fusabi.TUI` module
2. **Widget Construction**: Script calls builder functions
3. **Native Binding**: Fusabi VM invokes Rust native functions
4. **Builder Execution**: Rust builders validate and construct widgets
5. **Layout Computation**: Constraints applied to determine widget sizes
6. **Rendering**: Ratatui draws widgets to buffer
7. **Terminal Output**: Buffer flushed to terminal via crossterm
## Type System Design
### Error Handling
All public APIs use `anyhow::Result<T>`:
```rust
pub type Result<T> = anyhow::Result<T>;
pub fn build(self) -> Result<Widget> {
// validation
Ok(widget)
}
```
### Ownership Model
- **Widgets**: Owned values, moved during construction
- **Layouts**: Cloneable configuration structs
- **Canvas**: Mutable reference for drawing operations
### Thread Safety
Currently single-threaded, but designed for future `Send + Sync` support once Fusabi VM supports concurrent native function calls.
## Performance Considerations
### Zero-Copy Where Possible
- Use `&str` instead of `String` in widget APIs
- Pass buffers by reference
- Minimize allocations in hot paths
### Optimization Targets
- Widget construction: <100 μs
- Layout computation: <50 μs
- Render to buffer: <1 ms for typical screens
### Benchmarking
Criterion-based benchmarks in `benches/`:
- Widget builder performance
- Layout constraint solving
- Canvas rendering throughput
## Testing Strategy
### Unit Tests
Embedded in module files via `#[cfg(test)]`:
- Builder validation
- Constraint computation
- Type conversions
### Integration Tests
In `tests/integration_test.rs`:
- End-to-end widget creation
- Fusabi VM integration
- Error handling paths
### Property-Based Tests
Future: QuickCheck for constraint solving
## Dependencies
### Core Dependencies
- **ratatui 0.28**: TUI framework
- **fusabi-vm 0.16**: F# scripting runtime
- **serde 1.0**: Serialization
- **anyhow 1.0**: Error handling
- **crossterm 0.28**: Terminal abstraction
### Dev Dependencies
- **tempfile 3.8**: Test isolation
- **criterion 0.5**: Benchmarking
## Extraction Plan
This library is being extracted from the [Hibana](../hibana) project. The extraction follows this plan:
### Phase 1: Scaffold (✅ Complete)
- Repository structure
- Module stubs
- Build configuration
- Documentation templates
### Phase 2: Core Implementation (🔄 In Progress)
- Extract widget types from `hibana/src/top.rs`
- Extract layout utilities
- Create Ratatui wrapper abstractions
### Phase 3: Fusabi Integration (📋 Planned)
- Implement native function bindings
- Add F# type marshaling
- Register with Fusabi VM
### Phase 4: Testing & Documentation (📋 Planned)
- Comprehensive tests
- Usage examples
- API documentation
## Future Enhancements
### v0.2.0
- Additional widget types (Sparkline, BarChart, etc.)
- Event handling integration
- Mouse support
### v0.3.0
- Custom widget trait for user extensions
- Theme/style system
- Animation support
### v0.4.0
- Async rendering pipeline
- Multi-pane management
- Layout persistence
## References
- [Ratatui Documentation](https://ratatui.rs/)
- [Fusabi GitHub](https://github.com/fusabi-lang/fusabi)
- [Hibana Project](../hibana)
- [TUI Design Patterns](https://github.com/fdehau/tui-rs/blob/master/DESIGN.md)
---
**Last Updated**: 2025-01-26
**Version**: 0.1.0