rehowl-r18
Version:
Opinionated React wrapper for Howler.js with React 18
73 lines (72 loc) • 2.67 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = require("react");
var howler_1 = __importDefault(require("howler"));
/**
* A hook to get a Howl instance for use with `<Play />`.
*
* Recommended when using Rehowl from a function component. If you're
* using a class component, you'll need to use `<Rehowl />`.
*/
function useHowl(howlOptions) {
var src = howlOptions.src, sprite = howlOptions.sprite, format = howlOptions.format, html5 = howlOptions.html5, preload = howlOptions.preload, xhrWithCredentials = howlOptions.xhrWithCredentials, _a = howlOptions.defaultVolume, defaultVolume = _a === void 0 ? 0 : _a;
var _b = react_1.useState(null), howl = _b[0], setHowl = _b[1];
// Force rerender on load state changes.
var _c = react_1.useState('unloaded'), setState = _c[1];
// Force rerender on unlock.
var _d = react_1.useState(true), setLocked = _d[1];
var _e = react_1.useState(null), error = _e[0], setError = _e[1];
react_1.useEffect(function () {
var newHowl = new howler_1.default.Howl({
autoplay: false,
format: format,
html5: html5,
onload: function () { return setState('loaded'); },
onloaderror: function (id, message) { return setError({ id: id, message: message }); },
onunlock: function () {
setLocked(false);
},
preload: preload,
sprite: sprite,
src: src,
volume: defaultVolume,
xhrWithCredentials: xhrWithCredentials,
});
setHowl(newHowl);
return function () {
setHowl(null);
setState('unloaded');
setLocked(true);
setError(null);
if (!newHowl)
return;
newHowl.off();
newHowl.stop();
newHowl.unload();
};
}, [JSON.stringify(src), JSON.stringify(sprite), JSON.stringify(format), html5, xhrWithCredentials, preload, defaultVolume]);
if (!howl) {
return {
howl: null,
error: null,
state: 'unloaded',
load: function () { },
};
}
var state = howl.state();
return {
howl: howl,
error: error,
state: state,
load: state === 'unloaded'
? function () {
howl && howl.load();
setState('loading');
}
: function () { },
};
}
exports.default = useHowl;