waterui-core 0.3.2

Core functionality for the WaterUI framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
# waterui-core

The foundational crate providing essential building blocks for the WaterUI cross-platform reactive UI framework.

## Overview

`waterui-core` establishes the architectural foundation for WaterUI applications, enabling declarative, reactive user interfaces that render to native platform widgets. This crate provides the core abstractions used throughout the framework: the `View` trait for composable UI components, the `Environment` for type-safe context propagation, reactive primitives powered by the `nami` library, and type erasure utilities for dynamic composition.

Unlike traditional immediate-mode or retained-mode frameworks, WaterUI uses a reactive composition model where views automatically update when reactive state changes, and the entire view tree is transformed into native platform widgets (UIKit/AppKit on Apple platforms, Android View on Android) rather than custom rendering.

This crate is `no_std` compatible (with allocation) and works consistently across desktop, mobile, web, and embedded environments.

## Installation

Add to your `Cargo.toml`:

```toml
[dependencies]
waterui-core = "0.1.0"
```

For most applications, use the main `waterui` crate which re-exports all core functionality along with component libraries.

## Quick Start

```rust,ignore
use waterui::prelude::*;

// Define a custom view
fn counter(count: &Binding<i32>) -> impl View {
    let count = count.clone();
    text!("Count: {count}")
}

// Create an application environment
fn init() -> Environment {
    Environment::new()
}

// Define the root view
fn main() -> impl View {
    let count = binding(0);
    counter(&count)
}
```

## Core Concepts

### The View Trait

The `View` trait is the foundation of all UI components in WaterUI. It defines a single method that transforms the view into its rendered representation:

```rust
pub trait View: 'static {
    fn body(self, env: &Environment) -> impl View;
}
```

Views compose recursively - a view's `body` method returns another view, allowing complex UIs to be built from simple primitives. The framework handles the recursion, eventually reaching "raw views" (like `Text`, `Button`) that map directly to native widgets.

Implementing `View` for custom types:

```rust
use waterui_core::{View, Environment};

struct Greeting {
    name: String,
}

impl View for Greeting {
    fn body(self, _env: &Environment) -> impl View {
        format!("Hello, {}!", self.name)
    }
}
```

Many standard types implement `View` automatically:
- `&'static str`, `String`, `Cow<'static, str>` - render as text
- `()` - empty view
- `Option<V>` - renders `Some(view)` or nothing
- `Result<V, E>` - renders either the success or error view
- Closures `Fn() -> impl View` - lazy view construction

### Environment

The `Environment` is a type-indexed store that propagates context through the view hierarchy without explicit parameter passing:

```rust
use waterui_core::Environment;

#[derive(Clone)]
struct AppConfig {
    api_url: String,
}

let env = Environment::new()
    .with(AppConfig {
        api_url: "https://waterui.dev".to_string(),
    });

// Later, in a view:
use waterui_core::env::use_env;
use waterui_core::extract::Use;

let config_view = use_env(|Use(config): Use<AppConfig>| {
    format!("API: {}", config.api_url)
});
```

The environment supports:
- **Typed storage**: Insert values of any `'static` type
- **Plugin installation**: Modular extensions via the `Plugin` trait
- **View hooks**: Intercept and modify view configurations globally
- **Cloning**: Cheap cloning via `Rc` for child environments

### AnyView - Type Erasure

`AnyView` enables storing different view types in homogeneous collections:

```rust
use waterui_core::AnyView;

let views = [
    AnyView::new("Hello"),
    AnyView::new(42.to_string()),
    AnyView::new(()),
];
```

Type erasure is essential for dynamic UIs where the concrete view type isn't known at compile time. `AnyView` automatically unwraps nested erasure to avoid performance overhead.

### Reactive Primitives

WaterUI integrates the `nami` reactive system for fine-grained updates:

```rust,ignore
use waterui::prelude::*;

// Create reactive state
let count: Binding<i32> = binding(0);

// Signal-aware inputs update the exact text leaf.
let counter_view = text!("Count: {count}");

// Updating the binding automatically updates the view
count.set(5);
```

Key reactive types (re-exported from `nami`):
- `Binding<T>` - Mutable reactive state
- `Computed<T>` - Derived reactive values
- `Signal<T>` - Read-only reactive values
- `SignalExt` - Extension methods for all reactive types

Signal-aware component inputs bridge reactive state to the view system without rebuilding view structure. `Dynamic::watch` is reserved for genuine semantic structure changes: it replaces the watched subtree and therefore discards state owned inside that subtree.

### Native Views

Native views are leaf components that map directly to platform widgets. The `NativeView` trait marks types that should be handled by the platform backend:

```rust
use waterui_core::{NativeView, layout::StretchAxis};

struct CustomWidget;

impl NativeView for CustomWidget {
    fn stretch_axis(&self) -> StretchAxis {
        StretchAxis::Horizontal
    }
}
```

The `raw_view!` macro simplifies creating native views:

```rust
raw_view!(Spacer, StretchAxis::MainAxis);
raw_view!(Color, StretchAxis::Both);
```

## Examples

### Custom Component with State

```rust,ignore
use waterui::prelude::*;

struct Toggle {
    label: String,
    is_on: Binding<bool>,
}

impl Toggle {
    fn new(label: impl Into<String>) -> (Binding<bool>, Self) {
        let is_on = binding(false);
        (is_on.clone(), Self {
            label: label.into(),
            is_on,
        })
    }
}

impl View for Toggle {
    fn body(self, _env: &Environment) -> impl View {
        let status = self
            .is_on
            .map(|value| if value { "ON" } else { "OFF" })
            .computed();
        hstack((text(self.label), text!(": {status}")))
    }
}
```

