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
use super::*;
/// Formatting implementation for `DynamicUpdateError`.
impl fmt::Display for DynamicUpdateError {
/// Formats a human-readable dynamic update failure message.
///
/// # Arguments
///
/// - `&Self` - Error variant reference.
/// - `&mut Formatter<'_>` - Output formatter.
///
/// # Returns
///
/// - `fmt::Result` - Formatting result.
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::EmptyTargetId => write!(f, "dynamic update target ID or route cannot be empty"),
Self::ChecksumMismatch {
target,
expected,
actual,
} => write!(
f,
"checksum mismatch for `{target}`: expected {expected:#018x}, computed {actual:#018x}"
),
Self::VersionRegression {
target,
current,
incoming,
} => write!(
f,
"version regression for `{target}`: active v{current}, incoming v{incoming}"
),
Self::InvalidJson(msg) => write!(f, "invalid dynamic update JSON manifest: {msg}"),
Self::NoHistoryToRollback(target) => {
write!(
f,
"no dynamic update history available to rollback for `{target}`"
)
}
}
}
}
/// Standard `Error` marker for `DynamicUpdateError`.
impl Error for DynamicUpdateError {}
/// Style accessor and `Style` conversion helpers for `DynamicStyleSpec`.
impl DynamicStyleSpec {
/// Returns the optional explicit pixel width.
///
/// # Arguments
///
/// - `&Self` - Style spec reference.
///
/// # Returns
///
/// - `Option<f32>` - Width in logical pixels if set.
#[must_use]
pub fn width_px(&self) -> Option<f32> {
let Self { width, .. } = *self;
width
}
/// Returns the optional explicit pixel height.
///
/// # Arguments
///
/// - `&Self` - Style spec reference.
///
/// # Returns
///
/// - `Option<f32>` - Height in logical pixels if set.
#[must_use]
pub fn height_px(&self) -> Option<f32> {
let Self { height, .. } = *self;
height
}
/// Returns the optional uniform padding in logical pixels.
///
/// # Arguments
///
/// - `&Self` - Style spec reference.
///
/// # Returns
///
/// - `Option<f32>` - Padding in logical pixels if set.
#[must_use]
pub fn padding_px(&self) -> Option<f32> {
let Self { padding, .. } = *self;
padding
}
/// Returns the optional child gap in logical pixels.
///
/// # Arguments
///
/// - `&Self` - Style spec reference.
///
/// # Returns
///
/// - `Option<f32>` - Gap in logical pixels if set.
#[must_use]
pub fn gap_px(&self) -> Option<f32> {
let Self { gap, .. } = *self;
gap
}
/// Returns the optional uniform corner radius in logical pixels.
///
/// # Arguments
///
/// - `&Self` - Style spec reference.
///
/// # Returns
///
/// - `Option<f32>` - Corner radius in logical pixels if set.
#[must_use]
pub fn radius_px(&self) -> Option<f32> {
let Self { radius, .. } = *self;
radius
}
/// Returns the optional font size in logical pixels.
///
/// # Arguments
///
/// - `&Self` - Style spec reference.
///
/// # Returns
///
/// - `Option<f32>` - Font size in logical pixels if set.
#[must_use]
pub fn font_size_px(&self) -> Option<f32> {
let Self { font_size, .. } = *self;
font_size
}
/// Returns the optional 24-bit RGB hex background fill color.
///
/// # Arguments
///
/// - `&Self` - Style spec reference.
///
/// # Returns
///
/// - `Option<u32>` - RGB hex color if set.
#[must_use]
pub fn background_hex_value(&self) -> Option<u32> {
let Self { background_hex, .. } = *self;
background_hex
}
/// Returns the optional 24-bit RGB hex text foreground color.
///
/// # Arguments
///
/// - `&Self` - Style spec reference.
///
/// # Returns
///
/// - `Option<u32>` - RGB hex color if set.
#[must_use]
pub fn color_hex_value(&self) -> Option<u32> {
let Self { color_hex, .. } = *self;
color_hex
}
/// Returns the optional border stroke width in logical pixels.
///
/// # Arguments
///
/// - `&Self` - Style spec reference.
///
/// # Returns
///
/// - `Option<f32>` - Border width if set.
#[must_use]
pub fn border_width_px(&self) -> Option<f32> {
let Self { border_width, .. } = *self;
border_width
}
/// Returns the optional 24-bit RGB hex border stroke color.
///
/// # Arguments
///
/// - `&Self` - Style spec reference.
///
/// # Returns
///
/// - `Option<u32>` - RGB hex border color if set.
#[must_use]
pub fn border_hex_value(&self) -> Option<u32> {
let Self { border_hex, .. } = *self;
border_hex
}
/// Applies all configured style overrides onto `base` and returns the resolved native `Style`.
///
/// # Arguments
///
/// - `&Self` - Style override specification.
/// - `Style` - Base native style for the node kind.
///
/// # Returns
///
/// - `Style` - Compiled native style.
#[must_use]
pub fn apply_to(&self, mut base: Style) -> Style {
if self.get_full_width() {
base = base.width(Length::Percent(100.0));
}
if let Some(w) = self.width_px() {
base = base.width(Length::Px(w));
}
if let Some(h) = self.height_px() {
base = base.height(Length::Px(h));
}
if let Some(p) = self.padding_px() {
base = base.padding(Edges::all(p));
}
if let Some(g) = self.gap_px() {
base = base.gap(g);
}
if let Some(r) = self.radius_px() {
base = base.radius(r);
}
if let Some(sz) = self.font_size_px() {
base = base.font_size(sz);
}
if self.get_bold() {
base = base.font_weight(FontWeight::Bold);
}
if let Some(bg) = self.background_hex_value() {
base = base.background(Color::hex(bg));
}
if let Some(fg) = self.color_hex_value() {
base = base.color(Color::hex(fg));
}
if let (Some(bw), Some(bc)) = (self.border_width_px(), self.border_hex_value()) {
base = base.border(bw, Color::hex(bc));
}
if self.get_flex_grow() > 0.0 {
base = base.flex_grow(self.get_flex_grow());
}
base
}
}
/// Declarative builders and deterministic checksum helpers for `DynamicNodeSpec`.
impl DynamicNodeSpec {
/// Creates a vertical flexbox column node specification.
///
/// # Returns
///
/// - `Self` - Column specification.
#[must_use]
pub fn column() -> Self {
Self::new(DynamicNodeKind::Column)
}
/// Creates a horizontal flexbox row node specification.
///
/// # Returns
///
/// - `Self` - Row specification.
#[must_use]
pub fn row() -> Self {
Self::new(DynamicNodeKind::Row)
}
/// Creates a grid container node specification with `columns` equal-width columns.
///
/// # Arguments
///
/// - `u16` - Number of grid columns.
///
/// # Returns
///
/// - `Self` - Grid specification.
#[must_use]
pub fn grid(columns: u16) -> Self {
let mut node: Self = Self::new(DynamicNodeKind::Grid);
node.get_mut_style().set_columns(columns.max(1));
node
}
/// Creates a styled card surface node specification with an optional title.
///
/// # Arguments
///
/// - `String` - Card heading text.
///
/// # Returns
///
/// - `Self` - Card specification.
#[must_use]
pub fn card(title: String) -> Self {
let mut node: Self = Self::new(DynamicNodeKind::Card);
node.set_text(title);
node
}
/// Creates a native text node specification.
///
/// # Arguments
///
/// - `String` - UTF-8 text content.
///
/// # Returns
///
/// - `Self` - Text specification.
#[must_use]
pub fn text(content: String) -> Self {
let mut node: Self = Self::new(DynamicNodeKind::Text);
node.set_text(content);
node
}
/// Creates an interactive button node specification dispatching `action` when clicked.
///
/// # Arguments
///
/// - `String` - Visible button label.
/// - `String` - Action identifier emitted as `DynamicActionEvent`.
///
/// # Returns
///
/// - `Self` - Interactive button specification.
#[must_use]
pub fn button(label: String, action: String) -> Self {
let mut node: Self = Self::new(DynamicNodeKind::Button);
node.set_text(label).set_action(Some(action));
node
}
/// Creates a compact pill badge node specification.
///
/// # Arguments
///
/// - `String` - Badge label text.
///
/// # Returns
///
/// - `Self` - Badge specification.
#[must_use]
pub fn badge(label: String) -> Self {
let mut node: Self = Self::new(DynamicNodeKind::Badge);
node.set_text(label);
node
}
/// Creates a horizontal hairline divider node specification.
///
/// # Returns
///
/// - `Self` - Divider specification.
#[must_use]
pub fn divider() -> Self {
Self::new(DynamicNodeKind::Divider)
}
/// Returns the optional action identifier attached to this node.
///
/// # Arguments
///
/// - `&Self` - Node specification reference.
///
/// # Returns
///
/// - `Option<&str>` - Action identifier if interactive.
#[must_use]
pub fn action_name(&self) -> Option<&str> {
let Self { action, .. } = self;
action.as_deref()
}
/// Appends a child `DynamicNodeSpec` and returns `self` for fluent composition.
///
/// # Arguments
///
/// - `Self` - Parent specification.
/// - `Self` - Child specification to append.
///
/// # Returns
///
/// - `Self` - Updated parent specification.
#[must_use]
pub fn child(mut self, child: Self) -> Self {
self.get_mut_children().push(child);
self
}
/// Computes the deterministic cross-platform 64-bit FNV-1a checksum of this node tree.
///
/// # Arguments
///
/// - `&Self` - Node specification reference.
///
/// # Returns
///
/// - `u64` - Deterministic checksum digest.
#[must_use]
pub fn checksum(&self) -> u64 {
compute_spec_checksum(self)
}
}
/// Signing and JSON serialization helpers for `DynamicComponentUpdate`.
impl DynamicComponentUpdate {
/// Computes and stores the deterministic FNV-1a checksum of `self.spec`.
///
/// # Arguments
///
/// - `&Self` - Mutable component update.
///
/// # Returns
///
/// - `&mut Self` - Mutable reference for chaining.
pub fn sign(&mut self) -> &mut Self {
let digest: u64 = self.get_spec().checksum();
self.set_checksum(digest);
self
}
/// Serializes this component update to JSON for OTA / remote delivery.
///
/// # Arguments
///
/// - `&Self` - Component update reference.
///
/// # Returns
///
/// - `Result<String, DynamicUpdateError>` - JSON manifest string.
pub fn to_json(&self) -> Result<String, DynamicUpdateError> {
match to_string(self) {
Ok(json) => Ok(json),
Err(err) => Err(DynamicUpdateError::InvalidJson(err.to_string())),
}
}
/// Deserializes a `DynamicComponentUpdate` from a JSON string.
///
/// # Arguments
///
/// - `&str` - JSON payload.
///
/// # Returns
///
/// - `Result<Self, DynamicUpdateError>` - Parsed component update.
pub fn from_json(raw: &str) -> Result<Self, DynamicUpdateError> {
match from_str(raw) {
Ok(parsed) => Ok(parsed),
Err(err) => Err(DynamicUpdateError::InvalidJson(err.to_string())),
}
}
}
/// Signing and JSON serialization helpers for `DynamicPageUpdate`.
impl DynamicPageUpdate {
/// Computes and stores the deterministic FNV-1a checksum of `self.spec`.
///
/// # Arguments
///
/// - `&Self` - Mutable page update.
///
/// # Returns
///
/// - `&mut Self` - Mutable reference for chaining.
pub fn sign(&mut self) -> &mut Self {
let digest: u64 = self.get_spec().checksum();
self.set_checksum(digest);
self
}
/// Serializes this page update to JSON for OTA / remote delivery.
///
/// # Arguments
///
/// - `&Self` - Page update reference.
///
/// # Returns
///
/// - `Result<String, DynamicUpdateError>` - JSON manifest string.
pub fn to_json(&self) -> Result<String, DynamicUpdateError> {
match to_string(self) {
Ok(json) => Ok(json),
Err(err) => Err(DynamicUpdateError::InvalidJson(err.to_string())),
}
}
/// Deserializes a `DynamicPageUpdate` from a JSON string.
///
/// # Arguments
///
/// - `&str` - JSON payload.
///
/// # Returns
///
/// - `Result<Self, DynamicUpdateError>` - Parsed page update.
pub fn from_json(raw: &str) -> Result<Self, DynamicUpdateError> {
match from_str(raw) {
Ok(parsed) => Ok(parsed),
Err(err) => Err(DynamicUpdateError::InvalidJson(err.to_string())),
}
}
}
/// Builder and JSON manifest helpers for `DynamicUpdateBundle`.
impl DynamicUpdateBundle {
/// Appends a component-level update to this atomic bundle.
///
/// # Arguments
///
/// - `Self` - Source bundle.
/// - `DynamicComponentUpdate` - Component update entry.
///
/// # Returns
///
/// - `Self` - Updated bundle.
#[must_use]
pub fn push_component(mut self, update: DynamicComponentUpdate) -> Self {
self.get_mut_components().push(update);
self
}
/// Appends a page-level update to this atomic bundle.
///
/// # Arguments
///
/// - `Self` - Source bundle.
/// - `DynamicPageUpdate` - Page update entry.
///
/// # Returns
///
/// - `Self` - Updated bundle.
#[must_use]
pub fn push_page(mut self, update: DynamicPageUpdate) -> Self {
self.get_mut_pages().push(update);
self
}
/// Serializes the complete bundle manifest to pretty-printed JSON.
///
/// # Arguments
///
/// - `&Self` - Bundle reference.
///
/// # Returns
///
/// - `Result<String, DynamicUpdateError>` - JSON manifest string.
pub fn to_json(&self) -> Result<String, DynamicUpdateError> {
match to_string_pretty(self) {
Ok(json) => Ok(json),
Err(err) => Err(DynamicUpdateError::InvalidJson(err.to_string())),
}
}
/// Deserializes a `DynamicUpdateBundle` from a JSON manifest string.
///
/// # Arguments
///
/// - `&str` - JSON bundle manifest.
///
/// # Returns
///
/// - `Result<Self, DynamicUpdateError>` - Parsed bundle manifest.
pub fn from_json(raw: &str) -> Result<Self, DynamicUpdateError> {
match from_str(raw) {
Ok(parsed) => Ok(parsed),
Err(err) => Err(DynamicUpdateError::InvalidJson(err.to_string())),
}
}
}
/// Default empty `DynamicUpdateHub`.
impl Default for DynamicUpdateHub {
/// Creates an empty `DynamicUpdateHub` backed by fresh reactive signals.
///
/// # Returns
///
/// - `Self` - Initialized hub.
fn default() -> Self {
Self::new()
}
}
/// Component-level, page-level, and atomic bundle dynamic update orchestration on `DynamicUpdateHub`.
impl DynamicUpdateHub {
/// Creates a new `DynamicUpdateHub` with empty component/page registries and zero telemetry.
///
/// # Returns
///
/// - `Self` - Shared dynamic update hub handle.
#[must_use]
pub fn new() -> Self {
let state: DynamicHubState = DynamicHubState {
components: HashMap::new(),
component_signals: HashMap::new(),
pages: HashMap::new(),
page_signals: HashMap::new(),
routes_signal: Signal::new_detached(0),
telemetry_signal: Signal::new_detached(DynamicTelemetry::default()),
last_action: Signal::new_detached(None),
action_handlers: Vec::new(),
};
Self {
inner: Rc::new(RefCell::new(state)),
}
}
/// Applies a validated component-level dynamic update and surgically re-renders only that component slot.
///
/// # Arguments
///
/// - `&Self` - Hub reference.
/// - `DynamicComponentUpdate` - Incoming versioned component update.
///
/// # Returns
///
/// - `Result<u64, DynamicUpdateError>` - Newly active component version on success.
pub fn apply_component(
&self,
update: DynamicComponentUpdate,
) -> Result<u64, DynamicUpdateError> {
let id: String = update.get_id().trim().to_string();
if id.is_empty() {
self.record_rejection();
return Err(DynamicUpdateError::EmptyTargetId);
}
let actual_checksum: u64 = update.get_spec().checksum();
let expected_checksum: u64 = update.get_checksum();
if expected_checksum != 0 && expected_checksum != actual_checksum {
self.record_rejection();
return Err(DynamicUpdateError::ChecksumMismatch {
target: id,
expected: expected_checksum,
actual: actual_checksum,
});
}
let incoming_ver: u64 = update.get_version();
let allow_downgrade: bool = update.get_allow_downgrade();
let rev_sig_opt: Result<
(Signal<u64>, Signal<DynamicTelemetry>, DynamicTelemetry),
DynamicUpdateError,
> = self.with_state_mut(|state: &mut DynamicHubState| {
let active_ver: u64 = state
.components
.get(&id)
.and_then(|stack: &Vec<DynamicSlotRecord>| stack.last())
.map(|rec: &DynamicSlotRecord| rec.version)
.unwrap_or(0);
if !allow_downgrade && incoming_ver <= active_ver {
return Err(DynamicUpdateError::VersionRegression {
target: id.clone(),
current: active_ver,
incoming: incoming_ver,
});
}
let record: DynamicSlotRecord = DynamicSlotRecord {
version: incoming_ver,
title: String::new(),
checksum: actual_checksum,
payload: DynamicPayload::Spec(update.spec),
};
state.components.entry(id.clone()).or_default().push(record);
let sig: Signal<u64> = *state
.component_signals
.entry(id)
.or_insert_with(|| Signal::new_detached(0));
let mut tel: DynamicTelemetry = state.telemetry_signal.get_untracked();
tel.set_components_applied(tel.get_components_applied().saturating_add(1));
Ok((sig, state.telemetry_signal, tel))
});
match rev_sig_opt {
Ok((sig, tel_sig, tel)) => {
batch(|| {
let _: bool = sig.update(|v: &mut u64| *v = v.wrapping_add(1));
let _: bool = tel_sig.set(tel);
});
Ok(incoming_ver)
}
Err(err) => {
self.record_rejection();
Err(err)
}
}
}
/// Parses and applies a JSON-encoded component-level dynamic update manifest.
///
/// # Arguments
///
/// - `&Self` - Hub reference.
/// - `&str` - JSON string encoding a `DynamicComponentUpdate`.
///
/// # Returns
///
/// - `Result<u64, DynamicUpdateError>` - Newly active component version on success.
pub fn apply_component_json(&self, json: &str) -> Result<u64, DynamicUpdateError> {
let update: DynamicComponentUpdate = match DynamicComponentUpdate::from_json(json) {
Ok(parsed) => parsed,
Err(err) => {
self.record_rejection();
return Err(err);
}
};
self.apply_component(update)
}
/// Hot-swaps a component slot with a native Rust builder closure without rebuilding sibling UI.
///
/// # Arguments
///
/// - `&Self` - Hub reference.
/// - `String` - Target component slot ID.
/// - `u64` - Monotonic version number.
/// - `F` - Zero-context native Rust UI builder closure.
///
/// # Returns
///
/// - `Result<u64, DynamicUpdateError>` - Newly active component version on success.
pub fn swap_component_builder<F>(
&self,
id: String,
version: u64,
builder: F,
) -> Result<u64, DynamicUpdateError>
where
F: Fn() -> NodeId + 'static,
{
let trimmed: String = id.trim().to_string();
if trimmed.is_empty() {
self.record_rejection();
return Err(DynamicUpdateError::EmptyTargetId);
}
let builder_rc: DynamicBuilderFn = Rc::new(builder);
let res: Result<
(Signal<u64>, Signal<DynamicTelemetry>, DynamicTelemetry),
DynamicUpdateError,
> = self.with_state_mut(|state: &mut DynamicHubState| {
let active_ver: u64 = state
.components
.get(&trimmed)
.and_then(|stack: &Vec<DynamicSlotRecord>| stack.last())
.map(|rec: &DynamicSlotRecord| rec.version)
.unwrap_or(0);
if version <= active_ver {
return Err(DynamicUpdateError::VersionRegression {
target: trimmed.clone(),
current: active_ver,
incoming: version,
});
}
let record: DynamicSlotRecord = DynamicSlotRecord {
version,
title: String::new(),
checksum: 0,
payload: DynamicPayload::Native(builder_rc),
};
state
.components
.entry(trimmed.clone())
.or_default()
.push(record);
let sig: Signal<u64> = *state
.component_signals
.entry(trimmed)
.or_insert_with(|| Signal::new_detached(0));
let mut tel: DynamicTelemetry = state.telemetry_signal.get_untracked();
tel.set_components_applied(tel.get_components_applied().saturating_add(1));
Ok((sig, state.telemetry_signal, tel))
});
match res {
Ok((sig, tel_sig, tel)) => {
batch(|| {
let _: bool = sig.update(|v: &mut u64| *v = v.wrapping_add(1));
let _: bool = tel_sig.set(tel);
});
Ok(version)
}
Err(err) => {
self.record_rejection();
Err(err)
}
}
}
/// Rolls back a component slot to its previous revision (or `0` compiled fallback when the stack empties).
///
/// # Arguments
///
/// - `&Self` - Hub reference.
/// - `&str` - Target component slot ID.
///
/// # Returns
///
/// - `Result<u64, DynamicUpdateError>` - Restored active version (`0` means compiled fallback).
pub fn rollback_component(&self, id: &str) -> Result<u64, DynamicUpdateError> {
let key: String = id.trim().to_string();
let res: Result<
(u64, Signal<u64>, Signal<DynamicTelemetry>, DynamicTelemetry),
DynamicUpdateError,
> = self.with_state_mut(|state: &mut DynamicHubState| {
let popped: bool = state
.components
.get_mut(&key)
.and_then(|stack: &mut Vec<DynamicSlotRecord>| stack.pop())
.is_some();
if !popped {
return Err(DynamicUpdateError::NoHistoryToRollback(key.clone()));
}
let next_ver: u64 = state
.components
.get(&key)
.and_then(|stack: &Vec<DynamicSlotRecord>| stack.last())
.map(|rec: &DynamicSlotRecord| rec.version)
.unwrap_or(0);
let sig: Signal<u64> = *state
.component_signals
.entry(key)
.or_insert_with(|| Signal::new_detached(0));
let mut tel: DynamicTelemetry = state.telemetry_signal.get_untracked();
tel.set_rollbacks(tel.get_rollbacks().saturating_add(1));
Ok((next_ver, sig, state.telemetry_signal, tel))
});
let (next_ver, sig, tel_sig, tel): (
u64,
Signal<u64>,
Signal<DynamicTelemetry>,
DynamicTelemetry,
) = res?;
batch(|| {
let _: bool = sig.update(|v: &mut u64| *v = v.wrapping_add(1));
let _: bool = tel_sig.set(tel);
});
Ok(next_ver)
}
/// Applies a validated page-level dynamic update (overriding an existing route or injecting a new one).
///
/// # Arguments
///
/// - `&Self` - Hub reference.
/// - `DynamicPageUpdate` - Incoming versioned page update.
///
/// # Returns
///
/// - `Result<u64, DynamicUpdateError>` - Newly active page version on success.
pub fn apply_page(&self, update: DynamicPageUpdate) -> Result<u64, DynamicUpdateError> {
let route: String = normalize_dynamic_route(update.get_route());
if route.is_empty() {
self.record_rejection();
return Err(DynamicUpdateError::EmptyTargetId);
}
let actual_checksum: u64 = update.get_spec().checksum();
let expected_checksum: u64 = update.get_checksum();
if expected_checksum != 0 && expected_checksum != actual_checksum {
self.record_rejection();
return Err(DynamicUpdateError::ChecksumMismatch {
target: route,
expected: expected_checksum,
actual: actual_checksum,
});
}
let incoming_ver: u64 = update.get_version();
let allow_downgrade: bool = update.get_allow_downgrade();
let res: Result<PageApplyCommit, DynamicUpdateError> =
self.with_state_mut(|state: &mut DynamicHubState| {
let is_new_route: bool = state
.pages
.get(&route)
.map(|stack: &Vec<DynamicSlotRecord>| stack.is_empty())
.unwrap_or(true);
let active_ver: u64 = state
.pages
.get(&route)
.and_then(|stack: &Vec<DynamicSlotRecord>| stack.last())
.map(|rec: &DynamicSlotRecord| rec.version)
.unwrap_or(0);
if !allow_downgrade && incoming_ver <= active_ver {
return Err(DynamicUpdateError::VersionRegression {
target: route.clone(),
current: active_ver,
incoming: incoming_ver,
});
}
let record: DynamicSlotRecord = DynamicSlotRecord {
version: incoming_ver,
title: update.title,
checksum: actual_checksum,
payload: DynamicPayload::Spec(update.spec),
};
state.pages.entry(route.clone()).or_default().push(record);
let page_sig: Signal<u64> = *state
.page_signals
.entry(route)
.or_insert_with(|| Signal::new_detached(0));
let mut tel: DynamicTelemetry = state.telemetry_signal.get_untracked();
tel.set_pages_applied(tel.get_pages_applied().saturating_add(1));
Ok((
page_sig,
state.routes_signal,
state.telemetry_signal,
tel,
is_new_route,
))
});
match res {
Ok((page_sig, routes_sig, tel_sig, tel, is_new_route)) => {
batch(|| {
let _: bool = page_sig.update(|v: &mut u64| *v = v.wrapping_add(1));
if is_new_route {
let _: bool = routes_sig.update(|v: &mut u64| *v = v.wrapping_add(1));
}
let _: bool = tel_sig.set(tel);
});
Ok(incoming_ver)
}
Err(err) => {
self.record_rejection();
Err(err)
}
}
}
/// Parses and applies a JSON-encoded page-level dynamic update manifest.
///
/// # Arguments
///
/// - `&Self` - Hub reference.
/// - `&str` - JSON string encoding a `DynamicPageUpdate`.
///
/// # Returns
///
/// - `Result<u64, DynamicUpdateError>` - Newly active page version on success.
pub fn apply_page_json(&self, json: &str) -> Result<u64, DynamicUpdateError> {
let update: DynamicPageUpdate = match DynamicPageUpdate::from_json(json) {
Ok(parsed) => parsed,
Err(err) => {
self.record_rejection();
return Err(err);
}
};
self.apply_page(update)
}
/// Hot-swaps a page route with a native Rust page builder closure.
///
/// # Arguments
///
/// - `&Self` - Hub reference.
/// - `String` - Target route path.
/// - `String` - Page title.
/// - `u64` - Monotonic page version number.
/// - `F` - Zero-context native Rust page builder closure.
///
/// # Returns
///
/// - `Result<u64, DynamicUpdateError>` - Newly active page version on success.
pub fn swap_page_builder<F>(
&self,
route: String,
title: String,
version: u64,
builder: F,
) -> Result<u64, DynamicUpdateError>
where
F: Fn() -> NodeId + 'static,
{
let normalized: String = normalize_dynamic_route(&route);
if normalized.is_empty() {
self.record_rejection();
return Err(DynamicUpdateError::EmptyTargetId);
}
let builder_rc: DynamicBuilderFn = Rc::new(builder);
let res: Result<PageApplyCommit, DynamicUpdateError> =
self.with_state_mut(|state: &mut DynamicHubState| {
let is_new_route: bool = state
.pages
.get(&normalized)
.map(|stack: &Vec<DynamicSlotRecord>| stack.is_empty())
.unwrap_or(true);
let active_ver: u64 = state
.pages
.get(&normalized)
.and_then(|stack: &Vec<DynamicSlotRecord>| stack.last())
.map(|rec: &DynamicSlotRecord| rec.version)
.unwrap_or(0);
if version <= active_ver {
return Err(DynamicUpdateError::VersionRegression {
target: normalized.clone(),
current: active_ver,
incoming: version,
});
}
let record: DynamicSlotRecord = DynamicSlotRecord {
version,
title,
checksum: 0,
payload: DynamicPayload::Native(builder_rc),
};
state
.pages
.entry(normalized.clone())
.or_default()
.push(record);
let page_sig: Signal<u64> = *state
.page_signals
.entry(normalized)
.or_insert_with(|| Signal::new_detached(0));
let mut tel: DynamicTelemetry = state.telemetry_signal.get_untracked();
tel.set_pages_applied(tel.get_pages_applied().saturating_add(1));
Ok((
page_sig,
state.routes_signal,
state.telemetry_signal,
tel,
is_new_route,
))
});
match res {
Ok((page_sig, routes_sig, tel_sig, tel, is_new_route)) => {
batch(|| {
let _: bool = page_sig.update(|v: &mut u64| *v = v.wrapping_add(1));
if is_new_route {
let _: bool = routes_sig.update(|v: &mut u64| *v = v.wrapping_add(1));
}
let _: bool = tel_sig.set(tel);
});
Ok(version)
}
Err(err) => {
self.record_rejection();
Err(err)
}
}
}
/// Rolls back a dynamically updated page to its previous revision (or `0` compiled fallback).
///
/// # Arguments
///
/// - `&Self` - Hub reference.
/// - `&str` - Target route path.
///
/// # Returns
///
/// - `Result<u64, DynamicUpdateError>` - Restored page version (`0` means fallback / removed).
pub fn rollback_page(&self, route: &str) -> Result<u64, DynamicUpdateError> {
let normalized: String = normalize_dynamic_route(route);
let res: Result<PageRollbackCommit, DynamicUpdateError> =
self.with_state_mut(|state: &mut DynamicHubState| {
let popped: bool = state
.pages
.get_mut(&normalized)
.and_then(|stack: &mut Vec<DynamicSlotRecord>| stack.pop())
.is_some();
if !popped {
return Err(DynamicUpdateError::NoHistoryToRollback(normalized.clone()));
}
let next_ver: u64 = state
.pages
.get(&normalized)
.and_then(|stack: &Vec<DynamicSlotRecord>| stack.last())
.map(|rec: &DynamicSlotRecord| rec.version)
.unwrap_or(0);
let route_removed: bool = next_ver == 0;
let page_sig: Signal<u64> = *state
.page_signals
.entry(normalized)
.or_insert_with(|| Signal::new_detached(0));
let mut tel: DynamicTelemetry = state.telemetry_signal.get_untracked();
tel.set_rollbacks(tel.get_rollbacks().saturating_add(1));
Ok((
next_ver,
page_sig,
state.routes_signal,
state.telemetry_signal,
tel,
route_removed,
))
});
let (next_ver, page_sig, routes_sig, tel_sig, tel, route_removed): PageRollbackCommit =
res?;
batch(|| {
let _: bool = page_sig.update(|v: &mut u64| *v = v.wrapping_add(1));
if route_removed {
let _: bool = routes_sig.update(|v: &mut u64| *v = v.wrapping_add(1));
}
let _: bool = tel_sig.set(tel);
});
Ok(next_ver)
}
/// Validates all component and page entries in `bundle` before committing them atomically in a single `batch`.
///
/// # Arguments
///
/// - `&Self` - Hub reference.
/// - `DynamicUpdateBundle` - Multi-target atomic release bundle.
///
/// # Returns
///
/// - `Result<DynamicTelemetry, DynamicUpdateError>` - Updated telemetry snapshot on full commit, or error with zero partial mutation.
pub fn apply_bundle(
&self,
bundle: DynamicUpdateBundle,
) -> Result<DynamicTelemetry, DynamicUpdateError> {
let validation: Result<BundleApplyCommit, DynamicUpdateError> =
self.with_state_mut(|state: &mut DynamicHubState| {
let mut staged_comp_vers: HashMap<String, u64> = HashMap::new();
for comp in bundle.components.iter() {
let id: String = comp.get_id().trim().to_string();
if id.is_empty() {
return Err(DynamicUpdateError::EmptyTargetId);
}
let actual: u64 = comp.get_spec().checksum();
let expected: u64 = comp.get_checksum();
if expected != 0 && expected != actual {
return Err(DynamicUpdateError::ChecksumMismatch {
target: id,
expected,
actual,
});
}
let cur: u64 = staged_comp_vers.get(&id).copied().unwrap_or_else(|| {
state
.components
.get(&id)
.and_then(|s: &Vec<DynamicSlotRecord>| s.last())
.map(|r: &DynamicSlotRecord| r.version)
.unwrap_or(0)
});
if !comp.get_allow_downgrade() && comp.get_version() <= cur {
return Err(DynamicUpdateError::VersionRegression {
target: id,
current: cur,
incoming: comp.get_version(),
});
}
staged_comp_vers.insert(id, comp.get_version());
}
let mut staged_page_vers: HashMap<String, u64> = HashMap::new();
for page in bundle.pages.iter() {
let route: String = normalize_dynamic_route(page.get_route());
if route.is_empty() {
return Err(DynamicUpdateError::EmptyTargetId);
}
let actual: u64 = page.get_spec().checksum();
let expected: u64 = page.get_checksum();
if expected != 0 && expected != actual {
return Err(DynamicUpdateError::ChecksumMismatch {
target: route,
expected,
actual,
});
}
let cur: u64 = staged_page_vers.get(&route).copied().unwrap_or_else(|| {
state
.pages
.get(&route)
.and_then(|s: &Vec<DynamicSlotRecord>| s.last())
.map(|r: &DynamicSlotRecord| r.version)
.unwrap_or(0)
});
if !page.get_allow_downgrade() && page.get_version() <= cur {
return Err(DynamicUpdateError::VersionRegression {
target: route,
current: cur,
incoming: page.get_version(),
});
}
staged_page_vers.insert(route, page.get_version());
}
let mut dirty_signals: Vec<Signal<u64>> =
Vec::with_capacity(bundle.components.len() + bundle.pages.len());
let mut tel: DynamicTelemetry = state.telemetry_signal.get_untracked();
for comp in bundle.components.into_iter() {
let id: String = comp.get_id().trim().to_string();
let digest: u64 = comp.get_spec().checksum();
let record: DynamicSlotRecord = DynamicSlotRecord {
version: comp.version,
title: String::new(),
checksum: digest,
payload: DynamicPayload::Spec(comp.spec),
};
state.components.entry(id.clone()).or_default().push(record);
let sig: Signal<u64> = *state
.component_signals
.entry(id)
.or_insert_with(|| Signal::new_detached(0));
dirty_signals.push(sig);
tel.set_components_applied(tel.get_components_applied().saturating_add(1));
}
let mut added_route: bool = false;
for page in bundle.pages.into_iter() {
let route: String = normalize_dynamic_route(page.get_route());
let is_new: bool = state
.pages
.get(&route)
.map(|s: &Vec<DynamicSlotRecord>| s.is_empty())
.unwrap_or(true);
if is_new {
added_route = true;
}
let digest: u64 = page.get_spec().checksum();
let record: DynamicSlotRecord = DynamicSlotRecord {
version: page.version,
title: page.title,
checksum: digest,
payload: DynamicPayload::Spec(page.spec),
};
state.pages.entry(route.clone()).or_default().push(record);
let sig: Signal<u64> = *state
.page_signals
.entry(route)
.or_insert_with(|| Signal::new_detached(0));
dirty_signals.push(sig);
tel.set_pages_applied(tel.get_pages_applied().saturating_add(1));
}
Ok((
dirty_signals,
added_route,
state.routes_signal,
state.telemetry_signal,
tel,
))
});
match validation {
Ok((dirty_signals, added_route, routes_sig, tel_sig, tel)) => {
batch(|| {
for sig in dirty_signals.into_iter() {
let _: bool = sig.update(|v: &mut u64| *v = v.wrapping_add(1));
}
if added_route {
let _: bool = routes_sig.update(|v: &mut u64| *v = v.wrapping_add(1));
}
let _: bool = tel_sig.set(tel);
});
Ok(tel)
}
Err(err) => {
self.record_rejection();
Err(err)
}
}
}
/// Parses and atomically applies a JSON-encoded `DynamicUpdateBundle` manifest.
///
/// # Arguments
///
/// - `&Self` - Hub reference.
/// - `&str` - JSON bundle manifest string.
///
/// # Returns
///
/// - `Result<DynamicTelemetry, DynamicUpdateError>` - Updated telemetry snapshot on success.
pub fn apply_bundle_json(&self, json: &str) -> Result<DynamicTelemetry, DynamicUpdateError> {
let bundle: DynamicUpdateBundle = match DynamicUpdateBundle::from_json(json) {
Ok(parsed) => parsed,
Err(err) => {
self.record_rejection();
return Err(err);
}
};
self.apply_bundle(bundle)
}
/// Registers an action callback invoked whenever a button inside a dynamically updated component or page is clicked.
///
/// # Arguments
///
/// - `&Self` - Hub reference.
/// - `F` - Action callback receiving `&DynamicActionEvent`.
pub fn on_action<F>(&self, handler: F)
where
F: FnMut(&DynamicActionEvent) + 'static,
{
let cb: DynamicActionCallback = Rc::new(RefCell::new(handler));
self.with_state_mut(|state: &mut DynamicHubState| {
state.action_handlers.push(cb);
});
}
/// Dispatches a `DynamicActionEvent` to all registered handlers and updates `last_action` + telemetry.
///
/// # Arguments
///
/// - `&Self` - Hub reference.
/// - `DynamicActionEvent` - Action event emitted by a dynamic control.
pub fn dispatch_action(&self, event: DynamicActionEvent) {
let (handlers, last_sig, tel_sig, next_tel): (
Vec<DynamicActionCallback>,
Signal<Option<DynamicActionEvent>>,
Signal<DynamicTelemetry>,
DynamicTelemetry,
) = self.with_state_mut(|state: &mut DynamicHubState| {
let mut tel: DynamicTelemetry = state.telemetry_signal.get_untracked();
tel.set_actions_dispatched(tel.get_actions_dispatched().saturating_add(1));
(
state.action_handlers.clone(),
state.last_action,
state.telemetry_signal,
tel,
)
});
batch(|| {
let _: bool = last_sig.set(Some(event.clone()));
let _: bool = tel_sig.set(next_tel);
});
for cb in handlers.into_iter() {
if let Ok(mut func) = cb.try_borrow_mut() {
func(&event);
}
}
}
/// Returns the dedicated reactive revision signal for component slot `id`.
///
/// # Arguments
///
/// - `&Self` - Hub reference.
/// - `&str` - Component slot identifier.
///
/// # Returns
///
/// - `Signal<u64>` - Surgical revision signal bumped only when `id` updates.
#[must_use]
pub fn component_revision_signal(&self, id: &str) -> Signal<u64> {
let key: String = id.trim().to_string();
self.with_state_mut(|state: &mut DynamicHubState| {
*state
.component_signals
.entry(key)
.or_insert_with(|| Signal::new_detached(0))
})
}
/// Returns the dedicated reactive revision signal for page `route`.
///
/// # Arguments
///
/// - `&Self` - Hub reference.
/// - `&str` - Target route path.
///
/// # Returns
///
/// - `Signal<u64>` - Surgical revision signal bumped only when `route` updates.
#[must_use]
pub fn page_revision_signal(&self, route: &str) -> Signal<u64> {
let key: String = normalize_dynamic_route(route);
self.with_state_mut(|state: &mut DynamicHubState| {
*state
.page_signals
.entry(key)
.or_insert_with(|| Signal::new_detached(0))
})
}
/// Returns the currently active dynamic version for component slot `id` (`0` means compiled fallback).
///
/// # Arguments
///
/// - `&Self` - Hub reference.
/// - `&str` - Component slot identifier.
///
/// # Returns
///
/// - `u64` - Active component version.
#[must_use]
pub fn component_version(&self, id: &str) -> u64 {
let key: &str = id.trim();
self.with_state(|state: &DynamicHubState| {
state
.components
.get(key)
.and_then(|stack: &Vec<DynamicSlotRecord>| stack.last())
.map(|rec: &DynamicSlotRecord| rec.version)
.unwrap_or(0)
})
}
/// Returns the number of stacked dynamic revisions retained for component slot `id`.
///
/// # Arguments
///
/// - `&Self` - Hub reference.
/// - `&str` - Component slot identifier.
///
/// # Returns
///
/// - `usize` - Number of revisions on the rollback stack.
#[must_use]
pub fn component_history_len(&self, id: &str) -> usize {
let key: &str = id.trim();
self.with_state(|state: &DynamicHubState| {
state
.components
.get(key)
.map(|stack: &Vec<DynamicSlotRecord>| stack.len())
.unwrap_or(0)
})
}
/// Returns the currently active dynamic version for page `route` (`0` means compiled fallback).
///
/// # Arguments
///
/// - `&Self` - Hub reference.
/// - `&str` - Page route path.
///
/// # Returns
///
/// - `u64` - Active page version.
#[must_use]
pub fn page_version(&self, route: &str) -> u64 {
let key: String = normalize_dynamic_route(route);
self.with_state(|state: &DynamicHubState| {
state
.pages
.get(&key)
.and_then(|stack: &Vec<DynamicSlotRecord>| stack.last())
.map(|rec: &DynamicSlotRecord| rec.version)
.unwrap_or(0)
})
}
/// Returns the active dynamic page title for `route` if a dynamic page is mounted for it.
///
/// # Arguments
///
/// - `&Self` - Hub reference.
/// - `&str` - Page route path.
///
/// # Returns
///
/// - `Option<String>` - Active dynamic page title if any.
#[must_use]
pub fn page_title(&self, route: &str) -> Option<String> {
let key: String = normalize_dynamic_route(route);
self.with_state(|state: &DynamicHubState| {
state
.pages
.get(&key)
.and_then(|stack: &Vec<DynamicSlotRecord>| stack.last())
.map(|rec: &DynamicSlotRecord| rec.title.clone())
})
}
/// Returns `true` when `route` currently has an active dynamic page override or injected page.
///
/// # Arguments
///
/// - `&Self` - Hub reference.
/// - `&str` - Page route path.
///
/// # Returns
///
/// - `bool` - True when a dynamic page payload is active for `route`.
#[must_use]
pub fn has_dynamic_page(&self, route: &str) -> bool {
self.page_version(route) > 0
}
/// Returns the sorted list of all routes currently carrying active dynamic page payloads.
///
/// # Arguments
///
/// - `&Self` - Hub reference.
///
/// # Returns
///
/// - `Vec<String>` - Sorted active dynamic route paths.
#[must_use]
pub fn registered_routes(&self) -> Vec<String> {
self.with_state(|state: &DynamicHubState| {
let mut routes: Vec<String> = state
.pages
.iter()
.filter(|(_, stack): &(&String, &Vec<DynamicSlotRecord>)| !stack.is_empty())
.map(|(route, _): (&String, &Vec<DynamicSlotRecord>)| route.clone())
.collect();
routes.sort();
routes
})
}
/// Returns the reactive signal bumped whenever dynamic routes are added or removed.
///
/// # Arguments
///
/// - `&Self` - Hub reference.
///
/// # Returns
///
/// - `Signal<u64>` - Reactive route-set revision signal.
#[must_use]
pub fn routes_signal(&self) -> Signal<u64> {
let Self { inner } = self;
inner
.try_borrow()
.map(|state: Ref<'_, DynamicHubState>| state.routes_signal)
.unwrap_or_else(|_| Signal::new_detached(0))
}
/// Returns the reactive telemetry snapshot signal.
///
/// # Arguments
///
/// - `&Self` - Hub reference.
///
/// # Returns
///
/// - `Signal<DynamicTelemetry>` - Reactive dynamic update telemetry signal.
#[must_use]
pub fn telemetry(&self) -> Signal<DynamicTelemetry> {
let Self { inner } = self;
inner
.try_borrow()
.map(|state: Ref<'_, DynamicHubState>| state.telemetry_signal)
.unwrap_or_else(|_| Signal::new_detached(DynamicTelemetry::default()))
}
/// Returns the reactive signal storing the most recently dispatched `DynamicActionEvent`.
///
/// # Arguments
///
/// - `&Self` - Hub reference.
///
/// # Returns
///
/// - `Signal<Option<DynamicActionEvent>>` - Reactive latest action signal.
#[must_use]
pub fn last_action(&self) -> Signal<Option<DynamicActionEvent>> {
let Self { inner } = self;
inner
.try_borrow()
.map(|state: Ref<'_, DynamicHubState>| state.last_action)
.unwrap_or_else(|_| Signal::new_detached(None))
}
/// Mounts the active dynamic payload for component slot `id`, or executes `fallback` if none is active.
///
/// # Arguments
///
/// - `&Self` - Hub reference.
/// - `&str` - Component slot identifier.
/// - `&DynamicBuilderFn` - Compiled fallback builder closure.
///
/// # Returns
///
/// - `NodeId` - Mounted native scene node handle.
#[must_use]
pub fn mount_component_or_fallback(&self, id: &str, fallback: &DynamicBuilderFn) -> NodeId {
let key: String = id.trim().to_string();
let payload_opt: Option<DynamicPayload> = self.with_state(|state: &DynamicHubState| {
state
.components
.get(&key)
.and_then(|stack: &Vec<DynamicSlotRecord>| stack.last())
.map(|rec: &DynamicSlotRecord| rec.payload.clone())
});
match payload_opt {
Some(DynamicPayload::Spec(spec)) => mount_dynamic_spec(&spec, &key, self),
Some(DynamicPayload::Native(builder)) => builder(),
None => fallback(),
}
}
/// Mounts the active dynamic payload for page `route`, or executes `fallback` if none is active.
///
/// # Arguments
///
/// - `&Self` - Hub reference.
/// - `&str` - Target route path.
/// - `&DynamicBuilderFn` - Compiled fallback page builder closure.
///
/// # Returns
///
/// - `NodeId` - Mounted native page node handle.
#[must_use]
pub fn mount_page_or_fallback(&self, route: &str, fallback: &DynamicBuilderFn) -> NodeId {
let key: String = normalize_dynamic_route(route);
let payload_opt: Option<DynamicPayload> = self.with_state(|state: &DynamicHubState| {
state
.pages
.get(&key)
.and_then(|stack: &Vec<DynamicSlotRecord>| stack.last())
.map(|rec: &DynamicSlotRecord| rec.payload.clone())
});
match payload_opt {
Some(DynamicPayload::Spec(spec)) => mount_dynamic_spec(&spec, &key, self),
Some(DynamicPayload::Native(builder)) => builder(),
None => fallback(),
}
}
/// Increments the rejected-update telemetry counter safely outside any active state borrow.
///
/// # Arguments
///
/// - `&Self` - Hub reference.
fn record_rejection(&self) {
let tel_sig: Signal<DynamicTelemetry> = self.telemetry();
let mut next_tel: DynamicTelemetry = tel_sig.get_untracked();
next_tel.set_rejected(next_tel.get_rejected().saturating_add(1));
let _: bool = tel_sig.set(next_tel);
}
/// Executes a read-only closure on the internal `DynamicHubState` via safe `try_borrow`.
///
/// # Arguments
///
/// - `&Self` - Hub reference.
/// - `F` - Reader closure.
///
/// # Returns
///
/// - `R` - Closure return value or `R::default()` if re-entrantly borrowed.
fn with_state<F, R>(&self, operation: F) -> R
where
F: FnOnce(&DynamicHubState) -> R,
R: Default,
{
let Self { inner } = self;
match inner.try_borrow() {
Ok(guard) => operation(&guard),
Err(_) => R::default(),
}
}
/// Executes a mutable closure on the internal `DynamicHubState` via safe `try_borrow_mut`.
///
/// # Arguments
///
/// - `&Self` - Hub reference.
/// - `F` - Mutator closure.
///
/// # Returns
///
/// - `R` - Closure return value.
fn with_state_mut<F, R>(&self, operation: F) -> R
where
F: FnOnce(&mut DynamicHubState) -> R,
{
let Self { inner } = self;
if let Ok(mut guard) = inner.try_borrow_mut() {
return operation(&mut guard);
}
let mut fallback: DynamicHubState = DynamicHubState {
components: HashMap::new(),
component_signals: HashMap::new(),
pages: HashMap::new(),
page_signals: HashMap::new(),
routes_signal: Signal::new_detached(0),
telemetry_signal: Signal::new_detached(DynamicTelemetry::default()),
last_action: Signal::new_detached(None),
action_handlers: Vec::new(),
};
operation(&mut fallback)
}
}
/// `Mountable` implementation mounting a surgically updatable component slot.
impl Mountable for DynamicComponentSlot {
/// Mounts the host container and subscribes ONLY to this slot's dedicated revision signal.
///
/// # Arguments
///
/// - `Self` - Component slot descriptor.
/// - `&mut BuildContext` - Active build context.
///
/// # Returns
///
/// - `NodeId` - Mounted slot host handle.
fn mount(self, ctx: &mut BuildContext) -> NodeId {
let host_style: Style = self.get_style();
let Self {
id, fallback, hub, ..
} = self;
let active_hub: DynamicUpdateHub = hub.unwrap_or_else(|| ctx.get_dynamic_hub().clone());
let rev_sig: Signal<u64> = active_hub.component_revision_signal(&id);
let effective_style: Style = if host_style == Style::empty() {
Style::empty().column().width(Length::Percent(100.0))
} else {
host_style
};
let host: NodeId = ctx.view(effective_style);
let safe_sig: Signal<SafeAreaInsets> = ctx.get_safe_area();
ctx.bind_children(host, move || {
let _: u64 = rev_sig.get();
let mounted: NodeId = active_hub.mount_component_or_fallback(&id, &fallback);
if id == WASM_GLOBAL_ROOT_SLOT && active_hub.component_version(&id) > 0 {
let safe: SafeAreaInsets = safe_sig.get();
let mut sctx: BuildContext = current_build_context();
let scroller: NodeId = sctx.scroll_view(
Style::empty()
.column()
.width(Length::Percent(100.0))
.height(Length::Percent(100.0))
.align(AlignItems::Center)
.background(Color::hex(0xF8FAFC))
.padding(Edges::new(
safe.get_top() + 16.0,
safe.get_right() + 16.0,
safe.get_bottom() + 24.0,
safe.get_left() + 16.0,
)),
);
let container: NodeId = sctx.view(
Style::empty()
.column()
.width(Length::Percent(100.0))
.max_width(Length::Px(1040.0)),
);
sctx.append(container, mounted);
sctx.append(scroller, container);
vec![scroller]
} else {
vec![mounted]
}
});
host
}
}
/// `Mountable` implementation mounting a surgically updatable page slot for a fixed route.
impl Mountable for DynamicPageSlot {
/// Mounts the page container and subscribes ONLY to this route's dedicated revision signal.
///
/// # Arguments
///
/// - `Self` - Page slot descriptor.
/// - `&mut BuildContext` - Active build context.
///
/// # Returns
///
/// - `NodeId` - Mounted page slot host handle.
fn mount(self, ctx: &mut BuildContext) -> NodeId {
let host_style: Style = self.get_style();
let Self {
route,
fallback,
hub,
..
} = self;
let normalized: String = normalize_dynamic_route(&route);
let active_hub: DynamicUpdateHub = hub.unwrap_or_else(|| ctx.get_dynamic_hub().clone());
let rev_sig: Signal<u64> = active_hub.page_revision_signal(&normalized);
let effective_style: Style = if host_style == Style::empty() {
Style::empty().column().width(Length::Percent(100.0))
} else {
host_style
};
let host: NodeId = ctx.view(effective_style);
ctx.bind_children(host, move || {
let _: u64 = rev_sig.get();
vec![active_hub.mount_page_or_fallback(&normalized, &fallback)]
});
host
}
}
/// `Mountable` implementation mounting a reactive route-driven dynamic page outlet.
impl Mountable for DynamicPageOutlet {
/// Mounts a dynamic route outlet reacting to both route switches and live page-level updates.
///
/// # Arguments
///
/// - `Self` - Page outlet descriptor.
/// - `&mut BuildContext` - Active build context.
///
/// # Returns
///
/// - `NodeId` - Mounted outlet host handle.
fn mount(self, ctx: &mut BuildContext) -> NodeId {
let route_sig: Signal<String> = self.get_route();
let host_style: Style = self.get_style();
let Self { fallback, hub, .. } = self;
let active_hub: DynamicUpdateHub = hub.unwrap_or_else(|| ctx.get_dynamic_hub().clone());
let effective_style: Style = if host_style == Style::empty() {
Style::empty().column().width(Length::Percent(100.0))
} else {
host_style
};
let host: NodeId = ctx.view(effective_style);
let scene_for_anim: SceneHandle = ctx.get_scene().clone();
let prev_route_cell: Rc<RefCell<Option<String>>> = Rc::new(RefCell::new(None));
ctx.bind_children(host, move || {
let active_route: String = normalize_dynamic_route(&route_sig.get());
let page_rev_sig: Signal<u64> = active_hub.page_revision_signal(&active_route);
let _: u64 = page_rev_sig.get();
let fallback_c: DynamicRouteFallbackFn = fallback.clone();
let route_for_fb: String = active_route.clone();
let fb: DynamicBuilderFn = Rc::new(move || fallback_c(&route_for_fb));
let page_node: NodeId = active_hub.mount_page_or_fallback(&active_route, &fb);
let should_animate: bool = match prev_route_cell.try_borrow_mut() {
Ok(mut slot) => {
let changed: bool = slot
.as_deref()
.map(|prev: &str| prev != active_route.as_str())
.unwrap_or(false);
*slot = Some(active_route.clone());
changed
}
Err(_) => false,
};
if should_animate {
scene_for_anim.start_transition(NodeTransition::route_enter(page_node));
}
vec![page_node]
});
host
}
}