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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
//! # State Management
//!
//! Freya provides several options for managing state in your applications.
//!
//! ### Available APIs
//! - Local state ([`use_state`](crate::prelude::use_state)): State of components that is not trivial to be shared with the whole app, example: hovering a button.
//! - [freya_radio]: App-level state with nested data and fine gradined updates, example: You have a system of tabs where each tab has an independent yet global state.
//! - `Readable`/`Writable`: When you want to receive some kind of reactive state without knowing its specific backing storage, example: a reusable component.
//!
//! ## Local State
//!
//! Local state is managed with the [`use_state`](crate::prelude::use_state) hook.
//!
//! ```rust,no_run
//! # use freya::prelude::*;
//! #[derive(PartialEq)]
//! struct Counter;
//!
//! impl Component for Counter {
//! fn render(&self) -> impl IntoElement {
//! let mut count = use_state(|| 0);
//!
//! rect().child(format!("Count: {}", *count.read())).child(
//! Button::new()
//! .on_press(move |_| *count.write() += 1)
//! .child("+"),
//! )
//! }
//! }
//! ```
//!
//! You can pass it to descendant components too:
//!
//! ```rust,no_run
//! # use freya::prelude::*;
//! #[derive(PartialEq)]
//! struct Counter;
//!
//! impl Component for Counter {
//! fn render(&self) -> impl IntoElement {
//! let mut count = use_state(|| 0);
//!
//! rect().child(AnotherCounter(count)).child(
//! Button::new()
//! .on_press(move |_| *count.write() += 1)
//! .child("+"),
//! )
//! }
//! }
//!
//! #[derive(PartialEq)]
//! struct AnotherCounter(State<i32>);
//! impl Component for AnotherCounter {
//! fn render(&self) -> impl IntoElement {
//! self.0.read().to_string()
//! }
//! }
//! ```
//!
//! ## Global State with Freya Radio 🧬
//!
//! For complex applications that need to share state across multiple components,
//! Freya Radio provides a powerful global state management system with fine-grained reactivity.
//!
//! ### Key Concepts
//!
//! - **RadioStation**: The central hub that holds the global state and manages subscriptions.
//! - **RadioChannel**: Defines channels for subscribing to specific types of state changes.
//! - **Radio**: A reactive handle to the state for a specific channel.
//!
//! ### Basic Usage
//!
//! First, define your state type and channels:
//!
//! ```rust,no_run
//! # use freya::prelude::*;
//! # use freya::radio::*;
//! #[derive(Default, Clone)]
//! struct AppState {
//! count: i32,
//! }
//!
//! #[derive(PartialEq, Eq, Clone, Debug, Copy, Hash)]
//! enum AppChannel {
//! Count,
//! }
//!
//! impl RadioChannel<AppState> for AppChannel {}
//! ```
//!
//! Then, initialize the radio station and use it in components:
//!
//! ```rust,no_run
//! # use freya::prelude::*;
//! # use freya::radio::*;
//! # #[derive(Default, Clone)]
//! # struct AppState { count: i32 }
//! #
//! # #[derive(PartialEq, Eq, Clone, Debug, Copy, Hash)]
//! # enum AppChannel { Count }
//! #
//! # impl RadioChannel<AppState> for AppChannel {}
//! fn app() -> impl IntoElement {
//! // Initialize the radio station
//! use_init_radio_station::<AppState, AppChannel>(AppState::default);
//!
//! rect().child(Counter {})
//! }
//!
//! #[derive(PartialEq)]
//! struct Counter {}
//!
//! impl Component for Counter {
//! fn render(&self) -> impl IntoElement {
//! // Subscribe to the Count channel
//! let mut radio = use_radio(AppChannel::Count);
//!
//! rect()
//! .child(format!("Count: {}", radio.read().count))
//! .child(
//! Button::new()
//! .on_press(move |_| radio.write().count += 1)
//! .child("+"),
//! )
//! }
//! }
//! ```
//!
//! ### Multiple Channels
//!
//! You can use multiple channels for different types of updates:
//!
//! ```rust,no_run
//! # use freya::prelude::*;
//! # use freya::radio::*;
//! #[derive(Default, Clone)]
//! struct TodoState {
//! todos: Vec<String>,
//! filter: Filter,
//! }
//!
//! #[derive(Clone, Default)]
//! enum Filter {
//! #[default]
//! All,
//! Completed,
//! Pending,
//! }
//!
//! #[derive(PartialEq, Eq, Clone, Debug, Copy, Hash)]
//! enum TodoChannel {
//! AddTodo,
//! ToggleTodo(usize),
//! ChangeFilter,
//! }
//!
//! impl RadioChannel<TodoState> for TodoChannel {
//! fn derive_channel(self, _state: &TodoState) -> Vec<Self> {
//! match self {
//! TodoChannel::AddTodo | TodoChannel::ToggleTodo(_) => {
//! vec![self, TodoChannel::ChangeFilter] // Also notify filter subscribers
//! }
//! TodoChannel::ChangeFilter => vec![self],
//! }
//! }
//! }
//!
//! fn app() -> impl IntoElement {
//! use_init_radio_station::<TodoState, TodoChannel>(TodoState::default);
//!
//! rect().child(TodoList {}).child(FilterSelector {})
//! }
//!
//! #[derive(PartialEq)]
//! struct TodoList {}
//!
//! impl Component for TodoList {
//! fn render(&self) -> impl IntoElement {
//! let todos = use_radio(TodoChannel::AddTodo);
//!
//! rect().child(format!("Todos: {}", todos.read().todos.len()))
//! }
//! }
//!
//! #[derive(PartialEq)]
//! struct FilterSelector {}
//!
//! impl Component for FilterSelector {
//! fn render(&self) -> impl IntoElement {
//! let mut radio = use_radio(TodoChannel::ChangeFilter);
//!
//! rect()
//! .child(
//! Button::new()
//! .on_press(move |_| radio.write().filter = Filter::All)
//! .child("All"),
//! )
//! .child(
//! Button::new()
//! .on_press(move |_| radio.write().filter = Filter::Completed)
//! .child("Completed"),
//! )
//! }
//! }
//! ```
//!
//! ### Multi-Window Applications
//!
//! For applications with multiple windows, use a global radio station:
//!
//! ```rust,no_run
//! # use freya::prelude::*;
//! # use freya::radio::*;
//! #[derive(Default, Clone)]
//! struct AppState {
//! count: i32,
//! }
//!
//! #[derive(PartialEq, Eq, Clone, Debug, Copy, Hash)]
//! enum AppChannel {
//! Count,
//! }
//!
//! impl RadioChannel<AppState> for AppChannel {}
//!
//! fn main() {
//! let radio_station = RadioStation::create_global(AppState::default());
//!
//! launch(
//! LaunchConfig::new()
//! .with_window(WindowConfig::new_app(Window1 { radio_station }))
//! .with_window(WindowConfig::new_app(Window2 { radio_station })),
//! );
//! }
//!
//! struct Window1 {
//! radio_station: RadioStation<AppState, AppChannel>,
//! }
//!
//! impl App for Window1 {
//! fn render(&self) -> impl IntoElement {
//! use_share_radio(move || self.radio_station);
//! let mut radio = use_radio(AppChannel::Count);
//!
//! rect()
//! .child(format!("Window 1: {}", radio.read().count))
//! .child(
//! Button::new()
//! .on_press(move |_| radio.write().count += 1)
//! .child("+"),
//! )
//! }
//! }
//!
//! struct Window2 {
//! radio_station: RadioStation<AppState, AppChannel>,
//! }
//!
//! impl App for Window2 {
//! fn render(&self) -> impl IntoElement {
//! use_share_radio(move || self.radio_station);
//! let radio = use_radio(AppChannel::Count);
//!
//! rect().child(format!("Window 2: {}", radio.read().count))
//! }
//! }
//! ```
//!
//! ### Reducers
//!
//! For complex state updates, implement the reducer pattern:
//!
//! ```rust,no_run
//! # use freya::prelude::*;
//! # use freya::radio::*;
//! #[derive(Clone)]
//! struct CounterState {
//! count: i32,
//! }
//!
//! #[derive(Clone)]
//! enum CounterAction {
//! Increment,
//! Decrement,
//! Set(i32),
//! }
//!
//! #[derive(PartialEq, Eq, Clone, Debug, Copy, Hash)]
//! enum CounterChannel {
//! Count,
//! }
//!
//! impl RadioChannel<CounterState> for CounterChannel {}
//!
//! impl DataReducer for CounterState {
//! type Channel = CounterChannel;
//! type Action = CounterAction;
//!
//! fn reduce(&mut self, action: CounterAction) -> ChannelSelection<CounterChannel> {
//! match action {
//! CounterAction::Increment => self.count += 1,
//! CounterAction::Decrement => self.count -= 1,
//! CounterAction::Set(value) => self.count = value,
//! }
//! ChannelSelection::Current
//! }
//! }
//!
//! #[derive(PartialEq)]
//! struct CounterComponent {}
//!
//! impl Component for CounterComponent {
//! fn render(&self) -> impl IntoElement {
//! let mut radio = use_radio(CounterChannel::Count);
//!
//! rect()
//! .child(
//! Button::new()
//! .on_press(move |_| {
//! radio.apply(CounterAction::Increment);
//! })
//! .child("+"),
//! )
//! .child(format!("{}", radio.read().count))
//! .child(
//! Button::new()
//! .on_press(move |_| {
//! radio.apply(CounterAction::Decrement);
//! })
//! .child("-"),
//! )
//! }
//! }
//! ```
//!
//! ## Readable and Writable interfaces
//!
//! Freya provides [`Readable<T>`](crate::prelude::Readable) and [`Writable<T>`](crate::prelude::Writable)
//! as type-erased abstractions over different state sources. These allow components to accept state
//! without knowing whether it comes from local state (`use_state`) or global state (Freya Radio).
//!
//! ### Writable
//!
//! [`Writable<T>`](crate::prelude::Writable) is for state that can be both read and written to.
//! Components like [`Input`](crate::components::Input) accept `Writable` values, allowing you to
//! pass any state source that can be converted to a `Writable`.
//!
//! Sources that can be converted to `Writable`:
//! - [`State<T>`](crate::prelude::State) from `use_state` via [`IntoWritable`](crate::prelude::IntoWritable)
//! - [`RadioSliceMut`](freya_radio::prelude::RadioSliceMut) from Freya Radio via [`IntoWritable`](crate::prelude::IntoWritable)
//!
//! ```rust,no_run
//! # use freya::prelude::*;
//! # use freya_radio::prelude::*;
//! # #[derive(Default, Clone)]
//! # struct AppState { name: String }
//! #
//! # #[derive(PartialEq, Eq, Clone, Debug, Copy, Hash)]
//! # enum AppChannel { Name }
//! #
//! # impl RadioChannel<AppState> for AppChannel {}
//! #[derive(PartialEq)]
//! struct NameInput {
//! name: Writable<String>,
//! }
//!
//! impl Component for NameInput {
//! fn render(&self) -> impl IntoElement {
//! // Can read and write to the state
//! Input::new(self.name.clone())
//! }
//! }
//!
//! fn app() -> impl IntoElement {
//! use_init_radio_station::<AppState, AppChannel>(AppState::default);
//!
//! let local_name = use_state(|| "Alice".to_string());
//! let radio = use_radio(AppChannel::Name);
//! let name_slice = radio.slice_mut_current(|s| &mut s.name);
//!
//! rect()
//! // Pass local state as Writable
//! .child(NameInput {
//! name: local_name.into_writable(),
//! })
//! // Pass radio slice as Writable
//! .child(NameInput {
//! name: name_slice.into_writable(),
//! })
//! }
//! ```
//!
//! ### Readable
//!
//! [`Readable<T>`](crate::prelude::Readable) is for read-only state. It's the same concept as
//! `Writable` but only exposes read operations. This is useful when a component only needs to
//! display data without modifying it.
//!
//! Sources that can be converted to `Readable`:
//! - [`State<T>`](crate::prelude::State) from `use_state` via [`IntoReadable`](crate::prelude::IntoReadable)
//! - [`RadioSlice`](freya_radio::prelude::RadioSlice) from Freya Radio via [`IntoReadable`](crate::prelude::IntoReadable)
//! - [`Writable<T>`](crate::prelude::Writable) via [`From<Writable<T>>`](crate::prelude::Readable)
//!
//! ```rust,no_run
//! # use freya::prelude::*;
//! # use freya_radio::prelude::*;
//! # #[derive(Default, Clone)]
//! # struct AppState { count: i32 }
//! #
//! # #[derive(PartialEq, Eq, Clone, Debug, Copy, Hash)]
//! # enum AppChannel { Count }
//! #
//! # impl RadioChannel<AppState> for AppChannel {}
//! #[derive(PartialEq)]
//! struct Counter {
//! count: Readable<i32>,
//! }
//!
//! impl Component for Counter {
//! fn render(&self) -> impl IntoElement {
//! // Can only read the value
//! format!("Count: {}", self.count.read())
//! }
//! }
//!
//! fn app() -> impl IntoElement {
//! use_init_radio_station::<AppState, AppChannel>(AppState::default);
//!
//! let local_count = use_state(|| 0);
//! let radio = use_radio(AppChannel::Count);
//! let count_slice = radio.slice_current(|s| &s.count);
//!
//! rect()
//! // Pass local state as Readable
//! .child(Counter {
//! count: local_count.into_readable(),
//! })
//! // Pass radio slice as Readable
//! .child(Counter {
//! count: count_slice.into_readable(),
//! })
//! }
//! ```
//!
//! ## Choosing Between Local and Global State
//!
//! - **Use local state** (`use_state`) for:
//! - Component-specific data
//! - Simple state that doesn't need precise updates
//!
//! - **Use Freya Radio** for:
//! - Application-wide state
//! - Complex state logic with multiple subscribers
//! - Apps that require precise updates for max performance
//! - Multi-window applications
//!
//! ## Examples
//!
//! Check out these examples in the repository:
//!
//! - [`state_radio.rs`](https://github.com/marc2332/freya/tree/main/examples/state_radio.rs) - Basic radio usage
//! - [`feature_tray_radio_state.rs`](https://github.com/marc2332/freya/tree/main/examples/feature_tray_radio_state.rs) - Tray integration
//! - [`feature_multi_window_radio_state.rs`](https://github.com/marc2332/freya/tree/main/examples/feature_multi_window_radio_state.rs) - Multi-window state sharing