microsoft-webui-state 3.0.2

Core state management for WebUI framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

extern crate serde_json;

use std::borrow::Cow;

use serde_json::Value;

/// Objects with at most this many members are searched by direct comparison.
///
/// State objects reached from templates are usually small records (list items,
/// nested settings). Comparing a handful of keys is cheaper than hashing the
/// lookup key, which is what an order-preserving `serde_json::Map` does.
const LINEAR_MEMBER_LOOKUP_MAX: usize = 8;

#[inline]
fn object_member<'a>(map: &'a serde_json::Map<String, Value>, key: &str) -> Option<&'a Value> {
    if map.len() <= LINEAR_MEMBER_LOOKUP_MAX {
        return map
            .iter()
            .find_map(|(name, value)| (name == key).then_some(value));
    }
    map.get(key)
}

/// Finds a value in a JSON object by dotted path and returns a borrowed value when possible.
///
/// Most lookups borrow directly from `state`. Synthetic values such as array
/// and string `.length` are returned as owned values because they do not exist
/// in the source JSON tree.
#[must_use]
pub fn find_value_by_dotted_path_ref<'a>(path: &str, state: &'a Value) -> Option<Cow<'a, Value>> {
    let mut current_value: &Value = state;

    for part in path.split('.') {
        match current_value {
            Value::Object(map) => {
                current_value = object_member(map, part)?;
            }
            Value::Array(arr) if part == "length" => {
                return Some(Cow::Owned(Value::Number(serde_json::Number::from(
                    arr.len(),
                ))));
            }
            Value::String(s) if part == "length" => {
                return Some(Cow::Owned(Value::Number(serde_json::Number::from(s.len()))));
            }
            _ => return None,
        }
    }

    Some(Cow::Borrowed(current_value))
}

/// Finds a value in a JSON object by dotted path and returns an owned value.
///
/// Prefer [`find_value_by_dotted_path_ref`] in render-time hot paths so state
/// values can be borrowed without cloning.
#[must_use]
pub fn find_value_by_dotted_path(path: &str, state: &Value) -> Option<Value> {
    find_value_by_dotted_path_ref(path, state).map(Cow::into_owned)
}

#[cfg(test)]
mod tests {
    use super::*;
    use webui_test_utils::test_json;

    #[test]
    fn test_find_value_by_dotted_path() {
        // Create a JSON object
        let data = test_json!({
            "name": {
                "first": "John",
                "last": "Doe"
            },
            "favorite": {
                "categories": {
                    "movies": ["The Matrix", "The Godfather"],
                    "music": ["Jazz", "Blues"]
                }
            },
            "age": 30
        });

        // Test a successful path
        let value = find_value_by_dotted_path("name.first", &data);
        assert_eq!(
            value,
            Some(Value::String("John".to_string())),
            "Failed to get string."
        );

        // Test a path that leads to single string
        let value = find_value_by_dotted_path("age", &data);
        assert_eq!(
            value,
            Some(Value::Number(serde_json::Number::from(30))),
            "Failed to get number."
        );

        // Test a path that leads to an array
        let value = find_value_by_dotted_path("favorite.categories.music", &data);
        assert_eq!(
            value,
            Some(Value::Array(vec![
                Value::String("Jazz".to_string()),
                Value::String("Blues".to_string())
            ])),
            "Failed to get array."
        );

        // Test a non-existent path
        let value = find_value_by_dotted_path("name.middle", &data);
        assert_eq!(value, None, "Failed to handle non-existent path.");

        // Test a path that leads to a non-object value
        let value = find_value_by_dotted_path("age.years", &data);
        assert_eq!(
            value, None,
            "Failed to handle path that leads to a non-object value."
        );

        // Get length of array.
        let value = find_value_by_dotted_path("favorite.categories.music.length", &data);
        assert_eq!(
            value,
            Some(Value::Number(serde_json::Number::from(2))),
            "Failed to get length of array."
        );
    }

    #[test]
    fn test_nested_nested_path() {
        let data = test_json!({
            "user": {
                "profile": {
                    "nameObj": {
                        "first": "John"
                    }
                }
            }
        });
        let value = find_value_by_dotted_path("user.profile.nameObj.first", &data);
        assert_eq!(value, Some(Value::String("John".to_string())));
    }

    #[test]
    fn test_empty_string_path() {
        let data = test_json!({ "key": "value" });
        let value = find_value_by_dotted_path("", &data);
        assert_eq!(value, None);
    }

    #[test]
    fn test_path_with_spaces() {
        let data = test_json!({
            "user": {
                "profile": {
                    "name": "Alice"
                }
            }
        });
        let value = find_value_by_dotted_path("user.profile.non existent", &data);
        assert_eq!(value, None);
    }

    #[test]
    fn test_numeric_string_token() {
        let data = test_json!({ "numeric_string": "123" });
        let value = find_value_by_dotted_path("numeric_string", &data);
        assert_eq!(value, Some(Value::String("123".to_string())));
    }

    #[test]
    fn test_length_on_empty_list() {
        let data = test_json!({ "empty_list": [] });
        let value = find_value_by_dotted_path("empty_list.length", &data);
        assert_eq!(value, Some(Value::Number(serde_json::Number::from(0))));
    }

    #[test]
    fn test_length_on_nonempty_list() {
        let data = test_json!({ "items": [1, 2, 3] });
        let value = find_value_by_dotted_path("items.length", &data);
        assert_eq!(value, Some(Value::Number(serde_json::Number::from(3))));
    }

    #[test]
    fn test_member_lookup_on_both_sides_of_linear_limit() {
        for size in [LINEAR_MEMBER_LOOKUP_MAX, LINEAR_MEMBER_LOOKUP_MAX + 1] {
            let mut map = serde_json::Map::new();
            for index in 0..size {
                map.insert(format!("key{index}"), Value::from(index));
            }
            let data = Value::Object(map);
            for index in 0..size {
                assert_eq!(
                    find_value_by_dotted_path(&format!("key{index}"), &data),
                    Some(Value::from(index)),
                    "size {size}"
                );
            }
            assert_eq!(find_value_by_dotted_path("key", &data), None, "size {size}");
        }
    }

    #[test]
    fn test_length_named_property() {
        let data = test_json!({
            "nestedlength": {
                "length": "some value"
            }
        });
        let value = find_value_by_dotted_path("nestedlength.length", &data);
        assert_eq!(value, Some(Value::String("some value".to_string())));
    }

    #[test]
    fn test_length_on_nested_list() {
        let data = test_json!({
            "nested": {
                "data": ["a", "b"]
            }
        });
        let value = find_value_by_dotted_path("nested.data.length", &data);
        assert_eq!(value, Some(Value::Number(serde_json::Number::from(2))));
    }

    #[test]
    fn test_nonexistent_path_with_length() {
        let data = test_json!({ "existing": "value" });
        let value = find_value_by_dotted_path("non_existent.length", &data);
        assert_eq!(value, None);
    }

    #[test]
    fn test_length_on_string() {
        let data = test_json!({ "str_val": "hello" });
        let value = find_value_by_dotted_path("str_val.length", &data);
        assert_eq!(value, Some(Value::Number(serde_json::Number::from(5))));
    }

    #[test]
    fn test_length_on_string_matches_nodejs() {
        // NodeJS: 'string_value.length' on "test" → 4
        let data = test_json!({ "string_value": "test" });
        let value = find_value_by_dotted_path("string_value.length", &data);
        assert_eq!(value, Some(Value::Number(serde_json::Number::from(4))));
    }

    #[test]
    fn test_array_index_not_resolved() {
        let data = test_json!({
            "foo": {
                "bar": [10, 20, 30]
            }
        });
        let value = find_value_by_dotted_path("foo.bar.0", &data);
        assert_eq!(value, None);
    }

    #[test]
    fn test_negative_array_index_not_resolved() {
        let data = test_json!({
            "foo": {
                "bar": [10, 20, 30]
            }
        });
        let value = find_value_by_dotted_path("foo.bar.-1", &data);
        assert_eq!(value, None);
    }

