/** * Copyright (c) OpenLens Authors. All rights reserved. * Licensed under MIT License. See LICENSE in root directory for more information. */ import { action, observable, reaction } from "mobx"; import { autoBind, noop, StorageHelper, toJS } from "../../../utils"; import type { TabId } from "../dock/store"; export interface DockTabStoreOptions { autoInit?: boolean; // load data from storage when `storageKey` is provided and bind events, default: true storageKey?: string; // save data to persistent storage under the key } export type DockTabStorageState = Record; interface DockTabStoreDependencies { createStorage: (storageKey: string, options: DockTabStorageState) => StorageHelper>; } export class DockTabStore { /** * @internal */ protected storage?: StorageHelper>; private data = observable.map(); /** * @internal */ protected dependencies: DockTabStoreDependencies; constructor(dependencies: DockTabStoreDependencies, { autoInit = true, storageKey }: DockTabStoreOptions) { autoBind(this); this.dependencies = dependencies; this.init = storageKey ? (() => { this.storage = this.dependencies.createStorage(storageKey, {}); this.storage.whenReady.then(() => { this.data.replace(this.storage.value); reaction(() => this.toJSON(), data => this.storage.set(data)); }); }) : noop; if (autoInit) { this.init(); } } protected init: () => void; protected finalizeDataForSave(data: T): T { return data; } protected toJSON(): DockTabStorageState { const deepCopy = toJS(this.data); deepCopy.forEach((tabData, key) => { deepCopy.set(key, this.finalizeDataForSave(tabData)); }); return Object.fromEntries(deepCopy); } protected getAllData() { return this.data.toJSON(); } findTabIdFromData(inspecter: (val: T) => any): TabId | undefined { for (const [tabId, data] of this.data) { if (inspecter(data)) { return tabId; } } return undefined; } isReady(tabId: TabId): boolean { return this.getData(tabId) !== undefined; } getData(tabId: TabId) { return this.data.get(tabId); } setData(tabId: TabId, data: T) { this.data.set(tabId, data); } clearData(tabId: TabId) { this.data.delete(tabId); } @action reset() { for (const tabId of this.data.keys()) { this.clearData(tabId); } this.storage?.reset(); } }