Luigit
repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by admin

quickshell/nuguland/test-fixtures/ui/bar.mjs

Raw
import assert from 'node:assert/strict';
import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';

export const barSelection = 'bar';

export const barServiceFixtures = Object.freeze([
    'Niri',
    'Usage',
].map(name => ({ source: `test-fixtures/ui/fixture-services/bar/${name}.qml`, target: `${name}.qml` })));

export const sharedBarServiceFixtures = Object.freeze([
    { source: 'test-fixtures/ui/fixture-services/lifecycle/Privilege.qml', target: 'Privilege.qml' },
]);

export const barOverlayFixtures = Object.freeze([...barServiceFixtures, ...sharedBarServiceFixtures]);

export const barEntryFixture = Object.freeze({
    source: 'test-fixtures/ui/bar.qml',
    target: 'bar-ui-test.qml',
});

function within(rect, width, height) {
    return rect && rect.width > 0 && rect.height > 0 && rect.x >= 0 && rect.y >= 0 && rect.x + rect.width <= width && rect.y + rect.height <= height;
}

function center(rect) {
    return [String(Math.round(rect.x + rect.width / 2)), String(Math.round(rect.y + rect.height / 2))];
}

export async function runBar({ ipc, snapshot, input, key, click, check, screenshot, run, delay, only = '' }) {
    for (const helper of [ipc, snapshot, input, key, click, check, screenshot, run, delay])
        assert.equal(typeof helper, 'function', 'bar runner requires the parent UI helper contract');

    function assertGeometry(state, primary, name) {
        assert(state.width >= 520 && state.height >= 260, 'output is below the production popup minimum');
        assert(within(state.popup.card, state.width, state.height), `${name} popup card outside output`);
        assert(within(state.panel, state.width, state.height), `${name} production panel outside output`);
        assert(within(primary, state.width, state.height), `${name} primary control outside output`);
    }

    async function open(name, primary) {
        const before = snapshot();
        // The usage-ordered chip, or the entry's own control in the Bar's end slot.
        const control = before.chips[name] || before.barControls[name];
        assert(control && within(control.rect, before.width, before.height), `${name} Bar chip outside output`);
        click(control.rect);
        let previousGeometry = '';
        const state = await check(`${name} opens from the real Bar`, value => {
            if (value.popup.name !== name || value.popup.phase !== 'open' || !value.popup.windowActive || value.layoutFrames < 4 || !primary(value)) return false;
            const geometry = JSON.stringify([value.popup.card, value.panel, primary(value)]);
            const settled = geometry === previousGeometry;
            previousGeometry = geometry;
            return settled;
        });
        assertGeometry(state, primary(state), name);
        return state;
    }

    // Registry clipboard on the generic snapshot: its draft filters to one row.
    const clipboard = value => value.features.clipboard;
    const clipboardSearch = value => clipboard(value).items.searchField?.rect;
    const clipboardFiltered = value => clipboard(value).retained.query === 'needle' && !!clipboard(value).controls['needle document'] && !clipboard(value).controls['other document'];
    // Registry launcher on the generic snapshot: its draft filters to one app.
    const launcher = value => value.features.launcher;
    const launcherSearch = value => launcher(value).items.searchField;
    const launcherFiltered = value => launcher(value).retained.query === 'terminal' && !!launcher(value).controls['fixture terminal'] && !launcher(value).controls['fixture editor'];
    // The restored launcher draft is selected, so typing replaces it: 'editor', never 'terminaleditor'.
    const launcherReplaced = value => launcher(value).retained.query === 'editor' && !!launcher(value).controls['fixture editor'] && !launcher(value).controls['fixture terminal'];

    let state = await check('Bar fixture maps the configured output and real Bar', value => value.width > 0 && value.height > 0 && Object.values(value.chips).every(chip => within(chip.rect, value.width, value.height)));

    if (only) return runFeatureSuite(only);

    // A feature-local suite: `features/<name>/fixtures/suite.mjs` receives the
    // shared helpers and reads its feature from `snapshot().features.<name>`.
    async function runFeatureSuite(name) {
        assert.match(name, /^[a-z][a-z0-9-]*$/);
        const { default: suite } = await import(`../../features/${name}/fixtures/suite.mjs`);
        return suite({
            assert, snapshot, input, key, click, check, screenshot, open, within, delay,
            // Shared fixture state: `vertical` | `horizontal` Bar, `motion-on` | `motion-off`,
            // `focus-target` maps an ordinary application window (`snapshot().focusTargetActive`).
            fixture: event => {
                assert(['vertical', 'horizontal', 'motion-on', 'motion-off', 'focus-target'].includes(event), `unknown shared fixture event: ${event}`);
                ipc('external', event);
            },
            // The nested compositor's focused window, e.g. to prove focus return.
            focusedWindow: () => JSON.parse(run('niri', ['msg', '--json', 'focused-window'])),
            // The nested session's clipboard as plain text, or null while it offers other types.
            clipboardText: () => run('wl-paste', ['--list-types']).split('\n').includes('text/plain') ? run('wl-paste', ['--no-newline', '--type', 'text/plain']) : null,
            call: (feature, method, ...args) => ipc('external', `feature:${feature}:${method}:${JSON.stringify(args)}`),
        });
    }

    // The Bar's end slot holds every registry bar control (FeatureEntry.barControl).
    const endSlot = value => {
        const rects = Object.values(value.barControls).map(control => control.rect);
        if (rects.length === 0 || rects.some(rect => !rect)) return null;
        const x = Math.min(...rects.map(rect => rect.x));
        const y = Math.min(...rects.map(rect => rect.y));
        return { x, y, width: Math.max(...rects.map(rect => rect.x + rect.width)) - x, height: Math.max(...rects.map(rect => rect.y + rect.height)) - y };
    };
    state = await check('horizontal end slot stays at the far right with widgets before it', value => {
        const slot = endSlot(value);
        return slot && slot.x + slot.width === value.width - 10 && Object.values(value.chips).every(chip => chip.rect.x + chip.rect.width <= slot.x - 12);
    });
    await screenshot('bar-end-slot-right');
    // A warning differs from routine activity by shape, not only colour.
    assert(state.chips.tray.active && state.chips.tray.role === 'warning' && state.chips.tray.mark === 'warning', 'a warning chip shows the exclamation mark');
    assert(state.chips.notifications.active && state.chips.notifications.role !== 'warning' && state.chips.notifications.mark === 'activity', 'an activity chip shows the dot');
    assert(Object.values(state.chips).every(chip => chip.mark === '' || chip.active), 'quiet chips carry no mark');
    // Horizontal chips keep their words; hovering names the full feature in a tooltip
    // outside the thin bar surface, and pressing dismisses it.
    assert(Object.values(state.chips).every(chip => chip.icon === '' && chip.label.length > 0 && chip.accessibleName === chip.title && chip.title.length > 0), 'horizontal chips show words and carry their full name');
    input('mousemove', ...center(state.chips.clipboard.rect));
    state = await check('hovered chip shows its full name', value => value.chips.clipboard.tooltip === 'clipboard' && value.chips.clipboard.label === 'clips');
    await screenshot('bar-chip-tooltip');
    const clock = Object.keys(state.barControls)[0];
    input('mousemove', ...center(state.barControls[clock].rect));
    await check('hovered bar control shows its full name and the chip tooltip goes', value => value.barControls[clock].tooltip.length > 0 && value.chips.clipboard.tooltip === '');
    assert.equal(state.barEdge.height, 1, 'horizontal Bar accent is a hairline');
    assert.equal(state.barEdge.width, state.width);
    // Clipboard and launcher flows run in their own suites; this cross-task flow
    // keeps both drafts while they take over from each other; switching never
    // launches, so the launcher draft returns selected in its focused field.
    state = await open('clipboard', clipboardSearch);
    input('type', 'needle');
    state = await check('clipboard draft filters before switching bar', value => value.popup.name === 'clipboard' && clipboardFiltered(value));
    // Focus stays in the search field; the selected result shows its rail, not only a tint.
    assert(clipboard(state).controls['needle document'].selected && clipboardSearch(state) && clipboard(state).items.searchField.focused, 'the selected clipboard result carries its selection rail');
    await screenshot('bar-clipboard-selection');

    input('mousemove', ...center(state.chips.launcher.rect));
    await delay(120);
    state = await check('real Bar hover does not switch the active clipboard task', value => value.chips.launcher.hovered && value.popup.name === 'clipboard' && clipboardFiltered(value));
    click(state.chips.launcher.rect);
    state = await check('Bar activation switches from clipboard to launcher', value => value.popup.name === 'launcher' && value.popup.phase === 'open' && value.popup.windowActive && launcherSearch(value)?.focused);
    assertGeometry(state, launcherSearch(state).rect, 'launcher');
    input('type', 'terminal');
    state = await check('launcher draft filters after the switch', value => launcherFiltered(value));

    click(state.chips.clipboard.rect);
    state = await check('switching restores clipboard query and results', value => value.popup.name === 'clipboard' && clipboardFiltered(value));
    click(state.chips.clipboard.rect);
    await check('same Bar chip closes clipboard', value => !value.popup.open && value.popup.lastCloseReason === 'bar-toggle');
    state = await open('clipboard', clipboardSearch);
    assert(clipboardFiltered(state), 'clipboard draft must survive close and reopen');
    click(state.chips.launcher.rect);
    state = await check('switching back restores the launcher draft in its focused field', value => value.popup.name === 'launcher' && value.popup.windowActive && launcherSearch(value)?.focused && launcherFiltered(value));
    input('type', 'editor');
    state = await check('typing replaces the restored launcher draft', value => launcherReplaced(value));
    click(state.chips.launcher.rect);
    await check('same Bar chip closes launcher', value => !value.popup.open && value.popup.lastCloseReason === 'bar-toggle');

    // Feature suites (`features/*/fixtures/suite.mjs`) run in their own sandboxes.
    ipc('external', 'vertical');
    state = await check('real Bar moves to vertical layout', value => value.orientation === 'vertical' && Object.values(value.chips).every(chip => within(chip.rect, value.width, value.height)));
    // Vertical chips trade words for glyphs, never abbreviations, and keep their names.
    assert(Object.values(state.chips).every(chip => chip.icon.length > 0 && chip.accessibleName === chip.title && chip.title.length > 0), 'vertical chips show glyphs and carry their full name');
    input('mousemove', ...center(state.chips.connectivity.rect));
    await check('hovered vertical chip shows its full name beside the bar', value => value.chips.connectivity.tooltip === 'network and bluetooth');
    await screenshot('bar-chip-tooltip-vertical');
    // Dynamic chip state the horizontal labels spell out stays visible as glyph and badge.
    ipc('external', 'feature:audio:setMicActive:[true]');
    ipc('external', 'feature:noko:setMissingAssets:[true]');
    await check('vertical chips keep counts, privacy and attention visible', value => value.chips.tray.badge === '1' && value.chips.tray.active &&
        value.chips.audio.icon === '\u{F036C}' && value.chips.audio.accessibleName === 'microphone in use' && value.chips.audio.active &&
        value.chips.noko.badge === '!' && value.chips.noko.strong && value.chips.noko.role === 'warning');
    await screenshot('bar-chip-state-vertical');
    ipc('external', 'feature:audio:setMicActive:[false]');
    ipc('external', 'feature:noko:setMissingAssets:[false]');
    await check('vertical chips return to rest', value => value.chips.audio.icon === '\u{F057E}' && !value.chips.audio.active && value.chips.noko.badge === '' && !value.chips.noko.strong);
    await check('vertical end slot retains its centre and widget-clearance rule', value => {
        const slot = endSlot(value);
        return slot && slot.x + slot.width / 2 === value.barWidth / 2 && slot.y === Math.min(value.height / 2 - slot.height / 2, Math.min(...Object.values(value.chips).map(chip => chip.rect.y)) - slot.height - 12);
    });
    await check('vertical Bar accent remains a right-edge hairline after orientation change', value => value.barEdge.width === 1 && value.barEdge.height === value.height && value.barEdge.x === value.barWidth - 1);
    for (const [name, primary] of [
        ['clipboard', clipboardSearch],
        ['launcher', value => launcherSearch(value)?.rect],
        ['audio', value => value.features.audio.controls['fixture output output volume']?.rect],
        ['media', value => value.features.media.items.transportActions?.rect],
        ['tray', value => value.features.tray.controls['activate fixture tray']?.rect],
        ['power', value => value.features.power.controls.reboot?.rect],
        ['connectivity', value => value.features.connectivity.controls['expand fixture-secure']?.rect],
        ['notifications', value => value.features.notifications.controls['reply to fixture']?.rect],
        ['brightness', value => value.features.brightness.controls['fixture display brightness']?.rect],
        ['system', value => value.features.system.controls['open fixture service failed']?.rect],
        ['vault', value => value.features.vault.items.vaultMasterPassword?.rect],
        ['noko', value => value.features.noko.controls['start capture']?.rect],
    ]) {
        state = await open(name, primary);
        if (name === 'clipboard') assert(clipboardFiltered(state));
        if (name === 'launcher') assert(launcherReplaced(state), 'the replaced launcher draft survives the switch from clipboard');
        await screenshot(`bar-${name}-vertical`);
        // Empty states through each registry double, in vertical layout.
        const empty = {
            media: { set: value => ipc('external', `feature:media:setEmpty:${JSON.stringify([value])}`), shown: value => value.features.media.items.mediaEmptyState?.rect },
            tray: { set: value => ipc('external', `feature:tray:setEmpty:${JSON.stringify([value])}`), shown: value => value.features.tray.items.trayEmptyState?.rect },
        }[name];
        if (empty) {
            empty.set(true);
            state = await check(`${name} empty popup stays compact in vertical layout`, value => empty.shown(value) && value.popup.card.width === 352 && value.popup.card.height === 88);
            assertGeometry(state, empty.shown(state), `vertical empty ${name}`);
            await screenshot(`bar-${name}-empty-vertical`);
            empty.set(false);
            await check(`${name} repopulates in vertical layout`, value => !empty.shown(value) && primary(value));
        }
    }

    // Exercise the public command: desktop preference, compositor include,
    // and the already-running shell share one effective mode.
    const modeFile = `${process.env.XDG_STATE_HOME}/nugu/mode`;
    const modeCommand = command => run('env', ['GSETTINGS_BACKEND=keyfile', 'nu', '--no-config-file', '-c', `use /project/runtime/theme.nu; theme ${command}`]);
    const reloads = () => (readFileSync('/evidence/niri.log', 'utf8').match(/loaded config from/g) || []).length;
    const palettes = JSON.parse(readFileSync('/project/nugu.json', 'utf8'));
    function editorColours(mode) {
        const editor = JSON.parse(readFileSync('/evidence/theme-neovide.json', 'utf8'));
        return editor.mode === mode && editor.foreground === parseInt(palettes[mode].content.normal.slice(1), 16)
            && editor.background === parseInt(palettes[mode].content.backdrop.slice(1), 16) && editor.draft === 'retained editor draft';
    }
    async function selected(mode) {
        const before = reloads();
        const priorColours = readFileSync(`${process.env.HOME}/.nugu-runtime/niri.kdl`, 'utf8');
        assert.equal(modeCommand(`set ${mode}`), mode);
        assert.equal(readFileSync(modeFile, 'utf8'), `${mode}\n`);
        assert.equal(run('env', ['GSETTINGS_BACKEND=keyfile', 'gsettings', 'get', 'org.gnome.desktop.interface', 'color-scheme']), `'prefer-${mode}'`);
        const palette = JSON.parse(readFileSync('/project/nugu.json', 'utf8'))[mode];
        const colours = readFileSync(`${process.env.HOME}/.nugu-runtime/niri.kdl`, 'utf8');
        assert(colours.includes(`backdrop-color "${palette.ui.backdrop}"`));
        if (colours !== priorColours) await check(`niri reloads ${mode} colours without restart`, () => reloads() > before);
        await check(`native terminal follows ${mode} desktop appearance`, () => readFileSync('/evidence/theme-wezterm-mode', 'utf8') === `nugu-${mode}`);
        await check(`native editor follows ${mode} colours and retains draft`, () => editorColours(mode));
    }
    // Real aerc, private maildir, detached tmux PTY; no accounts or host sockets.
    for (const directory of ['cur', 'new', 'tmp']) mkdirSync(`/tmp/theme-mail/INBOX/${directory}`, { recursive: true });
    writeFileSync('/tmp/theme-mail/INBOX/new/message', 'From: fixture@example.invalid\nTo: fixture@example.invalid\nSubject: retained message\nDate: Fri, 14 Nov 2026 12:00:00 +0000\n\nretained body\n');
    writeFileSync('/tmp/theme-accounts.conf', '[fixture]\nsource=maildir:///tmp/theme-mail\ndefault=INBOX\nfrom=fixture@example.invalid\n');
    writeFileSync('/tmp/theme-aerc.conf', readFileSync('/aerc.conf', 'utf8').replace('[general]', '[general]\nlog-file=/evidence/theme-aerc.log\nlog-level=debug'));
    const tmux = args => run('tmux', ['-S', '/tmp/theme-tmux', ...args]);
    const pane = tmux(['-f', '/dev/null', 'new-session', '-d', '-P', '-F', '#{pane_id}', '-s', 'theme', '-x', '120', '-y', '35', 'TERM=tmux-direct aerc -C /tmp/theme-aerc.conf -A /tmp/theme-accounts.conf -B /aerc-binds.conf']);
    const mailScreen = () => tmux(['capture-pane', '-p', '-t', pane]);
    function mailColours(mode) {
        const rendered = tmux(['capture-pane', '-p', '-e', '-t', pane]);
        writeFileSync(`/evidence/theme-mail-${mode}.ansi`, rendered);
        let foreground = '', background = '';
        for (const token of rendered.matchAll(/\x1b\[([0-9;]*)m|([^\x1b]+)/g)) {
            if (token[2]?.includes('retained message')) return { foreground, background };
            if (token[1] === undefined) continue;
            const codes = token[1].split(';').map(Number);
            for (let index = 0; index < codes.length; index++) {
                const code = codes[index];
                if (code === 0) foreground = background = '';
                if (code === 39) foreground = '';
                if (code === 49) background = '';
                if (code !== 38 && code !== 48) continue;
                let colour;
                if (codes[++index] === 2) {
                    colour = '#' + codes.slice(index + 1, index + 4).map(value => value.toString(16).padStart(2, '0')).join('');
                    index += 3;
                } else {
                    colour = `indexed:${codes[++index]}`;
                }
                if (code === 38) foreground = colour;
                else background = colour;
            }
        }
        return null;
    }
    const mailExpected = mode => {
        const palette = JSON.parse(readFileSync('/project/nugu.json', 'utf8'))[mode];
        return { foreground: palette.ui.backdrop, background: palette.ui.focus };
    };
    try {
        await check('isolated mail view loads production styles', () => mailScreen().includes('retained message'));
        assert.deepEqual(mailColours('dark'), mailExpected('dark'), 'selected mail row renders dark Nugu colours');
        const mailPid = tmux(['display-message', '-p', '-t', pane, '#{pane_pid}']);
        const retained = snapshot().features.noko.service;
        const recoloured = mode => value => value.themeMode === mode && value.barEdge.height === value.height;
        assert.equal(state.themeMode, 'dark', 'missing mode state is dark');
        await selected('light');
        await check('a light mode switch recolours the running shell', recoloured('light'));
        assert.equal(snapshot().popup.name, 'noko', 'mode switch preserves open task');
        assert.deepEqual(snapshot().features.noko.service, retained, 'mode switch preserves service state');
        await check('mail renders light styles without losing selected message', () => JSON.stringify(mailColours('light')) === JSON.stringify(mailExpected('light')));
        assert.deepEqual(mailColours('light'), mailExpected('light'));
        assert.equal(tmux(['display-message', '-p', '-t', pane, '#{pane_pid}']), mailPid, 'mail process is not restarted');
        run('niri', ['msg', 'action', 'toggle-overview']);
        await check('light overview opens', () => JSON.parse(run('niri', ['msg', '--json', 'overview-state'])).is_open);
        await screenshot('bar-overview-light');
        run('niri', ['msg', 'action', 'toggle-overview']);
        for (const name of ['clipboard', 'launcher', 'audio', 'media', 'tray', 'power', 'connectivity', 'notifications', 'brightness', 'system', 'vault', 'noko']) {
            const control = snapshot().chips[name] || snapshot().barControls[name];
            click(control.rect);
            await check(`${name} opens in light mode`, value => value.popup.name === name && value.popup.phase === 'open' && value.popup.windowActive && value.themeMode === 'light');
            await screenshot(`bar-${name}-light`);
        }
        writeFileSync(modeFile, 'blue\n');
        await check('an invalid mode is dark', recoloured('dark'));
        await selected('light');
        await check('light returns', recoloured('light'));
        const beforeToggle = reloads();
        assert.equal(modeCommand('toggle'), 'dark');
        await check('the public toggle reloads niri dark', () => reloads() > beforeToggle);
        await check('the public toggle recolours the shell dark', recoloured('dark'));
        await check('native terminal returns dark', () => readFileSync('/evidence/theme-wezterm-mode', 'utf8') === 'nugu-dark');
        await check('native editor returns dark colours and retains draft', () => editorColours('dark'));
        assert.equal(modeCommand('status'), 'dark');
        rmSync(modeFile);
        await check('removed mode state is dark', recoloured('dark'));
        await screenshot('bar-dark-again');
        run('niri', ['msg', 'action', 'toggle-overview']);
        await check('dark overview opens', () => JSON.parse(run('niri', ['msg', '--json', 'overview-state'])).is_open);
        await screenshot('bar-overview-dark');
        run('niri', ['msg', 'action', 'toggle-overview']);
        await check('mail renders dark styles after round trip', () => JSON.stringify(mailColours('dark-again')) === JSON.stringify(mailExpected('dark')));
        assert.deepEqual(mailColours('dark-again'), mailExpected('dark'));
        assert(mailScreen().includes('retained message'), 'mail view survives complete round trip');
        assert.doesNotMatch(readFileSync('/evidence/theme-aerc.log', 'utf8'), /\b(?:ERROR|WARN)\b/);
    } finally {
        tmux(['kill-server']);
    }
}