@mun-ui/ui 0.0.0-stage → 0.2.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 (158) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +104 -2
  3. package/bin/compile.mjs +38 -0
  4. package/bin/dev-protocol.mjs +94 -0
  5. package/bin/formatter.mjs +109 -0
  6. package/bin/hot-reload.mjs +38 -0
  7. package/bin/mun.mjs +521 -0
  8. package/bin/native.mjs +133 -0
  9. package/bin/pnpm-workspace.mjs +58 -0
  10. package/bin/program-patch.mjs +104 -0
  11. package/bin/project.mjs +322 -0
  12. package/bin/watch.mjs +316 -0
  13. package/bin/workflow.mjs +261 -0
  14. package/dist/astro.d.ts +3 -0
  15. package/dist/astro.d.ts.map +1 -0
  16. package/dist/astro.js +3 -0
  17. package/dist/astro.js.map +1 -0
  18. package/dist/closures.d.ts +2 -0
  19. package/dist/closures.d.ts.map +1 -0
  20. package/dist/closures.js +2 -0
  21. package/dist/closures.js.map +1 -0
  22. package/dist/compiler/index.d.ts +2 -0
  23. package/dist/compiler/index.d.ts.map +1 -0
  24. package/dist/compiler/index.js +2 -0
  25. package/dist/compiler/index.js.map +1 -0
  26. package/dist/core.d.ts +3 -0
  27. package/dist/core.d.ts.map +1 -0
  28. package/dist/core.js +3 -0
  29. package/dist/core.js.map +1 -0
  30. package/dist/experimental.d.ts +2 -0
  31. package/dist/experimental.d.ts.map +1 -0
  32. package/dist/experimental.js +2 -0
  33. package/dist/experimental.js.map +1 -0
  34. package/dist/index.d.ts +3 -0
  35. package/dist/index.d.ts.map +1 -0
  36. package/dist/index.js +3 -0
  37. package/dist/index.js.map +1 -0
  38. package/dist/jsx-dev-runtime.d.ts +2 -0
  39. package/dist/jsx-dev-runtime.d.ts.map +1 -0
  40. package/dist/jsx-dev-runtime.js +2 -0
  41. package/dist/jsx-dev-runtime.js.map +1 -0
  42. package/dist/jsx-runtime.d.ts +2 -0
  43. package/dist/jsx-runtime.d.ts.map +1 -0
  44. package/dist/jsx-runtime.js +2 -0
  45. package/dist/jsx-runtime.js.map +1 -0
  46. package/dist/legacy.d.ts +3 -0
  47. package/dist/legacy.d.ts.map +1 -0
  48. package/dist/legacy.js +3 -0
  49. package/dist/legacy.js.map +1 -0
  50. package/dist/mun.d.ts +5 -0
  51. package/dist/mun.d.ts.map +1 -0
  52. package/dist/mun.js +4 -0
  53. package/dist/mun.js.map +1 -0
  54. package/dist/progressive-blur/index.d.ts +8 -0
  55. package/dist/progressive-blur/index.d.ts.map +1 -0
  56. package/dist/progressive-blur/index.js +8 -0
  57. package/dist/progressive-blur/index.js.map +1 -0
  58. package/dist/progressive-blur/plan.d.ts +3 -0
  59. package/dist/progressive-blur/plan.d.ts.map +1 -0
  60. package/dist/progressive-blur/plan.js +3 -0
  61. package/dist/progressive-blur/plan.js.map +1 -0
  62. package/dist/react-types.d.ts +2 -0
  63. package/dist/react-types.d.ts.map +1 -0
  64. package/dist/react-types.js +2 -0
  65. package/dist/react-types.js.map +1 -0
  66. package/dist/rendering-quality.d.ts +4 -0
  67. package/dist/rendering-quality.d.ts.map +1 -0
  68. package/dist/rendering-quality.js +4 -0
  69. package/dist/rendering-quality.js.map +1 -0
  70. package/dist/state.d.ts +2 -0
  71. package/dist/state.d.ts.map +1 -0
  72. package/dist/state.js +2 -0
  73. package/dist/state.js.map +1 -0
  74. package/dist/types.d.ts +2 -0
  75. package/dist/types.d.ts.map +1 -0
  76. package/dist/types.js +2 -0
  77. package/dist/types.js.map +1 -0
  78. package/dist/vite.d.ts +2 -0
  79. package/dist/vite.d.ts.map +1 -0
  80. package/dist/vite.js +2 -0
  81. package/dist/vite.js.map +1 -0
  82. package/editors/install.mjs +102 -0
  83. package/editors/lsp/mun-lsp.mjs +123 -0
  84. package/editors/lsp/service.mjs +306 -0
  85. package/editors/lsp/source.mjs +58 -0
  86. package/editors/vscode/client.mjs +40 -0
  87. package/editors/vscode/dev-client.mjs +83 -0
  88. package/editors/vscode/discovery.mjs +46 -0
  89. package/editors/vscode/export.mjs +42 -0
  90. package/editors/vscode/extension.cjs +226 -0
  91. package/editors/vscode/language-configuration.json +15 -0
  92. package/editors/vscode/package.json +119 -0
  93. package/editors/vscode/protocol.mjs +29 -0
  94. package/editors/vscode/syntaxes/mun.tmLanguage.json +130 -0
  95. package/native/Cargo.lock +3581 -0
  96. package/native/Cargo.toml +21 -0
  97. package/native/README.md +21 -0
  98. package/native/mun-native/Cargo.toml +23 -0
  99. package/native/mun-native/src/accessibility.rs +738 -0
  100. package/native/mun-native/src/dev.rs +604 -0
  101. package/native/mun-native/src/lib.rs +2676 -0
  102. package/native/mun-native/src/main.rs +204 -0
  103. package/native/mun-native/src/offscreen.rs +393 -0
  104. package/native/mun-native/src/rect.wgsl +63 -0
  105. package/native/mun-native/src/text.rs +310 -0
  106. package/native/mun-native/tests/offscreen_rendering.rs +161 -0
  107. package/native/mun-native/tests/stress.rs +408 -0
  108. package/native/mun-native/tests/window_lifecycle.rs +183 -0
  109. package/native/mun-runtime/Cargo.toml +13 -0
  110. package/native/mun-runtime/src/accessibility.rs +193 -0
  111. package/native/mun-runtime/src/collection.rs +1073 -0
  112. package/native/mun-runtime/src/gesture.rs +1070 -0
  113. package/native/mun-runtime/src/input.rs +325 -0
  114. package/native/mun-runtime/src/ir.rs +782 -0
  115. package/native/mun-runtime/src/kinetics.rs +500 -0
  116. package/native/mun-runtime/src/layout.rs +173 -0
  117. package/native/mun-runtime/src/layout_cache.rs +209 -0
  118. package/native/mun-runtime/src/lib.rs +49 -0
  119. package/native/mun-runtime/src/motion.rs +1162 -0
  120. package/native/mun-runtime/src/retained.rs +574 -0
  121. package/native/mun-runtime/src/runtime.rs +7078 -0
  122. package/native/mun-runtime/src/scene.rs +530 -0
  123. package/native/mun-runtime/src/scroll.rs +521 -0
  124. package/native/mun-runtime/src/scroll_view.rs +220 -0
  125. package/native/mun-runtime/src/text_edit.rs +670 -0
  126. package/native/mun-runtime/src/timeline.rs +1534 -0
  127. package/native/mun-runtime/src/validate.rs +677 -0
  128. package/native/mun-runtime/tests/accessibility_semantics.rs +168 -0
  129. package/native/mun-runtime/tests/compiler_contract.rs +110 -0
  130. package/native/mun-runtime/tests/flexible_frames.rs +47 -0
  131. package/native/mun-runtime/tests/hot_update.rs +367 -0
  132. package/native/mun-runtime/tests/incremental_runtime.rs +323 -0
  133. package/native/mun-runtime/tests/ir_validation.rs +167 -0
  134. package/native/mun-runtime/tests/keyed_collections.rs +251 -0
  135. package/native/mun-runtime/tests/native_controls_style.rs +491 -0
  136. package/native/mun-runtime/tests/native_demo.rs +285 -0
  137. package/native/mun-runtime/tests/native_layout_style.rs +175 -0
  138. package/native/mun-runtime/tests/native_settings_pane.rs +152 -0
  139. package/native/mun-runtime/tests/scroll_view.rs +403 -0
  140. package/native/mun-runtime/tests/text_editing.rs +491 -0
  141. package/package.json +210 -3
  142. package/schemas/README.md +19 -0
  143. package/schemas/semantic-ui-ir-v1.schema.json +1972 -0
  144. package/templates/native/App.mun +15 -0
  145. package/templates/native/gitignore +3 -0
  146. package/templates/native/mun.toml +8 -0
  147. package/templates/project/gitignore +5 -0
  148. package/templates/project/index.html +13 -0
  149. package/templates/project/package.json +21 -0
  150. package/templates/project/src/App.mun +13 -0
  151. package/templates/project/src/index.css +21 -0
  152. package/templates/project/src/main.ts +5 -0
  153. package/templates/project/tsconfig.json +20 -0
  154. package/templates/project/vite.config.ts +6 -0
  155. package/templates/vite/src/App.css +134 -0
  156. package/templates/vite/src/App.tsx +91 -0
  157. package/templates/vite/src/index.css +23 -0
  158. package/templates/vite/vite.config.ts +10 -0
