jackdaw 0.3.0

A 3D level editor built with Bevy
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
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
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
use std::collections::HashSet;

use bevy::{input_focus::InputFocus, prelude::*, ui::ui_transform::UiGlobalTransform};
use bevy_monitors::prelude::{Mutation, NotifyChanged};
use jackdaw_feathers::{
    context_menu::spawn_context_menu,
    icons::IconFont,
    text_edit::{self, EditorTextEdit, TextEditCommitEvent, TextEditProps, TextEditValue},
    tokens,
    tree_view::{ROW_BG, TreeRowStyle, tree_row},
};
use jackdaw_widgets::context_menu::{ContextMenuAction, ContextMenuCloseSet, ContextMenuState};
use jackdaw_widgets::tree_view::{
    EntityCategory, TreeChildrenPopulated, TreeFocused, TreeIndex, TreeNode, TreeNodeExpanded,
    TreeRowChildren, TreeRowClicked, TreeRowContent, TreeRowDropped, TreeRowDroppedOnRoot,
    TreeRowInlineRename, TreeRowLabel, TreeRowRenamed, TreeRowSelected, TreeRowStartRename,
    TreeRowVisibilityToggled,
};

use crate::{
    EditorEntity, EditorHidden,
    commands::{CommandHistory, EditorCommand, ReparentEntity, SetJsnField},
    entity_ops,
    layout::HierarchyFilter,
    selection::{Selected, Selection},
};
use jackdaw_feathers::dialog::{DialogActionEvent, DialogChildrenSlot};
use jackdaw_jsn::BrushGroup;

/// Stores the default name for the template save dialog.
#[derive(Resource, Default)]
struct PendingTemplateDefaultName(String);

/// Marker for the template name text input inside the dialog.
#[derive(Component)]
struct TemplateNameInput;

/// Marker for the hierarchy panel
#[derive(Component)]
#[require(EditorEntity)]
pub struct HierarchyPanel;

/// Marker for the container that holds tree rows
#[derive(Component)]
#[require(EditorEntity)]
pub struct HierarchyTreeContainer;

/// Controls whether the hierarchy shows all entities or only named ones.
/// `false` = named only (default), `true` = all entities (minus EditorEntity).
#[derive(Resource, Default)]
pub struct HierarchyShowAll(pub bool);

/// Marker for the show-all toggle button in the hierarchy panel.
#[derive(Component)]
pub struct HierarchyShowAllButton;

pub struct HierarchyPlugin;

impl Plugin for HierarchyPlugin {
    fn build(&self, app: &mut App) {
        app.init_resource::<ContextMenuState>()
            .init_resource::<PendingTemplateDefaultName>()
            .init_resource::<HierarchyShowAll>()
            .add_systems(
                OnEnter(crate::AppState::Editor),
                (
                    setup_name_watcher,
                    rebuild_hierarchy.after(crate::spawn_layout),
                ),
            )
            .add_systems(
                Update,
                (
                    apply_hierarchy_filter,
                    cancel_inline_rename,
                    auto_focus_inline_rename,
                    handle_hierarchy_right_click.after(ContextMenuCloseSet),
                    populate_template_dialog,
                    toggle_show_all_button,
                    update_show_all_button_appearance,
                    on_show_all_changed,
                    jackdaw_feathers::tree_view::tree_keyboard_navigation,
                )
                    .run_if(in_state(crate::AppState::Editor)),
            )
            .add_observer(handle_inline_rename_commit)
            .add_observer(on_root_entity_added)
            .add_observer(on_entity_reparented)
            .add_observer(on_tree_node_expanded)
            .add_observer(on_tree_row_clicked)
            .add_observer(on_entity_removed)
            .add_observer(on_name_changed)
            .add_observer(on_entity_selected)
            .add_observer(on_entity_deselected)
            .add_observer(on_tree_row_dropped)
            .add_observer(on_tree_row_dropped_on_root)
            .add_observer(on_tree_row_start_rename)
            .add_observer(on_tree_row_renamed)
            .add_observer(on_context_menu_action)
            .add_observer(on_visibility_toggled)
            .add_observer(on_template_dialog_action)
            .add_observer(on_entity_hidden);
    }
}

/// Classify a scene entity by its primary component for tree display.
fn classify_entity(world: &World, entity: Entity) -> EntityCategory {
    if world.get::<BrushGroup>(entity).is_some() {
        return EntityCategory::Mesh;
    }
    if world.get::<Camera>(entity).is_some() {
        return EntityCategory::Camera;
    }
    if world.get::<PointLight>(entity).is_some()
        || world.get::<DirectionalLight>(entity).is_some()
        || world.get::<SpotLight>(entity).is_some()
    {
        return EntityCategory::Light;
    }
    if world.get::<Mesh3d>(entity).is_some() {
        return EntityCategory::Mesh;
    }
    if world.get::<SceneRoot>(entity).is_some() {
        return EntityCategory::Scene;
    }
    EntityCategory::Entity
}

/// Check if an entity has any non-editor children.
fn has_visible_children(world: &World, entity: Entity) -> bool {
    let Some(children) = world.get::<Children>(entity) else {
        return false;
    };
    children.iter().any(|child| {
        world.get::<EditorEntity>(child).is_none() && world.get::<EditorHidden>(child).is_none()
    })
}

