1
0
mirror of https://github.com/funamitech/mastodon synced 2024-12-01 00:08:39 +09:00
YuruToot/app/javascript/mastodon/store/middlewares/sounds.ts

86 lines
1.9 KiB
TypeScript
Raw Normal View History

2024-01-08 19:57:40 +09:00
import { isAction } from '@reduxjs/toolkit';
import type { Middleware, UnknownAction } from '@reduxjs/toolkit';
import ready from 'mastodon/ready';
import { assetHost } from 'mastodon/utils/config';
import type { RootState } from '..';
interface AudioSource {
src: string;
type: string;
}
2024-01-08 19:57:40 +09:00
interface ActionWithMetaSound extends UnknownAction {
meta: { sound: string };
}
function isActionWithMetaSound(action: unknown): action is ActionWithMetaSound {
return (
isAction(action) &&
'meta' in action &&
typeof action.meta === 'object' &&
!!action.meta &&
'sound' in action.meta &&
typeof action.meta.sound === '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;
}
}
void audio.play();
};
2024-01-08 19:57:40 +09:00
export const soundsMiddleware = (): Middleware<
// eslint-disable-next-line @typescript-eslint/no-empty-object-type -- we need to use `{}` here to ensure the dispatch types can be merged
2024-04-02 18:56:03 +09:00
{},
2024-01-08 19:57:40 +09:00
RootState
> => {
const soundCache: Record<string, HTMLAudioElement> = {};
void ready(() => {
soundCache.boop = createAudio([
{
src: `${assetHost}/sounds/boop.ogg`,
type: 'audio/ogg',
},
{
src: `${assetHost}/sounds/boop.mp3`,
type: 'audio/mpeg',
},
]);
});
2024-01-08 19:57:40 +09:00
return () => (next) => (action) => {
if (isActionWithMetaSound(action)) {
const sound = action.meta.sound;
if (sound) {
const s = soundCache[sound];
if (s) play(s);
}
2024-01-08 19:57:40 +09:00
}
2024-01-08 19:57:40 +09:00
return next(action);
};
};