All files / src/components/music/piano PianoKeyboard.tsx

0% Statements 0/81
0% Branches 0/18
0% Functions 0/18
0% Lines 0/78

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
import React, { useCallback, useEffect, useRef } from "react";
import { StyledPianoKeyboard, StyledPianoKey } from "./style";
import { MAX_OCTAVE, TOTAL_OCTAVES } from "consts";
import { useAppSelector } from "store/hooks";
 
interface PianoKeyboardProps {
  onPlayNote: (noteIndex: number) => void;
}
 
interface PianoKeyProps {
  noteNumber: number;
  note: (typeof notes)[number];
  octave: number;
  isBlack: boolean;
  isTall: boolean;
  isC: boolean;
  onMouseDownNote: (noteNumber: number) => void;
  onMouseEnterNote: (noteNumber: number) => void;
}
 
const octaves = Array.from({ length: TOTAL_OCTAVES }, (_, i) => MAX_OCTAVE - i);
 
const notes = [
  "B",
  "A#",
  "A",
  "G#",
  "G",
  "F#",
  "F",
  "E",
  "D#",
  "D",
  "C#",
  "C",
] as const;
 
const blackNotes = new Set(["A#", "G#", "F#", "D#", "C#"]);
const tallNotes = new Set(["A", "G", "D"]);
 
const PianoKey = React.memo(
  ({
    noteNumber,
    note,
    octave,
    isBlack,
    isTall,
    isC,
    onMouseDownNote,
    onMouseEnterNote,
  }: PianoKeyProps) => {
    const isHighlighted = useAppSelector(
      (state) => state.tracker.hoverNote === noteNumber,
    );
 
    const handleMouseDown = useCallback(
      (e: React.MouseEvent<HTMLDivElement>) => {
        e.preventDefault();
        e.stopPropagation();
        Iif (e.buttons & 1) {
          onMouseDownNote(noteNumber);
        }
      },
      [noteNumber, onMouseDownNote],
    );
 
    const handleMouseEnter = useCallback(() => {
      onMouseEnterNote(noteNumber);
    }, [noteNumber, onMouseEnterNote]);
 
    return (
      <StyledPianoKey
        data-note-number={noteNumber}
        $color={isBlack ? "black" : "white"}
        $highlight={isHighlighted}
        $tall={isTall || undefined}
        title={`${note}${octave}`}
        onMouseDown={handleMouseDown}
        onMouseEnter={handleMouseEnter}
      >
        {isC ? `C${octave}` : undefined}
      </StyledPianoKey>
    );
  },
);
 
PianoKey.displayName = "PianoKey";
 
export const PianoKeyboard = ({ onPlayNote }: PianoKeyboardProps) => {
  const keyboardRef = useRef<HTMLDivElement | null>(null);
  const activeTouchesRef = useRef(new Map<number, number | null>());
  const isDraggingRef = useRef(false);
 
  const getNoteFromTouch = useCallback((touch: React.Touch | Touch) => {
    const element = document.elementFromPoint(
      touch.clientX,
      touch.clientY,
    ) as HTMLElement | null;
 
    const keyElement = element?.closest(
      "[data-note-number]",
    ) as HTMLElement | null;
 
    Iif (!keyElement) {
      return null;
    }
 
    const noteNumber = Number(keyElement.dataset.noteNumber);
    return Number.isNaN(noteNumber) ? null : noteNumber;
  }, []);
 
  const handleTouchStart = useCallback(
    (e: React.TouchEvent<HTMLDivElement>) => {
      e.preventDefault();
      e.stopPropagation();
 
      for (const touch of Array.from(e.changedTouches)) {
        const noteNumber = getNoteFromTouch(touch);
        activeTouchesRef.current.set(touch.identifier, noteNumber);
 
        Iif (noteNumber !== null) {
          onPlayNote(noteNumber);
        }
      }
    },
    [getNoteFromTouch, onPlayNote],
  );
 
  const handleTouchMove = useCallback(
    (e: React.TouchEvent<HTMLDivElement>) => {
      e.preventDefault();
      e.stopPropagation();
 
      for (const touch of Array.from(e.changedTouches)) {
        const previousNote = activeTouchesRef.current.get(touch.identifier);
        const noteNumber = getNoteFromTouch(touch);
 
        Iif (noteNumber !== previousNote) {
          activeTouchesRef.current.set(touch.identifier, noteNumber);
          Iif (noteNumber !== null) {
            onPlayNote(noteNumber);
          }
        }
      }
    },
    [getNoteFromTouch, onPlayNote],
  );
 
  const handleTouchEnd = useCallback((e: React.TouchEvent<HTMLDivElement>) => {
    e.preventDefault();
    e.stopPropagation();
    for (const touch of Array.from(e.changedTouches)) {
      activeTouchesRef.current.delete(touch.identifier);
    }
  }, []);
 
  const handleTouchCancel = useCallback(
    (e: React.TouchEvent<HTMLDivElement>) => {
      e.stopPropagation();
      for (const touch of Array.from(e.changedTouches)) {
        activeTouchesRef.current.delete(touch.identifier);
      }
    },
    [],
  );
 
  const handleMouseDown = useCallback(
    (noteNumber: number) => {
      isDraggingRef.current = true;
      onPlayNote(noteNumber);
    },
    [onPlayNote],
  );
 
  const handleMouseEnter = useCallback(
    (noteNumber: number) => {
      Iif (isDraggingRef.current) {
        onPlayNote(noteNumber);
      }
    },
    [onPlayNote],
  );
 
  useEffect(() => {
    const handleMouseUp = () => {
      isDraggingRef.current = false;
    };
 
    window.addEventListener("mouseup", handleMouseUp);
    return () => window.removeEventListener("mouseup", handleMouseUp);
  }, []);
 
  return (
    <StyledPianoKeyboard
      ref={keyboardRef}
      onTouchStart={handleTouchStart}
      onTouchMove={handleTouchMove}
      onTouchEnd={handleTouchEnd}
      onTouchCancel={handleTouchCancel}
      style={{ touchAction: "none" }}
    >
      {octaves.map((octave) => {
        const base = (octave - 3) * 12;
        return notes.map((note, index) => {
          const offset = notes.length - 1 - index;
          const noteNumber = base + offset;
          const isBlack = blackNotes.has(note);
          const isTall = tallNotes.has(note);
          const isC = note === "C";
 
          return (
            <PianoKey
              key={`${note}${octave}`}
              noteNumber={noteNumber}
              note={note}
              octave={octave}
              isBlack={isBlack}
              isTall={isTall}
              isC={isC}
              onMouseDownNote={handleMouseDown}
              onMouseEnterNote={handleMouseEnter}
            />
          );
        });
      })}
    </StyledPianoKeyboard>
  );
};