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
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
#![forbid(unsafe_code)]
use crate::{
    console_warn, create_effect,
    macros::debug_warn,
    node::NodeId,
    on_cleanup,
    runtime::{with_runtime, RuntimeId},
    Runtime, Scope, ScopeProperty,
};
use cfg_if::cfg_if;
use futures::Stream;
use std::{fmt::Debug, marker::PhantomData, pin::Pin, rc::Rc};
use thiserror::Error;

macro_rules! impl_get_fn_traits {
    ($($ty:ident $(($method_name:ident))?),*) => {
        $(
            #[cfg(not(feature = "stable"))]
            impl<T: Clone> FnOnce<()> for $ty<T> {
                type Output = T;

                extern "rust-call" fn call_once(self, _args: ()) -> Self::Output {
                    impl_get_fn_traits!(@method_name self $($method_name)?)
                }
            }

            #[cfg(not(feature = "stable"))]
            impl<T: Clone> FnMut<()> for $ty<T> {
                extern "rust-call" fn call_mut(&mut self, _args: ()) -> Self::Output {
                    impl_get_fn_traits!(@method_name self $($method_name)?)
                }
            }

            #[cfg(not(feature = "stable"))]
            impl<T: Clone> Fn<()> for $ty<T> {
                extern "rust-call" fn call(&self, _args: ()) -> Self::Output {
                    impl_get_fn_traits!(@method_name self $($method_name)?)
                }
            }
        )*
    };
    (@method_name $self:ident) => {
        $self.get()
    };
    (@method_name $self:ident $ident:ident) => {
        $self.$ident()
    };
}

macro_rules! impl_set_fn_traits {
    ($($ty:ident $($method_name:ident)?),*) => {
        $(
            #[cfg(not(feature = "stable"))]
            impl<T> FnOnce<(T,)> for $ty<T> {
                type Output = ();

                extern "rust-call" fn call_once(self, args: (T,)) -> Self::Output {
                    impl_set_fn_traits!(@method_name self $($method_name)? args)
                }
            }

            #[cfg(not(feature = "stable"))]
            impl<T> FnMut<(T,)> for $ty<T> {
                extern "rust-call" fn call_mut(&mut self, args: (T,)) -> Self::Output {
                    impl_set_fn_traits!(@method_name self $($method_name)? args)
                }
            }

            #[cfg(not(feature = "stable"))]
            impl<T> Fn<(T,)> for $ty<T> {
                extern "rust-call" fn call(&self, args: (T,)) -> Self::Output {
                    impl_set_fn_traits!(@method_name self $($method_name)? args)
                }
            }
        )*
    };
    (@method_name $self:ident $args:ident) => {
        $self.set($args.0)
    };
    (@method_name $self:ident $ident:ident $args:ident) => {
        $self.$ident($args.0)
    };
}

impl_get_fn_traits![ReadSignal, RwSignal];
impl_set_fn_traits![WriteSignal];

/// This prelude imports all signal types as well as all signal
/// traits needed to use those types.
pub mod prelude {
    pub use super::*;
    pub use crate::{
        memo::*, selector::*, signal_wrappers_read::*, signal_wrappers_write::*,
    };
}

/// This trait allows getting an owned value of the signals
/// inner type.
pub trait SignalGet<T> {
    /// Clones and returns the current value of the signal, and subscribes
    /// the running effect to this signal.
    ///
    /// # Panics
    /// Panics if you try to access a signal that was created in a [Scope] that has been disposed.
    #[track_caller]
    fn get(&self) -> T;

    /// Clones and returns the signal value, returning [`Some`] if the signal
    /// is still alive, and [`None`] otherwise.
    fn try_get(&self) -> Option<T>;
}

/// This trait allows obtaining an immutable reference to the signal's
/// inner type.
pub trait SignalWith<T> {
    /// Applies a function to the current value of the signal, and subscribes
    /// the running effect to this signal.
    ///
    /// # Panics
    /// Panics if you try to access a signal that was created in a [Scope] that has been disposed.
    #[track_caller]
    fn with<O>(&self, f: impl FnOnce(&T) -> O) -> O;

    /// Applies a function to the current value of the signal, and subscribes
    /// the running effect to this signal. Returns [`Some`] if the signal is
    /// valid and the function ran, otherwise returns [`None`].
    fn try_with<O>(&self, f: impl FnOnce(&T) -> O) -> Option<O>;

    /// Subscribes to this signal in the current reactive scope without doing anything with its value.
    fn track(&self) {
        _ = self.try_with(|_| {});
    }
}

/// This trait allows setting the value of a signal.
pub trait SignalSet<T> {
    /// Sets the signal’s value and notifies subscribers.
    ///
    /// **Note:** `set()` does not auto-memoize, i.e., it will notify subscribers
    /// even if the value has not actually changed.
    #[track_caller]
    fn set(&self, new_value: T);

    /// Sets the signal’s value and notifies subscribers. Returns [`None`]
    /// if the signal is still valid, [`Some(T)`] otherwise.
    ///
    /// **Note:** `set()` does not auto-memoize, i.e., it will notify subscribers
    /// even if the value has not actually changed.    
    fn try_set(&self, new_value: T) -> Option<T>;
}

/// This trait allows updating the inner value of a signal.
pub trait SignalUpdate<T> {
    /// Applies a function to the current value to mutate it in place
    /// and notifies subscribers that the signal has changed.
    ///
    /// **Note:** `update()` does not auto-memoize, i.e., it will notify subscribers
    /// even if the value has not actually changed.
    #[track_caller]
    fn update(&self, f: impl FnOnce(&mut T));

    /// Applies a function to the current value to mutate it in place
    /// and notifies subscribers that the signal has changed. Returns
    /// [`Some(O)`] if the signal is still valid, [`None`] otherwise.
    ///
    /// **Note:** `update()` does not auto-memoize, i.e., it will notify subscribers
    /// even if the value has not actually changed.
    #[deprecated = "Please use `try_update` instead. This method will be \
                    removed in a future version of this crate"]
    fn update_returning<O>(&self, f: impl FnOnce(&mut T) -> O) -> Option<O> {
        self.try_update(f)
    }

    /// Applies a function to the current value to mutate it in place
    /// and notifies subscribers that the signal has changed. Returns
    /// [`Some(O)`] if the signal is still valid, [`None`] otherwise.
    ///
    /// **Note:** `update()` does not auto-memoize, i.e., it will notify subscribers
    /// even if the value has not actually changed.
    fn try_update<O>(&self, f: impl FnOnce(&mut T) -> O) -> Option<O>;
}

/// Trait implemented for all signal types which you can `get` a value
/// from, such as [`ReadSignal`],
/// [`Memo`](crate::Memo), etc., which allows getting the inner value without
/// subscribing to the current scope.
pub trait SignalGetUntracked<T> {
    /// Gets the signal's value without creating a dependency on the
    /// current scope.
    ///
    /// # Panics
    /// Panics if you try to access a signal that was created in a [Scope] that has been disposed.
    #[track_caller]
    fn get_untracked(&self) -> T;

    /// Gets the signal's value without creating a dependency on the
    /// current scope. Returns [`Some(T)`] if the signal is still
    /// valid, [`None`] otherwise.
    fn try_get_untracked(&self) -> Option<T>;
}

