M0: WIT package, MoonBit components, JS host, docs, CI (#1)
CI / test (push) Successful in 19s
CI / test (push) Successful in 19s
This commit was merged in pull request #1.
This commit is contained in:
1 parent
e5548fc067
commit
880ecd4102
141 files changed
+9681
-1
No files matched your search
Generated
+3141
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"name": "moon-plasma-host",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"description": "Host runtime for moon-plasma (M0: Node/browser host over jco-transpiled components)",
|
||||
"scripts": {
|
||||
"test": "node --test test/*.test.mjs"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@bytecodealliance/jco": "1.42.0",
|
||||
"playwright-core": "^1.50.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
#!/usr/bin/env node
|
||||
// Minimal static server for the browser host (serves host/, config/, build/ only).
|
||||
// node host/serve.mjs [port] (default: $PORT or 8080)
|
||||
import http from 'node:http';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { join, extname, normalize } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const ROOT = join(fileURLToPath(import.meta.url), '..', '..');
|
||||
const MIME = { '.html': 'text/html', '.mjs': 'text/javascript', '.js': 'text/javascript', '.json': 'application/json', '.wasm': 'application/wasm' };
|
||||
const ALLOWED = ['host/', 'config/', 'build/'];
|
||||
|
||||
export function serve(port = 0) {
|
||||
const srv = http.createServer(async (req, res) => {
|
||||
try {
|
||||
let p = decodeURIComponent(new URL(req.url, 'http://x').pathname);
|
||||
if (p === '/') p = '/host/web/index.html';
|
||||
const rel = normalize(p).replace(/^\/+/, '');
|
||||
if (rel.includes('..') || !ALLOWED.some((a) => rel.startsWith(a)) || rel.startsWith('host/node_modules')) { res.writeHead(404).end('not found'); return; }
|
||||
const body = await readFile(join(ROOT, rel));
|
||||
res.writeHead(200, { 'content-type': MIME[extname(rel)] ?? 'application/octet-stream', 'cache-control': 'no-store' }).end(body);
|
||||
} catch { res.writeHead(404).end('not found'); }
|
||||
});
|
||||
return new Promise((resolve) => srv.listen(port, '127.0.0.1', () => resolve(srv)));
|
||||
}
|
||||
|
||||
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
||||
const srv = await serve(Number(process.argv[2] ?? process.env.PORT ?? 8080));
|
||||
console.log(`moon-plasma host: http://127.0.0.1:${srv.address().port}/`);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
// Terminal rasteriser: a coarse text-mode view of a render list, used for
|
||||
// headless runs and CI logs. (Real pixels come from the Canvas2D backend.)
|
||||
|
||||
const SHADES = ' .:-=+*#%@';
|
||||
const CW = 8, CH = 16;
|
||||
|
||||
export function renderAscii(ops, screen) {
|
||||
const cols = Math.ceil(screen.w / CW), rows = Math.ceil(screen.h / CH);
|
||||
const grid = Array.from({ length: rows }, () => Array(cols).fill(' '));
|
||||
const clips = [{ x: 0, y: 0, w: screen.w, h: screen.h }];
|
||||
const inClip = (px, py) => { const c = clips[clips.length - 1]; return px >= c.x && py >= c.y && px < c.x + c.w && py < c.y + c.h; };
|
||||
const lum = (c) => (0.299 * c.r + 0.587 * c.g + 0.114 * c.b) / 255;
|
||||
const shade = (c) => SHADES[Math.min(SHADES.length - 1, Math.floor(lum(c) * SHADES.length))];
|
||||
const put = (cx, cy, ch) => { if (cx >= 0 && cy >= 0 && cx < cols && cy < rows && inClip(cx * CW + CW / 2, cy * CH + CH / 2)) grid[cy][cx] = ch; };
|
||||
for (const op of ops) {
|
||||
const v = op.val;
|
||||
switch (op.tag) {
|
||||
case 'push-clip': {
|
||||
const c = clips[clips.length - 1];
|
||||
const x0 = Math.max(c.x, v.x), y0 = Math.max(c.y, v.y);
|
||||
const x1 = Math.min(c.x + c.w, v.x + v.w), y1 = Math.min(c.y + c.h, v.y + v.h);
|
||||
clips.push({ x: x0, y: y0, w: Math.max(0, x1 - x0), h: Math.max(0, y1 - y0) });
|
||||
break;
|
||||
}
|
||||
case 'pop-clip': if (clips.length < 2) throw new Error('pop-clip without push-clip'); clips.pop(); break;
|
||||
case 'fill-rect': {
|
||||
if (v.color.a < 40) break;
|
||||
for (let cy = Math.floor(v.rect.y / CH); cy <= Math.floor((v.rect.y + v.rect.h - 1) / CH); cy++)
|
||||
for (let cx = Math.floor(v.rect.x / CW); cx <= Math.floor((v.rect.x + v.rect.w - 1) / CW); cx++) put(cx, cy, shade(v.color));
|
||||
break;
|
||||
}
|
||||
case 'circle': {
|
||||
if (!v.filled || v.color.a < 120) break;
|
||||
for (let cy = 0; cy < rows; cy++) for (let cx = 0; cx < cols; cx++) {
|
||||
const dx = cx * CW + CW / 2 - v.center.x, dy = cy * CH + CH / 2 - v.center.y;
|
||||
if (dx * dx + dy * dy <= v.radius * v.radius) put(cx, cy, shade(v.color));
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'text': {
|
||||
const w = v.text.length;
|
||||
let x0 = v.origin.x;
|
||||
if (v.style.align === 'center') x0 -= (w * CW) / 2; else if (v.style.align === 'right') x0 -= w * CW;
|
||||
const cy = Math.floor(v.origin.y / CH);
|
||||
for (let i = 0; i < w; i++) put(Math.floor(x0 / CW) + i, cy, v.text[i]);
|
||||
break;
|
||||
}
|
||||
default: break; // stroke-rect / line: omitted in text mode
|
||||
}
|
||||
}
|
||||
return grid.map((r) => r.join('').replace(/\s+$/, '')).join('\n');
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
#!/usr/bin/env node
|
||||
// Headless desktop: boots all components under the Node host and prints the
|
||||
// composed desktop as text, optionally after a scripted interaction.
|
||||
// node host/src/cli.mjs [--config file] [--time ISO] [--click-launcher] [--scene out.json]
|
||||
import { writeFile } from 'node:fs/promises';
|
||||
import { bootDesktop } from './headless.mjs';
|
||||
import { renderAscii } from './ascii.mjs';
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const opt = (n) => { const i = args.indexOf(`--${n}`); return i < 0 ? undefined : args[i + 1]; };
|
||||
const flag = (n) => args.includes(`--${n}`);
|
||||
|
||||
const fixed = opt('time') ? new Date(opt('time')) : undefined;
|
||||
const { desktop, platform } = await bootDesktop({ configPath: opt('config'), now: fixed ? () => fixed : undefined });
|
||||
|
||||
let f = desktop.frame();
|
||||
if (flag('click-launcher')) {
|
||||
const e = desktop.hit.widgets.find((w) => w.widget.id === 'launcher');
|
||||
desktop.pointer('down', e.rect.x + 10, e.rect.y + 10);
|
||||
f = desktop.frame();
|
||||
if (flag('type')) { for (const ch of opt('type')) desktop.key(ch); f = desktop.frame(); }
|
||||
}
|
||||
console.log(renderAscii(f.ops, f.screen));
|
||||
console.log(`\n-- ${f.ops.length} draw-ops; widgets: ${desktop.widgets.map((w) => `${w.id}=${w.componentName}`).join(', ')}; theme=${platform.tokens.name}`);
|
||||
if (opt('scene')) await writeFile(opt('scene'), JSON.stringify(f, null, 1));
|
||||
if (desktop.faults.length) { console.error(`${desktop.faults.length} component fault(s)`); process.exit(1); }
|
||||
@@ -0,0 +1,201 @@
|
||||
// moon-plasma host core (platform-agnostic: runs in Node and the browser).
|
||||
//
|
||||
// Responsibilities (the *only* things that are not components):
|
||||
// * instantiate components and broker capabilities (deny-by-default grants)
|
||||
// * drive the frame loop: shell layout -> widget render -> render-list
|
||||
// * route input to the component that owns the surface under the pointer
|
||||
// * hot-swap a widget's implementation at runtime
|
||||
// All policy (layout, look, behaviour) lives in components.
|
||||
|
||||
import { CAPABILITIES } from './platform.mjs';
|
||||
import { place, translate } from './scene.mjs';
|
||||
|
||||
const PKG = 'moonplasma:desktop';
|
||||
const PLASMOID = `${PKG}/plasmoid`;
|
||||
const PANEL = `${PKG}/panel-layout`;
|
||||
const DESKTOP = `${PKG}/desktop-surface`;
|
||||
|
||||
export class PermissionError extends Error {
|
||||
constructor(msg) { super(msg); this.name = 'PermissionError'; }
|
||||
}
|
||||
export class ComponentFault extends Error {
|
||||
constructor(component, fn, cause) {
|
||||
super(`component "${component}" faulted in ${fn}: ${cause?.message ?? cause}`);
|
||||
this.name = 'ComponentFault';
|
||||
this.component = component;
|
||||
this.fn = fn;
|
||||
this.cause = cause;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @typedef {{meta: {name:string, world:string, imports:string[], exports:string[]},
|
||||
* instantiate: (imports: object) => Promise<object>}} LoadedComponent
|
||||
* @param {{config: any, loader: (name: string) => Promise<LoadedComponent>, platform: any}} opts
|
||||
*/
|
||||
export class Desktop {
|
||||
constructor({ config, loader, platform }) {
|
||||
this.config = config;
|
||||
this.loader = loader;
|
||||
this.platform = platform;
|
||||
this.screen = { w: config.screen.w, h: config.screen.h };
|
||||
this.shell = null;
|
||||
this.widgets = []; // {id, align, componentName, grants, meta, plasmoid}
|
||||
this.faults = []; // visible, never swallowed: also rendered as error tiles
|
||||
this.hit = { widgets: [], popup: null };
|
||||
this.hovered = null;
|
||||
}
|
||||
|
||||
async start() {
|
||||
this.shell = await this.#instantiate(this.config.shell.component, this.config.shell.grants, 'shell');
|
||||
for (const w of this.config.panel) {
|
||||
const inst = await this.#instantiate(w.component, w.grants, 'widget');
|
||||
this.widgets.push({ id: w.id, align: w.align ?? 'start', grants: w.grants, ...inst });
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Replace the implementation behind panel widget `id` without touching others. */
|
||||
async swap(id, componentName) {
|
||||
const i = this.widgets.findIndex((w) => w.id === id);
|
||||
if (i < 0) throw new Error(`swap: no widget with id "${id}"`);
|
||||
const old = this.widgets[i];
|
||||
const inst = await this.#instantiate(componentName, old.grants, 'widget');
|
||||
this.widgets[i] = { id, align: old.align, grants: old.grants, ...inst };
|
||||
this.hovered = null;
|
||||
}
|
||||
|
||||
async #instantiate(componentName, grants, role) {
|
||||
for (const g of grants) {
|
||||
if (!CAPABILITIES.includes(g)) throw new PermissionError(`config grants unknown capability "${g}" to ${componentName}`);
|
||||
}
|
||||
const c = await this.loader(componentName);
|
||||
const need = c.meta.imports;
|
||||
const denied = need.filter((n) => !grants.includes(n));
|
||||
if (denied.length) {
|
||||
throw new PermissionError(
|
||||
`component "${componentName}" imports [${denied.join(', ')}] which the desktop config does not grant ` +
|
||||
`(granted: [${grants.join(', ')}])`);
|
||||
}
|
||||
const exp = c.meta.exports;
|
||||
const wantExports = role === 'shell' ? ['panel-layout', 'desktop-surface'] : ['plasmoid'];
|
||||
for (const e of wantExports) {
|
||||
if (!exp.includes(e)) throw new Error(`component "${componentName}" does not export ${e}; cannot act as ${role}`);
|
||||
}
|
||||
// Only granted AND imported interfaces are wired; jco fails instantiation
|
||||
// loudly if anything else is missing.
|
||||
const imports = {};
|
||||
for (const n of need) imports[`${PKG}/${n}`] = this.platform.interfaces[n]();
|
||||
const instance = await c.instantiate(imports);
|
||||
const get = (iface) => instance[`${iface}@0.1.0`] ?? instance[iface];
|
||||
return role === 'shell'
|
||||
? { componentName, meta: c.meta, panel: get(PANEL), desktop: get(DESKTOP) }
|
||||
: { componentName, meta: c.meta, plasmoid: get(PLASMOID) };
|
||||
}
|
||||
|
||||
#call(owner, fn, thunk) {
|
||||
try {
|
||||
return thunk();
|
||||
} catch (e) {
|
||||
const f = new ComponentFault(owner.componentName, fn, e);
|
||||
this.faults.push(f);
|
||||
console.error(`[host] ${f.message}`);
|
||||
throw f;
|
||||
}
|
||||
}
|
||||
|
||||
/** Compose one frame. Returns {ops, layout, screen}. */
|
||||
frame() {
|
||||
const screen = this.screen;
|
||||
const ops = [];
|
||||
ops.push(...this.#call(this.shell, 'desktop-surface.render-background', () => this.shell.desktop.renderBackground(screen)));
|
||||
|
||||
const slots = this.widgets.map((w) => {
|
||||
const info = this.#call(w, 'plasmoid.info', () => w.plasmoid.info());
|
||||
w.info = info;
|
||||
return { id: w.id, preferred: info.preferred, minWidth: info.minWidth, stretch: info.stretch, align: w.align };
|
||||
});
|
||||
const layout = this.#call(this.shell, 'panel-layout.compute-layout', () => this.shell.panel.computeLayout(screen, slots));
|
||||
ops.push(...this.#call(this.shell, 'panel-layout.render-panel', () => this.shell.panel.renderPanel(screen, layout.panel)));
|
||||
|
||||
this.hit = { widgets: [], popup: null };
|
||||
const rects = new Map();
|
||||
for (const p of layout.placements) rects.set(p.id, p.rect);
|
||||
for (const w of this.widgets) {
|
||||
const rect = rects.get(w.id);
|
||||
if (!rect) throw new Error(`shell returned no placement for widget "${w.id}"`);
|
||||
this.hit.widgets.push({ widget: w, rect });
|
||||
let wops;
|
||||
try {
|
||||
wops = this.#call(w, 'plasmoid.render', () => w.plasmoid.render({ w: rect.w, h: rect.h }));
|
||||
} catch {
|
||||
wops = faultTile(rect, w.componentName);
|
||||
}
|
||||
ops.push(...place(wops, rect));
|
||||
}
|
||||
|
||||
// Popup layer (at most one popup open at a time).
|
||||
for (const entry of this.hit.widgets) {
|
||||
let pop;
|
||||
try {
|
||||
pop = this.#call(entry.widget, 'plasmoid.popup', () => entry.widget.plasmoid.popup());
|
||||
} catch { continue; }
|
||||
if (!pop) continue;
|
||||
const prect = this.#call(this.shell, 'panel-layout.popup-position', () =>
|
||||
this.shell.panel.popupPosition(screen, layout.panel, entry.rect, pop.size));
|
||||
this.hit.popup = { widget: entry.widget, anchor: entry.rect, rect: prect };
|
||||
ops.push(...place(pop.ops, prect));
|
||||
break;
|
||||
}
|
||||
return { ops, layout, screen };
|
||||
}
|
||||
|
||||
#send(widget, target, event) {
|
||||
return this.#call(widget, 'plasmoid.on-event', () => widget.plasmoid.onEvent(target, event));
|
||||
}
|
||||
|
||||
/** @param {'move'|'down'|'up'} kind Returns true when a redraw is needed. */
|
||||
pointer(kind, x, y) {
|
||||
const pt = { x, y };
|
||||
const inside = (r) => x >= r.x && y >= r.y && x < r.x + r.w && y < r.y + r.h;
|
||||
const tag = { move: 'pointer-move', down: 'pointer-down', up: 'pointer-up' }[kind];
|
||||
if (!tag) throw new Error(`unknown pointer kind ${kind}`);
|
||||
let dirty = false;
|
||||
const popup = this.hit.popup;
|
||||
if (popup && inside(popup.rect)) {
|
||||
return this.#send(popup.widget, 'popup', { tag, val: { x: x - popup.rect.x, y: y - popup.rect.y } });
|
||||
}
|
||||
if (popup && kind === 'down' && !inside(popup.anchor)) {
|
||||
// Click outside the popup: tell its owner it lost focus, then let the
|
||||
// click fall through to whatever is underneath.
|
||||
dirty = this.#send(popup.widget, 'widget', { tag: 'focus-lost', val: undefined }) || dirty;
|
||||
}
|
||||
const target = this.hit.widgets.find((e) => inside(e.rect));
|
||||
if (this.hovered && this.hovered !== target?.widget) {
|
||||
dirty = this.#send(this.hovered, 'widget', { tag: 'pointer-leave', val: undefined }) || dirty;
|
||||
}
|
||||
this.hovered = target?.widget ?? null;
|
||||
if (target) {
|
||||
dirty = this.#send(target.widget, 'widget', { tag, val: { x: x - target.rect.x, y: y - target.rect.y } }) || dirty;
|
||||
}
|
||||
void pt;
|
||||
return dirty;
|
||||
}
|
||||
|
||||
key(k) {
|
||||
const popup = this.hit.popup;
|
||||
if (!popup) return false;
|
||||
return this.#send(popup.widget, 'popup', { tag: 'key-down', val: k });
|
||||
}
|
||||
}
|
||||
|
||||
function faultTile(rect, name) {
|
||||
const red = { r: 200, g: 40, b: 40, a: 255 };
|
||||
return [
|
||||
{ tag: 'fill-rect', val: { rect: { x: 0, y: 0, w: rect.w, h: rect.h }, color: red, radius: 4 } },
|
||||
{ tag: 'text', val: { origin: { x: 6, y: Math.floor(rect.h / 2) }, text: `${name} crashed`,
|
||||
style: { size: 12, color: { r: 255, g: 255, b: 255, a: 255 }, align: 'left', bold: true } } },
|
||||
];
|
||||
}
|
||||
|
||||
export { translate };
|
||||
@@ -0,0 +1,19 @@
|
||||
// Headless bring-up shared by the CLI and the tests.
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { join, dirname } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { Desktop } from './desktop.mjs';
|
||||
import { createPlatform } from './platform.mjs';
|
||||
import { tokensFromJson } from './theme.mjs';
|
||||
import { nodeLoader } from './loader-node.mjs';
|
||||
|
||||
export const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
|
||||
|
||||
export async function bootDesktop({ configPath = join(ROOT, 'config', 'desktop.json'), now, buildDir = join(ROOT, 'build') } = {}) {
|
||||
const config = JSON.parse(await readFile(configPath, 'utf8'));
|
||||
const apps = JSON.parse(await readFile(join(ROOT, 'config', 'apps.json'), 'utf8'));
|
||||
const themeJson = JSON.parse(await readFile(join(ROOT, 'config', 'themes', `${config.theme}.json`), 'utf8'));
|
||||
const platform = createPlatform({ apps, tokens: tokensFromJson(themeJson), now });
|
||||
const desktop = await new Desktop({ config, loader: nodeLoader(buildDir), platform }).start();
|
||||
return { desktop, platform, config };
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
|
||||
/** Loader for Node: reads build/ produced by scripts/build.sh. */
|
||||
export function nodeLoader(buildDir) {
|
||||
return async (name) => {
|
||||
const meta = JSON.parse(await readFile(join(buildDir, 'components', `${name}.meta.json`), 'utf8'));
|
||||
const dir = join(buildDir, 'jco', name);
|
||||
const mod = await import(pathToFileURL(join(dir, `${name}.js`)).href);
|
||||
const getCoreModule = async (p) => WebAssembly.compile(await readFile(join(dir, p)));
|
||||
return { meta, instantiate: (imports) => mod.instantiate(getCoreModule, imports) };
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
/** Loader for browsers: fetches the jco output under <base>/build/. */
|
||||
export function webLoader(base) {
|
||||
return async (name) => {
|
||||
const r = await fetch(`${base}/build/components/${name}.meta.json`);
|
||||
if (!r.ok) throw new Error(`cannot load ${name}.meta.json: HTTP ${r.status}`);
|
||||
const meta = await r.json();
|
||||
const dir = `${base}/build/jco/${name}`;
|
||||
const mod = await import(`${dir}/${name}.js`);
|
||||
const getCoreModule = async (p) => {
|
||||
const res = await fetch(`${dir}/${p}`);
|
||||
if (!res.ok) throw new Error(`cannot fetch ${p}: HTTP ${res.status}`);
|
||||
return WebAssembly.compile(await res.arrayBuffer());
|
||||
};
|
||||
return { meta, instantiate: (imports) => mod.instantiate(getCoreModule, imports) };
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
// Host-side implementations of the capability interfaces components may import.
|
||||
// This is where a native host would talk to the OS; here it is in-memory so the
|
||||
// desktop is deterministic and testable.
|
||||
|
||||
/** @param {{now?: () => Date, apps: any[], tokens: any}} opts */
|
||||
export function createPlatform({ now = () => new Date(), apps, tokens }) {
|
||||
const p = {
|
||||
tokens,
|
||||
apps,
|
||||
launches: [],
|
||||
now,
|
||||
launchable: new Set(apps.map((a) => a.id)),
|
||||
};
|
||||
/** Capability name -> WIT interface implementation (jco import shape). */
|
||||
p.interfaces = {
|
||||
theme: () => ({ getTokens: () => p.tokens }),
|
||||
clock: () => ({
|
||||
now() {
|
||||
const d = p.now();
|
||||
return {
|
||||
year: d.getFullYear(), month: d.getMonth() + 1, day: d.getDate(),
|
||||
hour: d.getHours(), minute: d.getMinutes(), second: d.getSeconds(), weekday: d.getDay(),
|
||||
};
|
||||
},
|
||||
}),
|
||||
'app-catalog': () => ({ listApps: () => p.apps }),
|
||||
'app-launch': () => ({
|
||||
launch(id) {
|
||||
if (!p.launchable.has(id)) return { tag: 'err', val: `unknown application: ${id}` };
|
||||
p.launches.push(id);
|
||||
console.log(`[host] launch ${id}`);
|
||||
return { tag: 'ok', val: undefined };
|
||||
},
|
||||
}),
|
||||
};
|
||||
return p;
|
||||
}
|
||||
|
||||
export const CAPABILITIES = ['theme', 'clock', 'app-catalog', 'app-launch'];
|
||||
@@ -0,0 +1,36 @@
|
||||
// Render-list helpers. A draw-op is a jco-lifted WIT variant: {tag, val}.
|
||||
|
||||
/** Translate a draw-op list by (dx, dy), returning new ops. */
|
||||
export function translate(ops, dx, dy) {
|
||||
return ops.map((op) => {
|
||||
const v = op.val;
|
||||
switch (op.tag) {
|
||||
case 'fill-rect':
|
||||
case 'stroke-rect':
|
||||
return { tag: op.tag, val: { ...v, rect: { ...v.rect, x: v.rect.x + dx, y: v.rect.y + dy } } };
|
||||
case 'line':
|
||||
return { tag: op.tag, val: { ...v, start: { x: v.start.x + dx, y: v.start.y + dy }, end: { x: v.end.x + dx, y: v.end.y + dy } } };
|
||||
case 'circle':
|
||||
return { tag: op.tag, val: { ...v, center: { x: v.center.x + dx, y: v.center.y + dy } } };
|
||||
case 'text':
|
||||
return { tag: op.tag, val: { ...v, origin: { x: v.origin.x + dx, y: v.origin.y + dy } } };
|
||||
case 'push-clip':
|
||||
return { tag: op.tag, val: { ...v, x: v.x + dx, y: v.y + dy } };
|
||||
case 'pop-clip':
|
||||
return op;
|
||||
default:
|
||||
throw new Error(`unknown draw-op tag: ${op.tag}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** Place a component's local-space ops at `rect`, clipped to it. */
|
||||
export function place(ops, rect) {
|
||||
return [
|
||||
{ tag: 'push-clip', val: { ...rect } },
|
||||
...translate(ops, rect.x, rect.y),
|
||||
{ tag: 'pop-clip', val: undefined },
|
||||
];
|
||||
}
|
||||
|
||||
export const colorCss = (c) => `rgba(${c.r},${c.g},${c.b},${(c.a / 255).toFixed(3)})`;
|
||||
@@ -0,0 +1,29 @@
|
||||
// Theme files use kebab-case keys and #rrggbb[aa] colours; components see the
|
||||
// WIT `theme.tokens` record (camelCase in jco).
|
||||
|
||||
const camel = (k) => k.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
|
||||
|
||||
export function parseColor(s) {
|
||||
const m = /^#([0-9a-fA-F]{6})([0-9a-fA-F]{2})?$/.exec(s);
|
||||
if (!m) throw new Error(`invalid colour "${s}" (expected #rrggbb or #rrggbbaa)`);
|
||||
const n = parseInt(m[1], 16);
|
||||
return { r: (n >> 16) & 255, g: (n >> 8) & 255, b: n & 255, a: m[2] ? parseInt(m[2], 16) : 255 };
|
||||
}
|
||||
|
||||
const PALETTE_KEYS = ['desktop-top', 'desktop-bottom', 'surface', 'surface-hover', 'surface-popup',
|
||||
'foreground', 'foreground-muted', 'accent', 'accent-foreground', 'border'];
|
||||
const NUM_KEYS = ['font-size', 'radius', 'spacing', 'panel-height'];
|
||||
|
||||
export function tokensFromJson(json) {
|
||||
const palette = {};
|
||||
for (const k of PALETTE_KEYS) {
|
||||
if (!(k in (json.palette ?? {}))) throw new Error(`theme "${json.name}": missing palette.${k}`);
|
||||
palette[camel(k)] = parseColor(json.palette[k]);
|
||||
}
|
||||
const out = { name: json.name, palette };
|
||||
for (const k of NUM_KEYS) {
|
||||
if (!Number.isInteger(json[k]) || json[k] < 0) throw new Error(`theme "${json.name}": ${k} must be a non-negative integer`);
|
||||
out[camel(k)] = json[k];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
// Host integration tests: instantiate the real MoonBit components (built by
|
||||
// scripts/build.sh) under the Node host and exercise the desktop end to end.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFile, stat, writeFile, mkdtemp } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { bootDesktop, ROOT } from '../src/headless.mjs';
|
||||
import { PermissionError } from '../src/desktop.mjs';
|
||||
import { tokensFromJson } from '../src/theme.mjs';
|
||||
|
||||
const NOW = new Date(2026, 10, 24, 14, 7, 37); // Tue 24 Nov 2026, local time
|
||||
const fixed = () => NOW;
|
||||
const texts = (ops) => ops.filter((o) => o.tag === 'text').map((o) => o.val.text);
|
||||
const configWith = async (mutate) => {
|
||||
const cfg = JSON.parse(await readFile(join(ROOT, 'config', 'desktop.json'), 'utf8'));
|
||||
mutate(cfg);
|
||||
const dir = await mkdtemp(join(tmpdir(), 'moonplasma-'));
|
||||
const p = join(dir, 'desktop.json');
|
||||
await writeFile(p, JSON.stringify(cfg));
|
||||
return p;
|
||||
};
|
||||
|
||||
test('boots shell + widgets and composes a frame', async () => {
|
||||
const { desktop } = await bootDesktop({ now: fixed });
|
||||
const f = desktop.frame();
|
||||
assert.deepEqual(f.screen, { w: 1280, h: 720 });
|
||||
assert.ok(f.ops.length > 50);
|
||||
const t = texts(f.ops);
|
||||
assert.ok(t.includes('14:07'), `clock text missing: ${t}`);
|
||||
assert.ok(t.includes('Tue 24 Nov'));
|
||||
assert.ok(t.includes('moon-plasma'));
|
||||
assert.ok(t.includes('Applications'));
|
||||
assert.equal(desktop.faults.length, 0);
|
||||
});
|
||||
|
||||
test('shell lays the panel out at the bottom, launcher left, clock right', async () => {
|
||||
const { desktop } = await bootDesktop({ now: fixed });
|
||||
const { layout } = desktop.frame();
|
||||
assert.deepEqual(layout.panel, { x: 0, y: 720 - 44, w: 1280, h: 44 });
|
||||
const byId = Object.fromEntries(layout.placements.map((p) => [p.id, p.rect]));
|
||||
assert.ok(byId.launcher.x < 20);
|
||||
assert.equal(byId.clock.x + byId.clock.w, 1280 - 5);
|
||||
for (const r of Object.values(byId)) {
|
||||
assert.ok(r.y >= layout.panel.y && r.y + r.h <= 720, 'widget inside the panel');
|
||||
}
|
||||
});
|
||||
|
||||
test('launcher: click opens popup, row click launches via host capability, popup closes', async () => {
|
||||
const { desktop, platform } = await bootDesktop({ now: fixed });
|
||||
desktop.frame();
|
||||
const l = desktop.hit.widgets.find((w) => w.widget.id === 'launcher').rect;
|
||||
assert.equal(desktop.hit.popup, null);
|
||||
assert.equal(desktop.pointer('down', l.x + 5, l.y + 5), true);
|
||||
const f = desktop.frame();
|
||||
assert.ok(desktop.hit.popup, 'popup is open');
|
||||
assert.ok(texts(f.ops).includes('Terminal'));
|
||||
const pr = desktop.hit.popup.rect;
|
||||
assert.ok(pr.y + pr.h <= 720 - 44, 'popup sits above the panel');
|
||||
// second row (52px header + 46px rows)
|
||||
desktop.pointer('move', pr.x + 20, pr.y + 52 + 46 + 5);
|
||||
desktop.pointer('down', pr.x + 20, pr.y + 52 + 46 + 5);
|
||||
assert.deepEqual(platform.launches, ['org.moonplasma.files']);
|
||||
desktop.frame();
|
||||
assert.equal(desktop.hit.popup, null, 'popup closed after launch');
|
||||
});
|
||||
|
||||
test('launcher: keyboard search narrows the list and Enter launches the first match', async () => {
|
||||
const { desktop, platform } = await bootDesktop({ now: fixed });
|
||||
desktop.frame();
|
||||
const l = desktop.hit.widgets.find((w) => w.widget.id === 'launcher').rect;
|
||||
desktop.pointer('down', l.x + 5, l.y + 5);
|
||||
desktop.frame();
|
||||
for (const ch of 'calc') desktop.key(ch);
|
||||
const f = desktop.frame();
|
||||
const t = texts(f.ops);
|
||||
assert.ok(t.includes('Calculator') && !t.includes('Terminal'));
|
||||
desktop.key('Enter');
|
||||
assert.deepEqual(platform.launches, ['org.moonplasma.calc']);
|
||||
});
|
||||
|
||||
test('clicking outside the popup dismisses it (focus-lost)', async () => {
|
||||
const { desktop } = await bootDesktop({ now: fixed });
|
||||
desktop.frame();
|
||||
const l = desktop.hit.widgets.find((w) => w.widget.id === 'launcher').rect;
|
||||
desktop.pointer('down', l.x + 5, l.y + 5);
|
||||
desktop.frame();
|
||||
assert.ok(desktop.hit.popup);
|
||||
desktop.pointer('down', 900, 200);
|
||||
desktop.frame();
|
||||
assert.equal(desktop.hit.popup, null);
|
||||
});
|
||||
|
||||
test('permissions: a component importing an ungranted capability is refused', async () => {
|
||||
const cfg = await configWith((c) => { c.panel[1].grants = ['theme']; }); // clock needs "clock"
|
||||
await assert.rejects(bootDesktop({ configPath: cfg }), (e) => {
|
||||
assert.ok(e instanceof PermissionError);
|
||||
assert.match(e.message, /clock-digital.*imports \[clock\]/);
|
||||
return true;
|
||||
});
|
||||
});
|
||||
|
||||
test('permissions: unknown capability names in config are rejected', async () => {
|
||||
const cfg = await configWith((c) => { c.panel[1].grants.push('filesystem'); });
|
||||
await assert.rejects(bootDesktop({ configPath: cfg }), /unknown capability "filesystem"/);
|
||||
});
|
||||
|
||||
test('a component cannot act in a role it does not export', async () => {
|
||||
const cfg = await configWith((c) => { c.panel[1].component = 'shell'; c.panel[1].grants = ['theme']; });
|
||||
await assert.rejects(bootDesktop({ configPath: cfg }), /does not export plasmoid/);
|
||||
});
|
||||
|
||||
test('hot-swap: clock-digital -> clock-binary at runtime, other components untouched', async () => {
|
||||
const files = ['shell', 'launcher', 'clock-digital', 'clock-binary'].map((n) => join(ROOT, 'build', 'components', `${n}.wasm`));
|
||||
const before = await Promise.all(files.map(async (f) => (await stat(f)).mtimeMs));
|
||||
const { desktop } = await bootDesktop({ now: fixed });
|
||||
const a = desktop.frame();
|
||||
assert.ok(texts(a.ops).includes('14:07'));
|
||||
const launcherInstance = desktop.widgets.find((w) => w.id === 'launcher').plasmoid;
|
||||
await desktop.swap('clock', 'clock-binary');
|
||||
const b = desktop.frame();
|
||||
assert.ok(!texts(b.ops).includes('14:07'));
|
||||
assert.ok(b.ops.filter((o) => o.tag === 'circle').length >= 20, 'binary clock dots drawn');
|
||||
assert.equal(desktop.widgets.find((w) => w.id === 'launcher').plasmoid, launcherInstance, 'launcher instance reused');
|
||||
const after = await Promise.all(files.map(async (f) => (await stat(f)).mtimeMs));
|
||||
assert.deepEqual(after, before, 'no component binary was rebuilt');
|
||||
});
|
||||
|
||||
test('config-level swap (desktop.binary-clock.json) picks the other implementation', async () => {
|
||||
const { desktop } = await bootDesktop({ configPath: join(ROOT, 'config', 'desktop.binary-clock.json'), now: fixed });
|
||||
assert.equal(desktop.widgets.find((w) => w.id === 'clock').componentName, 'clock-binary');
|
||||
assert.ok(desktop.frame().ops.some((o) => o.tag === 'circle' && o.val.filled));
|
||||
});
|
||||
|
||||
test('theme tokens flow through to components (live theme switch)', async () => {
|
||||
const { desktop, platform } = await bootDesktop({ now: fixed });
|
||||
const firstFill = (ops) => ops.find((o) => o.tag === 'fill-rect').val.color;
|
||||
const night = firstFill(desktop.frame().ops);
|
||||
const day = JSON.parse(await readFile(join(ROOT, 'config', 'themes', 'moon-day.json'), 'utf8'));
|
||||
platform.tokens = tokensFromJson(day);
|
||||
const light = firstFill(desktop.frame().ops);
|
||||
assert.notDeepEqual(night, light);
|
||||
assert.deepEqual(light, { r: 0xcf, g: 0xe3, b: 0xff, a: 255 }); // desktop-top of moon-day
|
||||
});
|
||||
|
||||
test('component faults are surfaced loudly and isolated to the widget', async () => {
|
||||
const { desktop, platform } = await bootDesktop({ now: fixed });
|
||||
platform.now = () => { throw new Error('rtc exploded'); };
|
||||
const f = desktop.frame(); // does not take the desktop down
|
||||
assert.equal(desktop.faults.length, 1);
|
||||
assert.match(desktop.faults[0].message, /clock-digital.*render/);
|
||||
assert.ok(texts(f.ops).includes('clock-digital crashed'), 'visible error tile');
|
||||
assert.ok(texts(f.ops).includes('Applications'), 'other widgets still render');
|
||||
});
|
||||
|
||||
test('build manifests match scripts/components.txt', async () => {
|
||||
const lines = (await readFile(join(ROOT, 'scripts', 'components.txt'), 'utf8')).split('\n')
|
||||
.filter((l) => l.trim() && !l.startsWith('#'));
|
||||
for (const l of lines) {
|
||||
const [name, world] = l.trim().split(/\s+/);
|
||||
const meta = JSON.parse(await readFile(join(ROOT, 'build', 'components', `${name}.meta.json`), 'utf8'));
|
||||
assert.equal(meta.world, world);
|
||||
assert.ok(meta.imports.includes('theme'));
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
// Canvas2D backend: rasterises a render list (draw-ops in screen coordinates).
|
||||
import { colorCss } from '../src/scene.mjs';
|
||||
|
||||
function roundRectPath(ctx, r, radius) {
|
||||
ctx.beginPath();
|
||||
const rad = Math.min(radius, r.w / 2, r.h / 2);
|
||||
if (rad > 0) ctx.roundRect(r.x, r.y, r.w, r.h, rad); else ctx.rect(r.x, r.y, r.w, r.h);
|
||||
}
|
||||
|
||||
export function paint(ctx, ops, screen) {
|
||||
ctx.clearRect(0, 0, screen.w, screen.h);
|
||||
let depth = 0;
|
||||
for (const op of ops) {
|
||||
const v = op.val;
|
||||
switch (op.tag) {
|
||||
case 'push-clip':
|
||||
ctx.save(); depth++;
|
||||
ctx.beginPath(); ctx.rect(v.x, v.y, v.w, v.h); ctx.clip();
|
||||
break;
|
||||
case 'pop-clip':
|
||||
if (depth === 0) throw new Error('pop-clip without push-clip');
|
||||
ctx.restore(); depth--;
|
||||
break;
|
||||
case 'fill-rect':
|
||||
ctx.fillStyle = colorCss(v.color); roundRectPath(ctx, v.rect, v.radius); ctx.fill();
|
||||
break;
|
||||
case 'stroke-rect':
|
||||
ctx.strokeStyle = colorCss(v.color); ctx.lineWidth = v.width;
|
||||
roundRectPath(ctx, { x: v.rect.x + 0.5, y: v.rect.y + 0.5, w: v.rect.w - 1, h: v.rect.h - 1 }, v.radius); ctx.stroke();
|
||||
break;
|
||||
case 'line':
|
||||
ctx.strokeStyle = colorCss(v.color); ctx.lineWidth = v.width;
|
||||
ctx.beginPath(); ctx.moveTo(v.start.x + 0.5, v.start.y + 0.5); ctx.lineTo(v.end.x + 0.5, v.end.y + 0.5); ctx.stroke();
|
||||
break;
|
||||
case 'circle':
|
||||
ctx.beginPath(); ctx.arc(v.center.x, v.center.y, v.radius, 0, Math.PI * 2);
|
||||
if (v.filled) { ctx.fillStyle = colorCss(v.color); ctx.fill(); }
|
||||
else { ctx.strokeStyle = colorCss(v.color); ctx.lineWidth = 1.5; ctx.stroke(); }
|
||||
break;
|
||||
case 'text':
|
||||
ctx.font = `${v.style.bold ? '600 ' : ''}${v.style.size}px system-ui, "DejaVu Sans", sans-serif`;
|
||||
ctx.fillStyle = colorCss(v.style.color);
|
||||
ctx.textAlign = v.style.align; ctx.textBaseline = 'middle';
|
||||
ctx.fillText(v.text, v.origin.x, v.origin.y);
|
||||
break;
|
||||
default: throw new Error(`unknown draw-op ${op.tag}`);
|
||||
}
|
||||
}
|
||||
if (depth !== 0) throw new Error(`unbalanced clip stack (${depth})`);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>moon-plasma</title>
|
||||
<style>
|
||||
html, body { margin: 0; background: #05070d; color: #aab; font: 12px/1.4 system-ui, sans-serif; }
|
||||
#screen { display: block; margin: 0 auto; max-width: 100vw; }
|
||||
#status { text-align: center; padding: 4px; font-family: monospace; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<canvas id="screen" width="1280" height="720"></canvas>
|
||||
<div id="status">loading components…</div>
|
||||
<script type="module" src="./main.mjs"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,46 @@
|
||||
import { Desktop } from '../src/desktop.mjs';
|
||||
import { createPlatform } from '../src/platform.mjs';
|
||||
import { tokensFromJson } from '../src/theme.mjs';
|
||||
import { webLoader } from '../src/loader-web.mjs';
|
||||
import { paint } from './canvas.mjs';
|
||||
|
||||
const base = new URL('../../', import.meta.url).href.replace(/\/$/, '');
|
||||
const q = new URLSearchParams(location.search);
|
||||
const getJson = async (p) => {
|
||||
const r = await fetch(`${base}/${p}`);
|
||||
if (!r.ok) throw new Error(`GET ${p}: HTTP ${r.status}`);
|
||||
return r.json();
|
||||
};
|
||||
|
||||
const status = document.getElementById('status');
|
||||
try {
|
||||
const config = await getJson(`config/${q.get('config') ?? 'desktop.json'}`);
|
||||
const apps = await getJson('config/apps.json');
|
||||
const tokens = tokensFromJson(await getJson(`config/themes/${q.get('theme') ?? config.theme}.json`));
|
||||
const fixed = q.get('time') ? new Date(q.get('time')) : null;
|
||||
const platform = createPlatform({ apps, tokens, now: fixed ? () => fixed : undefined });
|
||||
const desktop = await new Desktop({ config, loader: webLoader(base), platform }).start();
|
||||
|
||||
const canvas = document.getElementById('screen');
|
||||
canvas.width = desktop.screen.w; canvas.height = desktop.screen.h;
|
||||
const ctx = canvas.getContext('2d');
|
||||
const redraw = () => paint(ctx, desktop.frame().ops, desktop.screen);
|
||||
const pos = (e) => { const r = canvas.getBoundingClientRect(); return [Math.round((e.clientX - r.left) * canvas.width / r.width), Math.round((e.clientY - r.top) * canvas.height / r.height)]; };
|
||||
for (const [ev, kind] of [['pointermove', 'move'], ['pointerdown', 'down'], ['pointerup', 'up']]) {
|
||||
canvas.addEventListener(ev, (e) => { const [x, y] = pos(e); if (desktop.pointer(kind, x, y)) redraw(); });
|
||||
}
|
||||
window.addEventListener('keydown', (e) => {
|
||||
const k = e.key.length === 1 || ['Backspace', 'Enter', 'Escape'].includes(e.key) ? e.key : null;
|
||||
if (k && desktop.key(k)) { e.preventDefault(); redraw(); }
|
||||
});
|
||||
redraw();
|
||||
if (!fixed) setInterval(redraw, 1000);
|
||||
status.textContent = `${desktop.widgets.map((w) => `${w.id}=${w.componentName}`).join(' ')} | theme: ${platform.tokens.name}`;
|
||||
// Handle for automation / the browser console.
|
||||
window.moonPlasma = { desktop, platform, redraw, swap: async (id, c) => { await desktop.swap(id, c); redraw(); }, ready: true };
|
||||
} catch (e) {
|
||||
status.textContent = `ERROR: ${e.message}`;
|
||||
status.style.color = '#f66';
|
||||
window.moonPlasmaError = String(e.stack ?? e);
|
||||
throw e;
|
||||
}
|
||||
Reference in new issue
Block a user