@c9up/orbit 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/Cargo.lock +146 -0
  2. package/Cargo.toml +16 -0
  3. package/LICENSE +21 -0
  4. package/README.md +314 -2
  5. package/android/orbit.cmake +31 -0
  6. package/android/src/main/cpp/NativeOrbit.cpp +309 -0
  7. package/android/src/main/cpp/NativeOrbit.h +35 -0
  8. package/android/src/main/cpp/orbit_host.h +34 -0
  9. package/android/src/main/java/com/c9up/orbit/OrbitEffects.kt +286 -0
  10. package/android/src/main/java/com/c9up/orbit/OrbitHost.kt +258 -0
  11. package/android/src/main/java/com/c9up/orbit/OrbitImage.kt +346 -0
  12. package/android/src/main/java/com/c9up/orbit/OrbitInput.kt +145 -0
  13. package/android/src/main/java/com/c9up/orbit/OrbitPress.kt +110 -0
  14. package/android/src/main/java/com/c9up/orbit/OrbitVector.kt +115 -0
  15. package/android/src/main/java/com/c9up/orbit/OrbitViews.kt +362 -0
  16. package/crates/orbit-host/Cargo.toml +14 -0
  17. package/crates/orbit-host/src/gesture.rs +561 -0
  18. package/crates/orbit-host/src/lib.rs +1608 -0
  19. package/crates/orbit-host/src/motion.rs +328 -0
  20. package/crates/orbit-host/src/vector.rs +917 -0
  21. package/dist/color.d.ts +10 -0
  22. package/dist/color.d.ts.map +1 -0
  23. package/dist/color.js +62 -0
  24. package/dist/color.js.map +1 -0
  25. package/dist/commit.d.ts +45 -0
  26. package/dist/commit.d.ts.map +1 -0
  27. package/dist/commit.js +172 -0
  28. package/dist/commit.js.map +1 -0
  29. package/dist/errors.d.ts +42 -0
  30. package/dist/errors.d.ts.map +1 -0
  31. package/dist/errors.js +15 -0
  32. package/dist/errors.js.map +1 -0
  33. package/dist/host.d.ts +49 -0
  34. package/dist/host.d.ts.map +1 -0
  35. package/dist/host.js +18 -0
  36. package/dist/host.js.map +1 -0
  37. package/dist/index.d.ts +29 -0
  38. package/dist/index.d.ts.map +1 -0
  39. package/dist/index.js +29 -0
  40. package/dist/index.js.map +1 -0
  41. package/dist/motion.d.ts +18 -0
  42. package/dist/motion.d.ts.map +1 -0
  43. package/dist/motion.js +66 -0
  44. package/dist/motion.js.map +1 -0
  45. package/dist/node.d.ts +46 -0
  46. package/dist/node.d.ts.map +1 -0
  47. package/dist/node.js +110 -0
  48. package/dist/node.js.map +1 -0
  49. package/dist/pages.d.ts +56 -0
  50. package/dist/pages.d.ts.map +1 -0
  51. package/dist/pages.js +157 -0
  52. package/dist/pages.js.map +1 -0
  53. package/dist/react-native/index.d.ts +25 -0
  54. package/dist/react-native/index.d.ts.map +1 -0
  55. package/dist/react-native/index.js +43 -0
  56. package/dist/react-native/index.js.map +1 -0
  57. package/dist/server.d.ts +85 -0
  58. package/dist/server.d.ts.map +1 -0
  59. package/dist/server.js +282 -0
  60. package/dist/server.js.map +1 -0
  61. package/dist/stack.d.ts +117 -0
  62. package/dist/stack.d.ts.map +1 -0
  63. package/dist/stack.js +299 -0
  64. package/dist/stack.js.map +1 -0
  65. package/dist/styles.d.ts +138 -0
  66. package/dist/styles.d.ts.map +1 -0
  67. package/dist/styles.js +920 -0
  68. package/dist/styles.js.map +1 -0
  69. package/dist/template.d.ts +27 -0
  70. package/dist/template.d.ts.map +1 -0
  71. package/dist/template.js +1392 -0
  72. package/dist/template.js.map +1 -0
  73. package/dist/url.d.ts +45 -0
  74. package/dist/url.d.ts.map +1 -0
  75. package/dist/url.js +302 -0
  76. package/dist/url.js.map +1 -0
  77. package/package.json +90 -3
  78. package/scripts/build-android.sh +27 -0
  79. package/scripts/test-styles.mjs +31 -0
  80. package/specs/NativeOrbit.ts +34 -0
  81. package/src/color.ts +73 -0
  82. package/src/commit.ts +206 -0
  83. package/src/errors.ts +48 -0
  84. package/src/host.ts +92 -0
  85. package/src/index.ts +60 -0
  86. package/src/motion.ts +86 -0
  87. package/src/node.ts +133 -0
  88. package/src/pages.ts +210 -0
  89. package/src/react-native/index.ts +76 -0
  90. package/src/react-native/react-native.d.ts +31 -0
  91. package/src/server.ts +359 -0
  92. package/src/stack.ts +434 -0
  93. package/src/styles.ts +1024 -0
  94. package/src/template.ts +1657 -0
  95. package/src/url.ts +326 -0
