foxygit / TV-Launcher Log in
commits tags

/qml/inject/tv-mode.js · 8.83 KB

raw
// TV-läge för webbappar: styr sidan med piltangenter/handkontroll.
// Injiceras både i den inbyggda motorn (QtWebEngine) och i Chromium (som
// tillägg). Launchern lägger före detta skript till
//   window.__tvModeConfig = { accent: "#rrggbb" }
//
// - Piltangenter flyttar fokus till närmaste klickbara element i den riktningen
//   (spatial navigation). Finns inget, scrollas sidan.
// - Enter klickar på element som inte reagerar på Enter själva (div med onclick ...).
// - Tydlig fokusram i temats färg; muspekaren döljs tills musen rörs.
// - Backar undan när sidan själv hanterar tangenterna (preventDefault), i
//   textfält, i helskärm och på sidor som domineras av en canvas (spel).
(() => {
    if (window.top !== window || window.__tvModeLoaded)
        return;
    window.__tvModeLoaded = true;

    const cfg = window.__tvModeConfig || {};
    const accent = cfg.accent || "#3daee9";

    const css = `
html.tv-nav *:focus, html.tv-nav .tv-focus {
    outline: ${Math.round(4 * (window.devicePixelRatio || 1))}px solid ${accent} !important;
    outline-offset: 2px !important;
}
html.tv-nav, html.tv-nav * { cursor: none !important; }
`;
    function addStyle() {
        const s = document.createElement("style");
        s.id = "tv-mode-style";
        s.textContent = css;
        (document.head || document.documentElement).appendChild(s);
    }
    if (document.documentElement) addStyle();
    else document.addEventListener("DOMContentLoaded", addStyle, { once: true });

    const FOCUSABLE = [
        "a[href]", "area[href]", "button", "input:not([type=hidden])", "select", "textarea",
        "summary", "video[controls]", "[tabindex]:not([tabindex='-1'])", "[contenteditable='true']",
        "[role=button]", "[role=link]", "[role=tab]", "[role=menuitem]", "[role=option]",
        "[role=checkbox]", "[role=switch]", "[onclick]"
    ].join(",");
    // Element som själva reagerar på Enter; övriga får ett klick av oss.
    const NATIVE_ENTER = /^(A|AREA|BUTTON|INPUT|SELECT|TEXTAREA|SUMMARY)$/;

    function isVisible(el, r) {
        if (r.width < 2 || r.height < 2) return false;
        if (el.disabled || el.closest("[inert],[aria-hidden='true']")) return false;
        const st = getComputedStyle(el);
        return st.visibility !== "hidden" && st.display !== "none" && parseFloat(st.opacity) > 0.05;
    }

    function candidates() {
        const out = [];
        for (const el of document.querySelectorAll(FOCUSABLE)) {
            const r = el.getBoundingClientRect();
            if (isVisible(el, r)) out.push({ el, r });
        }
        // Behåll bara det yttersta av nästlade klickbara element (a > div[onclick] ...).
        const set = new Set(out.map(c => c.el));
        return out.filter(c => {
            for (let p = c.el.parentElement; p; p = p.parentElement)
                if (set.has(p)) return false;
            return true;
        });
    }

    function current() {
        const a = document.activeElement;
        if (!a || a === document.body || a === document.documentElement) return null;
        const r = a.getBoundingClientRect();
        return isVisible(a, r) ? { el: a, r } : null;
    }

    // Avstånd mellan två intervall (0 om de överlappar).
    const gap = (a1, a2, b1, b2) => Math.max(0, Math.max(a1, b1) - Math.min(a2, b2));

    function best(dir, from, list) {
        const f = from.r;
        let bestC = null, bestScore = Infinity;
        for (const c of list) {
            if (c.el === from.el || c.el.contains(from.el) || from.el.contains(c.el)) continue;
            const r = c.r;
            let primary, secondary;
            const tol = 2;
            switch (dir) {
            case "down":  primary = r.top - f.bottom; if (r.top + r.height / 2 <= f.top + f.height / 2 + tol) continue;
                          secondary = gap(f.left, f.right, r.left, r.right); break;
            case "up":    primary = f.top - r.bottom; if (r.top + r.height / 2 >= f.top + f.height / 2 - tol) continue;
                          secondary = gap(f.left, f.right, r.left, r.right); break;
            case "right": primary = r.left - f.right; if (r.left + r.width / 2 <= f.left + f.width / 2 + tol) continue;
                          secondary = gap(f.top, f.bottom, r.top, r.bottom); break;
            case "left":  primary = f.left - r.right; if (r.left + r.width / 2 >= f.left + f.width / 2 - tol) continue;
                          secondary = gap(f.top, f.bottom, r.top, r.bottom); break;
            }
            // Överlappande i huvudriktningen räknas som nära; sidled straffas hårdare.
            const score = Math.max(primary, 0) + secondary * 3 + (primary < 0 ? -primary * 0.5 : 0);
            if (score < bestScore) { bestScore = score; bestC = c; }
        }
        return bestC;
    }

    function first(list) {
        // Första synliga elementet i läsordning (uppifrån, vänster till höger).
        const vh = window.innerHeight;
        const inView = list.filter(c => c.r.bottom > 0 && c.r.top < vh);
        const pool = inView.length ? inView : list;
        pool.sort((a, b) => (a.r.top - b.r.top) || (a.r.left - b.r.left));
        return pool[0] || null;
    }

    function focusEl(el) {
        if (el.tabIndex < 0 && !el.hasAttribute("tabindex"))
            el.setAttribute("tabindex", "-1");   // gör div[onclick] m.fl. fokuserbara
        el.focus({ preventScroll: true });
        const r = el.getBoundingClientRect();
        const margin = window.innerHeight * 0.15;
        if (r.top < margin || r.bottom > window.innerHeight - margin ||
            r.left < 0 || r.right > window.innerWidth)
            el.scrollIntoView({ block: "center", inline: "nearest", behavior: "smooth" });
    }

    function scrollPage(dir) {
        const dy = window.innerHeight * 0.4, dx = window.innerWidth * 0.4;
        const by = { up: [0, -dy], down: [0, dy], left: [-dx, 0], right: [dx, 0] }[dir];
        // Scrolla den största scrollbara ytan under fokus, annars hela sidan.
        let el = document.activeElement;
        while (el && el !== document.body) {
            const st = getComputedStyle(el);
            if (/(auto|scroll)/.test(st.overflowY + st.overflowX) &&
                (el.scrollHeight > el.clientHeight + 4 || el.scrollWidth > el.clientWidth + 4)) {
                el.scrollBy({ left: by[0], top: by[1], behavior: "smooth" });
                return;
            }
            el = el.parentElement;
        }
        window.scrollBy({ left: by[0], top: by[1], behavior: "smooth" });
    }

    function looksLikeGame() {
        // En canvas som täcker större delen av fönstret = spel; låt det få tangenterna.
        const area = window.innerWidth * window.innerHeight;
        for (const c of document.querySelectorAll("canvas")) {
            const r = c.getBoundingClientRect();
            if (r.width * r.height > area * 0.4) return true;
        }
        return false;
    }

    function isTextInput(el) {
        if (!el) return false;
        if (el.isContentEditable || el.tagName === "TEXTAREA") return true;
        if (el.tagName !== "INPUT") return false;
        return !/^(button|submit|reset|checkbox|radio|range|color|file|image)$/i.test(el.type);
    }

    const DIRS = { ArrowUp: "up", ArrowDown: "down", ArrowLeft: "left", ArrowRight: "right" };

    function onKey(e) {
        if (e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey) return;
        if (document.fullscreenElement || looksLikeGame()) return;
        const dir = DIRS[e.key];
        const active = document.activeElement;

        if (dir) {
            document.documentElement.classList.add("tv-nav");
            if (isTextInput(active) && (dir === "left" || dir === "right" || active.tagName === "TEXTAREA"))
                return;   // flytta textmarkören
            if (active && active.tagName === "SELECT") return;
            const list = candidates();
            const cur = current();
            const next = cur ? best(dir, cur, list) : first(list);
            // Långt utanför skärmen? Scrolla först så att man kan läsa sidan.
            if (next && cur && Math.abs((next.r.top + next.r.bottom) / 2 - (cur.r.top + cur.r.bottom) / 2) > window.innerHeight * 1.2
                && (dir === "up" || dir === "down")) {
                scrollPage(dir);
            } else if (next) {
                focusEl(next.el);
            } else {
                scrollPage(dir);
            }
            e.preventDefault();
            return;
        }

        if (e.key === "Enter" && active && active !== document.body && !NATIVE_ENTER.test(active.tagName)) {
            active.click();
            e.preventDefault();
        }
    }

    // Bubbelfasen: sidor som själva hanterar tangenterna (t.ex. youtube.com/tv)
    // hinner anropa preventDefault före oss.
    window.addEventListener("keydown", onKey);
    window.addEventListener("mousemove", () => document.documentElement.classList.remove("tv-nav"), { passive: true });
})();