@@ -0,0 +1,367 @@
1
+ #![recursion_limit = "512"]
2
+ //! Development hot update: atomic program replacement that carries runtime
3
+ //! state by semantic identity, replaces actions and keeps lifecycle honest.
4
+ use mun_runtime::text_edit::{Composition, TextEdit};
5
+ use mun_runtime::{InputEvent, Runtime};
6
+ use serde_json::{Value, json};
7
+
8
+ const COUNT: &str = "@component/entry/App/count";
9
+ const NAME: &str = "@component/entry/App/name";
10
+ const APPEARS: &str = "@component/entry/App/appears";
11
+ const NOTE: &str = "@component/row/note";
12
+
13
+ struct Edit {
14
+ count_initial: Value,
15
+ label: &'static str,
16
+ step: i64,
17
+ detail_branch: bool,
18
+ padding: f64,
19
+ extra_state: bool,
20
+ }
21
+
22
+ impl Default for Edit {
23
+ fn default() -> Self {
24
+ Self {
25
+ count_initial: json!(0),
26
+ label: "Count: ",
27
+ step: 1,
28
+ detail_branch: false,
29
+ padding: 8.0,
30
+ extra_state: false,
31
+ }
32
+ }
33
+ }
34
+
35
+ fn program(edit: &Edit) -> String {
36
+ let mut states = vec![
37
+ json!({"name": COUNT, "initial": edit.count_initial}),
38
+ json!({"name": NAME, "initial": ""}),
39
+ json!({"name": "@component/entry/App/secret", "initial": "hunter2"}),
40
+ json!({"name": APPEARS, "initial": 0}),
41
+ json!({"name": "@component/entry/App/rows", "initial": [{"id": "a"}, {"id": "b"}, {"id": "c"}]}),
42
+ json!({"name": NOTE, "initial": "", "scope": "list"}),
43
+ ];
44
+ if edit.extra_state {
45
+ states.push(json!({"name": "@component/entry/App/extra", "initial": true}));
46
+ }
47
+ let appear = json!({"appear": {"kind": "set-state", "state": APPEARS, "value": {"kind": "binary", "operator": "add",
48
+ "left": {"kind": "state", "state": APPEARS}, "right": {"kind": "literal", "value": 1}}}});
49
+ let detail = if edit.detail_branch {
50
+ json!({"kind": "text", "id": "detail-b", "value": {"kind": "literal", "value": "B"}, "lifecycle": appear})
51
+ } else {
52
+ json!({"kind": "text", "id": "detail-a", "value": {"kind": "literal", "value": "A"}, "lifecycle": appear})
53
+ };
54
+ json!({
55
+ "version": 1, "sourceLanguage": "mun", "entry": "App", "states": states,
56
+ "root": {"kind": "window", "id": "window-root", "title": "Hot", "child": {
57
+ "kind": "column", "id": "stack", "layout": {"padding": edit.padding}, "children": [
58
+ {"kind": "text", "id": "label", "value": {"kind": "binary", "operator": "add",
59
+ "left": {"kind": "literal", "value": edit.label},
60
+ "right": {"kind": "stringify", "value": {"kind": "state", "state": COUNT}}}},
61
+ {"kind": "action", "id": "add", "label": "Add", "action": {"kind": "set-state", "state": COUNT,
62
+ "value": {"kind": "binary", "operator": "add", "left": {"kind": "state", "state": COUNT},
63
+ "right": {"kind": "literal", "value": edit.step}}}},
64
+ {"kind": "textField", "id": "name", "state": NAME},
65
+ {"kind": "textField", "id": "secret", "state": "@component/entry/App/secret", "secure": true},
66
+ detail,
67
+ {"kind": "forEach", "id": "list", "collection": {"kind": "state", "state": "@component/entry/App/rows"},
68
+ "keyPath": ["id"], "children": [
69
+ {"kind": "row", "id": "row", "children": [
70
+ {"kind": "textField", "id": "note", "state": NOTE}
71
+ ]}
72
+ ]},
73
+ {"kind": "action", "id": "reverse", "label": "Reverse", "action": {"kind": "set-state",
74
+ "state": "@component/entry/App/rows",
75
+ "value": {"kind": "literal", "value": [{"id": "c"}, {"id": "b"}, {"id": "a"}]}}}
76
+ ]
77
+ }}
78
+ })
79
+ .to_string()
80
+ }
81
+
82
+ fn all_states(edit: &Edit) -> Vec<String> {
83
+ let source: Value = serde_json::from_str(&program(edit)).unwrap();
84
+ source["states"]
85
+ .as_array()
86
+ .unwrap()
87
+ .iter()
88
+ .map(|state| state["name"].as_str().unwrap().to_owned())
89
+ .collect()
90
+ }
91
+
92
+ fn count(runtime: &Runtime) -> Option<f64> {
93
+ runtime.state_value(COUNT).and_then(Value::as_f64)
94
+ }
95
+
96
+ fn appears(runtime: &Runtime) -> Option<f64> {
97
+ runtime.state_value(APPEARS).and_then(Value::as_f64)
98
+ }
99
+
100
+ fn type_into(runtime: &mut Runtime, id: &str, text: &str) {
101
+ assert!(runtime.focus_action(id));
102
+ runtime
103
+ .handle_input(
104
+ InputEvent::TextEdit(TextEdit::Insert(text.into())),
105
+ 400.0,
106
+ 600.0,
107
+ )
108
+ .unwrap();
109
+ }
110
+
111
+ fn base() -> Runtime {
112
+ let mut runtime = Runtime::from_json(&program(&Edit::default())).unwrap();
113
+ runtime.activate_action("add");
114
+ runtime.activate_action("add");
115
+ runtime
116
+ }
117
+
118
+ #[test]
119
+ fn text_and_modifier_edits_preserve_state_without_relaunching_lifecycle() {
120
+ let mut runtime = base();
121
+ type_into(&mut runtime, "note[s:b]", "beta");
122
+ assert_eq!(appears(&runtime), Some(1.0));
123
+ let edit = Edit {
124
+ label: "Current count: ",
125
+ padding: 20.0,
126
+ ..Edit::default()
127
+ };
128
+ let report = runtime
129
+ .hot_update(&program(&edit), &all_states(&edit))
130
+ .unwrap();
131
+ assert_eq!(count(&runtime), Some(2.0));
132
+ assert_eq!(
133
+ runtime.state_value("@component/row/note[s:b]"),
134
+ Some(&json!("beta"))
135
+ );
136
+ assert_eq!(report.reset_states, 0);
137
+ // onAppear must not fire again for a View that never left.
138
+ assert_eq!(appears(&runtime), Some(1.0));
139
+ assert_eq!(report.lifecycle_mutations, 0);
140
+ let tree = runtime.build_accessibility_tree(400.0, 600.0).unwrap();
141
+ assert!(
142
+ tree.nodes
143
+ .iter()
144
+ .any(|node| node.label.as_deref() == Some("Current count: 2"))
145
+ );
146
+ }
147
+
148
+ #[test]
149
+ fn replaced_actions_execute_new_semantics() {
150
+ let mut runtime = base();
151
+ let edit = Edit {
152
+ step: 10,
153
+ ..Edit::default()
154
+ };
155
+ runtime
156
+ .hot_update(&program(&edit), &all_states(&edit))
157
+ .unwrap();
158
+ runtime.activate_action("add");
159
+ assert_eq!(count(&runtime), Some(12.0));
160
+ }
161
+
162
+ #[test]
163
+ fn incompatible_state_resets_only_that_scope() {
164
+ let mut runtime = base();
165
+ type_into(&mut runtime, "name", "Ada");
166
+ let edit = Edit {
167
+ count_initial: json!(""),
168
+ ..Edit::default()
169
+ };
170
+ // Tooling excludes the retyped state from `preserve`.
171
+ let preserve: Vec<String> = all_states(&edit)
172
+ .into_iter()
173
+ .filter(|name| name != COUNT)
174
+ .collect();
175
+ let report = runtime.hot_update(&program(&edit), &preserve).unwrap();
176
+ assert_eq!(runtime.state_value(COUNT), Some(&json!("")));
177
+ assert_eq!(runtime.state_value(NAME), Some(&json!("Ada")));
178
+ assert_eq!(report.reset_states, 1);
179
+ }
180
+
181
+ #[test]
182
+ fn state_addition_and_removal_initialize_and_release() {
183
+ let mut runtime = base();
184
+ let added = Edit {
185
+ extra_state: true,
186
+ ..Edit::default()
187
+ };
188
+ runtime
189
+ .hot_update(&program(&added), &all_states(&Edit::default()))
190
+ .unwrap();
191
+ assert_eq!(
192
+ runtime.state_value("@component/entry/App/extra"),
193
+ Some(&json!(true))
194
+ );
195
+ runtime
196
+ .hot_update(&program(&Edit::default()), &all_states(&Edit::default()))
197
+ .unwrap();
198
+ assert_eq!(runtime.state_value("@component/entry/App/extra"), None);
199
+ assert_eq!(count(&runtime), Some(2.0));
200
+ }
201
+
202
+ #[test]
203
+ fn conditional_branch_change_runs_real_presence_lifecycle() {
204
+ let mut runtime = base();
205
+ let edit = Edit {
206
+ detail_branch: true,
207
+ ..Edit::default()
208
+ };
209
+ let report = runtime
210
+ .hot_update(&program(&edit), &all_states(&edit))
211
+ .unwrap();
212
+ // A different View became present: its onAppear runs exactly once.
213
+ assert_eq!(appears(&runtime), Some(2.0));
214
+ assert_eq!(report.lifecycle_mutations, 1);
215
+ }
216
+
217
+ #[test]
218
+ fn keyed_rows_keep_state_and_identity_through_reorder_and_body_edit() {
219
+ let mut runtime = base();
220
+ type_into(&mut runtime, "note[s:a]", "alpha");
221
+ runtime.activate_action("reverse");
222
+ let instance = runtime
223
+ .retained_tree()
224
+ .node("note[s:a]")
225
+ .unwrap()
226
+ .instance_id;
227
+ let edit = Edit {
228
+ padding: 4.0,
229
+ ..Edit::default()
230
+ };
231
+ runtime
232
+ .hot_update(&program(&edit), &all_states(&edit))
233
+ .unwrap();
234
+ assert_eq!(
235
+ runtime.state_value("@component/row/note[s:a]"),
236
+ Some(&json!("alpha"))
237
+ );
238
+ assert_eq!(
239
+ runtime
240
+ .retained_tree()
241
+ .node("note[s:a]")
242
+ .unwrap()
243
+ .instance_id,
244
+ instance
245
+ );
246
+ assert_eq!(runtime.scoped_state_count(), 3);
247
+ }
248
+
249
+ #[test]
250
+ fn rejected_update_leaves_program_state_and_focus_untouched() {
251
+ let mut runtime = base();
252
+ type_into(&mut runtime, "name", "Ada");
253
+ assert!(
254
+ runtime
255
+ .hot_update("{\"version\": 1, \"states\": 3}", &[])
256
+ .is_err()
257
+ );
258
+ assert!(runtime.hot_update("{", &[]).is_err());
259
+ assert_eq!(count(&runtime), Some(2.0));
260
+ assert_eq!(runtime.focused_action(), Some("name"));
261
+ runtime.activate_action("add");
262
+ assert_eq!(count(&runtime), Some(3.0));
263
+ }
264
+
265
+ #[test]
266
+ fn focused_text_field_survives_and_ime_composition_is_committed_once() {
267
+ let mut runtime = base();
268
+ type_into(&mut runtime, "name", "한");
269
+ runtime
270
+ .handle_input(
271
+ InputEvent::TextEdit(TextEdit::CompositionUpdate(Composition {
272
+ text: "글".into(),
273
+ selection: None,
274
+ })),
275
+ 400.0,
276
+ 600.0,
277
+ )
278
+ .unwrap();
279
+ runtime.take_ime_requests();
280
+ runtime
281
+ .hot_update(&program(&Edit::default()), &all_states(&Edit::default()))
282
+ .unwrap();
283
+ let text = runtime
284
+ .state_value(NAME)
285
+ .and_then(Value::as_str)
286
+ .unwrap()
287
+ .to_owned();
288
+ assert!(
289
+ text == "한글" || text == "한",
290
+ "composition neither duplicated nor corrupted: {text:?}"
291
+ );
292
+ assert_eq!(runtime.focused_action(), Some("name"));
293
+ assert!(
294
+ runtime
295
+ .focused_text_editor()
296
+ .unwrap()
297
+ .composition()
298
+ .is_none()
299
+ );
300
+ }
301
+
302
+ #[test]
303
+ fn removed_focus_target_clears_focus() {
304
+ let mut runtime = base();
305
+ type_into(&mut runtime, "note[s:c]", "x");
306
+ let source: Value = serde_json::from_str(&program(&Edit::default())).unwrap();
307
+ let mut source = source;
308
+ source["states"][4]["initial"] = json!([{"id": "a"}]);
309
+ // Collection membership comes from the preserved `rows` state, so drop it
310
+ // from `preserve` to remove "c" by reset.
311
+ let preserve: Vec<String> = all_states(&Edit::default())
312
+ .into_iter()
313
+ .filter(|name| !name.ends_with("/rows"))
314
+ .collect();
315
+ runtime.hot_update(&source.to_string(), &preserve).unwrap();
316
+ assert_eq!(runtime.focused_action(), None);
317
+ assert_eq!(runtime.scoped_state_count(), 1);
318
+ }
319
+
320
+ #[test]
321
+ fn inspection_redacts_secure_fields_and_omits_values_by_default() {
322
+ let runtime = base();
323
+ let snapshot = runtime.inspect(400.0, 600.0, false);
324
+ let text = snapshot.to_string();
325
+ assert!(!text.contains("hunter2"));
326
+ assert!(
327
+ snapshot["states"]
328
+ .as_array()
329
+ .unwrap()
330
+ .iter()
331
+ .all(|state| state.get("value").is_none())
332
+ );
333
+ let detailed = runtime.inspect(400.0, 600.0, true);
334
+ assert!(!detailed.to_string().contains("hunter2"));
335
+ assert!(detailed.to_string().contains("\"value\":2"));
336
+ assert!(
337
+ detailed["nodes"]
338
+ .as_array()
339
+ .unwrap()
340
+ .iter()
341
+ .any(|node| node["id"] == "label" && node.get("frame").is_some())
342
+ );
343
+ }
344
+
345
+ #[test]
346
+ fn a_thousand_sequential_updates_do_not_leak_state_or_nodes() {
347
+ let mut runtime = base();
348
+ let nodes = runtime.retained_tree().len();
349
+ for index in 0..1000 {
350
+ let edit = Edit {
351
+ padding: (index % 7) as f64,
352
+ extra_state: index % 2 == 0,
353
+ step: index % 3,
354
+ ..Edit::default()
355
+ };
356
+ runtime
357
+ .hot_update(&program(&edit), &all_states(&edit))
358
+ .unwrap();
359
+ if index % 100 == 0 {
360
+ runtime.hot_update("{", &[]).unwrap_err();
361
+ }
362
+ }
363
+ assert_eq!(count(&runtime), Some(2.0));
364
+ assert_eq!(runtime.retained_tree().len(), nodes);
365
+ assert_eq!(runtime.scoped_state_count(), 3);
366
+ assert_eq!(appears(&runtime), Some(1.0));
367
+ }
@@ -0,0 +1,323 @@
1
+ #![recursion_limit = "512"]
2
+ //! Runtime work is retained across frames and hot updates: unchanged forEach
3
+ //! expansions are reused and the layout tree is kept. Both must always produce
4
+ //! exactly what a from-scratch materialization/layout produces, and unchanged
5
+ //! input must not cause work.
6
+ use std::rc::Rc;
7
+
8
+ use mun_runtime::scene::Scene;
9
+ use mun_runtime::text_edit::TextEdit;
10
+ use mun_runtime::{InputEvent, IntrinsicMeasurer, IntrinsicSize, Runtime};
11
+ use serde_json::{Value, json};
12
+
13
+ /// Content-dependent metrics, so text edits change intrinsic sizes.
14
+ struct CharMeasurer;
15
+
16
+ impl IntrinsicMeasurer for CharMeasurer {
17
+ fn measure_text(&self, text: &str) -> IntrinsicSize {
18
+ IntrinsicSize::new(text.chars().count() as f32 * 11.0, 30.0)
19
+ }
20
+
21
+ fn measure_action(&self, label: &str) -> IntrinsicSize {
22
+ IntrinsicSize::new(label.chars().count() as f32 * 9.0 + 34.0, 38.0)
23
+ }
24
+
25
+ fn measure_panel(&self) -> IntrinsicSize {
26
+ IntrinsicSize::new(160.0, 96.0)
27
+ }
28
+ }
29
+
30
+ fn runtime(header: &str) -> Runtime {
31
+ let mut runtime = Runtime::from_json(&program(header)).unwrap();
32
+ runtime.set_intrinsic_measurer(Rc::new(CharMeasurer));
33
+ runtime
34
+ }
35
+
36
+ /// Order-independent rendering of everything a scene draws, with each
37
+ /// primitive's effective transform and clip.
38
+ fn describe(scene: &Scene) -> Vec<String> {
39
+ let presented = |id: &str| {
40
+ format!(
41
+ "{:?} {:?}",
42
+ scene.presentation.transform_for(id),
43
+ scene.presentation.clip_for(id)
44
+ )
45
+ };
46
+ let mut lines = Vec::new();
47
+ lines.extend(
48
+ scene
49
+ .rects
50
+ .iter()
51
+ .map(|item| format!("{item:?} {}", presented(&item.id))),
52
+ );
53
+ lines.extend(
54
+ scene
55
+ .texts
56
+ .iter()
57
+ .map(|item| format!("{item:?} {}", presented(&item.id))),
58
+ );
59
+ lines.extend(scene.gradients.iter().map(|item| format!("{item:?}")));
60
+ lines.extend(
61
+ scene
62
+ .actions
63
+ .iter()
64
+ .map(|item| format!("{item:?} {}", presented(&item.id))),
65
+ );
66
+ lines
67
+ }
68
+
69
+ const NOTE: &str = "@component/row/note";
70
+
71
+ fn item(path: &[&str]) -> Value {
72
+ json!({"kind": "item", "forEach": "list", "path": path})
73
+ }
74
+
75
+ fn row_action(id: &str, operation: Value) -> Value {
76
+ let mut action = json!({"kind": "collection", "state": "rows", "keyPath": ["id"]});
77
+ action
78
+ .as_object_mut()
79
+ .unwrap()
80
+ .extend(operation.as_object().unwrap().clone());
81
+ json!({"kind": "action", "id": id, "label": id, "action": action})
82
+ }
83
+
84
+ fn program(header: &str) -> String {
85
+ program_with(header, 6.0)
86
+ }
87
+
88
+ fn program_with(header: &str, row_spacing: f64) -> String {
89
+ let collection = json!({
90
+ "kind": "conditional",
91
+ "condition": {"kind": "state", "state": "onlyPinned"},
92
+ "then": {"kind": "filter", "collection": {"kind": "state", "state": "rows"}, "path": ["pinned"], "operator": "equal", "value": {"kind": "literal", "value": true}},
93
+ "otherwise": {"kind": "state", "state": "rows"}
94
+ });
95
+ json!({
96
+ "version": 1, "sourceLanguage": "mun", "entry": "Retained",
97
+ "states": [
98
+ {"name": "rows", "initial": [
99
+ {"id": "a", "title": "Alpha", "pinned": true},
100
+ {"id": "b", "title": "Beta", "pinned": false},
101
+ {"id": "c", "title": "Gamma", "pinned": true}
102
+ ]},
103
+ {"name": "onlyPinned", "initial": false},
104
+ {"name": "visible", "initial": true},
105
+ {"name": "next", "initial": 10},
106
+ {"name": NOTE, "initial": "", "scope": "list"}
107
+ ],
108
+ "root": {"kind": "window", "id": "window", "title": "Retained", "child": {
109
+ "kind": "column", "id": "stack", "layout": {"maxWidth": "infinity", "maxHeight": "infinity", "spacing": 4}, "children": [
110
+ {"kind": "text", "id": "header", "value": {"kind": "literal", "value": header}},
111
+ {"kind": "scroll", "id": "scroll", "axis": "vertical", "layout": {"maxWidth": "infinity", "maxHeight": "infinity"}, "children": [
112
+ {"kind": "conditional", "id": "gate", "condition": {"kind": "state", "state": "visible"}, "then": [
113
+ {"kind": "forEach", "id": "list", "collection": collection, "keyPath": ["id"], "children": [
114
+ {"kind": "row", "id": "row", "layout": {"spacing": row_spacing}, "children": [
115
+ {"kind": "text", "id": "title", "value": item(&["title"])},
116
+ {"kind": "spacer", "id": "gap"},
117
+ {"kind": "textField", "id": "note", "state": NOTE},
118
+ {"kind": "divider", "id": "rule"},
119
+ row_action("remove", json!({"operation": "remove", "key": item(&["id"])})),
120
+ row_action("up", json!({"operation": "move", "key": item(&["id"]), "offset": {"kind": "literal", "value": -1}})),
121
+ row_action("pin", json!({"operation": "update", "key": item(&["id"]), "path": ["pinned"], "value": {"kind": "not", "value": item(&["pinned"])}}))
122
+ ]}
123
+ ]}
124
+ ], "otherwise": [
125
+ {"kind": "panel", "id": "empty", "layout": {"maxWidth": 300, "minHeight": 20}}
126
+ ]}
127
+ ]},
128
+ {"kind": "action", "id": "append", "label": "Append", "action": {"kind": "sequence", "actions": [
129
+ {"kind": "collection", "state": "rows", "keyPath": ["id"], "operation": "append",
130
+ "value": {"kind": "record", "fields": {
131
+ "id": {"kind": "binary", "operator": "add", "left": {"kind": "literal", "value": "r"}, "right": {"kind": "stringify", "value": {"kind": "state", "state": "next"}}},
132
+ "title": {"kind": "literal", "value": "Appended with a longer title"},
133
+ "pinned": {"kind": "literal", "value": false}}}},
134
+ {"kind": "set-state", "state": "next", "value": {"kind": "binary", "operator": "add", "left": {"kind": "state", "state": "next"}, "right": {"kind": "literal", "value": 1}}}
135
+ ]}},
136
+ {"kind": "action", "id": "filter", "label": "Filter", "action": {"kind": "toggle-state", "state": "onlyPinned"}},
137
+ {"kind": "action", "id": "hide", "label": "Hide", "action": {"kind": "toggle-state", "state": "visible"}}
138
+ ]
139
+ }}
140
+ })
141
+ .to_string()
142
+ }
143
+
144
+ fn keyed(key: &str, template: &str) -> String {
145
+ format!("{template}[s:{key}]")
146
+ }
147
+
148
+ /// Retained layout of this frame equals a from-scratch layout of it.
149
+ fn assert_matches_fresh(runtime: &Runtime, width: f32, height: f32, step: &str) {
150
+ let retained = runtime.build_frame(width, height).unwrap();
151
+ runtime.discard_retained_layout();
152
+ let fresh = runtime.build_frame(width, height).unwrap();
153
+ let (retained_scene, fresh_scene) = (describe(&retained.scene), describe(&fresh.scene));
154
+ assert_eq!(
155
+ retained_scene.len(),
156
+ fresh_scene.len(),
157
+ "primitives after {step}"
158
+ );
159
+ for (retained, fresh) in retained_scene.iter().zip(&fresh_scene) {
160
+ assert_eq!(retained, fresh, "scene after {step}");
161
+ }
162
+ assert_eq!(
163
+ retained.accessibility, fresh.accessibility,
164
+ "accessibility after {step}"
165
+ );
166
+ }
167
+
168
+ #[test]
169
+ fn retained_layout_matches_fresh_layout_through_structural_changes() {
170
+ let mut r = runtime("Header");
171
+ let (w, h) = (420.0, 360.0);
172
+ assert_matches_fresh(&r, w, h, "launch");
173
+
174
+ type Step = (&'static str, Box<dyn Fn(&mut Runtime)>);
175
+ let steps: Vec<Step> = vec![
176
+ ("append", Box::new(|r| drop(r.activate_action("append")))),
177
+ (
178
+ "append again",
179
+ Box::new(|r| drop(r.activate_action("append"))),
180
+ ),
181
+ (
182
+ "move up",
183
+ Box::new(|r| drop(r.activate_action(&keyed("c", "up")))),
184
+ ),
185
+ (
186
+ "remove",
187
+ Box::new(|r| drop(r.activate_action(&keyed("b", "remove")))),
188
+ ),
189
+ (
190
+ "type",
191
+ Box::new(|r| {
192
+ assert!(r.focus_action(&keyed("a", "note")));
193
+ r.handle_input(
194
+ InputEvent::TextEdit(TextEdit::Insert("a note that widens the field".into())),
195
+ 420.0,
196
+ 360.0,
197
+ )
198
+ .unwrap();
199
+ }),
200
+ ),
201
+ ("filter", Box::new(|r| drop(r.activate_action("filter")))),
202
+ ("unfilter", Box::new(|r| drop(r.activate_action("filter")))),
203
+ ("hide", Box::new(|r| drop(r.activate_action("hide")))),
204
+ ("show", Box::new(|r| drop(r.activate_action("hide")))),
205
+ (
206
+ "pin",
207
+ Box::new(|r| drop(r.activate_action(&keyed("r10", "pin")))),
208
+ ),
209
+ (
210
+ "hot update",
211
+ Box::new(|r| {
212
+ r.hot_update(&program("A different header"), &[]).unwrap();
213
+ }),
214
+ ),
215
+ ];
216
+ for (step, apply) in steps {
217
+ r.build_frame(w, h).unwrap();
218
+ apply(&mut r);
219
+ assert_matches_fresh(&r, w, h, step);
220
+ }
221
+ // Window resizes reuse the tree too.
222
+ for (width, height) in [(300.0, 200.0), (800.0, 640.0), (420.0, 360.0)] {
223
+ r.build_frame(w, h).unwrap();
224
+ assert_matches_fresh(&r, width, height, "resize");
225
+ }
226
+ }
227
+
228
+ #[test]
229
+ fn unchanged_frames_and_hot_updates_invalidate_only_what_changed() {
230
+ let mut r = runtime("Header");
231
+ r.build_frame(420.0, 360.0).unwrap();
232
+ let first = r.last_layout_sync();
233
+ assert_eq!(
234
+ first.created, first.live,
235
+ "the first frame builds every node"
236
+ );
237
+
238
+ r.build_frame(420.0, 360.0).unwrap();
239
+ let idle = r.last_layout_sync();
240
+ assert_eq!(idle.live, first.live);
241
+ assert_eq!(idle.invalidated(), 0, "an unchanged frame touches nothing");
242
+
243
+ // A compatible hot update that changes one Text keeps every node and
244
+ // remeasures exactly that Text.
245
+ r.hot_update(&program("A different header"), &[]).unwrap();
246
+ r.build_frame(420.0, 360.0).unwrap();
247
+ let update = r.last_layout_sync();
248
+ assert_eq!(update.created + update.removed, 0, "{update:?}");
249
+ assert_eq!(update.remeasured, 1, "{update:?}");
250
+ assert!(update.invalidated() <= 2, "{update:?}");
251
+
252
+ // Appending a row creates only that row's nodes.
253
+ r.activate_action("append");
254
+ r.build_frame(420.0, 360.0).unwrap();
255
+ let append = r.last_layout_sync();
256
+ assert_eq!(append.removed, 0, "{append:?}");
257
+ assert_eq!(
258
+ append.created, 8,
259
+ "one row and its seven children: {append:?}"
260
+ );
261
+ }
262
+
263
+ const PRESERVE: [&str; 5] = ["rows", "onlyPinned", "visible", "next", NOTE];
264
+
265
+ fn preserve() -> Vec<String> {
266
+ PRESERVE.iter().map(|name| (*name).to_owned()).collect()
267
+ }
268
+
269
+ #[test]
270
+ fn reused_for_each_expansions_equal_fresh_materialization() {
271
+ let mut r = runtime("Header");
272
+ assert!(r.materialization_matches_fresh());
273
+ r.activate_action("append");
274
+ assert_eq!(r.last_reused_for_each_count(), 0, "the collection changed");
275
+ assert!(r.materialization_matches_fresh());
276
+ assert!(r.focus_action(&keyed("a", "note")));
277
+ r.handle_input(
278
+ InputEvent::TextEdit(TextEdit::Insert("kept".into())),
279
+ 420.0,
280
+ 360.0,
281
+ )
282
+ .unwrap();
283
+
284
+ // A hot update elsewhere reuses the list and keeps per-key state.
285
+ r.hot_update(&program("Edited header"), &preserve())
286
+ .unwrap();
287
+ assert_eq!(r.last_reused_for_each_count(), 1);
288
+ assert!(r.materialization_matches_fresh());
289
+ assert_eq!(r.state_value(&keyed("a", NOTE)), Some(&json!("kept")));
290
+ assert!(
291
+ r.build_frame(420.0, 360.0)
292
+ .unwrap()
293
+ .scene
294
+ .actions
295
+ .iter()
296
+ .any(|hit| hit.id == keyed("r10", "pin"))
297
+ );
298
+
299
+ // Editing the row template re-expands it.
300
+ r.hot_update(&program_with("Edited header", 9.0), &preserve())
301
+ .unwrap();
302
+ assert_eq!(r.last_reused_for_each_count(), 0, "the template changed");
303
+ assert!(r.materialization_matches_fresh());
304
+
305
+ // Toggling an unrelated structural state (a conditional around the
306
+ // list) re-materializes but reuses the unchanged list.
307
+ r.activate_action("hide");
308
+ r.activate_action("hide");
309
+ assert!(r.materialization_matches_fresh());
310
+
311
+ // Not preserving the collection resets it: a different value, no reuse.
312
+ r.hot_update(&program_with("Edited header", 9.0), &[NOTE.to_owned()])
313
+ .unwrap();
314
+ assert_eq!(r.last_reused_for_each_count(), 0);
315
+ assert!(r.materialization_matches_fresh());
316
+ assert_matches_fresh(&r, 420.0, 360.0, "reset hot update");
317
+
318
+ // A rejected update leaves the running materialization intact.
319
+ let before = r.build_frame(420.0, 360.0).unwrap().accessibility;
320
+ assert!(r.hot_update("{\"version\": 1}", &preserve()).is_err());
321
+ assert!(r.materialization_matches_fresh());
322
+ assert_eq!(r.build_frame(420.0, 360.0).unwrap().accessibility, before);
323
+ }