playbacks

This commit is contained in:
2025-09-30 14:43:39 +02:00
parent a78f8dcc9c
commit 6bb6576281
4 changed files with 1050 additions and 1004 deletions
@@ -0,0 +1,625 @@
import { useAudioPlayer } from "expo-audio";
import { BlurView } from "expo-blur";
import React, {
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import {
Image,
Pressable,
Share,
StyleSheet,
Text,
View,
useWindowDimensions,
} from "react-native";
import { icons, img } from "../../../assets";
import KaraokeLyrics from "../../../components/KaraokeLyrics";
import {
arrayRemove,
arrayUnion,
projectsRef,
usersRef,
} from "../../../config/firebase";
import { Routes } from "../../../navigation";
import { navigate } from "../../../navigation/NavigationService";
import { useUser } from "../../../providers/UserDataProvider";
import { Palette } from "../../../styles";
import { FONT_FAMILY } from "../../../styles/Fonts";
import { size } from "../../../styles/Style";
import CommentsPanel from "./CommentsPanel.web";
// NOTE: Web-only implementation that uses a native <video> element instead of expo-video
// - No Platform checks
// - Handles autoplay requirements (muted first, unmute on first gesture)
// - Keeps external audio track in sync when present
const PlaybackItem = ({ item, isActive, userCache, getUserByUid }) => {
const { width: viewportWidth, height: viewportHeight } =
useWindowDimensions();
const [layoutSize, setLayoutSize] = useState({
width: viewportWidth,
height: viewportHeight,
});
const [openComments, setOpenComments] = useState(false);
const commentInputRef = useRef(null);
const { currentUID, followUser, unfollowUser } = useUser() || {};
const videoUrl = item?.playbackUrl || null;
const videoRef = useRef(null); // HTMLVideoElement
const audioSource = useMemo(() => {
const fromSong = item?.songUrl ? { uri: item.songUrl } : null;
return fromSong;
}, [item]);
const hasExternalAudio = !!audioSource;
const initialLikedBy = Array.isArray(item?.likedBy) ? item.likedBy : [];
const [isLiked, setIsLiked] = useState(
currentUID ? initialLikedBy.includes(currentUID) : false
);
const [likesCount, setLikesCount] = useState(initialLikedBy.length);
const computedCommentsCount = useMemo(
() => Number(item?.commentsCount || 0),
[item?.commentsCount]
);
const [commentsCount, setCommentsCount] = useState(computedCommentsCount);
useEffect(() => {
setCommentsCount(computedCommentsCount);
}, [computedCommentsCount]);
const [owner, setOwner] = useState(
item?.userId && userCache?.current?.get(item.userId)
? userCache.current.get(item.userId)
: null
);
useEffect(() => {
let cancelled = false;
const run = async () => {
try {
const uid = item?.userId;
if (!uid || !userCache) return;
const cached = userCache.current.get(uid);
if (cached) {
if (!cancelled) setOwner(cached);
return;
}
const user = await getUserByUid?.(uid);
if (!cancelled && user) {
userCache.current.set(uid, user);
setOwner(user);
}
} catch (_e) {}
};
run();
return () => {
cancelled = true;
};
}, [item?.userId, userCache, getUserByUid]);
useEffect(() => {
const uid = item?.userId;
if (!uid) return;
const unsub = usersRef.doc(uid).onSnapshot(
(doc) => {
if (doc?.exists) {
const data = { id: doc.id, ...doc.data() };
setOwner(data);
try {
userCache?.current?.set(uid, data);
} catch (_e) {}
}
},
() => {}
);
return () => unsub?.();
}, [item?.userId, userCache]);
const [isFollowing, setIsFollowing] = useState(false);
useEffect(() => {
const list = Array.isArray(owner?.followedBy) ? owner.followedBy : [];
setIsFollowing(currentUID ? list.includes(currentUID) : false);
}, [owner?.followedBy, currentUID]);
useEffect(() => {
const lb = Array.isArray(item?.likedBy) ? item.likedBy : [];
setLikesCount(lb.length);
setIsLiked(currentUID ? lb.includes(currentUID) : false);
}, [item?.likedBy, currentUID]);
const audioPlayer = useAudioPlayer(audioSource || undefined);
// --- Playback control helpers (web <video>) ---
const playVideo = useCallback(async () => {
try {
const el = videoRef.current;
if (!el) return;
// Allow autoplay by keeping it muted initially
el.muted = true;
if (el.paused) {
await el.play().catch(() => {});
}
} catch (_e) {}
}, []);
const unmuteVideoOnFirstGesture = useCallback(() => {
if (typeof document === "undefined") return () => {};
const handler = async () => {
try {
const el = videoRef.current;
if (!el) return;
if (!hasExternalAudio) {
el.muted = false; // restore sound if video is the only audio
}
if (el.paused) await el.play();
if (hasExternalAudio && audioPlayer && !audioPlayer.playing) {
await audioPlayer.play?.();
}
} catch (_e) {}
};
const events = [
"pointerdown",
"click",
"touchstart",
"keydown",
"wheel",
"scroll",
];
events.forEach((ev) =>
document.addEventListener(ev, handler, { once: true, passive: true })
);
return () => {
events.forEach((ev) => document.removeEventListener(ev, handler));
};
}, [audioPlayer, hasExternalAudio]);
// Start/reset when active
useEffect(() => {
const el = videoRef.current;
if (!isActive || !el) return;
const start = async () => {
try {
// Reset clocks
if (audioPlayer && hasExternalAudio) await audioPlayer.seekTo?.(0);
el.currentTime = 0;
await playVideo();
if (hasExternalAudio && audioPlayer && !audioPlayer.playing) {
await audioPlayer.play?.();
}
} catch (_e) {}
};
start();
const removeGesture = unmuteVideoOnFirstGesture();
return () => {
removeGesture?.();
};
}, [
isActive,
playVideo,
audioPlayer,
hasExternalAudio,
unmuteVideoOnFirstGesture,
]);
// Keep external audio & video roughly in sync (when audio is the source of truth)
useEffect(() => {
if (!isActive || !hasExternalAudio) return;
const id = setInterval(() => {
try {
if (!audioPlayer?.playing) return;
const el = videoRef.current;
if (!el) return;
const a = Number(audioPlayer?.currentTime || 0);
const v = Number(el.currentTime || 0);
if (Math.abs(a - v) > 0.2) {
el.currentTime = Math.max(0, a);
}
} catch (_e) {}
}, 300);
return () => clearInterval(id);
}, [isActive, hasExternalAudio, audioPlayer]);
// Pause all on unmount
useEffect(() => {
return () => {
try {
const el = videoRef.current;
if (audioPlayer?.playing) audioPlayer.pause?.();
if (el && !el.paused) el.pause();
} catch (_e) {}
};
}, [audioPlayer]);
// Lyrics timing
const alignedWords = useMemo(() => {
const idx = Number(item?.songIndex) || 0;
const ts = item?.musicTimestamps?.[idx];
const arr = Array.isArray(ts?.alignedWords) ? ts.alignedWords : [];
return arr.map((w) => ({
word: String(w?.word ?? ""),
startS: Number(w?.startS ?? 0),
endS: Number(w?.endS ?? 0),
}));
}, [item?.musicTimestamps, item?.songIndex]);
const [currentTimeS, setCurrentTimeS] = useState(0);
useEffect(() => {
if (!isActive) return;
const id = setInterval(() => {
try {
const useAudioTime = hasExternalAudio && !!audioPlayer?.playing;
const t = useAudioTime
? Number(audioPlayer?.currentTime || 0)
: Number(videoRef.current?.currentTime || 0);
setCurrentTimeS(t);
} catch (_e) {}
}, 250);
return () => clearInterval(id);
}, [isActive, hasExternalAudio, audioPlayer]);
const descriptionText =
item?.description || item?.title || "Description chanson";
const handleLayout = useCallback((event) => {
const { width = 0, height = 0 } = event?.nativeEvent?.layout || {};
setLayoutSize((prev) => ({
width: width > 0 ? width : prev.width,
height: height > 0 ? height : prev.height,
}));
}, []);
const layoutWidth = layoutSize.width || viewportWidth;
const layoutHeight = layoutSize.height || viewportHeight;
const horizontalPadding = 64;
const innerWidth = Math.max(layoutWidth - horizontalPadding * 2, 0);
const gapBetweenColumns = 40;
const minVideoWidth = 420;
const maxVideoWidth = 720;
const minCommentsWidth = 300;
const maxCommentsWidth = 420;
let desiredHeight = Math.max(420, layoutHeight * 0.8);
let videoWidth = Math.min(
maxVideoWidth,
Math.max(minVideoWidth, innerWidth * 0.58)
);
let videoHeight = videoWidth * (16 / 9);
if (videoHeight > desiredHeight) {
videoHeight = desiredHeight;
videoWidth = videoHeight * (9 / 16);
}
let commentsWidth = Math.min(
maxCommentsWidth,
Math.max(minCommentsWidth, innerWidth - videoWidth - gapBetweenColumns)
);
const panelHeight = Math.min(videoHeight, desiredHeight);
return (
<View
onLayout={handleLayout}
style={[
styles.itemContainerBase,
styles.itemContainerRow,
{
height: "90%",
paddingHorizontal: horizontalPadding,
paddingVertical: Math.max((layoutHeight - panelHeight) / 2, 24),
},
]}
>
<View
style={[
styles.videoColumn,
{ width: videoWidth, marginRight: gapBetweenColumns },
]}
>
<View style={[styles.videoSurface, { height: panelHeight }]}>
<View style={styles.videoContainer}>
{!!videoUrl ? (
// Native HTML video for web
<video
ref={videoRef}
src={videoUrl}
playsInline
muted
autoPlay
loop
preload="auto"
// Using web CSS properties here on purpose
style={{
position: "absolute",
inset: 0,
width: "100%",
height: "100%",
objectFit: "cover",
display: "block",
}}
/>
) : (
<Image
source={img.placeholder3}
style={StyleSheet.absoluteFillObject}
resizeMode="cover"
/>
)}
<View style={styles.actionStack}>
<View style={styles.ownerBlock}>
<Pressable
style={styles.ownerAvatarButton}
onPress={() => {
navigate(Routes.SingerProfile, { userId: item?.userId });
}}
>
{owner?.profilePictureURL ? (
<Image
source={{ uri: owner.profilePictureURL }}
style={styles.ownerAvatar}
/>
) : (
<Image source={img.profile} style={styles.ownerAvatar} />
)}
</Pressable>
{owner?.id && currentUID && owner.id !== currentUID && (
<Pressable
style={styles.followPressable}
onPress={async () => {
try {
const next = !isFollowing;
setIsFollowing(next);
setOwner((prev) => {
const fb = Array.isArray(prev?.followedBy)
? prev.followedBy
: [];
const newFb = next
? Array.from(new Set([...fb, currentUID]))
: fb.filter((x) => x !== currentUID);
return prev ? { ...prev, followedBy: newFb } : prev;
});
if (next) await followUser?.(owner.id);
else await unfollowUser?.(owner.id);
} catch (_e) {
setIsFollowing((v) => !v);
}
}}
>
<BlurView
tint="dark"
intensity={20}
style={styles.followButton}
>
<Text style={styles.followButtonText}>
{isFollowing ? "Ne plus suivre" : "Suivre"}
</Text>
</BlurView>
</Pressable>
)}
</View>
<Pressable
onPress={async () => {
try {
if (!currentUID || !item?.id) return;
const nextLiked = !isLiked;
setIsLiked(nextLiked);
setLikesCount((c) => Math.max(0, c + (nextLiked ? 1 : -1)));
const ref = projectsRef.doc(item.id);
await ref.set(
{
likedBy: nextLiked
? arrayUnion(currentUID)
: arrayRemove(currentUID),
},
{ merge: true }
);
} catch (_e) {
setIsLiked((v) => !v);
setLikesCount((c) =>
isLiked ? c + 1 : Math.max(0, c - 1)
);
}
}}
style={[styles.actionButton, styles.actionSpacing]}
>
<Image
source={isLiked ? icons.heart : icons.heartOutline}
style={styles.actionIcon}
resizeMode="contain"
/>
{!!likesCount && (
<Text style={styles.actionLabel}>{likesCount}</Text>
)}
</Pressable>
<Pressable
onPress={() => {
setOpenComments((v) => !v);
}}
style={[styles.actionButton, styles.actionSpacing]}
>
<Image
source={icons.chatBubble}
style={styles.actionIcon}
resizeMode="contain"
/>
{!!commentsCount && (
<Text style={styles.actionLabel}>{commentsCount}</Text>
)}
</Pressable>
<Pressable
onPress={async () => {
try {
const url = item?.playbackUrl || "";
const title = item?.title || "Partager";
const base = item?.title
? `Découvre « ${item.title} » sur MusicLand`
: `Découvre ce playback sur MusicLand`;
const message = url ? `${base}\n${url}` : base;
await Share.share({ message, title, url });
} catch (_e) {}
}}
style={[styles.actionButton, styles.actionSpacing]}
>
<Image
source={icons.share}
style={styles.actionIcon}
resizeMode="contain"
/>
</Pressable>
</View>
<View style={styles.lyricsContainer}>
<BlurView tint="dark" intensity={20} style={styles.lyricsCard}>
{alignedWords?.length > 0 ? (
<KaraokeLyrics
alignedWords={alignedWords}
currentTimeS={currentTimeS}
/>
) : (
<Text style={styles.lyricsText}>{descriptionText}</Text>
)}
</BlurView>
</View>
</View>
</View>
</View>
{openComments && (
<View
style={[
styles.commentsColumn,
{ width: commentsWidth, height: panelHeight },
]}
>
<CommentsPanel
projectId={item?.id}
description={descriptionText}
commentsCount={commentsCount}
onCommentAdded={() =>
setCommentsCount((c) => Math.max(0, Number(c || 0) + 1))
}
inputRef={commentInputRef}
panelHeight={panelHeight}
/>
</View>
)}
</View>
);
};
export default PlaybackItem;
const styles = StyleSheet.create({
itemContainerBase: {
width: "100%",
paddingVertical: 36,
alignItems: "center",
},
itemContainerRow: {
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
},
videoColumn: {
alignItems: "center",
justifyContent: "center",
},
videoSurface: {
alignSelf: "center",
aspectRatio: 9 / 16,
borderRadius: 32,
overflow: "hidden",
backgroundColor: "#07040D",
shadowColor: "#000",
shadowOpacity: 0.45,
shadowRadius: 30,
shadowOffset: { width: 0, height: 20 },
elevation: 12,
},
videoContainer: {
flex: 1,
position: "relative",
},
actionStack: {
position: "absolute",
right: 18,
bottom: 120,
alignItems: "center",
},
ownerBlock: {
alignItems: "center",
marginBottom: 26,
},
ownerAvatarButton: {
marginBottom: 16,
},
ownerAvatar: {
...size({ size: 56 }),
borderRadius: 100,
},
followPressable: {
alignSelf: "center",
},
followButton: {
paddingVertical: 8,
paddingHorizontal: 18,
borderRadius: 14,
borderWidth: 1,
borderColor: Palette.white,
backgroundColor: "#FFFFFF20",
overflow: "hidden",
},
followButtonText: {
fontSize: 14,
color: Palette.white,
fontFamily: FONT_FAMILY.InterMedium,
},
actionButton: {
alignItems: "center",
justifyContent: "center",
},
actionSpacing: {
marginTop: 24,
},
actionIcon: {
...size({ size: 30 }),
},
actionLabel: {
marginTop: 6,
fontSize: 13,
color: Palette.white,
fontFamily: FONT_FAMILY.InterMedium,
textAlign: "center",
},
lyricsContainer: {
position: "absolute",
left: 24,
right: 24,
bottom: 32,
},
lyricsCard: {
paddingHorizontal: 18,
paddingVertical: 12,
borderRadius: 22,
backgroundColor: Palette.glass,
overflow: "hidden",
},
lyricsText: {
fontSize: 14,
color: Palette.white,
fontFamily: FONT_FAMILY.InterRegular,
},
commentsColumn: {
alignSelf: "stretch",
},
});