@c9up/orbit 0.0.0-stage → 0.1.1

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 (105) hide show
  1. package/Cargo.lock +139 -0
  2. package/Cargo.toml +20 -0
  3. package/LICENSE +21 -0
  4. package/README.md +320 -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 +161 -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 +2042 -0
  19. package/crates/orbit-host/src/motion.rs +328 -0
  20. package/crates/orbit-host/src/vector.rs +1173 -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 +77 -0
  26. package/dist/commit.d.ts.map +1 -0
  27. package/dist/commit.js +302 -0
  28. package/dist/commit.js.map +1 -0
  29. package/dist/errors.d.ts +76 -0
  30. package/dist/errors.d.ts.map +1 -0
  31. package/dist/errors.js +89 -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 +20 -0
  36. package/dist/host.js.map +1 -0
  37. package/dist/index.d.ts +31 -0
  38. package/dist/index.d.ts.map +1 -0
  39. package/dist/index.js +31 -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 +67 -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 +33 -0
  54. package/dist/react-native/index.d.ts.map +1 -0
  55. package/dist/react-native/index.js +71 -0
  56. package/dist/react-native/index.js.map +1 -0
  57. package/dist/report.d.ts +13 -0
  58. package/dist/report.d.ts.map +1 -0
  59. package/dist/report.js +22 -0
  60. package/dist/report.js.map +1 -0
  61. package/dist/server.d.ts +109 -0
  62. package/dist/server.d.ts.map +1 -0
  63. package/dist/server.js +290 -0
  64. package/dist/server.js.map +1 -0
  65. package/dist/stack.d.ts +117 -0
  66. package/dist/stack.d.ts.map +1 -0
  67. package/dist/stack.js +299 -0
  68. package/dist/stack.js.map +1 -0
  69. package/dist/styles.d.ts +138 -0
  70. package/dist/styles.d.ts.map +1 -0
  71. package/dist/styles.js +920 -0
  72. package/dist/styles.js.map +1 -0
  73. package/dist/template.d.ts +27 -0
  74. package/dist/template.d.ts.map +1 -0
  75. package/dist/template.js +1436 -0
  76. package/dist/template.js.map +1 -0
  77. package/dist/textDecoder.d.ts +29 -0
  78. package/dist/textDecoder.d.ts.map +1 -0
  79. package/dist/textDecoder.js +149 -0
  80. package/dist/textDecoder.js.map +1 -0
  81. package/dist/url.d.ts +45 -0
  82. package/dist/url.d.ts.map +1 -0
  83. package/dist/url.js +303 -0
  84. package/dist/url.js.map +1 -0
  85. package/package.json +96 -3
  86. package/scripts/build-android.sh +27 -0
  87. package/scripts/test-styles.mjs +31 -0
  88. package/specs/NativeOrbit.ts +34 -0
  89. package/src/color.ts +68 -0
  90. package/src/commit.ts +373 -0
  91. package/src/errors.ts +178 -0
  92. package/src/host.ts +91 -0
  93. package/src/index.ts +64 -0
  94. package/src/motion.ts +88 -0
  95. package/src/node.ts +133 -0
  96. package/src/pages.ts +207 -0
  97. package/src/react-native/index.ts +115 -0
  98. package/src/react-native/react-native.d.ts +39 -0
  99. package/src/report.ts +25 -0
  100. package/src/server.ts +395 -0
  101. package/src/stack.ts +428 -0
  102. package/src/styles.ts +1021 -0
  103. package/src/template.ts +1681 -0
  104. package/src/textDecoder.ts +162 -0
  105. package/src/url.ts +333 -0
