Skip to main content

euv_ui/overlay_stack/
impl.rs

1use super::*;
2
3/// Unified overlay stack management operations for `EuvOverlayStack`.
4impl EuvOverlayStack {
5    /// Publishes the current active overlay depth into the reactive count signal if alive.
6    fn sync_active_count_signal() {
7        let count: usize = Self::active_count();
8        OVERLAY_STACK_COUNT_SIG.with(|slot: &RefCell<Option<Signal<usize>>>| {
9            if let Ok(guard) = slot.try_borrow()
10                && let Some(sig) = *guard
11                && untracked(|| sig.try_get().is_some())
12            {
13                let _: bool = sig.set_if_changed(count);
14            }
15        });
16    }
17
18    /// Returns a reactive signal tracking the number of currently open overlays.
19    ///
20    /// # Returns
21    ///
22    /// - `Signal<usize>` - Live reactive active overlay depth signal.
23    #[must_use]
24    pub fn active_count_signal() -> Signal<usize> {
25        let reset_detected: bool =
26            OVERLAY_STACK_COUNT_SIG.with(|slot: &RefCell<Option<Signal<usize>>>| {
27                slot.try_borrow()
28                    .ok()
29                    .and_then(|guard: Ref<'_, Option<Signal<usize>>>| *guard)
30                    .is_some_and(|sig: Signal<usize>| untracked(|| sig.try_get().is_none()))
31            });
32        if reset_detected {
33            OVERLAY_STACK_ENTRIES.with(|stack: &RefCell<Vec<OverlayStackEntry>>| {
34                if let Ok(mut list) = stack.try_borrow_mut() {
35                    list.clear();
36                }
37            });
38        }
39        let count: usize = Self::active_count();
40        OVERLAY_STACK_COUNT_SIG.with(|slot: &RefCell<Option<Signal<usize>>>| {
41            if let Ok(guard) = slot.try_borrow()
42                && let Some(sig) = *guard
43                && untracked(|| sig.try_get().is_some())
44            {
45                let _: bool = sig.set_if_changed(count);
46                return sig;
47            }
48            let fresh: Signal<usize> = Signal::new(count);
49            if let Ok(mut guard) = slot.try_borrow_mut() {
50                *guard = Some(fresh);
51            }
52            fresh
53        })
54    }
55
56    /// Registers an open overlay onto the unified dismissal stack and returns its unique entry ID.
57    ///
58    /// # Arguments
59    ///
60    /// - `&str` - Human-readable overlay label.
61    /// - `i32` - Layer stacking z-index (`Z_INDEX_MODAL`, `Z_INDEX_DRAWER`, etc.).
62    /// - `F` - Closure closing the overlay when dismissed by system back.
63    ///
64    /// # Returns
65    ///
66    /// - `u64` - Unique registration ID used to remove the entry upon manual dismissal.
67    pub fn push<F>(label: &str, z_index: i32, on_dismiss: F) -> u64
68    where
69        F: FnMut() + 'static,
70    {
71        let id: u64 = OVERLAY_STACK_NEXT_ID.with(|seq: &Cell<u64>| {
72            let cur: u64 = seq.get();
73            seq.set(cur.wrapping_add(1).max(1));
74            cur
75        });
76        let entry: OverlayStackEntry = OverlayStackEntry {
77            id,
78            label: label.to_string(),
79            z_index,
80            on_dismiss: Rc::new(RefCell::new(on_dismiss)),
81        };
82        OVERLAY_STACK_ENTRIES.with(|stack: &RefCell<Vec<OverlayStackEntry>>| {
83            if let Ok(mut list) = stack.try_borrow_mut() {
84                list.push(entry);
85            }
86        });
87        Self::sync_active_count_signal();
88        id
89    }
90
91    /// Removes an overlay entry by `id` when closed outside the back-stack path (e.g. close button or scrim tap).
92    ///
93    /// # Arguments
94    ///
95    /// - `u64` - Registration ID returned by `push`.
96    pub fn remove(id: u64) {
97        if id == 0 {
98            return;
99        }
100        OVERLAY_STACK_ENTRIES.with(|stack: &RefCell<Vec<OverlayStackEntry>>| {
101            if let Ok(mut list) = stack.try_borrow_mut() {
102                list.retain(|entry: &OverlayStackEntry| entry.get_id() != id);
103            }
104        });
105        Self::sync_active_count_signal();
106    }
107
108    /// Dismisses ONLY the highest-priority (`z_index`, then most recent `id`) active overlay in LIFO order.
109    ///
110    /// # Returns
111    ///
112    /// - `bool` - `true` if an active overlay was dismissed; `false` if the overlay stack is empty.
113    pub fn dismiss_top() -> bool {
114        let top_cb: Option<Rc<RefCell<dyn FnMut()>>> =
115            OVERLAY_STACK_ENTRIES.with(|stack: &RefCell<Vec<OverlayStackEntry>>| {
116                let Ok(mut list) = stack.try_borrow_mut() else {
117                    return None;
118                };
119                if list.is_empty() {
120                    return None;
121                }
122                let mut best_idx: usize = 0;
123                for i in 1..list.len() {
124                    let a: &OverlayStackEntry = &list[best_idx];
125                    let b: &OverlayStackEntry = &list[i];
126                    if b.get_z_index() > a.get_z_index()
127                        || (b.get_z_index() == a.get_z_index() && b.get_id() > a.get_id())
128                    {
129                        best_idx = i;
130                    }
131                }
132                let removed: OverlayStackEntry = list.remove(best_idx);
133                let OverlayStackEntry { on_dismiss, .. } = removed;
134                Some(on_dismiss)
135            });
136        if let Some(cb) = top_cb {
137            Self::sync_active_count_signal();
138            if let Ok(mut func) = cb.try_borrow_mut() {
139                func();
140            }
141            return true;
142        }
143        false
144    }
145
146    /// Dismisses every active overlay currently open in top-to-bottom LIFO order.
147    ///
148    /// # Returns
149    ///
150    /// - `usize` - Number of overlays dismissed.
151    pub fn dismiss_all() -> usize {
152        let mut closed: usize = 0;
153        while Self::dismiss_top() {
154            closed += 1;
155        }
156        closed
157    }
158
159    /// Dismisses all active fullscreen overlays (`z_index >= Z_INDEX_FULLSCREEN`) in top-to-bottom LIFO order.
160    ///
161    /// # Returns
162    ///
163    /// - `usize` - Number of fullscreen overlays dismissed.
164    pub fn dismiss_fullscreen() -> usize {
165        let mut closed: usize = 0;
166        loop {
167            let top_fs_cb: Option<Rc<RefCell<dyn FnMut()>>> =
168                OVERLAY_STACK_ENTRIES.with(|stack: &RefCell<Vec<OverlayStackEntry>>| {
169                    let Ok(mut list) = stack.try_borrow_mut() else {
170                        return None;
171                    };
172                    let mut best_idx: Option<usize> = None;
173                    for (i, entry) in list.iter().enumerate() {
174                        if entry.get_z_index() < Z_INDEX_FULLSCREEN {
175                            continue;
176                        }
177                        let replace_best: bool = match best_idx {
178                            None => true,
179                            Some(prev_i) => {
180                                let prev: &OverlayStackEntry = &list[prev_i];
181                                entry.get_z_index() > prev.get_z_index()
182                                    || (entry.get_z_index() == prev.get_z_index()
183                                        && entry.get_id() > prev.get_id())
184                            }
185                        };
186                        if replace_best {
187                            best_idx = Some(i);
188                        }
189                    }
190                    let idx: usize = best_idx?;
191                    let removed: OverlayStackEntry = list.remove(idx);
192                    let OverlayStackEntry { on_dismiss, .. } = removed;
193                    Some(on_dismiss)
194                });
195            if let Some(cb) = top_fs_cb {
196                Self::sync_active_count_signal();
197                if let Ok(mut func) = cb.try_borrow_mut() {
198                    func();
199                }
200                closed += 1;
201            } else {
202                break;
203            }
204        }
205        closed
206    }
207
208    /// Returns whether any fullscreen overlay (`z_index >= Z_INDEX_FULLSCREEN`) is currently registered on the stack.
209    ///
210    /// # Returns
211    ///
212    /// - `bool` - `true` when at least one fullscreen portal is open.
213    #[must_use]
214    pub fn has_fullscreen() -> bool {
215        OVERLAY_STACK_ENTRIES.with(|stack: &RefCell<Vec<OverlayStackEntry>>| {
216            stack
217                .try_borrow()
218                .map(|list: Ref<'_, Vec<OverlayStackEntry>>| {
219                    list.iter()
220                        .any(|entry: &OverlayStackEntry| entry.get_z_index() >= Z_INDEX_FULLSCREEN)
221                })
222                .unwrap_or(false)
223        })
224    }
225
226    /// Returns the number of currently open overlays registered in the stack.
227    ///
228    /// # Returns
229    ///
230    /// - `usize` - Active overlay depth.
231    #[must_use]
232    pub fn active_count() -> usize {
233        OVERLAY_STACK_ENTRIES.with(|stack: &RefCell<Vec<OverlayStackEntry>>| {
234            stack
235                .try_borrow()
236                .map(|list: Ref<'_, Vec<OverlayStackEntry>>| list.len())
237                .unwrap_or(0)
238        })
239    }
240
241    /// Returns the ordered labels of all currently open overlays (bottom to top).
242    ///
243    /// # Returns
244    ///
245    /// - `Vec<String>` - Active overlay labels.
246    #[must_use]
247    pub fn active_labels() -> Vec<String> {
248        OVERLAY_STACK_ENTRIES.with(|stack: &RefCell<Vec<OverlayStackEntry>>| {
249            stack
250                .try_borrow()
251                .map(|list: Ref<'_, Vec<OverlayStackEntry>>| {
252                    list.iter()
253                        .map(|entry: &OverlayStackEntry| entry.get_label().clone())
254                        .collect()
255                })
256                .unwrap_or_default()
257        })
258    }
259
260    /// Clears all registered entries without invoking callbacks (useful for test reset).
261    pub fn clear() {
262        OVERLAY_STACK_ENTRIES.with(|stack: &RefCell<Vec<OverlayStackEntry>>| {
263            if let Ok(mut list) = stack.try_borrow_mut() {
264                list.clear();
265            }
266        });
267        Self::sync_active_count_signal();
268    }
269
270    /// Binds a boolean open signal (`EuvModal`, `EuvDrawer`, `EuvSheet`, `EuvAlertDialog`, etc.) to the unified overlay stack.
271    ///
272    /// # Arguments
273    ///
274    /// - `Signal<bool>` - Controlled overlay visibility signal.
275    /// - `&str` - Diagnostic overlay label.
276    /// - `i32` - Layer z-index priority.
277    ///
278    /// # Returns
279    ///
280    /// - `Effect` - Reactive effect keeping the stack synchronized with `open`.
281    pub fn bind_signal(open: Signal<bool>, label: &str, z_index: i32) -> Effect {
282        let entry_id: Rc<Cell<u64>> = Rc::new(Cell::new(0));
283        let cleanup_id: Rc<Cell<u64>> = Rc::clone(&entry_id);
284        on_cleanup(move || {
285            let stale_id: u64 = cleanup_id.replace(0);
286            if stale_id != 0 {
287                Self::remove(stale_id);
288            }
289        });
290        let label_owned: String = label.to_string();
291        Effect::new(move || {
292            let is_open: bool = open.get();
293            let cur_id: u64 = entry_id.get();
294            if is_open && cur_id == 0 {
295                let id_holder: Rc<Cell<u64>> = Rc::clone(&entry_id);
296                let new_id: u64 = Self::push(&label_owned, z_index, move || {
297                    id_holder.set(0);
298                    let _: bool = open.set_if_changed(false);
299                });
300                entry_id.set(new_id);
301            } else if !is_open && cur_id != 0 {
302                entry_id.set(0);
303                Self::remove(cur_id);
304            }
305        })
306    }
307}