aboutsummaryrefslogtreecommitdiff
path: root/src/content/components/content-input.js
diff options
context:
space:
mode:
authorShin'ya Ueoka <ueokande@i-beam.org>2017-10-08 15:19:25 +0900
committerGitHub <noreply@github.com>2017-10-08 15:19:25 +0900
commit0183161145d36cbafb7dbd86ca3a1aac6faca43f (patch)
treeaed757bfb5f8789156439d1e1fdff4e221376aaa /src/content/components/content-input.js
parent0f54a203dba38acdd080a928cee95f875fe84706 (diff)
parent57f798044d32ba7f9dc10a34ac31ad5dbdbf56ae (diff)
Merge pull request #22 from ueokande/separate-domains
Refactor: Separate domains
Diffstat (limited to 'src/content/components/content-input.js')
-rw-r--r--src/content/components/content-input.js67
1 files changed, 67 insertions, 0 deletions
diff --git a/src/content/components/content-input.js b/src/content/components/content-input.js
new file mode 100644
index 0000000..9568caf
--- /dev/null
+++ b/src/content/components/content-input.js
@@ -0,0 +1,67 @@
+export default class ContentInputComponent {
+ constructor(target) {
+ this.pressed = {};
+ this.onKeyListeners = [];
+
+ target.addEventListener('keypress', this.onKeyPress.bind(this));
+ target.addEventListener('keydown', this.onKeyDown.bind(this));
+ target.addEventListener('keyup', this.onKeyUp.bind(this));
+ }
+
+ update() {
+ }
+
+ onKey(cb) {
+ this.onKeyListeners.push(cb);
+ }
+
+ onKeyPress(e) {
+ if (this.pressed[e.key] && this.pressed[e.key] !== 'keypress') {
+ return;
+ }
+ this.pressed[e.key] = 'keypress';
+ this.capture(e);
+ }
+
+ onKeyDown(e) {
+ if (this.pressed[e.key] && this.pressed[e.key] !== 'keydown') {
+ return;
+ }
+ this.pressed[e.key] = 'keydown';
+ this.capture(e);
+ }
+
+ onKeyUp(e) {
+ delete this.pressed[e.key];
+ }
+
+ capture(e) {
+ if (this.fromInput(e)) {
+ if (e.key === 'Escape' && e.target.blur) {
+ e.target.blur();
+ }
+ return;
+ }
+ if (e.key === 'OS') {
+ return;
+ }
+
+ let stop = false;
+ for (let listener of this.onKeyListeners) {
+ stop = stop || listener(e.key, e.ctrlKey);
+ if (stop) {
+ break;
+ }
+ }
+ if (stop) {
+ e.preventDefault();
+ e.stopPropagation();
+ }
+ }
+
+ fromInput(e) {
+ return e.target instanceof HTMLInputElement ||
+ e.target instanceof HTMLTextAreaElement ||
+ e.target instanceof HTMLSelectElement;
+ }
+}