concinnity-dev 0.19.119

The Concinnity dev tooling library: world authoring, the in-engine editor, the debug server, docs and packaging
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
//! The add / edit form's lifecycle (`hook/editing.rs`): the type picker and its
//! search, opening the form from a row or the "+", the name rules a confirm
//! applies, and every field kind the form writes back -- scalars, colors,
//! nested objects, enums, asset references and their dropdowns, arrays, and a
//! disclosed vector. Also what survives a reinjection, a panel toggle, and a
//! delete that shifts the open form's index.

use concinnity_core::components::FrameInput;
use concinnity_core::components::Sprite;
use concinnity_core::components::TextInput;
use concinnity_core::ecs::World;

use super::fixtures::{
    click_row, entry, entry_with_args, hook, row_of, seed_tree, set_field, world_with_fields,
};
use crate::editor::hook::{EditorHook, FormTarget, declared_id, visible_slot};
use crate::frame_hook::FrameHook;

use crate::editor::inject;

use crate::editor::panels::form;
use crate::editor::panels::form_panel::{self, FormAction};

use crate::editor::panels::assets_panel::{self, PanelAction};
use crate::editor::panels::registry::PanelKey;

use crate::editor::hook::tests::fixtures::{active, entry_target, select, selected};
use crate::editor::widget;

// A live rebuild re-injects a fresh (blank) HUD; the field snapshot carries the
// editor's typed text (an open form's name, the combo filter) across it so a
// form open during the swap is not blanked.
#[test]
fn field_snapshot_carries_typed_text_across_a_reinjection() {
    let mut old = World::new();
    inject::editor_hud(&mut old);
    widget::seed_field(&mut old, form_panel::NAME_INPUT, "my_light");
    widget::seed_field(&mut old, assets_panel::SEARCH_INPUT, "Point");
    let snapshot = EditorHook::field_snapshot(&old);

    // A fresh HUD injection starts every field blank.
    let mut new = World::new();
    inject::editor_hud(&mut new);
    assert_eq!(widget::field_text(&new, form_panel::NAME_INPUT), "");

    EditorHook::restore_fields(&mut new, &snapshot);
    assert_eq!(widget::field_text(&new, form_panel::NAME_INPUT), "my_light");
    assert_eq!(
        widget::field_text(&new, assets_panel::SEARCH_INPUT),
        "Point"
    );
}

// While the "+" picker is open the field narrows its type options instead of
// the tree, so the two never fight over the same text.
#[test]
fn the_search_field_narrows_the_picker_while_it_is_open() {
    let mut h = hook(Vec::new());
    let mut world = world_with_fields();
    h.open[PanelKey::Assets] = true;
    h.apply_panel(PanelAction::TogglePicker, &mut world);
    set_field(&mut world, assets_panel::SEARCH_INPUT, "pointlight");
    let opts = h.picker_options(&world).unwrap();
    let names: Vec<&str> = opts.iter().map(|o| o.name.as_str()).collect();
    assert_eq!(names, ["PointLight"], "case-insensitive type narrowing");
    assert!(
        h.tree_rows(&world).is_empty(),
        "the tree is not filtered by the picker's text"
    );
}

#[test]
fn plus_picker_then_name_form_adds_the_entry() {
    let mut h = hook(Vec::new());
    let mut world = world_with_fields();
    h.open[PanelKey::Assets] = true;
    // "+" opens the picker, which types into the search field (the draw
    // asserts that focus onto the control each frame).
    h.apply_panel(PanelAction::TogglePicker, &mut world);
    assert!(h.assets.picker_open && h.assets.search_focus);
    // Pick the first offered type -> AddForm, name field prefilled + focused.
    let ty = h.picker_options(&world).unwrap()[0].name.clone();
    h.apply_panel(PanelAction::PickOption(0), &mut world);
    assert!(h.form_open());
    assert!(!h.assets.picker_open);
    assert_eq!(h.form.selected_type.as_deref(), Some(ty.as_str()));
    assert!((h.form.target == FormTarget::New));
    let name_field = world
        .get_by_id::<TextInput>(form_panel::NAME_INPUT)
        .unwrap();
    assert!(name_field.focused && !name_field.content.is_empty());
    // Edit the name, then confirm.
    set_field(&mut world, form_panel::NAME_INPUT, "my_light");
    h.apply_form(FormAction::Confirm, &mut world);
    assert!(!h.form_open());
    assert!(h.dirty);
    assert_eq!(h.entries.len(), 1);
    assert_eq!(h.entries[0]["args"]["$id"], "my_light");
    assert_eq!(h.entries[0]["type"], ty.as_str());
}

#[test]
fn row_click_opens_the_edit_form_for_a_rename() {
    let mut h = hook(vec![entry("lamp", "PointLight")]);
    let mut world = world_with_fields();
    h.open[PanelKey::Assets] = true;
    seed_tree(&mut h, Vec::new());
    // Clicking the name row opens the edit form prefilled for a rename.
    click_row(&mut h, "lamp", &mut world);
    assert!(h.form_open());
    assert_eq!(h.form.target, entry_target(&h, 0));
    assert_eq!(h.form.selected_type.as_deref(), Some("PointLight"));
    assert!(h.assets.row_menu.is_none());
    let name_field = world
        .get_by_id::<TextInput>(form_panel::NAME_INPUT)
        .unwrap();
    assert_eq!(name_field.content, "lamp", "name prefilled from the entry");
    // Rename and confirm: same entry, no new one.
    set_field(&mut world, form_panel::NAME_INPUT, "streetlamp");
    h.apply_form(FormAction::Confirm, &mut world);
    assert_eq!(h.entries.len(), 1, "edited in place, not appended");
    assert_eq!(h.entries[0]["args"]["$id"], "streetlamp");
    assert_eq!(h.entries[0]["type"], "PointLight");
    assert!(h.dirty);
}

