/** * NCThumbnail - Shared thumbnail loading utility. * * Provides consistent image element creation, error handling, * path encoding, and deferred loading across all services. * * Available at /shared/js/media/thumbnails.js via mountSharedStatic. */ window.NCThumbnail = (() => { /* ------------------------------------------------------------------ */ /* Utility */ /* ------------------------------------------------------------------ */ /** * Encode each segment of a path individually for safe URL embedding. * @param {string} p - e.g. 'folder/sub dir/file.jpg' * @returns {string} 'folder/sub%20dir/file.jpg' */ function encodePathSegments(p) { return String(p || '') .split('/') .map(encodeURIComponent) .join('/'); } /* ------------------------------------------------------------------ */ /* Image Element Creation */ /* ------------------------------------------------------------------ */ /** * Create a thumbnail `` with lazy loading and configurable error handling. * * @param {Object} opts * @param {string} opts.src - Image source URL * @param {string} [opts.alt=''] - Alt text * @param {string} [opts.className=''] - CSS class(es) * @param {boolean} [opts.lazy=true] - Set loading="lazy" * @param {boolean} [opts.asyncDecode=true] - Set decoding="async" * @param {string} [opts.fallbackSrc] - Swap to this URL on error * @param {string} [opts.fallbackIcon] - FA icon class for placeholder (e.g. 'fas fa-image') * @param {string} [opts.fallbackText] - Text shown inside placeholder * @param {string} [opts.fallbackClass] - Extra CSS class(es) on placeholder div * @param {Function}[opts.onError] - Custom onerror (overrides other fallbacks) * @param {Object} [opts.dataset={}] - data-* attributes * @returns {HTMLImageElement} */ function createImg(opts) { const img = document.createElement('img'); if (opts.className) img.className = opts.className; img.alt = opts.alt || ''; if (opts.lazy !== false) img.loading = 'lazy'; if (opts.asyncDecode !== false) img.decoding = 'async'; if (opts.src) img.src = opts.src; if (opts.dataset) { for (const [k, v] of Object.entries(opts.dataset)) img.dataset[k] = v; } if (typeof opts.onError === 'function') { img.onerror = opts.onError; } else if (opts.fallbackSrc) { img.onerror = function () { this.onerror = null; this.src = opts.fallbackSrc; }; } else if (opts.fallbackIcon || opts.fallbackText) { img.onerror = function () { this.onerror = null; const parent = this.parentElement; if (!parent) { this.style.display = 'none'; return; } this.remove(); const fb = document.createElement('div'); fb.className = opts.fallbackClass || 'flex flex-col items-center justify-center gap-1.5 text-slate-400'; if (opts.fallbackIcon) { const i = document.createElement('i'); i.className = opts.fallbackIcon; i.setAttribute('aria-hidden', 'true'); fb.appendChild(i); } if (opts.fallbackText) { const s = document.createElement('span'); s.className = 'text-xs'; s.textContent = opts.fallbackText; fb.appendChild(s); } parent.appendChild(fb); }; } return img; } /** * Create an `` paired with a hidden fallback sibling. * On error the image hides and the fallback shows - preserves layout. * * @param {Object} opts * @param {string} opts.src - Image source URL * @param {string} [opts.alt=''] - Alt text * @param {string} [opts.className=''] - CSS class(es) for the image * @param {string} [opts.fallbackHtml=''] - Inner HTML for the fallback * @param {string} [opts.fallbackClassName=''] - Extra class(es) on fallback * @param {Object} [opts.dataset={}] - data-* attributes on the image * @returns {{ img: HTMLImageElement, fallback: HTMLSpanElement }} */ function createImgWithFallback(opts) { const img = document.createElement('img'); if (opts.className) img.className = opts.className; img.alt = opts.alt || ''; img.loading = 'lazy'; img.decoding = 'async'; if (opts.src) img.src = opts.src; if (opts.dataset) { for (const [k, v] of Object.entries(opts.dataset)) img.dataset[k] = v; } const fallback = document.createElement('span'); fallback.className = 'hidden' + (opts.fallbackClassName ? ' ' + opts.fallbackClassName : ''); if (opts.fallbackHtml) fallback.innerHTML = opts.fallbackHtml; img.onerror = function () { this.onerror = null; this.classList.add('hidden'); fallback.classList.remove('hidden'); }; return { img, fallback }; } /* ------------------------------------------------------------------ */ /* Deferred Loading */ /* ------------------------------------------------------------------ */ /** * Deferred thumbnail loading via IntersectionObserver with a throttled * concurrent-request queue. * * Target images must use `data-src` (not `src`). When intersecting the * viewport, `data-src` is copied to `src`. * * @param {Object} opts * @param {string} [opts.selector='img[data-src]'] - Query selector * @param {Element} [opts.root=null] - Scroll container (null = viewport) * @param {string} [opts.rootMargin='300px'] - Preload margin * @param {number} [opts.maxConcurrent=4] - Max simultaneous loads * @param {Function}[opts.onLoad] - Callback per loaded image * @param {Function}[opts.onError] - Callback per failed image * @returns {{ destroy: Function, observe: Function }} */ function initDeferredLoading(opts = {}) { const { selector = 'img[data-src]', root = null, rootMargin = '300px', maxConcurrent = 4, onLoad, onError, } = opts; const queue = []; let inFlight = 0; const pump = () => { while (inFlight < maxConcurrent && queue.length) { const img = queue.shift(); if (!img || !img.isConnected) continue; const src = img.getAttribute('data-src'); if (!src) continue; img.removeAttribute('data-src'); inFlight++; const done = () => { inFlight = Math.max(0, inFlight - 1); pump(); }; img.addEventListener( 'load', () => { if (onLoad) onLoad(img); done(); }, { once: true } ); img.addEventListener( 'error', () => { if (onError) onError(img); done(); }, { once: true } ); img.src = src; } }; const observer = new IntersectionObserver( entries => { for (const e of entries) { if (!e.isIntersecting) continue; observer.unobserve(e.target); queue.push(e.target); } pump(); }, { root, rootMargin, threshold: 0.01 } ); const elements = document.querySelectorAll(selector); for (const el of elements) observer.observe(el); return { destroy() { observer.disconnect(); queue.length = 0; }, observe(el) { observer.observe(el); }, }; } /** * Attach load / error tracking to existing `` elements, toggling * an adjacent status-overlay element (e.g. "Loading..." -> hidden on * success, or "Couldn't load" on error). * * @param {Object} opts * @param {string} [opts.imgSelector='img[data-card-media]'] * @param {string} [opts.statusAttr='data-card-status'] * @param {string} [opts.errorText="Thumbnail couldn\u2019t load"] * @param {boolean} [opts.skipDeferred=false] - Skip imgs with data-src (handled by initDeferredLoading) */ function initStatusTracking(opts = {}) { const { imgSelector = 'img[data-card-media]', statusAttr = 'data-card-status', errorText = 'Thumbnail couldn\u2019t load', skipDeferred = false, } = opts; const images = document.querySelectorAll(imgSelector); for (const img of images) { if (skipDeferred && img.hasAttribute('data-src')) continue; const card = img.closest('[data-card]') || img.parentElement; const statusEl = card?.querySelector(`[${statusAttr}]`); img.addEventListener( 'load', () => { if (statusEl) statusEl.classList.add('hidden'); }, { once: true } ); img.addEventListener( 'error', () => { if (statusEl) { statusEl.textContent = errorText; statusEl.classList.remove('hidden'); } }, { once: true } ); // Handle already-cached images. try { if (img.complete && img.naturalWidth > 0 && statusEl) statusEl.classList.add('hidden'); } catch { /* ignore */ } } } /* ------------------------------------------------------------------ */ return { encodePathSegments, createImg, createImgWithFallback, initDeferredLoading, initStatusTracking, }; })();