sim-lib-view 0.1.3

View/editor codec contracts, Shape-based lens dispatch, lens stack, and the universal default lens for SIM Web.
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
//! Tests for the universal default view and editor.

use sim_kernel::{CodecId, Expr, NumberLiteral, Symbol};
use sim_lib_intent::{Origin, intent};

use crate::contract::{LensKind, View};
use crate::dispatch::{DispatchContext, DispatchReason, LensRegistry};
use crate::universal::{UNIVERSAL_EDITOR_ID, UNIVERSAL_VIEW_ID, register_universal_default};
use crate::universal_editor::{EDIT_MODES, UniversalEditor, render_draft};
use crate::universal_view::UniversalView;
use crate::{Draft, Editor};

use sim_kernel::testing::eager_cx as cx;

use sim_value::build::sym;
use sim_value::path::{Path, get};

fn number(value: &str) -> Expr {
    Expr::Number(NumberLiteral {
        domain: Symbol::new("i64"),
        canonical: value.to_owned(),
    })
}

fn sample_map() -> Expr {
    Expr::Map(vec![
        (sym("a"), number("1")),
        (sym("b"), number("2")),
        (
            sym("nested"),
            Expr::List(vec![Expr::String("x".to_owned()), Expr::Bool(true)]),
        ),
    ])
}

fn scalar_map() -> Expr {
    Expr::Map(vec![
        (sym("n"), number("1")),
        (sym("b"), Expr::Bool(true)),
        (sym("s"), sym("ready")),
        (sym("t"), Expr::String("raw".to_owned())),
    ])
}

#[test]
fn universal_view_renders_a_valid_four_region_scene() {
    let mut cx = cx();
    for value in [
        Expr::Nil,
        number("42"),
        Expr::String("hello".to_owned()),
        sample_map(),
        Expr::List(vec![Expr::Nil, sym("z")]),
    ] {
        let scene = UniversalView.encode(&mut cx, &value).unwrap();
        sim_lib_scene::validate_scene(&scene)
            .unwrap_or_else(|err| panic!("scene invalid for {value:?}: {err}"));
        // The root stack has exactly four regions.
        let children = region_children(&scene);
        assert_eq!(children, 4, "value {value:?} must open four regions");
    }
}

fn region_children(scene: &Expr) -> usize {
    let Expr::Map(entries) = scene else { return 0 };
    for (key, value) in entries {
        if matches!(key, Expr::Symbol(s) if &*s.name == "children")
            && let Expr::List(items) = value
        {
            return items.len();
        }
    }
    0
}

#[test]
fn any_value_dispatches_to_the_universal_default() {
    let mut cx = cx();
    let mut registry = LensRegistry::new();
    register_universal_default(&mut registry, false);
    let grant = |_: &sim_kernel::CapabilityName| true;
    let ctx = DispatchContext::permissive(&grant);
    let outcome = registry.dispatch_view(&mut cx, &Expr::Nil, &ctx).unwrap();
    assert_eq!(outcome.lens_id, Symbol::new(UNIVERSAL_VIEW_ID));
    assert_eq!(outcome.reason, DispatchReason::UniversalDefault);
}

#[test]
fn editing_a_field_commits_and_preserves_siblings() {
    let mut cx = cx();
    let editor = UniversalEditor::writable();
    let value = sample_map();
    // edit-field path [k a] := 9
    let edit = intent(
        "edit-field",
        Origin::human(1),
        vec![
            ("target", value.clone()),
            (
                "path",
                Expr::List(vec![Expr::Vector(vec![sym("k"), sym("a")])]),
            ),
            ("value", number("9")),
        ],
    );
    let draft = editor.decode(&mut cx, &value, &edit).unwrap();
    assert!(draft.committable, "a valid edit must be committable");
    // The proposed value updated `a` and preserved `b` and `nested`.
    let Expr::Map(entries) = &draft.proposed else {
        panic!("proposed must be a map")
    };
    assert_eq!(entries.len(), 3, "unknown fields preserved");
    let a = entries
        .iter()
        .find(|(k, _)| matches!(k, Expr::Symbol(s) if &*s.name == "a"))
        .map(|(_, v)| v);
    assert_eq!(a, Some(&number("9")));

    let op = editor.commit(&mut cx, &draft).unwrap();
    let Expr::Map(form) = &op.form else {
        panic!("operation form must be a map")
    };
    assert!(
        form.iter()
            .any(|(k, _)| matches!(k, Expr::Symbol(s) if &*s.name == "op"))
    );
}

