Untitled

Anonymous
Plain Text
09/15/2025 8:32 PM
11.5 KB
16
Indexable
Never
import React, { useState, useRef, useEffect } from "react";
// Spotify-style Practice Player ("EchoPlay")
// Single-file React component using Tailwind CSS.
// NOTE: This is for learning / UI practice only. Do NOT use any Spotify trademarks or assets.

// NPM deps available in the environment:
// - lucide-react (icons)
// Tailwind must be set up in your project to render styles.

import {
  Play,
  Pause,
  SkipForward,
  SkipBack,
  Volume,
  Shuffle,
  Repeat,
  Heart,
  Search,
} from "lucide-react";

const tracks = [
  {
    id: 1,
    title: "Ocean Drive",
    artist: "Practice Band",
    album: "Late Nights",
    duration: 184,
    // replace with a real mp3 URL or relative path in your project
    src: "",
    // optional cover art (data URL or external image)
    cover: "",
  },
  {
    id: 2,
    title: "City Lights",
    artist: "Practice Band",
    album: "Late Nights",
    duration: 212,
    src: "",
    cover: "",
  },
  {
    id: 3,
    title: "Easy Mornings",
    artist: "Practice Band",
    album: "Sunrise EP",
    duration: 161,
    src: "",
    cover: "",
  },
];

function formatTime(s) {
  if (!s && s !== 0) return "0:00";
  const minutes = Math.floor(s / 60);
  const seconds = Math.floor(s % 60)
    .toString()
    .padStart(2, "0");
  return `${minutes}:${seconds}`;
}