// The selection holds each member's session key, not its name, so renaming an
// asset through the form leaves it selected (it used to drop out of the set).
#[test]
fn renaming_an_asset_through_the_form_keeps_it_selected() {
    let mut h = hook(vec![entry("floor", "Decal"), entry("lamp", "PointLight")]);
    let mut world = world_with_fields();
    h.open[PanelKey::Assets] = true;
    seed_tree(&mut h, Vec::new());
    click_row(&mut h, "lamp", &mut world);
    assert_eq!(active(&h).as_deref(), Some("lamp"));

    set_field(&mut world, form_panel::NAME_INPUT, "streetlamp");
    h.apply_form(FormAction::Confirm, &mut world);
    assert_eq!(h.entries[1]["args"]["$id"], "streetlamp");
    assert_eq!(
        active(&h).as_deref(),
        Some("streetlamp"),
        "the member follows its entry through the rename"
    );
    assert_eq!(selected(&h).len(), 1, "and it is still the only member");
}

// The other way a name-keyed set went wrong: a member sitting after a deleted
// line. Keys do not shift, so the surviving member stays selected and no
// selection lands on the entry that took its place.
#[test]
fn deleting_an_earlier_entry_leaves_the_selection_on_its_own_member() {
    let mut h = hook(vec![entry("a", "Decal"), entry("b", "Decal")]);
    let mut world = world_with_fields();
    h.open[PanelKey::Assets] = true;
    seed_tree(&mut h, Vec::new());
    select(&mut h, &["b"]);

    let (g, i) = row_of(&h, "a");
    h.apply_panel(PanelAction::OpenRowMenu(g, i), &mut world);
    h.apply_panel(PanelAction::RowDelete, &mut world);
    assert_eq!(selected(&h), vec!["b"]);
    assert_eq!(h.handle_index(h.selection.active().unwrap()), Some(0));
}

#[test]
fn row_menu_delete_removes_the_entry() {
    let mut h = hook(vec![entry("a", "Decal"), entry("b", "Decal")]);
    let mut world = world_with_fields();
    h.open[PanelKey::Assets] = true;
    seed_tree(&mut h, Vec::new());
    let (g, i) = row_of(&h, "a");
    h.apply_panel(PanelAction::OpenRowMenu(g, i), &mut world);
    h.apply_panel(PanelAction::RowDelete, &mut world);
    assert_eq!(h.entries.len(), 1);
    assert_eq!(h.entries[0]["args"]["$id"], "b");
    assert!(h.dirty && h.assets.row_menu.is_none());
}

#[test]
fn edit_rename_to_a_duplicate_is_suffixed() {
    let mut h = hook(vec![entry("a", "Decal"), entry("b", "Decal")]);
    let mut world = world_with_fields();
    let target = entry_target(&h, 1);
    h.form.target = target;
    h.form.selected_type = Some("Decal".to_string());
    // Rename "b" to "a": collides with the other entry -> suffixed.
    set_field(&mut world, form_panel::NAME_INPUT, "a");
    h.apply_form(FormAction::Confirm, &mut world);
    assert_eq!(h.entries[1]["args"]["$id"], "a_1");
}

fn notices(h: &EditorHook) -> Vec<String> {
    h.notifier
        .stack()
        .cards
        .into_iter()
        .map(|c| c.message)
        .collect()
}

// A form rename moves what a build-only shorthand names: a Panel's screen
// follows the Screen, and its title, which only reads the name, stays.
#[test]
fn edit_rename_moves_a_build_only_reference() {
    let mut h = hook(vec![
        entry("pause", "Screen"),
        entry_with_args(
            "card",
            "Panel",
            serde_json::json!({"screen": "pause", "title": "pause"}),
        ),
    ]);
    let mut world = world_with_fields();
    h.form.target = entry_target(&h, 0);
    h.form.selected_type = Some("Screen".to_string());
    set_field(&mut world, form_panel::NAME_INPUT, "paused");
    h.apply_form(FormAction::Confirm, &mut world);
    assert_eq!(h.entries[0]["args"]["$id"], "paused");
    assert_eq!(h.entries[1]["args"]["screen"], "paused");
    assert_eq!(h.entries[1]["args"]["title"], "pause");
}

// Blanking the `$id` of an entry another names keeps the id and says why,
// since nothing can name an anonymous entry; an unreferenced one goes
// anonymous.
#[test]
fn blanking_a_referenced_id_keeps_it() {
    let mut h = hook(vec![
        entry("pause", "Screen"),
        entry_with_args("card", "Panel", serde_json::json!({"screen": "pause"})),
        entry("lone", "Screen"),
    ]);
    let mut world = world_with_fields();
    for at in [0, 2] {
        h.form.target = entry_target(&h, at);
        h.form.selected_type = Some("Screen".to_string());
        set_field(&mut world, form_panel::NAME_INPUT, "");
        h.apply_form(FormAction::Confirm, &mut world);
    }
    assert_eq!(h.entries[0]["args"]["$id"], "pause");
    assert_eq!(h.entries[1]["args"]["screen"], "pause");
    assert!(
        notices(&h)
            .iter()
            .any(|n| n == "'pause' keeps its `$id`: 1 reference names it")
    );
    assert_eq!(declared_id(&h.entries[2]), None);
}

#[test]
fn confirm_add_with_a_blank_id_adds_it_anonymous() {
    let mut h = hook(Vec::new());
    let mut world = world_with_fields();
    h.form.selected_type = Some("PointLight".to_string());
    // Field left blank.
    h.apply_form(FormAction::Confirm, &mut world);
    assert_eq!(h.entries.len(), 1);
    assert_eq!(declared_id(&h.entries[0]), None);
}

#[test]
fn confirm_add_makes_a_duplicate_name_unique() {
    let mut h = hook(vec![entry("lamp", "PointLight")]);
    let mut world = world_with_fields();
    h.form.selected_type = Some("PointLight".to_string());
    set_field(&mut world, form_panel::NAME_INPUT, "lamp");
    h.apply_form(FormAction::Confirm, &mut world);
    assert_eq!(
        h.entries[1]["args"]["$id"], "lamp_1",
        "collision is suffixed"
    );
}

