UNPKG

magnitude-core

Version:
68 lines (67 loc) 2.13 kB
// Keeps track of current tab, enables describing open tabs, and switching between open tabs import logger from "@/logger"; import EventEmitter from "eventemitter3"; export class TabManager { /** * Page / tab manager */ //private state!: TabState; context; activePage; // the page the agent currently sees and acts on events; constructor(context) { this.context = context; this.events = new EventEmitter(); // By default when a new page is created // (for any reason - just started, agent clicked something, user did new page), set it to active this.context.on('page', this.onPageCreated.bind(this)); } async onPageCreated(page) { // set active page immediately since agent and helpers expect it to exist this.setActivePage(page); } setActivePage(page) { this.activePage = page; this.events.emit('tabChanged', page); } async switchTab(index) { const pages = this.context.pages(); if (index < 0 || index >= pages.length) { throw new Error(`Invalid tab index: ${index}`); } const page = pages[index]; await page.bringToFront(); this.setActivePage(page); } getActivePage() { return this.activePage; } getPages() { return this.context.pages(); } async retrieveState() { //return this.state; let activeIndex = -1; let tabs = []; for (const [i, page] of this.context.pages().entries()) { if (page == this.activePage) { activeIndex = i; } // may need retries let title; try { title = await page.title(); } catch { logger.warn('Could not load page title while retrieving tab state'); title = '(could not load title)'; } const url = page.url(); tabs.push({ title, url }); //, page }); } return { activeTab: activeIndex, tabs: tabs }; } }