@mun-ui/ui 0.0.0-stage → 0.2.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 (176) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +114 -2
  3. package/bin/compile.mjs +38 -0
  4. package/bin/desktop.mjs +143 -0
  5. package/bin/dev-protocol.mjs +94 -0
  6. package/bin/formatter.mjs +109 -0
  7. package/bin/hot-reload.mjs +38 -0
  8. package/bin/mun.mjs +538 -0
  9. package/bin/native.mjs +133 -0
  10. package/bin/pnpm-workspace.mjs +58 -0
  11. package/bin/program-patch.mjs +104 -0
  12. package/bin/project.mjs +322 -0
  13. package/bin/watch.mjs +316 -0
  14. package/bin/workflow.mjs +261 -0
  15. package/dist/astro.d.ts +3 -0
  16. package/dist/astro.d.ts.map +1 -0
  17. package/dist/astro.js +3 -0
  18. package/dist/astro.js.map +1 -0
  19. package/dist/closures.d.ts +2 -0
  20. package/dist/closures.d.ts.map +1 -0
  21. package/dist/closures.js +2 -0
  22. package/dist/closures.js.map +1 -0
  23. package/dist/compiler/index.d.ts +2 -0
  24. package/dist/compiler/index.d.ts.map +1 -0
  25. package/dist/compiler/index.js +2 -0
  26. package/dist/compiler/index.js.map +1 -0
  27. package/dist/core.d.ts +3 -0
  28. package/dist/core.d.ts.map +1 -0
  29. package/dist/core.js +3 -0
  30. package/dist/core.js.map +1 -0
  31. package/dist/experimental.d.ts +2 -0
  32. package/dist/experimental.d.ts.map +1 -0
  33. package/dist/experimental.js +2 -0
  34. package/dist/experimental.js.map +1 -0
  35. package/dist/index.d.ts +3 -0
  36. package/dist/index.d.ts.map +1 -0
  37. package/dist/index.js +3 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/jsx-dev-runtime.d.ts +2 -0
  40. package/dist/jsx-dev-runtime.d.ts.map +1 -0
  41. package/dist/jsx-dev-runtime.js +2 -0
  42. package/dist/jsx-dev-runtime.js.map +1 -0
  43. package/dist/jsx-runtime.d.ts +2 -0
  44. package/dist/jsx-runtime.d.ts.map +1 -0
  45. package/dist/jsx-runtime.js +2 -0
  46. package/dist/jsx-runtime.js.map +1 -0
  47. package/dist/legacy.d.ts +3 -0
  48. package/dist/legacy.d.ts.map +1 -0
  49. package/dist/legacy.js +3 -0
  50. package/dist/legacy.js.map +1 -0
  51. package/dist/mun.d.ts +5 -0
  52. package/dist/mun.d.ts.map +1 -0
  53. package/dist/mun.js +4 -0
  54. package/dist/mun.js.map +1 -0
  55. package/dist/progressive-blur/index.d.ts +8 -0
  56. package/dist/progressive-blur/index.d.ts.map +1 -0
  57. package/dist/progressive-blur/index.js +8 -0
  58. package/dist/progressive-blur/index.js.map +1 -0
  59. package/dist/progressive-blur/plan.d.ts +3 -0
  60. package/dist/progressive-blur/plan.d.ts.map +1 -0
  61. package/dist/progressive-blur/plan.js +3 -0
  62. package/dist/progressive-blur/plan.js.map +1 -0
  63. package/dist/react-types.d.ts +2 -0
  64. package/dist/react-types.d.ts.map +1 -0
  65. package/dist/react-types.js +2 -0
  66. package/dist/react-types.js.map +1 -0
  67. package/dist/rendering-quality.d.ts +4 -0
  68. package/dist/rendering-quality.d.ts.map +1 -0
  69. package/dist/rendering-quality.js +4 -0
  70. package/dist/rendering-quality.js.map +1 -0
  71. package/dist/state.d.ts +2 -0
  72. package/dist/state.d.ts.map +1 -0
  73. package/dist/state.js +2 -0
  74. package/dist/state.js.map +1 -0
  75. package/dist/types.d.ts +2 -0
  76. package/dist/types.d.ts.map +1 -0
  77. package/dist/types.js +2 -0
  78. package/dist/types.js.map +1 -0
  79. package/dist/vite.d.ts +2 -0
  80. package/dist/vite.d.ts.map +1 -0
  81. package/dist/vite.js +2 -0
  82. package/dist/vite.js.map +1 -0
  83. package/editors/install.mjs +102 -0
  84. package/editors/lsp/mun-lsp.mjs +123 -0
  85. package/editors/lsp/service.mjs +306 -0
  86. package/editors/lsp/source.mjs +58 -0
  87. package/editors/vscode/client.mjs +40 -0
  88. package/editors/vscode/dev-client.mjs +83 -0
  89. package/editors/vscode/discovery.mjs +46 -0
  90. package/editors/vscode/export.mjs +42 -0
  91. package/editors/vscode/extension.cjs +226 -0
  92. package/editors/vscode/language-configuration.json +15 -0
  93. package/editors/vscode/package.json +119 -0
  94. package/editors/vscode/protocol.mjs +29 -0
  95. package/editors/vscode/syntaxes/mun.tmLanguage.json +130 -0
  96. package/native/Cargo.lock +3581 -0
  97. package/native/Cargo.toml +21 -0
  98. package/native/README.md +21 -0
  99. package/native/mun-native/Cargo.toml +23 -0
  100. package/native/mun-native/src/accessibility.rs +738 -0
  101. package/native/mun-native/src/dev.rs +604 -0
  102. package/native/mun-native/src/host_services.rs +202 -0
  103. package/native/mun-native/src/lib.rs +2843 -0
  104. package/native/mun-native/src/main.rs +204 -0
  105. package/native/mun-native/src/offscreen.rs +393 -0
  106. package/native/mun-native/src/rect.wgsl +63 -0
  107. package/native/mun-native/src/text.rs +401 -0
  108. package/native/mun-native/tests/offscreen_rendering.rs +161 -0
  109. package/native/mun-native/tests/stress.rs +408 -0
  110. package/native/mun-native/tests/window_lifecycle.rs +183 -0
  111. package/native/mun-runtime/Cargo.toml +13 -0
  112. package/native/mun-runtime/src/accessibility.rs +193 -0
  113. package/native/mun-runtime/src/collection.rs +1090 -0
  114. package/native/mun-runtime/src/gesture.rs +1070 -0
  115. package/native/mun-runtime/src/input.rs +325 -0
  116. package/native/mun-runtime/src/ir.rs +852 -0
  117. package/native/mun-runtime/src/kinetics.rs +500 -0
  118. package/native/mun-runtime/src/layout.rs +258 -0
  119. package/native/mun-runtime/src/layout_cache.rs +209 -0
  120. package/native/mun-runtime/src/lib.rs +52 -0
  121. package/native/mun-runtime/src/motion.rs +1162 -0
  122. package/native/mun-runtime/src/retained.rs +574 -0
  123. package/native/mun-runtime/src/runtime.rs +7449 -0
  124. package/native/mun-runtime/src/scene.rs +567 -0
  125. package/native/mun-runtime/src/scroll.rs +521 -0
  126. package/native/mun-runtime/src/scroll_view.rs +220 -0
  127. package/native/mun-runtime/src/text_edit.rs +670 -0
  128. package/native/mun-runtime/src/timeline.rs +1534 -0
  129. package/native/mun-runtime/src/validate.rs +677 -0
  130. package/native/mun-runtime/tests/accessibility_semantics.rs +168 -0
  131. package/native/mun-runtime/tests/compiler_contract.rs +110 -0
  132. package/native/mun-runtime/tests/flexible_frames.rs +47 -0
  133. package/native/mun-runtime/tests/host_services.rs +107 -0
  134. package/native/mun-runtime/tests/hot_update.rs +367 -0
  135. package/native/mun-runtime/tests/incremental_runtime.rs +323 -0
  136. package/native/mun-runtime/tests/ir_validation.rs +167 -0
  137. package/native/mun-runtime/tests/keyed_collections.rs +251 -0
  138. package/native/mun-runtime/tests/minimum_window_size.rs +80 -0
  139. package/native/mun-runtime/tests/native_controls_style.rs +491 -0
  140. package/native/mun-runtime/tests/native_demo.rs +285 -0
  141. package/native/mun-runtime/tests/native_layout_style.rs +175 -0
  142. package/native/mun-runtime/tests/native_settings_pane.rs +152 -0
  143. package/native/mun-runtime/tests/priority_proposals.rs +69 -0
  144. package/native/mun-runtime/tests/scroll_view.rs +403 -0
  145. package/native/mun-runtime/tests/text_editing.rs +491 -0
  146. package/native/mun-runtime/tests/text_proposals.rs +42 -0
  147. package/native/mun-runtime/tests/typography.rs +63 -0
  148. package/package.json +213 -3
  149. package/schemas/README.md +19 -0
  150. package/schemas/semantic-ui-ir-v1.schema.json +2061 -0
  151. package/templates/desktop/gitignore +5 -0
  152. package/templates/desktop/package.json +10 -0
  153. package/templates/desktop/src-tauri/Cargo.toml +14 -0
  154. package/templates/desktop/src-tauri/build.rs +1 -0
  155. package/templates/desktop/src-tauri/capabilities/main.json +12 -0
  156. package/templates/desktop/src-tauri/icons/icon.icns +0 -0
  157. package/templates/desktop/src-tauri/icons/icon.ico +0 -0
  158. package/templates/desktop/src-tauri/icons/icon.png +0 -0
  159. package/templates/desktop/src-tauri/src/main.rs +2 -0
  160. package/templates/desktop/src-tauri/tauri.conf.json +42 -0
  161. package/templates/desktop/vite.config.ts +10 -0
  162. package/templates/native/App.mun +15 -0
  163. package/templates/native/gitignore +3 -0
  164. package/templates/native/mun.toml +8 -0
  165. package/templates/project/gitignore +5 -0
  166. package/templates/project/index.html +13 -0
  167. package/templates/project/package.json +24 -0
  168. package/templates/project/src/App.mun +13 -0
  169. package/templates/project/src/index.css +30 -0
  170. package/templates/project/src/main.ts +5 -0
  171. package/templates/project/tsconfig.json +20 -0
  172. package/templates/project/vite.config.ts +6 -0
  173. package/templates/vite/src/App.css +134 -0
  174. package/templates/vite/src/App.tsx +91 -0
  175. package/templates/vite/src/index.css +23 -0
  176. package/templates/vite/vite.config.ts +10 -0
