Type Redux store and middleware (#24843)
This commit is contained in:
parent
e1f466fbbe
commit
6aeb162927
9 changed files with 61 additions and 35 deletions
56
app/javascript/mastodon/store/middlewares/sounds.ts
Normal file
56
app/javascript/mastodon/store/middlewares/sounds.ts
Normal file
|
@ -0,0 +1,56 @@
|
|||
import { Middleware, AnyAction } from 'redux';
|
||||
import { RootState } from '..';
|
||||
|
||||
interface AudioSource {
|
||||
src: string
|
||||
type: string
|
||||
}
|
||||
|
||||
const createAudio = (sources: AudioSource[]) => {
|
||||
const audio = new Audio();
|
||||
sources.forEach(({ type, src }) => {
|
||||
const source = document.createElement('source');
|
||||
source.type = type;
|
||||
source.src = src;
|
||||
audio.appendChild(source);
|
||||
});
|
||||
return audio;
|
||||
};
|
||||
|
||||
const play = (audio: HTMLAudioElement) => {
|
||||
if (!audio.paused) {
|
||||
audio.pause();
|
||||
if (typeof audio.fastSeek === 'function') {
|
||||
audio.fastSeek(0);
|
||||
} else {
|
||||
audio.currentTime = 0;
|
||||
}
|
||||
}
|
||||
|
||||
audio.play();
|
||||
};
|
||||
|
||||
export const soundsMiddleware = (): Middleware<Record<string, never>, RootState> => {
|
||||
const soundCache: {[key: string]: HTMLAudioElement} = {
|
||||
boop: createAudio([
|
||||
{
|
||||
src: '/sounds/boop.ogg',
|
||||
type: 'audio/ogg',
|
||||
},
|
||||
{
|
||||
src: '/sounds/boop.mp3',
|
||||
type: 'audio/mpeg',
|
||||
},
|
||||
]),
|
||||
};
|
||||
|
||||
return () => next => (action: AnyAction) => {
|
||||
const sound = action?.meta?.sound;
|
||||
|
||||
if (sound && soundCache[sound]) {
|
||||
play(soundCache[sound]);
|
||||
}
|
||||
|
||||
return next(action);
|
||||
};
|
||||
};
|
Loading…
Add table
Add a link
Reference in a new issue