Spaces:
Running
Running
Update index.html
Browse files2 unmodified lines34567891049 unmodified lines6061626364651 unmodified line67686970717273742 unmodified lines777879808182838485868788899026 unmodified lines1171181191201211221238 unmodified lines1321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602614 unmodified lines2662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952966 unmodified lines3033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807811 unmodified line7837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748752 unmodified lines<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>HF Video Library</title><style>* {box-sizing: border-box;margin: 0;49 unmodified linescursor: pointer;transition: all 0.2s;background-color: white;}.video-item:hover {transform: translateY(-5px);1 unmodified line}.video-thumbnail {width: 100%;height: 156px;background-color: #333;border-radius: 4px;display: flex;align-items: center;2 unmodified linesoverflow: hidden;position: relative;}.video-thumbnail img {width: 100%;height: 100%;object-fit: cover;}.video-item-title {font-weight: 500;margin-top: 10px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;26 unmodified linesleft: 0;width: 100%;height: 100%;background-color: rgba(0,0,0,0.8);display: flex;align-items: center;justify-content: center;8 unmodified lines}.popup-content {width: 90%;max-width: 1024px;background-color: #222;border-radius: 8px;overflow: hidden;position: relative;box-shadow: 0 10px 25px rgba(0,0,0,0.5);}.close-popup {position: absolute;top: 10px;right: 10px;background-color: rgba(0,0,0,0.5);color: white;border: none;width: 30px;height: 30px;border-radius: 50%;display: flex;align-items: center;justify-content: center;cursor: pointer;z-index: 10;font-size: 18px;}.player-wrapper {position: relative;width: 100%;padding-top: 56.25%; /* 16:9 Aspect Ratio */}#videoPlayer {position: absolute;top: 0;left: 0;width: 100%;height: 100%;background-color: #000;}.popup-title {color: white;padding: 15px;font-size: 1.2em;background-color: #111;}.controls {display: flex;gap: 10px;padding: 15px;background-color: #111;flex-wrap: wrap;}.btn {padding: 8px 16px;background-color: #333;color: white;border: none;border-radius: 4px;cursor: pointer;transition: background-color 0.2s;}.btn:hover {background-color: #555;}.btn.active {background-color: #007bff;}.instructions {color: #ccc;padding: 10px 15px;background-color: #111;font-size: 0.9em;}.play-icon {font-size: 50px;color: white;opacity: 0.8;transition: opacity 0.2s;position: absolute;}.video-item:hover .play-icon {opacity: 1;}.loading-spinner {position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);width: 40px;height: 40px;border: 4px solid rgba(255, 255, 255, 0.3);border-radius: 50%;border-top: 4px solid #fff;animation: spin 1s linear infinite;z-index: 10;display: none;}@keyframes spin {0% { transform: translate(-50%, -50%) rotate(0deg); }100% { transform: translate(-50%, -50%) rotate(360deg); }}.buffering-indicator {position: absolute;bottom: 60px;left: 10px;background-color: rgba(0,0,0,0.5);color: white;padding: 5px 10px;border-radius: 4px;font-size: 12px;z-index: 10;display: none;}.seek-preview {position: absolute;bottom: 100px;left: 50%;transform: translateX(-50%);background-color: rgba(0,0,0,0.7);color: white;padding: 5px 10px;border-radius: 4px;font-size: 14px;z-index: 10;display: none;}.no-videos {padding: 20px;text-align: center;4 unmodified linesgrid-template-columns: repeat(auto-fill, minmax(200px, 1fr));}.popup-content {width: 95%;}.controls {gap: 5px;padding: 10px;}.btn {padding: 6px 12px;font-size: 0.9em;}}</style></head><body><div class="container"><div class="header"><h1>HF Video Library</h1></div><div class="search-container"><input type="text" id="search" placeholder="Search videos..."></div><div class="video-list"><div class="video-grid" id="videoGrid"><div class="video-item"><div class="video-thumbnail">Loading...</div></div>6 unmodified lines<div class="popup-overlay" id="playerPopup"><div class="popup-content"><button class="close-popup" id="closePopup">✕</button><div class="buffering-indicator" id="bufferingIndicator">Buffering...</div><div class="seek-preview" id="seekPreview"></div><div class="popup-title" id="currentTitle">Video Title</div><div class="player-wrapper"><div class="loading-spinner" id="loadingSpinner"></div><video id="videoPlayer" preload="auto" playsinline>Your browser does not support the video tag.</video></div><div class="controls"><button class="btn" id="backwardBtn">⏪ 10s</button><button class="btn" id="playPauseBtn">⏯️ Play/Pause</button><button class="btn" id="forwardBtn">⏩ 10s</button><button class="btn" id="fullscreenBtn">⛶ Fullscreen</button><button class="btn" id="muteBtn">🔊 Mute/Unmute</button></div><div class="instructions"><p><strong>Keyboard Controls:</strong> Space (Play/Pause) • ← (Back 10s) • → (Forward 10s) • F (Fullscreen) • M (Mute/Unmute)</p><p><strong>Double-tap:</strong> Left side (Back 10s) • Center (Play/Pause) • Right side (Forward 10s)</p></div></div></div><script>// Global variableslet videoData = [];let filteredVideos = [];let currentVideo = null;let currentPage = 1;const videosPerPage = 10;let isSeeking = false;let preloadedSegments = new Set();// DOM Elementsconst videoGrid = document.getElementById('videoGrid');const pagination = document.getElementById('pagination');const searchInput = document.getElementById('search');const playerPopup = document.getElementById('playerPopup');const videoPlayer = document.getElementById('videoPlayer');const currentTitle = document.getElementById('currentTitle');const closePopup = document.getElementById('closePopup');const playPauseBtn = document.getElementById('playPauseBtn');const backwardBtn = document.getElementById('backwardBtn');const forwardBtn = document.getElementById('forwardBtn');const fullscreenBtn = document.getElementById('fullscreenBtn');const muteBtn = document.getElementById('muteBtn');const loadingSpinner = document.getElementById('loadingSpinner');const bufferingIndicator = document.getElementById('bufferingIndicator');const seekPreview = document.getElementById('seekPreview');// Function to fetch video dataasync function fetchVideoData() {try {const response = await fetch('database.json');if (!response.ok) {throw new Error('Failed to fetch video data');}const data = await response.json();// Check if data has videos array or is itself an arrayvideoData = Array.isArray(data) ? data :(data.videos && Array.isArray(data.videos) ? data.videos : []);// Optimize HF URLsvideoData.forEach(video => {if (video.url.includes('huggingface.co')) {// Force no-transform for HF URLsif (!video.url.includes('?')) {video.url += '?';}if (!video.url.includes('download=true')) {video.url += (video.url.endsWith('?') ? '' : '&') + 'download=true';}}});filteredVideos = [...videoData];renderPagination();renderVideoGrid();} catch (error) {console.error('Error fetching video data:', error);videoGrid.innerHTML = `<div class="no-videos">Error loading videos: ${error.message}</div>`;}}// Function to render video gridfunction renderVideoGrid() {if (filteredVideos.length === 0) {videoGrid.innerHTML = '<div class="no-videos">No videos found</div>';pagination.innerHTML = '';return;}// Calculate start and end index for current pageconst startIndex = (currentPage - 1) * videosPerPage;const endIndex = Math.min(startIndex + videosPerPage, filteredVideos.length);const currentVideos = filteredVideos.slice(startIndex, endIndex);videoGrid.innerHTML = currentVideos.map((video, index) => `<div class="video-item" data-index="${startIndex + index}"><div class="video-thumbnail"><div class="play-icon">▶</div></div><div class="video-item-title">${video.title}</div></div>`).join('');// Add click event listeners to video itemsdocument.querySelectorAll('.video-item').forEach(item => {item.addEventListener('click', function() {const index = parseInt(this.getAttribute('data-index'));if (!isNaN(index) && index >= 0 && index < filteredVideos.length) {playVideo(filteredVideos[index]);}});});}// Function to render paginationfunction renderPagination() {const totalPages = Math.ceil(filteredVideos.length / videosPerPage);if (totalPages <= 1) {pagination.innerHTML = '';return;}// Determine which page buttons to showlet buttons = [];if (totalPages <= 7) {// Show all pages if 7 or fewerfor (let i = 1; i <= totalPages; i++) {buttons.push(i);}} else {// Always include first pagebuttons.push(1);// Add ellipsis if current page is more than 3if (currentPage > 3) {buttons.push('...');}// Add pages around current pageconst startPage = Math.max(2, currentPage - 1);const endPage = Math.min(totalPages - 1, currentPage + 1);for (let i = startPage; i <= endPage; i++) {buttons.push(i);}// Add ellipsis if current page is less than totalPages - 2if (currentPage < totalPages - 2) {buttons.push('...');}// Always include last pagebuttons.push(totalPages);}// Create pagination HTMLpagination.innerHTML = buttons.map(button => {if (button === '...') {return '<span class="page-btn">...</span>';}return `<button class="page-btn ${button === currentPage ? 'active' : ''}" data-page="${button}">${button}</button>`;}).join('');// Add click event listeners to page buttonsdocument.querySelectorAll('.page-btn[data-page]').forEach(button => {button.addEventListener('click', function() {currentPage = parseInt(this.getAttribute('data-page'));renderPagination();renderVideoGrid();window.scrollTo(0, 0);});});}// Function to play video with ultra-fast seekingfunction playVideo(video) {currentVideo = video;currentTitle.textContent = video.title;// Reset stateisSeeking = false;preloadedSegments.clear();// Show loading spinnerloadingSpinner.style.display = 'block';bufferingIndicator.style.display = 'none';// Optimize HF URLlet videoUrl = video.url;if (videoUrl.includes('huggingface.co')) {if (!videoUrl.includes('?')) {videoUrl += '?';}if (!videoUrl.includes('download=true')) {videoUrl += (videoUrl.endsWith('?') ? '' : '&') + 'download=true';}}// Use MediaSource for advanced buffering control if supportedif (window.MediaSource && MediaSource.isTypeSupported('video/mp4')) {setupMediaSourcePlayer(videoUrl);} else {setupRegularPlayer(videoUrl);}// Show popupplayerPopup.classList.add('active');// Disable scrolling on body when popup is activedocument.body.style.overflow = 'hidden';}function setupMediaSourcePlayer(url) {const mediaSource = new MediaSource();videoPlayer.src = URL.createObjectURL(mediaSource);mediaSource.addEventListener('sourceopen', function() {const sourceBuffer = mediaSource.addSourceBuffer('video/mp4');// Start loading the initial segmentfetchSegment(url, 0, 1024 * 1024 * 2) // First 2MB.then(segment => {sourceBuffer.addEventListener('updateend', function() {if (!sourceBuffer.updating && mediaSource.readyState === 'open') {mediaSource.endOfStream();videoPlayer.play().catch(e => console.error('Play error:', e));loadingSpinner.style.display = 'none';// Start aggressive preloadingpreloadNextSegments(videoPlayer.duration, url);}}, { once: true });sourceBuffer.appendBuffer(segment);}).catch(error => {console.error('Error loading initial segment:', error);// Fallback to regular playersetupRegularPlayer(url);});// Handle seekingvideoPlayer.addEventListener('seeking', function() {if (!isSeeking && mediaSource.readyState === 'open') {isSeeking = true;const targetTime = videoPlayer.currentTime;seekPreview.textContent = formatTime(targetTime);seekPreview.style.display = 'block';// Load segment around seek positionconst segmentStart = Math.max(0, targetTime - 2);const segmentEnd = Math.min(videoPlayer.duration, targetTime + 2);fetchByteRange(url, segmentStart, segmentEnd).then(segment => {sourceBuffer.appendBuffer(segment);seekPreview.style.display = 'none';isSeeking = false;}).catch(error => {console.error('Seek error:', error);seekPreview.style.display = 'none';isSeeking = false;});}});});setupPlayerEventListeners();}function setupRegularPlayer(url) {videoPlayer.src = url;videoPlayer.load();// Set up event listeners for immediate playbackvideoPlayer.addEventListener('canplaythrough', function() {loadingSpinner.style.display = 'none';videoPlayer.play().catch(e => console.error('Play error:', e));// Start aggressive preloadingpreloadNextSegments(videoPlayer.duration, url);}, { once: true });videoPlayer.addEventListener('seeking', function() {const targetTime = videoPlayer.currentTime;seekPreview.textContent = formatTime(targetTime);seekPreview.style.display = 'block';setTimeout(() => {seekPreview.style.display = 'none';}, 1000);});setupPlayerEventListeners();}function preloadNextSegments(duration, url) {if (!duration || duration === Infinity) return;const currentTime = videoPlayer.currentTime;const segmentSize = 1024 * 1024 * 4; // 4MB segments// Preload next 3 segments aheadfor (let i = 1; i <= 3; i++) {const segmentStart = currentTime + (i * 5);if (segmentStart >= duration) break;const segmentEnd = Math.min(duration, segmentStart + 5);const segmentKey = `${Math.floor(segmentStart)}-${Math.floor(segmentEnd)}`;if (!preloadedSegments.has(segmentKey)) {preloadedSegments.add(segmentKey);// Just trigger the download, we don't need the data for regular playbackfetchByteRange(url, segmentStart, segmentEnd).catch(error => console.error('Preload error:', error));}}}async function fetchSegment(url, start, end) {const response = await fetch(url, {headers: {'Range': `bytes=${start}-${end}`}});if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}return response.arrayBuffer();}async function fetchByteRange(url, startTime, endTime) {// Estimate byte range based on time (approximation)const duration = videoPlayer.duration || 60; // Fallback to 60s if unknownconst fileSize = await getFileSize(url);const startByte = Math.floor((startTime / duration) * fileSize);const endByte = Math.floor((endTime / duration) * fileSize);return fetchSegment(url, startByte, endByte);}async function getFileSize(url) {try {const response = await fetch(url, { method: 'HEAD' });if (response.ok) {const contentLength = response.headers.get('Content-Length');return parseInt(contentLength) || 100 * 1024 * 1024; // Fallback to 100MB}} catch (error) {console.error('Error getting file size:', error);}return 100 * 1024 * 1024; // Default fallback}function setupPlayerEventListeners() {// Play/Pause buttonplayPauseBtn.addEventListener('click', togglePlayPause);// Backward/Forward buttonsbackwardBtn.addEventListener('click', () => seekRelative(-10));forwardBtn.addEventListener('click', () => seekRelative(10));// Fullscreen buttonfullscreenBtn.addEventListener('click', toggleFullscreen);// Mute buttonmuteBtn.addEventListener('click', toggleMute);// Player eventsvideoPlayer.addEventListener('play', () => {playPauseBtn.textContent = '⏸️ Pause';});videoPlayer.addEventListener('pause', () => {playPauseBtn.textContent = '⏯️ Play';});videoPlayer.addEventListener('waiting', () => {bufferingIndicator.style.display = 'block';});videoPlayer.addEventListener('playing', () => {bufferingIndicator.style.display = 'none';});videoPlayer.addEventListener('timeupdate', () => {// Continuously preload aheadpreloadNextSegments(videoPlayer.duration, videoPlayer.src);});videoPlayer.addEventListener('error', (e) => {console.error('Video error:', videoPlayer.error);loadingSpinner.style.display = 'none';bufferingIndicator.style.display = 'none';});}function togglePlayPause() {if (videoPlayer.paused) {videoPlayer.play().catch(error => {console.error('Error playing video:', error);});} else {videoPlayer.pause();}}function seekRelative(seconds) {const newTime = Math.max(0, Math.min(videoPlayer.duration, videoPlayer.currentTime + seconds));videoPlayer.currentTime = newTime;// Show seek previewseekPreview.textContent = formatTime(newTime);seekPreview.style.display = 'block';setTimeout(() => {seekPreview.style.display = 'none';}, 1000);}function formatTime(seconds) {const mins = Math.floor(seconds / 60);const secs = Math.floor(seconds % 60);return `${mins}:${secs < 10 ? '0' : ''}${secs}`;}function toggleFullscreen() {if (!document.fullscreenElement) {if (playerPopup.requestFullscreen) {playerPopup.requestFullscreen();} else if (playerPopup.webkitRequestFullscreen) {playerPopup.webkitRequestFullscreen();} else if (playerPopup.msRequestFullscreen) {playerPopup.msRequestFullscreen();}} else {if (document.exitFullscreen) {document.exitFullscreen();} else if (document.webkitExitFullscreen) {document.webkitExitFullscreen();} else if (document.msExitFullscreen) {document.msExitFullscreen();}}}function toggleMute() {videoPlayer.muted = !videoPlayer.muted;muteBtn.textContent = videoPlayer.muted ? '🔇 Unmute' : '🔊 Mute';}// Close popup functionfunction closePlayerPopup() {videoPlayer.pause();if (videoPlayer.src.startsWith('blob:')) {URL.revokeObjectURL(videoPlayer.src);}videoPlayer.src = '';playerPopup.classList.remove('active');document.body.style.overflow = '';}// Search functionalitysearchInput.addEventListener('input', function() {const searchTerm = this.value.toLowerCase();filteredVideos = videoData.filter(video =>video.title.toLowerCase().includes(searchTerm));currentPage = 1; // Reset to first page on search1 unmodified linerenderVideoGrid();});// Close popup when clicking close buttonclosePopup.addEventListener('click', closePlayerPopup);// Close popup when clicking outside contentplayerPopup.addEventListener('click', function(e) {if (e.target === playerPopup) {closePlayerPopup();}});// Keyboard controls (only active when popup is visible)document.addEventListener('keydown', function(e) {if (!playerPopup.classList.contains('active')) return;switch(e.key) {case ' ': // SpacetogglePlayPause();e.preventDefault();break;case 'ArrowRight':seekRelative(10);e.preventDefault();break;case 'ArrowLeft':seekRelative(-10);e.preventDefault();break;case 'f':case 'F':toggleFullscreen();e.preventDefault();break;case 'm':case 'M':toggleMute();e.preventDefault();break;case 'Escape':closePlayerPopup();e.preventDefault();break;}});// Double tap controls for mobile/touch deviceslet lastTap = 0;let tapTimeout;videoPlayer.addEventListener('click', function(e) {const currentTime = new Date().getTime();const tapLength = currentTime - lastTap;clearTimeout(tapTimeout);if (tapLength < 500 && tapLength > 0) {// Double tap detectedconst playerRect = videoPlayer.getBoundingClientRect();const clickX = e.clientX - playerRect.left;const playerWidth = playerRect.width;// Determine click position (left, center, or right third)if (clickX < playerWidth / 3) {// Left side - backwardseekRelative(-10);} else if (clickX > (playerWidth * 2) / 3) {// Right side - forwardseekRelative(10);} else {// Center - play/pausetogglePlayPause();}e.preventDefault();} else {// Single tap - wait to see if it becomes a double taptapTimeout = setTimeout(function() {// Single tap action (toggle controls visibility)if (videoPlayer.hasAttribute('controls')) {videoPlayer.removeAttribute('controls');} else {videoPlayer.setAttribute('controls', '');}}, 300);}lastTap = currentTime;});// InitializefetchVideoData();</script></body></html>2 unmodified lines345678910111213141549 unmodified lines65666768697071721 unmodified line74757677787980812 unmodified lines8485868788899091929394959697989910010110210310410510610726 unmodified lines1341351361371381391408 unmodified lines1491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132144 unmodified lines2192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492506 unmodified lines2572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455461 unmodified line5485495505515525535545555565575585595605615625635645655665675685695705715725732 unmodified lines<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>HF Video Library (Optimized with Plyr)</title><!-- Plyr CSS --><link rel="stylesheet" href="https://cdn.plyr.io/3.7.8/plyr.css" /><style>/* --- Keep your existing styles for layout, search, grid, etc. --- */* {box-sizing: border-box;margin: 0;49 unmodified linescursor: pointer;transition: all 0.2s;background-color: white;display: flex; /* Use flexbox for better alignment */flex-direction: column;}.video-item:hover {transform: translateY(-5px);1 unmodified line}.video-thumbnail {width: 100%;height: 156px; /* Maintain aspect ratio consistency */background-color: #e0e0e0; /* Lighter placeholder */border-radius: 4px;display: flex;align-items: center;2 unmodified linesoverflow: hidden;position: relative;}.video-thumbnail img { /* Optional: If you add thumbnail images later */width: 100%;height: 100%;object-fit: cover;}.play-icon { /* Simple text icon */font-size: 40px;color: rgba(0,0,0,0.6);opacity: 0.8;transition: opacity 0.2s;position: absolute;}.video-item:hover .play-icon {opacity: 1;}.video-item-title {font-weight: 500;margin-top: auto; /* Pushes title down if thumbnail varies slightly */white-space: nowrap;overflow: hidden;text-overflow: ellipsis;26 unmodified linesleft: 0;width: 100%;height: 100%;background-color: rgba(0,0,0,0.85); /* Slightly darker */display: flex;align-items: center;justify-content: center;8 unmodified lines}.popup-content {width: 90%;max-width: 1100px; /* Slightly wider for player */background-color: #000; /* Black background suits player */border-radius: 8px;overflow: hidden;position: relative;box-shadow: 0 10px 25px rgba(0,0,0,0.5);display: flex; /* Use flexbox for title + player */flex-direction: column;}.close-popup {position: absolute;top: 8px; /* Adjust for better placement */right: 8px; /* Adjust for better placement */background-color: rgba(30,30,30,0.7); /* Subtle background */color: white;border: none;width: 32px; /* Slightly larger */height: 32px;border-radius: 50%;display: flex;align-items: center;justify-content: center;cursor: pointer;z-index: 1001; /* Ensure it's above Plyr */font-size: 18px;line-height: 1; /* Ensure centering */}.close-popup:hover {background-color: rgba(50,50,50,0.9);}.popup-title {color: white;padding: 12px 15px; /* Adjust padding */font-size: 1.1em; /* Adjust size */background-color: #111;text-align: center;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;order: -1; /* Display title above video */}/* Remove custom controls, player-wrapper, spinner, indicators *//* .controls, .player-wrapper, #loadingSpinner, #bufferingIndicator, #seekPreview { display: none; } *//* Style the video element itself if needed, but Plyr handles most */#videoPlayer {display: block; /* Ensure it takes block layout */width: 100%;height: auto; /* Let Plyr manage height based on aspect ratio */max-height: 80vh; /* Prevent excessive height on tall screens */background-color: #000;}/* Plyr Customizations (Optional) */:root {--plyr-color-main: #007bff; /* Example: Blue theme */}.no-videos {padding: 20px;text-align: center;4 unmodified linesgrid-template-columns: repeat(auto-fill, minmax(200px, 1fr));}.popup-content {width: 98%; /* Almost full width on mobile */max-width: none;height: auto;}#videoPlayer {max-height: 85vh; /* Adjust max height for mobile */}.popup-title {font-size: 1em;}}</style></head><body><div class="container"><div class="header"><h1>HF Video Library <small>(Plyr Enhanced)</small></h1></div><div class="search-container"><input type="text" id="search" placeholder="Search videos..."></div><div class="video-list"><div class="video-grid" id="videoGrid"><!-- Video items will be loaded here --><div class="video-item"><div class="video-thumbnail">Loading...</div></div>6 unmodified lines<div class="popup-overlay" id="playerPopup"><div class="popup-content"><button class="close-popup" id="closePopup">✕</button><div class="popup-title" id="currentTitle">Video Title</div><!-- The video element Plyr will enhance --><video id="videoPlayer" playsinline controls preload="metadata"><!-- preload="metadata" is often a good balance -->Your browser does not support the video tag.</video><!-- Custom controls and instructions are removed - Plyr provides them --></div></div><!-- Plyr JS --><script src="https://cdn.plyr.io/3.7.8/plyr.js"></script><script>// Global variableslet videoData = [];let filteredVideos = [];let currentVideo = null;let currentPage = 1;const videosPerPage = 12; // Adjusted for potentially smaller cardslet player = null; // To hold the Plyr instance// DOM Elementsconst videoGrid = document.getElementById('videoGrid');const pagination = document.getElementById('pagination');const searchInput = document.getElementById('search');const playerPopup = document.getElementById('playerPopup');const videoPlayerElement = document.getElementById('videoPlayer'); // Get the elementconst currentTitle = document.getElementById('currentTitle');const closePopup = document.getElementById('closePopup');// --- Fetching, Rendering Grid, Pagination (Keep mostly the same) ---async function fetchVideoData() {try {// Show initial loading statevideoGrid.innerHTML = '<div class="no-videos">Loading video list...</div>';pagination.innerHTML = '';const response = await fetch('database.json'); // Ensure this path is correctif (!response.ok) {throw new Error(`Failed to fetch video data (Status: ${response.status})`);}const data = await response.json();videoData = Array.isArray(data) ? data :(data.videos && Array.isArray(data.videos) ? data.videos : []);// Optimize HF URLs (Keep this logic)videoData.forEach(video => {if (video.url && video.url.includes('huggingface.co')) {let url = new URL(video.url);// Ensure download=true is present without duplicating query paramsif(url.searchParams.get('download') !== 'true') {url.searchParams.set('download', 'true');}video.url = url.toString();}// Basic validationif (!video.title || !video.url) {console.warn("Skipping video with missing title or URL:", video);}});// Filter out invalid entries before proceedingvideoData = videoData.filter(video => video.title && video.url);if (videoData.length === 0) {videoGrid.innerHTML = '<div class="no-videos">No valid videos found in database.json</div>';return;}filteredVideos = [...videoData];currentPage = 1; // Reset to page 1renderPagination();renderVideoGrid();} catch (error) {console.error('Error fetching or processing video data:', error);videoGrid.innerHTML = `<div class="no-videos">Error loading videos: ${error.message}. Check console.</div>`;}}function renderVideoGrid() {videoGrid.innerHTML = ''; // Clear previous itemsif (filteredVideos.length === 0) {videoGrid.innerHTML = '<div class="no-videos">No videos match your search.</div>';// Don't clear pagination if there are videos overall, just no search resultsif (videoData.length > 0 && searchInput.value) {renderPagination(); // Keep pagination visible} else {pagination.innerHTML = ''; // Hide if no videos at all}return;}const startIndex = (currentPage - 1) * videosPerPage;const endIndex = Math.min(startIndex + videosPerPage, filteredVideos.length);const currentVideos = filteredVideos.slice(startIndex, endIndex);const fragment = document.createDocumentFragment();currentVideos.forEach((video, index) => {const videoItem = document.createElement('div');videoItem.className = 'video-item';videoItem.setAttribute('data-index', startIndex + index);videoItem.innerHTML = `<div class="video-thumbnail"><div class="play-icon">▶</div>${video.thumbnail ? `<img src="${video.thumbnail}" alt="${video.title} thumbnail" loading="lazy">` : ''}</div><div class="video-item-title" title="${video.title}">${video.title}</div>`;videoItem.addEventListener('click', function() {const dataIndex = parseInt(this.getAttribute('data-index'));if (!isNaN(dataIndex) && dataIndex >= 0 && dataIndex < filteredVideos.length) {playVideo(filteredVideos[dataIndex]);} else {console.error("Invalid video index clicked:", dataIndex);}});fragment.appendChild(videoItem);});videoGrid.appendChild(fragment);}function renderPagination() {const totalPages = Math.ceil(filteredVideos.length / videosPerPage);pagination.innerHTML = ''; // Clear existing buttonsif (totalPages <= 1) {return; // No pagination needed for 0 or 1 page}let buttons = [];const maxVisibleButtons = 7; // Max buttons like 1 ... 5 6 7 ... 10if (totalPages <= maxVisibleButtons) {for (let i = 1; i <= totalPages; i++) {buttons.push(i);}} else {buttons.push(1); // Always show first pagelet startPage, endPage;if (currentPage <= Math.floor(maxVisibleButtons / 2) + 1) {// Near the beginningstartPage = 2;endPage = maxVisibleButtons - 2; // 1 + (max-2 pages) + ... + lastfor (let i = startPage; i <= endPage; i++) buttons.push(i);buttons.push('...');} else if (currentPage >= totalPages - Math.floor(maxVisibleButtons / 2)) {// Near the endstartPage = totalPages - (maxVisibleButtons - 3); // first + ... + (max-2 pages) + lastbuttons.push('...');for (let i = startPage; i < totalPages; i++) buttons.push(i);} else {// In the middlebuttons.push('...');const sideButtons = Math.floor((maxVisibleButtons - 3) / 2); // Buttons around currentstartPage = currentPage - sideButtons;endPage = currentPage + sideButtons;for (let i = startPage; i <= endPage; i++) buttons.push(i);buttons.push('...');}buttons.push(totalPages); // Always show last page}// Create pagination HTMLpagination.innerHTML = buttons.map(button => {if (button === '...') {return '<span class="page-btn disabled">...</span>'; // Non-clickable ellipsis}return `<button class="page-btn ${button === currentPage ? 'active' : ''}" data-page="${button}">${button}</button>`;}).join('');// Add click event listeners to page buttonsdocument.querySelectorAll('.page-btn[data-page]').forEach(button => {button.addEventListener('click', function() {const newPage = parseInt(this.getAttribute('data-page'));if (newPage !== currentPage) {currentPage = newPage;renderPagination(); // Update buttons appearancerenderVideoGrid(); // Render new page contentwindow.scrollTo({ top: videoGrid.offsetTop - 20, behavior: 'smooth' }); // Scroll near top of grid}});});}// --- Player Logic (Using Plyr) ---function playVideo(video) {if (!video || !video.url) {console.error("Cannot play video: Invalid video data provided.");return;}currentVideo = video;currentTitle.textContent = video.title;currentTitle.setAttribute('title', video.title); // Add tooltip for long titles// Set the source for the video elementvideoPlayerElement.src = video.url;// Destroy previous Plyr instance if it existsif (player) {try {player.destroy();} catch (e) {console.warn("Error destroying previous Plyr instance:", e);}player = null;}// Initialize Plyrtry {player = new Plyr(videoPlayerElement, {// Plyr options (optional)title: video.title,controls: ['play-large', 'play', 'progress', 'current-time', 'mute', 'volume', 'captions', 'settings', 'pip', 'airplay', 'fullscreen'],settings: ['captions', 'quality', 'speed', 'loop'],// quality: {// // If you were using HLS/DASH, you'd configure quality options here// default: 720, // Example default quality// options: [1080, 720, 480]// },// tooltips: { controls: true, seek: true } // Enable tooltips});// Add event listener for when player is readyplayer.on('ready', () => {// Autoplay (optional, might be blocked by browsers)// player.play().catch(e => console.log("Autoplay prevented:", e));});// Add event listener for errorsplayer.on('error', event => {console.error('Plyr error:', event.detail.plyr.source, event);// Maybe display a user-friendly error message});// Show the popupplayerPopup.classList.add('active');document.body.style.overflow = 'hidden'; // Prevent background scroll} catch (error) {console.error("Failed to initialize Plyr:", error);// Fallback or error messagealert(`Error initializing video player for "${video.title}". Check console for details.`);// Still try to show the basic video element if Plyr fails?videoPlayerElement.load(); // Try loading without PlyrplayerPopup.classList.add('active');document.body.style.overflow = 'hidden';}}function closePlayerPopup() {if (player) {try {player.pause(); // Pause before destroyingplayer.destroy();} catch (e) {console.warn("Error destroying Plyr instance on close:", e)}player = null;}// Fallback if player wasn't initialized or destroyed properlyvideoPlayerElement.pause();videoPlayerElement.removeAttribute('src'); // Remove src to stop potential loadingvideoPlayerElement.load(); // Reset the media elementplayerPopup.classList.remove('active');document.body.style.overflow = ''; // Restore scrollcurrentVideo = null;}// --- Event Listeners (Search, Popup Close) ---searchInput.addEventListener('input', function() {const searchTerm = this.value.toLowerCase().trim();filteredVideos = videoData.filter(video =>video.title.toLowerCase().includes(searchTerm));currentPage = 1; // Reset to first page on search1 unmodified linerenderVideoGrid();});closePopup.addEventListener('click', closePlayerPopup);playerPopup.addEventListener('click', function(e) {// Close only if clicking the overlay itself, not the content insideif (e.target === playerPopup) {closePlayerPopup();}});// Close popup with Escape key (Plyr might handle this, but good fallback)document.addEventListener('keydown', function(e) {if (e.key === 'Escape' && playerPopup.classList.contains('active')) {closePlayerPopup();}});// --- Initial Load ---fetchVideoData();</script></body></html>
index.html+270-572