// Picking a config singleton from the "+" picker edits the world's existing
// instance if it has one (no second append), and adds one if it does not.
#[test]
fn config_singleton_picker_edits_existing_else_adds() {
    // A world that already has a GraphicsConfig: picking it opens an EDIT.
    let mut h = hook(vec![serde_json::json!({
        "type": "GraphicsConfig", "args": {"$id": "gfx"}
    })]);
    let mut world = world_with_fields();
    h.open[PanelKey::Assets] = true;
    h.apply_panel(PanelAction::TogglePicker, &mut world);
    let gi = h
        .picker_options(&world)
        .unwrap()
        .iter()
        .position(|o| o.name == "GraphicsConfig")
        .expect("GraphicsConfig is offered in the picker");
    h.apply_panel(PanelAction::PickOption(gi), &mut world);
    assert!(h.form_open());
    assert_eq!(
        h.form.target,
        entry_target(&h, 0),
        "picking a present singleton edits it, not a new add"
    );
    h.apply_form(FormAction::Confirm, &mut world);
    assert_eq!(
        h.entries
            .iter()
            .filter(|e| e["type"] == "GraphicsConfig")
            .count(),
        1,
        "the singleton was edited in place, never duplicated"
    );

    // A world WITHOUT the singleton: picking it opens a fresh add.
    let mut h2 = hook(Vec::new());
    let mut world2 = world_with_fields();
    h2.open[PanelKey::Assets] = true;
    h2.apply_panel(PanelAction::TogglePicker, &mut world2);
    let wi = h2
        .picker_options(&world2)
        .unwrap()
        .iter()
        .position(|o| o.name == "Window")
        .expect("Window is offered in the picker");
    h2.apply_panel(PanelAction::PickOption(wi), &mut world2);
    assert!(h2.form_open());
    assert!(
        (h2.form.target == FormTarget::New),
        "no existing Window -> an add form"
    );
    h2.apply_form(FormAction::Confirm, &mut world2);
    assert_eq!(
        h2.entries.iter().filter(|e| e["type"] == "Window").count(),
        1,
        "the missing singleton was added"
    );
}

#[test]
fn cancel_form_returns_to_the_list_without_adding() {
    let mut h = hook(Vec::new());
    let mut world = world_with_fields();
    h.form.selected_type = Some("Decal".to_string());
    h.apply_form(FormAction::Close, &mut world);
    assert!(!h.form_open());
    assert!(h.form.selected_type.is_none() && (h.form.target == FormTarget::New));
    assert!(h.entries.is_empty() && !h.dirty);
}

#[test]
fn picker_lists_types_alphabetically() {
    let mut h = hook(Vec::new());
    let world = world_with_fields();
    h.assets.picker_open = true;
    let opts = h.picker_options(&world).unwrap();
    let names: Vec<&str> = opts.iter().map(|o| o.name.as_str()).collect();
    let mut sorted = names.clone();
    sorted.sort();
    assert_eq!(names, sorted, "the picker is alphabetized ascending");
    assert_eq!(
        opts.len(),
        assets_panel::picker_types().count(),
        "every offered type shown (addables + config singletons)"
    );
    // Concretely: AudioCue sorts before Sprite, and a config singleton is mixed
    // in alphabetically (AppConfig sorts before AudioCue).
    let pos = |t: &str| opts.iter().position(|o| o.name == t).unwrap();
    assert!(pos("AudioCue") < pos("Sprite"));
    assert!(pos("AppConfig") < pos("AudioCue"));
}

#[test]
fn close_overlays_dismisses_the_picker_and_row_menu() {
    let mut h = hook(vec![entry("a", "Decal")]);
    let mut world = world_with_fields();
    h.assets.picker_open = true;
    h.assets.row_menu = Some(h.handle_for("a"));
    h.apply_panel(PanelAction::CloseOverlays, &mut world);
    assert!(!h.assets.picker_open);
    assert!(h.assets.row_menu.is_none());
}

// Clicking an asset's name row in the browse list (not just its row menu)
// opens the edit-form panel for that entry, and the row stays selected.
#[test]
fn clicking_a_list_row_opens_its_edit_form() {
    let mut h = hook(vec![entry("lamp", "PointLight")]);
    h.open[PanelKey::Assets] = true;
    seed_tree(&mut h, Vec::new());
    let vp = [1280.0, 720.0];
    let po = h.origin(PanelKey::Assets, vp);
    // Row 0 is the World group header; row 1 is the asset. Aim at its name,
    // clear of the hide toggle now heading the row.
    let row = assets_panel::row_rect(po, assets_panel::PANEL_W, 1);
    let mut world = World::new();
    inject::editor_hud(&mut world);
    world.add_component(FrameInput {
        viewport: vp,
        mouse_x: row[0] + 60.0,
        mouse_y: row[1] + 10.0,
        left_click: true,
        left_button_down: true,
        ..Default::default()
    });
    h.tick(&mut world);
    assert!(h.form_open(), "the row click opened the form");
    assert_eq!(h.form.target, entry_target(&h, 0));
    assert_eq!(h.form.selected_type.as_deref(), Some("PointLight"));
    assert_eq!(
        widget::field_text(&world, form_panel::NAME_INPUT),
        "lamp",
        "the name heading is seeded from the entry"
    );
}

