nami 0.11.1

A powerful, lightweight reactive 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
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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
//! # Reactive Bindings
//!
//! This module provides two-way reactive bindings that can both produce and consume values.
//! Unlike read-only signals, bindings can be modified and will notify watchers of changes.

use core::{
    any::{Any, type_name},
    cell::RefCell,
    fmt::Debug,
    marker::PhantomData,
    mem::ManuallyDrop,
    ops::{
        Add, BitAnd, BitOr, BitXor, Deref, DerefMut, Div, Mul, Neg, Not, RangeBounds, Rem, Shl,
        Shr, Sub,
    },
    panic::Location,
};

use alloc::{boxed::Box, rc::Rc};
use async_channel::{Sender, unbounded};
use executor_core::{LocalExecutor, Task};
use num_traits::Signed;

use crate::{
    Computed, Signal, SignalIdentity,
    watcher::{BoxWatcherGuard, Context, WatcherManager},
};
use nami_core::observe::Origin;

pub use nami_core::CustomBinding;

/// A `Binding<T>` represents a mutable value of type `T` that can be observed.
///
/// Bindings provide a reactive way to work with values. When a binding's value
/// changes, it can notify watchers that have registered interest in the value.
pub struct Binding<T: 'static>(Box<dyn BindingImpl<Output = T>>);

/// Internal trait that defines the operations required to implement a binding.
///
/// This trait is used to erase the specific type of binding while still preserving
/// the operations that can be performed on it.
trait BindingImpl: crate::signal::ComputedImpl {
    /// Sets a new value
    fn set(&self, value: Self::Output);

    fn cloned_binding(&self) -> Binding<Self::Output>;
}

impl<T: CustomBinding + Clone + 'static> BindingImpl for T {
    fn set(&self, value: Self::Output) {
        <T as CustomBinding>::set(self, value);
    }

    fn cloned_binding(&self) -> Binding<Self::Output> {
        Binding::custom(self.clone())
    }
}

impl<T> Debug for Binding<T> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str(type_name::<Self>())
    }
}

impl<T: 'static + Clone> Binding<T> {
    /// Creates a new binding from a value by wrapping it in a container.
    ///
    /// The container provides the reactive capabilities for the value.
    #[track_caller]
    pub fn container(value: T) -> Self {
        Self::custom(Container::new(value))
    }
}

impl<T: Default + Clone + 'static> Default for Binding<T> {
    /// Creates a binding with the default value for type T.
    #[track_caller]
    fn default() -> Self {
        Self::container(T::default())
    }
}

/// Creates a new binding from a value with automatic type conversion.
///
/// This function accepts any value that implements `Into<T>`, providing ergonomic
/// initialization without manual conversion. Common use cases include:
///
/// - `binding("text")` creates a `Binding<String>` from `&str`
/// - `binding(vec![1, 2, 3])` creates a `Binding<Vec<i32>>`
/// - `binding(42)` creates a `Binding<i32>`
///
/// # Warning
///
/// This function rely on Rust's type inference to determine the target type `T`.
/// If the type cannot be inferred, you may need to provide an explicit type annotation.
///
/// # Examples
///
/// ```
/// use nami::{binding, Binding};
///
/// // Automatic conversion from &str to String
/// let text: Binding<String> = binding("hello");
/// assert_eq!(text.get(), "hello");
///
/// // Direct initialization with owned types
/// let numbers: Binding<Vec<i32>> = binding(vec![1, 2, 3]);
/// assert_eq!(numbers.get(), vec![1, 2, 3]);
///
/// // Works with any type implementing Into
/// let count: Binding<i64> = binding(42i32); // i32 -> i64
/// assert_eq!(count.get(), 42i64);
/// ```
///
/// This is equivalent to `Binding::container(value.into())`.
#[track_caller]
pub fn binding<T: 'static + Clone>(value: impl Into<T>) -> Binding<T> {
    Binding::container(value.into())
}

impl_signal_binary_ops!(Binding<T>, [T], T);

/// A guard that provides mutable access to a binding's value.
///
/// When dropped, it will update the binding with the modified value.
#[must_use]
#[derive(Debug)]
pub struct BindingMutGuard<'a, T: 'static> {
    binding: &'a Binding<T>,
    value: ManuallyDrop<T>,
    dirty: bool,
}

impl<'a, T> BindingMutGuard<'a, T> {
    /// Creates a new guard for the given binding.
    pub fn new(binding: &'a Binding<T>) -> Self {
        Self {
            value: ManuallyDrop::new(binding.get()),
            binding,
            dirty: false,
        }
    }
}

impl<T> Deref for BindingMutGuard<'_, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.value
    }
}

impl<T> DerefMut for BindingMutGuard<'_, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.dirty = true;
        &mut self.value
    }
}