/// Spawn a single (non-recursive) tree row for a source entity.
/// Updates TreeIndex immediately.
fn spawn_single_tree_row(world: &mut World, source: Entity, parent_container: Entity) -> Entity {
    let label = world
        .get::<Name>(source)
        .map(|n| n.as_str().to_string())
        .unwrap_or_else(|| format!("Entity {source}"));
    let has_children = has_visible_children(world, source);
    let category = classify_entity(world, source);
    let icon_font = world.resource::<IconFont>().0.clone();
    let style = TreeRowStyle { icon_font };

    let tree_row_entity = world
        .spawn((
            tree_row(&label, has_children, false, source, category, &style),
            ChildOf(parent_container),
        ))
        .id();

    world
        .resource_mut::<TreeIndex>()
        .insert(source, tree_row_entity);
    tree_row_entity
}

/// Populate the hierarchy tree with root-level entities only (non-recursive).
/// Children are spawned lazily when parents are expanded.
fn rebuild_hierarchy(world: &mut World) {
    let container = world
        .query_filtered::<Entity, With<HierarchyTreeContainer>>()
        .iter(world)
        .next();

    let Some(container) = container else {
        return;
    };

    // Collect all root scene entities (Transform, no ChildOf, no editor markers)
    let roots: Vec<Entity> = world
        .query_filtered::<Entity, (
            With<Transform>,
            Without<EditorEntity>,
            Without<EditorHidden>,
            Without<ChildOf>,
        )>()
        .iter(world)
        .collect();

    let show_all = world.resource::<HierarchyShowAll>().0;

    // Sort by (category, name) for consistent ordering
    let mut root_data: Vec<(Entity, EntityCategory, String)> = roots
        .into_iter()
        .filter(|&e| !world.resource::<TreeIndex>().contains(e))
        .filter(|&e| show_all || world.get::<Name>(e).is_some())
        .map(|e| {
            let category = classify_entity(world, e);
            let name = world
                .get::<Name>(e)
                .map(|n| n.as_str().to_string())
                .unwrap_or_else(|| format!("Entity {e}"));
            (e, category, name)
        })
        .collect();

    root_data.sort_by(|(_, cat_a, name_a), (_, cat_b, name_b)| {
        cat_a.cmp(cat_b).then_with(|| name_a.cmp(name_b))
    });

    for (entity, _category, _name) in root_data {
        spawn_single_tree_row(world, entity, container);
    }
}

/// When a new entity gets Transform and has no parent, create a root tree row.
fn on_root_entity_added(
    trigger: On<Add, Transform>,
    mut commands: Commands,
    tree_index: Res<TreeIndex>,
    container: Option<Single<Entity, With<HierarchyTreeContainer>>>,
    editor_check: Query<(), Or<(With<EditorEntity>, With<EditorHidden>)>>,
    child_of_check: Query<(), With<ChildOf>>,
) {
    let entity = trigger.event_target();
    let Some(container) = container else {
        return;
    };

    if editor_check.contains(entity)
        || child_of_check.contains(entity)
        || tree_index.contains(entity)
    {
        return;
    }

    let container = *container;
    commands.queue(move |world: &mut World| {
        if world.resource::<TreeIndex>().contains(entity) {
            return;
        }
        // Re-check: ChildOf may have been added between observer and command flush
        if world.get::<ChildOf>(entity).is_some() {
            return;
        }
        if world.get::<EditorEntity>(entity).is_some()
            || world.get::<EditorHidden>(entity).is_some()
        {
            return;
        }
        // In named-only mode, skip entities without a Name
        if !world.resource::<HierarchyShowAll>().0 && world.get::<Name>(entity).is_none() {
            return;
        }
        spawn_single_tree_row(world, entity, container);
    });
}

/// When an entity's Name is added/changed, update its tree row label.
/// Also creates a tree row if the entity is a root without one.
fn on_name_changed(
    trigger: On<Add, Name>,
    mut commands: Commands,
    name_query: Query<&Name>,
    tree_index: Res<TreeIndex>,
    tree_nodes: Query<&Children, With<TreeNode>>,
    content_query: Query<&Children, With<TreeRowContent>>,
    mut label_query: Query<&mut Text, With<TreeRowLabel>>,
    container: Option<Single<Entity, With<HierarchyTreeContainer>>>,
    editor_check: Query<(), Or<(With<EditorEntity>, With<EditorHidden>)>>,
    child_of_check: Query<(), With<ChildOf>>,
) {
    let entity = trigger.event_target();
    let Ok(name) = name_query.get(entity) else {
        return;
    };

    if let Some(tree_entity) = tree_index.get(entity) {
        // Update existing label: TreeNode → Children → TreeRowContent → Children → TreeRowLabel
        let Ok(children) = tree_nodes.get(tree_entity) else {
            return;
        };
        for child in children.iter() {
            if let Ok(content_children) = content_query.get(child) {
                for grandchild in content_children.iter() {
                    if let Ok(mut text) = label_query.get_mut(grandchild) {
                        text.0 = name.as_str().to_string();
                        return;
                    }
                }
            }
        }
    } else {
        // Entity has no tree row. Create one if it's a visible root
        let Some(container) = container else {
            return;
        };
        if editor_check.contains(entity) || child_of_check.contains(entity) {
            return;
        }

        let container = *container;
        commands.queue(move |world: &mut World| {
            if world.resource::<TreeIndex>().contains(entity) {
                return;
            }
            // Re-check: ChildOf may have been added between observer and command flush
            if world.get::<ChildOf>(entity).is_some() {
                return;
            }
            if world.get::<EditorEntity>(entity).is_some()
                || world.get::<EditorHidden>(entity).is_some()
            {
                return;
            }
            spawn_single_tree_row(world, entity, container);
        });
    }
}

/// Spawn a watcher entity that notifies us when Name is mutated in-place.
fn setup_name_watcher(mut commands: Commands) {
    commands
        .spawn((EditorEntity, NotifyChanged::<Name>::default()))
        .observe(on_name_mutated);
}