/// This trait allows getting a reference to the signals inner value
/// without creating a dependency on the signal.
pub trait SignalWithUntracked<T> {
    /// Runs the provided closure with a reference to the current
    /// value without creating a dependency on the current scope.
    ///
    /// # Panics
    /// Panics if you try to access a signal that was created in a [Scope] that has been disposed.
    #[track_caller]
    fn with_untracked<O>(&self, f: impl FnOnce(&T) -> O) -> O;

    /// Runs the provided closure with a reference to the current
    /// value without creating a dependency on the current scope.
    /// Returns [`Some(O)`] if the signal is still valid, [`None`]
    /// otherwise.
    #[track_caller]
    fn try_with_untracked<O>(&self, f: impl FnOnce(&T) -> O) -> Option<O>;
}

/// Trait implemented for all signal types which you can `set` the inner
/// value, such as [`WriteSignal`] and [`RwSignal`], which allows setting
/// the inner value without causing effects which depend on the signal
/// from being run.
pub trait SignalSetUntracked<T> {
    /// Sets the signal's value without notifying dependents.
    #[track_caller]
    fn set_untracked(&self, new_value: T);

    /// Attempts to set the signal if it's still valid. Returns [`None`]
    /// if the signal was set, [`Some(T)`] otherwise.
    #[track_caller]
    fn try_set_untracked(&self, new_value: T) -> Option<T>;
}

/// This trait allows updating the signals value without causing
/// dependant effects to run.
pub trait SignalUpdateUntracked<T> {
    /// Runs the provided closure with a mutable reference to the current
    /// value without notifying dependents.
    #[track_caller]
    fn update_untracked(&self, f: impl FnOnce(&mut T));

    /// Runs the provided closure with a mutable reference to the current
    /// value without notifying dependents and returns
    /// the value the closure returned.
    #[deprecated = "Please use `try_update_untracked` instead. This method \
                    will be removed in a future version of `leptos`"]
    fn update_returning_untracked<U>(
        &self,
        f: impl FnOnce(&mut T) -> U,
    ) -> Option<U> {
        self.try_update_untracked(f)
    }

    /// Runs the provided closure with a mutable reference to the current
    /// value without notifying dependents and returns
    /// the value the closure returned.
    fn try_update_untracked<O>(&self, f: impl FnOnce(&mut T) -> O)
        -> Option<O>;
}

/// This trait allows converting a signal into a async [`Stream`].
pub trait SignalStream<T> {
    /// Generates a [`Stream`] that emits the new value of the signal
    /// whenever it changes.
    ///
    /// # Panics
    /// Panics if you try to access a signal that was created in a [Scope] that has been disposed.
    // We're returning an opaque type until impl trait in trait
    // positions are stabilized, and also so any underlying
    // changes are non-breaking
    #[track_caller]
    fn to_stream(&self, cx: Scope) -> Pin<Box<dyn Stream<Item = T>>>;
}

/// This trait allows disposing a signal before its [Scope] has been disposed.
pub trait SignalDispose {
    /// Disposes of the signal. This:
    /// 1. Detaches the signal from the reactive graph, preventing it from triggering
    ///    further updates; and
    /// 2. Drops the value contained in the signal.
    #[track_caller]
    fn dispose(self);
}

/// Creates a signal, the basic reactive primitive.
///
/// A signal is a piece of data that may change over time,
/// and notifies other code when it has changed. This is the
/// core primitive of Leptos’s reactive system.
///
/// Takes a reactive [Scope] and the initial value as arguments,
/// and returns a tuple containing a [ReadSignal] and a [WriteSignal],
/// each of which can be called as a function.
///
/// ```
/// # use leptos_reactive::*;
/// # create_scope(create_runtime(), |cx| {
/// let (count, set_count) = create_signal(cx, 0);
///
/// // ✅ calling the getter clones and returns the value
/// assert_eq!(count(), 0);
///
/// // ✅ calling the setter sets the value
/// set_count(1);
/// assert_eq!(count(), 1);
///
/// // ❌ don't try to call the getter within the setter
/// // set_count(count() + 1);
///
/// // ✅ instead, use .update() to mutate the value in place
/// set_count.update(|count: &mut i32| *count += 1);
/// assert_eq!(count(), 2);
///
/// // ✅ you can create "derived signals" with the same Fn() -> T interface
/// let double_count = move || count() * 2; // signals are `Copy` so you can `move` them anywhere
/// set_count(0);
/// assert_eq!(double_count(), 0);
/// set_count(1);
/// assert_eq!(double_count(), 2);
/// # }).dispose();
/// #
/// ```
#[cfg_attr(
    debug_assertions,
    instrument(
        level = "trace",
        skip_all,
        fields(
            scope = ?cx.id,
            ty = %std::any::type_name::<T>()
        )
    )
)]
#[track_caller]
pub fn create_signal<T>(
    cx: Scope,
    value: T,
) -> (ReadSignal<T>, WriteSignal<T>) {
    let s = cx.runtime.create_signal(value);
    cx.with_scope_property(|prop| prop.push(ScopeProperty::Signal(s.0.id)));
    s
}

/// Works exactly as [create_signal], but creates multiple signals at once.
#[cfg_attr(
    debug_assertions,
    instrument(
        level = "trace",
        skip_all,
        fields(
            scope = ?cx.id,
            ty = %std::any::type_name::<T>()
        )
    )
)]
#[track_caller]
pub fn create_many_signals<T>(
    cx: Scope,
    values: impl IntoIterator<Item = T>,
) -> Vec<(ReadSignal<T>, WriteSignal<T>)> {
    cx.runtime.create_many_signals_with_map(cx, values, |x| x)
}

/// Works exactly as [create_many_signals], but applies the map function to each signal pair.
#[cfg_attr(
    debug_assertions,
    instrument(
        level = "trace",
        skip_all,
        fields(
            scope = ?cx.id,
            ty = %std::any::type_name::<T>()
        )
    )
)]
#[track_caller]
pub fn create_many_signals_mapped<T, U>(
    cx: Scope,
    values: impl IntoIterator<Item = T>,
    map_fn: impl Fn((ReadSignal<T>, WriteSignal<T>)) -> U + 'static,
) -> Vec<U>
where
    T: 'static,
{
    cx.runtime.create_many_signals_with_map(cx, values, map_fn)
}

/// Creates a signal that always contains the most recent value emitted by a
/// [Stream](futures::stream::Stream).
/// If the stream has not yet emitted a value since the signal was created, the signal's
/// value will be `None`.
///
/// **Note**: If used on the server side during server rendering, this will return `None`
/// immediately and not begin driving the stream.
#[cfg_attr(
    debug_assertions,
    instrument(
        level = "trace",
        skip_all,
        fields(
            scope = ?cx.id,
        )
    )
)]
pub fn create_signal_from_stream<T>(
    cx: Scope,
    #[allow(unused_mut)] // allowed because needed for SSR
    mut stream: impl Stream<Item = T> + Unpin + 'static,
) -> ReadSignal<Option<T>> {
    cfg_if! {
        if #[cfg(feature = "ssr")] {
            _ = stream;
            let (read, _) = create_signal(cx, None);
            read
        } else {
            use crate::spawn_local;
            use futures::StreamExt;

            let (read, write) = create_signal(cx, None);
            spawn_local(async move {
                while let Some(value) = stream.next().await {
                    write.set(Some(value));
                }
            });
            read
        }
    }
}

