bevy_material_ui 0.2.7

Material Design 3 UI components for Bevy game engine
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
//! Material Design 3 Dialog component
//!
//! Dialogs inform users about a task and can contain critical information.
//! This module leverages native `BoxShadow` for elevation shadows.
//!
//! Reference: <https://m3.material.io/components/dialogs/overview>

use bevy::ecs::system::ParamSet;
use bevy::picking::Pickable;
use bevy::prelude::*;
use bevy::ui::BoxShadow;
use bevy::ui::FocusPolicy;

use crate::{
    elevation::Elevation,
    i18n::LocalizedText,
    telemetry::{InsertTestIdIfExists, TelemetryConfig, TestId},
    theme::MaterialTheme,
    tokens::{CornerRadius, Spacing},
};

/// Plugin for the dialog component
pub struct DialogPlugin;

impl Plugin for DialogPlugin {
    fn build(&self, app: &mut App) {
        if !app.is_plugin_added::<crate::MaterialUiCorePlugin>() {
            app.add_plugins(crate::MaterialUiCorePlugin);
        }
        app.add_message::<DialogOpenEvent>()
            .add_message::<DialogCloseEvent>()
            .add_message::<DialogConfirmEvent>()
            .init_resource::<DialogSpawnCounter>()
            .init_resource::<DialogOpenStack>()
            .add_systems(Startup, setup_dialog_overlay)
            .add_systems(
                Update,
                (
                    dialog_promote_to_overlay_system,
                    dialog_bring_to_front_on_open_system,
                    dialog_layer_z_index_system,
                    dialog_layer_visibility_system,
                    dialog_position_system,
                    dialog_mark_just_opened_system,
                    dialog_dismiss_on_scrim_click_system,
                    dialog_clear_just_opened_system,
                    dialog_dismiss_on_escape_system,
                    dialog_visibility_system,
                    dialog_scrim_visibility_system,
                    dialog_pickable_system,
                    dialog_scrim_pickable_system,
                    dialog_shadow_system,
                    dialog_telemetry_system,
                    dialog_scrim_telemetry_system,
                ),
            );
    }
}

/// Overlay root for dialog layers.
#[derive(Component)]
struct DialogOverlay;

/// Root entity that holds a dialog + its scrim.
#[derive(Component, Clone, Copy, Debug, PartialEq, Eq)]
struct DialogLayerRootFor(Entity);

/// Override which UI element's rect is used as the dialog's placement bounds.
///
/// By default (when this component is not present), dialogs are anchored to their original
/// parent at spawn time.
///
/// You can provide your own anchor node by inserting `MaterialDialogAnchor(your_anchor_entity)`
/// on the dialog entity. This is especially useful for positioning relative to a trigger button
/// or a custom layout container.
#[derive(Component, Clone, Copy, Debug, PartialEq, Eq)]
pub struct MaterialDialogAnchor(pub Entity);

/// Controls how the dialog is positioned relative to its `MaterialDialogAnchor`.
#[derive(Component, Debug, Clone, Copy, PartialEq)]
pub enum MaterialDialogPlacement {
    /// Center the dialog within the anchor bounds.
    CenterInAnchor,
    /// Center the dialog within the window/viewport.
    ///
    /// This ignores the anchor bounds and instead centers within the dialog overlay.
    /// Useful for top-level dialogs or examples where you don't have a convenient anchor entity.
    CenterInViewport,
    /// Place the dialog below the anchor.
    BelowAnchor {
        /// Gap below the anchor (logical px).
        gap_px: f32,
    },
    /// Place the dialog above the anchor.
    AboveAnchor {
        /// Gap above the anchor (logical px).
        gap_px: f32,
    },
    /// Place the dialog to the right of the anchor.
    RightOfAnchor {
        /// Gap to the right of the anchor (logical px).
        gap_px: f32,
    },
    /// Place the dialog to the left of the anchor.
    LeftOfAnchor {
        /// Gap to the left of the anchor (logical px).
        gap_px: f32,
    },
}

impl Default for MaterialDialogPlacement {
    fn default() -> Self {
        Self::CenterInAnchor
    }
}

impl MaterialDialogPlacement {
    pub fn center_in_viewport() -> Self {
        Self::CenterInViewport
    }

    pub fn below_anchor(gap_px: f32) -> Self {
        Self::BelowAnchor { gap_px }
    }

    pub fn above_anchor(gap_px: f32) -> Self {
        Self::AboveAnchor { gap_px }
    }

    pub fn right_of_anchor(gap_px: f32) -> Self {
        Self::RightOfAnchor { gap_px }
    }

    pub fn left_of_anchor(gap_px: f32) -> Self {
        Self::LeftOfAnchor { gap_px }
    }
}

/// Monotonic spawn counter used to produce stable z-ordering.
#[derive(Resource, Default)]
struct DialogSpawnCounter(u64);

/// Stable spawn order for dialogs.
#[derive(Component, Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
struct DialogSpawnOrder(u64);

/// Marker for dialogs that opened this frame.
#[derive(Component)]
struct DialogJustOpened;

/// Cached open stack ordered from bottom -> top.
#[derive(Resource, Default)]
struct DialogOpenStack {
    ordered: Vec<Entity>,
}

