1use std::collections::{HashMap, HashSet};
2
3use sui_core::{Point, WidgetId};
4
5use crate::{CommandKey, widget::FocusRequest};
6
7const MAX_OVERLAY_TRACE_SAMPLES: usize = 512;
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11pub enum OverlayKind {
12 Tooltip,
13 Popover,
14 Menu,
15 Dialog,
16 Sheet,
17 CommandPalette,
18 Notification,
19 DragPreview,
20 Custom,
21}
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
24pub enum OverlayModality {
25 #[default]
26 Modeless,
27 Modal,
28}
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
31pub enum OverlayInitialFocus {
32 #[default]
33 None,
34 Owner,
35 FirstFocusable,
36}
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
40pub struct OverlayFocusBehavior {
41 pub initial: OverlayInitialFocus,
42 pub trap: bool,
43 pub restore: bool,
44}
45
46impl OverlayFocusBehavior {
47 pub const NONE: Self = Self {
48 initial: OverlayInitialFocus::None,
49 trap: false,
50 restore: false,
51 };
52
53 pub const RESTORE: Self = Self {
54 initial: OverlayInitialFocus::None,
55 trap: false,
56 restore: true,
57 };
58
59 pub const CONTAINED: Self = Self {
60 initial: OverlayInitialFocus::FirstFocusable,
61 trap: true,
62 restore: true,
63 };
64}
65
66impl Default for OverlayFocusBehavior {
67 fn default() -> Self {
68 Self::RESTORE
69 }
70}
71
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
73pub struct OverlayDismissPolicy {
74 pub escape: bool,
75 pub outside_pointer: bool,
76}
77
78impl OverlayDismissPolicy {
79 pub const NONE: Self = Self {
80 escape: false,
81 outside_pointer: false,
82 };
83
84 pub const TRANSIENT: Self = Self {
85 escape: true,
86 outside_pointer: true,
87 };
88}
89
90impl Default for OverlayDismissPolicy {
91 fn default() -> Self {
92 Self::TRANSIENT
93 }
94}
95
96#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
102pub struct OverlayOptions {
103 pub kind: OverlayKind,
104 pub modality: OverlayModality,
105 pub dismiss: OverlayDismissPolicy,
106 pub focus: OverlayFocusBehavior,
107}
108
109impl OverlayOptions {
110 pub const fn new(kind: OverlayKind) -> Self {
111 Self {
112 kind,
113 modality: OverlayModality::Modeless,
114 dismiss: OverlayDismissPolicy::TRANSIENT,
115 focus: OverlayFocusBehavior::RESTORE,
116 }
117 }
118
119 pub const fn modal(mut self, modal: bool) -> Self {
120 self.modality = if modal {
121 OverlayModality::Modal
122 } else {
123 OverlayModality::Modeless
124 };
125 self
126 }
127
128 pub const fn dismiss(mut self, dismiss: OverlayDismissPolicy) -> Self {
129 self.dismiss = dismiss;
130 self
131 }
132
133 pub const fn focus(mut self, focus: OverlayFocusBehavior) -> Self {
134 self.focus = focus;
135 self
136 }
137}
138
139#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
140pub enum OverlayDismissReason {
141 Escape,
142 OutsidePointer,
143 Programmatic,
144}
145
146#[derive(Debug, Clone, Copy, PartialEq)]
147pub struct OverlayDismissRequest {
148 pub reason: OverlayDismissReason,
149 pub pointer_position: Option<Point>,
150}
151
152impl OverlayDismissRequest {
153 pub const fn new(reason: OverlayDismissReason) -> Self {
154 Self {
155 reason,
156 pointer_position: None,
157 }
158 }
159
160 pub const fn at(mut self, position: Point) -> Self {
161 self.pointer_position = Some(position);
162 self
163 }
164}
165
166pub const OVERLAY_DISMISS_REQUEST: CommandKey<OverlayDismissRequest> =
168 CommandKey::new("sui.overlay.dismiss");
169
170#[derive(Debug, Clone, PartialEq, Eq)]
171pub struct OverlaySnapshot {
172 pub owner: WidgetId,
173 pub parent: Option<WidgetId>,
174 pub surfaces: Vec<WidgetId>,
175 pub options: OverlayOptions,
176 pub order: usize,
177}
178
179#[derive(Debug, Clone, PartialEq, Eq, Default)]
180pub struct OverlayManagerSnapshot {
181 pub overlays: Vec<OverlaySnapshot>,
182 pub active_modal: Option<WidgetId>,
183 pub focus_trap: Option<WidgetId>,
184}
185
186#[derive(Debug, Clone, Copy, PartialEq, Eq)]
187pub enum OverlayTraceKind {
188 Opened,
189 Closed,
190 Reordered,
191 DismissRequested,
192 FocusEntered,
193 FocusRestored,
194}
195
196#[derive(Debug, Clone, PartialEq, Eq)]
197pub struct OverlayTraceSample {
198 pub owner: WidgetId,
199 pub kind: OverlayTraceKind,
200 pub overlay_kind: OverlayKind,
201 pub reason: Option<OverlayDismissReason>,
202}
203
204#[derive(Default)]
205pub(crate) struct OverlayManager {
206 active: Vec<OverlaySnapshot>,
207 focus_origins: HashMap<WidgetId, Option<WidgetId>>,
208 traces: Vec<OverlayTraceSample>,
209}
210
211impl OverlayManager {
212 pub(crate) fn sync(
213 &mut self,
214 next: Vec<OverlaySnapshot>,
215 graph: &crate::WidgetGraph,
216 focused: Option<WidgetId>,
217 ) -> Option<FocusRequest> {
218 let previous_by_owner = self
219 .active
220 .iter()
221 .map(|entry| (entry.owner, entry.clone()))
222 .collect::<HashMap<_, _>>();
223 let next_owners = next.iter().map(|entry| entry.owner).collect::<HashSet<_>>();
224
225 let mut focus_request = None;
226 for closed in self.active.iter().rev() {
227 if next_owners.contains(&closed.owner) {
228 continue;
229 }
230 push_trace(
231 &mut self.traces,
232 OverlayTraceSample {
233 owner: closed.owner,
234 kind: OverlayTraceKind::Closed,
235 overlay_kind: closed.options.kind,
236 reason: None,
237 },
238 );
239 let origin = self.focus_origins.remove(&closed.owner).flatten();
240 let focus_still_owned = focused.is_none_or(|focused| {
241 !graph.contains(focused)
242 || focused == closed.owner
243 || graph.is_ancestor_of(closed.owner, focused)
244 });
245 if focus_request.is_none()
246 && closed.options.focus.restore
247 && focus_still_owned
248 && let Some(origin) = origin.filter(|origin| graph.contains(*origin))
249 {
250 focus_request = Some(FocusRequest::Focus(origin));
251 push_trace(
252 &mut self.traces,
253 OverlayTraceSample {
254 owner: closed.owner,
255 kind: OverlayTraceKind::FocusRestored,
256 overlay_kind: closed.options.kind,
257 reason: None,
258 },
259 );
260 }
261 }
262
263 for opened in &next {
264 if previous_by_owner.contains_key(&opened.owner) {
265 continue;
266 }
267 self.focus_origins.insert(opened.owner, focused);
268 push_trace(
269 &mut self.traces,
270 OverlayTraceSample {
271 owner: opened.owner,
272 kind: OverlayTraceKind::Opened,
273 overlay_kind: opened.options.kind,
274 reason: None,
275 },
276 );
277 }
278
279 for opened in next.iter().rev() {
280 if previous_by_owner.contains_key(&opened.owner)
281 || focused.is_some_and(|focused| {
282 focused == opened.owner || graph.is_ancestor_of(opened.owner, focused)
283 })
284 {
285 continue;
286 }
287 let initial = match opened.options.focus.initial {
288 OverlayInitialFocus::None => None,
289 OverlayInitialFocus::Owner => graph
290 .node(opened.owner)
291 .filter(|node| node.accepts_focus)
292 .map(|_| opened.owner)
293 .or_else(|| graph.first_focusable_within(opened.owner, false)),
294 OverlayInitialFocus::FirstFocusable => graph
295 .first_focusable_within(opened.owner, false)
296 .or_else(|| {
297 graph
298 .node(opened.owner)
299 .filter(|node| node.accepts_focus)
300 .map(|_| opened.owner)
301 }),
302 };
303 if let Some(initial) = initial {
304 focus_request = Some(FocusRequest::Focus(initial));
305 push_trace(
306 &mut self.traces,
307 OverlayTraceSample {
308 owner: opened.owner,
309 kind: OverlayTraceKind::FocusEntered,
310 overlay_kind: opened.options.kind,
311 reason: None,
312 },
313 );
314 break;
315 }
316 }
317
318 if self
319 .active
320 .iter()
321 .map(|entry| entry.owner)
322 .collect::<Vec<_>>()
323 != next.iter().map(|entry| entry.owner).collect::<Vec<_>>()
324 && !self.active.is_empty()
325 && !next.is_empty()
326 && let Some(top) = next.last()
327 {
328 push_trace(
329 &mut self.traces,
330 OverlayTraceSample {
331 owner: top.owner,
332 kind: OverlayTraceKind::Reordered,
333 overlay_kind: top.options.kind,
334 reason: None,
335 },
336 );
337 }
338
339 self.active = next;
340 focus_request
341 }
342
343 pub(crate) fn snapshot(&self) -> OverlayManagerSnapshot {
344 OverlayManagerSnapshot {
345 overlays: self.active.clone(),
346 active_modal: self
347 .active
348 .iter()
349 .rev()
350 .find(|entry| entry.options.modality == OverlayModality::Modal)
351 .map(|entry| entry.owner),
352 focus_trap: self
353 .active
354 .iter()
355 .rev()
356 .find(|entry| entry.options.focus.trap)
357 .map(|entry| entry.owner),
358 }
359 }
360
361 pub(crate) fn focus_trap(&self) -> Option<WidgetId> {
362 self.active
363 .iter()
364 .rev()
365 .find(|entry| entry.options.focus.trap)
366 .map(|entry| entry.owner)
367 }
368
369 pub(crate) fn active_modal(&self) -> Option<WidgetId> {
370 self.active
371 .iter()
372 .rev()
373 .find(|entry| entry.options.modality == OverlayModality::Modal)
374 .map(|entry| entry.owner)
375 }
376
377 pub(crate) fn topmost_dismissible(
378 &self,
379 reason: OverlayDismissReason,
380 ) -> Option<&OverlaySnapshot> {
381 self.active.iter().rev().find(|entry| match reason {
382 OverlayDismissReason::Escape => entry.options.dismiss.escape,
383 OverlayDismissReason::OutsidePointer => entry.options.dismiss.outside_pointer,
384 OverlayDismissReason::Programmatic => true,
385 })
386 }
387
388 pub(crate) fn trace_dismissal(
389 &mut self,
390 owner: WidgetId,
391 kind: OverlayKind,
392 reason: OverlayDismissReason,
393 ) {
394 push_trace(
395 &mut self.traces,
396 OverlayTraceSample {
397 owner,
398 kind: OverlayTraceKind::DismissRequested,
399 overlay_kind: kind,
400 reason: Some(reason),
401 },
402 );
403 }
404
405 pub(crate) fn take_traces(&mut self) -> Vec<OverlayTraceSample> {
406 std::mem::take(&mut self.traces)
407 }
408}
409
410fn push_trace(traces: &mut Vec<OverlayTraceSample>, sample: OverlayTraceSample) {
411 if traces.len() == MAX_OVERLAY_TRACE_SAMPLES {
412 traces.remove(0);
413 }
414 traces.push(sample);
415}