/// The getter for a reactive signal.
///
/// A signal is a piece of data that may change over time,
/// and notifies other code when it has changed. This is the
/// core primitive of Leptos’s reactive system.
///
/// `ReadSignal` is also [Copy] and `'static`, so it can very easily moved into closures
/// or copied structs.
///
/// ## Core Trait Implementations
/// - [`.get()`](#impl-SignalGet<T>-for-ReadSignal<T>) (or calling the signal as a function) clones the current
///   value of the signal. If you call it within an effect, it will cause that effect
///   to subscribe to the signal, and to re-run whenever the value of the signal changes.
///   - [`.get_untracked()`](#impl-SignalGetUntracked<T>-for-ReadSignal<T>) clones the value of the signal
///   without reactively tracking it.
/// - [`.with()`](#impl-SignalWith<T>-for-ReadSignal<T>) allows you to reactively access the signal’s value without
///   cloning by applying a callback function.
///   - [`.with_untracked()`](#impl-SignalWithUntracked<T>-for-ReadSignal<T>) allows you to access the signal’s
///   value without reactively tracking it.
/// - [`.to_stream()`](#impl-SignalStream<T>-for-ReadSignal<T>) converts the signal to an `async` stream of values.
///
/// # Examples
/// ```
/// # use leptos_reactive::*;
/// # create_scope(create_runtime(), |cx| {
/// let (count, set_count) = create_signal(cx, 0);
///
/// // ✅ calling the getter clones and returns the value
/// assert_eq!(count(), 0);
///
/// // ✅ calling the setter sets the value
/// set_count(1);
/// assert_eq!(count(), 1);
///
/// // ❌ don't try to call the getter within the setter
/// // set_count(count() + 1);
///
/// // ✅ instead, use .update() to mutate the value in place
/// set_count.update(|count: &mut i32| *count += 1);
/// assert_eq!(count(), 2);
///
/// // ✅ you can create "derived signals" with the same Fn() -> T interface
/// let double_count = move || count() * 2; // signals are `Copy` so you can `move` them anywhere
/// set_count(0);
/// assert_eq!(double_count(), 0);
/// set_count(1);
/// assert_eq!(double_count(), 2);
/// # }).dispose();
/// #
/// ```
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct ReadSignal<T>
where
    T: 'static,
{
    pub(crate) runtime: RuntimeId,
    pub(crate) id: NodeId,
    pub(crate) ty: PhantomData<T>,
    #[cfg(debug_assertions)]
    pub(crate) defined_at: &'static std::panic::Location<'static>,
}

impl<T: Clone> SignalGetUntracked<T> for ReadSignal<T> {
    #[cfg_attr(
        debug_assertions,
        instrument(
            level = "trace",
            name = "ReadSignal::get_untracked()",
            skip_all,
            fields(
                id = ?self.id,
                defined_at = %self.defined_at,
                ty = %std::any::type_name::<T>()
            )
        )
    )]
    fn get_untracked(&self) -> T {
        match with_runtime(self.runtime, |runtime| {
            self.id.try_with_no_subscription(runtime, T::clone)
        })
        .expect("runtime to be alive")
        {
            Ok(t) => t,
            Err(_) => panic_getting_dead_signal(
                #[cfg(debug_assertions)]
                self.defined_at,
            ),
        }
    }

    #[cfg_attr(
        debug_assertions,
        instrument(
            level = "trace",
            name = "ReadSignal::try_get_untracked()",
            skip_all,
            fields(
                id = ?self.id,
                defined_at = %self.defined_at,
                ty = %std::any::type_name::<T>()
            )
        )
    )]
    fn try_get_untracked(&self) -> Option<T> {
        with_runtime(self.runtime, |runtime| {
            self.id.try_with_no_subscription(runtime, Clone::clone).ok()
        })
        .ok()
        .flatten()
    }
}

impl<T> SignalWithUntracked<T> for ReadSignal<T> {
    #[cfg_attr(
        debug_assertions,
        instrument(
            level = "trace",
            name = "ReadSignal::with_untracked()",
            skip_all,
            fields(
                id = ?self.id,
                defined_at = %self.defined_at,
                ty = %std::any::type_name::<T>()
            )
        )
    )]
    fn with_untracked<O>(&self, f: impl FnOnce(&T) -> O) -> O {
        self.with_no_subscription(f)
    }

    #[cfg_attr(
        debug_assertions,
        instrument(
            level = "trace",
            name = "ReadSignal::try_with_untracked()",
            skip_all,
            fields(
                id = ?self.id,
                defined_at = %self.defined_at,
                ty = %std::any::type_name::<T>()
            )
        )
    )]
    fn try_with_untracked<O>(&self, f: impl FnOnce(&T) -> O) -> Option<O> {
        with_runtime(self.runtime, |runtime| self.id.try_with(runtime, f))
            .ok()
            .transpose()
            .ok()
            .flatten()
    }
}

/// # Examples
///
/// ```
/// # use leptos_reactive::*;
/// # create_scope(create_runtime(), |cx| {
/// let (name, set_name) = create_signal(cx, "Alice".to_string());
///
/// // ❌ unnecessarily clones the string
/// let first_char = move || name().chars().next().unwrap();
/// assert_eq!(first_char(), 'A');
///
/// // ✅ gets the first char without cloning the `String`
/// let first_char = move || name.with(|n| n.chars().next().unwrap());
/// assert_eq!(first_char(), 'A');
/// set_name("Bob".to_string());
/// assert_eq!(first_char(), 'B');
/// # });
/// ```
impl<T> SignalWith<T> for ReadSignal<T> {
    #[cfg_attr(
        debug_assertions,
        instrument(
            level = "trace",
            name = "ReadSignal::with()",
            skip_all,
            fields(
                id = ?self.id,
                defined_at = %self.defined_at,
                ty = %std::any::type_name::<T>()
            )
        )
    )]
    fn with<O>(&self, f: impl FnOnce(&T) -> O) -> O {
        match with_runtime(self.runtime, |runtime| self.id.try_with(runtime, f))
            .expect("runtime to be alive ")
        {
            Ok(o) => o,
            Err(_) => panic_getting_dead_signal(
                #[cfg(debug_assertions)]
                self.defined_at,
            ),
        }
    }

    #[cfg_attr(
        debug_assertions,
        instrument(
            level = "trace",
            name = "ReadSignal::try_with()",
            skip_all,
            fields(
                id = ?self.id,
                defined_at = %self.defined_at,
                ty = %std::any::type_name::<T>()
            )
        )
    )]
    fn try_with<O>(&self, f: impl FnOnce(&T) -> O) -> Option<O> {
        with_runtime(self.runtime, |runtime| self.id.try_with(runtime, f).ok())
            .ok()
            .flatten()
    }
}