### Environment-based Configuration

```rust
use waterui_core::{View, Environment, env::use_env, extract::Use};

#[derive(Clone, Debug)]
struct Theme {
    primary_color: String,
}

fn themed_view() -> impl View {
    use_env(|Use(theme): Use<Theme>| {
        format!("Using theme color: {}", theme.primary_color)
    })
}

fn init() -> Environment {
    Environment::new().with(Theme {
        primary_color: "#007AFF".to_string(),
    })
}
```

### Reactive Computed Values

```rust,ignore
use waterui::prelude::*;

let count = binding(0);
let doubled: Computed<i32> = count.map(|n| n * 2);

let view = text!("Doubled: {doubled}");
```

### Explicit Structural Replacement

Use `Dynamic::watch` only when a signal selects a different semantic subtree,
not for changing text, color, size, enabled state, or collection membership:

```rust,ignore
use waterui::prelude::*;

let details_visible = binding(false);
let details = Dynamic::watch(details_visible, |visible| {
    if visible {
        AnyView::new(details_panel())
    } else {
        AnyView::new(summary_panel())
    }
});
```

### Plugin System

```rust
use waterui_core::{plugin::Plugin, Environment};

struct AnalyticsPlugin {
    app_id: String,
}

impl Plugin for AnalyticsPlugin {
    fn install(self, env: &mut Environment) {
        env.insert(self);
    }
}

let mut env = Environment::new();
AnalyticsPlugin {
    app_id: "my-app".to_string(),
}.install(&mut env);
```

## API Overview

### Core Traits
- `View` - The fundamental UI component trait
- `IntoView` - Convert types into views
- `TupleViews` - Convert tuples of views into collections
- `ConfigurableView` - Views with configuration objects
- `ViewConfiguration` - Configuration types for configurable views

### Type Erasure
- `AnyView` - Type-erased view container
- `Native<T>` - Wrapper for platform-native components
- `NativeView` - Trait for native platform widgets

### Reactive Components
- `Dynamic` - Runtime-updatable view component
- `DynamicHandler` - Handle for updating dynamic views
- `watch()` - Helper to create reactive views

### Environment & Context
- `Environment` - Type-indexed dependency injection store
- `UseEnv` - View that accesses environment values
- `use_env()` - Helper to create environment-aware views
- `With<V, T>` - Wrap a view with additional environment value

### Metadata & Hooks
- `Metadata<T>` - Attach metadata to views (must be handled by renderer)
- `IgnorableMetadata<T>` - Optional metadata (can be ignored by renderer)
- `Retain` - Keep values alive for view lifetime
- `Hook<C>` - Intercept and modify view configurations

### Layout Primitives
- `Rect`, `Size`, `Point` - Geometry types (logical pixels)
- `ProposalSize` - Size proposals for layout negotiation
- `StretchAxis` - Specify which axis a view expands on
- `Layout` - Trait for custom layout algorithms
- `SubView` - Proxy for querying child view sizes

### Event Handling
- `Event` - Enumeration of UI events (`Appear`, `Disappear`)
- `OnEvent` - Event handler component
- `Handler<T>`, `HandlerOnce<T>` - Handler traits for environment-based callbacks
- `ActionObject` - Type alias for action handlers

### View Collections
- `Views` - Trait for collections with stable identities
- `AnyViews<V>` - Type-erased view collection
- `ForEach<C, F, V>` - Transform data collections into views
- `ViewsExt` - Extension methods for view collections

### Animation
- `Animation` - Declarative animation specifications
- `AnimationExt` - Extension trait for reactive values
- `.animated()` - Apply the system-default animation
- `.with(animation)` - Apply a specific animation (from `SignalExt`)

## Features

### Default Features
- **None** - The crate has no default features for maximum flexibility

### Optional Features
- `std` - Enable standard library support (currently no-op, reserved for future use)
- `nightly` - Enable nightly-only features (e.g., `!` never type)
- `serde` - Enable Serde serialization support for core types

## Architecture Notes

### Layout System

WaterUI uses **logical pixels** (points) for all layout values, matching design tools like Figma:
- 1 logical pixel = 1 point in design tools
- Backends handle conversion to physical pixels based on screen density
- Consistent physical size across platforms and densities

Layout is a two-phase process:
1. **Sizing**: Determine container size given a proposal from parent
2. **Placement**: Position children within the final bounds

The `Layout` trait defines custom layout algorithms. The `StretchAxis` enum specifies which axes views expand on:
- `None` - Content-sized
- `Horizontal` / `Vertical` - Expand on one axis
- `Both` - Greedy, fills all space
- `MainAxis` / `CrossAxis` - Relative to container direction

### View Rendering Pipeline

```
Custom View → body() → ... → body() → Raw View → Native Backend → Platform Widget
```

1. Custom views define `body()` that returns other views
2. Framework recursively calls `body()` until reaching raw views
3. Raw views (marked with `NativeView`) are handled by the platform backend
4. Backend translates to native widgets (SwiftUI views, Compose composables, etc.)

### Handler System

The handler system supports automatic parameter extraction from environments:

```rust
use waterui_core::{handler::into_handler, extract::Use};

struct Config { value: i32 }

let handler = into_handler(|Use(config): Use<Config>| {
    println!("Config value: {}", config.value);
});
```

Handlers come in three flavors:
- `Handler<T>` - Reusable, takes `&mut self`
- `HandlerOnce<T>` - Single-use, consumes `self`
- `HandlerFn<P, T>` - Function-like trait with parameter extraction

## License

MIT