#[test]
fn an_unknown_path_is_a_field_anchored_diagnostic_not_a_commit() {
    let mut cx = cx();
    let editor = UniversalEditor::writable();
    let value = sample_map();
    let edit = intent(
        "edit-field",
        Origin::human(1),
        vec![
            ("target", value.clone()),
            (
                "path",
                Expr::List(vec![
                    Expr::Vector(vec![sym("k"), sym("missing")]),
                    Expr::Vector(vec![sym("k"), sym("deep")]),
                ]),
            ),
            ("value", number("9")),
        ],
    );
    let draft = editor.decode(&mut cx, &value, &edit).unwrap();
    assert!(!draft.committable, "an unknown nested path must not commit");
    assert!(!draft.diagnostics.is_empty(), "must carry a diagnostic");
    assert!(
        editor.commit(&mut cx, &draft).is_err(),
        "commit must fail closed"
    );
}

#[test]
fn readonly_editor_cannot_commit() {
    let mut cx = cx();
    let editor = UniversalEditor::readonly();
    let value = sample_map();
    let edit = intent(
        "edit-field",
        Origin::human(1),
        vec![
            ("target", value.clone()),
            (
                "path",
                Expr::List(vec![Expr::Vector(vec![sym("k"), sym("a")])]),
            ),
            ("value", number("9")),
        ],
    );
    let draft = editor.decode(&mut cx, &value, &edit).unwrap();
    assert!(!draft.committable, "readonly edits never commit");
    assert!(editor.commit(&mut cx, &draft).is_err());
}

#[test]
fn cancel_reverts_to_the_base() {
    let mut cx = cx();
    let editor = UniversalEditor::writable();
    let value = sample_map();
    let cancel = intent("cancel", Origin::human(1), vec![("pane", sym("p"))]);
    let draft = editor.decode(&mut cx, &value, &cancel).unwrap();
    assert_eq!(draft.proposed, draft.base, "cancel discards pending edits");
}

#[test]
fn every_advertised_edit_mode_renders_a_valid_scene_from_one_draft() {
    let draft = Draft::clean(sample_map(), sample_map());
    assert_eq!(
        EDIT_MODES,
        ["text", "raw"],
        "only the real modes are advertised"
    );
    for mode in EDIT_MODES {
        let scene = render_draft(&draft, mode).unwrap();
        sim_lib_scene::validate_scene(&scene)
            .unwrap_or_else(|err| panic!("mode {mode} scene invalid: {err}"));
    }
}

/// Recursively collect the `path` attribute of every `field` node in a scene.
fn field_paths(value: &Expr, out: &mut Vec<Expr>) {
    match value {
        Expr::Map(entries) => {
            let is_field = entries.iter().any(|(k, v)| {
                matches!(k, Expr::Symbol(s) if &*s.name == "kind")
                    && matches!(v, Expr::Symbol(s) if &*s.name == "field")
            });
            if is_field
                && let Some(path) = entries.iter().find_map(|(k, v)| {
                    matches!(k, Expr::Symbol(s) if &*s.name == "path").then(|| v.clone())
                })
            {
                out.push(path);
            }
            for (_, v) in entries {
                field_paths(v, out);
            }
        }
        Expr::List(items) | Expr::Vector(items) | Expr::Set(items) => {
            for item in items {
                field_paths(item, out);
            }
        }
        _ => {}
    }
}

/// Recursively collect every field node's map entries.
fn field_nodes<'a>(value: &'a Expr, out: &mut Vec<&'a [(Expr, Expr)]>) {
    match value {
        Expr::Map(entries) => {
            let is_field = entries.iter().any(|(k, v)| {
                matches!(k, Expr::Symbol(s) if &*s.name == "kind")
                    && matches!(v, Expr::Symbol(s) if &*s.name == "field")
            });
            if is_field {
                out.push(entries);
            }
            for (_, v) in entries {
                field_nodes(v, out);
            }
        }
        Expr::List(items) | Expr::Vector(items) | Expr::Set(items) => {
            for item in items {
                field_nodes(item, out);
            }
        }
        _ => {}
    }
}

fn attr<'a>(entries: &'a [(Expr, Expr)], name: &str) -> Option<&'a Expr> {
    entries.iter().find_map(|(key, value)| {
        matches!(key, Expr::Symbol(symbol) if &*symbol.name == name).then_some(value)
    })
}

fn symbol_attr<'a>(entries: &'a [(Expr, Expr)], name: &str) -> Option<&'a str> {
    match attr(entries, name) {
        Some(Expr::Symbol(symbol)) => Some(&symbol.name),
        _ => None,
    }
}

fn string_attr<'a>(entries: &'a [(Expr, Expr)], name: &str) -> Option<&'a str> {
    match attr(entries, name) {
        Some(Expr::String(text)) => Some(text),
        _ => None,
    }
}