/// # Examples
///
/// ```
/// # use leptos_reactive::*;
/// # create_scope(create_runtime(), |cx| {
/// let (count, set_count) = create_signal(cx, 0);
///
/// assert_eq!(count.get(), 0);
///
/// // count() is shorthand for count.get()
/// assert_eq!(count(), 0);
/// # });
/// ```
impl<T: Clone> SignalGet<T> for ReadSignal<T> {
    #[cfg_attr(
        debug_assertions,
        instrument(
            level = "trace",
            name = "ReadSignal::get()",
            skip_all,
            fields(
                id = ?self.id,
                defined_at = %self.defined_at,
                ty = %std::any::type_name::<T>()
            )
        )
    )]
    fn get(&self) -> T {
        match with_runtime(self.runtime, |runtime| {
            self.id.try_with(runtime, T::clone)
        })
        .expect("runtime to be alive")
        {
            Ok(t) => t,
            Err(_) => panic_getting_dead_signal(
                #[cfg(debug_assertions)]
                self.defined_at,
            ),
        }
    }

    #[cfg_attr(
        debug_assertions,
        instrument(
            level = "trace",
            name = "ReadSignal::try_get()",
            skip_all,
            fields(
                id = ?self.id,
                defined_at = %self.defined_at,
                ty = %std::any::type_name::<T>()
            )
        )
    )]
    fn try_get(&self) -> Option<T> {
        self.try_with(Clone::clone).ok()
    }
}

impl<T: Clone> SignalStream<T> for ReadSignal<T> {
    #[cfg_attr(
        debug_assertions,
        instrument(
            level = "trace",
            name = "ReadSignal::to_stream()",
            skip_all,
            fields(
                id = ?self.id,
                defined_at = %self.defined_at,
                ty = %std::any::type_name::<T>()
            )
        )
    )]
    fn to_stream(&self, cx: Scope) -> Pin<Box<dyn Stream<Item = T>>> {
        let (tx, rx) = futures::channel::mpsc::unbounded();

        let close_channel = tx.clone();

        on_cleanup(cx, move || close_channel.close_channel());

        let this = *self;

        create_effect(cx, move |_| {
            let _ = tx.unbounded_send(this.get());
        });

        Box::pin(rx)
    }
}

impl<T> SignalDispose for ReadSignal<T> {
    fn dispose(self) {
        _ = with_runtime(self.runtime, |runtime| runtime.dispose_node(self.id));
    }
}

impl<T> ReadSignal<T>
where
    T: 'static,
{
    pub(crate) fn with_no_subscription<U>(&self, f: impl FnOnce(&T) -> U) -> U {
        self.id.with_no_subscription(self.runtime, f)
    }

    /// Applies the function to the current Signal, if it exists, and subscribes
    /// the running effect.
    pub(crate) fn try_with<U>(
        &self,
        f: impl FnOnce(&T) -> U,
    ) -> Result<U, SignalError> {
        match with_runtime(self.runtime, |runtime| self.id.try_with(runtime, f))
        {
            Ok(Ok(v)) => Ok(v),
            Ok(Err(e)) => Err(e),
            Err(_) => Err(SignalError::RuntimeDisposed),
        }
    }
}

impl<T> Clone for ReadSignal<T> {
    fn clone(&self) -> Self {
        Self {
            runtime: self.runtime,
            id: self.id,
            ty: PhantomData,
            #[cfg(debug_assertions)]
            defined_at: self.defined_at,
        }
    }
}

impl<T> Copy for ReadSignal<T> {}

/// The setter for a reactive signal.
///
/// A signal is a piece of data that may change over time,
/// and notifies other code when it has changed. This is the
/// core primitive of Leptos’s reactive system.
///
/// Calling [WriteSignal::update] will mutate the signal’s value in place,
/// and notify all subscribers that the signal’s value has changed.
///
/// `WriteSignal` implements [Fn], such that `set_value(new_value)` is equivalent to
/// `set_value.update(|value| *value = new_value)`.
///
/// `WriteSignal` is [Copy] and `'static`, so it can very easily moved into closures
/// or copied structs.
///
/// ## Core Trait Implementations
/// - [`.set()`](#impl-SignalSet<T>-for-WriteSignal<T>) (or calling the setter as a function)
///   sets the signal’s value, and notifies all subscribers that the signal’s value has changed.
///   to subscribe to the signal, and to re-run whenever the value of the signal changes.
///   - [`.set_untracked()`](#impl-SignalSetUntracked<T>-for-WriteSignal<T>) sets the signal’s value
///   without notifying its subscribers.
/// - [`.update()`](#impl-SignalUpdate<T>-for-WriteSignal<T>) mutates the signal’s value in place
///   and notifies all subscribers that the signal’s value has changed.
///   - [`.update_untracked()`](#impl-SignalUpdateUntracked<T>-for-WriteSignal<T>) mutates the signal’s value
///   in place without notifying its subscribers.
///
/// ## Examples
/// ```
/// # use leptos_reactive::*;
/// # create_scope(create_runtime(), |cx| {
/// let (count, set_count) = create_signal(cx, 0);
///
/// // ✅ calling the setter sets the value
/// set_count(1);
/// assert_eq!(count(), 1);
///
/// // ❌ don't try to call the getter within the setter
/// // set_count(count() + 1);
///
/// // ✅ instead, use .update() to mutate the value in place
/// set_count.update(|count: &mut i32| *count += 1);
/// assert_eq!(count(), 2);
/// # }).dispose();
/// #
/// ```
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct WriteSignal<T>
where
    T: 'static,
{
    pub(crate) runtime: RuntimeId,
    pub(crate) id: NodeId,
    pub(crate) ty: PhantomData<T>,
    #[cfg(debug_assertions)]
    pub(crate) defined_at: &'static std::panic::Location<'static>,
}

impl<T> SignalSetUntracked<T> for WriteSignal<T>
where
    T: 'static,
{
    #[cfg_attr(
        debug_assertions,
        instrument(
            level = "trace",
            name = "WriteSignal::set_untracked()",
            skip_all,
            fields(
                id = ?self.id,
                defined_at = %self.defined_at,
                ty = %std::any::type_name::<T>()
            )
        )
    )]
    fn set_untracked(&self, new_value: T) {
        self.id
            .update_with_no_effect(self.runtime, |v| *v = new_value);
    }

    #[cfg_attr(
        debug_assertions,
        instrument(
            level = "trace",
            name = "WriteSignal::try_set_untracked()",
            skip_all,
            fields(
                id = ?self.id,
                defined_at = %self.defined_at,
                ty = %std::any::type_name::<T>()
            )
        )
    )]
    fn try_set_untracked(&self, new_value: T) -> Option<T> {
        let mut new_value = Some(new_value);

        self.id
            .update(self.runtime, |t| *t = new_value.take().unwrap());

        new_value
    }
}

impl<T> SignalUpdateUntracked<T> for WriteSignal<T> {
    #[cfg_attr(
        debug_assertions,
        instrument(
            level = "trace",
            name = "WriteSignal::updated_untracked()",
            skip_all,
            fields(
                id = ?self.id,
                defined_at = %self.defined_at,
                ty = %std::any::type_name::<T>()
            )
        )
    )]
    fn update_untracked(&self, f: impl FnOnce(&mut T)) {
        self.id.update_with_no_effect(self.runtime, f);
    }

    #[cfg_attr(
        debug_assertions,
        instrument(
            level = "trace",
            name = "WriteSignal::update_returning_untracked()",
            skip_all,
            fields(
                id = ?self.id,
                defined_at = %self.defined_at,
                ty = %std::any::type_name::<T>()
            )
        )
    )]
    fn update_returning_untracked<U>(
        &self,
        f: impl FnOnce(&mut T) -> U,
    ) -> Option<U> {
        self.id.update_with_no_effect(self.runtime, f)
    }

    fn try_update_untracked<O>(
        &self,
        f: impl FnOnce(&mut T) -> O,
    ) -> Option<O> {
        self.id.update_with_no_effect(self.runtime, f)
    }
}

