win-state
Version:
Save Electron apps windows state
75 lines (60 loc) • 1.86 kB
JavaScript
const Store = require('electron-store')
const winstate = new Store({ name: 'win-state' })
const objectSize = function (obj) {
return Object.keys(obj).length
}
const defaultOptions = {
show: true,
showCallback: null,
close: true,
closeCallback: null,
load: null
}
class WinState {
constructor () {
this._windows = {}
this._options = {}
}
_getCurrentState (id) {
const key = `win_${id}`
const bounds = this._windows[key].getBounds()
return {
bounds,
isMaximized: this._windows[key].isMaximized()
}
}
_saveState (id) {
let state = this._getCurrentState(id)
/* I do not know why, but keep adding 28px to y pos... at least on Linux both Unity and Gnome */
state.bounds.y -= 28
winstate.set(`win_${id}`, state)
}
_bindEvents (id) {
const key = `win_${id}`
const state = winstate.get(key, {})
if (this._options[key].load) { this._windows[key].loadURL(this._options[key].load) }
if (objectSize(state) > 0) {
if (state.isMaximized) {
this._windows[key].maximize()
} else {
this._windows[key].setBounds(state.bounds)
}
}
this._windows[key].once('ready-to-show', (evt) => {
if (this._options[key].show) { this._windows[key].show() }
if (typeof this._options[key].showCallback === 'function') { this._options[key].showCallback() }
})
this._windows[key].on('close', (evt) => {
this._saveState(id)
if (this._options[key].close) { this._windows[key] = null }
if (typeof this._options[key].closeCallback === 'function') { this._options[key].closeCallback() }
})
}
manage (win, options) {
const key = `win_${win.id}`
this._options[key] = Object.assign({}, defaultOptions, options)
this._windows[key] = win
this._bindEvents(win.id)
}
}
module.exports = WinState