fn setup_dialog_overlay(mut commands: Commands) {
    // Full-screen container used as a portal destination for dialogs.
    // Must NOT be pickable so it doesn't interfere with input.
    commands.spawn((
        DialogOverlay,
        Node {
            position_type: PositionType::Absolute,
            width: Val::Percent(100.0),
            height: Val::Percent(100.0),
            top: Val::Px(0.0),
            left: Val::Px(0.0),
            ..default()
        },
        GlobalZIndex(9000),
        Pickable::IGNORE,
    ));
}

/// Promote newly spawned dialogs into the global overlay so they're not clipped by
/// parent layout/overflow, while still using their original parent as an anchor.
fn dialog_promote_to_overlay_system(
    mut commands: Commands,
    theme: Res<MaterialTheme>,
    overlay_query: Query<Entity, With<DialogOverlay>>,
    mut spawn_counter: ResMut<DialogSpawnCounter>,
    added_dialogs: Query<(Entity, Option<&ChildOf>, &MaterialDialog), Added<MaterialDialog>>,
    existing_scrims: Query<(Entity, &DialogScrimFor), With<DialogScrim>>,
    existing_anchors: Query<&MaterialDialogAnchor>,
    existing_placements: Query<&MaterialDialogPlacement>,
) {
    let Some(overlay) = overlay_query.iter().next() else {
        return;
    };

    for (dialog_entity, parent, dialog) in added_dialogs.iter() {
        // Anchor placement to the caller-provided anchor if available.
        // Otherwise: use original parent if present, else fall back to the overlay.
        let anchor = existing_anchors
            .get(dialog_entity)
            .map(|a| a.0)
            .unwrap_or_else(|_| parent.map(|p| p.parent()).unwrap_or(overlay));

        // Ensure we always have a stable anchor available after promotion (ChildOf changes).
        commands
            .entity(dialog_entity)
            .insert(MaterialDialogAnchor(anchor));

        // Default placement if none was specified by caller.
        if existing_placements.get(dialog_entity).is_err() {
            commands
                .entity(dialog_entity)
                .insert(MaterialDialogPlacement::default());
        }

        // Assign stable spawn order for stacking.
        spawn_counter.0 += 1;
        let spawn_order = DialogSpawnOrder(spawn_counter.0);
        commands.entity(dialog_entity).insert(spawn_order);

        // Create a per-dialog layer root under the overlay.
        // Visibility is synced to the dialog's open state.
        let layer_root = commands
            .spawn((
                DialogLayerRootFor(dialog_entity),
                Node {
                    position_type: PositionType::Absolute,
                    left: Val::Px(0.0),
                    top: Val::Px(0.0),
                    width: Val::Percent(100.0),
                    height: Val::Percent(100.0),
                    display: Display::None,
                    ..default()
                },
            ))
            .id();

        // Attach the layer root to overlay, and move the dialog under it.
        commands.entity(overlay).add_child(layer_root);
        commands.entity(layer_root).add_child(dialog_entity);

        // Ensure dialog surface is always above its scrim.
        commands.entity(dialog_entity).insert((
            ZIndex(1),
            FocusPolicy::Block,
            // Dialog surface should never allow click-through.
            Pickable {
                should_block_lower: true,
                is_hoverable: false,
            },
        ));

        // Ensure we have a scrim for this dialog.
        // - If the user already spawned one via `create_dialog_scrim_for`, reuse it.
        // - Otherwise, spawn our default scrim.
        let scrim_entity = existing_scrims
            .iter()
            .find_map(|(entity, for_dialog)| (for_dialog.0 == dialog_entity).then_some(entity))
            .unwrap_or_else(|| {
                commands
                    .spawn((
                        DialogScrim,
                        DialogScrimFor(dialog_entity),
                        Node {
                            display: Display::None,
                            position_type: PositionType::Absolute,
                            left: Val::Px(0.0),
                            top: Val::Px(0.0),
                            width: Val::Percent(100.0),
                            height: Val::Percent(100.0),
                            ..default()
                        },
                        BackgroundColor(dialog.scrim_color(&theme)),
                        ZIndex(0),
                    ))
                    .id()
            });

        // Make the scrim a proper input blocker for bevy_ui and bevy_picking.
        commands.entity(scrim_entity).remove::<GlobalZIndex>();
        commands.entity(scrim_entity).insert((
            // Required for bevy_ui `Interaction` updates.
            Button,
            Interaction::None,
            FocusPolicy::Block,
            if dialog.modal {
                Pickable {
                    should_block_lower: true,
                    is_hoverable: true,
                }
            } else {
                Pickable::IGNORE
            },
            ZIndex(0),
        ));

        commands.entity(layer_root).add_child(scrim_entity);
    }
}