// The open form holds its entry's session key, so an unrelated delete leaves it
// on the same entry however far that entry moves; deleting the edited entry
// itself is what closes the form.
#[test]
fn deleting_an_unrelated_entry_leaves_the_open_form_on_its_own() {
    let mut h = hook(vec![entry("a", "Decal"), entry("b", "Decal")]);
    let mut world = world_with_fields();
    h.open[PanelKey::Assets] = true;
    // Edit "b" (index 1), then delete "a" (index 0): "b" slides to 0 and the
    // form is still on it.
    seed_tree(&mut h, Vec::new());
    let target = entry_target(&h, 1);
    h.open_form(&mut world, "Decal".to_string(), target);
    let (g, i) = row_of(&h, "a");
    h.apply_panel(PanelAction::OpenRowMenu(g, i), &mut world);
    h.apply_panel(PanelAction::RowDelete, &mut world);
    assert!(h.form_open(), "the form survives an unrelated delete");
    assert_eq!(
        h.form.target,
        entry_target(&h, 0),
        "the same entry, now at 0"
    );
    // Confirm still updates that entry and no other.
    set_field(&mut world, form_panel::NAME_INPUT, "b2");
    h.apply_form(FormAction::Confirm, &mut world);
    assert_eq!(h.entries.len(), 1);
    assert_eq!(h.entries[0]["args"]["$id"], "b2");

    // Deleting the edited entry itself closes the form.
    let mut h2 = hook(vec![entry("a", "Decal")]);
    let mut world2 = world_with_fields();
    h2.open[PanelKey::Assets] = true;
    seed_tree(&mut h2, Vec::new());
    let target = entry_target(&h2, 0);
    h2.open_form(&mut world2, "Decal".to_string(), target);
    let (g2, i2) = row_of(&h2, "a");
    h2.apply_panel(PanelAction::OpenRowMenu(g2, i2), &mut world2);
    h2.apply_panel(PanelAction::RowDelete, &mut world2);
    assert!(!h2.form_open(), "deleting the edited entry closes its form");
}

#[test]
fn add_form_writes_edited_arg_values() {
    let mut h = hook(Vec::new());
    let mut world = world_with_fields();
    h.open[PanelKey::Assets] = true;
    h.apply_panel(PanelAction::TogglePicker, &mut world);
    // Pick a type with a float arg through the real picker->pick path.
    let ty = "PointLight".to_string();
    let idx = h
        .picker_options(&world)
        .unwrap()
        .iter()
        .position(|o| o.name == ty)
        .expect("PointLight is offered");
    h.apply_panel(PanelAction::PickOption(idx), &mut world);
    assert!(h.form_open());
    assert!(!h.form.fields.is_empty(), "the type exposes arg fields");
    // Edit a float field via its input.
    let (j, key) = h
        .form
        .fields
        .iter()
        .enumerate()
        .find(|(_, f)| matches!(f.kind, form::FieldKind::Float))
        .map(|(j, f)| (j, f.key.clone()))
        .expect("a float arg field");
    set_field(&mut world, form_panel::form_input(j), "3.5");
    set_field(&mut world, form_panel::NAME_INPUT, "lamp");
    h.apply_form(FormAction::Confirm, &mut world);
    assert!(!h.form_open());
    assert_eq!(h.entries.len(), 1);
    assert_eq!(h.entries[0]["args"]["$id"], "lamp");
    assert_eq!(h.entries[0]["type"], ty.as_str());
    assert_eq!(
        h.entries[0]["args"][&key].as_f64(),
        Some(3.5),
        "the edited float persisted into args"
    );
}

#[test]
fn add_form_writes_an_edited_color_vector() {
    let mut h = hook(Vec::new());
    let mut world = world_with_fields();
    // VolumetricFog (a newly offered type) has a `color` RGB vector field.
    h.open_form(&mut world, "VolumetricFog".to_string(), FormTarget::New);
    let (j, key) = h
        .form
        .fields
        .iter()
        .enumerate()
        .find(|(_, f)| matches!(f.kind, form::FieldKind::Vec { color: true, .. }))
        .map(|(j, f)| (j, f.key.clone()))
        .expect("a color vector field");
    set_field(&mut world, form_panel::form_input(j), "0.1, 0.2, 0.3");
    set_field(&mut world, form_panel::NAME_INPUT, "fog");
    h.apply_form(FormAction::Confirm, &mut world);
    assert!(!h.form_open());
    assert_eq!(h.entries.len(), 1);
    assert_eq!(h.entries[0]["type"], "VolumetricFog");
    assert_eq!(
        h.entries[0]["args"][&key],
        serde_json::json!([0.1, 0.2, 0.3]),
        "the edited color persisted as a numeric array"
    );
}

// Editing a nested (dotted-path) field through the form persists into the
// sub-object: Camera3D's `controller.move_speed`.
#[test]
fn add_form_writes_a_nested_object_field() {
    let mut h = hook(Vec::new());
    let mut world = world_with_fields();
    h.open_form(&mut world, "Camera3D".to_string(), FormTarget::New);
    let j = h
        .form
        .fields
        .iter()
        .position(|f| f.key == "controller.move_speed")
        .expect("the nested controller.move_speed field is offered");
    assert!(matches!(h.form.fields[j].kind, form::FieldKind::Float));
    set_field(&mut world, form_panel::form_input(j), "12.5");
    set_field(&mut world, form_panel::NAME_INPUT, "cam");
    h.apply_form(FormAction::Confirm, &mut world);
    let cam = h
        .entries
        .iter()
        .find(|e| e["args"]["$id"] == "cam")
        .expect("the camera was added");
    assert_eq!(cam["type"], "Camera3D");
    assert_eq!(
        cam["args"]["controller"]["move_speed"].as_f64(),
        Some(12.5),
        "the nested edit persisted into args.controller.move_speed"
    );
}

// A KeyBinding is a key typed in and an action picked from what the world's
// Screens let one do.
#[test]
fn add_form_writes_a_key_and_a_picked_action_for_a_new_type() {
    let mut h = hook(vec![entry("pause", "Screen")]);
    let mut world = world_with_fields();
    h.open_form(&mut world, "KeyBinding".to_string(), FormTarget::New);
    let field_pos = |k: &str| {
        h.form
            .fields
            .iter()
            .position(|f| f.key == k)
            .unwrap_or_else(|| panic!("{k} field present"))
    };
    let (key_j, action_j) = (field_pos("key"), field_pos("action"));
    assert!(matches!(h.form.fields[key_j].kind, form::FieldKind::Str));
    let action = &mut h.form.fields[action_j];
    assert_eq!(action.variants[action.variant_idx], "(none)");
    action.variant_idx = action
        .variants
        .iter()
        .position(|v| v == "toggle pause")
        .expect("the Screen is offered");
    set_field(&mut world, form_panel::form_input(key_j), "Escape");
    set_field(&mut world, form_panel::NAME_INPUT, "pause_key");
    h.apply_form(FormAction::Confirm, &mut world);
    assert!(!h.form_open());
    assert_eq!(h.entries.len(), 2);
    assert_eq!(h.entries[1]["type"], "KeyBinding");
    assert_eq!(h.entries[1]["args"]["key"], "Escape");
    assert_eq!(
        h.entries[1]["args"]["action"],
        serde_json::json!({"toggle": "pause"})
    );
}

