key input sequence as action/reducer

jh-changes
Shin'ya Ueoka 7 years ago
parent adc6a5175c
commit 879b5afe66
  1. 4
      src/actions/index.js
  2. 15
      src/actions/input.js
  3. 56
      src/background/index.js
  4. 39
      src/background/keys.js
  5. 4
      src/background/tabs.js
  6. 10
      src/content/index.js
  7. 23
      src/reducers/input.js
  8. 50
      test/background/key-queue.test.js
  9. 31
      test/background/keys.test.js

@ -29,4 +29,8 @@ export default {
FOLLOW_START: 'follow.start', FOLLOW_START: 'follow.start',
HISTORY_PREV: 'history.prev', HISTORY_PREV: 'history.prev',
HISTORY_NEXT: 'history.next', HISTORY_NEXT: 'history.next',
// User input
INPUT_KEY_PRESS: 'input.key,press',
INPUT_CLEAR_KEYS: 'input.clear.keys',
}; };

@ -0,0 +1,15 @@
import actions from '../actions';
export function keyPress(code, ctrl) {
return {
type: actions.INPUT_KEY_PRESS,
code,
ctrl
};
}
export function clearKeys() {
return {
type: actions.INPUT_CLEAR_KEYS
}
}

@ -1,22 +1,10 @@
import * as tabs from './tabs'; 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 backgroundReducers from '../reducers/background';
import inputReducers from '../reducers/input';
const queue = new KeyQueue(); let inputState = inputReducers(undefined, {});
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);
});
};
const normalizeUrl = (string) => { const normalizeUrl = (string) => {
try { try {
@ -51,8 +39,6 @@ const cmdEnterHandle = (request, sender) => {
browser.runtime.onMessage.addListener((request, sender) => { browser.runtime.onMessage.addListener((request, sender) => {
switch (request.type) { switch (request.type) {
case 'event.keypress':
return keyPressHandle(request, sender);
case 'event.cmd.enter': case 'event.cmd.enter':
return cmdEnterHandle(request, sender); return cmdEnterHandle(request, sender);
default: default:
@ -60,6 +46,36 @@ browser.runtime.onMessage.addListener((request, sender) => {
} }
}); });
browser.runtime.onMessage.addListener((action, sender) => { const keyQueueChanged = (sender, prevState, state) => {
return backgroundReducers(undefined, action, sender); 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);

@ -1,6 +1,6 @@
import actions from '../actions'; import actions from '../actions';
const DEFAULT_KEYMAP = { const defaultKeymap = {
':': { type: actions.CMD_OPEN }, ':': { type: actions.CMD_OPEN },
'o': { type: actions.CMD_TABS_OPEN, alter: false }, 'o': { type: actions.CMD_TABS_OPEN, alter: false },
'O': { type: actions.CMD_TABS_OPEN, alter: true }, 'O': { type: actions.CMD_TABS_OPEN, alter: true },
@ -32,34 +32,8 @@ const DEFAULT_KEYMAP = {
'L': { type: actions.HISTORY_NEXT }, 'L': { type: actions.HISTORY_NEXT },
} }
export default class KeyQueue { const asKeymapChars = (keys) => {
return keys.map((k) => {
constructor(keymap = DEFAULT_KEYMAP) {
this.data = [];
this.keymap = keymap;
}
push(key) {
this.data.push(key);
let current = this.asKeymapChars();
let filtered = Object.keys(this.keymap).filter((keys) => {
return keys.startsWith(current);
});
if (filtered.length == 0) {
this.data = [];
return null;
} else if (filtered.length === 1 && current === filtered[0]) {
let action = this.keymap[filtered[0]];
this.data = [];
return action;
}
return null;
}
asKeymapChars() {
return this.data.map((k) => {
let c = String.fromCharCode(k.code); let c = String.fromCharCode(k.code);
if (k.ctrl) { if (k.ctrl) {
return '<C-' + c.toUpperCase() + '>'; return '<C-' + c.toUpperCase() + '>';
@ -69,8 +43,8 @@ export default class KeyQueue {
}).join(''); }).join('');
} }
asCaretChars() { const asCaretChars = (keys) => {
return this.data.map((k) => { return keys.map((k) => {
let c = String.fromCharCode(k.code); let c = String.fromCharCode(k.code);
if (k.ctrl) { if (k.ctrl) {
return '^' + c.toUpperCase(); return '^' + c.toUpperCase();
@ -79,4 +53,5 @@ export default class KeyQueue {
} }
}).join(''); }).join('');
} }
}
export { defaultKeymap, asKeymapChars, asCaretChars };

@ -59,7 +59,7 @@ const getCompletions = (keyword) => {
}; };
const selectPrevTab = (current, count) => { const selectPrevTab = (current, count) => {
return browser.tabs.query({ currentWindow: true }, (tabs) => { return browser.tabs.query({ currentWindow: true }).then((tabs) => {
if (tabs.length < 2) { if (tabs.length < 2) {
return; return;
} }
@ -70,7 +70,7 @@ const selectPrevTab = (current, count) => {
}; };
const selectNextTab = (current, count) => { const selectNextTab = (current, count) => {
return browser.tabs.query({ currentWindow: true }, (tabs) => { return browser.tabs.query({ currentWindow: true }).then((tabs) => {
if (tabs.length < 2) { if (tabs.length < 2) {
return; return;
} }

@ -1,4 +1,5 @@
import '../console/console-frame.scss'; import '../console/console-frame.scss';
import * as inputActions from '../actions/input';
import * as consoleFrames from '../console/frames'; import * as consoleFrames from '../console/frames';
import actions from '../actions'; import actions from '../actions';
import contentReducer from '../reducers/content'; import contentReducer from '../reducers/content';
@ -14,14 +15,7 @@ window.addEventListener("keypress", (e) => {
if (e.target instanceof HTMLInputElement) { if (e.target instanceof HTMLInputElement) {
return; return;
} }
browser.runtime.sendMessage(inputActions.keyPress(e.which, e.ctrlKey))
let request = {
type: 'event.keypress',
code: e.which,
ctrl: e.ctrlKey,
}
browser.runtime.sendMessage(request)
.catch((err) => { .catch((err) => {
console.error("Vim Vixen:", err); console.error("Vim Vixen:", err);
return consoleFrames.showError(err.message); return consoleFrames.showError(err.message);

@ -0,0 +1,23 @@
import actions from '../actions';
const defaultState = {
keys: [],
};
export default function reducer(state = defaultState, action = {}) {
switch (action.type) {
case actions.INPUT_KEY_PRESS:
return Object.assign({}, state, {
keys: state.keys.concat([{
code: action.code,
ctrl: action.ctrl
}])
});
case actions.INPUT_CLEAR_KEYS:
return Object.assign({}, state, {
keys: [],
});
default:
return state;
}
}

@ -1,50 +0,0 @@
import { expect } from "chai";
import KeyQueue from '../../src/background/key-queue';
describe("keyQueue class", () => {
const KEYMAP = {
'g<C-X>GG': [],
'gg': [ 'scroll.top' ],
};
const g = 'g'.charCodeAt(0);
const G = 'G'.charCodeAt(0);
const x = 'x'.charCodeAt(0);
describe("#push", () => {
it("returns matched action", () => {
let queue = new KeyQueue(KEYMAP);
queue.push({ code: g });
let action = queue.push({ code: g });
expect(action).to.deep.equal([ 'scroll.top' ]);
});
it("returns null on no actions matched", () => {
let queue = new KeyQueue(KEYMAP);
queue.push({ code: g });
let action = queue.push({ code: G });
expect(action).to.be.null;
expect(queue.asKeymapChars()).to.be.empty;
});
});
describe('#asKeymapChars', () => {
let queue = new KeyQueue(KEYMAP);
queue.push({ code: g });
queue.push({ code: x, ctrl: true });
queue.push({ code: G });
expect(queue.asKeymapChars()).to.equal('g<C-X>G');
});
describe('#asCaretChars', () => {
let queue = new KeyQueue(KEYMAP);
queue.push({ code: g });
queue.push({ code: x, ctrl: true });
queue.push({ code: G });
expect(queue.asCaretChars()).to.equal('g^XG');
});
});

@ -0,0 +1,31 @@
import { expect } from "chai";
import * as keys from '../../src/background/keys';
describe("keys", () => {
const KEYMAP = {
'g<C-X>GG': [],
'gg': { type: 'scroll.top' },
};
const g = 'g'.charCodeAt(0);
const G = 'G'.charCodeAt(0);
const x = 'x'.charCodeAt(0);
describe('#asKeymapChars', () => {
let keySequence = [
{ code: g },
{ code: x, ctrl: true },
{ code: G }
];
expect(keys.asKeymapChars(keySequence)).to.equal('g<C-X>G');
});
describe('#asCaretChars', () => {
let keySequence = [
{ code: g },
{ code: x, ctrl: true },
{ code: G }
];
expect(keys.asCaretChars(keySequence)).to.equal('g^XG');
});
});