impl<T: 'static> Drop for BindingMutGuard<'_, T> {
    /// When the guard is dropped, updates the binding with the modified value.
    fn drop(&mut self) {
        if self.dirty {
            let value = unsafe { ManuallyDrop::take(&mut self.value) };
            self.binding.set(value);
        } else {
            unsafe { ManuallyDrop::drop(&mut self.value) }
        }
    }
}

impl<T: 'static> Binding<T> {
    /// Creates a binding that uses a custom implementation of the `CustomBinding` trait.
    pub fn custom(custom: impl CustomBinding<Output = T> + Clone + 'static) -> Self {
        Self(Box::new(custom))
    }

    /// Gets the current value of the binding.
    #[must_use]
    pub fn get(&self) -> T {
        self.0.compute()
    }

    /// Gets mutable access to the binding's value through a guard.
    ///
    /// When the guard is dropped, the binding is updated with the modified value.
    ///
    /// > Note: In rust, `let _ = binding.get_mut();` DO NOT immediately drop the guard. Since it just binds to a variable named `_`, the guard will live until the end of the current scope. Please use `*guard` to modify the value in one line.
    ///
    /// # Example
    /// ```
    /// use nami::Binding;
    /// let n = Binding::i32(10);
    /// *n.get_mut() += 5; // do not bind the guard to a let pattern...even it is `_`
    /// ```
    ///
    /// Tip: For better performance when modifying container bindings, consider using the `with_mut` method instead.
    pub fn get_mut(&self) -> BindingMutGuard<'_, T> {
        BindingMutGuard::new(self)
    }

    /// Sets the binding to a new value
    pub fn set(&self, value: T) {
        self.0.set(value);
    }

    /// Takes the value out of the binding, replacing it with the default value.
    ///
    /// This is equivalent to `std::mem::take` and notifies watchers of the change.
    ///
    /// # Example
    /// ```
    /// use nami::{binding, Binding};
    /// let mut text: Binding<String> = binding("hello");
    /// let taken = text.take();
    /// assert_eq!(taken, "hello");
    /// assert_eq!(text.get(), String::new());
    /// ```
    #[must_use]
    pub fn take(&self) -> T
    where
        T: Default + Clone,
    {
        self.with_mut(|v| core::mem::take(v))
    }

    /// Sets the binding to a new value with automatic type conversion.
    ///
    /// Accepts any value that implements `Into<T>`, providing the same ergonomic
    /// benefits as the `binding()` constructor.
    ///
    /// # Examples
    ///
    /// ```
    /// use nami::{binding, Binding};
    ///
    /// let mut text: Binding<String> = binding("initial");
    ///
    /// // Direct &str usage - no .into() or .to_string() needed
    /// text.set_from("updated");
    /// assert_eq!(text.get(), "updated");
    ///
    /// let mut count: Binding<i64> = binding(0);
    /// count.set(42);
    /// assert_eq!(count.get(), 42i64);
    /// ```
    pub fn set_from(&self, value: impl Into<T>) {
        self.0.set(value.into());
    }

    fn as_container(&self) -> Option<&Container<T>> {
        let any = (self.0.as_ref()) as &dyn BindingImpl<Output = T> as &dyn Any;
        any.downcast_ref::<Container<T>>()
    }
    /// Applies a function to mutably borrow the binding's value.
    ///
    /// This is more efficient than `get_mut()` for container bindings as it avoids
    /// unnecessary cloning. The function receives a mutable reference to the value
    /// and any changes will notify watchers when the function completes.
    pub fn with_mut<R>(&self, f: impl FnOnce(&mut T) -> R) -> R
    where
        T: Clone,
    {
        if let Some(container) = self.as_container() {
            // optimize for container bindings
            let mut value = container.value.borrow_mut();
            let result = f(&mut *value);
            let updated = value.clone();
            drop(value);
            // notify watchers manually after releasing the RefCell borrow
            if !container.watchers.is_empty() {
                let context = Context::from(updated);
                container.watchers.notify(&context);
            }
            result
        } else {
            // fallback for non-container bindings
            let mut guard = self.get_mut();
            f(&mut *guard)
        }
    }

    /// Creates a bidirectional mapping between this binding and another type.
    ///
    /// The getter transforms values from this binding's type to the output type.
    /// The setter transforms values from the output type back to this binding's type.
    #[track_caller]
    pub fn mapping<Output, Getter, Setter>(
        source: &Self,
        getter: Getter,
        setter: Setter,
    ) -> Binding<Output>
    where
        Getter: 'static + Clone + Fn(T) -> Output,
        Setter: 'static + Clone + Fn(&Self, Output),
    {
        Binding::custom(Mapping {
            binding: source.clone(),
            getter,
            setter,
            discriminator: SignalIdentity::call_site_discriminator::<(Getter, Setter, Output)>(
                Location::caller(),
            ),
            _marker: PhantomData,
        })
    }

    /// Creates a binding that only allows values passing a filter function.
    ///
    /// When attempting to set a value that doesn't pass the filter, the operation is ignored.
    #[must_use]
    pub fn filter(&self, filter: impl 'static + Clone + Fn(&T) -> bool) -> Self
    where
        T: 'static,
    {
        Self::mapping(
            self,
            |value| value,
            move |binding, value| {
                if filter(&value) {
                    binding.set(value);
                }
            },
        )
    }

    /// Creates a binding that maps this binding's value to a boolean condition.
    ///
    /// The resulting binding is read-only and reflects whether the condition is met.
    ///
    /// # Example
    /// ```
    /// let number = nami::binding(5i32);
    /// let is_positive = number.condition(|&n: &i32| n > 0);
    /// assert_eq!(is_positive.get(), true);
    /// ```
    pub fn condition(&self, condition: impl 'static + Clone + Fn(&T) -> bool) -> Binding<bool>
    where
        T: 'static,
    {
        Self::mapping(self, move |value| condition(&value), move |_, _| {})
    }

    /// Creates a binding that tracks whether this binding's value equals a specific value.
    ///
    /// The resulting binding is read-only.
    ///
    /// # Example
    /// ```
    /// let text = nami::binding("hello".to_string());
    /// let is_hello = text.equal_to("hello".to_string());
    /// assert_eq!(is_hello.get(), true);
    /// ```
    pub fn equal_to(&self, other: T) -> Binding<bool>
    where
        T: Clone + PartialEq + 'static,
    {
        Self::mapping(self, move |value| value == other, move |_, _| {})
    }
}

type Job<T> = Box<dyn FnOnce(&mut Binding<T>) + 'static + Send>;

/// A handle for interacting with a background mailbox tied to a `Binding`.
#[derive(Debug)]
pub struct BindingMailbox<T: 'static> {
    sender: Sender<Job<T>>,
}