/// Sync the per-dialog layer root's visibility (and scrim visibility) with dialog state.
fn dialog_layer_visibility_system(
    dialogs: Query<&MaterialDialog>,
    mut sets: ParamSet<(
        Query<(&DialogLayerRootFor, &mut Node)>,
        Query<(&DialogScrimFor, &mut Node), With<DialogScrim>>,
    )>,
) {
    for (for_dialog, mut root_node) in sets.p0().iter_mut() {
        let Ok(dialog) = dialogs.get(for_dialog.0) else {
            root_node.display = Display::None;
            continue;
        };

        root_node.display = if dialog.open {
            Display::Flex
        } else {
            Display::None
        };
    }

    for (for_dialog, mut scrim_node) in sets.p1().iter_mut() {
        let Ok(dialog) = dialogs.get(for_dialog.0) else {
            scrim_node.display = Display::None;
            continue;
        };

        // Only show the scrim when modal.
        scrim_node.display = if dialog.open && dialog.modal {
            Display::Flex
        } else {
            Display::None
        };
    }
}

/// Maintain deterministic layering (nested dialogs above parents).
fn dialog_layer_z_index_system(
    mut commands: Commands,
    dialogs: Query<(Entity, &MaterialDialog, &DialogSpawnOrder)>,
    mut roots: Query<(Entity, &DialogLayerRootFor)>,
    scrims: Query<(Entity, &DialogScrimFor), With<DialogScrim>>,
    mut open_stack: ResMut<DialogOpenStack>,
) {
    // Collect all open dialogs sorted by spawn order.
    let mut open_dialogs: Vec<(Entity, DialogSpawnOrder)> = dialogs
        .iter()
        .filter_map(|(entity, dialog, order)| dialog.open.then_some((entity, *order)))
        .collect();
    open_dialogs.sort_by_key(|(_, order)| *order);
    open_stack.ordered = open_dialogs.iter().map(|(e, _)| *e).collect();

    // Assign z-index in increasing order, leaving room for other overlays.
    // Each dialog gets a root promoted at a unique GlobalZIndex.
    for (root_entity, for_dialog) in roots.iter_mut() {
        let Some((idx, _)) = open_dialogs
            .iter()
            .enumerate()
            .find(|(_, (dialog_entity, _))| *dialog_entity == for_dialog.0)
        else {
            // Closed dialogs can keep their current z.
            continue;
        };

        // Base above other modal UIs (date/time pickers use 9999).
        let z = 10000 + (idx as i32 * 2);
        commands.entity(root_entity).insert(GlobalZIndex(z));

        // Ensure scrim and dialog surface render above other UI as well.
        if let Some((scrim_entity, _)) = scrims
            .iter()
            .find(|(_, scrim_for)| scrim_for.0 == for_dialog.0)
        {
            commands.entity(scrim_entity).insert(GlobalZIndex(z));
        }

        commands.entity(for_dialog.0).insert(GlobalZIndex(z + 1));
    }
}

/// Bring newly opened dialogs to the top of the stack.
fn dialog_bring_to_front_on_open_system(
    mut commands: Commands,
    mut spawn_counter: ResMut<DialogSpawnCounter>,
    dialogs: Query<(Entity, &MaterialDialog), Changed<MaterialDialog>>,
    mut orders: Query<&mut DialogSpawnOrder>,
) {
    for (entity, dialog) in dialogs.iter() {
        if !dialog.open {
            continue;
        }

        spawn_counter.0 += 1;
        let new_order = DialogSpawnOrder(spawn_counter.0);

        if let Ok(mut order) = orders.get_mut(entity) {
            *order = new_order;
        } else {
            commands.entity(entity).insert(new_order);
        }
    }
}

