use std::collections::{HashMap, HashSet};
use gpui_kit::{AnyWindowHandle, App, Entity, EntityId, FocusHandle, Global, WeakEntity, Window};
#[derive(Default)]
pub(super) struct NavigatorRows {
order: Vec<FocusHandle>,
joined: HashSet<EntityId>,
}
#[derive(Default)]
struct Drawing(HashMap<AnyWindowHandle, WeakEntity<NavigatorRows>>);
impl Global for Drawing {}
#[derive(Clone, Copy)]
pub(super) enum Step {
Next,
Previous,
}
pub(super) fn begin(window: &mut Window, cx: &mut App) {
let rows = window.use_keyed_state("workspace-navigator-rows", cx, |_, _| {
NavigatorRows::default()
});
rows.update(cx, |rows, _| {
rows.order.clear();
rows.joined.clear();
});
let open = cx.windows();
let drawing = &mut cx.default_global::<Drawing>().0;
drawing.retain(|handle, _| open.contains(handle));
drawing.insert(window.window_handle(), rows.downgrade());
}
pub(super) fn push(
focus: &FocusHandle,
state: EntityId,
window: &Window,
cx: &mut App,
) -> Option<Entity<NavigatorRows>> {
let rows = cx
.try_global::<Drawing>()?
.0
.get(&window.window_handle())?
.upgrade()?;
rows.update(cx, |rows, _| {
if rows.joined.insert(state) {
rows.order.push(focus.clone());
}
});
Some(rows)
}
pub(super) fn step(
rows: Option<&Entity<NavigatorRows>>,
from: &FocusHandle,
direction: Step,
window: &mut Window,
cx: &mut App,
) {
let Some(rows) = rows else {
return;
};
let order = &rows.read(cx).order;
let Some(index) = order.iter().position(|row| row == from) else {
return;
};
let target = match direction {
Step::Next => index.checked_add(1),
Step::Previous => index.checked_sub(1),
}
.and_then(|index| order.get(index))
.cloned();
if let Some(target) = target {
window.focus(&target, cx);
}
}