#[test]
fn add_form_cycles_and_persists_an_enum_field() {
    let mut h = hook(Vec::new());
    let mut world = world_with_fields();
    // Sprite's `fit` is a string enum -> a cycling picker.
    h.open_form(&mut world, "Sprite".to_string(), FormTarget::New);
    let idx = h
        .form
        .fields
        .iter()
        .position(|f| f.key == "fit")
        .expect("fit enum field");
    assert!(matches!(h.form.fields[idx].kind, form::FieldKind::Enum));
    let n = h.form.fields[idx].variants.len();
    let start = h.form.fields[idx].variant_idx;
    // Cycle once, then confirm.
    h.apply_form(FormAction::CycleField(idx), &mut world);
    let picked = h.form.fields[idx].variants[(start + 1) % n].clone();
    assert_ne!(
        picked, h.form.fields[idx].variants[start],
        "cycled to a new value"
    );
    set_field(&mut world, form_panel::NAME_INPUT, "spr");
    h.apply_form(FormAction::Confirm, &mut world);
    assert_eq!(h.entries.len(), 1);
    assert_eq!(h.entries[0]["type"], "Sprite");
    assert_eq!(
        h.entries[0]["args"]["fit"], picked,
        "the cycled enum variant persisted into args"
    );
}

// A field naming two target types offers the assets of both, and nothing else.
#[test]
fn add_form_ref_field_offers_every_target_type() {
    let mut h = hook(vec![
        entry("door", "Prop"),
        entry("pivot", "SkyRotation"),
        entry("grass_tex", "Texture"),
    ]);
    let mut world = world_with_fields();
    h.open[PanelKey::Assets] = true;
    h.open_form(&mut world, "Prop".to_string(), FormTarget::New);
    let parent = h
        .form
        .fields
        .iter()
        .find(|f| f.key == "parent")
        .expect("parent ref field");
    assert_eq!(parent.variants, vec![form::NONE_LABEL, "door", "pivot"]);
}

#[test]
fn add_form_ref_field_offers_and_persists_an_existing_asset() {
    let mut h = hook(vec![
        entry("grass_tex", "Texture"),
        entry("stone_tex", "Texture"),
    ]);
    let mut world = world_with_fields();
    h.open[PanelKey::Assets] = true;
    // Add a Decal: its `texture` reference offers the two existing Textures.
    h.open_form(&mut world, "Decal".to_string(), FormTarget::New);
    let idx = h
        .form
        .fields
        .iter()
        .position(|f| f.key == "texture")
        .expect("texture ref field");
    assert!(
        matches!(h.form.fields[idx].kind, form::FieldKind::Ref { targets } if targets == ["Texture"])
    );
    assert_eq!(
        h.form.fields[idx].variants,
        vec![form::NONE_LABEL, "grass_tex", "stone_tex"],
        "options are (none) + the world's Textures"
    );
    assert_eq!(h.form.fields[idx].variant_idx, 0, "starts at (none)");
    // Cycle to the first Texture and confirm.
    h.apply_form(FormAction::CycleField(idx), &mut world);
    assert_eq!(
        h.form.fields[idx].variants[h.form.fields[idx].variant_idx],
        "grass_tex"
    );
    set_field(&mut world, form_panel::NAME_INPUT, "splat");
    h.apply_form(FormAction::Confirm, &mut world);
    let decal = h
        .entries
        .iter()
        .find(|e| e["args"]["$id"] == "splat")
        .expect("the decal was added");
    assert_eq!(decal["type"], "Decal");
    assert_eq!(
        decal["args"]["texture"], "grass_tex",
        "the reference persisted as the asset's name"
    );
}

// A ref field with many candidate assets opens a value dropdown (not a cycle):
// the dropdown picks an option, which persists as that asset's name.
#[test]
fn add_form_ref_field_dropdown_picks_and_persists() {
    // More Textures than the cycle cap, so the picker is a dropdown.
    let mut entries = Vec::new();
    for i in 0..(form_panel::CYCLE_MAX + 3) {
        entries.push(entry(&format!("tex_{i}"), "Texture"));
    }
    let mut h = hook(entries);
    let mut world = world_with_fields();
    h.open[PanelKey::Assets] = true;
    h.open_form(&mut world, "Decal".to_string(), FormTarget::New);
    let idx = h
        .form
        .fields
        .iter()
        .position(|f| f.key == "texture")
        .expect("texture ref field");
    // (none) + the textures exceeds CYCLE_MAX, so a click opens a dropdown.
    assert!(h.form.fields[idx].variants.len() > form_panel::CYCLE_MAX);
    h.apply_form(FormAction::OpenFieldDropdown(idx), &mut world);
    assert_eq!(h.form.field_dropdown, Some(idx), "the dropdown opened");
    // Pick option 3 (a real texture, past (none) at 0).
    let picked = h.form.fields[idx].variants[3].clone();
    h.apply_form(FormAction::PickFieldOption(3), &mut world);
    assert!(
        h.form.field_dropdown.is_none(),
        "picking closes the dropdown"
    );
    assert_eq!(h.form.fields[idx].variant_idx, 3, "the option was selected");
    set_field(&mut world, form_panel::NAME_INPUT, "splat");
    h.apply_form(FormAction::Confirm, &mut world);
    let decal = h
        .entries
        .iter()
        .find(|e| e["args"]["$id"] == "splat")
        .unwrap();
    assert_eq!(
        decal["args"]["texture"], picked,
        "the dropdown-picked reference persisted as the asset's name"
    );
}

