diff options
Diffstat (limited to 'src/background/index.js')
-rw-r--r-- | src/background/index.js | 56 |
1 files changed, 36 insertions, 20 deletions
diff --git a/src/background/index.js b/src/background/index.js index 3fa8553..4d75b33 100644 --- a/src/background/index.js +++ b/src/background/index.js @@ -1,22 +1,10 @@ import * as tabs from './tabs'; -import KeyQueue from './key-queue'; +import * as keys from './keys'; +import * as inputActions from '../actions/input'; import backgroundReducers from '../reducers/background'; +import inputReducers from '../reducers/input'; -const queue = new KeyQueue(); - -const keyPressHandle = (request, sender) => { - let action = queue.push({ - code: request.code, - ctrl: request.ctrl - }); - if (!action) { - return Promise.resolve(); - } - - return backgroundReducers(undefined, action, sender).then(() => { - return browser.tabs.sendMessage(sender.tab.id, action); - }); -}; +let inputState = inputReducers(undefined, {}); const normalizeUrl = (string) => { try { @@ -51,8 +39,6 @@ const cmdEnterHandle = (request, sender) => { browser.runtime.onMessage.addListener((request, sender) => { switch (request.type) { - case 'event.keypress': - return keyPressHandle(request, sender); case 'event.cmd.enter': return cmdEnterHandle(request, sender); default: @@ -60,6 +46,36 @@ browser.runtime.onMessage.addListener((request, sender) => { } }); -browser.runtime.onMessage.addListener((action, sender) => { +const keyQueueChanged = (sender, prevState, state) => { + if (state.keys.length === 0) { + return Promise.resolve(); + } + + let prefix = keys.asKeymapChars(state.keys); + let matched = Object.keys(keys.defaultKeymap).filter((keys) => { + return keys.startsWith(prefix); + }); + if (matched.length == 0) { + return handleMessage(inputActions.clearKeys(), sender); + } else if (matched.length > 1 || matched.length === 1 && prefix !== matched[0]) { + return Promise.resolve(); + } + let action = keys.defaultKeymap[matched]; + return handleMessage(inputActions.clearKeys(), sender).then(() => { + return backgroundReducers(undefined, action, sender).then(() => { + return browser.tabs.sendMessage(sender.tab.id, action); + }); + }); +}; + +const handleMessage = (action, sender) => { + let nextInputState = inputReducers(inputState, action); + if (JSON.stringify(nextInputState) !== JSON.stringify(inputState)) { + let prevState = inputState; + inputState = nextInputState; + return keyQueueChanged(sender, prevState, inputState); + } return backgroundReducers(undefined, action, sender); -}); +}; + +browser.runtime.onMessage.addListener(handleMessage); |