184 lines
5.8 KiB
JavaScript
184 lines
5.8 KiB
JavaScript
/*
|
|
util.js — small shared helpers (no dependencies).
|
|
|
|
h(tag, attrs, ...children) builds DOM without innerHTML:
|
|
h('a.card.card--wide', { href: '/x', onclick: fn, dataset: { id: 1 } }, 'text', node)
|
|
- tag may carry .class and #id suffixes
|
|
- attrs: class (string|array), style (string|object, supports --custom-props),
|
|
dataset, on<event> functions, booleans (true → present, false/null → omitted),
|
|
anything else → setAttribute. `attrs` may be omitted.
|
|
- children: strings (text nodes — never parsed as HTML), nodes, arrays, null/false (skipped)
|
|
*/
|
|
|
|
export function escapeHtml(value) {
|
|
return String(value == null ? '' : value)
|
|
.replace(/&/g, '&')
|
|
.replace(/</g, '<')
|
|
.replace(/>/g, '>')
|
|
.replace(/"/g, '"')
|
|
.replace(/'/g, ''');
|
|
}
|
|
|
|
const SVG_NS = 'http://www.w3.org/2000/svg';
|
|
const SVG_TAGS = new Set(['svg', 'path', 'circle', 'rect', 'line', 'polyline', 'polygon', 'g']);
|
|
|
|
export function h(tag, attrs, ...children) {
|
|
let name = 'div';
|
|
const classes = [];
|
|
let id = '';
|
|
const m = String(tag).match(/^([a-z0-9-]*)((?:[.#][\w-]+)*)$/i);
|
|
if (m) {
|
|
name = m[1] || 'div';
|
|
(m[2].match(/[.#][\w-]+/g) || []).forEach((p) => {
|
|
if (p[0] === '.') classes.push(p.slice(1));
|
|
else id = p.slice(1);
|
|
});
|
|
} else {
|
|
name = tag;
|
|
}
|
|
const isSvg = SVG_TAGS.has(name);
|
|
const el = isSvg ? document.createElementNS(SVG_NS, name) : document.createElement(name);
|
|
if (classes.length) el.setAttribute('class', classes.join(' '));
|
|
if (id) el.id = id;
|
|
if (attrs != null && (typeof attrs !== 'object' || attrs instanceof Node || Array.isArray(attrs))) {
|
|
children.unshift(attrs);
|
|
attrs = null;
|
|
}
|
|
if (attrs) {
|
|
for (const [k, v] of Object.entries(attrs)) {
|
|
if (v == null || v === false) continue;
|
|
if (k === 'class' || k === 'className') {
|
|
const extra = Array.isArray(v) ? v.filter(Boolean).join(' ') : String(v);
|
|
if (extra) el.setAttribute('class', [el.getAttribute('class'), extra].filter(Boolean).join(' '));
|
|
} else if (k === 'style') {
|
|
if (typeof v === 'string') el.setAttribute('style', v);
|
|
else {
|
|
for (const [sk, sv] of Object.entries(v)) {
|
|
if (sv == null) continue;
|
|
if (sk.startsWith('--')) el.style.setProperty(sk, sv);
|
|
else el.style[sk] = sv;
|
|
}
|
|
}
|
|
} else if (k === 'dataset') {
|
|
for (const [dk, dv] of Object.entries(v)) if (dv != null) el.dataset[dk] = dv;
|
|
} else if (k.startsWith('on') && typeof v === 'function') {
|
|
el.addEventListener(k.slice(2).toLowerCase(), v);
|
|
} else if (k === 'text') {
|
|
el.textContent = v;
|
|
} else if (!isSvg && (k === 'value' || k === 'checked' || k === 'selected')) {
|
|
el[k] = v;
|
|
} else if (v === true) {
|
|
el.setAttribute(k, '');
|
|
} else {
|
|
el.setAttribute(k, String(v));
|
|
}
|
|
}
|
|
}
|
|
appendChildren(el, children);
|
|
return el;
|
|
}
|
|
|
|
function appendChildren(el, children) {
|
|
for (const c of children) {
|
|
if (c == null || c === false || c === true) continue;
|
|
if (Array.isArray(c)) appendChildren(el, c);
|
|
else if (c instanceof Node) el.appendChild(c);
|
|
else el.appendChild(document.createTextNode(String(c)));
|
|
}
|
|
}
|
|
|
|
export function clear(el) {
|
|
if (el) el.replaceChildren();
|
|
return el;
|
|
}
|
|
|
|
// Reads a query param from the real query string or from a hash route (#/search?q=x).
|
|
export function getParam(name) {
|
|
const q = new URLSearchParams(location.search).get(name);
|
|
if (q != null) return q;
|
|
const hash = location.hash || '';
|
|
const i = hash.indexOf('?');
|
|
return i >= 0 ? new URLSearchParams(hash.slice(i + 1)).get(name) : null;
|
|
}
|
|
|
|
// 95 -> "1:35", 3675 -> "1:01:15"
|
|
export function formatSeconds(sec) {
|
|
sec = Math.max(0, Math.floor(sec || 0));
|
|
const hh = Math.floor(sec / 3600);
|
|
const m = Math.floor((sec % 3600) / 60);
|
|
const s = sec % 60;
|
|
const mm = hh ? String(m).padStart(2, '0') : String(m);
|
|
const ss = String(s).padStart(2, '0');
|
|
return hh ? `${hh}:${mm}:${ss}` : `${mm}:${ss}`;
|
|
}
|
|
|
|
// 141 -> "2h 21m"
|
|
export function runtimeLabel(mins) {
|
|
if (!mins || mins <= 0) return '';
|
|
const hh = Math.floor(mins / 60);
|
|
const m = Math.round(mins % 60);
|
|
return hh ? (m ? `${hh}h ${m}m` : `${hh}h`) : `${m}m`;
|
|
}
|
|
|
|
// seconds → "23m" / "1h 4m"
|
|
export function durationLabel(sec) {
|
|
return runtimeLabel(Math.max(1, Math.round((sec || 0) / 60)));
|
|
}
|
|
|
|
export function yearOf(date) {
|
|
return date ? String(date).slice(0, 4) : '';
|
|
}
|
|
|
|
export function debounce(fn, wait) {
|
|
let timer = null;
|
|
const d = function (...args) {
|
|
clearTimeout(timer);
|
|
timer = setTimeout(() => fn.apply(this, args), wait);
|
|
};
|
|
d.cancel = () => clearTimeout(timer);
|
|
return d;
|
|
}
|
|
|
|
// resize a full TMDB image URL (…/t/p/<size>/path) to another size
|
|
export function tmdbResize(url, size) {
|
|
if (!url) return '';
|
|
return String(url).replace(/\/t\/p\/[A-Za-z0-9._-]+/, `/t/p/${size}`);
|
|
}
|
|
|
|
export function clamp(n, lo, hi) {
|
|
return Math.min(hi, Math.max(lo, n));
|
|
}
|
|
|
|
export function plural(n, word, pluralWord) {
|
|
return `${n} ${n === 1 ? word : pluralWord || `${word}s`}`;
|
|
}
|
|
|
|
// Kept from v4 for the player workstream.
|
|
export function webPlayable(stream) {
|
|
const s = stream || {};
|
|
const url = String(s.url || '');
|
|
if (!/^https?:\/\//i.test(url)) return false;
|
|
const type = String(s.type || '').toLowerCase();
|
|
if (['magnet', 'torrent', 'dash', 'mkv', 'avi'].includes(type)) return false;
|
|
const isHls = type === 'm3u8' || /\.m3u8($|\?)/i.test(url);
|
|
const isDirect = type === 'mp4' || type === 'webm' || /\.(mp4|m4v|webm)(\?|#|$)/i.test(url);
|
|
return isHls || isDirect;
|
|
}
|
|
|
|
export function reducedMotion() {
|
|
try {
|
|
return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
|
} catch (e) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// Swallow errors from storage access in private mode etc.
|
|
export function safe(fn, fallback) {
|
|
try {
|
|
return fn();
|
|
} catch (e) {
|
|
return fallback;
|
|
}
|
|
}
|