/// When an entity's Name is mutated in-place (e.g. via inspector), update the tree row label.
fn on_name_mutated(
    trigger: On<Mutation<Name>>,
    name_query: Query<&Name>,
    tree_index: Res<TreeIndex>,
    tree_nodes: Query<&Children, With<TreeNode>>,
    content_query: Query<&Children, With<TreeRowContent>>,
    mut label_query: Query<&mut Text, With<TreeRowLabel>>,
) {
    let entity = trigger.mutated;
    let Ok(name) = name_query.get(entity) else {
        return;
    };
    let Some(tree_entity) = tree_index.get(entity) else {
        return;
    };
    let Ok(children) = tree_nodes.get(tree_entity) else {
        return;
    };
    for child in children.iter() {
        let Ok(content_children) = content_query.get(child) else {
            continue;
        };
        for grandchild in content_children.iter() {
            if let Ok(mut text) = label_query.get_mut(grandchild) {
                text.0 = name.as_str().to_string();
                return;
            }
        }
    }
}

/// When an entity gets a parent (ChildOf added or changed), reparent or create its tree row.
fn on_entity_reparented(
    trigger: On<Add, ChildOf>,
    mut commands: Commands,
    tree_index: Res<TreeIndex>,
    editor_check: Query<(), Or<(With<EditorEntity>, With<EditorHidden>)>>,
    tree_node_check: Query<(), With<TreeNode>>,
    child_of_query: Query<&ChildOf>,
    children_query: Query<&Children>,
    tree_row_children: Query<Entity, With<TreeRowChildren>>,
    populated_query: Query<&TreeChildrenPopulated>,
) {
    let entity = trigger.event_target();

    // Skip editor/hidden entities and tree row UI entities
    if editor_check.contains(entity) || tree_node_check.contains(entity) {
        return;
    }

    let Ok(&ChildOf(new_parent)) = child_of_query.get(entity) else {
        return;
    };

    // Find the new parent's TreeRowChildren container via TreeIndex + child walk
    let parent_container = tree_index.get(new_parent).and_then(|parent_tree| {
        children_query
            .get(parent_tree)
            .ok()
            .and_then(|children| children.iter().find(|c| tree_row_children.contains(*c)))
    });

    // If tree row already exists for this entity → reparent it
    if let Some(tree_entity) = tree_index.get(entity) {
        if let Some(container) = parent_container {
            commands.entity(tree_entity).insert(ChildOf(container));
        } else {
            // Parent has no tree row yet. Remove this incorrectly-rooted tree row.
            // Lazy loading will re-create it when the parent is expanded.
            let source = entity;
            commands.queue(move |world: &mut World| {
                world.resource_mut::<TreeIndex>().remove(source);
                if let Ok(ec) = world.get_entity_mut(tree_entity) {
                    ec.despawn();
                }
            });
        }
        return;
    }

    // No tree row exists. Only spawn if the parent's children are already populated
    let Some(parent_container) = parent_container else {
        return;
    };
    let parent_tree = tree_index.get(new_parent).unwrap(); // safe: we found parent_container from it
    let populated = populated_query
        .get(parent_tree)
        .map(|p| p.0)
        .unwrap_or(false);
    if !populated {
        return; // Lazy loading will handle it when parent is expanded
    }

    let container = parent_container;
    commands.queue(move |world: &mut World| {
        if world.resource::<TreeIndex>().contains(entity) {
            return;
        }
        // In named-only mode, skip entities without a Name
        if !world.resource::<HierarchyShowAll>().0 && world.get::<Name>(entity).is_none() {
            return;
        }
        spawn_single_tree_row(world, entity, container);
    });
}

/// When an entity's Name is removed, despawn its tree row.
fn on_entity_removed(
    trigger: On<Despawn, Name>,
    mut commands: Commands,
    tree_index: Res<TreeIndex>,
) {
    let entity = trigger.event_target();

    if let Some(tree_entity) = tree_index.get(entity) {
        if let Ok(mut ec) = commands.get_entity(tree_entity) {
            ec.despawn();
        }
    }
}

/// When EditorHidden is added, remove the tree row if one exists (handles race with observers).
fn on_entity_hidden(
    trigger: On<Add, EditorHidden>,
    mut commands: Commands,
    tree_index: Res<TreeIndex>,
) {
    let entity = trigger.event_target();

    if let Some(tree_entity) = tree_index.get(entity) {
        if let Ok(mut ec) = commands.get_entity(tree_entity) {
            ec.despawn();
        }
    }
}

