Luigit
repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by admin

quickshell/nuguland/live-panels.test.mjs

Raw
import assert from "node:assert/strict";
import vm from "node:vm";
import { test } from "node:test";
import { readSource } from "./test-fixtures/sources.js";

// Root and feature-local production sources alike, by basename.
const read = name => readSource(name);
const util = vm.createContext({});
vm.runInContext(read("Util.js").replace(/^\.pragma library\s*/, ""), util);

// Execute production QML JavaScript with synthetic services. This checks command
// routing and reconciliation, not Qt bindings, delegate lifetime or real input.
function panel(name, service, extra = {}) {
    const source = read(`${name}Panel.qml`);
    const serviceName = `${name.toLowerCase()}Service`;
    const context = vm.createContext({ [serviceName]: service, Util: util, ...extra });
    context.root = context;
    const expression = source.slice(source.indexOf("readonly property var panelState:") + "readonly property var panelState:".length,
        source.indexOf("\n    readonly property", source.indexOf("readonly property var panelState:") + 1));
    Object.defineProperty(context, "panelState", { get: () => vm.runInContext(`(${expression})`, context) });
    const start = source.indexOf("    function ");
    const end = source.indexOf("\n    width:", start);
    vm.runInContext(source.slice(start, end), context);
    return context;
}

// Typed panel properties, `readonly property <type> <name>: <expression>` on one
// line, evaluated live against the synthetic service like Qt bindings.
function bind(context, name, ...properties) {
    const source = read(`${name}Panel.qml`);
    for (const property of properties) {
        const expression = source.match(new RegExp(`^    readonly property \\w+ ${property}: (.+)$`, "m"))[1];
        Object.defineProperty(context, property, { get: () => vm.runInContext(`(${expression})`, context) });
    }
    return context;
}

function serviceFixture(initial) {
    const fixture = { current: initial, calls: [], stateJson() { return JSON.stringify(this.current); } };
    for (const name of ["setVolume", "toggleMute", "setDefaultSink", "setDefaultSource", "action", "seek", "select", "sessionAction", "confirmAction", "cancelAction", "primaryActivate", "displayMenu", "secondaryActivate"])
        fixture[name] = (...args) => {
            fixture.calls.push([name, ...args]);
            return '{"staleCommandReturn":true}';
        };
    return fixture;
}

function stableModel() {
    const rows = [];
    const operations = [];
    const context = vm.createContext({
        get count() { return rows.length; },
        get: index => rows[index],
        insert: (index, row) => { rows.splice(index, 0, { ...row }); operations.push("insert"); },
        set: (index, row) => { Object.assign(rows[index], row); operations.push("set"); },
        move: (from, to, count) => { rows.splice(to, 0, ...rows.splice(from, count)); operations.push("move"); },
        remove: (index, count) => { rows.splice(index, count); operations.push("remove"); },
    });
    const source = read("StableListModel.qml");
    vm.runInContext(source.slice(source.indexOf("    function sync("), source.lastIndexOf("\n}")), context);
    return { rows, operations, sync: context.sync };
}

test("stable reconciliation updates and reorders surviving rows without removal", () => {
    const model = stableModel();
    model.sync([{ id: "a", level: 0.2 }, { id: "b", level: 0.8 }]);
    const [a, b] = model.rows;
    model.operations.length = 0;
    model.sync([{ id: "a", level: 0.2 }, { id: "b", level: 0.8 }]);
    assert.deepEqual(model.operations, [], "unchanged snapshots do not emit model mutations");
    model.sync([{ id: "b", level: 0.9 }, { id: "c", level: 0.5 }, { id: "a", level: 0.3 }]);
    assert.equal(model.rows[0], b);
    assert.equal(model.rows[2], a);
    assert.equal(a.rowData.level, 0.3);
    assert.equal(b.rowData.level, 0.9);
    assert(!model.operations.includes("remove"));
    model.sync([{ id: "a", level: 0.4 }]);
    assert.equal(model.rows[0], a);
    assert.equal(model.rows.length, 1);
    model.sync([]);
    assert.equal(model.rows.length, 0);
});

test("every volume step reconciles into the same row during a simulated drag", () => {
    const model = stableModel();
    const service = serviceFixture({});
    service.sinks = [{ id: "speaker", percent: 0 }];
    const audio = bind(panel("Audio", service), "Audio", "sinks");
    model.sync(audio.sinks);
    const row = model.rows[0];
    for (let step = 0; step <= 20; step++) {
        audio.setVolume("speaker", step * 0.075);
        service.sinks = [{ id: "speaker", percent: Math.round(step * 7.5) }];
        model.sync(audio.sinks);
        assert.equal(model.rows[0], row);
    }
    assert.equal(service.calls.length, 21);
    assert.equal(row.rowData.percent, 150);
    assert.equal(model.operations.filter(op => op === "insert").length, 1);
    assert(!model.operations.includes("remove"));
});