/// Position dialogs relative to their original parent (anchor) rect.
///
/// This keeps dialogs independent of parent layout/clipping by rendering them in the overlay,
/// while still using the parent as the placement bounds.
fn dialog_position_system(
    mut dialogs: Query<(
        &MaterialDialog,
        Option<&MaterialDialogAnchor>,
        Option<&MaterialDialogPlacement>,
        &mut Node,
        &ComputedNode,
    )>,
    anchors: Query<(&UiGlobalTransform, &ComputedNode)>,
    roots: Query<&DialogLayerRootFor>,
    overlay_query: Query<(&UiGlobalTransform, &ComputedNode), With<DialogOverlay>>,
    windows: Query<&Window>,
) {
    let window = windows.iter().next();
    let scale_factor = window.map(|w| w.scale_factor()).unwrap_or(1.0);
    let window_physical_size = window.map(|w| {
        let mut size = w.physical_size().as_vec2();
        if size.x <= 0.0 || size.y <= 0.0 {
            size = Vec2::new(w.resolution.width(), w.resolution.height()) * w.scale_factor() as f32;
        }
        size
    });

    let (mut overlay_center, mut overlay_size) = overlay_query
        .iter()
        .next()
        .map(|(t, c)| (t.translation, c.size()))
        .unwrap_or((Vec2::ZERO, Vec2::ZERO));

    // If the overlay hasn't been laid out yet, fall back to the primary window size.
    if overlay_size.x <= 0.0 || overlay_size.y <= 0.0 {
        if let Some(window) = windows.iter().next() {
            let mut window_size = window.physical_size().as_vec2();

            if window_size.x <= 0.0 || window_size.y <= 0.0 {
                let logical = Vec2::new(window.resolution.width(), window.resolution.height());
                window_size = logical * window.scale_factor() as f32;
            }

            overlay_size = window_size;
            overlay_center = window_size / 2.0;
        }
    }

    let overlay_top_left = overlay_center - overlay_size / 2.0;

    for for_dialog in roots.iter() {
        let Ok((dialog, anchor, placement, mut dialog_node, dialog_computed)) =
            dialogs.get_mut(for_dialog.0)
        else {
            continue;
        };

        if !dialog.open {
            continue;
        }

        // Fullscreen dialogs just fill the overlay.
        if dialog.dialog_type == DialogType::FullScreen {
            dialog_node.left = Val::Px(0.0);
            dialog_node.top = Val::Px(0.0);
            continue;
        }

        let scale = scale_factor;

        let dialog_size_physical = dialog_computed.size();
        if dialog_size_physical.x <= 0.0 || dialog_size_physical.y <= 0.0 {
            // Not laid out yet.
            continue;
        }

        let placement = placement.copied().unwrap_or_default();

        let center_in_viewport = || {
            if let Some(window_size_physical) = window_physical_size {
                // Center within the window (physical pixels).
                (
                    (window_size_physical.x - dialog_size_physical.x) / 2.0,
                    (window_size_physical.y - dialog_size_physical.y) / 2.0,
                )
            } else {
                // Fallback to overlay size if window isn't available.
                (
                    overlay_top_left.x + (overlay_size.x - dialog_size_physical.x) / 2.0,
                    overlay_top_left.y + (overlay_size.y - dialog_size_physical.y) / 2.0,
                )
            }
        };

        let (screen_left_physical, screen_top_physical) = match placement {
            MaterialDialogPlacement::CenterInViewport => center_in_viewport(),
            other => {
                // All other placements require an anchor rect; fall back to viewport
                // if the anchor is unavailable or not yet laid out.
                if let Some(anchor) = anchor {
                    match anchors.get(anchor.0) {
                        Ok((anchor_transform, anchor_computed)) => {
                            // UiGlobalTransform and ComputedNode sizes are physical pixels.
                            let anchor_center_physical = anchor_transform.translation;
                            let anchor_size_physical = anchor_computed.size();
                            if anchor_size_physical.x <= 0.0 || anchor_size_physical.y <= 0.0 {
                                center_in_viewport()
                            } else {
                                let anchor_top_left_physical =
                                    anchor_center_physical - anchor_size_physical / 2.0;

                                match other {
                                    MaterialDialogPlacement::CenterInViewport => {
                                        center_in_viewport()
                                    }
                                    MaterialDialogPlacement::CenterInAnchor => (
                                        anchor_top_left_physical.x
                                            + (anchor_size_physical.x - dialog_size_physical.x)
                                                / 2.0,
                                        anchor_top_left_physical.y
                                            + (anchor_size_physical.y - dialog_size_physical.y)
                                                / 2.0,
                                    ),
                                    MaterialDialogPlacement::BelowAnchor { gap_px } => {
                                        let gap_physical = gap_px * scale;
                                        (
                                            anchor_top_left_physical.x
                                                + (anchor_size_physical.x
                                                    - dialog_size_physical.x)
                                                    / 2.0,
                                            anchor_top_left_physical.y
                                                + anchor_size_physical.y
                                                + gap_physical,
                                        )
                                    }
                                    MaterialDialogPlacement::AboveAnchor { gap_px } => {
                                        let gap_physical = gap_px * scale;
                                        (
                                            anchor_top_left_physical.x
                                                + (anchor_size_physical.x
                                                    - dialog_size_physical.x)
                                                    / 2.0,
                                            anchor_top_left_physical.y
                                                - dialog_size_physical.y
                                                - gap_physical,
                                        )
                                    }
                                    MaterialDialogPlacement::RightOfAnchor { gap_px } => {
                                        let gap_physical = gap_px * scale;
                                        (
                                            anchor_top_left_physical.x
                                                + anchor_size_physical.x
                                                + gap_physical,
                                            anchor_top_left_physical.y
                                                + (anchor_size_physical.y
                                                    - dialog_size_physical.y)
                                                    / 2.0,
                                        )
                                    }
                                    MaterialDialogPlacement::LeftOfAnchor { gap_px } => {
                                        let gap_physical = gap_px * scale;
                                        (
                                            anchor_top_left_physical.x
                                                - dialog_size_physical.x
                                                - gap_physical,
                                            anchor_top_left_physical.y
                                                + (anchor_size_physical.y
                                                    - dialog_size_physical.y)
                                                    / 2.0,
                                        )
                                    }
                                }
                            }
                        }
                        Err(_) => center_in_viewport(),
                    }
                } else {
                    center_in_viewport()
                }
            }
        };

        // Convert to logical pixels relative to the overlay.
        let left = (screen_left_physical - overlay_top_left.x) / scale;
        let top = (screen_top_physical - overlay_top_left.y) / scale;

        dialog_node.left = Val::Px(left);
        dialog_node.top = Val::Px(top);
    }
}