// A second click on an open dropdown's field toggles it closed; CloseOverlays
// also dismisses it.
#[test]
fn field_dropdown_toggles_and_close_overlays_dismisses_it() {
    let mut h = hook(Vec::new());
    let mut world = world_with_fields();
    h.form.selected_type = Some("Decal".to_string());
    h.apply_form(FormAction::OpenFieldDropdown(0), &mut world);
    assert_eq!(h.form.field_dropdown, Some(0));
    // Same field again -> closed.
    h.apply_form(FormAction::OpenFieldDropdown(0), &mut world);
    assert!(h.form.field_dropdown.is_none(), "a second click closes it");
    // Reopen, then the form's CloseOverlays dismisses it.
    h.apply_form(FormAction::OpenFieldDropdown(0), &mut world);
    h.apply_form(FormAction::CloseOverlays, &mut world);
    assert!(
        h.form.field_dropdown.is_none(),
        "CloseOverlays dismisses it"
    );
}

// Wheeling scrolls an open value dropdown (which can extend past the fixed
// panel body), independent of the cursor-over-body gate.
#[test]
fn scrolling_advances_an_open_field_dropdown() {
    let mut entries = Vec::new();
    for i in 0..(form_panel::MAX_DROP_ROWS + 4) {
        entries.push(entry(&format!("tex_{i}"), "Texture"));
    }
    let mut h = hook(entries);
    let mut world = world_with_fields();
    h.open[PanelKey::Assets] = true;
    h.open_form(&mut world, "Decal".to_string(), FormTarget::New);
    let idx = h
        .form
        .fields
        .iter()
        .position(|f| f.key == "texture")
        .expect("texture ref field");
    h.apply_form(FormAction::OpenFieldDropdown(idx), &mut world);
    assert_eq!(h.form.field_dropdown_scroll, 0);
    h.scroll_form(1.0, &mut world);
    assert_eq!(
        h.form.field_dropdown_scroll, 1,
        "wheel down advances the dropdown"
    );
    h.scroll_form(-1.0, &mut world);
    assert_eq!(h.form.field_dropdown_scroll, 0, "wheel up rewinds it");
    // It cannot scroll past the last page.
    for _ in 0..50 {
        h.scroll_form(1.0, &mut world);
    }
    let total = h.form.fields[idx].variants.len();
    assert_eq!(
        h.form.field_dropdown_scroll,
        total - form_panel::MAX_DROP_ROWS,
        "scroll clamps to the last full page"
    );
}

// Growing an array through the form's [+] and editing the new element persists:
// WaterSurface starts with one wave; add a second and set its amplitude.
#[test]
fn add_form_grows_an_array_and_edits_the_new_element() {
    let mut h = hook(Vec::new());
    let mut world = world_with_fields();
    h.open_form(&mut world, "WaterSurface".to_string(), FormTarget::New);
    let header = |h: &EditorHook| {
        h.form
            .fields
            .iter()
            .position(|f| f.key == "waves")
            .expect("waves array header")
    };
    let hj = header(&h);
    assert!(matches!(h.form.fields[hj].kind, form::FieldKind::Array));
    assert_eq!(h.form.fields[hj].variant_idx, 1, "one default wave");
    // [+] grows the array to two waves (fields re-derive).
    h.apply_form(FormAction::AddArrayElement(hj), &mut world);
    assert_eq!(
        h.form.fields[header(&h)].variant_idx,
        2,
        "grew to two waves"
    );
    // Edit the second wave's amplitude, then confirm.
    let ej = h
        .form
        .fields
        .iter()
        .position(|f| f.key == "waves.1.amplitude")
        .expect("the second wave's amplitude field");
    set_field(&mut world, form_panel::form_input(ej), "4.5");
    set_field(&mut world, form_panel::NAME_INPUT, "sea");
    h.apply_form(FormAction::Confirm, &mut world);
    let ws = h
        .entries
        .iter()
        .find(|e| e["args"]["$id"] == "sea")
        .expect("the water surface was added");
    assert_eq!(ws["type"], "WaterSurface");
    assert_eq!(
        ws["args"]["waves"].as_array().map(Vec::len),
        Some(2),
        "the grown array persisted with two waves"
    );
    assert_eq!(
        ws["args"]["waves"][1]["amplitude"].as_f64(),
        Some(4.5),
        "the edited new-element value persisted"
    );
}

// Removing an array element through the form's [-] shrinks it and persists.
#[test]
fn add_form_removes_an_array_element() {
    let mut h = hook(Vec::new());
    let mut world = world_with_fields();
    h.open_form(&mut world, "WaterSurface".to_string(), FormTarget::New);
    let hj = h.form.fields.iter().position(|f| f.key == "waves").unwrap();
    // Grow to two, then remove one back to one.
    h.apply_form(FormAction::AddArrayElement(hj), &mut world);
    let hj = h.form.fields.iter().position(|f| f.key == "waves").unwrap();
    assert_eq!(h.form.fields[hj].variant_idx, 2);
    h.apply_form(FormAction::RemoveArrayElement(hj), &mut world);
    let hj = h.form.fields.iter().position(|f| f.key == "waves").unwrap();
    assert_eq!(h.form.fields[hj].variant_idx, 1, "shrank back to one wave");
    set_field(&mut world, form_panel::NAME_INPUT, "pond");
    h.apply_form(FormAction::Confirm, &mut world);
    let ws = h
        .entries
        .iter()
        .find(|e| e["args"]["$id"] == "pond")
        .unwrap();
    assert_eq!(ws["args"]["waves"].as_array().map(Vec::len), Some(1));
}