// The panel's writes are quiet: it already shows the value, so no volume overlay.
test("audio commands ignore returned snapshots, bound volume and stay quiet", () => {
    const service = serviceFixture({});
    service.sinks = [{ id: "initial" }];
    service.pipewireReady = true;
    const audio = bind(panel("Audio", service), "Audio", "sinks", "serviceReady");
    audio.setVolume("sink", -1);
    audio.setVolume("sink", 2);
    audio.toggleMute("sink");
    audio.selectSink("sink");
    audio.selectSource("mic");
    assert.deepEqual(service.calls, [["setVolume", "sink", 0, true], ["setVolume", "sink", 1.5, true], ["toggleMute", "sink", true], ["setDefaultSink", "sink"], ["setDefaultSource", "mic"]]);
    assert.equal(audio.sinks[0].id, "initial", "returned snapshots never replace the bound rows");
    service.sinks = [{ id: "external" }];
    service.pipewireReady = false;
    assert.equal(audio.sinks[0].id, "external");
    assert.equal(audio.serviceReady, false);
});

test("media capability matrix gates every transport and seek command", () => {
    const service = serviceFixture({ activePlayer: { title: "first" } });
    const media = panel("Media", service, {
        nativePlayer: { canControl: true, canGoPrevious: false, canGoNext: false, canTogglePlaying: false },
        player: { length: 200, canSeek: false, canShuffle: false, canRepeat: false, playbackState: "playing" },
    });
    for (const name of ["canControl", "canSeek"]) {
        const binding = read("MediaPanel.qml").match(new RegExp(`readonly property bool ${name}: (.+)`))[1];
        Object.defineProperty(media, name, { get: () => vm.runInContext(binding, media) });
    }
    const capabilities = { shuffle: "canShuffle", repeat: "canRepeat", previous: "canGoPrevious", next: "canGoNext", playPause: "canTogglePlaying" };
    for (const [action, flag] of Object.entries(capabilities)) {
        const owner = ["shuffle", "repeat"].includes(action) ? media.player : media.nativePlayer;
        assert.equal(media.actionEnabled(action), false);
        media.runAction(action);
        assert.equal(service.calls.length, 0);
        owner[flag] = true;
        assert.equal(media.actionEnabled(action), true);
        media.runAction(action);
        // The panel's changes are quiet: the open panel already shows them, so no OSD.
        assert.deepEqual(service.calls.splice(0), [["action", action, true]]);
        media.nativePlayer.canControl = false;
        media.runAction(action);
        assert.equal(service.calls.length, 0);
        media.nativePlayer.canControl = true;
        owner[flag] = false;
    }
    // Previous and next come as a pair: at the end of a list next is shown, off.
    media.nativePlayer.canGoPrevious = true;
    assert.deepEqual(["previous", "next"].map(kind => [media.actionShown(kind), media.actionEnabled(kind)]), [[true, true], [true, false]]);
    assert.equal(media.disabledReason("next"), "no next track");
    media.nativePlayer.canGoPrevious = false;
    assert.equal(["shuffle", "previous", "playPause", "next", "repeat"].filter(kind => media.actionShown(kind)).join(), "playPause", "a player without capabilities shows play alone");
    media.nativePlayer.canControl = false;
    assert.equal(["shuffle", "previous", "playPause", "next", "repeat"].some(kind => media.actionShown(kind)), false, "an uncontrollable player shows no transport");
    media.nativePlayer.canControl = true;
    media.seekByRatio(0.5);
    assert.equal(service.calls.length, 0);
    media.player.canSeek = true;
    media.nativePlayer.canControl = false;
    media.seekByRatio(0.5);
    media.nativePlayer.canControl = true;
    media.player.length = 0;
    media.seekByRatio(0.5);
    assert.equal(service.calls.length, 0, "seek requires control capability and a positive duration");
    media.player.length = 200;
    media.seekByRatio(-1);
    media.seekByRatio(2);
    media.selectPlayer("other");
    assert.deepEqual(service.calls, [["seek", 0, true], ["seek", 200, true], ["select", "other", true]]);
    assert.equal(media.actionLabel("playPause"), "pause");
    media.player.playbackState = "paused";
    assert.equal(media.actionLabel("playPause"), "play");
    service.activePlayer = { title: "external" };
    bind(media, "Media", "player");
    assert.equal(media.player.title, "external");
    media.nativePlayer = null;
    assert.equal(media.actionEnabled("playPause"), false);
});