impl<T: 'static> BindingMailbox<T> {
    /// Sends a job to be executed with the binding on the background task.
    ///
    /// The job will be executed asynchronously and will have access to the binding
    /// for reading or modifying its value.
    ///
    /// # Panics
    ///
    /// Panics when the mailbox receiver is closed and the job cannot be enqueued.
    pub fn handle(&self, job: impl FnOnce(&mut Binding<T>) + 'static + Send) {
        self.sender
            .try_send(Box::new(job))
            .expect("BindingMailbox::handle failed to enqueue job");
    }

    /// Gets the current value of the binding asynchronously via the mailbox.
    ///
    /// # Panics
    ///
    /// Panics when the value request cannot be sent to the mailbox worker
    /// or when the response channel is unexpectedly closed.
    pub async fn get(&self) -> T
    where
        T: Clone + Send,
    {
        let (sender, receiver) = unbounded();
        self.handle(move |binding| {
            sender
                .try_send(binding.get())
                .expect("BindingMailbox::get failed to send response");
        });

        match receiver.recv().await {
            Ok(value) => value,
            Err(error) => panic!("BindingMailbox::get response channel closed: {error}"),
        }
    }

    /// Gets the current value of the binding asynchronously and converts it to type `T2`.
    ///
    /// This method retrieves the binding's value via the mailbox and automatically
    /// converts it to the target type using the `From` trait. This is particularly
    /// useful for bindings with non-`Send` types (like `waterui_str::Str`) that need to be
    /// converted to `Send` types (like `String`) for use across async boundaries.
    ///
    /// # Type Parameters
    ///
    /// * `T2` - The target type to convert to. Must implement `From<T>` where `T` is the binding's value type.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// // Convert Str binding to String for cross-thread usage
    /// use nami::{binding, Binding};
    /// use waterui_str::Str;
    /// let text_binding:Binding<Str> = nami::binding("hello world");
    /// let mailbox = text_binding.mailbox();
    /// let owned_string: String = mailbox.get_as().await;
    /// assert_eq!(owned_string, "hello world");
    /// ```
    ///
    /// # Panics
    ///
    /// Panics when the value request cannot be sent to the mailbox worker
    /// or when the response channel is unexpectedly closed.
    pub async fn get_as<T2>(&self) -> T2
    where
        T2: Send + 'static + From<T>,
    {
        let (sender, receiver) = unbounded();
        self.handle(move |binding| {
            sender
                .try_send(binding.get().into())
                .expect("BindingMailbox::get_as failed to send response");
        });

        match receiver.recv().await {
            Ok(value) => value,
            Err(error) => panic!("BindingMailbox::get_as response channel closed: {error}"),
        }
    }

    /// Sets a new value on the binding asynchronously via the mailbox.
    ///
    /// # Panics
    ///
    /// Panics when the set request cannot be sent to the mailbox worker
    /// or when the ack channel is unexpectedly closed.
    pub async fn set(&self, value: impl Into<T> + Send + 'static) {
        let (sender, receiver) = unbounded();
        self.handle(move |binding| {
            let value = value.into();
            binding.set(value);
            sender
                .try_send(())
                .expect("BindingMailbox::set failed to send ack");
        });
        receiver
            .recv()
            .await
            .expect("BindingMailbox::set ack channel closed");
    }
}

