freya_radio/hooks/use_radio.rs
1use std::{
2 cell::RefCell,
3 collections::HashMap,
4 hash::Hash,
5 ops::{
6 Deref,
7 DerefMut,
8 },
9 rc::Rc,
10};
11
12use freya_core::{
13 integration::FxHashSet,
14 prelude::*,
15};
16
17/// Defines notification channels for shared state.
18///
19/// Each update selects one source channel. Use [`Self::derive_channel`] to keep
20/// relationships between notified channels in one place.
21#[cfg(feature = "tracing")]
22pub trait RadioChannel<T>: 'static + PartialEq + Eq + Clone + Hash + std::fmt::Debug + Ord {
23 /// Return the channels to notify for this source channel.
24 ///
25 /// Defaults to only `self`. Returned channels are not recursively expanded.
26 fn derive_channel(self, _radio: &T) -> Vec<Self> {
27 vec![self]
28 }
29}
30
31/// Defines a channel for radio communication.
32/// Channels are used to subscribe to specific changes in the global state.
33/// Each channel must implement this trait to be used with [`RadioStation`] and [`Radio`].
34///
35/// Channels allow fine-grained control over which components re-render when the state changes.
36/// Components only re-render when a channel they are subscribed to is notified.
37///
38/// # Example
39///
40/// ```rust, no_run
41/// # use freya::radio::*;
42/// # struct Data;
43/// #[derive(PartialEq, Eq, Clone, Debug, Copy, Hash)]
44/// pub enum DataChannel {
45/// ListCreation,
46/// SpecificListItemUpdate(usize),
47/// }
48///
49/// impl RadioChannel<Data> for DataChannel {}
50/// ```
51#[cfg(not(feature = "tracing"))]
52pub trait RadioChannel<T>: 'static + PartialEq + Eq + Clone + Hash {
53 /// Derive additional channels based on the current state value.
54 /// This allows a single write operation to notify multiple channels.
55 ///
56 /// By default, returns a vector containing only `self`.
57 ///
58 /// Declaring related channels here is a best practice enforced by design.
59 /// Making every write list them by hand is verbose and easy to get wrong.
60 /// # Example
61 ///
62 /// ```rust, no_run
63 /// # use freya::radio::*;
64 /// # struct Data { items: Vec<u32> }
65 /// #[derive(PartialEq, Eq, Clone, Debug, Copy, Hash)]
66 /// pub enum DataChannel {
67 /// All,
68 /// Specific(usize),
69 /// }
70 ///
71 /// impl RadioChannel<Data> for DataChannel {
72 /// fn derive_channel(self, data: &Data) -> Vec<Self> {
73 /// match self {
74 /// DataChannel::All => {
75 /// let mut channels = vec![DataChannel::All];
76 /// channels.extend((0..data.items.len()).map(DataChannel::Specific));
77 /// channels
78 /// }
79 /// DataChannel::Specific(_) => vec![self],
80 /// }
81 /// }
82 /// }
83 /// ```
84 fn derive_channel(self, _radio: &T) -> Vec<Self> {
85 vec![self]
86 }
87}
88
89/// The central hub for global state management in Freya applications.
90/// A `RadioStation` holds the global state value and manages subscriptions to different channels.
91/// Components can subscribe to specific channels to receive notifications when the state changes.
92///
93/// Share a station between windows with `WindowConfig::with_root_context`.
94///
95/// # Examples
96///
97/// ## Basic usage
98///
99/// ```rust, no_run
100/// # use freya::prelude::*;
101/// # use freya::radio::*;
102/// #[derive(Default)]
103/// struct AppState {
104/// count: i32,
105/// }
106///
107/// #[derive(PartialEq, Eq, Clone, Debug, Copy, Hash)]
108/// enum AppChannel {
109/// Count,
110/// }
111///
112/// impl RadioChannel<AppState> for AppChannel {}
113///
114/// fn app() -> impl IntoElement {
115/// // Create a radio station (scoped to this component tree)
116/// use_init_radio_station::<AppState, AppChannel>(AppState::default);
117///
118/// let mut radio = use_radio(AppChannel::Count);
119///
120/// rect()
121/// .child(label().text(format!("Count: {}", radio.read().count)))
122/// .child(
123/// Button::new()
124/// .on_press(move |_| radio.write().count += 1)
125/// .child("Increment"),
126/// )
127/// }
128/// ```
129///
130/// ## Global radio station for multi-window apps
131///
132/// ```rust, ignore
133/// # use freya::prelude::*;
134/// # use freya::radio::*;
135///
136/// let radio_station = RadioStation::create_global(AppState::default);
137///
138/// launch(
139/// LaunchConfig::new()
140/// .with_window(WindowConfig::new(window1).with_root_context(radio_station))
141/// .with_window(WindowConfig::new(window2).with_root_context(radio_station)),
142/// );
143/// ```
144pub struct RadioStation<Value, Channel>
145where
146 Channel: RadioChannel<Value>,
147 Value: 'static,
148{
149 pub(crate) value: State<Value>,
150 listeners: State<HashMap<Channel, Rc<RefCell<FxHashSet<ReactiveContext>>>>>,
151}
152
153impl<Value, Channel> Clone for RadioStation<Value, Channel>
154where
155 Channel: RadioChannel<Value>,
156{
157 fn clone(&self) -> Self {
158 *self
159 }
160}
161
162impl<Value, Channel> Copy for RadioStation<Value, Channel> where Channel: RadioChannel<Value> {}
163
164impl<Value, Channel> RadioStation<Value, Channel>
165where
166 Channel: RadioChannel<Value>,
167{
168 pub fn create(init_value: Value) -> Self {
169 RadioStation {
170 value: State::create(init_value),
171 listeners: State::create(HashMap::default()),
172 }
173 }
174
175 /// Create a global `RadioStation` that lives for the entire application lifetime.
176 /// This is useful for sharing state across multiple windows.
177 ///
178 /// This is **not** a hook, do not use it inside components like you would [`use_radio`].
179 /// You would usually want to call this in your `main` function, not anywhere else.
180 ///
181 /// # Example
182 ///
183 /// ```rust, ignore
184 /// # use freya::prelude::*;
185 /// # use freya::radio::*;
186 /// let radio_station = RadioStation::create_global(AppState::default);
187 ///
188 /// launch(
189 /// LaunchConfig::new()
190 /// .with_window(WindowConfig::new(window1).with_root_context(radio_station))
191 /// .with_window(WindowConfig::new(window2).with_root_context(radio_station)),
192 /// );
193 /// ```
194 pub fn create_global(init_value: Value) -> Self {
195 RadioStation {
196 value: State::create_global(init_value),
197 listeners: State::create_global(HashMap::default()),
198 }
199 }
200
201 pub(crate) fn is_listening(
202 &self,
203 channel: &Channel,
204 reactive_context: &ReactiveContext,
205 ) -> bool {
206 let listeners = self.listeners.peek();
207 listeners
208 .get(channel)
209 .map(|contexts| contexts.borrow().contains(reactive_context))
210 .unwrap_or_default()
211 }
212
213 pub(crate) fn listen(&self, channel: Channel, mut reactive_context: ReactiveContext) {
214 let mut listeners = self.listeners.write_unchecked();
215 let listeners = listeners.entry(channel).or_default();
216 reactive_context.subscribe(listeners);
217 }
218
219 pub(crate) fn notify_listeners(&self, channel: &Channel) {
220 let listeners = self.listeners.write_unchecked();
221
222 #[cfg(feature = "tracing")]
223 tracing::info!("Notifying {channel:?}");
224
225 for (listener_channel, listeners) in listeners.iter() {
226 if listener_channel == channel {
227 for reactive_context in listeners.borrow().iter() {
228 reactive_context.notify();
229 }
230 }
231 }
232 }
233
234 /// Read the current state value and subscribe to all channel changes.
235 /// Any component calling this will re-render when any channel is notified.
236 ///
237 /// # Example
238 ///
239 /// ```rust, ignore
240 /// # use freya::radio::*;
241 /// let value = radio_station.read();
242 /// ```
243 #[track_caller]
244 pub fn read(&'_ self) -> ReadRef<'_, Value> {
245 self.value.read()
246 }
247
248 #[track_caller]
249 pub fn peek_unchecked(&self) -> ReadRef<'static, Value> {
250 self.value.peek_unchecked()
251 }
252
253 /// Read the current state value without subscribing to changes.
254 /// Components using this will not re-render when the state changes.
255 ///
256 /// # Example
257 ///
258 /// ```rust, ignore
259 /// # use freya::radio::*;
260 /// let value = radio_station.peek();
261 /// ```
262 #[track_caller]
263 pub fn peek(&'_ self) -> ReadRef<'_, Value> {
264 self.value.peek_unchecked()
265 }
266
267 pub(crate) fn cleanup(&self) {
268 let mut listeners = self.listeners.write_unchecked();
269
270 // Clean up those channels with no reactive contexts
271 listeners.retain(|_, listeners| !listeners.borrow().is_empty());
272
273 #[cfg(feature = "tracing")]
274 {
275 use itertools::Itertools;
276 use tracing::{
277 Level,
278 info,
279 span,
280 };
281
282 let mut channels_subscribers = HashMap::<&Channel, usize>::new();
283
284 for (channel, listeners) in listeners.iter() {
285 *channels_subscribers.entry(&channel).or_default() = listeners.borrow().len();
286 }
287
288 let span = span!(Level::DEBUG, "Radio Station Metrics");
289 let _enter = span.enter();
290
291 for (channel, count) in channels_subscribers.iter().sorted() {
292 info!(" {count} subscribers for {channel:?}")
293 }
294 }
295 }
296
297 /// Modify the state using a specific channel.
298 /// This will notify all subscribers to that channel (and any derived channels).
299 ///
300 /// Returns a [`RadioGuard`] that allows direct mutation of the state.
301 /// The guard automatically notifies listeners when dropped.
302 ///
303 /// # Example
304 ///
305 /// ```rust, ignore
306 /// # use freya::radio::*;
307 /// radio_station.write_channel(MyChannel::Update).count += 1;
308 /// ```
309 #[track_caller]
310 pub fn write_channel(&mut self, channel: Channel) -> RadioGuard<Value, Channel> {
311 let value = self.value.write_unchecked();
312 RadioGuard {
313 channels: channel.derive_channel(&*value),
314 station: *self,
315 value,
316 }
317 }
318}
319
320pub struct RadioAntenna<Value, Channel>
321where
322 Channel: RadioChannel<Value>,
323 Value: 'static,
324{
325 pub(crate) channel: Channel,
326 pub(crate) station: RadioStation<Value, Channel>,
327}
328
329impl<Value, Channel> RadioAntenna<Value, Channel>
330where
331 Channel: RadioChannel<Value>,
332{
333 pub fn new(
334 channel: Channel,
335 station: RadioStation<Value, Channel>,
336 ) -> RadioAntenna<Value, Channel> {
337 RadioAntenna { channel, station }
338 }
339}
340impl<Value, Channel> Clone for RadioAntenna<Value, Channel>
341where
342 Channel: RadioChannel<Value>,
343{
344 fn clone(&self) -> Self {
345 Self {
346 channel: self.channel.clone(),
347 station: self.station,
348 }
349 }
350}
351
352pub struct RadioGuard<Value, Channel>
353where
354 Channel: RadioChannel<Value>,
355 Value: 'static,
356{
357 pub(crate) station: RadioStation<Value, Channel>,
358 pub(crate) channels: Vec<Channel>,
359 pub(crate) value: WriteRef<'static, Value>,
360}
361
362impl<Value, Channel> Drop for RadioGuard<Value, Channel>
363where
364 Channel: RadioChannel<Value>,
365{
366 fn drop(&mut self) {
367 for channel in &mut self.channels {
368 self.station.notify_listeners(channel)
369 }
370 if !self.channels.is_empty() {
371 self.station.cleanup();
372 }
373 }
374}
375
376impl<Value, Channel> Deref for RadioGuard<Value, Channel>
377where
378 Channel: RadioChannel<Value>,
379{
380 type Target = WriteRef<'static, Value>;
381
382 fn deref(&self) -> &Self::Target {
383 &self.value
384 }
385}
386
387impl<Value, Channel> DerefMut for RadioGuard<Value, Channel>
388where
389 Channel: RadioChannel<Value>,
390{
391 fn deref_mut(&mut self) -> &mut WriteRef<'static, Value> {
392 &mut self.value
393 }
394}
395
396/// A reactive handle to the global state for a specific channel.
397/// `Radio` provides methods to read and write the global state, and automatically subscribes
398/// the current component to re-render when the associated channel is notified.
399///
400/// Each `Radio` instance is tied to a specific channel, allowing fine-grained control
401/// over which components update when the state changes.
402///
403/// # Examples
404///
405/// ## Basic usage
406///
407/// ```rust, ignore
408/// # use freya::prelude::*;
409/// # use freya::radio::*;
410/// #[derive(PartialEq)]
411/// struct MyComponent {}
412///
413/// impl Component for MyComponent {
414/// fn render(&self) -> impl IntoElement {
415/// let mut radio = use_radio(MyChannel::Count);
416///
417/// rect()
418/// .child(label().text(format!("Count: {}", radio.read().count)))
419/// .child(
420/// Button::new()
421/// .on_press(move |_| radio.write().count += 1)
422/// .child("Increment"),
423/// )
424/// }
425/// }
426/// ```
427///
428/// ## Using reducers
429///
430/// ```rust, ignore
431/// # use freya::prelude::*;
432/// # use freya::radio::*;
433/// #[derive(Clone)]
434/// struct CounterState {
435/// count: i32,
436/// }
437///
438/// impl DataReducer for CounterState {
439/// type Channel = CounterChannel;
440/// type Action = CounterAction;
441///
442/// fn reduce(&mut self, action: CounterAction) -> ChannelSelection<CounterChannel> {
443/// match action {
444/// CounterAction::Increment => self.count += 1,
445/// CounterAction::Decrement => self.count -= 1,
446/// }
447/// ChannelSelection::Current
448/// }
449/// }
450///
451/// #[derive(PartialEq)]
452/// struct CounterComponent {}
453///
454/// impl Component for CounterComponent {
455/// fn render(&self) -> impl IntoElement {
456/// let mut radio = use_radio(CounterChannel::Count);
457///
458/// rect()
459/// .child(
460/// Button::new()
461/// .on_press(move |_| radio.apply(CounterAction::Increment))
462/// .child("+"),
463/// )
464/// .child(label().text(format!("{}", radio.read().count)))
465/// .child(
466/// Button::new()
467/// .on_press(move |_| radio.apply(CounterAction::Decrement))
468/// .child("-"),
469/// )
470/// }
471/// }
472/// ```
473pub struct Radio<Value, Channel>
474where
475 Channel: RadioChannel<Value>,
476 Value: 'static,
477{
478 pub(crate) antenna: State<RadioAntenna<Value, Channel>>,
479}
480
481impl<Value, Channel> Clone for Radio<Value, Channel>
482where
483 Channel: RadioChannel<Value>,
484{
485 fn clone(&self) -> Self {
486 *self
487 }
488}
489impl<Value, Channel> Copy for Radio<Value, Channel> where Channel: RadioChannel<Value> {}
490
491impl<Value, Channel> PartialEq for Radio<Value, Channel>
492where
493 Channel: RadioChannel<Value>,
494{
495 fn eq(&self, other: &Self) -> bool {
496 self.antenna == other.antenna
497 }
498}
499
500impl<Value, Channel> Radio<Value, Channel>
501where
502 Channel: RadioChannel<Value>,
503{
504 pub fn new(antenna: State<RadioAntenna<Value, Channel>>) -> Radio<Value, Channel> {
505 Radio { antenna }
506 }
507
508 pub(crate) fn subscribe_if_not(&self) {
509 if let Some(rc) = ReactiveContext::try_current() {
510 let antenna = self.antenna.peek();
511 let channel = antenna.channel.clone();
512 let is_listening = antenna.station.is_listening(&channel, &rc);
513
514 // Subscribe the reader reactive context to the channel if it wasn't already
515 if !is_listening {
516 antenna.station.listen(channel, rc);
517 }
518 }
519 }
520
521 /// Read the current state value and subscribe the current component to changes
522 /// on this radio's channel. The component will re-render when this channel is notified.
523 ///
524 /// # Example
525 ///
526 /// ```rust, ignore
527 /// # use freya::radio::*;
528 /// let count = radio.read().count;
529 /// ```
530 #[track_caller]
531 pub fn read(&'_ self) -> ReadRef<'_, Value> {
532 self.subscribe_if_not();
533 self.antenna.peek().station.value.peek_unchecked()
534 }
535
536 /// Read the current state value inside a callback.
537 ///
538 /// Example:
539 ///
540 /// ```rust, ignore
541 /// # use freya::radio::*;
542 /// radio.with(|value| {
543 /// // Do something with `value`
544 /// });
545 /// ```
546 #[track_caller]
547 pub fn with(&self, cb: impl FnOnce(ReadRef<Value>)) {
548 self.subscribe_if_not();
549 let value = self.antenna.peek().station.value;
550 let borrow = value.peek();
551 cb(borrow);
552 }
553
554 /// Get a mutable reference to the state for writing.
555 /// Changes will notify subscribers to this radio's channel.
556 ///
557 /// Returns a [`RadioGuard`] that allows direct mutation of the state.
558 ///
559 /// # Example
560 ///
561 /// ```rust, ignore
562 /// # use freya::radio::*;
563 /// radio.write().count += 1;
564 /// ```
565 #[track_caller]
566 pub fn write(&mut self) -> RadioGuard<Value, Channel> {
567 let value = self.antenna.peek().station.value.write_unchecked();
568 let channel = self.antenna.peek().channel.clone();
569 RadioGuard {
570 channels: channel.derive_channel(&*value),
571 station: self.antenna.peek().station,
572 value,
573 }
574 }
575
576 /// Get a mutable reference to the current state value, inside a callback.
577 ///
578 /// Example:
579 ///
580 /// ```rust, ignore
581 /// # use freya::radio::*;
582 /// radio.write_with(|value| {
583 /// // Modify `value`
584 /// });
585 /// ```
586 #[track_caller]
587 pub fn write_with(&mut self, cb: impl FnOnce(RadioGuard<Value, Channel>)) {
588 let guard = self.write();
589 cb(guard);
590 }
591
592 /// Modify the state using a custom Channel.
593 ///
594 /// ## Example:
595 /// ```rust, ignore
596 /// # use freya::radio::*;
597 /// radio.write_channel(Channel::Whatever).value = 1;
598 /// ```
599 #[track_caller]
600 pub fn write_channel(&mut self, channel: Channel) -> RadioGuard<Value, Channel> {
601 let value = self.antenna.peek().station.value.write_unchecked();
602 RadioGuard {
603 channels: channel.derive_channel(&*value),
604 station: self.antenna.peek().station,
605 value,
606 }
607 }
608
609 /// Get a mutable reference to the current state value, inside a callback.
610 ///
611 /// Example:
612 ///
613 /// ```rust, ignore
614 /// # use freya::radio::*;
615 /// radio.write_channel_with(Channel::Whatever, |value| {
616 /// // Modify `value`
617 /// });
618 /// ```
619 #[track_caller]
620 pub fn write_channel_with(
621 &mut self,
622 channel: Channel,
623 cb: impl FnOnce(RadioGuard<Value, Channel>),
624 ) {
625 let guard = self.write_channel(channel);
626 cb(guard);
627 }
628
629 /// Mutate the state and choose which source channel to notify afterward.
630 ///
631 /// Example:
632 ///
633 /// ```rust, ignore
634 /// # use freya::radio::*;
635 /// radio.write_with_channel_selection(|value| {
636 /// // Modify `value`
637 /// if value.cool {
638 /// ChannelSelection::Select(Channel::Whatever)
639 /// } else {
640 /// ChannelSelection::Silence
641 /// }
642 /// });
643 /// ```
644 #[track_caller]
645 pub fn write_with_channel_selection(
646 &mut self,
647 cb: impl FnOnce(&mut Value) -> ChannelSelection<Channel>,
648 ) -> ChannelSelection<Channel> {
649 let value = self.antenna.peek().station.value.write_unchecked();
650 let mut guard = RadioGuard {
651 channels: Vec::default(),
652 station: self.antenna.peek().station,
653 value,
654 };
655 let channel_selection = cb(&mut guard.value);
656 let channel = match channel_selection.clone() {
657 ChannelSelection::Current => Some(self.antenna.peek().channel.clone()),
658 ChannelSelection::Silence => None,
659 ChannelSelection::Select(c) => Some(c),
660 };
661 if let Some(channel) = channel {
662 for channel in channel.derive_channel(&guard.value) {
663 self.antenna.peek().station.notify_listeners(&channel)
664 }
665 self.antenna.peek().station.cleanup();
666 }
667
668 channel_selection
669 }
670
671 /// Modify the state silently, no component will be notified.
672 ///
673 /// This is not recommended, the only intended usage for this is inside [RadioAsyncReducer].
674 #[track_caller]
675 pub fn write_silently(&mut self) -> RadioGuard<Value, Channel> {
676 let value = self.antenna.peek().station.value.write_unchecked();
677 RadioGuard {
678 channels: Vec::default(),
679 station: self.antenna.peek().station,
680 value,
681 }
682 }
683}
684
685impl<Value, Channel> WritableUtils<Value> for Radio<Value, Channel>
686where
687 Channel: RadioChannel<Value>,
688 Value: 'static,
689{
690 fn write_state(&mut self) -> WriteRef<'_, Value> {
691 let antenna = self.antenna.peek();
692 let channel = antenna.channel.clone();
693 let value = antenna.station.value.write_unchecked();
694 for ch in channel.derive_channel(&*value) {
695 antenna.station.notify_listeners(&ch);
696 }
697 antenna.station.cleanup();
698 value
699 }
700
701 fn peek_state(&self) -> ReadRef<'_, Value> {
702 self.antenna.peek().station.peek_unchecked()
703 }
704}
705
706impl<Channel> Copy for ChannelSelection<Channel> where Channel: Copy {}
707
708/// Selects the source channel to notify after a state update.
709///
710/// `Current` and `Select` expand through [`RadioChannel::derive_channel`], so a
711/// single selection can notify multiple related channels.
712#[derive(Clone)]
713pub enum ChannelSelection<Channel> {
714 /// Notify the channel associated with the used [`Radio`] and its derived channels.
715 Current,
716 /// Notify the given channel and its derived channels.
717 Select(Channel),
718 /// Keep state changes without notifying subscribers.
719 Silence,
720}
721
722impl<Channel> ChannelSelection<Channel> {
723 /// Change to [ChannelSelection::Current]
724 pub fn current(&mut self) {
725 *self = Self::Current
726 }
727
728 /// Change to [ChannelSelection::Select]
729 pub fn select(&mut self, channel: Channel) {
730 *self = Self::Select(channel)
731 }
732
733 /// Change to [ChannelSelection::Silence]
734 pub fn silence(&mut self) {
735 *self = Self::Silence
736 }
737
738 /// Check if it is of type [ChannelSelection::Current]
739 pub fn is_current(&self) -> bool {
740 matches!(self, Self::Current)
741 }
742
743 /// Check if it is of type [ChannelSelection::Select] and return the channel.
744 pub fn is_select(&self) -> Option<&Channel> {
745 match self {
746 Self::Select(channel) => Some(channel),
747 _ => None,
748 }
749 }
750
751 /// Check if it is of type [ChannelSelection::Silence]
752 pub fn is_silence(&self) -> bool {
753 matches!(self, Self::Silence)
754 }
755}
756
757/// Subscribe to the global state for a specific channel.
758/// Returns a [`Radio`] handle that allows reading and writing the state.
759/// The current component will re-render whenever the specified channel is notified.
760///
761/// This hook must be called within a component that has access to a [`RadioStation`]
762/// (either through [`use_init_radio_station`] or the context API).
763///
764/// # Example
765///
766/// ```rust, ignore
767/// # use freya::prelude::*;
768/// # use freya::radio::*;
769///
770/// fn app() -> impl IntoElement {
771/// use_init_radio_station::<AppState, AppChannel>(AppState::default);
772///
773/// rect().child(Counter {})
774/// }
775///
776/// #[derive(PartialEq)]
777/// struct Counter {}
778///
779/// impl Component for Counter {
780/// fn render(&self) -> impl IntoElement {
781/// let mut radio = use_radio(AppChannel::Count);
782///
783/// rect()
784/// .child(label().text(format!("Count: {}", radio.read().count)))
785/// .child(
786/// Button::new()
787/// .on_press(move |_| radio.write().count += 1)
788/// .child("+"),
789/// )
790/// }
791/// }
792/// ```
793#[track_caller]
794pub fn use_radio<Value, Channel>(channel: Channel) -> Radio<Value, Channel>
795where
796 Channel: RadioChannel<Value>,
797 Value: 'static,
798{
799 let station = use_consume::<RadioStation<Value, Channel>>();
800
801 let mut radio = use_hook(|| {
802 let antenna = RadioAntenna::new(channel.clone(), station);
803 Radio::new(State::create(antenna))
804 });
805
806 if radio.antenna.peek().channel != channel {
807 radio.antenna.write().channel = channel;
808 }
809
810 radio
811}
812
813/// Initialize a new radio station in the current component tree.
814/// This provides the global state to all descendant components.
815///
816/// Returns the [`RadioStation`] instance for direct access if needed.
817///
818/// # Example
819///
820/// ```rust, ignore
821/// # use freya::prelude::*;
822/// # use freya::radio::*;
823///
824/// fn app() -> impl IntoElement {
825/// use_init_radio_station::<AppState, AppChannel>(AppState::default);
826///
827/// rect().child(MyComponent {})
828/// }
829/// ```
830pub fn use_init_radio_station<Value, Channel>(
831 init_value: impl FnOnce() -> Value,
832) -> RadioStation<Value, Channel>
833where
834 Channel: RadioChannel<Value>,
835 Value: 'static,
836{
837 use_provide_context(|| RadioStation::create(init_value()))
838}
839
840#[track_caller]
841pub fn use_radio_station<Value, Channel>() -> RadioStation<Value, Channel>
842where
843 Channel: RadioChannel<Value>,
844 Value: 'static,
845{
846 use_consume::<RadioStation<Value, Channel>>()
847}
848
849/// Trait for implementing a reducer pattern on your state.
850/// Reducers allow you to define actions that modify the state in a controlled way.
851///
852/// Implement this trait on your state type to enable the [`RadioReducer`] functionality.
853///
854/// # Example
855///
856/// ```rust, ignore
857/// # use freya::radio::*;
858///
859/// #[derive(Clone)]
860/// struct Counter {
861/// count: i32,
862/// }
863///
864/// #[derive(Clone)]
865/// enum CounterAction {
866/// Increment,
867/// Decrement,
868/// Set(i32),
869/// }
870///
871/// impl DataReducer for Counter {
872/// type Channel = CounterChannel;
873/// type Action = CounterAction;
874///
875/// fn reduce(&mut self, action: Self::Action) -> ChannelSelection<Self::Channel> {
876/// match action {
877/// CounterAction::Increment => self.count += 1,
878/// CounterAction::Decrement => self.count -= 1,
879/// CounterAction::Set(value) => self.count = value,
880/// }
881/// ChannelSelection::Current
882/// }
883/// }
884/// ```
885pub trait DataReducer {
886 /// Notification channel type used by this state's radio station.
887 type Channel;
888 /// Action accepted by this reducer.
889 type Action;
890
891 /// Apply an action to the state and select the source channel to notify.
892 ///
893 /// See [`ChannelSelection`].
894 ///
895 /// This method only mutates state and returns a selection. Dispatch through
896 /// [`RadioReducer::apply`] to notify subscribers using the updated state.
897 fn reduce(&mut self, action: Self::Action) -> ChannelSelection<Self::Channel>;
898}
899
900/// Dispatch synchronous actions through a [`Radio`] whose state implements [`DataReducer`].
901pub trait RadioReducer {
902 /// Action accepted by the state's reducer.
903 type Action;
904 /// Notification channel type used by the radio.
905 type Channel;
906
907 /// Run [`DataReducer::reduce`] synchronously and notify the selected channels.
908 ///
909 /// See [`ChannelSelection`].
910 fn apply(&mut self, action: Self::Action) -> ChannelSelection<Self::Channel>;
911}
912
913impl<Data: DataReducer<Channel = Channel, Action = Action>, Channel: RadioChannel<Data>, Action>
914 RadioReducer for Radio<Data, Channel>
915{
916 type Action = Action;
917 type Channel = Channel;
918
919 fn apply(&mut self, action: Action) -> ChannelSelection<Channel> {
920 self.write_with_channel_selection(|data| data.reduce(action))
921 }
922}
923
924/// Define asynchronous actions for shared state, dispatched with [`RadioAsyncReducer`].
925///
926/// Unlike [`DataReducer`], this reducer receives a radio handle so state borrows
927/// can be scoped around asynchronous work instead of held across await points.
928pub trait DataAsyncReducer {
929 /// Notification channel type used by this state's radio station.
930 type Channel;
931 /// Action accepted by this reducer.
932 type Action;
933
934 /// Process an action asynchronously and select the final notification channel.
935 ///
936 /// Use [`Radio::write_silently`] for mutations that should only notify when
937 /// [`RadioAsyncReducer::async_apply`] processes the returned selection.
938 /// Ordinary writes still send their own notifications. Release all read and
939 /// write guards before awaiting so other tasks can access the state.
940 ///
941 /// Returning [`ChannelSelection::Silence`] skips the final notification but
942 /// does not undo state changes or notifications already sent by writes.
943 #[allow(async_fn_in_trait)]
944 async fn async_reduce(
945 _radio: &mut Radio<Self, Self::Channel>,
946 _action: Self::Action,
947 ) -> ChannelSelection<Self::Channel>
948 where
949 Self::Channel: RadioChannel<Self>,
950 Self: Sized;
951}
952
953/// Dispatch asynchronous actions through a [`Radio`] whose state implements [`DataAsyncReducer`].
954pub trait RadioAsyncReducer {
955 /// Action accepted by the state's asynchronous reducer.
956 type Action;
957
958 /// Spawn a Freya task to run [`DataAsyncReducer::async_reduce`] and return immediately.
959 ///
960 /// When the reducer completes, its selection is processed against the updated
961 /// state, including [`RadioChannel::derive_channel`] for non-silent selections.
962 /// This method returns neither the selection nor a task handle. Separate calls
963 /// spawn independent tasks, so their completion order is not guaranteed.
964 fn async_apply(&mut self, _action: Self::Action)
965 where
966 Self::Action: 'static;
967}
968
969impl<
970 Data: DataAsyncReducer<Channel = Channel, Action = Action>,
971 Channel: RadioChannel<Data>,
972 Action,
973> RadioAsyncReducer for Radio<Data, Channel>
974{
975 type Action = Action;
976
977 fn async_apply(&mut self, action: Self::Action)
978 where
979 Self::Action: 'static,
980 {
981 let mut radio = *self;
982 spawn(async move {
983 let channel = Data::async_reduce(&mut radio, action).await;
984 radio.write_with_channel_selection(|_| channel);
985 });
986 }
987}