use gpui::{App, Global, SharedString, WeakEntity};
use crate::Cx;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PendingNavigation {
Push(SharedString),
Replace(SharedString),
Back,
Forward,
}
struct BlockerState {
when: bool,
}
#[derive(Default)]
struct Blockers {
active: Vec<WeakEntity<BlockerState>>,
pending: Option<PendingNavigation>,
bypass: bool,
}
impl Global for Blockers {}
pub(super) fn intercept(navigation: PendingNavigation, cx: &mut App) -> bool {
let Some(blockers) = cx.try_global::<Blockers>() else {
return false;
};
if blockers.bypass {
return false;
}
let active = blockers
.active
.iter()
.filter_map(WeakEntity::upgrade)
.any(|state| state.read(cx).when);
if active {
let blockers = cx.global_mut::<Blockers>();
blockers.active.retain(|state| state.upgrade().is_some());
blockers.pending = Some(navigation);
cx.refresh_windows();
}
active
}
fn perform(navigation: PendingNavigation, cx: &mut App) {
cx.default_global::<Blockers>().bypass = true;
match navigation {
PendingNavigation::Push(path) => super::navigate(path, cx),
PendingNavigation::Replace(path) => super::replace(path, cx),
PendingNavigation::Back => super::back(cx),
PendingNavigation::Forward => super::forward(cx),
}
cx.default_global::<Blockers>().bypass = false;
}
#[derive(Clone)]
pub struct Blocker {
pending: Option<PendingNavigation>,
}
impl Blocker {
#[must_use]
pub fn is_blocked(&self) -> bool {
self.pending.is_some()
}
#[must_use]
pub fn pending(&self) -> Option<&PendingNavigation> {
self.pending.as_ref()
}
pub fn proceed(&self, cx: &mut App) {
if let Some(navigation) = cx.default_global::<Blockers>().pending.take() {
perform(navigation, cx);
}
}
pub fn reset(&self, cx: &mut App) {
cx.default_global::<Blockers>().pending = None;
cx.refresh_windows();
}
}
#[track_caller]
pub fn use_blocker(cx: &mut Cx, when: bool) -> Blocker {
let state = cx.window.use_state(cx.app, |_, _| BlockerState { when });
state.update(cx.app, |state, _| state.when = when);
let weak = state.downgrade();
let blockers = cx.app.default_global::<Blockers>();
if !blockers.active.iter().any(|active| active == &weak) {
blockers.active.push(weak);
}
Blocker {
pending: if when { blockers.pending.clone() } else { None },
}
}