@@ -0,0 +1,1090 @@
1
+ //! Runtime-owned keyed collections and item state scopes.
2
+ //!
3
+ //! The semantic IR describes `forEach` templates. Before layout, the runtime
4
+ //! materializes one instance of the template per collection item:
5
+ //!
6
+ //! * instance identity = template node identity + `[`encoded key`]` (one
7
+ //! bracketed segment per enclosing `forEach`; `[` never occurs in compiler
8
+ //! identities because key segments and `.id(_:)` keys are percent-encoded),
9
+ //! for every node in the instance, so focus, editors, scroll offsets,
10
+ //! retained identity, transitions and FLIP follow the *key*, never the index;
11
+ //! * item expressions are substituted with the item's values;
12
+ //! * View-local state declared inside the template (`UiState::scope`) is renamed
13
+ //! to per-key instance storage, created on first appearance of the key and
14
+ //! released when the key leaves its collection.
15
+ //!
16
+ //! Duplicate keys are rejected explicitly; they are never aliased.
17
+ use std::{
18
+ collections::{BTreeMap, HashMap, HashSet},
19
+ rc::Rc,
20
+ };
21
+
22
+ use serde_json::Value;
23
+
24
+ use crate::ir::{UiAction, UiCollectionOperation, UiExpression, UiFilterOperator, UiNode, UiState};
25
+
26
+ /// Static facts about item-scoped state derived from the IR once at load.
27
+ #[derive(Clone, Debug, Default)]
28
+ pub(crate) struct ScopeModel {
29
+ /// Template state name -> declaring `forEach` template id.
30
+ scoped_states: HashMap<String, String>,
31
+ /// Template state name -> initial value.
32
+ initials: HashMap<String, Value>,
33
+ /// States read by any `forEach` collection expression (structural deps).
34
+ pub(crate) structural_states: HashSet<String>,
35
+ /// Template states that can change retained structure: read by a
36
+ /// conditional's condition, a `.id(_:)` identity key or a `forEach`
37
+ /// collection. Edits to any other state cannot insert, remove, replace or
38
+ /// reparent retained nodes.
39
+ structure_states: HashSet<String>,
40
+ }
41
+
42
+ impl ScopeModel {
43
+ pub(crate) fn new(states: &[UiState], template: &UiNode) -> Self {
44
+ let mut model = Self::default();
45
+ for state in states {
46
+ if let Some(scope) = &state.scope {
47
+ model
48
+ .scoped_states
49
+ .insert(state.name.clone(), scope.clone());
50
+ model
51
+ .initials
52
+ .insert(state.name.clone(), state.initial.clone());
53
+ }
54
+ }
55
+ collect_structural_states(template, &mut model.structural_states);
56
+ model.structure_states = model.structural_states.clone();
57
+ collect_structure_states(template, &mut model.structure_states);
58
+ model
59
+ }
60
+
61
+ /// Whether a concrete state (template name or per-key instance) can change
62
+ /// the retained node structure.
63
+ pub(crate) fn affects_structure(&self, state: &str) -> bool {
64
+ let template = state
65
+ .split_once('[')
66
+ .map_or(state, |(template, _)| template);
67
+ self.structure_states.contains(template)
68
+ }
69
+
70
+ pub(crate) fn add_structure_expression(&mut self, expression: &UiExpression) {
71
+ expression_states(expression, &mut self.structure_states);
72
+ }
73
+
74
+ pub(crate) fn is_scoped(&self, state: &str) -> bool {
75
+ self.scoped_states.contains_key(state)
76
+ }
77
+
78
+ /// Whether a concrete state name is a per-key instance of scoped state.
79
+ pub(crate) fn is_instance(&self, name: &str) -> bool {
80
+ name.split_once('[')
81
+ .is_some_and(|(template, _)| self.is_scoped(template))
82
+ }
83
+
84
+ pub(crate) fn has_collections(&self) -> bool {
85
+ !self.structural_states.is_empty()
86
+ }
87
+ }
88
+
89
+ fn collect_structural_states(node: &UiNode, output: &mut HashSet<String>) {
90
+ if let UiNode::ForEach { collection, .. } = node {
91
+ expression_states(collection, output);
92
+ }
93
+ if let UiNode::Conditional {
94
+ then_nodes,
95
+ otherwise,
96
+ ..
97
+ } = node
98
+ {
99
+ for child in then_nodes.iter().chain(otherwise) {
100
+ collect_structural_states(child, output);
101
+ }
102
+ }
103
+ for child in node.children() {
104
+ collect_structural_states(child, output);
105
+ }
106
+ }
107
+
108
+ fn collect_structure_states(node: &UiNode, output: &mut HashSet<String>) {
109
+ if let Some(key) = &node.base().identity_key {
110
+ expression_states(key, output);
111
+ }
112
+ if let UiNode::Conditional {
113
+ condition,
114
+ then_nodes,
115
+ otherwise,
116
+ ..
117
+ } = node
118
+ {
119
+ expression_states(condition, output);
120
+ for child in then_nodes.iter().chain(otherwise) {
121
+ collect_structure_states(child, output);
122
+ }
123
+ }
124
+ for child in node.children() {
125
+ collect_structure_states(child, output);
126
+ }
127
+ }
128
+
129
+ fn expression_states(expression: &UiExpression, output: &mut HashSet<String>) {
130
+ match expression {
131
+ UiExpression::State { state } => {
132
+ output.insert(state.clone());
133
+ }
134
+ UiExpression::Not { value } | UiExpression::Stringify { value } => {
135
+ expression_states(value, output)
136
+ }
137
+ UiExpression::Binary { left, right, .. } => {
138
+ expression_states(left, output);
139
+ expression_states(right, output);
140
+ }
141
+ UiExpression::Conditional {
142
+ condition,
143
+ then_value,
144
+ otherwise,
145
+ } => {
146
+ expression_states(condition, output);
147
+ expression_states(then_value, output);
148
+ expression_states(otherwise, output);
149
+ }
150
+ UiExpression::Record { fields } => {
151
+ for field in fields.values() {
152
+ expression_states(field, output);
153
+ }
154
+ }
155
+ UiExpression::Count { collection } => expression_states(collection, output),
156
+ UiExpression::Filter {
157
+ collection, value, ..
158
+ } => {
159
+ expression_states(collection, output);
160
+ expression_states(value, output);
161
+ }
162
+ UiExpression::Literal { .. } | UiExpression::Item { .. } => {}
163
+ }
164
+ }
165
+
166
+ /// Canonical, collision-free key segment: strings and finite numbers only.
167
+ pub fn key_segment(value: &Value) -> Option<String> {
168
+ match value {
169
+ Value::String(text) => Some(format!("s:{}", percent_encode(text))),
170
+ Value::Number(number) => {
171
+ let number = number.as_f64()?;
172
+ if !number.is_finite() {
173
+ return None;
174
+ }
175
+ let number = if number == 0.0 { 0.0 } else { number };
176
+ Some(format!("n:{number}"))
177
+ }
178
+ _ => None,
179
+ }
180
+ }
181
+
182
+ fn percent_encode(text: &str) -> String {
183
+ let mut output = String::with_capacity(text.len());
184
+ for byte in text.bytes() {
185
+ if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.') {
186
+ output.push(byte as char);
187
+ } else {
188
+ output.push_str(&format!("%{byte:02X}"));
189
+ }
190
+ }
191
+ output
192
+ }
193
+
194
+ pub fn value_at_path<'a>(value: &'a Value, path: &[String]) -> Option<&'a Value> {
195
+ path.iter()
196
+ .try_fold(value, |current, field| current.as_object()?.get(field))
197
+ }
198
+
199
+ /// Pure expression evaluation over a state map.
200
+ pub(crate) fn evaluate(expression: &UiExpression, state: &HashMap<String, Value>) -> Value {
201
+ match expression {
202
+ UiExpression::Literal { value } => value.clone(),
203
+ UiExpression::State { state: name } => state.get(name).cloned().unwrap_or(Value::Null),
204
+ UiExpression::Not { value } => {
205
+ Value::Bool(!evaluate(value, state).as_bool().unwrap_or(false))
206
+ }
207
+ UiExpression::Stringify { value } => {
208
+ Value::String(crate::runtime::scalar_string(&evaluate(value, state)))
209
+ }
210
+ UiExpression::Binary {
211
+ operator,
212
+ left,
213
+ right,
214
+ } => crate::runtime::evaluate_binary(
215
+ *operator,
216
+ evaluate(left, state),
217
+ evaluate(right, state),
218
+ ),
219
+ UiExpression::Conditional {
220
+ condition,
221
+ then_value,
222
+ otherwise,
223
+ } => {
224
+ if evaluate(condition, state).as_bool().unwrap_or(false) {
225
+ evaluate(then_value, state)
226
+ } else {
227
+ evaluate(otherwise, state)
228
+ }
229
+ }
230
+ // Materialization substitutes every item reference; one surviving here
231
+ // is outside any forEach and has no value.
232
+ UiExpression::Item { .. } => Value::Null,
233
+ UiExpression::Record { fields } => Value::Object(
234
+ fields
235
+ .iter()
236
+ .map(|(name, field)| (name.clone(), evaluate(field, state)))
237
+ .collect(),
238
+ ),
239
+ UiExpression::Count { collection } => match evaluate(collection, state) {
240
+ Value::Array(items) => Value::from(items.len()),
241
+ _ => Value::from(0),
242
+ },
243
+ UiExpression::Filter {
244
+ collection,
245
+ path,
246
+ operator,
247
+ value,
248
+ } => {
249
+ let expected = evaluate(value, state);
250
+ let Value::Array(items) = evaluate(collection, state) else {
251
+ return Value::Array(Vec::new());
252
+ };
253
+ Value::Array(
254
+ items
255
+ .into_iter()
256
+ .filter(|item| {
257
+ let matches = value_at_path(item, path) == Some(&expected);
258
+ match operator {
259
+ UiFilterOperator::Equal => matches,
260
+ UiFilterOperator::NotEqual => !matches,
261
+ }
262
+ })
263
+ .collect(),
264
+ )
265
+ }
266
+ }
267
+ }
268
+
269
+ #[derive(Clone, Debug, PartialEq, Eq)]
270
+ pub enum CollectionError {
271
+ /// Two items of one `forEach` (or one keyed mutation) share a key.
272
+ DuplicateKey { collection: String, key: String },
273
+ /// An item key is missing or not a string/finite number.
274
+ InvalidKey { collection: String },
275
+ /// A `forEach` collection or a mutated state is not an array.
276
+ NotACollection { collection: String },
277
+ }
278
+
279
+ impl std::fmt::Display for CollectionError {
280
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
281
+ match self {
282
+ Self::DuplicateKey { collection, key } => {
283
+ write!(
284
+ formatter,
285
+ "duplicate item key {key} in collection '{collection}'"
286
+ )
287
+ }
288
+ Self::InvalidKey { collection } => write!(
289
+ formatter,
290
+ "collection '{collection}' has an item whose key is not a string or finite number"
291
+ ),
292
+ Self::NotACollection { collection } => {
293
+ write!(
294
+ formatter,
295
+ "'{collection}' is not a collection (array) value"
296
+ )
297
+ }
298
+ }
299
+ }
300
+ }
301
+
302
+ struct Scope<'a> {
303
+ for_each: &'a str,
304
+ segment: String,
305
+ item: Value,
306
+ }
307
+
308
+ /// What one top-level `forEach` expansion depended on and created. The
309
+ /// expansion is a pure function of its template subtree, its evaluated
310
+ /// collection and the item-scoped state declarations, so when all three are
311
+ /// unchanged the previous instances are reused instead of re-expanded.
312
+ #[derive(Clone, Debug)]
313
+ pub(crate) struct ForEachMemo {
314
+ template: Rc<UiNode>,
315
+ collection: Rc<Value>,
316
+ /// Concrete per-key state instances the expansion renamed state to.
317
+ instances: Rc<[String]>,
318
+ }
319
+
320
+ /// Top-level `forEach` id -> its last expansion.
321
+ pub(crate) type MaterializationMemo = HashMap<String, ForEachMemo>;
322
+
323
+ /// A previous materialization whose unchanged `forEach` expansions may be reused.
324
+ pub(crate) struct PreviousMaterialization<'a> {
325
+ pub(crate) memo: &'a MaterializationMemo,
326
+ pub(crate) model: &'a ScopeModel,
327
+ }
328
+
329
+ /// Result of materializing the template against the current state.
330
+ pub(crate) struct Materialized {
331
+ pub(crate) root: UiNode,
332
+ pub(crate) memo: MaterializationMemo,
333
+ /// `forEach` fragments emitted empty because the previous expansion is
334
+ /// still exact; the caller moves the previous instances in with
335
+ /// [`splice_reused`] once the new materialization is committed.
336
+ pub(crate) reused: Vec<String>,
337
+ }
338
+
339
+ pub(crate) fn materialize(
340
+ template: &UiNode,
341
+ model: &ScopeModel,
342
+ state: &mut HashMap<String, Value>,
343
+ previous: Option<PreviousMaterialization<'_>>,
344
+ ) -> Result<Materialized, CollectionError> {
345
+ // Renaming depends on which forEach declares each item-scoped state.
346
+ let previous = previous.filter(|previous| previous.model.scoped_states == model.scoped_states);
347
+ let mut expander = Expander {
348
+ model,
349
+ state,
350
+ live_instances: HashSet::new(),
351
+ previous: previous.map(|previous| previous.memo),
352
+ memo: MaterializationMemo::new(),
353
+ reused: Vec::new(),
354
+ recording: None,
355
+ };
356
+ let mut scopes = Vec::new();
357
+ let root = expander.node(template, &mut scopes)?;
358
+ let (memo, reused) = (expander.memo, expander.reused);
359
+ let live_instances = expander.live_instances;
360
+ // Release instance state for keys that left their collection.
361
+ let stale = state
362
+ .keys()
363
+ .filter(|name| !live_instances.contains(*name) && model.is_instance(name))
364
+ .cloned()
365
+ .collect::<Vec<_>>();
366
+ for name in stale {
367
+ state.remove(&name);
368
+ }
369
+ Ok(Materialized { root, memo, reused })
370
+ }
371
+
372
+ /// Move the instances of every reused `forEach` fragment from `source` (the
373
+ /// previous materialized tree) into the empty fragment of the same id in
374
+ /// `target`.
375
+ pub(crate) fn splice_reused(target: &mut UiNode, source: &mut UiNode, reused: &[String]) {
376
+ for id in reused {
377
+ let instances = fragment_mut(source, id)
378
+ .map(std::mem::take)
379
+ .expect("a reused forEach fragment exists in the previous materialization");
380
+ *fragment_mut(target, id).expect("a reused forEach fragment was emitted") = instances;
381
+ }
382
+ }
383
+
384
+ fn fragment_mut<'a>(node: &'a mut UiNode, id: &str) -> Option<&'a mut Vec<UiNode>> {
385
+ match node {
386
+ UiNode::Conditional {
387
+ base,
388
+ then_nodes,
389
+ otherwise,
390
+ ..
391
+ } => {
392
+ if base.id == id {
393
+ return Some(then_nodes);
394
+ }
395
+ then_nodes
396
+ .iter_mut()
397
+ .chain(otherwise.iter_mut())
398
+ .find_map(|child| fragment_mut(child, id))
399
+ }
400
+ UiNode::Column { children, .. }
401
+ | UiNode::Row { children, .. }
402
+ | UiNode::Scroll { children, .. }
403
+ | UiNode::Overlay { children, .. } => children
404
+ .iter_mut()
405
+ .find_map(|child| fragment_mut(child, id)),
406
+ _ => None,
407
+ }
408
+ }
409
+
410
+ fn contains_for_each(nodes: &[UiNode]) -> bool {
411
+ nodes.iter().any(|node| match node {
412
+ UiNode::ForEach { .. } => true,
413
+ UiNode::Conditional {
414
+ then_nodes,
415
+ otherwise,
416
+ ..
417
+ } => contains_for_each(then_nodes) || contains_for_each(otherwise),
418
+ _ => contains_for_each(node.children()),
419
+ })
420
+ }
421
+
422
+ struct Expander<'m, 's> {
423
+ model: &'m ScopeModel,
424
+ state: &'s mut HashMap<String, Value>,
425
+ live_instances: HashSet<String>,
426
+ previous: Option<&'m MaterializationMemo>,
427
+ memo: MaterializationMemo,
428
+ reused: Vec<String>,
429
+ /// Instances renamed while expanding the current top-level forEach.
430
+ recording: Option<Vec<String>>,
431
+ }
432
+
433
+ impl Expander<'_, '_> {
434
+ fn suffix(scopes: &[Scope<'_>]) -> String {
435
+ scopes
436
+ .iter()
437
+ .map(|scope| format!("[{}]", scope.segment))
438
+ .collect()
439
+ }
440
+
441
+ fn rename_state(&mut self, name: &str, scopes: &[Scope<'_>]) -> String {
442
+ let Some(declared) = self.model.scoped_states.get(name) else {
443
+ return name.to_owned();
444
+ };
445
+ let Some(position) = scopes.iter().position(|scope| scope.for_each == declared) else {
446
+ return name.to_owned();
447
+ };
448
+ let concrete = format!("{name}{}", Self::suffix(&scopes[..=position]));
449
+ if !self.state.contains_key(&concrete) {
450
+ let initial = self
451
+ .model
452
+ .initials
453
+ .get(name)
454
+ .cloned()
455
+ .unwrap_or(Value::Null);
456
+ self.state.insert(concrete.clone(), initial);
457
+ }
458
+ if let Some(recording) = &mut self.recording {
459
+ recording.push(concrete.clone());
460
+ }
461
+ self.live_instances.insert(concrete.clone());
462
+ concrete
463
+ }
464
+
465
+ fn expression(&mut self, expression: &UiExpression, scopes: &[Scope<'_>]) -> UiExpression {
466
+ let boxed =
467
+ |this: &mut Self, value: &UiExpression| Box::new(this.expression(value, scopes));
468
+ match expression {
469
+ UiExpression::Literal { .. } => expression.clone(),
470
+ UiExpression::State { state } => UiExpression::State {
471
+ state: self.rename_state(state, scopes),
472
+ },
473
+ UiExpression::Not { value } => UiExpression::Not {
474
+ value: boxed(self, value),
475
+ },
476
+ UiExpression::Stringify { value } => UiExpression::Stringify {
477
+ value: boxed(self, value),
478
+ },
479
+ UiExpression::Binary {
480
+ operator,
481
+ left,
482
+ right,
483
+ } => UiExpression::Binary {
484
+ operator: *operator,
485
+ left: boxed(self, left),
486
+ right: boxed(self, right),
487
+ },
488
+ UiExpression::Conditional {
489
+ condition,
490
+ then_value,
491
+ otherwise,
492
+ } => UiExpression::Conditional {
493
+ condition: boxed(self, condition),
494
+ then_value: boxed(self, then_value),
495
+ otherwise: boxed(self, otherwise),
496
+ },
497
+ UiExpression::Item { for_each, path } => {
498
+ let value = scopes
499
+ .iter()
500
+ .rev()
501
+ .find(|scope| scope.for_each == for_each)
502
+ .and_then(|scope| value_at_path(&scope.item, path))
503
+ .cloned()
504
+ .unwrap_or(Value::Null);
505
+ UiExpression::Literal { value }
506
+ }
507
+ UiExpression::Record { fields } => UiExpression::Record {
508
+ fields: fields
509
+ .iter()
510
+ .map(|(name, field)| (name.clone(), self.expression(field, scopes)))
511
+ .collect::<BTreeMap<_, _>>(),
512
+ },
513
+ UiExpression::Count { collection } => UiExpression::Count {
514
+ collection: boxed(self, collection),
515
+ },
516
+ UiExpression::Filter {
517
+ collection,
518
+ path,
519
+ operator,
520
+ value,
521
+ } => UiExpression::Filter {
522
+ collection: boxed(self, collection),
523
+ path: path.clone(),
524
+ operator: *operator,
525
+ value: boxed(self, value),
526
+ },
527
+ }
528
+ }
529
+
530
+ fn optional(
531
+ &mut self,
532
+ expression: &Option<UiExpression>,
533
+ scopes: &[Scope<'_>],
534
+ ) -> Option<UiExpression> {
535
+ expression
536
+ .as_ref()
537
+ .map(|expression| self.expression(expression, scopes))
538
+ }
539
+
540
+ fn action(&mut self, action: &UiAction, scopes: &[Scope<'_>]) -> UiAction {
541
+ match action {
542
+ UiAction::ToggleState { state, transaction } => UiAction::ToggleState {
543
+ state: self.rename_state(state, scopes),
544
+ transaction: transaction.clone(),
545
+ },
546
+ UiAction::SetState {
547
+ state,
548
+ value,
549
+ transaction,
550
+ } => UiAction::SetState {
551
+ state: self.rename_state(state, scopes),
552
+ value: self.expression(value, scopes),
553
+ transaction: transaction.clone(),
554
+ },
555
+ UiAction::Collection {
556
+ state,
557
+ key_path,
558
+ operation,
559
+ transaction,
560
+ } => UiAction::Collection {
561
+ state: self.rename_state(state, scopes),
562
+ key_path: key_path.clone(),
563
+ operation: match operation {
564
+ UiCollectionOperation::Insert { index, value } => {
565
+ UiCollectionOperation::Insert {
566
+ index: self.expression(index, scopes),
567
+ value: self.expression(value, scopes),
568
+ }
569
+ }
570
+ UiCollectionOperation::Append { value } => UiCollectionOperation::Append {
571
+ value: self.expression(value, scopes),
572
+ },
573
+ UiCollectionOperation::Remove { key } => UiCollectionOperation::Remove {
574
+ key: self.expression(key, scopes),
575
+ },
576
+ UiCollectionOperation::Move { key, offset } => UiCollectionOperation::Move {
577
+ key: self.expression(key, scopes),
578
+ offset: self.expression(offset, scopes),
579
+ },
580
+ UiCollectionOperation::Update { key, path, value } => {
581
+ UiCollectionOperation::Update {
582
+ key: self.expression(key, scopes),
583
+ path: path.clone(),
584
+ value: self.expression(value, scopes),
585
+ }
586
+ }
587
+ },
588
+ transaction: transaction.clone(),
589
+ },
590
+ UiAction::Sequence {
591
+ actions,
592
+ transaction,
593
+ } => UiAction::Sequence {
594
+ actions: actions
595
+ .iter()
596
+ .map(|action| self.action(action, scopes))
597
+ .collect(),
598
+ transaction: transaction.clone(),
599
+ },
600
+ UiAction::Host {
601
+ service,
602
+ operation,
603
+ arguments,
604
+ state,
605
+ transaction,
606
+ } => UiAction::Host {
607
+ service: service.clone(),
608
+ operation: operation.clone(),
609
+ arguments: arguments
610
+ .iter()
611
+ .map(|argument| self.expression(argument, scopes))
612
+ .collect(),
613
+ state: state.as_ref().map(|state| self.rename_state(state, scopes)),
614
+ transaction: transaction.clone(),
615
+ },
616
+ }
617
+ }
618
+
619
+ fn base(&mut self, base: &crate::ir::NodeBase, scopes: &[Scope<'_>]) -> crate::ir::NodeBase {
620
+ let mut output = base.clone();
621
+ output.id = format!("{}{}", base.id, Self::suffix(scopes));
622
+ output.identity_key = self.optional(&base.identity_key, scopes);
623
+ if let Some(layout) = &mut output.layout {
624
+ layout.width = layout
625
+ .width
626
+ .take()
627
+ .map(|value| self.expression(&value, scopes));
628
+ layout.height = layout
629
+ .height
630
+ .take()
631
+ .map(|value| self.expression(&value, scopes));
632
+ }
633
+ if let Some(visual) = &mut output.visual {
634
+ visual.opacity = visual
635
+ .opacity
636
+ .take()
637
+ .map(|value| self.expression(&value, scopes));
638
+ visual.translation_x = visual
639
+ .translation_x
640
+ .take()
641
+ .map(|value| self.expression(&value, scopes));
642
+ visual.translation_y = visual
643
+ .translation_y
644
+ .take()
645
+ .map(|value| self.expression(&value, scopes));
646
+ }
647
+ if let Some(accessibility) = &mut output.accessibility {
648
+ accessibility.enabled = accessibility
649
+ .enabled
650
+ .take()
651
+ .map(|value| self.expression(&value, scopes));
652
+ }
653
+ if let Some(lifecycle) = &mut output.lifecycle {
654
+ lifecycle.appear = lifecycle
655
+ .appear
656
+ .take()
657
+ .map(|action| self.action(&action, scopes));
658
+ lifecycle.disappear = lifecycle
659
+ .disappear
660
+ .take()
661
+ .map(|action| self.action(&action, scopes));
662
+ }
663
+ for binding in &mut output.motion {
664
+ binding.value = self.expression(&binding.value, scopes);
665
+ binding.trigger = binding
666
+ .trigger
667
+ .take()
668
+ .map(|value| self.expression(&value, scopes));
669
+ }
670
+ output
671
+ }
672
+
673
+ fn nodes<'t>(
674
+ &mut self,
675
+ nodes: &'t [UiNode],
676
+ scopes: &mut Vec<Scope<'t>>,
677
+ ) -> Result<Vec<UiNode>, CollectionError> {
678
+ nodes.iter().map(|node| self.node(node, scopes)).collect()
679
+ }
680
+
681
+ fn node<'t>(
682
+ &mut self,
683
+ node: &'t UiNode,
684
+ scopes: &mut Vec<Scope<'t>>,
685
+ ) -> Result<UiNode, CollectionError> {
686
+ Ok(match node {
687
+ UiNode::ForEach {
688
+ base,
689
+ collection,
690
+ key_path,
691
+ children,
692
+ } => {
693
+ let id = format!("{}{}", base.id, Self::suffix(scopes));
694
+ let collection_expression = self.expression(collection, scopes);
695
+ let evaluated = evaluate(&collection_expression, self.state);
696
+ // Only top-level expansions without nested forEach are pure
697
+ // functions of (template, collection, scoped declarations).
698
+ let memoized =
699
+ scopes.is_empty() && self.recording.is_none() && !contains_for_each(children);
700
+ if memoized {
701
+ let previous = self.previous.and_then(|memo| memo.get(&id)).filter(|memo| {
702
+ *memo.collection == evaluated && memo.template.as_ref() == node
703
+ });
704
+ if let Some(memo) = previous {
705
+ for instance in memo.instances.iter() {
706
+ if !self.state.contains_key(instance) {
707
+ let template = instance
708
+ .split_once('[')
709
+ .map_or(instance.as_str(), |(name, _)| name);
710
+ let initial = self
711
+ .model
712
+ .initials
713
+ .get(template)
714
+ .cloned()
715
+ .unwrap_or(Value::Null);
716
+ self.state.insert(instance.clone(), initial);
717
+ }
718
+ self.live_instances.insert(instance.clone());
719
+ }
720
+ self.memo.insert(id.clone(), memo.clone());
721
+ self.reused.push(id.clone());
722
+ return Ok(UiNode::Conditional {
723
+ base: crate::ir::NodeBase {
724
+ id,
725
+ ..Default::default()
726
+ },
727
+ condition: UiExpression::Literal {
728
+ value: Value::Bool(true),
729
+ },
730
+ then_nodes: Vec::new(),
731
+ otherwise: Vec::new(),
732
+ });
733
+ }
734
+ self.recording = Some(Vec::new());
735
+ }
736
+ let recorded_collection = memoized.then(|| Rc::new(evaluated.clone()));
737
+ let items = match evaluated {
738
+ Value::Array(items) => items,
739
+ Value::Null => Vec::new(),
740
+ _ => return Err(CollectionError::NotACollection { collection: id }),
741
+ };
742
+ let mut seen = HashSet::new();
743
+ let mut instances = Vec::with_capacity(items.len() * children.len());
744
+ for item in items {
745
+ let segment = value_at_path(&item, key_path)
746
+ .and_then(key_segment)
747
+ .ok_or_else(|| CollectionError::InvalidKey {
748
+ collection: id.clone(),
749
+ })?;
750
+ if !seen.insert(segment.clone()) {
751
+ return Err(CollectionError::DuplicateKey {
752
+ collection: id,
753
+ key: segment,
754
+ });
755
+ }
756
+ scopes.push(Scope {
757
+ for_each: &base.id,
758
+ segment,
759
+ item,
760
+ });
761
+ let instance = self.nodes(children, scopes);
762
+ scopes.pop();
763
+ instances.extend(instance?);
764
+ }
765
+ if let Some(collection) = recorded_collection {
766
+ let recorded = self.recording.take().unwrap_or_default();
767
+ self.memo.insert(
768
+ id.clone(),
769
+ ForEachMemo {
770
+ template: Rc::new(node.clone()),
771
+ collection,
772
+ instances: recorded.into(),
773
+ },
774
+ );
775
+ }
776
+ // Materialized as a transparent fragment: like a conditional's
777
+ // active branch, it contributes children without a layout box.
778
+ UiNode::Conditional {
779
+ base: crate::ir::NodeBase {
780
+ id,
781
+ ..Default::default()
782
+ },
783
+ condition: UiExpression::Literal {
784
+ value: Value::Bool(true),
785
+ },
786
+ then_nodes: instances,
787
+ otherwise: Vec::new(),
788
+ }
789
+ }
790
+ UiNode::Column { base, children } => UiNode::Column {
791
+ base: self.base(base, scopes),
792
+ children: self.nodes(children, scopes)?,
793
+ },
794
+ UiNode::Row { base, children } => UiNode::Row {
795
+ base: self.base(base, scopes),
796
+ children: self.nodes(children, scopes)?,
797
+ },
798
+ UiNode::Scroll {
799
+ base,
800
+ axis,
801
+ children,
802
+ } => UiNode::Scroll {
803
+ base: self.base(base, scopes),
804
+ axis: *axis,
805
+ children: self.nodes(children, scopes)?,
806
+ },
807
+ UiNode::Overlay {
808
+ base,
809
+ alignment,
810
+ children,
811
+ } => UiNode::Overlay {
812
+ base: self.base(base, scopes),
813
+ alignment: *alignment,
814
+ children: self.nodes(children, scopes)?,
815
+ },
816
+ UiNode::Conditional {
817
+ base,
818
+ condition,
819
+ then_nodes,
820
+ otherwise,
821
+ } => UiNode::Conditional {
822
+ base: self.base(base, scopes),
823
+ condition: self.expression(condition, scopes),
824
+ then_nodes: self.nodes(then_nodes, scopes)?,
825
+ otherwise: self.nodes(otherwise, scopes)?,
826
+ },
827
+ UiNode::Text { base, value, font } => UiNode::Text {
828
+ base: self.base(base, scopes),
829
+ value: self.expression(value, scopes),
830
+ font: *font,
831
+ },
832
+ UiNode::Panel { base, shape } => UiNode::Panel {
833
+ base: self.base(base, scopes),
834
+ shape: *shape,
835
+ },
836
+ UiNode::TextField {
837
+ base,
838
+ state,
839
+ placeholder,
840
+ secure,
841
+ } => UiNode::TextField {
842
+ base: self.base(base, scopes),
843
+ state: self.rename_state(state, scopes),
844
+ placeholder: placeholder.clone(),
845
+ secure: *secure,
846
+ },
847
+ UiNode::Toggle { base, state, label } => UiNode::Toggle {
848
+ base: self.base(base, scopes),
849
+ state: self.rename_state(state, scopes),
850
+ label: label.clone(),
851
+ },
852
+ UiNode::Progress {
853
+ base,
854
+ value,
855
+ total,
856
+ label,
857
+ } => UiNode::Progress {
858
+ base: self.base(base, scopes),
859
+ value: self.expression(value, scopes),
860
+ total: total.as_ref().map(|total| self.expression(total, scopes)),
861
+ label: label.clone(),
862
+ },
863
+ UiNode::Spacer { base, min_length } => UiNode::Spacer {
864
+ base: self.base(base, scopes),
865
+ min_length: *min_length,
866
+ },
867
+ UiNode::Divider { base } => UiNode::Divider {
868
+ base: self.base(base, scopes),
869
+ },
870
+ UiNode::RadioGroup {
871
+ base,
872
+ state,
873
+ options,
874
+ } => UiNode::RadioGroup {
875
+ base: self.base(base, scopes),
876
+ state: self.rename_state(state, scopes),
877
+ options: options.clone(),
878
+ },
879
+ UiNode::Action {
880
+ base,
881
+ label,
882
+ action,
883
+ } => UiNode::Action {
884
+ base: self.base(base, scopes),
885
+ label: label.clone(),
886
+ action: self.action(action, scopes),
887
+ },
888
+ })
889
+ }
890
+ }
891
+
892
+ /// Apply one evaluated keyed mutation to a collection value. Items are found by
893
+ /// key; a mutation producing duplicate or invalid keys fails without effect.
894
+ pub(crate) fn apply_operation(
895
+ collection_name: &str,
896
+ collection: &Value,
897
+ key_path: &[String],
898
+ operation: &EvaluatedOperation,
899
+ ) -> Result<Value, CollectionError> {
900
+ let mut items = match collection {
901
+ Value::Array(items) => items.clone(),
902
+ Value::Null => Vec::new(),
903
+ _ => {
904
+ return Err(CollectionError::NotACollection {
905
+ collection: collection_name.to_owned(),
906
+ });
907
+ }
908
+ };
909
+ let position = |items: &[Value], key: &Value| {
910
+ let wanted = key_segment(key)?;
911
+ items.iter().position(|item| {
912
+ value_at_path(item, key_path)
913
+ .and_then(key_segment)
914
+ .as_deref()
915
+ == Some(&wanted)
916
+ })
917
+ };
918
+ match operation {
919
+ EvaluatedOperation::Insert { index, value } => {
920
+ let index = index.clamp(0.0, items.len() as f64) as usize;
921
+ items.insert(index, value.clone());
922
+ }
923
+ EvaluatedOperation::Append { value } => items.push(value.clone()),
924
+ EvaluatedOperation::Remove { key } => {
925
+ if let Some(index) = position(&items, key) {
926
+ items.remove(index);
927
+ }
928
+ }
929
+ EvaluatedOperation::Move { key, offset } => {
930
+ if let Some(index) = position(&items, key) {
931
+ let target = (index as f64 + offset.trunc())
932
+ .clamp(0.0, items.len().saturating_sub(1) as f64)
933
+ as usize;
934
+ let item = items.remove(index);
935
+ items.insert(target, item);
936
+ }
937
+ }
938
+ EvaluatedOperation::Update { key, path, value } => {
939
+ if let Some(index) = position(&items, key) {
940
+ let mut cursor = &mut items[index];
941
+ for (depth, field) in path.iter().enumerate() {
942
+ let Some(object) = cursor.as_object_mut() else {
943
+ break;
944
+ };
945
+ if depth + 1 == path.len() {
946
+ object.insert(field.clone(), value.clone());
947
+ break;
948
+ }
949
+ cursor = object
950
+ .entry(field.clone())
951
+ .or_insert_with(|| Value::Object(Default::default()));
952
+ }
953
+ }
954
+ }
955
+ }
956
+ let mut seen = HashSet::new();
957
+ for item in &items {
958
+ let segment = value_at_path(item, key_path)
959
+ .and_then(key_segment)
960
+ .ok_or_else(|| CollectionError::InvalidKey {
961
+ collection: collection_name.to_owned(),
962
+ })?;
963
+ if !seen.insert(segment.clone()) {
964
+ return Err(CollectionError::DuplicateKey {
965
+ collection: collection_name.to_owned(),
966
+ key: segment,
967
+ });
968
+ }
969
+ }
970
+ Ok(Value::Array(items))
971
+ }
972
+
973
+ pub(crate) enum EvaluatedOperation {
974
+ Insert {
975
+ index: f64,
976
+ value: Value,
977
+ },
978
+ Append {
979
+ value: Value,
980
+ },
981
+ Remove {
982
+ key: Value,
983
+ },
984
+ Move {
985
+ key: Value,
986
+ offset: f64,
987
+ },
988
+ Update {
989
+ key: Value,
990
+ path: Vec<String>,
991
+ value: Value,
992
+ },
993
+ }
994
+
995
+ impl EvaluatedOperation {
996
+ pub(crate) fn evaluate(
997
+ operation: &UiCollectionOperation,
998
+ state: &HashMap<String, Value>,
999
+ ) -> Self {
1000
+ let number =
1001
+ |expression: &UiExpression| evaluate(expression, state).as_f64().unwrap_or(0.0);
1002
+ match operation {
1003
+ UiCollectionOperation::Insert { index, value } => Self::Insert {
1004
+ index: number(index),
1005
+ value: evaluate(value, state),
1006
+ },
1007
+ UiCollectionOperation::Append { value } => Self::Append {
1008
+ value: evaluate(value, state),
1009
+ },
1010
+ UiCollectionOperation::Remove { key } => Self::Remove {
1011
+ key: evaluate(key, state),
1012
+ },
1013
+ UiCollectionOperation::Move { key, offset } => Self::Move {
1014
+ key: evaluate(key, state),
1015
+ offset: number(offset),
1016
+ },
1017
+ UiCollectionOperation::Update { key, path, value } => Self::Update {
1018
+ key: evaluate(key, state),
1019
+ path: path.clone(),
1020
+ value: evaluate(value, state),
1021
+ },
1022
+ }
1023
+ }
1024
+ }
1025
+
1026
+ #[cfg(test)]
1027
+ mod tests {
1028
+ use super::*;
1029
+
1030
+ #[test]
1031
+ fn key_segments_are_typed_and_collision_free() {
1032
+ assert_eq!(key_segment(&Value::from("a")).unwrap(), "s:a");
1033
+ assert_ne!(key_segment(&Value::from("1")), key_segment(&Value::from(1)));
1034
+ assert_eq!(
1035
+ key_segment(&Value::from(-0.0)),
1036
+ key_segment(&Value::from(0))
1037
+ );
1038
+ assert_eq!(
1039
+ key_segment(&Value::from("a#b/c:option:1")).unwrap(),
1040
+ "s:a%23b%2Fc%3Aoption%3A1"
1041
+ );
1042
+ assert!(key_segment(&Value::Bool(true)).is_none());
1043
+ assert!(key_segment(&Value::Null).is_none());
1044
+ }
1045
+
1046
+ #[test]
1047
+ fn keyed_operations_address_items_by_key_and_reject_duplicates() {
1048
+ let path = vec!["id".to_owned()];
1049
+ let items = serde_json::json!([{"id": "a"}, {"id": "b"}, {"id": "c"}]);
1050
+ let moved = apply_operation(
1051
+ "rows",
1052
+ &items,
1053
+ &path,
1054
+ &EvaluatedOperation::Move {
1055
+ key: Value::from("c"),
1056
+ offset: -5.0,
1057
+ },
1058
+ )
1059
+ .unwrap();
1060
+ assert_eq!(
1061
+ moved,
1062
+ serde_json::json!([{"id": "c"}, {"id": "a"}, {"id": "b"}])
1063
+ );
1064
+ let duplicate = apply_operation(
1065
+ "rows",
1066
+ &items,
1067
+ &path,
1068
+ &EvaluatedOperation::Append {
1069
+ value: serde_json::json!({"id": "a"}),
1070
+ },
1071
+ );
1072
+ assert_eq!(
1073
+ duplicate,
1074
+ Err(CollectionError::DuplicateKey {
1075
+ collection: "rows".into(),
1076
+ key: "s:a".into()
1077
+ })
1078
+ );
1079
+ let missing = apply_operation(
1080
+ "rows",
1081
+ &items,
1082
+ &path,
1083
+ &EvaluatedOperation::Insert {
1084
+ index: 0.0,
1085
+ value: serde_json::json!({"title": "no key"}),
1086
+ },
1087
+ );
1088
+ assert!(matches!(missing, Err(CollectionError::InvalidKey { .. })));
1089
+ }
1090
+ }