// A plain vector opens collapsed; disclosing it exposes per-element leaves whose
// edits write back into the vector (keeping its length) and persist.
#[test]
fn form_discloses_a_vector_and_edits_one_element() {
    let mut h = hook(Vec::new());
    let mut world = world_with_fields();
    h.open_form(&mut world, "PointLight".to_string(), FormTarget::New);
    let pos = |h: &EditorHook| {
        h.form
            .fields
            .iter()
            .position(|f| f.key == "position")
            .expect("a position vector field")
    };
    // Collapsed: no element leaves yet.
    assert!(
        h.form
            .fields
            .iter()
            .all(|f| !f.key.starts_with("position."))
    );
    // Disclose it: the element leaves appear and the path is tracked expanded.
    h.apply_form(FormAction::ToggleVecExpand(pos(&h)), &mut world);
    assert!(h.form.vec_expanded.contains("position"));
    let yj = h
        .form
        .fields
        .iter()
        .position(|f| f.key == "position.1")
        .expect("the y element leaf");
    // Edit y through its control, then confirm.
    let slot = visible_slot(yj, h.form.scroll, h.form_window()).expect("y leaf visible");
    set_field(&mut world, form_panel::form_input(slot), "4.5");
    set_field(&mut world, form_panel::NAME_INPUT, "lamp");
    h.apply_form(FormAction::Confirm, &mut world);
    let lamp = h
        .entries
        .iter()
        .find(|e| e["args"]["$id"] == "lamp")
        .unwrap();
    assert_eq!(
        lamp["args"]["position"].as_array().map(Vec::len),
        Some(3),
        "the vector kept its length"
    );
    assert_eq!(lamp["args"]["position"][1].as_f64(), Some(4.5));
}

// Collapsing a disclosed vector after editing an element keeps the edit (capture
// runs before the field list re-derives).
#[test]
fn collapsing_a_vector_keeps_its_element_edits() {
    let mut h = hook(Vec::new());
    let mut world = world_with_fields();
    h.open_form(&mut world, "PointLight".to_string(), FormTarget::New);
    let pj = h
        .form
        .fields
        .iter()
        .position(|f| f.key == "position")
        .unwrap();
    h.apply_form(FormAction::ToggleVecExpand(pj), &mut world);
    let xj = h
        .form
        .fields
        .iter()
        .position(|f| f.key == "position.0")
        .unwrap();
    let slot = visible_slot(xj, h.form.scroll, h.form_window()).unwrap();
    set_field(&mut world, form_panel::form_input(slot), "2.0");
    // Collapse again: the element leaves go away but the edit is folded in.
    let pj = h
        .form
        .fields
        .iter()
        .position(|f| f.key == "position")
        .unwrap();
    h.apply_form(FormAction::ToggleVecExpand(pj), &mut world);
    assert!(!h.form.vec_expanded.contains("position"));
    assert!(
        h.form
            .fields
            .iter()
            .all(|f| !f.key.starts_with("position."))
    );
    set_field(&mut world, form_panel::NAME_INPUT, "lamp");
    h.apply_form(FormAction::Confirm, &mut world);
    let lamp = h
        .entries
        .iter()
        .find(|e| e["args"]["$id"] == "lamp")
        .unwrap();
    assert_eq!(lamp["args"]["position"][0].as_f64(), Some(2.0));
}

// A form wider than the control pool scrolls: a field past the window is edited
// by wheeling down to it. WaterSurface exposes more than a pool's worth of
// fields, so `roughness` is only reachable after scrolling; its edit must still
// persist (and the untouched off-window fields keep their defaults).
#[test]
fn add_form_scrolls_to_and_edits_an_off_window_field() {
    let mut h = hook(Vec::new());
    let mut world = world_with_fields();
    h.open_form(&mut world, "WaterSurface".to_string(), FormTarget::New);
    assert!(
        h.form.fields.len() > form::FIELD_POOL,
        "WaterSurface overflows the control pool"
    );
    let rj = h
        .form
        .fields
        .iter()
        .position(|f| f.key == "roughness")
        .expect("a roughness field");
    assert!(
        visible_slot(rj, h.form.scroll, h.form_window()).is_none(),
        "roughness starts past the visible window"
    );
    // Wheel to the bottom; roughness scrolls into the window.
    for _ in 0..h.form.fields.len() {
        h.scroll_form(1.0, &mut world);
    }
    let slot =
        visible_slot(rj, h.form.scroll, h.form_window()).expect("roughness scrolled into view");
    // Edit it through its now-visible control and confirm.
    set_field(&mut world, form_panel::form_input(slot), "0.9");
    set_field(&mut world, form_panel::NAME_INPUT, "sea");
    h.apply_form(FormAction::Confirm, &mut world);
    let ws = h
        .entries
        .iter()
        .find(|e| e["args"]["$id"] == "sea")
        .expect("the water surface was added");
    assert_eq!(
        ws["args"]["roughness"].as_f64(),
        Some(0.9),
        "the off-window field's edit persisted after scrolling to it"
    );
    // An untouched off-window top field kept its default (not blanked on capture).
    assert_eq!(
        ws["args"]["extent"],
        form::base_args("WaterSurface")["extent"],
        "a scrolled-away field kept its value"
    );
}

// A reference left at (none) persists as null, not a dangling name.
#[test]
fn add_form_ref_field_defaults_to_none() {
    let mut h = hook(vec![entry("grass_tex", "Texture")]);
    let mut world = world_with_fields();
    h.open_form(&mut world, "Decal".to_string(), FormTarget::New);
    set_field(&mut world, form_panel::NAME_INPUT, "bare");
    h.apply_form(FormAction::Confirm, &mut world);
    let decal = h
        .entries
        .iter()
        .find(|e| e["args"]["$id"] == "bare")
        .unwrap();
    assert_eq!(decal["args"]["texture"], serde_json::Value::Null);
}