/// # Examples
/// ```
/// # use leptos_reactive::*;
/// # create_scope(create_runtime(), |cx| {
/// let (count, set_count) = create_signal(cx, 0);
///
/// // notifies subscribers
/// set_count.update(|n| *n = 1); // it's easier just to call set_count(1), though!
/// assert_eq!(count(), 1);
///
/// // you can include arbitrary logic in this update function
/// // also notifies subscribers, even though the value hasn't changed
/// set_count.update(|n| if *n > 3 { *n += 1 });
/// assert_eq!(count(), 1);
/// # }).dispose();
/// ```
impl<T> SignalUpdate<T> for WriteSignal<T> {
    #[cfg_attr(
        debug_assertions,
        instrument(
            name = "WriteSignal::update()",
            level = "trace",
            skip_all,
            fields(
                id = ?self.id,
                defined_at = %self.defined_at,
                ty = %std::any::type_name::<T>()
            )
        )
    )]
    fn update(&self, f: impl FnOnce(&mut T)) {
        if self.id.update(self.runtime, f).is_none() {
            warn_updating_dead_signal(
                #[cfg(debug_assertions)]
                self.defined_at,
            );
        }
    }

    #[cfg_attr(
        debug_assertions,
        instrument(
            name = "WriteSignal::try_update()",
            level = "trace",
            skip_all,
            fields(
                id = ?self.id,
                defined_at = %self.defined_at,
                ty = %std::any::type_name::<T>()
            )
        )
    )]
    fn try_update<O>(&self, f: impl FnOnce(&mut T) -> O) -> Option<O> {
        self.id.update(self.runtime, f)
    }
}

/// # Examples
///
/// ```
/// # use leptos_reactive::*;
/// # create_scope(create_runtime(), |cx| {
/// let (count, set_count) = create_signal(cx, 0);
///
/// // notifies subscribers
/// set_count.update(|n| *n = 1); // it's easier just to call set_count(1), though!
/// assert_eq!(count(), 1);
///
/// // you can include arbitrary logic in this update function
/// // also notifies subscribers, even though the value hasn't changed
/// set_count.update(|n| if *n > 3 { *n += 1 });
/// assert_eq!(count(), 1);
/// # }).dispose();
/// ```
impl<T> SignalSet<T> for WriteSignal<T> {
    #[cfg_attr(
        debug_assertions,
        instrument(
            level = "trace",
            name = "WriteSignal::set()",
            skip_all,
            fields(
                id = ?self.id,
                defined_at = %self.defined_at,
                ty = %std::any::type_name::<T>()
            )
        )
    )]
    fn set(&self, new_value: T) {
        self.id.update(self.runtime, |n| *n = new_value);
    }

    #[cfg_attr(
        debug_assertions,
        instrument(
            level = "trace",
            name = "WriteSignal::try_set()",
            skip_all,
            fields(
                id = ?self.id,
                defined_at = %self.defined_at,
                ty = %std::any::type_name::<T>()
            )
        )
    )]
    fn try_set(&self, new_value: T) -> Option<T> {
        let mut new_value = Some(new_value);

        self.id
            .update(self.runtime, |t| *t = new_value.take().unwrap());

        new_value
    }
}

impl<T> SignalDispose for WriteSignal<T> {
    fn dispose(self) {
        _ = with_runtime(self.runtime, |runtime| runtime.dispose_node(self.id));
    }
}

impl<T> Clone for WriteSignal<T> {
    fn clone(&self) -> Self {
        Self {
            runtime: self.runtime,
            id: self.id,
            ty: PhantomData,
            #[cfg(debug_assertions)]
            defined_at: self.defined_at,
        }
    }
}

impl<T> Copy for WriteSignal<T> {}

/// Creates a reactive signal with the getter and setter unified in one value.
/// You may prefer this style, or it may be easier to pass around in a context
/// or as a function argument.
/// ```
/// # use leptos_reactive::*;
/// # create_scope(create_runtime(), |cx| {
/// let count = create_rw_signal(cx, 0);
///
/// // ✅ set the value
/// count.set(1);
/// assert_eq!(count(), 1);
///
/// // ❌ don't try to call the getter within the setter
/// // count.set(count.get() + 1);
///
/// // ✅ instead, use .update() to mutate the value in place
/// count.update(|count: &mut i32| *count += 1);
/// assert_eq!(count(), 2);
/// # }).dispose();
/// #
/// ```
#[cfg_attr(
    debug_assertions,
    instrument(
        level = "trace",
        skip_all,
        fields(
            ty = %std::any::type_name::<T>()
        )
    )
)]
#[track_caller]
pub fn create_rw_signal<T>(cx: Scope, value: T) -> RwSignal<T> {
    let s = cx.runtime.create_rw_signal(value);
    cx.with_scope_property(|prop| prop.push(ScopeProperty::Signal(s.id)));
    s
}

/// A signal that combines the getter and setter into one value, rather than
/// separating them into a [ReadSignal] and a [WriteSignal]. You may prefer this
/// its style, or it may be easier to pass around in a context or as a function argument.
///
/// ## Core Trait Implementations
/// - [`.get()`](#impl-SignalGet<T>-for-RwSignal<T>) clones the current
///   value of the signal. If you call it within an effect, it will cause that effect
///   to subscribe to the signal, and to re-run whenever the value of the signal changes.
///   - [`.get_untracked()`](#impl-SignalGetUntracked<T>-for-RwSignal<T>) clones the value of the signal
///   without reactively tracking it.
/// - [`.with()`](#impl-SignalWith<T>-for-RwSignal<T>) allows you to reactively access the signal’s value without
///   cloning by applying a callback function.
///   - [`.with_untracked()`](#impl-SignalWithUntracked<T>-for-RwSignal<T>) allows you to access the signal’s
///   value without reactively tracking it.
/// - [`.set()`](#impl-SignalSet<T>-for-RwSignal<T>) sets the signal’s value,
///   and notifies all subscribers that the signal’s value has changed.
///   to subscribe to the signal, and to re-run whenever the value of the signal changes.
///   - [`.set_untracked()`](#impl-SignalSetUntracked<T>-for-RwSignal<T>) sets the signal’s value
///   without notifying its subscribers.
/// - [`.update()`](#impl-SignalUpdate<T>-for-RwSignal<T>) mutates the signal’s value in place
///   and notifies all subscribers that the signal’s value has changed.
///   - [`.update_untracked()`](#impl-SignalUpdateUntracked<T>-for-RwSignal<T>) mutates the signal’s value
///   in place without notifying its subscribers.
/// - [`.to_stream()`](#impl-SignalStream<T>-for-RwSignal<T>) converts the signal to an `async` stream of values.
///
/// ```
/// # use leptos_reactive::*;
/// # create_scope(create_runtime(), |cx| {
/// let count = create_rw_signal(cx, 0);
///
/// // ✅ set the value
/// count.set(1);
/// assert_eq!(count(), 1);
///
/// // ❌ don't try to call the getter within the setter
/// // count.set(count.get() + 1);
///
/// // ✅ instead, use .update() to mutate the value in place
/// count.update(|count: &mut i32| *count += 1);
/// assert_eq!(count(), 2);
/// # }).dispose();
/// #
/// ```
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct RwSignal<T>
where
    T: 'static,
{
    pub(crate) runtime: RuntimeId,
    pub(crate) id: NodeId,
    pub(crate) ty: PhantomData<T>,
    #[cfg(debug_assertions)]
    pub(crate) defined_at: &'static std::panic::Location<'static>,
}