@@ -0,0 +1,2042 @@
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
+ //! A batch the host refuses may have been applied in part; JS then sends what
15
+ //! it carried again, so `"c"` on a tag the host holds replaces that node.
16
+
17
+ use std::cell::RefCell;
18
+ use std::collections::hash_map::DefaultHasher;
19
+ use std::collections::{HashMap, HashSet};
20
+ use std::hash::{Hash, Hasher};
21
+ use std::time::Instant;
22
+
23
+ pub mod gesture;
24
+ pub mod motion;
25
+ pub mod vector;
26
+
27
+ use serde_json::{Map, Value};
28
+ use taffy::prelude::*;
29
+
30
+ /// Measures encoded text (see `encode_text`) under a maximum width, in dp.
31
+ /// Returns the width and height as the high and low 32 bits of f32 bit patterns.
32
+ pub type MeasureFn = extern "C" fn(spans: *const u8, len: usize, max_width: f32) -> u64;
33
+
34
+ // Mount operation codes, shared with OrbitHost.kt.
35
+ /// How deep views may nest under the root (the root is level 1). taffy lays
36
+ /// a tree out by recursing once per level on the caller's stack — React
37
+ /// Native's JS thread, about 1 MiB — at about 6 KB a level (x86_64, release):
38
+ /// some 170 levels overflow it, and a stack overflow is not a panic
39
+ /// `catch_unwind` could stop. Deeper is refused, coded, before any layout.
40
+ pub const MAX_DEPTH: usize = 100;
41
+
42
+ const OP_CREATE: u8 = 1;
43
+ const OP_DELETE: u8 = 2;
44
+ const OP_CHILDREN: u8 = 3;
45
+ const OP_FRAME: u8 = 4;
46
+ const OP_VIEW_STYLE: u8 = 5;
47
+ const OP_TEXT: u8 = 6;
48
+ const OP_ROOT: u8 = 7;
49
+ const OP_INPUT: u8 = 8;
50
+ const OP_IMAGE: u8 = 9;
51
+ const OP_EFFECTS: u8 = 10;
52
+ const OP_VECTOR: u8 = 11;
53
+
54
+ const KIND_VIEW: u8 = 0;
55
+ const KIND_TEXT: u8 = 1;
56
+ const KIND_SCROLL: u8 = 2;
57
+ const KIND_INPUT: u8 = 3;
58
+ const KIND_IMAGE: u8 = 4;
59
+ const KIND_VECTOR: u8 = 5;
60
+
61
+ #[derive(Clone, Copy, PartialEq, Eq, Debug)]
62
+ enum Kind {
63
+ View,
64
+ Scroll,
65
+ Text,
66
+ RawText,
67
+ VirtualText,
68
+ /// A native text field: a layout leaf the platform measures by its font.
69
+ TextInput,
70
+ /// An image: a layout leaf sized by its style alone, decoded by the platform.
71
+ Image,
72
+ /// An `<svg>`: a layout leaf sized by its style, drawn from `vector.rs`'s paths.
73
+ Vector,
74
+ }
75
+
76
+ impl Kind {
77
+ fn of(view_name: &str) -> Kind {
78
+ match view_name {
79
+ "RCTText" | "RCTParagraph" => Kind::Text,
80
+ "RCTRawText" => Kind::RawText,
81
+ "RCTVirtualText" => Kind::VirtualText,
82
+ "RCTScrollView" => Kind::Scroll,
83
+ "OrbitTextInput" => Kind::TextInput,
84
+ "OrbitImage" => Kind::Image,
85
+ "OrbitVector" => Kind::Vector,
86
+ _ => Kind::View,
87
+ }
88
+ }
89
+ fn is_layout(self) -> bool {
90
+ matches!(
91
+ self,
92
+ Kind::View | Kind::Scroll | Kind::Text | Kind::TextInput | Kind::Image | Kind::Vector
93
+ )
94
+ }
95
+ }
96
+
97
+ #[derive(Clone, Default, PartialEq, Debug)]
98
+ struct TextStyle {
99
+ color: Option<i32>,
100
+ size: Option<f32>,
101
+ /// The CSS font weight, 100..=900.
102
+ weight: Option<u16>,
103
+ italic: Option<bool>,
104
+ line_height: Option<f32>,
105
+ align: Option<u8>,
106
+ }
107
+
108
+ impl TextStyle {
109
+ fn over(&self, base: &TextStyle) -> TextStyle {
110
+ TextStyle {
111
+ color: self.color.or(base.color),
112
+ size: self.size.or(base.size),
113
+ weight: self.weight.or(base.weight),
114
+ italic: self.italic.or(base.italic),
115
+ line_height: self.line_height.or(base.line_height),
116
+ align: self.align.or(base.align),
117
+ }
118
+ }
119
+ }
120
+
121
+ #[derive(Clone, Default, PartialEq, Debug)]
122
+ struct Visual {
123
+ background: Option<i32>,
124
+ border_color: Option<i32>,
125
+ border_width: f32,
126
+ radius: f32,
127
+ opacity: f32,
128
+ }
129
+
130
+ struct Node {
131
+ kind: Kind,
132
+ props: Map<String, Value>,
133
+ taffy: Option<NodeId>,
134
+ children: Vec<i32>,
135
+ text: String,
136
+ /// A vector node's drawing, encoded when its `vector` prop is set.
137
+ vector: Vec<u8>,
138
+ }
139
+
140
+ /// What a view draws beyond its box: a CSS box shadow, a backdrop blur, and
141
+ /// whether it clips its children (`overflow: hidden`).
142
+ #[derive(Clone, Default, PartialEq, Debug)]
143
+ struct Effects {
144
+ shadow_x: f32,
145
+ shadow_y: f32,
146
+ shadow_blur: f32,
147
+ shadow_spread: f32,
148
+ shadow_color: i32,
149
+ backdrop_blur: f32,
150
+ clip: bool,
151
+ }
152
+
153
+ #[derive(Default)]
154
+ struct Mounted {
155
+ frame: [f32; 4],
156
+ visual: Option<Visual>,
157
+ effects: Option<Effects>,
158
+ text: Vec<u8>,
159
+ children: Vec<i32>,
160
+ }
161
+
162
+ #[derive(Default, Debug)]
163
+ pub struct CommitInfo {
164
+ pub deleted: Vec<i32>,
165
+ pub parse_us: u128,
166
+ pub layout_us: u128,
167
+ pub diff_us: u128,
168
+ pub measures: u32,
169
+ pub nodes: usize,
170
+ /// Values of drawings left out, coded (`E_ORBIT_SVG_VALUE: …`).
171
+ pub warnings: Vec<String>,
172
+ }
173
+
174
+ pub struct Host {
175
+ nodes: HashMap<i32, Node>,
176
+ parent: HashMap<i32, i32>,
177
+ tree: TaffyTree<i32>,
178
+ root: Option<i32>,
179
+ mounted_root: Option<i32>,
180
+ mounted: HashMap<i32, Mounted>,
181
+ spans: HashMap<i32, Vec<u8>>,
182
+ measure_cache: HashMap<(u64, u32), (f32, f32)>,
183
+ viewport: (f32, f32),
184
+ measure: Option<MeasureFn>,
185
+ }
186
+
187
+ impl Default for Host {
188
+ fn default() -> Self {
189
+ Host {
190
+ nodes: HashMap::new(),
191
+ parent: HashMap::new(),
192
+ tree: TaffyTree::new(),
193
+ root: None,
194
+ mounted_root: None,
195
+ mounted: HashMap::new(),
196
+ spans: HashMap::new(),
197
+ measure_cache: HashMap::new(),
198
+ viewport: (400.0, 800.0),
199
+ measure: None,
200
+ }
201
+ }
202
+ }
203
+
204
+ // ---------------------------------------------------------------- props -> style
205
+
206
+ fn num(v: &Value) -> Option<f32> {
207
+ match v {
208
+ Value::Number(n) => n.as_f64().map(|f| f as f32),
209
+ Value::String(s) => s.trim_end_matches("px").parse::<f32>().ok(),
210
+ _ => None,
211
+ }
212
+ }
213
+
214
+ fn color(v: &Value) -> Option<i32> {
215
+ v.as_i64().map(|n| n as i32)
216
+ }
217
+
218
+ fn dimension(v: &Value) -> Dimension {
219
+ match v {
220
+ Value::String(s) if s.ends_with('%') => s
221
+ .trim_end_matches('%')
222
+ .parse::<f32>()
223
+ .map(|p| Dimension::percent(p / 100.0))
224
+ .unwrap_or(Dimension::auto()),
225
+ Value::String(s) if s == "auto" => Dimension::auto(),
226
+ _ => num(v).map(Dimension::length).unwrap_or(Dimension::auto()),
227
+ }
228
+ }
229
+
230
+ fn length_percentage(v: &Value) -> LengthPercentage {
231
+ match v {
232
+ Value::String(s) if s.ends_with('%') => s
233
+ .trim_end_matches('%')
234
+ .parse::<f32>()
235
+ .map(|p| LengthPercentage::percent(p / 100.0))
236
+ .unwrap_or(LengthPercentage::length(0.0)),
237
+ _ => LengthPercentage::length(num(v).unwrap_or(0.0)),
238
+ }
239
+ }
240
+
241
+ fn length_percentage_auto(v: &Value) -> LengthPercentageAuto {
242
+ match v {
243
+ Value::String(s) if s == "auto" => LengthPercentageAuto::auto(),
244
+ Value::String(s) if s.ends_with('%') => s
245
+ .trim_end_matches('%')
246
+ .parse::<f32>()
247
+ .map(|p| LengthPercentageAuto::percent(p / 100.0))
248
+ .unwrap_or(LengthPercentageAuto::length(0.0)),
249
+ _ => LengthPercentageAuto::length(num(v).unwrap_or(0.0)),
250
+ }
251
+ }
252
+
253
+ /// A min or max size. Unparseable means no bound, as it did when these took a
254
+ /// `Dimension`; a margin or inset parses `length_percentage_auto` instead,
255
+ /// where unparseable means zero.
256
+ fn size_bound(v: &Value) -> LengthPercentageAuto {
257
+ match v {
258
+ Value::String(s) if s.ends_with('%') => s
259
+ .trim_end_matches('%')
260
+ .parse::<f32>()
261
+ .map(|p| LengthPercentageAuto::percent(p / 100.0))
262
+ .unwrap_or(LengthPercentageAuto::auto()),
263
+ _ => num(v)
264
+ .map(LengthPercentageAuto::length)
265
+ .unwrap_or(LengthPercentageAuto::auto()),
266
+ }
267
+ }
268
+
269
+ fn align(v: &Value) -> Option<AlignItems> {
270
+ match v.as_str()? {
271
+ "flex-start" | "start" => Some(AlignItems::FLEX_START),
272
+ "flex-end" | "end" => Some(AlignItems::FLEX_END),
273
+ "center" => Some(AlignItems::CENTER),
274
+ "stretch" => Some(AlignItems::STRETCH),
275
+ "baseline" => Some(AlignItems::BASELINE),
276
+ _ => None,
277
+ }
278
+ }
279
+
280
+ fn justify(v: &Value) -> Option<JustifyContent> {
281
+ match v.as_str()? {
282
+ "flex-start" | "start" => Some(JustifyContent::FLEX_START),
283
+ "flex-end" | "end" => Some(JustifyContent::FLEX_END),
284
+ "center" => Some(JustifyContent::CENTER),
285
+ "space-between" => Some(JustifyContent::SPACE_BETWEEN),
286
+ "space-around" => Some(JustifyContent::SPACE_AROUND),
287
+ "space-evenly" => Some(JustifyContent::SPACE_EVENLY),
288
+ _ => None,
289
+ }
290
+ }
291
+
292
+ /// Four-sided shorthand in React Native's precedence: side > axis > all.
293
+ fn sides<T: Copy>(
294
+ props: &Map<String, Value>,
295
+ prefix: &str,
296
+ suffix: &str,
297
+ zero: T,
298
+ parse: fn(&Value) -> T,
299
+ ) -> Rect<T> {
300
+ let get = |name: &str| props.get(&format!("{prefix}{name}{suffix}")).map(parse);
301
+ let all = get("").unwrap_or(zero);
302
+ let horizontal = get("Horizontal").unwrap_or(all);
303
+ let vertical = get("Vertical").unwrap_or(all);
304
+ Rect {
305
+ left: get("Left").or_else(|| get("Start")).unwrap_or(horizontal),
306
+ right: get("Right").or_else(|| get("End")).unwrap_or(horizontal),
307
+ top: get("Top").unwrap_or(vertical),
308
+ bottom: get("Bottom").unwrap_or(vertical),
309
+ }
310
+ }
311
+
312
+ fn style_of(props: &Map<String, Value>) -> Style {
313
+ // React Native's defaults, not CSS's: column, no shrink, and relative
314
+ // positioning — insets apply to every box and an absolute child is placed
315
+ // in its parent, not in the nearest positioned ancestor (taffy, like CSS,
316
+ // defaults to `static` since 0.15).
317
+ let mut s = Style {
318
+ flex_direction: FlexDirection::Column,
319
+ flex_shrink: 0.0,
320
+ position: Position::Relative,
321
+ ..Style::default()
322
+ };
323
+ if let Some(v) = props.get("flexDirection").and_then(Value::as_str) {
324
+ s.flex_direction = match v {
325
+ "row" => FlexDirection::Row,
326
+ "row-reverse" => FlexDirection::RowReverse,
327
+ "column-reverse" => FlexDirection::ColumnReverse,
328
+ _ => FlexDirection::Column,
329
+ };
330
+ }
331
+ if props.get("flexWrap").and_then(Value::as_str) == Some("wrap") {
332
+ s.flex_wrap = FlexWrap::Wrap;
333
+ }
334
+ if let Some(f) = props.get("flex").and_then(num) {
335
+ if f > 0.0 {
336
+ s.flex_grow = f;
337
+ s.flex_shrink = 1.0;
338
+ s.flex_basis = Dimension::length(0.0);
339
+ }
340
+ }
341
+ if let Some(f) = props.get("flexGrow").and_then(num) {
342
+ s.flex_grow = f;
343
+ }
344
+ if let Some(f) = props.get("flexShrink").and_then(num) {
345
+ s.flex_shrink = f;
346
+ }
347
+ if let Some(v) = props.get("flexBasis") {
348
+ s.flex_basis = dimension(v);
349
+ }
350
+ // `normal` is what an unset value meant: stretch for align-items, start
351
+ // for justify-content, in a flex container.
352
+ s.align_items = props
353
+ .get("alignItems")
354
+ .and_then(align)
355
+ .unwrap_or(AlignItems::NORMAL);
356
+ s.align_self = props.get("alignSelf").and_then(align);
357
+ s.justify_content = props
358
+ .get("justifyContent")
359
+ .and_then(justify)
360
+ .unwrap_or(JustifyContent::NORMAL);
361
+ for (key, slot) in [("width", &mut s.size.width), ("height", &mut s.size.height)] {
362
+ if let Some(v) = props.get(key) {
363
+ *slot = dimension(v);
364
+ }
365
+ }
366
+ for (key, slot) in [
367
+ ("minWidth", &mut s.min_size.width),
368
+ ("minHeight", &mut s.min_size.height),
369
+ ("maxWidth", &mut s.max_size.width),
370
+ ("maxHeight", &mut s.max_size.height),
371
+ ] {
372
+ if let Some(v) = props.get(key) {
373
+ *slot = size_bound(v);
374
+ }
375
+ }
376
+ s.padding = sides(
377
+ props,
378
+ "padding",
379
+ "",
380
+ LengthPercentage::length(0.0),
381
+ length_percentage,
382
+ );
383
+ s.margin = sides(
384
+ props,
385
+ "margin",
386
+ "",
387
+ LengthPercentageAuto::length(0.0),
388
+ length_percentage_auto,
389
+ );
390
+ s.border = sides(
391
+ props,
392
+ "border",
393
+ "Width",
394
+ LengthPercentage::length(0.0),
395
+ length_percentage,
396
+ );
397
+ let gap = props
398
+ .get("gap")
399
+ .map(length_percentage)
400
+ .unwrap_or(LengthPercentage::length(0.0));
401
+ s.gap = Size {
402
+ width: props.get("columnGap").map(length_percentage).unwrap_or(gap),
403
+ height: props.get("rowGap").map(length_percentage).unwrap_or(gap),
404
+ };
405
+ if props.get("position").and_then(Value::as_str) == Some("absolute") {
406
+ s.position = Position::Absolute;
407
+ }
408
+ s.inset = Rect {
409
+ left: props
410
+ .get("left")
411
+ .map(length_percentage_auto)
412
+ .unwrap_or(LengthPercentageAuto::auto()),
413
+ right: props
414
+ .get("right")
415
+ .map(length_percentage_auto)
416
+ .unwrap_or(LengthPercentageAuto::auto()),
417
+ top: props
418
+ .get("top")
419
+ .map(length_percentage_auto)
420
+ .unwrap_or(LengthPercentageAuto::auto()),
421
+ bottom: props
422
+ .get("bottom")
423
+ .map(length_percentage_auto)
424
+ .unwrap_or(LengthPercentageAuto::auto()),
425
+ };
426
+ s.aspect_ratio = props.get("aspectRatio").and_then(num);
427
+ if props.get("display").and_then(Value::as_str) == Some("none") {
428
+ s.display = Display::None;
429
+ }
430
+ s
431
+ }
432
+
433
+ /// A scroll view does not grow to its content: its content child does, and
434
+ /// the platform scrolls that child inside the view's frame.
435
+ fn style_for(kind: Kind, props: &Map<String, Value>) -> Style {
436
+ let mut s = style_of(props);
437
+ if kind == Kind::Scroll {
438
+ s.overflow = taffy::geometry::Point {
439
+ x: taffy::style::Overflow::Visible,
440
+ y: taffy::style::Overflow::Scroll,
441
+ };
442
+ s.scrollbar_width = 0.0;
443
+ }
444
+ s
445
+ }
446
+
447
+ fn visual_of(props: &Map<String, Value>) -> Visual {
448
+ Visual {
449
+ background: props.get("backgroundColor").and_then(color),
450
+ border_color: props.get("borderColor").and_then(color),
451
+ border_width: props.get("borderWidth").and_then(num).unwrap_or(0.0),
452
+ radius: props.get("borderRadius").and_then(num).unwrap_or(0.0),
453
+ opacity: props.get("opacity").and_then(num).unwrap_or(1.0),
454
+ }
455
+ }
456
+
457
+ /// The gestures a node's handlers ask for (see `gesture`).
458
+ fn gesture_flags(props: &Map<String, Value>) -> u8 {
459
+ props
460
+ .get("gestures")
461
+ .and_then(Value::as_u64)
462
+ .map(|n| (n & 0xff) as u8)
463
+ .unwrap_or(0)
464
+ }
465
+
466
+ fn effects_of(props: &Map<String, Value>) -> Effects {
467
+ let length = |key: &str| props.get(key).and_then(num).unwrap_or(0.0);
468
+ Effects {
469
+ shadow_x: length("shadowX"),
470
+ shadow_y: length("shadowY"),
471
+ shadow_blur: length("shadowBlur").max(0.0),
472
+ shadow_spread: length("shadowSpread"),
473
+ shadow_color: props.get("shadowColor").and_then(color).unwrap_or(0),
474
+ backdrop_blur: length("backdropBlur").max(0.0),
475
+ clip: props.get("overflow").and_then(Value::as_str) == Some("hidden"),
476
+ }
477
+ }
478
+
479
+ fn text_style_of(props: &Map<String, Value>) -> TextStyle {
480
+ TextStyle {
481
+ color: props.get("color").and_then(color),
482
+ size: props.get("fontSize").and_then(num),
483
+ weight: props.get("fontWeight").and_then(|w| match w {
484
+ Value::String(s) if s == "bold" => Some(700),
485
+ Value::String(s) if s == "normal" => Some(400),
486
+ Value::String(s) => s.parse::<u16>().ok(),
487
+ Value::Number(n) => n.as_u64().map(|n| n as u16),
488
+ _ => None,
489
+ }),
490
+ italic: props
491
+ .get("fontStyle")
492
+ .and_then(Value::as_str)
493
+ .map(|s| s == "italic"),
494
+ line_height: props.get("lineHeight").and_then(num),
495
+ align: props
496
+ .get("textAlign")
497
+ .and_then(Value::as_str)
498
+ .map(|s| match s {
499
+ "center" => 1,
500
+ "right" => 2,
501
+ _ => 0,
502
+ }),
503
+ }
504
+ }
505
+
506
+ // ---------------------------------------------------------------- encoding
507
+
508
+ /// A run's flags: bit 0 bold (600 and up), bit 1 italic, bits 4.. the weight.
509
+ fn run_flags(style: &TextStyle) -> i32 {
510
+ let weight = i32::from(style.weight.unwrap_or(400).clamp(1, 1000));
511
+ i32::from(weight >= 600) | (i32::from(style.italic.unwrap_or(false)) << 1) | (weight << 4)
512
+ }
513
+
514
+ fn put_i32(out: &mut Vec<u8>, v: i32) {
515
+ out.extend_from_slice(&v.to_le_bytes());
516
+ }
517
+ fn put_f32(out: &mut Vec<u8>, v: f32) {
518
+ out.extend_from_slice(&v.to_le_bytes());
519
+ }
520
+
521
+ const DEFAULT_INPUT_WIDTH: f32 = 160.0;
522
+
523
+ /// What a text field is measured with: one sample line per row, in its font.
524
+ fn encode_input_sample(props: &Map<String, Value>) -> Vec<u8> {
525
+ let style = text_style_of(props);
526
+ let rows = props
527
+ .get("rows")
528
+ .and_then(num)
529
+ .map(|r| r.max(1.0) as usize)
530
+ .unwrap_or(1);
531
+ // Sized by its content (CSS field-sizing): measured on what it holds,
532
+ // wraps included, so it grows with its lines; empty, it keeps its rows.
533
+ let content = props
534
+ .get("measureText")
535
+ .or_else(|| props.get("text"))
536
+ .and_then(Value::as_str)
537
+ .unwrap_or("");
538
+ let sized_by_content = props.get("fieldSizing").and_then(Value::as_str) == Some("content");
539
+ let sample = if sized_by_content && !content.is_empty() {
540
+ content.to_owned()
541
+ } else {
542
+ vec!["Mg"; rows].join("\n")
543
+ };
544
+ let mut out = vec![0u8];
545
+ put_f32(&mut out, style.line_height.unwrap_or(0.0));
546
+ put_i32(&mut out, 1);
547
+ put_i32(&mut out, style.color.unwrap_or(0xFF00_0000u32 as i32));
548
+ put_f32(&mut out, style.size.unwrap_or(14.0));
549
+ let flags = run_flags(&style);
550
+ put_i32(&mut out, flags);
551
+ put_i32(&mut out, sample.len() as i32);
552
+ out.extend_from_slice(sample.as_bytes());
553
+ out
554
+ }
555
+
556
+ /// A text field's mount payload: its props as JSON, plus the padding taffy
557
+ /// placed around its text (the platform field insets its text by it).
558
+ fn encode_input(props: &Map<String, Value>, layout: &taffy::Layout) -> Vec<u8> {
559
+ let mut field = Map::new();
560
+ for key in [
561
+ "placeholder",
562
+ "placeholderColor",
563
+ "multiline",
564
+ "rows",
565
+ "secure",
566
+ "keyboard",
567
+ "maxLength",
568
+ "editable",
569
+ "autocomplete",
570
+ "text",
571
+ "textVersion",
572
+ "fontSize",
573
+ "color",
574
+ "fontWeight",
575
+ "fontStyle",
576
+ "textAlign",
577
+ ] {
578
+ if let Some(v) = props.get(key) {
579
+ field.insert(key.to_owned(), v.clone());
580
+ }
581
+ }
582
+ let p = layout.padding;
583
+ field.insert(
584
+ "padding".to_owned(),
585
+ serde_json::json!([p.left, p.top, p.right, p.bottom]),
586
+ );
587
+ Value::Object(field).to_string().into_bytes()
588
+ }
589
+
590
+ /// An image's mount payload: where it comes from, how it fits its box, and
591
+ /// what a screen reader says. Its frame and corners travel as for any view.
592
+ fn encode_image(props: &Map<String, Value>) -> Vec<u8> {
593
+ let text = |key: &str| props.get(key).and_then(Value::as_str).unwrap_or("");
594
+ serde_json::json!({
595
+ "src": text("src"),
596
+ "fit": match text("objectFit") {
597
+ fit @ ("cover" | "contain" | "none" | "scale-down") => fit,
598
+ _ => "fill",
599
+ },
600
+ "alt": text("alt"),
601
+ })
602
+ .to_string()
603
+ .into_bytes()
604
+ }
605
+
606
+ impl Host {
607
+ fn set_measure(&mut self, measure: MeasureFn) {
608
+ self.measure = Some(measure);
609
+ }
610
+
611
+ fn set_viewport(&mut self, width: f32, height: f32) {
612
+ self.viewport = (width, height);
613
+ }
614
+
615
+ /// The attributed text of a Text node: its runs with inherited styles.
616
+ fn encode_text(&self, tag: i32) -> Vec<u8> {
617
+ if let Some(node) = self.nodes.get(&tag) {
618
+ if node.kind == Kind::TextInput {
619
+ return encode_input_sample(&node.props);
620
+ }
621
+ }
622
+ let mut runs: Vec<(TextStyle, String)> = Vec::new();
623
+ let Some(node) = self.nodes.get(&tag) else {
624
+ return Vec::new();
625
+ };
626
+ let base = text_style_of(&node.props);
627
+ self.collect_runs(&node.children, &base, &mut runs);
628
+ let mut out = Vec::new();
629
+ out.push(base.align.unwrap_or(0));
630
+ put_f32(&mut out, base.line_height.unwrap_or(0.0));
631
+ put_i32(&mut out, runs.len() as i32);
632
+ for (style, text) in runs {
633
+ put_i32(&mut out, style.color.unwrap_or(0xFF00_0000u32 as i32));
634
+ put_f32(&mut out, style.size.unwrap_or(14.0));
635
+ let flags = run_flags(&style);
636
+ put_i32(&mut out, flags);
637
+ put_i32(&mut out, text.len() as i32);
638
+ out.extend_from_slice(text.as_bytes());
639
+ }
640
+ out
641
+ }
642
+
643
+ fn collect_runs(
644
+ &self,
645
+ children: &[i32],
646
+ inherited: &TextStyle,
647
+ runs: &mut Vec<(TextStyle, String)>,
648
+ ) {
649
+ for child in children {
650
+ let Some(node) = self.nodes.get(child) else {
651
+ continue;
652
+ };
653
+ match node.kind {
654
+ Kind::RawText => runs.push((inherited.clone(), node.text.clone())),
655
+ Kind::VirtualText | Kind::Text => {
656
+ let style = text_style_of(&node.props).over(inherited);
657
+ self.collect_runs(&node.children, &style, runs);
658
+ }
659
+ Kind::View | Kind::Scroll | Kind::TextInput | Kind::Image | Kind::Vector => {}
660
+ }
661
+ }
662
+ }
663
+
664
+ /// The Text node a text-bearing node belongs to (itself for a Text).
665
+ /// A path to the root is never longer than the tree is large: a longer
666
+ /// walk is going round a cycle a bad batch made.
667
+ fn owning_text(&self, mut tag: i32) -> Option<i32> {
668
+ for _ in 0..=self.nodes.len() {
669
+ let node = self.nodes.get(&tag)?;
670
+ if matches!(node.kind, Kind::Text | Kind::TextInput) {
671
+ return Some(tag);
672
+ }
673
+ tag = *self.parent.get(&tag)?;
674
+ }
675
+ None
676
+ }
677
+
678
+ /// Where nodes were laid out: `[x, y, width, height]` in the root's
679
+ /// coordinates (a scroll view's offset left out), or null for a tag with
680
+ /// no layout. A lazy list reads its rows' heights and its viewport here.
681
+ pub fn frames(&self, tags: &[i32]) -> Vec<Option<[f32; 4]>> {
682
+ tags.iter()
683
+ .map(|&tag| {
684
+ let id = self.nodes.get(&tag)?.taffy?;
685
+ let own = self.tree.layout(id).ok()?;
686
+ let (mut x, mut y) = (own.location.x, own.location.y);
687
+ let mut at = tag;
688
+ let mut steps = 0;
689
+ while let Some(&parent) = self.parent.get(&at) {
690
+ // A cycle a bad batch made (see `owning_text`).
691
+ steps += 1;
692
+ if steps > self.nodes.len() {
693
+ return None;
694
+ }
695
+ if let Some(id) = self.nodes.get(&parent).and_then(|n| n.taffy) {
696
+ let layout = self.tree.layout(id).ok()?;
697
+ x += layout.location.x;
698
+ y += layout.location.y;
699
+ }
700
+ at = parent;
701
+ }
702
+ Some([x, y, own.size.width, own.size.height])
703
+ })
704
+ .collect()
705
+ }
706
+
707
+ /// Refuse a tree taffy would recurse into deeper than `MAX_DEPTH`: the
708
+ /// paths taffy follows, walked without recursion. A node reached again
709
+ /// (two parents) is not walked twice; a cycle never ends, so it is
710
+ /// refused as too deep.
711
+ fn check_depth(&self, root: NodeId) -> Result<(), String> {
712
+ let too_deep = || {
713
+ format!(
714
+ "E_ORBIT_TREE_TOO_DEEP: the views nest more than {MAX_DEPTH} levels deep, \
715
+ more than the host lays out"
716
+ )
717
+ };
718
+ // The levels below and including each node walked whole.
719
+ let mut height: HashMap<NodeId, usize> = HashMap::new();
720
+ // The path being walked: each node, its children, the next one to visit,
721
+ // and the tallest child seen so far.
722
+ let children = |id: NodeId| self.tree.children(id).unwrap_or_default();
723
+ let mut path: Vec<(NodeId, Vec<NodeId>, usize, usize)> = vec![(root, children(root), 0, 0)];
724
+ while let Some(top) = path.last_mut() {
725
+ let (id, kids, next, tallest) = (top.0, &top.1, top.2, top.3);
726
+ if let Some(&child) = kids.get(next) {
727
+ top.2 += 1;
728
+ let level = path.len() + 1;
729
+ if let Some(&h) = height.get(&child) {
730
+ if level - 1 + h > MAX_DEPTH {
731
+ return Err(too_deep());
732
+ }
733
+ if let Some(top) = path.last_mut() {
734
+ top.3 = top.3.max(h);
735
+ }
736
+ continue;
737
+ }
738
+ if level > MAX_DEPTH {
739
+ return Err(too_deep());
740
+ }
741
+ path.push((child, children(child), 0, 0));
742
+ } else {
743
+ path.pop();
744
+ height.insert(id, tallest + 1);
745
+ if let Some(parent) = path.last_mut() {
746
+ parent.3 = parent.3.max(tallest + 1);
747
+ }
748
+ }
749
+ }
750
+ Ok(())
751
+ }
752
+
753
+ pub fn commit(&mut self, ops_json: &[u8], out: &mut Vec<u8>) -> Result<CommitInfo, String> {
754
+ let mut info = CommitInfo::default();
755
+ let t0 = Instant::now();
756
+ let ops: Vec<Value> = serde_json::from_slice(ops_json).map_err(|e| e.to_string())?;
757
+ let mut text_dirty: HashSet<i32> = HashSet::new();
758
+ let mut touched: Vec<i32> = Vec::new();
759
+ for op in &ops {
760
+ let Some(arr) = op.as_array() else { continue };
761
+ let code = arr.first().and_then(Value::as_str).unwrap_or("");
762
+ let tag = arr.get(1).and_then(Value::as_i64).unwrap_or(0) as i32;
763
+ match code {
764
+ "c" => {
765
+ let kind = Kind::of(arr.get(2).and_then(Value::as_str).unwrap_or("RCTView"));
766
+ let props = arr
767
+ .get(3)
768
+ .and_then(Value::as_object)
769
+ .cloned()
770
+ .unwrap_or_default();
771
+ let text = props
772
+ .get("text")
773
+ .and_then(Value::as_str)
774
+ .unwrap_or("")
775
+ .to_owned();
776
+ let vector = match (kind, props.get("vector")) {
777
+ (Kind::Vector, Some(v)) => vector::encode(v, &mut info.warnings),
778
+ _ => Vec::new(),
779
+ };
780
+ // Sent again after a refused batch the host had applied in part.
781
+ if let Some(old) = self.nodes.remove(&tag) {
782
+ if let Some(id) = old.taffy {
783
+ let _ = self.tree.remove(id);
784
+ }
785
+ }
786
+ if kind.is_layout() {
787
+ let flags = gesture_flags(&props);
788
+ gesture::with(|g| g.set_node(tag, flags, kind == Kind::Scroll));
789
+ }
790
+ let taffy = if kind.is_layout() {
791
+ Some(
792
+ self.tree
793
+ .new_leaf_with_context(style_for(kind, &props), tag)
794
+ .map_err(|e| e.to_string())?,
795
+ )
796
+ } else {
797
+ None
798
+ };
799
+ self.nodes.insert(
800
+ tag,
801
+ Node {
802
+ kind,
803
+ props,
804
+ taffy,
805
+ children: Vec::new(),
806
+ text,
807
+ vector,
808
+ },
809
+ );
810
+ touched.push(tag);
811
+ }
812
+ "u" => {
813
+ let patch = arr
814
+ .get(2)
815
+ .and_then(Value::as_object)
816
+ .cloned()
817
+ .unwrap_or_default();
818
+ if let Some(node) = self.nodes.get_mut(&tag) {
819
+ if patch.contains_key("gestures") && node.kind.is_layout() {
820
+ let flags = gesture_flags(&patch);
821
+ let scroll = node.kind == Kind::Scroll;
822
+ gesture::with(|g| g.set_node(tag, flags, scroll));
823
+ }
824
+ if let Some(t) = patch.get("text").and_then(Value::as_str) {
825
+ node.text = t.to_owned();
826
+ }
827
+ if let (Kind::Vector, Some(v)) = (node.kind, patch.get("vector")) {
828
+ node.vector = vector::encode(v, &mut info.warnings);
829
+ }
830
+ node.props.extend(patch);
831
+ if let Some(id) = node.taffy {
832
+ self.tree
833
+ .set_style(id, style_for(node.kind, &node.props))
834
+ .map_err(|e| e.to_string())?;
835
+ }
836
+ touched.push(tag);
837
+ }
838
+ }
839
+ "k" => {
840
+ let children: Vec<i32> = arr
841
+ .get(2)
842
+ .and_then(Value::as_array)
843
+ .map(|a| {
844
+ a.iter()
845
+ .filter_map(Value::as_i64)
846
+ .map(|n| n as i32)
847
+ .collect()
848
+ })
849
+ .unwrap_or_default();
850
+ for child in &children {
851
+ self.parent.insert(*child, tag);
852
+ }
853
+ gesture::with(|g| {
854
+ for child in &children {
855
+ g.set_parent(*child, tag);
856
+ }
857
+ });
858
+ let layout_children: Vec<NodeId> = children
859
+ .iter()
860
+ .filter_map(|c| self.nodes.get(c).and_then(|n| n.taffy))
861
+ .collect();
862
+ if let Some(node) = self.nodes.get_mut(&tag) {
863
+ node.children = children;
864
+ if matches!(node.kind, Kind::View | Kind::Scroll) {
865
+ if let Some(id) = node.taffy {
866
+ self.tree
867
+ .set_children(id, &layout_children)
868
+ .map_err(|e| e.to_string())?;
869
+ }
870
+ }
871
+ touched.push(tag);
872
+ }
873
+ }
874
+ "r" => self.root = Some(tag),
875
+ _ => {}
876
+ }
877
+ }
878
+ for tag in touched {
879
+ if let Some(text) = self.owning_text(tag) {
880
+ text_dirty.insert(text);
881
+ }
882
+ }
883
+ for text in text_dirty {
884
+ let encoded = self.encode_text(text);
885
+ if self.spans.get(&text) != Some(&encoded) {
886
+ self.spans.insert(text, encoded);
887
+ if let Some(id) = self.nodes.get(&text).and_then(|n| n.taffy) {
888
+ self.tree.mark_dirty(id).map_err(|e| e.to_string())?;
889
+ }
890
+ }
891
+ }
892
+ info.parse_us = t0.elapsed().as_micros();
893
+
894
+ let Some(root) = self.root else {
895
+ return Ok(info);
896
+ };
897
+ let Some(root_id) = self.nodes.get(&root).and_then(|n| n.taffy) else {
898
+ return Ok(info);
899
+ };
900
+ self.check_depth(root_id)?;
901
+ let t1 = Instant::now();
902
+ let mut root_style = self.tree.style(root_id).map_err(|e| e.to_string())?.clone();
903
+ root_style.size = Size {
904
+ width: Dimension::length(self.viewport.0),
905
+ height: Dimension::length(self.viewport.1),
906
+ };
907
+ self.tree
908
+ .set_style(root_id, root_style)
909
+ .map_err(|e| e.to_string())?;
910
+ {
911
+ let inputs: HashSet<i32> = self
912
+ .nodes
913
+ .iter()
914
+ .filter(|(_, n)| n.kind == Kind::TextInput)
915
+ .map(|(t, _)| *t)
916
+ .collect();
917
+ let Host {
918
+ tree,
919
+ spans,
920
+ measure_cache,
921
+ measure,
922
+ ..
923
+ } = self;
924
+ let measure = *measure;
925
+ let mut measures = 0u32;
926
+ tree.compute_layout_with_measure(
927
+ root_id,
928
+ Size {
929
+ width: AvailableSpace::Definite(self.viewport.0),
930
+ height: AvailableSpace::Definite(self.viewport.1),
931
+ },
932
+ |input, _id, ctx, style| {
933
+ // Since taffy 0.14 the leaf's box model (padding, border,
934
+ // min/max, aspect ratio) is the caller's: compute_leaf_layout
935
+ // applies it around the content measure, as taffy did itself.
936
+ let tag = ctx.map(|t| *t);
937
+ taffy::compute_leaf_layout(
938
+ input,
939
+ style,
940
+ |_, _| 0.0,
941
+ |known, available| {
942
+ if let (Some(w), Some(h)) = (known.width, known.height) {
943
+ return Size {
944
+ width: w,
945
+ height: h,
946
+ };
947
+ }
948
+ let Some(tag) = tag else {
949
+ return Size::ZERO;
950
+ };
951
+ let Some(encoded) = spans.get(&tag) else {
952
+ return Size::ZERO;
953
+ };
954
+ let max_width = known.width.unwrap_or(match available.width {
955
+ AvailableSpace::Definite(w) => w,
956
+ AvailableSpace::MinContent => 0.0,
957
+ AvailableSpace::MaxContent => f32::INFINITY,
958
+ });
959
+ let mut hasher = DefaultHasher::new();
960
+ encoded.hash(&mut hasher);
961
+ let hash = hasher.finish();
962
+ let mut call = |width: f32| {
963
+ measures += 1;
964
+ match measure {
965
+ Some(f) => {
966
+ let packed = f(encoded.as_ptr(), encoded.len(), width);
967
+ (
968
+ f32::from_bits((packed >> 32) as u32),
969
+ f32::from_bits(packed as u32),
970
+ )
971
+ }
972
+ // Desktop tests: 7 dp per byte, 16 dp per line.
973
+ None => ((encoded.len() as f32 * 7.0).min(width), 16.0),
974
+ }
975
+ };
976
+ // One platform call per text in the common case: its natural
977
+ // size answers every constraint at least that wide. Only a
978
+ // narrower constraint (wrapping) costs another call.
979
+ let natural = *measure_cache
980
+ .entry((hash, f32::INFINITY.to_bits()))
981
+ .or_insert_with(|| call(f32::INFINITY));
982
+ let (w, h) = if max_width >= natural.0 {
983
+ natural
984
+ } else {
985
+ *measure_cache
986
+ .entry((hash, max_width.to_bits()))
987
+ .or_insert_with(|| call(max_width))
988
+ };
989
+ // A field is as wide as its box says, like an HTML input:
990
+ // its text does not size it. 160 dp when nothing does.
991
+ let w = if inputs.contains(&tag) {
992
+ DEFAULT_INPUT_WIDTH
993
+ } else {
994
+ w
995
+ };
996
+ Size {
997
+ width: known.width.unwrap_or(w),
998
+ height: known.height.unwrap_or(h),
999
+ }
1000
+ },
1001
+ )
1002
+ },
1003
+ )
1004
+ .map_err(|e| e.to_string())?;
1005
+ info.measures = measures;
1006
+ }
1007
+ info.layout_us = t1.elapsed().as_micros();
1008
+
1009
+ let t2 = Instant::now();
1010
+ let mut reachable: Vec<i32> = Vec::new();
1011
+ let mut stack = vec![root];
1012
+ while let Some(tag) = stack.pop() {
1013
+ let Some(node) = self.nodes.get(&tag) else {
1014
+ continue;
1015
+ };
1016
+ reachable.push(tag);
1017
+ stack.extend(node.children.iter().rev());
1018
+ }
1019
+ let reachable_set: HashSet<i32> = reachable.iter().copied().collect();
1020
+ let mut creates = Vec::new();
1021
+ let mut attrs = Vec::new();
1022
+ let mut kids = Vec::new();
1023
+ for &tag in &reachable {
1024
+ let Some(node) = self.nodes.get(&tag) else {
1025
+ continue;
1026
+ };
1027
+ if !node.kind.is_layout() {
1028
+ continue;
1029
+ }
1030
+ let Some(id) = node.taffy else { continue };
1031
+ let mounted = self.mounted.entry(tag).or_insert_with(|| {
1032
+ creates.push(OP_CREATE);
1033
+ put_i32(&mut creates, tag);
1034
+ creates.push(match node.kind {
1035
+ Kind::Text => KIND_TEXT,
1036
+ Kind::Scroll => KIND_SCROLL,
1037
+ Kind::TextInput => KIND_INPUT,
1038
+ Kind::Image => KIND_IMAGE,
1039
+ Kind::Vector => KIND_VECTOR,
1040
+ _ => KIND_VIEW,
1041
+ });
1042
+ Mounted {
1043
+ frame: [f32::NAN; 4],
1044
+ ..Mounted::default()
1045
+ }
1046
+ });
1047
+ let layout = self.tree.layout(id).map_err(|e| e.to_string())?;
1048
+ let frame = [
1049
+ layout.location.x,
1050
+ layout.location.y,
1051
+ layout.size.width,
1052
+ layout.size.height,
1053
+ ];
1054
+ if frame != mounted.frame {
1055
+ attrs.push(OP_FRAME);
1056
+ put_i32(&mut attrs, tag);
1057
+ for v in frame {
1058
+ put_f32(&mut attrs, v);
1059
+ }
1060
+ mounted.frame = frame;
1061
+ }
1062
+ let visual = visual_of(&node.props);
1063
+ if mounted.visual.as_ref() != Some(&visual) {
1064
+ attrs.push(OP_VIEW_STYLE);
1065
+ put_i32(&mut attrs, tag);
1066
+ put_i32(&mut attrs, visual.background.unwrap_or(0));
1067
+ put_i32(&mut attrs, visual.border_color.unwrap_or(0));
1068
+ put_f32(&mut attrs, visual.border_width);
1069
+ put_f32(&mut attrs, visual.radius);
1070
+ put_f32(&mut attrs, visual.opacity);
1071
+ mounted.visual = Some(visual);
1072
+ }
1073
+ // Sent once a view has any, and whenever they change after that.
1074
+ let effects = effects_of(&node.props);
1075
+ let first_and_none = mounted.effects.is_none() && effects == Effects::default();
1076
+ if !first_and_none && mounted.effects.as_ref() != Some(&effects) {
1077
+ attrs.push(OP_EFFECTS);
1078
+ put_i32(&mut attrs, tag);
1079
+ for v in [
1080
+ effects.shadow_x,
1081
+ effects.shadow_y,
1082
+ effects.shadow_blur,
1083
+ effects.shadow_spread,
1084
+ ] {
1085
+ put_f32(&mut attrs, v);
1086
+ }
1087
+ put_i32(&mut attrs, effects.shadow_color);
1088
+ put_f32(&mut attrs, effects.backdrop_blur);
1089
+ attrs.push(u8::from(effects.clip));
1090
+ mounted.effects = Some(effects);
1091
+ }
1092
+ if node.kind == Kind::Vector {
1093
+ if node.vector != mounted.text {
1094
+ attrs.push(OP_VECTOR);
1095
+ put_i32(&mut attrs, tag);
1096
+ put_i32(&mut attrs, node.vector.len() as i32);
1097
+ attrs.extend_from_slice(&node.vector);
1098
+ mounted.text = node.vector.clone();
1099
+ }
1100
+ } else if node.kind == Kind::Image {
1101
+ let encoded = encode_image(&node.props);
1102
+ if encoded != mounted.text {
1103
+ attrs.push(OP_IMAGE);
1104
+ put_i32(&mut attrs, tag);
1105
+ put_i32(&mut attrs, encoded.len() as i32);
1106
+ attrs.extend_from_slice(&encoded);
1107
+ mounted.text = encoded;
1108
+ }
1109
+ } else if node.kind == Kind::TextInput {
1110
+ let encoded = encode_input(&node.props, layout);
1111
+ if encoded != mounted.text {
1112
+ attrs.push(OP_INPUT);
1113
+ put_i32(&mut attrs, tag);
1114
+ put_i32(&mut attrs, encoded.len() as i32);
1115
+ attrs.extend_from_slice(&encoded);
1116
+ mounted.text = encoded;
1117
+ }
1118
+ } else if node.kind == Kind::Text {
1119
+ let encoded = self.spans.get(&tag).cloned().unwrap_or_default();
1120
+ if encoded != mounted.text {
1121
+ attrs.push(OP_TEXT);
1122
+ put_i32(&mut attrs, tag);
1123
+ put_i32(&mut attrs, encoded.len() as i32);
1124
+ attrs.extend_from_slice(&encoded);
1125
+ mounted.text = encoded;
1126
+ }
1127
+ } else {
1128
+ let layout_children: Vec<i32> = node
1129
+ .children
1130
+ .iter()
1131
+ .copied()
1132
+ .filter(|c| {
1133
+ self.nodes
1134
+ .get(c)
1135
+ .map(|n| n.kind.is_layout())
1136
+ .unwrap_or(false)
1137
+ })
1138
+ .collect();
1139
+ if layout_children != mounted.children {
1140
+ kids.push(OP_CHILDREN);
1141
+ put_i32(&mut kids, tag);
1142
+ put_i32(&mut kids, layout_children.len() as i32);
1143
+ for c in &layout_children {
1144
+ put_i32(&mut kids, *c);
1145
+ }
1146
+ mounted.children = layout_children;
1147
+ }
1148
+ }
1149
+ }
1150
+ out.extend_from_slice(&creates);
1151
+ out.extend_from_slice(&attrs);
1152
+ out.extend_from_slice(&kids);
1153
+ if self.mounted_root != Some(root) {
1154
+ out.push(OP_ROOT);
1155
+ put_i32(out, root);
1156
+ self.mounted_root = Some(root);
1157
+ }
1158
+ // Drop what is no longer reachable: the views, the taffy nodes, the tags.
1159
+ let gone: Vec<i32> = self
1160
+ .nodes
1161
+ .keys()
1162
+ .copied()
1163
+ .filter(|t| !reachable_set.contains(t))
1164
+ .collect();
1165
+ for tag in gone {
1166
+ if let Some(node) = self.nodes.remove(&tag) {
1167
+ if let Some(id) = node.taffy {
1168
+ let _ = self.tree.remove(id);
1169
+ }
1170
+ }
1171
+ if self.mounted.remove(&tag).is_some() {
1172
+ out.push(OP_DELETE);
1173
+ put_i32(out, tag);
1174
+ }
1175
+ self.parent.remove(&tag);
1176
+ self.spans.remove(&tag);
1177
+ gesture::with(|g| g.remove(tag));
1178
+ motion::with(|m| m.forget_view(tag));
1179
+ info.deleted.push(tag);
1180
+ }
1181
+ info.nodes = self.nodes.len();
1182
+ info.diff_us = t2.elapsed().as_micros();
1183
+ Ok(info)
1184
+ }
1185
+ }
1186
+
1187
+ // ---------------------------------------------------------------- C ABI
1188
+
1189
+ thread_local! {
1190
+ static HOST: RefCell<Host> = RefCell::new(Host::default());
1191
+ }
1192
+
1193
+ #[repr(C)]
1194
+ pub struct OrbitBuf {
1195
+ pub ptr: *mut u8,
1196
+ pub len: usize,
1197
+ pub cap: usize,
1198
+ }
1199
+
1200
+ impl OrbitBuf {
1201
+ fn from_vec(mut v: Vec<u8>) -> OrbitBuf {
1202
+ let buf = OrbitBuf {
1203
+ ptr: v.as_mut_ptr(),
1204
+ len: v.len(),
1205
+ cap: v.capacity(),
1206
+ };
1207
+ std::mem::forget(v);
1208
+ buf
1209
+ }
1210
+ }
1211
+
1212
+ /// Run an exported function's body. A panic must not unwind into the C++
1213
+ /// caller (that aborts the app): it becomes `fallback()` instead. This covers
1214
+ /// panics only — a stack overflow is not one, which is what `MAX_DEPTH` is for.
1215
+ fn guarded<T>(fallback: impl FnOnce() -> T, body: impl FnOnce() -> T) -> T {
1216
+ std::panic::catch_unwind(std::panic::AssertUnwindSafe(body)).unwrap_or_else(|_| fallback())
1217
+ }
1218
+
1219
+ /// `len` items at `ptr`, or none when there are none (a null pointer included).
1220
+ ///
1221
+ /// # Safety
1222
+ /// When `len > 0`, `ptr` must point to `len` readable items.
1223
+ unsafe fn items<'a, T>(ptr: *const T, len: usize) -> &'a [T] {
1224
+ if ptr.is_null() || len == 0 {
1225
+ &[]
1226
+ } else {
1227
+ std::slice::from_raw_parts(ptr, len)
1228
+ }
1229
+ }
1230
+
1231
+ /// # Safety
1232
+ /// `buf` must come from this library and be freed once.
1233
+ #[no_mangle]
1234
+ pub unsafe extern "C" fn orbit_buf_free(buf: OrbitBuf) {
1235
+ if !buf.ptr.is_null() {
1236
+ guarded(
1237
+ || (),
1238
+ || drop(Vec::from_raw_parts(buf.ptr, buf.len, buf.cap)),
1239
+ );
1240
+ }
1241
+ }
1242
+
1243
+ #[no_mangle]
1244
+ pub extern "C" fn orbit_set_measure(measure: MeasureFn) {
1245
+ guarded(|| (), || HOST.with(|h| h.borrow_mut().set_measure(measure)));
1246
+ }
1247
+
1248
+ #[no_mangle]
1249
+ pub extern "C" fn orbit_set_viewport(width: f32, height: f32) {
1250
+ guarded(
1251
+ || (),
1252
+ || HOST.with(|h| h.borrow_mut().set_viewport(width, height)),
1253
+ );
1254
+ }
1255
+
1256
+ fn panic_message(payload: Box<dyn std::any::Any + Send>) -> String {
1257
+ payload
1258
+ .downcast_ref::<&str>()
1259
+ .map(|s| (*s).to_owned())
1260
+ .or_else(|| payload.downcast_ref::<String>().cloned())
1261
+ .unwrap_or_else(|| "panic".to_owned())
1262
+ }
1263
+
1264
+ fn info_json(info: &CommitInfo, ops_bytes: usize) -> String {
1265
+ serde_json::json!({
1266
+ "deleted": info.deleted,
1267
+ "parseUs": info.parse_us as u64,
1268
+ "layoutUs": info.layout_us as u64,
1269
+ "diffUs": info.diff_us as u64,
1270
+ "measures": info.measures,
1271
+ "nodes": info.nodes,
1272
+ "opsBytes": ops_bytes,
1273
+ "warnings": info.warnings,
1274
+ })
1275
+ .to_string()
1276
+ }
1277
+
1278
+ /// A touch from the UI thread (see `gesture::Gestures::touch`); `out`
1279
+ /// receives the commands.
1280
+ ///
1281
+ /// # Safety
1282
+ /// `out` must be valid.
1283
+ #[no_mangle]
1284
+ pub unsafe extern "C" fn orbit_touch(
1285
+ action: u8,
1286
+ x: f32,
1287
+ y: f32,
1288
+ now_ns: i64,
1289
+ hit: i32,
1290
+ out: *mut OrbitBuf,
1291
+ ) {
1292
+ let commands = guarded(Vec::new, || {
1293
+ let mut commands = Vec::new();
1294
+ gesture::with(|g| g.touch(action, x, y, now_ns, hit, &mut commands));
1295
+ commands
1296
+ });
1297
+ *out = OrbitBuf::from_vec(commands);
1298
+ }
1299
+
1300
+ /// Every vsync on the UI thread: long presses and delayed feedback.
1301
+ ///
1302
+ /// # Safety
1303
+ /// `out` must be valid.
1304
+ #[no_mangle]
1305
+ pub unsafe extern "C" fn orbit_gesture_tick(now_ns: i64, out: *mut OrbitBuf) {
1306
+ let commands = guarded(Vec::new, || {
1307
+ let mut commands = Vec::new();
1308
+ gesture::with(|g| g.tick(now_ns, &mut commands));
1309
+ commands
1310
+ });
1311
+ *out = OrbitBuf::from_vec(commands);
1312
+ }
1313
+
1314
+ /// The frames of a JSON array of tags, as a JSON array of `[x, y, w, h]` or
1315
+ /// null (see `Host::frames`). Returns 0, 1 with `{"error": …}`, or 2 when it
1316
+ /// panicked.
1317
+ ///
1318
+ /// # Safety
1319
+ /// `tags` must point to `len` readable bytes; `out` must be valid.
1320
+ #[no_mangle]
1321
+ pub unsafe extern "C" fn orbit_layout(tags: *const u8, len: usize, out: *mut OrbitBuf) -> i32 {
1322
+ let input = items(tags, len);
1323
+ let result = std::panic::catch_unwind(|| match serde_json::from_slice::<Vec<i32>>(input) {
1324
+ Ok(tags) => (
1325
+ 0,
1326
+ serde_json::to_string(&HOST.with(|h| h.borrow().frames(&tags)))
1327
+ .unwrap_or_else(|_| "[]".to_owned()),
1328
+ ),
1329
+ Err(e) => (1, serde_json::json!({ "error": e.to_string() }).to_string()),
1330
+ });
1331
+ let (code, json) = result.unwrap_or_else(|p| {
1332
+ (
1333
+ 2,
1334
+ serde_json::json!({ "error": panic_message(p) }).to_string(),
1335
+ )
1336
+ });
1337
+ *out = OrbitBuf::from_vec(json.into_bytes());
1338
+ code
1339
+ }
1340
+
1341
+ /// Commit a JSON batch. `mount_ops` receives the binary mount operations,
1342
+ /// `info` a JSON object (or `{"error": …}`). Returns 0 on success.
1343
+ ///
1344
+ /// # Safety
1345
+ /// `ops` must point to `len` readable bytes; both out-pointers must be valid.
1346
+ #[no_mangle]
1347
+ pub unsafe extern "C" fn orbit_commit(
1348
+ ops: *const u8,
1349
+ len: usize,
1350
+ mount_ops: *mut OrbitBuf,
1351
+ info: *mut OrbitBuf,
1352
+ ) -> i32 {
1353
+ let input = items(ops, len);
1354
+ let result = std::panic::catch_unwind(|| {
1355
+ HOST.with(|h| {
1356
+ let mut out = Vec::new();
1357
+ let info = h.borrow_mut().commit(input, &mut out)?;
1358
+ Ok::<_, String>((out, info))
1359
+ })
1360
+ });
1361
+ let (code, ops_out, info_out) = match result {
1362
+ Ok(Ok((out, i))) => {
1363
+ let json = info_json(&i, out.len());
1364
+ (0, out, json)
1365
+ }
1366
+ Ok(Err(e)) => (1, Vec::new(), serde_json::json!({ "error": e }).to_string()),
1367
+ Err(p) => (
1368
+ 2,
1369
+ Vec::new(),
1370
+ serde_json::json!({ "error": panic_message(p) }).to_string(),
1371
+ ),
1372
+ };
1373
+ *mount_ops = OrbitBuf::from_vec(ops_out);
1374
+ *info = OrbitBuf::from_vec(info_out.into_bytes());
1375
+ code
1376
+ }
1377
+
1378
+ #[no_mangle]
1379
+ pub extern "C" fn orbit_motion_value(tag: i32, initial: f64) {
1380
+ guarded(|| (), || motion::with(|m| m.value(tag, initial)));
1381
+ }
1382
+
1383
+ /// # Safety
1384
+ /// `from` and `to` must point to `len` readable f64s.
1385
+ #[no_mangle]
1386
+ pub unsafe extern "C" fn orbit_motion_interpolate(
1387
+ tag: i32,
1388
+ input: i32,
1389
+ from: *const f64,
1390
+ to: *const f64,
1391
+ len: usize,
1392
+ ) {
1393
+ let from = items(from, len).to_vec();
1394
+ let to = items(to, len).to_vec();
1395
+ guarded(
1396
+ || (),
1397
+ || motion::with(|m| m.interpolation(tag, input, from, to)),
1398
+ );
1399
+ }
1400
+
1401
+ #[no_mangle]
1402
+ pub extern "C" fn orbit_motion_set(tag: i32, value: f64) {
1403
+ guarded(|| (), || motion::with(|m| m.set(tag, value)));
1404
+ }
1405
+
1406
+ #[no_mangle]
1407
+ pub extern "C" fn orbit_motion_stop(tag: i32) {
1408
+ guarded(|| (), || motion::with(|m| m.stop(tag)));
1409
+ }
1410
+
1411
+ /// # Safety
1412
+ /// `frames` must point to `len` readable f64s.
1413
+ #[no_mangle]
1414
+ pub unsafe extern "C" fn orbit_motion_frames(
1415
+ tag: i32,
1416
+ frames: *const f64,
1417
+ len: usize,
1418
+ to: f64,
1419
+ looping: bool,
1420
+ ) {
1421
+ let frames = items(frames, len).to_vec();
1422
+ guarded(
1423
+ || (),
1424
+ || motion::with(|m| m.frames(tag, frames, to, looping)),
1425
+ );
1426
+ }
1427
+
1428
+ #[no_mangle]
1429
+ pub extern "C" fn orbit_motion_spring(tag: i32, to: f64, stiffness: f64, damping: f64, mass: f64) {
1430
+ guarded(
1431
+ || (),
1432
+ || motion::with(|m| m.spring(tag, to, stiffness, damping, mass)),
1433
+ );
1434
+ }
1435
+
1436
+ #[no_mangle]
1437
+ pub extern "C" fn orbit_motion_dispose(tag: i32) {
1438
+ guarded(|| (), || motion::with(|m| m.dispose(tag)));
1439
+ }
1440
+
1441
+ #[no_mangle]
1442
+ pub extern "C" fn orbit_motion_bind(view: i32, prop: u8, node: i32) {
1443
+ guarded(|| (), || motion::with(|m| m.bind(view, prop, node)));
1444
+ }
1445
+
1446
+ #[no_mangle]
1447
+ pub extern "C" fn orbit_motion_bind_scroll(scroll_view: i32, value: i32) {
1448
+ guarded(
1449
+ || (),
1450
+ || motion::with(|m| m.bind_scroll(scroll_view, value)),
1451
+ );
1452
+ }
1453
+
1454
+ /// Advance every animation to `now_ns` (UI thread). `scroll_tags`/`scroll_y`
1455
+ /// carry `count` scroll offsets in dp. `out` receives 9-byte records
1456
+ /// (i32 view, u8 prop, f32 value). Returns 1 while an animation is running.
1457
+ ///
1458
+ /// # Safety
1459
+ /// The input pointers must hold `count` items; `out` must be valid.
1460
+ #[no_mangle]
1461
+ pub unsafe extern "C" fn orbit_motion_tick(
1462
+ now_ns: i64,
1463
+ scroll_tags: *const i32,
1464
+ scroll_y: *const f32,
1465
+ count: usize,
1466
+ out: *mut OrbitBuf,
1467
+ ) -> i32 {
1468
+ let tags = items(scroll_tags, count);
1469
+ let ys = items(scroll_y, count);
1470
+ let scrolls: Vec<(i32, f32)> = tags.iter().copied().zip(ys.iter().copied()).collect();
1471
+ let (active, buf) = guarded(
1472
+ || (false, Vec::new()),
1473
+ || {
1474
+ let mut buf = Vec::new();
1475
+ let active = motion::with(|m| m.tick(now_ns, &scrolls, &mut buf));
1476
+ (active, buf)
1477
+ },
1478
+ );
1479
+ *out = OrbitBuf::from_vec(buf);
1480
+ i32::from(active)
1481
+ }
1482
+
1483
+ #[cfg(test)]
1484
+ mod tests {
1485
+ use super::*;
1486
+
1487
+ /// The op codes of a mount buffer, in order.
1488
+ fn codes(buf: &[u8]) -> Vec<u8> {
1489
+ let i32_at =
1490
+ |i: usize| i32::from_le_bytes([buf[i], buf[i + 1], buf[i + 2], buf[i + 3]]) as usize;
1491
+ let mut out = Vec::new();
1492
+ let mut i = 0;
1493
+ while i < buf.len() {
1494
+ let code = buf[i];
1495
+ out.push(code);
1496
+ i += 5; // code + tag
1497
+ i += match code {
1498
+ OP_CREATE => 1,
1499
+ OP_DELETE | OP_ROOT => 0,
1500
+ OP_CHILDREN => 4 + 4 * i32_at(i),
1501
+ OP_FRAME => 16,
1502
+ OP_VIEW_STYLE => 20,
1503
+ OP_EFFECTS => 25,
1504
+ OP_TEXT | OP_INPUT | OP_IMAGE | OP_VECTOR => 4 + i32_at(i),
1505
+ _ => panic!("unknown op {code}"),
1506
+ };
1507
+ }
1508
+ out
1509
+ }
1510
+
1511
+ fn commit(host: &mut Host, ops: &str) -> (Vec<u8>, CommitInfo) {
1512
+ let mut out = Vec::new();
1513
+ let info = host.commit(ops.as_bytes(), &mut out).expect("commit");
1514
+ (out, info)
1515
+ }
1516
+
1517
+ #[test]
1518
+ fn mounts_lays_out_and_patches_only_what_changed() {
1519
+ let mut host = Host::default();
1520
+ host.set_viewport(300.0, 600.0);
1521
+ let (first, _) = commit(
1522
+ &mut host,
1523
+ r#"[["c",1,"RCTView",{"padding":10}],["c",3,"RCTView",{"flexDirection":"row","height":20,"backgroundColor":-16776961}],
1524
+ ["c",5,"RCTText",{"fontSize":12}],["c",7,"RCTRawText",{"text":"hello"}],
1525
+ ["k",5,[7]],["k",3,[5]],["k",1,[3]],["r",1]]"#,
1526
+ );
1527
+ let first = codes(&first);
1528
+ assert_eq!(first.iter().filter(|c| **c == OP_CREATE).count(), 3);
1529
+ assert_eq!(first.last(), Some(&OP_ROOT));
1530
+ let row = host.tree.layout(host.nodes[&3].taffy.unwrap()).unwrap();
1531
+ assert_eq!(
1532
+ (
1533
+ row.location.x,
1534
+ row.location.y,
1535
+ row.size.width,
1536
+ row.size.height
1537
+ ),
1538
+ (10.0, 10.0, 280.0, 20.0)
1539
+ );
1540
+
1541
+ // Only the raw text changes: one TEXT op for its Text node (and its new frame).
1542
+ let (second, info) = commit(&mut host, r#"[["u",7,{"text":"hello world"}]]"#);
1543
+ assert_eq!(codes(&second), vec![OP_FRAME, OP_TEXT]);
1544
+ assert!(info.deleted.is_empty());
1545
+
1546
+ // Nothing changed: nothing to mount.
1547
+ let (third, _) = commit(&mut host, "[]");
1548
+ assert!(third.is_empty());
1549
+ }
1550
+
1551
+ #[test]
1552
+ fn a_text_field_is_a_measured_leaf_with_its_props_and_padding() {
1553
+ let mut host = Host::default();
1554
+ host.set_viewport(300.0, 600.0);
1555
+ let (first, _) = commit(
1556
+ &mut host,
1557
+ r#"[["c",1,"RCTView",{"flexDirection":"row","alignItems":"center"}],
1558
+ ["c",3,"OrbitTextInput",{"padding":12,"fontSize":16,"placeholder":"Message","text":"","textVersion":0}],
1559
+ ["k",1,[3]],["r",1]]"#,
1560
+ );
1561
+ assert!(codes(&first).contains(&OP_INPUT));
1562
+ let field = host.tree.layout(host.nodes[&3].taffy.unwrap()).unwrap();
1563
+ // No width from its box in a row: the default; height: one line + padding.
1564
+ assert_eq!(field.size.width, DEFAULT_INPUT_WIDTH + 24.0);
1565
+ assert_eq!(field.size.height, 16.0 + 24.0);
1566
+ let json = String::from_utf8_lossy(&first);
1567
+ assert!(
1568
+ json.contains(r#""padding":[12.0,12.0,12.0,12.0]"#),
1569
+ "{json}"
1570
+ );
1571
+ assert!(json.contains(r#""placeholder":"Message""#), "{json}");
1572
+
1573
+ // The app clears the field: one INPUT op, nothing else.
1574
+ let (second, _) = commit(&mut host, r#"[["u",3,{"text":"","textVersion":1}]]"#);
1575
+ assert_eq!(codes(&second), vec![OP_INPUT]);
1576
+ }
1577
+
1578
+ #[test]
1579
+ fn a_field_sized_by_its_content_grows_with_its_lines() {
1580
+ let mut host = Host::default();
1581
+ host.set_viewport(300.0, 600.0);
1582
+ commit(
1583
+ &mut host,
1584
+ r#"[["c",1,"RCTView",{"alignItems":"flex-start"}],
1585
+ ["c",3,"OrbitTextInput",{"multiline":true,"rows":1,"fieldSizing":"content","maxHeight":40,"fontSize":16}],
1586
+ ["k",1,[3]],["r",1]]"#,
1587
+ );
1588
+ let height = |host: &Host| {
1589
+ host.tree
1590
+ .layout(host.nodes[&3].taffy.unwrap())
1591
+ .unwrap()
1592
+ .size
1593
+ .height
1594
+ };
1595
+ assert_eq!(height(&host), 16.0);
1596
+ // Desktop fallback measure: 16 dp a line, whatever the line count — so
1597
+ // what this checks is that the measured text changes, and max-h caps it.
1598
+ commit(&mut host, r#"[["u",3,{"measureText":"un\ndeux"}]]"#);
1599
+ assert!(host.spans[&3].ends_with(b"un\ndeux"));
1600
+ commit(&mut host, r#"[["u",3,{"maxHeight":8}]]"#);
1601
+ assert_eq!(height(&host), 8.0);
1602
+ }
1603
+
1604
+ #[test]
1605
+ fn a_vector_is_a_leaf_sent_with_its_paths_once_per_change() {
1606
+ let mut host = Host::default();
1607
+ host.set_viewport(300.0, 600.0);
1608
+ 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"}}]}}"##;
1609
+ let (first, _) = commit(
1610
+ &mut host,
1611
+ &format!(
1612
+ r#"[["c",1,"RCTView",{{}}],["c",3,"OrbitVector",{{"width":24,"height":24,"vector":{icon}}}],["k",1,[3]],["r",1]]"#
1613
+ ),
1614
+ );
1615
+ let size = host
1616
+ .tree
1617
+ .layout(host.nodes[&3].taffy.unwrap())
1618
+ .unwrap()
1619
+ .size;
1620
+ assert_eq!((size.width, size.height), (24.0, 24.0));
1621
+ assert_eq!(codes(&first).iter().filter(|c| **c == OP_VECTOR).count(), 1);
1622
+ let create = first
1623
+ .windows(6)
1624
+ .position(|w| w[0] == OP_CREATE && w[1..5] == 3i32.to_le_bytes())
1625
+ .unwrap();
1626
+ assert_eq!(first[create + 5], KIND_VECTOR);
1627
+
1628
+ // A resize alone sends no paths; a new drawing does.
1629
+ let (second, _) = commit(&mut host, r#"[["u",3,{"width":32,"height":32}]]"#);
1630
+ assert!(!codes(&second).contains(&OP_VECTOR));
1631
+ let red = icon.replace("-16777216", "-65536");
1632
+ let (third, _) = commit(&mut host, &format!(r#"[["u",3,{{"vector":{red}}}]]"#));
1633
+ assert_eq!(codes(&third), vec![OP_VECTOR]);
1634
+
1635
+ let broken = r#"[["u",3,{"vector":{"root":{"t":"svg","a":{"viewBox":"0 0 1 1"},"c":[{"t":"path","a":{"d":"M0 0 Q"}}]}}}]]"#;
1636
+ // Path data in error is drawn up to the error and reported, not refused.
1637
+ let (_, info) = commit(&mut host, broken);
1638
+ assert_eq!(info.warnings.len(), 1);
1639
+ }
1640
+
1641
+ #[test]
1642
+ fn an_image_is_a_leaf_sized_by_its_style_and_sent_with_its_source() {
1643
+ let mut host = Host::default();
1644
+ host.set_viewport(300.0, 600.0);
1645
+ let (first, info) = commit(
1646
+ &mut host,
1647
+ r#"[["c",1,"RCTView",{}],
1648
+ ["c",3,"OrbitImage",{"width":"100%","aspectRatio":1.5,"borderRadius":8,"src":"https://cdn.example.com/a.jpg","alt":"Plage","objectFit":"cover"}],
1649
+ ["c",5,"OrbitImage",{"src":"asset:logo.png"}],
1650
+ ["k",1,[3,5]],["r",1]]"#,
1651
+ );
1652
+ assert_eq!(info.measures, 0, "an image is never measured");
1653
+ let size = |tag: i32| {
1654
+ host.tree
1655
+ .layout(host.nodes[&tag].taffy.unwrap())
1656
+ .unwrap()
1657
+ .size
1658
+ };
1659
+ assert_eq!((size(3).width, size(3).height), (300.0, 200.0));
1660
+ // Unsized, it gets no height (stretched across the column, as any
1661
+ // item): its box does not wait for the decode to learn a size.
1662
+ assert_eq!((size(5).width, size(5).height), (300.0, 0.0));
1663
+ assert_eq!(codes(&first).iter().filter(|c| **c == OP_IMAGE).count(), 2);
1664
+ let json = String::from_utf8_lossy(&first);
1665
+ assert!(
1666
+ json.contains(r#"{"alt":"Plage","fit":"cover","src":"https://cdn.example.com/a.jpg"}"#),
1667
+ "{json}"
1668
+ );
1669
+ assert!(
1670
+ json.contains(r#""fit":"fill""#),
1671
+ "CSS's default fit: {json}"
1672
+ );
1673
+
1674
+ // A new source: one IMAGE op; a resize alone: only the frame.
1675
+ let (second, _) = commit(&mut host, r#"[["u",5,{"src":"bytes:2"}]]"#);
1676
+ assert_eq!(codes(&second), vec![OP_IMAGE]);
1677
+ let (third, _) = commit(&mut host, r#"[["u",5,{"width":40,"height":40}]]"#);
1678
+ assert_eq!(codes(&third), vec![OP_FRAME]);
1679
+ }
1680
+
1681
+ #[test]
1682
+ fn frames_are_in_the_roots_coordinates_and_hidden_nodes_take_no_room() {
1683
+ let mut host = Host::default();
1684
+ host.set_viewport(300.0, 600.0);
1685
+ commit(
1686
+ &mut host,
1687
+ r#"[["c",1,"RCTView",{"padding":10}],
1688
+ ["c",3,"RCTView",{"height":0,"display":"none"}],
1689
+ ["c",5,"RCTView",{"paddingTop":4}],
1690
+ ["c",7,"RCTView",{"height":30}],
1691
+ ["c",9,"RCTView",{"height":40}],
1692
+ ["k",5,[7,9]],["k",1,[3,5]],["r",1]]"#,
1693
+ );
1694
+ let frames = host.frames(&[3, 7, 9, 42]);
1695
+ assert_eq!(frames[0].map(|f| f[3]), Some(0.0));
1696
+ // 10 of the root's padding, 4 of the container's: the hidden spacer takes none.
1697
+ assert_eq!(frames[1], Some([10.0, 14.0, 280.0, 30.0]));
1698
+ assert_eq!(frames[2], Some([10.0, 44.0, 280.0, 40.0]));
1699
+ assert_eq!(frames[3], None);
1700
+ }
1701
+
1702
+ #[test]
1703
+ fn effects_are_sent_when_a_view_has_any_and_when_they_change() {
1704
+ let mut host = Host::default();
1705
+ let (first, _) = commit(
1706
+ &mut host,
1707
+ r#"[["c",1,"RCTView",{}],
1708
+ ["c",3,"RCTView",{"height":40,"shadowY":10,"shadowBlur":15,"shadowSpread":-3,"shadowColor":436207616}],
1709
+ ["c",5,"RCTView",{"height":40,"backdropBlur":16,"overflow":"hidden"}],
1710
+ ["k",1,[3,5]],["r",1]]"#,
1711
+ );
1712
+ // Two views have effects; the root has none and gets no op.
1713
+ assert_eq!(
1714
+ codes(&first).iter().filter(|c| **c == OP_EFFECTS).count(),
1715
+ 2
1716
+ );
1717
+ let at = first
1718
+ .windows(5)
1719
+ .position(|w| w[0] == OP_EFFECTS && w[1..5] == 3i32.to_le_bytes())
1720
+ .expect("the shadowed view's effects");
1721
+ let f = |i: usize| {
1722
+ f32::from_le_bytes(first[at + 5 + 4 * i..at + 9 + 4 * i].try_into().unwrap())
1723
+ };
1724
+ assert_eq!((f(0), f(1), f(2), f(3)), (0.0, 10.0, 15.0, -3.0));
1725
+ // Unchanged: nothing; the shadow removed: one op, back to none.
1726
+ let (second, _) = commit(&mut host, r#"[["u",5,{"height":50}]]"#);
1727
+ assert!(!codes(&second).contains(&OP_EFFECTS));
1728
+ let (third, _) = commit(
1729
+ &mut host,
1730
+ r#"[["u",3,{"shadowY":null,"shadowBlur":null,"shadowSpread":null,"shadowColor":null}]]"#,
1731
+ );
1732
+ assert_eq!(codes(&third), vec![OP_EFFECTS]);
1733
+ }
1734
+
1735
+ #[test]
1736
+ fn a_commit_keeps_the_gesture_tree_the_ui_thread_recognizes_on() {
1737
+ // Tags of their own: the gesture tree is shared by every host in the process.
1738
+ let mut host = Host::default();
1739
+ commit(
1740
+ &mut host,
1741
+ r#"[["c",901,"RCTScrollView",{}],["c",903,"RCTView",{}],
1742
+ ["c",905,"RCTView",{"height":40,"gestures":1}],["c",907,"RCTText",{}],
1743
+ ["k",905,[907]],["k",903,[905]],["k",901,[903]],["r",901]]"#,
1744
+ );
1745
+ let tap = |host_tag: i32| {
1746
+ let mut out = Vec::new();
1747
+ gesture::with(|g| {
1748
+ g.touch(gesture::DOWN, 5.0, 5.0, 0, host_tag, &mut out);
1749
+ g.touch(gesture::UP, 5.0, 5.0, 300_000_000, host_tag, &mut out);
1750
+ });
1751
+ out
1752
+ };
1753
+ // A tap on the row's text presses the row (in a scroll view: the
1754
+ // feedback flashes on release, then the event).
1755
+ let out = tap(907);
1756
+ assert_eq!(out.first(), Some(&gesture::CMD_PRESSED));
1757
+ assert_eq!(out[1..5], 905i32.to_le_bytes());
1758
+ assert!(out.windows(8).any(|w| w == b"topPress"));
1759
+ // Its handler gone: nothing.
1760
+ commit(&mut host, r#"[["u",905,{"gestures":0}]]"#);
1761
+ assert!(tap(907).is_empty());
1762
+ }
1763
+
1764
+ #[test]
1765
+ fn drops_nodes_that_left_the_tree() {
1766
+ let mut host = Host::default();
1767
+ commit(
1768
+ &mut host,
1769
+ r#"[["c",1,"RCTView",{}],["c",3,"RCTView",{}],["k",1,[3]],["r",1]]"#,
1770
+ );
1771
+ let (out, info) = commit(&mut host, r#"[["k",1,[]]]"#);
1772
+ assert_eq!(info.deleted, vec![3]);
1773
+ assert_eq!(codes(&out), vec![OP_CHILDREN, OP_DELETE]);
1774
+ }
1775
+
1776
+ /// Frames of every tag in `tags`, in the root's coordinates.
1777
+ fn layout_of(ops: &str, tags: &[i32]) -> Vec<Option<[f32; 4]>> {
1778
+ let mut host = Host::default();
1779
+ host.set_viewport(300.0, 600.0);
1780
+ commit(&mut host, ops);
1781
+ host.frames(tags)
1782
+ }
1783
+
1784
+ /// The boxes React Native's rules give, checked against the frames taffy
1785
+ /// 0.9 produced before the move to 0.15 (identical on every scene): an
1786
+ /// absolute child placed in its parent, insets moving an in-flow box,
1787
+ /// alignment, min/max sizes (unparseable means no bound), wrapping, flex
1788
+ /// sizing, aspect ratio, a measured text in a padded box, a scroll view.
1789
+ #[test]
1790
+ fn lays_out_boxes_by_react_natives_rules() {
1791
+ type Frames = Vec<Option<[f32; 4]>>;
1792
+ let scenes: &[(&str, &[i32], Frames)] = &[
1793
+ // absolute child of a nested box: placed in its parent, insets from it
1794
+ (
1795
+ r#"[["c",1,"RCTView",{"padding":10}],["c",3,"RCTView",{"margin":20,"height":100,"padding":5}],
1796
+ ["c",5,"RCTView",{"position":"absolute","top":4,"right":6,"width":30,"height":30}],
1797
+ ["c",7,"RCTView",{"position":"absolute","left":"10%","bottom":0,"height":10,"right":0}],
1798
+ ["k",3,[5,7]],["k",1,[3]],["r",1]]"#,
1799
+ &[3, 5, 7],
1800
+ vec![
1801
+ Some([30.0, 30.0, 240.0, 100.0]),
1802
+ Some([234.0, 34.0, 30.0, 30.0]),
1803
+ Some([54.0, 120.0, 216.0, 10.0]),
1804
+ ],
1805
+ ),
1806
+ // insets on an in-flow box move it (relative positioning)
1807
+ (
1808
+ r#"[["c",1,"RCTView",{}],["c",3,"RCTView",{"height":40,"top":7,"left":9}],["c",5,"RCTView",{"height":40}],
1809
+ ["k",1,[3,5]],["r",1]]"#,
1810
+ &[3, 5],
1811
+ vec![
1812
+ Some([9.0, 7.0, 300.0, 40.0]),
1813
+ Some([0.0, 40.0, 300.0, 40.0]),
1814
+ ],
1815
+ ),
1816
+ // alignment: center, flex-end, space-between, alignSelf, stretch by default
1817
+ (
1818
+ r#"[["c",1,"RCTView",{"flexDirection":"row","justifyContent":"space-between","alignItems":"center","height":100}],
1819
+ ["c",3,"RCTView",{"width":50,"height":20}],["c",5,"RCTView",{"width":50,"alignSelf":"stretch"}],
1820
+ ["c",7,"RCTView",{"width":50,"height":30,"alignSelf":"flex-end"}],
1821
+ ["c",9,"RCTView",{"height":60}],["c",11,"RCTView",{"height":10,"marginHorizontal":15}],
1822
+ ["k",9,[11]],["k",1,[3,5,7]],["c",13,"RCTView",{}],["k",13,[1,9]],["r",13]]"#,
1823
+ &[1, 3, 5, 7, 9, 11],
1824
+ vec![
1825
+ Some([0.0, 0.0, 300.0, 100.0]),
1826
+ Some([0.0, 40.0, 50.0, 20.0]),
1827
+ Some([125.0, 0.0, 50.0, 100.0]),
1828
+ Some([250.0, 70.0, 50.0, 30.0]),
1829
+ Some([0.0, 100.0, 300.0, 60.0]),
1830
+ Some([15.0, 100.0, 270.0, 10.0]),
1831
+ ],
1832
+ ),
1833
+ // justify center / flex-end, space-around, space-evenly
1834
+ (
1835
+ r#"[["c",1,"RCTView",{}],["c",3,"RCTView",{"flexDirection":"row","justifyContent":"center","height":20}],
1836
+ ["c",5,"RCTView",{"width":40,"height":10}],["c",7,"RCTView",{"flexDirection":"row","justifyContent":"space-evenly","height":20}],
1837
+ ["c",9,"RCTView",{"width":40,"height":10}],["c",11,"RCTView",{"width":40,"height":10}],
1838
+ ["k",3,[5]],["k",7,[9,11]],["k",1,[3,7]],["r",1]]"#,
1839
+ &[5, 9, 11],
1840
+ vec![
1841
+ Some([130.0, 0.0, 40.0, 10.0]),
1842
+ Some([73.0, 20.0, 40.0, 10.0]),
1843
+ Some([187.0, 20.0, 40.0, 10.0]),
1844
+ ],
1845
+ ),
1846
+ // min / max sizes: lengths, percentages, unparseable values
1847
+ (
1848
+ r#"[["c",1,"RCTView",{"alignItems":"flex-start"}],["c",3,"RCTView",{"minWidth":120,"height":10}],
1849
+ ["c",5,"RCTView",{"width":250,"maxWidth":"50%","height":10}],["c",7,"RCTView",{"maxWidth":"wide","width":200,"height":10}],
1850
+ ["c",9,"RCTView",{"minHeight":"nope","height":10,"width":10}],["c",11,"RCTView",{"flex":1,"maxHeight":50}],
1851
+ ["k",1,[3,5,7,9,11]],["r",1]]"#,
1852
+ &[3, 5, 7, 9, 11],
1853
+ vec![
1854
+ Some([0.0, 0.0, 120.0, 10.0]),
1855
+ Some([0.0, 10.0, 150.0, 10.0]),
1856
+ Some([0.0, 20.0, 200.0, 10.0]),
1857
+ Some([0.0, 30.0, 10.0, 10.0]),
1858
+ Some([0.0, 40.0, 0.0, 50.0]),
1859
+ ],
1860
+ ),
1861
+ // wrap, flex grow / shrink / basis, aspect ratio, percentage widths
1862
+ (
1863
+ r#"[["c",1,"RCTView",{"flexDirection":"row","flexWrap":"wrap","padding":4}],
1864
+ ["c",3,"RCTView",{"width":"40%","aspectRatio":2}],["c",5,"RCTView",{"width":"40%","height":15}],
1865
+ ["c",7,"RCTView",{"width":"40%","height":25}],["c",9,"RCTView",{"flexGrow":1,"height":5}],
1866
+ ["c",11,"RCTView",{"flexDirection":"row","height":30}],["c",13,"RCTView",{"flex":1}],["c",15,"RCTView",{"flex":2}],
1867
+ ["c",17,"RCTView",{"flexBasis":60,"flexShrink":1}],["k",11,[13,15,17]],
1868
+ ["c",19,"RCTView",{}],["k",1,[3,5,7,9]],["k",19,[1,11]],["r",19]]"#,
1869
+ &[1, 3, 5, 7, 9, 13, 15, 17],
1870
+ vec![
1871
+ Some([0.0, 0.0, 300.0, 91.0]),
1872
+ Some([4.0, 4.0, 117.0, 58.0]),
1873
+ Some([121.0, 4.0, 117.0, 15.0]),
1874
+ Some([4.0, 62.0, 117.0, 25.0]),
1875
+ Some([121.0, 62.0, 175.0, 5.0]),
1876
+ Some([0.0, 91.0, 80.0, 30.0]),
1877
+ Some([80.0, 91.0, 160.0, 30.0]),
1878
+ Some([240.0, 91.0, 60.0, 30.0]),
1879
+ ],
1880
+ ),
1881
+ // measured text in a padded, bordered box, wrapping under a narrow width
1882
+ (
1883
+ r#"[["c",1,"RCTView",{"alignItems":"flex-start"}],["c",3,"RCTText",{"fontSize":12,"padding":6,"borderWidth":2}],
1884
+ ["c",5,"RCTRawText",{"text":"hello world"}],["c",7,"RCTText",{"fontSize":12,"width":40,"paddingHorizontal":3}],
1885
+ ["c",9,"RCTRawText",{"text":"a long sentence that wraps"}],["k",3,[5]],["k",7,[9]],["k",1,[3,7]],["r",1]]"#,
1886
+ &[3, 7],
1887
+ vec![Some([0.0, 0.0, 268.0, 32.0]), Some([0.0, 32.0, 40.0, 16.0])],
1888
+ ),
1889
+ // scroll view: content child grows past the frame
1890
+ (
1891
+ r#"[["c",1,"RCTView",{}],["c",3,"RCTScrollView",{"height":100}],["c",5,"RCTView",{}],
1892
+ ["c",7,"RCTView",{"height":400}],["k",5,[7]],["k",3,[5]],["k",1,[3]],["r",1]]"#,
1893
+ &[3, 5, 7],
1894
+ vec![
1895
+ Some([0.0, 0.0, 300.0, 100.0]),
1896
+ Some([0.0, 0.0, 300.0, 400.0]),
1897
+ Some([0.0, 0.0, 300.0, 400.0]),
1898
+ ],
1899
+ ),
1900
+ ];
1901
+ for (i, (ops, tags, expected)) in scenes.iter().enumerate() {
1902
+ assert_eq!(&layout_of(ops, tags), expected, "scene {i}");
1903
+ }
1904
+ }
1905
+
1906
+ /// A chain of `depth` nested views, `extra` ops appended before the root.
1907
+ fn chain(depth: usize, extra: &str) -> String {
1908
+ let mut ops = String::from("[");
1909
+ for i in 1..=depth {
1910
+ ops.push_str(&format!(r#"["c",{},"RCTView",{{"padding":1}}],"#, i * 2));
1911
+ }
1912
+ for i in 1..depth {
1913
+ ops.push_str(&format!(r#"["k",{},[{}]],"#, i * 2, i * 2 + 2));
1914
+ }
1915
+ ops.push_str(extra);
1916
+ ops.push_str(r#"["r",2]]"#);
1917
+ ops
1918
+ }
1919
+
1920
+ #[test]
1921
+ fn refuses_views_nested_deeper_than_the_bound_before_layout() {
1922
+ let mut host = Host::default();
1923
+ host.set_viewport(300.0, 600.0);
1924
+ let mut out = Vec::new();
1925
+ assert!(host
1926
+ .commit(chain(MAX_DEPTH, "").as_bytes(), &mut out)
1927
+ .is_ok());
1928
+ let mut host = Host::default();
1929
+ let mut out = Vec::new();
1930
+ let error = host
1931
+ .commit(chain(MAX_DEPTH + 1, "").as_bytes(), &mut out)
1932
+ .unwrap_err();
1933
+ assert!(error.starts_with("E_ORBIT_TREE_TOO_DEEP: "), "{error}");
1934
+ assert!(out.is_empty());
1935
+ // Text runs are not laid out: a deep chain of them does not count.
1936
+ let mut ops = chain(MAX_DEPTH - 1, "");
1937
+ ops.truncate(ops.len() - r#"["r",2]]"#.len());
1938
+ let last = MAX_DEPTH * 2 - 2;
1939
+ ops.push_str(&format!(
1940
+ r#"["c",9001,"RCTText",{{}}],["c",9003,"RCTVirtualText",{{}}],["c",9005,"RCTRawText",{{"text":"x"}}],["k",9003,[9005]],["k",9001,[9003]],["k",{last},[9001]],["r",2]]"#
1941
+ ));
1942
+ let mut host = Host::default();
1943
+ assert!(host.commit(ops.as_bytes(), &mut Vec::new()).is_ok());
1944
+ }
1945
+
1946
+ #[test]
1947
+ fn refuses_a_cycle_and_counts_a_moved_view_where_it_is() {
1948
+ // 2 → 4 → 6 → 2: the walk taffy would do never ends.
1949
+ let mut host = Host::default();
1950
+ let error = host
1951
+ .commit(chain(3, r#"["k",6,[2]],"#).as_bytes(), &mut Vec::new())
1952
+ .unwrap_err();
1953
+ assert!(error.starts_with("E_ORBIT_TREE_TOO_DEEP: "), "{error}");
1954
+ // A view listed under a second parent moves there, as taffy moves it:
1955
+ // the deepest one of a chain of MAX_DEPTH, moved under the root.
1956
+ let mut host = Host::default();
1957
+ let moved = chain(MAX_DEPTH, &format!(r#"["k",2,[4,{}]],"#, MAX_DEPTH * 2));
1958
+ assert!(host.commit(moved.as_bytes(), &mut Vec::new()).is_ok());
1959
+ let deeper = chain(
1960
+ MAX_DEPTH + 1,
1961
+ &format!(r#"["k",2,[4,{}]],"#, MAX_DEPTH * 2 + 2),
1962
+ );
1963
+ assert!(Host::default()
1964
+ .commit(deeper.as_bytes(), &mut Vec::new())
1965
+ .is_ok());
1966
+ let error = Host::default()
1967
+ .commit(chain(MAX_DEPTH + 1, "").as_bytes(), &mut Vec::new())
1968
+ .unwrap_err();
1969
+ assert!(error.starts_with("E_ORBIT_TREE_TOO_DEEP: "), "{error}");
1970
+ }
1971
+
1972
+ #[test]
1973
+ fn creating_a_tag_it_holds_replaces_that_node() {
1974
+ let mut host = Host::default();
1975
+ host.set_viewport(300.0, 600.0);
1976
+ let ops = r#"[["c",1,"RCTView",{}],["c",3,"RCTView",{"height":20}],["k",1,[3]],["r",1]]"#;
1977
+ commit(&mut host, ops);
1978
+ let before = host.tree.total_node_count();
1979
+ // A refused batch sent again: the same creates and children.
1980
+ let (_, info) = commit(
1981
+ &mut host,
1982
+ r#"[["c",3,"RCTView",{"height":30}],["k",1,[3]]]"#,
1983
+ );
1984
+ assert_eq!(host.tree.total_node_count(), before);
1985
+ assert!(info.deleted.is_empty());
1986
+ assert_eq!(host.frames(&[3]), vec![Some([0.0, 0.0, 300.0, 30.0])]);
1987
+ }
1988
+
1989
+ #[test]
1990
+ fn a_drawing_value_it_cannot_read_costs_that_shape_not_the_commit() {
1991
+ let mut host = Host::default();
1992
+ host.set_viewport(300.0, 600.0);
1993
+ let ops = r#"[["c",1,"RCTView",{}],["c",3,"OrbitVector",{"width":100,"height":50,"vector":{"color":-16777216,"root":
1994
+ {"t":"svg","a":{"viewBox":"0 0 100 50"},"c":[
1995
+ {"t":"rect","a":{"width":"40","height":"NaN"},"c":[]},
1996
+ {"t":"g","a":{"transform":")("},"c":[]},
1997
+ {"t":"rect","a":{"width":"40","height":"20"},"c":[]}]}}}],["k",1,[3]],["r",1]]"#;
1998
+ let (out, info) = commit(&mut host, ops);
1999
+ assert!(codes(&out).contains(&OP_VECTOR));
2000
+ assert_eq!(info.warnings.len(), 1);
2001
+ assert!(info.warnings[0].starts_with("E_ORBIT_SVG_VALUE: "));
2002
+ // A patch too.
2003
+ let (_, info) = commit(
2004
+ &mut host,
2005
+ r#"[["u",3,{"vector":{"root":{"t":"svg","c":[{"t":"path","a":{"d":"M0 0 L1 NaN"}}]}}}]]"#,
2006
+ );
2007
+ assert_eq!(info.warnings.len(), 1);
2008
+ let json = info_json(&info, 0);
2009
+ assert!(
2010
+ json.contains(r#""warnings":["E_ORBIT_SVG_VALUE: "#),
2011
+ "{json}"
2012
+ );
2013
+ }
2014
+
2015
+ #[test]
2016
+ fn a_panic_never_leaves_an_exported_function() {
2017
+ assert_eq!(guarded(|| 7, || panic!("boom")), 7);
2018
+ assert_eq!(guarded(|| 7, || 3), 3);
2019
+ assert!(unsafe { items::<u8>(std::ptr::null(), 4) }.is_empty());
2020
+ // The C ABI with nothing to read and nothing to tick.
2021
+ let mut out = OrbitBuf {
2022
+ ptr: std::ptr::null_mut(),
2023
+ len: 0,
2024
+ cap: 0,
2025
+ };
2026
+ let code = unsafe { orbit_layout(std::ptr::null(), 0, &mut out) };
2027
+ assert_eq!(code, 1);
2028
+ unsafe { orbit_buf_free(out) };
2029
+ let mut out = OrbitBuf {
2030
+ ptr: std::ptr::null_mut(),
2031
+ len: 0,
2032
+ cap: 0,
2033
+ };
2034
+ let active =
2035
+ unsafe { orbit_motion_tick(0, std::ptr::null(), std::ptr::null(), 0, &mut out) };
2036
+ assert_eq!(active, 0);
2037
+ unsafe { orbit_buf_free(out) };
2038
+ unsafe { orbit_motion_interpolate(1, 2, std::ptr::null(), std::ptr::null(), 0) };
2039
+ unsafe { orbit_motion_frames(1, std::ptr::null(), 0, 1.0, false) };
2040
+ orbit_motion_dispose(1);
2041
+ }
2042
+ }