Compare commits

..

No commits in common. "e8bb2a4326b1542eb1eb75ae2dd7277afef89cb2" and "2e32a3c3b67cdd390265b137e25047a29a588b9e" have entirely different histories.

6 changed files with 85 additions and 216 deletions

View File

@ -148,15 +148,6 @@ router.get('/playlist/*', async (req: Request, res: Response) => {
const totalSongs = await Song.countDocuments(query);
const totalPages = Math.ceil(totalSongs / limit);
// Calculate total duration for the entire playlist
const allPlaylistSongs = await Song.find({ id: { $in: trackIds } }).lean();
const totalDuration = allPlaylistSongs.reduce((total, song: any) => {
if (!song.totalTime) return total;
const totalTimeStr = String(song.totalTime);
const seconds = Math.floor(Number(totalTimeStr) / (totalTimeStr.length > 4 ? 1000 : 1));
return total + seconds;
}, 0);
// Get songs with pagination
const songs = await Song.find(query)
.sort({ title: 1 })
@ -175,8 +166,7 @@ router.get('/playlist/*', async (req: Request, res: Response) => {
totalPages,
hasNextPage: page < totalPages,
hasPrevPage: page > 1
},
totalDuration: totalDuration
}
});
} catch (error) {
console.error('Error fetching playlist songs:', error);

View File

@ -8,7 +8,6 @@ import { SongDetails } from "./components/SongDetails";
import { Configuration } from "./pages/Configuration";
import { useXmlParser } from "./hooks/useXmlParser";
import { usePaginatedSongs } from "./hooks/usePaginatedSongs";
import { formatTotalDuration } from "./utils/formatters";
import { api } from "./services/api";
import type { Song, PlaylistNode } from "./types/interfaces";
@ -57,7 +56,7 @@ const findPlaylistByName = (playlists: PlaylistNode[], name: string): PlaylistNo
return null;
};
const getAllPlaylistTracks = (node: PlaylistNode): string[] => {
const getAllPlaylistTracks = (node: PlaylistNode): string[] => {
if (!node.type || node.type === 'playlist') { // Handle both old and new playlist formats
return node.tracks || [];
}
@ -65,32 +64,22 @@ const findPlaylistByName = (playlists: PlaylistNode[], name: string): PlaylistNo
return node.children.flatMap(child => getAllPlaylistTracks(child));
}
return [];
};
};
export default function RekordboxReader() {
const { playlists, setPlaylists, loading: xmlLoading } = useXmlParser();
const [selectedSong, setSelectedSong] = useState<Song | null>(null);
const [isDatabaseInitialized, setIsDatabaseInitialized] = useState(false);
// Memoized song selection handler to prevent unnecessary re-renders
const handleSongSelect = useCallback((song: Song) => {
setSelectedSong(song);
}, []);
// Format total duration for display
const getFormattedTotalDuration = useCallback((durationSeconds?: number): string => {
if (!durationSeconds) return "";
return formatTotalDuration(durationSeconds);
}, []);
const navigate = useNavigate();
const location = useLocation();
const initialLoadDone = useRef(false);
const { isOpen, onOpen, onClose } = useDisclosure();
const { isOpen: isWelcomeOpen, onOpen: onWelcomeOpen, onClose: onWelcomeClose } = useDisclosure({ defaultIsOpen: false });
const { isOpen: isWelcomeOpen, onClose: onWelcomeClose } = useDisclosure({ defaultIsOpen: true });
const isMobile = useBreakpointValue({ base: true, md: false });
const [sidebarWidth, setSidebarWidth] = useState(400);
@ -107,38 +96,11 @@ export default function RekordboxReader() {
loading: songsLoading,
hasMore,
totalSongs,
totalDuration,
loadNextPage,
searchSongs,
searchQuery
} = usePaginatedSongs({ pageSize: 50, playlistName: currentPlaylist });
// Check if database is initialized (has songs or playlists) - moved after useDisclosure
useEffect(() => {
const checkDatabaseInitialized = async () => {
try {
// Check if there are any songs in the database
const songCount = await api.getSongCount();
const hasPlaylists = playlists.length > 0;
const isInitialized = songCount > 0 || hasPlaylists;
setIsDatabaseInitialized(isInitialized);
// Only show welcome modal if database is truly empty
if (!isInitialized) {
onWelcomeOpen();
}
} catch (error) {
// If we can't get the song count, assume database is not initialized
setIsDatabaseInitialized(false);
onWelcomeOpen();
}
};
if (!xmlLoading) {
checkDatabaseInitialized();
}
}, [xmlLoading, playlists.length, onWelcomeOpen]);
useEffect(() => {
// Only run this check after the initial data load
if (!xmlLoading && playlists.length > 0) {
@ -351,11 +313,16 @@ export default function RekordboxReader() {
};
}, [isResizing]);
if (xmlLoading) {
if (xmlLoading || songsLoading) {
return (
<Flex height="100vh" align="center" justify="center" direction="column" gap={4}>
<Spinner size="xl" />
<Text>Loading your library...</Text>
{currentPlaylist !== "All Songs" && (
<Text fontSize="sm" color="gray.500">
Navigating to playlist: {currentPlaylist}
</Text>
)}
</Flex>
);
}
@ -388,7 +355,7 @@ export default function RekordboxReader() {
userSelect={isResizing ? 'none' : 'auto'}
>
{/* Welcome Modal */}
{!xmlLoading && !isDatabaseInitialized && (
{!xmlLoading && !songsLoading && songs.length === 0 && (
<Modal isOpen={isWelcomeOpen} onClose={onWelcomeClose} isCentered>
<ModalOverlay />
<ModalContent bg="gray.800" maxW="md">
@ -543,7 +510,6 @@ export default function RekordboxReader() {
loading={songsLoading}
hasMore={hasMore}
totalSongs={totalSongs}
totalPlaylistDuration={getFormattedTotalDuration(totalDuration)}
onLoadMore={loadNextPage}
onSearch={searchSongs}
searchQuery={searchQuery}

View File

@ -34,7 +34,6 @@ interface PaginatedSongListProps {
loading: boolean;
hasMore: boolean;
totalSongs: number;
totalPlaylistDuration?: string; // Total duration of the entire playlist
onLoadMore: () => void;
onSearch: (query: string) => void;
searchQuery: string;
@ -112,7 +111,6 @@ export const PaginatedSongList: React.FC<PaginatedSongListProps> = memo(({
loading,
hasMore,
totalSongs,
totalPlaylistDuration,
onLoadMore,
onSearch,
searchQuery,
@ -123,20 +121,6 @@ export const PaginatedSongList: React.FC<PaginatedSongListProps> = memo(({
const observerRef = useRef<IntersectionObserver | null>(null);
const loadingRef = useRef<HTMLDivElement>(null);
const scrollContainerRef = useRef<HTMLDivElement>(null);
const isTriggeringRef = useRef(false);
const timeoutRef = useRef<NodeJS.Timeout | null>(null);
// Store current values in refs to avoid stale closures
const hasMoreRef = useRef(hasMore);
const loadingRef_state = useRef(loading);
const onLoadMoreRef = useRef(onLoadMore);
// Update refs when props change
useEffect(() => {
hasMoreRef.current = hasMore;
loadingRef_state.current = loading;
onLoadMoreRef.current = onLoadMore;
}, [hasMore, loading, onLoadMore]);
// Debounce search to prevent excessive API calls
const debouncedSearchQuery = useDebounce(localSearchQuery, 300);
@ -215,19 +199,15 @@ export const PaginatedSongList: React.FC<PaginatedSongListProps> = memo(({
));
}, [songs, selectedSongs, selectedSongId, handleSongSelect, toggleSelection, depth]);
// Use total playlist duration if available, otherwise calculate from current songs
// Memoized total duration calculation
const totalDuration = useMemo(() => {
if (totalPlaylistDuration) {
return totalPlaylistDuration;
}
// Fallback to calculating from current songs
const totalSeconds = songs.reduce((total, song) => {
if (!song.totalTime) return total;
const seconds = Math.floor(Number(song.totalTime) / (song.totalTime.length > 4 ? 1000 : 1));
return total + seconds;
}, 0);
return formatTotalDuration(totalSeconds);
}, [songs, totalPlaylistDuration]);
}, [songs]);
// Memoized playlist options for bulk actions
const playlistOptions = useMemo(() => {
@ -250,14 +230,8 @@ export const PaginatedSongList: React.FC<PaginatedSongListProps> = memo(({
if (loadingRef.current) {
observerRef.current = new IntersectionObserver(
(entries) => {
// Use current values from refs to avoid stale closure
if (entries[0].isIntersecting && hasMoreRef.current && !loadingRef_state.current && !isTriggeringRef.current) {
isTriggeringRef.current = true;
onLoadMoreRef.current();
// Reset the flag after a short delay to prevent multiple triggers
timeoutRef.current = setTimeout(() => {
isTriggeringRef.current = false;
}, 1000);
if (entries[0].isIntersecting && hasMore && !loading) {
onLoadMore();
}
},
{
@ -273,11 +247,8 @@ export const PaginatedSongList: React.FC<PaginatedSongListProps> = memo(({
if (observerRef.current) {
observerRef.current.disconnect();
}
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
};
}, []); // Remove dependencies to prevent recreation
}, [hasMore, loading, onLoadMore]);
return (
<Flex direction="column" height="100%">
@ -327,11 +298,6 @@ export const PaginatedSongList: React.FC<PaginatedSongListProps> = memo(({
</Checkbox>
<Text color="gray.400" fontSize="sm">
{songs.length} of {totalSongs} songs {totalDuration}
{hasMore && songs.length > 0 && (
<Text as="span" color="blue.400" ml={2}>
Scroll for more
</Text>
)}
</Text>
</HStack>
@ -388,26 +354,14 @@ export const PaginatedSongList: React.FC<PaginatedSongListProps> = memo(({
{/* Loading indicator for infinite scroll */}
{loading && (
<Flex justify="center" align="center" p={6} key="loading-spinner" gap={3}>
<Flex justify="center" p={4} key="loading-spinner">
<Spinner size="md" color="blue.400" />
<Text color="gray.400" fontSize="sm">
Loading more songs...
</Text>
</Flex>
)}
{/* Intersection observer target */}
<div ref={loadingRef} style={{ height: '20px' }} key="intersection-target" />
{/* Loading more indicator (subtle) */}
{!loading && hasMore && songs.length > 0 && (
<Flex justify="center" p={3} key="loading-more-indicator">
<Text color="gray.600" fontSize="xs">
Scroll for more songs
</Text>
</Flex>
)}
{/* End of results message */}
{!hasMore && songs.length > 0 && (
<Flex justify="center" p={4} key="end-message">

View File

@ -78,7 +78,7 @@ const PlaylistItem: React.FC<PlaylistItemProps> = ({
allFolders,
}) => {
const [isOpen, setIsOpen] = useState(false);
const indent = level * 10; // Reverted back to 10px per level
const indent = level * 10;
if (node.type === 'folder') {
return (
@ -89,9 +89,7 @@ const PlaylistItem: React.FC<PlaylistItemProps> = ({
{...getButtonStyles(false)}
onClick={() => setIsOpen(!isOpen)}
ml={indent}
pl={level > 0 ? 6 : 4} // Add extra padding for nested items
justifyContent="flex-start"
position="relative"
leftIcon={
<Box position="relative" display="flex" alignItems="center">
<ChevronRightIcon
@ -104,18 +102,6 @@ const PlaylistItem: React.FC<PlaylistItemProps> = ({
</Box>
}
>
{level > 0 && (
<Box
position="absolute"
left="8px"
top="50%"
transform="translateY(-50%)"
width="2px"
height="12px"
bg="gray.500"
borderRadius="1px"
/>
)}
<Icon
viewBox="0 0 24 24"
color="blue.300"
@ -157,24 +143,10 @@ const PlaylistItem: React.FC<PlaylistItemProps> = ({
{...getButtonStyles(selectedItem === node.name)}
onClick={() => onPlaylistSelect(node.name)}
ml={indent}
pl={level > 0 ? 6 : 4} // Add extra padding for nested items
borderRightRadius={0}
borderRight="1px solid"
borderRightColor="whiteAlpha.200"
position="relative"
>
{level > 0 && (
<Box
position="absolute"
left="8px"
top="50%"
transform="translateY(-50%)"
width="2px"
height="12px"
bg="gray.500"
borderRadius="1px"
/>
)}
{node.name}
</Button>
<Menu>
@ -294,9 +266,21 @@ export const PlaylistManager: React.FC<PlaylistManagerProps> = ({
>
All Songs
</Button>
{playlists.map((node, index) => (
<PlaylistItem
key={node.id || index}
node={node}
level={0}
selectedItem={selectedItem}
onPlaylistSelect={onPlaylistSelect}
onPlaylistDelete={onPlaylistDelete}
onPlaylistMove={onPlaylistMove}
allFolders={allFolders}
/>
))}
</VStack>
{/* Add Playlist and Folder buttons at the top */}
<Flex gap={2} mb={2}>
<Flex gap={2}>
<Button
onClick={onPlaylistModalOpen}
colorScheme="blue"
@ -327,20 +311,6 @@ export const PlaylistManager: React.FC<PlaylistManagerProps> = ({
</Button>
</Flex>
{playlists.map((node, index) => (
<PlaylistItem
key={node.id || index}
node={node}
level={0}
selectedItem={selectedItem}
onPlaylistSelect={onPlaylistSelect}
onPlaylistDelete={onPlaylistDelete}
onPlaylistMove={onPlaylistMove}
allFolders={allFolders}
/>
))}
</VStack>
{/* New Playlist Modal */}
<Modal
isOpen={isPlaylistModalOpen}

View File

@ -18,13 +18,10 @@ export const usePaginatedSongs = (options: UsePaginatedSongsOptions = {}) => {
const [currentPage, setCurrentPage] = useState(1);
const [searchQuery, setSearchQuery] = useState(initialSearch);
const [totalSongs, setTotalSongs] = useState(0);
const [totalDuration, setTotalDuration] = useState<number | undefined>(undefined);
const [isInitialLoad, setIsInitialLoad] = useState(true);
const loadingRef = useRef(false);
const currentPlaylistRef = useRef(playlistName);
const currentSearchQueryRef = useRef(searchQuery);
const previousPlaylistRef = useRef(playlistName);
const abortControllerRef = useRef<AbortController | null>(null);
// Cleanup function to prevent memory leaks
@ -37,11 +34,10 @@ export const usePaginatedSongs = (options: UsePaginatedSongsOptions = {}) => {
}, []);
// Load songs for a specific page
const loadPage = useCallback(async (page: number, search?: string, targetPlaylist?: string) => {
const loadPage = useCallback(async (page: number, search: string = searchQuery, targetPlaylist?: string) => {
if (loadingRef.current) return;
const searchToUse = search ?? currentSearchQueryRef.current;
const playlistToUse = targetPlaylist ?? currentPlaylistRef.current;
const playlistToUse = targetPlaylist || playlistName;
// Cleanup previous request
cleanup();
@ -58,10 +54,10 @@ export const usePaginatedSongs = (options: UsePaginatedSongsOptions = {}) => {
if (playlistToUse && playlistToUse !== 'All Songs') {
// Load songs for specific playlist
response = await api.getPlaylistSongsPaginated(playlistToUse, page, pageSize, searchToUse);
response = await api.getPlaylistSongsPaginated(playlistToUse, page, pageSize, search);
} else {
// Load all songs
response = await api.getSongsPaginated(page, pageSize, searchToUse);
response = await api.getSongsPaginated(page, pageSize, search);
}
// Check if request was aborted
@ -79,7 +75,6 @@ export const usePaginatedSongs = (options: UsePaginatedSongsOptions = {}) => {
setHasMore(response.pagination.hasNextPage);
setTotalSongs(response.pagination.totalSongs);
setTotalDuration(response.totalDuration);
setCurrentPage(page);
} catch (err) {
// Don't set error if request was aborted
@ -93,7 +88,7 @@ export const usePaginatedSongs = (options: UsePaginatedSongsOptions = {}) => {
setIsInitialLoad(false);
}
}
}, [pageSize, cleanup]); // Remove searchQuery and playlistName from dependencies
}, [pageSize, searchQuery, playlistName, cleanup]);
// Load next page (for infinite scroll)
const loadNextPage = useCallback(() => {
@ -105,8 +100,7 @@ export const usePaginatedSongs = (options: UsePaginatedSongsOptions = {}) => {
// Search songs with debouncing
const searchSongs = useCallback((query: string) => {
setSearchQuery(query);
// Clear songs for new search to replace them
setSongs([]);
// Don't clear songs immediately - let the new search results replace them
setHasMore(true);
setCurrentPage(1);
setError(null);
@ -137,14 +131,10 @@ export const usePaginatedSongs = (options: UsePaginatedSongsOptions = {}) => {
// Handle playlist changes
useEffect(() => {
if (!isInitialLoad && previousPlaylistRef.current !== playlistName) {
// Update refs
if (currentPlaylistRef.current !== playlistName) {
currentPlaylistRef.current = playlistName;
currentSearchQueryRef.current = searchQuery;
previousPlaylistRef.current = playlistName;
// Clear songs for new playlist to replace them
setSongs([]);
if (!isInitialLoad) {
// Don't clear songs immediately - let the new playlist results replace them
setHasMore(true);
setCurrentPage(1);
setSearchQuery(initialSearch);
@ -154,6 +144,7 @@ export const usePaginatedSongs = (options: UsePaginatedSongsOptions = {}) => {
loadPage(1, initialSearch, playlistName);
}, 0);
}
}
}, [playlistName, isInitialLoad, initialSearch, loadPage]);
return {
@ -162,7 +153,6 @@ export const usePaginatedSongs = (options: UsePaginatedSongsOptions = {}) => {
error,
hasMore,
totalSongs,
totalDuration,
currentPage,
searchQuery,
isInitialLoad,

View File

@ -14,7 +14,6 @@ export interface PaginationInfo {
export interface SongsResponse {
songs: Song[];
pagination: PaginationInfo;
totalDuration?: number; // Total duration of the entire playlist in seconds
}
class Api {