#[test]
fn canonical_text_fields_scope_to_leaf_paths_and_preserve_siblings() {
    let mut cx = cx();
    let value = sample_map();
    let scene = UniversalView.encode(&mut cx, &value).unwrap();

    let mut paths = Vec::new();
    field_paths(&scene, &mut paths);
    assert!(!paths.is_empty(), "scalar leaves must be editable fields");
    let root = Expr::List(vec![]);
    for path in &paths {
        assert_ne!(
            *path, root,
            "no canonical-text field may bind to the root path (that clobbers the whole value)"
        );
    }

    // Driving an edit-field through one scoped path preserves every sibling key.
    let path = paths[0].clone();
    let edit = intent(
        "edit-field",
        Origin::human(1),
        vec![
            ("target", value.clone()),
            ("path", path),
            ("value", number("99")),
        ],
    );
    let editor = UniversalEditor::writable();
    let draft = editor.decode(&mut cx, &value, &edit).unwrap();
    assert!(draft.committable, "a scoped leaf edit commits");
    let Expr::Map(entries) = &draft.proposed else {
        panic!("proposed must stay a map")
    };
    assert_eq!(
        entries.len(),
        3,
        "the scoped edit preserved every sibling key"
    );
}

#[test]
fn canonical_text_fields_carry_scalar_value_metadata() {
    let mut cx = cx();
    let value = scalar_map();
    let scene = UniversalView.encode(&mut cx, &value).unwrap();

    let mut fields = Vec::new();
    field_nodes(&scene, &mut fields);
    assert_eq!(fields.len(), 4, "each scalar leaf is rendered as a field");

    let mut kinds = fields
        .iter()
        .map(|entries| symbol_attr(entries, "value-kind").unwrap_or(""))
        .collect::<Vec<_>>();
    kinds.sort_unstable();
    assert_eq!(kinds, ["bool", "number", "string", "symbol"]);

    for entries in fields {
        let displayed = string_attr(entries, "value").expect("field carries display value");
        let encoded = string_attr(entries, "value-codec").expect("field carries encoded value");
        let decoded = sim_codec::decode_portable(CodecId(0), encoded).unwrap();
        assert_eq!(
            displayed,
            crate::universal_view::render_value(&decoded),
            "field metadata decodes to the displayed scalar"
        );
    }
}

#[test]
fn scalar_text_edits_rehydrate_against_the_current_leaf_shape() {
    let mut cx = cx();
    let value = scalar_map();
    let editor = UniversalEditor::writable();
    let cases = [
        ("n", "9", number("9")),
        ("b", "false", Expr::Bool(false)),
        ("s", "done", sym("done")),
        ("t", "changed", Expr::String("changed".to_owned())),
    ];

    for (key, text, expected) in cases {
        let path = Path::new().key(sym(key));
        let edit = intent(
            "edit-field",
            Origin::human(1),
            vec![
                ("target", value.clone()),
                ("path", path.to_expr()),
                ("value", Expr::String(text.to_owned())),
            ],
        );
        let draft = editor.decode(&mut cx, &value, &edit).unwrap();
        assert!(draft.committable, "{key} edit must be committable");
        assert_eq!(
            get(&draft.proposed, &path),
            Some(&expected),
            "{key} edit preserves the leaf type"
        );
    }
}

#[test]
fn invalid_scalar_text_edits_are_rejected() {
    let mut cx = cx();
    let editor = UniversalEditor::writable();
    let value = scalar_map();
    let path = Path::new().key(sym("n"));
    let edit = intent(
        "edit-field",
        Origin::human(1),
        vec![
            ("target", value.clone()),
            ("path", path.to_expr()),
            ("value", Expr::String("not-a-number".to_owned())),
        ],
    );
    let draft = editor.decode(&mut cx, &value, &edit).unwrap();
    assert!(!draft.committable, "invalid number text must not commit");
    assert_eq!(draft.proposed, value, "rejected edits preserve the base");
    assert!(
        draft
            .diagnostics
            .iter()
            .any(|diagnostic| diagnostic.message.contains("cannot parse")),
        "the rejection explains the scalar parse failure"
    );
}

#[test]
fn universal_default_lens_ids_are_distinct_kinds() {
    let mut registry = LensRegistry::new();
    register_universal_default(&mut registry, false);
    let view = registry.get(&Symbol::new(UNIVERSAL_VIEW_ID)).unwrap();
    let editor = registry.get(&Symbol::new(UNIVERSAL_EDITOR_ID)).unwrap();
    assert_eq!(view.meta.kind, LensKind::View);
    assert_eq!(editor.meta.kind, LensKind::Editor);
}