Turn any website into a lightweight desktop app with one command, on macOS, Windows and Linux.
Rust chatgptclaudeclidesktopdesktop-appelectron-alternativegeminilinuxmacosnativefierno-electronrusttauriweb-to-desktopwebsite-to-appwebviewwindowsyoutube
import fs from "fs";
import path from "path";
import { runInNewContext } from "node:vm";
import { describe, expect, it } from "vitest";
const source = fs.readFileSync(
path.join(process.cwd(), "src-tauri/src/inject/title_bar.js"),
"utf-8",
);
// Colors are written as "r,g,b,a" so the fake canvas can resolve them without
// a real CSS parser; anything else behaves like an unsupported value.
function parse(value) {
const parts = String(value).split(",").map(Number);
return parts.length === 4 && parts.every((n) => Number.isFinite(n))
? parts
: null;
}
function element(background, parentElement = null) {
return { background, parentElement };
}
function loadTitleBar({
columns,
width = 1000,
metas = [],
matching = [],
hidden = false,
}) {
const calls = [];
let current = columns;
let timer = null;
let intervalTick = null;
let observed = null;
const docListeners = {};
const winListeners = {};
const context = {
console,
setTimeout: (callback) => {
timer = callback;
return 1;
},
setInterval: (callback) => {
intervalTick = callback;
return 1;
},
MutationObserver: class {
constructor(callback) {
observed = callback;
}
observe() {}
},
document: {
readyState: "complete",
hidden,
documentElement: {},
body: {},
addEventListener(type, handler) {
docListeners[type] = docListeners[type] || [];
docListeners[type].push(handler);
},
createElement() {
let fill = [0, 0, 0, 0];
return {
getContext: () => ({
clearRect() {},
fillRect() {},
set fillStyle(value) {
const parsed = parse(value);
if (parsed) fill = parsed;
},
getImageData: () => ({ data: fill }),
}),
};
},
querySelectorAll: (selector) =>
selector === 'meta[name="theme-color"]'
? metas.map((attributes) => ({
getAttribute: (name) => attributes[name] ?? null,
}))
: [],
elementFromPoint(x) {
const column = Math.min(2, Math.floor((x / width) * 3));
return current[column];
},
},
window: {
innerWidth: width,
addEventListener(type, handler) {
winListeners[type] = winListeners[type] || [];
winListeners[type].push(handler);
},
matchMedia: (query) => ({ matches: matching.includes(query) }),
getComputedStyle: (node) => ({ backgroundColor: node.background }),
__PAKE_NATIVE__: {
core: {
invoke(command, args) {
calls.push({ command, args });
return Promise.resolve();
},
},
},
},
};
context.window.document = context.document;
runInNewContext(source, context);
const flushTimer = () => {
const run = timer;
timer = null;
run?.();
};
return {
calls,
// A page mutation followed by the debounce timer firing.
repaint(next) {
current = next;
observed();
flushTimer();
},
tickInterval(next) {
if (next) current = next;
intervalTick?.();
flushTimer();
},
setHidden(nextHidden, next) {
if (next) current = next;
context.document.hidden = nextHidden;
for (const fn of docListeners.visibilitychange || []) fn();
flushTimer();
},
setHiddenQuietly(nextHidden) {
context.document.hidden = nextHidden;
},
fireWindowEvent(type, next) {
if (next) current = next;
for (const fn of winListeners[type] || []) fn();
flushTimer();
},
};
}
describe("macOS transparent title bar color", () => {
it("sends the color most of the top edge shares", () => {
const white = element("255,255,255,255");
const logo = element("240,240,240,255");
const { calls } = loadTitleBar({ columns: [white, logo, white] });
expect(calls).toEqual([
{
command: "set_title_bar_color",
args: { red: 255, green: 255, blue: 255 },
},
]);
});
it("walks up past transparent layers to the painted ancestor", () => {
const page = element("20,20,24,255");
const overlay = element("0,0,0,0", page);
const { calls } = loadTitleBar({ columns: [overlay, overlay, overlay] });
expect(calls[0].args).toEqual({ red: 20, green: 20, blue: 24 });
});
it("uses the center sample when all three differ", () => {
const { calls } = loadTitleBar({
columns: [
element("10,10,10,255"),
element("200,100,50,255"),
element("90,90,90,255"),
],
});
expect(calls[0].args).toEqual({ red: 200, green: 100, blue: 50 });
});
it("sends again only when the top color changes", () => {
const white = element("255,255,255,255");
const { calls, repaint } = loadTitleBar({ columns: [white, white, white] });
repaint([white, white, white]);
expect(calls).toHaveLength(1);
const dark = element("30,30,30,255");
repaint([dark, dark, dark]);
expect(calls.map((call) => call.args.red)).toEqual([255, 30]);
});
it("falls back to the theme-color whose media query matches", () => {
const clear = element("0,0,0,0");
const { calls } = loadTitleBar({
columns: [clear, clear, clear],
metas: [
{ content: "250,250,250,255", media: "(prefers-color-scheme: light)" },
{ content: "18,18,20,255", media: "(prefers-color-scheme: dark)" },
],
matching: ["(prefers-color-scheme: dark)"],
});
expect(calls[0].args).toEqual({ red: 18, green: 18, blue: 20 });
});
it("prefers the painted top edge over the theme-color", () => {
const page = element("40,40,40,255");
const { calls } = loadTitleBar({
columns: [page, page, page],
metas: [{ content: "250,250,250,255" }],
});
expect(calls[0].args).toEqual({ red: 40, green: 40, blue: 40 });
});
it("leaves the native color alone when nothing on top is painted", () => {
const clear = element("0,0,0,0");
const { calls } = loadTitleBar({ columns: [clear, clear, null] });
expect(calls).toEqual([]);
});
it("still samples initially when document.hidden is true, then skips background polling until visible", () => {
const white = element("255,255,255,255");
const dark = element("24,24,28,255");
const navy = element("12,24,48,255");
const { calls, tickInterval, setHidden, fireWindowEvent } = loadTitleBar({
columns: [white, white, white],
hidden: true,
});
expect(calls).toHaveLength(1);
expect(calls[0].args).toEqual({ red: 255, green: 255, blue: 255 });
// Background interval ticks must not resample while hidden.
tickInterval([dark, dark, dark]);
expect(calls).toHaveLength(1);
// Becoming visible resamples immediately.
setHidden(false);
expect(calls).toHaveLength(2);
expect(calls[1].args).toEqual({ red: 24, green: 24, blue: 28 });
// SPA route events also schedule a sample when visible.
fireWindowEvent("popstate", [navy, navy, navy]);
expect(calls).toHaveLength(3);
expect(calls[2].args).toEqual({ red: 12, green: 24, blue: 48 });
});
it("keeps sampling on page events while hidden, so a window revealed after load is colored", () => {
const white = element("255,255,255,255");
const dark = element("24,24,28,255");
const navy = element("12,24,48,255");
const { calls, repaint, fireWindowEvent, tickInterval, setHiddenQuietly } =
loadTitleBar({ columns: [white, white, white], hidden: true });
expect(calls).toHaveLength(1);
// The page finishes loading and repaints while its window is still hidden.
fireWindowEvent("load", [dark, dark, dark]);
expect(calls).toHaveLength(2);
expect(calls[1].args).toEqual({ red: 24, green: 24, blue: 28 });
repaint([navy, navy, navy]);
expect(calls).toHaveLength(3);
// Revealed without a visibilitychange event: the poll resumes on its own.
setHiddenQuietly(false);
tickInterval([white, white, white]);
expect(calls).toHaveLength(4);
expect(calls[3].args).toEqual({ red: 255, green: 255, blue: 255 });
});
});