Migrate auth to AuthGuard, retiring local Postgres-backed accounts
Same pattern as GameStream (commit 6a46007), adapted for CollabTable being genuinely multi-user (not single-admin): admin user management (list/create/update/delete, role reassignment, superadmin protection) is fully proxied to AuthGuard, which already enforces the same rules CollabTable checked locally. Cookie forwarding, no local session token, AUTHGUARD_URL optional (unset = auth fully disabled), transport failures always surface as errAuthGuardUnavailable rather than ever letting a request through - proven with live tests against a closed socket. CollabTable's device-sync API token feature (separate from browser sessions) is deliberately left local-only regardless of AUTHGUARD_URL, keyed by a new currentUserID helper (AuthGuard's id when enabled, the shared placeholder id 0 when disabled) - a real, functional token either way, not faked data. Real bug found and fixed: api_tokens.user_id had a hard FK into the local auth_users table, which would reject new tokens once accounts stop being written locally. Dropped the now-invalid FK. Known, accepted gap (same as GameStream): self-service profile editing for non-admin accounts is lost, since AuthGuard only exposes an admin endpoint, no self-edit. TOTP QR issuer branding now comes from AuthGuard rather than CollabTable. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
a1c29728f0
commit
9a6ec940f7
48 files changed
+12401
-511
No files matched your search
@@ -0,0 +1,28 @@
|
||||
(() => {
|
||||
function normalizeBlocks(blocks) {
|
||||
if (Array.isArray(blocks)) return blocks;
|
||||
if (blocks == null) return [];
|
||||
return [blocks];
|
||||
}
|
||||
|
||||
function renderLayout(config = {}) {
|
||||
const previewHtml = String(config.previewHtml || '');
|
||||
const contentBlocks = normalizeBlocks(config.contentBlocks)
|
||||
.map(block => String(block || '').trim())
|
||||
.filter(Boolean)
|
||||
.join('');
|
||||
const rootClass = String(config.rootClass || 'flex flex-col gap-3 md:flex-row md:gap-3').trim();
|
||||
const contentClass = String(config.contentClass || 'flex-1 min-w-0 space-y-5').trim();
|
||||
|
||||
return `<div class="${rootClass}">
|
||||
${previewHtml}
|
||||
<div class="${contentClass}">
|
||||
${contentBlocks}
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
window.NCMediaDetailView = {
|
||||
renderLayout,
|
||||
};
|
||||
})();
|
||||
@@ -0,0 +1,481 @@
|
||||
// NCMediaPreview - shared fullscreen image / video preview component.
|
||||
// Served at /shared/js/media/media-preview.js by applySharedBase.
|
||||
//
|
||||
// Two modes:
|
||||
// attach(opts) -> attach to existing overlay + frame elements in the DOM.
|
||||
// Returns a controller with { open, close, prev, next,
|
||||
// setItems, isOpen, currentIndex, preloader, destroy }.
|
||||
//
|
||||
// lightbox(opts) -> dynamically create a minimal single-image lightbox.
|
||||
// Returns { open(url, alt), close, destroy }.
|
||||
//
|
||||
// attach() opts:
|
||||
// overlayEl {Element} required - fixed fullscreen overlay div
|
||||
// frameEl {Element} required - inner div where img/video is mounted
|
||||
// preloadRadius {number} default 2 - neighbors to eagerly preload
|
||||
// loop {boolean} default false - wrap-around navigation
|
||||
// renderItem {function(frameEl, item)} - custom render; used instead of
|
||||
// default img/video creation when provided
|
||||
// onClose {function()}
|
||||
// onNavigate {function(idx, item)}
|
||||
//
|
||||
// Items shape for setItems(): [{ url, thumbnail?, name?, mediaType? }]
|
||||
// mediaType 'video' forces video element; otherwise URL extension is used.
|
||||
//
|
||||
// lightbox() opts:
|
||||
// id {string} default 'ncLightboxOverlay'
|
||||
// zIndex {string} default 'z-50'
|
||||
// imgClass {string} default: centered object-contain image style
|
||||
|
||||
(function (global) {
|
||||
'use strict';
|
||||
|
||||
var VIDEO_EXT = /\.(mp4|webm|mov|avi|mkv)$/i;
|
||||
var AUDIO_EXT = /\.(mp3|flac|wav|ogg|aac|m4a|opus|wma|aiff)$/i;
|
||||
|
||||
/** Returns true when the URL path has a recognised video extension. */
|
||||
function isVideo(url) {
|
||||
return VIDEO_EXT.test(String(url || '').split('?')[0]);
|
||||
}
|
||||
|
||||
/** Returns true when the URL path has a recognised audio extension. */
|
||||
function isAudio(url) {
|
||||
return AUDIO_EXT.test(String(url || '').split('?')[0]);
|
||||
}
|
||||
|
||||
/** Build a simple image-preload cache. */
|
||||
function makePreloader() {
|
||||
var cache = new Map();
|
||||
return {
|
||||
load: function (url) {
|
||||
if (!url) return Promise.reject(new Error('no url'));
|
||||
if (cache.has(url)) return cache.get(url);
|
||||
var p = new Promise(function (res, rej) {
|
||||
var im = new Image();
|
||||
im.onload = function () {
|
||||
res(im);
|
||||
};
|
||||
im.onerror = rej;
|
||||
im.src = url;
|
||||
});
|
||||
cache.set(url, p);
|
||||
return p;
|
||||
},
|
||||
clear: function () {
|
||||
cache.clear();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Shared CSS for the media element inside the frame. */
|
||||
var MEDIA_CLS =
|
||||
'max-h-full max-w-full rounded-md bg-black object-contain shadow-[var(--shadow-2xl,0_10px_40px_rgba(0,0,0,.6))]';
|
||||
|
||||
/**
|
||||
* Keep fullscreen media inside comfortable insets so content is not clipped
|
||||
* by overlay edges or covered by overlay chrome.
|
||||
*/
|
||||
function applySafeMediaLayout(node) {
|
||||
if (!node) return;
|
||||
try {
|
||||
node.style.width = 'auto';
|
||||
node.style.height = 'auto';
|
||||
node.style.maxWidth = 'calc(100% - 1.5rem)';
|
||||
node.style.maxHeight = 'calc(100% - 1.5rem)';
|
||||
node.style.objectFit = 'contain';
|
||||
node.style.objectPosition = 'center';
|
||||
// eslint-disable-next-line no-empty
|
||||
} catch {}
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggle overlay visibility using both class-based and attribute-based
|
||||
* strategies so it works with all existing overlay markup in the codebase.
|
||||
*/
|
||||
function setVisible(overlayEl, visible) {
|
||||
if (!overlayEl) return;
|
||||
if (visible) {
|
||||
overlayEl.classList.remove('hidden');
|
||||
overlayEl.classList.add('flex', 'is-active');
|
||||
overlayEl.style.removeProperty('display');
|
||||
overlayEl.hidden = false;
|
||||
overlayEl.setAttribute('aria-hidden', 'false');
|
||||
try {
|
||||
document.body.classList.add('overflow-hidden');
|
||||
document.documentElement.classList.add('overflow-hidden');
|
||||
// eslint-disable-next-line no-empty
|
||||
} catch {}
|
||||
} else {
|
||||
overlayEl.classList.remove('flex', 'is-active');
|
||||
overlayEl.classList.add('hidden');
|
||||
overlayEl.style.setProperty('display', 'none', 'important');
|
||||
overlayEl.hidden = true;
|
||||
overlayEl.setAttribute('aria-hidden', 'true');
|
||||
try {
|
||||
document.body.classList.remove('overflow-hidden');
|
||||
document.documentElement.classList.remove('overflow-hidden');
|
||||
// eslint-disable-next-line no-empty
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
// -- attach() ----------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Attach a media preview controller to existing overlay + frame DOM elements.
|
||||
*
|
||||
* The component automatically wires:
|
||||
* • [data-overlay-prev] -> prev()
|
||||
* • [data-overlay-next] -> next()
|
||||
* • [aria-label="Close"] -> close() (searched inside overlayEl)
|
||||
* • Backdrop click (click directly on overlayEl) -> close()
|
||||
* • Keyboard: Escape -> close, ArrowLeft -> prev, ArrowRight -> next
|
||||
*
|
||||
* @param {object} opts
|
||||
* @returns controller
|
||||
*/
|
||||
function attach(opts) {
|
||||
opts = opts || {};
|
||||
var overlayEl = opts.overlayEl;
|
||||
var frameEl = opts.frameEl;
|
||||
if (!overlayEl || !frameEl) {
|
||||
throw new Error('NCMediaPreview.attach: overlayEl and frameEl are required');
|
||||
}
|
||||
|
||||
var radius = Math.max(0, Number(opts.preloadRadius) || 2);
|
||||
var loop = !!opts.loop;
|
||||
var items = []; // [{ url, thumbnail, name, mediaType }]
|
||||
var _idx = -1;
|
||||
var _open = false;
|
||||
var preloader = makePreloader();
|
||||
|
||||
// Auto-discover standard buttons within the overlay
|
||||
var closeBtn = overlayEl.querySelector('[aria-label="Close"]');
|
||||
var prevBtn = overlayEl.querySelector('[data-overlay-prev]');
|
||||
var nextBtn = overlayEl.querySelector('[data-overlay-next]');
|
||||
|
||||
var hasInFrameClose = !!(closeBtn && frameEl.contains(closeBtn));
|
||||
|
||||
// Reserve safe space inside the frame so media is never hidden under
|
||||
// in-frame close controls and never touches overlay boundaries.
|
||||
try {
|
||||
frameEl.style.boxSizing = 'border-box';
|
||||
frameEl.style.padding = hasInFrameClose ? '3.25rem 0.75rem 0.75rem 0.75rem' : '0.75rem';
|
||||
// eslint-disable-next-line no-empty
|
||||
} catch {}
|
||||
|
||||
function applyFramePaddingForItem(item) {
|
||||
try {
|
||||
if (!hasInFrameClose) {
|
||||
frameEl.style.padding = '0.75rem';
|
||||
return;
|
||||
}
|
||||
|
||||
var kind = String((item && item.mediaType) || '').toLowerCase();
|
||||
var url = String((item && item.url) || '');
|
||||
var isImageLike = kind !== 'video' && kind !== 'audio' && !isVideo(url) && !isAudio(url);
|
||||
|
||||
// For image previews, keep vertical insets symmetric.
|
||||
frameEl.style.padding = isImageLike
|
||||
? '3.25rem 0.75rem 3.25rem 0.75rem'
|
||||
: '3.25rem 0.75rem 0.75rem 0.75rem';
|
||||
// eslint-disable-next-line no-empty
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// Ensure overlays always start hidden after attach in case responsive
|
||||
// display utilities override class-based hidden rules on first paint.
|
||||
setVisible(overlayEl, false);
|
||||
|
||||
function updateButtons() {
|
||||
if (prevBtn) prevBtn.disabled = loop ? false : _idx <= 0;
|
||||
if (nextBtn) nextBtn.disabled = loop ? false : _idx >= items.length - 1;
|
||||
}
|
||||
|
||||
/** Pause + remove any img/video/audio children from the frame. */
|
||||
function clearFrame() {
|
||||
Array.from(frameEl.querySelectorAll('video,audio')).forEach(function (v) {
|
||||
try {
|
||||
v.pause();
|
||||
// eslint-disable-next-line no-empty
|
||||
} catch {}
|
||||
});
|
||||
Array.from(frameEl.querySelectorAll('img,video,audio')).forEach(function (n) {
|
||||
if (n.parentNode === frameEl) frameEl.removeChild(n);
|
||||
});
|
||||
}
|
||||
|
||||
/** Mount the media element for the given item. */
|
||||
function renderFrame(item) {
|
||||
clearFrame();
|
||||
if (!item) return;
|
||||
applyFramePaddingForItem(item);
|
||||
|
||||
// Delegate to caller-supplied renderer if provided
|
||||
if (opts.renderItem) {
|
||||
try {
|
||||
opts.renderItem(frameEl, item);
|
||||
// eslint-disable-next-line no-empty
|
||||
} catch {}
|
||||
return;
|
||||
}
|
||||
|
||||
if (isVideo(item.url) || item.mediaType === 'video') {
|
||||
var v = document.createElement('video');
|
||||
v.className = MEDIA_CLS;
|
||||
v.src = item.url;
|
||||
v.controls = true;
|
||||
v.autoplay = true;
|
||||
v.loop = true;
|
||||
v.muted = false;
|
||||
v.playsInline = true;
|
||||
applySafeMediaLayout(v);
|
||||
frameEl.appendChild(v);
|
||||
} else if (isAudio(item.url) || item.mediaType === 'audio') {
|
||||
var a = document.createElement('audio');
|
||||
a.src = item.url;
|
||||
a.controls = true;
|
||||
a.autoplay = true;
|
||||
a.style.minWidth = '320px';
|
||||
a.style.maxWidth = '90vw';
|
||||
frameEl.appendChild(a);
|
||||
} else {
|
||||
var img = document.createElement('img');
|
||||
img.className = MEDIA_CLS;
|
||||
img.alt = item.name || 'Media preview';
|
||||
applySafeMediaLayout(img);
|
||||
frameEl.appendChild(img);
|
||||
// Show thumbnail immediately, swap to full-res when ready
|
||||
if (item.thumbnail) img.src = item.thumbnail;
|
||||
var capturedIdx = _idx;
|
||||
preloader
|
||||
.load(item.url)
|
||||
.then(function () {
|
||||
img.src = item.url;
|
||||
})
|
||||
.catch(function () {
|
||||
img.src = item.url;
|
||||
})
|
||||
.finally(function () {
|
||||
// Preload neighbors after current is resolved
|
||||
for (var d = 1; d <= radius; d++) {
|
||||
var li = capturedIdx - d,
|
||||
ri = capturedIdx + d;
|
||||
if (li >= 0 && items[li]) preloader.load(items[li].url).catch(function () {});
|
||||
if (ri < items.length && items[ri])
|
||||
preloader.load(items[ri].url).catch(function () {});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function open(i) {
|
||||
if (!items.length) return;
|
||||
_idx = Math.max(0, Math.min(i, items.length - 1));
|
||||
_open = true;
|
||||
renderFrame(items[_idx]);
|
||||
setVisible(overlayEl, true);
|
||||
updateButtons();
|
||||
if (opts.onNavigate)
|
||||
try {
|
||||
opts.onNavigate(_idx, items[_idx]);
|
||||
// eslint-disable-next-line no-empty
|
||||
} catch {}
|
||||
}
|
||||
|
||||
function close() {
|
||||
_open = false;
|
||||
clearFrame();
|
||||
_idx = -1;
|
||||
setVisible(overlayEl, false);
|
||||
if (opts.onClose)
|
||||
try {
|
||||
opts.onClose();
|
||||
// eslint-disable-next-line no-empty
|
||||
} catch {}
|
||||
}
|
||||
|
||||
function prev() {
|
||||
if (!_open || !items.length) return;
|
||||
var n = loop ? (_idx - 1 + items.length) % items.length : _idx - 1;
|
||||
if (!loop && n < 0) return;
|
||||
_idx = n;
|
||||
renderFrame(items[_idx]);
|
||||
updateButtons();
|
||||
if (opts.onNavigate)
|
||||
try {
|
||||
opts.onNavigate(_idx, items[_idx]);
|
||||
// eslint-disable-next-line no-empty
|
||||
} catch {}
|
||||
}
|
||||
|
||||
function next() {
|
||||
if (!_open || !items.length) return;
|
||||
var n = loop ? (_idx + 1) % items.length : _idx + 1;
|
||||
if (!loop && n >= items.length) return;
|
||||
_idx = n;
|
||||
renderFrame(items[_idx]);
|
||||
updateButtons();
|
||||
if (opts.onNavigate)
|
||||
try {
|
||||
opts.onNavigate(_idx, items[_idx]);
|
||||
// eslint-disable-next-line no-empty
|
||||
} catch {}
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace the item list. Clears the preload cache.
|
||||
* Must be called with the full up-to-date list before open().
|
||||
*/
|
||||
function setItems(newItems) {
|
||||
items = Array.isArray(newItems) ? newItems : [];
|
||||
preloader.clear();
|
||||
}
|
||||
|
||||
// Wire built-in buttons
|
||||
if (closeBtn) closeBtn.addEventListener('click', close);
|
||||
if (prevBtn) prevBtn.addEventListener('click', prev);
|
||||
if (nextBtn) nextBtn.addEventListener('click', next);
|
||||
|
||||
// Backdrop click - close when clicking directly on the overlay backdrop
|
||||
overlayEl.addEventListener('click', function (e) {
|
||||
if (e.target === overlayEl) close();
|
||||
});
|
||||
|
||||
// Keyboard - Escape / arrows
|
||||
function onKey(e) {
|
||||
if (!_open) return;
|
||||
if (e.key === 'Escape') close();
|
||||
else if (e.key === 'ArrowLeft') prev();
|
||||
else if (e.key === 'ArrowRight') next();
|
||||
}
|
||||
window.addEventListener('keydown', onKey);
|
||||
|
||||
var ctrl = {
|
||||
open: open,
|
||||
close: close,
|
||||
prev: prev,
|
||||
next: next,
|
||||
setItems: setItems,
|
||||
isOpen: function () {
|
||||
return _open;
|
||||
},
|
||||
preloader: preloader,
|
||||
destroy: function () {
|
||||
window.removeEventListener('keydown', onKey);
|
||||
},
|
||||
};
|
||||
Object.defineProperty(ctrl, 'currentIndex', {
|
||||
get: function () {
|
||||
return _idx;
|
||||
},
|
||||
});
|
||||
return ctrl;
|
||||
}
|
||||
|
||||
// -- lightbox() --------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Build a minimal single-item image lightbox that creates its own DOM.
|
||||
* Useful for cases where no overlay markup exists (e.g. MediaModerator).
|
||||
*
|
||||
* @param {object} [opts] { id, zIndex, imgClass }
|
||||
* @returns {{ open(url, alt?), close, destroy }}
|
||||
*/
|
||||
function lightbox(opts) {
|
||||
opts = opts || {};
|
||||
var id = opts.id || 'ncLightboxOverlay';
|
||||
var zIndex = opts.zIndex || 'z-50';
|
||||
var imgCls =
|
||||
opts.imgClass ||
|
||||
'block max-h-full max-w-full rounded-lg object-contain shadow-[0_8px_24px_rgba(0,0,0,0.5)]';
|
||||
|
||||
var el = null,
|
||||
img = null;
|
||||
|
||||
function ensure() {
|
||||
if (el) return;
|
||||
el = document.createElement('div');
|
||||
el.id = id;
|
||||
el.setAttribute('role', 'dialog');
|
||||
el.setAttribute('aria-modal', 'true');
|
||||
el.className = [
|
||||
'fixed inset-0',
|
||||
zIndex,
|
||||
'hidden items-center justify-center bg-black/85 p-4',
|
||||
].join(' ');
|
||||
|
||||
var inner = document.createElement('div');
|
||||
inner.className = 'relative flex h-full w-full items-center justify-center';
|
||||
|
||||
var closeBtn = document.createElement('button');
|
||||
closeBtn.type = 'button';
|
||||
closeBtn.setAttribute('aria-label', 'Close');
|
||||
closeBtn.className =
|
||||
'absolute right-4 top-4 z-10 flex h-9 w-9 cursor-pointer items-center justify-center rounded-full border border-slate-700 bg-black text-white';
|
||||
closeBtn.innerHTML =
|
||||
'<svg class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>';
|
||||
closeBtn.addEventListener('click', close);
|
||||
|
||||
img = document.createElement('img');
|
||||
img.alt = 'Preview';
|
||||
img.className = imgCls;
|
||||
|
||||
inner.appendChild(closeBtn);
|
||||
inner.appendChild(img);
|
||||
el.appendChild(inner);
|
||||
document.body.appendChild(el);
|
||||
|
||||
el.addEventListener('click', function (e) {
|
||||
if (e.target === el) close();
|
||||
});
|
||||
document.addEventListener('keydown', function (e) {
|
||||
if (e.key === 'Escape' && !el.classList.contains('hidden')) close();
|
||||
});
|
||||
}
|
||||
|
||||
function open(url, alt) {
|
||||
ensure();
|
||||
img.src = url || '';
|
||||
if (alt) img.alt = alt;
|
||||
applySafeMediaLayout(img);
|
||||
try {
|
||||
// Use equal viewport insets so image top and bottom spacing match.
|
||||
img.style.maxWidth = 'calc(100vw - 4rem)';
|
||||
img.style.maxHeight = 'calc(100vh - 4rem)';
|
||||
img.style.margin = '0 auto';
|
||||
// eslint-disable-next-line no-empty
|
||||
} catch {}
|
||||
el.classList.remove('hidden');
|
||||
el.classList.add('flex');
|
||||
try {
|
||||
document.body.classList.add('overflow-hidden');
|
||||
// eslint-disable-next-line no-empty
|
||||
} catch {}
|
||||
}
|
||||
|
||||
function close() {
|
||||
if (!el) return;
|
||||
el.classList.add('hidden');
|
||||
el.classList.remove('flex');
|
||||
img.src = '';
|
||||
try {
|
||||
document.body.classList.remove('overflow-hidden');
|
||||
// eslint-disable-next-line no-empty
|
||||
} catch {}
|
||||
}
|
||||
|
||||
function destroy() {
|
||||
close();
|
||||
if (el) {
|
||||
el.remove();
|
||||
el = null;
|
||||
img = null;
|
||||
}
|
||||
}
|
||||
|
||||
return { open: open, close: close, destroy: destroy };
|
||||
}
|
||||
|
||||
global.NCMediaPreview = { attach: attach, lightbox: lightbox, isVideo: isVideo };
|
||||
})(window);
|
||||
@@ -0,0 +1,287 @@
|
||||
/**
|
||||
* 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 `<img>` 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 `<img>` 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 <span>
|
||||
* @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 `<img>` 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,
|
||||
};
|
||||
})();
|
||||
Reference in new issue
Block a user