import debug from 'debug'; import _ from 'lodash'; const _d = debug('@developDebugger'); export type DebugModule_T = { // name name: string; // 调试端口 port: number; // 是否打开html调试 html: boolean; // 是否打开服务端调试 server: boolean; }; export class DebugSessionStorage { private _storKey = 'debugModules'; public portMap = {} as { [k: number]: DebugModule_T }; public debugModuleMap = {} as { [k: string]: DebugModule_T }; constructor() { this._read(); this._save(); } private _makePortMap() { const map: any = {}; _.forEach(this.debugModuleMap, (mod, name) => { map[mod.port] = mod; }); this.portMap = map; } private _read() { try { const str = sessionStorage.getItem(this._storKey); if (_.isEmpty(str)) throw new Error('debugModuleMap empty'); this.debugModuleMap = JSON.parse(str as string); } catch (e) { this.debugModuleMap = {}; _d('sessionStorage.debugModules Invalid,reset to {}', e.message); } this._makePortMap(); } private _save() { sessionStorage.setItem(this._storKey, JSON.stringify(this.debugModuleMap)); } // setDebugModulePort(moduleName: string, localPort: number) { // const debugModules = this._read(); // debugModules[moduleName] = { port: localPort, html: false, server: false }; // sessionStorage.setItem(this._storKey, JSON.stringify(debugModules)); // } findDebugModuleByName(moduleName: string) { return this.debugModuleMap[moduleName]; } findDebugModuleByPort(port: number) { return this.portMap[port]; } // 切换指定组件为debug状态 switchDebugByPort(port: number, modName: string, htmlOrServer: 'html' | 'server') { const list = [] as DebugModule_T[]; let mod = this.portMap[port]; if (_.isEmpty(mod)) { // 创建新的调试信息 mod = { html: false, server: false, name: modName, port: port }; this.debugModuleMap[modName] = mod; } if (htmlOrServer === 'html') { mod.html = !mod.html; // 关掉前台时,后台一起关闭 if (!mod.html) { mod.server = false; } } else { mod.server = !mod.server; if (mod.server) { // 调试后台时,html必须打开 mod.html = true; } } // 删除其他同名组件调试信息 _.forEach(this.debugModuleMap, (mod, name) => { if (mod.port !== port && name === modName) { delete this.debugModuleMap[name]; } }); this._makePortMap(); this._save(); } } export default new DebugSessionStorage();