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    /// - `CallbackFn` - 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<CallbackFn>(label: &str, z_index: i32, on_dismiss: CallbackFn) -> u64
68    where
69        CallbackFn: 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 item_index in 1..list.len() {
124                    let alpha_val: &OverlayStackEntry = &list[best_idx];
125                    let blue_val: &OverlayStackEntry = &list[item_index];
126                    if blue_val.get_z_index() > alpha_val.get_z_index()
127                        || (blue_val.get_z_index() == alpha_val.get_z_index()
128                            && blue_val.get_id() > alpha_val.get_id())
129                    {
130                        best_idx = item_index;
131                    }
132                }
133                let removed: OverlayStackEntry = list.remove(best_idx);
134                let OverlayStackEntry { on_dismiss, .. } = removed;
135                Some(on_dismiss)
136            });
137        if let Some(callback_fn) = top_cb {
138            Self::sync_active_count_signal();
139            if let Ok(mut func) = callback_fn.try_borrow_mut() {
140                func();
141            }
142            return true;
143        }
144        false
145    }
146
147    /// Dismisses every active overlay currently open in top-to-bottom LIFO order.
148    ///
149    /// # Returns
150    ///
151    /// - `usize` - Number of overlays dismissed.
152    pub fn dismiss_all() -> usize {
153        let mut closed: usize = 0;
154        while Self::dismiss_top() {
155            closed += 1;
156        }
157        closed
158    }
159
160    /// Dismisses all active fullscreen overlays (`z_index >= Z_INDEX_FULLSCREEN`) in top-to-bottom LIFO order.
161    ///
162    /// # Returns
163    ///
164    /// - `usize` - Number of fullscreen overlays dismissed.
165    pub fn dismiss_fullscreen() -> usize {
166        let mut closed: usize = 0;
167        loop {
168            let top_fs_cb: Option<Rc<RefCell<dyn FnMut()>>> =
169                OVERLAY_STACK_ENTRIES.with(|stack: &RefCell<Vec<OverlayStackEntry>>| {
170                    let Ok(mut list) = stack.try_borrow_mut() else {
171                        return None;
172                    };
173                    let mut best_idx: Option<usize> = None;
174                    for (item_index, entry) in list.iter().enumerate() {
175                        if entry.get_z_index() < Z_INDEX_FULLSCREEN {
176                            continue;
177                        }
178                        let replace_best: bool = match best_idx {
179                            None => true,
180                            Some(prev_i) => {
181                                let prev: &OverlayStackEntry = &list[prev_i];
182                                entry.get_z_index() > prev.get_z_index()
183                                    || (entry.get_z_index() == prev.get_z_index()
184                                        && entry.get_id() > prev.get_id())
185                            }
186                        };
187                        if replace_best {
188                            best_idx = Some(item_index);
189                        }
190                    }
191                    let idx: usize = best_idx?;
192                    let removed: OverlayStackEntry = list.remove(idx);
193                    let OverlayStackEntry { on_dismiss, .. } = removed;
194                    Some(on_dismiss)
195                });
196            if let Some(callback_fn) = top_fs_cb {
197                Self::sync_active_count_signal();
198                if let Ok(mut func) = callback_fn.try_borrow_mut() {
199                    func();
200                }
201                closed += 1;
202            } else {
203                break;
204            }
205        }
206        closed
207    }
208
209    /// Returns whether any fullscreen overlay (`z_index >= Z_INDEX_FULLSCREEN`) is currently registered on the stack.
210    ///
211    /// # Returns
212    ///
213    /// - `bool` - `true` when at least one fullscreen portal is open.
214    #[must_use]
215    pub fn has_fullscreen() -> bool {
216        OVERLAY_STACK_ENTRIES.with(|stack: &RefCell<Vec<OverlayStackEntry>>| {
217            stack
218                .try_borrow()
219                .map(|list: Ref<'_, Vec<OverlayStackEntry>>| {
220                    list.iter()
221                        .any(|entry: &OverlayStackEntry| entry.get_z_index() >= Z_INDEX_FULLSCREEN)
222                })
223                .unwrap_or(false)
224        })
225    }
226
227    /// Returns the number of currently open overlays registered in the stack.
228    ///
229    /// # Returns
230    ///
231    /// - `usize` - Active overlay depth.
232    #[must_use]
233    pub fn active_count() -> usize {
234        OVERLAY_STACK_ENTRIES.with(|stack: &RefCell<Vec<OverlayStackEntry>>| {
235            stack
236                .try_borrow()
237                .map(|list: Ref<'_, Vec<OverlayStackEntry>>| list.len())
238                .unwrap_or(0)
239        })
240    }
241
242    /// Returns the ordered labels of all currently open overlays (bottom to top).
243    ///
244    /// # Returns
245    ///
246    /// - `Vec<String>` - Active overlay labels.
247    #[must_use]
248    pub fn active_labels() -> Vec<String> {
249        OVERLAY_STACK_ENTRIES.with(|stack: &RefCell<Vec<OverlayStackEntry>>| {
250            stack
251                .try_borrow()
252                .map(|list: Ref<'_, Vec<OverlayStackEntry>>| {
253                    list.iter()
254                        .map(|entry: &OverlayStackEntry| entry.get_label().clone())
255                        .collect()
256                })
257                .unwrap_or_default()
258        })
259    }
260
261    /// Clears all registered entries without invoking callbacks (useful for test reset).
262    pub fn clear() {
263        OVERLAY_STACK_ENTRIES.with(|stack: &RefCell<Vec<OverlayStackEntry>>| {
264            if let Ok(mut list) = stack.try_borrow_mut() {
265                list.clear();
266            }
267        });
268        Self::sync_active_count_signal();
269    }
270
271    /// Binds a boolean open signal (`EuvModal`, `EuvDrawer`, `EuvSheet`, `EuvAlertDialog`, etc.) to the unified overlay stack.
272    ///
273    /// # Arguments
274    ///
275    /// - `Signal<bool>` - Controlled overlay visibility signal.
276    /// - `&str` - Diagnostic overlay label.
277    /// - `i32` - Layer z-index priority.
278    ///
279    /// # Returns
280    ///
281    /// - `Effect` - Reactive effect keeping the stack synchronized with `open`.
282    pub fn bind_signal(open: Signal<bool>, label: &str, z_index: i32) -> Effect {
283        let entry_id: Rc<Cell<u64>> = Rc::new(Cell::new(0));
284        let cleanup_id: Rc<Cell<u64>> = Rc::clone(&entry_id);
285        on_cleanup(move || {
286            let stale_id: u64 = cleanup_id.replace(0);
287            if stale_id != 0 {
288                Self::remove(stale_id);
289            }
290        });
291        let label_owned: String = label.to_string();
292        Effect::new(move || {
293            let is_open: bool = open.get();
294            let cur_id: u64 = entry_id.get();
295            if is_open && cur_id == 0 {
296                let id_holder: Rc<Cell<u64>> = Rc::clone(&entry_id);
297                let new_id: u64 = Self::push(&label_owned, z_index, move || {
298                    id_holder.set(0);
299                    let _: bool = open.set_if_changed(false);
300                });
301                entry_id.set(new_id);
302            } else if !is_open && cur_id != 0 {
303                entry_id.set(0);
304                Self::remove(cur_id);
305            }
306        })
307    }
308}