feat: fixes and formatter

This commit is contained in:
2026-01-12 16:01:32 +01:00
parent 85c6084351
commit 11e632acff
353 changed files with 23315 additions and 27361 deletions
+179 -215
View File
@@ -1,10 +1,4 @@
import React, {
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import {
FlatList,
Image,
@@ -14,87 +8,78 @@ import {
StyleSheet,
Text,
View,
} from "react-native";
import { BlurView } from "expo-blur";
import { responsiveHeight } from "react-native-responsive-dimensions";
import { background, icons } from "../../assets";
import BorderGradientButton from "../../components/BorderGradientButton";
import SearchBar from "../../components/SearchBar";
import ShareBtn from "../../components/ShareBtn/ShareBtn";
import firebase, { projectsRef, usersRef } from "../../config/firebase";
import useDataFromRef from "../../hooks/useDataFromRef";
import useNavigateToMusicDetails from "../../hooks/useNavigateToMusicDetails";
import useSearch from "../../hooks/useSearch";
import Page from "../../layouts/Page";
import { Routes } from "../../navigation";
import { navigate } from "../../navigation/NavigationService";
import { Palette, Style } from "../../styles";
import { FONT_FAMILY } from "../../styles/Fonts";
import CreateLyricsHeader from "../Writing/components/CreateLyricsHeader";
import MobileCoinBadge from "../../components/MobileCoinBadge";
import ResearchHeader from "../Library/components/ResearchHeader";
import SearchResultsList from "../Library/components/SearchResultsList";
import PlaybacksCard from "./components/PlaybacksCard";
import SongCard from "./components/SongCard";
import BorderGradient from "../../components/BorderGradient/BorderGradient.web";
} from 'react-native'
import { BlurView } from 'expo-blur'
import { responsiveHeight } from 'react-native-responsive-dimensions'
import { background, icons } from '../../assets'
import BorderGradientButton from '../../components/BorderGradientButton'
import SearchBar from '../../components/SearchBar'
import ShareBtn from '../../components/ShareBtn/ShareBtn'
import firebase, { projectsRef, usersRef } from '../../config/firebase'
import useDataFromRef from '../../hooks/useDataFromRef'
import useNavigateToMusicDetails from '../../hooks/useNavigateToMusicDetails'
import useSearch from '../../hooks/useSearch'
import Page from '../../layouts/Page'
import { Routes } from '../../navigation'
import { navigate } from '../../navigation/NavigationService'
import { Palette, Style } from '../../styles'
import { FONT_FAMILY } from '../../styles/Fonts'
import CreateLyricsHeader from '../Writing/components/CreateLyricsHeader'
import MobileCoinBadge from '../../components/MobileCoinBadge'
import ResearchHeader from '../Library/components/ResearchHeader'
import SearchResultsList from '../Library/components/SearchResultsList'
import PlaybacksCard from './components/PlaybacksCard'
import SongCard from './components/SongCard'
import BorderGradient from '../../components/BorderGradient/BorderGradient.web'
const allowedPremiumLevels = new Set(["starter", "pro", "premium"]);
const allowedPremiumLevels = new Set(['starter', 'pro', 'premium'])
const normalizePremiumLevel = (value) => {
if (typeof value !== "string") {
return null;
if (typeof value !== 'string') {
return null
}
const normalized = value.trim().toLowerCase();
return allowedPremiumLevels.has(normalized) ? normalized : null;
};
const normalized = value.trim().toLowerCase()
return allowedPremiumLevels.has(normalized) ? normalized : null
}
const chunkArray = (items = [], size = 10) => {
const chunks = [];
const chunks = []
for (let i = 0; i < items.length; i += size) {
chunks.push(items.slice(i, i + size));
chunks.push(items.slice(i, i + size))
}
return chunks;
};
return chunks
}
const HitParade = () => {
const [selectedCategory, setSelectedCategory] = useState("Chansons");
const navigateToMusicDetails = useNavigateToMusicDetails();
const [selectedCategory, setSelectedCategory] = useState('Chansons')
const navigateToMusicDetails = useNavigateToMusicDetails()
const { data: topSongs } = useDataFromRef({
ref: projectsRef.where("views", ">", 0).orderBy("views", "desc").limit(20),
ref: projectsRef.where('views', '>', 0).orderBy('views', 'desc').limit(20),
simpleRef: false,
listener: true,
condition: true,
});
})
const { data: topPlaybacks } = useDataFromRef({
ref: projectsRef.where("views", ">", 0).orderBy("views", "desc").limit(60),
ref: projectsRef.where('views', '>', 0).orderBy('views', 'desc').limit(60),
format: (docs) => docs.filter((d) => d?.playbackUrl != null).slice(0, 20),
simpleRef: false,
listener: true,
condition: true,
});
})
const songsList = useMemo(
() => (Array.isArray(topSongs) ? topSongs : []),
[topSongs]
);
const songsList = useMemo(() => (Array.isArray(topSongs) ? topSongs : []), [topSongs])
const playbackList = useMemo(
() => (Array.isArray(topPlaybacks) ? topPlaybacks : []),
[topPlaybacks]
);
)
const resolvePlaybackThumbnail = useCallback((project) => {
const candidates = [
project?.thumbnailUrl,
project?.songThumbnailUrl,
project?.coverUrl,
];
const uri = candidates.find(
(value) => typeof value === "string" && value.trim().length > 0
);
return uri || null;
}, []);
const candidates = [project?.thumbnailUrl, project?.songThumbnailUrl, project?.coverUrl]
const uri = candidates.find((value) => typeof value === 'string' && value.trim().length > 0)
return uri || null
}, [])
// === RENDUS PAR PLATEFORME ===
const renderSongsMobile = () => (
@@ -108,7 +93,7 @@ const HitParade = () => {
renderItem={({ item, index }) => (
<SongCard
rank={index + 1}
title={item?.title || "Sans titre"}
title={item?.title || 'Sans titre'}
artist={item?.userName}
coverUrl={item?.coverUrl || null}
subscriptionLevel={getCreatorLevel(item)}
@@ -122,7 +107,7 @@ const HitParade = () => {
/>
)}
/>
);
)
const renderPlaybacksMobile = () => (
<FlatList
@@ -135,7 +120,7 @@ const HitParade = () => {
renderItem={({ item, index }) => (
<PlaybacksCard
rank={index + 1}
title={item?.title || "Sans titre"}
title={item?.title || 'Sans titre'}
artist={item?.userName}
thumbnailUrl={resolvePlaybackThumbnail(item)}
subscriptionLevel={getCreatorLevel(item)}
@@ -143,7 +128,7 @@ const HitParade = () => {
/>
)}
/>
);
)
const renderSongList = () => (
<View style={{ gap: 10 }}>
@@ -151,7 +136,7 @@ const HitParade = () => {
<SongCard
key={item.id}
rank={idx + 1}
title={item?.title || "Sans titre"}
title={item?.title || 'Sans titre'}
artist={item?.userName}
coverUrl={item?.coverUrl || null}
subscriptionLevel={getCreatorLevel(item)}
@@ -165,7 +150,7 @@ const HitParade = () => {
/>
))}
</View>
);
)
const renderPlaybackColumns = () => (
<View style={{ gap: 10 }}>
@@ -173,7 +158,7 @@ const HitParade = () => {
<PlaybacksCard
key={item.id}
rank={idx + 1}
title={item?.title || "Sans titre"}
title={item?.title || 'Sans titre'}
artist={item?.userName}
thumbnailUrl={resolvePlaybackThumbnail(item)}
subscriptionLevel={getCreatorLevel(item)}
@@ -181,9 +166,9 @@ const HitParade = () => {
/>
))}
</View>
);
)
const isWeb = Platform.OS === "web";
const isWeb = Platform.OS === 'web'
const {
search,
setSearch,
@@ -193,216 +178,195 @@ const HitParade = () => {
musics = [],
playbacks = [],
loading: searchLoading,
} = useSearch();
} = useSearch()
const [dropdownVisible, setDropdownVisible] = useState(false);
const searchWrapperRef = useRef(null);
const hasSearchQuery = search.trim().length > 0;
const [dropdownVisible, setDropdownVisible] = useState(false)
const searchWrapperRef = useRef(null)
const hasSearchQuery = search.trim().length > 0
const toggleSearchSelected = useCallback(
(value) => {
setSearchSelected((previous) => (previous === value ? null : value));
setSearchSelected((previous) => (previous === value ? null : value))
},
[setSearchSelected]
);
)
const musicResults = useMemo(
() => (Array.isArray(musics) ? musics : []),
[musics]
);
const musicResults = useMemo(() => (Array.isArray(musics) ? musics : []), [musics])
const [creatorsById, setCreatorsById] = useState({});
const [creatorsById, setCreatorsById] = useState({})
const requiredUserIds = useMemo(() => {
const collected = new Set();
const collected = new Set()
const collectUserId = (project) => {
const uid =
project && typeof project.userId === "string"
? project.userId.trim()
: null;
const uid = project && typeof project.userId === 'string' ? project.userId.trim() : null
if (uid) {
collected.add(uid);
collected.add(uid)
}
};
songsList.forEach(collectUserId);
playbackList.forEach(collectUserId);
return Array.from(collected);
}, [playbackList, songsList]);
}
songsList.forEach(collectUserId)
playbackList.forEach(collectUserId)
return Array.from(collected)
}, [playbackList, songsList])
const fetchCreatorsByIds = useCallback(
async (userIds) => {
if (!Array.isArray(userIds) || userIds.length === 0) {
return;
return
}
const normalizedIds = userIds
.map((id) => (typeof id === "string" ? id.trim() : null))
.filter(Boolean);
.map((id) => (typeof id === 'string' ? id.trim() : null))
.filter(Boolean)
if (normalizedIds.length === 0) {
return;
return
}
const pendingIds = new Set(normalizedIds);
const nextCreators = {};
const pendingIds = new Set(normalizedIds)
const nextCreators = {}
const idChunks = chunkArray(normalizedIds, 10);
const idChunks = chunkArray(normalizedIds, 10)
await Promise.all(
idChunks.map(async (chunk) => {
try {
const snapshot = await usersRef
.where(firebase.firestore.FieldPath.documentId(), "in", chunk)
.get();
.where(firebase.firestore.FieldPath.documentId(), 'in', chunk)
.get()
snapshot.docs.forEach((doc) => {
const data = doc.data() || {};
const data = doc.data() || {}
nextCreators[doc.id] = {
premiumLevel: normalizePremiumLevel(data.premiumLevel),
};
pendingIds.delete(doc.id);
});
}
pendingIds.delete(doc.id)
})
} catch (error) {
console.log(
"HitParade: unable to fetch creators",
error?.message || error
);
console.log('HitParade: unable to fetch creators', error?.message || error)
}
})
);
)
pendingIds.forEach((userId) => {
nextCreators[userId] = { premiumLevel: null };
});
nextCreators[userId] = { premiumLevel: null }
})
if (Object.keys(nextCreators).length > 0) {
setCreatorsById((previous) => ({ ...previous, ...nextCreators }));
setCreatorsById((previous) => ({ ...previous, ...nextCreators }))
}
},
[setCreatorsById]
);
)
useEffect(() => {
const missingIds = requiredUserIds.filter((id) => !creatorsById[id]);
const missingIds = requiredUserIds.filter((id) => !creatorsById[id])
if (missingIds.length === 0) {
return;
return
}
fetchCreatorsByIds(missingIds);
}, [creatorsById, fetchCreatorsByIds, requiredUserIds]);
fetchCreatorsByIds(missingIds)
}, [creatorsById, fetchCreatorsByIds, requiredUserIds])
const getCreatorLevel = useCallback(
(project) => {
const uid =
project && typeof project.userId === "string"
? project.userId.trim()
: null;
const uid = project && typeof project.userId === 'string' ? project.userId.trim() : null
if (!uid) {
return null;
return null
}
return creatorsById?.[uid]?.premiumLevel || null;
return creatorsById?.[uid]?.premiumLevel || null
},
[creatorsById]
);
)
const playbackResults = useMemo(
() => (Array.isArray(playbacks) ? playbacks : []),
[playbacks]
);
const playbackResults = useMemo(() => (Array.isArray(playbacks) ? playbacks : []), [playbacks])
const userResults = useMemo(
() => (Array.isArray(users) ? users : []),
[users]
);
const userResults = useMemo(() => (Array.isArray(users) ? users : []), [users])
const musicsLoading = searchLoading;
const playbacksLoading = searchLoading;
const usersLoading = searchLoading;
const musicsLoading = searchLoading
const playbacksLoading = searchLoading
const usersLoading = searchLoading
const closeDropdown = useCallback(() => {
setDropdownVisible(false);
setSearchSelected(null);
setSearch("");
}, [setSearch, setSearchSelected]);
setDropdownVisible(false)
setSearchSelected(null)
setSearch('')
}, [setSearch, setSearchSelected])
const handleSearchFocus = useCallback(() => {
if (isWeb) {
setDropdownVisible(true);
setDropdownVisible(true)
}
}, [isWeb]);
}, [isWeb])
const handleSearchChange = useCallback(
(value) => {
setSearch(value);
setSearch(value)
if (isWeb) {
setDropdownVisible(true);
setDropdownVisible(true)
}
},
[isWeb, setSearch]
);
)
useEffect(() => {
if (!isWeb || !dropdownVisible) {
return undefined;
return undefined
}
const handleClickOutside = (event) => {
if (searchWrapperRef.current?.contains?.(event.target)) {
return;
return
}
closeDropdown();
};
document.addEventListener("mousedown", handleClickOutside);
document.addEventListener("touchstart", handleClickOutside);
return () => {
document.removeEventListener("mousedown", handleClickOutside);
document.removeEventListener("touchstart", handleClickOutside);
};
}, [closeDropdown, dropdownVisible, isWeb]);
const shouldShowResults = isWeb && dropdownVisible;
const shouldBlurContent = shouldShowResults;
const handlePlayRandomSong = useCallback(() => {
const arr = Array.isArray(topSongs) ? topSongs : [];
if (!arr.length) {
console.warn("Aucune chanson disponible pour le moment.");
return;
closeDropdown()
}
const randomSong = arr[Math.floor(Math.random() * arr.length)];
document.addEventListener('mousedown', handleClickOutside)
document.addEventListener('touchstart', handleClickOutside)
return () => {
document.removeEventListener('mousedown', handleClickOutside)
document.removeEventListener('touchstart', handleClickOutside)
}
}, [closeDropdown, dropdownVisible, isWeb])
const shouldShowResults = isWeb && dropdownVisible
const shouldBlurContent = shouldShowResults
const handlePlayRandomSong = useCallback(() => {
const arr = Array.isArray(topSongs) ? topSongs : []
if (!arr.length) {
console.warn('Aucune chanson disponible pour le moment.')
return
}
const randomSong = arr[Math.floor(Math.random() * arr.length)]
navigateToMusicDetails({
projectId: randomSong.id,
songUrl: randomSong?.songUrl,
project: randomSong,
});
}, [navigateToMusicDetails, topSongs]);
})
}, [navigateToMusicDetails, topSongs])
const categoryLabel =
selectedCategory === "Playback" ? "playbacks" : "chansons";
const categoryLabel = selectedCategory === 'Playback' ? 'playbacks' : 'chansons'
const heroTitle = isWeb
? "Coups de coeur des utilisateurs"
: `Coups de coeur des utilisateurs catégorie ${selectedCategory}`;
? 'Coups de coeur des utilisateurs'
: `Coups de coeur des utilisateurs catégorie ${selectedCategory}`
const heroSubtitle = isWeb
? "Les 3 chansons et playbacks les plus likées du mois reçoivent des tokens."
: `Les 3 ${categoryLabel} les plus likées du mois reçoivent des tokens.`;
? 'Les 3 chansons et playbacks les plus likées du mois reçoivent des tokens.'
: `Les 3 ${categoryLabel} les plus likées du mois reçoivent des tokens.`
const renderHero = () => (
<View
style={{ gap: 11, maxWidth: 800, width: "100%", alignSelf: "center" }}
>
<View style={{ gap: 11, maxWidth: 800, width: '100%', alignSelf: 'center' }}>
{/* <Pressable onPress={handlePlayRandomSong}>
<Image
source={icons.play}
style={{ alignSelf: "center", marginVertical: 10 }}
/>
</Pressable> */}
<CreateLyricsHeader gradientProps={{ colors: ["#F94697", "#7023F7"] }}>
<CreateLyricsHeader gradientProps={{ colors: ['#F94697', '#7023F7'] }}>
<Text
style={{
fontSize: 16,
@@ -423,7 +387,7 @@ const HitParade = () => {
</Text>
</CreateLyricsHeader>
</View>
);
)
const renderWebContent = () => (
<ScrollView
@@ -433,14 +397,14 @@ const HitParade = () => {
paddingBottom: responsiveHeight(20),
}}
showsVerticalScrollIndicator={false}
style={{ flex: 1, position: "relative", zIndex: 5 }}
style={{ flex: 1, position: 'relative', zIndex: 5 }}
>
{renderHero()}
<View
style={{
flexDirection: "row",
flexDirection: 'row',
gap: 16,
alignItems: "flex-start",
alignItems: 'flex-start',
}}
>
<View style={{ flex: 1, gap: 12 }}>
@@ -448,9 +412,9 @@ const HitParade = () => {
intensity={50}
tint="dark"
style={{
alignSelf: "flex-start",
alignSelf: 'flex-start',
borderRadius: 10,
overflow: "hidden",
overflow: 'hidden',
paddingHorizontal: 20,
paddingVertical: 10,
}}
@@ -474,9 +438,9 @@ const HitParade = () => {
intensity={50}
tint="dark"
style={{
alignSelf: "flex-start",
alignSelf: 'flex-start',
borderRadius: 10,
overflow: "hidden",
overflow: 'hidden',
paddingHorizontal: 20,
paddingVertical: 10,
}}
@@ -497,7 +461,7 @@ const HitParade = () => {
</View>
</View>
</ScrollView>
);
)
const renderMobileContent = () => (
<View style={{ flex: 1, gap: 24 }}>
@@ -505,17 +469,17 @@ const HitParade = () => {
<View
style={{
...Style.containerRow,
justifyContent: "space-between",
width: "auto",
justifyContent: 'space-between',
width: 'auto',
gap: 12,
}}
>
{["Chansons", "Playback"].map((item, index) => (
{['Chansons', 'Playback'].map((item, index) => (
<BorderGradientButton
key={index}
title={item}
onPress={() => setSelectedCategory(item)}
tint={selectedCategory === item ? "light" : "dark"}
tint={selectedCategory === item ? 'light' : 'dark'}
containerStyle={{ flex: 1 }}
titleStyle={{
fontSize: 16,
@@ -525,11 +489,11 @@ const HitParade = () => {
))}
</View>
{selectedCategory === "Chansons" && renderSongsMobile()}
{selectedCategory === "Playback" && renderPlaybacksMobile()}
{selectedCategory === 'Chansons' && renderSongsMobile()}
{selectedCategory === 'Playback' && renderPlaybacksMobile()}
{/* "Clips" pourra reprendre la même logique si tu le réactives */}
</View>
);
)
return (
<Page
@@ -543,10 +507,10 @@ const HitParade = () => {
{!isWeb ? (
<View
style={{
width: "100%",
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
width: '100%',
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
gap: 12,
marginBottom: 4,
}}
@@ -558,20 +522,20 @@ const HitParade = () => {
<View style={{ gap: 12, flex: 1 }}>
<Image
source={icons.musicLandLogo}
style={{ alignSelf: "center", height: 150, resizeMode: "contain" }}
style={{ alignSelf: 'center', height: 150, resizeMode: 'contain' }}
/>
{isWeb && (
<View
ref={searchWrapperRef}
style={{
position: "relative",
alignSelf: "center",
width: "65%",
position: 'relative',
alignSelf: 'center',
width: '65%',
maxWidth: 520,
minWidth: 360,
zIndex: dropdownVisible ? 40 : 1,
overflow: "visible",
overflow: 'visible',
}}
>
<SearchBar
@@ -585,12 +549,12 @@ const HitParade = () => {
{shouldShowResults && (
<View
style={{
position: "absolute",
position: 'absolute',
top: 60,
left: 0,
right: 0,
zIndex: 50,
width: "100%",
width: '100%',
}}
>
<View
@@ -600,7 +564,7 @@ const HitParade = () => {
padding: 16,
backgroundColor: Palette.ultraLightWhite,
...Style.defaultBorder,
width: "100%",
width: '100%',
zIndex: 50,
elevation: 12,
}}
@@ -627,7 +591,7 @@ const HitParade = () => {
</View>
)}
<View style={{ flex: 1, position: "relative" }}>
<View style={{ flex: 1, position: 'relative' }}>
{shouldBlurContent && (
<BlurView
intensity={35}
@@ -637,8 +601,8 @@ const HitParade = () => {
{
zIndex: 10,
borderRadius: 18,
backgroundColor: "rgba(0, 0, 0, 0.25)",
overflow: "hidden",
backgroundColor: 'rgba(0, 0, 0, 0.25)',
overflow: 'hidden',
},
]}
/>
@@ -648,7 +612,7 @@ const HitParade = () => {
</View>
</View>
</Page>
);
};
)
}
export default HitParade;
export default HitParade