/// When a tree node is expanded for the first time, spawn tree rows for its children.
fn on_tree_node_expanded(
    trigger: On<Mutation<TreeNodeExpanded>>,
    mut commands: Commands,
    tree_query: Query<(
        &TreeNodeExpanded,
        &TreeChildrenPopulated,
        &TreeNode,
        &Children,
    )>,
    tree_row_children_marker: Query<Entity, With<TreeRowChildren>>,
    remote_check: Query<(), With<crate::remote::entity_browser::RemoteEntityProxy>>,
) {
    let entity = trigger.event_target();
    let Ok((expanded, populated, tree_node, children)) = tree_query.get(entity) else {
        return;
    };

    // Only populate on first expansion
    if !expanded.0 || populated.0 {
        return;
    }

    let source = tree_node.0;

    // Skip remote entity proxies, handled by entity_browser observer
    if remote_check.contains(source) {
        return;
    }

    let Some(container) = children
        .iter()
        .find(|c| tree_row_children_marker.contains(*c))
    else {
        return;
    };
    let tree_row_entity = entity;

    commands.queue(move |world: &mut World| {
        // Double-check populated flag (guard against duplicate events)
        if let Some(pop) = world.get::<TreeChildrenPopulated>(tree_row_entity) {
            if pop.0 {
                return;
            }
        }

        // Mark as populated
        if let Some(mut pop) = world.get_mut::<TreeChildrenPopulated>(tree_row_entity) {
            pop.0 = true;
        }

        // Collect visible children with classification
        let source_children: Vec<Entity> = world
            .get::<Children>(source)
            .map(|c| c.iter().collect())
            .unwrap_or_default();

        let mut child_data: Vec<(Entity, String, EntityCategory)> = Vec::new();
        for child in source_children {
            if world.get::<EditorEntity>(child).is_some()
                || world.get::<EditorHidden>(child).is_some()
            {
                continue;
            }
            // Skip children that already have tree rows
            if world.resource::<TreeIndex>().contains(child) {
                continue;
            }
            let name = world
                .get::<Name>(child)
                .map(|n| n.as_str().to_string())
                .unwrap_or_else(|| format!("Entity {child}"));
            let category = classify_entity(world, child);
            child_data.push((child, name, category));
        }

        // Sort by (category, name)
        child_data.sort_by(|(_, name_a, cat_a), (_, name_b, cat_b)| {
            cat_a.cmp(cat_b).then_with(|| name_a.cmp(name_b))
        });

        // Spawn tree rows
        for (child_entity, _name, _category) in child_data {
            spawn_single_tree_row(world, child_entity, container);
        }
    });
}

/// Handle tree row click → select the source entity.
/// Plain click on selected entity → deselect. Ctrl+Click → toggle.
fn on_tree_row_clicked(
    event: On<TreeRowClicked>,
    mut commands: Commands,
    mut selection: ResMut<Selection>,
    mut focused: ResMut<TreeFocused>,
    keyboard: Res<ButtonInput<KeyCode>>,
    parent_query: Query<&ChildOf>,
    tree_nodes: Query<Entity, With<TreeNode>>,
    remote_check: Query<(), With<crate::remote::entity_browser::RemoteEntityProxy>>,
) {
    // Skip remote entity proxies, handled by entity_browser observer
    if remote_check.contains(event.source_entity) {
        return;
    }

    let ctrl = keyboard.any_pressed([KeyCode::ControlLeft, KeyCode::ControlRight]);

    if ctrl {
        selection.toggle(&mut commands, event.source_entity);
    } else if selection.is_selected(event.source_entity) {
        selection.clear(&mut commands);
    } else {
        selection.select_single(&mut commands, event.source_entity);
    }

    // Set keyboard focus to the tree row containing this content
    let content_entity = event.entity;
    if let Ok(&ChildOf(tree_row)) = parent_query.get(content_entity) {
        if tree_nodes.contains(tree_row) {
            focused.0 = Some(tree_row);
        }
    }
}

/// When Selected is added, highlight the corresponding tree row.
fn on_entity_selected(
    trigger: On<Add, Selected>,
    mut commands: Commands,
    tree_index: Res<TreeIndex>,
    tree_nodes: Query<&Children, With<TreeNode>>,
    tree_row_contents: Query<Entity, With<TreeRowContent>>,
    mut bg_query: Query<&mut BackgroundColor>,
    mut border_query: Query<&mut BorderColor>,
) {
    let entity = trigger.event_target();

    let Some(tree_entity) = tree_index.get(entity) else {
        return;
    };
    let Ok(children) = tree_nodes.get(tree_entity) else {
        return;
    };

    for child in children.iter() {
        if tree_row_contents.contains(child) {
            if let Ok(mut ec) = commands.get_entity(child) {
                ec.insert(TreeRowSelected);
            }
            if let Ok(mut bg) = bg_query.get_mut(child) {
                bg.0 = tokens::SELECTED_BG;
            }
            if let Ok(mut border) = border_query.get_mut(child) {
                *border = BorderColor::all(tokens::SELECTED_BORDER);
            }
            return;
        }
    }
}

/// When Selected is removed, unhighlight the corresponding tree row.
fn on_entity_deselected(
    trigger: On<Remove, Selected>,
    mut commands: Commands,
    tree_index: Res<TreeIndex>,
    tree_nodes: Query<&Children, With<TreeNode>>,
    tree_row_contents: Query<Entity, With<TreeRowContent>>,
    mut bg_query: Query<&mut BackgroundColor>,
    mut border_query: Query<&mut BorderColor>,
) {
    let entity = trigger.event_target();

    let Some(tree_entity) = tree_index.get(entity) else {
        return;
    };
    let Ok(children) = tree_nodes.get(tree_entity) else {
        return;
    };

    for child in children.iter() {
        if tree_row_contents.contains(child) {
            if let Ok(mut ec) = commands.get_entity(child) {
                ec.remove::<TreeRowSelected>();
            }
            if let Ok(mut bg) = bg_query.get_mut(child) {
                bg.0 = ROW_BG;
            }
            if let Ok(mut border) = border_query.get_mut(child) {
                *border = BorderColor::all(Color::NONE);
            }
            return;
        }
    }
}

/// Handle tree row dropped → reparent the scene entity with undo support.
fn on_tree_row_dropped(
    event: On<TreeRowDropped>,
    mut commands: Commands,
    parent_query: Query<&ChildOf>,
) {
    let dragged = event.dragged_source;
    let target = event.target_source;

    if dragged == target {
        return;
    }

    // Cycle check: walk up from target, ensure dragged is not an ancestor
    let mut current = target;
    while let Ok(&ChildOf(parent)) = parent_query.get(current) {
        if parent == dragged {
            return;
        }
        current = parent;
    }

    let old_parent = parent_query.get(dragged).ok().map(|c| c.0);

    let mut cmd = ReparentEntity {
        entity: dragged,
        old_parent,
        new_parent: Some(target),
    };

    commands.queue(move |world: &mut World| {
        cmd.execute(world);
        world
            .resource_mut::<CommandHistory>()
            .undo_stack
            .push(Box::new(cmd));
        world.resource_mut::<CommandHistory>().redo_stack.clear();
    });
}

