-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathActionEventBus.ts
89 lines (78 loc) · 2.59 KB
/
ActionEventBus.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import { Action, ActionEvent, InputType } from './Action';
import { KeyboardEvent, MouseEvent } from 'react';
import * as _ from 'lodash';
import { CanvasEngine } from '../CanvasEngine';
import { BaseModel } from '../core-models/BaseModel';
export class ActionEventBus {
protected actions: { [id: string]: Action };
protected engine: CanvasEngine;
protected keys: { [key: string]: boolean };
constructor(engine: CanvasEngine) {
this.actions = {};
this.engine = engine;
this.keys = {};
}
getKeys(): string[] {
return _.keys(this.keys);
}
registerAction(action: Action): () => void {
action.setEngine(this.engine);
this.actions[action.id] = action;
return () => {
this.deregisterAction(action);
};
}
deregisterAction(action: Action) {
action.setEngine(null);
delete this.actions[action.id];
}
getActionsForType(type: InputType): Action[] {
return _.filter(this.actions, (action) => {
return action.options.type === type;
});
}
getModelForEvent(actionEvent: ActionEvent<MouseEvent>): BaseModel {
if (actionEvent.model) {
return actionEvent.model;
}
return this.engine.getMouseElement(actionEvent.event);
}
getActionsForEvent(actionEvent: ActionEvent): Action[] {
const { event } = actionEvent;
if (event.type === 'mousedown') {
return this.getActionsForType(InputType.MOUSE_DOWN);
} else if (event.type === 'mouseup') {
return this.getActionsForType(InputType.MOUSE_UP);
} else if (event.type === 'keydown') {
// store the recorded key
this.keys[(event as KeyboardEvent).key.toLowerCase()] = true;
return this.getActionsForType(InputType.KEY_DOWN);
} else if (event.type === 'keyup') {
// delete the recorded key
delete this.keys[(event as KeyboardEvent).key.toLowerCase()];
return this.getActionsForType(InputType.KEY_UP);
} else if (event.type === 'mousemove') {
return this.getActionsForType(InputType.MOUSE_MOVE);
} else if (event.type === 'wheel') {
return this.getActionsForType(InputType.MOUSE_WHEEL);
} else if (event.type === 'touchstart') {
return this.getActionsForType(InputType.TOUCH_START);
} else if (event.type === 'touchend') {
return this.getActionsForType(InputType.TOUCH_END);
} else if (event.type === 'touchmove') {
return this.getActionsForType(InputType.TOUCH_MOVE);
}
return [];
}
fireAction(actionEvent: ActionEvent) {
const actions = this.getActionsForEvent(actionEvent);
for (let action of actions) {
action.options.fire(actionEvent as any);
}
}
clearKeys() {
_.forEach(Object.keys(this.keys), (key) => {
document.dispatchEvent(new KeyboardEvent('keyup', { key: key }));
});
}
}