impl<T> Clone for RwSignal<T> {
    fn clone(&self) -> Self {
        Self {
            runtime: self.runtime,
            id: self.id,
            ty: self.ty,
            #[cfg(debug_assertions)]
            defined_at: self.defined_at,
        }
    }
}

impl<T> Copy for RwSignal<T> {}

impl<T: Clone> SignalGetUntracked<T> for RwSignal<T> {
    #[cfg_attr(
        debug_assertions,
        instrument(
            level = "trace",
            name = "RwSignal::get_untracked()",
            skip_all,
            fields(
                id = ?self.id,
                defined_at = %self.defined_at,
                ty = %std::any::type_name::<T>()
            )
        )
    )]
    fn get_untracked(&self) -> T {
        self.id.with_no_subscription(self.runtime, Clone::clone)
    }

    #[cfg_attr(
        debug_assertions,
        instrument(
            level = "trace",
            name = "RwSignal::try_get_untracked()",
            skip_all,
            fields(
                id = ?self.id,
                defined_at = %self.defined_at,
                ty = %std::any::type_name::<T>()
            )
        )
    )]
    fn try_get_untracked(&self) -> Option<T> {
        match with_runtime(self.runtime, |runtime| {
            self.id.try_with_no_subscription(runtime, Clone::clone)
        })
        .expect("runtime to be alive")
        {
            Ok(t) => t,
            Err(_) => panic_getting_dead_signal(
                #[cfg(debug_assertions)]
                self.defined_at,
            ),
        }
    }
}

impl<T> SignalWithUntracked<T> for RwSignal<T> {
    #[cfg_attr(
        debug_assertions,
        instrument(
            level = "trace",
            name = "RwSignal::with_untracked()",
            skip_all,
            fields(
                id = ?self.id,
                defined_at = %self.defined_at,
                ty = %std::any::type_name::<T>()
            )
        )
    )]
    fn with_untracked<O>(&self, f: impl FnOnce(&T) -> O) -> O {
        self.id.with_no_subscription(self.runtime, f)
    }

    #[cfg_attr(
        debug_assertions,
        instrument(
            level = "trace",
            name = "RwSignal::try_with_untracked()",
            skip_all,
            fields(
                id = ?self.id,
                defined_at = %self.defined_at,
                ty = %std::any::type_name::<T>()
            )
        )
    )]
    fn try_with_untracked<O>(&self, f: impl FnOnce(&T) -> O) -> Option<O> {
        with_runtime(self.runtime, |runtime| self.id.try_with(runtime, f))
            .ok()
            .transpose()
            .ok()
            .flatten()
    }
}

impl<T> SignalSetUntracked<T> for RwSignal<T> {
    #[cfg_attr(
        debug_assertions,
        instrument(
            level = "trace",
            name = "RwSignal::set_untracked()",
            skip_all,
            fields(
                id = ?self.id,
                defined_at = %self.defined_at,
                ty = %std::any::type_name::<T>()
            )
        )
    )]
    fn set_untracked(&self, new_value: T) {
        self.id
            .update_with_no_effect(self.runtime, |v| *v = new_value);
    }

    #[cfg_attr(
        debug_assertions,
        instrument(
            level = "trace",
            name = "RwSignal::try_set_untracked()",
            skip_all,
            fields(
                id = ?self.id,
                defined_at = %self.defined_at,
                ty = %std::any::type_name::<T>()
            )
        )
    )]
    fn try_set_untracked(&self, new_value: T) -> Option<T> {
        let mut new_value = Some(new_value);

        self.id
            .update(self.runtime, |t| *t = new_value.take().unwrap());

        new_value
    }
}

impl<T> SignalUpdateUntracked<T> for RwSignal<T> {
    #[cfg_attr(
    debug_assertions,
    instrument(
        level = "trace",
        name = "RwSignal::update_untracked()",
        skip_all,
        fields(
            id = ?self.id,
            defined_at = %self.defined_at,
            ty = %std::any::type_name::<T>()
        )
    )
    )]
    fn update_untracked(&self, f: impl FnOnce(&mut T)) {
        self.id.update_with_no_effect(self.runtime, f);
    }

    #[cfg_attr(
    debug_assertions,
    instrument(
        level = "trace",
        name = "RwSignal::update_returning_untracked()",
        skip_all,
        fields(
            id = ?self.id,
            defined_at = %self.defined_at,
            ty = %std::any::type_name::<T>()
        )
    )
    )]
    fn update_returning_untracked<U>(
        &self,
        f: impl FnOnce(&mut T) -> U,
    ) -> Option<U> {
        self.id.update_with_no_effect(self.runtime, f)
    }

    #[cfg_attr(
        debug_assertions,
        instrument(
            level = "trace",
            name = "RwSignal::try_update_untracked()",
            skip_all,
            fields(
                id = ?self.id,
                defined_at = %self.defined_at,
                ty = %std::any::type_name::<T>()
            )
        )
    )]
    fn try_update_untracked<O>(
        &self,
        f: impl FnOnce(&mut T) -> O,
    ) -> Option<O> {
        self.id.update_with_no_effect(self.runtime, f)
    }
}

/// # Examples
///
/// ```
/// # use leptos_reactive::*;
/// # create_scope(create_runtime(), |cx| {
/// let name = create_rw_signal(cx, "Alice".to_string());
///
/// // ❌ unnecessarily clones the string
/// let first_char = move || name().chars().next().unwrap();
/// assert_eq!(first_char(), 'A');
///
/// // ✅ gets the first char without cloning the `String`
/// let first_char = move || name.with(|n| n.chars().next().unwrap());
/// assert_eq!(first_char(), 'A');
/// name.set("Bob".to_string());
/// assert_eq!(first_char(), 'B');
/// # }).dispose();
/// #
/// ```
impl<T> SignalWith<T> for RwSignal<T> {
    #[cfg_attr(
        debug_assertions,
        instrument(
            level = "trace",
            name = "RwSignal::with()",
            skip_all,
            fields(
                id = ?self.id,
                defined_at = %self.defined_at,
                ty = %std::any::type_name::<T>()
            )
        )
    )]
    fn with<O>(&self, f: impl FnOnce(&T) -> O) -> O {
        match with_runtime(self.runtime, |runtime| self.id.try_with(runtime, f))
            .expect("runtime to be alive")
        {
            Ok(o) => o,
            Err(_) => panic_getting_dead_signal(
                #[cfg(debug_assertions)]
                self.defined_at,
            ),
        }
    }

    #[cfg_attr(
        debug_assertions,
        instrument(
            level = "trace",
            name = "RwSignal::try_with()",
            skip_all,
            fields(
                id = ?self.id,
                defined_at = %self.defined_at,
                ty = %std::any::type_name::<T>()
            )
        )
    )]
    fn try_with<O>(&self, f: impl FnOnce(&T) -> O) -> Option<O> {
        with_runtime(self.runtime, |runtime| self.id.try_with(runtime, f).ok())
            .ok()
            .flatten()
    }
}