/// Handle tree row dropped on root container → deparent the scene entity.
fn on_tree_row_dropped_on_root(
    event: On<TreeRowDroppedOnRoot>,
    mut commands: Commands,
    parent_query: Query<&ChildOf, Without<EditorEntity>>,
    tree_index: Res<TreeIndex>,
    container: Single<Entity, With<HierarchyTreeContainer>>,
) {
    let dragged = event.dragged_source;

    let old_parent = match parent_query.get(dragged) {
        Ok(child_of) => Some(child_of.0),
        Err(_) => return,
    };

    let container_entity = *container;

    let mut cmd = ReparentEntity {
        entity: dragged,
        old_parent,
        new_parent: None,
    };

    commands.queue(move |world: &mut World| {
        cmd.execute(world);
        world
            .resource_mut::<CommandHistory>()
            .undo_stack
            .push(Box::new(cmd));
        world.resource_mut::<CommandHistory>().redo_stack.clear();
    });

    // Move the tree row to the root container
    if let Some(tree_entity) = tree_index.get(dragged) {
        commands
            .entity(tree_entity)
            .insert(ChildOf(container_entity));
    }
}

/// Detect right-click on tree rows and open a context menu.
fn handle_hierarchy_right_click(
    mouse: Res<ButtonInput<MouseButton>>,
    mut commands: Commands,
    mut state: ResMut<ContextMenuState>,
    windows: Query<&Window>,
    selection: Res<Selection>,
    tree_row_contents: Query<(Entity, &ChildOf), With<TreeRowContent>>,
    tree_nodes: Query<&TreeNode>,
    computed_nodes: Query<(&ComputedNode, &UiGlobalTransform), With<TreeRowContent>>,
) {
    if !mouse.just_pressed(MouseButton::Right) {
        return;
    }

    let Ok(window) = windows.single() else {
        return;
    };
    let Some(cursor_pos) = window.cursor_position() else {
        return;
    };

    // Close any existing context menu
    if let Some(menu) = state.menu_entity.take() {
        if let Ok(mut ec) = commands.get_entity(menu) {
            ec.despawn();
        }
    }

    // Find which tree row content the cursor is over by hit testing
    let mut target_source = None;
    for (content_entity, child_of) in &tree_row_contents {
        let Ok((computed, global_transform)) = computed_nodes.get(content_entity) else {
            continue;
        };
        let size = computed.size();
        let (_, _, translation) = global_transform.to_scale_angle_translation();
        let pos = translation;
        let half = size / 2.0;
        let rect = Rect::from_center_half_size(pos, half);
        if rect.contains(cursor_pos) {
            if let Ok(tree_node) = tree_nodes.get(child_of.0) {
                target_source = Some(tree_node.0);
                break;
            }
        }
    }

    let Some(target) = target_source else {
        return;
    };

    // If the right-clicked entity isn't selected, select it
    if !selection.is_selected(target) {
        commands.queue(move |world: &mut World| {
            let old_entities: Vec<Entity> = world.resource::<Selection>().entities.clone();
            let mut selection = world.resource_mut::<Selection>();
            selection.entities.clear();
            selection.entities.push(target);

            for &e in &old_entities {
                if e != target {
                    if let Ok(mut ec) = world.get_entity_mut(e) {
                        ec.remove::<Selected>();
                    }
                }
            }
            if let Ok(mut ec) = world.get_entity_mut(target) {
                ec.insert(Selected);
            }
        });
    }

    let menu_items = &[
        ("hierarchy.focus", "Focus                    F"),
        ("hierarchy.rename", "Rename              F2"),
        ("hierarchy.duplicate", "Duplicate        Ctrl+D"),
        ("hierarchy.delete", "Delete             Del"),
        ("---", ""),
        ("hierarchy.save_template", "Save as Template..."),
        ("---", ""),
        ("hierarchy.add_cube", "Add Child Cube"),
        ("hierarchy.add_sphere", "Add Child Sphere"),
        ("hierarchy.add_light", "Add Child Light"),
        ("hierarchy.add_empty", "Add Child Empty"),
    ];

    // Filter out separators for spawn_context_menu (it doesn't handle them)
    let items: Vec<(&str, &str)> = menu_items
        .iter()
        .filter(|(action, _)| *action != "---")
        .copied()
        .collect();

    let menu = spawn_context_menu(&mut commands, cursor_pos, Some(target), &items);
    state.menu_entity = Some(menu);
    state.target_entity = Some(target);
}