@@ -0,0 +1,1608 @@
1
+ //! orbit-host — orbit's native host under aurora.
2
+ //!
3
+ //! JS (aurora's native renderer) commits a batch of tree operations as JSON:
4
+ //! ["c", tag, viewName, props] create a node
5
+ //! ["u", tag, props] merge a props patch
6
+ //! ["k", tag, [childTags]] replace a node's children
7
+ //! ["r", tag] set the root
8
+ //! The host keeps the tree, lays it out with taffy (text measured by the
9
+ //! platform through a callback), diffs it against what is mounted, and returns
10
+ //! a compact binary list of mount operations for the platform layer (Kotlin)
11
+ //! to apply to real views. Nodes no longer reachable from the root are dropped
12
+ //! and their tags reported back so JS can forget them.
13
+
14
+ use std::cell::RefCell;
15
+ use std::collections::hash_map::DefaultHasher;
16
+ use std::collections::{HashMap, HashSet};
17
+ use std::hash::{Hash, Hasher};
18
+ use std::time::Instant;
19
+
20
+ pub mod gesture;
21
+ pub mod motion;
22
+ pub mod vector;
23
+
24
+ use serde_json::{Map, Value};
25
+ use taffy::prelude::*;
26
+
27
+ /// Measures encoded text (see `encode_text`) under a maximum width, in dp.
28
+ /// Returns the width and height as the high and low 32 bits of f32 bit patterns.
29
+ pub type MeasureFn = extern "C" fn(spans: *const u8, len: usize, max_width: f32) -> u64;
30
+
31
+ // Mount operation codes, shared with OrbitHost.kt.
32
+ const OP_CREATE: u8 = 1;
33
+ const OP_DELETE: u8 = 2;
34
+ const OP_CHILDREN: u8 = 3;
35
+ const OP_FRAME: u8 = 4;
36
+ const OP_VIEW_STYLE: u8 = 5;
37
+ const OP_TEXT: u8 = 6;
38
+ const OP_ROOT: u8 = 7;
39
+ const OP_INPUT: u8 = 8;
40
+ const OP_IMAGE: u8 = 9;
41
+ const OP_EFFECTS: u8 = 10;
42
+ const OP_VECTOR: u8 = 11;
43
+
44
+ const KIND_VIEW: u8 = 0;
45
+ const KIND_TEXT: u8 = 1;
46
+ const KIND_SCROLL: u8 = 2;
47
+ const KIND_INPUT: u8 = 3;
48
+ const KIND_IMAGE: u8 = 4;
49
+ const KIND_VECTOR: u8 = 5;
50
+
51
+ #[derive(Clone, Copy, PartialEq, Eq, Debug)]
52
+ enum Kind {
53
+ View,
54
+ Scroll,
55
+ Text,
56
+ RawText,
57
+ VirtualText,
58
+ /// A native text field: a layout leaf the platform measures by its font.
59
+ TextInput,
60
+ /// An image: a layout leaf sized by its style alone, decoded by the platform.
61
+ Image,
62
+ /// An `<svg>`: a layout leaf sized by its style, drawn from `vector.rs`'s paths.
63
+ Vector,
64
+ }
65
+
66
+ impl Kind {
67
+ fn of(view_name: &str) -> Kind {
68
+ match view_name {
69
+ "RCTText" | "RCTParagraph" => Kind::Text,
70
+ "RCTRawText" => Kind::RawText,
71
+ "RCTVirtualText" => Kind::VirtualText,
72
+ "RCTScrollView" => Kind::Scroll,
73
+ "OrbitTextInput" => Kind::TextInput,
74
+ "OrbitImage" => Kind::Image,
75
+ "OrbitVector" => Kind::Vector,
76
+ _ => Kind::View,
77
+ }
78
+ }
79
+ fn is_layout(self) -> bool {
80
+ matches!(
81
+ self,
82
+ Kind::View | Kind::Scroll | Kind::Text | Kind::TextInput | Kind::Image | Kind::Vector
83
+ )
84
+ }
85
+ }
86
+
87
+ #[derive(Clone, Default, PartialEq, Debug)]
88
+ struct TextStyle {
89
+ color: Option<i32>,
90
+ size: Option<f32>,
91
+ /// The CSS font weight, 100..=900.
92
+ weight: Option<u16>,
93
+ italic: Option<bool>,
94
+ line_height: Option<f32>,
95
+ align: Option<u8>,
96
+ }
97
+
98
+ impl TextStyle {
99
+ fn over(&self, base: &TextStyle) -> TextStyle {
100
+ TextStyle {
101
+ color: self.color.or(base.color),
102
+ size: self.size.or(base.size),
103
+ weight: self.weight.or(base.weight),
104
+ italic: self.italic.or(base.italic),
105
+ line_height: self.line_height.or(base.line_height),
106
+ align: self.align.or(base.align),
107
+ }
108
+ }
109
+ }
110
+
111
+ #[derive(Clone, Default, PartialEq, Debug)]
112
+ struct Visual {
113
+ background: Option<i32>,
114
+ border_color: Option<i32>,
115
+ border_width: f32,
116
+ radius: f32,
117
+ opacity: f32,
118
+ }
119
+
120
+ struct Node {
121
+ kind: Kind,
122
+ props: Map<String, Value>,
123
+ taffy: Option<NodeId>,
124
+ children: Vec<i32>,
125
+ text: String,
126
+ /// A vector node's drawing, encoded when its `vector` prop is set.
127
+ vector: Vec<u8>,
128
+ }
129
+
130
+ /// What a view draws beyond its box: a CSS box shadow, a backdrop blur, and
131
+ /// whether it clips its children (`overflow: hidden`).
132
+ #[derive(Clone, Default, PartialEq, Debug)]
133
+ struct Effects {
134
+ shadow_x: f32,
135
+ shadow_y: f32,
136
+ shadow_blur: f32,
137
+ shadow_spread: f32,
138
+ shadow_color: i32,
139
+ backdrop_blur: f32,
140
+ clip: bool,
141
+ }
142
+
143
+ #[derive(Default)]
144
+ struct Mounted {
145
+ frame: [f32; 4],
146
+ visual: Option<Visual>,
147
+ effects: Option<Effects>,
148
+ text: Vec<u8>,
149
+ children: Vec<i32>,
150
+ }
151
+
152
+ #[derive(Default, Debug)]
153
+ pub struct CommitInfo {
154
+ pub deleted: Vec<i32>,
155
+ pub parse_us: u128,
156
+ pub layout_us: u128,
157
+ pub diff_us: u128,
158
+ pub measures: u32,
159
+ pub nodes: usize,
160
+ }
161
+
162
+ pub struct Host {
163
+ nodes: HashMap<i32, Node>,
164
+ parent: HashMap<i32, i32>,
165
+ tree: TaffyTree<i32>,
166
+ root: Option<i32>,
167
+ mounted_root: Option<i32>,
168
+ mounted: HashMap<i32, Mounted>,
169
+ spans: HashMap<i32, Vec<u8>>,
170
+ measure_cache: HashMap<(u64, u32), (f32, f32)>,
171
+ viewport: (f32, f32),
172
+ measure: Option<MeasureFn>,
173
+ }
174
+
175
+ impl Default for Host {
176
+ fn default() -> Self {
177
+ Host {
178
+ nodes: HashMap::new(),
179
+ parent: HashMap::new(),
180
+ tree: TaffyTree::new(),
181
+ root: None,
182
+ mounted_root: None,
183
+ mounted: HashMap::new(),
184
+ spans: HashMap::new(),
185
+ measure_cache: HashMap::new(),
186
+ viewport: (400.0, 800.0),
187
+ measure: None,
188
+ }
189
+ }
190
+ }
191
+
192
+ // ---------------------------------------------------------------- props -> style
193
+
194
+ fn num(v: &Value) -> Option<f32> {
195
+ match v {
196
+ Value::Number(n) => n.as_f64().map(|f| f as f32),
197
+ Value::String(s) => s.trim_end_matches("px").parse::<f32>().ok(),
198
+ _ => None,
199
+ }
200
+ }
201
+
202
+ fn color(v: &Value) -> Option<i32> {
203
+ v.as_i64().map(|n| n as i32)
204
+ }
205
+
206
+ fn dimension(v: &Value) -> Dimension {
207
+ match v {
208
+ Value::String(s) if s.ends_with('%') => s
209
+ .trim_end_matches('%')
210
+ .parse::<f32>()
211
+ .map(|p| Dimension::percent(p / 100.0))
212
+ .unwrap_or(Dimension::auto()),
213
+ Value::String(s) if s == "auto" => Dimension::auto(),
214
+ _ => num(v).map(Dimension::length).unwrap_or(Dimension::auto()),
215
+ }
216
+ }
217
+
218
+ fn length_percentage(v: &Value) -> LengthPercentage {
219
+ match v {
220
+ Value::String(s) if s.ends_with('%') => s
221
+ .trim_end_matches('%')
222
+ .parse::<f32>()
223
+ .map(|p| LengthPercentage::percent(p / 100.0))
224
+ .unwrap_or(LengthPercentage::length(0.0)),
225
+ _ => LengthPercentage::length(num(v).unwrap_or(0.0)),
226
+ }
227
+ }
228
+
229
+ fn length_percentage_auto(v: &Value) -> LengthPercentageAuto {
230
+ match v {
231
+ Value::String(s) if s == "auto" => LengthPercentageAuto::auto(),
232
+ Value::String(s) if s.ends_with('%') => s
233
+ .trim_end_matches('%')
234
+ .parse::<f32>()
235
+ .map(|p| LengthPercentageAuto::percent(p / 100.0))
236
+ .unwrap_or(LengthPercentageAuto::length(0.0)),
237
+ _ => LengthPercentageAuto::length(num(v).unwrap_or(0.0)),
238
+ }
239
+ }
240
+
241
+ fn align(v: &Value) -> Option<AlignItems> {
242
+ match v.as_str()? {
243
+ "flex-start" | "start" => Some(AlignItems::FlexStart),
244
+ "flex-end" | "end" => Some(AlignItems::FlexEnd),
245
+ "center" => Some(AlignItems::Center),
246
+ "stretch" => Some(AlignItems::Stretch),
247
+ "baseline" => Some(AlignItems::Baseline),
248
+ _ => None,
249
+ }
250
+ }
251
+
252
+ fn justify(v: &Value) -> Option<JustifyContent> {
253
+ match v.as_str()? {
254
+ "flex-start" | "start" => Some(JustifyContent::FlexStart),
255
+ "flex-end" | "end" => Some(JustifyContent::FlexEnd),
256
+ "center" => Some(JustifyContent::Center),
257
+ "space-between" => Some(JustifyContent::SpaceBetween),
258
+ "space-around" => Some(JustifyContent::SpaceAround),
259
+ "space-evenly" => Some(JustifyContent::SpaceEvenly),
260
+ _ => None,
261
+ }
262
+ }
263
+
264
+ /// Four-sided shorthand in React Native's precedence: side > axis > all.
265
+ fn sides<T: Copy>(
266
+ props: &Map<String, Value>,
267
+ prefix: &str,
268
+ suffix: &str,
269
+ zero: T,
270
+ parse: fn(&Value) -> T,
271
+ ) -> Rect<T> {
272
+ let get = |name: &str| props.get(&format!("{prefix}{name}{suffix}")).map(parse);
273
+ let all = get("").unwrap_or(zero);
274
+ let horizontal = get("Horizontal").unwrap_or(all);
275
+ let vertical = get("Vertical").unwrap_or(all);
276
+ Rect {
277
+ left: get("Left").or_else(|| get("Start")).unwrap_or(horizontal),
278
+ right: get("Right").or_else(|| get("End")).unwrap_or(horizontal),
279
+ top: get("Top").unwrap_or(vertical),
280
+ bottom: get("Bottom").unwrap_or(vertical),
281
+ }
282
+ }
283
+
284
+ fn style_of(props: &Map<String, Value>) -> Style {
285
+ // React Native's defaults, not CSS's: column, no shrink.
286
+ let mut s = Style {
287
+ flex_direction: FlexDirection::Column,
288
+ flex_shrink: 0.0,
289
+ ..Style::default()
290
+ };
291
+ if let Some(v) = props.get("flexDirection").and_then(Value::as_str) {
292
+ s.flex_direction = match v {
293
+ "row" => FlexDirection::Row,
294
+ "row-reverse" => FlexDirection::RowReverse,
295
+ "column-reverse" => FlexDirection::ColumnReverse,
296
+ _ => FlexDirection::Column,
297
+ };
298
+ }
299
+ if props.get("flexWrap").and_then(Value::as_str) == Some("wrap") {
300
+ s.flex_wrap = FlexWrap::Wrap;
301
+ }
302
+ if let Some(f) = props.get("flex").and_then(num) {
303
+ if f > 0.0 {
304
+ s.flex_grow = f;
305
+ s.flex_shrink = 1.0;
306
+ s.flex_basis = Dimension::length(0.0);
307
+ }
308
+ }
309
+ if let Some(f) = props.get("flexGrow").and_then(num) {
310
+ s.flex_grow = f;
311
+ }
312
+ if let Some(f) = props.get("flexShrink").and_then(num) {
313
+ s.flex_shrink = f;
314
+ }
315
+ if let Some(v) = props.get("flexBasis") {
316
+ s.flex_basis = dimension(v);
317
+ }
318
+ s.align_items = props.get("alignItems").and_then(align);
319
+ s.align_self = props.get("alignSelf").and_then(align);
320
+ s.justify_content = props.get("justifyContent").and_then(justify);
321
+ for (key, slot) in [
322
+ ("width", &mut s.size.width),
323
+ ("height", &mut s.size.height),
324
+ ("minWidth", &mut s.min_size.width),
325
+ ("minHeight", &mut s.min_size.height),
326
+ ("maxWidth", &mut s.max_size.width),
327
+ ("maxHeight", &mut s.max_size.height),
328
+ ] {
329
+ if let Some(v) = props.get(key) {
330
+ *slot = dimension(v);
331
+ }
332
+ }
333
+ s.padding = sides(
334
+ props,
335
+ "padding",
336
+ "",
337
+ LengthPercentage::length(0.0),
338
+ length_percentage,
339
+ );
340
+ s.margin = sides(
341
+ props,
342
+ "margin",
343
+ "",
344
+ LengthPercentageAuto::length(0.0),
345
+ length_percentage_auto,
346
+ );
347
+ s.border = sides(
348
+ props,
349
+ "border",
350
+ "Width",
351
+ LengthPercentage::length(0.0),
352
+ length_percentage,
353
+ );
354
+ let gap = props
355
+ .get("gap")
356
+ .map(length_percentage)
357
+ .unwrap_or(LengthPercentage::length(0.0));
358
+ s.gap = Size {
359
+ width: props.get("columnGap").map(length_percentage).unwrap_or(gap),
360
+ height: props.get("rowGap").map(length_percentage).unwrap_or(gap),
361
+ };
362
+ if props.get("position").and_then(Value::as_str) == Some("absolute") {
363
+ s.position = Position::Absolute;
364
+ }
365
+ s.inset = Rect {
366
+ left: props
367
+ .get("left")
368
+ .map(length_percentage_auto)
369
+ .unwrap_or(LengthPercentageAuto::auto()),
370
+ right: props
371
+ .get("right")
372
+ .map(length_percentage_auto)
373
+ .unwrap_or(LengthPercentageAuto::auto()),
374
+ top: props
375
+ .get("top")
376
+ .map(length_percentage_auto)
377
+ .unwrap_or(LengthPercentageAuto::auto()),
378
+ bottom: props
379
+ .get("bottom")
380
+ .map(length_percentage_auto)
381
+ .unwrap_or(LengthPercentageAuto::auto()),
382
+ };
383
+ s.aspect_ratio = props.get("aspectRatio").and_then(num);
384
+ if props.get("display").and_then(Value::as_str) == Some("none") {
385
+ s.display = Display::None;
386
+ }
387
+ s
388
+ }
389
+
390
+ /// A scroll view does not grow to its content: its content child does, and
391
+ /// the platform scrolls that child inside the view's frame.
392
+ fn style_for(kind: Kind, props: &Map<String, Value>) -> Style {
393
+ let mut s = style_of(props);
394
+ if kind == Kind::Scroll {
395
+ s.overflow = taffy::geometry::Point {
396
+ x: taffy::style::Overflow::Visible,
397
+ y: taffy::style::Overflow::Scroll,
398
+ };
399
+ s.scrollbar_width = 0.0;
400
+ }
401
+ s
402
+ }
403
+
404
+ fn visual_of(props: &Map<String, Value>) -> Visual {
405
+ Visual {
406
+ background: props.get("backgroundColor").and_then(color),
407
+ border_color: props.get("borderColor").and_then(color),
408
+ border_width: props.get("borderWidth").and_then(num).unwrap_or(0.0),
409
+ radius: props.get("borderRadius").and_then(num).unwrap_or(0.0),
410
+ opacity: props.get("opacity").and_then(num).unwrap_or(1.0),
411
+ }
412
+ }
413
+
414
+ /// The gestures a node's handlers ask for (see `gesture`).
415
+ fn gesture_flags(props: &Map<String, Value>) -> u8 {
416
+ props
417
+ .get("gestures")
418
+ .and_then(Value::as_u64)
419
+ .map(|n| (n & 0xff) as u8)
420
+ .unwrap_or(0)
421
+ }
422
+
423
+ fn effects_of(props: &Map<String, Value>) -> Effects {
424
+ let length = |key: &str| props.get(key).and_then(num).unwrap_or(0.0);
425
+ Effects {
426
+ shadow_x: length("shadowX"),
427
+ shadow_y: length("shadowY"),
428
+ shadow_blur: length("shadowBlur").max(0.0),
429
+ shadow_spread: length("shadowSpread"),
430
+ shadow_color: props.get("shadowColor").and_then(color).unwrap_or(0),
431
+ backdrop_blur: length("backdropBlur").max(0.0),
432
+ clip: props.get("overflow").and_then(Value::as_str) == Some("hidden"),
433
+ }
434
+ }
435
+
436
+ fn text_style_of(props: &Map<String, Value>) -> TextStyle {
437
+ TextStyle {
438
+ color: props.get("color").and_then(color),
439
+ size: props.get("fontSize").and_then(num),
440
+ weight: props.get("fontWeight").and_then(|w| match w {
441
+ Value::String(s) if s == "bold" => Some(700),
442
+ Value::String(s) if s == "normal" => Some(400),
443
+ Value::String(s) => s.parse::<u16>().ok(),
444
+ Value::Number(n) => n.as_u64().map(|n| n as u16),
445
+ _ => None,
446
+ }),
447
+ italic: props
448
+ .get("fontStyle")
449
+ .and_then(Value::as_str)
450
+ .map(|s| s == "italic"),
451
+ line_height: props.get("lineHeight").and_then(num),
452
+ align: props
453
+ .get("textAlign")
454
+ .and_then(Value::as_str)
455
+ .map(|s| match s {
456
+ "center" => 1,
457
+ "right" => 2,
458
+ _ => 0,
459
+ }),
460
+ }
461
+ }
462
+
463
+ // ---------------------------------------------------------------- encoding
464
+
465
+ /// A run's flags: bit 0 bold (600 and up), bit 1 italic, bits 4.. the weight.
466
+ fn run_flags(style: &TextStyle) -> i32 {
467
+ let weight = i32::from(style.weight.unwrap_or(400).clamp(1, 1000));
468
+ i32::from(weight >= 600) | (i32::from(style.italic.unwrap_or(false)) << 1) | (weight << 4)
469
+ }
470
+
471
+ fn put_i32(out: &mut Vec<u8>, v: i32) {
472
+ out.extend_from_slice(&v.to_le_bytes());
473
+ }
474
+ fn put_f32(out: &mut Vec<u8>, v: f32) {
475
+ out.extend_from_slice(&v.to_le_bytes());
476
+ }
477
+
478
+ const DEFAULT_INPUT_WIDTH: f32 = 160.0;
479
+
480
+ /// What a text field is measured with: one sample line per row, in its font.
481
+ fn encode_input_sample(props: &Map<String, Value>) -> Vec<u8> {
482
+ let style = text_style_of(props);
483
+ let rows = props
484
+ .get("rows")
485
+ .and_then(num)
486
+ .map(|r| r.max(1.0) as usize)
487
+ .unwrap_or(1);
488
+ // Sized by its content (CSS field-sizing): measured on what it holds,
489
+ // wraps included, so it grows with its lines; empty, it keeps its rows.
490
+ let content = props
491
+ .get("measureText")
492
+ .or_else(|| props.get("text"))
493
+ .and_then(Value::as_str)
494
+ .unwrap_or("");
495
+ let sized_by_content = props.get("fieldSizing").and_then(Value::as_str) == Some("content");
496
+ let sample = if sized_by_content && !content.is_empty() {
497
+ content.to_owned()
498
+ } else {
499
+ vec!["Mg"; rows].join("\n")
500
+ };
501
+ let mut out = vec![0u8];
502
+ put_f32(&mut out, style.line_height.unwrap_or(0.0));
503
+ put_i32(&mut out, 1);
504
+ put_i32(&mut out, style.color.unwrap_or(0xFF00_0000u32 as i32));
505
+ put_f32(&mut out, style.size.unwrap_or(14.0));
506
+ let flags = run_flags(&style);
507
+ put_i32(&mut out, flags);
508
+ put_i32(&mut out, sample.len() as i32);
509
+ out.extend_from_slice(sample.as_bytes());
510
+ out
511
+ }
512
+
513
+ /// A text field's mount payload: its props as JSON, plus the padding taffy
514
+ /// placed around its text (the platform field insets its text by it).
515
+ fn encode_input(props: &Map<String, Value>, layout: &taffy::Layout) -> Vec<u8> {
516
+ let mut field = Map::new();
517
+ for key in [
518
+ "placeholder",
519
+ "placeholderColor",
520
+ "multiline",
521
+ "rows",
522
+ "secure",
523
+ "keyboard",
524
+ "maxLength",
525
+ "editable",
526
+ "autocomplete",
527
+ "text",
528
+ "textVersion",
529
+ "fontSize",
530
+ "color",
531
+ "fontWeight",
532
+ "fontStyle",
533
+ "textAlign",
534
+ ] {
535
+ if let Some(v) = props.get(key) {
536
+ field.insert(key.to_owned(), v.clone());
537
+ }
538
+ }
539
+ let p = layout.padding;
540
+ field.insert(
541
+ "padding".to_owned(),
542
+ serde_json::json!([p.left, p.top, p.right, p.bottom]),
543
+ );
544
+ Value::Object(field).to_string().into_bytes()
545
+ }
546
+
547
+ /// An image's mount payload: where it comes from, how it fits its box, and
548
+ /// what a screen reader says. Its frame and corners travel as for any view.
549
+ fn encode_image(props: &Map<String, Value>) -> Vec<u8> {
550
+ let text = |key: &str| props.get(key).and_then(Value::as_str).unwrap_or("");
551
+ serde_json::json!({
552
+ "src": text("src"),
553
+ "fit": match text("objectFit") {
554
+ fit @ ("cover" | "contain" | "none" | "scale-down") => fit,
555
+ _ => "fill",
556
+ },
557
+ "alt": text("alt"),
558
+ })
559
+ .to_string()
560
+ .into_bytes()
561
+ }
562
+
563
+ impl Host {
564
+ fn set_measure(&mut self, measure: MeasureFn) {
565
+ self.measure = Some(measure);
566
+ }
567
+
568
+ fn set_viewport(&mut self, width: f32, height: f32) {
569
+ self.viewport = (width, height);
570
+ }
571
+
572
+ /// The attributed text of a Text node: its runs with inherited styles.
573
+ fn encode_text(&self, tag: i32) -> Vec<u8> {
574
+ if let Some(node) = self.nodes.get(&tag) {
575
+ if node.kind == Kind::TextInput {
576
+ return encode_input_sample(&node.props);
577
+ }
578
+ }
579
+ let mut runs: Vec<(TextStyle, String)> = Vec::new();
580
+ let Some(node) = self.nodes.get(&tag) else {
581
+ return Vec::new();
582
+ };
583
+ let base = text_style_of(&node.props);
584
+ self.collect_runs(&node.children, &base, &mut runs);
585
+ let mut out = Vec::new();
586
+ out.push(base.align.unwrap_or(0));
587
+ put_f32(&mut out, base.line_height.unwrap_or(0.0));
588
+ put_i32(&mut out, runs.len() as i32);
589
+ for (style, text) in runs {
590
+ put_i32(&mut out, style.color.unwrap_or(0xFF00_0000u32 as i32));
591
+ put_f32(&mut out, style.size.unwrap_or(14.0));
592
+ let flags = run_flags(&style);
593
+ put_i32(&mut out, flags);
594
+ put_i32(&mut out, text.len() as i32);
595
+ out.extend_from_slice(text.as_bytes());
596
+ }
597
+ out
598
+ }
599
+
600
+ fn collect_runs(
601
+ &self,
602
+ children: &[i32],
603
+ inherited: &TextStyle,
604
+ runs: &mut Vec<(TextStyle, String)>,
605
+ ) {
606
+ for child in children {
607
+ let Some(node) = self.nodes.get(child) else {
608
+ continue;
609
+ };
610
+ match node.kind {
611
+ Kind::RawText => runs.push((inherited.clone(), node.text.clone())),
612
+ Kind::VirtualText | Kind::Text => {
613
+ let style = text_style_of(&node.props).over(inherited);
614
+ self.collect_runs(&node.children, &style, runs);
615
+ }
616
+ Kind::View | Kind::Scroll | Kind::TextInput | Kind::Image | Kind::Vector => {}
617
+ }
618
+ }
619
+ }
620
+
621
+ /// The Text node a text-bearing node belongs to (itself for a Text).
622
+ fn owning_text(&self, mut tag: i32) -> Option<i32> {
623
+ loop {
624
+ let node = self.nodes.get(&tag)?;
625
+ if matches!(node.kind, Kind::Text | Kind::TextInput) {
626
+ return Some(tag);
627
+ }
628
+ tag = *self.parent.get(&tag)?;
629
+ }
630
+ }
631
+
632
+ /// Where nodes were laid out: `[x, y, width, height]` in the root's
633
+ /// coordinates (a scroll view's offset left out), or null for a tag with
634
+ /// no layout. A lazy list reads its rows' heights and its viewport here.
635
+ pub fn frames(&self, tags: &[i32]) -> Vec<Option<[f32; 4]>> {
636
+ tags.iter()
637
+ .map(|&tag| {
638
+ let id = self.nodes.get(&tag)?.taffy?;
639
+ let own = self.tree.layout(id).ok()?;
640
+ let (mut x, mut y) = (own.location.x, own.location.y);
641
+ let mut at = tag;
642
+ while let Some(&parent) = self.parent.get(&at) {
643
+ if let Some(id) = self.nodes.get(&parent).and_then(|n| n.taffy) {
644
+ let layout = self.tree.layout(id).ok()?;
645
+ x += layout.location.x;
646
+ y += layout.location.y;
647
+ }
648
+ at = parent;
649
+ }
650
+ Some([x, y, own.size.width, own.size.height])
651
+ })
652
+ .collect()
653
+ }
654
+
655
+ pub fn commit(&mut self, ops_json: &[u8], out: &mut Vec<u8>) -> Result<CommitInfo, String> {
656
+ let mut info = CommitInfo::default();
657
+ let t0 = Instant::now();
658
+ let ops: Vec<Value> = serde_json::from_slice(ops_json).map_err(|e| e.to_string())?;
659
+ let mut text_dirty: HashSet<i32> = HashSet::new();
660
+ let mut touched: Vec<i32> = Vec::new();
661
+ for op in &ops {
662
+ let Some(arr) = op.as_array() else { continue };
663
+ let code = arr.first().and_then(Value::as_str).unwrap_or("");
664
+ let tag = arr.get(1).and_then(Value::as_i64).unwrap_or(0) as i32;
665
+ match code {
666
+ "c" => {
667
+ let kind = Kind::of(arr.get(2).and_then(Value::as_str).unwrap_or("RCTView"));
668
+ let props = arr
669
+ .get(3)
670
+ .and_then(Value::as_object)
671
+ .cloned()
672
+ .unwrap_or_default();
673
+ let text = props
674
+ .get("text")
675
+ .and_then(Value::as_str)
676
+ .unwrap_or("")
677
+ .to_owned();
678
+ let vector = match (kind, props.get("vector")) {
679
+ (Kind::Vector, Some(v)) => vector::encode(v)?,
680
+ _ => Vec::new(),
681
+ };
682
+ if kind.is_layout() {
683
+ let flags = gesture_flags(&props);
684
+ gesture::with(|g| g.set_node(tag, flags, kind == Kind::Scroll));
685
+ }
686
+ let taffy = if kind.is_layout() {
687
+ Some(
688
+ self.tree
689
+ .new_leaf_with_context(style_for(kind, &props), tag)
690
+ .map_err(|e| e.to_string())?,
691
+ )
692
+ } else {
693
+ None
694
+ };
695
+ self.nodes.insert(
696
+ tag,
697
+ Node {
698
+ kind,
699
+ props,
700
+ taffy,
701
+ children: Vec::new(),
702
+ text,
703
+ vector,
704
+ },
705
+ );
706
+ touched.push(tag);
707
+ }
708
+ "u" => {
709
+ let patch = arr
710
+ .get(2)
711
+ .and_then(Value::as_object)
712
+ .cloned()
713
+ .unwrap_or_default();
714
+ if let Some(node) = self.nodes.get_mut(&tag) {
715
+ if patch.contains_key("gestures") && node.kind.is_layout() {
716
+ let flags = gesture_flags(&patch);
717
+ let scroll = node.kind == Kind::Scroll;
718
+ gesture::with(|g| g.set_node(tag, flags, scroll));
719
+ }
720
+ if let Some(t) = patch.get("text").and_then(Value::as_str) {
721
+ node.text = t.to_owned();
722
+ }
723
+ if let (Kind::Vector, Some(v)) = (node.kind, patch.get("vector")) {
724
+ node.vector = vector::encode(v)?;
725
+ }
726
+ node.props.extend(patch);
727
+ if let Some(id) = node.taffy {
728
+ self.tree
729
+ .set_style(id, style_for(node.kind, &node.props))
730
+ .map_err(|e| e.to_string())?;
731
+ }
732
+ touched.push(tag);
733
+ }
734
+ }
735
+ "k" => {
736
+ let children: Vec<i32> = arr
737
+ .get(2)
738
+ .and_then(Value::as_array)
739
+ .map(|a| {
740
+ a.iter()
741
+ .filter_map(Value::as_i64)
742
+ .map(|n| n as i32)
743
+ .collect()
744
+ })
745
+ .unwrap_or_default();
746
+ for child in &children {
747
+ self.parent.insert(*child, tag);
748
+ }
749
+ gesture::with(|g| {
750
+ for child in &children {
751
+ g.set_parent(*child, tag);
752
+ }
753
+ });
754
+ let layout_children: Vec<NodeId> = children
755
+ .iter()
756
+ .filter_map(|c| self.nodes.get(c).and_then(|n| n.taffy))
757
+ .collect();
758
+ if let Some(node) = self.nodes.get_mut(&tag) {
759
+ node.children = children;
760
+ if matches!(node.kind, Kind::View | Kind::Scroll) {
761
+ if let Some(id) = node.taffy {
762
+ self.tree
763
+ .set_children(id, &layout_children)
764
+ .map_err(|e| e.to_string())?;
765
+ }
766
+ }
767
+ touched.push(tag);
768
+ }
769
+ }
770
+ "r" => self.root = Some(tag),
771
+ _ => {}
772
+ }
773
+ }
774
+ for tag in touched {
775
+ if let Some(text) = self.owning_text(tag) {
776
+ text_dirty.insert(text);
777
+ }
778
+ }
779
+ for text in text_dirty {
780
+ let encoded = self.encode_text(text);
781
+ if self.spans.get(&text) != Some(&encoded) {
782
+ self.spans.insert(text, encoded);
783
+ if let Some(id) = self.nodes.get(&text).and_then(|n| n.taffy) {
784
+ self.tree.mark_dirty(id).map_err(|e| e.to_string())?;
785
+ }
786
+ }
787
+ }
788
+ info.parse_us = t0.elapsed().as_micros();
789
+
790
+ let Some(root) = self.root else {
791
+ return Ok(info);
792
+ };
793
+ let Some(root_id) = self.nodes.get(&root).and_then(|n| n.taffy) else {
794
+ return Ok(info);
795
+ };
796
+ let t1 = Instant::now();
797
+ let mut root_style = self.tree.style(root_id).map_err(|e| e.to_string())?.clone();
798
+ root_style.size = Size {
799
+ width: Dimension::length(self.viewport.0),
800
+ height: Dimension::length(self.viewport.1),
801
+ };
802
+ self.tree
803
+ .set_style(root_id, root_style)
804
+ .map_err(|e| e.to_string())?;
805
+ {
806
+ let inputs: HashSet<i32> = self
807
+ .nodes
808
+ .iter()
809
+ .filter(|(_, n)| n.kind == Kind::TextInput)
810
+ .map(|(t, _)| *t)
811
+ .collect();
812
+ let Host {
813
+ tree,
814
+ spans,
815
+ measure_cache,
816
+ measure,
817
+ ..
818
+ } = self;
819
+ let measure = *measure;
820
+ let mut measures = 0u32;
821
+ tree.compute_layout_with_measure(
822
+ root_id,
823
+ Size {
824
+ width: AvailableSpace::Definite(self.viewport.0),
825
+ height: AvailableSpace::Definite(self.viewport.1),
826
+ },
827
+ |known, available, _id, ctx, _style| {
828
+ if let (Some(w), Some(h)) = (known.width, known.height) {
829
+ return Size {
830
+ width: w,
831
+ height: h,
832
+ };
833
+ }
834
+ let Some(tag) = ctx.map(|t| *t) else {
835
+ return Size::ZERO;
836
+ };
837
+ let Some(encoded) = spans.get(&tag) else {
838
+ return Size::ZERO;
839
+ };
840
+ let max_width = known.width.unwrap_or(match available.width {
841
+ AvailableSpace::Definite(w) => w,
842
+ AvailableSpace::MinContent => 0.0,
843
+ AvailableSpace::MaxContent => f32::INFINITY,
844
+ });
845
+ let mut hasher = DefaultHasher::new();
846
+ encoded.hash(&mut hasher);
847
+ let hash = hasher.finish();
848
+ let mut call = |width: f32| {
849
+ measures += 1;
850
+ match measure {
851
+ Some(f) => {
852
+ let packed = f(encoded.as_ptr(), encoded.len(), width);
853
+ (
854
+ f32::from_bits((packed >> 32) as u32),
855
+ f32::from_bits(packed as u32),
856
+ )
857
+ }
858
+ // Desktop tests: 7 dp per byte, 16 dp per line.
859
+ None => ((encoded.len() as f32 * 7.0).min(width), 16.0),
860
+ }
861
+ };
862
+ // One platform call per text in the common case: its natural
863
+ // size answers every constraint at least that wide. Only a
864
+ // narrower constraint (wrapping) costs another call.
865
+ let natural = *measure_cache
866
+ .entry((hash, f32::INFINITY.to_bits()))
867
+ .or_insert_with(|| call(f32::INFINITY));
868
+ let (w, h) = if max_width >= natural.0 {
869
+ natural
870
+ } else {
871
+ *measure_cache
872
+ .entry((hash, max_width.to_bits()))
873
+ .or_insert_with(|| call(max_width))
874
+ };
875
+ // A field is as wide as its box says, like an HTML input:
876
+ // its text does not size it. 160 dp when nothing does.
877
+ let w = if inputs.contains(&tag) {
878
+ DEFAULT_INPUT_WIDTH
879
+ } else {
880
+ w
881
+ };
882
+ Size {
883
+ width: known.width.unwrap_or(w),
884
+ height: known.height.unwrap_or(h),
885
+ }
886
+ },
887
+ )
888
+ .map_err(|e| e.to_string())?;
889
+ info.measures = measures;
890
+ }
891
+ info.layout_us = t1.elapsed().as_micros();
892
+
893
+ let t2 = Instant::now();
894
+ let mut reachable: Vec<i32> = Vec::new();
895
+ let mut stack = vec![root];
896
+ while let Some(tag) = stack.pop() {
897
+ let Some(node) = self.nodes.get(&tag) else {
898
+ continue;
899
+ };
900
+ reachable.push(tag);
901
+ stack.extend(node.children.iter().rev());
902
+ }
903
+ let reachable_set: HashSet<i32> = reachable.iter().copied().collect();
904
+ let mut creates = Vec::new();
905
+ let mut attrs = Vec::new();
906
+ let mut kids = Vec::new();
907
+ for &tag in &reachable {
908
+ let Some(node) = self.nodes.get(&tag) else {
909
+ continue;
910
+ };
911
+ if !node.kind.is_layout() {
912
+ continue;
913
+ }
914
+ let Some(id) = node.taffy else { continue };
915
+ let mounted = self.mounted.entry(tag).or_insert_with(|| {
916
+ creates.push(OP_CREATE);
917
+ put_i32(&mut creates, tag);
918
+ creates.push(match node.kind {
919
+ Kind::Text => KIND_TEXT,
920
+ Kind::Scroll => KIND_SCROLL,
921
+ Kind::TextInput => KIND_INPUT,
922
+ Kind::Image => KIND_IMAGE,
923
+ Kind::Vector => KIND_VECTOR,
924
+ _ => KIND_VIEW,
925
+ });
926
+ Mounted {
927
+ frame: [f32::NAN; 4],
928
+ ..Mounted::default()
929
+ }
930
+ });
931
+ let layout = self.tree.layout(id).map_err(|e| e.to_string())?;
932
+ let frame = [
933
+ layout.location.x,
934
+ layout.location.y,
935
+ layout.size.width,
936
+ layout.size.height,
937
+ ];
938
+ if frame != mounted.frame {
939
+ attrs.push(OP_FRAME);
940
+ put_i32(&mut attrs, tag);
941
+ for v in frame {
942
+ put_f32(&mut attrs, v);
943
+ }
944
+ mounted.frame = frame;
945
+ }
946
+ let visual = visual_of(&node.props);
947
+ if mounted.visual.as_ref() != Some(&visual) {
948
+ attrs.push(OP_VIEW_STYLE);
949
+ put_i32(&mut attrs, tag);
950
+ put_i32(&mut attrs, visual.background.unwrap_or(0));
951
+ put_i32(&mut attrs, visual.border_color.unwrap_or(0));
952
+ put_f32(&mut attrs, visual.border_width);
953
+ put_f32(&mut attrs, visual.radius);
954
+ put_f32(&mut attrs, visual.opacity);
955
+ mounted.visual = Some(visual);
956
+ }
957
+ // Sent once a view has any, and whenever they change after that.
958
+ let effects = effects_of(&node.props);
959
+ let first_and_none = mounted.effects.is_none() && effects == Effects::default();
960
+ if !first_and_none && mounted.effects.as_ref() != Some(&effects) {
961
+ attrs.push(OP_EFFECTS);
962
+ put_i32(&mut attrs, tag);
963
+ for v in [
964
+ effects.shadow_x,
965
+ effects.shadow_y,
966
+ effects.shadow_blur,
967
+ effects.shadow_spread,
968
+ ] {
969
+ put_f32(&mut attrs, v);
970
+ }
971
+ put_i32(&mut attrs, effects.shadow_color);
972
+ put_f32(&mut attrs, effects.backdrop_blur);
973
+ attrs.push(u8::from(effects.clip));
974
+ mounted.effects = Some(effects);
975
+ }
976
+ if node.kind == Kind::Vector {
977
+ if node.vector != mounted.text {
978
+ attrs.push(OP_VECTOR);
979
+ put_i32(&mut attrs, tag);
980
+ put_i32(&mut attrs, node.vector.len() as i32);
981
+ attrs.extend_from_slice(&node.vector);
982
+ mounted.text = node.vector.clone();
983
+ }
984
+ } else if node.kind == Kind::Image {
985
+ let encoded = encode_image(&node.props);
986
+ if encoded != mounted.text {
987
+ attrs.push(OP_IMAGE);
988
+ put_i32(&mut attrs, tag);
989
+ put_i32(&mut attrs, encoded.len() as i32);
990
+ attrs.extend_from_slice(&encoded);
991
+ mounted.text = encoded;
992
+ }
993
+ } else if node.kind == Kind::TextInput {
994
+ let encoded = encode_input(&node.props, layout);
995
+ if encoded != mounted.text {
996
+ attrs.push(OP_INPUT);
997
+ put_i32(&mut attrs, tag);
998
+ put_i32(&mut attrs, encoded.len() as i32);
999
+ attrs.extend_from_slice(&encoded);
1000
+ mounted.text = encoded;
1001
+ }
1002
+ } else if node.kind == Kind::Text {
1003
+ let encoded = self.spans.get(&tag).cloned().unwrap_or_default();
1004
+ if encoded != mounted.text {
1005
+ attrs.push(OP_TEXT);
1006
+ put_i32(&mut attrs, tag);
1007
+ put_i32(&mut attrs, encoded.len() as i32);
1008
+ attrs.extend_from_slice(&encoded);
1009
+ mounted.text = encoded;
1010
+ }
1011
+ } else {
1012
+ let layout_children: Vec<i32> = node
1013
+ .children
1014
+ .iter()
1015
+ .copied()
1016
+ .filter(|c| {
1017
+ self.nodes
1018
+ .get(c)
1019
+ .map(|n| n.kind.is_layout())
1020
+ .unwrap_or(false)
1021
+ })
1022
+ .collect();
1023
+ if layout_children != mounted.children {
1024
+ kids.push(OP_CHILDREN);
1025
+ put_i32(&mut kids, tag);
1026
+ put_i32(&mut kids, layout_children.len() as i32);
1027
+ for c in &layout_children {
1028
+ put_i32(&mut kids, *c);
1029
+ }
1030
+ mounted.children = layout_children;
1031
+ }
1032
+ }
1033
+ }
1034
+ out.extend_from_slice(&creates);
1035
+ out.extend_from_slice(&attrs);
1036
+ out.extend_from_slice(&kids);
1037
+ if self.mounted_root != Some(root) {
1038
+ out.push(OP_ROOT);
1039
+ put_i32(out, root);
1040
+ self.mounted_root = Some(root);
1041
+ }
1042
+ // Drop what is no longer reachable: the views, the taffy nodes, the tags.
1043
+ let gone: Vec<i32> = self
1044
+ .nodes
1045
+ .keys()
1046
+ .copied()
1047
+ .filter(|t| !reachable_set.contains(t))
1048
+ .collect();
1049
+ for tag in gone {
1050
+ if let Some(node) = self.nodes.remove(&tag) {
1051
+ if let Some(id) = node.taffy {
1052
+ let _ = self.tree.remove(id);
1053
+ }
1054
+ }
1055
+ if self.mounted.remove(&tag).is_some() {
1056
+ out.push(OP_DELETE);
1057
+ put_i32(out, tag);
1058
+ }
1059
+ self.parent.remove(&tag);
1060
+ self.spans.remove(&tag);
1061
+ gesture::with(|g| g.remove(tag));
1062
+ motion::with(|m| m.forget_view(tag));
1063
+ info.deleted.push(tag);
1064
+ }
1065
+ info.nodes = self.nodes.len();
1066
+ info.diff_us = t2.elapsed().as_micros();
1067
+ Ok(info)
1068
+ }
1069
+ }
1070
+
1071
+ // ---------------------------------------------------------------- C ABI
1072
+
1073
+ thread_local! {
1074
+ static HOST: RefCell<Host> = RefCell::new(Host::default());
1075
+ }
1076
+
1077
+ #[repr(C)]
1078
+ pub struct OrbitBuf {
1079
+ pub ptr: *mut u8,
1080
+ pub len: usize,
1081
+ pub cap: usize,
1082
+ }
1083
+
1084
+ impl OrbitBuf {
1085
+ fn from_vec(mut v: Vec<u8>) -> OrbitBuf {
1086
+ let buf = OrbitBuf {
1087
+ ptr: v.as_mut_ptr(),
1088
+ len: v.len(),
1089
+ cap: v.capacity(),
1090
+ };
1091
+ std::mem::forget(v);
1092
+ buf
1093
+ }
1094
+ }
1095
+
1096
+ /// # Safety
1097
+ /// `buf` must come from this library and be freed once.
1098
+ #[no_mangle]
1099
+ pub unsafe extern "C" fn orbit_buf_free(buf: OrbitBuf) {
1100
+ if !buf.ptr.is_null() {
1101
+ drop(Vec::from_raw_parts(buf.ptr, buf.len, buf.cap));
1102
+ }
1103
+ }
1104
+
1105
+ #[no_mangle]
1106
+ pub extern "C" fn orbit_set_measure(measure: MeasureFn) {
1107
+ HOST.with(|h| h.borrow_mut().set_measure(measure));
1108
+ }
1109
+
1110
+ #[no_mangle]
1111
+ pub extern "C" fn orbit_set_viewport(width: f32, height: f32) {
1112
+ HOST.with(|h| h.borrow_mut().set_viewport(width, height));
1113
+ }
1114
+
1115
+ fn panic_message(payload: Box<dyn std::any::Any + Send>) -> String {
1116
+ payload
1117
+ .downcast_ref::<&str>()
1118
+ .map(|s| (*s).to_owned())
1119
+ .or_else(|| payload.downcast_ref::<String>().cloned())
1120
+ .unwrap_or_else(|| "panic".to_owned())
1121
+ }
1122
+
1123
+ fn info_json(info: &CommitInfo, ops_bytes: usize) -> String {
1124
+ serde_json::json!({
1125
+ "deleted": info.deleted,
1126
+ "parseUs": info.parse_us as u64,
1127
+ "layoutUs": info.layout_us as u64,
1128
+ "diffUs": info.diff_us as u64,
1129
+ "measures": info.measures,
1130
+ "nodes": info.nodes,
1131
+ "opsBytes": ops_bytes,
1132
+ })
1133
+ .to_string()
1134
+ }
1135
+
1136
+ /// A touch from the UI thread (see `gesture::Gestures::touch`); `out`
1137
+ /// receives the commands.
1138
+ ///
1139
+ /// # Safety
1140
+ /// `out` must be valid.
1141
+ #[no_mangle]
1142
+ pub unsafe extern "C" fn orbit_touch(
1143
+ action: u8,
1144
+ x: f32,
1145
+ y: f32,
1146
+ now_ns: i64,
1147
+ hit: i32,
1148
+ out: *mut OrbitBuf,
1149
+ ) {
1150
+ let mut commands = Vec::new();
1151
+ gesture::with(|g| g.touch(action, x, y, now_ns, hit, &mut commands));
1152
+ *out = OrbitBuf::from_vec(commands);
1153
+ }
1154
+
1155
+ /// Every vsync on the UI thread: long presses and delayed feedback.
1156
+ ///
1157
+ /// # Safety
1158
+ /// `out` must be valid.
1159
+ #[no_mangle]
1160
+ pub unsafe extern "C" fn orbit_gesture_tick(now_ns: i64, out: *mut OrbitBuf) {
1161
+ let mut commands = Vec::new();
1162
+ gesture::with(|g| g.tick(now_ns, &mut commands));
1163
+ *out = OrbitBuf::from_vec(commands);
1164
+ }
1165
+
1166
+ /// The frames of a JSON array of tags, as a JSON array of `[x, y, w, h]` or
1167
+ /// null (see `Host::frames`). Returns 0, or 1 with `{"error": …}`.
1168
+ ///
1169
+ /// # Safety
1170
+ /// `tags` must point to `len` readable bytes; `out` must be valid.
1171
+ #[no_mangle]
1172
+ pub unsafe extern "C" fn orbit_layout(tags: *const u8, len: usize, out: *mut OrbitBuf) -> i32 {
1173
+ let input = std::slice::from_raw_parts(tags, len);
1174
+ let (code, json) = match serde_json::from_slice::<Vec<i32>>(input) {
1175
+ Ok(tags) => (
1176
+ 0,
1177
+ serde_json::to_string(&HOST.with(|h| h.borrow().frames(&tags)))
1178
+ .unwrap_or_else(|_| "[]".to_owned()),
1179
+ ),
1180
+ Err(e) => (1, serde_json::json!({ "error": e.to_string() }).to_string()),
1181
+ };
1182
+ *out = OrbitBuf::from_vec(json.into_bytes());
1183
+ code
1184
+ }
1185
+
1186
+ /// Commit a JSON batch. `mount_ops` receives the binary mount operations,
1187
+ /// `info` a JSON object (or `{"error": …}`). Returns 0 on success.
1188
+ ///
1189
+ /// # Safety
1190
+ /// `ops` must point to `len` readable bytes; both out-pointers must be valid.
1191
+ #[no_mangle]
1192
+ pub unsafe extern "C" fn orbit_commit(
1193
+ ops: *const u8,
1194
+ len: usize,
1195
+ mount_ops: *mut OrbitBuf,
1196
+ info: *mut OrbitBuf,
1197
+ ) -> i32 {
1198
+ let input = std::slice::from_raw_parts(ops, len);
1199
+ let result = std::panic::catch_unwind(|| {
1200
+ HOST.with(|h| {
1201
+ let mut out = Vec::new();
1202
+ let info = h.borrow_mut().commit(input, &mut out)?;
1203
+ Ok::<_, String>((out, info))
1204
+ })
1205
+ });
1206
+ let (code, ops_out, info_out) = match result {
1207
+ Ok(Ok((out, i))) => {
1208
+ let json = info_json(&i, out.len());
1209
+ (0, out, json)
1210
+ }
1211
+ Ok(Err(e)) => (1, Vec::new(), serde_json::json!({ "error": e }).to_string()),
1212
+ Err(p) => (
1213
+ 2,
1214
+ Vec::new(),
1215
+ serde_json::json!({ "error": panic_message(p) }).to_string(),
1216
+ ),
1217
+ };
1218
+ *mount_ops = OrbitBuf::from_vec(ops_out);
1219
+ *info = OrbitBuf::from_vec(info_out.into_bytes());
1220
+ code
1221
+ }
1222
+
1223
+ #[no_mangle]
1224
+ pub extern "C" fn orbit_motion_value(tag: i32, initial: f64) {
1225
+ motion::with(|m| m.value(tag, initial));
1226
+ }
1227
+
1228
+ /// # Safety
1229
+ /// `from` and `to` must point to `len` readable f64s.
1230
+ #[no_mangle]
1231
+ pub unsafe extern "C" fn orbit_motion_interpolate(
1232
+ tag: i32,
1233
+ input: i32,
1234
+ from: *const f64,
1235
+ to: *const f64,
1236
+ len: usize,
1237
+ ) {
1238
+ let from = std::slice::from_raw_parts(from, len).to_vec();
1239
+ let to = std::slice::from_raw_parts(to, len).to_vec();
1240
+ motion::with(|m| m.interpolation(tag, input, from, to));
1241
+ }
1242
+
1243
+ #[no_mangle]
1244
+ pub extern "C" fn orbit_motion_set(tag: i32, value: f64) {
1245
+ motion::with(|m| m.set(tag, value));
1246
+ }
1247
+
1248
+ #[no_mangle]
1249
+ pub extern "C" fn orbit_motion_stop(tag: i32) {
1250
+ motion::with(|m| m.stop(tag));
1251
+ }
1252
+
1253
+ /// # Safety
1254
+ /// `frames` must point to `len` readable f64s.
1255
+ #[no_mangle]
1256
+ pub unsafe extern "C" fn orbit_motion_frames(
1257
+ tag: i32,
1258
+ frames: *const f64,
1259
+ len: usize,
1260
+ to: f64,
1261
+ looping: bool,
1262
+ ) {
1263
+ let frames = std::slice::from_raw_parts(frames, len).to_vec();
1264
+ motion::with(|m| m.frames(tag, frames, to, looping));
1265
+ }
1266
+
1267
+ #[no_mangle]
1268
+ pub extern "C" fn orbit_motion_spring(tag: i32, to: f64, stiffness: f64, damping: f64, mass: f64) {
1269
+ motion::with(|m| m.spring(tag, to, stiffness, damping, mass));
1270
+ }
1271
+
1272
+ #[no_mangle]
1273
+ pub extern "C" fn orbit_motion_dispose(tag: i32) {
1274
+ motion::with(|m| m.dispose(tag));
1275
+ }
1276
+
1277
+ #[no_mangle]
1278
+ pub extern "C" fn orbit_motion_bind(view: i32, prop: u8, node: i32) {
1279
+ motion::with(|m| m.bind(view, prop, node));
1280
+ }
1281
+
1282
+ #[no_mangle]
1283
+ pub extern "C" fn orbit_motion_bind_scroll(scroll_view: i32, value: i32) {
1284
+ motion::with(|m| m.bind_scroll(scroll_view, value));
1285
+ }
1286
+
1287
+ /// Advance every animation to `now_ns` (UI thread). `scroll_tags`/`scroll_y`
1288
+ /// carry `count` scroll offsets in dp. `out` receives 9-byte records
1289
+ /// (i32 view, u8 prop, f32 value). Returns 1 while an animation is running.
1290
+ ///
1291
+ /// # Safety
1292
+ /// The input pointers must hold `count` items; `out` must be valid.
1293
+ #[no_mangle]
1294
+ pub unsafe extern "C" fn orbit_motion_tick(
1295
+ now_ns: i64,
1296
+ scroll_tags: *const i32,
1297
+ scroll_y: *const f32,
1298
+ count: usize,
1299
+ out: *mut OrbitBuf,
1300
+ ) -> i32 {
1301
+ let tags = if count == 0 {
1302
+ &[][..]
1303
+ } else {
1304
+ std::slice::from_raw_parts(scroll_tags, count)
1305
+ };
1306
+ let ys = if count == 0 {
1307
+ &[][..]
1308
+ } else {
1309
+ std::slice::from_raw_parts(scroll_y, count)
1310
+ };
1311
+ let scrolls: Vec<(i32, f32)> = tags.iter().copied().zip(ys.iter().copied()).collect();
1312
+ let mut buf = Vec::new();
1313
+ let active = motion::with(|m| m.tick(now_ns, &scrolls, &mut buf));
1314
+ *out = OrbitBuf::from_vec(buf);
1315
+ i32::from(active)
1316
+ }
1317
+
1318
+ #[cfg(test)]
1319
+ mod tests {
1320
+ use super::*;
1321
+
1322
+ /// The op codes of a mount buffer, in order.
1323
+ fn codes(buf: &[u8]) -> Vec<u8> {
1324
+ let i32_at =
1325
+ |i: usize| i32::from_le_bytes([buf[i], buf[i + 1], buf[i + 2], buf[i + 3]]) as usize;
1326
+ let mut out = Vec::new();
1327
+ let mut i = 0;
1328
+ while i < buf.len() {
1329
+ let code = buf[i];
1330
+ out.push(code);
1331
+ i += 5; // code + tag
1332
+ i += match code {
1333
+ OP_CREATE => 1,
1334
+ OP_DELETE | OP_ROOT => 0,
1335
+ OP_CHILDREN => 4 + 4 * i32_at(i),
1336
+ OP_FRAME => 16,
1337
+ OP_VIEW_STYLE => 20,
1338
+ OP_EFFECTS => 25,
1339
+ OP_TEXT | OP_INPUT | OP_IMAGE | OP_VECTOR => 4 + i32_at(i),
1340
+ _ => panic!("unknown op {code}"),
1341
+ };
1342
+ }
1343
+ out
1344
+ }
1345
+
1346
+ fn commit(host: &mut Host, ops: &str) -> (Vec<u8>, CommitInfo) {
1347
+ let mut out = Vec::new();
1348
+ let info = host.commit(ops.as_bytes(), &mut out).expect("commit");
1349
+ (out, info)
1350
+ }
1351
+
1352
+ #[test]
1353
+ fn mounts_lays_out_and_patches_only_what_changed() {
1354
+ let mut host = Host::default();
1355
+ host.set_viewport(300.0, 600.0);
1356
+ let (first, _) = commit(
1357
+ &mut host,
1358
+ r#"[["c",1,"RCTView",{"padding":10}],["c",3,"RCTView",{"flexDirection":"row","height":20,"backgroundColor":-16776961}],
1359
+ ["c",5,"RCTText",{"fontSize":12}],["c",7,"RCTRawText",{"text":"hello"}],
1360
+ ["k",5,[7]],["k",3,[5]],["k",1,[3]],["r",1]]"#,
1361
+ );
1362
+ let first = codes(&first);
1363
+ assert_eq!(first.iter().filter(|c| **c == OP_CREATE).count(), 3);
1364
+ assert_eq!(first.last(), Some(&OP_ROOT));
1365
+ let row = host.tree.layout(host.nodes[&3].taffy.unwrap()).unwrap();
1366
+ assert_eq!(
1367
+ (
1368
+ row.location.x,
1369
+ row.location.y,
1370
+ row.size.width,
1371
+ row.size.height
1372
+ ),
1373
+ (10.0, 10.0, 280.0, 20.0)
1374
+ );
1375
+
1376
+ // Only the raw text changes: one TEXT op for its Text node (and its new frame).
1377
+ let (second, info) = commit(&mut host, r#"[["u",7,{"text":"hello world"}]]"#);
1378
+ assert_eq!(codes(&second), vec![OP_FRAME, OP_TEXT]);
1379
+ assert!(info.deleted.is_empty());
1380
+
1381
+ // Nothing changed: nothing to mount.
1382
+ let (third, _) = commit(&mut host, "[]");
1383
+ assert!(third.is_empty());
1384
+ }
1385
+
1386
+ #[test]
1387
+ fn a_text_field_is_a_measured_leaf_with_its_props_and_padding() {
1388
+ let mut host = Host::default();
1389
+ host.set_viewport(300.0, 600.0);
1390
+ let (first, _) = commit(
1391
+ &mut host,
1392
+ r#"[["c",1,"RCTView",{"flexDirection":"row","alignItems":"center"}],
1393
+ ["c",3,"OrbitTextInput",{"padding":12,"fontSize":16,"placeholder":"Message","text":"","textVersion":0}],
1394
+ ["k",1,[3]],["r",1]]"#,
1395
+ );
1396
+ assert!(codes(&first).contains(&OP_INPUT));
1397
+ let field = host.tree.layout(host.nodes[&3].taffy.unwrap()).unwrap();
1398
+ // No width from its box in a row: the default; height: one line + padding.
1399
+ assert_eq!(field.size.width, DEFAULT_INPUT_WIDTH + 24.0);
1400
+ assert_eq!(field.size.height, 16.0 + 24.0);
1401
+ let json = String::from_utf8_lossy(&first);
1402
+ assert!(
1403
+ json.contains(r#""padding":[12.0,12.0,12.0,12.0]"#),
1404
+ "{json}"
1405
+ );
1406
+ assert!(json.contains(r#""placeholder":"Message""#), "{json}");
1407
+
1408
+ // The app clears the field: one INPUT op, nothing else.
1409
+ let (second, _) = commit(&mut host, r#"[["u",3,{"text":"","textVersion":1}]]"#);
1410
+ assert_eq!(codes(&second), vec![OP_INPUT]);
1411
+ }
1412
+
1413
+ #[test]
1414
+ fn a_field_sized_by_its_content_grows_with_its_lines() {
1415
+ let mut host = Host::default();
1416
+ host.set_viewport(300.0, 600.0);
1417
+ commit(
1418
+ &mut host,
1419
+ r#"[["c",1,"RCTView",{"alignItems":"flex-start"}],
1420
+ ["c",3,"OrbitTextInput",{"multiline":true,"rows":1,"fieldSizing":"content","maxHeight":40,"fontSize":16}],
1421
+ ["k",1,[3]],["r",1]]"#,
1422
+ );
1423
+ let height = |host: &Host| {
1424
+ host.tree
1425
+ .layout(host.nodes[&3].taffy.unwrap())
1426
+ .unwrap()
1427
+ .size
1428
+ .height
1429
+ };
1430
+ assert_eq!(height(&host), 16.0);
1431
+ // Desktop fallback measure: 16 dp a line, whatever the line count — so
1432
+ // what this checks is that the measured text changes, and max-h caps it.
1433
+ commit(&mut host, r#"[["u",3,{"measureText":"un\ndeux"}]]"#);
1434
+ assert!(host.spans[&3].ends_with(b"un\ndeux"));
1435
+ commit(&mut host, r#"[["u",3,{"maxHeight":8}]]"#);
1436
+ assert_eq!(height(&host), 8.0);
1437
+ }
1438
+
1439
+ #[test]
1440
+ fn a_vector_is_a_leaf_sent_with_its_paths_once_per_change() {
1441
+ let mut host = Host::default();
1442
+ host.set_viewport(300.0, 600.0);
1443
+ let icon = r##"{"color":-16777216,"root":{"t":"svg","a":{"viewBox":"0 0 24 24","fill":"none","stroke":"currentColor"},"c":[{"t":"path","a":{"d":"M5 12h14"}}]}}"##;
1444
+ let (first, _) = commit(
1445
+ &mut host,
1446
+ &format!(
1447
+ r#"[["c",1,"RCTView",{{}}],["c",3,"OrbitVector",{{"width":24,"height":24,"vector":{icon}}}],["k",1,[3]],["r",1]]"#
1448
+ ),
1449
+ );
1450
+ let size = host
1451
+ .tree
1452
+ .layout(host.nodes[&3].taffy.unwrap())
1453
+ .unwrap()
1454
+ .size;
1455
+ assert_eq!((size.width, size.height), (24.0, 24.0));
1456
+ assert_eq!(codes(&first).iter().filter(|c| **c == OP_VECTOR).count(), 1);
1457
+ let create = first
1458
+ .windows(6)
1459
+ .position(|w| w[0] == OP_CREATE && w[1..5] == 3i32.to_le_bytes())
1460
+ .unwrap();
1461
+ assert_eq!(first[create + 5], KIND_VECTOR);
1462
+
1463
+ // A resize alone sends no paths; a new drawing does.
1464
+ let (second, _) = commit(&mut host, r#"[["u",3,{"width":32,"height":32}]]"#);
1465
+ assert!(!codes(&second).contains(&OP_VECTOR));
1466
+ let red = icon.replace("-16777216", "-65536");
1467
+ let (third, _) = commit(&mut host, &format!(r#"[["u",3,{{"vector":{red}}}]]"#));
1468
+ assert_eq!(codes(&third), vec![OP_VECTOR]);
1469
+
1470
+ let broken = r#"[["u",3,{"vector":{"root":{"t":"svg","a":{"viewBox":"0 0 1 1"},"c":[{"t":"path","a":{"d":"M0 0 Q"}}]}}}]]"#;
1471
+ assert!(host.commit(broken.as_bytes(), &mut Vec::new()).is_err());
1472
+ }
1473
+
1474
+ #[test]
1475
+ fn an_image_is_a_leaf_sized_by_its_style_and_sent_with_its_source() {
1476
+ let mut host = Host::default();
1477
+ host.set_viewport(300.0, 600.0);
1478
+ let (first, info) = commit(
1479
+ &mut host,
1480
+ r#"[["c",1,"RCTView",{}],
1481
+ ["c",3,"OrbitImage",{"width":"100%","aspectRatio":1.5,"borderRadius":8,"src":"https://cdn.example.com/a.jpg","alt":"Plage","objectFit":"cover"}],
1482
+ ["c",5,"OrbitImage",{"src":"asset:logo.png"}],
1483
+ ["k",1,[3,5]],["r",1]]"#,
1484
+ );
1485
+ assert_eq!(info.measures, 0, "an image is never measured");
1486
+ let size = |tag: i32| {
1487
+ host.tree
1488
+ .layout(host.nodes[&tag].taffy.unwrap())
1489
+ .unwrap()
1490
+ .size
1491
+ };
1492
+ assert_eq!((size(3).width, size(3).height), (300.0, 200.0));
1493
+ // Unsized, it gets no height (stretched across the column, as any
1494
+ // item): its box does not wait for the decode to learn a size.
1495
+ assert_eq!((size(5).width, size(5).height), (300.0, 0.0));
1496
+ assert_eq!(codes(&first).iter().filter(|c| **c == OP_IMAGE).count(), 2);
1497
+ let json = String::from_utf8_lossy(&first);
1498
+ assert!(
1499
+ json.contains(r#"{"alt":"Plage","fit":"cover","src":"https://cdn.example.com/a.jpg"}"#),
1500
+ "{json}"
1501
+ );
1502
+ assert!(
1503
+ json.contains(r#""fit":"fill""#),
1504
+ "CSS's default fit: {json}"
1505
+ );
1506
+
1507
+ // A new source: one IMAGE op; a resize alone: only the frame.
1508
+ let (second, _) = commit(&mut host, r#"[["u",5,{"src":"bytes:2"}]]"#);
1509
+ assert_eq!(codes(&second), vec![OP_IMAGE]);
1510
+ let (third, _) = commit(&mut host, r#"[["u",5,{"width":40,"height":40}]]"#);
1511
+ assert_eq!(codes(&third), vec![OP_FRAME]);
1512
+ }
1513
+
1514
+ #[test]
1515
+ fn frames_are_in_the_roots_coordinates_and_hidden_nodes_take_no_room() {
1516
+ let mut host = Host::default();
1517
+ host.set_viewport(300.0, 600.0);
1518
+ commit(
1519
+ &mut host,
1520
+ r#"[["c",1,"RCTView",{"padding":10}],
1521
+ ["c",3,"RCTView",{"height":0,"display":"none"}],
1522
+ ["c",5,"RCTView",{"paddingTop":4}],
1523
+ ["c",7,"RCTView",{"height":30}],
1524
+ ["c",9,"RCTView",{"height":40}],
1525
+ ["k",5,[7,9]],["k",1,[3,5]],["r",1]]"#,
1526
+ );
1527
+ let frames = host.frames(&[3, 7, 9, 42]);
1528
+ assert_eq!(frames[0].map(|f| f[3]), Some(0.0));
1529
+ // 10 of the root's padding, 4 of the container's: the hidden spacer takes none.
1530
+ assert_eq!(frames[1], Some([10.0, 14.0, 280.0, 30.0]));
1531
+ assert_eq!(frames[2], Some([10.0, 44.0, 280.0, 40.0]));
1532
+ assert_eq!(frames[3], None);
1533
+ }
1534
+
1535
+ #[test]
1536
+ fn effects_are_sent_when_a_view_has_any_and_when_they_change() {
1537
+ let mut host = Host::default();
1538
+ let (first, _) = commit(
1539
+ &mut host,
1540
+ r#"[["c",1,"RCTView",{}],
1541
+ ["c",3,"RCTView",{"height":40,"shadowY":10,"shadowBlur":15,"shadowSpread":-3,"shadowColor":436207616}],
1542
+ ["c",5,"RCTView",{"height":40,"backdropBlur":16,"overflow":"hidden"}],
1543
+ ["k",1,[3,5]],["r",1]]"#,
1544
+ );
1545
+ // Two views have effects; the root has none and gets no op.
1546
+ assert_eq!(
1547
+ codes(&first).iter().filter(|c| **c == OP_EFFECTS).count(),
1548
+ 2
1549
+ );
1550
+ let at = first
1551
+ .windows(5)
1552
+ .position(|w| w[0] == OP_EFFECTS && w[1..5] == 3i32.to_le_bytes())
1553
+ .expect("the shadowed view's effects");
1554
+ let f = |i: usize| {
1555
+ f32::from_le_bytes(first[at + 5 + 4 * i..at + 9 + 4 * i].try_into().unwrap())
1556
+ };
1557
+ assert_eq!((f(0), f(1), f(2), f(3)), (0.0, 10.0, 15.0, -3.0));
1558
+ // Unchanged: nothing; the shadow removed: one op, back to none.
1559
+ let (second, _) = commit(&mut host, r#"[["u",5,{"height":50}]]"#);
1560
+ assert!(!codes(&second).contains(&OP_EFFECTS));
1561
+ let (third, _) = commit(
1562
+ &mut host,
1563
+ r#"[["u",3,{"shadowY":null,"shadowBlur":null,"shadowSpread":null,"shadowColor":null}]]"#,
1564
+ );
1565
+ assert_eq!(codes(&third), vec![OP_EFFECTS]);
1566
+ }
1567
+
1568
+ #[test]
1569
+ fn a_commit_keeps_the_gesture_tree_the_ui_thread_recognizes_on() {
1570
+ // Tags of their own: the gesture tree is shared by every host in the process.
1571
+ let mut host = Host::default();
1572
+ commit(
1573
+ &mut host,
1574
+ r#"[["c",901,"RCTScrollView",{}],["c",903,"RCTView",{}],
1575
+ ["c",905,"RCTView",{"height":40,"gestures":1}],["c",907,"RCTText",{}],
1576
+ ["k",905,[907]],["k",903,[905]],["k",901,[903]],["r",901]]"#,
1577
+ );
1578
+ let tap = |host_tag: i32| {
1579
+ let mut out = Vec::new();
1580
+ gesture::with(|g| {
1581
+ g.touch(gesture::DOWN, 5.0, 5.0, 0, host_tag, &mut out);
1582
+ g.touch(gesture::UP, 5.0, 5.0, 300_000_000, host_tag, &mut out);
1583
+ });
1584
+ out
1585
+ };
1586
+ // A tap on the row's text presses the row (in a scroll view: the
1587
+ // feedback flashes on release, then the event).
1588
+ let out = tap(907);
1589
+ assert_eq!(out.first(), Some(&gesture::CMD_PRESSED));
1590
+ assert_eq!(out[1..5], 905i32.to_le_bytes());
1591
+ assert!(out.windows(8).any(|w| w == b"topPress"));
1592
+ // Its handler gone: nothing.
1593
+ commit(&mut host, r#"[["u",905,{"gestures":0}]]"#);
1594
+ assert!(tap(907).is_empty());
1595
+ }
1596
+
1597
+ #[test]
1598
+ fn drops_nodes_that_left_the_tree() {
1599
+ let mut host = Host::default();
1600
+ commit(
1601
+ &mut host,
1602
+ r#"[["c",1,"RCTView",{}],["c",3,"RCTView",{}],["k",1,[3]],["r",1]]"#,
1603
+ );
1604
+ let (out, info) = commit(&mut host, r#"[["k",1,[]]]"#);
1605
+ assert_eq!(info.deleted, vec![3]);
1606
+ assert_eq!(codes(&out), vec![OP_CHILDREN, OP_DELETE]);
1607
+ }
1608
+ }