/// # Examples
///
/// ```
/// # use leptos_reactive::*;
/// # create_scope(create_runtime(), |cx| {
/// let count = create_rw_signal(cx, 0);
///
/// assert_eq!(count.get(), 0);
///
/// // count() is shorthand for count.get()
/// assert_eq!(count(), 0);
/// # }).dispose();
/// #
/// ```
impl<T: Clone> SignalGet<T> for RwSignal<T> {
    #[cfg_attr(
        debug_assertions,
        instrument(
            level = "trace",
            name = "RwSignal::get()",
            skip_all,
            fields(
                id = ?self.id,
                defined_at = %self.defined_at,
                ty = %std::any::type_name::<T>()
            )
        )
    )]
    fn get(&self) -> T
    where
        T: Clone,
    {
        match with_runtime(self.runtime, |runtime| {
            self.id.try_with(runtime, T::clone)
        })
        .expect("runtime to be alive")
        {
            Ok(t) => t,
            Err(_) => panic_getting_dead_signal(
                #[cfg(debug_assertions)]
                self.defined_at,
            ),
        }
    }

    #[cfg_attr(
        debug_assertions,
        instrument(
            level = "trace",
            name = "RwSignal::try_get()",
            skip_all,
            fields(
                id = ?self.id,
                defined_at = %self.defined_at,
                ty = %std::any::type_name::<T>()
            )
        )
    )]
    fn try_get(&self) -> Option<T> {
        with_runtime(self.runtime, |runtime| {
            self.id.try_with(runtime, Clone::clone).ok()
        })
        .ok()
        .flatten()
    }
}

/// # Examples
///
/// ```
/// # use leptos_reactive::*;
/// # create_scope(create_runtime(), |cx| {
/// let count = create_rw_signal(cx, 0);
///
/// // notifies subscribers
/// count.update(|n| *n = 1); // it's easier just to call set_count(1), though!
/// assert_eq!(count(), 1);
///
/// // you can include arbitrary logic in this update function
/// // also notifies subscribers, even though the value hasn't changed
/// count.update(|n| {
///     if *n > 3 {
///         *n += 1
///     }
/// });
/// assert_eq!(count(), 1);
/// # }).dispose();
/// ```
impl<T> SignalUpdate<T> for RwSignal<T> {
    #[cfg_attr(
        debug_assertions,
        instrument(
            level = "trace",
            name = "RwSignal::update()",
            skip_all,
            fields(
                id = ?self.id,
                defined_at = %self.defined_at,
                ty = %std::any::type_name::<T>()
            )
        )
    )]
    fn update(&self, f: impl FnOnce(&mut T)) {
        if self.id.update(self.runtime, f).is_none() {
            warn_updating_dead_signal(
                #[cfg(debug_assertions)]
                self.defined_at,
            );
        }
    }

    #[cfg_attr(
        debug_assertions,
        instrument(
            level = "trace",
            name = "RwSignal::try_update()",
            skip_all,
            fields(
                id = ?self.id,
                defined_at = %self.defined_at,
                ty = %std::any::type_name::<T>()
            )
        )
    )]
    fn try_update<O>(&self, f: impl FnOnce(&mut T) -> O) -> Option<O> {
        self.id.update(self.runtime, f)
    }
}

/// # Examples
///
/// ```
/// # use leptos_reactive::*;
/// # create_scope(create_runtime(), |cx| {
/// let count = create_rw_signal(cx, 0);
///
/// assert_eq!(count(), 0);
/// count.set(1);
/// assert_eq!(count(), 1);
/// # }).dispose();
/// ```
impl<T> SignalSet<T> for RwSignal<T> {
    #[cfg_attr(
        debug_assertions,
        instrument(
            level = "trace",
            name = "RwSignal::set()",
            skip_all,
            fields(
                id = ?self.id,
                defined_at = %self.defined_at,
                ty = %std::any::type_name::<T>()
            )
        )
    )]
    fn set(&self, value: T) {
        self.id.update(self.runtime, |n| *n = value);
    }

    #[cfg_attr(
        debug_assertions,
        instrument(
            level = "trace",
            name = "RwSignal::try_set()",
            skip_all,
            fields(
                id = ?self.id,
                defined_at = %self.defined_at,
                ty = %std::any::type_name::<T>()
            )
        )
    )]
    fn try_set(&self, new_value: T) -> Option<T> {
        let mut new_value = Some(new_value);

        self.id
            .update(self.runtime, |t| *t = new_value.take().unwrap());

        new_value
    }
}

impl<T: Clone> SignalStream<T> for RwSignal<T> {
    fn to_stream(&self, cx: Scope) -> Pin<Box<dyn Stream<Item = T>>> {
        let (tx, rx) = futures::channel::mpsc::unbounded();

        let close_channel = tx.clone();

        on_cleanup(cx, move || close_channel.close_channel());

        let this = *self;

        create_effect(cx, move |_| {
            let _ = tx.unbounded_send(this.get());
        });

        Box::pin(rx)
    }
}

impl<T> SignalDispose for RwSignal<T> {
    fn dispose(self) {
        _ = with_runtime(self.runtime, |runtime| runtime.dispose_node(self.id));
    }
}

impl<T> RwSignal<T> {
    /// Returns a read-only handle to the signal.
    ///
    /// Useful if you're trying to give read access to another component but ensure that it can't write
    /// to the signal and cause other parts of the DOM to update.
    /// ```
    /// # use leptos_reactive::*;
    /// # create_scope(create_runtime(), |cx| {
    /// let count = create_rw_signal(cx, 0);
    /// let read_count = count.read_only();
    /// assert_eq!(count(), 0);
    /// assert_eq!(read_count(), 0);
    /// count.set(1);
    /// assert_eq!(count(), 1);
    /// assert_eq!(read_count(), 1);
    /// # }).dispose();
    /// ```
    #[cfg_attr(
        debug_assertions,
        instrument(
            level = "trace",
            name = "RwSignal::read_only()",
            skip_all,
            fields(
                id = ?self.id,
                defined_at = %self.defined_at,
                ty = %std::any::type_name::<T>()
            )
        )
    )]
    #[track_caller]
    pub fn read_only(&self) -> ReadSignal<T> {
        ReadSignal {
            runtime: self.runtime,
            id: self.id,
            ty: PhantomData,
            #[cfg(debug_assertions)]
            defined_at: std::panic::Location::caller(),
        }
    }

    /// Returns a write-only handle to the signal.
    ///
    /// Useful if you're trying to give write access to another component, or split an
    /// `RwSignal` into a [ReadSignal] and a [WriteSignal].
    /// ```
    /// # use leptos_reactive::*;
    /// # create_scope(create_runtime(), |cx| {
    /// let count = create_rw_signal(cx, 0);
    /// let set_count = count.write_only();
    /// assert_eq!(count(), 0);
    /// set_count(1);
    /// assert_eq!(count(), 1);
    /// # }).dispose();
    /// ```
    #[cfg_attr(
        debug_assertions,
        instrument(
            level = "trace",
            name = "RwSignal::write_only()",
            skip_all,
            fields(
                id = ?self.id,
                defined_at = %self.defined_at,
                ty = %std::any::type_name::<T>()
            )
        )
    )]
    #[track_caller]
    pub fn write_only(&self) -> WriteSignal<T> {
        WriteSignal {
            runtime: self.runtime,
            id: self.id,
            ty: PhantomData,
            #[cfg(debug_assertions)]
            defined_at: std::panic::Location::caller(),
        }
    }

    /// Splits an `RwSignal` into its getter and setter.
    /// ```
    /// # use leptos_reactive::*;
    /// # create_scope(create_runtime(), |cx| {
    /// let count = create_rw_signal(cx, 0);
    /// let (get_count, set_count) = count.split();
    /// assert_eq!(count(), 0);
    /// assert_eq!(get_count(), 0);
    /// set_count(1);
    /// assert_eq!(count(), 1);
    /// assert_eq!(get_count(), 1);
    /// # }).dispose();
    /// ```
    #[cfg_attr(
        debug_assertions,
        instrument(
            level = "trace",
            name = "RwSignal::split()",
            skip_all,
            fields(
                id = ?self.id,
                defined_at = %self.defined_at,
                ty = %std::any::type_name::<T>()
            )
        )
    )]
    #[track_caller]
    pub fn split(&self) -> (ReadSignal<T>, WriteSignal<T>) {
        (
            ReadSignal {
                runtime: self.runtime,
                id: self.id,
                ty: PhantomData,
                #[cfg(debug_assertions)]
                defined_at: std::panic::Location::caller(),
            },
            WriteSignal {
                runtime: self.runtime,
                id: self.id,
                ty: PhantomData,
                #[cfg(debug_assertions)]
                defined_at: std::panic::Location::caller(),
            },
        )
    }
}