impl<T: 'static> Binding<T> {
    /// Attaches this `Binding` to a mailbox using a provided executor.
    ///
    /// Returns a `BindingMailbox` which can be cloned and used to send the
    /// binding to other tasks for mutation or observation.
    pub fn mailbox_with_executor<E: LocalExecutor>(&self, executor: E) -> BindingMailbox<T> {
        let (sender, receiver) = unbounded::<Job<T>>();

        {
            let mut binding = self.clone();
            executor
                .spawn_local(async move {
                    while let Ok(job) = receiver.recv().await {
                        job(&mut binding);
                    }
                })
                .detach();
        }

        BindingMailbox { sender }
    }

    #[cfg(feature = "std")]
    /// Attaches this `Binding` to a mailbox using the default native executor.
    #[must_use]
    pub fn mailbox(&self) -> BindingMailbox<T> {
        self.mailbox_with_executor(executor_core::DefaultExecutor)
    }
}

impl<T: PartialOrd + 'static> Binding<T> {
    /// Creates a binding that only allows values within a specified range.
    #[must_use]
    pub fn range(&self, range: impl RangeBounds<T> + Clone + 'static) -> Self {
        self.filter(move |value| range.contains(value))
    }

    /// Creates a binding that clamps values to the specified range.
    ///
    /// Values below the range minimum are clamped to the minimum.
    /// Values above the range maximum are clamped to the maximum.
    #[must_use]
    pub fn clamp(&self, range: impl RangeBounds<T> + Clone + 'static) -> Self
    where
        T: Clone,
    {
        fn clamp_value<T, R>(range: &R, value: T) -> T
        where
            T: Clone + PartialOrd,
            R: RangeBounds<T>,
        {
            if let core::ops::Bound::Included(min) = range.start_bound()
                && value < min.clone()
            {
                return min.clone();
            }
            if let core::ops::Bound::Included(max) = range.end_bound()
                && value > max.clone()
            {
                return max.clone();
            }
            value
        }
        let read_range = range.clone();
        let write_range = range;

        Self::mapping(
            self,
            move |value| clamp_value(&read_range, value),
            move |binding, value| {
                let clamped = clamp_value(&write_range, value);
                binding.set(clamped);
            },
        )
    }
}

impl<T: Signed> Binding<T> {
    /// Creates a binding that tracks the sign of this binding's value.
    ///
    /// The resulting binding is `true` for positive values and `false` for negative values.
    /// Setting `true` makes the value positive, setting `false` makes it negative.
    ///
    /// > Tip: Zero is considered positive.
    ///
    /// # Example
    /// ```
    /// use nami::Binding;
    /// let number = Binding::i32(-10i32);
    /// let sign = number.sign();
    /// assert_eq!(sign.get(), false);
    /// ```
    #[must_use]
    pub fn sign(&self) -> Binding<bool> {
        Self::mapping(
            self,
            move |value| !value.is_negative(),
            move |binding, value| {
                let current = binding.get();
                if value {
                    binding.set(current.abs());
                } else {
                    binding.set(-current.abs());
                }
            },
        )
    }
}