/// Handle context menu actions for hierarchy operations.
fn on_context_menu_action(
    event: On<ContextMenuAction>,
    mut commands: Commands,
    global_transforms: Query<&GlobalTransform>,
    mut camera_query: Query<&mut Transform, With<jackdaw_camera::JackdawCameraSettings>>,
) {
    let target_entity = event.target_entity;

    match event.action.as_str() {
        "hierarchy.focus" => {
            if let Some(target) = target_entity {
                if let Ok(global_tf) = global_transforms.get(target) {
                    let target_pos = global_tf.translation();
                    let scale = global_tf.compute_transform().scale;
                    let dist = (scale.length() * 3.0).max(5.0);

                    for mut transform in &mut camera_query {
                        let forward = transform.forward().as_vec3();
                        transform.translation = target_pos - forward * dist;
                        *transform = transform.looking_at(target_pos, Vec3::Y);
                    }
                }
            }
        }
        "hierarchy.rename" => {
            if let Some(target) = target_entity {
                commands.trigger(TreeRowStartRename {
                    entity: Entity::PLACEHOLDER,
                    source_entity: target,
                });
            }
        }
        "hierarchy.duplicate" => {
            commands.queue(|world: &mut World| {
                entity_ops::duplicate_selected(world);
            });
        }
        "hierarchy.delete" => {
            commands.queue(|world: &mut World| {
                entity_ops::delete_selected(world);
            });
        }
        "hierarchy.add_cube" => {
            if let Some(parent) = target_entity {
                commands.queue(move |world: &mut World| {
                    entity_ops::create_entity_in_world(world, entity_ops::EntityTemplate::Cube);
                    // Reparent the newly created entity under the target
                    let selection = world.resource::<Selection>();
                    if let Some(new_entity) = selection.primary() {
                        world.entity_mut(new_entity).insert(ChildOf(parent));
                    }
                });
            }
        }
        "hierarchy.add_sphere" => {
            if let Some(parent) = target_entity {
                commands.queue(move |world: &mut World| {
                    entity_ops::create_entity_in_world(world, entity_ops::EntityTemplate::Sphere);
                    let selection = world.resource::<Selection>();
                    if let Some(new_entity) = selection.primary() {
                        world.entity_mut(new_entity).insert(ChildOf(parent));
                    }
                });
            }
        }
        "hierarchy.add_light" => {
            if let Some(parent) = target_entity {
                commands.queue(move |world: &mut World| {
                    entity_ops::create_entity_in_world(
                        world,
                        entity_ops::EntityTemplate::PointLight,
                    );
                    let selection = world.resource::<Selection>();
                    if let Some(new_entity) = selection.primary() {
                        world.entity_mut(new_entity).insert(ChildOf(parent));
                    }
                });
            }
        }
        "hierarchy.add_empty" => {
            if let Some(parent) = target_entity {
                commands.queue(move |world: &mut World| {
                    entity_ops::create_entity_in_world(world, entity_ops::EntityTemplate::Empty);
                    let selection = world.resource::<Selection>();
                    if let Some(new_entity) = selection.primary() {
                        world.entity_mut(new_entity).insert(ChildOf(parent));
                    }
                });
            }
        }
        "hierarchy.save_template" => {
            if let Some(target) = target_entity {
                // Store the target entity and open a dialog for template name
                commands.queue(move |world: &mut World| {
                    world
                        .resource_mut::<crate::entity_templates::PendingTemplateSave>()
                        .entity = Some(target);
                    // Get the entity name as default template name
                    let default_name = world
                        .get::<Name>(target)
                        .map(|n| n.as_str().to_string())
                        .unwrap_or_else(|| "template".to_string());
                    world.resource_mut::<PendingTemplateDefaultName>().0 = default_name;
                });
                commands.trigger(jackdaw_feathers::dialog::OpenDialogEvent::new(
                    "Save as Template",
                    "Save",
                ));
            }
        }
        _ => {}
    }
}

/// Toggle entity visibility when the eye icon is clicked.
fn on_visibility_toggled(
    event: On<TreeRowVisibilityToggled>,
    mut commands: Commands,
    visibility_query: Query<&Visibility>,
) {
    let source = event.source_entity;

    let current = visibility_query
        .get(source)
        .copied()
        .unwrap_or(Visibility::Inherited);

    let new_visibility = match current {
        Visibility::Hidden => Visibility::Inherited,
        _ => Visibility::Hidden,
    };

    let old_json = serde_json::Value::String(format!("{current:?}"));
    let new_json = serde_json::Value::String(format!("{new_visibility:?}"));

    let cmd = SetJsnField {
        entity: source,
        type_path: "bevy_camera::visibility::Visibility".to_string(),
        field_path: String::new(),
        old_value: old_json,
        new_value: new_json,
    };

    commands.queue(move |world: &mut World| {
        let mut cmd = Box::new(cmd);
        cmd.execute(world);
        let mut history = world.resource_mut::<CommandHistory>();
        history.undo_stack.push(cmd);
        history.redo_stack.clear();
    });
}

/// Marker for inline rename text_edit entity, linking back to the label entity and source entity.
#[derive(Component)]
struct InlineRenameInput {
    label_entity: Entity,
    source_entity: Entity,
}

/// Cancel inline rename on Escape key.
fn cancel_inline_rename(
    keyboard: Res<ButtonInput<KeyCode>>,
    mut commands: Commands,
    rename_query: Query<(Entity, &InlineRenameInput)>,
    names: Query<&Name>,
    mut input_focus: ResMut<InputFocus>,
) {
    if !keyboard.just_pressed(KeyCode::Escape) {
        return;
    }
    for (rename_entity, inline_rename) in &rename_query {
        input_focus.clear();

        let original_name = names
            .get(inline_rename.source_entity)
            .map(|n| n.as_str().to_string())
            .unwrap_or_default();

        // Unhide the label and restore its text
        commands
            .entity(inline_rename.label_entity)
            .remove::<TreeRowInlineRename>();
        if let Ok(mut ec) = commands.get_entity(inline_rename.label_entity) {
            ec.insert(Text::new(original_name));
            ec.entry::<Node>().and_modify(|mut node| {
                node.display = Display::Flex;
            });
        }

        // Despawn the rename text_edit entity
        commands.entity(rename_entity).despawn();
    }
}

