Last active
February 8, 2017 22:11
-
-
Save eric-wood/39352ce1abc85cff3400389cc71c47be to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function withMidi(WrappedComponent) { | |
return class extends React.Component { | |
constructor(props) { | |
super(props); | |
hasMidi = Boolean(navigator.requestMIDIAccess); | |
this.state = { | |
access: undefined, | |
input: undefined, | |
output: undefined, | |
status: hasMidi ? 'pending' : 'unavailable' | |
}; | |
this.refreshIO = this.refreshIO.bind(this); | |
this.requestSuccess = this.requestSuccess.bind(this); | |
this.requestFailure = this.requestFailure.bind(this); | |
if(hasMidi) { | |
navigator.requestMIDIAccess({ sysex: props.sysex }) | |
.then(this.requestSuccess, this.requestFailure); | |
} | |
} | |
requestSuccess(access) { | |
access.addEventListener('onstatechange', this.refreshIO); | |
this.setState({ access }); | |
this.refreshIO(); | |
} | |
refreshIO() { | |
this.setState({ | |
input: MIDI.getInput(this.state.access), | |
output: MIDI.getOutput(this.state.access) | |
}); | |
} | |
requestFailure(error) { | |
this.setState({ | |
status: 'declined' | |
}); | |
} | |
render() { | |
return <WrappedComponent midi={this.state} {...this.props} />; | |
} | |
} | |
} |
P.S. this.setState()
updates state asynchronously, so accessing this.state.access
in refreshIO
might not pull the right value. You can force refreshIO
's setState call to be atomic by passing a function instead of an object.
refreshIO() {
this.setState((prevState, props) => ({
input: MIDI.getInput(prevState.access),
output: MIDI.getOutput(prevState.access)
}));
}
See https://facebook.github.io/react/docs/react-component.html#setstate for more info
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you're using Babel stage-2+ presets, you can auto-bind the functions by declaring them as arrow-function class properties
You need to pass
access
tothis.refreshIO()
also
hasMidi
is being declared as a global. Otherwise, LGTM!