macro_rules! impl_binding {
    ( $( #[$meta:meta] )* $ty:ident ) => {
        impl Binding<$ty> {
            $( #[$meta] )*
            #[must_use]
            #[track_caller]
            pub fn $ty(value: $ty) -> Self {
                Self::container(value)
            }
        }
    };
}

impl_binding!(
    /// Creates a new u32 binding with the given value.
    ///
    /// # Example
    /// ```
    /// let counter = nami::Binding::u32(42);
    /// assert_eq!(counter.get(), 42);
    /// ```
    u32
);

impl_binding!(
    /// Creates a new u64 binding with the given value.
    ///
    /// # Example
    /// ```
    /// let counter = nami::Binding::u64(42);
    /// assert_eq!(counter.get(), 42);
    /// ```
    u64
);

impl_binding!(
    /// Creates a new usize binding with the given value.
    ///
    /// # Example
    /// ```
    /// let index = nami::Binding::usize(10);
    /// assert_eq!(index.get(), 10);
    /// ```
    ///
    usize
);

impl_binding!(
    /// Creates a new i32 binding with the given value.
    ///
    /// # Example
    /// ```
    /// let counter = nami::Binding::i32(42);
    /// assert_eq!(counter.get(), 42);
    /// ```
    i32
);

impl_binding!(
    /// Creates a new i64 binding with the given value.
    ///
    /// # Example
    /// ```
    /// let counter = nami::Binding::i64(42);
    /// assert_eq!(counter.get(), 42);
    /// ```
    i64
);

impl_binding!(
    /// Create a new isize binding with the given value.
    ///
    /// # Example
    /// ```
    /// let index = nami::Binding::isize(10);
    /// assert_eq!(index.get(), 10);
    /// ```
    ///
    isize
);

impl_binding!(
    /// Creates a new f32 binding with the given value.
    ///
    /// # Example
    /// ```
    /// let ratio = nami::Binding::f32(3.14);
    /// assert_eq!(ratio.get(), 3.14);
    /// ```
    f32
);

impl_binding!(
    /// Creates a new f64 binding with the given value.
    ///
    /// # Example
    /// ```
    /// let ratio = nami::Binding::f64(3.14);
    /// assert_eq!(ratio.get(), 3.14);
    /// ```
    f64
);
impl_binding!(
    /// Creates a new bool binding with the given value.
    ///
    /// # Example
    /// ```
    /// let flag = nami::Binding::bool(true);
    /// assert_eq!(flag.get(), true);
    /// ```
    bool
);
impl<T: Clone> Binding<T> {
    /// Appends an element to the binding's value and notifies watchers.
    ///
    /// The binding's value must implement `Extend` for the element type.
    ///
    /// # Example
    /// ```
    /// let mut text: nami::Binding<String> = nami::binding(String::from("Hello"));
    /// text.append(" World");
    /// assert_eq!(text.get(), "Hello World");
    /// ```
    pub fn append<Ele>(&self, ele: Ele)
    where
        T: Extend<Ele>,
    {
        self.with_mut(|value| {
            value.extend(core::iter::once(ele));
        });
    }
}

macro_rules! ops {
    ($trait:ident, $method:ident, $op:tt) => {
        impl<T: $trait<Output = T> + Clone + 'static> Binding<T> {
            #[doc = concat!("Applies the `", stringify!($op), "` operation to the binding's current value and the provided value.")]
            pub fn $method(&self, other: T) {
                self.with_mut(|value| {
                    *value = value.clone() $op other;
                });
            }
        }
    };
}

ops!(Add, add_assign, +);
ops!(Sub, sub_assign, -);
ops!(Mul, mul_assign, *);
ops!(Div, div_assign, /);
ops!(Rem, rem_assign, %);
ops!(BitAnd, bitand_assign, &);
ops!(BitOr, bitor_assign, |);
ops!(BitXor, bitxor_assign, ^);
ops!(Shl, shl_assign, <<);
ops!(Shr, shr_assign, >>);

impl<T> Binding<Option<T>> {
    /// Creates a binding that unwraps the option or uses a default value from a closure.
    ///
    /// When setting values on the returned binding, they are wrapped in `Some`.
    ///
    /// # Example
    /// ```
    /// let maybe_text = nami::binding(None::<String>);
    /// let text = maybe_text.unwrap_or_else(|| "default".to_string());
    /// assert_eq!(text.get(), "default");
    /// ```
    pub fn unwrap_or_else(&self, default: impl 'static + Clone + Fn() -> T) -> Binding<T>
    where
        T: Clone + 'static,
    {
        Self::mapping(
            self,
            move |value| value.unwrap_or_else(&default),
            move |binding, value| {
                binding.set(Some(value));
            },
        )
    }

    /// Creates a binding that unwraps the option or uses a default value.
    ///
    /// When setting values on the returned binding, they are wrapped in `Some`.
    ///
    /// # Example
    /// ```
    /// let maybe_number = nami::binding(None::<i32>);
    /// let number = maybe_number.unwrap_or(42);
    /// assert_eq!(number.get(), 42);
    /// ```
    pub fn unwrap_or(&self, default: T) -> Binding<T>
    where
        T: Clone + 'static,
    {
        self.unwrap_or_else(move || default.clone())
    }

    /// Creates a binding that unwraps the option or uses the type's default value.
    ///
    /// When setting values on the returned binding, they are wrapped in `Some`.
    ///
    /// # Example
    /// ```
    /// let maybe_vec = nami::binding(None::<Vec<i32>>);
    /// let vec: nami::Binding<Vec<i32>> = maybe_vec.unwrap_or_default();
    /// assert!(vec.get().is_empty());
    /// ```
    pub fn unwrap_or_default(&self) -> Binding<T>
    where
        T: Default + Clone + 'static,
    {
        self.unwrap_or_else(T::default)
    }

    /// Creates a binding that tracks whether this option contains a specific value.
    ///
    /// The resulting binding is `true` when this option contains `Some(equal)`,
    /// and `false` when it contains `Some(other_value)` or `None`.
    /// Setting `true` on the result sets this binding to `Some(equal)`.
    /// Setting `false` has no effect on the binding.
    ///
    /// # Example
    /// ```
    /// let maybe_text = nami::binding(Some("hello".to_string()));
    /// let is_hello = maybe_text.some_equal_to("hello".to_string());
    /// assert_eq!(is_hello.get(), true);
    /// ```
    pub fn some_equal_to(&self, equal: T) -> Binding<bool>
    where
        T: Eq + Clone + 'static,
    {
        Self::mapping(
            self,
            {
                let equal = equal.clone();
                move |value| value.as_ref().is_some_and(|value| *value == equal)
            },
            move |binding, value| {
                if value {
                    binding.set(Some(equal.clone()));
                }
            },
        )
    }
}

impl Binding<bool> {
    /// Toggles the boolean value and notifies watchers.
    ///
    /// True becomes false, false becomes true.
    ///
    /// # Example
    /// ```
    /// let mut flag = nami::binding(false);
    /// flag.toggle();
    /// assert_eq!(flag.get(), true);
    /// ```
    pub fn toggle(&self) {
        self.with_mut(|v| {
            *v = !*v;
        });
    }

    /// Creates a conditional binding that returns `Some(value)` when true, `None` when false.
    ///
    /// Setting `Some(value)` on the result sets this binding to `true`.
    /// Setting `None` sets this binding to `false`.
    ///
    /// # Example
    /// ```
    /// let is_logged_in = nami::binding(true);
    /// let username = is_logged_in.then("alice".to_string());
    /// assert_eq!(username.get(), Some("alice".to_string()));
    /// ```
    pub fn then<T>(&self, if_true: T) -> Binding<Option<T>>
    where
        T: Clone + 'static,
    {
        Self::mapping(
            self,
            move |value| {
                if value { Some(if_true.clone()) } else { None }
            },
            move |binding, value| {
                binding.set(value.is_some());
            },
        )
    }

    /// Creates a conditional binding that returns `Some(value)` when true, `None` when false.
    ///
    /// This is identical to `then()` but follows Rust's `Option::then_some()` naming convention.
    ///
    /// # Example
    /// ```
    /// let enabled = nami::binding(false);
    /// let button_text = enabled.then_some("Click me!".to_string());
    /// assert_eq!(button_text.get(), None);
    /// ```
    pub fn then_some<T>(&self, if_true: T) -> Binding<Option<T>>
    where
        T: Clone + 'static,
    {
        Self::mapping(
            self,
            move |value| {
                if value { Some(if_true.clone()) } else { None }
            },
            move |binding, value| {
                binding.set(value.is_some());
            },
        )
    }

    /// Creates a bidirectional binding that selects between two values based on this boolean.
    ///
    /// Returns `if_true` when this binding is `true`, `if_false` when `false`.
    /// Setting the `if_true` value on the result sets this binding to `true`.
    /// Setting the `if_false` value sets this binding to `false`.
    ///
    /// This is a two-way binding. For one-way selection (e.g., in animations),
    /// use [`SignalExt::select`](crate::SignalExt::select) instead which doesn't require `T: Eq`.
    ///
    /// # Example
    /// ```
    /// let dark_mode = nami::binding(false);
    /// let theme = dark_mode.bidirectional_select("dark".to_string(), "light".to_string());
    /// assert_eq!(theme.get(), "light");
    /// ```
    pub fn bidirectional_select<T>(&self, if_true: T, if_false: T) -> Binding<T>
    where
        T: Eq + Clone + 'static,
    {
        let if_true_clone = if_true.clone();
        Self::mapping(
            self,
            move |value| {
                if value {
                    if_true.clone()
                } else {
                    if_false.clone()
                }
            },
            move |binding, value| {
                binding.set(value == if_true_clone);
            },
        )
    }
    /// Creates a binding that returns the logical inverse of this boolean binding.
    ///
    /// When this binding is `true`, the returned binding is `false`, and vice versa.
    /// Setting a value on the returned binding will set the inverse value on this binding.
    ///
    /// # Example
    /// ```
    /// let enabled = nami::binding(true);
    /// let disabled = enabled.reverse();
    /// assert_eq!(disabled.get(), false);
    /// ```
    #[must_use]
    pub fn reverse(&self) -> Self {
        Self::mapping(
            self,
            |value| !value,
            move |binding, value| {
                binding.set(!value);
            },
        )
    }
}

impl Not for Binding<bool> {
    type Output = Self;

    /// Implements the logical NOT operator for boolean bindings.
    fn not(self) -> Self::Output {
        self.reverse()
    }
}

impl<T> Binding<T>
where
    T: Clone + Neg<Output = T> + 'static,
{
    /// Creates a binding that produces the negated value of this binding.
    ///
    /// Updating the derived binding will reflect the negated value back to the source.
    #[must_use]
    pub fn negate(&self) -> Self {
        Self::mapping(self, core::ops::Neg::neg, move |binding, value| {
            binding.set(value.neg());
        })
    }
}

impl<T> Neg for Binding<T>
where
    T: Clone + Neg<Output = T> + 'static,
{
    type Output = Self;

    /// Implements unary negation for bindings.
    fn neg(self) -> Self::Output {
        self.negate()
    }
}

impl<T> Clone for Binding<T> {
    /// Creates a clone of this binding.
    fn clone(&self) -> Self {
        self.0.cloned_binding()
    }
}

/// A container for a value that can be observed.
///
/// The container is the basic implementation of a binding that holds a value
/// and notifies watchers when the value changes.
#[derive(Debug, Clone)]
pub struct Container<T: 'static> {
    /// The contained value, wrapped in Reference-counted [`RefCell`] for interior mutability
    value: Rc<RefCell<T>>,
    /// Manager for watchers that are interested in changes to the value
    watchers: WatcherManager<T>,
}

impl<T> From<T> for Container<T>
where
    T: 'static + Clone,
{
    #[track_caller]
    fn from(value: T) -> Self {
        Self::new(value)
    }
}

impl<T: 'static + Clone + Default> Default for Container<T> {
    #[track_caller]
    fn default() -> Self {
        Self::new(T::default())
    }
}

impl<T: 'static + Clone> Container<T> {
    /// Creates a new container with the given value.
    #[track_caller]
    pub fn new(value: T) -> Self {
        let value = Rc::new(RefCell::new(value));
        let origin = Origin::capture::<Self>(SignalIdentity::from_rc(&value));
        Self {
            value,
            watchers: WatcherManager::with_origin(origin),
        }
    }
}

impl<T: 'static + Clone> Signal for Container<T> {
    type Output = T;
    type Guard = BoxWatcherGuard;

    /// Retrieves the current value.
    fn get(&self) -> Self::Output {
        self.value.borrow().deref().clone()
    }

    fn identity(&self) -> Option<SignalIdentity> {
        Some(SignalIdentity::from_rc(&self.value))
    }

    /// Registers a watcher to be notified when the value changes.
    fn watch(&self, watcher: impl Fn(Context<Self::Output>) + 'static) -> Self::Guard {
        Box::new(self.watchers.register_as_guard(watcher))
    }
}

impl<T: 'static + Clone> CustomBinding for Container<T> {
    /// Sets a new value and notifies watchers.
    fn set(&self, value: T) {
        self.value.replace(value.clone());
        if self.watchers.is_empty() {
            return;
        }
        let context = Context::from(value);
        self.watchers.notify(&context);
    }
}