/// Start inline rename: hide the label and spawn a text_edit sibling.
fn on_tree_row_start_rename(
    event: On<TreeRowStartRename>,
    mut commands: Commands,
    tree_index: Res<TreeIndex>,
    tree_nodes: Query<&Children, With<TreeNode>>,
    content_query: Query<(Entity, &Children), With<TreeRowContent>>,
    label_query: Query<Entity, With<TreeRowLabel>>,
    names: Query<&Name>,
    rename_check: Query<(), With<InlineRenameInput>>,
) {
    let source = event.source_entity;

    // Don't start a rename if one is already active
    if !rename_check.is_empty() {
        return;
    }

    let Some(tree_entity) = tree_index.get(source) else {
        return;
    };
    let Ok(children) = tree_nodes.get(tree_entity) else {
        return;
    };

    // Find the TreeRowContent entity and the TreeRowLabel entity within it
    let mut label_entity = None;
    let mut content_entity = None;
    for child in children.iter() {
        if let Ok((content_e, content_children)) = content_query.get(child) {
            for grandchild in content_children.iter() {
                if label_query.contains(grandchild) {
                    label_entity = Some(grandchild);
                    content_entity = Some(content_e);
                    break;
                }
            }
        }
    }
    let Some(label_entity) = label_entity else {
        return;
    };
    let Some(content_entity) = content_entity else {
        return;
    };

    let current_name = names
        .get(source)
        .map(|n| n.as_str().to_string())
        .unwrap_or_default();

    // Hide the label and mark it so we can restore later
    commands.entity(label_entity).insert(TreeRowInlineRename);
    commands
        .entity(label_entity)
        .entry::<Node>()
        .and_modify(|mut node| {
            node.display = Display::None;
        });

    // Spawn the text_edit as a sibling inside the content entity
    commands.spawn((
        InlineRenameInput {
            label_entity,
            source_entity: source,
        },
        text_edit::text_edit(
            TextEditProps::default()
                .with_default_value(current_name)
                .allow_empty(),
        ),
        ChildOf(content_entity),
    ));
}

/// Auto-focus inline rename text_edit inputs one frame after spawn.
fn auto_focus_inline_rename(
    rename_inputs: Query<(Entity, &InlineRenameInput, &Children)>,
    wrappers: Query<&jackdaw_feathers::text_edit::TextEditConfig>,
    wrapper_children: Query<&Children>,
    editor_text_edits: Query<Entity, With<EditorTextEdit>>,
    mut input_focus: ResMut<InputFocus>,
) {
    for (_rename_entity, _inline, children) in &rename_inputs {
        // The text_edit outer entity has children: [wrapper] which has children: [..., EditorTextEdit]
        for child in children.iter() {
            if wrappers.contains(child) {
                // this is the label/wrapper -- skip, we need the actual wrapper node
                continue;
            }
            // child might be the wrapper entity (has TextEditWrapper inside)
            if let Ok(wrapper_kids) = wrapper_children.get(child) {
                for wk in wrapper_kids.iter() {
                    if editor_text_edits.contains(wk) {
                        if input_focus.0 != Some(wk) {
                            input_focus.0 = Some(wk);
                        }
                        return;
                    }
                }
            }
        }
    }
}

/// Handle TextEditCommitEvent for inline renames.
fn handle_inline_rename_commit(
    event: On<TextEditCommitEvent>,
    rename_inputs: Query<(Entity, &InlineRenameInput)>,
    child_of_query: Query<&ChildOf>,
    mut commands: Commands,
    mut input_focus: ResMut<InputFocus>,
) {
    // Walk up from the committed entity to find if it belongs to an InlineRenameInput
    // event.entity is the inner EditorTextEdit → parent is wrapper → parent is text_edit outer → parent is content
    // The InlineRenameInput is on the text_edit outer entity
    let mut current = event.entity;
    let mut found = None;
    for _ in 0..4 {
        let Ok(child_of) = child_of_query.get(current) else {
            break;
        };
        if let Ok((rename_entity, inline_rename)) = rename_inputs.get(child_of.parent()) {
            found = Some((
                rename_entity,
                inline_rename.label_entity,
                inline_rename.source_entity,
            ));
            break;
        }
        current = child_of.parent();
    }

    let Some((rename_entity, label_entity, source_entity)) = found else {
        return;
    };

    input_focus.clear();

    // Restore label
    commands
        .entity(label_entity)
        .remove::<TreeRowInlineRename>();
    commands
        .entity(label_entity)
        .insert(Text::new(event.text.clone()));
    commands
        .entity(label_entity)
        .entry::<Node>()
        .and_modify(|mut node| {
            node.display = Display::Flex;
        });

    // Despawn the rename text_edit entity
    commands.entity(rename_entity).despawn();

    // Trigger the rename
    commands.trigger(TreeRowRenamed {
        entity: label_entity,
        source_entity,
        new_name: event.text.clone(),
    });
}

/// Commit inline rename: update Name with undo.
fn on_tree_row_renamed(event: On<TreeRowRenamed>, mut commands: Commands, names: Query<&Name>) {
    let source = event.source_entity;
    let new_name = event.new_name.clone();

    // Apply name change with undo
    let old_name = names
        .get(source)
        .map(|n| n.as_str().to_string())
        .unwrap_or_default();

    if old_name == new_name {
        return;
    }

    commands.queue(move |world: &mut World| {
        let cmd = SetJsnField {
            entity: source,
            type_path: "bevy_ecs::name::Name".to_string(),
            field_path: String::new(),
            old_value: serde_json::Value::String(old_name),
            new_value: serde_json::Value::String(new_name),
        };
        let mut cmd = Box::new(cmd);
        cmd.execute(world);
        let mut history = world.resource_mut::<CommandHistory>();
        history.undo_stack.push(cmd);
        history.redo_stack.clear();
    });
}