#[test]
fn invalid_arg_keeps_the_form_open_with_an_error() {
    let mut h = hook(Vec::new());
    let mut world = world_with_fields();
    // Font has a u32 `size_px` field; a negative value cannot re-serialize.
    h.open_form(&mut world, "Font".to_string(), FormTarget::New);
    let j = h
        .form
        .fields
        .iter()
        .position(|f| f.key == "size_px")
        .expect("size_px field present");
    assert!(matches!(h.form.fields[j].kind, form::FieldKind::Int));
    set_field(&mut world, form_panel::form_input(j), "-5");
    set_field(&mut world, form_panel::NAME_INPUT, "myfont");
    h.apply_form(FormAction::Confirm, &mut world);
    assert!(h.form_open(), "the form stays open on invalid input");
    assert!(h.form.error.is_some(), "an error message is shown");
    assert!(h.entries.is_empty(), "nothing invalid was committed");
}

// Toggling the Assets panel off then on (via the View panel) keeps the open
// form + its browse selection (the state is retained, only hidden), so the same
// view returns.
#[test]
fn toggling_the_assets_panel_keeps_the_open_form_state() {
    let mut h = hook(vec![entry("lamp", "PointLight")]);
    let mut world = world_with_fields();
    h.open[PanelKey::Assets] = true;
    let target = entry_target(&h, 0);
    h.open_form(&mut world, "PointLight".to_string(), target);
    assert!(h.form_open() && h.form.target == entry_target(&h, 0));
    // Toggle the assets UI off: the form + selection are kept, not discarded.
    h.toggle_view_row(0, &mut world);
    assert!(!h.open[PanelKey::Assets]);
    assert!(
        h.form_open(),
        "the form is kept when the panel is toggled off"
    );
    assert_eq!(
        h.form.target,
        entry_target(&h, 0),
        "the browse selection is kept"
    );
    // Toggle back on: the same form and selection are restored.
    h.toggle_view_row(0, &mut world);
    assert!(h.open[PanelKey::Assets] && h.form_open());
    assert_eq!(h.form.target, entry_target(&h, 0));
}

// Hiding the assets UI hides the form's elements (but keeps its state); showing
// it again re-renders the form.
#[test]
fn a_hidden_assets_panel_hides_the_form_elements() {
    let mut world = World::new();
    inject::editor_hud(&mut world);
    world.add_component(FrameInput {
        viewport: [1280.0, 720.0],
        ..Default::default()
    });
    let mut h = hook(vec![entry("lamp", "PointLight")]);
    h.open[PanelKey::Assets] = true;
    let target = entry_target(&h, 0);
    h.open_form(&mut world, "PointLight".to_string(), target);
    let form_shown = |w: &World| w.get_by_id::<Sprite>(form_panel::EDIT_BG).unwrap().visible;
    h.tick(&mut world);
    assert!(form_shown(&world), "form shown while the panel is open");
    // Toggle off: the form elements hide, but its state is retained.
    h.toggle_view_row(0, &mut world);
    h.tick(&mut world);
    assert!(!form_shown(&world), "form elements hidden when toggled off");
    assert!(h.form_open(), "but the form state is retained");
    // Toggle on: the form re-renders.
    h.toggle_view_row(0, &mut world);
    h.tick(&mut world);
    assert!(form_shown(&world), "form shown again on toggle-on");
}

#[test]
fn edit_form_seeds_and_updates_existing_args() {
    let mut h = hook(vec![serde_json::json!({
        "type": "PointLight", "args": {"$id": "lamp"}
    })]);
    let mut world = world_with_fields();
    h.open[PanelKey::Assets] = true;
    seed_tree(&mut h, Vec::new());
    click_row(&mut h, "lamp", &mut world);
    assert_eq!(h.form.target, entry_target(&h, 0));
    assert!(!h.form.fields.is_empty());
    // The name field was seeded from the entry.
    assert_eq!(widget::field_text(&world, form_panel::NAME_INPUT), "lamp");
    // Edit a float and confirm; the same entry gains a full args object.
    let (j, key) = h
        .form
        .fields
        .iter()
        .enumerate()
        .find(|(_, f)| matches!(f.kind, form::FieldKind::Float))
        .map(|(j, f)| (j, f.key.clone()))
        .expect("a float arg field");
    set_field(&mut world, form_panel::form_input(j), "9.0");
    h.apply_form(FormAction::Confirm, &mut world);
    assert_eq!(h.entries.len(), 1, "edited in place");
    assert_eq!(h.entries[0]["args"][&key].as_f64(), Some(9.0));
}

// Renaming through the form moves every reference to the old name with it, in
// the same undo step: a Prop naming the Material follows, and a name that
// collides is made unique and the references follow THAT name.
#[test]
fn renaming_through_the_form_moves_the_references_with_it() {
    let mut h = hook(vec![
        entry("mat", "Material"),
        entry("stone", "Material"),
        entry_with_args(
            "box",
            "Prop",
            serde_json::json!({"mesh": "cube", "material": "mat"}),
        ),
        entry_with_args(
            "cube",
            "ProceduralMesh",
            serde_json::json!({"generator": "box"}),
        ),
    ]);
    let mut world = world_with_fields();
    let target = entry_target(&h, 0);
    h.open_form(&mut world, "Material".to_string(), target);
    set_field(&mut world, form_panel::NAME_INPUT, "stone");
    h.apply_form(FormAction::Confirm, &mut world);
    assert_eq!(h.entries[0]["args"]["$id"], "stone_1");
    assert_eq!(h.entries[2]["args"]["material"], "stone_1");

    let target = entry_target(&h, 3);
    h.open_form(&mut world, "ProceduralMesh".to_string(), target);
    set_field(&mut world, form_panel::NAME_INPUT, "crate");
    h.apply_form(FormAction::Confirm, &mut world);
    assert_eq!(
        h.entries[2]["args"]["mesh"], "crate",
        "a structured reference"
    );

    h.undo(&mut world);
    assert_eq!(h.entries[3]["args"]["$id"], "cube");
    assert_eq!(h.entries[2]["args"]["mesh"], "cube");
    h.undo(&mut world);
    assert_eq!(h.entries[0]["args"]["$id"], "mat");
    assert_eq!(h.entries[2]["args"]["material"], "mat");
    assert!(!h.can_undo(), "each rename was one step");
}