impl<T: 'static> Signal for Binding<T> {
    type Output = T;
    type Guard = BoxWatcherGuard;

    /// Computes the current value of the binding.
    fn get(&self) -> Self::Output {
        self.get()
    }

    fn identity(&self) -> Option<SignalIdentity> {
        self.0.identity()
    }

    /// Registers a watcher to be notified when the binding's value changes.
    fn watch(&self, watcher: impl Fn(Context<Self::Output>) + 'static) -> Self::Guard {
        Box::new(self.0.add_watcher(Rc::new(watcher)))
    }
}

/// A mapping between one binding type and another.
///
/// This allows creating derived bindings that transform values from one type to another,
/// with bidirectional capabilities.
struct Mapping<Input: 'static, Output, Getter, Setter> {
    /// The source binding that is being mapped
    binding: Binding<Input>,
    /// Function to convert from input type to output type
    getter: Getter,
    /// Function to convert from output type back to input type
    setter: Setter,
    discriminator: usize,
    /// Phantom data to keep track of the Output type parameter
    _marker: PhantomData<Output>,
}

impl<Input, Output, Getter: Clone, Setter: Clone> Clone for Mapping<Input, Output, Getter, Setter> {
    fn clone(&self) -> Self {
        Self {
            binding: self.binding.clone(),
            getter: self.getter.clone(),
            setter: self.setter.clone(),
            discriminator: self.discriminator,
            _marker: PhantomData,
        }
    }
}

impl<Input, Output, Getter, Setter> Signal for Mapping<Input, Output, Getter, Setter>
where
    Input: 'static,
    Output: 'static,
    Getter: 'static + Clone + Fn(Input) -> Output,
    Setter: 'static + Clone,
{
    type Output = Output;
    type Guard = <Binding<Input> as Signal>::Guard;

    /// Computes the output value by applying the getter to the input value.
    fn get(&self) -> Self::Output {
        (self.getter)(self.binding.get())
    }

    fn identity(&self) -> Option<SignalIdentity> {
        self.binding
            .identity()
            .map(|identity| identity.with_discriminator(self.discriminator))
    }

    /// Registers a watcher that will be notified when the input binding changes.
    ///
    /// The watcher receives the transformed value.
    fn watch(&self, watcher: impl Fn(Context<Self::Output>) + 'static) -> Self::Guard {
        let getter = self.getter.clone();

        self.binding.watch(move |context| {
            let context = context.map(&(getter));
            watcher(context);
        })
    }
}

