source: frontend/src/pages/SongDetail.tsx@ a5406e1

main
Last change on this file since a5406e1 was a5406e1, checked in by Filip Gavrilovski <filipgavrilovski28@…>, 5 months ago

song repository bug fix; minor ui change

  • Property mode set to 100644
File size: 21.2 KB
Line 
1import { useEffect, useRef, useState } from "react";
2import { Link, useParams } from "react-router-dom";
3import axiosInstance from "../api/axiosInstance";
4import { useAuth } from "../context/authContext";
5import { usePlayer } from "../context/playerContext";
6import type { SongDetail as SongDetailType } from "../utils/types";
7
8const ROLE_LABELS: Record<string, string> = {
9 MAIN_VOCAL: "Main Vocal",
10 FEATURED: "Featured",
11 PRODUCER: "Producer",
12 SONGWRITER: "Songwriter",
13 COMPOSER: "Composer",
14 MIXER: "Mixer",
15 ENGINEER: "Engineer",
16};
17
18const formatRole = (role: string): string => {
19 return ROLE_LABELS[role] || role.replace(/_/g, " ");
20};
21
22// convert a regular youtube URL to an embeddable URL
23const toEmbedUrl = (url: string): string => {
24 try {
25 const parsed = new URL(url);
26 // youtube.com/watch?v=ID
27 if (
28 (parsed.hostname === "www.youtube.com" ||
29 parsed.hostname === "youtube.com") &&
30 parsed.searchParams.has("v")
31 ) {
32 return `https://www.youtube.com/embed/${parsed.searchParams.get("v")}`;
33 }
34 // youtu.be/ID
35 if (parsed.hostname === "youtu.be") {
36 return `https://www.youtube.com/embed${parsed.pathname}`;
37 }
38 // already an embed URL or other provider – return as-is
39 return url;
40 } catch {
41 return url;
42 }
43};
44
45const renderStars = (grade: number) => {
46 return (
47 <div className="flex gap-0.5">
48 {[1, 2, 3, 4, 5].map((star) => (
49 <svg
50 key={star}
51 className={`w-4 h-4 ${star <= grade ? "text-yellow-400" : "text-gray-600"}`}
52 fill="currentColor"
53 viewBox="0 0 20 20"
54 >
55 <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
56 </svg>
57 ))}
58 </div>
59 );
60};
61
62const SongDetail = () => {
63 const { id } = useParams<{ id: string }>();
64 const { user } = useAuth();
65 const { play, currentSong } = usePlayer();
66 const [song, setSong] = useState<SongDetailType | null>(null);
67 const [loading, setLoading] = useState(true);
68 const [error, setError] = useState<string | null>(null);
69 const [showReviewModal, setShowReviewModal] = useState(false);
70 const [reviewRating, setReviewRating] = useState(0);
71 const [reviewComment, setReviewComment] = useState("");
72 const [hoverRating, setHoverRating] = useState(0);
73 const [showPlaylistDropdown, setShowPlaylistDropdown] = useState(false);
74 const playlistDropdownRef = useRef<HTMLDivElement>(null);
75 console.log(user);
76 useEffect(() => {
77 const fetchSong = async () => {
78 try {
79 setLoading(true);
80 const response = await axiosInstance.get(`/songs/${id}/details`);
81 setSong(response.data);
82 } catch (err) {
83 console.error("Error fetching song details:", err);
84 setError("Failed to load song details.");
85 } finally {
86 setLoading(false);
87 }
88 };
89 if (id) fetchSong();
90 }, [id]);
91
92 // handle click outside for playlist dropdown
93 useEffect(() => {
94 const handleClickOutside = (event: MouseEvent) => {
95 if (
96 playlistDropdownRef.current &&
97 !playlistDropdownRef.current.contains(event.target as Node)
98 ) {
99 setShowPlaylistDropdown(false);
100 }
101 };
102
103 document.addEventListener("mousedown", handleClickOutside);
104 return () => {
105 document.removeEventListener("mousedown", handleClickOutside);
106 };
107 }, []);
108
109 const handleSubmitReview = async () => {
110 if (reviewRating === 0) {
111 // todo: replace with toast
112 alert("Please select a rating");
113 return;
114 }
115 try {
116 await axiosInstance.post(`reviews/${song?.id}`, {
117 grade: reviewRating,
118 comment: reviewComment,
119 });
120 const response = await axiosInstance.get(`/songs/${id}/details`);
121 setSong(response.data);
122 } catch (err) {
123 // todo: replace with toast
124 console.error("Error submitting review:", err);
125 } finally {
126 setShowReviewModal(false);
127 setReviewRating(0);
128 setReviewComment("");
129 setHoverRating(0);
130 }
131 };
132
133 const deleteReview = async () => {
134 try {
135 await axiosInstance.delete(`reviews/${song?.id}`);
136 const response = await axiosInstance.get(`/songs/${id}/details`);
137 setSong(response.data);
138 } catch (err) {
139 // todo :add toast
140 console.error("Error deleting review:", err);
141 }
142 };
143
144 const toggleLike = async () => {
145 if (!song) return;
146 try {
147 await axiosInstance.post(`/musical-entity/${song.id}/like`);
148 setSong((prev) =>
149 prev
150 ? { ...prev, isLikedByCurrentUser: !prev.isLikedByCurrentUser }
151 : prev,
152 );
153 } catch (err) {
154 console.error("Error toggling like:", err);
155 }
156 };
157
158 const handleAddToPlaylist = (playlistName: string) => {
159 console.log(`Adding song ${song?.id} to ${playlistName}`);
160 // TODO: actual API call
161 setShowPlaylistDropdown(false);
162 };
163
164 const handleCreateNewPlaylist = () => {
165 console.log(`Creating new playlist for song ${song?.id}`);
166 // TODO: actual playlist creation
167 setShowPlaylistDropdown(false);
168 };
169
170 if (loading) {
171 return (
172 <div className="min-h-screen bg-linear-to-br from-[#1e1e2e] to-[#0f0f1e] flex items-center justify-center">
173 <div className="flex flex-col items-center gap-4">
174 <div className="w-12 h-12 border-4 border-white/10 border-t-[#1db954] rounded-full animate-spin" />
175 <p className="text-gray-400 text-lg">Loading song…</p>
176 </div>
177 </div>
178 );
179 }
180
181 if (error || !song) {
182 return (
183 <div className="min-h-screen bg-linear-to-br from-[#1e1e2e] to-[#0f0f1e] flex items-center justify-center">
184 <div className="text-center">
185 <p className="text-red-400 text-xl mb-4">
186 {error ?? "Song not found"}
187 </p>
188 <Link to="/" className="text-[#1db954] hover:underline text-sm">
189 ← Back to Home
190 </Link>
191 </div>
192 </div>
193 );
194 }
195
196 const otherContributors = song.contributions.filter(
197 (c) => c.artistName !== song.releasedBy,
198 );
199
200 const avgRating =
201 song.reviews.length > 0
202 ? (
203 song.reviews.reduce((sum, r) => sum + r.grade, 0) /
204 song.reviews.length
205 ).toFixed(1)
206 : null;
207
208 return (
209 <div className="min-h-screen bg-linear-to-br from-[#1e1e2e] to-[#0f0f1e] text-white">
210 <div className="max-w-5xl mx-auto px-6 py-10">
211 {/* Back link */}
212 <Link
213 to="/"
214 className="inline-flex items-center gap-1 text-gray-400 hover:text-white text-sm mb-8 transition-colors"
215 >
216 <svg
217 className="w-4 h-4"
218 fill="none"
219 stroke="currentColor"
220 viewBox="0 0 24 24"
221 >
222 <path
223 strokeLinecap="round"
224 strokeLinejoin="round"
225 strokeWidth={2}
226 d="M15 19l-7-7 7-7"
227 />
228 </svg>
229 Back to Home
230 </Link>
231
232 {/* Hero section */}
233 <div className="flex flex-col md:flex-row gap-8 mb-10">
234 {/* Cover art */}
235 <div className="w-full md:w-72 shrink-0">
236 <div className="relative w-full pt-[100%] rounded-xl overflow-hidden shadow-2xl bg-[#181818]">
237 <img
238 src={song.cover || "/favicon.png"}
239 alt={song.title}
240 className="absolute inset-0 w-full h-full object-cover"
241 onError={(e) => {
242 (e.target as HTMLImageElement).src = "/favicon.png";
243 }}
244 />
245 </div>
246 </div>
247
248 {/* Song info */}
249 <div className="flex flex-col justify-end gap-3 min-w-0">
250 <span className="text-xs uppercase tracking-widest text-gray-400 font-medium">
251 {song.genre} • Song
252 </span>
253 <h1 className="text-4xl md:text-5xl font-extrabold leading-tight truncate">
254 {song.title}
255 </h1>
256
257 {/* Main artist */}
258 <p className="text-xl text-gray-300 font-semibold">
259 {song.releasedBy}
260 </p>
261
262 {/* Album */}
263 {song.album && (
264 <p className="text-sm text-gray-500">
265 Album: <span className="text-gray-300">{song.album}</span>
266 </p>
267 )}
268
269 {/* Rating summary */}
270 {avgRating && (
271 <div className="flex items-center gap-2 mt-1">
272 {renderStars(Math.round(Number(avgRating)))}
273 <span className="text-sm text-gray-400">
274 {avgRating} · {song.reviews.length}{" "}
275 {song.reviews.length === 1 ? "review" : "reviews"}
276 </span>
277 </div>
278 )}
279
280 {/* Action buttons */}
281 <div className="flex items-center gap-3 mt-4">
282 {/* Play button */}
283 {song.link && (
284 <button
285 onClick={() =>
286 play({
287 id: song.id,
288 title: song.title,
289 artist: song.releasedBy,
290 cover: song.cover,
291 embedUrl: toEmbedUrl(song.link!),
292 })
293 }
294 className={`flex items-center gap-2 px-6 py-3 rounded-full text-sm font-semibold transition-all cursor-pointer ${
295 currentSong?.id === song.id
296 ? "bg-white text-[#1db954]"
297 : "bg-[#1db954] text-black hover:bg-[#1ed760] hover:scale-105"
298 }`}
299 >
300 {currentSong?.id === song.id ? (
301 <>
302 <svg
303 className="w-5 h-5"
304 fill="currentColor"
305 viewBox="0 0 24 24"
306 >
307 <path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z" />
308 </svg>
309 Now Playing
310 </>
311 ) : (
312 <>
313 <svg
314 className="w-5 h-5"
315 fill="currentColor"
316 viewBox="0 0 24 24"
317 >
318 <path d="M8 5v14l11-7z" />
319 </svg>
320 Play Song
321 </>
322 )}
323 </button>
324 )}
325
326 {user && (
327 <>
328 <button
329 onClick={toggleLike}
330 className={`flex items-center gap-2 px-5 py-3 rounded-full text-sm font-semibold transition-colors cursor-pointer ${
331 song.isLikedByCurrentUser
332 ? "bg-[#1db954] text-black"
333 : "bg-white/10 text-white hover:bg-white/20"
334 }`}
335 >
336 {song.isLikedByCurrentUser ? (
337 <svg
338 className="w-5 h-5"
339 fill="currentColor"
340 viewBox="0 0 24 24"
341 >
342 <path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z" />
343 </svg>
344 ) : (
345 <svg
346 className="w-5 h-5"
347 fill="none"
348 stroke="currentColor"
349 viewBox="0 0 24 24"
350 >
351 <path
352 strokeLinecap="round"
353 strokeLinejoin="round"
354 strokeWidth={2}
355 d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"
356 />
357 </svg>
358 )}
359 {song.isLikedByCurrentUser ? "Liked" : "Like"}
360 </button>
361
362 {/* Add to Playlist button */}
363 <div className="relative" ref={playlistDropdownRef}>
364 <button
365 onClick={() =>
366 setShowPlaylistDropdown(!showPlaylistDropdown)
367 }
368 className="flex items-center gap-2 px-5 py-3 rounded-full text-sm font-semibold bg-white/10 text-white hover:bg-white/20 transition-colors cursor-pointer"
369 >
370 <svg
371 className="w-5 h-5"
372 fill="none"
373 stroke="currentColor"
374 viewBox="0 0 24 24"
375 >
376 <path
377 strokeLinecap="round"
378 strokeLinejoin="round"
379 strokeWidth={2}
380 d="M12 4v16m8-8H4"
381 />
382 </svg>
383 Add to Playlist
384 </button>
385
386 {/* Playlist dropdown */}
387 {showPlaylistDropdown && (
388 <div className="absolute left-0 top-full mt-2 w-56 bg-[#282828] rounded-lg shadow-2xl py-1 z-50 border border-white/10">
389 <div className="px-3 py-2 text-xs text-gray-400 border-b border-white/10">
390 Add to playlist
391 </div>
392 <button
393 onClick={() => handleAddToPlaylist("Hello")}
394 className="w-full text-left px-4 py-2.5 text-sm text-white hover:bg-white/10 transition-colors"
395 >
396 Hello
397 </button>
398 <button
399 onClick={() => handleAddToPlaylist("Dimi")}
400 className="w-full text-left px-4 py-2.5 text-sm text-white hover:bg-white/10 transition-colors"
401 >
402 Dimi
403 </button>
404 <button
405 onClick={() => handleAddToPlaylist("lmao")}
406 className="w-full text-left px-4 py-2.5 text-sm text-white hover:bg-white/10 transition-colors"
407 >
408 Kako hello world ama ti si mojot world
409 </button>
410 <button
411 onClick={handleCreateNewPlaylist}
412 className="w-full text-left px-4 py-2.5 text-sm text-[#1db954] hover:bg-white/10 transition-colors border-t border-white/10 flex items-center gap-2"
413 >
414 <svg
415 className="w-4 h-4"
416 fill="none"
417 stroke="currentColor"
418 viewBox="0 0 24 24"
419 >
420 <path
421 strokeLinecap="round"
422 strokeLinejoin="round"
423 strokeWidth={2}
424 d="M12 4v16m8-8H4"
425 />
426 </svg>
427 Create new playlist
428 </button>
429 </div>
430 )}
431 </div>
432 </>
433 )}
434 </div>
435 </div>
436 </div>
437
438 {/* Credits / Contributions */}
439 {song.contributions.length > 0 && (
440 <section className="mb-10">
441 <h2 className="text-2xl font-bold mb-4">Credits</h2>
442 <div className="bg-[#1a1a2e]/60 rounded-xl p-5 divide-y divide-white/5">
443 {/* Main artist first */}
444 {song.contributions
445 .filter((c) => c.artistName === song.releasedBy)
446 .map((c, i) => (
447 <div
448 key={`main-${i}`}
449 className="flex items-center justify-between py-3 first:pt-0 last:pb-0"
450 >
451 <div className="flex items-center gap-3">
452 <div className="w-10 h-10 bg-[#1db954] rounded-full flex items-center justify-center text-black font-bold text-sm">
453 {c.artistName.charAt(0).toUpperCase()}
454 </div>
455 <div>
456 <p className="text-white font-semibold text-lg">
457 {c.artistName}
458 </p>
459 </div>
460 </div>
461 <span className="text-sm text-gray-400 bg-white/5 px-3 py-1 rounded-full">
462 {formatRole(c.role)}
463 </span>
464 </div>
465 ))}
466
467 {/* Other contributors */}
468 {otherContributors.map((c, i) => (
469 <div
470 key={`contrib-${i}`}
471 className="flex items-center justify-between py-3 first:pt-0 last:pb-0"
472 >
473 <div className="flex items-center gap-3">
474 <div className="w-9 h-9 bg-white/10 rounded-full flex items-center justify-center text-white font-medium text-sm">
475 {c.artistName.charAt(0).toUpperCase()}
476 </div>
477 <p className="text-gray-300 font-medium">{c.artistName}</p>
478 </div>
479 <span className="text-sm text-gray-500 bg-white/5 px-3 py-1 rounded-full">
480 {formatRole(c.role)}
481 </span>
482 </div>
483 ))}
484 </div>
485 </section>
486 )}
487
488 {/* Reviews */}
489 <section>
490 <div className="flex items-center justify-between mb-4">
491 <h2 className="text-2xl font-bold">
492 Reviews
493 {song.reviews.length > 0 && (
494 <span className="text-base font-normal text-gray-500 ml-2">
495 ({song.reviews.length})
496 </span>
497 )}
498 </h2>
499 <button
500 onClick={() => setShowReviewModal(true)}
501 className="flex items-center gap-2 bg-[#1db954] hover:bg-[#1ed760] text-black text-sm font-semibold px-4 py-2 rounded-full transition-colors"
502 >
503 <svg
504 className="w-4 h-4"
505 fill="none"
506 stroke="currentColor"
507 viewBox="0 0 24 24"
508 >
509 <path
510 strokeLinecap="round"
511 strokeLinejoin="round"
512 strokeWidth={2}
513 d="M12 4v16m8-8H4"
514 />
515 </svg>
516 Add Review
517 </button>
518 </div>
519
520 {song.reviews.length === 0 ? (
521 <div className="bg-[#1a1a2e]/60 rounded-xl p-10 text-center">
522 <p className="text-gray-500 text-lg">No reviews yet.</p>
523 <p className="text-gray-600 text-sm mt-1">
524 Be the first to share your thoughts!
525 </p>
526 </div>
527 ) : (
528 <div className="space-y-4">
529 {song.reviews.map((review) => (
530 <div
531 key={`${review.id.listenerId}-${review.id.musicalEntityId}`}
532 className="bg-[#1a1a2e]/60 rounded-xl p-5 hover:bg-[#1a1a2e]/80 transition-colors"
533 >
534 <div className="flex items-start justify-between mb-2">
535 <div className="flex items-center gap-3">
536 <div className="w-9 h-9 bg-blue-500/20 rounded-full flex items-center justify-center">
537 <span className="text-blue-400 font-semibold text-sm">
538 {review.author.charAt(0).toUpperCase()}
539 </span>
540 </div>
541 <div>
542 <p className="text-white font-medium">
543 {review.author}
544 </p>
545 {renderStars(review.grade)}
546 </div>
547 </div>
548 {user?.username === review.authorUsername && (
549 <button
550 onClick={deleteReview}
551 className="text-gray-500 hover:text-red-400 transition-colors p-2 rounded-lg hover:bg-red-400/10"
552 title="Delete review"
553 >
554 <svg
555 className="w-5 h-5"
556 fill="none"
557 stroke="currentColor"
558 viewBox="0 0 24 24"
559 >
560 <path
561 strokeLinecap="round"
562 strokeLinejoin="round"
563 strokeWidth={2}
564 d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
565 />
566 </svg>
567 </button>
568 )}
569 </div>
570 <p className="text-gray-300 text-sm leading-relaxed mt-3 pl-12">
571 {review.comment}
572 </p>
573 </div>
574 ))}
575 </div>
576 )}
577 </section>
578 </div>
579
580 {/* Review Modal */}
581 {showReviewModal && (
582 <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/70 backdrop-blur-sm">
583 <div className="bg-[#1a1a2e] rounded-2xl p-6 max-w-md w-full shadow-2xl">
584 <div className="flex items-center justify-between mb-6">
585 <h3 className="text-2xl font-bold">Add Review</h3>
586 <button
587 onClick={() => {
588 setShowReviewModal(false);
589 setReviewRating(0);
590 setReviewComment("");
591 setHoverRating(0);
592 }}
593 className="text-gray-400 hover:text-white transition-colors"
594 >
595 <svg
596 className="w-6 h-6"
597 fill="none"
598 stroke="currentColor"
599 viewBox="0 0 24 24"
600 >
601 <path
602 strokeLinecap="round"
603 strokeLinejoin="round"
604 strokeWidth={2}
605 d="M6 18L18 6M6 6l12 12"
606 />
607 </svg>
608 </button>
609 </div>
610
611 {/* Star Rating */}
612 <div className="mb-6">
613 <label className="block text-sm font-medium mb-3">
614 Rating <span className="text-red-400">*</span>
615 </label>
616 <div className="flex gap-2">
617 {[1, 2, 3, 4, 5].map((star) => (
618 <button
619 key={star}
620 onClick={() => setReviewRating(star)}
621 onMouseEnter={() => setHoverRating(star)}
622 onMouseLeave={() => setHoverRating(0)}
623 className="transition-transform hover:scale-110"
624 >
625 <svg
626 className={`w-10 h-10 ${
627 star <= (hoverRating || reviewRating)
628 ? "text-yellow-400"
629 : "text-gray-600"
630 }`}
631 fill="currentColor"
632 viewBox="0 0 20 20"
633 >
634 <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
635 </svg>
636 </button>
637 ))}
638 </div>
639 </div>
640
641 {/* Comment */}
642 <div className="mb-6">
643 <label className="block text-sm font-medium mb-2">
644 Comment <span className="text-gray-500">(optional)</span>
645 </label>
646 <textarea
647 value={reviewComment}
648 onChange={(e) => setReviewComment(e.target.value)}
649 placeholder="Share your thoughts about this song..."
650 rows={4}
651 className="w-full bg-[#0f0f1e] border border-white/10 rounded-lg px-4 py-3 text-white placeholder-gray-500 focus:outline-none focus:border-[#1db954] transition-colors resize-none"
652 />
653 </div>
654
655 {/* Actions */}
656 <div className="flex gap-3 justify-end">
657 <button
658 onClick={() => {
659 setShowReviewModal(false);
660 setReviewRating(0);
661 setReviewComment("");
662 setHoverRating(0);
663 }}
664 className="px-5 py-2.5 rounded-full text-sm font-semibold bg-white/10 hover:bg-white/20 transition-colors"
665 >
666 Cancel
667 </button>
668 <button
669 onClick={handleSubmitReview}
670 disabled={reviewRating === 0}
671 className="px-5 py-2.5 rounded-full text-sm font-semibold bg-[#1db954] hover:bg-[#1ed760] text-black transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
672 >
673 Submit
674 </button>
675 </div>
676 </div>
677 </div>
678 )}
679 </div>
680 );
681};
682
683export default SongDetail;
Note: See TracBrowser for help on using the repository browser.