/// When the template dialog opens, populate its children slot with a name input.
fn populate_template_dialog(
    mut commands: Commands,
    pending: Res<crate::entity_templates::PendingTemplateSave>,
    default_name: Res<PendingTemplateDefaultName>,
    slots: Query<(Entity, &Children), (With<DialogChildrenSlot>, Changed<Children>)>,
    existing_inputs: Query<(), With<TemplateNameInput>>,
) {
    // Only act when there's a pending template save
    if pending.entity.is_none() {
        return;
    }
    // Don't re-populate if we already have an input
    if !existing_inputs.is_empty() {
        return;
    }
    for (slot_entity, children) in &slots {
        if children.is_empty() {
            commands.spawn((
                TemplateNameInput,
                text_edit::text_edit(
                    TextEditProps::default()
                        .with_placeholder("Template name...")
                        .with_default_value(default_name.0.clone())
                        .allow_empty(),
                ),
                ChildOf(slot_entity),
            ));
        }
    }
}

/// When the dialog's action button is clicked, save the template.
fn on_template_dialog_action(
    _event: On<DialogActionEvent>,
    mut commands: Commands,
    pending: Res<crate::entity_templates::PendingTemplateSave>,
    name_inputs: Query<&TextEditValue, With<TemplateNameInput>>,
) {
    let Some(_entity) = pending.entity else {
        return;
    };

    let name = name_inputs
        .iter()
        .next()
        .map(|input| input.0.trim().to_string())
        .unwrap_or_default();

    if name.is_empty() {
        return;
    }

    commands.queue(move |world: &mut World| {
        crate::entity_templates::save_entity_template(world, &name);
        world
            .resource_mut::<crate::entity_templates::PendingTemplateSave>()
            .entity = None;
    });
}

/// Toggle the show-all state when the button is pressed.
fn toggle_show_all_button(
    mut show_all: ResMut<HierarchyShowAll>,
    interactions: Query<&Interaction, (Changed<Interaction>, With<HierarchyShowAllButton>)>,
) {
    for interaction in &interactions {
        if *interaction == Interaction::Pressed {
            show_all.0 = !show_all.0;
        }
    }
}

/// Update the show-all button icon color based on active state.
fn update_show_all_button_appearance(
    show_all: Res<HierarchyShowAll>,
    buttons: Query<&Children, With<HierarchyShowAllButton>>,
    mut text_colors: Query<&mut TextColor>,
) {
    if !show_all.is_changed() {
        return;
    }
    let color = if show_all.0 {
        tokens::TEXT_PRIMARY
    } else {
        tokens::TEXT_SECONDARY
    };
    for children in &buttons {
        for child in children.iter() {
            if let Ok(mut tc) = text_colors.get_mut(child) {
                tc.0 = color;
            }
        }
    }
}

/// When the show-all toggle changes, clear and rebuild the hierarchy.
fn on_show_all_changed(show_all: Res<HierarchyShowAll>, mut commands: Commands) {
    if show_all.is_changed() && !show_all.is_added() {
        commands.queue(|world: &mut World| {
            clear_all_tree_rows(world);
            rebuild_hierarchy(world);
        });
    }
}

/// Despawn all tree rows and clear the TreeIndex.
pub fn clear_all_tree_rows(world: &mut World) {
    let container = world
        .query_filtered::<Entity, With<HierarchyTreeContainer>>()
        .iter(world)
        .next();
    let Some(container) = container else {
        return;
    };

    // Collect tree row children of the container
    let tree_rows: Vec<Entity> = world
        .get::<Children>(container)
        .map(|c| c.iter().collect())
        .unwrap_or_default();

    for row in tree_rows {
        if let Ok(ec) = world.get_entity_mut(row) {
            ec.despawn();
        }
    }

    world.resource_mut::<TreeIndex>().clear();
}

/// Filter hierarchy tree rows based on the filter text input.
fn apply_hierarchy_filter(
    filter_input: Query<&TextEditValue, (With<HierarchyFilter>, Changed<TextEditValue>)>,
    tree_nodes: Query<(Entity, &TreeNode)>,
    names: Query<&Name>,
    parent_query: Query<&ChildOf>,
    tree_row_children_query: Query<(), With<TreeRowChildren>>,
    mut display_query: Query<&mut Node>,
) {
    let Ok(text_edit_value) = filter_input.single() else {
        return;
    };

    let filter = text_edit_value.0.trim().to_lowercase();

    if filter.is_empty() {
        for (tree_entity, _) in &tree_nodes {
            if let Ok(mut node) = display_query.get_mut(tree_entity) {
                node.display = Display::Flex;
            }
        }
        return;
    }

    // First pass: determine which source entities match the filter
    let mut visible_tree_entities: HashSet<Entity> = HashSet::new();

    for (tree_entity, tree_node) in &tree_nodes {
        let label = names
            .get(tree_node.0)
            .map(|n| n.as_str().to_lowercase())
            .unwrap_or_else(|_| format!("entity {}", tree_node.0).to_lowercase());
        let matches = label.contains(&filter);

        if matches {
            visible_tree_entities.insert(tree_entity);

            // Walk up ancestors: tree row → ChildOf → TreeRowChildren → ChildOf → parent tree row
            let mut current = tree_entity;
            while let Ok(&ChildOf(parent)) = parent_query.get(current) {
                if tree_row_children_query.contains(parent) {
                    if let Ok(&ChildOf(grandparent)) = parent_query.get(parent) {
                        visible_tree_entities.insert(grandparent);
                        current = grandparent;
                    } else {
                        break;
                    }
                } else {
                    break;
                }
            }
        }
    }

    // Second pass: set display on all tree rows
    for (tree_entity, _) in &tree_nodes {
        if let Ok(mut node) = display_query.get_mut(tree_entity) {
            node.display = if visible_tree_entities.contains(&tree_entity) {
                Display::Flex
            } else {
                Display::None
            };
        }
    }
}