test("power dispatch does not take ownership of confirmation state", () => {
    const service = serviceFixture({});
    service.pendingConfirmation = "";
    service.batteryPercent = 72;
    const focused = [];
    const power = panel("Power", service, {
        safeActions: ["lock", "suspend", "monitor-off"],
        destructiveActions: ["logout", "reboot", "poweroff"],
        Qt: { TabFocusReason: "tab" },
        actionRepeater: { itemAt: index => index < 0 ? null : { forceActiveFocus: reason => focused.push([index, reason]) } },
    });
    // The panel reads the service's typed properties through its bindings.
    for (const [type, name] of [["string", "pendingConfirmation"], ["int", "batteryPercent"]]) {
        const binding = read("PowerPanel.qml").match(new RegExp(`readonly property ${type} ${name}: (.+)`))[1];
        Object.defineProperty(power, name, { get: () => vm.runInContext(binding, power) });
    }
    power.runSession("reboot");
    service.pendingConfirmation = "reboot";
    assert.equal(power.pendingConfirmation, "reboot");
    power.confirm("reboot");
    power.cancel();
    service.pendingConfirmation = "";
    service.batteryPercent = 42;
    assert.equal(power.pendingConfirmation, "");
    assert.equal(power.batteryPercent, 42);
    assert.deepEqual(service.calls, [["sessionAction", "reboot"], ["confirmAction", "reboot"], ["cancelAction"]]);
    assert.deepEqual(focused, [[4, "tab"], [4, "tab"]]);
});

test("tray primary, native menu and menu-only fallback route exactly once", () => {
    const service = serviceFixture({});
    service.items = [{ id: "app", title: "before" }];
    const tray = panel("Tray", service);
    const source = read("TrayPanel.qml");
    const items = source.match(/readonly property var items: (.+)/)[1];
    Object.defineProperty(tray, "items", { get: () => vm.runInContext(items, tray) });
    const nativeMenu = { menu: null, anchor: {}, opens: 0, open() { this.opens++; } };
    const cell = vm.createContext({
        root: tray, rowData: { id: "app", onlyMenu: false }, width: 100, height: 60, nativeMenu,
        Qt: { rect: (x, y, width, height) => ({ x, y, width, height }) },
        QsWindow: { window: "window" },
        mapToItem: (_, x, y) => ({ x: x + 200, y: y + 100 }),
    });
    cell.itemCell = cell;
    const start = source.indexOf("                function openMenu(");
    vm.runInContext(source.slice(start, source.indexOf("\n                theme:", start)), cell);
    cell.activate();
    assert.deepEqual(service.calls.splice(0), [["primaryActivate", "app", "window", 250, 130]]);
    cell.rowData.onlyMenu = true;
    cell.activate();
    assert.deepEqual(service.calls.splice(0), [["displayMenu", "app", "window", 250, 130]]);
    nativeMenu.menu = {};
    cell.activate();
    assert.equal(nativeMenu.opens, 1);
    assert.deepEqual(nativeMenu.anchor.rect, { x: 50, y: 30, width: 1, height: 1 });
    assert.equal(service.calls.length, 0);
    tray.secondary("app");
    assert.deepEqual(service.calls, [["secondaryActivate", "app"]]);
    service.items = [{ id: "app", title: "external" }];
    assert.equal(tray.items[0].title, "external");
});

test("panel source contracts retain state bindings and host-bounded scrolling", () => {
    for (const name of ["Audio", "Brightness", "Media", "Power", "Tray"]) {
        const source = read(`${name}Panel.qml`);
        // Typed panels bind service properties and never parse service JSON.
        assert.doesNotMatch(source, /panelState|stateJson\(|stateObject\(|parseJson\(|JSON\.parse/);
        assert.match(source, /Flickable\s*\{\s*id: root/);
        assert.match(source, /contentHeight:/);
        assert.match(source, /clip: true/);
    }
    for (const name of ["Audio", "Brightness", "Tray"])
        assert.match(read(`${name}Panel.qml`), /StableListModel\s*\{/);
    for (const name of ["Audio", "Brightness", "Media"])
        assert.match(read(`${name}Panel.qml`), /Accessible\.name:.*(?:volume|brightness|playback)/);
    assert.doesNotMatch(read("AudioPanel.qml"), /MouseArea\s*\{/);
    assert.match(read("TrayPanel.qml"), /acceptedButtons: Qt\.MiddleButton \| Qt\.RightButton/);
    assert.doesNotMatch(read("PowerPanel.qml"), /Keys\.on(?:Return|Enter|Escape)Pressed/);
});