jackdaw 0.3.1

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
use crate::EditorEntity;
use crate::colors;
use crate::custom_properties::CustomProperties;
use crate::selection::{Selected, Selection};
use std::any::TypeId;

use bevy::{
    ecs::{
        archetype::Archetype,
        component::{ComponentId, Components},
        reflect::{AppTypeRegistry, ReflectComponent},
    },
    prelude::*,
    reflect::serde::TypedReflectSerializer,
};
use jackdaw_feathers::{
    icons::{EditorFont, Icon, IconFont},
    tokens,
};
use jackdaw_widgets::collapsible::{
    CollapsibleBody, CollapsibleHeader, CollapsibleSection, ToggleCollapsible,
};

use jackdaw_feathers::text_edit::TextEditValue;
use std::collections::HashSet;

use bevy_monitors::prelude::{Addition, Monitor, NotifyAdded};

use super::{
    AddComponentButton, ComponentDisplay, ComponentDisplayBody, ComponentName, ComponentPicker,
    Inspector, InspectorDirty, InspectorGroupSection, InspectorSearch, InspectorTarget,
    ReflectDisplayable, ReflectEditorMeta, brush_display, custom_props_display,
    extract_module_group, material_display, reflect_fields,
};

pub(crate) fn add_component_displays(
    _: On<Add, Selected>,
    mut commands: Commands,
    components: &Components,
    type_registry: Res<AppTypeRegistry>,
    selection: Res<Selection>,
    entity_query: Query<(&Archetype, EntityRef), (With<Selected>, Without<EditorEntity>)>,
    inspector: Single<Entity, With<Inspector>>,
    names: Query<&Name>,
    icon_font: Res<IconFont>,
    editor_font: Res<EditorFont>,
    materials: Res<Assets<StandardMaterial>>,
    ast: Res<jackdaw_jsn::SceneJsnAst>,
) {
    let Some(primary) = selection.primary() else {
        return;
    };
    let Ok((archetype, entity_ref)) = entity_query.get(primary) else {
        return;
    };

    let source_entity = entity_ref.entity();
    let sel_count = selection.entities.len();

    // Collect AST-tracked component type paths
    let jsn_type_paths: HashSet<String> = ast
        .node_for_entity(source_entity)
        .map(|node| node.components.keys().cloned().collect())
        .unwrap_or_default();

    build_inspector_displays(
        &mut commands,
        components,
        &type_registry,
        source_entity,
        archetype,
        entity_ref,
        *inspector,
        sel_count,
        &names,
        &icon_font,
        &editor_font,
        false,
        &materials,
        &jsn_type_paths,
    );

    // Set up monitoring: watch the selected entity for InspectorDirty
    commands.entity(*inspector).insert((
        InspectorTarget(primary),
        Monitor(primary),
        NotifyAdded::<InspectorDirty>::default(),
    ));
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn build_inspector_displays(
    commands: &mut Commands,
    components: &Components,
    type_registry: &Res<AppTypeRegistry>,
    source_entity: Entity,
    archetype: &Archetype,
    entity_ref: EntityRef,
    inspector_entity: Entity,
    selection_count: usize,
    names: &Query<&Name>,
    icon_font: &IconFont,
    editor_font: &EditorFont,
    _read_only: bool,
    materials: &Assets<StandardMaterial>,
    jsn_type_paths: &HashSet<String>,
) {
    // Show multi-selection header when multiple entities are selected
    if selection_count > 1 {
        commands.spawn((
            ComponentDisplay,
            Node {
                padding: UiRect::axes(Val::Px(tokens::SPACING_MD), Val::Px(tokens::SPACING_SM)),
                width: Val::Percent(100.0),
                ..Default::default()
            },
            BackgroundColor(tokens::SELECTED_BG),
            ChildOf(inspector_entity),
            children![(
                Text::new(format!(
                    "{selection_count} entities selected, edits apply to all"
                )),
                TextFont {
                    font: editor_font.0.clone(),
                    font_size: tokens::FONT_SM,
                    ..Default::default()
                },
                TextColor(tokens::TEXT_PRIMARY),
            )],
        ));
    }

    // Physics section -- always visible, combines RigidBody + AvianCollider
    super::physics_display::spawn_physics_section(
        commands,
        inspector_entity,
        source_entity,
        entity_ref,
        &icon_font.0,
        &editor_font.0,
        type_registry,
        names,
    );

    let registry = type_registry.read();

    // Check for prefab baseline (override tracking)
    let baseline = entity_ref.get::<jackdaw_jsn::JsnPrefabBaseline>().cloned();

    // (short_name, module_group, component_id)
    let mut custom_groups = std::collections::HashSet::new();
    let mut comp_list: Vec<(String, String, ComponentId)> = archetype
        .iter_components()
        .filter_map(|component_id| {
            let info = components.get_info(component_id)?;
            let type_id = info.type_id();

            // Try TypeRegistry first for proper names
            if let Some(type_id) = type_id
                && let Some(registration) = registry.get(type_id)
            {
                let table = registration.type_info().type_path_table();
                let full_path = table.path();
                if full_path.starts_with("jackdaw")
                    && !full_path.starts_with("jackdaw_jsn")
                    && !full_path.starts_with("jackdaw_avian_integration")
                    && !full_path.starts_with("jackdaw_animation")
                {
                    return None;
                }
                // Hide all avian3d + AvianCollider components from generic
                // groups -- they're managed by the dedicated Physics section.
                if full_path.starts_with("avian3d::")
                    || full_path == "jackdaw_avian_integration::AvianCollider"
                {
                    return None;
                }
                // AST filter: only show components tracked in the AST
                if !jsn_type_paths.is_empty() && !jsn_type_paths.contains(full_path) {
                    return None;
                }
                let short = table.short_path().to_string();
                let module_group = if let Some(meta) = registration.data::<ReflectEditorMeta>()
                    && !meta.category.is_empty()
                {
                    let cat = meta.category.to_string();
                    custom_groups.insert(cat.clone());
                    cat
                } else {
                    extract_module_group(table.module_path())
                };
                return Some((short, module_group, component_id));
            }

            // Fallback: use Components name
            let name = components.get_name(component_id)?;
            if name.starts_with("jackdaw")
                && !name.starts_with("jackdaw_jsn")
                && !name.starts_with("jackdaw_avian_integration")
                && !name.starts_with("jackdaw_animation")
            {
                return None;
            }
            Some((
                name.shortname().to_string(),
                "Other".to_string(),
                component_id,
            ))
        })
        .collect();

    // Sort: custom-category groups first, then alphabetical within each tier
    comp_list.sort_by(|a, b| {
        let a_custom = custom_groups.contains(&a.1);
        let b_custom = custom_groups.contains(&b.1);
        b_custom
            .cmp(&a_custom)
            .then_with(|| a.1.cmp(&b.1))
            .then_with(|| a.0.to_lowercase().cmp(&b.0.to_lowercase()))
    });

    // Spawn components with subtle group dividers
    let mut current_group = String::new();
    for (name, module_group, component_id) in &comp_list {
        // Category group divider with icon
        if *module_group != current_group {
            current_group = module_group.clone();
            let group_icon = if custom_groups.contains(module_group) {
                Icon::Tag
            } else {
                Icon::Package
            };
            commands.spawn((
                ComponentDisplay,
                Node {
                    flex_direction: FlexDirection::Row,
                    align_items: AlignItems::Center,
                    justify_content: JustifyContent::Center,
                    column_gap: Val::Px(tokens::SPACING_SM),
                    width: Val::Percent(100.0),
                    padding: UiRect::new(
                        Val::Px(tokens::SPACING_XS),
                        Val::ZERO,
                        Val::Px(tokens::SPACING_MD),
                        Val::ZERO,
                    ),
                    ..Default::default()
                },
                ChildOf(inspector_entity),
                children![
                    (
                        Text::new(String::from(group_icon.unicode())),
                        TextFont {
                            font: icon_font.0.clone(),
                            font_size: tokens::TEXT_SIZE,
                            ..Default::default()
                        },
                        TextColor(tokens::TEXT_SECONDARY),
                    ),
                    (
                        Text::new(module_group.clone()),
                        TextFont {
                            font: editor_font.0.clone(),
                            font_size: tokens::FONT_SM,
                            weight: FontWeight::MEDIUM,
                            ..Default::default()
                        },
                        TextColor(tokens::TEXT_SECONDARY),
                    ),
                ],
            ));
        }

        let component_id = *component_id;

        // Detect override: compare current component value vs baseline
        let is_overridden = baseline.as_ref().is_some_and(|bl| {
            let type_id = components
                .get_info(component_id)
                .and_then(|info| info.type_id());
            if let Some(type_id) = type_id
                && let Some(registration) = registry.get(type_id)
                && let Some(reflect_component) = registration.data::<ReflectComponent>()
                && let Some(component_ref) = reflect_component.reflect(entity_ref)
            {
                let type_path = registration.type_info().type_path_table().path();
                if let Some(baseline_val) = bl.components.get(type_path) {
                    let serializer = TypedReflectSerializer::new(component_ref, &registry);
                    if let Ok(current_val) = serde_json::to_value(&serializer) {
                        return current_val != *baseline_val;
                    }
                }
            }
            false
        });

        let (display_entity, body_entity) = spawn_component_display(
            commands,
            name,
            source_entity,
            Some(component_id),
            &icon_font.0,
            &editor_font.0,
            is_overridden,
        );
        commands
            .entity(display_entity)
            .insert(ChildOf(inspector_entity));

        // Try Displayable first, then reflection, then fallback
        let type_id = components
            .get_info(component_id)
            .and_then(|info| info.type_id());

        if let Some(type_id) = type_id
            && let Some(registration) = registry.get(type_id)
            && let Some(reflect_component) = registration.data::<ReflectComponent>()
            && let Some(reflected) = reflect_component.reflect(entity_ref)
        {
            // Priority 1: Displayable trait override
            if let Some(reflect_displayable) = registration.data::<ReflectDisplayable>()
                && let Some(displayable) = reflect_displayable.get(reflected)
            {
                let mut body_commands = commands.entity(body_entity);
                displayable.display(&mut body_commands, source_entity);
                continue;
            }

            // Priority 2: MeshMaterial3d<StandardMaterial>, display material fields
            if type_id == TypeId::of::<MeshMaterial3d<StandardMaterial>>() {
                material_display::spawn_material_display_deferred(
                    commands,
                    body_entity,
                    source_entity,
                );
                continue;
            }

            // Priority 3: CustomProperties, specialized property editor
            if type_id == TypeId::of::<CustomProperties>() {
                if let Some(cp) = reflected.downcast_ref::<CustomProperties>() {
                    custom_props_display::spawn_custom_properties_display(
                        commands,
                        body_entity,
                        source_entity,
                        cp,
                        &editor_font.0,
                        &icon_font.0,
                    );
                }
                continue;
            }

            // Priority 3b: Brush, show face/vertex info
            if type_id == TypeId::of::<crate::brush::Brush>() {
                if let Some(brush) = reflected.downcast_ref::<crate::brush::Brush>() {
                    brush_display::spawn_brush_display(commands, body_entity, brush, materials);
                }
                continue;
            }

            // Priority 3c: Terrain, custom inspector sections
            if type_id == TypeId::of::<jackdaw_jsn::Terrain>() {
                crate::terrain::inspector::spawn_terrain_inspector_container(commands, body_entity);
                continue;
            }

            // Priority 3: Generic reflection display
            let full_path = registration.type_info().type_path_table().path();
            reflect_fields::spawn_reflected_fields(
                commands,
                body_entity,
                reflected,
                0,
                String::new(),
                source_entity,
                full_path,
                names,
                type_registry,
                &editor_font.0,
                &icon_font.0,
            );
            continue;
        }

        // Fallback: no reflection data
        commands.spawn((
            Text::new("(read-only)"),
            TextFont {
                font_size: tokens::FONT_SM,
                ..Default::default()
            },
            TextColor(tokens::TEXT_SECONDARY),
            ChildOf(body_entity),
        ));
    }

    // Add Component button is in the static layout header (layout.rs entity_inspector)
    // so we don't spawn a dynamic one here.
}

pub(crate) fn remove_component_displays(
    _: On<Remove, Selected>,
    mut commands: Commands,
    inspector: Single<(Entity, Option<&Children>), With<Inspector>>,
    displays: Query<
        Entity,
        Or<(
            With<ComponentDisplay>,
            With<AddComponentButton>,
            With<ComponentPicker>,
        )>,
    >,
) {
    let (entity, children) = inspector.into_inner();

    // Clean up monitoring components
    commands
        .entity(entity)
        .remove::<(InspectorTarget, Monitor, NotifyAdded<InspectorDirty>)>();

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

    for child in displays.iter_many(children.collection()) {
        if let Ok(mut ec) = commands.get_entity(child) {
            ec.despawn();
        }
    }
}

/// Handles `Addition<InspectorDirty>` on the Inspector entity: despawn existing
/// displays and rebuild from the monitored source entity.
pub(crate) fn on_inspector_dirty(
    _: On<Addition<InspectorDirty>>,
    mut commands: Commands,
    components: &Components,
    type_registry: Res<AppTypeRegistry>,
    inspector: Single<(Entity, &InspectorTarget, Option<&Children>), With<Inspector>>,
    entity_query: Query<(&Archetype, EntityRef), Without<EditorEntity>>,
    selection: Res<Selection>,
    names: Query<&Name>,
    icon_font: Res<IconFont>,
    editor_font: Res<EditorFont>,
    displays: Query<
        Entity,
        Or<(
            With<ComponentDisplay>,
            With<AddComponentButton>,
            With<ComponentPicker>,
        )>,
    >,
    materials: Res<Assets<StandardMaterial>>,
    ast: Res<jackdaw_jsn::SceneJsnAst>,
) {
    let (inspector_entity, target, children) = inspector.into_inner();
    let source_entity = target.0;

    // Despawn existing display children
    if let Some(children) = children {
        for child in displays.iter_many(children.collection()) {
            if let Ok(mut ec) = commands.get_entity(child) {
                ec.despawn();
            }
        }
    }

    // Remove InspectorDirty from the source entity
    if let Ok(mut ec) = commands.get_entity(source_entity) {
        ec.remove::<InspectorDirty>();
    }

    // Rebuild
    let Ok((archetype, entity_ref)) = entity_query.get(source_entity) else {
        return;
    };
    let sel_count = selection.entities.len();

    let jsn_type_paths: HashSet<String> = ast
        .node_for_entity(source_entity)
        .map(|node| node.components.keys().cloned().collect())
        .unwrap_or_default();

    build_inspector_displays(
        &mut commands,
        components,
        &type_registry,
        source_entity,
        archetype,
        entity_ref,
        inspector_entity,
        sel_count,
        &names,
        &icon_font,
        &editor_font,
        false,
        &materials,
        &jsn_type_paths,
    );
}

pub(crate) fn spawn_component_display(
    commands: &mut Commands,
    name: &str,
    entity: Entity,
    component: Option<ComponentId>,
    icon_font: &Handle<Font>,
    editor_font: &Handle<Font>,
    is_overridden: bool,
) -> (Entity, Entity) {
    let font = icon_font.clone();
    let body_font = editor_font.clone();

    let body_entity = commands
        .spawn((
            ComponentDisplayBody,
            CollapsibleBody,
            Node {
                padding: UiRect::new(
                    Val::Px(tokens::SPACING_MD),
                    Val::Px(tokens::SPACING_SM),
                    Val::Px(tokens::SPACING_XS),
                    Val::Px(tokens::SPACING_XS),
                ),
                flex_direction: FlexDirection::Column,
                width: Val::Percent(100.0),
                ..Default::default()
            },
        ))
        .id();

    let section_entity = commands
        .spawn((
            ComponentDisplay,
            ComponentName(name.to_string()),
            CollapsibleSection { collapsed: false },
            Node {
                flex_direction: FlexDirection::Column,
                width: Val::Percent(100.0),
                border: UiRect::all(Val::Px(1.0)),
                border_radius: BorderRadius::all(Val::Px(tokens::COMPONENT_CARD_RADIUS)),
                ..Default::default()
            },
            BackgroundColor(tokens::COMPONENT_CARD_BG),
            BorderColor::all(tokens::COMPONENT_CARD_BORDER),
            BoxShadow(vec![ShadowStyle {
                x_offset: Val::ZERO,
                y_offset: Val::ZERO,
                blur_radius: Val::Px(1.0),
                spread_radius: Val::ZERO,
                color: tokens::SHADOW_COLOR,
            }]),
        ))
        .id();

    // Header (Figma: space-between with [chevron] [icon+name] [ellipsis])
    let header = commands
        .spawn((
            CollapsibleHeader,
            Node {
                flex_direction: FlexDirection::Row,
                align_items: AlignItems::Center,
                justify_content: JustifyContent::SpaceBetween,
                width: Val::Percent(100.0),
                padding: UiRect::axes(Val::Px(tokens::SPACING_MD), Val::Px(tokens::SPACING_SM)),
                column_gap: Val::Px(tokens::SPACING_SM),
                border_radius: BorderRadius::top(Val::Px(tokens::COMPONENT_CARD_RADIUS)),
                ..Default::default()
            },
            BackgroundColor(tokens::COMPONENT_CARD_HEADER_BG),
            ChildOf(section_entity),
        ))
        .id();

    // Toggle area (chevron + icon + title) -- click to collapse/expand
    let toggle_area = commands
        .spawn((
            Node {
                flex_direction: FlexDirection::Row,
                align_items: AlignItems::Center,
                column_gap: Val::Px(tokens::SPACING_SM),
                flex_grow: 1.0,
                ..Default::default()
            },
            ChildOf(header),
        ))
        .id();

    // Chevron icon
    commands.spawn((
        Text::new(String::from(Icon::ChevronDown.unicode())),
        TextFont {
            font: font.clone(),
            font_size: tokens::FONT_SM,
            ..Default::default()
        },
        TextColor(tokens::TEXT_SECONDARY),
        ChildOf(toggle_area),
    ));

    // Component icon (matching Figma: lucide/move-3d style icon)
    commands.spawn((
        Text::new(String::from(Icon::Move3d.unicode())),
        TextFont {
            font: font.clone(),
            font_size: tokens::TEXT_SIZE,
            ..Default::default()
        },
        TextColor(tokens::TEXT_SECONDARY),
        ChildOf(toggle_area),
    ));

    // Component name (orange if overridden)
    let name_color = if is_overridden {
        colors::INSPECTOR_OVERRIDE
    } else {
        tokens::TEXT_DISPLAY_COLOR.into()
    };
    commands.spawn((
        Text::new(name.to_string()),
        TextFont {
            font: body_font,
            font_size: tokens::FONT_SM,
            weight: FontWeight::MEDIUM,
            ..Default::default()
        },
        TextColor(name_color),
        ChildOf(toggle_area),
    ));

    // Toggle on click (on toggle area, not on the X button)
    let section = section_entity;
    commands
        .entity(toggle_area)
        .observe(move |_: On<Pointer<Click>>, mut commands: Commands| {
            commands.trigger(ToggleCollapsible { entity: section });
        });

    if let Some(component) = component {
        // Revert button (only shown for overridden prefab components)
        if is_overridden {
            let source_entity = entity;
            commands.spawn((
                Text::new(String::from(Icon::RotateCcw.unicode())),
                TextFont {
                    font: font.clone(),
                    font_size: tokens::FONT_SM,
                    ..Default::default()
                },
                TextColor(colors::INSPECTOR_OVERRIDE),
                ChildOf(header),
                bevy::ui_widgets::observe(move |_: On<Pointer<Click>>, mut commands: Commands| {
                    commands.queue(move |world: &mut World| {
                        revert_component_to_baseline(world, source_entity, component);
                    });
                }),
            ));
        }

        // Remove component button (X icon)
        commands.spawn((
            Text::new(String::from(Icon::X.unicode())),
            TextFont {
                font: font.clone(),
                font_size: tokens::FONT_SM,
                ..Default::default()
            },
            TextColor(tokens::TEXT_SECONDARY),
            ChildOf(header),
            bevy::ui_widgets::observe(move |_: On<Pointer<Click>>, mut commands: Commands| {
                commands.entity(entity).remove_by_id(component);
            }),
        ));
    }

    // Ellipsis menu icon
    commands.spawn((
        Text::new(String::from(Icon::Ellipsis.unicode())),
        TextFont {
            font: font.clone(),
            font_size: tokens::FONT_SM,
            ..Default::default()
        },
        TextColor(tokens::TEXT_SECONDARY),
        ChildOf(header),
    ));

    // Hover effect on header
    commands.entity(header).observe(
        |hover: On<Pointer<Over>>, mut bg: Query<&mut BackgroundColor, With<CollapsibleHeader>>| {
            if let Ok(mut bg) = bg.get_mut(hover.event_target()) {
                bg.0 = tokens::HOVER_BG;
            }
        },
    );
    commands.entity(header).observe(
        |out: On<Pointer<Out>>, mut bg: Query<&mut BackgroundColor, With<CollapsibleHeader>>| {
            if let Ok(mut bg) = bg.get_mut(out.event_target()) {
                bg.0 = tokens::COMPONENT_CARD_HEADER_BG;
            }
        },
    );

    // Attach body to section
    commands.entity(body_entity).insert(ChildOf(section_entity));

    (section_entity, body_entity)
}

/// Filter inspector components based on the search input.
pub(crate) fn filter_inspector_components(
    search_query: Query<&TextEditValue, (With<InspectorSearch>, Changed<TextEditValue>)>,
    components: Query<(Entity, &ComponentName), With<ComponentDisplay>>,
    groups: Query<(Entity, &Children), With<InspectorGroupSection>>,
    mut node_query: Query<&mut Node>,
) {
    let Ok(search) = search_query.single() else {
        return;
    };
    let filter = search.0.trim().to_lowercase();

    // Track which component entities are visible
    let mut visible_components: HashSet<Entity> = HashSet::new();

    // Filter individual component displays by name
    for (entity, comp_name) in &components {
        let matches = filter.is_empty() || comp_name.0.to_lowercase().contains(&filter);

        if let Ok(mut node) = node_query.get_mut(entity) {
            node.display = if matches {
                Display::Flex
            } else {
                Display::None
            };
        }

        if matches {
            visible_components.insert(entity);
        }
    }

    // Hide group sections where all children are hidden
    for (group_entity, children) in &groups {
        let has_visible_child = children
            .iter()
            .any(|child| visible_components.contains(&child));

        if let Ok(mut node) = node_query.get_mut(group_entity) {
            node.display = if filter.is_empty() || has_visible_child {
                Display::Flex
            } else {
                Display::None
            };
        }
    }
}

/// Revert a single component on a prefab instance back to its baseline value.
fn revert_component_to_baseline(world: &mut World, entity: Entity, component_id: ComponentId) {
    use bevy::ecs::reflect::AppTypeRegistry;
    use bevy::reflect::serde::TypedReflectDeserializer;
    use serde::de::DeserializeSeed;

    let Some(baseline) = world.get::<jackdaw_jsn::JsnPrefabBaseline>(entity).cloned() else {
        return;
    };

    let Some(type_id) = world
        .components()
        .get_info(component_id)
        .and_then(|info| info.type_id())
    else {
        return;
    };

    let registry = world.resource::<AppTypeRegistry>().clone();
    let registry = registry.read();

    let Some(registration) = registry.get(type_id) else {
        return;
    };
    let type_path = registration.type_info().type_path_table().path();

    let Some(baseline_val) = baseline.components.get(type_path) else {
        return;
    };

    let Some(reflect_component) = registration.data::<ReflectComponent>() else {
        return;
    };

    let deserializer = TypedReflectDeserializer::new(registration, &registry);
    let Ok(reflected) = deserializer.deserialize(baseline_val) else {
        warn!("Failed to deserialize baseline for '{type_path}'");
        return;
    };

    let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        reflect_component.apply(world.entity_mut(entity), reflected.as_ref());
    }));

    drop(registry);

    // Trigger inspector rebuild
    world.entity_mut(entity).insert(InspectorDirty);
}