WIT package, MoonBit components, Node host and tests (WIP)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e5548fc067
commit
e0bde1d150
125 files changed
+8681
No files matched your search
@@ -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,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;
|
||||
}
|
||||
Reference in new issue
Block a user