forked from marijnh/Eloquent-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path19_1_keyboard_bindings.html
More file actions
52 lines (48 loc) · 1.51 KB
/
19_1_keyboard_bindings.html
File metadata and controls
52 lines (48 loc) · 1.51 KB
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
<!doctype html>
<base href="https://eloquentjavascript.net/">
<script src="code/chapter/19_paint.js"></script>
<div></div>
<script>
class PixelEditor {
constructor(state, config) {
let {tools, controls, dispatch} = config;
this.state = state;
this.canvas = new PictureCanvas(state.picture, pos => {
let tool = tools[this.state.tool];
let onMove = tool(pos, this.state, dispatch);
if (onMove) {
return pos => onMove(pos, this.state, dispatch);
}
});
this.controls = controls.map(
Control => new Control(state, config));
this.dom = elt("div", {
tabIndex: 0,
onkeydown: event => this.keyDown(event, config)
}, this.canvas.dom, elt("br"),
...this.controls.reduce(
(a, c) => a.concat(" ", c.dom), []));
}
keyDown(event, config) {
if (event.key == "z" && (event.ctrlKey || event.metaKey)) {
event.preventDefault();
config.dispatch({undo: true});
} else if (!event.ctrlKey && !event.metaKey && !event.altKey) {
for (let tool of Object.keys(config.tools)) {
if (tool[0] == event.key) {
event.preventDefault();
config.dispatch({tool});
return;
}
}
}
}
syncState(state) {
this.state = state;
this.canvas.syncState(state.picture);
for (let ctrl of this.controls) ctrl.syncState(state);
}
}
document.querySelector("div")
.appendChild(startPixelEditor({}));
</script>