示例
实用示例,实时演示。
挑一个示例全屏打开,运行效果和源码并排呈现。
挑一个示例全屏打开,运行效果和源码并排呈现。
一个功能齐全的桌面,里面有文件、便笺、终端、计算器、计时器、看板、财务和日历。在保存于浏览器中的共享模拟磁盘上创建、整理文件夹,编辑便笺,运行 shell 命令。你可以直接用键盘在计算器里输入,点终端的任意位置聚焦输入行,在看板的列之间拖卡片,或者在财务电子表格里记一笔账,看图表跟着变,账本保存在 IndexedDB 里。移动、缩放、切换应用时,窗口都保留着自己的状态;运行中的计时器会用 into() 填进任务栏托盘。
// app.ts: the desktop. The windows are a list() over one array of plain // objects, placed by a dynamic style. Raising a window only changes its // z-index, so its element never moves and whatever is typed in it stays. // The layout leaves two regions: the tray in the top bar and a modal layer // over everything. A window fills them with into() from inside itself, and // what it puts there lives as long as the window does: close a running Timer // and its tray icon goes with it. Close an unsaved note and the dialog that // asks first is written in the window but drawn above the whole desktop. // // The shell follows GNOME: a top bar with Activities, the clock and the tray, // a dock of programs under the workspace, and an overview with a search, the // open windows and the app grid. // // Updates are scoped: every window carries scope(winScopeId(win)), and the // top bar, the dock, the overview, the clock and the context menu carry their own, so a // keystroke in one window (or a chart hover) re-evaluates that window alone. // A plain update() is left for the rare structural changes — opening or // closing a window, which rebuilds the windows list everywhere. import "nuclo"; import { calendar, files, finance, kanban, notes, openFile, PROGRAMS, settings, terminal, type Program } from "./programs.ts"; import { active, close, compact, focus, minimize, move, open, remove, requestClose, resize, setDesk, snap, toggleMaximize, unsnap, windows, winScopeId, type Frame, type Win, type Zone } from "./windows.ts"; import { icon } from "./icons.ts"; import { getEntry, loadDisk } from "./filesystem.ts"; import { ContextMenu, contextMenuKey, contextMenuLifecycle, dismissContextMenu, showContextMenu } from "./context-menu.ts"; import { appearance, loadAppearance, theme } from "./settings.ts"; import { s } from "./styles.ts"; let menuOpen = false; let search = ""; let clock = "--:--"; let date = ""; let booted = false; let diskLoaded = false; let snapZone: Zone = ""; // where the window being dragged would snap: drawn as a preview open(files); type Press = PointerEvent & { currentTarget: HTMLElement }; /** Re-evaluates one window — and, for manager changes, the task buttons too. */ const winUpdate = (win: Win, ...extra: string[]) => update(winScopeId(win), ...extra); /** Raises a window: its frame and the previously active frame, plus the taskbar. */ function raise(win: Win) { const prev = active(); focus(win); update(winScopeId(win), ...(prev && prev !== win ? [winScopeId(prev)] : []), "os-taskbar"); } /** Where a window sits. Its style binding returns this, and a drag writes the same thing straight to the element. */ const frame = (win: Win) => win.maximized ? { translate: "none", width: "100%", height: "100%" } : { translate: `${win.x}px ${win.y}px`, width: `${win.w}px`, height: `${win.h}px` }; // A drag handle. Pointer capture keeps the moves coming to the handle even // outside the window, for a mouse, a pen or a finger (touch-action: none). // A drag is the hot path: the moves are folded into one write per frame, and // that write goes to the frame's own style (a composited translate), so the // window's contents are not re-evaluated until the drag ends. // A title drag also snaps: let go at the top edge to maximize, at a side for // that half of the desktop, and pull a snapped window away to get it back. function drag(win: Win, from: () => [number, number], to: (a: number, b: number) => void, title = false) { let dx = 0, dy = 0, a = 0, b = 0, raf = 0, startX = 0, startY = 0, armed = false; let el: HTMLElement | null = null; let desk: DOMRect; const place = () => { raf = 0; if (!el) return; to(a, b); Object.assign(el.style, frame(win)); }; const preview = (zone: Zone) => { if (zone !== snapZone) { snapZone = zone; update("os-snap"); } }; return { onPointerDown: (e: Press) => { if (e.button !== 0 || compact() || (win.maximized && !title)) return; // on a phone-sized desktop windows fill the screen and stay put e.currentTarget.setPointerCapture(e.pointerId); el = e.currentTarget.closest<HTMLElement>("[data-os-window]")!; desk = el.parentElement!.getBoundingClientRect(); [a, b] = from(); dx = a - e.clientX; dy = b - e.clientY; startX = e.clientX; startY = e.clientY; armed = !title; // a title drag starts after a few pixels, so a click or a double-click never moves the window if (armed) el.dataset.moving = ""; }, onPointerMove: (e: Press) => { if (!el || !e.currentTarget.hasPointerCapture(e.pointerId)) return; if (!armed) { if (Math.hypot(e.clientX - startX, e.clientY - startY) < 5) return; armed = true; el.dataset.moving = ""; if (win.maximized || win.restore) { // Pulled off its snap: its own size again, still under the pointer. const rect = el.getBoundingClientRect(); const ratio = (e.clientX - rect.left) / rect.width; unsnap(win); dx = -desk.left - ratio * win.w; dy = rect.top - desk.top - e.clientY; el.classList.remove(...s.maximized.className.split(" ")); // its binding catches up when the drag ends } } a = e.clientX + dx; b = e.clientY + dy; raf ||= requestAnimationFrame(place); if (title) { const x = e.clientX - desk.left; const halves = desk.width >= 600; // two windows side by side need the room preview(e.clientY - desk.top <= 6 ? "max" : halves && x <= 6 ? "left" : halves && x >= desk.width - 6 ? "right" : ""); } }, // Released or cancelled: land the last move, then let the bindings catch up once. onLostPointerCapture: () => { if (!el) return; if (raf) { cancelAnimationFrame(raf); place(); } delete el.dataset.moving; el = null; snap(win, snapZone); preview(""); winUpdate(win); }, }; } /** A resize handle: the frame as the drag begins, then how far the pointer has gone. */ function edge(win: Win, dir: string) { let from: Frame = win; return drag(win, () => { from = { x: win.x, y: win.y, w: win.w, h: win.h }; return [0, 0]; }, (dx, dy) => resize(win, dir, from, dx, dy)); } function ConfirmDialog(win: Win) { return div( s.backdrop, div( s.dialog, { role: "alertdialog", "aria-modal": "true", "aria-label": "Discard changes?" }, { onKeyDown: (e) => { if (e.key === "Escape") { e.stopPropagation(); win.confirming = false; winUpdate(win); } if (e.key === "Tab") { const controls = e.currentTarget.querySelectorAll<HTMLButtonElement>("button"); if (e.shiftKey && document.activeElement === controls[0]) { e.preventDefault(); controls[1].focus(); } else if (!e.shiftKey && document.activeElement === controls[1]) { e.preventDefault(); controls[0].focus(); } } } }, h3("Discard changes?"), p(`${win.title} has text that is not saved.`), div( s.actions, button(s.btn, "Keep editing", { onMount: (el) => el.focus(), onClick: () => { win.confirming = false; winUpdate(win); } }), // Closing the window removes its list() row, and this dialog with it. button(s.btn, s.danger, "Discard", { onClick: () => { close(win); update(); } }), ), ), ); } function windowActions(win: Win) { return [ { label: "Bring to front", icon: win.program.icon, run: () => focus(win) }, { label: "Minimize", icon: "minimize", disabled: win.minimized, run: () => minimize(win) }, { label: win.maximized ? "Restore size" : "Maximize", icon: win.maximized ? "restore" : "maximize", run: () => { focus(win); toggleMaximize(win); } }, { label: "Close window", icon: "close", danger: true, run: () => requestClose(win) }, ]; } function desktopActions() { return [ { label: "Open Files", icon: "files", run: () => { open(files); } }, { label: "New note", icon: "notes", run: () => { open(notes); } }, { label: "Open Terminal", icon: "terminal", run: () => { open(terminal); } }, { label: "Open Kanban", icon: "kanban", run: () => { open(kanban); } }, { label: "Open Finance", icon: "finance", run: () => { open(finance); } }, { label: "Open Calendar", icon: "calendar", run: () => { open(calendar); } }, { label: "Change wallpaper", icon: "settings", run: () => { open(settings); } }, { label: "Show desktop", icon: "minimize", disabled: !windows.some((win) => !win.minimized), run: () => { for (const win of windows) minimize(win); } }, ]; } function WindowView(win: Win) { return section( s.win, scope(winScopeId(win)), { "data-os-window": String(win.id), "aria-label": () => win.title, class: () => cx(s.win, win === active() ? s.active : null, win.minimized ? s.minimized : null, win.maximized ? s.maximized : null, win.closing ? s.closing : null).className, style: () => ({ ...frame(win), zIndex: String(win.z) }), onPointerDown: () => raise(win), }, header( s.bar, { tabIndex: 0, "aria-haspopup": "menu", "aria-label": () => `${win.title} window controls`, onContextMenu: (e) => { focus(win); winUpdate(win, "os-taskbar"); showContextMenu(e, win.title, windowActions(win)); }, onKeyDown: (e) => { contextMenuKey(e, win.title, windowActions(win)); } }, div(s.title, { onDblClick: () => { toggleMaximize(win); winUpdate(win); } }, drag(win, () => [win.x, win.y], (x, y) => move(win, x, y), true), span(() => win.title), span(s.dirty, () => win.program.unsaved?.(win) ? "•" : "")), button(s.ctl, { title: "Minimize", "aria-label": "Minimize", onClick: () => { minimize(win); winUpdate(win, "os-taskbar"); } }, icon("minimize", 13)), button(s.ctl, s.ctlMax, { title: () => (win.maximized ? "Restore" : "Maximize"), "aria-label": "Maximize", "aria-pressed": () => String(win.maximized), onClick: () => { toggleMaximize(win); winUpdate(win); } }, icon("maximize", 11)), // Closing is structural: the windows list rebuilds, so one global update. button(s.ctl, { title: "Close", "aria-label": "Close", onClick: () => { requestClose(win); update(); } }, icon("close", 13)), ), div(s.body, win.program.view(win)), // Every side and corner resizes. The corners come last, so they sit over the sides. ...["n", "s", "e", "w", "nw", "ne", "sw"].map((dir) => div(s.edge, { "data-dir": dir }, edge(win, dir))), div(s.grip, edge(win, "se")), when(() => win.confirming, into("os-modal", ConfirmDialog(win))), // Closing: the frame fades out (see s.closing), then the window leaves the list. when(() => win.closing, span({ hidden: true }, on("mount", () => { const id = setTimeout(() => { remove(win); update(); }, 140); return () => clearTimeout(id); }))), ); } const running = (program: Program) => windows.filter((win) => win.program === program && !win.closing); const matches = () => Object.values(PROGRAMS).filter((program) => program.name.toLowerCase().includes(search.toLowerCase())); /** Opens or closes the Activities overview: the top bar's button and the overview itself. */ function overview(on: boolean) { if (on === menuOpen) return; menuOpen = on; search = ""; update("os-topbar", "os-overview"); } /** Opens a program in a new window. Structural: one global update. */ function launch(program: Program) { menuOpen = false; open(program); update(); } // One dock icon per program, with a dot under it while it runs. A click opens // the program, or brings its window forward; on the window already in front // it minimizes it, and with several windows it goes round them. function DockItem(program: Program) { const press = () => { const mine = running(program); if (!mine.length) return launch(program); const front = active(); const next = front && mine.includes(front) ? mine.filter((win) => win !== front).sort((a, b) => a.z - b.z)[0] : mine.sort((a, b) => b.z - a.z)[0]; if (next) focus(next); else minimize(front!); update(...[front, next].filter((win) => !!win).map((win) => winScopeId(win!)), "os-taskbar"); }; const actions = () => { const top = running(program).sort((a, b) => b.z - a.z)[0]; return [{ label: top ? "New window" : `Open ${program.name}`, icon: program.icon, run: () => { open(program); } }, ...(top ? windowActions(top) : [])]; }; return button( s.dockItem, { title: program.name, "aria-label": () => `${program.name}${running(program).length ? " · running" : ""}`, "aria-haspopup": "menu", "data-running": () => String(running(program).length > 0), "data-active": () => String(active()?.program === program), onClick: press, onContextMenu: (e) => showContextMenu(e, program.name, actions()), onKeyDown: (e) => { contextMenuKey(e, program.name, actions()); }, }, span(s.glyph, { "data-app": program.icon }, icon(program.icon, 22)), span(s.dockDot, { "aria-hidden": "true" }), ); } /** An app icon with its name: the phone's home screen and the grid in the overview. */ function Icon(program: Program) { const actions = () => [{ label: `Open ${program.name}`, icon: program.icon, run: () => { open(program); } }]; return button( s.icon, { "aria-haspopup": "menu", onContextMenu: (e) => showContextMenu(e, program.name, actions()), onKeyDown: (e) => { contextMenuKey(e, program.name, actions()); }, title: `Open ${program.name}`, // On a phone an app is one screen: tapping its icon goes back to it. Elsewhere it opens another window. onClick: () => { const top = compact() ? running(program).sort((a, b) => b.z - a.z)[0] : undefined; if (!top) return launch(program); menuOpen = false; focus(top); update(); }, }, span(s.glyph, { "data-app": program.icon }, icon(program.icon, 25)), program.name, ); } function Clock() { return time( s.clock, scope("os-clock"), on("mount", () => { const tick = () => { const now = new Date(); clock = now.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }); date = now.toLocaleDateString([], { month: "short", day: "numeric" }); update("os-clock"); }; tick(); const id = setInterval(tick, 30000); return () => clearInterval(id); }), span(() => date), span(() => clock), ); } // The Activities overview, over the workspace: a search, the open windows and // the app grid. Typing filters the apps, and Enter opens the first match. function Overview() { return div( s.overview, { role: "dialog", "aria-label": "Activities", onClick: (e) => { if (e.target === e.currentTarget) overview(false); } }, input(s.overviewSearch, { type: "search", "aria-label": "Search apps", placeholder: "Type to search", value: () => search, onMount: (el) => el.focus(), onInput: (e) => { search = e.currentTarget.value; update("os-overview"); }, onKeyDown: (e) => { if (e.key === "Enter" && matches()[0]) launch(matches()[0]); } }), when(() => !search && windows.some((win) => !win.closing), div(s.overviewWindows, list(() => windows.filter((win) => !win.closing), (win) => button(s.overviewWindow, { title: () => win.title, onClick: () => { menuOpen = false; focus(win); update(); } }, span(s.glyph, { "data-app": win.program.icon }, icon(win.program.icon, 18)), span(() => win.title)))), ), div(s.overviewApps, list(matches, Icon)), when(() => !matches().length, p(s.overviewEmpty, "No matching apps")), ); } export function Desktop() { return div( s.app, contextMenuLifecycle(), { tabIndex: -1, "data-wallpaper": () => appearance.wallpaper, "data-accent": () => appearance.accent, "data-os-theme": theme, "data-booted": () => String(booted), // false in the server's HTML: a phone keeps the windows hidden until it has put them away onContextMenu: (e) => { if (e.defaultPrevented) return; if ((e.target as Element).closest(".os-backdrop")) { e.preventDefault(); return; } const id = (e.target as Element).closest("[data-os-window]")?.getAttribute("data-os-window"); const win = windows.find((win) => String(win.id) === id); showContextMenu(e, win?.title ?? "Desktop", win ? windowActions(win) : desktopActions()); }, onKeyDown: (e) => { if (e.key === "Escape" && menuOpen) { e.stopPropagation(); overview(false); } if (e.key !== "ContextMenu" && !(e.shiftKey && e.key === "F10")) return; if ((e.target as Element).closest(".os-backdrop")) { e.preventDefault(); return; } const id = (e.target as Element).closest("[data-os-window]")?.getAttribute("data-os-window"); const win = windows.find((win) => String(win.id) === id); contextMenuKey(e, win?.title ?? "Desktop", win ? windowActions(win) : desktopActions()); }, }, on("mount", () => { if (!diskLoaded) { loadDisk(); diskLoaded = true; } loadAppearance(); // With the "auto" theme the desktop follows the page, then the system: watch both. const system = matchMedia("(prefers-color-scheme: dark)"); const repaint = () => update(); const page = new MutationObserver(repaint); system.addEventListener("change", repaint); page.observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme"] }); update(); return () => { system.removeEventListener("change", repaint); page.disconnect(); }; }), // The top bar: Activities, the clock, and the tray, where programs put // their own icons with into("os-tray", ...). header( s.topbar, scope("os-topbar"), button(s.topButton, { "aria-expanded": () => String(menuOpen), onClick: () => { dismissContextMenu(); overview(!menuOpen); } }, "Activities"), Clock(), div(s.tray, region({ id: "os-tray", type: "stack" }), button(s.topButton, { title: "Settings", "aria-label": "Settings", onClick: () => launch(settings) }, icon("settings", 15))), ), div( s.desk, on("mount", (el) => { const sizes = new ResizeObserver(() => { if (!el.clientWidth) return; // hidden while a source tab is showing: keep the windows as they are setDesk(el.clientWidth, el.clientHeight); if (!booted) { const welcome = getEntry("welcome"); if (welcome) { openFile(welcome); const win = windows.at(-1)!; move(win, el.clientWidth - win.w - 24, 36); } // A phone starts on its home screen: the apps wait in the dock. if (compact()) for (const win of windows) minimize(win); booted = true; } update(); }); sizes.observe(el); return () => sizes.disconnect(); }), { tabIndex: 0, "aria-haspopup": "menu", "aria-label": "Desktop workspace", onContextMenu: (e) => { if ((e.target as Element).closest("[data-os-window], .os-icon")) return; showContextMenu(e, "Desktop", desktopActions()); }, onKeyDown: (e) => { if (e.target === e.currentTarget) contextMenuKey(e, "Desktop", desktopActions()); } }, div(s.wallpaper, { "aria-hidden": "true" }, div(s.orbit), div(s.orbit, s.orbitTwo)), div(s.desktopHeading, strong("A little room to work."), span("Your files. Your ideas. Your pace.")), // The home screen of a phone-sized desktop; a wider one keeps its apps in the dock. div(s.icons, ...Object.values(PROGRAMS).map(Icon)), list(() => windows, WindowView), // After the windows, one layer under the one being dragged. div(s.snap, scope("os-snap"), { "aria-hidden": "true", "data-zone": () => snapZone, style: () => ({ zIndex: String((active()?.z ?? 1) - 1) }) }), div(scope("os-overview"), when(() => menuOpen, Overview())), ), // The dock: every program, and the grid that opens the overview. footer( s.taskbar, scope("os-taskbar"), nav(s.dock, { "aria-label": "Dock" }, ...Object.values(PROGRAMS).map(DockItem), span(s.dockSeparator, { "aria-hidden": "true" }), button(s.dockItem, { title: "Show apps", "aria-label": "Show apps", onClick: () => { dismissContextMenu(); overview(!menuOpen); } }, span(s.dockGrid, icon("grid", 20))), ), ), // The modal layer, over the desktop and the dock. The context menu // list runs inside its own wrapper, so its scope stays out of the windows. div(scope("os-context-menu"), ContextMenu()), region({ id: "os-modal", type: "stack" }), ); }
// windows.ts: the window manager. A window is a plain object in one array, // and every operation is a few assignments on it. Focus raises a window by // handing it the next z-index, not by moving it to the end of the array: the // list() that draws the windows never moves an element, so a textarea keeps // its text, its caret and its focus. Nothing here knows about the UI. import type { Program } from "./programs.ts"; export interface Win<S = unknown> { id: number; program: Program<S>; title: string; x: number; y: number; w: number; h: number; // px, inside the desktop z: number; // the highest is on top minimized: boolean; maximized: boolean; confirming: boolean; // asking whether to throw away unsaved work closing: boolean; // on its way out: the desktop lets it fade, then calls remove() restore: [w: number, h: number] | null; // its own size, kept while it is snapped to half the desktop state: S; // the program's state lives on its window, so it outlives the view } const MIN = { w: 300, h: 220 }; export const windows: Win[] = []; const desk = { w: 960, h: 520 }; // the desktop's size: a guess on the server, measured in the browser let topZ = 0; // the highest z-index handed out so far let nextId = 1; const clamp = (v: number, max: number) => Math.round(Math.max(0, Math.min(v, max))); // whole pixels keep text sharp /** A phone-sized desktop: every window fills it, like an app on a phone (see the 600px container queries in styles.ts). */ export const compact = () => desk.w <= 600; /** The topmost window that is not minimized. */ export const active = () => windows.reduce<Win | null>((a, w) => (!w.minimized && !w.closing && (!a || w.z > a.z) ? w : a), null); export function open<S>(program: Program<S>): Win<S> { const step = (windows.length % 6) * 28; // cascade: each new window a little lower and to the right const [w, h] = program.size; const win: Win<S> = { id: nextId++, program, title: program.name, x: 0, y: 0, w: Math.max(1, Math.min(w, desk.w - 16)), h: Math.max(1, Math.min(h, desk.h - 16)), z: ++topZ, minimized: false, maximized: false, confirming: false, closing: false, restore: null, state: program.init(), }; move(win, 40 + step, 24 + step); windows.push(win); return win; } /** Starts closing it. It stays in the array while it fades out; remove() takes it away. */ export function close(win: Win) { win.confirming = false; win.closing = true; } export function remove(win: Win) { const index = windows.indexOf(win); if (index !== -1) windows.splice(index, 1); } /** Closes it, unless its program has unsaved work: then it asks first. */ export function requestClose(win: Win) { if (win.program.unsaved?.(win)) win.confirming = true; else close(win); } /** Raises it, restoring it if it was minimized. The array order never changes. */ export function focus(win: Win) { win.minimized = false; if (win.z !== topZ) win.z = ++topZ; } /** * The update scope id of a window's element. The desktop tags each window * with scope(winScopeId(win)), so update(winScopeId(win)) re-evaluates that * window and nothing else — other windows, the taskbar and the desktop stay * untouched. Programs use it for their own keystrokes, ticks and drags, and * the window manager adds "os-taskbar" when the task buttons need it too. */ export const winScopeId = (win: Win) => `os-win-${win.id}`; /** The scope ids of every window running `program`, for data its windows share. */ export const scopesOf = (program: Program) => windows.filter((w) => w.program === program).map(winScopeId); export function minimize(win: Win) { win.minimized = true; } export function toggleMaximize(win: Win) { win.maximized = !win.maximized; } export function move(win: Win, x: number, y: number) { win.x = clamp(x, desk.w - win.w); win.y = clamp(y, desk.h - win.h); } export type Zone = "" | "max" | "left" | "right"; /** Drop a window on an edge: the top maximizes it, a side gives it that half of the desktop. */ export function snap(win: Win, zone: Zone) { if (!zone) return; if (zone === "max") { win.maximized = true; return; } win.restore ??= [win.w, win.h]; win.maximized = false; win.w = Math.round(desk.w / 2); win.h = desk.h; win.x = zone === "left" ? 0 : desk.w - win.w; win.y = 0; } /** Pulled off its edge: its own size again. The caller places it. */ export function unsnap(win: Win) { win.maximized = false; if (win.restore) [win.w, win.h] = win.restore; win.restore = null; } export type Frame = Pick<Win, "x" | "y" | "w" | "h">; /** * Resizes from any side. `dir` names the edges that follow the pointer ("n", * "se", ...), `from` is the frame when the drag began and dx/dy how far the * pointer has gone since. The opposite edges stay where they were. */ export function resize(win: Win, dir: string, from: Frame, dx: number, dy: number) { win.restore = null; // sized by hand: this is its own size now const right = from.x + from.w; const bottom = from.y + from.h; if (dir.includes("e")) win.w = Math.round(Math.min(desk.w - from.x, Math.max(MIN.w, from.w + dx))); if (dir.includes("s")) win.h = Math.round(Math.min(desk.h - from.y, Math.max(MIN.h, from.h + dy))); if (dir.includes("w")) { win.x = Math.round(Math.max(0, Math.min(from.x + dx, right - MIN.w))); win.w = right - win.x; } if (dir.includes("n")) { win.y = Math.round(Math.max(0, Math.min(from.y + dy, bottom - MIN.h))); win.h = bottom - win.y; } } /** The desktop changed size: every window shrinks and moves back inside it. */ export function setDesk(w: number, h: number) { desk.w = w; desk.h = h; for (const win of windows) { win.w = Math.min(win.w, w); win.h = Math.min(win.h, h); move(win, win.x, win.y); } }
// programs.ts: what runs in the windows. A program is a plain object: a name, // an icon, a default size, init() for the state of a new window, and a view // of that state. The state is kept on the window, so leaving the example and // coming back builds the views again around the same note, sum, shell // history and board. The Timer reaches outside its window: while it runs, it // puts its countdown in the top bar's tray with into(). import "nuclo"; import { focus, open, windows, winScopeId, type Win } from "./windows.ts"; import { contextMenuKey, showContextMenu } from "./context-menu.ts"; import { icon } from "./icons.ts"; import { available, children, createEntry, emptyTrash, entries, fmtCount, fmtSize, getEntry, moveEntry, pathOf, renameEntry, resolvePath, restoreEntry, sizeOf, trashEntry, writeEntry, type Entry } from "./filesystem.ts"; import { kanban } from "./kanban.ts"; import { calendar } from "./calendar.ts"; import { finance } from "./finance.ts"; import { appearance, setAppearance, settings } from "./settings.ts"; import { s } from "./styles.ts"; export { kanban, calendar, finance, settings }; export interface Program<S = unknown> { name: string; icon: string; size: [w: number, h: number]; init(): S; view(win: Win<S>): NodeModLike<"div">; unsaved?(win: Win<S>): boolean; // while true, closing the window asks first } interface Note { text: string; saved: string; file: string; name: string; error: string } const unsaved = (win: Win<Note>) => win.state.text !== win.state.saved; function saveNote(win: Win<Note>, copy = false) { const note = win.state; try { if (!note.file || copy) { const file = createEntry(available("documents") ? "documents" : "root", note.name, "file"); note.file = file.id; writeEntry(file.id, note.text); } else writeEntry(note.file, note.text, note.saved); note.saved = note.text; note.error = ""; win.title = getEntry(note.file)!.name; } catch (error) { note.error = (error as Error).message; } update(); // rare, and cross-window: the new file shows in Files, the new title in the taskbar } export function openFile(entry: Entry) { if (entry.kind !== "file" || !available(entry.id)) return; const existing = windows.find((w) => w.program === notes && (w.state as Note).file === entry.id); if (existing) { focus(existing); return; } const win = open(notes); Object.assign(win.state, { file: entry.id, name: entry.name, text: entry.content, saved: entry.content }); win.title = entry.name; } export const notes: Program<Note> = { name: "Notes", icon: "notes", size: [380, 360], init: () => ({ text: "", saved: "", file: "", name: "Untitled.txt", error: "" }), unsaved, view: (win) => div(s.notes, div(s.toolbar, input(s.input, { "aria-label": "File name for new note or copy", title: "Name for a new note or Save copy", value: win.state.name, onInput: (e) => { win.state.name = e.currentTarget.value; } }), button(s.btn, s.primary, "Save", { onClick: () => saveNote(win) }), button(s.btn, "Save copy", { onClick: () => saveNote(win, true) }), ), textarea(s.textarea, { "aria-label": "Note", placeholder: "A little room for your thoughts…", value: () => win.state.text, onInput: (e) => { win.state.text = e.currentTarget.value; update(winScopeId(win)); }, onKeyDown: (e) => { if ((e.ctrlKey || e.metaKey) && e.key === "s") { e.preventDefault(); saveNote(win); } } }), when(() => !!win.state.error, p(s.error, { role: "alert" }, () => win.state.error)), div(s.foot, span(() => unsaved(win) ? "Unsaved changes" : win.state.file ? "All changes saved" : "New note · save to Documents"), span(() => `${win.state.text.length} characters`)), ), }; interface Explorer { folder: string; selected: string; search: string; action: string; name: string; destination: string; error: string; layout: string; sort: "name" | "modified" | "size"; desc: boolean; trail: string[]; at: number } const HOME = { id: "root", name: "Home" }; const TRASH = { id: "trash", name: "Trash" }; const fmtWhen = (t: number) => !t ? "—" : new Date(t).toDateString() === new Date().toDateString() ? new Date(t).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }) : new Date(t).toLocaleDateString([], { month: "short", day: "numeric" }); const fmtEntrySize = (entry: Entry) => entry.kind === "folder" ? fmtCount(children(entry.id).length) : fmtSize(sizeOf(entry)); export const files: Program<Explorer> = { name: "Files", icon: "files", size: [660, 420], init: () => ({ folder: "documents", selected: "", search: "", action: "", name: "", destination: "root", error: "", layout: "list", sort: "name", desc: false, trail: ["documents"], at: 0 }), view: (win) => { const state = win.state; const refresh = () => update(winScopeId(win)); // files updates stay in this window // The folders visited are a trail with a cursor, like a browser's history: Back and Forward move the cursor. const navigate = (folder: string, record = true) => { if (record && folder !== state.folder) { state.trail.splice(state.at + 1, Infinity, folder); state.at = state.trail.length - 1; } Object.assign(state, { folder, selected: "", search: "", action: "", error: "" }); refresh(); }; const travel = (step: number) => { const to = state.trail[state.at + step]; if (to === undefined) return; state.at += step; navigate(to, false); }; const isTrash = () => state.folder === "trash"; const trashed = () => entries.filter((e) => e.trashed); const weight = (e: Entry) => state.sort === "modified" ? e.modified : e.kind === "folder" ? children(e.id).length : sizeOf(e); const rows = () => (isTrash() ? trashed() : available(state.folder) ? children(state.folder) : []) .filter((e) => e.name.toLowerCase().includes(state.search.toLowerCase())) .sort((a, b) => Number(b.kind === "folder") - Number(a.kind === "folder") || (state.sort === "name" ? a.name.localeCompare(b.name) : weight(a) - weight(b)) * (state.desc ? -1 : 1) || a.name.localeCompare(b.name)); const selected = () => rows().find((entry) => entry.id === state.selected); // The path as buttons: Home, then each folder down to this one. const crumbs = () => { if (isTrash()) return [TRASH]; const path: { id: string; name: string }[] = []; for (let e = getEntry(state.folder); e; e = getEntry(e.parent)) path.unshift(e); return [HOME, ...path]; }; const perform = (fn: () => void) => { try { fn(); state.error = ""; state.action = ""; } catch (e) { state.error = (e as Error).message; } refresh(); }; const start = (action: string) => { state.action = action; state.name = action === "rename" ? selected()?.name ?? "" : action === "file" ? "Untitled.txt" : "New folder"; state.error = ""; refresh(); }; const trash = () => perform(() => { trashEntry(state.selected); state.selected = ""; }); const sortBy = (key: Explorer["sort"]) => { state.desc = state.sort === key ? !state.desc : false; state.sort = key; refresh(); }; // Opening a note (or another window) changes the window list: one global update. const activate = (entry: Entry) => { if (isTrash()) return; if (entry.kind === "folder") navigate(entry.id); else { openFile(entry); update(); } }; const folderActions = () => isTrash() ? [ { label: "Empty Trash", icon: "trash", danger: true, disabled: !trashed().length, run: () => start("empty") }, ] : [ { label: "New folder", icon: "files", disabled: !available(state.folder), run: () => start("folder") }, { label: "New note", icon: "notes", disabled: !available(state.folder), run: () => start("file") }, { label: state.layout === "list" ? "View as grid" : "View as list", icon: "grid", run: () => { state.layout = state.layout === "list" ? "grid" : "list"; refresh(); } }, { label: "Open in Terminal", icon: "terminal", disabled: !available(state.folder), run: () => { open(terminal).state.cwd = state.folder; update(); } }, ]; const entryActions = (entry: Entry) => { state.selected = entry.id; return isTrash() ? [ { label: "Restore", icon: "restore", run: () => perform(() => { restoreEntry(entry.id); state.selected = ""; }) }, ] : [ { label: "Open", icon: entry.kind === "folder" ? "files" : "notes", run: () => activate(entry) }, { label: "Rename", icon: "notes", run: () => start("rename") }, { label: "Move to folder", icon: "files", run: () => start("move") }, { label: "Move to Trash", icon: "trash", danger: true, run: trash }, ]; }; const column = (key: Explorer["sort"], text: string, ...mods: NodeModLike<"button">[]) => button(s.fileHeadCell, ...mods, { title: `Sort by ${text.toLowerCase()}`, "aria-pressed": () => String(state.sort === key), onClick: () => sortBy(key) }, text, span(() => state.sort === key ? (state.desc ? " ↓" : " ↑") : "")); return div(s.explorer, aside(s.sidebar, span(s.sidebarTitle, "Workspace"), ...[["root", "Home", "grid"], ["documents", "Documents", "notes"], ["projects", "Projects", "files"], ["trash", "Trash", "trash"]].map(([id, label, glyph]) => button(s.sideItem, { "aria-label": label, title: label, "aria-current": () => state.folder === id ? "page" : "false", onClick: () => navigate(id) }, icon(glyph, 17), span(label), id === "trash" ? span(s.sideCount, () => String(trashed().length || "")) : null)), p(s.diskHint, "Simulated disk", br(), "Private to this browser"), ), div(s.fileMain, div(s.toolbar, button(s.btn, s.iconBtn, { "aria-label": "Back", title: "Back", disabled: () => state.at === 0, onClick: () => travel(-1) }, icon("back", 16)), button(s.btn, s.iconBtn, { "aria-label": "Forward", title: "Forward", disabled: () => state.at >= state.trail.length - 1, onClick: () => travel(1) }, icon("forward", 16)), button(s.btn, s.iconBtn, { "aria-label": "Parent folder", title: "Parent folder", disabled: () => state.folder === "root" || isTrash(), onClick: () => navigate(getEntry(state.folder)?.parent ?? "root") }, icon("up", 16)), nav(s.crumbs, { "aria-label": "Path" }, list(crumbs, (crumb) => button(s.crumb, { "aria-current": () => crumb.id === state.folder ? "page" : "false", onClick: () => navigate(crumb.id) }, () => crumb.name))), button(s.btn, s.iconBtn, { "aria-label": "Toggle file layout", title: () => state.layout === "list" ? "View as grid" : "View as list", onClick: () => { state.layout = state.layout === "list" ? "grid" : "list"; refresh(); } }, icon("grid", 16)), ), div(s.toolbar, input(s.input, { type: "search", "aria-label": "Search files", placeholder: () => isTrash() ? "Search Trash" : "Search this folder", value: () => state.search, onInput: (e) => { state.search = e.currentTarget.value; refresh(); } }), when(isTrash, button(s.btn, s.danger, { disabled: () => !trashed().length, onClick: () => start("empty") }, "Empty Trash")) .else(button(s.btn, { onClick: () => start("folder") }, "New folder"), button(s.btn, s.primary, { onClick: () => start("file") }, "New note")), ), when(() => !!state.action, form(s.inlineForm, { onSubmit: (e) => { e.preventDefault(); perform(() => { if (state.action === "rename") renameEntry(state.selected, state.name); else if (state.action === "move") moveEntry(state.selected, state.destination); else if (state.action === "empty") { emptyTrash(); state.selected = ""; } else { const entry = createEntry(state.folder, state.name, state.action === "folder" ? "folder" : "file"); state.selected = entry.id; } }); } }, when(() => state.action === "move", select(s.input, { "aria-label": "Destination folder", value: () => state.destination, onChange: (e) => { state.destination = e.currentTarget.value; } }, option({ value: "root" }, "Home"), list(() => entries.filter((e) => e.kind === "folder" && available(e.id)), (e) => option({ value: e.id }, () => pathOf(e.id))))), when(() => state.action === "empty", span(s.inlineText, () => `Delete ${fmtCount(trashed().length)} for good? This cannot be undone.`)), when(() => state.action !== "move" && state.action !== "empty", input(s.input, { "aria-label": "Item name", value: () => state.name, onMount: (el) => { el.focus(); el.select(); }, onInput: (e) => { state.name = e.currentTarget.value; } })), button(s.btn, { type: "submit", class: () => cx(s.btn, state.action === "empty" ? s.danger : s.primary).className }, () => state.action === "rename" ? "Rename" : state.action === "move" ? "Move" : state.action === "empty" ? "Delete" : "Create"), button(s.btn, { type: "button", onClick: () => { state.action = ""; state.error = ""; refresh(); } }, "Cancel"), )), when(() => !!state.error, p(s.error, { role: "alert" }, () => state.error)), // Click a column to sort by it; click it again to turn the order around. div(s.fileHead, { class: () => cx(s.fileHead, state.layout === "grid" ? s.hidden : null).className }, column("name", "Name", s.fileHeadName), column("modified", "Modified", s.fileWhen), column("size", "Size", s.fileSize)), div(s.fileList, { tabIndex: 0, "aria-haspopup": "menu", "aria-label": "Folder contents", onContextMenu: (e) => showContextMenu(e, isTrash() ? "Trash" : pathOf(state.folder), folderActions()), class: () => cx(s.fileList, state.layout === "grid" ? s.fileGrid : null).className, // Arrows walk the selection, Enter opens it (on the row), F2 renames, Delete moves it to Trash. onKeyDown: (e) => { if (e.target === e.currentTarget && contextMenuKey(e, isTrash() ? "Trash" : pathOf(state.folder), folderActions())) return; const all = rows(); const index = all.findIndex((entry) => entry.id === state.selected); const step = ({ ArrowDown: 1, ArrowRight: 1, ArrowUp: -1, ArrowLeft: -1 } as Record<string, number>)[e.key]; if (step) { const next = Math.max(0, Math.min(all.length - 1, index + step)); if (!all[next]) return; e.preventDefault(); state.selected = all[next].id; refresh(); e.currentTarget.querySelectorAll<HTMLElement>(".os-file-row")[next]?.focus(); } else if (index >= 0 && !isTrash() && (e.key === "Delete" || e.key === "F2")) { e.preventDefault(); if (e.key === "F2") start("rename"); else trash(); } } }, list(rows, (entry) => button(s.fileRow, { "aria-haspopup": "menu", onContextMenu: (e) => showContextMenu(e, entry.name, entryActions(entry)), "aria-pressed": () => String(state.selected === entry.id), // A finger has no double-click: tapping the selected item again opens it. onClick: () => { if (state.selected === entry.id && matchMedia("(pointer: coarse)").matches) activate(entry); else { state.selected = entry.id; refresh(); } }, onDblClick: () => activate(entry), onKeyDown: (e) => { if (e.key === "ContextMenu" || (e.shiftKey && e.key === "F10")) { contextMenuKey(e, entry.name, entryActions(entry)); return; } if (e.key === "Enter") { e.preventDefault(); activate(entry); } } }, span(s.fileIcon, icon(entry.kind === "folder" ? "files" : "notes", 25)), span(s.fileName, () => entry.name), span(s.fileMeta, s.fileWhen, () => fmtWhen(entry.modified)), span(s.fileMeta, s.fileSize, () => fmtEntrySize(entry)), )), when(() => !rows().length, div(s.empty, icon(isTrash() ? "trash" : "files", 32), strong(() => state.search ? "No matching files" : isTrash() ? "Trash is empty" : "This folder is empty"), p(() => state.search ? "Try another name." : isTrash() ? "Items you remove can be restored here." : "Create a folder or your first note."))), when(() => !isTrash() && !available(state.folder), button(s.btn, "Return home", { onClick: () => navigate("root") })), ), div(s.fileActions, span(s.selection, () => { const entry = selected(); return entry ? `${entry.name} · ${fmtEntrySize(entry)}${entry.modified ? ` · ${fmtWhen(entry.modified)}` : ""}` : fmtCount(rows().length); }), when(() => !!selected() && !isTrash(), button(s.btn, "Open", { onClick: () => activate(selected()!) }), button(s.btn, "Rename", { onClick: () => start("rename") }), button(s.btn, "Move", { onClick: () => start("move") }), button(s.btn, s.iconBtn, { "aria-label": "Move to Trash", title: "Move to Trash", onClick: trash }, icon("trash", 16)), ), when(() => !!selected() && isTrash(), button(s.btn, s.primary, "Restore", { onClick: () => perform(() => { restoreEntry(state.selected); state.selected = ""; }) })), ), ), ); }, }; interface Calc { shown: string; acc: number; op: string; fresh: boolean } // fresh: the next digit starts a new number const OPS: Record<string, (a: number, b: number) => number> = { "+": (a, b) => a + b, "−": (a, b) => a - b, "×": (a, b) => a * b, "÷": (a, b) => a / b }; const KEYS = [..."789÷456×123−C0.+="]; const cleared = (): Calc => ({ shown: "0", acc: 0, op: "", fresh: true }); // The keyboard reaches the same press() as the buttons: digits and "." type, // + - * / are the operators, Enter (or =) equals, Escape (or Delete, c) clears. function calcKey(key: string): string | null { if (/^[0-9.]$/.test(key)) return key; if (key === "+" || key === "-" || key === "*" || key === "/") return { "+": "+", "-": "−", "*": "×", "/": "÷" }[key]!; if (key === "Enter" || key === "=") return "="; if (key === "Escape" || key === "Delete" || key === "Backspace" || key === "c" || key === "C") return "C"; return null; } function press(c: Calc, key: string) { if (key === "C") Object.assign(c, cleared()); else if (key === "=" || key in OPS) { // Left to right, like a pocket calculator: 2 + 3 × 4 = 20. if (c.op && !c.fresh) c.shown = String(+OPS[c.op](c.acc, +c.shown).toPrecision(12)); c.acc = +c.shown; c.op = key === "=" ? "" : key; c.fresh = true; } else if (key !== "." || c.fresh || !c.shown.includes(".")) { c.shown = c.fresh || c.shown === "0" ? (key === "." ? "0." : key) : c.shown + key; c.fresh = false; } } export const calculator: Program<Calc> = { name: "Calculator", icon: "calculator", size: [250, 330], init: cleared, view: (win) => div(s.calc, { tabIndex: 0, "aria-label": "Calculator. Type on your keyboard.", onKeyDown: (e) => { const key = calcKey(e.key); if (!key) return; e.preventDefault(); press(win.state, key); update(winScopeId(win)); }, onMount: (el) => el.focus() }, output(s.display, () => win.state.shown), div(s.keys, ...KEYS.map((key) => button(cx(s.key, key === "=" ? s.primary : null), key, { onClick: () => { press(win.state, key); update(winScopeId(win)); } }))), p(s.calcHint, "Type with the keyboard · Enter = · Esc clears"), ), }; const mmss = (t: number) => `${String(Math.floor(t / 60)).padStart(2, "0")}:${String(t % 60).padStart(2, "0")}`; export const timer: Program<{ left: number; running: boolean }> = { name: "Timer", icon: "timer", size: [280, 210], init: () => ({ left: 60, running: false }), view: (win) => { const t = win.state; // The countdown is drawn twice: in the window and, while it runs, in the // top bar's tray — so a tick refreshes this window and the top bar scope. const tick = () => update(winScopeId(win), "os-topbar"); return div( s.timer, // The window owns the interval: closing it, or leaving the example, stops it. on("mount", () => { const id = setInterval(() => { if (!t.running) return; t.running = --t.left > 0; // stops at zero tick(); }, 1000); return () => clearInterval(id); }), output(s.countdown, () => mmss(t.left)), div( s.row, button(s.btn, s.primary, () => (t.running ? "Pause" : "Start"), { disabled: () => t.left === 0, onClick: () => { t.running = !t.running; tick(); } }), button(s.btn, "+1 min", { onClick: () => { t.left += 60; tick(); } }), button(s.btn, "Reset", { onClick: () => { Object.assign(t, timer.init()); tick(); } }), ), // Written here, drawn in the top bar. It goes when the timer stops or this window closes. when(() => t.running, into("os-tray", button(s.trayItem, { title: "Show the timer", onClick: () => { focus(win); update(winScopeId(win), "os-taskbar"); } }, icon("timer", 13), () => mmss(t.left)))), ); }, }; interface Line { kind: "in" | "out" | "err"; text: string; cwd?: string } interface Shell { lines: Line[]; cwd: string; history: string[]; cursor: number } const print = (shell: Shell, text: string, kind: Line["kind"] = "out") => { shell.lines.push({ kind, text }); if (shell.lines.length > 500) shell.lines.splice(0, shell.lines.length - 500); // a scrollback, not an archive }; const HELP = [ ["ls [path]", "list a folder"], ["cd <folder>", "go to a folder"], ["pwd", "where you are"], ["cat <file>", "print a file"], ["mkdir <name>", "new folder"], ["touch <name>", "new empty file"], ["echo <text> > <file>", "write a file"], ["mv <path> <to>", "move or rename"], ["rm <path>", "move to Trash"], ["open <app or file>", "open in a window"], ["apps", "list the apps"], ["windows", "list open windows"], ["theme [mode]", "auto, light or dark"], ["history", "past commands"], ["date", "the time"], ["clear", "empty the screen"], ]; const COMMANDS: Record<string, (args: string[], shell: Shell) => string | void> = { help: () => `${HELP.map(([usage, what]) => `${usage.padEnd(22)}${what}`).join("\n")}\n\nTab completes · ↑ ↓ recall · Ctrl+L clears · Ctrl+C cancels\nQuote names with spaces. rm moves items to Trash.`, pwd: (_, shell) => pathOf(shell.cwd), ls: ([path = "."], shell) => { const id = resolvePath(path, shell.cwd); if (!id) throw new Error("Folder not found."); if (getEntry(id)?.kind === "file") return getEntry(id)!.name; return children(id).map((e) => e.name + (e.kind === "folder" ? "/" : "")).join(" ") || "(empty folder)"; }, cd: ([path = "/"], shell) => { const id = resolvePath(path, shell.cwd); if (!id || (id !== "root" && getEntry(id)?.kind !== "folder")) throw new Error("Folder not found."); shell.cwd = id; }, cat: ([path = ""], shell) => { const file = getEntry(resolvePath(path, shell.cwd) ?? ""); if (!file || file.kind !== "file") throw new Error("File not found."); return file.content || "(empty file)"; }, mkdir: ([name = ""], shell) => { createAtPath(name, shell.cwd, "folder"); }, touch: ([name = ""], shell) => { if (!resolvePath(name, shell.cwd)) createAtPath(name, shell.cwd, "file"); }, rm: ([path = ""], shell) => { const id = resolvePath(path, shell.cwd); if (!path || !id || id === "root") throw new Error("Choose a file or folder to move to Trash."); trashEntry(id); return "Moved to Trash. Restore it in Files."; }, // Into a folder when the target is one; otherwise the last part of the target is the new name. mv: ([from = "", to = ""], shell) => { const id = resolvePath(from, shell.cwd); if (!to || !id || id === "root") throw new Error("Use mv <path> <folder or new name>."); const target = resolvePath(to, shell.cwd); if (target && (target === "root" || getEntry(target)?.kind === "folder")) { moveEntry(id, target); return; } if (target) throw new Error("An item with that name already exists."); const slash = to.lastIndexOf("/"); const parent = slash < 0 ? shell.cwd : resolvePath(to.slice(0, slash) || "/", shell.cwd); if (!parent) throw new Error("Folder not found."); if (parent !== getEntry(id)!.parent) moveEntry(id, parent); renameEntry(id, to.slice(slash + 1)); }, echo: (args, shell) => { const redirect = args.indexOf(">"); if (redirect < 0) return args.join(" "); const path = args[redirect + 1]; if (!path || args.length !== redirect + 2) throw new Error("Use echo <text> > <file>."); const id = resolvePath(path, shell.cwd) ?? createAtPath(path, shell.cwd, "file").id; writeEntry(id, args.slice(0, redirect).join(" ") + "\n"); }, apps: () => Object.keys(PROGRAMS).join(" "), date: () => new Date().toString(), clear: (_, shell) => { shell.lines.length = 0; }, history: (_, shell) => shell.history.map((line, i) => `${String(i + 1).padStart(3)} ${line}`).join("\n"), theme: ([mode]) => { if (!mode) return `theme: ${appearance.theme}`; if (!["auto", "light", "dark"].includes(mode)) throw new Error("Use theme auto, light or dark."); setAppearance("theme", mode); }, open: ([name = ""], shell) => { if (PROGRAMS[name.toLowerCase()]) { open(PROGRAMS[name.toLowerCase()]); return; } const entry = getEntry(resolvePath(name, shell.cwd) ?? ""); if (!entry) throw new Error('App or file not found. Try "apps" or "ls".'); if (entry.kind === "file") openFile(entry); else Object.assign(open(files).state, { folder: entry.id, trail: [entry.id] }); }, windows: () => windows.map((w) => `#${w.id} ${w.title}${w.minimized ? " minimized" : ""}`).join("\n"), }; function createAtPath(path: string, cwd: string, kind: Entry["kind"]) { const slash = path.lastIndexOf("/"); const parent = slash < 0 ? cwd : resolvePath(path.slice(0, slash) || "/", cwd); if (!parent) throw new Error("Parent folder not found."); return createEntry(parent, path.slice(slash + 1), kind); } /** Runs one command line: the line is echoed with its prompt, then what it printed or the error. */ function run(shell: Shell, line: string) { if (!available(shell.cwd)) shell.cwd = "root"; shell.lines.push({ kind: "in", text: line, cwd: pathOf(shell.cwd) }); if (!line.trim()) return; shell.history.push(line); shell.cursor = shell.history.length; try { const tokens = line.match(/"[^"\n]*"|'[^'\n]*'|[^\s]+/g) ?? []; const [name, ...args] = tokens.map((token) => token.replace(/^(["'])(.*)\1$/, "$2")); if (!COMMANDS[name]) throw new Error(`${name}: command not found. Try help.`); const out = COMMANDS[name](args, shell); if (out) print(shell, out); } catch (e) { print(shell, (e as Error).message, "err"); } } /** * Tab: finishes the word being typed — a command first, then a path (or an * app, after "open"). With several matches it goes as far as they agree and * prints them. */ function complete(shell: Shell, value: string) { const start = value.lastIndexOf(" ") + 1; const head = value.slice(0, start); const word = value.slice(start); const base = head.trim() ? word.slice(0, word.lastIndexOf("/") + 1) : ""; let options = Object.keys(COMMANDS).map((name) => name + " "); if (head.trim()) { const folder = resolvePath(base || ".", shell.cwd); // ponytail: names with spaces are skipped, since a word ends at a space here. Quote-aware completion if it matters. options = (folder ? children(folder) : []).filter((e) => !e.name.includes(" ")).map((e) => e.name + (e.kind === "folder" ? "/" : " ")); if (head.trim() === "open" && !base) options.push(...Object.keys(PROGRAMS).map((name) => name + " ")); } const typed = word.slice(base.length).toLowerCase(); const hits = options.filter((option) => option.toLowerCase().startsWith(typed)); if (!hits.length) return value; let common = hits[0]; for (const hit of hits) while (!hit.toLowerCase().startsWith(common.toLowerCase())) common = common.slice(0, -1); if (hits.length > 1) print(shell, hits.map((hit) => hit.trim()).join(" ")); return head + base + common; } export const terminal: Program<Shell> = { name: "Terminal", icon: "terminal", size: [560, 360], init: () => ({ lines: [{ kind: "out", text: 'Nuclo shell · your local workspace\nType "help" for commands. Tab completes.' }], cwd: "documents", history: [], cursor: 0 }), view: (win) => { const shell = win.state; const refresh = () => update(winScopeId(win)); const set = (field: HTMLInputElement, value: string) => { field.value = value; field.setSelectionRange(value.length, value.length); }; // What the keys do, by name: the keyboard and the touch keys under the screen both come here. const act = (field: HTMLInputElement, action: string) => { if (action === "tab") set(field, complete(shell, field.value)); else if (action === "up" || action === "down") { shell.cursor = Math.max(0, Math.min(shell.history.length, shell.cursor + (action === "up" ? -1 : 1))); set(field, shell.history[shell.cursor] ?? ""); } else if (action === "clear") shell.lines.length = 0; else if (action === "cancel") { shell.lines.push({ kind: "in", text: `${field.value}^C`, cwd: pathOf(shell.cwd) }); shell.cursor = shell.history.length; set(field, ""); } else if (action === "enter") { run(shell, field.value); set(field, ""); update(); return; } // a command may touch files, windows or the theme: everything updates refresh(); }; const field = (from: HTMLElement) => from.closest(".os-term-wrap")!.querySelector<HTMLInputElement>("input")!; return div(s.termWrap, // Click anywhere — on the output, the prompt, the blank space — and the // input line takes the keystrokes. Only a click on the input itself keeps // the caret where it is. div(s.term, { title: "Click anywhere to type", onClick: (e) => { const input = field(e.currentTarget); if (e.target === input) return; input.focus(); set(input, input.value); } }, div( list(() => shell.lines, (line) => line.kind === "in" ? div(s.termIn, span(s.termPath, line.cwd), span(s.termSigil, " $ "), line.text) : pre(line.kind === "err" ? s.termErr : null, line.text)), div(s.prompt, span(s.termPath, () => pathOf(shell.cwd)), span(s.termSigil, "$"), input({ "aria-label": "Command", autocomplete: "off", autocapitalize: "off", spellcheck: false, onMount: (el) => el.focus(), onKeyDown: (e) => { const ctrl = e.ctrlKey && !e.shiftKey && !e.altKey && !e.metaKey; // Tab completes only once something is typed, so an empty prompt still lets the keyboard tab away. const action = e.key === "Enter" ? "enter" : e.key === "Tab" && !e.shiftKey && e.currentTarget.value ? "tab" : e.key === "ArrowUp" ? "up" : e.key === "ArrowDown" ? "down" : ctrl && e.key === "l" ? "clear" : ctrl && e.key === "c" ? "cancel" : ""; if (!action) return; e.preventDefault(); act(e.currentTarget, action); } })), ), ), // A phone keyboard has no Tab or arrows: these stand in for them. They keep the focus on the input. div(s.termKeys, { onMouseDown: (e) => e.preventDefault() }, ...[["tab", "tab"], ["up", "↑"], ["down", "↓"], ["cancel", "^C"], ["clear", "clear"]].map(([action, text]) => button({ type: "button", "aria-label": action, onClick: (e) => { const input = field(e.currentTarget); act(input, action); input.focus(); } }, text))), ); }, }; export const about: Program<null> = { name: "About", icon: "about", size: [360, 310], init: () => null, view: () => div(s.about, h3("Welcome to Nuclo OS"), p("A small desktop with room to work. Files, Notes and Terminal share one simulated disk; the Kanban board and the Calendar keep their own notes, and Finance keeps a ledger in IndexedDB."), p("Open an app from the dock, or from Activities in the top bar. Drag a title to move its window, drop it on an edge to snap it, or double-click to maximize. Settings has a light and a dark theme."), button(s.btn, "Explore your files", { onClick: () => { open(files); update(); } }), h3("Running apps"), ol(list(() => [...windows].sort((a, b) => b.z - a.z), (w) => li(button(s.runningApp, { onClick: () => { focus(w); update(); } }, icon(w.program.icon, 16), () => w.title, span(() => w.minimized ? "Minimized" : "Open"))))), ), }; export const PROGRAMS: Record<string, Program> = { files, notes, terminal, calculator, timer, kanban, finance, calendar, settings, about };
// settings.ts: how the desktop looks, and the Settings window that changes it. // The look is three plain strings — a theme, an accent and a wallpaper — that // the desktop root turns into attributes; styles.ts does the rest with custom // properties. Every change is saved in this browser and is global: one // update() repaints every window, the taskbar and the wallpaper. import "nuclo"; import type { Program } from "./programs.ts"; import { winScopeId } from "./windows.ts"; import { entries, fmtCount, fmtSize, resetDisk, sizeOf, storageStatus } from "./filesystem.ts"; import { s } from "./styles.ts"; const OPTIONS = { theme: ["auto", "light", "dark"], accent: ["blue", "green", "purple", "orange"], wallpaper: ["adwaita", "dusk", "slate"] } as const; type Key = keyof typeof OPTIONS; const KEY = "nuclo-desktop-appearance-v1"; export const appearance: Record<Key, string> = { theme: "auto", accent: "blue", wallpaper: "adwaita" }; /** Reads the saved look, once, in the browser. Anything unknown is ignored. */ export function loadAppearance() { try { const saved = { wallpaper: localStorage.getItem("nuclo-desktop-wallpaper"), ...JSON.parse(localStorage.getItem(KEY) ?? "{}") }; for (const key of Object.keys(OPTIONS) as Key[]) if ((OPTIONS[key] as readonly string[]).includes(saved[key])) appearance[key] = saved[key]; } catch {} } export function setAppearance(key: Key, value: string) { appearance[key] = value; try { localStorage.setItem(KEY, JSON.stringify(appearance)); } catch {} update(); // the attributes live on the desktop root, outside any window } /** * The theme in effect. "auto" follows the page when it has a theme of its own * (the docs set <html data-theme>), then the system. On the server it stays * "auto", and a prefers-color-scheme rule in styles.ts covers the first paint. */ export function theme(): string { if (appearance.theme !== "auto" || typeof matchMedia !== "function") return appearance.theme; const page = document.documentElement?.dataset?.theme; return page === "dark" || page === "light" ? page : matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"; } const label = (value: string) => value[0].toUpperCase() + value.slice(1); /** One choice of a setting: a button that is pressed while it is the current one. */ const choice = (key: Key, value: string, ...mods: NodeModLike<"button">[]) => button({ "aria-pressed": () => String(appearance[key] === value), title: label(value), onClick: () => setAppearance(key, value) }, ...mods); const usage = () => { const live = entries.filter((e) => !e.trashed); return `${fmtCount(live.length)} · ${fmtSize(live.reduce((sum, e) => sum + sizeOf(e), 0))}`; }; export const settings: Program<{ confirming: boolean }> = { name: "Settings", icon: "settings", size: [440, 500], init: () => ({ confirming: false }), view: (win) => { const confirm = (on: boolean) => { win.state.confirming = on; update(winScopeId(win)); }; return div(s.setPage, section(s.setGroup, h3("Appearance"), div(s.setCard, div(s.setRow, div(s.setLabel, strong("Theme"), span(() => appearance.theme === "auto" ? `Automatic · ${theme()} now` : `Always ${appearance.theme}`)), div(s.seg, { role: "group", "aria-label": "Theme" }, ...OPTIONS.theme.map((value) => choice("theme", value, s.segItem, label(value)))), ), div(s.setRow, div(s.setLabel, strong("Accent"), span("Buttons, selections and highlights")), div(s.setDots, { role: "group", "aria-label": "Accent" }, ...OPTIONS.accent.map((value) => choice("accent", value, s.setDot, { "data-accent": value, "aria-label": label(value) }))), ), div(s.setRow, s.setStack, div(s.setLabel, strong("Wallpaper"), span("The backdrop behind your windows")), div(s.setWalls, { role: "group", "aria-label": "Wallpaper" }, ...OPTIONS.wallpaper.map((value) => choice("wallpaper", value, s.setWall, { "data-wallpaper": value }, span(s.setWallArt, { "aria-hidden": "true" }), label(value)))), ), ), ), section(s.setGroup, h3("Storage"), div(s.setCard, div(s.setRow, div(s.setLabel, strong("Simulated disk"), span(() => storageStatus)), span(s.setValue, usage), ), div(s.setRow, div(s.setLabel, strong("Reset files"), span(() => win.state.confirming ? "Every file and folder will be erased. This cannot be undone." : "Erase everything and bring back the starter files")), when(() => win.state.confirming, div(s.row, button(s.btn, "Cancel", { onMount: (el) => el.focus(), onClick: () => confirm(false) }), button(s.btn, s.danger, "Erase", { onClick: () => { resetDisk(); win.state.confirming = false; update(); } })), ).else(button(s.btn, "Reset…", { onClick: () => confirm(true) })), ), ), ), p(s.setFoot, "Your settings and files stay in this browser. No real files on your device are changed."), ); }, };
// A simulated disk shared by Files, Notes and Terminal. Only browser-local data. export interface Entry { id: string; parent: string; name: string; kind: "folder" | "file"; content: string; modified: number; trashed: boolean } const KEY = "nuclo-desktop-disk-v1"; const seed = (): Entry[] => [ { id: "documents", parent: "root", name: "Documents", kind: "folder", content: "", modified: 0, trashed: false }, { id: "projects", parent: "root", name: "Projects", kind: "folder", content: "", modified: 0, trashed: false }, { id: "welcome", parent: "documents", name: "Welcome.txt", kind: "file", content: "Welcome to your workspace.\n\nMake yourself at home. Open Files to create folders and notes, or try the Terminal. Everything shares the same simulated disk.\n\nYour files stay in this browser between visits. Nothing is uploaded.\n\nA few things to try\n\n• Create a note in Documents, write something, and save.\n• Rename or move a file, then find it in Terminal.\n• Move a file to Trash and restore it.\n• Drag windows, double-click a title to maximize, or use the taskbar to switch apps.\n", modified: 0, trashed: false }, { id: "ideas", parent: "documents", name: "Ideas.txt", kind: "file", content: "A little room for big ideas.\n\n- A reading list\n- A weekend project\n- Something worth remembering\n", modified: 0, trashed: false }, { id: "readme", parent: "projects", name: "Readme.txt", kind: "file", content: "My projects\n\nStart with a folder. Make something good.\n", modified: 0, trashed: false }, ]; export const entries = seed(); export let storageStatus = "Saved in this browser"; export const getEntry = (id: string) => entries.find((entry) => entry.id === id); export function available(id: string): boolean { if (id === "root") return true; const entry = getEntry(id); return !!entry && !entry.trashed && available(entry.parent); } export const children = (parent: string) => entries.filter((entry) => entry.parent === parent && !entry.trashed).sort((a, b) => Number(b.kind === "folder") - Number(a.kind === "folder") || a.name.localeCompare(b.name)); export const pathOf = (id: string): string => id === "root" ? "/" : getEntry(id) ? `${pathOf(getEntry(id)!.parent).replace(/\/$/, "")}/${getEntry(id)!.name}` : "/"; export function resolvePath(path: string, cwd = "root") { let id = path.startsWith("/") ? "root" : cwd; for (const part of path.split("/").filter(Boolean)) { if (part === ".") continue; if (part === "..") { id = getEntry(id)?.parent ?? "root"; continue; } if (id !== "root" && getEntry(id)?.kind !== "folder") return undefined; const entry = children(id).find((entry) => entry.name === part); if (!entry || !available(entry.id)) return undefined; id = entry.id; } return available(id) ? id : undefined; } export function persist() { try { localStorage.setItem(KEY, JSON.stringify(entries)); storageStatus = "Saved in this browser"; } catch { storageStatus = "Browser storage unavailable · files stay for this session"; } } export function loadDisk() { try { const raw = localStorage.getItem(KEY); if (!raw) return; const saved: unknown = JSON.parse(raw); if (!Array.isArray(saved) || !saved.every((e) => e && typeof e.id === "string" && e.id !== "root" && typeof e.parent === "string" && typeof e.name === "string" && e.name.trim() && !/[\/\\]/.test(e.name) && ["file", "folder"].includes(e.kind) && typeof e.content === "string" && typeof e.modified === "number" && typeof e.trashed === "boolean")) throw new Error("Invalid disk"); const ids = new Set(saved.map((e) => e.id)); if (ids.size !== saved.length) throw new Error("Duplicate IDs"); for (const entry of saved) { const seen = new Set([entry.id]); let parent = entry.parent; while (parent !== "root") { const folder = saved.find((e) => e.id === parent); if (!folder || folder.kind !== "folder" || seen.has(parent)) throw new Error("Invalid folder tree"); seen.add(parent); parent = folder.parent; } if (saved.some((e) => e !== entry && !e.trashed && !entry.trashed && e.parent === entry.parent && e.name === entry.name)) throw new Error("Duplicate names"); } entries.splice(0, entries.length, ...saved); } catch { storageStatus = "Could not load saved disk · using starter files"; } } function validateName(parent: string, name: string, except?: string) { if (!name.trim() || name !== name.trim() || name === "." || name === ".." || /[\/\\\x00-\x1f]/.test(name) || name.length > 80) throw new Error("Use 1–80 characters without slashes or surrounding spaces."); if (!available(parent) || (parent !== "root" && getEntry(parent)?.kind !== "folder")) throw new Error("That folder is no longer available."); if (children(parent).some((entry) => entry.name === name && entry.id !== except)) throw new Error("An item with that name already exists."); } export function createEntry(parent: string, name: string, kind: Entry["kind"]) { validateName(parent, name); const entry: Entry = { id: crypto.randomUUID(), parent, name, kind, content: "", modified: Date.now(), trashed: false }; entries.push(entry); persist(); return entry; } export function renameEntry(id: string, name: string) { const entry = getEntry(id); if (!entry || !available(id)) throw new Error("That item is no longer available."); validateName(entry.parent, name, id); entry.name = name; persist(); } export function moveEntry(id: string, parent: string) { const entry = getEntry(id); if (!entry || !available(id)) throw new Error("That item is no longer available."); let ancestor = parent; while (ancestor !== "root") { if (ancestor === id) throw new Error("A folder cannot be moved inside itself."); ancestor = getEntry(ancestor)?.parent ?? "root"; } validateName(parent, entry.name, id); entry.parent = parent; persist(); } export function trashEntry(id: string) { const entry = getEntry(id); if (!entry || !available(id)) throw new Error("That item is no longer available."); entry.trashed = true; persist(); } /** Deletes everything in Trash for good, along with whatever is inside the folders there. */ export function emptyTrash() { const gone = (entry: Entry): boolean => entry.trashed || (entry.parent !== "root" && (!getEntry(entry.parent) || gone(getEntry(entry.parent)!))); entries.splice(0, entries.length, ...entries.filter((entry) => !gone(entry))); persist(); } /** Starts the disk over with the starter files. */ export function resetDisk() { entries.splice(0, entries.length, ...seed()); persist(); } export const sizeOf = (entry: Entry) => new TextEncoder().encode(entry.content).length; export const fmtCount = (n: number) => `${n} item${n === 1 ? "" : "s"}`; export const fmtSize = (bytes: number) => bytes < 1024 ? `${bytes} B` : `${(bytes / 1024).toFixed(1)} KB`; export function restoreEntry(id: string) { const entry = getEntry(id); if (!entry?.trashed) throw new Error("That item is not in Trash."); const parent = available(entry.parent) ? entry.parent : "root"; validateName(parent, entry.name, id); entry.parent = parent; entry.trashed = false; persist(); } export function writeEntry(id: string, content: string, expected?: string) { const entry = getEntry(id); if (!entry || entry.kind !== "file" || !available(id)) throw new Error("This file was moved to Trash. Restore it in Files before saving."); if (expected !== undefined && entry.content !== expected) throw new Error("This file changed in another window. Save a copy to keep your edits."); entry.content = content; entry.modified = Date.now(); persist(); }
// board.ts: the Kanban model for the desktop. Columns hold cards in plain // arrays, and every change is a few plain array operations on the same card // objects. The board is one shared, saved board: each change is written to // localStorage, and loadBoard() puts the saved board back on the next visit — // like the files on the simulated disk. export interface Card { id: number; title: string; priority: 1 | 2 | 3 } // 3 is urgent export interface Column { id: string; title: string; cards: Card[] } const KEY = "nuclo-desktop-board-v1"; let nextId = 1; const card = (title: string, priority: Card["priority"]): Card => ({ id: nextId++, title, priority }); const seed = (): Column[] => [ { id: "todo", title: "To do", cards: [card("Write the release notes", 3), card("Fix the flaky test", 2), card("Design the empty state", 1)] }, { id: "doing", title: "In progress", cards: [card("Ship the desktop", 2), card("Profile the list diff", 1)] }, { id: "done", title: "Done", cards: [card("Set up CI", 2), card("Pick a logo", 1)] }, ]; /** The board every Kanban window reads. loadBoard() may replace it with the saved one. */ export const columns: Column[] = seed(); let booted = false; /** Replaces the seed with the saved board, once, when the app starts in a browser. */ export function loadBoard() { if (booted) return; booted = true; try { const saved = localStorage.getItem(KEY); if (!saved) return; const parsed = JSON.parse(saved) as Column[]; const valid = (c: Column) => c && typeof c.id === "string" && typeof c.title === "string" && Array.isArray(c.cards) && c.cards.every((k) => k && typeof k.id === "number" && typeof k.title === "string"); if (!Array.isArray(parsed) || !parsed.every(valid)) return; nextId = parsed.flatMap((c) => c.cards).reduce((max, k) => Math.max(max, k.id), 0) + 1; columns.splice(0, columns.length, ...parsed); } catch {} } export function saveBoard() { try { localStorage.setItem(KEY, JSON.stringify(columns)); } catch {} } /** Starts the board over. */ export function resetBoard() { columns.splice(0, columns.length, ...seed()); saveBoard(); } export const columnOf = (c: Card) => columns.find((col) => col.cards.includes(c))!; /** Moves a card to `index` in `to`, from wherever it is now. */ export function moveCard(c: Card, to: Column, index = to.cards.length) { const from = columnOf(c); const at = from.cards.indexOf(c); from.cards.splice(at, 1); if (from === to && at < index) index--; to.cards.splice(index, 0, c); saveBoard(); } export function addCard(col: Column, title: string) { col.cards.unshift(card(title, 2)); saveBoard(); } export function removeCard(c: Card) { const cards = columnOf(c).cards; cards.splice(cards.indexOf(c), 1); saveBoard(); } export function cyclePriority(c: Card) { c.priority = c.priority === 3 ? 1 : ((c.priority + 1) as Card["priority"]); saveBoard(); } export function sortByPriority(col: Column) { col.cards.sort((a, b) => b.priority - a.priority); saveBoard(); }
// kanban.ts: the Kanban window. The model lives in board.ts, shared by every // window and saved after each change; this file is the view. Columns are a // list() of columns, cards a list() of each column's cards. Rows are matched // by identity, so dragging a card, sorting a column or renaming a card // splices or patches the same objects and the elements just move. Every // Kanban window shows the same board, so a change refreshes all of them; the // forms being typed in belong to their own window. import "nuclo"; import type { Program } from "./programs.ts"; import { addCard, columns, cyclePriority, loadBoard, moveCard, removeCard, resetBoard, saveBoard, sortByPriority, type Card, type Column } from "./board.ts"; import { scopesOf, type Win } from "./windows.ts"; import { s } from "./styles.ts"; interface Forms { adding: Column | null; // the column whose new-card form is open draft: string; // the title being typed in that form editing: Card | null; // the card whose title is being typed editDraft: string; } type KanbanWin = Win<Forms>; const PRIORITY = { 1: "low", 2: "normal", 3: "urgent" }; // One drag at a time, across every Kanban window: a card can be dropped into another one. let dragging: Card | null = null; let over: { win: KanbanWin; column: Column; index: number } | null = null; // where it would land /** The board is shared, so every Kanban window updates, and nothing else. */ const refresh = () => update(...scopesOf(kanban)); const isOver = (win: KanbanWin, column: Column, index: number) => over?.win === win && over.column === column && over.index === index; function setOver(win: KanbanWin, column: Column, index: number) { if (isOver(win, column, index)) return; over = { win, column, index }; refresh(); } function drop() { if (dragging && over) moveCard(dragging, over.column, over.index); dragging = over = null; refresh(); } function startEdit(forms: Forms, card: Card) { forms.editing = card; forms.editDraft = card.title; refresh(); } function commitEdit(forms: Forms, card: Card) { if (forms.editing !== card) return; const title = forms.editDraft.trim(); if (title) card.title = title; forms.editing = null; saveBoard(); refresh(); } function CardView(win: KanbanWin, card: Card, column: Column) { const forms = win.state; return div( s.kanbanCard, { draggable: true, tabIndex: 0 }, { class: () => cx(s.kanbanCard, card === dragging ? s.kanbanLifted : null, isOver(win, column, column.cards.indexOf(card)) ? s.kanbanBefore : null).className }, { onKeyDown: (e) => { if (e.key === "Enter" && e.target === e.currentTarget) startEdit(forms, card); }, onDragStart: (e) => { e.dataTransfer?.setData("text/plain", card.title); dragging = card; refresh(); }, onDragEnd: () => { dragging = over = null; refresh(); }, onDragOver: (e) => { e.preventDefault(); e.stopPropagation(); const below = e.offsetY > e.currentTarget.offsetHeight / 2; setOver(win, column, column.cards.indexOf(card) + (below ? 1 : 0)); }, }, div(s.kanbanCardHead, button(s.kanbanPriority, { title: "Change priority", class: () => cx(s.kanbanPriority, s[`kanbanP${card.priority}`]).className, onClick: () => { cyclePriority(card); refresh(); } }, () => PRIORITY[card.priority]), span(s.kanbanId, `#${card.id}`), ...([[-1, "←", "previous"], [1, "→", "next"]] as const).map(([step, arrow, where]) => { const to = columns[columns.indexOf(column) + step]; return button(s.kanbanIcon, s.kanbanMove, { title: `Move to the ${where} column`, "aria-label": `Move to the ${where} column`, disabled: !to, onClick: () => { moveCard(card, to); refresh(); } }, arrow); }), button(s.kanbanIcon, { title: "Move to top", "aria-label": "Move to top", onClick: () => { moveCard(card, column, 0); refresh(); } }, "↑"), button(s.kanbanIcon, { title: "Delete", "aria-label": "Delete", onClick: () => { removeCard(card); refresh(); } }, "×"), ), when(() => forms.editing === card, input(s.kanbanEdit, { "aria-label": "Card title", value: () => forms.editDraft, onMount: (el) => { el.focus(); el.select(); }, onInput: (e) => { forms.editDraft = e.currentTarget.value; }, onKeyDown: (e) => { if (e.key === "Enter") commitEdit(forms, card); else if (e.key === "Escape") { forms.editing = null; refresh(); } }, onBlur: () => { if (forms.editing === card) commitEdit(forms, card); } }), ).else(div(s.kanbanTitle, { title: "Double-click to edit", onDblClick: () => startEdit(forms, card) }, () => card.title)), ); } function ColumnView(win: KanbanWin, column: Column) { const forms = win.state; return section( s.kanbanColumn, { class: () => cx(s.kanbanColumn, isOver(win, column, column.cards.length) ? s.kanbanAfter : null).className }, { onDragOver: (e) => { e.preventDefault(); setOver(win, column, column.cards.length); }, onDragLeave: (e) => { if (!e.currentTarget.contains(e.relatedTarget as Node | null)) { over = null; refresh(); } }, onDrop: (e) => { e.preventDefault(); drop(); }, }, header(s.kanbanColumnHead, h3(column.title, span(s.kanbanCount, () => String(column.cards.length))), button(s.kanbanSmall, { title: "Sort by priority", onClick: () => { sortByPriority(column); refresh(); } }, "Sort"), button(s.kanbanSmall, { title: () => (forms.adding === column ? "Close the form" : "Add a task"), "aria-pressed": () => String(forms.adding === column), onClick: () => { forms.adding = forms.adding === column ? null : column; forms.draft = ""; refresh(); } }, "+ Add"), ), when(() => forms.adding === column, form(s.kanbanAdd, { onSubmit: (e) => { e.preventDefault(); if (forms.draft.trim()) { addCard(column, forms.draft.trim()); forms.draft = ""; forms.adding = null; } refresh(); } }, input(s.input, { "aria-label": "New task title", placeholder: "What needs to be done?", value: () => forms.draft, onMount: (el) => el.focus(), onInput: (e) => { forms.draft = e.currentTarget.value; }, onKeyDown: (e) => { if (e.key === "Escape") { forms.adding = null; refresh(); } } }), button(s.btn, s.primary, { type: "submit" }, "Add"), )), div(s.kanbanCards, list(() => column.cards, (card) => CardView(win, card, column)), when(() => !column.cards.length, p(s.kanbanEmpty, "Drop a task here.")), ), ); } export const kanban: Program<Forms> = { name: "Kanban", icon: "kanban", size: [660, 400], init: () => { loadBoard(); return { adding: null, draft: "", editing: null, editDraft: "" }; }, view: (win) => div(s.kanban, div(s.toolbar, strong(s.kanbanHeading, "Board"), span(s.kanbanHint, "Drag cards between columns · saved in this browser"), button(s.btn, "Reset", { title: "Start the board over", onClick: () => { resetBoard(); refresh(); } }), ), div(s.kanbanBoard, list(() => columns, (column) => ColumnView(win, column))), ), };
// calendar.ts: a month calendar for the desktop. The grid is plain Date math // over the window's state, and each day can carry a short note, kept in one // small object saved to localStorage — like the wallpaper and the board. import "nuclo"; import type { Program } from "./programs.ts"; import { winScopeId } from "./windows.ts"; import { icon } from "./icons.ts"; import { s } from "./styles.ts"; const KEY = "nuclo-desktop-calendar-v1"; const WEEKDAYS = ["Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"]; const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; // Hand-rolled (no Intl): the 42 day labels re-evaluate on every calendar update. const FULL_DAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; const keyOf = (year: number, month: number, day: number) => `${year}-${String(month + 1).padStart(2, "0")}-${String(day).padStart(2, "0")}`; const labelOf = (key: string) => { const [y, m, d] = key.split("-").map(Number); const date = new Date(y, m - 1, d); return `${FULL_DAYS[date.getDay()]}, ${MONTHS[m - 1]} ${d}`; }; let notes: Record<string, string> = {}; function loadNotes() { try { const saved = localStorage.getItem(KEY); if (saved) notes = JSON.parse(saved); } catch {} } const saveNotes = () => { try { localStorage.setItem(KEY, JSON.stringify(notes)); } catch {} }; interface CalState { year: number; month: number; selected: string } // month: 0-11, selected: "YYYY-MM-DD" export const calendar: Program<CalState> = { name: "Calendar", icon: "calendar", size: [360, 430], init: () => { loadNotes(); const now = new Date(); return { year: now.getFullYear(), month: now.getMonth(), selected: keyOf(now.getFullYear(), now.getMonth(), now.getDate()) }; }, view: (win) => { const state = win.state; const refresh = () => update(winScopeId(win)); // the calendar updates only its window const now = new Date(); const today = keyOf(now.getFullYear(), now.getMonth(), now.getDate()); const lead = (new Date(state.year, state.month, 1).getDay() + 6) % 7; // Monday-first const days = new Date(state.year, state.month + 1, 0).getDate(); const cells: ({ day: number; key: string } | null)[] = [ ...Array.from({ length: lead }, () => null), ...Array.from({ length: days }, (_, i) => ({ day: i + 1, key: keyOf(state.year, state.month, i + 1) })), ]; const moveMonth = (dir: number) => { const next = new Date(state.year, state.month + dir, 1); Object.assign(state, { year: next.getFullYear(), month: next.getMonth() }); refresh(); }; const goToday = () => { Object.assign(state, { year: now.getFullYear(), month: now.getMonth(), selected: today }); refresh(); }; return div(s.calendar, div(s.toolbar, button(s.btn, { "aria-label": "Previous month", onClick: () => moveMonth(-1) }, icon("back", 15)), strong(s.calMonth, () => `${MONTHS[state.month]} ${state.year}`), button(s.btn, { "aria-label": "Next month", onClick: () => moveMonth(1) }, icon("forward", 15)), button(s.btn, "Today", { onClick: goToday }), ), div(s.calGrid, ...WEEKDAYS.map((day) => span(s.calWeekday, day)), ...cells.map((cell) => cell ? button(s.calDay, { "aria-label": () => labelOf(cell.key), "aria-pressed": () => String(state.selected === cell.key), "aria-current": () => (cell.key === today ? "date" : "false"), class: () => cx(s.calDay, cell.key === today ? s.calToday : null).className, onClick: () => { state.selected = cell.key; refresh(); }, }, String(cell.day), when(() => !!notes[cell.key], span(s.calDot))) : span(s.calGap)), ), div(s.calNote, div(s.calNoteHead, strong(() => labelOf(state.selected)), button(s.btn, "Clear", { disabled: () => !notes[state.selected], onClick: () => { delete notes[state.selected]; saveNotes(); refresh(); } }), ), textarea(s.calInput, { "aria-label": "Note for the selected day", placeholder: "A note for this day…", value: () => notes[state.selected] ?? "", onInput: (e) => { const value = e.currentTarget.value; if (value) notes[state.selected] = value; else delete notes[state.selected]; saveNotes(); refresh(); } }), ), ); }, };
// money.ts: the Finance model. Transactions are plain objects in one array, // and every chart is a few reduce() calls over them. Pure: no DOM, no // storage, so it can be unit-tested and reused by the spreadsheet and the // charts alike. Amounts are plain numbers; a negative amount is spending. export interface Tx { id: number; date: string; description: string; category: string; amount: number } // "YYYY-MM-DD" export const CATEGORIES = ["Salary", "Freelance", "Housing", "Food", "Transport", "Utilities", "Health", "Fun", "Shopping", "Other"]; /** One fixed color per category, so the same slice is always the same color. */ export const CATEGORY_COLORS: Record<string, string> = { Salary: "#237556", Freelance: "#4a9d84", Housing: "#c25b4e", Food: "#d9a13b", Transport: "#4a7d9c", Utilities: "#6a4a94", Health: "#b0762f", Fun: "#d97b8f", Shopping: "#3b8a5e", Other: "#8a93a0", }; const MONTH_NAMES = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; // Hand-rolled number and date formatting: these run inside chart bindings on // every update, and Intl (toLocaleString / toLocaleDateString) builds a new // formatter per call — far too slow there. export const money = (n: number) => { const [whole, frac] = Math.abs(n).toFixed(2).split("."); return `${whole.replace(/\B(?=(\d{3})+(?!\d))/g, ",")}.${frac}`; }; export const signed = (n: number) => (n > 0 ? `+${money(n)}` : n < 0 ? `−${money(-n)}` : money(0)); /** "2026-10-12" → "Oct 12", with the year when it is not the current one. */ export function fmtDate(iso: string) { const [y, m, d] = iso.split("-").map(Number); return y === new Date().getFullYear() ? `${MONTH_NAMES[m - 1]} ${d}` : `${MONTH_NAMES[m - 1]} ${d}, ${y}`; } const monthKey = (d: Date) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`; // The demo ledger: six months of a small household, generated relative to // today so the charts always cover the recent past. Nothing is written here. let nextId = 1; const tx = (date: string, description: string, category: string, amount: number): Tx => ({ id: nextId++, date, description, category, amount }); export function seed(): Tx[] { const now = new Date(); const at = (monthsAgo: number, dayOfMonth: number) => { const d = new Date(now.getFullYear(), now.getMonth() - monthsAgo, Math.min(dayOfMonth, 28)); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`; }; const txs: Tx[] = []; const add = (monthsAgo: number, dayOfMonth: number, description: string, category: string, amount: number) => { if (monthsAgo === 0 && dayOfMonth > now.getDate()) return; // no future rows in the current month txs.push(tx(at(monthsAgo, dayOfMonth), description, category, amount)); }; for (let m = 5; m >= 0; m--) { add(m, 1, "Salary", "Salary", 4200); add(m, 3, "Rent", "Housing", -1500); add(m, 6, "Electricity", "Utilities", -(104 + m * 3)); add(m, 6, "Internet", "Utilities", -45); add(m, 9, "Groceries", "Food", -(290 + m * 9)); add(m, 12, "Transit pass", "Transport", -60); add(m, 15, "Dinner out", "Food", -85); add(m, 18, "Cinema", "Fun", -50); add(m, 20, "Groceries", "Food", -170); add(m, 22, "Clothes", "Shopping", m % 3 === 0 ? -120 : -60); add(m, 24, "Gym", "Health", -40); if (m % 2 === 0) add(m, 26, "Freelance work", "Freelance", 350); } return txs; } /** Newest first; the same objects, so a list() over it moves rows, not mounts. */ export const byDate = (txs: Tx[]) => [...txs].sort((a, b) => (a.date < b.date ? 1 : a.date > b.date ? -1 : b.id - a.id)); export interface Month { key: string; label: string; income: number; expense: number; net: number; balance: number } /** Income, spending and running balance for the last `count` months. */ export function monthly(txs: Tx[], count = 6): Month[] { const now = new Date(); const months: Month[] = []; for (let m = count - 1; m >= 0; m--) { const d = new Date(now.getFullYear(), now.getMonth() - m, 1); months.push({ key: monthKey(d), label: MONTH_NAMES[d.getMonth()], income: 0, expense: 0, net: 0, balance: 0 }); } const byKey = new Map(months.map((month) => [month.key, month])); let balance = 0; for (const t of byDate(txs).reverse()) { const month = byKey.get(t.date.slice(0, 7)); if (!month) { balance += t.amount; continue; } // older than the window: already earned if (t.amount >= 0) month.income += t.amount; else month.expense += -t.amount; month.net += t.amount; } for (const month of months) { balance += month.net; month.balance = balance; } return months; } export interface Slice { category: string; value: number; share: number } /** Spending grouped by category, biggest first. */ export function byCategory(txs: Tx[]): Slice[] { const sums = new Map<string, number>(); for (const t of txs) if (t.amount < 0) sums.set(t.category, (sums.get(t.category) ?? 0) + -t.amount); const total = [...sums.values()].reduce((a, b) => a + b, 0); return [...sums.entries()].map(([category, value]) => ({ category, value, share: total ? value / total : 0 })).sort((a, b) => b.value - a.value); } /** The whole ledger in three numbers. */ export function totals(txs: Tx[]) { let income = 0; let expense = 0; for (const t of txs) t.amount >= 0 ? (income += t.amount) : (expense += -t.amount); return { income, expense, balance: income - expense, count: txs.length }; } /** The current month in three numbers. */ export function monthTotals(txs: Tx[]) { const key = monthKey(new Date()); let income = 0; let expense = 0; for (const t of txs) if (t.date.slice(0, 7) === key) t.amount >= 0 ? (income += t.amount) : (expense += -t.amount); return { income, expense, net: income - expense }; }
// db.ts: a tiny IndexedDB wrapper for Finance. The ledger lives in one object // store, keyed by id; every edit is a put() or delete(). Nothing here touches // the DOM, and every call is a promise, so the views can await a load and // move on after a save. All access is guarded so the docs server can import // this module and render the page without a database. import type { Tx } from "./money.ts"; const DB = "nuclo-desktop-finance"; const STORE = "transactions"; export const supported = () => typeof indexedDB !== "undefined"; function open(): Promise<IDBDatabase> { return new Promise((resolve, reject) => { const req = indexedDB.open(DB, 1); req.onupgradeneeded = () => { const db = req.result; if (!db.objectStoreNames.contains(STORE)) db.createObjectStore(STORE, { keyPath: "id" }); }; req.onsuccess = () => resolve(req.result); req.onerror = () => reject(req.error ?? new Error("Could not open the database")); }); } function request(mode: IDBTransactionMode, run: (store: IDBObjectStore) => IDBRequest): Promise<any> { return open().then((db) => new Promise((resolve, reject) => { const tx = db.transaction(STORE, mode); const req = run(tx.objectStore(STORE)); req.onsuccess = () => resolve(req.result); req.onerror = () => reject(req.error ?? tx.error); tx.oncomplete = () => db.close(); })); } export const loadTxs = (): Promise<Tx[]> => request("readonly", (store) => store.getAll()); export const saveTx = (t: Tx): Promise<void> => request("readwrite", (store) => store.put(t)); export const deleteTx = (id: number): Promise<void> => request("readwrite", (store) => store.delete(id)); /** Wipes the store and writes a fresh set, for the demo Reset. */ export function replaceAll(txs: Tx[]): Promise<void> { return open().then((db) => new Promise((resolve, reject) => { const tx = db.transaction(STORE, "readwrite"); const store = tx.objectStore(STORE); store.clear(); for (const t of txs) store.put(t); tx.oncomplete = () => { db.close(); resolve(); }; tx.onerror = () => reject(tx.error); })); }
// charts.ts: hand-rolled SVG charts for Finance — a line/area chart with a // hover readout, grouped bars, and a donut. Each chart is one svgSvg() with // viewBox coordinates and width 100%, so it scales with the window. // // The desktop's update() re-evaluates function bindings, it does not rebuild // components — so every chart takes its data as a factory: the elements are // built once, and each data-driven attribute, label and text re-derives from // the factory on every update. That is how editing the ledger moves a chart // without rebuilding it. import "nuclo"; const TEXT = { "font-size": 9.5, "font-family": "ui-monospace, monospace" } as const; // --------------------------------------------------------------------------- // Line chart (with optional area fill, dots and labels). The hover marker is // one shared state: moving over a chart updates its index and update() redraws. // --------------------------------------------------------------------------- export interface LinePoint { label: string; value: number } export interface LineOpts { width?: number; height?: number; color?: string; area?: boolean; dots?: boolean; labels?: boolean; format?: (n: number) => string; scope?: string } let hover: { id: string; index: number } | null = null; export function LineChart(id: string, points: () => LinePoint[], opts: LineOpts = {}) { const W = opts.width ?? 360; const H = opts.height ?? 160; const pad = { l: 10, r: 10, t: 12, b: 18 }; const color = opts.color ?? "var(--os-accent)"; const fmt = opts.format ?? ((n: number) => String(Math.round(n))); const refresh = () => (opts.scope ? update(opts.scope) : update()); const pts = () => points(); const values = () => pts().map((p) => p.value); const min = () => Math.min(0, ...values()); const max = () => Math.max(0, ...values()); const span = () => max() - min() || 1; const x = (i: number) => pad.l + (pts().length === 1 ? (W - pad.l - pad.r) / 2 : (i * (W - pad.l - pad.r)) / (pts().length - 1)); const y = (v: number) => pad.t + (H - pad.t - pad.b) * (1 - (v - min()) / span()); const step = () => (W - pad.l - pad.r) / Math.max(1, pts().length - 1); const line = () => pts().map((p, i) => `${i ? "L" : "M"}${x(i).toFixed(1)},${y(p.value).toFixed(1)}`).join(" "); const area = () => `${line()} L${x(pts().length - 1).toFixed(1)},${H - pad.b} L${x(0).toFixed(1)},${H - pad.b} Z`; const show = () => (hover && hover.id === id ? hover.index : -1); const tip = () => { const i = show(); return i >= 0 ? `${pts()[i].label} · ${fmt(pts()[i].value)}` : ""; }; const tipX = () => x(Math.max(0, show())); const tipY = () => y(pts()[Math.max(0, show())].value); return svgSvg( { viewBox: `0 0 ${W} ${H}`, width: "100%", height: H, role: "img", "aria-label": "Line chart", style: { display: "block" } }, { onPointerMove: (e) => { const el = e.currentTarget; const rect = el.getBoundingClientRect(); if (!rect.width || pts().length < 2) return; const xv = ((e.clientX - rect.left) / rect.width) * W; const index = Math.max(0, Math.min(pts().length - 1, Math.round((xv - pad.l) / step()))); if (hover?.id === id && hover.index === index) return; hover = { id, index }; refresh(); }, onPointerLeave: () => { if (hover?.id === id) { hover = null; refresh(); } } }, lineSvg({ x1: pad.l, x2: W - pad.r, y1: H - pad.b, y2: H - pad.b, style: { stroke: "var(--os-line)" } }), textSvg({ x: W - pad.r, y: pad.t - 3, "text-anchor": "end", fill: "var(--os-muted)", ...TEXT }, () => fmt(max())), textSvg({ x: W - pad.r, y: H - pad.b - 5, "text-anchor": "end", fill: "var(--os-muted)", ...TEXT }, () => fmt(min())), ...(opts.area ? [pathSvg({ d: () => area(), fill: color, opacity: 0.14, stroke: "none" })] : []), pathSvg({ d: () => line(), fill: "none", stroke: color, "stroke-width": 2, "stroke-linecap": "round", "stroke-linejoin": "round" }), ...(opts.dots === false ? [] : pts().map((_, i) => circleSvg({ cx: () => x(i), cy: () => y(pts()[i].value), r: 2.6, fill: "var(--os-panel)", stroke: color, "stroke-width": 1.6 }))), ...(opts.labels === false ? [] : pts().flatMap((_, i) => (i === 0 || i === pts().length - 1 || pts().length <= 6) ? [textSvg({ x: () => x(i), y: H - 5, "text-anchor": "middle", fill: "var(--os-muted)", ...TEXT }, () => pts()[i].label)] : [])), gSvg({}, lineSvg({ x1: () => tipX(), x2: () => tipX(), y1: pad.t, y2: H - pad.b, stroke: color, "stroke-width": 1, "stroke-dasharray": "3 3", opacity: () => (show() < 0 ? 0 : 0.35) }), circleSvg({ cx: () => tipX(), cy: () => tipY(), r: 4, fill: color, stroke: "var(--os-panel)", "stroke-width": 2, opacity: () => (show() < 0 ? 0 : 1) }), rectSvg({ x: () => Math.min(W - tip().length * 5.6 - 18, Math.max(4, tipX() - tip().length * 2.8 - 9)), y: () => Math.max(2, tipY() - 26), width: () => tip().length * 5.6 + 18, height: 16, rx: 5, fill: "var(--os-panel)", stroke: "var(--os-line)", "stroke-width": 1, opacity: () => (show() < 0 ? 0 : 1) }), textSvg({ x: () => Math.min(W - tip().length * 2.8 - 9, Math.max(13, tipX())), y: () => (tipY() > 26 ? tipY() - 14 : tipY() + 20), "text-anchor": "middle", fill: "var(--os-text)", "font-size": 9, "font-family": "ui-monospace, monospace", opacity: () => (show() < 0 ? 0 : 1) }, () => tip()), ), ); } // --------------------------------------------------------------------------- // Grouped bars: one bar per series, side by side for every group. // --------------------------------------------------------------------------- export interface BarSeries { value: number; color: string } export interface BarGroup { label: string; values: BarSeries[] } export interface BarOpts { height?: number; format?: (n: number) => string } export function BarChart(groups: () => BarGroup[], opts: BarOpts = {}) { const W = 360; const H = opts.height ?? 170; const pad = { l: 10, r: 10, t: 14, b: 18 }; const fmt = opts.format ?? ((n: number) => String(Math.round(n))); const grp = () => groups(); const max = () => Math.max(1, ...grp().flatMap((g) => g.values.map((v) => v.value))); const groupW = () => (W - pad.l - pad.r) / Math.max(1, grp().length); const bars = () => grp()[0]?.values.length ?? 1; const barW = () => Math.min(18, Math.max(3, (groupW() - 10) / bars())); const xOf = (gi: number, si: number) => pad.l + gi * groupW() + (groupW() - grp()[gi].values.length * barW()) / 2 + si * barW(); const yOf = (v: number) => pad.t + (H - pad.t - pad.b) * (1 - v / max()); return svgSvg( { viewBox: `0 0 ${W} ${H}`, width: "100%", height: H, role: "img", "aria-label": "Bar chart", style: { display: "block" } }, lineSvg({ x1: pad.l, x2: W - pad.r, y1: H - pad.b, y2: H - pad.b, style: { stroke: "var(--os-line)" } }), textSvg({ x: W - pad.r, y: pad.t - 3, "text-anchor": "end", fill: "var(--os-muted)", ...TEXT }, () => fmt(max())), ...grp().flatMap((_, gi) => grp()[gi].values.map((v, si) => rectSvg({ x: () => xOf(gi, si), y: () => yOf(grp()[gi].values[si].value), width: () => barW(), height: () => Math.max(0.5, H - pad.b - yOf(grp()[gi].values[si].value)), rx: () => Math.min(3, barW() / 2), fill: v.color, style: { transition: "height .35s ease, y .35s ease" } }))), ...grp().map((_, gi) => textSvg({ x: () => pad.l + gi * groupW() + groupW() / 2, y: H - 5, "text-anchor": "middle", fill: "var(--os-muted)", ...TEXT }, () => grp()[gi].label)), ); } // --------------------------------------------------------------------------- // Donut: circle strokes with dasharray segments, one per slice, plus the // total in the hole. The slices are a factory, but the ring keeps a fixed // number of segment circles, so updates only re-size the arcs. // --------------------------------------------------------------------------- export interface DonutSlice { label: string; value: number; color: string } export interface DonutOpts { size?: number; thickness?: number } export function DonutChart(slices: () => DonutSlice[], center: { value: () => string; sub: string }, opts: DonutOpts = {}) { const size = opts.size ?? 150; const thickness = opts.thickness ?? 20; const r = (size - thickness) / 2 - 2; const c = size / 2; const segs = () => { const list = slices(); const total = list.reduce((a, s) => a + s.value, 0) || 1; const C = 2 * Math.PI * r; let acc = 0; return list.map((s) => { const frac = s.value / total; const seg = { dash: Math.max(0, frac * C - 1.5), offset: acc }; // the 1.5 leaves a hairline gap acc += frac * C; return seg; }); }; const C = 2 * Math.PI * r; return svgSvg( { viewBox: `0 0 ${size} ${size}`, width: size, height: size, role: "img", "aria-label": "Donut chart", style: { display: "block" } }, ...(slices().length ? slices().map((_, i) => circleSvg({ cx: c, cy: c, r, fill: "none", stroke: () => slices()[i].color, "stroke-width": thickness, "stroke-dasharray": () => `${segs()[i].dash} ${C - segs()[i].dash}`, "stroke-dashoffset": () => -segs()[i].offset, transform: `rotate(-90 ${c} ${c})`, style: { transition: "stroke-dasharray .4s ease, stroke-dashoffset .4s ease" } })) : [circleSvg({ cx: c, cy: c, r, fill: "none", stroke: "var(--os-line)", "stroke-width": thickness })]), textSvg({ x: c, y: c - 4, "text-anchor": "middle", fill: "var(--os-text)", "font-size": 15, "font-weight": 600 }, () => center.value()), textSvg({ x: c, y: c + 11, "text-anchor": "middle", fill: "var(--os-muted)", ...TEXT }, () => center.sub), ); }
// finance.ts: personal finance for the desktop — an editable ledger // spreadsheet and a dashboard of charts over the same array. Every Tx is a // plain object; the spreadsheet edits cells in place and the charts read the // same array through function bindings, so editing a cell moves every chart. // The ledger is one array shared by every Finance window: it is loaded from // IndexedDB once and saved after every change. // // Like the rest of the desktop, views are built once and update() re-runs // the dynamic bindings — so the charts take their data as factories, and the // two tabs stay mounted with their visibility toggled by a binding. Updates // are scoped: a change to the ledger refreshes every Finance window and // nothing else, opening an editor or switching tabs refreshes only its own // window, and the chart hover refreshes only the charts sub-scope, never the // 63-row spreadsheet. import "nuclo"; import type { Program } from "./programs.ts"; import { scopesOf, winScopeId } from "./windows.ts"; import { byCategory, byDate, CATEGORIES, CATEGORY_COLORS, fmtDate, money, monthly, monthTotals, seed, signed, totals, type Tx } from "./money.ts"; import { deleteTx, loadTxs, replaceAll, saveTx, supported } from "./db.ts"; import { BarChart, DonutChart, LineChart, type DonutSlice } from "./charts.ts"; import { s } from "./styles.ts"; /** What each window keeps for itself: the tab it shows and the cell it edits. */ interface FinState { tab: "charts" | "sheet"; editing: { id: number; field: Field } | null; draft: string; } type Field = "date" | "description" | "category" | "amount"; type KeyEvent = KeyboardEvent & { currentTarget: HTMLElement }; /** The ledger every Finance window reads. */ const ledger = { txs: [] as Tx[], loaded: false, error: "" }; let loading = false; let nextId = 1; const today = () => { const d = new Date(); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`; }; /** The ledger changed: every Finance window updates, and nothing else. */ const refresh = () => update(...scopesOf(finance)); // IndexedDB only exists in the browser, so the ledger loads when the first // window mounts, not at init: the server renders the window with its loading state. async function loadLedger() { if (loading) return; loading = true; if (!supported()) ledger.error = "IndexedDB is not available here."; else try { let rows = await loadTxs(); if (!rows.length) { rows = seed(); await replaceAll(rows); } ledger.txs = rows; nextId = rows.reduce((m, t) => Math.max(m, t.id), 0) + 1; } catch (error) { ledger.error = (error as Error).message; } ledger.loaded = true; refresh(); } function commit(state: FinState) { const e = state.editing; if (!e) return; const t = ledger.txs.find((tx) => tx.id === e.id); if (t) { const v = state.draft.trim(); if (e.field === "date") t.date = v || t.date; else if (e.field === "description") t.description = v; else if (e.field === "category") t.category = v || t.category; else if (e.field === "amount") { const n = Number(v); if (Number.isFinite(n)) t.amount = n; } saveTx(t); } state.editing = null; refresh(); } /** One cell of the spreadsheet: a button that shows the value, or the editor. */ function Cell(state: FinState, t: Tx, field: Field, scopeId: string) { const start = () => { state.editing = { id: t.id, field }; state.draft = String(t[field]); update(scopeId); }; const display = () => { if (field === "amount") return signed(t.amount); if (field === "date") return fmtDate(t.date); if (field === "category") return t.category; return t.description || "—"; }; const keys = (e: KeyEvent) => { if (e.key === "Enter") commit(state); else if (e.key === "Escape") { state.editing = null; update(scopeId); } }; return when(() => state.editing?.id === t.id && state.editing.field === field, field === "category" ? select(s.finInput, { "aria-label": "Category", value: () => state.draft, onMount: (el) => el.focus(), onChange: (e) => { state.draft = e.currentTarget.value; }, onBlur: () => commit(state), onKeyDown: keys }, ...CATEGORIES.map((c) => option({ value: c }, c))) : input(s.finInput, { "aria-label": field, type: field === "date" ? "date" : field === "amount" ? "number" : "text", step: field === "amount" ? "0.01" : undefined, value: () => state.draft, onMount: (el) => { el.focus(); el.select(); }, onInput: (e) => { state.draft = e.currentTarget.value; }, onBlur: () => commit(state), onKeyDown: keys }), ).else(button(s.finCell, { title: "Click to edit", class: () => cx(s.finCell, field === "description" && !t.description ? s.finPlaceholder : null).className, onClick: start }, () => display())); } function RowView(state: FinState, t: Tx, scopeId: string) { return tr(s.finRow, td(s.finTd, Cell(state, t, "date", scopeId)), td(s.finTd, Cell(state, t, "description", scopeId)), td(s.finTd, Cell(state, t, "category", scopeId)), td(s.finTd, s.finAmount, { class: () => cx(s.finTd, s.finAmount, t.amount < 0 ? s.finExpense : s.finIncome).className }, Cell(state, t, "amount", scopeId)), td(s.finTd, s.finDelete, button(s.finIcon, { title: "Delete", "aria-label": "Delete", onClick: () => { ledger.txs.splice(ledger.txs.indexOf(t), 1); state.editing = null; deleteTx(t.id); refresh(); } }, "×")), ); } function SheetView(state: FinState, scopeId: string) { const rows = () => byDate(ledger.txs); return div(s.finSheet, div(s.finScroller, table(s.finTable, thead(tr( th(s.finTh, "Date"), th(s.finTh, "Description"), th(s.finTh, "Category"), th(s.finTh, s.finAmount, "Amount"), th(s.finTh, s.finDelete), )), tbody( list(() => rows(), (t) => RowView(state, t, scopeId)), when(() => !rows().length, tr(td(s.finEmpty, { colSpan: 5 }, "No transactions yet. Add one, or reset the demo data."))), ), ), ), div(s.finFoot, button(s.btn, s.primary, "+ Add", { onClick: () => { const t: Tx = { id: nextId++, date: today(), description: "", category: "Other", amount: 0 }; ledger.txs.push(t); state.editing = { id: t.id, field: "description" }; state.draft = ""; saveTx(t); refresh(); } }), span(() => `${rows().length} transactions`), span(s.finFootTotal, "Balance ", strong(() => signed(totals(ledger.txs).balance))), ), ); } function StatCard(title: string, sub: string, value: () => string, positive: () => boolean) { return div(s.finCard, s.finStat, span(s.finStatTitle, title), span(s.finStatSub, sub), strong({ class: () => cx(s.finStatValue, positive() ? s.finPos : s.finNeg).className }, value), ); } /** Every category, with its spending, in a fixed order: the donut keeps its segments. */ const donutSlices = (txs: Tx[]): DonutSlice[] => { const sums = new Map<string, number>(); for (const t of txs) if (t.amount < 0) sums.set(t.category, (sums.get(t.category) ?? 0) + -t.amount); return CATEGORIES.map((category) => ({ label: category, value: sums.get(category) ?? 0, color: CATEGORY_COLORS[category] ?? "#8a93a0" })); }; function ChartsView(scopeId: string) { const months = () => monthly(ledger.txs, 6); const top = () => byCategory(ledger.txs); // The legend is six fixed slots (no list() rebuilds on every update); each // slot reads the i-th biggest category, hiding itself when there is none. const Legend = () => div(s.finLegend, ...Array.from({ length: 6 }, (_, i) => div(s.finLegendItem, { class: () => cx(s.finLegendItem, top()[i] ? null : s.finHidden).className }, span(s.finLegendDot, { style: () => ({ backgroundColor: top()[i] ? CATEGORY_COLORS[top()[i].category] ?? "#8a93a0" : "transparent" }) }), span(s.finLegendLabel, () => top()[i]?.category ?? ""), span(s.finLegendValue, () => top()[i] ? `${Math.round(top()[i].share * 100)}% · −${money(top()[i].value)}` : ""), ))); return div(s.finCharts, div(s.finCards, StatCard("Balance", "all time", () => signed(totals(ledger.txs).balance), () => totals(ledger.txs).balance >= 0), StatCard("Income", "this month", () => `+${money(monthTotals(ledger.txs).income)}`, () => true), StatCard("Spending", "this month", () => `−${money(monthTotals(ledger.txs).expense)}`, () => false), StatCard("Saved", "this month", () => signed(monthTotals(ledger.txs).net), () => monthTotals(ledger.txs).net >= 0), ), div(s.finGrid, section(s.finCard, s.finWide, div(s.finCardHead, h3("Balance"), span(s.finCardSub, "running total · last 6 months · hover the line")), LineChart("balance", () => months().map((m) => ({ label: m.label, value: Math.round(m.balance) })), { height: 168, area: true, color: "#237556", format: (n) => money(n), scope: scopeId }), ), section(s.finCard, div(s.finCardHead, h3("Spending"), span(s.finCardSub, "by category · all time")), div(s.finDonutRow, DonutChart(() => donutSlices(ledger.txs), { value: () => `−${money(totals(ledger.txs).expense)}`, sub: "all time" }), Legend(), ), ), section(s.finCard, s.finWide, div(s.finCardHead, h3("Income and spending"), span(s.finCardSub, "per month · last 6 months")), BarChart(() => months().map((m) => ({ label: m.label, values: [{ value: m.income, color: "#237556" }, { value: m.expense, color: "#c25b4e" }] })), { format: (n) => money(n) }), div(s.finKey, span(s.finKeyItem, span(s.finLegendDot, { style: { backgroundColor: "#237556" } }), "Income"), span(s.finKeyItem, span(s.finLegendDot, { style: { backgroundColor: "#c25b4e" } }), "Spending"), ), ), ), ); } export const finance: Program<FinState> = { name: "Finance", icon: "finance", size: [780, 500], init: () => ({ tab: "charts", editing: null, draft: "" }), view: (win) => { const state = win.state; const scopeId = winScopeId(win); const chartsScope = `os-fin-charts-${win.id}`; // the hover refreshes the charts, not the spreadsheet return div(s.finance, on("mount", loadLedger), div(s.toolbar, strong(s.financeHeading, "Finance"), div(s.finTabs, { role: "tablist", "aria-label": "Finance views" }, button({ role: "tab", "aria-selected": () => String(state.tab === "charts"), class: () => cx(s.finTab, state.tab === "charts" ? s.finTabOn : null).className, onClick: () => { state.tab = "charts"; update(scopeId); } }, "Charts"), button({ role: "tab", "aria-selected": () => String(state.tab === "sheet"), class: () => cx(s.finTab, state.tab === "sheet" ? s.finTabOn : null).className, onClick: () => { state.tab = "sheet"; update(scopeId); } }, "Spreadsheet"), ), span(s.finHint, "Saved in this browser · IndexedDB"), button(s.btn, "Reset demo", { title: "Restore the sample ledger", disabled: () => !ledger.loaded, onClick: () => { const fresh = seed(); ledger.txs = fresh; nextId = fresh.reduce((m, t) => Math.max(m, t.id), 0) + 1; replaceAll(fresh); refresh(); } }), ), when(() => !!ledger.error, p(s.error, { role: "alert" }, () => ledger.error)), // Both tabs stay mounted; a binding toggles the visible one. That way // the charts and the sheet are built once and update() keeps them live. p(s.finLoading, { class: () => cx(s.finLoading, ledger.loaded ? s.finHidden : null).className }, "Opening the ledger…"), div(s.finBody, scope(chartsScope), { class: () => cx(s.finBody, ledger.loaded && state.tab === "charts" ? null : s.finHidden).className }, ChartsView(chartsScope)), div(s.finBody, { class: () => cx(s.finBody, ledger.loaded && state.tab === "sheet" ? null : s.finHidden).className }, SheetView(state, scopeId)), ); }, };
import "nuclo"; // One small stroke icon family, shared by the launcher, windows and file browser. const paths: Record<string, string> = { files: "M3 7V5a2 2 0 0 1 2-2h5l2 3h7a2 2 0 0 1 2 2v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7Z", notes: "M14 3H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9l-6-6Zm0 0v6h6M8 13h8M8 17h5", calculator: "M6 3h12a1 1 0 0 1 1 1v16a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1ZM8 7h8M8 12h1m6 0h1M8 16h1m6 0h1", timer: "M9 2h6m-3 0v3m6 1 2-2M12 9v5l3 2M12 5a8 8 0 1 0 0 16 8 8 0 0 0 0-16Z", terminal: "M4 4h16a1 1 0 0 1 1 1v14a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1Zm3 4 4 4-4 4m6 0h4", kanban: "M4 5h16a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1ZM9 5v14m6-14v14", calendar: "M4 7h16a1 1 0 0 1 1 1v11a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V8a1 1 0 0 1 1-1ZM8 4v4m8-4v4M3 11h18", finance: "M3 3v18h18M8 17V9m4 8V5m4 12v-6", settings: "M12 3v3m0 12v3M3 12h3m12 0h3M6 6l2 2m8 8 2 2M6 18l2-2m8-8 2-2M12 7a5 5 0 1 0 0 10 5 5 0 0 0 0-10Z", about: "M12 11v6m0-10v.01M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18Z", grid: "M3 3h7v7H3ZM14 3h7v7h-7ZM3 14h7v7H3ZM14 14h7v7h-7Z", trash: "M3 6h18M9 6V3h6v3M5 6l1 15h12l1-15M10 10v7m4-7v7", back: "m14 5-7 7 7 7", forward: "m10 5 7 7-7 7", up: "m5 14 7-7 7 7", search: "M10 3a7 7 0 1 0 0 14 7 7 0 0 0 0-14Zm5 12 6 6", close: "m6 6 12 12M6 18 18 6", minimize: "M5 12h14", maximize: "M5 5h14v14H5Z", restore: "M8 3h13v13M3 8h13v13H3Z", }; export function icon(name: string, size = 20) { return svgSvg({ viewBox: "0 0 24 24", width: size, height: size, fill: "none", stroke: "currentColor", "stroke-width": 1.7, "stroke-linecap": "round", "stroke-linejoin": "round", "aria-hidden": "true", style: { flexShrink: "0" } }, pathSvg({ d: paths[name] ?? paths.notes })); }
import "nuclo"; import { icon } from "./icons.ts"; import { s } from "./styles.ts"; interface Action { label: string; icon: string; run(): void; disabled?: boolean; danger?: boolean } interface Menu { label: string; actions: Action[]; anchor: HTMLElement; x: number; y: number } let menu: Menu | null = null; export function dismissContextMenu(restoreFocus = false) { const anchor = menu?.anchor; menu = null; if (restoreFocus && anchor?.isConnected) anchor.focus(); update("os-context-menu"); } function show(anchor: HTMLElement, x: number, y: number, label: string, actions: Action[]) { menu = { anchor, x, y, label, actions }; update("os-context-menu"); } export function showContextMenu(event: MouseEvent & { currentTarget: HTMLElement }, label: string, actions: Action[]) { event.preventDefault(); event.stopPropagation(); show(event.currentTarget, event.clientX, event.clientY, label, actions); } export function contextMenuKey(event: KeyboardEvent & { currentTarget: HTMLElement }, label: string, actions: Action[]) { if (event.key !== "ContextMenu" && !(event.shiftKey && event.key === "F10")) return false; event.preventDefault(); event.stopPropagation(); const rect = event.currentTarget.getBoundingClientRect(); show(event.currentTarget, rect.left + 12, rect.top + Math.min(rect.height, 32), label, actions); return true; } export function ContextMenu() { return list(() => menu ? [menu] : [], (current) => div(s.contextMenu, { role: "menu", "aria-label": current.label, onContextMenu: (e) => e.preventDefault(), onKeyDown: (e) => { e.stopPropagation(); const items = [...e.currentTarget.querySelectorAll<HTMLButtonElement>('button:not(:disabled)')]; const index = items.indexOf(document.activeElement as HTMLButtonElement); if (["ArrowDown", "ArrowUp", "Home", "End"].includes(e.key)) { e.preventDefault(); const next = e.key === "Home" ? 0 : e.key === "End" ? items.length - 1 : (index + (e.key === "ArrowDown" ? 1 : -1) + items.length) % items.length; items[next]?.focus(); } else if (e.key === "Escape" || e.key === "Tab") { if (e.key === "Escape") e.preventDefault(); dismissContextMenu(true); } }, onMount: (el) => { const app = el.closest<HTMLElement>(".os-app")!; const rect = app.getBoundingClientRect(); // Measure the actual menu, including wrapped labels, before keeping it inside the desktop. el.style.left = `${Math.max(6, Math.min(current.x - rect.left, app.clientWidth - el.offsetWidth - 6))}px`; el.style.top = `${Math.max(6, Math.min(current.y - rect.top, app.clientHeight - el.offsetHeight - 6))}px`; el.querySelector<HTMLButtonElement>('button:not(:disabled)')?.focus(); } }, span(s.contextHeading, current.label), ...current.actions.map((action) => button(s.contextItem, action.danger ? s.contextDanger : null, { role: "menuitem", tabIndex: -1, disabled: action.disabled, onClick: () => { dismissContextMenu(true); action.run(); update(); } }, icon(action.icon, 17), action.label, )), )); } export function contextMenuLifecycle() { return on("mount", () => { const outside = (event: Event) => { if (menu && !(event.target instanceof Element && event.target.closest('[role="menu"]'))) dismissContextMenu(); }; const dismiss = () => { if (menu) dismissContextMenu(); }; document.addEventListener("pointerdown", outside, true); window.addEventListener("resize", dismiss); window.addEventListener("blur", dismiss); return () => { document.removeEventListener("pointerdown", outside, true); window.removeEventListener("resize", dismiss); window.removeEventListener("blur", dismiss); menu = null; }; }); }
import "nuclo"; const mono = "ui-monospace, SFMono-Regular, Consolas, monospace"; // Adwaita-style controls: flat, no border, a wash of the text color that deepens on hover. const control = { minHeight: "34px", padding: "0 13px", borderRadius: "8px", border: "1px solid transparent", backgroundColor: "color-mix(in srgb, currentColor 10%, transparent)", color: "var(--os-text)", fontFamily: "inherit", fontSize: "0.78rem", fontWeight: "600", whiteSpace: "nowrap", display: "inline-flex", alignItems: "center", justifyContent: "center", gap: "6px" }; const pop = keyframes({ from: { opacity: "0", transform: "scale(0.96)" } }); // windows, menus and dialogs arrive like this const fade = keyframes({ from: { opacity: "0" } }); // The palette follows GNOME's Adwaita: neutral grays, a blue accent, 12px // window corners. The theme is a handful of custom properties on the desktop root. Dark swaps // them, by choice ([data-os-theme=dark]) or, before the page has loaded, with the system ([data-os-theme=auto]). // --os-accent is the fill, --os-accent-ink the same hue as text, and // --os-tint a wash of it over the panel, so one accent colors everything. const light = { "color-scheme": "light", "--os-panel": "#fafafa", "--os-soft": "#ebebeb", "--os-hover": "#dedede", "--os-field": "#fff", "--os-paper": "#fff", "--os-text": "#2e2e2e", "--os-muted": "#686868", "--os-line": "#d5d5d5", "--os-accent-ink": "color-mix(in srgb, var(--os-accent) 78%, black)", "--os-danger": "#e01b24", "--os-danger-ink": "#c01c28", "--os-danger-soft": "#f9e0e1", "--os-dim": "0%" }; const dark = { "color-scheme": "dark", "--os-panel": "#242424", "--os-soft": "#303030", "--os-hover": "#3d3d3d", "--os-field": "#1e1e1e", "--os-paper": "#1e1e1e", "--os-text": "#f2f2f2", "--os-muted": "#a8a8a8", "--os-line": "#434343", "--os-accent-ink": "color-mix(in srgb, var(--os-accent) 50%, white)", "--os-danger": "#c01c28", "--os-danger-ink": "#ff938c", "--os-danger-soft": "#4a2224", "--os-dim": "35%" }; const focusRing = { outline: "2px solid var(--os-accent-ink)", outlineOffset: "2px" }; export const s = { contextMenu: css("os-context-menu", { transformOrigin: "top left", animation: `${pop} 0.12s ease-out`, position: "absolute", zIndex: 9, width: "min(224px, calc(100% - 12px))", maxHeight: "calc(100% - 12px)", overflowY: "auto", padding: "6px", borderRadius: "10px", backgroundColor: "var(--os-panel)", boxShadow: "0 10px 32px rgb(0 0 0 / .28)" }), contextHeading: css("os-context-heading", { display: "block", padding: "7px 10px 8px", marginBottom: "4px", borderBottom: "1px solid var(--os-line)", overflow: "hidden", whiteSpace: "nowrap", textOverflow: "ellipsis", color: "var(--os-muted)", fontSize: "0.65rem", fontWeight: "600" }), contextItem: css("os-context-item", { display: "flex", alignItems: "center", gap: "10px", width: "100%", minHeight: "36px", padding: "7px 10px", borderRadius: "6px", color: "var(--os-text)", textAlign: "left", fontSize: "0.8rem", hover: { backgroundColor: "var(--os-soft)" }, "&:focus-visible": { outlineOffset: "-2px", backgroundColor: "var(--os-soft)" } }), contextDanger: css("os-context-danger", { color: "var(--os-danger-ink)", hover: { backgroundColor: "var(--os-danger-soft)" } }), app: css("os-app", { position: "relative", isolation: "isolate", display: "flex", flexDirection: "column", width: "100%", height: "100%", overflow: "hidden", borderRadius: "14px", fontFamily: "'Adwaita Sans', Inter, Cantarell, ui-sans-serif, system-ui, sans-serif", backgroundColor: "color-mix(in srgb, var(--os-warm), #000 var(--os-dim))", color: "var(--os-text)", raw: { ...light, "--os-accent": "#3584e4", "--os-warm": "#1a5fb4", "--os-tint": "color-mix(in srgb, var(--os-accent) 15%, var(--os-panel))", "scrollbar-color": "color-mix(in srgb, var(--os-muted) 50%, transparent) transparent", "scrollbar-width": "thin", "-webkit-user-select": "none", "-webkit-touch-callout": "none", "-webkit-tap-highlight-color": "transparent", "container-type": "inline-size" }, userSelect: "none", cursor: "default", touchAction: "manipulation", "& input, & textarea": { userSelect: "text", raw: { "-webkit-user-select": "text" } }, "& button, & select, & summary, & label": { cursor: "default" }, "& button:active:not(:disabled)": { filter: "brightness(.93)" }, "& svg, & img, & a": { raw: { "-webkit-user-drag": "none" } }, "& *": { raw: { "overscroll-behavior": "contain" } }, "@media (prefers-reduced-motion: reduce)": { "& *": { animation: "none" } }, "& button:focus-visible, & input:focus-visible, & textarea:focus-visible, & select:focus-visible, & [tabindex='0']:focus-visible": focusRing, "@media (pointer: coarse)": { "& .os-btn, & .os-side-item": { minHeight: "38px" }, "& .os-ctl": { width: "30px", height: "30px" }, "& input, & textarea, & select": { fontSize: "16px" }, "& .os-input": { height: "38px" } }, "& button:disabled": { opacity: ".45", cursor: "default" }, "& ::selection": { backgroundColor: "color-mix(in srgb, var(--os-accent) 30%, var(--os-panel))", color: "var(--os-text)" }, "@container (max-width: 600px)": { "&:not([data-booted=true]) [data-os-window]": { display: "none" } }, "&[data-os-theme=dark]": { raw: dark }, "@media (prefers-color-scheme: dark)": { "&[data-os-theme=auto]": { raw: dark } }, "&[data-accent=green]": { raw: { "--os-accent": "#3a944a" } }, "&[data-accent=purple]": { raw: { "--os-accent": "#9141ac" } }, "&[data-accent=orange]": { raw: { "--os-accent": "#e66100" } }, "&[data-wallpaper=dusk]": { raw: { "--os-warm": "#613583" } }, "&[data-wallpaper=slate]": { raw: { "--os-warm": "#3d3846" } } }), desk: css("os-desk", { position: "relative", isolation: "isolate", flex: "1", minHeight: "0", overflow: "hidden", backgroundColor: "transparent" }), wallpaper: css("os-wallpaper", { position: "absolute", inset: "0", overflow: "hidden", pointerEvents: "none", backgroundImage: "linear-gradient(130deg, rgb(255 255 255 / .08), transparent 55%)" }), orbit: css("os-orbit", { position: "absolute", width: "850px", height: "850px", right: "-270px", top: "-330px", borderRadius: "50%", border: "100px solid rgb(255 255 255 / .045)" }), orbitTwo: css("os-orbit-two", { width: "1150px", height: "1150px", right: "-420px", top: "-480px", borderWidth: "1px", borderColor: "rgb(255 255 255 / .15)" }), desktopHeading: css("os-desktop-heading", { position: "absolute", bottom: "28px", right: "32px", display: "flex", flexDirection: "column", gap: "6px", textAlign: "right", pointerEvents: "none", color: "rgb(255 255 255 / .92)", "& strong": { fontSize: "1.7rem", fontWeight: "500", letterSpacing: "-.03em" }, "& span": { fontSize: "0.8rem" }, "@container (max-width: 600px)": { display: "none" } }), icons: css("os-icons", { display: "none", "@container (max-width: 600px)": { display: "grid", gridTemplateColumns: "repeat(4, minmax(0, 1fr))", alignContent: "start", justifyItems: "center", gap: "18px 4px", height: "100%", padding: "24px 12px", overflowY: "auto", "& > button": { width: "100%" }, "& .os-glyph": { width: "54px", height: "54px", borderRadius: "15px" } } }), // the home screen of a phone-sized desktop icon: css("os-icon", { display: "flex", flexDirection: "column", alignItems: "center", gap: "5px", width: "80px", padding: "7px 4px", borderRadius: "10px", fontSize: "0.7rem", fontWeight: "500", color: "#fff", touchAction: "manipulation", userSelect: "none", hover: { backgroundColor: "rgb(255 255 255 / .12)" } }), glyph: css("os-glyph", { display: "flex", alignItems: "center", justifyContent: "center", width: "43px", height: "43px", borderRadius: "12px", color: "#1a5fb4", backgroundColor: "#d7e6f9", boxShadow: "0 3px 6px rgb(0 0 0 / .12)", "&[data-app=notes]": { color: "#795522", backgroundColor: "#f7eacb" }, "&[data-app=terminal]": { color: "#fff", backgroundColor: "#2e2e2e" }, "&[data-app=calculator]": { color: "#494672", backgroundColor: "#e7e3f2" }, "&[data-app=timer]": { color: "#7d463c", backgroundColor: "#f2ddd5" }, "&[data-app=kanban]": { color: "#6a4a94", backgroundColor: "#e8dcf1" }, "&[data-app=calendar]": { color: "#96623a", backgroundColor: "#f6e6d2" }, "&[data-app=finance]": { color: "#275d8a", backgroundColor: "#dfe9f2" } }), win: css("os-win", { position: "absolute", left: "0", top: "0", raw: { contain: "layout paint" }, animation: `${pop} 0.14s ease-out`, transition: "opacity 0.14s ease-in, transform 0.14s ease-in, display 0.14s allow-discrete", "&[data-moving]": { willChange: "translate" }, "@container (max-width: 600px)": { borderRadius: "0", boxShadow: "none", raw: { translate: "none !important", width: "100% !important", height: "100% !important" } }, display: "flex", flexDirection: "column", borderRadius: "12px", overflow: "hidden", backgroundColor: "var(--os-panel)", boxShadow: "0 0 0 1px var(--os-line), 0 8px 28px rgb(0 0 0 / .19)" }), active: css("os-active", { boxShadow: "0 0 0 1px var(--os-line), 0 16px 42px rgb(0 0 0 / .28)", "& > header": { color: "var(--os-text)" } }), minimized: css("os-minimized", { display: "none", opacity: "0", transform: "translateY(28px) scale(0.9)", pointerEvents: "none" }), // sinks toward the taskbar; display flips when the transition ends closing: css("os-closing", { opacity: "0", transform: "scale(0.96)", pointerEvents: "none" }), snap: css("os-snap", { position: "absolute", inset: "8px", borderRadius: "12px", border: "1px solid rgb(255 255 255 / .55)", backgroundColor: "rgb(255 255 255 / .16)", opacity: "0", pointerEvents: "none", transition: "opacity 0.12s ease-out", "&[data-zone=max], &[data-zone=left], &[data-zone=right]": { opacity: "1" }, "&[data-zone=left]": { right: "calc(50% + 4px)" }, "&[data-zone=right]": { left: "calc(50% + 4px)" } }), maximized: css("os-maximized", { borderRadius: "0", "& .os-grip, & .os-edge": { display: "none" } }), bar: css("os-bar", { display: "flex", alignItems: "center", gap: "8px", height: "46px", flexShrink: 0, paddingRight: "10px", borderBottom: "1px solid var(--os-line)", backgroundColor: "var(--os-soft)", color: "var(--os-muted)", userSelect: "none" }), title: css("os-title", { display: "flex", alignItems: "center", justifyContent: "center", gap: "6px", flex: "1", minWidth: "0", height: "100%", paddingLeft: "98px", fontSize: "0.8rem", fontWeight: "700", touchAction: "none", "& span": { overflow: "hidden", whiteSpace: "nowrap", textOverflow: "ellipsis" }, "@container (max-width: 600px)": { paddingLeft: "66px" } }), // the padding mirrors the buttons, so the title sits in the middle dirty: css("os-dirty", { color: "var(--os-accent-ink)" }), ctl: css("os-ctl", { display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0, width: "24px", height: "24px", borderRadius: "50%", color: "var(--os-text)", backgroundColor: "color-mix(in srgb, currentColor 10%, transparent)", hover: { backgroundColor: "color-mix(in srgb, currentColor 18%, transparent)" } }), ctlMax: css("os-ctl-max", { "@container (max-width: 600px)": { display: "none" } }), // a phone-sized desktop has nothing to maximize into body: css("os-body", { display: "flex", flexDirection: "column", flex: "1", minHeight: "0", overflow: "hidden", raw: { "container-type": "inline-size" } }) /* apps lay themselves out by the width of their window, not of the screen */, edge: css("os-edge", { position: "absolute", touchAction: "none", "&[data-dir=n], &[data-dir=s]": { left: "0", right: "0", height: "5px", cursor: "ns-resize" }, "&[data-dir=e], &[data-dir=w]": { top: "0", bottom: "0", width: "5px", cursor: "ew-resize" }, "&[data-dir=n], &[data-dir=nw], &[data-dir=ne]": { top: "0" }, "&[data-dir=s], &[data-dir=sw]": { bottom: "0" }, "&[data-dir=w], &[data-dir=nw], &[data-dir=sw]": { left: "0" }, "&[data-dir=e], &[data-dir=ne]": { right: "0" }, "&[data-dir=nw], &[data-dir=ne], &[data-dir=sw]": { width: "10px", height: "10px" }, "&[data-dir=nw]": { cursor: "nwse-resize" }, "&[data-dir=ne], &[data-dir=sw]": { cursor: "nesw-resize" }, "@media (pointer: coarse)": { "&[data-dir=n], &[data-dir=s]": { height: "12px" }, "&[data-dir=e], &[data-dir=w]": { width: "12px" }, "&[data-dir=nw], &[data-dir=ne], &[data-dir=sw]": { width: "22px", height: "22px" } }, "@container (max-width: 600px)": { display: "none" } }), // a finger needs more to hold than a mouse grip: css("os-grip", { position: "absolute", right: "1px", bottom: "1px", width: "16px", height: "16px", "@media (pointer: coarse)": { width: "24px", height: "24px" }, "@container (max-width: 600px)": { display: "none" }, cursor: "nwse-resize", touchAction: "none", backgroundImage: "linear-gradient(135deg, transparent 55%, var(--os-muted) 55% 62%, transparent 62% 76%, var(--os-muted) 76% 83%, transparent 83%)" }), backdrop: css("os-backdrop", { animation: `${fade} 0.12s ease-out`, position: "absolute", inset: "0", zIndex: 10, display: "flex", alignItems: "center", justifyContent: "center", padding: "16px", backgroundColor: "rgb(12 27 20 / .5)" }), dialog: css("os-dialog", { animation: `${pop} 0.12s ease-out`, borderRadius: "14px", backgroundColor: "var(--os-panel)", display: "flex", flexDirection: "column", gap: "8px", width: "min(340px, 100%)", padding: "24px", boxShadow: "0 20px 60px rgb(0 0 0 / .25)", textAlign: "center", "& h3": { fontSize: "1.1rem", fontWeight: "700" }, "& p": { fontSize: "0.875rem", color: "var(--os-muted)" } }), actions: css("os-actions", { display: "flex", justifyContent: "flex-end", gap: "8px", marginTop: "12px", "& > *": { flex: "1" } }), topbar: css("os-topbar", { display: "grid", gridTemplateColumns: "1fr auto 1fr", alignItems: "center", flexShrink: 0, height: "32px", padding: "0 8px", backgroundColor: "#131313", color: "#fff", fontSize: "0.78rem", fontWeight: "700" }), topButton: css("os-top-button", { justifySelf: "start", display: "inline-flex", alignItems: "center", height: "24px", padding: "0 11px", borderRadius: "999px", color: "inherit", fontSize: "inherit", fontWeight: "inherit", hover: { backgroundColor: "rgb(255 255 255 / .14)" }, "&[aria-expanded=true]": { backgroundColor: "rgb(255 255 255 / .22)" }, "@media (pointer: coarse)": { height: "28px" } }), taskbar: css("os-taskbar", { display: "flex", justifyContent: "center", flexShrink: 0, padding: "6px 8px calc(8px + env(safe-area-inset-bottom, 0px))" }), // The dock keeps the shell's dark glass in both themes, like the top bar. dock: css("os-dock", { display: "flex", alignItems: "center", gap: "4px", maxWidth: "100%", overflowX: "auto", padding: "6px", borderRadius: "20px", backgroundColor: "rgb(28 28 28 / .8)", boxShadow: "inset 0 0 0 1px rgb(255 255 255 / .09)", raw: { "scrollbar-width": "none" } }), dockItem: css("os-dock-item", { position: "relative", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0, width: "48px", height: "48px", borderRadius: "14px", hover: { backgroundColor: "rgb(255 255 255 / .12)" }, "&[data-active=true]": { backgroundColor: "rgb(255 255 255 / .17)" }, "& .os-glyph": { width: "38px", height: "38px", borderRadius: "11px", boxShadow: "none" }, "&[data-running=true] .os-dock-dot": { opacity: "1" }, "@container (max-width: 600px)": { "&[data-running=false]": { display: "none" } } }), // a phone's dock holds what is running; its home screen has the rest dockDot: css("os-dock-dot", { position: "absolute", bottom: "1px", left: "50%", width: "5px", height: "5px", marginLeft: "-2.5px", borderRadius: "50%", backgroundColor: "#fff", opacity: "0" }), dockSeparator: css("os-dock-separator", { flexShrink: 0, width: "1px", height: "28px", margin: "0 4px", backgroundColor: "rgb(255 255 255 / .16)" }), dockGrid: css("os-dock-grid", { display: "flex", alignItems: "center", justifyContent: "center", width: "38px", height: "38px", color: "#fff" }), overview: css("os-overview", { position: "absolute", inset: "0", zIndex: 2147483000, display: "flex", flexDirection: "column", alignItems: "center", gap: "22px", padding: "28px 20px", overflowY: "auto", backgroundColor: "rgb(20 20 20 / .9)", color: "#fff", animation: `${fade} 0.14s ease-out` }), overviewSearch: css("os-overview-search", { flexShrink: 0, width: "min(340px, 100%)", height: "38px", padding: "0 16px", borderRadius: "999px", border: "1px solid rgb(255 255 255 / .12)", backgroundColor: "rgb(255 255 255 / .12)", color: "#fff", fontFamily: "inherit", fontSize: "0.85rem", textAlign: "center", "&::placeholder": { color: "rgb(255 255 255 / .6)" } }), overviewWindows: css("os-overview-windows", { display: "flex", flexWrap: "wrap", justifyContent: "center", gap: "8px", maxWidth: "720px" }), overviewWindow: css("os-overview-window", { display: "flex", alignItems: "center", gap: "8px", maxWidth: "220px", height: "40px", padding: "0 12px 0 6px", borderRadius: "10px", backgroundColor: "rgb(255 255 255 / .1)", color: "#fff", fontSize: "0.78rem", fontWeight: "600", hover: { backgroundColor: "rgb(255 255 255 / .18)" }, "& .os-glyph": { width: "28px", height: "28px", borderRadius: "8px", boxShadow: "none", flexShrink: 0 }, "& > span:last-child": { overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" } }), overviewApps: css("os-overview-apps", { display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(96px, 1fr))", justifyItems: "center", gap: "14px 6px", width: "min(640px, 100%)", "& .os-icon": { width: "100%", maxWidth: "104px" }, "& .os-glyph": { width: "56px", height: "56px", borderRadius: "16px" } }), overviewEmpty: css("os-overview-empty", { color: "rgb(255 255 255 / .7)", fontSize: "0.8rem" }), tray: css("os-tray", { justifySelf: "end", display: "flex", alignItems: "center", gap: "4px", fontVariantNumeric: "tabular-nums" }), trayItem: css("os-tray-item", { ...control, minHeight: "24px", padding: "0 9px", borderRadius: "999px", backgroundColor: "rgb(255 255 255 / .16)", color: "#fff", fontSize: "0.72rem" }), clock: css("os-clock", { display: "flex", gap: "8px", padding: "0 10px", fontVariantNumeric: "tabular-nums" }), btn: css("os-btn", { ...control, hover: { backgroundColor: "color-mix(in srgb, currentColor 16%, transparent)" } }), iconBtn: css("os-icon-btn", { width: "34px", padding: "0", flexShrink: 0, "@media (pointer: coarse)": { width: "38px" } }), hidden: css("os-hidden", { display: "none" }), primary: css("os-primary", { backgroundColor: "var(--os-accent)", borderColor: "transparent", color: "#fff", hover: { backgroundColor: "var(--os-accent)", filter: "brightness(.92)" } }), danger: css("os-danger", { backgroundColor: "var(--os-danger)", borderColor: "transparent", color: "#fff", hover: { backgroundColor: "var(--os-danger)", filter: "brightness(.92)" } }), input: css("os-input", { minWidth: "0", width: "100%", height: "34px", padding: "0 11px", border: "1px solid transparent", borderRadius: "8px", backgroundColor: "color-mix(in srgb, var(--os-text) 8%, transparent)", color: "var(--os-text)", fontFamily: "inherit", fontSize: "0.8rem", "&::placeholder": { color: "var(--os-muted)" } }), toolbar: css("os-toolbar", { display: "flex", alignItems: "center", gap: "7px", padding: "9px 12px", flexShrink: 0, borderBottom: "1px solid var(--os-line)", "@container (max-width: 340px)": { flexWrap: "wrap", padding: "7px" } }), notes: css("os-notes", { display: "flex", flexDirection: "column", flex: "1", minHeight: "0" }), textarea: css("os-textarea", { flex: "1", minHeight: "0", width: "100%", padding: "20px", border: "none", resize: "none", backgroundColor: "var(--os-paper)", color: "var(--os-text)", fontFamily: "inherit", fontSize: "0.875rem", lineHeight: "1.8", raw: { "caret-color": "var(--os-accent-ink)" }, "&::placeholder": { color: "var(--os-muted)" }, "@container (max-width: 340px)": { padding: "14px" } }), foot: css("os-foot", { display: "flex", justifyContent: "space-between", alignItems: "center", gap: "10px", padding: "9px 14px", borderTop: "1px solid var(--os-line)", fontSize: "0.65rem", color: "var(--os-muted)" }), error: css("os-error", { padding: "8px 12px", backgroundColor: "var(--os-danger-soft)", color: "var(--os-danger-ink)", fontSize: "0.75rem", flexShrink: 0 }), explorer: css("os-explorer", { display: "flex", flex: "1", minHeight: "0" }), sidebar: css("os-sidebar", { display: "flex", flexDirection: "column", flexShrink: 0, width: "145px", padding: "18px 8px 10px", gap: "4px", backgroundColor: "var(--os-soft)", "@container (max-width: 480px)": { width: "46px", padding: "12px 4px", "& .os-side-item span, & .os-sidebar-title, & .os-disk-hint": { display: "none" }, "& .os-side-item": { justifyContent: "center", padding: "0" } } }), sidebarTitle: css("os-sidebar-title", { fontSize: "0.65rem", fontWeight: "600", color: "var(--os-muted)", padding: "0 10px 8px" }), sideItem: css("os-side-item", { display: "flex", alignItems: "center", gap: "8px", minHeight: "35px", padding: "0 10px", borderRadius: "7px", fontSize: "0.75rem", textAlign: "left", color: "var(--os-text)", "&[aria-current=page]": { backgroundColor: "var(--os-tint)", color: "var(--os-accent-ink)", fontWeight: "600" }, "& svg + span": { flex: "1" }, hover: { backgroundColor: "var(--os-hover)" } }), sideCount: css("os-side-count", { color: "var(--os-muted)", fontSize: "0.65rem", fontWeight: "600", fontVariantNumeric: "tabular-nums" }), diskHint: css("os-disk-hint", { marginTop: "auto", padding: "14px 10px 0", fontSize: "0.6rem", lineHeight: "1.6", color: "var(--os-muted)" }), fileMain: css("os-file-main", { display: "flex", flexDirection: "column", flex: "1", minWidth: "0", minHeight: "0" }), crumbs: css("os-crumbs", { display: "flex", alignItems: "center", flex: "1", minWidth: "0", overflowX: "auto", raw: { "scrollbar-width": "none" } }), crumb: css("os-crumb", { flexShrink: 0, height: "28px", padding: "0 6px", borderRadius: "6px", fontSize: "0.75rem", fontWeight: "600", color: "var(--os-muted)", whiteSpace: "nowrap", hover: { backgroundColor: "var(--os-soft)", color: "var(--os-text)" }, "&[aria-current=page]": { color: "var(--os-text)" }, "&:not(:first-child)::before": { content: '"/"', marginRight: "10px", marginLeft: "-2px", color: "var(--os-muted)", fontWeight: "400" } }), inlineText: css("os-inline-text", { flex: "1", minWidth: "0", alignSelf: "center", fontSize: "0.75rem", color: "var(--os-text)" }), fileHead: css("os-file-head", { display: "flex", alignItems: "center", gap: "10px", flexShrink: 0, padding: "0 20px", borderBottom: "1px solid var(--os-line)" }), fileHeadCell: css("os-file-head-cell", { height: "28px", fontSize: "0.62rem", fontWeight: "700", textTransform: "uppercase", letterSpacing: "0.04em", color: "var(--os-muted)", textAlign: "left", whiteSpace: "nowrap", hover: { color: "var(--os-text)" }, "&[aria-pressed=true]": { color: "var(--os-text)" } }), fileHeadName: css("os-file-head-name", { flex: "1", minWidth: "0", paddingLeft: "35px" }), fileWhen: css("os-file-when", { width: "74px", flexShrink: 0, "@container (max-width: 460px)": { display: "none" } }), fileSize: css("os-file-size", { width: "62px", flexShrink: 0, textAlign: "right" }), inlineForm: css("os-inline-form", { display: "flex", gap: "6px", padding: "10px 12px", backgroundColor: "var(--os-soft)", flexShrink: 0 }), fileList: css("os-file-list", { flex: "1", minHeight: "0", overflowY: "auto", padding: "10px" }), fileRow: css("os-file-row", { display: "flex", alignItems: "center", gap: "10px", width: "100%", minHeight: "44px", padding: "6px 10px", borderRadius: "7px", textAlign: "left", color: "var(--os-text)", hover: { backgroundColor: "var(--os-soft)" }, "&[aria-pressed=true]": { backgroundColor: "var(--os-tint)" } }), fileIcon: css("os-file-icon", { display: "flex", color: "var(--os-muted)" }), fileName: css("os-file-name", { flex: "1", minWidth: "0", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", fontSize: "0.8rem" }), fileMeta: css("os-file-meta", { color: "var(--os-muted)", fontSize: "0.65rem", whiteSpace: "nowrap", fontVariantNumeric: "tabular-nums" }), fileGrid: css("os-file-grid", { display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(110px, 1fr))", alignContent: "start", gap: "4px", "& .os-file-row": { flexDirection: "column", textAlign: "center", gap: "7px", padding: "16px 6px" }, "& .os-file-name": { width: "100%", flex: "none" }, "& .os-file-when": { display: "none" }, "& .os-file-size": { width: "auto", textAlign: "center" } }), fileActions: css("os-file-actions", { display: "flex", alignItems: "center", gap: "5px", padding: "8px 12px", borderTop: "1px solid var(--os-line)", flexShrink: 0, flexWrap: "wrap" }), selection: css("os-selection", { flex: "1", minWidth: "40px", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", color: "var(--os-muted)", fontSize: "0.65rem" }), empty: css("os-empty", { display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: "9px", padding: "25px 10px", color: "var(--os-muted)", textAlign: "center", fontSize: "0.75rem", gridColumn: "1 / -1" }), calc: css("os-calc", { display: "flex", flexDirection: "column", gap: "10px", flex: "1", minHeight: "0", padding: "14px" }), display: css("os-display", { display: "block", padding: "12px", borderRadius: "8px", backgroundColor: "var(--os-soft)", fontFamily: mono, fontSize: "1.7rem", textAlign: "right", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }), keys: css("os-keys", { display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gridAutoRows: "1fr", gap: "6px", flex: "1", minHeight: "0" }), key: css("os-key", { borderRadius: "7px", backgroundColor: "var(--os-soft)", color: "var(--os-text)", fontSize: "1rem", fontWeight: "600", hover: { backgroundColor: "var(--os-hover)" }, "&:nth-child(4n)": { color: "var(--os-accent-ink)" }, "&:last-child": { gridColumn: "span 4", color: "#fff", backgroundColor: "var(--os-accent)" } }), calcHint: css("os-calc-hint", { color: "var(--os-muted)", fontSize: "0.62rem", textAlign: "center" }), timer: css("os-timer", { display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: "20px", flex: "1", padding: "16px" }), countdown: css("os-countdown", { fontSize: "3rem", fontWeight: "400", letterSpacing: "-.03em", fontVariantNumeric: "tabular-nums" }), row: css("os-row", { display: "flex", flexWrap: "wrap", justifyContent: "center", gap: "6px" }), termWrap: css("os-term-wrap", { display: "flex", flexDirection: "column", flex: "1", minHeight: "0", backgroundColor: "#1e1e1e" }), // a terminal keeps its own dark palette in both themes term: css("os-term", { display: "flex", flexDirection: "column-reverse", flex: "1", minHeight: "0", overflowY: "auto", padding: "16px", backgroundColor: "#1e1e1e", color: "#e6e6e6", fontFamily: mono, fontSize: "0.75rem", lineHeight: "1.7", cursor: "text", "& pre": { margin: "0", whiteSpace: "pre-wrap", wordBreak: "break-word", fontFamily: "inherit" } }), prompt: css("os-prompt", { display: "flex", alignItems: "baseline", gap: "8px", color: "#8ff0a4", "& span": { whiteSpace: "nowrap" }, "& input:focus-visible": { outline: "none" }, "& input": { flex: "1", minWidth: "0", border: "none", backgroundColor: "transparent", color: "#fff", fontFamily: "inherit", fontSize: "inherit", caretColor: "#8ff0a4" } }), termIn: css("os-term-in", { whiteSpace: "pre-wrap", wordBreak: "break-word", color: "#fff" }), termPath: css("os-term-path", { color: "#8ff0a4" }), termSigil: css("os-term-sigil", { color: "#9a9996" }), termErr: css("os-term-err", { color: "#ff7b63" }), termKeys: css("os-term-keys", { display: "none", gap: "6px", flexShrink: 0, padding: "7px 10px", borderTop: "1px solid rgb(255 255 255 / .08)", overflowX: "auto", "@media (pointer: coarse)": { display: "flex" }, "& button": { flexShrink: 0, height: "34px", minWidth: "44px", padding: "0 12px", borderRadius: "7px", backgroundColor: "rgb(255 255 255 / .09)", color: "#e6e6e6", fontFamily: mono, fontSize: "0.75rem" } }), about: css("os-about", { display: "flex", flexDirection: "column", gap: "12px", flex: "1", minHeight: "0", overflowY: "auto", padding: "22px", fontSize: "0.8rem", lineHeight: "1.7", color: "var(--os-muted)", "& h3": { fontSize: "1rem", fontWeight: "600", color: "var(--os-text)" }, "& ol": { listStyle: "none", padding: "0" }, "& li + li": { borderTop: "1px solid var(--os-line)" } }), runningApp: css("os-running-app", { display: "flex", alignItems: "center", gap: "8px", width: "100%", padding: "8px 0", color: "var(--os-text)", "& span": { marginLeft: "auto", fontSize: "0.65rem", color: "var(--os-muted)" } }), setPage: css("os-set-page", { display: "flex", flexDirection: "column", gap: "18px", flex: "1", minHeight: "0", overflowY: "auto", padding: "18px", backgroundColor: "var(--os-soft)", "@container (max-width: 380px)": { padding: "12px" } }), setGroup: css("os-set-group", { display: "flex", flexDirection: "column", gap: "8px", "& h3": { padding: "0 4px", fontSize: "0.65rem", fontWeight: "700", textTransform: "uppercase", letterSpacing: "0.05em", color: "var(--os-muted)" } }), setCard: css("os-set-card", { borderRadius: "12px", border: "1px solid var(--os-line)", backgroundColor: "var(--os-panel)", "& > * + *": { borderTop: "1px solid var(--os-line)" } }), setRow: css("os-set-row", { display: "flex", alignItems: "center", justifyContent: "space-between", flexWrap: "wrap", gap: "10px 14px", minHeight: "58px", padding: "12px 14px" }), setStack: css("os-set-stack", { flexDirection: "column", flexWrap: "nowrap", alignItems: "stretch", "& .os-set-label": { flex: "none" } }), setLabel: css("os-set-label", { display: "flex", flexDirection: "column", gap: "2px", flex: "1 1 150px", minWidth: "0", "& strong": { fontSize: "0.8rem", fontWeight: "600" }, "& span": { fontSize: "0.68rem", lineHeight: "1.45", color: "var(--os-muted)" } }), setValue: css("os-set-value", { fontSize: "0.72rem", color: "var(--os-muted)", fontVariantNumeric: "tabular-nums", whiteSpace: "nowrap" }), seg: css("os-seg", { display: "flex", gap: "2px", padding: "2px", borderRadius: "9px", border: "1px solid var(--os-line)", backgroundColor: "var(--os-soft)" }), segItem: css("os-seg-item", { height: "28px", padding: "0 13px", borderRadius: "7px", fontSize: "0.72rem", fontWeight: "600", color: "var(--os-muted)", hover: { color: "var(--os-text)" }, "&[aria-pressed=true]": { backgroundColor: "var(--os-panel)", color: "var(--os-text)", boxShadow: "0 1px 2px rgb(0 0 0 / .16)" }, "@media (pointer: coarse)": { height: "36px" } }), setDots: css("os-set-dots", { display: "flex", gap: "10px", padding: "0 4px" }), setDot: css("os-set-dot", { width: "24px", height: "24px", borderRadius: "50%", backgroundColor: "#3584e4", "&[data-accent=green]": { backgroundColor: "#3a944a" }, "&[data-accent=purple]": { backgroundColor: "#9141ac" }, "&[data-accent=orange]": { backgroundColor: "#e66100" }, "&[aria-pressed=true]": { boxShadow: "0 0 0 2px var(--os-panel), 0 0 0 4px var(--os-text)" }, "@media (pointer: coarse)": { width: "32px", height: "32px" } }), setWalls: css("os-set-walls", { display: "grid", gridTemplateColumns: "repeat(3, minmax(0, 1fr))", gap: "8px" }), setWall: css("os-set-wall", { display: "flex", flexDirection: "column", gap: "6px", padding: "6px 6px 8px", borderRadius: "10px", fontSize: "0.7rem", fontWeight: "600", color: "var(--os-muted)", textAlign: "center", hover: { backgroundColor: "var(--os-soft)" }, "&[aria-pressed=true]": { backgroundColor: "var(--os-tint)", color: "var(--os-accent-ink)" }, "&[data-wallpaper=dusk] .os-set-wall-art": { backgroundColor: "#613583" }, "&[data-wallpaper=slate] .os-set-wall-art": { backgroundColor: "#3d3846" } }), // A wallpaper in miniature: its color, a window and the taskbar, drawn with two gradients. setWallArt: css("os-set-wall-art", { display: "block", aspectRatio: "16 / 10", borderRadius: "7px", backgroundColor: "#1a5fb4", backgroundRepeat: "no-repeat", backgroundImage: "linear-gradient(var(--os-panel), var(--os-panel)), linear-gradient(var(--os-panel), var(--os-panel))", backgroundSize: "46% 44%, 100% 16%", backgroundPosition: "26% 28%, 0 100%", boxShadow: "inset 0 0 0 1px rgb(0 0 0 / .12)" }), setFoot: css("os-set-foot", { padding: "0 4px", fontSize: "0.65rem", lineHeight: "1.5", color: "var(--os-muted)", textAlign: "center" }), kanban: css("os-kanban", { display: "flex", flexDirection: "column", flex: "1", minHeight: "0" }), kanbanHeading: css("os-kanban-heading", { fontSize: "0.8rem", fontWeight: "700" }), kanbanHint: css("os-kanban-hint", { "@container (max-width: 420px)": { visibility: "hidden" }, flex: "1", minWidth: "0", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", color: "var(--os-muted)", fontSize: "0.65rem" }), kanbanBoard: css("os-kanban-board", { display: "flex", gap: "8px", flex: "1", minHeight: "0", overflowX: "auto", padding: "12px", "@container (max-width: 560px)": { raw: { "scroll-snap-type": "x mandatory", "scroll-padding": "0 12px" } } }), kanbanColumn: css("os-kanban-column", { display: "flex", flexDirection: "column", flex: "1 1 0", minWidth: "170px", "@container (max-width: 560px)": { flex: "0 0 86%", raw: { "scroll-snap-align": "start" } }, borderRadius: "10px", border: "1px solid var(--os-line)", backgroundColor: "var(--os-soft)" }), kanbanAfter: css("os-kanban-after", { boxShadow: "inset 0 -3px 0 var(--os-accent)" }), kanbanColumnHead: css("os-kanban-column-head", { display: "flex", alignItems: "center", gap: "4px", padding: "9px 9px 7px", "& h3": { flex: "1", minWidth: "0", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", fontSize: "0.75rem", fontWeight: "700" } }), kanbanCount: css("os-kanban-count", { marginLeft: "5px", color: "var(--os-muted)", fontWeight: "500", fontVariantNumeric: "tabular-nums" }), kanbanSmall: css("os-kanban-small", { height: "24px", padding: "0 7px", borderRadius: "6px", fontSize: "0.7rem", fontWeight: "600", color: "var(--os-muted)", hover: { color: "var(--os-text)", backgroundColor: "var(--os-hover)" } }), kanbanCards: css("os-kanban-cards", { display: "flex", flexDirection: "column", gap: "6px", flex: "1", minHeight: "60px", padding: "0 7px 7px", overflowY: "auto" }), kanbanCard: css("os-kanban-card", { raw: { "-webkit-user-drag": "element" }, padding: "7px 8px 8px", borderRadius: "8px", border: "1px solid var(--os-line)", backgroundColor: "var(--os-panel)", boxShadow: "0 1px 2px rgb(0 0 0 / .05)", cursor: "grab", "&:active": { cursor: "grabbing" } }), kanbanLifted: css("os-kanban-lifted", { opacity: "0.4" }), kanbanBefore: css("os-kanban-before", { boxShadow: "0 -7px 0 -2px var(--os-accent)" }), kanbanCardHead: css("os-kanban-card-head", { display: "flex", alignItems: "center", gap: "5px", marginBottom: "3px" }), kanbanPriority: css("os-kanban-priority", { height: "18px", padding: "0 6px", borderRadius: "999px", fontSize: "0.6rem", fontWeight: "700", textTransform: "uppercase", letterSpacing: "0.02em" }), kanbanP1: css("os-kanban-p1", { backgroundColor: "var(--os-hover)", color: "var(--os-muted)" }), kanbanP2: css("os-kanban-p2", { backgroundColor: "var(--os-tint)", color: "var(--os-accent-ink)" }), kanbanP3: css("os-kanban-p3", { backgroundColor: "var(--os-accent)", color: "#fff" }), kanbanId: css("os-kanban-id", { flex: "1", color: "var(--os-muted)", fontSize: "0.6rem", fontFamily: mono, fontVariantNumeric: "tabular-nums" }), kanbanIcon: css("os-kanban-icon", { width: "22px", height: "22px", borderRadius: "5px", fontSize: "0.8rem", color: "var(--os-muted)", hover: { color: "var(--os-text)", backgroundColor: "var(--os-soft)" } }), kanbanMove: css("os-kanban-move", { display: "none", "@media (pointer: coarse)": { display: "inline-block" } }), // a finger cannot drag a card across: these carry it to the next column kanbanTitle: css("os-kanban-title", { fontSize: "0.78rem", lineHeight: "1.4", overflowWrap: "anywhere" }), kanbanEdit: css("os-kanban-edit", { width: "100%", padding: "4px 6px", border: "1px solid var(--os-accent)", borderRadius: "6px", fontSize: "0.78rem", fontFamily: "inherit", color: "var(--os-text)", backgroundColor: "var(--os-field)" }), kanbanAdd: css("os-kanban-add", { display: "flex", gap: "5px", padding: "0 7px 7px", "& input": { flex: "1" } }), kanbanEmpty: css("os-kanban-empty", { padding: "10px 8px", color: "var(--os-muted)", fontSize: "0.7rem", textAlign: "center" }), calendar: css("os-calendar", { display: "flex", flexDirection: "column", gap: "10px", flex: "1", minHeight: "0", overflowY: "auto", padding: "12px" }), calMonth: css("os-cal-month", { flex: "1", textAlign: "center", fontSize: "0.8rem", fontWeight: "700" }), calGrid: css("os-cal-grid", { display: "grid", gridTemplateColumns: "repeat(7, 1fr)", gap: "3px" }), calWeekday: css("os-cal-weekday", { padding: "2px 0 5px", textAlign: "center", fontSize: "0.62rem", fontWeight: "700", color: "var(--os-muted)", textTransform: "uppercase", letterSpacing: "0.03em" }), calDay: css("os-cal-day", { position: "relative", display: "flex", alignItems: "center", justifyContent: "center", aspectRatio: "1", minHeight: "32px", borderRadius: "7px", fontSize: "0.8rem", color: "var(--os-text)", hover: { backgroundColor: "var(--os-soft)" }, "&[aria-pressed=true]": { backgroundColor: "var(--os-accent)", color: "#fff" }, "&[aria-pressed=true] .os-cal-dot": { backgroundColor: "#fff" } }), calToday: css("os-cal-today", { color: "var(--os-accent-ink)", fontWeight: "700" }), calDot: css("os-cal-dot", { position: "absolute", bottom: "5px", left: "50%", transform: "translateX(-50%)", width: "5px", height: "5px", borderRadius: "50%", backgroundColor: "var(--os-accent)" }), calGap: css("os-cal-gap", { minHeight: "32px" }), calNote: css("os-cal-note", { display: "flex", flexDirection: "column", gap: "6px", paddingTop: "10px", borderTop: "1px solid var(--os-line)" }), calNoteHead: css("os-cal-note-head", { display: "flex", alignItems: "center", gap: "8px", "& strong": { flex: "1", minWidth: "0", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", fontSize: "0.75rem" } }), calInput: css("os-cal-input", { width: "100%", minHeight: "54px", padding: "8px 10px", borderRadius: "7px", border: "1px solid var(--os-line)", backgroundColor: "var(--os-panel)", color: "var(--os-text)", fontFamily: "inherit", fontSize: "0.78rem", lineHeight: "1.5", resize: "none", "&::placeholder": { color: "var(--os-muted)" } }), finance: css("os-finance", { display: "flex", flexDirection: "column", flex: "1", minHeight: "0" }), finBody: css("os-fin-body", { display: "flex", flexDirection: "column", flex: "1", minHeight: "0" }), finHidden: css("os-fin-hidden", { display: "none" }), financeHeading: css("os-finance-heading", { fontSize: "0.8rem", fontWeight: "700" }), finHint: css("os-fin-hint", { "@container (max-width: 420px)": { visibility: "hidden" }, flex: "1", minWidth: "0", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", color: "var(--os-muted)", fontSize: "0.65rem" }), finTabs: css("os-fin-tabs", { display: "flex", gap: "2px", padding: "2px", borderRadius: "8px", border: "1px solid var(--os-line)", backgroundColor: "var(--os-soft)" }), finTab: css("os-fin-tab", { height: "26px", padding: "0 12px", borderRadius: "6px", fontSize: "0.72rem", fontWeight: "600", color: "var(--os-muted)", hover: { color: "var(--os-text)" } }), finTabOn: css("os-fin-tab-on", { backgroundColor: "var(--os-panel)", color: "var(--os-text)", boxShadow: "0 1px 2px rgb(0 0 0 / .08)", hover: { color: "var(--os-text)" } }), finLoading: css("os-fin-loading", { padding: "40px 12px", textAlign: "center", color: "var(--os-muted)", fontSize: "0.75rem" }), finCharts: css("os-fin-charts", { display: "flex", flexDirection: "column", gap: "10px", flex: "1", minHeight: "0", overflowY: "auto", padding: "12px" }), finCards: css("os-fin-cards", { display: "grid", gridTemplateColumns: "repeat(4, minmax(0, 1fr))", gap: "8px", "@container (max-width: 560px)": { gridTemplateColumns: "repeat(2, minmax(0, 1fr))" } }), finStat: css("os-fin-stat", { gap: "2px", padding: "12px 14px" }), finStatTitle: css("os-fin-stat-title", { fontSize: "0.68rem", fontWeight: "700" }), finStatSub: css("os-fin-stat-sub", { fontSize: "0.62rem", color: "var(--os-muted)" }), finStatValue: css("os-fin-stat-value", { fontSize: "1.05rem", fontWeight: "600", fontVariantNumeric: "tabular-nums" }), finPos: css("os-fin-pos", { color: "var(--os-accent-ink)" }), finNeg: css("os-fin-neg", { color: "var(--os-danger-ink)" }), finGrid: css("os-fin-grid", { display: "grid", gridTemplateColumns: "minmax(0, 1.5fr) minmax(0, 1fr)", gap: "10px", alignItems: "start", "@container (max-width: 560px)": { gridTemplateColumns: "minmax(0, 1fr)" } }), finCard: css("os-fin-card", { display: "flex", flexDirection: "column", gap: "10px", padding: "14px", borderRadius: "10px", border: "1px solid var(--os-line)", backgroundColor: "var(--os-panel)" }), finWide: css("os-fin-wide", { gridColumn: "1 / -1" }), finCardHead: css("os-fin-card-head", { display: "flex", alignItems: "baseline", gap: "8px", "& h3": { fontSize: "0.8rem", fontWeight: "700" } }), finCardSub: css("os-fin-card-sub", { color: "var(--os-muted)", fontSize: "0.62rem" }), finDonutRow: css("os-fin-donut-row", { display: "flex", alignItems: "center", gap: "14px", flexWrap: "wrap" }), finLegend: css("os-fin-legend", { display: "flex", flexDirection: "column", gap: "5px", flex: "1", minWidth: "130px" }), finLegendItem: css("os-fin-legend-item", { display: "flex", alignItems: "center", gap: "7px", fontSize: "0.68rem" }), finLegendDot: css("os-fin-legend-dot", { width: "9px", height: "9px", borderRadius: "3px", flexShrink: 0 }), finLegendLabel: css("os-fin-legend-label", { flex: "1", minWidth: "0", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }), finLegendValue: css("os-fin-legend-value", { color: "var(--os-muted)", fontVariantNumeric: "tabular-nums", whiteSpace: "nowrap" }), finKey: css("os-fin-key", { display: "flex", gap: "14px", justifyContent: "center", color: "var(--os-muted)", fontSize: "0.65rem" }), finKeyItem: css("os-fin-key-item", { display: "flex", alignItems: "center", gap: "6px" }), finSheet: css("os-fin-sheet", { display: "flex", flexDirection: "column", flex: "1", minHeight: "0" }), finScroller: css("os-fin-scroller", { flex: "1", minHeight: "0", overflow: "auto" }), finTable: css("os-fin-table", { width: "100%", borderCollapse: "separate", borderSpacing: "0", fontSize: "0.76rem" }), finTh: css("os-fin-th", { position: "sticky", top: "0", zIndex: 1, padding: "7px 10px", textAlign: "left", fontSize: "0.62rem", fontWeight: "700", textTransform: "uppercase", letterSpacing: "0.04em", color: "var(--os-muted)", backgroundColor: "var(--os-panel)", borderBottom: "1px solid var(--os-line)" }), finTd: css("os-fin-td", { padding: "0", borderBottom: "1px solid var(--os-line)", verticalAlign: "middle" }), finRow: css("os-fin-row", { hover: { backgroundColor: "var(--os-soft)" } }), finCell: css("os-fin-cell", { display: "block", width: "100%", padding: "7px 10px", textAlign: "inherit", fontSize: "inherit", color: "var(--os-text)", cursor: "text", hover: { backgroundColor: "var(--os-soft)" } }), finPlaceholder: css("os-fin-placeholder", { color: "var(--os-muted)" }), finInput: css("os-fin-input", { width: "100%", height: "30px", padding: "0 8px", border: "1px solid var(--os-accent)", borderRadius: "6px", backgroundColor: "var(--os-field)", color: "var(--os-text)", fontFamily: "inherit", fontSize: "inherit", textAlign: "inherit" }), finAmount: css("os-fin-amount", { textAlign: "right", fontVariantNumeric: "tabular-nums" }), finIncome: css("os-fin-income", { color: "var(--os-accent-ink)" }), finExpense: css("os-fin-expense", { color: "var(--os-danger-ink)" }), finDelete: css("os-fin-delete", { width: "34px" }), finIcon: css("os-fin-icon", { display: "flex", alignItems: "center", justifyContent: "center", width: "26px", height: "26px", margin: "2px auto", borderRadius: "6px", fontSize: "0.85rem", color: "var(--os-muted)", hover: { color: "var(--os-danger-ink)", backgroundColor: "var(--os-danger-soft)" } }), finEmpty: css("os-fin-empty", { padding: "34px 12px", textAlign: "center", color: "var(--os-muted)", fontSize: "0.75rem" }), finFoot: css("os-fin-foot", { display: "flex", alignItems: "center", gap: "10px", padding: "9px 12px", borderTop: "1px solid var(--os-line)", color: "var(--os-muted)", fontSize: "0.68rem" }), finFootTotal: css("os-fin-foot-total", { marginLeft: "auto", whiteSpace: "nowrap", "& strong": { color: "var(--os-text)", fontVariantNumeric: "tabular-nums" } }), };