2017-11-09 00:41:07 +00:00
|
|
|
/** Tridactyl shared state
|
2017-11-08 23:20:41 +00:00
|
|
|
|
2017-11-09 00:41:07 +00:00
|
|
|
Any context with access to browser.storage can safely import this file and
|
|
|
|
get a self-updating consistent copy of the shared program state.
|
2017-11-08 23:20:41 +00:00
|
|
|
|
2017-11-09 00:41:07 +00:00
|
|
|
Any context may modify their copy of the state and that modification will
|
|
|
|
be propagated to the rest of the program.
|
|
|
|
|
|
|
|
This works by proxying the state object such that setting any property
|
|
|
|
causes the entire state to be saved to storage and adding a listener that
|
|
|
|
listens for storage events and updates the proxied object on each storage
|
|
|
|
event.
|
|
|
|
|
|
|
|
If this turns out to be expensive there are improvements available.
|
|
|
|
*/
|
2017-11-08 23:20:41 +00:00
|
|
|
|
2017-12-02 23:54:37 +08:00
|
|
|
export type ModeName = 'normal' | 'insert' | 'hint' | 'ignore' | 'gobble' | 'input'
|
2017-11-09 08:04:05 +00:00
|
|
|
class State {
|
2017-11-08 23:20:41 +00:00
|
|
|
mode: ModeName = 'normal'
|
2017-11-09 08:04:05 +00:00
|
|
|
cmdHistory: string[] = []
|
2017-12-02 12:08:30 +01:00
|
|
|
last_ex_str: string = ""
|
2017-10-05 18:01:44 +01:00
|
|
|
}
|
|
|
|
|
2017-11-09 00:41:07 +00:00
|
|
|
// Don't change these from const or you risk breaking the Proxy below.
|
2017-11-09 08:04:05 +00:00
|
|
|
const defaults = Object.freeze(new State())
|
2017-11-09 00:41:07 +00:00
|
|
|
|
|
|
|
const overlay = {} as any
|
|
|
|
browser.storage.local.get('state').then(res=>{
|
|
|
|
if ('state' in res) {
|
|
|
|
console.log("Loaded initial state:", res.state)
|
|
|
|
Object.assign(overlay, res.state)
|
|
|
|
}
|
|
|
|
}).catch(console.error)
|
|
|
|
|
|
|
|
const state = new Proxy(overlay, {
|
|
|
|
|
|
|
|
/** Give defaults if overlay doesn't have the key */
|
|
|
|
get: function (target, property) {
|
|
|
|
if (property in target) {
|
|
|
|
return target[property]
|
|
|
|
} else {
|
|
|
|
return defaults[property]
|
|
|
|
}
|
|
|
|
},
|
|
|
|
|
|
|
|
/** Persist sets to storage immediately */
|
|
|
|
set: function(target, property, value) {
|
|
|
|
console.log("State changed!", property, value)
|
|
|
|
target[property] = value
|
|
|
|
browser.storage.local.set({state: target})
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2017-11-09 08:04:05 +00:00
|
|
|
}) as any as State
|
2017-11-09 00:41:07 +00:00
|
|
|
|
|
|
|
browser.storage.onChanged.addListener(
|
|
|
|
(changes, areaname) => {
|
|
|
|
if (areaname === "local" && 'state' in changes) {
|
|
|
|
Object.assign(overlay, changes.state.newValue)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
2017-10-05 18:01:44 +01:00
|
|
|
export {state as default}
|