impl<Input, Output, Getter, Setter> CustomBinding for Mapping<Input, Output, Getter, Setter>
where
    Input: 'static,
    Output: 'static,
    Getter: 'static + Clone + Fn(Input) -> Output,
    Setter: 'static + Clone + Fn(&Binding<Input>, Output),
{
    /// Sets a new value by applying the setter to convert from output to input.
    fn set(&self, value: Output) {
        (self.setter)(&self.binding, value);
    }
}

// Reduce once heap allocate
impl<T> From<Binding<T>> for Computed<T> {
    fn from(val: Binding<T>) -> Self {
        let boxed = val.0 as Box<_>;
        Self(boxed)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::{string::String, vec, vec::Vec};

    #[test]
    fn test_binding_into_conversion() {
        // Test &str -> String conversion
        let text: Binding<String> = binding("hello");
        assert_eq!(text.get(), "hello");

        // Test direct initialization
        let number: Binding<i32> = binding(42);
        assert_eq!(number.get(), 42);

        // Test Vec initialization
        let items: Binding<Vec<i32>> = binding(vec![1, 2, 3]);
        assert_eq!(items.get(), vec![1, 2, 3]);

        // Test i32 -> i64 conversion
        let count: Binding<i64> = binding(100i32);
        assert_eq!(count.get(), 100i64);
    }

    #[test]
    fn test_binding_operations() {
        let text: Binding<String> = binding("initial");
        text.set_from("updated"); // Now works directly with &str!
        assert_eq!(text.get(), "updated");

        let counter: Binding<i32> = binding(0);
        counter.add_assign(5);
        assert_eq!(counter.get(), 5);
        counter.sub_assign(2);
        assert_eq!(counter.get(), 3);
    }

    #[test]
    fn test_set_with_into_conversion() {
        // Test various Into conversions with set()
        let text: Binding<String> = binding(String::new());

        // &str -> String
        text.set_from("hello");
        assert_eq!(text.get(), "hello");

        // String -> String (owned)
        text.set(String::from("world"));
        assert_eq!(text.get(), "world");

        // Cross-type conversions
        let number: Binding<i64> = binding(0i64);
        number.set(42); // i32 -> i64
        assert_eq!(number.get(), 42i64);
        number.set(100); // Direct i64
        assert_eq!(number.get(), 100i64);
    }

    #[test]
    fn test_with_mut_allows_nested_get() {
        use alloc::rc::Rc;
        use core::cell::RefCell;

        let binding: Binding<i32> = binding(0);
        let watcher_binding = binding.clone();
        let reader_binding = binding.clone();

        let notifications = Rc::new(RefCell::new(0usize));
        let notifications_clone = notifications.clone();

        let _guard = watcher_binding.watch(move |_| {
            let _ = reader_binding.get();
            *notifications_clone.borrow_mut() += 1;
        });

        binding.with_mut(|value| *value += 1);

        assert_eq!(binding.get(), 1);
        assert_eq!(*notifications.borrow(), 1);
    }

    #[test]
    fn test_binding_sign() {
        let number = binding(10i32);
        let sign = number.sign();

        // Test getting the sign
        assert!(sign.get(), "Positive number should have positive sign");
        number.set(-10);
        assert!(!sign.get(), "Negative number should have negative sign");
        number.set(0);
        assert!(sign.get(), "Zero should have positive sign");

        // Test setting the sign
        number.set(20);
        assert_eq!(number.get(), 20);
        sign.set(false); // Set to negative
        assert_eq!(
            number.get(),
            -20,
            "Setting sign to false should make number negative"
        );

        number.set(-30);
        assert_eq!(number.get(), -30);
        sign.set(true); // Set to positive
        assert_eq!(
            number.get(),
            30,
            "Setting sign to true should make number positive"
        );

        // Test reactivity
        let is_positive = number.sign();
        number.set(-5);
        assert!(!is_positive.get());
        number.set(5);
        assert!(is_positive.get());
    }

    #[test]
    fn test_binding_clamp_enforces_range_on_set() {
        let source: Binding<i32> = binding(5);
        let clamped = source.clamp(0..=10);

        clamped.set(-42);
        assert_eq!(
            source.get(),
            0,
            "values below range should clamp to lower bound"
        );

        clamped.set(42);
        assert_eq!(
            source.get(),
            10,
            "values above range should clamp to upper bound"
        );

        clamped.set(7);
        assert_eq!(
            source.get(),
            7,
            "in-range values should pass through unchanged"
        );
    }

    #[test]
    fn test_get_mut_without_mutation_does_not_notify() {
        use alloc::rc::Rc;
        use core::cell::RefCell;

        let binding: Binding<i32> = binding(1);
        let notifications = Rc::new(RefCell::new(Vec::new()));
        let notifications_clone = notifications.clone();

        let _guard = binding.watch(move |ctx| {
            notifications_clone.borrow_mut().push(ctx.into_value());
        });

        {
            let _unused_guard = binding.get_mut();
        }

        assert!(
            notifications.borrow().is_empty(),
            "Dropping guard without mutation should not notify watchers"
        );
    }
}