mymusics

retro MySpace-style music player
Log | Files | Refs | README

usePlayerKeyboard.ts (1032B)


      1 import { useEffect, type RefObject } from "react";
      2 
      3 type Options = {
      4   audioRef: RefObject<HTMLAudioElement | null>;
      5   enabled: boolean;
      6   onNext: () => void;
      7 };
      8 
      9 export function usePlayerKeyboard({ audioRef, enabled, onNext }: Options) {
     10   useEffect(() => {
     11     if (!enabled) return;
     12     const onKey = (e: KeyboardEvent) => {
     13       const tag = (e.target as HTMLElement)?.tagName?.toLowerCase();
     14       if (tag === "input" || tag === "textarea" || tag === "select") return;
     15       const a = audioRef.current;
     16       if (!a) return;
     17       if (e.code === "Space") {
     18         e.preventDefault();
     19         if (a.paused) void a.play().catch(() => {});
     20         else a.pause();
     21       } else if (e.key === "n" || e.key === "N") {
     22         e.preventDefault();
     23         onNext();
     24       } else if (e.key === "m" || e.key === "M") {
     25         e.preventDefault();
     26         a.muted = !a.muted;
     27       }
     28     };
     29     window.addEventListener("keydown", onKey);
     30     return () => window.removeEventListener("keydown", onKey);
     31   }, [audioRef, enabled, onNext]);
     32 }