jadefin/JadefinUtils.js

156 lines
3.9 KiB
JavaScript

//@ts-check
import JadefinIntegrity from "./JadefinIntegrity.js";
import JadefinModules from "./JadefinModules.js";
export default JadefinIntegrity("JadefinUtils", import.meta.url, () => window["JadefinUtils"] = new (class JadefinUtils {
events = new EventTarget();
eventTypes = {
WORKER_CREATING: "workerCreating",
WORKER_CREATED: "workerCreated",
HTML_VIDEO_PLAYER_CHANGED: "htmlVideoPlayerChanged"
};
htmlVideoPlayers = new Set();
/** @type {any} */
htmlVideoPlayer = null;
get isInMovie() {
return !!document.querySelector(".osdHeader");
}
get video() {
return /** @type {HTMLVideoElement} */ (document.querySelector(".videoPlayerContainer > video.htmlvideoplayer"));
}
get assCanvas() {
return /** @type {HTMLCanvasElement} */ (document.querySelector(".videoPlayerContainer > .libassjs-canvas-parent > canvas.libassjs-canvas"));
}
get routePath() {
return JadefinModules.Emby.Page.lastPath;
}
get routePathIsVideo() {
return this.routePath == "/video";
}
get currentPlayer() {
return JadefinModules.playbackManager._currentPlayer;
}
/**
* @param {() => any} cb
* @param {number} [tries]
* @param {number} [time]
*/
waitUntil(cb, tries, time) {
let triesLeft = tries || Number.POSITIVE_INFINITY;
return new Promise((resolve, reject) => {
const interval = setInterval(() => {
const v = cb();
if (v) {
resolve(v);
clearInterval(interval);
} else if ((--triesLeft) <= 0) {
reject(v);
clearInterval(interval);
}
}, time || 100);
});
}
/**
* @template T
* @param {T | null | undefined} value
* @returns {T}
*/
notnull(value) {
if (value === null || value === undefined) {
throw new Error("notnull encountered null");
}
return value;
}
/**
* @param {Node | null} el
* @param {Node} check
*/
hasParent(el, check) {
for (let curr = el; curr; curr = curr?.parentNode) {
if (curr == check) {
return true;
}
}
return false;
}
/**
* @param {{ [x: string]: any; }} obj
* @param {number} levels
* @param {(level: number, v: any, k: string, obj: any) => any} cond
* @param {(level: number, v: any, k: string, obj: any) => void} [cb]
*/
findDeep(obj, levels, cond, cb) {
if (levels <= 0) {
return null;
}
if (typeof(parent) == "object") {
for (const k in obj) {
let v;
try {
v = obj[k];
} catch {
continue;
}
let rv;
try {
rv = cond(levels, v, k, obj);
} catch {
continue;
}
if (cond(levels, v, k, obj)) {
cb?.(levels, v, k, obj);
if (levels > 1) {
return this.findDeep(obj, levels - 1, cond, cb);
}
return v;
}
}
}
return null;
}
/**
* @param {any[]} arr
* @param {(value: any, [index]: any, [array]: any) => any} cb
*/
filterMap(arr, cb) {
return arr.reduce((res, value, index, array) => {
const rv = cb(value, index, array);
if (rv) {
if (typeof(rv) == "object" || typeof(rv) == "function") {
res.push(rv);
} else {
res.push(value);
}
}
return res;
}, []);
}
})());