fn dialog_dismiss_on_scrim_click_system(
    mouse: Res<ButtonInput<MouseButton>>,
    mut close_events: MessageWriter<DialogCloseEvent>,
    mut dialogs: Query<&mut MaterialDialog>,
    just_opened: Query<(), With<DialogJustOpened>>,
    mut scrims: Query<(&DialogScrimFor, &Interaction), (With<DialogScrim>, Changed<Interaction>)>,
) {
    for (for_dialog, interaction) in scrims.iter_mut() {
        if *interaction != Interaction::Pressed {
            continue;
        }

        // Ignore scrim presses on the same frame the dialog was opened.
        if just_opened.get(for_dialog.0).is_ok() {
            continue;
        }

        // Avoid immediately dismissing a dialog when its scrim becomes visible while the
        // mouse button is still held down from clicking the trigger.
        if !mouse.just_pressed(MouseButton::Left) {
            continue;
        }

        let Ok(mut dialog) = dialogs.get_mut(for_dialog.0) else {
            continue;
        };
        if !dialog.open || !dialog.dismiss_on_scrim_click {
            continue;
        }

        dialog.open = false;
        close_events.write(DialogCloseEvent {
            entity: for_dialog.0,
            dismissed: true,
        });
    }
}

/// Mark dialogs that opened this frame so scrim clicks can be ignored.
fn dialog_mark_just_opened_system(
    mut commands: Commands,
    dialogs: Query<(Entity, &MaterialDialog), Changed<MaterialDialog>>,
) {
    for (entity, dialog) in dialogs.iter() {
        if dialog.open {
            commands.entity(entity).insert(DialogJustOpened);
        }
    }
}

/// Clear the just-opened marker after scrim handling.
fn dialog_clear_just_opened_system(
    mut commands: Commands,
    dialogs: Query<Entity, With<DialogJustOpened>>,
) {
    for entity in dialogs.iter() {
        commands.entity(entity).remove::<DialogJustOpened>();
    }
}

fn dialog_dismiss_on_escape_system(
    keys: Res<ButtonInput<KeyCode>>,
    open_stack: Res<DialogOpenStack>,
    mut close_events: MessageWriter<DialogCloseEvent>,
    mut dialogs: Query<&mut MaterialDialog>,
) {
    if !keys.just_pressed(KeyCode::Escape) {
        return;
    }

    let Some(&topmost) = open_stack.ordered.last() else {
        return;
    };

    let Ok(mut dialog) = dialogs.get_mut(topmost) else {
        return;
    };

    if !dialog.open || !dialog.dismiss_on_escape {
        return;
    }

    dialog.open = false;
    close_events.write(DialogCloseEvent {
        entity: topmost,
        dismissed: true,
    });
}

/// Update dialog pickability when dialog modality changes.
///
/// This prevents clicks from going through the dialog surface to UI behind it.
fn dialog_pickable_system(
    mut commands: Commands,
    changed_dialogs: Query<(Entity, &MaterialDialog), Changed<MaterialDialog>>,
    mut pickables: Query<&mut Pickable>,
) {
    if changed_dialogs.is_empty() {
        return;
    }

    for (entity, _dialog) in changed_dialogs.iter() {
        // Dialog surfaces should always block click-through. Modality is enforced by the scrim.
        let pickable = Pickable {
            should_block_lower: true,
            is_hoverable: false,
        };

        if let Ok(mut existing) = pickables.get_mut(entity) {
            *existing = pickable;
        } else {
            commands.entity(entity).insert(pickable);
        }
    }
}

fn dialog_telemetry_system(
    mut commands: Commands,
    telemetry: Option<Res<TelemetryConfig>>,
    dialogs: Query<(&TestId, &Children), With<MaterialDialog>>,
    children_query: Query<&Children>,
    headlines: Query<(), With<DialogHeadline>>,
    contents: Query<(), With<DialogContent>>,
    actions: Query<(), With<DialogActions>>,
) {
    let Some(telemetry) = telemetry else {
        return;
    };
    if !telemetry.enabled {
        return;
    }

    for (test_id, children) in dialogs.iter() {
        let base = test_id.id();

        let mut found_headline = false;
        let mut found_content = false;
        let mut found_actions = false;

        let mut stack: Vec<Entity> = children.iter().collect();
        while let Some(entity) = stack.pop() {
            if !found_headline && headlines.get(entity).is_ok() {
                found_headline = true;
                commands.queue(InsertTestIdIfExists {
                    entity,
                    id: format!("{base}/headline"),
                });
            }

            if !found_content && contents.get(entity).is_ok() {
                found_content = true;
                commands.queue(InsertTestIdIfExists {
                    entity,
                    id: format!("{base}/content"),
                });
            }

            if !found_actions && actions.get(entity).is_ok() {
                found_actions = true;
                commands.queue(InsertTestIdIfExists {
                    entity,
                    id: format!("{base}/actions"),
                });
            }

            if found_headline && found_content && found_actions {
                break;
            }

            if let Ok(children) = children_query.get(entity) {
                stack.extend(children.iter());
            }
        }
    }
}