#[derive(Debug, Error)]
pub(crate) enum SignalError {
    #[error("tried to access a signal in a runtime that had been disposed")]
    RuntimeDisposed,
    #[error("tried to access a signal that had been disposed")]
    Disposed,
    #[error("error casting signal to type {0}")]
    Type(&'static str),
}

impl NodeId {
    pub(crate) fn subscribe(&self, runtime: &Runtime) {
        // add subscriber
        if let Some(observer) = runtime.observer.get() {
            // add this observer to this node's dependencies (to allow notification)
            let mut subs = runtime.node_subscribers.borrow_mut();
            if let Some(subs) = subs.entry(*self) {
                subs.or_default().borrow_mut().insert(observer);
            }

            // add this node to the observer's sources (to allow cleanup)
            let mut sources = runtime.node_sources.borrow_mut();
            if let Some(sources) = sources.entry(observer) {
                let sources = sources.or_default();
                sources.borrow_mut().insert(*self);
            }
        }
    }

    pub(crate) fn try_with_no_subscription<T, U>(
        &self,
        runtime: &Runtime,
        f: impl FnOnce(&T) -> U,
    ) -> Result<U, SignalError>
    where
        T: 'static,
    {
        runtime.update_if_necessary(*self);
        let value = {
            let nodes = runtime.nodes.borrow();
            let node = nodes.get(*self).ok_or(SignalError::Disposed)?;
            Rc::clone(&node.value)
        };

        let value = value.borrow();
        let value = value
            .downcast_ref::<T>()
            .ok_or_else(|| SignalError::Type(std::any::type_name::<T>()))
            .expect("to downcast signal type");
        Ok(f(value))
    }

    pub(crate) fn try_with<T, U>(
        &self,
        runtime: &Runtime,
        f: impl FnOnce(&T) -> U,
    ) -> Result<U, SignalError>
    where
        T: 'static,
    {
        self.subscribe(runtime);

        self.try_with_no_subscription(runtime, f)
    }

    pub(crate) fn with_no_subscription<T, U>(
        &self,
        runtime: RuntimeId,
        f: impl FnOnce(&T) -> U,
    ) -> U
    where
        T: 'static,
    {
        with_runtime(runtime, |runtime| {
            self.try_with_no_subscription(runtime, f).unwrap()
        })
        .expect("runtime to be alive")
    }

    fn update_value<T, U>(
        &self,
        runtime: RuntimeId,
        f: impl FnOnce(&mut T) -> U,
    ) -> Option<U>
    where
        T: 'static,
    {
        with_runtime(runtime, |runtime| {
            let value = {
                let signals = runtime.nodes.borrow();
                signals.get(*self).map(|node| Rc::clone(&node.value))
            };
            if let Some(value) = value {
                let mut value = value.borrow_mut();
                if let Some(value) = value.downcast_mut::<T>() {
                    Some(f(value))
                } else {
                    debug_warn!(
                        "[Signal::update] failed when downcasting to \
                         Signal<{}>",
                        std::any::type_name::<T>()
                    );
                    None
                }
            } else {
                debug_warn!(
                    "[Signal::update] You’re trying to update a Signal<{}> \
                     that has already been disposed of. This is probably \
                     either a logic error in a component that creates and \
                     disposes of scopes, or a Resource resolving after its \
                     scope has been dropped without having been cleaned up.",
                    std::any::type_name::<T>()
                );
                None
            }
        })
        .unwrap_or_default()
    }

    pub(crate) fn update<T, U>(
        &self,
        runtime_id: RuntimeId,
        f: impl FnOnce(&mut T) -> U,
    ) -> Option<U>
    where
        T: 'static,
    {
        with_runtime(runtime_id, |runtime| {
            let value = {
                let signals = runtime.nodes.borrow();
                signals.get(*self).map(|node| Rc::clone(&node.value))
            };
            let updated = if let Some(value) = value {
                let mut value = value.borrow_mut();
                if let Some(value) = value.downcast_mut::<T>() {
                    Some(f(value))
                } else {
                    debug_warn!(
                        "[Signal::update] failed when downcasting to \
                         Signal<{}>",
                        std::any::type_name::<T>()
                    );
                    None
                }
            } else {
                debug_warn!(
                    "[Signal::update] You’re trying to update a Signal<{}> \
                     that has already been disposed of. This is probably \
                     either a logic error in a component that creates and \
                     disposes of scopes, or a Resource resolving after its \
                     scope has been dropped without having been cleaned up.",
                    std::any::type_name::<T>()
                );
                None
            };

            // mark descendants dirty
            runtime.mark_dirty(*self);

            // notify subscribers
            if updated.is_some() && !runtime.batching.get() {
                Runtime::run_effects(runtime_id);
            };
            updated
        })
        .unwrap_or_default()
    }

    pub(crate) fn update_with_no_effect<T, U>(
        &self,
        runtime: RuntimeId,
        f: impl FnOnce(&mut T) -> U,
    ) -> Option<U>
    where
        T: 'static,
    {
        // update the value
        self.update_value(runtime, f)
    }
}

#[track_caller]
fn format_signal_warning(
    msg: &str,
    #[cfg(debug_assertions)] defined_at: &'static std::panic::Location<'static>,
) -> String {
    let location = std::panic::Location::caller();

    let defined_at_msg = {
        #[cfg(debug_assertions)]
        {
            format!("signal created here: {defined_at}\n")
        }

        #[cfg(not(debug_assertions))]
        {
            String::default()
        }
    };

    format!("{msg}\n{defined_at_msg}warning happened here: {location}",)
}

#[track_caller]
pub(crate) fn panic_getting_dead_signal(
    #[cfg(debug_assertions)] defined_at: &'static std::panic::Location<'static>,
) -> ! {
    panic!(
        "{}",
        format_signal_warning(
            "Attempted to get a signal after it was disposed.",
            #[cfg(debug_assertions)]
            defined_at,
        )
    )
}

#[track_caller]
pub(crate) fn warn_updating_dead_signal(
    #[cfg(debug_assertions)] defined_at: &'static std::panic::Location<'static>,
) {
    console_warn(&format_signal_warning(
        "Attempted to update a signal after it was disposed.",
        #[cfg(debug_assertions)]
        defined_at,
    ));
}