Examples
Practical examples। Live demos।
कोई example चुनिए और फ़ुल-स्क्रीन में खोलिए: live preview और source code साथ-साथ।
कोई example चुनिए और फ़ुल-स्क्रीन में खोलिए: live preview और source code साथ-साथ।
files, notes, terminal, calculator, timer, kanban board, finance app और calendar वाला चलता-फिरता desktop। browser में save होने वाली shared simulated disk पर folders बनाइए और organize कीजिए, notes edit कीजिए और shell commands चलाइए। calculator में सीधे keyboard से टाइप कीजिए, input पर focus करने के लिए terminal में कहीं भी click कीजिए, board पर columns के बीच cards drag कीजिए, या finance spreadsheet में हिसाब रखिए और chart बदलते देखिए। हिसाब IndexedDB में रहता है। app की windows खिसकाने, resize करने या app बदलने पर उनका state बना रहता है। चलता हुआ timer into() से taskbar tray भरता है।
// 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 taskbar 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. // // Updates are scoped: every window carries scope(winScopeId(win)), and the // taskbar, the clock and the context menu carry their own scopes, 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 { appearance, calendar, files, finance, kanban, notes, openFile, PROGRAMS, settings, terminal, type Program } from "./programs.ts"; import { active, close, focus, minimize, move, open, requestClose, resize, setDesk, toggleMaximize, windows, winScopeId, type Win } 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 { s } from "./styles.ts"; let menuOpen = false; let search = ""; let clock = "--:--"; let date = ""; let booted = false; let diskLoaded = false; 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"); } // 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). function drag(win: Win, from: () => [number, number], to: (a: number, b: number) => void) { let dx = 0; let dy = 0; return { onPointerDown: (e: Press) => { if (win.maximized || e.button !== 0) return; e.currentTarget.setPointerCapture(e.pointerId); const [a, b] = from(); dx = a - e.clientX; dy = b - e.clientY; }, onPointerMove: (e: Press) => { if (!e.currentTarget.hasPointerCapture(e.pointerId)) return; to(e.clientX + dx, e.clientY + dy); winUpdate(win); // only this window's frame moves }, }; } 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).className, style: () => { const [left, top, width, height] = win.maximized ? ["0", "0", "100%", "100%"] : [win.x, win.y, win.w, win.h].map((n) => `${n}px`); return { left, top, width, height, 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)), icon(win.program.icon, 17), 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", 15)), button(s.ctl, { title: () => (win.maximized ? "Restore" : "Maximize"), "aria-label": "Maximize", "aria-pressed": () => String(win.maximized), onClick: () => { toggleMaximize(win); winUpdate(win); } }, icon("maximize", 14)), // Closing is structural: the windows list rebuilds, so one global update. button(s.ctl, s.close, { title: "Close", "aria-label": "Close", onClick: () => { requestClose(win); update(); } }, icon("close", 15)), ), div(s.body, win.program.view(win)), div(s.grip, drag(win, () => [win.w, win.h], (w, h) => resize(win, w, h))), when(() => win.confirming, into("os-modal", ConfirmDialog(win))), ); } function TaskButton(win: Win) { return button( s.task, { class: () => cx(s.task, win === active() ? s.current : null, win.minimized ? s.faded : null).className, "aria-haspopup": "menu", onContextMenu: (e) => showContextMenu(e, win.title, windowActions(win)), onKeyDown: (e) => { contextMenuKey(e, win.title, windowActions(win)); }, title: () => win.title, "aria-pressed": () => String(win === active()), onClick: () => { const prev = active(); if (win === prev) minimize(win); else focus(win); update(winScopeId(win), ...(prev && prev !== win ? [winScopeId(prev)] : []), "os-taskbar"); }, }, icon(win.program.icon, 18), span(s.label, () => win.title), ); } function Icon(program: Program) { return button( s.icon, { "aria-haspopup": "menu", onContextMenu: (e) => showContextMenu(e, program.name, [{ label: `Open ${program.name}`, icon: program.icon, run: () => { open(program); } }]), onKeyDown: (e) => { contextMenuKey(e, program.name, [{ label: `Open ${program.name}`, icon: program.icon, run: () => { open(program); } }]); }, title: `Open ${program.name}`, onClick: () => { open(program); 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(() => clock), span(s.clockDate, () => date), ); } export function Desktop() { return div( s.app, contextMenuLifecycle(), { tabIndex: -1, "data-wallpaper": () => appearance.wallpaper, 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); menuOpen = false; showContextMenu(e, win?.title ?? "Desktop", win ? windowActions(win) : desktopActions()); }, onKeyDown: (e) => { if (e.key === "Escape" && menuOpen) { e.stopPropagation(); menuOpen = false; update("os-taskbar"); } 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; } try { const saved = localStorage.getItem("nuclo-desktop-wallpaper"); if (saved && ["grove", "dusk", "slate"].includes(saved)) appearance.wallpaper = saved; } catch {} update(); }), 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); } 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; menuOpen = false; showContextMenu(e, "Desktop", desktopActions()); }, onKeyDown: (e) => { if (e.target === e.currentTarget) contextMenuKey(e, "Desktop", desktopActions()); }, onPointerDown: () => { if (menuOpen) { menuOpen = false; update("os-taskbar"); } } }, 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.")), div(s.icons, ...Object.values(PROGRAMS).slice(0, 7).map(Icon)), list(() => windows, WindowView), ), footer( s.taskbar, scope("os-taskbar"), button(s.start, { "aria-expanded": () => String(menuOpen), onClick: () => { dismissContextMenu(); menuOpen = !menuOpen; update("os-taskbar"); } }, icon("grid", 18), span("Apps")), when(() => menuOpen, nav(s.menu, { "aria-label": "Applications" }, div(s.launcherHeading, strong("Your workspace"), span("Find something to open")), input(s.input, { type: "search", "aria-label": "Search apps", placeholder: "Search apps…", value: () => search, onMount: (el) => el.focus(), onInput: (e) => { search = e.currentTarget.value; update("os-taskbar"); }, onKeyDown: (e) => { if (e.key === "Enter") { const program = Object.values(PROGRAMS).find((p) => p.name.toLowerCase().includes(search.toLowerCase())); if (program) { open(program); menuOpen = false; update(); } } } }), list(() => Object.values(PROGRAMS).filter((p) => p.name.toLowerCase().includes(search.toLowerCase())), (p) => button(s.item, { onClick: () => { menuOpen = false; open(p); update(); } }, icon(p.icon), p.name)), when(() => !Object.values(PROGRAMS).some((p) => p.name.toLowerCase().includes(search.toLowerCase())), p(s.empty, "No matching apps")), )), div(s.tasks, list(() => windows, TaskButton)), button(s.showDesktop, { title: "Show desktop", "aria-label": "Show desktop", onClick: () => { for (const win of windows) minimize(win); update(...windows.map((win) => winScopeId(win)), "os-taskbar"); } }, icon("minimize", 18)), // The tray: programs put their own icons here with into("os-tray", ...). div(s.tray, region({ id: "os-tray", type: "stack" }), Clock()), ), // The modal layer, over the desktop and the taskbar. 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 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.max(0, Math.min(v, max)); /** The topmost window that is not minimized. */ export const active = () => windows.reduce<Win | null>((a, w) => (!w.minimized && (!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, state: program.init(), }; move(win, 104 + step, 16 + step); // right of the desktop icons windows.push(win); return win; } export function close(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 function resize(win: Win, w: number, h: number) { win.w = Math.min(desk.w - win.x, Math.max(MIN.w, w)); win.h = Math.min(desk.h - win.y, Math.max(MIN.h, h)); } /** 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 taskbar 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, entries, getEntry, moveEntry, pathOf, renameEntry, resolvePath, restoreEntry, storageStatus, trashEntry, writeEntry, type Entry } from "./filesystem.ts"; import { kanban } from "./kanban.ts"; import { calendar } from "./calendar.ts"; import { finance } from "./finance.ts"; import { s } from "./styles.ts"; export { kanban, calendar, finance }; 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 } export const files: Program<Explorer> = { name: "Files", icon: "files", size: [620, 380], init: () => ({ folder: "documents", selected: "", search: "", action: "", name: "", destination: "root", error: "", layout: "list" }), view: (win) => { const state = win.state; const refresh = () => update(winScopeId(win)); // files updates stay in this window const navigate = (folder: string) => { Object.assign(state, { folder, selected: "", search: "", action: "", error: "" }); refresh(); }; const selected = () => rows().find((entry) => entry.id === state.selected); const isTrash = () => state.folder === "trash"; const rows = () => (isTrash() ? entries.filter((e) => e.trashed) : available(state.folder) ? children(state.folder) : []).filter((e) => e.name.toLowerCase().includes(state.search.toLowerCase())); 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(); }; // 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 = () => [ { label: "New folder", icon: "files", disabled: isTrash() || !available(state.folder), run: () => start("folder") }, { label: "New note", icon: "notes", disabled: isTrash() || !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: isTrash() || !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: () => perform(() => { trashEntry(entry.id); state.selected = ""; }) }, ]; }; 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))), p(s.diskHint, "Simulated disk", br(), "Private to this browser"), ), div(s.fileMain, div(s.toolbar, button(s.btn, { "aria-label": "Parent folder", disabled: () => state.folder === "root" || isTrash(), onClick: () => navigate(getEntry(state.folder)?.parent ?? "root") }, icon("up", 16)), span(s.breadcrumb, () => isTrash() ? "Trash" : pathOf(state.folder)), button(s.btn, { "aria-label": "Toggle file layout", 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: "Search this folder", value: () => state.search, onInput: (e) => { state.search = e.currentTarget.value; refresh(); } }), button(s.btn, { disabled: isTrash, onClick: () => start("folder") }, "New folder"), button(s.btn, s.primary, { disabled: isTrash, 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 { 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))))) .else(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, s.primary, { type: "submit" }, () => state.action === "rename" ? "Rename" : state.action === "move" ? "Move" : "Create"), button(s.btn, { type: "button", onClick: () => { state.action = ""; state.error = ""; refresh(); } }, "Cancel"), )), when(() => !!state.error, p(s.error, { role: "alert" }, () => state.error)), div(s.fileList, { tabIndex: 0, "aria-haspopup": "menu", "aria-label": "Folder contents", onContextMenu: (e) => showContextMenu(e, isTrash() ? "Trash" : pathOf(state.folder), folderActions()), onKeyDown: (e) => { if (e.target === e.currentTarget) contextMenuKey(e, isTrash() ? "Trash" : pathOf(state.folder), folderActions()); }, class: () => cx(s.fileList, state.layout === "grid" ? s.fileGrid : null).className }, list(rows, (entry) => button(s.fileRow, { "aria-haspopup": "menu", onContextMenu: (e) => showContextMenu(e, entry.name, entryActions(entry)), "aria-pressed": () => String(state.selected === entry.id), onClick: () => { 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, () => entry.kind === "folder" ? `${children(entry.id).length} items` : `${new TextEncoder().encode(entry.content).length} B`), )), 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, () => selected()?.name ?? `${rows().length} items`), 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, { "aria-label": "Move to Trash", onClick: () => perform(() => { trashEntry(state.selected); state.selected = ""; }) }, 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 // taskbar tray — so a tick refreshes this window and the taskbar scope. const tick = () => update(winScopeId(win), "os-taskbar"); 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 taskbar. 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", 15), () => mmss(t.left)))), ); }, }; interface Shell { lines: string[]; cwd: string; history: string[]; cursor: number; opened: boolean } const COMMANDS: Record<string, (args: string[], shell: Shell) => string | void> = { help: () => "Files: pwd · ls [path] · cd <folder> · cat <file>\nEdit: mkdir <name> · touch <name> · echo <text> > <file> · rm <path>\nApps: apps · open <app or file> · windows\nOther: date · clear · help\nUse quotes for 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."; }, 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; }, open: ([name = ""], shell) => { shell.opened = true; // a new window joins the desktop: the caller needs a global update 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 open(files).state.folder = 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. Returns true when it opened a window: then the caller needs a global update. */ function run(shell: Shell, line: string) { if (!available(shell.cwd)) shell.cwd = "root"; shell.lines.push(`${pathOf(shell.cwd)} $ ${line}`); if (!line.trim()) return false; shell.history.push(line); shell.cursor = shell.history.length; shell.opened = false; 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) shell.lines.push(out); } catch (e) { shell.lines.push((e as Error).message); } return shell.opened; } export const terminal: Program<Shell> = { name: "Terminal", icon: "terminal", size: [510, 340], init: () => ({ lines: ['Nuclo shell · your local workspace', 'Type "help" for commands.'], cwd: "documents", history: [], cursor: 0, opened: false }), view: (win) => div(s.term, // 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. { title: "Click anywhere to type", onClick: (e) => { const input = e.currentTarget.querySelector<HTMLInputElement>("input"); if (!input || e.target === input) return; input.focus(); const end = input.value.length; input.setSelectionRange(end, end); } }, div(pre(() => win.state.lines.join("\n")), div(s.prompt, span(() => `${pathOf(win.state.cwd)} $`), input({ "aria-label": "Command", autocomplete: "off", spellcheck: false, onMount: (el) => el.focus(), onKeyDown: (e) => { if (e.key === "ArrowUp" || e.key === "ArrowDown") { e.preventDefault(); win.state.cursor = Math.max(0, Math.min(win.state.history.length, win.state.cursor + (e.key === "ArrowUp" ? -1 : 1))); e.currentTarget.value = win.state.history[win.state.cursor] ?? ""; return; } if (e.key !== "Enter") return; const opened = run(win.state, e.currentTarget.value); e.currentTarget.value = ""; if (opened) update(); else update(winScopeId(win)); // opening an app changes the windows list } })), ), ), }; export const appearance = { wallpaper: "grove" }; export const settings: Program<null> = { name: "Settings", icon: "settings", size: [360, 320], init: () => null, view: () => div(s.about, h3("Make it yours"), p("Choose a backdrop for your workspace."), // Global: the wallpaper attribute lives on the desktop root, outside this window. div(s.wallpapers, ...[["grove", "Grove"], ["dusk", "Dusk"], ["slate", "Slate"]].map(([value, label]) => button(s.swatch, { "aria-pressed": () => String(appearance.wallpaper === value), "data-wallpaper": value, onClick: () => { appearance.wallpaper = value; try { localStorage.setItem("nuclo-desktop-wallpaper", value); } catch {} update(); } }, label))), h3("Your local workspace"), p(() => storageStatus), p("This is a simulated file system. Files stay in this browser, and no real files on your device are changed."), ), }; 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 with one click. Drag a title to move its window; double-click to maximize. Your open apps live in the taskbar."), 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 };
// 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(); } 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}`), 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"; const control = { minHeight: "32px", padding: "0 11px", borderRadius: "7px", border: "1px solid var(--os-line)", backgroundColor: "var(--os-panel)", color: "var(--os-text)", fontFamily: "inherit", fontSize: "0.75rem", fontWeight: "600", whiteSpace: "nowrap", display: "inline-flex", alignItems: "center", justifyContent: "center", gap: "6px", cursor: "pointer" }; const focusRing = { outline: "2px solid var(--os-accent)", outlineOffset: "2px" }; export const s = { contextMenu: css("os-context-menu", { 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", cursor: "pointer", hover: { backgroundColor: "var(--os-soft)" }, "&:focus-visible": { outlineOffset: "-2px", backgroundColor: "var(--os-soft)" } }), contextDanger: css("os-context-danger", { color: "#a23737", hover: { backgroundColor: "#f9e8e4" } }), app: css("os-app", { position: "relative", isolation: "isolate", display: "flex", flexDirection: "column", width: "100%", height: "100%", overflow: "hidden", borderRadius: "14px", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif", color: "var(--os-text)", raw: { "--os-panel": "#f9fbfa", "--os-soft": "#edf2ef", "--os-text": "#233c34", "--os-muted": "#596c64", "--os-line": "#d7e1db", "--os-accent": "#237556", "--os-warm": "#174c3c", "scrollbar-color": "#9bafa3 transparent", "scrollbar-width": "thin" }, "& button:focus-visible, & input:focus-visible, & textarea:focus-visible, & select:focus-visible, & [tabindex='0']:focus-visible": focusRing, "@media (max-width: 600px)": { "& .os-btn, & .os-ctl, & .os-side-item": { minHeight: "36px" } }, "& button:disabled": { opacity: ".45", cursor: "default" }, "& ::selection": { backgroundColor: "#c5ead4", color: "#163d2c" }, "&[data-wallpaper=dusk]": { raw: { "--os-warm": "#624c67" } }, "&[data-wallpaper=slate]": { raw: { "--os-warm": "#344b61" } } }), desk: css("os-desk", { position: "relative", isolation: "isolate", flex: "1", minHeight: "0", overflow: "hidden", backgroundColor: "var(--os-warm)" }), 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: "#e0eee5", "& strong": { fontSize: "1.7rem", fontWeight: "500", letterSpacing: "-.03em" }, "& span": { fontSize: "0.8rem" }, "@media (max-width: 600px)": { display: "none" } }), icons: css("os-icons", { display: "flex", flexDirection: "column", flexWrap: "wrap", alignContent: "flex-start", gap: "3px", height: "100%", padding: "14px 8px", "@media (max-width: 600px)": { "& > button:nth-child(n+4)": { display: "none" } } }), 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: "#f0f7f2", touchAction: "manipulation", userSelect: "none", cursor: "pointer", hover: { backgroundColor: "rgb(255 255 255 / .12)" } }), glyph: css("os-glyph", { display: "flex", alignItems: "center", justifyContent: "center", width: "43px", height: "43px", borderRadius: "12px", color: "#285644", backgroundColor: "#dfebdf", boxShadow: "0 3px 6px rgb(0 0 0 / .12)", "&[data-app=notes]": { color: "#795522", backgroundColor: "#f7eacb" }, "&[data-app=terminal]": { color: "#def0e6", backgroundColor: "#253c33" }, "&[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", display: "flex", flexDirection: "column", borderRadius: "12px", overflow: "hidden", backgroundColor: "var(--os-panel)", boxShadow: "0 8px 28px rgb(0 0 0 / .19)" }), active: css("os-active", { boxShadow: "0 16px 42px rgb(0 0 0 / .28)", "& > header": { backgroundColor: "#f9fbfa", color: "var(--os-text)" } }), minimized: css("os-minimized", { display: "none" }), maximized: css("os-maximized", { borderRadius: "0", "& .os-grip": { display: "none" } }), bar: css("os-bar", { display: "flex", alignItems: "center", gap: "3px", height: "42px", flexShrink: 0, paddingRight: "7px", borderBottom: "1px solid var(--os-line)", backgroundColor: "var(--os-soft)", color: "var(--os-muted)", userSelect: "none" }), title: css("os-title", { display: "flex", alignItems: "center", gap: "8px", flex: "1", minWidth: "0", height: "100%", paddingLeft: "14px", fontSize: "0.75rem", fontWeight: "600", cursor: "grab", touchAction: "none", "& span": { overflow: "hidden", whiteSpace: "nowrap", textOverflow: "ellipsis" } }), dirty: css("os-dirty", { color: "var(--os-accent)" }), ctl: css("os-ctl", { display: "flex", alignItems: "center", justifyContent: "center", width: "30px", height: "30px", borderRadius: "7px", color: "var(--os-muted)", cursor: "pointer", hover: { color: "var(--os-text)", backgroundColor: "#e4ebe6" } }), close: css("os-close", { hover: { color: "#9e3434", backgroundColor: "#f6dede" } }), body: css("os-body", { display: "flex", flexDirection: "column", flex: "1", minHeight: "0", overflow: "hidden" }), grip: css("os-grip", { position: "absolute", right: "1px", bottom: "1px", width: "16px", height: "16px", cursor: "nwse-resize", touchAction: "none", backgroundImage: "linear-gradient(135deg, transparent 55%, #879e90 55% 62%, transparent 62% 76%, #879e90 76% 83%, transparent 83%)" }), backdrop: css("os-backdrop", { position: "absolute", inset: "0", zIndex: 10, display: "flex", alignItems: "center", justifyContent: "center", padding: "16px", backgroundColor: "rgb(12 27 20 / .5)" }), dialog: css("os-dialog", { 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)", "& h3": { fontSize: "1.1rem", fontWeight: "600" }, "& p": { fontSize: "0.875rem", color: "var(--os-muted)" } }), actions: css("os-actions", { display: "flex", justifyContent: "flex-end", gap: "8px", marginTop: "12px" }), taskbar: css("os-taskbar", { position: "relative", display: "flex", alignItems: "center", gap: "8px", height: "58px", flexShrink: 0, padding: "0 12px", backgroundColor: "var(--os-panel)", "@media (max-width: 600px)": { gap: "4px", padding: "0 6px" } }), start: css("os-start", { ...control, minHeight: "36px", flexShrink: 0, backgroundColor: "var(--os-text)", borderColor: "transparent", color: "#fff", hover: { backgroundColor: "var(--os-accent)" } }), menu: css("os-menu", { position: "absolute", left: "12px", bottom: "calc(100% + 10px)", zIndex: 1, display: "flex", flexDirection: "column", gap: "3px", width: "min(280px, calc(100vw - 72px))", maxHeight: "min(460px, 65vh)", overflowY: "auto", padding: "14px", borderRadius: "14px", backgroundColor: "var(--os-panel)", boxShadow: "0 12px 40px rgb(0 0 0 / .25)" }), launcherHeading: css("os-launcher-heading", { display: "flex", flexDirection: "column", gap: "3px", marginBottom: "10px", "& strong": { fontSize: "0.95rem" }, "& span": { fontSize: "0.75rem", color: "var(--os-muted)" } }), item: css("os-item", { display: "flex", alignItems: "center", gap: "12px", minHeight: "38px", padding: "0 10px", borderRadius: "7px", fontSize: "0.8rem", color: "var(--os-text)", textAlign: "left", cursor: "pointer", hover: { backgroundColor: "var(--os-soft)" } }), tasks: css("os-tasks", { display: "flex", gap: "5px", flex: "1", minWidth: "0", overflowX: "auto", raw: { "scrollbar-width": "none" } }), task: css("os-task", { display: "flex", alignItems: "center", gap: "8px", flexShrink: 0, maxWidth: "170px", height: "38px", padding: "0 12px", borderRadius: "8px", fontSize: "0.75rem", color: "var(--os-muted)", cursor: "pointer", hover: { backgroundColor: "var(--os-soft)" } }), current: css("os-current", { color: "#20583f", backgroundColor: "#dfede3", boxShadow: "inset 0 -2px 0 #237556", hover: { backgroundColor: "#dfede3" } }), faded: css("os-faded", { color: "#687b70" }), label: css("os-label", { overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", "@media (max-width: 600px)": { display: "none" } }), showDesktop: css("os-show-desktop", { ...control, width: "32px", padding: "0", "@media (max-width: 600px)": { display: "none" } }), tray: css("os-tray", { display: "flex", alignItems: "center", gap: "6px", flexShrink: 0, fontSize: "0.75rem", fontVariantNumeric: "tabular-nums" }), trayItem: css("os-tray-item", { ...control, color: "var(--os-accent)", backgroundColor: "var(--os-soft)" }), clock: css("os-clock", { display: "flex", flexDirection: "column", alignItems: "flex-end", gap: "2px", padding: "0 6px", color: "var(--os-text)", fontSize: "0.75rem", fontWeight: "600" }), clockDate: css("os-clock-date", { color: "var(--os-muted)", fontSize: "0.65rem", fontWeight: "400" }), btn: css("os-btn", { ...control, hover: { backgroundColor: "var(--os-soft)" } }), primary: css("os-primary", { backgroundColor: "var(--os-accent)", borderColor: "transparent", color: "#fff", hover: { backgroundColor: "#18583f" } }), danger: css("os-danger", { backgroundColor: "#ad3434", borderColor: "transparent", color: "#fff", hover: { backgroundColor: "#912727" } }), input: css("os-input", { minWidth: "0", width: "100%", height: "32px", padding: "0 10px", border: "1px solid var(--os-line)", borderRadius: "7px", backgroundColor: "var(--os-panel)", color: "var(--os-text)", fontFamily: "inherit", fontSize: "0.8rem", "&::placeholder": { color: "var(--os-muted)" }, "@media (max-width: 600px)": { fontSize: "16px" } }), toolbar: css("os-toolbar", { display: "flex", alignItems: "center", gap: "7px", padding: "9px 12px", flexShrink: 0, borderBottom: "1px solid var(--os-line)", "@media (max-width: 600px)": { 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: "#fffdf5", color: "#3f473c", fontFamily: "inherit", fontSize: "0.875rem", lineHeight: "1.8", raw: { "caret-color": "#237556" }, "&::placeholder": { color: "#63715f" }, "@media (max-width: 600px)": { fontSize: "16px", 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: "#fff0ed", color: "#933b30", 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)", "@media (max-width: 600px)": { 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)", cursor: "pointer", "&[aria-current=page]": { backgroundColor: "#d9e7dc", color: "#20583f", fontWeight: "600" }, hover: { backgroundColor: "#e0e9e2" } }), 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" }), breadcrumb: css("os-breadcrumb", { flex: "1", minWidth: "0", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", fontSize: "0.75rem", fontWeight: "600" }), 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: "48px", padding: "8px 10px", borderRadius: "7px", textAlign: "left", cursor: "pointer", color: "var(--os-text)", hover: { backgroundColor: "var(--os-soft)" }, "&[aria-pressed=true]": { backgroundColor: "#dfede3" } }), fileIcon: css("os-file-icon", { display: "flex", color: "#688a70" }), 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%" } }), 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", cursor: "pointer", hover: { backgroundColor: "#dce7df" }, "&:nth-child(4n)": { color: "var(--os-accent)" }, "&: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" }), term: css("os-term", { display: "flex", flexDirection: "column-reverse", flex: "1", minHeight: "0", overflowY: "auto", padding: "16px", backgroundColor: "#172b23", color: "#d9e9df", 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: "#a3dab6", "& span": { whiteSpace: "nowrap" }, "& input": { flex: "1", minWidth: "0", border: "none", backgroundColor: "transparent", color: "#e1eee6", fontFamily: "inherit", fontSize: "inherit", caretColor: "#a3dab6" } }), 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)", cursor: "pointer", "& span": { marginLeft: "auto", fontSize: "0.65rem", color: "var(--os-muted)" } }), wallpapers: css("os-wallpapers", { display: "flex", gap: "8px", flexWrap: "wrap" }), swatch: css("os-swatch", { padding: "18px 14px", borderRadius: "8px", color: "#fff", backgroundColor: "#174c3c", fontSize: "0.75rem", cursor: "pointer", "&[data-wallpaper=dusk]": { backgroundColor: "#624c67" }, "&[data-wallpaper=slate]": { backgroundColor: "#344b61" }, "&[aria-pressed=true]": { outline: "2px solid var(--os-accent)", outlineOffset: "3px" } }), 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", { 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" }), kanbanColumn: css("os-kanban-column", { display: "flex", flexDirection: "column", flex: "1 1 0", minWidth: "170px", 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)", cursor: "pointer", hover: { color: "var(--os-text)", backgroundColor: "#dce7df" } }), 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", { 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", cursor: "pointer" }), kanbanP1: css("os-kanban-p1", { backgroundColor: "#e6ece7", color: "var(--os-muted)" }), kanbanP2: css("os-kanban-p2", { backgroundColor: "#cfe3d4", color: "#1d5c42" }), 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)", cursor: "pointer", hover: { color: "var(--os-text)", backgroundColor: "var(--os-soft)" } }), 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: "#fff" }), 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)", cursor: "pointer", 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)", 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", { 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)", cursor: "pointer", 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", "@media (max-width: 600px)": { 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: "#1d5c42" }), finNeg: css("os-fin-neg", { color: "#b04a3a" }), finGrid: css("os-fin-grid", { display: "grid", gridTemplateColumns: "minmax(0, 1.5fr) minmax(0, 1fr)", gap: "10px", alignItems: "start" }), 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: "#fff", 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: "#1d5c42" }), finExpense: css("os-fin-expense", { color: "#b04a3a" }), 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)", cursor: "pointer", hover: { color: "#9e3434", backgroundColor: "#f6dede" } }), 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" } }), };