fn dialog_scrim_telemetry_system(
    mut commands: Commands,
    telemetry: Option<Res<TelemetryConfig>>,
    scrims: Query<(Entity, &DialogScrimFor), With<DialogScrim>>,
    dialogs: Query<&TestId, With<MaterialDialog>>,
) {
    let Some(telemetry) = telemetry else {
        return;
    };
    if !telemetry.enabled {
        return;
    }

    for (scrim_entity, for_dialog) in scrims.iter() {
        let Ok(dialog_id) = dialogs.get(for_dialog.0) else {
            continue;
        };
        let base = dialog_id.id();

        commands.queue(InsertTestIdIfExists {
            entity: scrim_entity,
            id: format!("{base}/scrim"),
        });
    }
}

/// Dialog types
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum DialogType {
    /// Basic dialog with title and content
    #[default]
    Basic,
    /// Full-screen dialog
    FullScreen,
}

/// Material dialog component
#[derive(Component)]
pub struct MaterialDialog {
    /// Dialog type
    pub dialog_type: DialogType,
    /// Whether the dialog is currently open
    pub open: bool,
    /// Dialog title
    pub title: Option<String>,
    /// Dialog icon
    pub icon: Option<String>,
    /// Whether clicking the scrim closes the dialog
    pub dismiss_on_scrim_click: bool,
    /// Whether pressing Escape closes the dialog
    pub dismiss_on_escape: bool,

    /// Whether the dialog should behave as a modal (block pointer interactions behind it).
    ///
    /// When `true`, the dialog scrim will be pickable and will block lower entities from receiving
    /// pointer interactions. When `false`, the scrim will be click-through.
    pub modal: bool,
}

impl MaterialDialog {
    /// Create a new dialog
    pub fn new() -> Self {
        Self {
            dialog_type: DialogType::default(),
            open: false,
            title: None,
            icon: None,
            dismiss_on_scrim_click: true,
            dismiss_on_escape: true,
            modal: true,
        }
    }

    /// Set the dialog type
    pub fn with_type(mut self, dialog_type: DialogType) -> Self {
        self.dialog_type = dialog_type;
        self
    }

    /// Set the title
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Set the icon
    pub fn icon(mut self, icon: impl Into<String>) -> Self {
        self.icon = Some(icon.into());
        self
    }

    /// Set initial open state
    pub fn open(mut self, open: bool) -> Self {
        self.open = open;
        self
    }

    /// Disable scrim click dismissal
    pub fn no_scrim_dismiss(mut self) -> Self {
        self.dismiss_on_scrim_click = false;
        self
    }

    /// Disable escape key dismissal
    pub fn no_escape_dismiss(mut self) -> Self {
        self.dismiss_on_escape = false;
        self
    }

    /// Set whether the dialog is modal (blocks pointer interactions behind it).
    pub fn modal(mut self, modal: bool) -> Self {
        self.modal = modal;
        self
    }

    /// Get the surface color
    pub fn surface_color(&self, theme: &MaterialTheme) -> Color {
        theme.surface_container_high
    }

    /// Get the scrim color
    pub fn scrim_color(&self, theme: &MaterialTheme) -> Color {
        theme.scrim.with_alpha(0.32)
    }

    /// Get the title color
    pub fn title_color(&self, theme: &MaterialTheme) -> Color {
        theme.on_surface
    }

    /// Get the content color
    pub fn content_color(&self, theme: &MaterialTheme) -> Color {
        theme.on_surface_variant
    }

    /// Get the icon color
    pub fn icon_color(&self, theme: &MaterialTheme) -> Color {
        theme.secondary
    }

    /// Get the elevation
    pub fn elevation(&self) -> Elevation {
        Elevation::Level3
    }
}

impl Default for MaterialDialog {
    fn default() -> Self {
        Self::new()
    }
}

/// Event to open a dialog
#[derive(Event, bevy::prelude::Message)]
pub struct DialogOpenEvent {
    pub entity: Entity,
}

/// Event when dialog is closed
#[derive(Event, bevy::prelude::Message)]
pub struct DialogCloseEvent {
    pub entity: Entity,
    /// Whether it was dismissed (scrim/escape) vs confirmed
    pub dismissed: bool,
}

/// Event when dialog action is confirmed
#[derive(Event, bevy::prelude::Message)]
pub struct DialogConfirmEvent {
    pub entity: Entity,
}

/// Dialog dimensions
pub const DIALOG_MIN_WIDTH: f32 = 280.0;
pub const DIALOG_MAX_WIDTH: f32 = 560.0;

/// System to handle dialog visibility
fn dialog_visibility_system(
    mut dialogs: Query<(&MaterialDialog, &mut Node), Changed<MaterialDialog>>,
) {
    for (dialog, mut node) in dialogs.iter_mut() {
        node.display = if dialog.open {
            Display::Flex
        } else {
            Display::None
        };
    }
}

/// System to update dialog shadows using native BoxShadow
fn dialog_shadow_system(
    mut dialogs: Query<(&MaterialDialog, &mut BoxShadow), Changed<MaterialDialog>>,
) {
    for (dialog, mut shadow) in dialogs.iter_mut() {
        // Only show shadow when dialog is open
        if dialog.open {
            *shadow = dialog.elevation().to_box_shadow();
        } else {
            *shadow = BoxShadow::default();
        }
    }
}

