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} />; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
P.S.
this.setState()
updates state asynchronously, so accessingthis.state.access
inrefreshIO
might not pull the right value. You can forcerefreshIO
's setState call to be atomic by passing a function instead of an object.See https://facebook.github.io/react/docs/react-component.html#setstate for more info