import * as labels from './labels.js' export const init = ({ tabs: browserTabs, onStateUpdate, }) => { /* Initial state */ const state = { tabs: [], results: [], query: '', } /* */ const addLabel = (tabs) => (tab) => ({ label: labels.id2label(tab.id, tabs), ...tab, }) const pickFields = (tab) => [ 'favIconUrl', 'id', 'label', 'title', 'url', ].reduce((acc, x) => (acc[x] = tab[x], acc), {}) const addDisplayName = (tab) => ({ displayName: ` ${tab.label} ${tab.title} / ${tab.url}`, ...tab, }) const shapeTabs = (tabs) => tabs .map(addLabel(tabs)) .map(pickFields) .map(addDisplayName) const fetchTabs = () => browserTabs.query({ currentWindow: true, active: false }) .then(shapeTabs) .then((tabs) => tabs.reverse()) .then((tabs) => { void (state.tabs = tabs) void (state.results = tabs) }) /* */ const updateResults = () => { state.results = state.query.length === 0 ? state.tabs : [] } /* */ const updateState = () => Promise.resolve() .then(fetchTabs) .then(updateResults) .then(() => onStateUpdate(state)) updateState() /* */ return { getCurrentState() { return state }, actions: { goToTab(id) { browserTabs.update(id, { active: true }) .then(updateState) }, closeTab(id) { browserTabs.remove(id) .then(updateState) }, updateQuery(query) { state.query = query updateState() }, }, } }