/// Keep dialog scrims in sync with their dialog's open state.
fn dialog_scrim_visibility_system(
    dialogs: Query<&MaterialDialog>,
    mut scrims: Query<(&DialogScrimFor, &mut Node), With<DialogScrim>>,
) {
    for (for_dialog, mut node) in scrims.iter_mut() {
        let Ok(dialog) = dialogs.get(for_dialog.0) else {
            node.display = Display::None;
            continue;
        };

        node.display = if dialog.open && dialog.modal {
            Display::Flex
        } else {
            Display::None
        };
    }
}

/// Update scrim pickability when dialog modality changes.
fn dialog_scrim_pickable_system(
    dialogs: Query<&MaterialDialog>,
    mut scrims: Query<(&DialogScrimFor, &mut Pickable), With<DialogScrim>>,
) {
    for (for_dialog, mut pickable) in scrims.iter_mut() {
        let Ok(dialog) = dialogs.get(for_dialog.0) else {
            *pickable = Pickable::IGNORE;
            continue;
        };

        // Scrims should *only* block pointer interactions while visible.
        // Otherwise they can accidentally intercept clicks even when hidden.
        *pickable = if dialog.open && dialog.modal {
            Pickable {
                should_block_lower: true,
                is_hoverable: true,
            }
        } else {
            Pickable::IGNORE
        };
    }
}

/// Builder for dialogs
pub struct DialogBuilder {
    dialog: MaterialDialog,
    title_key: Option<String>,
}

impl DialogBuilder {
    /// Create a new dialog builder
    pub fn new() -> Self {
        Self {
            dialog: MaterialDialog::new(),
            title_key: None,
        }
    }

    /// Set dialog type
    pub fn dialog_type(mut self, dialog_type: DialogType) -> Self {
        self.dialog.dialog_type = dialog_type;
        self
    }

    /// Make full-screen dialog
    pub fn full_screen(self) -> Self {
        self.dialog_type(DialogType::FullScreen)
    }

    /// Set title
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.dialog.title = Some(title.into());
        self
    }

    /// Set title from an i18n key.
    pub fn title_key(mut self, key: impl Into<String>) -> Self {
        self.dialog.title = Some(String::new());
        self.title_key = Some(key.into());
        self
    }

    /// Set icon
    pub fn icon(mut self, icon: impl Into<String>) -> Self {
        self.dialog.icon = Some(icon.into());
        self
    }

    /// Start open
    pub fn open(mut self) -> Self {
        self.dialog.open = true;
        self
    }

    /// Disable scrim dismissal
    pub fn no_scrim_dismiss(mut self) -> Self {
        self.dialog.dismiss_on_scrim_click = false;
        self
    }

    /// Disable escape dismissal
    pub fn no_escape_dismiss(mut self) -> Self {
        self.dialog.dismiss_on_escape = false;
        self
    }

    /// Set whether the dialog is modal (blocks pointer interactions behind it).
    pub fn modal(mut self, modal: bool) -> Self {
        self.dialog.modal = modal;
        self
    }

    /// Build the dialog bundle with native BoxShadow
    pub fn build(self, theme: &MaterialTheme) -> impl Bundle {
        let bg_color = self.dialog.surface_color(theme);
        let is_full_screen = self.dialog.dialog_type == DialogType::FullScreen;
        let modal = self.dialog.modal;

        (
            self.dialog,
            Node {
                display: Display::None, // Hidden by default
                position_type: PositionType::Absolute,
                width: if is_full_screen {
                    Val::Percent(100.0)
                } else {
                    Val::Auto
                },
                height: if is_full_screen {
                    Val::Percent(100.0)
                } else {
                    Val::Auto
                },
                min_width: if is_full_screen {
                    Val::Auto
                } else {
                    Val::Px(DIALOG_MIN_WIDTH)
                },
                max_width: if is_full_screen {
                    Val::Auto
                } else {
                    Val::Px(DIALOG_MAX_WIDTH)
                },
                padding: UiRect::all(Val::Px(Spacing::EXTRA_LARGE)),
                flex_direction: FlexDirection::Column,
                border_radius: BorderRadius::all(Val::Px(if is_full_screen {
                    0.0
                } else {
                    CornerRadius::EXTRA_LARGE
                })),
                ..default()
            },
            BackgroundColor(bg_color),
            // Native Bevy 0.17 shadow support (starts hidden since dialog is closed)
            BoxShadow::default(),
            // Ensure modal dialogs block pointer interactions behind the dialog surface.
            if modal {
                Pickable {
                    should_block_lower: true,
                    is_hoverable: false,
                }
            } else {
                Pickable {
                    should_block_lower: false,
                    is_hoverable: false,
                }
            },
        )
    }
}

impl Default for DialogBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// Marker for dialog scrim overlay
#[derive(Component)]
pub struct DialogScrim;

/// Associates a dialog scrim with a specific dialog entity.
#[derive(Component, Clone, Copy, Debug, PartialEq, Eq)]
pub struct DialogScrimFor(pub Entity);

/// Marker for dialog headline/title
#[derive(Component)]
pub struct DialogHeadline;

/// Marker for dialog content area
#[derive(Component)]
pub struct DialogContent;

/// Marker for dialog actions area
#[derive(Component)]
pub struct DialogActions;

/// Helper to create a dialog scrim
pub fn create_dialog_scrim(theme: &MaterialTheme) -> impl Bundle {
    (
        DialogScrim,
        Node {
            position_type: PositionType::Absolute,
            left: Val::Px(0.0),
            top: Val::Px(0.0),
            width: Val::Percent(100.0),
            height: Val::Percent(100.0),
            justify_content: JustifyContent::Center,
            align_items: AlignItems::Center,
            ..default()
        },
        BackgroundColor(theme.scrim.with_alpha(0.32)),
        // Default scrim behavior is modal: block pointer interactions behind it.
        Pickable {
            should_block_lower: true,
            is_hoverable: false,
        },
    )
}

/// Helper to create a dialog scrim linked to a specific dialog entity.
///
/// The scrim starts hidden and is shown/hidden automatically based on the dialog's `open` state.
/// When `modal` is true, the scrim blocks pointer interactions behind it.
pub fn create_dialog_scrim_for(
    theme: &MaterialTheme,
    dialog_entity: Entity,
    modal: bool,
) -> impl Bundle {
    (
        DialogScrim,
        DialogScrimFor(dialog_entity),
        Node {
            display: Display::None, // Hidden by default; synced by system.
            position_type: PositionType::Absolute,
            left: Val::Px(0.0),
            top: Val::Px(0.0),
            width: Val::Percent(100.0),
            height: Val::Percent(100.0),
            justify_content: JustifyContent::Center,
            align_items: AlignItems::Center,
            ..default()
        },
        BackgroundColor(theme.scrim.with_alpha(0.32)),
        if modal {
            Pickable {
                should_block_lower: true,
                is_hoverable: false,
            }
        } else {
            Pickable::IGNORE
        },
    )
}

// ============================================================================
// Spawn Traits for ChildSpawnerCommands
// ============================================================================

/// Extension trait to spawn Material dialogs as children
///
/// This trait provides a clean API for spawning dialogs within UI hierarchies.
///
/// ## Example:
/// ```no_run
/// use bevy::prelude::*;
/// use bevy_material_ui::dialog::SpawnDialogChild;
/// use bevy_material_ui::theme::MaterialTheme;
///
/// fn setup(mut commands: Commands, theme: Res<MaterialTheme>) {
///     commands.spawn(Node::default()).with_children(|children| {
///         children.spawn_dialog(&theme, "Confirm", |dialog| {
///             dialog.spawn((Text::new("Are you sure?"), TextColor(theme.on_surface)));
///         });
///     });
/// }
/// ```
pub trait SpawnDialogChild {
    /// Spawn a dialog with headline and content builder
    fn spawn_dialog(
        &mut self,
        theme: &MaterialTheme,
        headline: impl Into<String>,
        with_content: impl FnOnce(&mut ChildSpawnerCommands),
    );

    /// Spawn a dialog with full builder control
    fn spawn_dialog_with(
        &mut self,
        theme: &MaterialTheme,
        builder: DialogBuilder,
        with_content: impl FnOnce(&mut ChildSpawnerCommands),
    );

    /// Spawn a dialog scrim overlay
    fn spawn_dialog_scrim(&mut self, theme: &MaterialTheme);
}

impl SpawnDialogChild for ChildSpawnerCommands<'_> {
    fn spawn_dialog(
        &mut self,
        theme: &MaterialTheme,
        headline: impl Into<String>,
        with_content: impl FnOnce(&mut ChildSpawnerCommands),
    ) {
        self.spawn_dialog_with(theme, DialogBuilder::new().title(headline), with_content);
    }

    fn spawn_dialog_with(
        &mut self,
        theme: &MaterialTheme,
        builder: DialogBuilder,
        with_content: impl FnOnce(&mut ChildSpawnerCommands),
    ) {
        let title_text: Option<String> = builder.dialog.title.clone();
        let title_key: Option<String> = builder.title_key.clone();
        let headline_color = theme.on_surface;

        self.spawn(builder.build(theme)).with_children(|dialog| {
            // Headline/Title
            if let Some(ref title) = title_text {
                if let Some(key) = title_key.as_deref() {
                    dialog.spawn((
                        DialogHeadline,
                        Text::new(""),
                        LocalizedText::new(key),
                        TextFont {
                            font_size: 24.0,
                            ..default()
                        },
                        TextColor(headline_color),
                        Node {
                            margin: UiRect::bottom(Val::Px(16.0)),
                            ..default()
                        },
                    ));
                } else {
                    dialog.spawn((
                        DialogHeadline,
                        Text::new(title.as_str()),
                        TextFont {
                            font_size: 24.0,
                            ..default()
                        },
                        TextColor(headline_color),
                        Node {
                            margin: UiRect::bottom(Val::Px(16.0)),
                            ..default()
                        },
                    ));
                }
            }

            // Content area
            dialog
                .spawn((
                    DialogContent,
                    Node {
                        flex_direction: FlexDirection::Column,
                        flex_grow: 1.0,
                        ..default()
                    },
                ))
                .with_children(with_content);
        });
    }

    fn spawn_dialog_scrim(&mut self, theme: &MaterialTheme) {
        self.spawn(create_dialog_scrim(theme));
    }
}