    #[test]
    fn test_numeric_property_on_object() {
        let data = test_json!({
            "foo": {
                "barObj": {
                    "0": "not an array"
                }
            }
        });
        let value = find_value_by_dotted_path("foo.barObj.0", &data);
        assert_eq!(value, Some(Value::String("not an array".to_string())));
    }

    #[test]
    fn test_property_value_zero() {
        let data = test_json!({
            "foo": {
                "zero": 0
            }
        });
        let value = find_value_by_dotted_path("foo.zero", &data);
        assert_eq!(value, Some(Value::Number(serde_json::Number::from(0))));
    }

    #[test]
    fn test_property_value_false() {
        let data = test_json!({
            "foo": {
                "isFalse": false
            }
        });
        let value = find_value_by_dotted_path("foo.isFalse", &data);
        assert_eq!(value, Some(Value::Bool(false)));
    }

    #[test]
    fn test_property_value_empty_string() {
        let data = test_json!({
            "foo": {
                "empty": ""
            }
        });
        let value = find_value_by_dotted_path("foo.empty", &data);
        assert_eq!(value, Some(Value::String("".to_string())));
    }

    #[test]
    fn test_deeply_nested_property() {
        let data = test_json!({
            "a": {
                "b": {
                    "c": {
                        "d": {
                            "e": {
                                "f": 42
                            }
                        }
                    }
                }
            }
        });
        let value = find_value_by_dotted_path("a.b.c.d.e.f", &data);
        assert_eq!(value, Some(Value::Number(serde_json::Number::from(42))));
    }

    #[test]
    fn test_property_with_special_char() {
        let data = test_json!({
            "foo": {
                "$bar": 123
            }
        });
        let value = find_value_by_dotted_path("foo.$bar", &data);
        assert_eq!(value, Some(Value::Number(serde_json::Number::from(123))));
    }

    #[test]
    fn test_property_named_tostring() {
        let data = test_json!({
            "foo": {
                "toString": "stringify"
            }
        });
        let value = find_value_by_dotted_path("foo.toString", &data);
        assert_eq!(value, Some(Value::String("stringify".to_string())));
    }

    #[test]
    fn test_intermediate_property_not_found() {
        let data = test_json!({
            "foo": {
                "bar": "baz"
            }
        });
        let value = find_value_by_dotted_path("foo.undefinedMid.baz", &data);
        assert_eq!(value, None);
    }

    #[test]
    fn test_string_in_deeply_nested_path() {
        let data = test_json!({
            "first": {
                "second": {
                    "third": {
                        "data": "deep_string"
                    }
                }
            }
        });
        let value = find_value_by_dotted_path("first.second.third.data", &data);
        assert_eq!(value, Some(Value::String("deep_string".to_string())));
    }

    #[test]
    fn test_double_value_directly() {
        let data = test_json!({ "double_value": 1.23 });
        let value = find_value_by_dotted_path("double_value", &data);
        assert_eq!(
            value,
            Some(Value::Number(serde_json::Number::from_f64(1.23).unwrap()))
        );
    }

    #[test]
    fn test_ref_lookup_borrows_existing_value() {
        let data = test_json!({
            "user": {
                "name": "Alice"
            }
        });
        let value = find_value_by_dotted_path_ref("user.name", &data).expect("value");
        let expected = data
            .get("user")
            .and_then(|user| user.get("name"))
            .expect("expected value");

        assert!(matches!(value, std::borrow::Cow::Borrowed(_)));
        assert!(std::ptr::eq(value.as_ref(), expected));
    }

    #[test]
    fn test_ref_lookup_owns_synthetic_length() {
        let data = test_json!({ "items": [1, 2, 3] });
        let value = find_value_by_dotted_path_ref("items.length", &data).expect("value");

        assert!(matches!(value, std::borrow::Cow::Owned(_)));
        assert_eq!(value.as_ref(), &Value::Number(serde_json::Number::from(3)));
    }
}