export default function EchoPlay() {
  const [currentIndex, setCurrentIndex] = useState(0);
  const [isPlaying, setIsPlaying] = useState(false);
  const [progress, setProgress] = useState(0); // seconds
  const [volume, setVolume] = useState(0.8);
  const [shuffle, setShuffle] = useState(false);
  const [repeat, setRepeat] = useState(false);
  const [liked, setLiked] = useState({});

  const audioRef = useRef(null);
  const progressRef = useRef(null);

  const current = tracks[currentIndex];

  useEffect(() => {
    const audio = audioRef.current;
    if (!audio) return;

    audio.volume = volume;

    const timeUpdate = () => setProgress(audio.currentTime);
    const ended = () => {
      if (repeat) {
        audio.currentTime = 0;
        audio.play();
      } else {
        handleNext();
      }
    };

    audio.addEventListener("timeupdate", timeUpdate);
    audio.addEventListener("ended", ended);

    return () => {
      audio.removeEventListener("timeupdate", timeUpdate);
      audio.removeEventListener("ended", ended);
    };
  }, [currentIndex, volume, repeat]);

  useEffect(() => {
    const audio = audioRef.current;
    if (!audio) return;
    if (isPlaying) audio.play().catch(() => setIsPlaying(false));
    else audio.pause();
  }, [isPlaying, currentIndex]);

  const handlePlayPause = () => setIsPlaying((p) => !p);

  const handlePrev = () => {
    setProgress(0);
    setIsPlaying(false);
    setTimeout(() => {
      setCurrentIndex((i) => (i === 0 ? tracks.length - 1 : i - 1));
      setIsPlaying(true);
    }, 50);
  };

  const handleNext = () => {
    setProgress(0);
    setIsPlaying(false);
    setTimeout(() => {
      setCurrentIndex((i) => {
        if (shuffle) return Math.floor(Math.random() * tracks.length);
        return i === tracks.length - 1 ? 0 : i + 1;
      });
      setIsPlaying(true);
    }, 50);
  };

  const handleSeek = (e) => {
    const audio = audioRef.current;
    if (!audio) return;
    const rect = progressRef.current.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const pct = Math.max(0, Math.min(1, x / rect.width));
    audio.currentTime = pct * audio.duration || 0;
    setProgress(audio.currentTime);
  };

  const handleVolume = (e) => {
    const v = parseFloat(e.target.value);
    setVolume(v);
    if (audioRef.current) audioRef.current.volume = v;
  };

  const toggleLike = (id) => {
    setLiked((l) => ({ ...l, [id]: !l[id] }));
  };

  return (
    <div className="min-h-screen bg-gradient-to-b from-gray-100 to-white flex flex-col">
      <div className="flex-1 max-w-6xl mx-auto w-full p-6 grid grid-cols-12 gap-6">
        {/* Sidebar */}
        <aside className="col-span-2 bg-white rounded-2xl p-4 shadow-md flex flex-col">
          <div className="mb-4 text-sm font-semibold text-gray-700">EchoPlay</div>

          <nav className="flex-1 space-y-2">
            <button className="w-full text-left flex items-center gap-3 px-3 py-2 rounded-lg hover:bg-gray-50">
              <svg className="w-5 h-5 opacity-80" viewBox="0 0 24 24" fill="none">
                <circle cx="12" cy="12" r="10" strokeWidth="1.5" stroke="#9ca3af" />
              </svg>
              <span className="text-sm font-medium">Home</span>
            </button>
            <button className="w-full text-left flex items-center gap-3 px-3 py-2 rounded-lg hover:bg-gray-50">
              <Search className="w-5 h-5 opacity-80" />
              <span className="text-sm font-medium">Search</span>
            </button>
            <button className="w-full text-left flex items-center gap-3 px-3 py-2 rounded-lg hover:bg-gray-50">
              <svg className="w-5 h-5 opacity-80" viewBox="0 0 24 24" fill="none">
                <rect x="3" y="5" width="18" height="14" rx="2" stroke="#9ca3af" strokeWidth="1.5" />
              </svg>
              <span className="text-sm font-medium">Your Library</span>
            </button>
          </nav>

          <div className="mt-4 text-xs text-gray-500">Practice UI — for learning. Not affiliated with any music service.</div>
        </aside>

        {/* Main content */}
        <main className="col-span-8 bg-white rounded-2xl p-6 shadow-md">
          <header className="flex items-center justify-between mb-6">
            <div className="text-lg font-semibold">Browse</div>
            <div className="flex items-center gap-3">
              <input
                placeholder="Search songs, artists..."
                className="px-3 py-2 rounded-full border border-gray-200 text-sm w-64"
              />
              <button className="px-3 py-2 rounded-full bg-gray-50 border">Upgrade</button>
            </div>
          </header>

          <section className="grid grid-cols-3 gap-4">
            {tracks.map((t, i) => (
              <article key={t.id} className="p-4 rounded-xl bg-gradient-to-b from-white to-gray-50 border">
                <div className="w-full h-40 bg-gray-100 rounded-lg flex items-center justify-center text-gray-400 font-semibold">
                  {t.cover ? (
                    <img src={t.cover} alt={`${t.title} cover`} className="w-full h-full object-cover rounded-lg" />
                  ) : (
                    <div className="text-sm">Album Art</div>
                  )}
                </div>
                <div className="mt-3 flex items-start justify-between">
                  <div>
                    <div className="font-semibold">{t.title}</div>
                    <div className="text-xs text-gray-500">{t.artist}</div>
                  </div>
                  <div className="text-xs text-gray-500">{formatTime(t.duration)}</div>
                </div>
                <div className="mt-3 flex items-center gap-2">
                  <button
                    onClick={() => {
                      setCurrentIndex(i);
                      setIsPlaying(true);
                    }}
                    className="flex-1 px-3 py-2 rounded-lg border hover:bg-gray-50"
                  >
                    Play
                  </button>
                  <button onClick={() => toggleLike(t.id)} className="p-2 rounded-lg hover:bg-gray-50">
                    <Heart className={`w-4 h-4 ${liked[t.id] ? "text-red-500" : "text-gray-400"}`} />
                  </button>
                </div>
              </article>
            ))}
          </section>
        </main>

        {/* Right column - queue / mini info */}
        <aside className="col-span-2 bg-white rounded-2xl p-4 shadow-md flex flex-col">
          <div className="text-sm font-semibold mb-3">Now Playing</div>

          <div className="flex items-center gap-3">
            <div className="w-14 h-14 bg-gray-100 rounded-md flex items-center justify-center">Art</div>
            <div>
              <div className="font-medium">{current.title}</div>
              <div className="text-xs text-gray-500">{current.artist}</div>
            </div>
          </div>

          <div className="mt-4 text-sm font-semibold">Queue</div>
          <ol className="mt-2 space-y-2 text-sm text-gray-600 flex-1 overflow-auto">
            {tracks.map((t, i) => (
              <li key={t.id} className={`flex items-center justify-between p-2 rounded ${i === currentIndex ? "bg-gray-50" : ""}`}>
                <div>
                  <div className="truncate w-36">{t.title}</div>
                  <div className="text-xs text-gray-400">{t.artist}</div>
                </div>
                <div className="text-xs text-gray-400">{formatTime(t.duration)}</div>
              </li>
            ))}
          </ol>
        </aside>
      </div>

      {/* Player bar */}
      <div className="w-full bg-white border-t shadow-inner">
        <div className="max-w-6xl mx-auto px-6 py-3 flex items-center justify-between">
          <div className="flex items-center gap-3 w-1/4">
            <div className="w-12 h-12 bg-gray-100 rounded-md flex items-center justify-center">Art</div>
            <div>
              <div className="text-sm font-semibold">{current.title}</div>
              <div className="text-xs text-gray-500">{current.artist}</div>
            </div>
            <button className="ml-2 p-1 rounded hover:bg-gray-50" onClick={() => toggleLike(current.id)}>
              <Heart className={`w-4 h-4 ${liked[current.id] ? "text-red-500" : "text-gray-400"}`} />
            </button>
          </div>

          <div className="flex flex-col items-center w-1/2">
            <div className="flex items-center gap-6 mb-2">
              <Shuffle className={`w-5 h-5 cursor-pointer ${shuffle ? "text-green-600" : "text-gray-400"}`} onClick={() => setShuffle((s) => !s)} />
              <SkipBack className="w-6 h-6 cursor-pointer" onClick={handlePrev} />

              <button
                onClick={handlePlayPause}
                className="w-12 h-12 rounded-full flex items-center justify-center shadow-md bg-white border"
              >
                {isPlaying ? <Pause className="w-5 h-5" /> : <Play className="w-5 h-5" />}
              </button>

              <SkipForward className="w-6 h-6 cursor-pointer" onClick={handleNext} />
              <Repeat className={`w-5 h-5 cursor-pointer ${repeat ? "text-green-600" : "text-gray-400"}`} onClick={() => setRepeat((r) => !r)} />
            </div>

            <div className="w-full flex items-center gap-3">
              <div className="text-xs text-gray-500">{formatTime(progress)}</div>
              <div
                ref={progressRef}
                onClick={handleSeek}
                className="h-2 bg-gray-200 rounded-full flex-1 relative cursor-pointer"
              >
                <div
                  style={{ width: `${(progress / (audioRef.current?.duration || 1)) * 100}%` }}
                  className="h-2 rounded-full bg-gradient-to-r from-green-400 to-blue-500"
                />
              </div>
              <div className="text-xs text-gray-500">{formatTime(audioRef.current?.duration || current.duration)}</div>
            </div>
          </div>

          <div className="flex items-center gap-3 w-1/4 justify-end">
            <Volume className="w-5 h-5" />
            <input type="range" min="0" max="1" step="0.01" value={volume} onChange={handleVolume} />
          </div>
        </div>
      </div>

      {/* Hidden audio element */}
      <audio ref={audioRef} src={current.src} preload="metadata" />
    </div>
  );
}
Editor is loading...
Leave a Comment