MCPcopy Create free account
hub / github.com/SuboptimalEng/coding-tutorials / Piano

Class Piano

react-piano/src/components/Piano.js:12–88  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

10} from '../global/constants';
11
12class Piano extends React.Component {
13 constructor(props) {
14 super(props);
15 this.state = {
16 pressedKeys: [],
17 };
18 }
19
20 playNote = (note) => {
21 if (!_.isEmpty(note)) {
22 const noteAudio = new Audio(document.getElementById(note).src);
23 noteAudio.play();
24 }
25 }
26
27 handleKeyDown = (event) => {
28 if (event.repeat) {
29 return;
30 }
31 const key = event.key;
32 const updatedPressedKeys = [...this.state.pressedKeys];
33 if (!updatedPressedKeys.includes(key) && VALID_KEYS.includes(key)) {
34 updatedPressedKeys.push(key);
35 }
36 this.setState({
37 pressedKeys: updatedPressedKeys,
38 });
39 this.playNote(KEY_TO_NOTE[key]);
40 }
41
42 handleKeyUp = (event) => {
43 const index = this.state.pressedKeys.indexOf(event.key);
44 if (index > -1) {
45 this.setState(state => ({
46 pressedKeys: state.pressedKeys.splice(index, 1)
47 }));
48 }
49 }
50
51 componentDidMount = () => {
52 window.addEventListener('keydown', this.handleKeyDown);
53 window.addEventListener('keyup', this.handleKeyUp);
54 }
55
56 render() {
57 const keys = _.map(NOTES, (note, index) => {
58 return (
59 <Key
60 key={index}
61 note={note}
62 pressedKeys={this.state.pressedKeys}
63 />
64 );
65 });
66
67 const audioFiles = _.map(NOTES, (note, index) => {
68 return (
69 <audio

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected