use std::collections::HashMap;
use oxibrowser_core::{Browser, Tab};
pub struct TabManager {
tabs: HashMap<String, Tab>,
next_id: u32,
}
impl TabManager {
pub fn new() -> Self {
Self {
tabs: HashMap::new(),
next_id: 1,
}
}
pub async fn create_tab(&mut self, browser: &Browser) -> Result<String, String> {
let id = format!("t{}", self.next_id);
self.next_id += 1;
let tab = browser.new_tab().await.map_err(|e| format!("{e}"))?;
self.tabs.insert(id.clone(), tab);
Ok(id)
}
pub fn get(&self, tab_id: &str) -> Option<&Tab> {
self.tabs.get(tab_id)
}
pub async fn close_tab(&mut self, tab_id: &str) -> Result<(), String> {
if let Some(tab) = self.tabs.remove(tab_id) {
tab.close().await.map_err(|e| format!("{e}"))?;
}
Ok(())
}
pub async fn close_all(&mut self) {
for (_, tab) in self.tabs.drain() {
let _ = tab.close().await;
}
}
pub fn list(&self) -> Vec<String> {
let mut ids: Vec<String> = self.tabs.keys().cloned().collect();
ids.sort();
ids
}
pub fn len(&self) -> usize {
self.tabs.len()
}
#[allow(dead_code)]
pub fn is_empty(&self) -> bool {
self.tabs.is_empty()
}
}
impl Default for TabManager {
fn default() -> Self {
Self::new()
}
}